language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
4,311
3.359375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- from numpy import tan from numpy import pi class Drone : def __init__(self): self.launch() def launch(self): self.setHeight(1.5) def setHeight(self, height): self.height=height def rotateSelf(self): return True def rotateLeft(self, distance): return True def rotateRight(self, distance): return True def leave(self): return True def comeBack(self): return True def left(self): return True def right(self): return True def land(self): print "J'atteris" class Barre : def __init__(self, x, y, side): self.x=x self.y=y self.side=side print("Creation d'une barre !") def decrisToi(self, string): print("La barre {} a pour coordonnees ({},{}).\n".format(string, self.x, self.y)) def main(): drone = Drone() b1 = Barre(100,250,True) b0 = Barre(360,250,False) b2 = Barre(500,250,True) tab = [b1,b0,b2] for i in range(len(tab)): if tab[i].side == False or len(tab) == 1 : barreMilieu = tab[i] barreMilieu.decrisToi("du milieu") else : if i > 0 : if tab[i].x > tab[i-1].x : barreDroite = tab[i] barreDroite.decrisToi("de droite") else : barreGauche = tab[i] barreGauche.decrisToi("de gauche") else : if tab[i].x > tab[i+1].x : barreDroite = tab[i] barreDroite.decrisToi("de droite") else : barreGauche = tab[i] barreGauche.decrisToi("de gauche") distanceDroneHomme = 5 pixelHoriBGBD = abs(barreDroite.x-barreGauche.x) distanceHoriBGBD = distanceDroneHomme*tan(93*(pi/180)*pixelHoriBGBD/640) pixelHoriBGBM = abs(barreGauche.x-barreMilieu.x) distanceHoriBGBM = distanceDroneHomme*tan(93*(pi/180)*pixelHoriBGBM/640) pixelHoriBMBD = abs(barreMilieu.x-barreDroite.x) distanceHoriBMBD = distanceDroneHomme*tan(93*(pi/180)*pixelHoriBMBD/640) pixelVertiBGBD = abs(barreDroite.y-barreGauche.y) distanceVertiBGBD = distanceDroneHomme*tan(93*(pi/180)*pixelVertiBGBD/640) pixelVertiBGBM = abs(barreGauche.y-barreMilieu.y) distanceVertiBGBM = distanceDroneHomme*tan(93*(pi/180)*pixelVertiBGBM/640) pixelVertiBMBD = abs(barreMilieu.y-barreDroite.y) distanceVertiBMBD = distanceDroneHomme*tan(93*(pi/180)*pixelVertiBMBD/640) pixelHoriBMOr = barreMilieu.x-320 if pixelHoriBMOr < 0 : distanceHoriBMOr = distanceDroneHomme*tan(93*(pi/180)*pixelHoriBMOr/640) elif pixelHoriBMOr > 0 : distanceHoriBMOr = -distanceDroneHomme*tan(93*(pi/180)*pixelHoriBMOr/640) if len(tab) <= 1 : drone.rotateSelf() elif len(tab) == 2 : if barreMilieu == None : return True elif barreGauche == None : drone.rotateRight() else : drone.rotateGauche() else : if distanceHoriBGBM < 0.05 and distanceHoriBMBD < 0.05 : drone.land() elif 0.2 < distanceVertiBGBM < 0.9 or 0.2 < distanceVertiBMBD < 0.9 : drone.setAltitude(19.2857*distanceVertiBGBM - 2.3571) elif pixelHoriBGBD < 40 : while pixelHoriBGBD < 40 : drone.comeBack() elif pixelHoriBGBD > 80 : while pixelHoriBGBD > 80 : drone.leave() elif distanceHoriBMOr < 0.3 : drone.left() elif barreMilieu.x > 6 : drone.right() if __name__ == '__main__' : main()
SQL
UTF-8
4,994
3.328125
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 18-Nov-2020 às 18:18 -- Versão do servidor: 10.4.14-MariaDB -- versão do PHP: 7.4.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `fseletro` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `comentarios` -- CREATE TABLE `comentarios` ( `id` int(11) NOT NULL, `nome` varchar(100) DEFAULT NULL, `msg` varchar(300) DEFAULT NULL, `data` datetime DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `comentarios` -- INSERT INTO `comentarios` (`id`, `nome`, `msg`, `data`) VALUES (2, 'Fabiana', 'Olá Full Stack Eletro!', '2020-11-15 14:24:52'), (3, 'Daniel', 'Eu gostaria de comprar um Playstation 5!', '2020-11-15 14:55:50'), (5, 'Rafa', 'Já chegou o produto que eu pedi?', '2020-11-15 15:10:17'), (9, 'Edson', 'Olá, quero um notebook', '2020-11-15 15:12:32'), (11, 'Ícaro', 'Olá galera!', '2020-11-15 15:13:48'); -- -------------------------------------------------------- -- -- Estrutura da tabela `pedidos` -- CREATE TABLE `pedidos` ( `id_pedidos` int(11) NOT NULL, `nome` varchar(100) DEFAULT NULL, `endereco` varchar(150) NOT NULL, `telefone` int(15) NOT NULL, `descricao` varchar(150) NOT NULL, `precofinal` decimal(8,2) DEFAULT NULL, `quantidade` int(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `pedidos` -- INSERT INTO `pedidos` (`id_pedidos`, `nome`, `endereco`, `telefone`, `descricao`, `precofinal`, `quantidade`) VALUES (2, 'Fabiana', 'Rua Jorge Amado', 98988989, 'Geladeira', '2000.00', 1), (5, 'Ricardo', 'Rua A', 34566789, 'Fogão', '1000.00', 1); -- -------------------------------------------------------- -- -- Estrutura da tabela `produtos` -- CREATE TABLE `produtos` ( `idproduto` int(11) NOT NULL, `categoria` varchar(45) NOT NULL, `descricao` varchar(150) NOT NULL, `preco` decimal(8,2) DEFAULT NULL, `precofinal` decimal(8,2) DEFAULT NULL, `imagem` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `produtos` -- INSERT INTO `produtos` (`idproduto`, `categoria`, `descricao`, `preco`, `precofinal`, `imagem`) VALUES (1, 'geladeira', 'Geladeira Frost Free Brastemp Side Inverse 540L', '6389.00', '5019.00', 'imagens/geladeiraprata.jpeg'), (2, 'geladeira', 'Geladeira Frost Free Brastemp Branca 375 Litros', '2068.00', '1910.00', 'imagens/geladeira.jpeg'), (3, 'geladeira', 'Geladeira Frost Free Consul Prata 340 Litros', '2199.00', '2069.00', 'imagens/geladeiraprata2.png'), (4, 'fogao', 'Fogão 4 Bocas Consul Inox com Mesa de Vidro', '1299.00', '1129.00', 'imagens/fogaoPequeno.jpeg'), (5, 'fogao', 'Fogão de Piso 4 Bocas Atlas Monaco com Acendimento Automático', '600.00', '519.00', 'imagens/fogao.jpeg'), (6, 'microondas', 'Micro-ondas Consul 32 Litros inox 220V', '580.00', '409.00', 'imagens/micro.jpeg'), (7, 'microondas', 'Microondas 25L Espelhado Philco 220V', '508.00', '464.00', 'imagens/micro2.jpeg'), (8, 'microondas', 'Forno de Microondas Eletrolux 20L Branco', '1299.00', '1129.00', 'imagens/microondas.jpeg'), (9, 'lavalouca', 'Lava-louça Eletrolux Inox com 10 serviços, 06 Programas de Lavagem e Painel Blue Touch', '3599.00', '2799.00', 'imagens/lavalouca1.jpeg'), (10, 'lavalouca', 'Lava Louça Compacta, 8 Serviços Branca 127V Brastemp', '1970.00', '1730.00', 'imagens/lavalouca2.jpeg'), (11, 'lavaroupa', 'Lavadoura de Roupas Philco Inverter', '2399.00', '2179.00', 'imagens/secadora.jpeg'), (12, 'lavaroupa', 'Lavadoura de Roupas Brastemp 15k branca', '2399.00', '2179.00', 'imagens/lavadora.jpeg'); -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `comentarios` -- ALTER TABLE `comentarios` ADD PRIMARY KEY (`id`); -- -- Índices para tabela `pedidos` -- ALTER TABLE `pedidos` ADD PRIMARY KEY (`id_pedidos`); -- -- Índices para tabela `produtos` -- ALTER TABLE `produtos` ADD PRIMARY KEY (`idproduto`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `comentarios` -- ALTER TABLE `comentarios` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT de tabela `pedidos` -- ALTER TABLE `pedidos` MODIFY `id_pedidos` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT de tabela `produtos` -- ALTER TABLE `produtos` MODIFY `idproduto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
1,490
3.328125
3
[]
no_license
#include "LongestCommonPrefix.h" inline int minStr(string &s1,string &s2) { return (s1.size() > s2.size()) ? s2.size() : s1.size(); }; string longestCommonPrefix(vector<string>& strs) { string theLongest=""; int longest=0; vector<string>::iterator it_first; vector<string>::iterator it_second; int minStrSize; theLongest = *strs.begin(); for (it_first = strs.begin(); it_first != strs.end(); it_first++) { for (it_second = it_first+1; it_second != strs.end(); it_second++) { minStrSize = minStr(*it_first, *it_second); string temp; for (int i = 0; i < minStrSize; i++) { if ((*it_first).substr(i, 1) ==(*it_second).substr(i, 1)) { temp.append((*it_first).substr(i, 1)); } else break; } if (temp.size() > longest) { theLongest = temp; longest = temp.size(); } } } return theLongest; } string longestCommonPrefix_Leetcode(vector<string>& strs) { string prefix = ""; for (int idx = 0; strs.size()>0; prefix += strs[0][idx], idx++) for (int i = 0; i<strs.size(); i++) if (idx >= strs[i].size() || (i > 0 && strs[i][idx] != strs[i - 1][idx])) return prefix; return prefix; } void testlongestCommonPrefix() { vector<string> str = { { "asdfghjkl" }, { "qwertyuiop" }, { "zxcvbnm" }, { "asdcvbnm" }, { "asdrtyuiop" }, { "asdftbnm" }, { "asdfgbnm" } }; vector<string> str1 = { {"a"} }; vector<string> str2 = { { "" } }; cout << longestCommonPrefix(str2) << endl; };
Java
UTF-8
16,151
2.140625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package login; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Anurag */ public class signup extends javax.swing.JFrame { /** * Creates new form signup */ private Socket Clientsocket=null; public signup() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel9 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); un = new javax.swing.JTextField(); cpass = new javax.swing.JTextField(); pass = new javax.swing.JTextField(); eid = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(204, 204, 255)); jLabel9.setFont(new java.awt.Font("Dialog", 0, 48)); // NOI18N jLabel9.setForeground(new java.awt.Color(0, 0, 0)); jLabel9.setText("Chat Appilcation"); jLabel11.setFont(new java.awt.Font("Dialog", 0, 36)); // NOI18N jLabel11.setForeground(new java.awt.Color(0, 0, 0)); jLabel11.setText("SignUp"); jLabel10.setIcon(new javax.swing.ImageIcon("C:\\Users\\Anurag\\Desktop\\unauthorized-person.png")); // NOI18N jLabel10.setText("jLabel10"); un.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { unActionPerformed(evt); } }); cpass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cpassActionPerformed(evt); } }); pass.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { passActionPerformed(evt); } }); eid.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eidActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jLabel7.setForeground(new java.awt.Color(0, 0, 0)); jLabel7.setText("User Name"); jLabel8.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jLabel8.setForeground(new java.awt.Color(0, 0, 0)); jLabel8.setText("Confirm Password"); jLabel8.setToolTipText(""); jLabel12.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jLabel12.setForeground(new java.awt.Color(0, 0, 0)); jLabel12.setText("Email-Id"); jLabel13.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jLabel13.setForeground(new java.awt.Color(0, 0, 0)); jLabel13.setText("Password"); jButton4.setBackground(new java.awt.Color(0, 153, 204)); jButton4.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jButton4.setText("SignUp"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setBackground(new java.awt.Color(0, 153, 204)); jButton5.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N jButton5.setText("Back"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(43, 43, 43) .addComponent(jLabel9)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(227, 227, 227) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 21, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eid, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(un, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(50, 50, 50) .addComponent(cpass, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(123, 123, 123) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(8, 8, 8))) .addGap(73, 73, 73)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel11) .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(un, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(eid, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pass, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cpass, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton5) .addComponent(jButton4)) .addGap(26, 26, 26)) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 610, 450)); pack(); }// </editor-fold>//GEN-END:initComponents private void unActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unActionPerformed // TODO add your handling code here: }//GEN-LAST:event_unActionPerformed private void cpassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cpassActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cpassActionPerformed private void passActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passActionPerformed // TODO add your handling code here: }//GEN-LAST:event_passActionPerformed private void eidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eidActionPerformed // TODO add your handling code here: }//GEN-LAST:event_eidActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: String name=un.getText();String eeid=eid.getText(); String password=pass.getText();String cpassword=cpass.getText(); if(password.equals(cpassword)) { try { Clientsocket=new Socket("localhost",8818); String s = "!!CreateNewUser!!-"+name+"-"+eeid+"-"+password+"-"+cpassword; PrintWriter pw= new PrintWriter(Clientsocket.getOutputStream(),true); pw.println(s); StartChat sc=new StartChat(Clientsocket); sc.NameOfUser.setText(name); sc.setVisible(true); this.dispose(); } catch (IOException ex) { Logger.getLogger(signup.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButton4ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed // TODO add your handling code here: new login().show(); this.dispose(); }//GEN-LAST:event_jButton5ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(signup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new signup().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField cpass; private javax.swing.JTextField eid; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JTextField pass; private javax.swing.JTextField un; // End of variables declaration//GEN-END:variables }
Python
UTF-8
3,318
2.640625
3
[]
no_license
__author__ = 'Zac, Shawyn Kane' import Graphics, pygame, sys, GameState, Pieces, AI from pygame.locals import * pygame.init() myDisplay = pygame.display.set_mode(Graphics.resolution, 0, 32) gameState = GameState.GameState() fpsClock = pygame.time.Clock() while True: if AI.is_checked(gameState): gameState.status = "Check" if AI.is_checkmate(gameState): gameState.status = "Checkmate" Graphics.build_border(myDisplay) Graphics.build_board(myDisplay) Graphics.build_menu(myDisplay) Graphics.build_pieces(myDisplay, gameState.pieces) Graphics.build_status(myDisplay, gameState.status) Graphics.build_score(myDisplay, gameState.score) Graphics.build_suggest(myDisplay) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_1: gameState.pieces = gameState.preset1() if event.type == MOUSEBUTTONDOWN: # Checks for reset button click if Graphics.reset_text.collidepoint(pygame.mouse.get_pos()): gameState.reset() print("reset") if Graphics.suggestButton.collidepoint(pygame.mouse.get_pos()): gameState = AI.suggested_move(gameState) print("suggest") # Checks for selection a position myBool = False for x in range(8): temp = Graphics.board[x] for y in range(8): local = temp[y] if local.collidepoint(pygame.mouse.get_pos()): if ((gameState.selectedPiece is None) and (gameState.get_piece((x, y)) is not None)) and (gameState.get_piece((x, y)).isWhite is gameState.whitesTurn): print(x, y) if gameState.whitesTurn == gameState.get_piece((x, y)).isWhite: gameState.selectedPiece = gameState.get_piece((x, y)) myBool = True break gameState.selectedPiece = gameState.get_piece((x, y)) myBool = True break # The following elif block will select the tile to move the selected piece and try to move the # currently selected piece (if there is one selected) if the tile selected is not valid to move # to the currently selected piece will be deselected (in AI.make_move() function). elif (gameState.selectedPiece is not None) and ((gameState.get_piece((x, y)) is None) or \ ((gameState.get_piece((x, y)) is not None) and \ (gameState.get_piece((x, y)).isWhite is not gameState.selectedPiece.isWhite))): print("Target:", (x, y)) #gameState.selectedPiece.move(gameState.pieces, (x, y), False) gameState = AI.make_move(gameState, (x, y)) myBool = True break if myBool: break fpsClock.tick(60) pygame.display.update()
JavaScript
UTF-8
6,460
2.640625
3
[]
no_license
const express = require( 'express' ); const bodyParser = require('body-parser'); const morgan = require('morgan'); const uuid = require('uuid'); const {Bookmarks} = require('./bookmarkModel'); const mongoose = require('mongoose'); const {DATABASE_URL, PORT} = require('./config'); const apiKEY = "2abbf7c3-245b-404f-9473-ade729ed4653"; const app = express(); const jsonParser = bodyParser.json(); app.use( express.static( "public" )); app.use( morgan( 'dev' ) ); function middleware(req, res, next){ console.log("middleware"); req.test = {}; req.test.message = "Adding something to the request"; next(); } function validateApiKey (req, res, next){ if(req.headers.authorization === `Bearer ${apiKEY}`){ next(); } else if(req.query.apiKey === apiKEY){ next(); } else if(req.headers['book-api-key'] === apiKEY){ next(); } else { req.statusMessage = "No API key sent or incorrect."; return res.status(401).end(); } } app.use(validateApiKey); let listOfBookmarks = [ { id : uuid.v4(), title : "Youtube", description: "Watch videos", url : "https://www.youtube.com", rating : 5 }, { id : uuid.v4(), title : "Facebook", description: "Post media with friends", url : "https://www.facebook.com", rating : 5 } ]; app.get('/bookmarks', middleware, (req, res) => { console.log("Getting all bookmarks."); Bookmarks .getAllBookmarks() .then(result => { return res.status(200).json(result); }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); }); app.get('/bookmark', (req, res) => { console.log("Getting a bookmark by title using query string."); console.log(req.query); let title = req.query.title; if(title == undefined){ res.statusMessage = "Please send the 'title' as parameter."; return res.status(406).end(); } Bookmarks .getBookmark(title) .then(result => { if(result != ""){ return res.status(200).json(result); } else { res.statusMessage = "A bookmark with that title does not exist."; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); }); app.post('/bookmarks', jsonParser, (req, res) => { console.log("Adding a new bookmark to the list."); console.log("Body ", req.body); let id = uuid.v4(); let title = req.body.title; let description = req.body.description; let url = req.body.url; let rating = req.body.rating; if(!title || !description || !url || !rating){ res.statusMessage = "Some parameters are missing."; return res.status(406).end(); } const newBookmark = { id, title, description, url, rating }; Bookmarks .createBookmark(newBookmark) .then(result => { return res.status(201).json(result); }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); }); app.delete('/bookmark/:id', (req, res) => { let id = req.params.id; if(!id){ res.statusMessage = "Please send the 'id' to delete a bookmark"; return res.status(406).end(); } Bookmarks .deleteBookmark(id) .then(result => { if(result.deletedCount != 0){ return res.status(200).end(); } else { res.statusMessage = `Bookmark with id: ${id} not found`; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); }); app.patch('/bookmark/:id', jsonParser, async(req, res) => { let id = req.params.id; console.log("Body ", req.body); let title = req.body.title; let description = req.body.description; let url = req.body.url; let rating = req.body.rating; if(!id){ res.statusMessage = "Please send the 'id' to update a bookmark"; return res.status(406).end(); } // Pass in the body an object with the updated content of the bookmark. let flag = false; if(title != undefined){ await Bookmarks .patchBookmark(id, {"title" : title}) .then(result => { if(result.n == 0){ res.statusMessage = "Could not find bookmark with that id."; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); flag = true; } if(description != undefined){ await Bookmarks .patchBookmark(id, {"description" : description}) .then(result => { if(result.n == 0){ res.statusMessage = "Could not find bookmark with that id."; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); flag = true; } if(url != undefined){ await Bookmarks .patchBookmark(id, {"url" : url}) .then(result => { if(result.n == 0){ res.statusMessage = "Could not find bookmark with that id."; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); flag = true; } if(rating != undefined){ await Bookmarks .patchBookmark(id, {"rating" : rating}) .then(result => { if(result.n == 0){ res.statusMessage = "Could not find bookmark with that id."; return res.status(404).end(); } }) .catch(err => { res.statusMessage = "Something went wrong with the DB. Try again later."; return res.status(500).end(); }); flag = true; } if(!flag){ res.statusMessage = "No parameters were sent to update."; return res.status(406).end(); } res.statusMessage = "Update successful"; return res.status(202).end(); }); app.listen( PORT, () => { console.log("This server is running on port 8080"); new Promise(( resolve, reject) => { mongoose.connect(DATABASE_URL, {useNewUrlParser: true, useUnifiedTopology: true}, (err) => { if(err){ reject(err); } else{ console.log("bookmarksdb connected successfully"); return resolve(); } }) }) .catch(err => { mongoose.disconnect(); console.log(err); }) }); // Base URL : http://localhost:8080/ // GET endpoint: http://localhost:8080/bookmarks // GET endpoint with title parameter: http://localhost:8080/bookmark?title=value // POST endpoint: http://localhost:8080/bookmarks // DELETE endpoint: http://localhost:8080/bookmark/:id
SQL
UTF-8
511
3.46875
3
[]
no_license
-- +goose Up ALTER TABLE entries DROP COLUMN user_id; CREATE TABLE journals ( id serial not null primary key, user_id integer not null references users(id), created date not null, updated date not null, name text not null ); ALTER TABLE entries ADD COLUMN journal_id integer not null references journals(id) default 0; -- +goose Down ALTER TABLE entries ADD COLUMN user_id integer not null references users(id) default 0; DROP TABLE journals; ALTER TABLE entries DROP COLUMN journal_id;
Markdown
UTF-8
11,291
2.8125
3
[]
no_license
--- title: Handling JAX-RS and Bean Validation Errors with MVC author: Michal Gajdoš type: post date: 2014-01-28T09:35:12+00:00 url: /handling-jax-rs-and-bean-validation-errors-with-mvc/ aliases: /2014/01/28/handling-jax-rs-and-bean-validation-errors-with-mvc/ categories: - Jersey tags: - jax-rs - jersey - mvc - bean-validation --- Since JAX-RS 2.0 you can use Bean Validation to validate inputs received from users and outputs created in your application. It&#8217;s a handy feature and in most cases it works great. But what if you&#8217;re using also MVC and you want to display custom error page if something goes wrong? Or what if you want to handle Bean Validation issues in a slightly different way than JAX-RS implementation you&#8217;re using does? This article will give you some answers to these questions. <!--more--> Topics covered by this article: * [Handling Error States with Jersey MVC][1], * [Handling Bean Validation errors with Jersey MVC][2], and * [Handling Bean Validation errors in a custom way in JAX-RS 2.0][3] ## <a name="errors"></a>Handling Error States with Jersey MVC In addition to <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/Template.html">@Template</a> annotation that has been present in Jersey MVC since 2.0 release a <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/ErrorTemplate.html">@ErrorTemplate</a> annotation has been introduced in Jersey 2.3. The purpose of this annotation is to bind the model to an error view in case an exception has been raised during processing of a request. This is true for any exception thrown after the resource matching phase (i.e. this not only applies to JAX-RS resources but providers and even Jersey runtime as well). The model in this case is the thrown exception itself. > All code samples in this section are taken from **shortener-webapp** example that is available as <a href="https://github.com/jersey/jersey/tree/master/examples/shortener-webapp">sources</a> or as a <a href="http://jersey-shortener-webapp.herokuapp.com/">live demo</a>. The next snippet shows how to use _@ErrorTemplate_ on a resource method. If all goes well with the method processing, then the _/short-link_ template is used to as page sent to the user. Otherwise if an exception is raised then the _/error-form_ template is shown to the user. {{< highlight java "hl_lines=4-5" >}} @POST @Produces("text/html") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Template(name = "/short-link") @ErrorTemplate(name = "/error-form") public ShortenedLink createLink(@FormParam("link") final String link) { // ... } {{< / highlight >}} > <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/ErrorTemplate.html">@ErrorTemplate</a> can be used on a resource class or a resource method to merely handle error states. There is no need to use <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/Template.html">@Template</a> or <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/Viewable.html">Viewable</a> with it. The annotation is handled by custom <a href="http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/ext/ExceptionMapper.html">ExceptionMapper<E extends Throwable></a> which creates an instance of _Viewable_ that is further processed by Jersey. This exception mapper is registered automatically with any _*MvcFeature_. ## <a name="bv-errors"></a>Handling Bean Validation Errors with Jersey MVC _@ErrorTemplate_ can be used in also with Bean Validation to display specific error pages in case the validation of input/output values fails for some reason. Everything works as described above except the model is not the thrown exception but rather a list of <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/validation/ValidationError.html">ValidationError</a>s. This list can be iterated in the template and all the validation errors can be shown to the user in a desirable way. Let&#8217;s add some validation annotations to our resource method from above: {{< highlight java "hl_lines=6-7" >}} @POST @Produces("text/html") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Template(name = "/short-link") @ErrorTemplate(name = "/error-form") @Valid public ShortenedLink createLink(@ShortenLink @FormParam("link") final String link) { // ... } {{< / highlight >}} In case the method gets an invalid form parameter (or creates invalid output for a user) we can iterate _ValidationError_s in _/error-form_ as follows (<a href="https://github.com/spullara/mustache.java">Mustache</a> templating engine): {{< highlight xhtml "hl_lines=6-8" >}} <div> <div class="panel-heading"> <h3 class="panel-title">Errors occurred during link shortening.</h3> </div> <div class="panel-body"> {{#.}} {{message}} "<strong>{{invalidValue}}</strong>"<br/> {{/.}} </div> </div> {{< / highlight >}} Support for Bean Validation in Jersey MVC Templates is provided by a <a href="https://jersey.github.io/project-info/2.5.1/jersey/project/jersey-mvc-bean-validation/dependencies.html">jersey-mvc-bean-validation</a> extension module. Coordinates of this module are: > <a href="http://repo1.maven.org/maven2/org/glassfish/jersey/ext/jersey-mvc-bean-validation/2.5.1/jersey-mvc-bean-validation-2.5.1.jar">org.glassfish.jersey.ext:jersey-mvc-bean-validation:2.5.1</a> The JAX-RS Feature provided by this module (<a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/beanvalidation/MvcBeanValidationFeature.html">MvcBeanValidationFeature</a>) has to be registered in order to use this functionality: {{< highlight java "hl_lines=9 13" >}} @ApplicationPath("/") public class ShortenerApplication extends ResourceConfig { public ShortenerApplication() { // Resources. packages(ShortenerResource.class.getPackage().getName()); // Features. register(MvcBeanValidationFeature.class); // Providers. register(LoggingFilter.class); register(MustacheMvcFeature.class); // Properties. property(MustacheMvcFeature.TEMPLATE_BASE_PATH, "/mustache"); } } {{< / highlight >}} ## <a name="custom"></a>Custom Handling of Bean Validation Errors in JAX-RS 2.0 In case the approach described above doesn&#8217;t work for you for some reason (i.e. you have implemented your own MVC support or you&#8217;re using other JAX-RS 2.0 implementation) you need to follow these steps to achieve similar result as with _@ErrorTemplate_: 1. (Jersey specific) add the dependencies on Bean Validation module (_jersey-bean-validation_) and, optionally, on one of the MVC modules providing support for custom templates (_jersey-mvc-*_) 2. create an <a href="https://jax-rs.github.io/apidocs/2.0.1/javax/ws/rs/ext/ExceptionMapper.html">ExceptionMapper</a> for <a href="http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/javax/validation/ConstraintViolationException.html">ConstraintViolationException</a> 3. register all your providers I&#8217;ll skip the first step as it&#8217;s easy enough and we&#8217;re going to take a look at creating custom _ExceptionMapper_ and registering it. ### Custom ExceptionMapper {#dependencies} Bean Validation runtime throws a _ConstraintViolationException_ when something goes wrong during validating an incoming entity, request parameters or even JAX-RS resource. Every JAX-RS 2.0 implementation is required to provide a standard _ExceptionMapper_ to handle this type of exceptions (_ValidationException_ to be precise) and based on the context return correct HTTP status code (_400_ or _500_). If you want to handle Bean Validation issues differently, you need to write an _ExceptionMapper_ of your own: {{< highlight java >}} @Provider @Priority(Priorities.USER) public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { @Override public Response toResponse(final ConstraintViolationException exception) { return Response // Define your own status. .status(400) // Process given Exception and set an entity // i.e. Set an instance of Viewable to the response // so that Jersey MVC support can handle it. .entity(new Viewable("/error", exception)) .build(); } } {{< / highlight >}} With the _ExceptionMapper_ above you&#8217;ll be handling all thrown _ConstraintViolationException_s and the final response will have HTTP _400_ response status. Entity set (in our case <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/mvc/Viewable.html">Viewable</a>) to the response will be processed by <a href="https://jax-rs.github.io/apidocs/2.0.1/javax/ws/rs/ext/MessageBodyWriter.html">MessageBodyWriter</a> from Jersey MVC module and it will basically output a processed web-page. The first parameter of the _Viewable_ is path to a template (you can use relative or absolute path), the second is the model the MVC will use for rendering. For more on this topic, refer to the section about <a href="https://jersey.github.io/documentation/latest/mvc.html">MVC</a> in Jersey Users Guide. ### Registering Providers {#registeringproviders} The last step you need to make is to register your providers into your <a href="https://jax-rs.github.io/apidocs/2.0.1/javax/ws/rs/core/Application.html">Application</a> (I&#8217;ll show you an example using <a href="https://jersey.github.io/apidocs/latest/jersey/org/glassfish/jersey/server/ResourceConfig.html">ResourceConfig</a> from Jersey which extends _Application_ class): {{< highlight java >}} new ResourceConfig() // Look for JAX-RS reosurces and providers. .package("my.package") // Register Jersey MVC Mustache processor. .register(MustacheMvcFeature.class) // Register custom ExceptionMapper (not needed as it's annotated with @Provider). .register(ConstraintViolationExceptionMapper.class) // Register Bean Validation (this is optional as BV is automatically registered // when jersey-bean-validation is on the class-path but it's good to know it's happening). .register(ValidationFeature.class); {{< / highlight >}} More information about how different ways how to register providers and resources is available in this <a href="/2013/11/19/registering-resources-and-providers-in-jersey-2/">article</a>. ## Resources Sample Application: * <a href="http://jersey-shortener-webapp.herokuapp.com/">jersey-shortener-webapp</a> deployed on Heroku * <a href="https://github.com/jersey/jersey/tree/master/examples/shortener-webapp">examples/shortener-webapp</a> sources on Github ## Further Reading * <a href="https://jersey.github.io/documentation/latest/mvc.html">MVC Templates</a> * <a href="/2013/11/19/registering-resources-and-providers-in-jersey-2/">Registering Resources and Providers in Jersey 2</a> * <a href="/2014/01/09/running-jersey-2-applications-on-heroku/">Running Jersey 2 Applications on Heroku</a> [1]: #errors [2]: #bv-errors [3]: #custom
Python
UTF-8
2,630
2.53125
3
[]
no_license
# -*-coding:utf-8-*- import pymysql DB_CONFIG = { 'user': 'root', 'password': '', 'host': '127.0.0.1', 'charset': 'utf8mb4' } DB_NAME = 'joboffer' CREATE_TABLE_JOB = """ CREATE TABLE IF NOT EXISTS `JOB`( `ID` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY , `KEYWORD` VARCHAR(100), `MONTHLYSALARY` VARCHAR(100), `WORKINGPLACE` VARCHAR(100), `RELEASEDATE` VARCHAR(100), `JOBTYPE` VARCHAR(100), `WORKEXPERIENCE` VARCHAR(100), `LOWESTDEGREE` VARCHAR(100), `RECRUITMENTNUMBER` VARCHAR(100), `POSITIONCATEGORY` VARCHAR(100), `DEMAND` VARCHAR(10000) )ENGINE=INNODB DEFAULT CHARSET=UTF8; """ INSERT_TABLE_JOB = """ INSERT INTO `JOB`(`KEYWORD`, `MONTHLYSALARY`, `WORKINGPLACE`, `RELEASEDATE`, `JOBTYPE`, `WORKEXPERIENCE`, `LOWESTDEGREE`, `RECRUITMENTNUMBER`, `POSITIONCATEGORY`, `DEMAND`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ SELECT_TABLE_JOB = """ SELECT ID, KEYWORD, MONTHLYSALARY, WORKINGPLACE, RELEASEDATE, JOBTYPE, WORKEXPERIENCE, LOWESTDEGREE, RECRUITMENTNUMBER, POSITIONCATEGORY, DEMAND FROM `JOB` WHERE KEYWORD like %s """ SELECT_DISTINCT_KEYWORD = """ SELECT distinct keyword FROM JOB """ DELETE_JOB = """ delete FROM JOB where KEYWORD = %s """ def create_database(): conn = pymysql.connect(**DB_CONFIG) cursor = conn.cursor() cursor.execute("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME)) cursor.close() conn.close() def get_db_conn(): conn = pymysql.connect(database='joboffer', **DB_CONFIG) return conn def create_table_job(): conn = get_db_conn() cursor = conn.cursor() cursor.execute(CREATE_TABLE_JOB) cursor.close() conn.close() def insert_table_job(joboffer): conn = get_db_conn() cursor = conn.cursor() cursor.execute(INSERT_TABLE_JOB, joboffer) conn.commit() cursor.close() conn.close() def select_table_job(searchkey): conn = get_db_conn() cursor = conn.cursor() cursor.execute(SELECT_TABLE_JOB, searchkey) values = cursor.fetchall() cursor.close() conn.close() return values def select_distinct_keyword(): conn = get_db_conn() cursor = conn.cursor() cursor.execute(SELECT_DISTINCT_KEYWORD) values = cursor.fetchall() cursor.close() conn.close() return values def delete_job(searchkey): conn = get_db_conn() cursor = conn.cursor() cursor.execute(DELETE_JOB, searchkey) conn.commit() cursor.close() conn.close() #create_database() #create_table_job() #cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael']) #insert_table_job(joboffer) #select_table_job('java') #delete_job('java')
Markdown
UTF-8
978
3.046875
3
[ "Apache-2.0" ]
permissive
# What are you building This demo create a project into an organization. # Steps to run ## Requirements 1. Terraform installed on your machine 2. a Service Account with `Resource Manager` > `Organization Viewer` and `Resource Manager` > `Project Creator` IAM rules on your organization ## Run it Before starting, edit the file `demo.tfvars` with your preferred data, then prepare your workspace and apply as following. ```bash # use a dedicated workspace terraform workspace new "demo" # initialize all providers terraform init # see what will happen to your project, this will produce a state file called demo.out terraform plan -var-file="demo.tfvars" -out=demo.out # apply your plan leveraging the file demo.out terraform apply "demo.out" # see the status of your project terraform show ``` ## Clean up ```bash # Warning: this will destroy everything you created before. You wont be able to undo it! terraform destroy -var-file="demo.tfvars" -auto-approve ```
Python
UTF-8
878
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri May 21 22:21:57 2021 @author: kunal """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.svm import SVC import pickle import json def SVM(Symptom1, Symptom2, Symptom3, Symptom4, Symptom5): filename = 'finalized_model.sav' # pickle.dump(model, open(filename, 'wb')) # load the model from disk loaded_model = pickle.load(open(filename, 'rb')) with open('symptoms.json') as f: data = json.load(f) psymptoms = [Symptom1,Symptom2,Symptom3,Symptom4,Symptom5] for i in range(5): psymptoms[i] = data[psymptoms[i]][1] nulls = [0,0,0,0,0,0,0,0,0,0,0,0] psy = [psymptoms + nulls] pred2 = loaded_model.predict(psy) print(psy,pred2) return pred2[0] # return "model"
PHP
UTF-8
5,236
2.5625
3
[ "Apache-2.0" ]
permissive
<?php session_start(); $_SESSION['pays']['Cle']= array(); $_SESSION['pays']['Cle']['Code']=array(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="Style.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Make sure you put this AFTER Leaflet's CSS --> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <title>Document</title> </head> <header> <?php // Il me manque un bouton de retour au départ $api = json_decode(file_get_contents('https://restcountries.eu/rest/v2/all')); foreach ($api as $key=>$value) { array_push ($_SESSION['pays']['Cle'], $key); array_push ($_SESSION['pays']['Cle']['Code'],$value->alpha3Code); } ?> <div class='jumbotron change' > <div class='d-flex justify-content-between'> <!-- Répartit le contenu de façon centrée sur la page --> <div class='p-2 bd-highlight '> <!-- Box du globe tournant --> <img src='terre.gif'height = 110px></div> <div class='p-2 bd-highlight'> <!-- Box dy pays --> <h1> Pays : <?php echo $api[$_GET['cle']]->name ?> </h1></div ><div class='p-2 bd-highlight'> <!-- Box du drapeau du pays --> <img src= <?php echo $api[$_GET['cle']]->flag ?> class='images_petit'></div> </div></br><hr class='my-4'> <p>Retrouvez le détail de la fiche du pays : <?php echo $api[$_GET['cle']]->name ?></p></div> </header> <body> <!-- Ligne Continent --> <div class="d-flex justify-content-center"><div class='d-flex align-items-center'><div class='d-flex justify-content-start'> <!-- Box image du continent --> <div class='p-2 bd-highlight '> <img src= <?php echo $api[$_GET['cle']]->region ?>.jpg width : 100px height = 60 px></div> <!-- Box titre continent --> <div class='p-2 bd-highlight '> <h2> Continent : </h2></div> <!-- Box nom du continent --> <div class='p-2 bd-highlight '> <p> <?php echo $api[$_GET['cle']]->region ?></p></div></div></div></div></br> <!-- Ligne Capitale --> <div class="d-flex justify-content-center"><div class='d-flex align-items-center'><div class='d-flex justify-content-start'> <div class='p-2 bd-highlight '> <!-- Box icone Capitale --> <img src = 'Capitale.jpg' width = 80 px height = 60 px></div> <div class='p-2 bd-highlight '> <!-- Box titre Capitale --> <h2> Capitale : </h2></div> <div class='p-2 bd-highlight '> <!-- Box nom Capitale --> <p><?php echo $api[$_GET['cle']]->capital ?></p></div></div></div></div></br> <!-- Ligne Population --> <div class="d-flex justify-content-center"><div class='d-flex align-items-center'><div class='d-flex justify-content-start'> <div class='p-2 bd-highlight '> <!-- Box icone Population--> <img src= 'population.png' width = 70 px height = 60 px></div> <div class='p-2 bd-highlight '> <!-- Box Titre Population --> <h2> Population : </h2></div> <div class='p-2 bd-highlight '> <!-- Box nombre d'habitants --> <p> <?php echo number_format($api[$_GET['cle']]->population,0,'1',' ') ?> habitants.</p></div></div></div></div></br> <!-- Ligne Superficie --> <div class="d-flex justify-content-center"><div class='d-flex align-items-center'><div class='d-flex justify-content-start'> <div class='p-2 bd-highlight '> <!-- Box icone Surface --> <img src = 'surface.png' width = 60 px height = 60 px></div> <div class='p-2 bd-highlight '> <!-- Box titre surface --> <h2> Superficie : </h2></div> <div class='p-2 bd-highlight '> <!-- Box surface --> <p> <?php echo number_format($api[$_GET['cle']]->area,0,'1',' ')?> km2.</p></div></div></div></div></br> <?php $latitude = $api[$_GET['cle']]->latlng[0]; $longitude = $api[$_GET['cle']]->latlng[1]; if(empty($api[$_GET['cle']]->borders)) { echo "<div class='d-flex align-items-center'><div class='d-flex justify-content-start'><h2>Pays frontaliers : </h2><p>Ce pays est une île et ne comporte pas de frontières terrestres directes.</div></div></p>"; } else { echo "<div class='p-2 bd-highlight '><h2>Pays frontaliers : </div></h2>"; echo "<div class='d-flex flex-wrap'>"; foreach ($api[$_GET['cle']]->borders as $key=>$value) { $CleFrontiere = array_search ($value,$_SESSION['pays']['Cle']['Code']); $cleLien = array_keys($_SESSION['pays']['Cle']['Code'], $value); echo "<a href='Detail_pays.php?cle=".$cleLien[0]."'target='_blank'><img src=".$api[$CleFrontiere]->flag." class='images_petit'></a>"; } echo "</div>"; } // et maintenant l'API carte ?> </br> <div class='p-2 bd-highlight '><h2>Carte : </h2></div> </br> <div id="mapid"> </div> <script> var mymap = L.map('mapid').setView([<?php echo $latitude.", ".$longitude; ?>], 7); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(mymap); </script> </body> </html>
C#
UTF-8
2,481
3.515625
4
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BankingDatabase; namespace UnitTests { //Excecutes Unit tests for the bankingDatabase VS Project. class UnitTestExe { //The main/only method used for doing unit tests. //ONLY UNIT TESTS THE DATABASE. static void Main(string[] args) { //Build the databases. CustomerDB custDatabase = new CustomerDB(); AccountDB acctDatabase = new AccountDB(); //Add two customers to the database. Give Bill gates an account. He should be customer number 2, and have account number 100 (the first account). //The databases do all of the work creating the customers and accounts! custDatabase.addNewCustomer("Donald Trump", "New York City"); custDatabase.addNewCustomer("Bill Gates", "Microsoft Lane, Seatle"); int accountNum = acctDatabase.addNewAccount(2, 500.50); custDatabase.addAccountToCustomer(2, accountNum); //Customer numbers begin at 001 and increase from there. This should disply both customers with the correct information. Console.WriteLine(custDatabase.lookUpCustomer(1).toString()); Console.WriteLine(); Console.WriteLine(custDatabase.lookUpCustomer(2).toString()); Console.WriteLine(); //an actual customer will never be able to do this for obvious reasons. The system can, however. Console.Write("Bill Gates provides his account number (100), and should have his customer number returned (2): "); Console.WriteLine(acctDatabase.lookUpAccountReturnCustomerNumber(100)); Console.Write("Bill Gates makes a reqest for his balance (500.50): $"); Console.WriteLine(acctDatabase.returnAccountBalance(100)); Console.Write("Bill Gates withdraws $200. New Balance: $"); acctDatabase.withdrawFromAccount(100, 200.00); Console.WriteLine(acctDatabase.returnAccountBalance(100)); Console.Write("Bill Gates deposits $50. New Balance: $"); acctDatabase.depositIntoAccount(100, 50.00); Console.WriteLine("" + acctDatabase.returnAccountBalance(100)); Console.WriteLine("Unit tests complete. Press enter to quit."); Console.ReadLine(); } } }
PHP
UTF-8
1,035
3.21875
3
[]
no_license
<?php namespace App\Entity; class Airport { private $id; private $code; private $name; /** * Airport constructor. * @param $id * @param $code * @param $name */ public function __construct($id, $code, $name) { $this->id = $id; $this->code = $code; $this->name = $name; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return mixed */ public function getCode() { return $this->code; } /** * @param mixed $code */ public function setCode($code): void { $this->code = $code; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name): void { $this->name = $name; } }
C#
UTF-8
1,676
2.546875
3
[ "MIT" ]
permissive
// Copyright (c) 2007-2018 Thong Nguyen (tumtumtum@gmail.com) using System; using System.Collections.Generic; using System.Linq.Expressions; namespace Shaolinq.Persistence.Linq.Expressions { /// <summary> /// Represents an SQL function call such as DATE, YEAR, SUBSTRING or ISNULL. /// </summary> public class SqlFunctionCallExpression : SqlBaseExpression { public SqlFunction Function { get; } public string UserDefinedFunctionName { get; } public IReadOnlyList<Expression> Arguments { get; } public override ExpressionType NodeType => (ExpressionType)SqlExpressionType.FunctionCall; public SqlFunctionCallExpression(Type type, SqlFunction function, params Expression[] arguments) : this(type, function, arguments.ToReadOnlyCollection()) { } public SqlFunctionCallExpression(Type type, string userDefinedFunctionName, params Expression[] arguments) : this(type, SqlFunction.UserDefined, arguments.ToReadOnlyCollection()) { this.UserDefinedFunctionName = userDefinedFunctionName; } public SqlFunctionCallExpression(Type type, SqlFunction function, IEnumerable<Expression> arguments) : this(type, function, arguments.ToReadOnlyCollection()) { } public SqlFunctionCallExpression(Type type, string userDefinedFunctionName, IEnumerable<Expression> arguments) : this(type, SqlFunction.UserDefined, arguments.ToReadOnlyCollection()) { this.UserDefinedFunctionName = userDefinedFunctionName; } public SqlFunctionCallExpression(Type type, SqlFunction function, IReadOnlyList<Expression> arguments) : base(type) { this.Function = function; this.Arguments = arguments; } } }
Java
UTF-8
530
2.671875
3
[]
no_license
package business.validation; import java.util.ArrayList; import java.util.List; public class BusinessValidationImpl implements BusinessInvalidation { private List<BusinessRule> rules = new ArrayList<>(); public BusinessValidationImpl() {} public BusinessValidationImpl(BusinessRule rule) { withRule(rule); } @Override public Boolean exists() { return rules.stream().anyMatch(BusinessRule::check); } @Override public BusinessInvalidation withRule(BusinessRule rule) { rules.add(rule); return this; } }
Java
UTF-8
234
2.109375
2
[]
no_license
package cn.edu.nju.software.game.fighting.model.role.equipment.exception; public class FullEquipmentTypeException extends Exception { public FullEquipmentTypeException() { super("该装备类型的槽位已满"); } }
JavaScript
UTF-8
2,600
2.875
3
[]
no_license
'use strict'; /* Módosítsd a Storage nevű modul 3. feladatát úgy, hogy amennyiben a kérés során bármilyen hiba van, szintén a localStorage-ból olvassa ki az adatokat a program! Ilyenkor jeleníts meg egy üzenetet, hogy az alkalmazás offline! Amennyiben a localStorage is üres, jelents meg egy szabadon választott hibaüzenetet, és alapértelmezetten 5 másodpercenként ismételd meg újra a kérést összesen 10 alkalommal! Ez a két érték paraméterként megadható legyen! Ha a 10-ből bármelyik alkalommal sikeres a kérés, akkor aszerint járj el (kiíratás, tárolás, stb.). */ const userHandle = { getList(resolveFunction) { return new Promise((resolve, reject) => { resolve = resolveFunction? resolveFunction: resolve;// ha kapott paramétert, akkor az legyen a resolve fetch('./users.json') .then(response => { if(!response.ok){ throw new Error('File not found'); } else { return response.json(); } }) .then(data => resolve(data.users)) .catch(error => { console.error(error); if(this.repeatNum<this.repeat){ // még kell próbálkozni setTimeout(() => { this.getList(resolve);// az eredeti getList resolve-jára iratkoztak fel, ezért azt kell majd használni this.repeatNum++; }, this.delay*1000); } else { console.log('Az alkalmazás offline'); } }); }); }, showList(parent, delay=5, repeat=10) { this.delay = delay; this.repeat = repeat; this.repeatNum = 1; parent = document.querySelector(parent); if (localStorage.users && localStorage.users !== "[]") { const list = JSON.parse(localStorage.users); this.generateList(parent, list); } else { this.getList().then(list => { localStorage.setItem('users', JSON.stringify(list)); this.generateList(parent, list); }); } }, generateList(parent, list) { list.forEach(item => { const p = document.createElement('p'); p.classList.add('user-row'); p.textContent = `${item.firstName} ${item.lastName}`; parent.appendChild(p); }); } }; userHandle.showList('.container',3,10);
Java
UTF-8
6,133
2.671875
3
[]
no_license
package com.thenewprogramming.Bukkit.Vote4TempBan; import java.util.ArrayList; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class Vote4TempBan extends JavaPlugin{ //begin defining variables (made like this so it does not get in the way of other plugins) int VotingTask; private int yesvotes = 0; private int novotes = 0; private boolean votingcurrently = false; private ArrayList<String> playersvoted = new ArrayList<String>(); private ArrayList<String> playercooldown = new ArrayList<String>(); private ArrayList<String> playersbanned = new ArrayList<String>(); public int getyesvotes(){ return yesvotes; } public void setyesvotes(int yesvotes){ this.yesvotes = yesvotes; } public int getnovotes(){ return novotes; } public void setnovotes(int novotes){ this.novotes = novotes; } public boolean getvotingcurrently(){ return votingcurrently; } public void setvotingcurrently(boolean votingcurrently){ this.votingcurrently = votingcurrently; } public ArrayList<String> getplayersvoted(){ return playersvoted; } public void setplayersvoted(ArrayList<String> playersvoted){ this.playersvoted=playersvoted; } public ArrayList<String> getplayercooldown(){ return playercooldown; } public void setplayercooldown(ArrayList<String> playercooldown){ this.playercooldown=playercooldown; } public ArrayList<String> getplayersbanned(){ return playersbanned; } public void setplayersbanned(ArrayList<String> playersbanned){ this.playersbanned = playersbanned; } //end defining variables @Override public void onEnable(){ //init the config and listeners this.saveDefaultConfig(); getCommand("vote").setExecutor(new Vote4TempBanCommandExecutor(this)); new Vote4TempBanListener(this); getLogger().info("Vote4TempBan has been Enabled!"); } @Override public void onDisable() { getLogger().info("Vote4TempBan has been Disabled!"); } public void startvote(CommandSender sender, String[] args){ this.votingcurrently=true; //better managing the cooldowns in another class this.playercooldown(sender); final Player target = Bukkit.getServer().getPlayer(args[1]); String reason = args[2]; //converting args[3] to a string and pasting it inside reason. int loopcount = 3; while(!(loopcount==args.length)){ reason += " " + args[loopcount]; loopcount += 1; } Bukkit.getLogger().info(Vote4TempBan.this.getConfig().getStringList("messages.votestart").toString()); //some boring server messages Bukkit.getServer().broadcastMessage("§c"+sender.getName()+"§a has started a vote to temporarily ban:"); Bukkit.getServer().broadcastMessage("§aPlayer: §c"+target.getName()+"§a for reason: §c"+reason); Bukkit.getServer().broadcastMessage("§aTo vote, use: /vote yes/no"); Bukkit.getServer().broadcastMessage("§aThe vote will end in "+(Vote4TempBan.this.getConfig().getLong("timesettings.votelength")/20)/60+" min, be fast!"); VotingTask = this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { Bukkit.getServer().broadcastMessage("§aThe vote ended with:"); Bukkit.getServer().broadcastMessage("§ayes votes: §c"+yesvotes+"§a no votes: §c"+novotes); //here i check if the player will be banned or not if (yesvotes>novotes){ //i want at least 2 yes votes, otherwise it's not fair if (yesvotes>1){ target.kickPlayer("Think about what you've done and come back in "+(Vote4TempBan.this.getConfig().getLong("timesettings.bantime")/20)/60+" min"); //i need to manage who is banned or not, so i can unban them onDisable() playersbanned.add(target.getName()); Bukkit.getServer().broadcastMessage("§c"+target.getName()+"§a has been banned for "+(Vote4TempBan.this.getConfig().getLong("timesettings.bantime")/20)/60+" min"); //i wanted to have this piece of code a bit clean, so i put this somewhere else aftervote(target); } else{ Bukkit.getServer().broadcastMessage("§c"+target.getName()+"§a has been spared..."); } } else if (yesvotes<=novotes){ Bukkit.getServer().broadcastMessage("§c"+target.getName()+"§a has been spared..."); } //resetting variables votingcurrently=false; yesvotes=0; novotes=0; playersvoted.clear(); } }, Vote4TempBan.this.getConfig().getInt("timesettings.votelength")); } public void aftervote(final Player target){ //this part will make sure the player gets unbanned after the specified time. this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { playersbanned.remove(target.getDisplayName()); Bukkit.getServer().broadcastMessage("§c"+target.getName()+"§a has been unbanned... Watch out!"); } }, Vote4TempBan.this.getConfig().getInt("timesettings.bantime")); } public void playercooldown(final CommandSender sender){ //first of all, add the player to the cooled down players list playercooldown.add(sender.getName()); this.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { //after an hour, remove it from the list playercooldown.remove(sender.getName()); } }, Vote4TempBan.this.getConfig().getInt("timesettings.votecooldown")); } public void cancelvote(CommandSender sender){ votingcurrently=false; yesvotes=0; novotes=0; playersvoted.clear(); Bukkit.getServer().broadcastMessage("§c"+sender.getName()+"§a has canceled the voting."); this.getServer().getScheduler().cancelTask(VotingTask); } public void ubanplayer(CommandSender sender, String playername){ playersbanned.remove(playername); Bukkit.getServer().broadcastMessage("§c"+sender.getName()+"§c has ubanned §c"+ playername); Bukkit.getServer().broadcastMessage("§c"+playername+"§a has been unbanned... Watch out!"); } }
C++
UTF-8
1,433
3.296875
3
[]
no_license
#pragma once #include <unordered_map> #include <boost\thread.hpp> class Dictionary { private: std::unordered_map<std::string, size_t> wordToIdMap_; std::unordered_map<size_t, std::string> IdToWordMap_; boost::shared_mutex mutex_; size_t IdCounter_; size_t getNewId() { return IdCounter_++; } public: Dictionary() : IdCounter_(0) { } ~Dictionary() { std::cout << "Dictionary destroyed" << std::endl; } size_t getId(std::string& word) { boost::shared_lock<boost::shared_mutex> readLock(mutex_); auto wordIterator = wordToIdMap_.find(word); if (wordIterator != wordToIdMap_.end()) { return wordIterator->second; } else { readLock.unlock(); boost::unique_lock<boost::shared_mutex> writeLock(mutex_); auto wordNewIterator = wordToIdMap_.find(word); if (wordNewIterator != wordToIdMap_.end()) { return wordIterator->second; } else { size_t id = getNewId(); wordToIdMap_.emplace(word, id); IdToWordMap_.emplace(id, word); return id; } } } std::string& getWord(size_t id) { boost::shared_lock<boost::shared_mutex> readLock(mutex_); auto wordIterator = IdToWordMap_.find(id); if (wordIterator != IdToWordMap_.end()) { return wordIterator->second; } else { throw std::logic_error("Invalid id" + std::to_string(id)); } } size_t getSize() { return wordToIdMap_.size(); } };
Java
UTF-8
314
2.5
2
[]
no_license
package entity.gameboard; import java.awt.Color; public class Company extends Field { public Company(String navn, String description, Color color, int price, int index, int pawnValue) { super(navn, description, color, index); this.isOwned = false; this.price = price; this.pawnValue = pawnValue; } }
Markdown
UTF-8
9,151
2.859375
3
[]
no_license
+ 默认全局配置文件 + application.properties ``` server.port = 8888 ``` + 对于如果想要针对不同场景使用不同的properties文件(比如存在以下三个配置文件) + application.properties + application-dev.properties + application-prod.properties ``` 如果进行配置,系统会默认选择第一个配置文件 如果想要指定第二个配置文件则需要在application.properties文件中加入:spring.profiles.active = dev 同理指定为第三个配置文件:spring.profiles.active = prod ``` + application.yml ``` 通过缩进表示嵌套关系,冒号后如果有值需要加空格 server: port: 8888 ``` + 如果想在不同场景下使用不同的yml配置 + 在yml文件中使用---表示不同的配置区块 ``` server: port: 8080 spring: profiles: active: prod --- server: port: 8081 spring: profiles: dev --- server: port: 8082 spring: profiles: prod ``` + 或者使用终端命令启动时加入配置 ``` --spring.profiles.active = prod ``` + 以上两者都可以为类的对象赋值但是类文件需要两个注解 ``` @Component @ConfigurationProperties(prefix="nickname") public class student { .... } .yml中 nickname: name: zs set: - xxx - xxx list: - xxx - xxx map: {key1: 1,key2: 2} ``` + 当内容分布在不同文件中时使用@ProperySource指定文件与@ConfigurationProperties配合使用 ``` @ProperySource(value = {classpath: xxx.properties}) ``` + 使用xml配置项目 + idea中新建springconfig类型的xml文件编辑内容,通过bean的id寻找方法,class寻找类 + ImportResource(locations = {"classpath: xxx.xml"}) + 或者不用上面的注释,创建配置类完成xml配置导入,配置类标识@Configuration,通过@Bean标识与xml中id相对应的方法 + 启动方式 + idea运行程序时注意 ``` 如果是module创建多个项目很可能在运行项目时启动路径一直默认为第一个项目路径,需要在运行配置的working directory中写入:$MODULE_DIR$ ``` + 编译器内run + 在项目文件夹下 ``` mvn spring-boot:run ``` + 部署到服务器中 ``` mvn clear package java -jar target/xxx.jar ``` + 基本概念 + bean <p>javabean简单的讲就是实体类,用来封装对象,这个类里面全部都是属性值,和get,set方法。</p> + 注解(参考http://blog.csdn.net/weixin_39805338/article/details/80770472) + @GetMapping("/path") <p>内容在某路径下生效</p> + @Value("${xxx}")在配置文件properties中对xxx进行赋值 ``` @Value("${now}") private String now; ``` + @PostConstruct 和 @PreDestory <p>实现初始化和销毁bean之前进行的操作,只能有一个方法可以用此注释进行注释,方法不能有参数,返回值必需是void,方法需要是非静态的。</p> + @Autowired <p> Autowired默认先按byType,如果发现找到多个bean,则,又按照byName方式比对,如果还有多个,则报出异常。 1.可以手动指定按byName方式注入,使用@Qualifier。 //通过此注解完成从spring配置文件中 查找满足Fruit的bean,然后按//@Qualifier指定pean @Autowired @Qualifier(“pean”) public Fruit fruit; 2.如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) public Fruit fruit; </p> + @Lazy(true) <p>用于指定该Bean是否取消预初始化,用于注解类,延迟初始化</p> + @Primary <p>自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常</p> + @Resource <pre> 默认按 byName(id)自动注入,如果找不到再按byType(class)找bean,如果还是找不到则抛异常,无论按byName还是byType如果找到多个,则抛异常。 可以手动指定bean,它有2个属性分别是name和type,使用name属性,则使用byName的自动注入,而使用type属性时则使用byType自动注入。 @Resource(name=”bean名字”) 或 @Resource(type=”bean的class”) 这个注解是属于J2EE的,减少了与spring的耦合。 </pre> + @Async <pre> java里使用线程用3种方法: 1. 继承Thread,重写run方法 2. 实现Runnable,重写run方法 3. 使用Callable和Future接口创建线程,并能得到返回值 @Async可视为第4种方法。基于@Async标注的方法,称之为异步方法,这个注解用于标注某个方法或某个类里面的所有方法都是需要异步处理的。被注解的方法被调用的时候,会在新线程中执行,而调用它的方法会在原来的线程中执行。 </pre> + @Named <pre> @Named和Spring的@Component功能相同。@Named可以有值,如果没有值生成的Bean名称默认和类名相同。比如 @Named public class Person 或 @Named(“cc”) public class Person </pre> + @Validated <pre> @Valid是对javabean的校验,如果想对使用@RequestParam方式接收参数方式校验使用@Validated </pre> + @CrossOrigin <pre> 是Cross-Origin ResourceSharing(跨域资源共享)的简写 </pre> + @RestController <pre> @RestController = @Controller + @ResponseBody。 是2个注解的合并效果,即指定了该controller是组件,又指定方法返回的是String或json类型数据,不会解决成jsp页面,注定不够灵活,如果一个Controller即有SpringMVC返回视图的方法,又有返回json数据的方法即使用@RestController太死板。 灵活的作法是:定义controller的时候,直接使用@Controller,如果需要返回json可以直接在方法中添加@ResponseBody </pre> + @Controller:处理http请求 + @ResponseBody <pre> 当加上@ResponseBody注解后不会解析成跳转地址 会解析成相应的json格式的对象 集合 字符串或者xml等直接返回给前台 可以通过 ajax 的“success”:fucntion(data){} data直接获取到。 </pre> + @RequestMapping <pre> 处理映射请求的注解。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。有6个属性。 1、 value, method: value:指定请求的实际地址,指定的地址可以是URI Template 模式; method:指定请求的method类型, GET、POST、PUT、DELETE等; @RequestMapping(value = “/testValid”, method = RequestMethod.POST) 2、 consumes,produces: consumes: 指定处理请求的提交内容类型(Content-Type),例如@RequestMapping(value = ”/test”, consumes=”application/json”)处理application/json内容类型 produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回; 3、 params、headers: params: 指定request中必须包含某些参数值是,才让该方法处理。 headers:指定request中必须包含某些指定的header值,才能让该方法处理请求 </pre> + @GetMapping和@PostMapping <pre> @GetMapping(value = “page”)等价于@RequestMapping(value = “page”, method = RequestMethod.GET) @PostMapping(value = “page”)等价于@RequestMapping(value = “page”, method = RequestMethod.POST) </pre> + @Override是伪代码,表示重写(当然不写也可以),不过写上有如下好处: <pre> 1、可以当注释用,方便阅读; 2、编译器可以给你验证@Override下面的方法名是否是你父类中所有的,如果没有则报错。例如,你如果没写@Override,而你下面的方法名又写错了,这时你的编译器是可以编译通过的,因为编译器以为这个方法是你的子类中自己增加的方法。 </pre>
C
UTF-8
238
3.09375
3
[ "MIT" ]
permissive
#include <stdio.h> struct s { int a; int b; char *c; }; int main() { struct s x={19,83,"Zhang"}; struct s *px=&x; printf("%d,%d,%s,",px->a,(*px).b, px->c); printf("%c,%s\n",*px->c-1, &px->c[1]); return 0; }
Java
UTF-8
367
2.09375
2
[]
no_license
package cn.zw.spring.aop.advice; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class HiZwAfterMethod implements AfterReturningAdvice{ public void afterReturning(Object returnValue, Method method, Object[] arg2, Object target) throws Throwable { System.out.println("HiZwAfterMethod : After method hizw"); } }
Markdown
UTF-8
2,828
3.515625
4
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
# Bar series A bar chart shows price movements in the form of bars. Vertical line length of a bar is limited by the highest and lowest price values. Open & Close values are represented by tick marks, on the left & right hand side of the bar respectively. ![Bar chart example](./images/bar-series.png "Bar chart example") ## How to create bar series ```javascript const barSeries = chart.addBarSeries({ thinBars: false, }); // set the data barSeries.setData([ { time: "2018-12-19", open: 141.77, high: 170.39, low: 120.25, close: 145.72 }, { time: "2018-12-20", open: 145.72, high: 147.99, low: 100.11, close: 108.19 }, { time: "2018-12-21", open: 108.19, high: 118.43, low: 74.22, close: 75.16 }, { time: "2018-12-22", open: 75.16, high: 82.84, low: 36.16, close: 45.72 }, { time: "2018-12-23", open: 45.12, high: 53.90, low: 45.12, close: 48.09 }, { time: "2018-12-24", open: 60.71, high: 60.71, low: 53.39, close: 59.29 }, { time: "2018-12-25", open: 68.26, high: 68.26, low: 59.04, close: 60.50 }, { time: "2018-12-26", open: 67.71, high: 105.85, low: 66.67, close: 91.04 }, { time: "2018-12-27", open: 91.04, high: 121.40, low: 82.70, close: 111.40 }, { time: "2018-12-28", open: 111.51, high: 142.83, low: 103.34, close: 131.25 }, { time: "2018-12-29", open: 131.33, high: 151.17, low: 77.68, close: 96.43 }, { time: "2018-12-30", open: 106.33, high: 110.20, low: 90.39, close: 98.10 }, { time: "2018-12-31", open: 109.87, high: 114.69, low: 85.66, close: 111.26 }, ]); ``` ## Data format Each item of the bar series is [OHLC](./ohlc.md) item. ## Customization By default, bars are displayed as thin sticks each being 1 px wide. Bar width can be increased to 2 px by disabling the `thinBars` option. Colors for rising & falling bars have to be set separately. A bar series series interface can be customized using the following set of options: |Name|Type|Default|Description| |----|----|-------|-----------| |`thinBars`|`boolean`|`true`|If true, bars are represented as sticks| |`upColor`|`string`|`#26a69a`|Growing bar color| |`downColor`|`string`|`#ef5350`|Falling bar color| |`openVisible`|`boolean`|`true`|If true, then the open line of a bar is shown| ### Examples - set initial options for bar series: ```javascript const barSeries = chart.addBarSeries({ thinBars: false, upColor: 'rgba(37, 148, 51, 0.2)', downColor: 'rgba(191, 55, 48, 0.2)', openVisible: true, }); ``` - change options after series is created: ```javascript // for example, let's disable thin bars and open price visibility barSeries.applyOptions({ thinBars: false, openVisible: false, }); ``` ## What's next - [Customization](./customization.md) - [OHLC](./ohlc.md) - [Time](./time.md)
PHP
UTF-8
2,091
2.78125
3
[]
no_license
<?php /** Chapters * */ class Chapters { public function __construct($id){ if($id != ''){ $book = do_query_obj("SELECT * FROM chapters WHERE id=$id", LMS_Database); if(isset($book->id)){ foreach($book as $key =>$value){ $this->$key = $value; } return $this; } else { return false; } } else { return false;} } public function getName(){ return $this->title; } public function getUnits(){ if(!isset($this->units)){ $units = do_query_array("SELECT id FROM summarys WHERE chapter_id=$this->id", LMS_Database); $out = array(); foreach($units as $unit){ $out[] = new Units($unit->id); } $this->units = $out; } return $this->units; } public function getUnitsTable(){ $trs= array(); $units = $this->getUnits(); foreach($units as $unit){ $trs[] = fillTemplate("modules/lms/templates/summary_list.tpl", $unit); /*$trs[] = write_html('tr', '', write_html('td', 'width="24"', write_html('button', 'type="button" action="openSummary" summaryid="'.$unit->id.'" class="ui-state-default hoverable circle_button"', write_icon('extlink')) ). write_html('td', '', $unit->getName()) );*/ } $out = write_html('table', 'class="result"', write_html('tbody', '', implode('', $trs)) ); return $out; } static function _save($post){ $result = false; if(isset($post['id']) && $post['id'] != ''){ $result = do_update_obj($post, 'id='.$post['id'], 'chapters', LMS_Database); } elseif(isset($post['id'])){ $result = do_insert_obj($post, 'chapters', LMS_Database); } if($result!=false){ $answer['id'] = $result; $answer['error'] = ""; } else { global $lang; $answer['id'] = ""; $answer['error'] = $lang['error_updaing']; } return json_encode($answer); } static function _delete($id){ if(do_query_edit("DELETE FROM chapters WHERE id=$id", LMS_Database)){ $answer['id'] = $id; $answer['error'] = ""; } else { global $lang; $answer['id'] = ""; $answer['error'] = $lang['error_updaing']; } return json_encode($answer); } }
Python
UTF-8
3,624
2.5625
3
[ "MIT" ]
permissive
import sys import os import shapefile from shapely import geometry #from shapely.geometry import shape import pprint pp = pprint.PrettyPrinter(indent = 4) import zipfile import tempfile import shutil class Chorpleth: def __init__(self, the_type): assert the_type in ['state', 'county'] if the_type == 'state': path = os.path.join(sys.prefix, 'map_data', 'cb_2017_us_state_5m.zip') else: path = os.path.join(sys.prefix, 'map_data', 'cb_2017_us_county_5m.zip') temp_dir = tempfile.mkdtemp() with zipfile.ZipFile(path) as zip_ref: zip_ref.extractall(temp_dir) if the_type == 'state': path = os.path.join(temp_dir, 'cb_2017_us_state_5m.shp' ) else: path = os.path.join(temp_dir, 'cb_2017_us_county_5m.shp' ) xs, ys, names = self.create_sf_data(path) shutil.rmtree(temp_dir) self.dict = {} self.points_dict = {} for counter, i in enumerate(names): #getting rid of small territories belonging to AK if not self.points_dict.get(i): self.points_dict[i] = [] self.points_dict[i].append((xs[counter], ys[counter])) """ if i == 'AK': if max(xs[counter]) < 0: self.points_dict[i].append((xs[counter], ys[counter])) else: self.points_dict[i].append((xs[counter], ys[counter])) """ for counter, i in enumerate(xs): if not self.dict.get(names[counter]): self.dict[names[counter]] = [] self.dict[names[counter]].append(geometry.Polygon(list(zip(i, ys[counter]))[0:-1])) def add_names(slef, indices, itererator, names): for i in indices: names.append(itererator.record[4]) def make_all_data(self, sf): counter = 0 xs = [] ys = [] names = [] for i in sf.iterShapeRecords(): indices = i.shape.parts.tolist() x_polygon = self.make_polygon(indices, i, 'x') xs.extend(self.make_polygon(indices, i, 'x')) ys.extend(self.make_polygon(indices, i, 'y')) self.add_names(indices, i, names) return xs, ys, names def make_polygon(self, indices, itererator, x_or_y): if x_or_y == 'x': index = 0 else: index = 1 x = [x[index] for x in itererator.shape.points] return [x[i:j] + [float('NaN')] for i, j in zip(indices, indices[1:]+[None])] def create_sf_data(self, shape_path): sf = shapefile.Reader(shape_path) xs, ys, names = self.make_all_data(sf) assert len(xs) == len(ys) assert len(xs) == len(names) return xs, ys, names def get_id_of_shape(self, points): p = geometry.Point(points) for key in list(self.dict.keys()): shapes = self.dict[key] for sh in shapes: if sh.contains(p): return key return None def get_shape(self, the_id): return self.dict.get(the_id) def get_points(self, the_id): return self.points_dict.get(the_id) def get_points_flatten(self, the_id): xs = [] ys = [] if not self.points_dict.get(the_id): return None, None for i in self.points_dict[the_id]: xs += i[0] ys += i[1] return (xs, ys) if __name__ == '__main__': choropleth = Chorpleth(the_type = 'state') print(choropleth.get_id_of_shape((-71.097320, 42.338124)))
Java
UTF-8
272
1.75
2
[]
no_license
package lesson_1.homework_1; import lombok.*; @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor public class Telefon { private int id; private String Brend; private String Model; private double DisplaySize; private int MemorySize; }
PHP
UTF-8
1,053
2.546875
3
[]
no_license
<?php namespace Paypal\Api; include_once('AbstractRequestType.php'); class DoReauthorizationRequestType extends AbstractRequestType { /** * @var string $AuthorizationID * @access public */ public $AuthorizationID = null; /** * @var BasicAmountType $Amount * @access public */ public $Amount = null; /** * @var string $MsgSubID * @access public */ public $MsgSubID = null; /** * @param DetailLevelCodeType[] $DetailLevel * @param string $ErrorLanguage * @param string $Version * @param string $any * @param string $AuthorizationID * @param BasicAmountType $Amount * @param string $MsgSubID * @access public */ public function __construct($DetailLevel, $ErrorLanguage, $Version, $any, $AuthorizationID, $Amount, $MsgSubID) { parent::__construct($DetailLevel, $ErrorLanguage, $Version, $any); $this->AuthorizationID = $AuthorizationID; $this->Amount = $Amount; $this->MsgSubID = $MsgSubID; } }
Swift
UTF-8
2,804
3.453125
3
[]
no_license
// // String+Extensions.swift // Mestika Dashboard // // Created by Prima Jatnika on 26/10/20. // import Foundation import UIKit extension String { var digits: [Int] { var result = [Int]() for char in self { if let number = Int(String(char)) { result.append(number) } } return result } func replace(myString: String, _ index: [Int], _ newChar: Character) -> String { var chars = Array(myString) if chars.count > 5 { for data in index { chars[data] = newChar } } let modifiedString = String(chars) return modifiedString } func index(from: Int) -> Index { return self.index(startIndex, offsetBy: from) } func substring(from: Int) -> String { let fromIndex = index(from: from) return String(self[fromIndex...]) } func substring(to: Int) -> String { let toIndex = index(from: to) return String(self[..<toIndex]) } func substring(with r: Range<Int>) -> String { let startIndex = index(from: r.lowerBound) let endIndex = index(from: r.upperBound) return String(self[startIndex..<endIndex]) } func subStringRange(from: Int, to: Int) -> String { let startIndex = self.index(self.startIndex, offsetBy: from) let endIndex = self.index(self.startIndex, offsetBy: to) return String(self[startIndex..<endIndex]) } func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } func toBase64() -> String { return Data(self.utf8).base64EncodedString() } func base64ToImage() -> UIImage? { let cleanBase64 = self.replacingOccurrences(of: "data:image/jpeg;base64,", with: "") .replacingOccurrences(of: "data:image/png;base64,", with: "") if let dataDecoded = Data(base64Encoded: cleanBase64, options: []), let img = UIImage(data: dataDecoded) { return img } else { return nil } } func thousandSeparator() -> String { if let num = Int64(self) { return num.formattedWithSeparator } else { return self } } func isNotEmpty() -> Bool { return !self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } func toDate(withFormat format: String = "dd-MM-YYYY")-> Date?{ let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "in_ID") dateFormatter.dateFormat = format let date = dateFormatter.date(from: self) return date } }
Java
UTF-8
174
1.859375
2
[ "MIT" ]
permissive
package org.home.polukeev.model; import java.util.EventListener; public interface ModelListener extends EventListener { void modelChanged(ModelEvent event); }
Python
UTF-8
90
2.640625
3
[]
no_license
k = int(input()) s = [int(x) for x in list(str(k))] S = sum(s) print(S) for k in K
C++
UTF-8
1,741
2.875
3
[ "MIT" ]
permissive
#ifndef CMAKE_CMAKEFUNCTION_H #define CMAKE_CMAKEFUNCTION_H #include <memory> #include <string> #include <vector> namespace cmake { struct FilePosition { unsigned int line_; unsigned int column_; }; struct CmakeFunctionArgument { CmakeFunctionArgument(std::string value); CmakeFunctionArgument(std::string value, bool quoted); CmakeFunctionArgument(std::string value, const FilePosition position); CmakeFunctionArgument(std::string value, const FilePosition position, bool quoted); std::string value_; std::shared_ptr<FilePosition> position_; bool quoted_; }; class CmakeFunction { public: static std::shared_ptr<CmakeFunction> create( const std::string& name, const std::vector<CmakeFunctionArgument>& arguments ); static std::shared_ptr<CmakeFunction> create( const std::string& name, const std::vector<CmakeFunctionArgument>& arguments, const FilePosition startPosition, const FilePosition endPosition ); bool hasPosition() const; const std::string& name() const; const FilePosition* startPosition() const; const FilePosition* endPosition() const; const std::vector<CmakeFunctionArgument>& arguments() const; void move(const int lines); void insertArgument(const unsigned int position, const CmakeFunctionArgument& argument); void removeArgument(const std::string& name); private: CmakeFunction( const std::string& name, const std::vector<CmakeFunctionArgument>& arguments, std::unique_ptr<FilePosition> startPosition, std::unique_ptr<FilePosition> endPosition ); std::string name_; std::vector<CmakeFunctionArgument> arguments_; std::unique_ptr<FilePosition> startPosition_; std::unique_ptr<FilePosition> endPosition_; }; } #endif
Python
UTF-8
2,231
2.9375
3
[]
no_license
import pandas as pd import logging import requests from flask import current_app log = logging.getLogger('demo.covidapiclient') # covid-api client class CovidApiClient: countries_df = None # init method or constructor def __init__(self, countries_df): self.countries_df = countries_df # Get data def get_results(self): if self.countries_df is None: return None # Init results df results_df = pd.DataFrame( columns=['date', 'iso', 'num_confirmed', 'num_deaths', 'num_recovered']) for index, row in self.countries_df.iterrows(): # Create payload payload = { 'iso': row['iso'], 'date': row['date'] } # GET Request try: r = requests.get( current_app.config["REPORTS_FULL_URL"], params=payload).json() except Exception as e: log.error( "couldn't retreive data from covid-api with error: {}\n Make sure you're using YYYY-MM-DD format in the input csv file (default: /input/countries.csv".format(e)) return None # Get summaries num_confirmed, num_deaths, num_recovered = self.get_summaries(r) # Add results into a result_df results_df = results_df.append({'date': row['date'], 'iso': row['iso'], 'num_confirmed': num_confirmed, 'num_deaths': num_deaths, 'num_recovered': num_recovered}, ignore_index=True) return results_df # Aggregate country data to obtain total summaries for that country def get_summaries(self, r): # Check data is valid if r.get("data") is None or len(r.get("data")) == 0: return None, None, None # Init num_confirmed = 0 num_deaths = 0 num_recovered = 0 for region in r.get("data"): num_confirmed = num_confirmed + region.get("confirmed") num_deaths = num_deaths + region.get("deaths") num_recovered = num_recovered + region.get("recovered") return num_confirmed, num_deaths, num_recovered
Java
UTF-8
422
1.523438
2
[]
no_license
package com.google.zxing.client.android; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; /** * Created by xiong on 2018/2/1. */ public class aaa extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aaa); } }
Java
UTF-8
1,928
2.234375
2
[]
no_license
package com.mpa.leaderboard; import android.os.Parcel; import android.os.Parcelable; import android.widget.ImageView; import androidx.databinding.BindingAdapter; import androidx.databinding.ObservableField; import com.mpa.leaderboard.Leader; import com.squareup.picasso.Picasso; public class IqLeader extends Leader implements Parcelable { public ObservableField<Integer> score = new ObservableField<Integer>(); public IqLeader(String name, String country, String badgeUrl,int score) { try { this.name.set(name); this.country.set(country); this.badgeUrl.set(badgeUrl); this.score.set(score); } catch (Exception e) { e.printStackTrace(); } } protected IqLeader(Parcel in) { name.set(in.readString()); country.set(in.readString()); badgeUrl.set(in.readString()); score.set(in.readInt()); } public static final Creator<IqLeader> CREATOR = new Creator<IqLeader>() { @Override public IqLeader createFromParcel(Parcel in) { return new IqLeader(in); } @Override public IqLeader[] newArray(int size) { return new IqLeader[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(name.get()); parcel.writeString(country.get()); parcel.writeString(badgeUrl.get()); parcel.writeInt(score.get()); } @BindingAdapter({"android:imageUrl"}) public static void loadImage(ImageView view, String imageUrl) { Picasso.with(view.getContext()) .load(imageUrl) .placeholder(R.drawable.skill) .into(view); } }
SQL
GB18030
10,708
3.484375
3
[]
no_license
CREATE OR REPLACE PROCEDURE P_TMP_CHEAT_USER_ALARM_D(V_DATE VARCHAR2, V_RETCODE OUT VARCHAR2, V_RETINFO OUT VARCHAR2) IS /***************************************************************** * --%NAME:P_TMP_CHEAT_USER_ALARM_D *ִ --%PERIOD: * --%CREATOR:MAJIANHUI *ʱ --%CREATED_TIME:2017-12-3 *******************************************************************/ V_PKG VARCHAR2(40); V_PROCNAME VARCHAR2(40); V_COUNT NUMBER; V_COUNT2 NUMBER; V_LAST_DAY VARCHAR2(20); V_LAST_DAY_7 VARCHAR2(20); CURSOR V_AREA IS SELECT * FROM DIM.DIM_AREA_NO WHERE AREA_NO <> '018'; BEGIN V_PKG := 'ÿթûԤ'; V_PROCNAME := 'P_TMP_CHEAT_USER_ALARM_D'; V_LAST_DAY := TO_CHAR(TO_DATE(V_DATE, 'YYYYMMDD') - 1, 'YYYYMMDD'); V_LAST_DAY_7 := TO_CHAR(TO_DATE(V_DATE, 'YYYYMMDD') - 7, 'YYYYMMDD'); SELECT COUNT(1) INTO V_COUNT FROM DW.DW_EXECUTE_LOG A WHERE A.ACCT_MONTH = V_DATE AND A.PROCNAME IN ('P_DW_V_USER_CDR_CDMA_OCS', 'P_DW_V_USER_CDR_CDMA', 'P_DW_V_USER_TERMINAL_D') AND A.RESULT = 'SUCCESS'; SELECT COUNT(*) INTO V_COUNT2 FROM (SELECT AREA_NO, DEVICE_NUMBER FROM TMP_RISK_USER MINUS SELECT * FROM TMP_RISK_USER_LAST); --־ ALLDM.P_ALLDM_INSERT_LOG(V_DATE, V_PKG, V_PROCNAME, '12', SYSDATE); IF V_COUNT >= 3 THEN ------------------1ȡÿҡݻ--------------------- --EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_CHEAT_MID_01'; DELETE FROM TMP_CHEAT_MID_01 WHERE DAY_ID = V_LAST_DAY_7; COMMIT; DELETE FROM TMP_CHEAT_MID_01 WHERE DAY_ID = V_DATE; COMMIT; FOR C1 IN V_AREA LOOP INSERT INTO TMP_CHEAT_MID_01 SELECT V_DATE, C1.AREA_NO, DEVICE_NUMBER, ORG_TRM_ID, OPPOSE_NUMBER, CELL_NO, FUNC_GET_QIZHA_REGION(ROAM_AREA_CODE) FROM DW.DW_V_USER_CDR_CDMA_OCS WHERE ACCT_MONTH = SUBSTR(V_DATE, 1, 6) AND CALL_DATE = SUBSTR(V_DATE, 7, 2) AND AREA_NO = C1.AREA_NO AND ROAM_AREA_CODE IN ('384', '395','305','568','912','713','503','825') UNION ALL SELECT V_DATE, C1.AREA_NO, DEVICE_NUMBER, ORG_TRM_ID, OPPOSE_NUMBER, CELL_NO, FUNC_GET_QIZHA_REGION(ROAM_AREA_CODE) FROM DW.DW_V_USER_CDR_CDMA WHERE ACCT_MONTH = SUBSTR(V_DATE, 1, 6) AND CALL_DATE = SUBSTR(V_DATE, 7, 2) AND AREA_NO = C1.AREA_NO AND ROAM_AREA_CODE IN ('384', '395','305','568','912','713','503','825'); COMMIT; END LOOP; ------------------CI⣬ж永ûûб仯б仯͸--------------------- IF V_COUNT2 <> 0 THEN EXECUTE IMMEDIATE 'TRUNCATE TABLE MID_RISK_CELL'; INSERT INTO MID_RISK_CELL SELECT CELL_NO, LEVEL_IDX FROM (SELECT CELL_NO, LEVEL_IDX, ROW_NUMBER() OVER(PARTITION BY CELL_NO ORDER BY LEVEL_IDX ASC) RN FROM (SELECT A.CELL_NO, COUNT(*) LEVEL_IDX FROM TMP_CHEAT_MID_01 A, TMP_RISK_USER B WHERE A.DEVICE_NUMBER = B.DEVICE_NUMBER GROUP BY A.CELL_NO UNION ALL SELECT * FROM TMP_MAJH_RISK_CELL)) WHERE RN = 1; COMMIT; EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_MAJH_RISK_CELL'; INSERT INTO TMP_MAJH_RISK_CELL SELECT * FROM MID_RISK_CELL; COMMIT; END IF; ------------------2ռȡɢͳû--------------------- EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_CHEAT_MID_02'; INSERT INTO TMP_CHEAT_MID_02 SELECT V_DATE, T.AREA_NO, T.DEVICE_NUMBER, ZHU_CALL_CDR, BEI_CALL_CDR, BEI_USER_CDR, T.ROAM_REGION FROM (SELECT T.DEVICE_NUMBER, T.AREA_NO, T.ROAM_REGION, SUM(CASE WHEN ORG_TRM_ID = '10' THEN 1 ELSE 0 END) ZHU_CALL_CDR, SUM(CASE WHEN ORG_TRM_ID = '11' THEN 1 ELSE 0 END) BEI_CALL_CDR, COUNT(DISTINCT CASE WHEN ORG_TRM_ID = '10' THEN OPPOSE_NUMBER END) BEI_USER_CDR FROM TMP_CHEAT_MID_01 T GROUP BY T.DEVICE_NUMBER, T.AREA_NO,T.ROAM_REGION) T WHERE T.ZHU_CALL_CDR / (T.ZHU_CALL_CDR + T.BEI_CALL_CDR) > 0.83232 AND T.BEI_USER_CDR / T.ZHU_CALL_CDR > 0.70928 AND T.ZHU_CALL_CDR > 3; COMMIT; ------------------3永ķCIû--------------------- EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_CHEAT_MID_03'; INSERT INTO TMP_CHEAT_MID_03 SELECT V_DATE, B.AREA_NO, B.DEVICE_NUMBER, A.LEVEL_IDX,B.ROAM_REGION FROM TMP_MAJH_RISK_CELL A, TMP_CHEAT_MID_01 B WHERE A.CELL_NO = B.CELL_NO; COMMIT; ------------------4עնϢ--------------------- EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_CHEAT_MID_04'; INSERT INTO TMP_CHEAT_MID_04 SELECT V_DATE, AREA_NO, DEVICE_NO DEVICE_NUMBER, TERMINAL_CODE, TERMINAL_MODEL, TERMINAL_CORP FROM DW.DW_V_USER_TERMINAL_D WHERE ACCT_MONTH = TO_CHAR(SYSDATE - 1, 'YYYYMM') AND DAY_ID = TO_CHAR(SYSDATE - 1, 'DD') AND TO_CHAR(REG_DATE, 'YYYYMMDD') = V_DATE AND LENGTH(TERMINAL_CODE) > 8 --޳쳣ն; ; COMMIT; ------------------ն˿⣬ж永ûûб仯б仯͸--------------------- IF V_COUNT2 <> 0 THEN EXECUTE IMMEDIATE 'TRUNCATE TABLE MID_RISK_DEVICE'; INSERT INTO MID_RISK_DEVICE SELECT TERMINAL_CODE, TERMINAL_CORP, TERMINAL_MODEL, TERMINAL_TYPE FROM (SELECT TERMINAL_CODE, TERMINAL_CORP, TERMINAL_MODEL, TERMINAL_TYPE, ROW_NUMBER() OVER(PARTITION BY TERMINAL_CODE ORDER BY TERMINAL_TYPE) RN FROM (SELECT B.TERMINAL_CODE, B.TERMINAL_CORP, B.TERMINAL_MODEL, '1' TERMINAL_TYPE FROM TMP_RISK_USER A, (SELECT DEVICE_NO, TERMINAL_CODE, TERMINAL_CORP, TERMINAL_MODEL FROM DW.DW_V_USER_TERMINAL_D WHERE ACCT_MONTH = SUBSTR(V_DATE,1,6) AND DAY_ID = SUBSTR(V_DATE,7,2) AND LENGTH(TERMINAL_CODE) > 8) B WHERE A.DEVICE_NUMBER = B.DEVICE_NO AND A.DAY_ID = V_DATE UNION SELECT * FROM TMP_ZQP_RISK_DEVICE)) WHERE RN = 1; COMMIT; EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_ZQP_RISK_DEVICE'; INSERT INTO TMP_ZQP_RISK_DEVICE SELECT * FROM MID_RISK_DEVICE; COMMIT; END IF; ------------------5û--------------------- DELETE FROM TMP_CHEAT_RISK_USER WHERE DAY_ID = V_DATE; COMMIT; INSERT INTO TMP_CHEAT_RISK_USER SELECT V_DATE, B.AREA_DESC, A.DEVICE_NUMBER, MAX(CASE WHEN FLAG = '1' THEN '1' ELSE '0' END) CALL_RISK_FLAG, MAX(CASE WHEN FLAG = '2' THEN '1' ELSE '0' END) CELL_RISK_FLAG, MAX(CASE WHEN FLAG = '3' THEN '1' ELSE '0' END) TERMINAL_RISK_FLAG, NVL(A.ROAM_REGION,''), FUNC_GET_QIZHA_FLAG(A.ROAM_REGION) FROM (SELECT AREA_NO, DEVICE_NUMBER, '1' FLAG, ROAM_REGION FROM TMP_CHEAT_MID_02 UNION SELECT AREA_NO, DEVICE_NUMBER, '2', ROAM_REGION FROM TMP_CHEAT_MID_03 UNION SELECT AREA_NO, DEVICE_NUMBER, '3' , '' FROM TMP_CHEAT_MID_04 X, TMP_ZQP_RISK_DEVICE Y WHERE X.TERMINAL_CODE = Y.TERMINAL_CODE) A, DIM.DIM_AREA_NO B, (SELECT * FROM TMP_CHEAT_RISK_USER WHERE DAY_ID <= V_LAST_DAY) C WHERE A.AREA_NO = B.AREA_NO AND A.DEVICE_NUMBER = C.DEVICE_NUMBER(+) AND C.DEVICE_NUMBER IS NULL GROUP BY B.AREA_DESC, A.DEVICE_NUMBER, B.IDX_NO, NVL(A.ROAM_REGION,''),FUNC_GET_QIZHA_FLAG(A.ROAM_REGION) ORDER BY B.IDX_NO; COMMIT; --·û EXECUTE IMMEDIATE 'TRUNCATE TABLE TMP_RISK_USER_LAST'; INSERT INTO TMP_RISK_USER_LAST SELECT AREA_NO,DEVICE_NUMBER FROM TMP_RISK_USER; COMMIT; --־ V_RETCODE := 'SUCCESS'; ALLDM.P_ALLDM_UPDATE_LOG(V_DATE, V_PKG, V_PROCNAME, '', 'SUCCESS', SYSDATE); ELSE V_RETCODE := 'WAIT'; ALLDM.P_ALLDM_UPDATE_LOG(V_DATE, V_PKG, V_PROCNAME, 'ȴ', 'WAIT', SYSDATE); END IF; EXCEPTION WHEN OTHERS THEN V_RETCODE := 'FAIL'; V_RETINFO := SQLERRM; ALLDM.P_ALLDM_UPDATE_LOG(V_DATE, V_PKG, V_PROCNAME, V_RETINFO, 'FAIL', SYSDATE); END; /
Shell
UTF-8
1,091
3.03125
3
[ "CC0-1.0" ]
permissive
GetIconDir() { echo './src/00_denv/01_md/00_icon'; } GetIconPath() { echo "$(GetIconDir)/${1,,}.svg"; } #https://github.com/ytyaru/Image.Icon.20191120145829/src/00_denv/01_md/00_icon GetRootAbsDir() { local dir="${1:-$(GetThisDir)}" local name="$(basename $dir)" local abs_parent="$(cd $(dirname $dir); pwd)" [ '/' = "$abs_parent" ] && return; [ 'src' = "$name" ] && { echo "$abs_parent"; return; } || GetRootAbsDir "$abs_parent"; } GetIconAbsDir() { echo "$(GetRootAbsDir "$(GetThisDir)")/src/00_denv/01_md/00_icon"; } GetIconAbsPath() { echo "$(GetIconAbsDir)/${1,,}.svg"; } GetThisDir() { echo "$(cd $(dirname $0); pwd)"; } GetIconRealDir() { realpath --relative-to="$(GetThisDir)" "$(GetIconAbsDir)"; } GetIconRealPath() { echo "$(GetIconRealDir)/${1,,}.svg"; } #GetRootAbsDir "$(GetThisDir)" #GetIconRealDir #GetIconRealPath linux #GetIconRealPath debian #GetIconRealPath raspbian #echo $(GetIconPath linux) #echo $(GetIconPath debian) #echo $(GetIconPath raspbian) #GetThisDir #GetIconDir #GetIconRealDir #GetIconRealPath linux #GetIconRealPath debian #GetIconRealPath raspbian
Python
UTF-8
349
3
3
[]
no_license
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: remain = {} for i in range(len(nums)): if nums[i] in remain: # note that checking if nums[i] exists in key is O(1) return [remain[nums[i]], i] else: remain[ target - nums[i] ] = i
Markdown
UTF-8
2,739
2.9375
3
[]
no_license
# emscripten-sdl2-ogles2 *OpenGL to WebGL using Emscripten* Demonstrates the basics of porting desktop graphics to the web using Emscripten, via a collection of code samples. Code is written in C++, SDL2, and OpenGLES2 and transpiled into Javascript and WebGL by Emscripten. ### [Run Hello Triangle](https://erik-larsen.github.io/emscripten-sdl2-ogles2/hello_triangle.html) ([source](https://github.com/erik-larsen/emscripten-sdl2-ogles2/blob/master/src/hello_triangle.cpp)) ![Hello Triangle](media/hello_triangle.png) Demonstrates a colorful triangle using shaders, with support for mouse and touch input: * Pan using left mouse or finger drag. * Zoom using mouse wheel or pinch gesture. ### [Run Hello Texture](https://erik-larsen.github.io/emscripten-sdl2-ogles2/hello_texture.html) ([source](https://github.com/erik-larsen/emscripten-sdl2-ogles2/blob/master/src/hello_texture.cpp)) ![Hello Texture](media/hello_texture.png) Demonstrates a textured triangle, using SDL to load an image from a file. ### [Run Hello Text](https://erik-larsen.github.io/emscripten-sdl2-ogles2/hello_text_ttf.html) ([source](https://github.com/erik-larsen/emscripten-sdl2-ogles2/blob/master/src/hello_text_ttf.cpp)) ![Hello Text](media/hello_text_ttf.png) Demonstrates TrueType text, using SDL to render a string into a texture and apply it to a quad. ### [Run Hello Texture Atlas](https://erik-larsen.github.io/emscripten-sdl2-ogles2/hello_text_txf.html) ([source](https://github.com/erik-larsen/emscripten-sdl2-ogles2/blob/master/src/hello_text_txf.cpp)) ![Hello Texture Atlas](media/hello_text_txf.png) Demonstrates SGI's Texfont text, loading a font texture atlas from a .txf file and applying it to a quad, as well as rendering of text strings. ### [Run Hello Image](https://erik-larsen.github.io/emscripten-sdl2-ogles2/hello_image.html) ([source](https://github.com/erik-larsen/emscripten-sdl2-ogles2/blob/master/src/hello_image.cpp)) ![Hello Image](media/hello_image.png) Demonstrates a checkberboard background texture created from an in-memory pixel array. ## Motivation ### Why Emscripten? For users, running an app in the browser is the ultimate convenience: no need to manually install anything, and the app can run equally well on desktop, tablet, and phone. For developers, Emscripten does the work to produce optimal Javascript/WASM, replacing the boring and error-prone process of manually porting code. ### Why SDL2? These demos require OS-dependent stuff (keyboard, mouse, touch, text, audio, networking, etc.). SDL provides a cross-platform library to access this. ### Why OpenGLES2? WebGL provides GPU-accelerated graphics in the browser, and OpenGLES is the subset of OpenGL which most closely matches WebGL.
JavaScript
UTF-8
666
2.734375
3
[]
no_license
class dustbin { constructor(){ this.bottomBody=Bodies.rectangle(1100,530,200,20, {isStatic:true}) this.leftWallBody=Bodies.rectangle(990,490,20,100,{isStatic:true}) this.rightWallBody=Bodies.rectangle(1200,490,20,100,{isStatic:true}) World.add(world, this.bottomBody) World.add(world, this.leftWallBody) World.add(world, this.rightWallBody); } display() { var posBottom=this.bottomBody.position; var posLeft=this.leftWallBody.position; var posRight=this.rightWallBody.position; fill("black") rect(posLeft.x,posLeft.y,20,100); rect(posRight.x,posRight.y,20,100 ); rect(posBottom.x,posBottom.y,200,20 ); } }
Java
UTF-8
2,952
2.234375
2
[]
no_license
package com.jikgorae.api.organization.application; import static com.jikgorae.api.fixture.OrganizationFixture.*; import static com.jikgorae.api.organization.domain.RandomOrganizationCodeGenerator.*; import static com.jikgorae.api.organization.exception.OrganizationAlreadyExistsException.*; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.jikgorae.api.organization.domain.CustomOrganizationCodeGenerator; import com.jikgorae.api.organization.domain.Organization; import com.jikgorae.api.organization.domain.OrganizationCodeGenerator; import com.jikgorae.api.organization.domain.OrganizationRepository; import com.jikgorae.api.organization.exception.OrganizationAlreadyExistsException; @ExtendWith(value = MockitoExtension.class) class OrganizationServiceTest { @Mock private OrganizationRepository organizationRepository; private OrganizationCodeGenerator organizationCodeGenerator; private OrganizationService organizationService; @BeforeEach void setUp() { organizationCodeGenerator = new CustomOrganizationCodeGenerator(); organizationService = new OrganizationService(organizationRepository, organizationCodeGenerator); } @DisplayName("조직 생성 메서드 호출 시 동일한 이름의 조직이 존재하는지 확인 후 생성 코드를 포함하여 생성") @Test void create() { when(organizationRepository.existsByName(anyString())).thenReturn(false); when(organizationRepository.existsByCode(anyString())).thenAnswer( invocation -> { Object argument = invocation.getArgument(0); return argument.equals("000000"); } ); when(organizationRepository.save(any())).thenReturn(직고래); Organization organization = organizationService.create(직고래_요청); assertAll( () -> assertThat(organization.getId()).isNotNull(), () -> assertThat(organization.getName()).isEqualTo(직고래_NAME), () -> assertThat(organization.getCode()).hasSize(CODE_LENGTH) ); } @DisplayName("이미 존재하는 조직의 경우 OrganizationAlreadyExistsException 예외 발생") @Test void create_OrganizationAlreadyExistsException() { when(organizationRepository.existsByName(anyString())).thenReturn(true); assertThatThrownBy(() -> organizationService.create(직고래_요청)) .isInstanceOf(OrganizationAlreadyExistsException.class) .hasMessage(ALREADY_EXISTS_ORGANIZATION_NAME); } }
Java
UTF-8
520
2.296875
2
[ "MIT" ]
permissive
package com.sdet.auto.pageObjects; import static com.sdet.auto.seleniumExtensions.WebDriverExtensions.getElementBySelector; public class ForgetPasswordPage { private final static String txtEmail = "#email"; private final static String btnRetrievePassword = ".icon-2x.icon-signin"; public static void EnterEmail(String email){ getElementBySelector(txtEmail).sendKeys(email); } public static void ClickRetrieveButton(){ getElementBySelector(btnRetrievePassword).click(); } }
Java
UTF-8
997
3.8125
4
[]
no_license
package iterator; import java.util.ArrayList; import java.util.Iterator; //下面是输出的例子 public class DeepIteratorImp { public static Iterator getIterator(ArrayList lists) { return new DeepIterator(lists); } public static void main(String[] args) { ArrayList finalLists = new ArrayList(); finalLists.add(0); ArrayList firstLevelList = new ArrayList(); firstLevelList.add(1); firstLevelList.add(2); finalLists.add(firstLevelList); finalLists.add(3); firstLevelList = new ArrayList(); firstLevelList.add(4); ArrayList secondLevelList = new ArrayList(); secondLevelList.add(5); secondLevelList.add(6); firstLevelList.add(secondLevelList); finalLists.add(firstLevelList); System.out.print("The original Lists is --- > " + finalLists); Iterator iterator = getIterator(finalLists); System.out.println(); System.out.print("The flatten Lists is --- > "); while (iterator.hasNext()) { System.out.print(iterator.next() + " --> "); } } }
Java
UTF-8
7,326
1.898438
2
[]
no_license
package com.giveu.shoppingmall.me.view.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.view.Gravity; import android.view.View; import android.widget.TextView; import com.android.volley.mynet.BaseBean; import com.android.volley.mynet.BaseRequestAgent; import com.giveu.shoppingmall.R; import com.giveu.shoppingmall.base.BaseActivity; import com.giveu.shoppingmall.base.BaseApplication; import com.giveu.shoppingmall.base.CustomDialog; import com.giveu.shoppingmall.model.ApiImpl; import com.giveu.shoppingmall.utils.CommonUtils; import com.giveu.shoppingmall.utils.LoginHelper; import com.giveu.shoppingmall.utils.StringUtils; import com.giveu.shoppingmall.utils.ToastUtils; import com.giveu.shoppingmall.utils.listener.TextChangeListener; import com.giveu.shoppingmall.widget.ClickEnabledTextView; import com.giveu.shoppingmall.widget.EditView; import com.giveu.shoppingmall.widget.SendCodeTextView; import com.giveu.shoppingmall.widget.dialog.NormalHintDialog; import com.giveu.shoppingmall.widget.emptyview.CommonLoadingView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 修改手机号 * Created by 101900 on 2017/6/29. */ public class ChangePhoneNumberActivity extends BaseActivity { @BindView(R.id.tv_send_code) SendCodeTextView tvSendCode; @BindView(R.id.et_phone_number) EditView etPhoneNumber; @BindView(R.id.et_send_code) EditView etSendCode; @BindView(R.id.tv_finish) ClickEnabledTextView tvFinish; @BindView(R.id.tv_unreceived) TextView tvUnreceived; private CustomDialog callDialog; private TextView tvDial; String randCode;//校验交易密码返回的随机码 String phoneNumber; NormalHintDialog changeSuccessDialog; public static void startIt(Activity mActivity, String randCode) { Intent intent = new Intent(mActivity, ChangePhoneNumberActivity.class); intent.putExtra("randCode", randCode); mActivity.startActivity(intent); } @Override public void initView(Bundle savedInstanceState) { setContentView(R.layout.activity_change_phone_number); baseLayout.setTitle("修改手机号"); tvSendCode.setSendTextColor(false); randCode = getIntent().getStringExtra("randCode"); initCallDialog(); changeSuccessDialog = new NormalHintDialog(mBaseContext, "绑定手机修改成功!\n\n", "登录手机号已同步,请通过绑定手机+登录密码登录"); changeSuccessDialog.setOnDialogDismissListener(new NormalHintDialog.OnDialogDismissListener() { @Override public void onDismiss() { finish(); } }); } @Override public void setListener() { super.setListener(); etPhoneNumber.checkFormat(11); etSendCode.checkFormat(6); etPhoneNumber.addTextChangedListener(new TextChangeListener() { @Override public void afterTextChanged(Editable s) { buttonCanClick(false); } }); etSendCode.addTextChangedListener(new TextChangeListener() { @Override public void afterTextChanged(Editable s) { buttonCanClick(false); } }); } private void initCallDialog() { callDialog = new CustomDialog(mBaseContext, R.layout.dialg_dial_phone, R.style.customerDialog, Gravity.CENTER, false); tvDial = (TextView) callDialog.findViewById(R.id.tv_dial); tvDial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { callDialog.dismiss(); CommonUtils.callPhone(mBaseContext, "4001868888"); } }); } @Override public void setData() { } private void buttonCanClick(boolean showToast) { tvFinish.setClickEnabled(false); String phoneNumber = StringUtils.getTextFromView(etPhoneNumber); String sendCode = StringUtils.getTextFromView(etSendCode); if (!StringUtils.checkPhoneNumberAndTipError(phoneNumber, showToast)) { return; } if (StringUtils.isNull(sendCode)) { if (showToast) { ToastUtils.showShortToast("请输入6位验证码"); } return; } else if (sendCode.length() != 6) { if (showToast) { ToastUtils.showShortToast("请输入6位验证码"); } return; } if (!showToast) { tvFinish.setClickEnabled(true); } } @Override protected void onDestroy() { super.onDestroy(); if (tvSendCode != null) { tvSendCode.onDestory(); } } @OnClick({R.id.tv_send_code, R.id.tv_finish, R.id.tv_unreceived}) @Override public void onClick(View view) { super.onClick(view); phoneNumber = StringUtils.getTextFromView(etPhoneNumber); String sendCode = StringUtils.getTextFromView(etSendCode); switch (view.getId()) { case R.id.tv_send_code: if (phoneNumber.length() == 11) { ApiImpl.sendSMSCode(mBaseContext, phoneNumber, "updatephone", new BaseRequestAgent.ResponseListener<BaseBean>() { @Override public void onSuccess(BaseBean response) { tvSendCode.startCount(null); } @Override public void onError(BaseBean errorBean) { CommonLoadingView.showErrorToast(errorBean); } }); } else { ToastUtils.showShortToast("请输入11位的手机号"); } break; case R.id.tv_finish: if (tvFinish.isClickEnabled()) { ApiImpl.updatePhone(mBaseContext, LoginHelper.getInstance().getIdPerson(), phoneNumber, randCode, sendCode, new BaseRequestAgent.ResponseListener<BaseBean>() { @Override public void onSuccess(BaseBean response) { LoginHelper.getInstance().setPhone(phoneNumber); BaseApplication.getInstance().fetchUserInfo(); changeSuccessDialog.showDialog(); } @Override public void onError(BaseBean errorBean) { NormalHintDialog normalHintDialog = new NormalHintDialog(mBaseContext, errorBean.message); normalHintDialog.showDialog(); } }); } else { buttonCanClick(true); } break; case R.id.tv_unreceived: callDialog.show(); break; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
Shell
UTF-8
6,366
3.46875
3
[]
no_license
#!/bin/bash # # Wocker環境かどうか # read -p "Is Wocker? [y/n]" ANSWER case $ANSWER in "" | "Y" | "y" | "yes" | "Yes" | "YES" ) PREFIX="wocker";; *) PREFIX="";; esac # # Download sample text files # 別にtxtファイルを用意した場合に上書きされるのを防ぐため、ダウンロードするか選択式に。 # read -p "Download Sample Text Files? [y/n]" DOWNLOAD_ANSWER # # 同じパーマリンクのページを削除してから作成するかどうか # read -p "Remove same permalink pages? [y/n]" REMOVE_ANSWER # # Download sample text files # case $DOWNLOAD_ANSWER in "" | "Y" | "y" | "yes" | "Yes" | "YES" ) mkdir page-contents if [ $PREFIX = "wocker" ]; then DOWNLOAD_TXT_PREFIX="docker exec $(docker ps -q)" else DOWNLOAD_TXT_PREFIX="" fi $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/company.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/company.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/company-message.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/company-message.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/company-history.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/company-history.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/access.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/access.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/facility.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/facility.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/business.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/business.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/recruit.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/recruit.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/faq.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/faq.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/contact.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/contact.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/sitemap.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/sitemap.html $DOWNLOAD_TXT_PREFIX curl -L -o page-contents/privacy.html https://raw.githubusercontent.com/esnetk6/wp-cli-page-create-sample/master/page-contents/privacy.html ;; esac # # Remove same pages # case $REMOVE_ANSWER in "" | "Y" | "y" | "yes" | "Yes" | "YES" ) $PREFIX wp post delete --force $($PREFIX wp post list --name="company" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="message" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="history" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="access" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="facility" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="business" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="recruit" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="faq" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="contact" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="sitemap" --post_type="page" --field="ID") $PREFIX wp post delete --force $($PREFIX wp post list --name="privacy" --post_type="page" --field="ID") ;; esac # # wp post create # # 会社概要 $PREFIX wp post create page-contents/company.html --post_title="会社概要" --post_name="company" --post_type="page" --post_status="publish" --page_template="default" --user="1" # 会社概要 / ご挨拶 $PREFIX wp post create page-contents/company-message.html --post_title="ご挨拶" --post_name="message" --post_type="page" --post_status="publish" --page_template="default" --user="1" --post_parent=$($PREFIX wp post list --post_type="page" --field="ID" --name="company") # 会社概要 / 沿革 $PREFIX wp post create page-contents/company-history.html --post_title="沿革" --post_name="history" --post_type="page" --post_status="publish" --page_template="default" --user="1" --post_parent=$($PREFIX wp post list --post_type="page" --field="ID" --name="company") # アクセス $PREFIX wp post create page-contents/access.html --post_title="アクセス" --post_name="access" --post_type="page" --post_status="publish" --page_template="default" --user="1" # 施設案内 $PREFIX wp post create page-contents/facility.html --post_title="施設案内" --post_name="facility" --post_type="page" --post_status="publish" --page_template="default" --user="1" # 業務内容 $PREFIX wp post create page-contents/business.html --post_title="業務内容" --post_name="business" --post_type="page" --post_status="publish" --page_template="default" --user="1" # 求人情報 $PREFIX wp post create page-contents/recruit.html --post_title="求人情報" --post_name="recruit" --post_type="page" --post_status="publish" --page_template="default" --user="1" # よくあるご質問 $PREFIX wp post create page-contents/faq.html --post_title="よくあるご質問" --post_name="faq" --post_type="page" --post_status="publish" --page_template="default" --user="1" # お問い合わせ $PREFIX wp post create page-contents/contact.html --post_title="お問い合わせ" --post_name="contact" --post_type="page" --post_status="publish" --page_template="default" --user="1" # サイトマップ $PREFIX wp post create page-contents/sitemap.html --post_title="サイトマップ" --post_name="sitemap" --post_type="page" --post_status="publish" --page_template="default" --user="1" # プライバシーポリシー $PREFIX wp post create page-contents/privacy.html --post_title="プライバシーポリシー" --post_name="privacy" --post_type="page" --post_status="publish" --page_template="default" --user="1"
C
UTF-8
5,210
3.5625
4
[]
no_license
// Joshua Johnson // R11486776 // CS1412-001 // Puzzle Game in C // 12/6/16 // Scaffold for puzzle problem #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX_FILE_LENGTH 30 #define PUZZLE_SIDE 4 #define EMPTY_SLOT 0 void loadPuzzle(int puzzle[][PUZZLE_SIDE], FILE *fin); int getMove(); void printPuzzle(int puzzle[][PUZZLE_SIDE]); int doMove(int puzzle[][PUZZLE_SIDE], int move); void swap(int *a, int *b); int solved(int puzzle[][PUZZLE_SIDE]); int main() { int puzzle[PUZZLE_SIDE][PUZZLE_SIDE]; char filename[31]; int ans = 0; // Had to change this line to make it work in visual studio srand(time(0)); printf("Welcome to the PUZZLE game!\n"); // Get the puzzle file. printf("Enter the file storing all of the puzzle configurations.\n"); scanf_s("%s", filename, sizeof(filename)); while (ans != 2) { FILE *fin; errno_t file = fopen_s(&fin, filename, "r"); // Had to change this line to make it work in visual studio // Load the puzzle. loadPuzzle(puzzle, fin); fclose(fin); // Let's play! int move; printPuzzle(puzzle); move = getMove(); // Keep on playing until the user gives up. while (move != 0) { // Execute this move, seeing if it's okay. int okay = doMove(puzzle, move); // Print an error message for an invalid move. if (!okay) { printf("Sorry, that is not a valid square to slide into "); printf(" the open slot.\nNo move has been executed.\n"); } // Get out of the game for a winning move! else if (solved(puzzle)) break; // Go get the next move. printPuzzle(puzzle); move = getMove(); } // Output an appropriate puzzle ending message. if (move != 0) printf("Great, you solved the puzzle!!!\n"); else printf("Sorry, looks like you gave up on the puzzle.\n"); // Get their next selection. printf("Which selection would you like?\n"); printf("1. Load a new puzzle.\n"); printf("2. Quit.\n"); scanf_s("%d", &ans); } } // Pre-conditions: fin is pointed to the beginning of a file with a valid // file format for this problem. // Post-conditions: A random puzzle from the file pointed to by fin will be // stored in puzzle. void loadPuzzle(int puzzle[][PUZZLE_SIDE], FILE *fin) { int numOfPuzzles, selectedPuzzle, i = 0, j, x, y, number; int *ptr = NULL; // Read in the file if it doesn't exist, exit if (fin != NULL) { // Read the first line in the file fscanf_s(fin, "%d", &numOfPuzzles); selectedPuzzle = rand() % numOfPuzzles; // Read all ints after until you the selected puzzle is reached then start storing them in the puzzle array while (!feof (fin)) { if (selectedPuzzle == 0) { for (x = 0; x < PUZZLE_SIDE; x++) { for (y = 0; y < PUZZLE_SIDE; y++) { fscanf_s(fin, "%d", &number); puzzle[x][y] = number; } } break; } fscanf_s(fin, "%d", &number); i++; if (i == selectedPuzzle * (PUZZLE_SIDE * PUZZLE_SIDE)) { for (x = 0; x < PUZZLE_SIDE; x++) { for (y = 0; y < PUZZLE_SIDE; y++) { fscanf_s(fin, "%d", &number); puzzle[x][y] = number; } } } } } else { printf("file error\n"); exit(-1); } } // Pre-conditions: none. // Post-conditions: A basic menu will be prompted and the user's result returned. int getMove() { int move; printf("\nWhich piece would you like to slide into the open slot?\nNote, answering 0 means you quit the game without winning\n"); scanf_s("%d", &move, sizeof(move)); return move; } // Pre-conditions: A valid puzzle is stored in puzzle. // Post-conditions: A depiction of the puzzle will be printed out. void printPuzzle(int puzzle[][PUZZLE_SIDE]) { int i, j; printf("\n"); for (i = 0; i < PUZZLE_SIDE; i++) { for (j = 0; j < PUZZLE_SIDE; j++) { if (puzzle[i][j] == 0) { printf("_\t"); } else printf("%d\t", puzzle[i][j]); } printf("\n"); } } // Pre-conditions: puzzle stores a valid puzzle configuration. // Post-conditions: If move is a valid square to slide into the open slot, // the move is executed and 1 is returned. Otherwise, 0 // is returned and no change is made to puzzle. int doMove(int puzzle[][PUZZLE_SIDE], int move) { int *ptr = NULL, *ptr2 = NULL, j, k, i; for (j = 0; j < PUZZLE_SIDE; j++) { for (k = 0; k < PUZZLE_SIDE; k++) { if (puzzle[j][k] == 0) { ptr2 = &puzzle[j][k]; } if (puzzle[j][k] == move) { ptr = &puzzle[j][k]; } } if ((ptr - ptr2 == 1) || (ptr - ptr2 == -1)) { swap(ptr, ptr2); return 0; } else if ((ptr - ptr2 == 4) || (ptr - ptr2 == -4)) { swap(ptr, ptr2); return 0; } else return 1; } } // Pre-condition: none // Post-condition: swaps the values in the variables pointed to by a and b. void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; printf("%d and %d", a, b); } // Pre-condition: puzzle stores a valid puzzle configuration. // Post-condition: Returns 1 if puzzles is solved, 0 otherwise. int solved(int puzzle[][PUZZLE_SIDE]) { int i, j, temp = -1; for (i = 0; i < PUZZLE_SIDE; i++) { for (j = 0; j < PUZZLE_SIDE; j++) { if (temp > puzzle[i][j]) { return 0; } temp = puzzle[i][j]; } } return 1; }
C#
UTF-8
1,005
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlSharp.Elements; namespace HtmlSharp.Css { public class AttributeExactFilter : AttributeFilter { string text; public AttributeExactFilter(string type, string text) : base(type) { this.text = text; } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } else { AttributeExactFilter t = (AttributeExactFilter)obj; return text.Equals(t.text) && base.Equals(obj); } } public override int GetHashCode() { return base.GetHashCode() ^ text.GetHashCode(); } public override IEnumerable<Tag> Apply(IEnumerable<Tag> tags) { return tags.Where(tag => tag[type] == text); } } }
Python
UTF-8
6,942
2.953125
3
[ "MIT" ]
permissive
class Node: def __init__(self, var, posCof, negCof): self.var = var self.posCof = posCof self.negCof = negCof class Formula: def __init__(self, node, compBit): self.node = node self.compBit = compBit class ROBDD: # init def __init__(self, varSeq): self.varSeq = varSeq + ['1'] self.table = dict() self.formulas = dict() self.addLeafNode() self.formulas['T'] = Formula(self.leafNode, False) self.formulas['F'] = Formula(self.leafNode, True) self.formulas['1'] = self.formulas['T'] self.formulas['0'] = self.formulas['F'] for var in varSeq: self.formulas[var] = Formula(Node(var, self.formulas['T'], self.formulas['F']), False) self.formulas['~'+var] = Formula(Node(var, self.formulas['T'], self.formulas['F']), True) # add the leaf node '1' def addLeafNode(self): self.leafNode = Node('1', None, None) entry = ('1', -1, -1, -1, -1) self.table[entry] = self.leafNode # add a node to the unique table # returns a Node def addNode(self, var, posCof, negCof): if self.cmpFormula(posCof, negCof): return posCof.node, posCof.compBit pc = self.cpyFormula(posCof) nc = self.cpyFormula(negCof) # guarentee that the posCof edge must be a regular edge cb = pc.compBit if cb: pc.compBit = not(pc.compBit) nc.compBit = not(nc.compBit) # check if repetitive node node = self.findNode(var, pc, nc) if node != None: return node, cb # add a new node else: entry = (var, id(pc.node), pc.compBit, id(nc.node), nc.compBit) # create a new node node = Node(var, pc, nc) self.table[entry] = node return node, cb # find a node from the unique table # returns None if not found def findNode(self, var, posCof, negCof): if var == '1': return self.leafNode pc = posCof nc = negCof entry = (var, id(pc.node), pc.compBit, id(nc.node), nc.compBit) node = self.table.get(entry) return node # add a new formula to the formula collection def addFormula(self, Xstr, var, posCof, negCof, compBit): node, cb = self.addNode(var, posCof, negCof) X = Formula(node, compBit ^ cb) self.formulas[Xstr] = X return X # apply ite(F,G,H) and add the formula to the formula collection self.formulas # calls self.applyIteRec to apply ite recursively def addIteFormula(self, Xstr, Fstr, Gstr, Hstr): F = self.formulas[Fstr] G = self.formulas[Gstr] H = self.formulas[Hstr] X = self.applyIte(F, G, H, 0) self.formulas[Xstr] = X return X # apply ite(F,G,H) recursively # returns a Formula def applyIte(self, F, G, H, varIndex): # check terminal cases if self.cmpFormula(F, self.formulas['T']): return G elif self.cmpFormula(F, self.formulas['F']): return H elif self.cmpFormula(G, self.formulas['T']) and self.cmpFormula(H, self.formulas['F']): return F elif self.cmpFormula(G, self.formulas['F']) and self.cmpFormula(H, self.formulas['T']): return Formula(F.node, not F.compBit) # F.node的index可能大于varIndex(一次跳多级) var = self.varSeq[varIndex] if F.node.var == var: Fpc = F.node.posCof Fnc = F.node.negCof if F.compBit == True: Fpc = self.cpyFormula(Fpc) Fnc = self.cpyFormula(Fnc) Fpc.compBit = not Fpc.compBit Fnc.compBit = not Fnc.compBit else: Fpc = F Fnc = F if G.node.var == var: Gpc = G.node.posCof Gnc = G.node.negCof if G.compBit == True: Gpc = self.cpyFormula(Gpc) Gnc = self.cpyFormula(Gnc) Gpc.compBit = not Gpc.compBit Gnc.compBit = not Gnc.compBit else: Gpc = G Gnc = G if H.node.var == var: Hpc = H.node.posCof Hnc = H.node.negCof if H.compBit == True: Hpc = self.cpyFormula(Hpc) Hnc = self.cpyFormula(Hnc) Hpc.compBit = not Hpc.compBit Hnc.compBit = not Hnc.compBit else: Hpc = H Hnc = H # apply ite recursively posCof = self.applyIte(Fpc, Gpc, Hpc, varIndex + 1) negCof = self.applyIte(Fnc, Gnc, Hnc, varIndex + 1) # add the new node node, cb = self.addNode(var, posCof, negCof) return Formula(node, cb) # apply cofactor and add the formula to the formula collection self.formulas # calls self.applyCof to apply cofactor recursively def addCofFormula(self, Fstr, tgVar, sign): tgVarIndex = self.varSeq.index(tgVar) F = self.formulas[Fstr] X = self.applyCof(F, tgVarIndex, sign) self.formulas[Fstr + sign + tgVar] = X # apply cofactor # returns a Formula def applyCof(self, F, tgVarIndex, sign): # check terminal cases if tgVarIndex < self.varSeq.index(F.node.var): return F pc = self.cpyFormula(F.node.posCof) nc = self.cpyFormula(F.node.negCof) if F.compBit == True: pc.compBit = not pc.compBit nc.compBit = not nc.compBit if tgVarIndex == self.varSeq.index(F.node.var): if sign == '+': return pc else: return nc # apply cofactor posCof = self.applyCof(pc) negCof = self.applyCof(nc) # add the new node node, cb = self.addNode(F.node.var, posCof, negCof) return Formula(node, cb) # compares two formulas def cmpFormula(self, F1, F2): return F1.node == F2.node and F1.compBit == F2.compBit # copies a formula def cpyFormula(self, F): return Formula(F.node, F.compBit) # def showFormula(self, Xstr): X = self.formulas[Xstr] if X.node.var == '1': print(Xstr, '=', not X.compBit) else: print(Xstr, '=', end = ' ') self.showRec(X, False, list()) print(0) def showRec(self, X, compBit, varList): if X.node == self.leafNode: if X.compBit ^ compBit: return else: for var in varList: print(var, end = '') print(' + ', end = '') else: self.showRec(X.node.posCof, compBit ^ X.compBit, varList + [X.node.var]) self.showRec(X.node.negCof, compBit ^ X.compBit, varList + ['~' + X.node.var])
Markdown
UTF-8
991
3.890625
4
[]
no_license
# ALGORITHMS This repository contains codes of various algorithms required for coding interview preparation ## KADANE'S ALGORITHM: kadane's algorithm helps us to compute maximum subarray sum in linear time -> O(N); where N is the size of the input array. According to kadane's algorithm , we don't need to compute sums of all possible subarray (and find out the greatest sum). Instead, we can do in a single loop by maintaining 2 variables (current_sum, max_sum)."max_sum" variable gives the maximum sum of subarray. ## SEARCHING AN ELEMENT IN A SORTED BUT ROTATED ARRAY: Searching an element in a sorted but rotated array can be done by the application of binary search in O(logn) time.The first main step is to find if the mid lies in first fragment or second fragment (1st and 2nd fragments explained in code). After finding mid two cases arise for each possibility of mid(part1 and part2 search space).Whwn we get the search space apply binary search.
Java
UTF-8
899
2.234375
2
[ "MIT" ]
permissive
package com.barbershop.com.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.barbershop.com.model.UserRegisterModel; import com.barbershop.com.repository.UserRegisterRepository; @Service public class ImplementUserDetailService implements UserDetailsService { @Autowired UserRegisterRepository repository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserRegisterModel user = repository.findUserByLogin(username); if(user == null) { throw new UsernameNotFoundException("user not found "); } return user; } }
Java
UTF-8
7,056
2.1875
2
[]
no_license
package org.hedera.io.etl; import static org.hedera.io.input.WikiRevisionInputFormat.SKIP_NON_ARTICLES; import static org.hedera.io.input.WikiRevisionInputFormat.SKIP_REDIRECT; import static org.hedera.io.input.WikiRevisionInputFormat.START_TITLE; import static org.hedera.io.input.WikiRevisionInputFormat.END_TITLE; import static org.hedera.io.input.WikiRevisionInputFormat.START_NAMESPACE; import static org.hedera.io.input.WikiRevisionInputFormat.END_NAMESPACE; import static org.hedera.io.input.WikiRevisionInputFormat.START_ID; import static org.hedera.io.input.WikiRevisionInputFormat.END_ID; import static org.hedera.io.input.WikiRevisionInputFormat.START_REVISION; import static org.hedera.io.input.WikiRevisionInputFormat.START_REDIRECT; import java.io.IOException; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.log4j.Logger; import org.hedera.io.RevisionHeader; import org.mortbay.log.Log; /** * A default WikiRevisionETLReader that extracts title, page id, namespace * from the page header */ public abstract class DefaultRevisionETLReader<KEYIN, VALUEIN> extends RevisionETLReader<KEYIN, VALUEIN, RevisionHeader> { private static final Logger LOG = Logger.getLogger(DefaultRevisionETLReader.class); // option to whether skip non-article or redirect pages protected boolean skipNonArticles = false; protected boolean skipRedirect = false; @Override public void initialize(InputSplit input, TaskAttemptContext tac) throws IOException, InterruptedException { super.initialize(input, tac); skipNonArticles = tac.getConfiguration() .getBoolean(SKIP_NON_ARTICLES, false); skipRedirect = tac.getConfiguration() .getBoolean(SKIP_REDIRECT, false); LOG.info("Splitting option: [skip non-article: " + skipNonArticles + ", skip redirect: " + SKIP_REDIRECT + "]"); } @Override protected RevisionHeader initializeMeta() { return new RevisionHeader(); } @Override // Read the page header // -1: EOF // 1 - outside the <page> tag // 2 - just passed the <page> tag but outside the <title> // 3 - just passed the <title> tag // 4 - just passed the </title> tag but outside the <namespace> // 5 - just passed the <namespace> // 6 - just passed the </namespace> but outside the <id> // 7 - just passed the (page's) <id> // 8 - just passed the </id> tag but outside the <revision> // 9 - (optionally) just passed the <redirect> // 10 - just passed the (next) <revision> protected Ack readToPageHeader(RevisionHeader meta) throws IOException { int i = 0; int flag = 2; boolean skipped = false; int revOrRedirect = -1; try (DataOutputBuffer pageTitle = new DataOutputBuffer(); DataOutputBuffer nsBuf = new DataOutputBuffer(); DataOutputBuffer keyBuf = new DataOutputBuffer()) { while (true) { if (!fetchMore()) return Ack.EOF; while (hasData()) { byte b = nextByte(); // when passing the namespace and we realize that // this is not an article, and that the option of skipping // non-article pages is on, we simply skip everything until // the closing </page> if (skipped) { if (flag >= 6) { Log.warn("Peculiar read after skipping namespace"); /* if (b == END_PAGE[i]) { i++; } else i = 0; if (i >= END_PAGE.length) { return Ack.SKIPPED; } */ return Ack.FAILED; } else return Ack.SKIPPED; } if (flag == 2) { if (b == START_TITLE[i]) { i++; } else i = 0; if (i >= START_TITLE.length) { flag = 3; i = 0; } } // put everything between <title></title> block into title else if (flag == 3) { if (b == END_TITLE[i]) { i++; } else i = 0; pageTitle.write(b); if (i >= END_TITLE.length) { flag = 4; String title = new String(pageTitle.getData(), 0, pageTitle.getLength() - END_TITLE.length); meta.setPageTitle(title); pageTitle.reset(); i = 0; } } else if (flag == 4) { if (b == START_NAMESPACE[i]) { i++; } else i = 0; if (i >= START_NAMESPACE.length) { flag = 5; i = 0; } } else if (flag == 5) { if (b == END_NAMESPACE[i]) { i++; } else i = 0; nsBuf.write(b); if (i >= END_NAMESPACE.length) { flag = 6; String nsStr = new String(nsBuf.getData(), 0, nsBuf.getLength() - END_NAMESPACE.length); int ns = Integer.parseInt(nsStr); nsBuf.reset(); if (ns != 0) { if (skipNonArticles) { skipped = true; meta.clear(); return Ack.SKIPPED; } } meta.setNamespace(ns); i = 0; } } else if (flag == 6) { if (b == START_ID[i]) { i++; } else i = 0; if (i >= START_ID.length) { flag = 7; i = 0; } } // put everything in outer <id></id> block into keyBuf else if (flag == 7) { if (b == END_ID[i]) { i++; } else i = 0; keyBuf.write(b); if (i >= END_ID.length) { flag = 8; String idStr = new String(keyBuf.getData(), 0, keyBuf.getLength() - END_ID.length); long pageId = Long.parseLong(idStr); meta.setPageId(pageId); i = 0; } } else if (flag == 8) { int curMatch = 0; if ((i < START_REVISION.length && b == START_REVISION[i]) && (i < START_REDIRECT.length && b == START_REDIRECT[i]) // subtle bug here: some tag names can overlap // multiple times && (revOrRedirect == 3 || revOrRedirect == -1)){ curMatch = 3; } else if (i < START_REVISION.length && b == START_REVISION[i] && revOrRedirect != 2) { curMatch = 1; } else if (i < START_REDIRECT.length && b == START_REDIRECT[i] && revOrRedirect != 1) { curMatch = 2; } else { curMatch = 0; } if (curMatch > 0 && (i == 0 || revOrRedirect == 3 || curMatch == revOrRedirect)) { i++; revOrRedirect = curMatch; } else i = 0; if ((revOrRedirect == 2 || revOrRedirect == 3) && i >= START_REDIRECT.length) { if (skipRedirect) { skipped = true; meta.clear(); return Ack.SKIPPED; } revOrRedirect = -1; flag = 9; i = 0; } else if ((revOrRedirect == 1 || revOrRedirect == 3) && i >= START_REVISION.length) { flag = 10; revOrRedirect = -1; return Ack.PASSED_TO_NEXT_TAG; } } else if (flag == 9 && !skipRedirect) { if (b == START_REVISION[i]) { i++; } else i = 0; if (i >= START_REVISION.length) { flag = 10; return Ack.PASSED_TO_NEXT_TAG; } } } } } } }
JavaScript
UTF-8
7,667
2.734375
3
[]
no_license
var planetNames = ["Su", "Mo", "Ev", "Gi", "Ke", "Mu", "Mi", "Du", "Ik", "Dr", "Jo", "La", "Ty", "Va", "Bo", "Po", "Ee"]; var planetFullNames = ["Sun-Kerbol", "Moho", "Eve", "Gilly", "Kerbin", "Mun", "Minmus", "Duna", "Ike", "Dres", "Jool", "Laythe", "Tylo", "Vall", "Bop", "Pol", "Eeloo"]; var planetFillColors = ['#ffe91f', '#a87316', '#7e4185', '#856e41', '#4f81bd', '#8f8e8e', '#92ff8a', '#ab2c2c', '#2e2e2e', '#7a7a7a', '#60cf4a', '#2b9cff', '#d6d6d6', '#9cced6', '#634734', '#cfab36', '#ffffff']; var planetFringeColors = ['#ad9e15', '#5e4617', '#4d2852', '#473b23', '#0056bd', '#5c5b5b', '#62ab5c', '#571616', '#000000', '#404040', '#418c32', '#1e6cb0', '#ababab', '#7ea7ad', '#3b2a1f', '#997e28', '#a8a8a8']; var planetHierarchyIndexes = [0, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2, 2, 2, 1]; /* Above are preset values for planet mdoels*/ var planets = new Array(); var planetModels = new Array(); var planetShown = false; //whether the correct planet is shown var planetModelShown = false; function PlanetModel(name, fullName, fillColor, fringeColor, hierarchyIndex) { this.name = name; this.fullName = fullName; this.fillColor = fillColor; this.fringeColor = fringeColor; this.hierarchyIndex = hierarchyIndex; planetModels.push(this); this.children = new Array(); updateSelector(); } function initiatePlanets(){ for (var x = 0; x < 17; x++){ new PlanetModel(planetNames[x], planetFullNames[x], planetFillColors[x], planetFringeColors[x], planetHierarchyIndexes[x]); } } function resetPlanetModels(button){ for (var x = 0; x < 17; x++){ planetModels[x].name = planetNames[x]; planetModels[x].fullName = planetFullNames[x]; planetModels[x].fillColor = planetFillColors[x]; planetModels[x].fringeColor = planetFringeColors[x]; planetModels[x].hierarchyIndex = planetHierarchyIndexes[x]; } planets.forEach(function(entry) { entry.radius = 32 * Math.pow(2, -entry.model.hierarchyIndex); }); planetShown = false; planetModelShown = false; updateSelector(); } function Planet(model){ this.model = model; this.position = [0, 0]; this.radius = 32 * Math.pow(2, -model.hierarchyIndex); planets.push(this); this.selected = false; model.children.push(this); this.childId = model.children.indexOf(this); } function deletePlanetButton(button){ planets.splice(planets.indexOf(currentPlanet), 1); currentPlanet.model.children.splice(currentPlanet.model.children.indexOf(currentPlanet), 1); updateSelector(); currentPlanet = false; } function deletePlanetModelButton(button){ if (planetModels.indexOf(currentPlanetModel) > 16){ planetModels.splice(craftModels.indexOf(currentPlanetModel), 1); currentPlanetModel.children.forEach(function(entry) { entry.model = planetModels[0]; planetModels[0].children.push(entry); entry.childId = entry.model.children.indexOf(entry); }); planetShown = false; currentPlanetModel = false; updateSelector(); } } function setPlanetModelToCurrent(ind){ currentPlanet.model.children.splice(currentPlanet.model.children.indexOf(currentPlanet), 1); currentPlanet.model = currentPlanetModel; currentPlanetModel.children.push(currentPlanet); planetShown = false; currentPlanet.radius = 32 * Math.pow(2, -currentPlanet.model.hierarchyIndex); } function planetRecenterButton(button){ currentPlanet.position[0] = 0; currentPlanet.position[1] = 0; } function drawPlanets(){ lineWidth = 3; planets.forEach(function(entry) { drawColor = entry.model.fillColor; fillCircleLocal(entry.position[0], entry.position[1], entry.radius); drawColor = entry.model.fringeColor; drawCircleLocal(entry.position[0], entry.position[1], entry.radius); }); if (currentPlanet){ if (!planetShown){ updateSelector(); $("#label1").show(); $("#planet").show(); //document.getElementById("label1").innerHTML = currentPlanet.model.fullName + " (Instance)"; document.getElementById("label1").innerHTML = currentPlanet.model.fullName + " ("+ (currentPlanet.model.children.indexOf(currentPlanet) + 1) +")"; $("#selPlanet").hide(); $("#selPlanet2").hide(); planetShown = true; document.getElementById("label6").innerHTML = "Model: " + currentPlanet.model.fullName; } } else{ $("#planet").hide(); $("#label1").hide(); $("#selPlanet").show(); planetShown = false; } if (currentPlanetModel){ if (currentPlanetModel != currentPlanet.model){ $("#label7").show(); } else{ $("#label7").hide(); } if (!planetModelShown){ if (planetModels.indexOf(currentPlanetModel) <= 16){ document.getElementById("deletePlanetModelButton").style.color = "#808080"; } else{ document.getElementById("deletePlanetModelButton").style.color = "#000000"; } updateSelector(); $("#label0").show(); $("#planet2").show(); document.getElementById('color0').color.fromString(currentPlanetModel.fringeColor); document.getElementById('color1').color.fromString(currentPlanetModel.fillColor); document.getElementById('name1').value = currentPlanetModel.fullName; document.getElementById('abbr').value = currentPlanetModel.name; document.getElementById('ind').value = currentPlanetModel.hierarchyIndex; document.getElementById("label0").innerHTML = currentPlanetModel.fullName + " (Model)"; document.getElementById("label7").innerHTML = "Change to selected model: '" + currentPlanetModel.fullName + "'"; $("#selPlanet2").hide(); planetModelShown = true; } } else{ $("#label7").hide(); $("#planet2").hide(); $("#label0").hide(); $("#selPlanet2").show(); planetModelShown = false; } } function ind(textbox){ currentPlanetModel.hierarchyIndex = textbox.value; planets.forEach(function(entry) { entry.radius = 32 * Math.pow(2, -entry.model.hierarchyIndex); }); } function name1(textbox){ currentPlanetModel.fullName = document.getElementById('name1').value; //updateSelector(); planetModelShown = false; planetShown = false; } function abbr(textbox){ currentPlanetModel.name = document.getElementById('abbr').value; } function createPlanetModel(button){ new PlanetModel("Un", "Untitled Planet", '#' + Math.round(Math.random() * 255 * 256 * 256).toString(16).toUpperCase(), '#' + Math.round(Math.random() * 255 * 256 * 256).toString(16).toUpperCase(), Math.round(Math.random() * 3 - 0.5)); updateSelector(); } function createPlanet(button, model){ var c = new Planet(model); c.selected = true; currentPlanet = c; click = true; planetShown = false; } function selectPlanets(){ planets.forEach(function(entry) { if(distance(entry.position[0] + midScreenPos[0], entry.position[1] + midScreenPos[1], locateMouseX(), locateMouseY()) < entry.radius){ deselectAll(); entry.selected = true; currentPlanet = entry; planetShown = false; } }); } function deselectPlanets(){ planets.forEach(function(entry) { entry.selected = false; entry.position[0] = rangify(entry.position[0], -midScreenPos[0], midScreenPos[0]); entry.position[1] = rangify(entry.position[1], -midScreenPos[1], midScreenPos[1]); }); } function dragPlanets(){ planets.forEach(function(entry) { if(entry.selected){ entry.position[0] = locateMouseX() - midScreenPos[0]; entry.position[1] = locateMouseY() - midScreenPos[1]; snap(entry.position); } }); } function distance(x1, y1, x2, y2){ return Math.sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2)); }; function snap(pos){ var vert = Number(document.getElementById("verticalSnap").value); if (vert > 0){ pos[1] = vert * Math.round(pos[1] / vert); } var horiz = Number(document.getElementById("horizontalSnap").value); if (horiz > 0){ pos[0] = horiz * Math.round(pos[0] / horiz); } }
Java
UTF-8
350
2.265625
2
[]
no_license
package shop.jpa.domain; import lombok.Getter; import javax.persistence.Embeddable; @Embeddable @Getter public class Address { private String address; private String postcode; protected Address() { } public Address(String address, String postcode) { this.address = address; this.postcode = postcode; } }
Java
UTF-8
573
3.140625
3
[]
no_license
/* Created by IntelliJ IDEA. * User: Divyansh Bhardwaj (dbc2201) * Date: 22/10/20 * Time: 3:15 PM * File Name : Example1.java * */ package sectionI.thread.examples; public class Example1 { private static final int LIMIT = 10; public static void main(String[] args) { for (int index = 0; index < LIMIT; index++) { System.out.println(index); try { Thread.sleep(1000L); // wait for 300 ms } catch (InterruptedException e) { System.out.println(e.getMessage()); } } } }
Java
UTF-8
5,614
2.5625
3
[]
no_license
package uk.calebwhiting.tk.bus; import com.google.common.eventbus.Subscribe; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import uk.calebwhiting.tk.annotations.Destructor; import uk.calebwhiting.tk.annotations.EventHandler; import uk.calebwhiting.tk.annotations.Initializer; import uk.calebwhiting.tk.event.Exiting; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.*; /** * A bad implementation of a semi-asynchronous event-bus. * * With this implementation handlers are multi-threaded, however the dispatch method will wait * for all of the handlers to finish execution before returning. */ public class EventBus { @Getter private final ExecutorService executorService; private final Map<Class<?>, Set<Callback>> callbacks = new HashMap<>(); private final Map<Class<?>, Set<Method>> initializers = new LinkedHashMap<>(); private final Map<Class<?>, Set<Method>> destructors = new LinkedHashMap<>(); private boolean rejectEvents = false; public EventBus(ExecutorService executorService) { this.executorService = executorService; } public void register(Object o) { synchronized (callbacks) { Stack<Class<?>> stack = new Stack<>(); stack.push(o.getClass()); while (stack.size() > 0) { Class<?> c = stack.pop(); Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(EventHandler.class) || method.isAnnotationPresent(Subscribe.class)) { if (method.getReturnType() != void.class) continue; if (method.getParameterCount() != 1) continue; method.setAccessible(true); Parameter param = method.getParameters()[0]; Set<Callback> callbacks = this.callbacks.computeIfAbsent(param.getType(), x -> new LinkedHashSet<>()); callbacks.add(new Callback(o, c, method)); } else if (method.isAnnotationPresent(Initializer.class)) { method.setAccessible(true); Set<Method> initializers = this.initializers.computeIfAbsent(c, x -> new LinkedHashSet<>()); initializers.add(method); } else if (method.isAnnotationPresent(Destructor.class)) { method.setAccessible(true); Set<Method> destructors = this.destructors.computeIfAbsent(c, x -> new LinkedHashSet<>()); destructors.add(method); } } Collections.addAll(stack, c.getInterfaces()); if (c.getSuperclass() != null) stack.push(c.getSuperclass()); } } call(this.initializers, o); } public void resign(Object o) { synchronized (callbacks) { this.callbacks.forEach((k, v) -> v.removeIf(c -> c.instance == o)); } call(this.destructors, o); } public void dispatch(Object o) { if (this.executorService.isShutdown() || this.rejectEvents) { return; } Set<Future<?>> futures = new HashSet<>(); synchronized (callbacks) { Stack<Class<?>> stack = new Stack<>(); stack.push(o.getClass()); while (stack.size() > 0) { Class<?> c = stack.pop(); Set<Callback> callbacks = this.callbacks.get(c); if (callbacks != null) { for (Callback callback : callbacks) { Future<?> future = this.executorService.submit( () -> call(callback.method, callback.instance, o)); futures.add(future); } } Collections.addAll(stack, c.getInterfaces()); if (c.getSuperclass() != null) stack.push(c.getSuperclass()); } } for (Future<?> future : futures) { try { future.get(); } catch (InterruptedException ignore) { break; } catch (ExecutionException e) { e.printStackTrace(); } } } private void call(Map<Class<?>, Set<Method>> methods, Object o, Object... args) { for (Class<?> c : methods.keySet()) { if (c.isInstance(o)) { for (Method m : methods.get(c)) { try { m.invoke(o, m, args); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } } } private void call(Method method, Object instance, Object... args) { try { method.invoke(instance, args); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } public void shutdown() { this.dispatch(new Exiting()); this.rejectEvents = true; this.getExecutorService().shutdown(); } @EqualsAndHashCode @RequiredArgsConstructor private static class Callback { private final Object instance; private final Class<?> clazz; private final Method method; } }
Markdown
UTF-8
9,119
2.625
3
[]
no_license
# 1.*zk进阶--集群--分布式管理--注册中心--分布式JOB--分布式锁** | ID | Problem | | --- | --- | | 000 |分布式集群管理 | | 001 |分布式注册中心 | | 002 |分布式JOB | | 003 |分布式锁 | ## 一、 分布式集群管理 --- ### **分布式集群管理的需求** 1. 主动查看线上服务节点 2. 查看服务节点资源使用情况 3. 服务离线通知 4. 服务资源(CPU、内存、硬盘)超出阀值通知 ### **架构设计** ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk8.png) **节点结构:** 1. qiurunze-manger // 根节点 1. server00001 :<json> //服务节点 1 2. server00002 :<json>//服务节点 2 3. server........n :<json>//服务节点 n 服务状态信息: 1. ip 2. cpu 3. memory 4. disk ### **功能实现** **数据生成与上报:** 1. 创建临时节点: 2. 定时变更节点状态信息: **主动查询:** 1、实时查询 zookeeper 获取集群节点的状态信息。 **被动通知:** 1. 监听根节点下子节点的变化情况,如果CPU 等硬件资源低于警告位则发出警报。 **关键示例代码:** zkdesign-hardcode Agent类 可查看 实现效果图: ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk9.png) ## 二 、分布式注册中心 --- 在单体式服务中,通常是由多个客户端去调用一个服务,只要在客户端中配置唯一服务节点地址即可,当升级到分布式后,服务节点变多,像阿里一线大厂服务节点更是上万之多,这么多节点不可能手动配置在客户端,这里就需要一个中间服务,专门用于帮助客户端发现服务节点,即许多技术书籍经常提到的**服务发现**。 ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk10.png) 一个完整的注册中心涵盖以下功能特性: * **服务注册:**提供者上线时将自提供的服务提交给注册中心。 * **服务注销:**通知注册心提供者下线。 * **服务订阅**:动态实时接收服务变更消息。 * **可靠**:注册服务本身是集群的,数据冗余存储。避免单点故障,及数据丢失。 * **容错**:当服务提供者出现宕机,断电等极情况时,注册中心能够动态感知并通知客户端服务提供者的状态。 ### **Dubbo 对zookeeper的使用** 阿里著名的开源项目Dubbo 是一个基于JAVA的RCP框架,其中必不可少的注册中心可基于多种第三方组件实现,但其官方推荐的还是Zookeeper做为注册中心服务。 ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk11.png) ### **Dubbo Zookeeper注册中心存储结构:** ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk12.png) **节点说明:** | **类别** | **属性** | **说明** | |:----|:----|:----| | **Root** | 持久节点 | 根节点名称,默认是 "dubbo" | | **Service** | 持久节点 | 服务名称,完整的服务类名 | | **type** | 持久节点 | 可选值:providers(提供者)、consumers(消费者)、configurators(动态配置)、routers | | **URL** | 临时节点 | url名称 包含服务提供者的 IP 端口 及配置等信息。 | ### **流程说明** 1. 服务提供者启动时: 向 /dubbo/com.foo.BarService/providers 目录下写入自己的 URL 地址 2. 服务消费者启动时: 订阅 /dubbo/com.foo.BarService/providers 目录下的提供者 URL 地址。并向 /dubbo/com.foo.BarService/consumers 目录下写入自己的 URL 地址 3. 监控中心启动时: 订阅 /dubbo/com.foo.BarService 目录下的所有提供者和消费者 URL 地址 ### **示例演示** 服务端代码: 在 zkdesign-dubboexample -- 举例 : Server Clent 查询zk 实际存储内容: ``` /dubbo /dubbo/com.zkdesign.zk.dubbo.UserService /dubbo/com.zkdesign.zk.dubbo.UserService/configurators /dubbo/com.zkdesign.zk.dubbo.UserService/routers /dubbo/com.zkdesign.zk.dubbo.UserService/providers /dubbo/com.zkdesign.zk.dubbo.UserService/providers/dubbo://192.168.0.132:20880/com.qiurunze.zk.dubbo.UserService?anyhost=true&application=simple-app&dubbo=2.6.2&generic=false&interface=com.qiurunze.zk.dubbo.UserService&methods=getUser&pid=11128&side=provider&threads=200&timestamp=1570518302772 /dubbo/com.zkdesign.zk.dubbo.UserService/providers/dubbo://192.168.0.132:20881/com.qiurunze.zk.dubbo.UserService?anyhost=true&application=simple-app&dubbo=2.6.2&generic=false&interface=com.qiurunze.zk.dubbo.UserService&methods=getUser&pid=12956&side=provider&threads=200&timestamp=1570518532382 /dubbo/com.zkdesign.zk.dubbo.UserService/providers/dubbo://192.168.0.132:20882/com.qiurunze.zk.dubbo.UserService?anyhost=true&application=simple-app&dubbo=2.6.2&generic=false&interface=com.qiurunze.zk.dubbo.UserService&methods=getUser&pid=2116&side=provider&threads=200&timestamp=1570518537021 /dubbo/com.zkdesign.zk.dubbo.UserService/consumers /dubbo/com.zkdesign.zk.dubbo.UserService/consumers/consumer://192.168.0.132/com.qiurunze.zk.dubbo.UserService?application=young-app&category=consumers&check=false&dubbo=2.6.2&interface=com.qiurunze.zk.dubbo.UserService&methods=getUser&pid=9200&side=consumer&timeout=5000&timestamp=1570518819628 ``` 在 这些节点下 只有privider 和 consumer 底下的节点是 临时节点 其他的都是持久节点 ## 三、分布式JOB --- ### 分布式JOB需求: 1. 多个服务节点只允许其中一个主节点运行JOB任务。 2. 当主节点挂掉后能自动切换主节点,继续执行JOB任务。 ### 架构设计: ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk13.png) **node结构:** 1. qiurunze-master 1. server0001:master 2. server0002:slave 3. server000n:slave **选举流程:** 服务启动: 1. 在qiurunze-maste下创建server子节点,值为slave 2. 获取所有qiurunze-master 下所有子节点 3. 判断是否存在master 节点 4. 如果没有设置自己为master节点 子节点删除事件触发: 1. 获取所有qiurunze-master 下所有子节点 2. 判断是否存在master 节点 3. 如果没有设置最小值序号为master 节点 ## 四、分布式锁 --- ### **锁的的基本概念:** 开发中锁的概念并不陌生,通过锁可以实现在多个线程或多个进程间在争抢资源时,能够合理的分配置资源的所有权 在单体应用中我们可以通过 synchronized 或ReentrantLock 来实现锁。但在分布式系统中,仅仅是加synchronized 是不够的,需要借助第三组件来实现。比如一些简单的做法是使用 关系型数据行级锁来实现不同进程之间的互斥,但大型分布式系统的性能瓶颈往往集中在数据库操作上。为了提高性能得采用如Redis、Zookeeper之内的组件实现分布式锁。 **共享锁:**也称作只读锁,当一方获得共享锁之后,其它方也可以获得共享锁。但其只允许读取。在共享锁全部释放之前,其它方不能获得写锁。 **排它锁:**也称作读写锁,获得排它锁后,可以进行数据的读写。在其释放之前,其它方不能获得任何锁。 ### 锁的获取: 某银行帐户,可以同时进行帐户信息的读取,但读取其间不能修改帐户数据。其帐户ID为:888 * 获得读锁流程: ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk14.png) 1、基于资源ID创建临时序号读锁节点 /lock/888.R0000000002 Read 2、获取 /lock 下所有子节点,判断其最小的节点是否为读锁,如果是则获锁成功 3、最小节点不是读锁,则阻塞等待。添加lock/ 子节点变更监听。 4、当节点变更监听触发,执行第2步 **数据结构:** ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk15.png) * 获得写锁: 1、基于资源ID创建临时序号写锁节点 /lock/888.R0000000002 Write 2、获取 /lock 下所有子节点,判断其最小的节点是否为自己,如果是则获锁成功 3、最小节点不是自己,则阻塞等待。添加lock/ 子节点变更监听。 4、当节点变更监听触发,执行第2步 * 释放锁: 读取完毕后,手动删除临时节点,如果获锁期间宕机,则会在会话失效后自动删除。 ### **关于羊群效应:** 在等待锁获得期间,所有等待节点都在监听 Lock节点,一但lock 节点变更所有等待节点都会被触发,然后在同时反查Lock 子节点。如果等待对列过大会使用Zookeeper承受非常大的流量压力。 ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk17.png) 为了改善这种情况,可以采用监听链表的方式,每个等待对列只监听前一个节点,如果前一个节点释放锁的时候,才会被触发通知。这样就形成了一个监听链表。 ![图片](https://raw.githubusercontent.com/qiurunze123/imageall/master/zk18.png) ### **示例演示:** http://blog.itpub.net/31562040/viewspace-2640310/ 参考
Java
UTF-8
884
1.859375
2
[ "Apache-2.0" ]
permissive
package dwz.persistence.mapper; import java.util.Date; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import dwz.dal.BaseMapper; import dwz.persistence.BaseConditionVO; import sop.persistence.beans.Supplier; /** * @Author: LCF * @Date: 2020/1/8 17:32 * @Package: dwz.persistence.mapper */ @Repository public interface SupplierMapper extends BaseMapper<Supplier, String> { List<Supplier> findPageBreakByCondition(BaseConditionVO vo, RowBounds rb); Integer findNumberByCondition(BaseConditionVO vo); void updateStatus(@Param("code") String ccyCode, @Param("deleted") boolean b, @Param("modUsr") String modUsr, @Param("modDate") Date date); Supplier getSupplierByCode(@Param("code") String code); List<Supplier> findAllSuppliers(); }
Ruby
UTF-8
7,988
3.109375
3
[]
no_license
require 'csv' require 'rails' require_relative 'weather_utils' # airports = CSV.read("../Downloads/airports.csv", headers: true) # italy = airports.select {|x| x["iso_country"] == "IT"} # large_airports = italy.select {|x| x["type"] == "large_airport"} # 2.1.2 :090 > airports.headers # => ["id", "ident", "type", "name", "latitude_deg", "longitude_deg", "elevation_ft", "continent", "iso_country", "iso_region", "municipality", "scheduled_service", "gps_code", "iata_code", "local_code", "home_link", "wikipedia_link", "keywords"] @info = { venice: { airport_code: "LIPZ", start_date: Date.new(2015, 11, 1), end_date: Date.new(2015, 11, 4) }, florence: { airport_code: "LIRQ", start_date: Date.new(2015, 11, 4), end_date: Date.new(2015, 11, 7) }, rome: { airport_code: "LIRF", start_date: Date.new(2015, 11, 7), end_date: Date.new(2015, 11, 9) }, naples: { airport_code: "LIRN", start_date: Date.new(2015, 11, 9), end_date: Date.new(2015, 11, 10) }, salerno: { airport_code: "LIRI", start_date: Date.new(2015, 11, 9), end_date: Date.new(2015, 11, 10) } } @years = [2010, 2011, 2012, 2013, 2014, 2015] @cities = [ :venice, :florence, :rome, :naples, :salerno ] def download_data puts "Downloading data" @cities.each do |city| city = @info[city] weather = WeatherUtils.new(city[:airport_code]) start_date = city[:start_date] end_date = city[:end_date] @years.each do |year| start_date = start_date.change(year: year) end_date = end_date.change(year: year) weather.download_days_for_range(start_date, end_date) weather.download_file_for_year(year) end end end def calculate_averages @cities.each do |city| info = @info[city] airport = info[:airport_code] weather = WeatherUtils.new(airport) end end # download_data calculate_averages # 2.1.2 :045 > large_airports.map {|x| x["municipality"]} # => ["Bari", "Catania", "Palermo", "Cagliari", "Milan", "Bergamo", "Torino", "Genova", "Milan", "Cuneo", "Bologna", "Treviso", "Verona", "Venice", "Roma", "Rome", "Nápoli", "Pisa"] # 2.1.2 :052 > large_airports.map {|x| x["ident"]} # => ["LIBD", "LICC", "LICJ", "LIEE", "LIMC", "LIME", "LIMF", "LIMJ", "LIML", "LIMZ", "LIPE", "LIPH", "LIPX", "LIPZ", "LIRA", "LIRF", "LIRN", "LIRP"] # 2.1.2 :085 > large_airports.map {|x| puts "#{x['ident']} #{x['municipality'].ljust(9)} #{x['latitude_deg'].ljust(20)} #{x['longitude_deg']}"} # LIBD Bari 41.1389007568 16.7605991364 # LICC Catania 37.466800689699994 15.0663995743 # LICJ Palermo 38.1759986877 13.0909996033 # LIEE Cagliari 39.251499176 9.05428028107 # LIMC Milan 45.6305999756 8.728110313419998 # LIME Bergamo 45.6739006042 9.70417022705 # LIMF Torino 45.2008018494 7.64963006973 # LIMJ Genova 44.41329956049999 8.83749961853 # LIML Milan 45.445098877 9.27674007416 # LIMZ Cuneo 44.547000885 7.623219966890001 # LIPE Bologna 44.535400390599996 11.2887001038 # LIPH Treviso 45.648399353 12.1943998337 # LIPX Verona 45.3956985474 10.8885002136 # LIPZ Venice 45.5052986145 12.3519001007 # LIRA Roma 41.7994003296 12.5949001312 # LIRF Rome 41.8045005798 12.2508001328 # LIRN Nápoli 40.8860015869 14.290800094600002 # LIRP Pisa 43.683898925799994 10.3927001953 # 2.1.2 :028 > large_airports = italy.select {|x| x["type"] == "large_airport" || x["type"] == "medium_airport"} # 2.1.2 :027 > large_airports.map {|x| puts "#{x['ident']} #{x['municipality'].try(:ljust, 9)} #{x['latitude_deg'].try(:ljust, 20)} #{x['longitude_deg']}"} # LIBA Foggia 41.54140090942383 15.718099594116211 # LIBC Crotone 38.99720001220703 17.0802001953125 # LIBD Bari 41.1389007568 16.7605991364 # LIBF Foggia 41.4328994751 15.534999847400002 # LIBG Grottaglie 40.5175018311 17.4032001495 # LIBN 40.239200592 18.1333007812 # LIBP Pescara 42.43170166015625 14.181099891662598 # LIBR Brindisi 40.6576004028 17.9470005035 # LIBV Gioia Del Colle 40.767799377399996 16.9333000183 # LICA Lamezia Terme 38.905399322509766 16.242300033569336 # LICB Comiso 36.9946010208 14.6071815491 # LICC Catania 37.466800689699994 15.0663995743 # LICD Lampedusa 35.49789810180664 12.6181001663208 # LICG Pantelleria 36.81650161743164 11.968899726867676 # LICJ Palermo 38.1759986877 13.0909996033 # LICP Palermo 38.110801696799996 13.3133001328 # LICR Reggio Calabria 38.07120132446289 15.651599884033203 # LICT Trapani 37.911399841299996 12.4879999161 # LICZ 37.40169906616211 14.92240047454834 # LIDM Mantova 45.135833740234375 10.79444408416748 # LIDR Ravenna 44.36429977416992 12.224900245666504 # LIDT Trento 46.021400451699996 11.1241998672 # LIEA Alghero 40.6320991516 8.29076957703 # LIED Decimomannu 39.35419845581055 8.972479820251465 # LIEE Cagliari 39.251499176 9.05428028107 # LIEO Olbia 40.8987007141 9.51762962341 # LIET Arbatax 39.918800354 9.68297958374 # LILA Alessandria 44.925201416 8.62512969971 # LILE Biella 45.495300293 8.102780342099999 # LILI Vercelli 45.3111991882 8.41742038727 # LILM Casale Monferrato 45.1111984253 8.456029891970001 # LILN Varese 45.7421989441 8.88823032379 # LIMA Torino 45.0863990784 7.60337018967 # LIMC Milan 45.6305999756 8.728110313419998 # LIME Bergamo 45.6739006042 9.70417022705 # LIMF Torino 45.2008018494 7.64963006973 # LIMG Albenga 44.0505981445 8.12742996216 # LIMJ Genova 44.41329956049999 8.83749961853 # LIML Milan 45.445098877 9.27674007416 # LIMN Cameri (NO) 45.5295982361 8.6692199707 # LIMP Parma 44.824501037597656 10.29640007019043 # LIMR Novi Ligure 44.779998779299994 8.78639030457 # LIMS Piacenza 44.913101 9.723323 # LIMW Aosta 45.7384986877 7.36872005463 # LIMZ Cuneo 44.547000885 7.623219966890001 # LIPA Aviano 46.031898498535156 12.596500396728516 # LIPB Bolzano 46.460201263427734 11.326399803161621 # LIPC Cervia 44.2242012024 12.3072004318 # LIPE Bologna 44.535400390599996 11.2887001038 # LIPH Treviso 45.648399353 12.1943998337 # LIPI Codroipo 45.97869873046875 13.049300193786621 # LIPK Forlì 44.1948013306 12.070099830600002 # LIPL Ghedi 45.43220139 10.2677002 # LIPO Montichiari 45.428901672399995 10.3305997849 # LIPQ Trieste 45.8274993896 13.4722003937 # LIPR Rimini 44.0203018188 12.611700058 # LIPS Istrana 45.684898376464844 12.082900047302246 # LIPT Vicenza 45.57339859008789 11.529500007629395 # LIPU Padova 45.39580154418945 11.847900390625 # LIPX Verona 45.3956985474 10.8885002136 # LIPY Ancona 43.6162986755 13.3622999191 # LIPZ Venice 45.5052986145 12.3519001007 # LIQS Siena 43.25630187989999 11.255000114399998 # LIQW Sarzana 44.0880012512 9.987950325009999 # LIRA Roma 41.7994003296 12.5949001312 # LIRE Pomezia 41.65449905395508 12.445199966430664 # LIRF Rome 41.8045005798 12.2508001328 # LIRG Guidonia 41.990299224853516 12.740799903869629 # LIRI Salerno 40.6203994751 14.9112997055 # LIRJ Marina Di Campo 42.76029968261719 10.239399909973145 # LIRL Latina 41.54240036010742 12.909000396728516 # LIRM Caserta 41.06079864501953 14.081899642944336 # LIRN Nápoli 40.8860015869 14.290800094600002 # LIRP Pisa 43.683898925799994 10.3927001953 # LIRQ Firenze 43.8100013733 11.205100059500001 # LIRS Grosetto 42.759700775146484 11.071900367736816 # LIRU Roma 41.951900482177734 12.498900413513184 # LIRV Viterbo 42.430198669433594 12.064200401306152 # LIRZ Perugia 43.0959014893 12.513199806200001
C#
UTF-8
10,124
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Globalization; using UnityEngine; using System.IO; using System.Security.Cryptography; /// <summary> /// A collection of utility Methods useful for saving and loading data. /// </summary> public class SaveUtility { #region Data Type Conversion public static List<string> csvToStringList(string input, string delimiter) { if (String.IsNullOrEmpty(input)) return new List<string>(); List<string> retList = new List<string>(input.Split(delimiter[0])); return retList; } public static List<string> csvToStringList(string input) { List<string> retList = new List<string>(input.Split(',')); return retList; } public static string ListToCsv<T> (IList<T> list) { if (list == null || list.Count == 0) { return ""; } string retString = list[0].ToString(); for (int i = 1; i < list.Count; i++) { retString += "," + list[i].ToString(); } return retString; } public static Vector2Int csvToVector2Int(string input) { input = input.Replace("(", "").Replace(")", ""); if (input == "") return new Vector2Int(); List<string> valueList = csvToStringList(input); Vector2Int retVal = new Vector2Int(int.Parse(valueList[0]), int.Parse(valueList[1])); return retVal; } public static Vector2 csvToVector2(string input) { input = input.Replace("(", "").Replace(")", ""); if (input == "") return new Vector2(); List<string> valueList = csvToStringList(input); Vector2 retVal = new Vector2(float.Parse(valueList[0]), float.Parse(valueList[1])); return retVal; } public static Vector3Int csvToVector3Int(string input) { input = input.Replace("(", "").Replace(")", ""); if (input == "") return new Vector3Int(); List<string> valueList = csvToStringList(input); Vector3Int retVal = new Vector3Int(int.Parse(valueList[0]), int.Parse(valueList[1]), int.Parse(valueList[2])); return retVal; } public static Vector3 csvToVector3(string input, string delimiter = ",") { input = input.Replace("(", "").Replace(")", ""); if (input == "") return new Vector3(); List<string> valueList = csvToStringList(input, delimiter); Vector3 retVal; if (valueList.Count == 2) retVal = new Vector3(float.Parse(valueList[0]), float.Parse(valueList[1])); else if (valueList.Count == 3) retVal = new Vector3(float.Parse(valueList[0]), float.Parse(valueList[1]), float.Parse(valueList[2])); else retVal = new Vector3(); return retVal; } public static Vector3 csvToVector3(string input, float zDepth) { input = input.Replace("(", "").Replace(")", ""); if (input == "") return new Vector3(); List<string> valueList = csvToStringList(input); Vector3 retVal; if (valueList.Count == 2) retVal = new Vector3(float.Parse(valueList[0]), float.Parse(valueList[1]), zDepth); else retVal = new Vector3(0, 0, zDepth); return retVal; } public static string Vector3ToCsv(Vector3 input, string delimiter = ",") { string retVal = input.ToString(); if(delimiter != ",") { retVal.Replace(',', delimiter[0]); } return retVal; } public static Rect csvToRect(string input, Rect defaultValue) { if (input == "") return defaultValue; List<string> valueList = csvToStringList(input); Rect retVal = new Rect(float.Parse(valueList[0]), float.Parse(valueList[1]), float.Parse(valueList[2]), float.Parse(valueList[3])); return retVal; } public static Color csvRGBAToColor(string input) { if (input == "") return new Color(1, 1, 1, 1); List<string> valueList = csvToStringList(input); float r = stringToFloat(valueList[0]); float g = stringToFloat(valueList[1]); float b = stringToFloat(valueList[2]); float a = stringToFloat(valueList[3]); if (r > 1) { r = r / 255; } if (g > 1) { g = g / 255; } if (b > 1) { b = b / 255; } if (a > 1) { a = a / 255; } return new Color(r, g, b, a); } public static Color csvRGBAToColor(string input, Color defaultValue) { if (input == "") return defaultValue; return csvRGBAToColor(input); } public static bool stringToBool(string input) { return stringToBool(input, false); } public static bool stringToBool(string input, bool defaultVal) { if (input.ToLower() == "true" || input == "1" || input.ToLower() == "yes") { return true; } else if (input.ToLower() == "false" || input == "0" || input.ToLower() == "no") { return false; } else { return defaultVal; } } public static float stringToFloat(string input, int digits = -1) { return stringToFloat(input, 0, digits); } public static float stringToFloat(string input, float defaultVal, int digits = -1) { input = input.Replace(",", "").Replace(" ", ""); try { float retVal = float.Parse(input); if (digits >= 0) { retVal = (float)Math.Round(retVal, digits); } return retVal; } catch { return defaultVal; } } public static int stringToInt(string input) { return stringToInt(input, 0); } public static int stringToInt(string input, int defaultVal) { input = input.Replace(",", "").Replace(" ", ""); try { return int.Parse(input); } catch { return defaultVal; } } public static DateTime stringToDateTime(string input) { return DateTime.Parse(input); } public static bool TryParseInt64(string input, out long output) { try { output = Int64.Parse(input); return true; } catch { output = 0; return false; } } public static long ParseInt64(string input) { try { return Int64.Parse(input); } catch { return 0; } } public static bool TryParseDouble(string input, out double output) { try { output = Double.Parse(input); return true; } catch { output = 0.0; return false; } } public static T stringToEnum<T>(string value, T defaultEnum) { try { value = value.Replace(" ", "").Trim(); //.Replace("_", "") object retval = Enum.Parse(typeof(T), value, true); if (retval != null) return (T)retval; else return defaultEnum; } catch { return defaultEnum; } } public static byte[] intToByteArray(int input) { return BitConverter.GetBytes(input); } public static int byteArrayToInt(byte[] input) { return BitConverter.ToInt32(input, 0); } public static byte[] stringToByteArray(string input) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); return encoding.GetBytes(input); } public static string byteArrayToString(byte[] input) { return System.Text.ASCIIEncoding.ASCII.GetString(input); } #endregion #region Saving and Loading public static bool SaveFile(string fileText, string path) { try { FileStream file = File.Open(path, FileMode.Create); StreamWriter writer = new StreamWriter(file); writer.WriteLine(fileText); writer.Dispose(); file.Dispose(); return true; } catch { return false; } } public static bool SaveFile(byte[] bytes, string path) { try { File.WriteAllBytes(path, bytes); return true; } catch { return false; } } #if UNITY_EDITOR public static string SaveFileAs(string fileText, string windowTitle = "Save File", string directory = "", string fileName = "", string extension = "txt") { if (string.IsNullOrEmpty(directory)) { directory = Application.dataPath; } string path = UnityEditor.EditorUtility.SaveFilePanel(windowTitle, directory, fileName, extension); if (SaveFile(fileText, path)) { return path; } return ""; } #endif public static string LoadFile(string path) { if (FileExists(path)) { FileStream file = File.Open(path, FileMode.Open); StreamReader reader = new StreamReader(file); string fileText = reader.ReadToEnd(); reader.Dispose(); file.Dispose(); return fileText; } return null; } public static bool FileExists(string path) { return File.Exists(path); } #endregion public static string getParentFolder(string folder) { return folder.Substring(0, folder.LastIndexOf("/")); } static public string CreateMD5Hash(string input) { // Use input string to calculate MD5 hash MD5 md5 = MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hashBytes = md5.ComputeHash(inputBytes); // Convert the byte array to hexadecimal string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("X2")); // To force the hex string to lower-case letters instead of // upper-case, use he following line instead: // sb.Append(hashBytes[i].ToString("x2")); } return sb.ToString(); } }
C++
UTF-8
826
3.21875
3
[]
no_license
#ifndef PIECE_H #define PIECE_H #include <cstring> #include <map> #include <iostream> using namespace std; enum Classification { n_a, king, queen, knight, bishop, castle, pawn }; class Piece { protected: /**ATTRIBUTES**/ Classification type; bool white_color; bool first_move; public: //CONSTRUCTOR - SETS THE COLOR AND FIRST_MOVE TO TRUE Piece (bool color); //VIRTUAL DESTRUCTOR virtual ~Piece () {}; //VIRTUAL VALID MOVE FUNCTION virtual bool valid_move (const char*, const char*, bool) = 0; //RETURNS FIRST_MOVE BOOL bool check_first_move (); //CHANGES FIRST_MOVE BOOL TO FALSE void not_first_move (); //RETURNS WHITE_COLOR BOOL bool get_white_color () const; //RETURNS STRING TYPE OF PIECE BASED ON CLASSIFICATION, e.g."King" string get_type() const; }; #endif /*PIECE_H*/
Python
UTF-8
1,095
4.34375
4
[]
no_license
""" As we'll see in subsequent lectures, everything in Python is an object. Objects are special because we can associate special functions, referred to as object methods, with the object. In this problem you'll be working with string objects, and their built-in methods. As we'll see in subsequent lectures, everything in Python is an object. Objects are special because we can associate special functions, referred to as object methods, with the object. In this problem you'll be working with string objects, and their built-in methods. >>> s = 'abc' >>> s.capitalize <built-in method capitalize of str object at 0x104c35878> >>> s.capitalize() 'Abc' """ str1 = 'exterminate!' str2 = 'number one - the larch' """ str1.upper str1.upper() str1 str1.isupper() str1.islower() str2 = str2.capitalize() str2 str2.swapcase() str1.index('e') str2.index('n') str2.find('n') str2.index('!') str2.find('!') """ Note: Be sure to make note of the difference between the find and index string methods... """ str1.count('e') str1 = str1.replace('e', '*') str1 str2.replace('one', 'seven') """
C++
UTF-8
1,886
3.828125
4
[]
no_license
#include <iostream> #include <string> #include "Stack.h" using std::cin; using std::cout; using std::endl; using std::string; using std::stod; int main() { Stack s; while (true) { // read a word (token) from input string token; cin >> token; if (isdigit(token[0]) || token[0] == '.') { // TODO: use std::stod() to convert token to double double x = stod(token); // TODO: push operand onto stack push(s, x); } else { char c = token[0]; if (c == '=') { break; } // Otherwise, it should be one of the operators +, -, * / // TODO: Pop the value to be the right-hand side of the operator double r = pop(s); double l = pop(s); // TODO: Pop the value to be the left-hand side of the operator // Do the computation and push the result to the stack switch (c) { case '+': // TODO: Do plus, and push the result to the stack push(s, l + r); break; case '-': // TODO: Do minus, and push the result to the stack push(s, l - r); break; case '*': // TODO: Do multiplication, and push the result to the stack push(s, l * r); break; case '/': // TODO: Do division, and push the result to the stack push(s, l / r); break; default: cout << "[ERROR] invalid operator: " << c << endl; return 1; } } } // pop result from stack, and print it to the terminal cout << pop(s) << endl; // free the stack memory delete[] s.A; return 0; }
Java
UTF-8
903
2.109375
2
[ "Unlicense" ]
permissive
package net.timxekhach.operation.data.entity; // ____________________ ::IMPORT_SEPARATOR:: ____________________ // import lombok.Getter; import lombok.Setter; import net.timxekhach.operation.data.mapped.Buss_MAPPED; import net.timxekhach.utility.XeStringUtils; import javax.persistence.Entity; import java.util.List; import java.util.stream.Collectors; // ____________________ ::IMPORT_SEPARATOR:: ____________________ // @Entity @Getter @Setter public class Buss extends Buss_MAPPED { public Buss() {} public Buss(BussType bussType, Company company) { super(bussType, company); } // ____________________ ::BODY_SEPARATOR:: ____________________ // public List<Integer> getLockedSeats() { return XeStringUtils.commaGt0ToStreamSortedAsc(this.lockedSeatsString).collect(Collectors.toList()); } // ____________________ ::BODY_SEPARATOR:: ____________________ // }
Ruby
UTF-8
1,059
4.3125
4
[]
no_license
# PEDAC # Problem # Find the sum of all the natural numbers below an input number that are multiples of 3 or 5. If the number # is a multiple of both 3 and 5, only count it once. # input = integer, output = integer # Assumptions # if there are no multiples of 3 or 5 below the input number, return 0 # Examples / Test Cases # Algorithm # 1. Get all numbers up to n - 1 in an array # 2. Declare a variable sum and set it equal to 0. # 3. Iterate through array # If num divisible by 3 and 5, increment sum by the number # If num divisible by 3, increment sum by the number # If sum divisible by 5, increment by the number # 4. Return sum def find_sum_of_multiples(n) range_of_numbers = (1..n-1).to_a sum = 0 range_of_numbers.each do |num|,6 if num % 3 == 0 and num % 5 == 0 p num sum += num elsif num % 3 == 0 p num sum += num elsif num % 5 == 0 p num sum += num end end sum end # find_sum_of_multiples(10) == 23 # find_sum_of_multiples(3) == 0 find_sum_of_multiples(20) == 62
Python
UTF-8
821
2.65625
3
[]
no_license
import zmq import time import json port = str(5555) context = zmq.Context() socket = context.socket(zmq.PAIR) socket.bind("tcp://*:%s" % port) while True: print("Job executor is waiting for a new job request.") msg = socket.recv() print("Job executor has received a new job request.") msg_dict = json.loads(msg.decode('ascii')) print(msg_dict) msg_dict_value = msg_dict["job_ID"] print(msg_dict_value) print("Job execution is starting.") time.sleep(3) print("Job is completed.") print("Job executor is about to report the completion of the job back to the requester.") msg_content_dict = {} msg_content_dict["some_other_key"] = msg_dict_value msg_content = str(json.dumps(msg_content_dict)) msg_string = msg_content.encode('ascii') socket.send(msg_string)
PHP
UTF-8
16,869
2.59375
3
[]
no_license
<?php require_once ("php_action/core.php"); //conexion a la BD para obtener la info require_once("config/db.php"); /** Se agrega la libreria PHPExcel */ require_once("classes/lib/PHPExcel/PHPExcel.php"); //obtengo un array de lo que hay en la tabla actualmente require_once("classes/conversor.php"); //conexion a la BD para obtener la info // cargar la clase de login require_once("classes/DBMaster.php"); //instancio el objeto de la clase sql $conexion = new DBMaster(); //instancio el objeto de la clase sql $conversor = new NumberToLetterConverter(); $consulta = "SELECT * FROM adicion;"; $resultado = $connect->query($consulta); //obtengo la fecha actual. $hoy = getdate(); if ($resultado->num_rows > 0) { date_default_timezone_set('America/Guatemala'); // create new PHPExcel object $objPHPExcel = new PHPExcel; // create the writer $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007"); $hoja = $objPHPExcel->getActiveSheet(); // Se asignan las propiedades del libro $objPHPExcel->getProperties()->setCreator("Codedrinks") //Autor ->setLastModifiedBy("Ocampo") //Ultimo usuario que lo modificó ->setTitle("Reporte Excel") ->setSubject("Reporte Excel") ->setDescription("Reporte de activos y adiciones") ->setKeywords("reporte adicion activos") ->setCategory("Reporte excel"); $titulosColumnas = array('FECHA', 'CUENTA', 'SUBCUENTA', 'NoInventario', 'CANT', 'DESCRIPCION', 'SUBTOTAL', 'TOTAL','ESTADO','PRECIO UNITARIO','FOLIO'); // Se agregan los encabezados de la tabla $hoja ->setCellValue('A1', $titulosColumnas[0]) ->setCellValue('B1', $titulosColumnas[1]) ->setCellValue('C1', $titulosColumnas[2]) ->setCellValue('D1', $titulosColumnas[3]) ->setCellValue('E1', $titulosColumnas[4]) ->setCellValue('F1', $titulosColumnas[5]) ->setCellValue('G1', $titulosColumnas[6]) ->setCellValue('H1', $titulosColumnas[7]); //letra roja y negrita para el folio... $hoja->getStyle('I2')->getFont()->setBold(true); $hoja->getStyle('I2')->getFont()->getColor()->setRGB('8A0808'); // Se agrega info del mem $hoja ->setCellValue('F2', 'MINISTERIO DE ENERGÍA Y MINAS') ->setCellValue('F3', 'DIRECCION GENERAL ADMINISTRATIVA') ->setCellValue('F4', 'DEPARTAMENTO FINANCIERO') ->setCellValue('F5', obtenerMes($hoy['mon']) . ' ' . $hoy['year']); //Se agregan los datos de las adiciones $i = 6; while ($fila = $resultado->fetch_array()) { $codigoAdicion = $fila['codigo_adicion']; $consultaAdicion = "call obtenerTotalAdicion($codigoAdicion,@total)"; $connect->query($consultaAdicion); $c = "select @total as salida"; $query4 = $connect->query($c); $rs = $query4->fetch_assoc(); $totalAdicion = $rs['salida']; if ($totalAdicion != 0) { $total = $totalAdicion; } else { $total = 0; } //escribo las adiciones $hoja->setCellValue('F' . $i, $fila['nombre_adicion']); //seteo la celda tipo numerico. $hoja->getStyle('G' . $i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); $hoja->setCellValue('G' . $i, $total); $i++; } //ESTILO PARA EL ENCABEZADO DE LA TABLA. $estiloEncabezado = array( 'font' => array( 'name' => 'Arial', 'bold' => TRUE, 'size' => 9, 'color' => array( 'rgb' => '000000' ) ), 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'b8c0ef') ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN ) ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => TRUE )); //ESTILO PARA DONDE DICE MEM... $estiloInformacion = new PHPExcel_Style(); $estiloInformacion->applyFromArray( array( 'font' => array( 'name' => 'Arial', 'bold' => TRUE, 'size' => 14 ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => TRUE ) )); //estilo para el contenido $estiloContenido = new PHPExcel_Style(); $estiloContenido->applyFromArray( array( 'font' => array( 'name' => 'Arial', 'size' => 12 ), 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => TRUE ), 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN ) ) )); //seteo el ancho de cada columna... $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(10); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(13); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(14); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(110); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10); $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10); //aplico los estilos... $hoja->getStyle('A1:H1')->applyFromArray($estiloEncabezado); $hoja->setSharedStyle($estiloInformacion, "F2:F5"); //escribo el pie con total.. $mes = obtenerMes($hoy['mon']); $totalInventario = "EL TOTAL DEL INVENTARIO AL " . $hoy['mday'] . " DE " . $mes . " DEL AÑO " . $hoy['year'] . " ES DE:"; //seteo el valor y pinto la celda. $hoja->setCellValue('F' . ($i + 2), $totalInventario); $hoja->getStyle('F' . ($i + 2))->getFont()->setBold(TRUE); $hoja->getStyle('F' . ($i + 2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('9fb1b7'); $consultaTotal = "call obtenerTotalIngresos(@total)"; $connect->query($consultaTotal); $c = "select @total as salida"; $query4 = $connect->query($c); $rs = $query4->fetch_assoc(); $totalIngresos = $rs['salida']; $totalIng = number_format($totalIngresos, 2); $cadenaTotal = $conversor->to_word($totalIng); //seteo el valor y pinto la celda. $hoja->setCellValue('F' . ($i + 3), $cadenaTotal); $hoja->getStyle('F' . ($i + 3))->getFont()->setBold(TRUE); $hoja->getStyle('F' . ($i + 3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('9fb1b7'); //seteo el valor y le doy formato. $hoja->getStyle('H' . ($i + 3))->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); $hoja->setCellValue('H' . ($i + 3), '=SUM(G6:G'.($i-1).')'); //escribo los nombres y firmas... $hoja->setCellValue('F48', "FRANCISCO JOSE OCAMPO GONZALEZ ANA LETICIA ARAGON CASTILLO"); $hoja->getStyle('F48')->getFont()->setBold(TRUE); $hoja->setCellValue('F49', "ENCARGADO DE INVENTARIOS JEFE DE DEPARTAMENTO FINANCIERO"); $hoja->getStyle('F49')->getFont()->setBold(TRUE); $hoja->setCellValue('F50', "DIRECCION SUPERIOR DIRECCION SUPERIOR"); $hoja->getStyle('F50')->getFont()->setBold(TRUE); //centrado $hoja->getStyle('F48')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('F49')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('F50')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //busco todas las adiciones... $consulta = "SELECT * FROM adicion;"; $resultado = $connect->query($consulta); $x = 53; $contador = 1; if ($resultado->num_rows > 0) { while ($adiciones[] = $resultado->fetch_array()); //recorro las adiciones... foreach ($adiciones as $adicion) { $codAdicion = $adicion['codigo_adicion']; //obtengo el total de cada adicion... $consultaAdicion = "call obtenerTotalAdicion('$codAdicion',@total)"; $connect->query($consultaAdicion); $c = "select @total as salida"; $query4 = $connect->query($c); $rs = $query4->fetch_assoc(); $totalAdicion = $rs['salida']; //contador registros... if ($totalAdicion != null) { $hoja->setCellValue('F' . ($x + $contador), "ADICION No. " . $codAdicion . ' - ' . $adicion['nombre_adicion']); $hoja->getStyle('F' . ($x + $contador))->getFont()->setBold(TRUE); $hoja->getStyle('F' . ($x + $contador))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('9fb1b7'); $hoja->getStyle('F' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $contador++; //obtengo los activos por cada adicion... $rs = $conexion->obtenerActivosAdicion($codAdicion); while ($activo = $rs->fetch_array()) { //escribo la info del activo y la centro. $hoja->setCellValue('A' . ($x + $contador), $activo['fecha']); $hoja->getStyle('A' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //cuenta $hoja->setCellValue('B' . ($x + $contador), $activo['CUENTA_codigo_cuenta']); $hoja->getStyle('B' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //subcuenta $hoja->setCellValue('C' . ($x + $contador), $activo['codigo_subcuenta']); $hoja->getStyle('C' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //cod.inventario $hoja->setCellValue('D' . ($x + $contador), $activo['codigo_inventario']); $hoja->getStyle('D' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //cantidad $hoja->setCellValue('E' . ($x + $contador), $activo['cantidad']); $hoja->getStyle('E' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('E' . $i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); //descripcion $hoja->setCellValue('F' . ($x + $contador), $activo['descripcion']); $hoja->getStyle('F' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //estado $hoja->setCellValue('G' . ($x + $contador), obtenerEstado($activo['estado'])); $hoja->getStyle('G' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //precio unitario $hoja->setCellValue('H' . ($x + $contador), $activo['precio_unitario']); $hoja->getStyle('H' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('H' . $i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); //total $hoja->setCellValue('I' . ($x + $contador),'='.'E' . ($x + $contador).'*'.'H' . ($x + $contador)); $hoja->getStyle('I' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('I' . $i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1); //folio $hoja->setCellValue('J' . ($x + $contador), $activo['folio']); $hoja->getStyle('J' . ($x + $contador))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); $hoja->getStyle('J' . ($x + $contador))->getFont()->setBold(true); $hoja->getStyle('J' . ($x + $contador))->getFont()->getColor()->setRGB('8A0808'); //incremento... $x++; } } } } $inicio= 53; $hoja ->setCellValue('A' . ($inicio), $titulosColumnas[0]) ->setCellValue('B' . ($inicio), $titulosColumnas[1]) ->setCellValue('C' . ($inicio), $titulosColumnas[2]) ->setCellValue('D' . ($inicio), $titulosColumnas[3]) ->setCellValue('E' . ($inicio), $titulosColumnas[4]) ->setCellValue('F' . ($inicio), $titulosColumnas[5]) ->setCellValue('G' . ($inicio), 'ESTADO') ->setCellValue('H' . ($inicio), 'VALOR UNITARIO') ->setCellValue('I' . ($inicio), 'TOTAL') ->setCellValue('J' . ($inicio), 'FOLIO'); // Se agregan los encabezados de la tabla al finalizar los registros... $hoja ->setCellValue('A' . ($x + $contador + 1), $titulosColumnas[0]) ->setCellValue('B' . ($x + $contador + 1), $titulosColumnas[1]) ->setCellValue('C' . ($x + $contador + 1), $titulosColumnas[2]) ->setCellValue('D' . ($x + $contador + 1), $titulosColumnas[3]) ->setCellValue('E' . ($x + $contador + 1), $titulosColumnas[4]) ->setCellValue('F' . ($x + $contador + 1), $titulosColumnas[5]) ->setCellValue('G' . ($x + $contador + 1), 'ESTADO') ->setCellValue('H' . ($x + $contador + 1), 'VALOR UNITARIO') ->setCellValue('I' . ($x + $contador + 1), 'TOTAL') ->setCellValue('J' . ($x + $contador + 1), 'FOLIO'); //aplico los estilos... $hoja->getStyle('A'.$inicio.':J'.$inicio)->applyFromArray($estiloEncabezado); $hoja->getStyle('A' . ($x + $contador + 1) . ':J' . ($x + $contador + 1))->applyFromArray($estiloEncabezado); $objPHPExcel->getActiveSheet()->setTitle("ACTIVOS"); //Setting the header type $nombreArchivo = "LIBRO_" . $hoy['mday'] . "." . $hoy['mon'] . "." . $hoy["year"] . "_" . $hoy['hours'] . "." . $hoy['minutes'] . "." . $hoy['seconds'] . ".xlsx"; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $nombreArchivo . '"'); header('Cache-Control: max-age=0'); ob_clean(); $objWriter->save('php://output'); exit; } else { print_r('No hay resultados para mostrar'); } function obtenerMes($numeroMes) { switch ($numeroMes) { case 1: return "Enero"; case 2: return "Febrero"; case 3: return "Marzo"; case 4: return "Abril"; case 5: return "Mayo"; case 6: return "Junio"; case 7: return "Julio"; case 8: return "Agosto"; case 9: return "Septiembre"; case 10: return "Octubre"; case 11: return "Noviembre"; case 12: return "Diciembre"; } } function obtenerEstado($numeroEstado) { switch ($numeroEstado) { case 1: return "Disponible"; case 2: return "Certificado"; case 3: return "Pendiente"; case 0: return "De baja"; } } ?>
PHP
UTF-8
349
2.65625
3
[ "MIT" ]
permissive
--TEST-- imagehistgram() function --SKIPIF-- --FILE-- <?php chdir(dirname(__FILE__)); $im = imagecreatefromjpeg('../examples/images/mosaic.jpg'); $histgram = imagehistgram($im); if (is_array($histgram) && count($histgram) === 3 && is_array($histgram[0]) && count($histgram[0]) == 256) { echo 'OK'; } else { echo 'NG'; } ?> --EXPECT-- OK
Swift
UTF-8
1,281
2.59375
3
[]
no_license
// // LittleCategoryCell.swift // itvTask // // Created by Jahongir Nematov on 6/15/19. // Copyright © 2019 Jahongir Nematov. All rights reserved. // import UIKit class LittleCategoryCell : CategoryCell { private let littleItemCellId = "littleItemCellId" override func setupView() { super.setupView() itemCollectionView.register(LittleItemCell.self, forCellWithReuseIdentifier: littleItemCellId) } } extension LittleCategoryCell { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: littleItemCellId, for: indexPath) as! LittleItemCell cell.item = itemData?[indexPath.item] return cell } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let screenSize : CGRect = UIScreen.main.bounds //Ipad if screenSize.width > 750 { return CGSize(width: frame.width/5 - 12, height: frame.height-54) } return CGSize(width: frame.width/3 - 15, height: frame.height-54) } }
Markdown
UTF-8
1,586
2.9375
3
[]
no_license
# DjangoTest Python Django Framework test project # Info: Ці команди вводяться в git bash або в консолі якщо ви при установці вказали роботу з гітом через консоль; перед введенням команд потрібно перейти в директорію вашого проекту (якщо через баш то можна перейти в папку там пкм і вибрати git bash) # Для нового проекта робіть нову гілку `git init` - якщо просто оновлення то без цього `git add *` `git commit -m "коміт шоб було понятно шо за хуйню ви кидаєте"` `git remote add origin https://github.com/Vionikk/DjangoTest` `git push origin <назва гілки в яку хочете закинути>` # Клонувати проект собі на компухтєр `git clone <адреса яка появляється після нажатія на зелену кнопочку code>` (тільки слідкуйте за гілкою бо я так пару раз проїбався колись) `git pull` - оновити репозиторій в себе на машині # Робота з гілками + перехід на основну гілку: `git checkout front` + створити нову гілку і одразу перейти на неї: `git checkout -b <newBranchName>` + вивести всі гілки репозиторію: `git branch -a`
Java
UTF-8
1,235
2.34375
2
[ "MIT" ]
permissive
package com.wuhulala.rabbitmq.chapter2.persistence; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.wuhulala.rabbitmq.util.ChannelFactory; import java.io.IOException; /** * 0_0 o^o * * @author wuhulala<br> * @date 2019/5/27<br> * @description o_o<br> * @since v1.0<br> */ public class PersistenceProducer { public static final AMQP.BasicProperties PERSISTENT_TEXT_PLAIN = new AMQP.BasicProperties("text/plain", null, null, 2, // 持久化 0, null, null, null, null, null, null, null, null, null) ; public static void main(String[] args) { Channel channel = ChannelFactory.getChannelInstance(); try { channel.exchangeDeclare("persistence-exchange", BuiltinExchangeType.DIRECT, true); channel.queueDeclare("d", true, true, true, null); } catch (IOException e) { e.printStackTrace(); } } }
Java
UTF-8
293
3.375
3
[]
no_license
import java.util.*; public class strrev { public static void main(String args[]) { System.out.println(stringreverse("qwe").toString()); } public static String stringreverse(String a) { String rev=""; for(int i=a.length()-1;i>=0;i--) { rev+=a.charAt(i); } return rev; } }
Markdown
UTF-8
2,801
2.609375
3
[ "MIT" ]
permissive
--- author: Bela Seeger date: 2015-11-10 10:00:56 image: src : /static/images/projects/openbudgets.png layout: post tags: - Transparenz title: "OpenBudgets - OKF DE will contribute to advance fiscal transparency in Europe" type: post --- [**OpenBudgets.eu**](http://openbudgets.eu/), a new project promoting transparency and accountability in the domain of public spending, is launched. The Horizon2020-funded project provides journalists, civil society organisations, NGOs, citizens and public administrations with the tools, data and stories they need to advocate and fight for fiscal transparency. *"Democratic political life as we know it is inconceivable without public access to information about public money”* says Jonathan Gray, director of Policy and Research at Open Knowledge. While an increasing amount of budget and transaction data is made publicly available in Europe, different data standards and accounting models restrict its utility. Sören Auer, professor in Enterprise Information Systems at Fraunhofer and Bonn University and coordinator of OpenBudgets.eu: *“The heterogeneity and lack of standardization of Open Spending and Budget data prevents many interesting applications from being realized”*, such as *“the comparative analysis between different cities or regions, to improve the efficiency and effectiveness of public spending”*. [**OpenBudgets.eu**](http://openbudgets.eu/) aims to solve this issue by developing a platform that will be easy-to-use, flexible, and capable of interpreting previously incompatible types of budget and spending data. The platform’s users will be able to simply upload, visualise, and analyse public budget and spending data to explore and learn stories behind it. In May this year the project started and the first milestones have already been reached. We are currently seeking the input from its future user groups by actively involving them. The first stakeholder workshop will take place at the end of November in Berlin. The [**OpenBudgets.eu**](http://openbudgets.eu/) team invites those who are interested in giving input to get in touch with them. *[OpenBudgets.eu](http://openbudgets.eu/) is a 30-month project run by an international consortium of nine partners: Open Knowledge International, Journalism++, Open Knowledge Greece, Bonn University, Fraunhofer IAIS, Open Knowledge Foundation Deutschland, Fundación Civio, Transparency International-EU, and University of Economics, Prague.* More information: http://openbudgets.eu Press contact: Anna Alberts - Open Knowledge Foundation Germany [OpenBudgets.eu](http://openbudgets.eu/) | [@OpenBudgetsEU](https://twitter.com/OpenBudgetsEU) [Anna Alberts](mailto:anna.alberts@okfn.de) | [@Anna_Alberts](https://twitter.com/Anna_Alberts) Office: +49 30 57703666 0 Mobile: +49 176 21370998
Markdown
UTF-8
2,158
2.765625
3
[ "Apache-2.0" ]
permissive
# Sensors ## Sensors - Get All ```shell curl -X GET "https://cloud.verisolutions.co/api/v7/sensors" -H "Authorization: Basic <token>" -H "Content-Type: application/vnd.api+json" ``` This endpoint retrieves all Sensors that you have access to. ### Filtering Almost all attributes are filterable. The following contains special-case information. Refer to the Filtering section for definitions and examples. Parameter | Type | Details --------- | ---- | ----------- `battery` | Number Range `humidity` | Number Range `last-online` | Time Range `readings-count` | Number Range `rssi` | Number Range `successful-readings-count` | Number Range `temp` | Number Range ## Sensors - Create ```shell curl --request POST \ --url https://cloud.verisolutions.co/api/v7/sensors \ --header 'Authorization: Basic <token>' \ --header 'Content-Type: application/vnd.api+json' \ --data '{"data":{"type":"sensors","attributes":{"name":"<name>","unit-id":<unit-id>}}}' ``` ### Validations Parameter | Rule --------- | ---- `unit-id` | Must be an integer <aside class="warning"> This functionality is only for Admins. </aside> ## Sensors - Update ```shell curl --request PATCH \ --url http://localhost:9292/api/v7/sensors/<id> \ --header 'Authorization: Basic <token>' \ --header 'Content-Type: application/vnd.api+json' \ --data '{"data":{"type":"sensors","id":"<id>","attributes":{"name":"<name>"}}}' ``` ### Validations Parameter | Rule --------- | ---- `unit-id` | If provided, must be an integer `location-id` | If provided, must be a Cooler id or null. If provided, must set `location-type` to `"Cooler"` or `null`, respectively `location-type` | Must be `"Cooler"` or `null`. If `"Cooler"` provided, then must set `location-id` to a Cooler id ## Sensors - Destroy ```shell curl --request DELETE \ --url http://localhost:9292/api/v7/sensors/<id> \ --header 'Authorization: Basic <token>' \ --header 'Content-Type: application/vnd.api+json' \ ``` ### Validations Cannot destroy Sensors that have `hardware-status: 'active'`. Change this before destorying. <aside class="warning"> This functionality is only for Admins. </aside>
C++
UTF-8
881
2.703125
3
[]
no_license
#include <sstream> #include "Subte.h" Subte::Subte (std::string datos){ this->leerInformacion(datos); } void Subte::leerInformacion(std::string datos){ std::stringstream registro; std::string dato; std::string longitud, latitud; registro<<datos; unsigned int columnaLeida=1; while(getline(registro,dato,',')){ switch(columnaLeida){ case 1:{ longitud=dato; }break; case 2:{ latitud=dato; }break; case 3:{ this->id=dato; }break; case 4:{ this->linea=dato; }break; case 5:{ this->estacion=dato; }break; case 7:{ this->destino=dato; }break; case 8:{ this->combinaciones=dato; }break; case 15:{ this->calle=dato; }break; case 16:{ this->altura=dato; }break; } columnaLeida++; } this->ubicacion=new Coordenadas(longitud, latitud); }
Python
UTF-8
260
2.75
3
[]
no_license
import urllib.request data = {} data['word'] = 'Jinx' url_values = urllib.parse.urlencode(data) url = "http://www.baidu.com/s?" full_url = url + url_values print(full_url) data = urllib.request.urlopen(full_url).read() data = data.decode('UTF-8') print(data)
PHP
UTF-8
6,215
2.921875
3
[ "MIT" ]
permissive
<?php namespace Pletfix\Ldap\Services; use Pletfix\Ldap\Exceptions\LdapException; use Pletfix\Ldap\Services\Contracts\Ldap as LdapContract; /** * LDAP is the Lightweight Directory Access Protocol, and is a protocol used to access a Active Directory Servers. * * @see http://de2.php.net/manual/en/book.ldap.php for more details. */ class Ldap implements LdapContract { /** * The LDAP link identifier. * * @var resource */ private $ldap; /** * Connection parameters. * * @var array */ private $config; /** * Create a new Ldap instance. */ public function __construct() { $this->config = config('ldap'); } /** * Get a LDAP link identifier. * * @return resource * @throws LdapException */ private function getLdap() { if ($this->ldap === null) { $conn = $this->config['connection']; $protocol = isset($conn['use_ssl']) && $conn['use_ssl'] == true ? 'ldaps://' : 'ldap://'; $port = isset($conn['port']) ? $conn['port'] : ($protocol == 'ldap://' ? 389 : 636); foreach ($conn['domain_controllers'] as $dc) { $host = $protocol . $dc; $resource = @ldap_connect($host, $port); if ($resource !== false && ldap_bind($resource)) { $this->ldap = $resource; break; } } if ($this->ldap === null) { throw new LdapException('Connect to LDAP server failed!'); } ldap_set_option($this->ldap, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($this->ldap, LDAP_OPT_REFERRALS, isset($conn['referrals']) ? $conn['referrals'] : false); } return $this->ldap; } /** * @inheritdoc */ public function search($filter) { // Set the attributes that is to be received. $attributes = $this->config['attributes']; if (!in_array('userprincipalname', $attributes)) { $attributes[] = 'userprincipalname'; } // Search LDAP tree. $ldap = $this->getLdap(); $dn = $this->config['connection']['base_dn']; $sr = @ldap_search($ldap, $dn, $filter, $attributes); if ($sr === false) { throw new LdapException($ldap); } // Get the searching result $data = @ldap_get_entries($ldap, $sr); if ($data === false) { throw new LdapException($ldap); } // Convert the result data to a simple array. Each entry get each attribute that is defined. $entries = []; $count = $data['count']; for ($i = 0; $i < $count; $i++) { $entries[$i] = []; foreach ($attributes as $attribute) { if (!isset($data[$i][$attribute])) { $entries[$i][$attribute] = null; continue; } $n = $data[$i][$attribute]['count']; if ($n > 1 || in_array($attribute, ['memberof'])) { $entries[$i][$attribute] = []; for ($j=0; $j < $n; $j++) { $entries[$i][$attribute][$j] = $data[$i][$attribute][$j]; } } else { $entries[$i][$attribute] = $data[$i][$attribute][0]; } } // Determine the user role if (in_array('memberof', $attributes)) { $entries[$i]['role'] = $this->getRole($entries[$i]['memberof'] ?: []); } } return $entries; } /** * @inheritdoc */ public function getUsers($filter = '*') { return $this->search('userprincipalname=' . $filter); } /** * @inheritdoc */ public function getUser($username) { $entries = $this->search('userprincipalname=' . $this->principal($username)); return !empty($entries) ? $entries[0] : []; } /** * @inheritdoc */ public function authenticate($username, $password) { $ok = @ldap_bind($this->getLdap(), $this->principal($username), $password); return $ok; } /** * Convert the username into the userPrincipalName attribute. * @param string $username * @return string */ private function principal($username) { if (strpos($username, '@') === false) { $username .= $this->config['connection']['account_suffix']; } return $username; } /** * Return the applications user role by given memberof attribute. * * @param array $memberOf * @return array */ private function getRole(array $memberOf) { if (empty($memberOf)) { return $this->config['role']['default']; } // Get the Common Names (CN) of the members. $cns = []; foreach ($memberOf as $member) { foreach (explode(',', $member) as $item) { if (substr($item, 0, 3) == 'CN=') { $cns[substr($item, 3)] = true; } } } // Find the first matching role in the mapping table. foreach ($this->config['role']['mapping'] as $cn => $role) { if (isset($cns[$cn])) { return $role; } } return $this->config['role']['default']; } /** * @inheritdoc */ public function getErrorCode() { $errorCode = ldap_errno($this->ldap); return $errorCode; } /** * @inheritdoc */ public function getErrorMessage() { $error = ldap_error($this->ldap); return $error; } // private function bindControlUser() // { // // Control User an Server binden. // $account = $this->config['operator_account']; // $success = @ldap_bind($this->getLdap(), $account['username'], $account['password']); // if (!$success) { // throw new LdapException('LDAP bind failed.'); // } // // return $success; // } }
C++
UTF-8
4,798
2.734375
3
[]
no_license
float correlation(ImagePtr I1, ImagePtr I2, int &xx, int &yy) { // init vars to suppress compiler warnings int dx = 0; int dy = 0; float corr = 0; // image dimensions int w = I1->width (); int h = I1->height(); // template dimensions int ww = I2->width (); int hh = I2->height(); // error checking: size of image I1 must be >= than template I2 if(!(ww<=w && hh<=h)) { fprintf(stderr, "Correlation: image is smaller than template\n"); return 0.; } // cast image into buffer of type float ImagePtr II1; if(I1->channelType(0) != FLOAT_TYPE) { II1 = IP_allocImage(I1->width(), I1->height(), FLOATCH_TYPE); IP_castChannel(I1, 0, II1, 0, FLOAT_TYPE); } else II1 = I1; // cast template into buffer of type float ImagePtr II2; if(I2->channelType(0) != FLOAT_TYPE) { II2 = IP_allocImage(I2->width(), I2->height(), FLOATCH_TYPE); IP_castChannel(I2, 0, II2, 0, FLOAT_TYPE); } else II2 = I2; // create image and template pyramids with original images at base; // if no multiresolution is used, pyramids consist of only one level. int mxlevel; ImagePtr pyramid1[8], pyramid2[8]; pyramid1[0] = II1; // base: original image pyramid2[0] = II2; // base: original template mxlevel = 0; // init search window int x1 = 0; int y1 = 0; int x2 = (w-ww)>>mxlevel; int y2 = (h-hh)>>mxlevel; // declarations int total; float sum1, sum2, tmpl_pow; ChannelPtr<float> image, templ; ImagePtr Iblur, Ifft1, Ifft2; // multiresolution correlation: use results of lower-res correlation // (at the top of the pyramid) to narrow the search in the higher-res // correlation (towards the base of the pyramid). for(int n=mxlevel; n>=0; n--) { // init vars based on pyramid at level n w = pyramid1[n]->width(); h = pyramid1[n]->height(); ww = pyramid2[n]->width(); hh = pyramid2[n]->height(); // pointers to image and template data ChannelPtr<float> p1 = pyramid1[n][0]; // image ptr ChannelPtr<float> p2 = pyramid2[n][0]; // template ptr // init min and max float max = 0.; for(int y=y1; y<=y2; y++) { // visit rows for(int x=x1; x<=x2; x++) { // slide window sum1 = sum2 = 0; image = p1 + y*w + x; templ = p2; for(int i=0; i<hh; i++) { // convolution for(int j=0; j<ww; j++) { sum1 += (templ[j] * image[j]); sum2 += (image[j] * image[j]); } image += w; templ += ww; } if(sum2 == 0) continue; corr = sum1 / sqrt(sum2); if(corr > max) { max = corr; dx = x; dy = y; } } } // update search window or normalize final correlation value if(n) { // set search window for next pyramid level x1 = MAX(0, 2*dx - n); y1 = MAX(0, 2*dy - n); x2 = MIN(2*w, 2*dx + n); y2 = MIN(2*h, 2*dy + n); } else { // normalize correlation value at final level tmpl_pow = 0; total = ww * hh; for(int i=0; i<total; i++) tmpl_pow += (p2[i] * p2[i]); corr = max / sqrt(tmpl_pow); } } xx = dx; yy = dy; return corr; } float* HW_correlation(ImagePtr I1, ImagePtr Itemplate, ImagePtr I2) { ImagePtr tempImage; IP_copyImageHeader(I1, I2); IP_copyImageHeader(I1, tempImage); int width = I1->width(); int height = I1->width(); int width_k = Itemplate->width(); int height_k = Itemplate->height(); int xx, yy; // coordinate of where template image sits in input image // get cross-correlation value float corr = correlation(I1, Itemplate, xx, yy); int type; ChannelPtr<uchar> p1, p2, p3, endd; for(int ch = 0; IP_getChannel(I1, ch, p1, type); ch++) { IP_getChannel(I2, ch, p2, type); IP_getChannel(Itemplate, ch, p3, type); for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { if(i < yy) { // if we are above template image *p2++ = *p1/2; p1++; } else if(i >= yy && i <= (yy-1+height_k)) { // if we are on the rows where template image resides if(j < xx) { // if we are before the template image columns *p2 = *p1/2; } else if(j >= xx && j < (xx+width_k)) { // if we are on the columns where template resides *p2 = *p1/2 + *p3/2; p3++; } else { // if we are after the template image columns *p2 = *p1/2; } p1++; p2++; } else { // if we are below the template images *p2++ = *p1/2; p1++; } } } } float *buf = new float[3]; buf[0] = xx; buf[1] = yy; buf[2] = corr; return buf; }
C++
UTF-8
1,277
3
3
[ "MIT" ]
permissive
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #define INF 0x7FFFFFF #define PIG_WEIGHT 10001 #define SIZE 501 using namespace std; typedef struct Node { int value; int weight; } coin; coin arr[SIZE]; int dp[PIG_WEIGHT]; int main() { ios::sync_with_stdio(false); int caseNum; cin >> caseNum; for (int t = 0; t < caseNum; t++) { int emptyPigWeight, pigWeight; cin >> emptyPigWeight >> pigWeight; pigWeight -= emptyPigWeight; int coinNum; cin >> coinNum; for (int i = 0; i < coinNum; i++) cin >> arr[i].value >> arr[i].weight; dp[0] = 0; for (int j = 1; j <= pigWeight; j++) dp[j] = INF; for (int i = 0; i < coinNum; i++) { if (arr[i].weight > pigWeight) continue; for (int j = arr[i].weight; j <= pigWeight; j++) { dp[j] = min(dp[j], dp[j - arr[i].weight] + arr[i].value); } } if (dp[pigWeight] == INF) cout << "This is impossible." << endl; else cout << "The minimum amount of money in the piggy-bank is " << dp[pigWeight] << "." << endl; } return 0; }
PHP
UTF-8
213
3.03125
3
[]
no_license
<?php class Solution { /** * @param String $address * @return String */ function defangIPaddr($address) { $res = str_replace('.', '[.]', $address); return $res; } }
C
UTF-8
657
2.671875
3
[]
no_license
#include "test_driver.h" int testPeople(int* failed) { struct gameState g; int k[10] = {smithy,adventurer,gardens,embargo,cutpurse,mine,ambassador, outpost,baron,tribute}; int r = initializeGame(2, k, 5, &g); myassert(failed, r == 0, "No duplicates, 2 players, should succeed"); int k2[10] = {smithy,adventurer,gardens,embargo,cutpurse,mine,ambassador, outpost,baron,adventurer}; r = initializeGame(2, k2, 5, &g); myassert(failed, r == -1,"Duplicate card in setup, should fail"); r = initializeGame(200, k, 5, &g); myassert(failed, r == 0,"I should be allowed to play with a lot of people!"); return 0; }
C#
UTF-8
830
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using SurrealistGames.GameLogic; namespace GameLogic.Tests.cs { [TestFixture] public class AnswerFormatterTests { [TestCase("The meaning of life.", "The meaning of life.", TestName="Format_OnAlreadyFormattedAnswer_ReturnsTheAnswer")] [TestCase(" God ", "God", TestName="Format_OnAnswerWithLeadingAndTrailingWhiteSpace_ReturnsTrimmedAnswer")] public void Format_OnTestCases(string input, string expected) { var formatter = new AnswerFormatter(); var actual = formatter.Format(input); Assert.AreEqual(expected, actual); } } }
C#
UTF-8
1,680
3.28125
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestDeck_ImageGenerator { public class FileDelimeter { public static DataTable DataFromTextFile(string location, char delimeter) { DataTable result; string[] LineArray = File.ReadAllLines(location); result = FormDataTable(LineArray, delimeter); return result; } private static DataTable FormDataTable(string[] LineArray, char delimeter) { DataTable dt = new DataTable(); AddColumnToTable(LineArray, delimeter, ref dt); AddRowToTable(LineArray, delimeter, ref dt); return dt; } private static void AddRowToTable(string[] valueCollection, char delimeter, ref DataTable dt) { for (int i = 1; i < valueCollection.Length; i++) { string[] values = valueCollection[i].Split(delimeter); DataRow dr = dt.NewRow(); for (int j = 0; j < values.Length; j++) { dr[j] = values[j]; } dt.Rows.Add(dr); } } private static void AddColumnToTable(string[] columnCollection, char delimeter, ref DataTable dt) { string[] columns = columnCollection[0].Split(delimeter); foreach (string columnName in columns) { DataColumn dc = new DataColumn(columnName, typeof(string)); dt.Columns.Add(dc); } } } }
Java
UTF-8
690
2.15625
2
[]
no_license
package com.cos.blogapp2.web.dto; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import com.cos.blogapp2.domain.user.User; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class JoinReqDto { @Size(min = 2, max = 20) @NotBlank private String username; @Size(min = 4, max = 20) @NotBlank private String password; @Size(min = 4, max = 50) @NotBlank private String email; public User toEntity() { User user = User.builder().username(username).password(password).email(email).build(); return user; } }
JavaScript
UTF-8
1,782
2.9375
3
[ "MIT" ]
permissive
define(() => { 'use strict'; const scoreSorter = (a, b) => { if(a.disqualified !== b.disqualified) { return a.disqualified ? 1 : -1; } if(a.food !== b.food) { return b.food - a.food; } return b.workers - a.workers; }; return { score: (config, {teams}) => { const gameTeamScores = teams.map((team) => { let teamWorkers = 0; let food = 0; let disqualified = true; const entries = []; team.entries.forEach((entry) => { let entryWorkers = 0; entry.workers.forEach((count) => entryWorkers += count); if(!entry.disqualified) { disqualified = false; teamWorkers += entryWorkers; food += entry.food; } entries.push({ id: entry.id, food: entry.food, workers: entryWorkers, disqualified: entry.disqualified, }); }); entries.sort(scoreSorter); return { id: team.id, food, workers: teamWorkers, disqualified, winner: false, score: 0, entries, }; }); gameTeamScores.sort(scoreSorter); // Score = number of teams with food strictly less than current team let tiedFood = 0; let tiedTeams = 0; let accumScore = 0; for(let i = gameTeamScores.length; (i --) > 0;) { const place = gameTeamScores[i]; if(place.food !== tiedFood) { tiedFood = place.food; accumScore += tiedTeams; tiedTeams = 0; } if(!place.disqualified) { place.score = accumScore; } ++ tiedTeams; } // Winners = teams tied for most food for(let i = 0; i < gameTeamScores.length; ++ i) { const place = gameTeamScores[i]; if(place.disqualified || place.food < gameTeamScores[0].food) { break; } place.winner = true; } return {teams: gameTeamScores}; }, }; });
C
UTF-8
1,220
4.03125
4
[]
no_license
#include <stdio.h> #define MAS 100 // Maximum Array size int main() { // Start main() int Arr[MAS], n, i, j, k ,l=0, temp,gap; label: printf("Enter number of elements in the Array (max %d) : ",MAS); scanf("%d", &n); if(n<1||n>100) { printf("Please enter a valid Array size ! \n"); goto label; } printf("Enter Array elements : ", n); for ( i = 0 ; i < n ; i++ ) // Take input scanf("%d", &Arr[i]); for(gap=n/2; gap > 0; gap /= 2) // Loop to perform Shell sort { l+=1; for(i=gap;i< n; i += 1) { temp = Arr[i]; for (j = i; j >= gap && Arr[j - gap] > temp; j -= gap) Arr[j] = Arr[j - gap]; Arr[j] = temp; } printf("The Array after iteration %d is : ",l); for ( k = 0 ; k < n ; k++ ) // Show intermediate Arrays printf("%d ", Arr[k]); printf("\n"); } printf("\nThe Sorted Array in ascending order is : "); for ( i = 0 ; i < n ; i++ ) // Display Sorted Array printf("%d ", Arr[i]); return 0; } // End main()
JavaScript
UTF-8
427
2.75
3
[]
no_license
$(document).ready(function () { $('.tweet-field').on('input', function () { const tweetLength = this.value.length; const tweetCounter = $(this).siblings('.counter'); const errorMessage = $('.error-msg'); tweetCounter.html(140 - tweetLength); tweetCounter.css({color: '#4a5a9b'}); errorMessage.hide(); if (tweetLength > 140) { tweetCounter.css({color: '#d33829'}); } }); });
Java
UTF-8
3,689
2.546875
3
[ "MIT" ]
permissive
package tech.yaog.utils.statemachine; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; /** * Created by ygl_h on 2017/7/17. */ public class StateMachineTest { private StateMachine<Integer, Integer> tradeStateMachine; private enum STATE { IDEL(0), WAIT_TO_CONFIRM(1), CONFIRMED(2), QR_GETED(3), WAIT_TO_PAY(4), PAYED(5), WAIT_CHECK(6), SUCCEED(7), TO_RESET(8) ; int val; STATE(int val) { this.val = val; } } enum EVENT { SELECT(0), CANCEL(1), SELECTED(2), SELECT_FAILED(52), CONFIRMED(3), CONFIRM_FAILED(53), U_PAYED(4), U_PAY_FAILED(54), RESETED(5), TIMEOUT(6), QR_GETED(7), QR_GETFAILED(57), W_PAYED(8), W_PAYFAILED(9), CAN_OUT(10), CANNOT_OUT(11) ; int val; EVENT(int val) { this.val = val; } } private String output = ""; @Before public void setUp() throws Exception { tradeStateMachine = new StateMachine<>(); State<Integer, Integer> idle = new State<Integer, Integer>(STATE.IDEL.val) .onEntry(new State.Handler() { @Override public void handle(Object... data) { output+="IDEL;"; } }) .onEvent(EVENT.SELECT.val, STATE.WAIT_TO_CONFIRM.val, new State.Handler() { @Override public void handle(Object... data) { output+=String.valueOf(data[0])+";"; } }); State<Integer, Integer> selected = new State<Integer, Integer>(STATE.WAIT_TO_CONFIRM.val) .onEntry(new State.Handler() { @Override public void handle(Object... data) { output+="TO_CONFIRM;CONFIRM_SEND;"; } }) .onEvent(EVENT.CANCEL.val, STATE.TO_RESET.val, new State.Handler() { @Override public void handle(Object... data) { output+="CANCELED;"; } }) .onEvent(EVENT.TIMEOUT.val, STATE.TO_RESET.val); State<Integer, Integer> toRest = new State<Integer, Integer>(STATE.TO_RESET.val) .onEntry(new State.Handler() { @Override public void handle(Object... data) { output+="TO_RESET;"; } }) .onEvent(EVENT.RESETED.val,STATE.IDEL.val) .onExit(new State.Handler() { @Override public void handle(Object... data) { output+="TO_RESET_EXIT;"; } }); tradeStateMachine.setStates(idle, selected, toRest); } @Test public void testSelectAndCancel() { output = ""; tradeStateMachine.start(); Event<Integer> selectEvent = new Event<>(EVENT.SELECT.val); selectEvent.setData(1); tradeStateMachine.event(selectEvent); tradeStateMachine.event(new Event<>(EVENT.CANCEL.val)); tradeStateMachine.event(new Event<>(EVENT.CANCEL.val)); tradeStateMachine.event(new Event<>(EVENT.RESETED.val)); assertEquals("IDEL;1;TO_CONFIRM;CONFIRM_SEND;CANCELED;TO_RESET;TO_RESET_EXIT;IDEL;", output); } }
Go
UTF-8
1,319
3.515625
4
[]
no_license
package main import ( "fmt" "math" ) // 验证二叉搜索树 func isValidBST(root *TreeNode) bool { return checkBST(root, math.MinInt64, math.MaxInt64) } func checkBST(node *TreeNode, minValue int, maxValue int) bool { if node == nil { return true } if node.Val <= minValue || node.Val >= maxValue { return false } return checkBST(node.Left, minValue, node.Val) && checkBST(node.Right, node.Val, maxValue) } // 用中序遍历 func checkBSTByMiddleOrder(root *TreeNode) bool { return inOrder(root) } var pre int = math.MinInt64 func inOrder(root *TreeNode) bool { if root == nil { return true } l := inOrder(root.Left) if root.Val <= pre { return false } pre = root.Val r := inOrder(root.Right) return l && r } func middleOrder(root *TreeNode) { if root == nil { return } middleOrder(root.Left) fmt.Printf("%d ", root.Val) middleOrder(root.Right) } func isValidBST2(root *TreeNode) bool { if root == nil { return false } stack := []*TreeNode{} cur := root var pre *TreeNode = nil for cur != nil || len(stack) > 0 { if cur != nil { stack = append(stack, cur) cur = cur.Left } else { cur = stack[len(stack)-1] stack = stack[:len(stack)-1] if pre != nil && cur.Val <= pre.Val { return false } pre = cur cur = cur.Right } } return true }
Markdown
UTF-8
5,795
2.625
3
[]
no_license
--- manual:WebAPI version:0 lang:zh rawUrl:https://developer.mozilla.org/zh-CN/docs/Web/API/Animation/finish --- <bdi>我们的志愿者还没有将这篇文章翻译为<bdi>中文 (简体)</bdi>。[加入我们帮助完成翻译]22626 "")<br></br>您也可以阅读此文章的[English (US)]14091 "")版。</bdi> **This is an[experimental technology]3404 "")**<br></br>Check the[Browser compatibility table](%3464#Browser_compatibility "")carefully before using this in production. The**`finish()`**method of the[Web Animations API]3476 "")&#39;s[`Animation`]3478 "The Animation interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source.")Interface sets the current playback time to the end of the animation corresponding to the current playback direction.That is, if the animation is playing forward, it sets the playback time to the length of the animation sequence, and if the animation is playing in reverse (having had its[`reverse()`]14102 "The Animation.reverse() method of the Animation Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse.")method called), it sets the playback time to 0. ## Syntax<a name="Syntax"></a> ``` Animation.finish(); ``` ### Parameters<a name="Parameters"></a> None. ### Return value<a name="Return_value"></a> None. <dl></dl> ### Exceptions<a name="Exceptions"></a> <dl><dt id=''>`InvalidState`</dt><dd>The player&#39;s playback rate is 0 or the animation&#39;s playback rate is greater than 0 and the end time of the animation is infinity.</dd></dl> ## **Examples**<a name="Examples"></a> The following example shows how to use the`finish()`method and catch an`InvalidState`error. ``` interfaceElement.addEventListener("mousedown", function() { try { player.finish(); } catch(e if e instanceof InvalidState) { console.log("finish() called on paused or finished animation."); } catch(e); logMyErrors(e); //pass exception object to error handler } }); ``` The following example finishes all the animations on a single element, regardless of their direction of playback. ``` elem.getAnimations().forEach( function(animation){ return animation.finish(); } ); ``` ## Specifications<a name="Specifications"></a> Specification | Status | Comment [Web Animations<br></br><small>The definition of &#39;finish()&#39; in that specification.</small>]22628 "") | Working Draft | ## Browser compatibility<a name="Browser_compatibility"></a> [新的兼容性表格正在测试中<i></i>]3360 "") <abbr>Desktop<i></i></abbr> | <abbr>Mobile<i></i></abbr> <abbr>Chrome<i></i></abbr> | <abbr>Edge<i></i></abbr> | <abbr>Firefox<i></i></abbr> | <abbr>Internet Explorer<i></i></abbr> | <abbr>Opera<i></i></abbr> | <abbr>Safari<i></i></abbr> | <abbr>Android webview<i></i></abbr> | <abbr>Chrome for Android<i></i></abbr> | <abbr>Edge Mobile<i></i></abbr> | <abbr>Firefox for Android<i></i></abbr> | <abbr>Opera for Android<i></i></abbr> | <abbr>iOS Safari<i></i></abbr> | <abbr>Samsung Internet<i></i></abbr> --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | Basic support<abbr>Experimental<i></i></abbr> | <abbr>Full support</abbr>39 | <abbr>?</abbr> | <abbr>Full support</abbr>48 | <abbr>No support</abbr>No | <abbr>Full support</abbr>26 | <abbr>No support</abbr>No | <abbr>Full support</abbr>39 | <abbr>Full support</abbr>39 | <abbr>?</abbr> | <abbr>Full support</abbr>48 | <abbr>Full support</abbr>26 | <abbr>No support</abbr>No | <abbr>Full support</abbr>4.0 ### Legend<a name="Legend"></a> <dl><dt id=''><abbr>Full support</abbr></dt><dd>Full support</dd><dt id=''><abbr>No support</abbr></dt><dd>No support</dd><dt id=''><abbr>Compatibility unknown</abbr></dt><dd>Compatibility unknown</dd><dt id=''><abbr>Experimental. Expect behavior to change in the future.<i></i></abbr></dt><dd>Experimental. Expect behavior to change in the future.</dd><dt id=''><abbr>User must explicitly enable this feature.<i></i></abbr></dt><dd>User must explicitly enable this feature.</dd></dl> ## See also<a name="See_also"></a> * [Web Animations API]3476 "") * [`Animation`]3478 "The Animation interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source.")for other methods and properties you can use to control web page animation. * [`Animation.play()`]14099 "The play() method of the Web Animations API's Animation Interface starts or resumes playing of an animation. If the animation is finished, calling play() restarts the animation, playing it from the beginning.")to play an animation forward. * [`Animation.reverse()`]14102 "The Animation.reverse() method of the Animation Interface reverses the playback direction, meaning the animation ends at its beginning. If called on an unplayed animation, the whole animation is played backwards. If called on a paused animation, the animation will continue in reverse.")to play an animation backward. ## 文档标签和贡献者 **标签:** * [Animation]3470 "") * [API]50 "") * [Finish]22629 "") * [Interface]3380 "") * [Method]14476 "") * [Reference]3381 "") * [waapi]3554 "") * [Web Animations]3490 "") * [web animations api]3491 "") **此页面的贡献者:**[fscholz]60 ""),[jpmedley]3413 ""),[birtles]3555 ""),[sebastien-bartoli]22630 ""),[Sheppy]405 ""),[chrisdavidmills]3495 ""),[rachelnabors]3494 ""),[teoli]160 ""),[kscarfone]3900 "") **最后编辑者:**[fscholz]60 ""),<time>Feb 13, 2018, 2:20:07 AM</time>
C#
UTF-8
2,325
2.546875
3
[]
no_license
using FluentAssertions; using Game; using Game.Geometry; using NUnit.Framework; namespace UnitTests { [TestFixture] public class FastCoord_Neighbor_Test { [OneTimeSetUp] public void SetUp() { FastCoord.Init(); } [TestCase(0)] [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] [TestCase(5)] public void InsideMap_ReturnsValidFastCoord(int orientation) { for (int x = 0; x < Constants.MAP_WIDTH; x++) for (int y = 0; y < Constants.MAP_HEIGHT; y++) { var coord = new Coord(x, y); var fastCoord = FastCoord.Create(coord); var neighbor = FastCoord.Neighbor(fastCoord, orientation); var actual = FastCoord.ToCoord(neighbor); actual.Should().Be(coord.Neighbor(orientation)); } } [TestCase(-1, -1, 0)] [TestCase(-1, -1, 5)] [TestCase(-1, -1, 4)] [TestCase(Constants.MAP_WIDTH, -1, 3)] [TestCase(Constants.MAP_WIDTH, -1, 4)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 2)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 3)] [TestCase(-1, Constants.MAP_HEIGHT, 0)] [TestCase(-1, Constants.MAP_HEIGHT, 1)] [TestCase(-1, Constants.MAP_HEIGHT, 2)] public void NearMap_GoIn_ReturnsValidFastCoord(int x, int y, int orientation) { var coord = new Coord(x, y); var fastCoord = FastCoord.Create(coord); var neighbor = FastCoord.Neighbor(fastCoord, orientation); var actual = FastCoord.ToCoord(neighbor); actual.Should().Be(coord.Neighbor(orientation)); } [TestCase(-1, -1, 1)] [TestCase(-1, -1, 2)] [TestCase(-1, -1, 3)] [TestCase(Constants.MAP_WIDTH, -1, 0)] [TestCase(Constants.MAP_WIDTH, -1, 1)] [TestCase(Constants.MAP_WIDTH, -1, 2)] [TestCase(Constants.MAP_WIDTH, -1, 5)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 0)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 1)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 4)] [TestCase(Constants.MAP_WIDTH, Constants.MAP_HEIGHT, 5)] [TestCase(-1, Constants.MAP_HEIGHT, 3)] [TestCase(-1, Constants.MAP_HEIGHT, 4)] [TestCase(-1, Constants.MAP_HEIGHT, 5)] public void NearMap_GoOut_ReturnsValidFastCoord(int x, int y, int orientation) { var coord = new Coord(x, y); var fastCoord = FastCoord.Create(coord); var neighbor = FastCoord.Neighbor(fastCoord, orientation); neighbor.Should().Be(-1); } } }
PHP
UTF-8
512
2.53125
3
[ "MIT" ]
permissive
<?php namespace verbb\cpnav\records; use craft\db\ActiveRecord; use yii\db\ActiveQueryInterface; class Layout extends ActiveRecord { // Public Static Methods // ========================================================================= public static function tableName(): string { return '{{%cpnav_layout}}'; } public function getNavigations(): ActiveQueryInterface { return $this->hasMany(Navigation::className(), ['navId' => 'id'])->inverseOf('layout'); } }
TypeScript
UTF-8
1,671
2.734375
3
[]
no_license
export class Database { private db: IDBDatabase; constructor() { this.db = null; } public init(dbName: string, version?: number): Promise<IDBDatabase> { return new Promise((resolve, reject) => { const iDb = window.indexedDB; const openRequest = iDb.open(dbName, version); openRequest.onupgradeneeded = () => { const database = openRequest.result; const store = database.createObjectStore(dbName, { keyPath: 'id', autoIncrement: true, }); store.createIndex('score', 'score'); this.db = database; resolve(this.db); }; openRequest.onsuccess = () => { this.db = openRequest.result; resolve(this.db); }; openRequest.onerror = () => { reject(this.db); }; }); } public write(collection: string, data: { [key: string]: unknown }): void { const transaction = this.db.transaction(collection, 'readwrite'); const store = transaction.objectStore(collection); const res = store.add({}); res.onsuccess = () => { const newRecord = { ...data, id: res.result }; const result = store.put(newRecord); return result; }; } public readAll(collection: string): Promise<{ [key: string]: unknown }[]> { return new Promise((resolve, reject) => { const transaction = this.db.transaction(collection, 'readonly'); const store = transaction.objectStore(collection); const result = store.getAll(); transaction.oncomplete = () => { resolve(result.result); }; transaction.onerror = () => { reject(result.error); }; }); } }
Python
UTF-8
2,326
3.5625
4
[]
no_license
from game_of_life import next_board_state from game_of_life import render """ TODO: there's a lot of repeated code here. Can you move some of into reusable functions to make it shorter and neater? """ def test(test_num, expected_next_state, actual_next_state): if expected_next_state == actual_next_state: print("PASSED", test_num) else: print("FAILED {}!".format(test_num)) print("Expected:") render(expected_next_state) print("Actual:") render(actual_next_state) if __name__ == "__main__": # TEST 1: dead cells with no live neighbors # should stay dead. init_state1 = [ [0,0,0], [0,0,0], [0,0,0] ] expected_next_state1 = [ [0,0,0], [0,0,0], [0,0,0] ] actual_next_state1 = next_board_state(init_state1) test("1", expected_next_state1, actual_next_state1) # TEST 2: dead cells with exactly 3 neighbors # should come alive. init_state2 = [ [0,0,1], [0,1,1], [0,0,0] ] expected_next_state2 = [ [0,1,1], [0,1,1], [0,0,0] ] actual_next_state2 = next_board_state(init_state2) test("2", expected_next_state2, actual_next_state2) # TEST 3: live cells wih more thn 3 live neighbors # should die init_state3 = [ [1,1,1], [0,1,1], [0,0,0] ] expected_next_state3 = [ [1,0,1], [0,0,1], [0,0,0] ] actual_next_state3 = next_board_state(init_state3) test("3", expected_next_state3, actual_next_state3) # TEST 4: cells on the edges of the board behave # as expected init_state4 = [ [1,1,1], [1,0,1], [1,1,1] ] expected_next_state4 = [ [1,0,1], [0,0,0], [1,0,1] ] actual_next_state4 = next_board_state(init_state4) test("4", expected_next_state4, actual_next_state4) # TEST 5: dead cells in corners should come alive # if neighbored by 3 live cells init_state5 = [ [0,1,0], [1,1,0], [0,0,0] ] expected_next_state5 = [ [1,1,0], [1,1,0], [0,0,0] ] actual_next_state5 = next_board_state(init_state5) test("5", expected_next_state5, actual_next_state5)
PHP
UTF-8
528
2.90625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; //para trabajar con un modelo lo incluimos use LaraDex\Role; class RoleTableSeeder extends Seeder { /** * creacion de un nuevo rol * le almaceno informacion por defecto a la BDD. */ public function run() { $role = new Role(); $role->name = "admin"; $role->description = "Administrador"; $role->save(); $role = new Role(); $role->name = "user"; $role->description = "User"; $role->save(); } }
Java
UTF-8
2,066
2.515625
3
[]
no_license
package com.payee.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import com.payee.domain.BankAccount; import com.payee.domain.User; import com.payee.utility.DBUtility; public class BankAccountService { private Connection connection; public BankAccountService() { connection = DBUtility.getConnection(); } public BankAccount addBankAccount(BankAccount bankAccount) { try { PreparedStatement preparedStatement = connection .prepareStatement("insert into bankAccount(country,bankName,accountNumber,bankCode,userId) values (?,?,?,?,? )"); // Parameters start with 1 //preparedStatement.setInt(1, user.getUserid()); int i=0; preparedStatement.setString(++i, bankAccount.getCountryName()); preparedStatement.setString(++i, bankAccount.getBankName()); preparedStatement.setString(++i, bankAccount.getAccountNumber()); preparedStatement.setString(++i, bankAccount.getBankCode()); //preparedStatement.setString(++i, bankAccount.getAccountName()); preparedStatement.setString(++i, bankAccount.getUserId()); preparedStatement.executeUpdate(); bankAccount.setValid(true); } catch (SQLException e) { e.printStackTrace(); } return bankAccount; } public BankAccount getBankAccountById(String userId) { BankAccount bankAccount = new BankAccount(); try { PreparedStatement preparedStatement = connection. prepareStatement("select * from bankAccount where userId = ?"); preparedStatement.setString(1, userId); ResultSet rs = preparedStatement.executeQuery(); if (rs.next()) { //user.setUserid(rs.getInt("userid")); bankAccount.setCountryName(rs.getString("country")); bankAccount.setBankName(rs.getString("bankName")); bankAccount.setAccountNumber(rs.getString("accountNumber")); } } catch (SQLException e) { e.printStackTrace(); } return bankAccount; } }
PHP
UTF-8
600
2.5625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use yii\db\ActiveRecord; class TokenModel extends ActiveRecord { public static function tableName() { return 'tokens'; } public function rules() { return [ [['user_id', 'token'], 'required'], [['user_id'], 'integer'], [['user_id'], 'unique'], [['expire_time'], 'safe'], [['token'], 'string', 'max' => 255], ]; } public function generateToken($time) { $this->time = $time; $this->token = \Yii::$app->security->generateRandomString(20); } }
C++
UTF-8
1,315
2.578125
3
[]
no_license
#include <LEDDisplay.h> LEDDisplay led; //Diese Include-Datei hat die Bitmaps und zwei Funktionen //Sie erwartet, dass es "led" gibt #include <wuerfel.h> void setup(void) { led.begin(); /* Default Mode of the LED display is "FIFO_DISPLAY" adding something to the display moves existing content to the left Here we set mode=FIXED_DISPLAY Using led.setCursor(pos) + led.add(...) overwrites content on a defined position. */ led.setConf(FIXED_DISPLAY, 160); } uint16_t pos = 0; uint8_t rot; uint8_t wert = 0; uint8_t schritt = 9; void loop(void) { if (led.int0_flag) { if (led.wokeupFromSleep()) { randomSeed(millis()); wert = 1; pos = 0; schritt = 9; led.clear(); } led.setSpeed(); if (wert) { led.setCursor(pos); led.clear(10); //move 8px to the right pos += schritt; led.setCursor(pos); if (pos < (160 - 24)) { if (rot % 4) { printWuerfelRollend(rot % 4); } else { led.setCursor(pos + 2); wert = random(1, 7); printWuerfel(wert); schritt--; } } else { if (wert) { printWuerfel(wert); wert = 0; } } rot++; } led.run(); } led.sleep(); }
Java
UTF-8
492
2.984375
3
[]
no_license
package com.gui.part02_layout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; public class GridLayoutTest extends JFrame{ public static void main(String[] args) { JFrame mf = new JFrame(); mf.setSize(600 , 400); mf.setLayout(new GridLayout(5 , 5)); for(int i=1; i<26; i++) { String str = new Integer(i).toString(); mf.add(new JButton(str)); } mf.setVisible(true); mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
Markdown
UTF-8
1,409
3.859375
4
[]
no_license
# Time_Travel_Search_Algorithms ## Project description The goal in this project is to use AI search algorithms in the 3D space to reach from an initial location to a target location with the optimal shortest path under some constratins. The constraints for every fixed z are as following: 1) the space is considered to be grid of points (x,y) such that the point (0,0) is the southwest corner of the grid and the agent can move to one of the eight neighboring grid locations, 2) there are some points in the space that let the agent to move bi-direcitally to the upper or lower layer, i.e., increase or decrease its z value. The program gets an input.txt file in which has the follwoing format, The first line shows which algorthim to use, A*, BFS, UCS. Second line consists of two integers showing the size of the grid, "W H". Third line shows the inital point in the format "z x y" where 0<= x <= W-1 and 0<= y <= H-1 . Forth line is the target location in the same format as inital point location. Fifth line is an inter N, indicationg the number of connecting channels among differetn layers in space. Next N line consisits of these channel in the format "z1 x y z2", which shows there is a bi-directioanl channel between layer z1 and z2 at point (x,y). The program will output a text file showing the moves agent needs to take, total number of steps the agent takes and the resuling total cost.