method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
2caaab70-4b0f-49a1-b10c-5d72d432f7a8 | 2 | public FunDecl lookupFunc(String name, int len) {
FunDecl funDecl = funDecls.get(name);
if(funDecl==null) {
if(parent!=null) {
return parent.lookupFunc(name, len);
}
else {
throw new RuntimeException("Function <" + name + "> undefined");
}
}
return funDecl;
} |
1a8a239f-e866-4f26-b567-8434381663e7 | 1 | @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
protected void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
btnNome = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
lblCpf = new javax.swing.JLabel();
lblRg = new javax.swing.JLabel();
lblData = new javax.swing.JLabel();
txtNome = new javax.swing.JTextField();
txtCpf = new javax.swing.JTextField();
txtRg = new javax.swing.JTextField();
txtDataNascimento = new javax.swing.JFormattedTextField();
jPanel2 = new javax.swing.JPanel();
lblRua = new javax.swing.JLabel();
lblBairro = new javax.swing.JLabel();
lblCep = new javax.swing.JLabel();
lblCidade = new javax.swing.JLabel();
txtRua = new javax.swing.JTextField();
txtBairro = new javax.swing.JTextField();
txtCep = new javax.swing.JTextField();
lblEstado = new javax.swing.JLabel();
lblNumeroEndereco = new javax.swing.JLabel();
txtNumeroEndereco = new javax.swing.JTextField();
txtCidade = new javax.swing.JTextField();
txtEstado = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
tblEndereco = new javax.swing.JTable();
btnAdicionarEndereco = new javax.swing.JButton();
btnRemoverEndereco = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
lblNumero = new javax.swing.JLabel();
lblDdd = new javax.swing.JLabel();
txtDdd = new javax.swing.JTextField();
txtNumeroTelefone = new javax.swing.JTextField();
btnAdicionarTelefone = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblTelefones = new javax.swing.JTable();
btnRemoverTelefone = new javax.swing.JButton();
jPanel4 = new javax.swing.JPanel();
lblEnderecoEmail = new javax.swing.JLabel();
txtEnderecoEmail = new javax.swing.JTextField();
btnAdicionarEmail = new javax.swing.JButton();
btnRemoverEmail = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
tblEmail = new javax.swing.JTable();
btnSalvar = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
setClosable(true);
setMaximizable(true);
setResizable(true);
setMinimumSize(new java.awt.Dimension(900, 600));
setName(""); // NOI18N
setPreferredSize(new java.awt.Dimension(900, 600));
btnNome.setText("Nome: ");
lblCpf.setText("CPF: ");
lblRg.setText("RG:");
lblData.setText("Data de Nascimento: ");
try {
txtDataNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txtDataNascimento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtDataNascimentoActionPerformed(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()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblData)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnNome)
.addGap(18, 18, 18)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 545, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(lblRg)
.addGap(18, 18, 18)
.addComponent(txtRg))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblCpf)
.addGap(18, 18, 18)
.addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(222, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(34, 34, 34)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnNome)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(50, 50, 50)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCpf)
.addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addGap(59, 59, 59)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblRg)
.addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(43, 43, 43)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblData)
.addComponent(txtDataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(126, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Dados Gerais", jPanel1);
lblRua.setText("Rua: ");
lblBairro.setText("Bairro");
lblCep.setText("Cep:");
lblCidade.setText("Cidade:");
lblEstado.setText("Estado:");
lblNumeroEndereco.setText("Nº:");
tblEndereco.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tblEndereco.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblEnderecoMouseClicked(evt);
}
});
jScrollPane2.setViewportView(tblEndereco);
btnAdicionarEndereco.setText("Adicionar");
btnAdicionarEndereco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarEnderecoActionPerformed(evt);
}
});
btnRemoverEndereco.setText("Remover");
btnRemoverEndereco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoverEnderecoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(lblRua)
.addGap(16, 16, 16)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(txtRua, javax.swing.GroupLayout.PREFERRED_SIZE, 455, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lblNumeroEndereco)
.addGap(18, 18, 18)
.addComponent(txtNumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(327, 327, 327)
.addComponent(lblCep))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtCidade, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtBairro, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 261, Short.MAX_VALUE))
.addGap(66, 66, 66)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCep, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(lblEstado)
.addGap(18, 18, 18)
.addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addComponent(lblBairro)
.addComponent(lblCidade)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 667, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnAdicionarEndereco)
.addComponent(btnRemoverEndereco))))
.addContainerGap(75, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblRua)
.addComponent(lblNumeroEndereco)
.addComponent(txtNumeroEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblBairro)
.addComponent(txtBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblCep)
.addComponent(txtCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCidade)
.addComponent(txtCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblEstado)
.addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addComponent(btnAdicionarEndereco)
.addGap(29, 29, 29)
.addComponent(btnRemoverEndereco)))
.addContainerGap(36, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Endereço", jPanel2);
lblNumero.setText("Numero:");
lblDdd.setText("DDD:");
btnAdicionarTelefone.setText("Adicionar");
btnAdicionarTelefone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarTelefoneActionPerformed(evt);
}
});
tblTelefones.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tblTelefones.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblTelefonesMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tblTelefones);
btnRemoverTelefone.setText("Remover");
btnRemoverTelefone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoverTelefoneActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 719, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(lblDdd)
.addGap(31, 31, 31)
.addComponent(txtDdd, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(lblNumero)
.addGap(18, 18, 18)
.addComponent(txtNumeroTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(69, 69, 69)
.addComponent(btnAdicionarTelefone)
.addGap(18, 18, 18)
.addComponent(btnRemoverTelefone)))
.addContainerGap(114, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblDdd)
.addComponent(txtDdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblNumero)
.addComponent(txtNumeroTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdicionarTelefone)
.addComponent(btnRemoverTelefone))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(57, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Telefone", jPanel3);
lblEnderecoEmail.setText("Endereço:");
btnAdicionarEmail.setText("Adicionar");
btnAdicionarEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAdicionarEmailActionPerformed(evt);
}
});
btnRemoverEmail.setText("Remover");
btnRemoverEmail.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRemoverEmailActionPerformed(evt);
}
});
tblEmail.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
tblEmail.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tblEmailMouseClicked(evt);
}
});
jScrollPane3.setViewportView(tblEmail);
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 758, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(lblEnderecoEmail)
.addGap(18, 18, 18)
.addComponent(txtEnderecoEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(56, 56, 56)
.addComponent(btnAdicionarEmail)
.addGap(38, 38, 38)
.addComponent(btnRemoverEmail)))
.addContainerGap(75, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblEnderecoEmail)
.addComponent(txtEnderecoEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAdicionarEmail)
.addComponent(btnRemoverEmail))
.addGap(37, 37, 37)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Email", jPanel4);
btnSalvar.setText("Salvar");
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnCancelar.setText("Cancelar");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
btnSair.setText("Sair");
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(143, 143, 143)
.addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(65, 65, 65)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(81, 81, 81)
.addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 466, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSalvar)
.addComponent(btnCancelar)
.addComponent(btnSair))
.addContainerGap(34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents |
b71bcb8f-472e-4076-9420-0bb7ca98c698 | 4 | public static Object load(String nom, String version) {
// Controler la validité des paramètres
//
if (nom == null || version == null) {
// Indiquer l'erreur
//
System.err.println("ConfigXML : Param�tre null !");
return false;
}
// Construire le nom de fichier a utiliser
//
String nomCompletFichier = dossier + nom + "-" + version + ".xml";
// Créer le fichier logique
//
File fichier = new File(nomCompletFichier);
// Créer un écrivain
//
FileReader lecteur;
try {
lecteur = new FileReader(fichier);
} catch (Exception e) {
System.err
.println("ConfigXML : erreur a la creation du lecteur !");
return null;
}
// Enregistrer le XML
//
Object objet = xstream.fromXML(lecteur);
// Fermer le flux
//
try {
lecteur.close();
} catch (Exception e) {
System.err
.println("ConfigXML : erreur a la fermeture du lecteur !");
return null;
}
// Afficher un message
//
System.out.println("ConfigXML : Chargement du fichier "
+ nomCompletFichier + " OK");
return objet;
} |
8cc55343-17c5-4746-9eba-51f586658c81 | 4 | public double standardizedPersonStandardDeviation(int index){
if(!this.dataPreprocessed)this.preprocessData();
if(index<1 || index>this.nPersons)throw new IllegalArgumentException("The person index, " + index + ", must lie between 1 and the number of persons," + this.nPersons + ", inclusive");
if(!this.variancesCalculated)this.meansAndVariances();
return this.standardizedPersonStandardDeviations[index-1];
} |
8157bf16-d72f-479f-89a9-532859af1163 | 0 | public FrameDesc() {
pageNo = new PageId();
pageNo.pid = INVALID_PAGE;
dirty = false;
pin_cnt = 0;
} // end constructor |
4f2f8f89-85db-4336-b2d3-0bfbef0cff76 | 9 | public int[] OrdenSeleccion(int arreglo[], String ordenamiento) {
int indice = 0, indice2 = 0, menor = 0, posicion = 0, temporal = 0;
if (ordenamiento.equals(arreglo)) {
for (indice = 0; indice < arreglo.length; indice++) {
menor = arreglo[indice];
posicion = indice;
for (indice2 = indice + 1; indice2 < arreglo.length; indice2++) {
if (arreglo[indice2] < menor) {
menor = arreglo[indice2];
posicion = indice2;
}
}
if (posicion != indice) {
temporal = arreglo[indice];
arreglo[indice] = arreglo[posicion];
arreglo[posicion] = temporal;
}
}
} else {
for (indice = 0; indice < arreglo.length; indice++) {
menor = arreglo[indice];
posicion = indice;
for (indice2 = indice + 1; indice2 > arreglo.length; indice2++) {
if (arreglo[indice2] > menor) {
menor = arreglo[indice2];
posicion = indice2;
}
}
if (posicion != indice) {
temporal = arreglo[indice];
arreglo[indice] = arreglo[posicion];
arreglo[posicion] = temporal;
}
}
}
return arreglo;
} |
f2749cfd-4a88-4320-a2b7-f34086108168 | 4 | public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: java " + RandomProjectionsAccuracy.class.getCanonicalName() + " train_file test_file");
System.exit(1);
}
String trainFile = args[0];
String testFile = args[1];
Pipe<String, DataFrame<MultiClassLabel>> exactPipe = new Pipe<String, Iterable<String>>(new FileProcessor(true))
.add(new DataProcessor(1000, 10))
.add(new DataFrameProcessorDecorator<MultiClassLabel>(new TFIDF(3)));
DataFrame<MultiClassLabel> trainExact = exactPipe.train(trainFile);
DataFrame<MultiClassLabel> testExact = exactPipe.process(testFile);
for(int proj = 3; proj < 10000; proj += proj) {
ParallelPipe<DataFrame<MultiClassLabel>, DataFrame<MultiClassLabel>> rpPipe = new ParallelPipe<DataFrame<MultiClassLabel>, DataFrame<MultiClassLabel>>(4, new ParallelDataFrameProcessorDecorator<MultiClassLabel>(new VerySparseRandomProjections(proj, 10)));
rpPipe.getContext().getProgressReporter().disable();
DataFrame<MultiClassLabel> trainRP = rpPipe.train(trainExact);
DataFrame<MultiClassLabel> testRP = rpPipe.process(testExact);
rpPipe.close();
double rmse = 0;
double mean = 0;
for(int r = 0; r<testExact.getRows(); r++) {
Vector exact = testExact.getData(r);
Vector rp = testRP.getData(r);
for(int i=0; i<trainExact.getRows(); i++) {
double ex = VectorUtils.cosineSimilarity(trainExact.getData(i), exact);
double es = VectorUtils.cosineSimilarity((BitVector)trainRP.getData(i), (BitVector)rp);
rmse += (es-ex)*(es-ex);
mean += es-ex;
}
}
rmse = Math.sqrt(rmse);
System.out.println(proj + "," + StringFormat.format(rmse) + "," + StringFormat.format(mean));
}
} |
82a7c020-8b72-4e26-9ae5-9625dc6d2661 | 1 | public int getFuelTimer() {
if(isFuel())
return fuelTimer;
else
return -1;
} |
41ab3aaa-c828-48de-abb1-6d7dcf567df6 | 5 | private void cargar_Campos (int valor){
try{
this.vaciarCampos();
r_con.Connection();
PreparedStatement pstm = r_con.getConn().prepareStatement(
"SELECT *"+
" FROM "+name_tabla+
" WHERE prod_codigo = "+valor);
ResultSet res = pstm.executeQuery();
String imp_porc;
String imp_fij;
while(res.next()){
field_codigo.setText(res.getString(1));
field_descripcion.setText(res.getString(2));
field_cantidad.setText(res.getString(3));
field_costo_u.setText(res.getString(4));
field_precio_venta.setText(res.getString(5));
field_tasa_iva.setText(res.getString(6));
imp_porc = res.getString(7);
imp_fij = res.getString(8);
if((imp_porc.equals("0.0")) && (imp_fij.equals("0.0"))){
field_impuesto.setText("");
combo_tipo_imp.setSelectedIndex(0);
lab_tipo_imp.setText(" ");
}
else{
if(imp_porc.equals("0.0")){
field_impuesto.setText(imp_fij);
combo_tipo_imp.setSelectedIndex(2);
lab_tipo_imp.setText("($)");
}
else{
field_impuesto.setText(imp_porc);
combo_tipo_imp.setSelectedIndex(1);
lab_tipo_imp.setText("(%)");
}
}
}
res.close();
} catch(SQLException e){
System.out.println(e);
} finally {
r_con.cierraConexion();
}
} |
8669a59f-5ea6-4af3-9019-ee98891f0dbe | 8 | private void chosePotions() {
if (Bank.getItem(RSC.EXTREME_RANGING_FLASK_IDS[5]) != null) {
potionId = RSC.EXTREME_RANGING_FLASK_IDS[5];
} else if (Bank.getItem(RSC.EXTREME_RANGING_POTION_IDS[3]) != null) {
potionId = RSC.EXTREME_RANGING_POTION_IDS[3];
} else if (Bank.getItem(RSC.RANGING_FLASK_IDS[5]) != null) {
potionId = RSC.RANGING_FLASK_IDS[5];
} else if (Bank.getItem(RSC.RANGING_POTION_IDS[3]) != null) {
potionId = RSC.RANGING_POTION_IDS[3];
} else {
potionId = -1;
}
if (Bank.getItem(RSC.ANTI_POISON_PP_IDS) != null) {
antiPoisonId = RSC.ANTI_POISON_PP_IDS[3];
} else if (Bank.getItem(RSC.ANTI_POISON_P_IDS[3]) != null) {
antiPoisonId = RSC.ANTI_POISON_P_IDS[3];
} else if (Bank.getItem(RSC.SUPER_ANTI_POISON_IDS[3]) != null) {
antiPoisonId = RSC.SUPER_ANTI_POISON_IDS[3];
} else if (Bank.getItem(RSC.ANTI_POISON_IDS[3]) != null) {
antiPoisonId = RSC.ANTI_POISON_IDS[3];
} else {
antiPoisonId = -1;
}
} |
5c12bd68-e828-49c3-8911-18129ea399cb | 6 | public double getAngle(double a,double b,double c, double d){
if((a>=c&&b>=d)||(a>=c&&b<=d))
return Math.asin((b-d)/
Math.sqrt(Math.pow((a-c),2)+
Math.pow((b-d), 2)));
else if(a<c&&b>=d)
return Math.toRadians(90.0)+Math.acos((b-d)/
Math.sqrt(Math.pow((a-c),2)+
Math.pow((b-d), 2)));
else return -Math.toRadians(90.0)+Math.asin((a-c)/
Math.sqrt(Math.pow((a-c),2)+
Math.pow((b-d), 2)));
} |
fdbf9526-29c4-4507-97fd-55280f48fc61 | 6 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection c = null;
Statement stmt = null;
String sql;
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String ID = request.getParameter("id");
int intId = Integer.parseInt(ID);
System.out.println(intId);
String rating = request.getParameter("rating");
String actors ="";
for(int l=0;l<5;l++){
String m = "a"+(l+1);
String actor = request.getParameter(m);
if(actor!=null && actor!="" && !actor.isEmpty() ){
actor = actor+", ";
actors = actors + actor;
}
}
if(actors.endsWith( ", " )){
actors = actors.substring(0, actors.length()-2);
}
System.out.println(actors);
try {
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/test1","akash", "akash131");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
sql = "UPDATE MOVIES set RATING = "+
rating+
", ACTORS = '"+
actors+
"' where ID = "+
intId+
";";
stmt.executeUpdate(sql);
c.commit();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records updated successfully");
String site = "list.jsp" ;
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
} |
e2acd74b-a183-471c-b906-a648d196a2df | 9 | public SetupFrame() {
super("Atoms Setup");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
setLayout(new GridLayout(0, 4));
for (final Field fld : AtomSetup.class.getDeclaredFields()) {
add(new JLabel(fld.getName()));
if (fld.getType() == AtomSetup.Packing.class) {
final JComboBox cb = new JComboBox(AtomSetup.Packing.values());
cb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
fld.set(setup, cb.getSelectedItem());
} catch (Exception e) {
e.printStackTrace();
}
}
});
add(cb);
} else {
final JTextField tf = new JTextField("" + fld.get(setup));
tf.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { update(); }
public void removeUpdate(DocumentEvent e) { update(); }
public void changedUpdate(DocumentEvent e) { update(); }
void update() {
if ((fld.getType() + "").equals("double")) {
try {
fld.set(setup, Double.parseDouble(tf.getText()));
} catch (Exception e) {
//e.printStackTrace();
}
} else {
if ((fld.getType() + "").contains("String")) {
try {
fld.set(setup, tf.getText());
} catch (Exception e) {
//e.printStackTrace();
}
} else {
try {
fld.set(setup, Integer.parseInt(tf.getText()));
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}
});
add(tf);
}
}
} catch (Exception e) {
e.printStackTrace();
}
setSize(500, 600);
JButton startB = new JButton("Start");
startB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new AtomFrame(setup);
}
});
add(startB);
setVisible(true);
} |
a5565349-55b0-4e02-87ba-0bce5f342584 | 7 | private synchronized void doFileTransfer() throws IOException {
try {
int lengthOfSenderName = dis.readInt(); //II
byte[] senderNameB = new byte[lengthOfSenderName];
dis.read(senderNameB); //III
String sender = new String(senderNameB);
int lengthOfFileName = dis.readInt(); //IV
byte[] fileNameB = new byte[lengthOfFileName];
dis.read(fileNameB); //V
String fileName = new String(fileNameB);
int option = JOptionPane.showConfirmDialog(null,sender + " wants to transfer file " + fileName,"FileTransferRequest",JOptionPane.YES_NO_OPTION);
if(option != JOptionPane.YES_OPTION) {
throw new AboardByUserException();
} else {
dos.writeInt(Constants.FILE_TRANSFER_START);
}
File f = null;
do {
String filePath = JOptionPane.showInputDialog(null, "please state path to save file to");
try {
f = new File(filePath);
} catch(Exception e) {
JOptionPane.showMessageDialog(null,"FileTransferCancel:" + e.getMessage());
continue;
}
if(f == null) {
JOptionPane.showMessageDialog(null,"unable to open/create specified file");
}
} while (f == null);
DebugPrint.print("receiving file");
int fileSize = dis.readInt(); //VI
DebugPrint.print("the file to be received is size " + fileSize);
byte[] file = new byte[fileSize];
DebugPrint.print("file receviced");
for(int i = 0; i != fileSize;++i) {
file[i] = dis.readByte();
}
//dis.read(file);
FileOutputStream fos = new FileOutputStream(f);
fos.write(file);
dos.writeInt(Constants.FILE_TRANSFER_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
dos.writeInt(Constants.FILE_TRANSFER_ABOARD);
JOptionPane.showMessageDialog(null,"FileTransferCancel:" + e.getMessage());
} catch (AboardByUserException e) {
e.printStackTrace();
dos.writeInt(Constants.FILE_TRANSFER_ABOARD);
return;
}
} |
c7bdaff9-d5b2-4cc0-abcb-a3d6b13c4fb4 | 9 | public static String getSpellByAscii(int ascii) {
if (ascii > 0 && ascii < 160) { // 单字符
return String.valueOf((char) ascii);
}
if (ascii < -20319 || ascii > -10247) { // 不知道的字符
return "";
}
String spell = null; //key
Integer asciiRang; //value
String spellPrevious = null; //用来保存上次轮循环的key
int asciiRangPrevious = -20319; //用来保存上一次循环的value
for (Iterator<String> it = spellMap.keySet().iterator(); it.hasNext();) {
spell = it.next(); //拼音
asciiRang = spellMap.get(spell); //拼音的ASCII
if(asciiRang != null){
if (ascii >= asciiRangPrevious && ascii < asciiRang) { // 区间找到, 返回对应的拼音
return (spellPrevious == null) ? spell : spellPrevious;
} else {
spellPrevious = spell;
asciiRangPrevious = asciiRang;
}
}
}
return "";
} |
ec89fb52-a19a-4f14-a82f-1e2e167adfff | 2 | public BencodeTreeModel ( Value<?> root ) {
this.root = root == null ? null : new BencodeTreeNode( root, null, null );
System.out.println( root );
} |
7df1d8d1-3d4e-4f78-b1fb-259e8ac96680 | 4 | @Override
public boolean init(List<String> argumentList, DebuggerVirtualMachine dvm) {
functionLines = new LinkedHashMap<String, Boolean>();
if (argumentList.size() > 0) {
UserInterface.println("This command takes no arguments.");
HelpCommand.displayHelp(this);
return false;
}
functionName = dvm.getFunctionName();
startLineNumber = dvm.getFunctionStartLine();
int endLineNumber = dvm.getFunctionEndLine();
currentLineNumber = dvm.getCurrentLine();
if (currentLineNumber == -1) {
return true;
}
if (startLineNumber == -2) {
functionName = "none";
startLineNumber = 1;
endLineNumber = dvm.getSourceLinesSize() - 1;
}
for (int i = startLineNumber; i <= endLineNumber; i++) {
functionLines.put(dvm.getSourceLine(i), dvm.isBreakpointSet(i));
}
return true;
} |
e9003199-788a-42fb-97de-60d6f34a877d | 5 | public void draw(Graphics2D g)
{
for (int r = rowOffset; r < numberOfRowsToDraw + rowOffset; r++)
{
if (r >= numberOfRows) // Stop drawing if we run out of rows to draw
break;
for (int c = colOffset; c < numberOfColsToDraw + colOffset; c++)
{
if (c >= numberOfCols) // Stop drawing if we run out of cols
break;
if (tileMap[r][c] == null) // We don't need to draw empty space
continue;
g.drawImage(tileMap[r][c].getImage(), (int) x + (c * tileSize), (int) y + (r * tileSize), tileSize, tileSize, null);
}
}
} |
aa9f678a-7913-4ed2-908f-1b1da45820c0 | 1 | public final JSONObject getJSONObject(int index) throws JSONException {
Object o = get(index);
if (o instanceof JSONObject) {
return (JSONObject)o;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
} |
fc573aa0-07df-4f70-855b-9cc664aac2e0 | 0 | public EncryptedKeyType createEncryptedKeyType() {
return new EncryptedKeyType();
} |
f0002f2f-70f8-4006-8420-11b70e938911 | 5 | @Override
public boolean equals(Object obj) {
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
if (this == obj) {
return true;
}
if (obj.getClass() == this.getClass()) {
Wesen w = (Wesen) obj;// typecast Object zu
// Festkommazahl
if (this.lebenspunkte == w.lebenspunkte) {
return true;
}
}
return false;
} |
6b52768c-99e6-4203-90de-bd2901c50449 | 2 | public static void downloadBlob(String blobUri) {
String filePath = Connection.filePath;
try {
CloudStorageAccount storageAccount = CloudStorageAccount
.parse(Connection.storageConnectionString);
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
CloudBlobContainer container = blobClient
.getContainerReference(containerName);
CloudBlob blob = container.getBlockBlobReference(blobUri);
blob.downloadAttributes();
File yourFile = new File(filePath + blob.getName());
if (!yourFile.exists()) {
yourFile.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(blob.getName());
blob.download(fos);
fos.close();
} catch (URISyntaxException | InvalidKeyException | StorageException
| IOException ex) {
Logger.getLogger(BlobManager.class.getName()).log(Level.SEVERE,
null, ex);
}
} |
67a7bc20-731c-426f-9172-75b3d56a24dd | 9 | public void start(StreamLoader streamLoader, client client1)
{
String as[] = {
"model_version", "anim_version", "midi_version", "map_version"
};
for(int i = 0; i < 4; i++)
{
byte abyte0[] = streamLoader.getDataForName(as[i]);
int j = abyte0.length / 2;
Stream stream = new Stream(abyte0);
versions[i] = new int[j];
fileStatus[i] = new byte[j];
for(int l = 0; l < j; l++)
versions[i][l] = stream.readUnsignedWord();
}
String as1[] = {
"model_crc", "anim_crc", "midi_crc", "map_crc"
};
for(int k = 0; k < 4; k++)
{
byte abyte1[] = streamLoader.getDataForName(as1[k]);
int i1 = abyte1.length / 4;
Stream stream_1 = new Stream(abyte1);
crcs[k] = new int[i1];
for(int l1 = 0; l1 < i1; l1++)
crcs[k][l1] = stream_1.readDWord();
}
byte abyte2[] = streamLoader.getDataForName("model_index");
int j1 = versions[0].length;
modelIndices = new byte[j1];
for(int k1 = 0; k1 < j1; k1++)
if(k1 < abyte2.length)
modelIndices[k1] = abyte2[k1];
else
modelIndices[k1] = 0;
abyte2 = streamLoader.getDataForName("map_index");
Stream stream2 = new Stream(abyte2);
j1 = abyte2.length / 7;
mapIndices1 = new int[j1];
mapIndices2 = new int[j1];
mapIndices3 = new int[j1];
mapIndices4 = new int[j1];
for(int i2 = 0; i2 < j1; i2++)
{
mapIndices1[i2] = stream2.readUnsignedWord();
mapIndices2[i2] = stream2.readUnsignedWord();
mapIndices3[i2] = stream2.readUnsignedWord();
mapIndices4[i2] = stream2.readUnsignedByte();
}
abyte2 = streamLoader.getDataForName("anim_index");
stream2 = new Stream(abyte2);
j1 = abyte2.length / 2;
anIntArray1360 = new int[j1];
for(int j2 = 0; j2 < j1; j2++)
anIntArray1360[j2] = stream2.readUnsignedWord();
abyte2 = streamLoader.getDataForName("midi_index");
stream2 = new Stream(abyte2);
j1 = abyte2.length;
anIntArray1348 = new int[j1];
for(int k2 = 0; k2 < j1; k2++)
anIntArray1348[k2] = stream2.readUnsignedByte();
clientInstance = client1;
running = true;
clientInstance.startRunnable(this, 2);
} |
ae3b8d73-0c0e-402e-a2ed-05dcb2b55fa1 | 8 | private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
// TODO add your handling code here:
jList1.updateUI();
if (jList1.getSelectedIndex()>=0) {
Field f = Game.fields.get(fieldsR.get(jList1.getSelectedIndex()));
if (f.getClass()==Brewery.class) {
Brewery brew = ((Brewery)f);
if (brew.Mortgage) {
brew.Mortgage=false;
Game.players.get(brew.Owner).ChangeMoney(-(brew.Price/2));
}else{
brew.Mortgage=true;
Game.players.get(brew.Owner).ChangeMoney((brew.Price/2));
}
}else if (f.getClass()==Street.class) {
Street street = ((Street)f);
if (street.Mortgage) {
street.Mortgage=false;
Game.players.get(street.Owner).ChangeMoney(-(street.Price/2));
}else{
if (street.Houses==0) {
street.Mortgage=true;
Game.players.get(street.Owner).ChangeMoney((street.Price/2));
}else{
JOptionPane.showMessageDialog(rootPane, "Du kan ikke pantsætte en gade med huse");
}
}
}else if (f.getClass()==ShippingLines.class) {
ShippingLines sl = ((ShippingLines)f);
if (sl.Mortgage) {
sl.Mortgage=false;
Game.players.get(sl.Owner).ChangeMoney(-(sl.Price/2));
}else{
sl.Mortgage=true;
Game.players.get(sl.Owner).ChangeMoney((sl.Price/2));
}
}
Game.gameboard.refreshGameControl();
this.dispose();
}
}//GEN-LAST:event_jButton1MouseClicked |
8ca921e0-b720-4d57-879f-2916510bc45e | 2 | public int compareClock(Clock otherClock) {
LogicClock otherLocalClock = (LogicClock)otherClock;
// thisClock < otherClock
if (this.clock < otherLocalClock.clock)
return -1;
// thisClock > otherClock
if (this.clock > otherLocalClock.clock)
return 1;
// thisClock = otherClock
return 0;
} |
7fcec595-644c-48ea-bd92-270a807f07c3 | 1 | public boolean isExpired(SkiPass sp) {
Date currentDate = new Date(System.currentTimeMillis());
return (currentDate.before(sp.getExpirationDate()) ? false : true);
} |
0358af00-d28a-47b0-865e-5c794fadb5a1 | 5 | private static FileHandler getFileHandler(boolean devLog) throws IOException {
FileHandler handler = null;
Formatter formatter = null;
String suffix = "";
switch (commandLineOptions.getLogFormat()) {
case HTML:
if(devLog) {
formatter = new HTMLFormatter(false);
suffix = "-dev.html";
} else {
formatter = new HTMLFormatter(true);
suffix = "-sim.html";
}
break;
case XML:
formatter = new XMLFormatter();
if(devLog) {
suffix = "-dev.xml";
} else {
suffix = "-sim.xml";
}
break;
default:
if(devLog) {
formatter = new DevLogFormatter();
suffix = "-dev.log";
} else {
formatter = new SimLogFormatter();
suffix = "-sim.log";
}
break;
}
handler = new FileHandler("log/" + getFileName()
+ suffix);
handler.setFormatter(formatter);
return handler;
} |
e30bebdd-67af-4604-ac98-2b2f2b75e15b | 0 | @Override
public void setReceiveMessage(IReceiveMessage receiveMessage) {
this.receiveMessage = receiveMessage;
} |
b3cf7a53-6f89-45ae-b203-0f567a1afd7f | 1 | public CheckCreditForm(int clientId) {
//Fix clients id
this.clientId = clientId;
initComponents();
locateForm();
//Load to table all credita or credits for concrete user
if (clientId != 0) {
creditDAO.initTableModel(creditTable, creditDAO.getCreditsByClientsId(clientId));
} else {
creditDAO.initTableModel(creditTable, creditDAO.listAll());
}
//Set the context menu to table
setPopupMenu(creditTable);
} |
49e52c61-98da-4c75-a148-fceefc24267c | 5 | public void writeErrorReport(String folder) {
File dir = new File(folder);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(dir.getAbsoluteFile()+"\\readingErrors.txt");
if (file.exists()) {
file.delete();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(errorReport.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
a55c69cc-9287-416a-9125-ea80bbcd2bcf | 0 | public void setUsed(Boolean used) {
this.used = used;
} |
1b1833fe-1d32-43f8-a132-dbab99448586 | 6 | public Brick(int xPos, int yPos, int width, int height, int hp, boolean powerUpsEnabled, int difficulty) {
this.xPos = xPos;
this.yPos = yPos;
this.width = width;
this.height = height;
this.hp = hp;
this.powerUp = new PowerUp(powerUpsEnabled, difficulty);
switch(hp) {
case -1: this.color = Color.gray; break;
case 0: this.color = Color.black; break;
case 1: this.color = Color.yellow; break;
case 2: this.color = Color.orange; break;
case 3: this.color = Color.blue; break;
case 4: this.color = Color.red; break;
}
} |
a8dff4b2-10c8-49de-99b6-bf6e88cf6479 | 4 | public static void main(String[] args){
routes[0][0]=1;
for (int i=0;i<21;i++){
for (int j=0;j<21;j++){
if (i==0 && j==0) continue;
routes[i][j] = sumOfPred(i, j);
}
}
System.out.println(routes[20][20]);
} |
770cef71-fc9d-4637-81ee-018a2fd84e7b | 1 | private void queueFile(int n) {
int index = mp3list.getIndex();
if (index >= 0) {
FramePanel fp = (FramePanel) tabbedPane.getComponent(n);
fp.getCon().add(mp3list.get(index), fp.getSearchPanel());
fp.getMp3List().update();
}
} |
1995d5ca-508a-4407-8c5e-5684b06b6dc7 | 7 | public static String getData(){
ObjectMapper mapper = new ObjectMapper();
List<Player> playersObj = new ArrayList<Player>();
for (Player player : plugin.getServer().getOnlinePlayers()) {
playersObj.add(player);
}
Map<String,Object> servers = new HashMap<String,Object>();
Map<String,Object> data = new HashMap<String,Object>();
Map<String,Object> playersList = new HashMap<String,Object>();
for (Player plr : playersObj){
Map<String,String> player = new HashMap<String,String>();
//Player's IP Address
player.put("ADDRESS", Encryption.encryptString(plr.getAddress().toString()));
//Player UUID. New in Minecraft v1.7
player.put("UUID", Encryption.encryptString(plr.getUniqueId().toString()));
//Player's XP Level
player.put("XPLEVELS", Encryption.encryptString(String.valueOf(plr.getLevel())));
//How long the player has been playing this login session.
long plrSessionTime = 0;
plrSessionTime = System.currentTimeMillis() - Minetrends.playerJoins.get(plr.getName());
player.put("sessionTime", Encryption.encryptString((plrSessionTime / 1000) + ""));
//Player's Minecraft Language
player.put("appLanguage", Encryption.encryptString(getLanguage(plr)));
//Add to the main data array
playersList.put(Encryption.encryptString(plr.getName()), player);
}
data.put("players", playersList);
data.put("BUKKITVERSION", Encryption.encryptString(plugin.getServer().getBukkitVersion().toString()));
data.put("TIMEZONE", Encryption.encryptString(TimeZone.getDefault().getDisplayName()));
data.put("TIMEZONEID", Encryption.encryptString(TimeZone.getDefault().getID()));
data.put("TIMELOCAL", Encryption.encryptString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())));
//Memory Usage
data.put("memoryFree", "" + Encryption.encryptString(Runtime.getRuntime().freeMemory() + ""));
data.put("memoryTotal", "" + Encryption.encryptString(Runtime.getRuntime().totalMemory() + ""));
data.put("memoryMax", Encryption.encryptString(Runtime.getRuntime().maxMemory() + ""));
//Java Virtual Machine Uptime
long JVMStartTime = ManagementFactory.getRuntimeMXBean().getStartTime();
long currentTime = new Date().getTime();
long upTime = (currentTime - JVMStartTime) / 1000;
data.put("uptime", "" + Encryption.encryptString(upTime + ""));
//Total Number of Entities
int totalEntities = 0;
for (World world : Bukkit.getWorlds()) {
totalEntities = totalEntities + world.getEntities().size();
}
data.put("totalEntities", Encryption.encryptString(totalEntities + ""));
//TPS Monitor
data.put("TPS", Encryption.encryptString(new DecimalFormat("#.####").format(TPSChecker.getTPS()) + ""));
//Diskspace Usage
File hd = new File("/");
data.put("diskspaceFree", Encryption.encryptString(hd.getUsableSpace() + ""));
data.put("diskspaceTotal", Encryption.encryptString(hd.getTotalSpace() + ""));
//Installed plugin version.
data.put("pluginVersion", plugin.getDescription().getVersion());
if (Minetrends.privateKey == null){
data.put("secure", false);
} else {
data.put("secure", true);
}
servers.put(Minetrends.publicKey, data);
try {
//String result = mapper.writeValueAsString(data);
String result = mapper.writeValueAsString(servers);
return result;
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} |
f9d4cff1-b9f8-4ac6-9902-dd0bf0d0853f | 1 | private static JLabel getLabel(String string) {
JLabel label = new JLabel(string);
if (IMAGE != null)
label.setForeground(Color.black);
return label;
} |
369d6ebc-baf0-4ace-bcfc-cfeed3f517dc | 2 | private void DisplayLCS(int[][] b, char[] x, int max, int mIndex) {
if (max == 0)
System.out.println("no LCSubstring");
System.out.println("-----max: " + max);
System.out.println("-----maxIndex: " + mIndex);
int i = mIndex;
while (max > 0) {
System.out.print(x[i++]);
max--;
}
System.out.println();
} |
ce10512e-4f95-4f13-a597-c2c24b4cf9c8 | 8 | protected void createDefaultConfiguration(String name) {
File actual = new File(getDataFolder(), name);
if (!actual.exists()) {
InputStream input =
this.getClass().getResourceAsStream("/" + name);
if (input != null) {
FileOutputStream output = null;
try {
output = new FileOutputStream(actual);
byte[] buf = new byte[8192];
int length = 0;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
System.out.println(getDescription().getName()
+ ": Default configuration file written: " + name);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {}
try {
if (output != null)
output.close();
} catch (IOException e) {}
}
}
}
} |
31767173-24e4-4ba8-bc88-748afe6a7190 | 8 | public void setFieldValue(_Fields field, Object value) {
switch (field) {
case FIRST_NAME:
if (value == null) {
unsetFirstName();
} else {
setFirstName((String)value);
}
break;
case LAST_NAME:
if (value == null) {
unsetLastName();
} else {
setLastName((String)value);
}
break;
case STATUS:
if (value == null) {
unsetStatus();
} else {
setStatus((Status)value);
}
break;
case ID:
if (value == null) {
unsetId();
} else {
setId((Integer)value);
}
break;
}
} |
4ae98a89-1774-46a6-9113-ca7a015fa9ba | 6 | public void run() {
ajpacket msg = null;
try {
while (run) {
msg = (ajpacket) in.readObject(); // recieve messages
if (cdata != null) {
cdata.recv(this, msg);
}
}
} catch (IOException e) {
if (run) {
System.err.println("ajclient: connection error");
this.close();
}
} catch (ClassNotFoundException e) {
if (run) {
System.err.println("ajclient: message save error");
}
}
this.close();
} |
35548930-f9df-468a-96bf-45bfe8a7d007 | 1 | public static String SQLdecrypted (String decrypt) {
String decrypted = "";
try {
// Encryption used DES. We can also use AES
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(secretSalt.getBytes());
SecretKey key = keyFactory.generateSecret(keySpec);
// Create encrypter/decrypter class
DesEncrypter encrypter = new DesEncrypter(key);
// Decrypt
decrypted = encrypter.decrypt(decrypt);
} catch (Exception e) {
Error_Frame.Error(e.toString());
}
return decrypted;
} |
975e06e5-8f16-4949-8ce1-6bde7f2f8148 | 9 | public void func_40381_b(int par1, int par2, byte[] par3ArrayOfByte, BiomeGenBase[] par4ArrayOfBiomeGenBase)
{
for (int var5 = 0; var5 < 16; ++var5)
{
for (int var6 = 0; var6 < 16; ++var6)
{
byte var7 = 1;
int var8 = -1;
byte var9 = (byte)Block.whiteStone.blockID;
byte var10 = (byte)Block.whiteStone.blockID;
for (int var11 = 127; var11 >= 0; --var11)
{
int var12 = (var6 * 16 + var5) * 128 + var11;
byte var13 = par3ArrayOfByte[var12];
if (var13 == 0)
{
var8 = -1;
}
else if (var13 == Block.stone.blockID)
{
if (var8 == -1)
{
if (var7 <= 0)
{
var9 = 0;
var10 = (byte)Block.whiteStone.blockID;
}
var8 = var7;
if (var11 >= 0)
{
par3ArrayOfByte[var12] = var9;
}
else
{
par3ArrayOfByte[var12] = var10;
}
}
else if (var8 > 0)
{
--var8;
par3ArrayOfByte[var12] = var10;
}
}
}
}
}
} |
913a1e14-cd04-473f-aea7-890bc2f97c42 | 7 | public static String getDescriptor ( byte multiplier, byte type ) {
switch ( type ) {
case 0:
switch ( multiplier ) {
case 1:
return "" ;
case 2:
return "Double Letter Score" ;
case 3:
return "Triple Letter Score" ;
default:
return null ;
}
case 2:
return "Double Word Score" ;
case 3:
return "Triple Word Score" ;
case 4:
return "Starting Position" ;
default:
return null ;
}
} |
3a4ebd0d-34ef-4b47-8f05-2c9856e3107b | 8 | public void handleWindow(Window window, int eventID) {
String setting = Settings.settings().getString("ExistingSessionDetectedAction", "manual");
if (setting.equalsIgnoreCase("primary")) {
Utils.logToConsole("End the other session and continue this one");
if (!SwingUtils.clickButton(window, "OK") &&
!SwingUtils.clickButton(window, "Continue Login") &&
!SwingUtils.clickButton(window, "Reconnect This Session")) {
Utils.logError("could not handle 'Existing session detected' dialog because the 'OK' or 'Continue Login' or 'Reconnect This Session' button wasn't found.");
}
} else if (setting.equalsIgnoreCase("secondary")) {
Utils.logToConsole("End this session and let the other session proceed");
if (!SwingUtils.clickButton(window, "Cancel") && !SwingUtils.clickButton(window, "Exit Application")) {
Utils.logError("could not handle 'Existing session detected' dialog because the 'Cancel' or 'Exit Application' button wasn't found.");
}
} else if (setting.equalsIgnoreCase("manual")) {
Utils.logToConsole("User must choose whether to continue with this session");
// nothing to do
} else {
Utils.logError("could not handle 'Existing session detected' dialog because the ExistingSessionDetectedAction setting is invalid.");
}
} |
515d353f-4c79-4c05-8443-3e65534c3b3f | 1 | public void printFund() {
int total = 0;
for(Konto k:accountList) {
total += k.getSaldo();
}
System.out.println("Total funds: " + total);
} |
ed639bbc-a62b-40ca-a7c4-8ec71397a22d | 8 | void loadResources() {
if (isEmpty())
return;
String address = null;
if (Page.isApplet()) {
synchronized (mdList) {
for (PageMd3d md : mdList) {
address = FileUtilities.removeSuffix(page.getAddress()) + "$" + md.getIndex() + ".mdd";
URL url = null;
try {
url = new URL(address);
}
catch (MalformedURLException e) {
e.printStackTrace();
if (!FileUtilities.isRemote(address)) {
try {
url = new File(address).toURI().toURL();
}
catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
}
if (url != null)
md.input(url, false);
}
}
}
else {
synchronized (mdList) {
for (PageMd3d md : mdList) {
address = FileUtilities.removeSuffix(page.getAddress()) + "$" + md.getIndex() + ".mdd";
md.input(address, false);
}
}
}
} |
66c60d40-7efb-423c-8a75-fb49d11b2c9e | 6 | public void get(int key) {
HashPrinter.tryGet(key);
/** Run along the array */
int runner = 0;
int hash = (key % table.length);
while (table[hash] != null && runner < table.length) {
if (table[hash].getKey() == key) {
break;
}
runner++;
hash = ((key + runner * runner) % table.length);
}
if (runner == table.length || table[hash].getKey() != key) {
HashPrinter.notFound(key);
} else if (table[hash].getKey() == key) {
HashPrinter.found(table, key, hash);
}
} |
e0dbed66-1d95-4e86-9bbf-09cb809cbec1 | 4 | public void visitInsn(final int opcode) {
if (mv != null) {
mv.visitInsn(opcode);
}
execute(opcode, 0, null);
if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN)
|| opcode == Opcodes.ATHROW) {
this.locals = null;
this.stack = null;
}
} |
a67069d6-24b7-48af-8340-c866762927b1 | 9 | public boolean execute(CommandSender sender, String[] args, String label) {
FileConfiguration messages = plugin.getMessageConfig();
final String notPlayer = messages.getString("info.warnings.playerCommand");
final String usage = messages.getString("commands.unfriend.usage");
final String noPerms = messages.getString("info.warnings.noPerms");
final String notOwner = messages.getString("info.warnings.notOwner");
final String notFriend = messages.getString("commands.unfriend.alerts.notFriend");
final String unfriended = messages.getString("commands.unfriend.alerts.unfriended");
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.DARK_RED + notPlayer);
} else {
if (args.length < 2) {
sender.sendMessage(ChatColor.RED + usage.replace("#{label}", label).replace("#{command}", args[0]));
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("landlord.player.own")) {
player.sendMessage(ChatColor.RED + noPerms);
return true;
}
Chunk currChunk = player.getLocation().getChunk();
/*
* *************************************
* mark for possible change !!!!!!!!!
* *************************************
*/
Friend frd = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]));
OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName());
if (land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends"))) {
player.sendMessage(ChatColor.RED + notOwner);
return true;
}
if (!land.removeFriend(frd)) {
player.sendMessage(ChatColor.YELLOW + notFriend.replace("#{playerName}", args[1]));
return true;
}
if (plugin.getConfig().getBoolean("options.particleEffects", true)) { //conf
land.highlightLand(player, Effect.VILLAGER_THUNDERCLOUD, 2);
}
plugin.getDatabase().save(land);
if (plugin.getConfig().getBoolean("options.soundEffects", true)) { //conf
player.playSound(player.getLocation(), Sound.ENTITY_ZOMBIE_INFECT, 10, .5f);
}
player.sendMessage(ChatColor.GREEN + unfriended.replace("#{playerName}", args[1]));
}
return true;
} |
6f13fbe1-709e-45bf-b992-99ba5fe98182 | 4 | public void hit() {
for (int i = 0; i < Game.missiles.size(); i++) {
if (hitBox.intersects(Game.missiles.get(i)) && Game.missiles.get(i).hit) {
health -= Game.missiles.get(i).getDamage();
atPl = true;
if (health < 1) {
dropMana(Game.missiles.get(i).getDamage() * 5);
Game.p.addXP(0.3);
}
Game.missiles.remove(Game.missiles.get(i));
}
}
} |
6efbbbee-bc94-4648-8e34-ffe2fc464741 | 3 | public void deleteHabitat(int id) {
if (id <= 0) return;
if (!existsHabitat(id)) return;
try {
PreparedStatement deleteHabitat = db.prepareStatement("DELETE FROM " + CuboidHandler.habitatTable + " WHERE cuboidid = '" + id + "';");
deleteHabitat.executeUpdate();
getHabitats().remove(id);
} catch(Exception e) {
e.printStackTrace();
}
} |
f514e83c-dcb3-4d27-ac1b-1888661b1cd7 | 2 | public List<EntidadBancaria> findByCodigo(String codigo){
try{
List<EntidadBancaria> ListaEntidades;
Connection connection = connectionFactory.getConnection();
ListaEntidades = new ArrayList();
String buscarPorCodigo = "SELECT * FROM entidadbancaria where codigoEntidad = ?";
PreparedStatement prepared = null;
prepared = connection.prepareStatement(buscarPorCodigo);
prepared.setString(1, codigo);
ResultSet result = prepared.executeQuery();
while (result.next()) {
EntidadBancaria entidadBancaria = new EntidadBancaria();
entidadBancaria.setIdEntidad(result.getInt("idEntidad"));
entidadBancaria.setCodigoEntidadBancaria(result.getString("codigoEntidad"));
entidadBancaria.setNombre(result.getString("nombre"));
entidadBancaria.setCif(result.getString("cif"));
entidadBancaria.setTipo(TipoEntidadBancaria.valueOf(result.getString("tipoEntidad")));
ListaEntidades.add(entidadBancaria);
}
return ListaEntidades;
}catch(Exception ex){
throw new RuntimeException(ex);
}
} |
e5104d2f-0684-406f-812b-3bd0e3da68d4 | 2 | public LocalVariable localAt(int index) {
LocalVariable local = (LocalVariable) locals.get(new Integer(index));
if (local == null) {
local = new LocalVariable(index);
locals.put(new Integer(index), local);
if (index >= maxLocals) {
maxLocals = index++; // Dangerous?
}
}
return (local);
} |
7d72d930-05b8-4972-b499-486bfda292f1 | 6 | private BufferedImage twistImage() {
double dMultValue = random.nextInt(7) + 3;// 波形的幅度倍数,越大扭曲的程序越高,一般为3
double dPhase = random.nextInt(6);// 波形的起始相位,取值区间(0-2*PI)
BufferedImage destBi = new BufferedImage(buffImg.getWidth(),
buffImg.getHeight(), BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < destBi.getWidth(); i++) {
for (int j = 0; j < destBi.getHeight(); j++) {
int nOldX = getXPosition4Twist(dPhase, dMultValue,
destBi.getHeight(), i, j);
int nOldY = j;
if (nOldX >= 0 && nOldX < destBi.getWidth() && nOldY >= 0
&& nOldY < destBi.getHeight()) {
destBi.setRGB(nOldX, nOldY, buffImg.getRGB(i, j));
}
}
}
return destBi;
} |
abc4cd7d-9ff8-4fe8-88d5-5d8f15652d98 | 9 | public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("addresses.list"));
String line;
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
br.close();
ArrayList<CheckingThread> threads = new ArrayList<CheckingThread>();
for (int i = 0; i < lines.size(); i += 10000) {
int iEnd = i + 10000;
if (iEnd > lines.size() - 1) {
iEnd = lines.size() - 1;
}
CheckingThread current = new CheckingThread(lines.subList(i, iEnd));
Thread t = new Thread(current);
t.start();
threads.add(current);
}
System.out.println("Threads started = " + threads.size());
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
System.out.println(CheckedReflectors.size() + "/" + lines.size() + " checked...");
if (totalWorkFinished(threads)) {
break;
}
}
System.out.println("===================");
System.out.println("Reflectors Checked!");
System.out.println(lines.size() + " lines checked!");
System.out.println("Saving on file...");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("addresses.list.CHECKED", true)), false);
int totalRealReflectors = 0;
for (Entry<String, Couple<Integer, Boolean>> reflector : CheckedReflectors.entrySet()) {
if (reflector.getValue().second) {
out.println(reflector.getKey() + " <resolver> " + reflector.getValue().first);
totalRealReflectors++;
}
}
System.out.println(totalRealReflectors + "/" + CheckedReflectors.size() + " real reflectors found&saved!");
out.flush();
out.close();
CheckedReflectors.clear();
} catch (IOException e) {
e.printStackTrace();
}
} |
c69d268f-179a-44bc-833b-2b4c57328b23 | 9 | @Override
public void parse() {
BufferedReader reader = new BufferedReader(new StringReader(getInput()));
String line;
Pattern nCount = Pattern.compile("n=(?<N>\\d+)");
Pattern person = Pattern.compile("(?<index>\\d+) (?<name>[a-zA-Z0-9-']+)");
Pattern preferences = Pattern.compile("(?<index>\\d+): (?<list>([0-9 ])+)");
Matcher nCountMatcher;
Matcher personMatcher;
Matcher preferenceMatcher;
int menIdx = 1;
int womenIdx = 1;
try {
// Parse each line
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
if (line.charAt(0) == '#') { // skip comments
continue;
}
// Matches n=XXX
nCountMatcher = nCount.matcher(line);
if (nCountMatcher.matches()) {
this.menMap = new HashMap<Integer, String>();
this.menIdLookup = new HashMap<Integer, Integer>();
this.menReverseIdLookup = new HashMap<Integer, Integer>();
this.womenMap = new HashMap<Integer, String>();
this.womenIdLookup = new HashMap<Integer, Integer>();
this.womenReverseIdLookup = new HashMap<Integer, Integer>();
this.idLookup = new HashMap<Integer, Integer>();
this.freeMen = new PriorityQueue<Integer>();
this.N = Integer.parseInt(nCountMatcher.group("N"));
// Initialize buffers for men and women
this.wife = new int[this.N + 1];
this.husband = new int[this.N + 1];
this.menNextWomanPointerList = new int[this.N + 1];
Arrays.fill(this.menNextWomanPointerList, 1);
this.preferenceList = new int[2 * this.N + 1][this.N + 1];
this.inversePreferenceList = new int[2 * this.N + 1][this.N + 1];
continue;
}
// Matches X <name>
personMatcher = person.matcher(line);
if (personMatcher.matches()) {
int index = Integer.parseInt(personMatcher.group("index"));
boolean isMan = index % 2 == 1;
if (isMan) {
this.menMap.put(index, personMatcher.group("name"));
this.menReverseIdLookup.put(menIdx, index);
this.idLookup.put(index, menIdx);
this.menIdLookup.put(index, menIdx++);
} else {
this.womenMap.put(index, personMatcher.group("name"));
this.womenReverseIdLookup.put(womenIdx, index);
this.idLookup.put(index, womenIdx);
this.womenIdLookup.put(index, womenIdx++);
}
continue;
}
// Matches X: 1 2 ... n
preferenceMatcher = preferences.matcher(line);
if (preferenceMatcher.matches()) {
String[] prefStr = preferenceMatcher.group("list").split(" ");
int personId = Integer.parseInt(preferenceMatcher.group("index"));
for (int personIndex = 1; personIndex <= prefStr.length; personIndex++) {
int id = Integer.parseInt(prefStr[personIndex - 1]);
int personIdToPersonIndex = idLookup.get(id);
preferenceList[personId][personIndex] = personIdToPersonIndex;
inversePreferenceList[personId][preferenceList[personId][personIndex]] = personIndex;
}
continue;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} |
840654c0-9e0b-431c-8fc2-6b79b4e7df07 | 6 | public static void main(String[] args) {
Game g = new Game();
Scanner in = new Scanner(System.in);
while (true) {
// display the board
System.out.println(g.board);
System.out.println("Player " + g.getCurrentPlayerIndex());
// display the player's hand
Player p = g.getPlayer(g.getCurrentPlayerIndex());
System.out.println("Your hand: " + p.getHand());
System.out.print("Your scores: ");
for (int i = 0; i < 6; i++) {
System.out.print(g.getPlayer(g.getCurrentPlayerIndex())
.getScore(i) + " ");
}
System.out.println();
// get the player's chosen tile
System.out.println("Which tile do you want to play (index 0 to "
+ (p.getHand().size() - 1) + ")?");
int tileIndex = in.nextInt();
Tile tile = p.getHand().get(tileIndex);
// get placement info
System.out.println("Give the rotation of the tile:");
int rotation = in.nextInt();
System.out.println("Give row to place tile:");
int row = in.nextInt();
System.out.println("Give column to place tile:");
int column = in.nextInt();
// try to place the tile, and give option to swap hand (if legal) or
// refresh
if (g.play(g.getCurrentPlayerIndex(), tile, row, column, rotation)) {
p.getHand().remove(tileIndex);
System.out.println("Player who scored");
if (g.getPlayer(g.getCurrentPlayerIndex()).getPlaysLeft() == 0) {
// give the player the option to refresh hand or to swap
// hand completely
if (p.canSwapTiles()) {
System.out
.println("Do you want to swap your hand (0 = no, 1 = yes)?");
// get the answer
int answer = in.nextInt();
if (answer == 1) {
p.swapTiles();
continue;
}
}
p.refreshHand();
}
} else {
System.out.println("Invalid move: try again");
}
}
} |
96e96195-61f0-4633-96f7-ffa86700c860 | 3 | public static void enregistrer_client(Client c)
{
SAXBuilder sxb = new SAXBuilder();
try {
document = sxb.build(fichier);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
racine = document.getRootElement();
//Création des Element à ajouter.
Element client=new Element("client");
Element id=new Element("id");
Element mdp=new Element("mdp");
//Enregistrement de l'id
client.addContent(id);
id.setText(c.getId());
//Enregistrement du mdp
client.addContent(mdp);
mdp.setText(c.getMdp());
//On ajoute le client à la racine
racine.addContent(client);
//On enregistre le fichier XML
try
{
//ON Enregistre le fichier
XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
sortie.output(document, new FileOutputStream(fichier));
System.out.println("Les données ont été modifié");
}
catch (java.io.IOException e){}
} |
b940d6e8-6072-421f-8982-4bed185c6d71 | 9 | private boolean hasStraight() {
if (cards[4].getRank() == CardRank.ACE
&& cards[0].getRank() == CardRank.TWO) {
// Possible ace-low straight
if (
cards[1].getRank() == CardRank.THREE &&
cards[2].getRank() == CardRank.FOUR &&
cards[3].getRank() == CardRank.FIVE) {
return true;
}
} else {
if (cards[0].getRank().ordinal() == cards[1].getRank().ordinal() - 1
&& cards[1].getRank().ordinal() == cards[2].getRank()
.ordinal() - 1
&& cards[2].getRank().ordinal() == cards[3].getRank()
.ordinal() - 1
&& cards[3].getRank().ordinal() == cards[4].getRank()
.ordinal() - 1
) {
return true;
}
}
return false;
} |
6bc6ea1d-8826-4f11-820b-c6e8ed1d0e96 | 4 | public void start() {
if(!(GameController.props.getProperty("os.name").contains("Linux") && GameController.props.getProperty("java.runtime.name").contains("OpenJDK"))) {
lastSong = null;
if(playList != null) {
if(currentSongIndex >= playList.size()) {
currentSongIndex = 0;
}
GameSong gs = playList.get(currentSongIndex);
hitFadeOutNext = false;
stopping = false;
gs.play();
}
}
} |
4f500c09-eec0-4930-82ac-cf373076d78a | 8 | public static void main(String[] args) throws IOException{
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
// while ((line = bi.readLine()) != null)
// for (String numStr: line.split("\\s"))
// sum += Integer.parseInt(numStr);
int n= Integer.parseInt(bi.readLine());
int[] a = new int[n];
int bSize = (int) Math.sqrt(n);
long[] bSums = new long[(int)Math.sqrt(n)+2];
long[] bSumsSorted = new long[(int)Math.sqrt(n)+2];
long sum=0;
line = bi.readLine();
String[] num = line.split("\\s+");
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(num[i]);
sum+=a[i];
if(i>0 && i%bSize==0){
bSums[i/bSize]=sum;
sum=0;
}
}
int[] aSorted = Arrays.copyOf(a, a.length);
Arrays.sort(aSorted);
sum=0;
for(int i=0;i<n;i++){
sum+=aSorted[i];
if(i>0 && i%bSize==0){
bSumsSorted[i/bSize]=sum;
sum=0;
}
}
int m=Integer.parseInt(bi.readLine());
StringBuilder sb = new StringBuilder();
for(int i=0;i<m;i++){
line = bi.readLine();
num = line.split("\\s+");
int type = Integer.parseInt(num[0]);
int l = Integer.parseInt(num[1])-1;
int r = Integer.parseInt(num[2])-1;
if(type == 1){
rangeQ(l, r, bSize, a, bSums, sb);
} else {
rangeQ(l, r, bSize, aSorted, bSumsSorted, sb);
}
}
System.out.println(sb.toString());
} |
a4d2acb8-6463-4098-928c-271026e599eb | 5 | @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BeanMa_train bm_train = null;
try {
bm_train = new BeanMa_train();
if("yahoo".equals(request.getParameter("datasource"))){
//使用yahoofinance資料來源
bm_train.setRDataSource(request.getParameter("trainStockSymbol"),request.getParameter("trainStartDate"),request.getParameter("trainEndDate"));
request.setAttribute("trainStartDatetime", request.getParameter("trainStartDate"));
request.setAttribute("trainEndDatetime", request.getParameter("trainEndDate"));
}else if("db".equals(request.getParameter("datasource"))){
ServletContext sc = this.getServletConfig().getServletContext();
bm_train.setRDataSource(sc,request.getParameter("trainStockSymbol"),request.getParameter("trainStartDate"),request.getParameter("trainStartTime"),request.getParameter("trainEndDate"),request.getParameter("trainEndTime"));
request.setAttribute("trainStartDatetime", request.getParameter("trainStartDate") + " " + request.getParameter("trainStartTime"));
request.setAttribute("trainEndDatetime", request.getParameter("trainEndDate") + " " + request.getParameter("trainEndTime"));
}
bm_train.excute();
} catch (Exception ex) {
throw new ServletException(ex);
}finally{
//關閉Rconnection連結
if(bm_train!=null) try {
bm_train.closeRconn();
} catch (RserveException ex) {
throw new ServletException(ex);
}
}
String bests = bm_train.getBestS();
String bestl = bm_train.getBestL();
request.setAttribute("Bests", bests);
request.setAttribute("Bestl", bestl);
request.getRequestDispatcher("/WEB-INF/MaPages/training/displayMa_train.jsp").forward(request, response);
} |
d8d68828-764b-47ad-a5e7-0bd739ae16b2 | 9 | public void initialize(Subject newSubject, CallbackHandler newCallbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
log.trace("Initializing HTTP OATH OTP LoginModule");
this.subject = newSubject;
this.callbackHandler = newCallbackHandler;
this.protectedUrl = options.get(OPTION_HTTPOATHOTP_PROTECTED_URL).toString();
if (options.get(OPTION_HTTPOATHOTP_EXPECTED_OUTPUT) != null) {
this.expectedOutput = options.get(OPTION_HTTPOATHOTP_EXPECTED_OUTPUT).toString();
}
if (options.get(OPTION_HTTPOATHOTP_MIN_LENGTH) != null) {
this.minLength = Integer.parseInt(options.get(OPTION_HTTPOATHOTP_MIN_LENGTH).toString());
}
if (options.get(OPTION_HTTPOATHOTP_MAX_LENGTH) != null) {
this.maxLength = Integer.parseInt(options.get(OPTION_HTTPOATHOTP_MAX_LENGTH).toString());
}
if (options.get(OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS) != null) {
String s = options.get(OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS).toString();
if (s.equals("true")) {
this.requireAllDigits = true;
} else if (s.equals("false")) {
this.requireAllDigits = false;
} else {
log.error("Bad value for option {}", OPTION_HTTPOATHOTP_REQUIRE_ALL_DIGITS);
}
}
/* Realm of principals added after authentication */
if (options.get(OPTION_HTTPOATHOTP_ID_REALM) != null) {
this.idRealm = options.get(OPTION_HTTPOATHOTP_ID_REALM).toString();
}
} |
f20ea0e0-7b71-4dab-9d00-bcfc15bca9ce | 1 | @Override
public int rowsX() {
return isNotPlayerInventory() ? 3 : 5;
} |
cb6f8dd7-e573-4853-aaf3-1ace786e282e | 8 | int alphabeta(int alpha, int beta, int depth, int player, FieldContainer fc) {
if (depth == 0) {
return estimateComplex(fc.getField(), player);
}
int best, score;
ArrayList<Field> moves = new ArrayList<Field>();
gen_moves(moves, fc.getField(), player);
if (player == 2) {
best = alpha;
for (int i = 0; i < moves.size(); ++i) {
if (best > beta) {
break;
}
score = alphabeta(best, beta, depth - 1, 1, new FieldContainer(moves.get(i)));
if (score > best) {
fc.setField(moves.get(i));
best = score;
}
}
return best;
} else {
best = beta;
for (int i = 0; i < moves.size(); ++i) {
if (best < alpha) {
break;
}
score = alphabeta(alpha, best, depth - 1, 2, new FieldContainer(moves.get(i)));
if (score < best) {
fc.setField(moves.get(i));
best = score;
}
}
return best;
}
} |
64021882-db24-4f75-bd6c-15a2b702e0cc | 5 | @Override
public void run(){
if(bidderListeners.size() > 0){
timer.start();
for(IAllowedBidsEventListener e : bidderListeners) e.onAllowedToBid(new AllowedToBidEvent(this));
while(currentTime > 0){
try {
sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
for(IAllowedBidsEventListener c : bidderListeners) c.onAllBidsAreClosed(new BidsClosedEvent(this, currentBidder));
winningCustomer = currentBidder;
System.out.println("Winner for: " + getProductName() + " is: " + winningCustomer.getCustomerName());
timer.end();
}
} |
8bb7fbf2-5b86-47f1-9e5f-56f754d906a3 | 6 | public String readLine() throws IOException {
if (lookaheadChar == UNDEFINED) {
lookaheadChar = super.read();
}
line.clear(); //reuse
// return null if end of stream has been reached
if (lookaheadChar == END_OF_STREAM) {
return null;
}
// do we have a line termination already
char laChar = (char) lookaheadChar;
if (laChar == '\n' || laChar == '\r') {
lastChar = lookaheadChar;
lookaheadChar = super.read();
// ignore '\r\n' as well
if ((char) lookaheadChar == '\n') {
lastChar = lookaheadChar;
lookaheadChar = super.read();
}
lineCounter++;
return line.toString();
}
// create the rest-of-line return and update the lookahead
line.append(laChar);
String restOfLine = super.readLine(); // TODO involves copying
lastChar = lookaheadChar;
lookaheadChar = super.read();
if (restOfLine != null) {
line.append(restOfLine);
}
lineCounter++;
return line.toString();
} |
8b54b1a0-4ec2-4dc1-9c56-fd3b573ae97e | 0 | public double getXCoordinate()
{
return xCoordinate;
} |
795a22c1-8661-48ba-a50d-eb641674be1d | 7 | @Override
public void enter(GameContainer gc, StateBasedGame game) throws SlickException {
if(!musicRef.equals("")) {
ResourceManager.getMusic(musicRef).setPosition(musicPos);
ResourceManager.getMusic(musicRef).loop();
}
System.out.println(musicRef);
gc.getInput().clearKeyPressedRecord();
Game.getCamera().setScale(map.getScale());
Game.getCamera().setMap(map);
if(!PreviouslyEntered && !PauseState){
TiledMap tmap = map.getMap();
int id;
for(int i = 0; i < tmap.getLayerCount(); i++) {
for(int k = 0; k < tmap.getWidth(); k++) {
for(int j = 0; j < tmap.getHeight(); j++) {
id = tmap.getTileId(k, j, i);
if(Boolean.parseBoolean(tmap.getTileProperty(id, "startingPos", "false"))) {
map.setStartingPos(new Vector2f(k * tmap.getTileWidth(), j * tmap.getTileHeight()));
player.getShape().setLocation(k * tmap.getTileWidth(), j * tmap.getTileHeight()+32 - player.getShape().getHeight());
}
}
}
}
map.update(gc, game, 1);
}
PreviouslyEntered = true;
} |
9406da2a-46a0-4488-b6ca-dd921ed426be | 2 | public void setInterfaces(CtClass[] list) {
checkModify();
String[] ifs;
if (list == null)
ifs = new String[0];
else {
int num = list.length;
ifs = new String[num];
for (int i = 0; i < num; ++i)
ifs[i] = list[i].getName();
}
getClassFile2().setInterfaces(ifs);
} |
8b74e0ec-5b39-449b-a1fa-72e4c3e0d79e | 8 | @SuppressWarnings ({ "unchecked", "rawtypes" } )
public static <T> Reflect<T> create( Object o )
{
if (o == null)
{
return (Reflect<T>)ReflectNull.INSTANCE;
}
else if (o instanceof Method)
{
return (Reflect<T>)addMethod( (Method)o );
}
Class<?> oclass = (o instanceof Class ? (Class<?>)o : o.getClass());
Reflect<T> reflect = ReflectRegistry.get( oclass );
if (reflect != null)
{
return reflect;
}
if (oclass.isArray())
{
reflect = new ReflectArray( oclass );
ReflectRegistry.add( reflect );
}
else if (oclass.isEnum())
{
reflect = new ReflectEnum( oclass );
ReflectRegistry.add( reflect );
}
else
{
reflect = (Reflect<T>)addObject( oclass );
}
return reflect;
} |
90719333-26fa-4beb-bd30-e8d85b072f18 | 4 | private void populateToolBar()
{
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
mButtons = new HashMap();
Action clear = new AbstractAction("Clear", null)
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try
{
mTP1.setText("");
mTP2.setText("");
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
};
mTB.add(clear);
Action load = new AbstractAction("Open", RHImageLoader
.getImageIcon("OPEN.gif"))
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try
{
mTP1.setText("");
mTP2.setText("");
mTP1.getEditorKit().read(new StringReader(mInputHTML),
mTP1.getDocument(), 0);
mTP2.getEditorKit().read(
new FileInputStream("c:\\temp\\test.rtf"),
mTP2.getDocument(), 0);
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
};
mTB.add(createButton(load, "Open", false));
Action save = new AbstractAction("Save", RHImageLoader
.getImageIcon("SAVE.gif"))
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
try
{
mTP1.getEditorKit().write(System.out, mTP1.getDocument(),
0, mTP1.getDocument().getLength());
System.out.println("**********************************");
mTP2.getEditorKit().write(System.out, mTP2.getDocument(),
0, mTP2.getDocument().getLength());
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
};
mTB.add(createButton(save, "Save", false));
mTB.addSeparator(new Dimension(40, 12));
mFontFamily = new JComboBox(fonts);
mFontFamily.addItemListener(this);
mTB.add(mFontFamily);
mTB.addSeparator(new Dimension(10, 16));
mFontSize = new JComboBox();
for (int x = 0; x < FONT_SIZES.length; x++)
{
mFontSize.addItem(String.valueOf(FONT_SIZES[x]));
}
mFontSize.addItemListener(this);
mTB.add(mFontSize);
mTB.addSeparator();
Action colourChoice = new AbstractAction("Colour Chooser",
RHImageLoader.getImageIcon("COLOUR.gif"))
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e)
{
Color c = chooseColour(mLastColor);
Action fontColor = new StyledEditorKit.ForegroundAction(
"fg-colour", c);
fontColor.actionPerformed(new ActionEvent(e.getSource(), e
.getID(), String.valueOf(c.getRGB())));
}
};
mTB.add(createButton(colourChoice, "Colour", false));
mTB.addSeparator();
Action bold = new StyledEditorKit.BoldAction();
mTB.add(createButton(bold, "Bold", true));
Action italic = new StyledEditorKit.ItalicAction();
mTB.add(createButton(italic, "Italic", true));
Action underline = new StyledEditorKit.UnderlineAction();
mTB.add(createButton(underline, "Underline", true));
mTB.addSeparator();
Action leftJustify = new StyledEditorKit.AlignmentAction("Left",
StyleConstants.ALIGN_LEFT); // LEFT
AbstractButton b1 = createButton(leftJustify, "Left-Align", true);
Action centerJustify = new StyledEditorKit.AlignmentAction("Center",
StyleConstants.ALIGN_CENTER); // CENTER
AbstractButton b2 = createButton(centerJustify, "Center-Align", true);
Action rightJustify = new StyledEditorKit.AlignmentAction("Right",
StyleConstants.ALIGN_RIGHT); // RIGHT
AbstractButton b3 = createButton(rightJustify, "Right-Align", true);
// Action justified = new StyledEditorKit.AlignmentAction("Justified", StyleConstants.ALIGN_JUSTIFIED);
// //Justified
// AbstractButton b4 = createButton(rightJustify, "Justified", true);
JToggleButton nullButton = new JToggleButton();
mNullButtonModel = nullButton.getModel();
mAlignmentGroup = new ButtonGroup();
mAlignmentGroup.add(b1);
mAlignmentGroup.add(b2);
mAlignmentGroup.add(b3);
mAlignmentGroup.add(nullButton);
mTB.add(b1);
mTB.add(b2);
mTB.add(b3);
} |
a09102ec-03b8-4edf-bbcf-c758e5df281e | 0 | public DefaultComboBoxModel getModeleJComboBoxLabo() {
return modeleJComboBoxLabo;
} |
335a6977-8ee2-4ebc-a45e-b78bed2a80b7 | 9 | static boolean isVowel(char a){
return a=='A'||a=='E'||a=='I'||a=='O'||a=='U'||a=='a'||a=='e'||a=='i'||a=='o'||a=='u';
} |
2b380e33-d7dd-45eb-a86f-e2ff425c55ec | 5 | public int getQuantity(String str)
{
int lettersLength = getLetters(str).length();
if(str.length() == lettersLength) //if the string is too short for a quantity
return 1; //default quantity is 1
if(Character.isDigit(str.charAt(lettersLength))) //if there are numbers after the letters
{
int breakPos = 0;
for(int i = lettersLength; i < str.length(); i++) //get all the numbers
{
char ch = str.charAt(i);
if(!Character.isDigit(ch))
{
breakPos = i;
break;
}
if(i == str.length()-1)
breakPos = i+1;
}
return Integer.parseInt(str.substring(lettersLength, breakPos)); //return the numbers found
}
return 1;
} |
6d18fbe8-0ee1-428a-82ec-9df6aaf8fd8a | 9 | public void writeValue (final Value<?> value) throws IOException {
if (value instanceof StringValue) {
final StringValue sv = (StringValue) value;
stream.print(sv.getValueLength());
stream.print(':');
stream.write(sv.getValue());
} else if (value instanceof IntegerValue) {
final IntegerValue iv = (IntegerValue) value;
stream.print('i');
stream.print(iv.getValue());
stream.print('e');
} else if (value instanceof ListValue) {
final ListValue lv = (ListValue) value;
stream.print('l');
for (final Value<?> val : lv.getValue()) {
writeValue(val);
}
stream.print('e');
} else if (value instanceof DictionaryValue) {
final DictionaryValue dv = (DictionaryValue) value;
stream.print('d');
for (final Map.Entry<String,Value<?>> me : dv.getValue().entrySet()) {
writeValue(new StringValue(me.getKey()));
writeValue(me.getValue());
}
stream.print('e');
} else {
throw new IllegalArgumentException("Invalid value type");
}
} |
40f726af-3666-4217-8da1-3aa4246447a3 | 5 | @Override
public Integer getIdFromDataBase() throws SQLException {
Integer id = null;
if(nameAnswer == null || nameAnswer.isEmpty()){
return id;
} else if(question == null || question.getIdTest() == null){
return id;
}
Statement statement = ua.edu.odeku.pet.database.ConnectionDataBase.getStatement();
ResultSet rs = statement.executeQuery("Select id_answer "
+ "from answer "
+ "where id_question = " + question.getIdQuestion() + " "
+ "and name_answer = '"+nameAnswer+"'; ");
if(rs.next()){
id = rs.getInt(1);
}
return id;
} |
dcd98fae-d585-4f54-aa87-448a903019a3 | 2 | public void test() throws Exception
{
MarketQuote quote = new MarketQuote( new Symbol("SIRI"));
for(MarketQuotesResponseField f: MarketQuotesResponseField.values())
{
if (quote.hasField(f))
{
System.out.println(f.name() + " " + quote.getField(f));
}
}
} |
8eb831b4-8304-439c-9932-cab7c536588b | 5 | public void run() {
while (true) {
String instruction = null;
try{
instruction = replicas.poll(1, TimeUnit.SECONDS);
if (instruction != null) {
Replica replica = ReplicaFactory.buildReplica(this.getLocation(), instruction); //Auto digested
if (replica.getOperations().name().equals("REPLY_CREATE") ||
replica.getOperations().name().equals("REPLY_MODIFY")){
ledger.add(replica.getFile(), replica.getCheckpoint());
log.info(String.format("local %d, Remote %d\n",
replica.getCheckpoint(),ledger.get(replica.getFile())));
}
}
}catch(Exception e){
log.error(e.getMessage());
}
instruction = null; //Nullify
}
} |
007f2bf5-4a6a-49be-a1a1-0ff884f0cfec | 9 | @Override
public boolean importGroup27ReadingCO2(JSONObject toImport, String device_serial,String product_id) throws Exception {
String latitude = __jdbcProperties.getProperty("sql.latitude");
String longitude = __jdbcProperties.getProperty("sql.longitude");
String method = __jdbcProperties.getProperty("sql.method");
String deviceid = device_serial + "_co2";
String current_value = (String)toImport.get("current_value");
String max_value = (String)toImport.get("max_value");
String min_value = (String)toImport.get("min_value");
int currentdata = parsevalue(current_value);
int maxdata = parsevalue(max_value);
int mindata = parsevalue(min_value);
String datetime = (String) toImport.get("at");//2014-04-29T03:11:31.118995Z
Calendar cal = DatatypeConverter.parseDateTime(datetime);
Date d = cal.getTime();
String tags = null;
JSONArray tagary = (JSONArray)toImport.get("tags");
for (int i = 0; i < tagary.size(); i++) {
if (tags == null) tags = (String) tagary.get(i);
else tags += ","+(String) tagary.get(i);
}
Connection c = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
boolean previousAC = true;
if (toImport.isEmpty())
return false;
try {
c = _getConnection();
previousAC = c.getAutoCommit();
c.setAutoCommit(false);
ps1 = c.prepareStatement(__jdbcProperties.getProperty("sql.importCommonReadings"));
ps2 = c.prepareStatement(__jdbcProperties.getProperty("sql.importGroup27Co2Readings"));
ps1.setString(1, deviceid);
ps1.setTimestamp(2, new java.sql.Timestamp(d.getTime()), AQMDAOFactory.AQM_CALENDAR);
ps1.setDouble(3, Double.parseDouble(latitude));
ps1.setDouble(4, Double.parseDouble(longitude));
ps1.setString(5, method);
ps2.setString(1, product_id);
ps2.setString(2, deviceid);
ps2.setTimestamp(3, new java.sql.Timestamp(d.getTime()), AQMDAOFactory.AQM_CALENDAR);
ps2.setInt(4, currentdata);
ps2.setInt(5, maxdata);
ps2.setInt(6, mindata);
ps2.setString(7, tags);
ps2.setString(8, (String) ((JSONObject)toImport.get("unit")).get("label"));
ps2.setString(9, (String) ((JSONObject)toImport.get("unit")).get("symbol"));
System.out.println("co2 1");
ps1.executeUpdate();
ps1.clearParameters();
ps2.executeUpdate();
ps2.clearParameters();
c.commit();
System.out.println("co2 finish");
} catch (SQLException se) {
se.printStackTrace();
throw new Exception(se);
} catch (Throwable t) {
t.printStackTrace();
throw new Exception(t);
} finally {
try {
if (ps1 != null)
ps1.close();
if (ps2 != null)
ps2.close();
if (c != null) {
c.rollback();
c.setAutoCommit(previousAC);
c.close();
}
} catch (SQLException se2) {
se2.printStackTrace();
}
}
return true;
} |
4c40e428-9eb8-4747-9c1c-9a3fe0a9d4fd | 2 | private EmailKontaktList readContacts() {
JAXBContext context = null;
if (!new File(EMAILCONTACTS_XML).exists())
return new EmailKontaktList();
try {
context = JAXBContext.newInstance(EmailKontaktList.class);
Unmarshaller um = context.createUnmarshaller();
EmailKontaktList emailContacts = (EmailKontaktList) um
.unmarshal(new File(EMAILCONTACTS_XML));
return emailContacts;
} catch (JAXBException e) {
e.printStackTrace();
return new EmailKontaktList();
}
} |
ba60dc6c-58f6-4472-b389-4f06e70d411d | 6 | @Override
public void mousePressed(MouseEvent arg0) {
switch (arg0.getButton()) {
case MouseEvent.BUTTON1:
keymap.put(VK_MOUSE_1, true);
break;
case MouseEvent.BUTTON3:
keymap.put(VK_MOUSE_2, true);
break;
case MouseEvent.BUTTON2:
keymap.put(VK_MOUSE_WHEEL, true);
break;
default:
if (arg0.getButton() != MouseEvent.NOBUTTON) {
if (keymap.containsKey(arg0.getButton())) {
keymap.put(arg0.getButton(), true);
}
}
}
synchronized(screens) {
Iterator<Screen> it = screens.iterator();
while (it.hasNext()) {
it.next().mousePressed(arg0);
}
}
} |
471b0081-6caa-4acd-9546-1ad5776a4581 | 0 | public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
} |
26219625-49a9-4789-b2d9-2a3a8948e042 | 9 | public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[41];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 18; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 41; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
} |
513a9ae0-721e-47ca-bc5b-3a3c3175c1b7 | 0 | private void placeIntegrationParameters() {
//Set layout to all internal panels
integrationParametersPanel.setLayout(gridBagLayout);
buttonsPanel.setLayout(gridBagLayout);
//Create GridBagConstraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.NORTHWEST;
constraints.insets = DEFAULT_INSETS;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
//Set constraints to all UI controls
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(numLabel, constraints);
constraints.gridx++;
gridBagLayout.setConstraints(numberOfPointsTextField, constraints);
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(timeLabel, constraints);
constraints.gridx++;
gridBagLayout.setConstraints(timeStepTextField, constraints);
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(timePeriodLabel, constraints);
constraints.gridx++;
gridBagLayout.setConstraints(timePeriodTextField, constraints);
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(integrationMethodLabel, constraints);
constraints.gridx++;
constraints.gridwidth = 4;
gridBagLayout.setConstraints(integrationMethodsComboBox, constraints);
constraints.gridy++;
constraints.gridx = 0;
gridBagLayout.setConstraints(angleLabel, constraints);
constraints.gridx++;
constraints.gridwidth = 4;
gridBagLayout.setConstraints(angleComboBox, constraints);
integrationParametersPanel.add(numLabel);
integrationParametersPanel.add(numberOfPointsTextField);
integrationParametersPanel.add(timeLabel);
integrationParametersPanel.add(timeStepTextField);
integrationParametersPanel.add(timePeriodLabel);
integrationParametersPanel.add(timePeriodTextField);
integrationParametersPanel.add(integrationMethodLabel);
integrationParametersPanel.add(integrationMethodsComboBox);
integrationParametersPanel.add(angleLabel);
integrationParametersPanel.add(angleComboBox);
} |
413c747e-93bc-447d-ba59-2f751e935987 | 8 | private void setMethod(Method m) {
// Validate the method return
if (!m.getReturnType().equals(Void.TYPE)) {
throw new IllegalArgumentException("The target method must return null.");
}
// Validate the method modifier
if ((m.getModifiers() & Modifier.STATIC) != 0) {
throw new IllegalArgumentException("The target method cannot be static.");
}
// Check the parameters
Class<?> params[] = m.getParameterTypes();
if (isUnnamed()) {
// Default argument
if (params.length != 1) {
throw new IllegalArgumentException("The unnamed setter must have one parameter.");
}
if (!params[0].equals(String.class)) {
throw new IllegalArgumentException("The unnamed setter parameter must be a string.");
}
setType(params[0]);
} else {
// Validate the argument type
if (params.length > 1) {
throw new IllegalArgumentException("The target method cannot have more than one parameter.");
} else if (params.length == 1) {
setType(params[0]);
}
}
// Set the method
this.method = m;
} |
b54732ed-c4d1-4d81-82c9-5556aa5a84dc | 2 | private int getPosOfMinimumFromPos(int pos) {
int min = get(pos), minPos = pos;
for (int i = pos + 1; i < len(); i++) {
if(get(i) < min) {
minPos = i;
min = get(i);
}
}
return minPos;
} |
2aa9d3ec-9893-44e5-813e-1e86c712bbf4 | 7 | @Override
public void run() {
try {
long startTime = System.currentTimeMillis();
long currentTime = startTime;
Random r = new Random();
double amount = 1000.0;
double percent = 20.0;
while(isRunning()){
switch(operations){
case deposit:
executeOperationInMessageQueue();
myBank.multicastDeposit(Account.DEFAULT_ACCOUNT_ID, amount);
break;
case withdraw:
executeOperationInMessageQueue();
myBank.multicastWithdraw(Account.DEFAULT_ACCOUNT_ID, amount);
break;
case addInPercent:
executeOperationInMessageQueue();
myBank.multicastAddInPercent(Account.DEFAULT_ACCOUNT_ID, 20.0);
break;
}
Thread.sleep((r.nextInt(5)+1)*1000);
currentTime = System.currentTimeMillis();
setRunning((currentTime - startTime) <= execTime);
}
} catch (InterruptedException e) {
// TODO transaction is invoked. Set back all amounts.
e.printStackTrace();
} catch (BankIDException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AccountException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
a443176b-03a7-4e8a-bccb-cca3fe36565a | 0 | @XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "EncryptedData")
public JAXBElement<EncryptedDataType> createEncryptedData(EncryptedDataType value) {
return new JAXBElement<EncryptedDataType>(_EncryptedData_QNAME, EncryptedDataType.class, null, value);
} |
cff9bdee-1a5a-4fab-a381-268cab963f06 | 8 | public Frame1() {
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USER, PASS);
statement = conn.createStatement();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
setTitle("KutaRaya, 1 - 18");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(400, 50, 625, 630);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon(Frame1.class.getResource("/gambar/Frame 1.jpg")));
lblNewLabel.setBounds(10,61,347, 502);
contentPane.add(lblNewLabel);
JLabel lblKutaraya = new JLabel("KutaRaya, 1 - 18");
lblKutaraya.setHorizontalAlignment(SwingConstants.CENTER);
lblKutaraya.setFont(new Font("Monospaced", Font.BOLD, 20));
lblKutaraya.setBounds(10, 11, 346, 41);
contentPane.add(lblKutaraya);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBounds(399, 139, 179, 158);
contentPane.add(panel);
JLabel label = new JLabel("Kavling");
label.setBounds(10, 11, 46, 14);
panel.add(label);
JLabel label_1 = new JLabel("No Rumah");
label_1.setBounds(10, 33, 55, 14);
panel.add(label_1);
JLabel label_2 = new JLabel("LB");
label_2.setBounds(10, 80, 55, 14);
panel.add(label_2);
JLabel label_3 = new JLabel("LT");
label_3.setBounds(10, 58, 46, 14);
panel.add(label_3);
JLabel label_4 = new JLabel("Harga");
label_4.setBounds(10, 105, 55, 14);
panel.add(label_4);
JLabel label_5 = new JLabel("Status");
label_5.setBounds(10, 130, 55, 14);
panel.add(label_5);
textField = new JTextField();
textField.setText((String) null);
textField.setColumns(10);
textField.setBounds(71, 8, 98, 20);
panel.add(textField);
textField_1 = new JTextField();
textField_1.setText((String) null);
textField_1.setColumns(10);
textField_1.setBounds(71, 30, 98, 20);
panel.add(textField_1);
textField_2 = new JTextField();
textField_2.setText((String) null);
textField_2.setColumns(10);
textField_2.setBounds(71, 77, 98, 20);
panel.add(textField_2);
textField_3 = new JTextField();
textField_3.setText((String) null);
textField_3.setColumns(10);
textField_3.setBounds(71, 55, 98, 20);
panel.add(textField_3);
textField_4 = new JTextField();
textField_4.setText((String) null);
textField_4.setColumns(10);
textField_4.setBounds(71, 105, 98, 20);
panel.add(textField_4);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(71, 127, 98, 20);
panel.add(textField_5);
JLabel lblPilihanRumah = new JLabel("Pilihan Rumah :");
lblPilihanRumah.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblPilihanRumah.setBounds(398, 91, 90, 14);
contentPane.add(lblPilihanRumah);
JButton btnNewButton = new JButton("Kembali ke Peta Awal");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
PetaAwal frame = new PetaAwal();
frame.setVisible(true);
}
});
btnNewButton.setBounds(404, 359, 176, 30);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Masuk ke Menu Rumah");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isSelected){
MainRumah.noRumahDariPeta = rumah.getNoRumah();
setVisible(false);
MainRumah frameMain = new MainRumah();
frameMain.setVisible(true);
}
else if (!isSelected){
JOptionPane.showMessageDialog(null, "Rumah belum dipilih, silahkan pilih terlebih dahulu");
}
}
});
btnNewButton_1.setBounds(405, 320, 173, 30);
contentPane.add(btnNewButton_1);
comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (comboBox.getSelectedItem().equals("")){
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
textField_4.setText("");
textField_5.setText("");
isSelected = false;
}
else{
isSelected = true;
String noRumah = (String) comboBox.getSelectedItem();
rumah = new Rumah(noRumah);
String sql = "SELECT * FROM `tabel_rumah` WHERE noRumah='"+rumah.getNoRumah()+"';";
try {
ResultSet rs = statement.executeQuery(sql);
if (!rs.isBeforeFirst()){
System.out.println("Tabel Kosong");
}
while(rs.next()){
rumah.setIDRumah(rs.getInt("idRumah"));
rumah.setTipe(rs.getString("tipeRumah"));
rumah.setLT(rs.getInt("LT"));
rumah.LTAwal = rs.getInt("LTAwal");
rumah.setLB(rs.getInt("LB"));
rumah.setHargaAwal(rs.getInt("HargaAwal"));
rumah.setHargaNett(rs.getInt("HargaNett"));
rumah.setIsBought(rs.getBoolean("isBought"));
rumah.setIsEdited(rs.getBoolean("isEdited"));
rumah.setIsLocked(rs.getBoolean("isLocked"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
textField.setText(rumah.getTipe());
textField_1.setText(rumah.getNoRumah());
textField_3.setText(rumah.getStrLT());
textField_2.setText(rumah.getStrLB());
textField_4.setText(rumah.getStrHN());
textField_5.setText(rumah.getStrIsBought(rumah.getIsBought()));
}
}
});
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 12));
comboBox.setModel(new DefaultComboBoxModel(new String[] {"", "KR-1", "KR-2", "KR-3", "KR-4", "KR-5", "KR-6", "KR-7", "KR-8", "KR-9", "KR10", "KR-11", "KR-12", "KR-14", "KR-15", "KR-16", "KR-17", "KR-18"}));
comboBox.setBounds(516, 87, 63, 20);
contentPane.add(comboBox);
} |
06b71ae9-311e-43e8-8e98-4e109ea59934 | 4 | @Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (rotation % 2 == 1) {
g.drawOval(75, 75, 50, 50);
g.drawLine(0, 100, 75, 100);
g.drawLine(125, 100, 200, 100);
}
if (rotation % 2 == 0) {
g.drawOval(75, 75, 50, 50);
g.drawLine(100, 0, 100, 75);
g.drawLine(100, 125, 100, 200);
}
if (getCurrent()==0) {
g.drawLine(100, 83, 115, 113);
g.drawLine(100, 83, 85, 113);
g.drawLine(92, 100, 108, 100);
}
else {
if (getCurrent() < 1) {
g.drawString(String.valueOf(new BigDecimal(getCurrent()).round(new MathContext(2))) + "A", 85, 105);
} else g.drawString(String.valueOf(new BigDecimal(getCurrent()).round(new MathContext(3))) + "A", 85, 105);
}
} |
19d25758-5d1f-48fc-bf6d-01c40f540c59 | 7 | public String deleteMessage(String s) {
if (s != null) {
int count = 0;
int suchMessageNummer = Integer.parseInt(s);
File suchFile;
for (File box : dir.listFiles()) {
for (File file : box.listFiles()) {
if (file.isFile() && file.getName().endsWith(".mail") && suchMessageNummer == ++count) {
suchFile = new File(new File(getFile(dir.getName()), box.getName()), "/TODEL " + file.getName());
if (file.renameTo(suchFile)) {
return "+OK message " + s + " mark to delete" + CRLF;
}
}
}
}
}
return "-ERR no such message " + s + CRLF;
} |
0256e0e2-adc4-4119-8cdd-8f5a61e4ff29 | 5 | public Result download() {
Result back = Result.UPDATED;
File updateFolder = this.plugin.getServer().getUpdateFolderFile();
String url = (String) this.latest.get(this.DL_URL);
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
URL call = new URL(url);
rbc = Channels.newChannel(call.openStream());
fos = new FileOutputStream(this.file);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (MalformedURLException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Error finding plugin update to download!", ex);
back = Result.ERROR_FILENOTFOUND;
} catch (IOException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Error transferring plugin data!", ex);
back = Result.ERROR_DOWNLOAD_FAILED;
} finally {
try {
if (fos != null) {
fos.close();
}
if (rbc != null) {
rbc.close();
}
} catch (IOException ex) {
this.plugin.getLogger().log(Level.SEVERE, "Error closing streams/channels for download!", ex);
}
}
return back;
} |
430eee48-fb31-4887-9c6f-8e1af1e5126a | 2 | private void getExams() {
try {
Exam_DAO exam_DAO = new Exam_DAO();
ResultSet rs = exam_DAO.getList("");
exams = new ArrayList<sols.Model.Exam>();
while (rs.next()) {
sols.Model.Exam examTemp = new sols.Model.Exam();
examTemp.setExam_ID(rs.getInt("Exam_ID"));
examTemp.setInstructions(rs.getString("Instructions"));
examTemp.setIsPublic(rs.getBoolean("isPublic"));
exams.add(examTemp);
}
} catch (SQLException ex) {
Logger.getLogger(ExamOverview.class.getName()).log(Level.SEVERE, null, ex);
}
} |
a91dc26d-64a8-4991-baf2-8d103e09fb6a | 4 | @Override
public Operation simplify() {
Expression L = Simplify.mod(this.L);
Expression R = Simplify.mod(this.R);
if ( "0.0".equals(L.getString()) || "0.0".equals(R.getString()) ){
return new Number(0);
} else if ( "1.0".equals(L.getString()) ){
return R.operation;
} else if ( "1.0".equals(R.getString()) ){
return L.operation;
} else {
return new Product( L, R );
}
} |
e298119a-4c92-45cd-8479-9bbc8ba0a531 | 0 | public home(int x,int y)
{
super(x,y);
URL loc = this.getClass().getResource("/karel/themes/LTTPHome.png");
ImageIcon iia = new ImageIcon(loc);
image = iia.getImage();
this.setImage(image);
} |
5aea3337-427a-4e3c-97eb-8fcc750aa920 | 4 | public synchronized void mouseClicked(MouseEvent me) {
if(me.getButton() == MouseEvent.BUTTON1) {
if(!player.getRelativeMouse()) {
player.setRelativeMouse(true);
canvas.hideCursor();
}
else {
ball.releaseBall();
Shooter shooter = player.getPaddleShooter();
if(shooter != null)
{
shooter.shoot();
}
}
}
else if(me.getButton() == MouseEvent.BUTTON3) {
player.setRelativeMouse(false);
canvas.showCursor();
}
} |
31cc7aaf-3a28-4859-afd4-80dcb32821f3 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (catalogNumber == null) {
if (other.catalogNumber != null)
return false;
} else if (!catalogNumber.equals(other.catalogNumber))
return false;
if (subject == null) {
if (other.subject != null)
return false;
} else if (!subject.equals(other.subject))
return false;
return true;
} |
5ebbed40-b09c-4f5b-8cce-33e15d6db368 | 7 | private boolean jj_3R_51()
{
if (jj_scan_token(IF)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(THEN)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(ELSE)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(END)) return true;
return false;
} |
b5fdad38-d73b-4b5e-8d65-2de9388b2ed5 | 9 | public static BufferedImage parametrizedGaussBlur(BufferedImage input, double sigma) {
// build blur kernel
int size = (int) (((int) (Math.ceil(6 * sigma)) % 2) == 1 ? Math.ceil(6 * sigma) : (Math.ceil(6 * sigma) + 1));
double kernel[] = new double[size];
int sigmaIndex = size/2;
double norm = 0;
for (int i = -sigmaIndex, j = 0; i <= sigmaIndex; i++, j++) {
kernel[j] = Math.exp(-Math.pow(i/sigma,2)/2)/(sigma*Math.sqrt(2*Math.PI));
norm += kernel[j];
}
for (int i = -sigmaIndex, j = 0; i <= sigmaIndex; i++, j++) {
kernel[j] /= norm;
}
BufferedImage horizontallyBlurred = new BufferedImage(input.getWidth(), input.getHeight(), input.getType());
for (int i = 0; i < horizontallyBlurred.getWidth(); i++)
for (int j = 0; j < horizontallyBlurred.getHeight(); j++) {
double newRed = 0;
double newGreen = 0;
double newBlue = 0;
int counter = 0;
for (int k = -sigmaIndex; k <= sigmaIndex; k++, counter++) {
Color c = new Color(input.getRGB(Math.abs(i + k) % horizontallyBlurred.getWidth(), j));
newRed += kernel[counter]*c.getRed();
newGreen += kernel[counter]*c.getGreen();
newBlue += kernel[counter]*c.getBlue();
}
horizontallyBlurred.setRGB(i, j, new Color((int) newRed, (int) newGreen, (int) newBlue).getRGB());
}
BufferedImage result = new BufferedImage(input.getWidth(), input.getHeight(), input.getType());
for (int i = 0; i < result.getWidth(); i++)
for (int j = 0; j < result.getHeight(); j++) {
double newRed = 0;
double newGreen = 0;
double newBlue = 0;
int counter = 0;
for (int k = -sigmaIndex; k <= sigmaIndex; k++, counter++) {
Color c = new Color(horizontallyBlurred.getRGB(i, Math.abs(j + k) % horizontallyBlurred.getHeight()));
newRed += kernel[counter]*c.getRed();
newGreen += kernel[counter]*c.getGreen();
newBlue += kernel[counter]*c.getBlue();
}
result.setRGB(i, j, new Color((int) newRed, (int) newGreen, (int) newBlue).getRGB());
}
return result;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.