method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
f6e2f653-a899-4dc2-b77d-b811f6cb73ff
6
public static void makeGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout; try { layout = (SpringLayout)parent.getLayout(); } catch (ClassCastException exc) { System.err.println("The first argument to makeGrid must use SpringLayout."); return; } Spring xPadSpring = Spring.constant(xPad); Spring yPadSpring = Spring.constant(yPad); Spring initialXSpring = Spring.constant(initialX); Spring initialYSpring = Spring.constant(initialY); int max = rows * cols; //Calculate Springs that are the max of the width/height so that all //cells have the same size. Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). getWidth(); Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). getHeight(); for (int i = 1; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); } //Apply the new width/height Spring. This forces all the //components to have the same size. for (int i = 0; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); cons.setWidth(maxWidthSpring); cons.setHeight(maxHeightSpring); } //Then adjust the x/y constraints of all the cells so that they //are aligned in a grid. SpringLayout.Constraints lastCons = null; SpringLayout.Constraints lastRowCons = null; for (int i = 0; i < max; i++) { SpringLayout.Constraints cons = layout.getConstraints( parent.getComponent(i)); if (i % cols == 0) { //start of new row lastRowCons = lastCons; cons.setX(initialXSpring); } else { //x position depends on previous component cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), xPadSpring)); } if (i / cols == 0) { //first row cons.setY(initialYSpring); } else { //y position depends on previous row cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), yPadSpring)); } lastCons = cons; } //Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, Spring.sum( Spring.constant(yPad), lastCons.getConstraint(SpringLayout.SOUTH))); pCons.setConstraint(SpringLayout.EAST, Spring.sum( Spring.constant(xPad), lastCons.getConstraint(SpringLayout.EAST))); }
c1301e67-23ed-4559-9ab5-5b0da48cbec4
1
public static List<TableColumnDesc> getColumns(String sql) throws SQLException{ List<TableColumnDesc> result = new ArrayList<TableColumnDesc>(); Statement stt = con.createStatement(); ResultSet rs = stt.executeQuery(sql); while (rs.next()) { TableColumnDesc tcd = new TableColumnDesc(); tcd.setField(rs.getString("FIELD")); tcd.setType(rs.getString("TYPE")); tcd.setIsKey(rs.getString("KEY")); tcd.setIsNull(rs.getString("NULL")); tcd.setExtra(rs.getString("EXTRA")); tcd.setDefault_(rs.getString("DEFAULT")); result.add(tcd); } return result; }
e8184b60-2214-4d41-ab65-d44aebb9b486
3
public void cambiarPosicionJugado2(){ for(int x=0;x<8;x++){ for(int y=0;y<8;y++){ if(pd.mapa_jugador2[x][y].equals(codigo)) pd.mapa_jugador2[x][y]=""; } } int x=rd.nextInt(0)+7; int y=rd.nextInt(0)+7; cambiarPosicionJugado2(); }
a8b4d9ed-a56d-4d94-8db3-c0e959f27688
3
protected String getBoxDescription(Box box) { if (box.getType() == Type.TEXT_CONTENT) return box.getText(); else { final String cls = box.getAttribute("class"); final String id = box.getAttribute("id"); StringBuilder ret = new StringBuilder("<"); ret.append(box.getTagName()); if (id != null) ret.append(" id=").append(id); if (cls != null) ret.append(" class=").append(cls); ret.append(">"); return ret.toString(); } }
9b6b5c80-826f-4b20-b8d7-6ff76c4693dd
8
void removeInternal(Node<K, V> node, boolean unlink) { if (unlink) { node.prev.next = node.next; node.next.prev = node.prev; } Node<K, V> left = node.left; Node<K, V> right = node.right; Node<K, V> originalParent = node.parent; if (left != null && right != null) { /* * To remove a node with both left and right subtrees, move an * adjacent node from one of those subtrees into this node's place. * * Removing the adjacent node may change this node's subtrees. This * node may no longer have two subtrees once the adjacent node is * gone! */ Node<K, V> adjacent = (left.height > right.height) ? left.last() : right.first(); removeInternal(adjacent, false); // takes care of rebalance and size-- int leftHeight = 0; left = node.left; if (left != null) { leftHeight = left.height; adjacent.left = left; left.parent = adjacent; node.left = null; } int rightHeight = 0; right = node.right; if (right != null) { rightHeight = right.height; adjacent.right = right; right.parent = adjacent; node.right = null; } adjacent.height = Math.max(leftHeight, rightHeight) + 1; replaceInParent(node, adjacent); return; } else if (left != null) { replaceInParent(node, left); node.left = null; } else if (right != null) { replaceInParent(node, right); node.right = null; } else { replaceInParent(node, null); } rebalance(originalParent, false); size--; modCount++; }
87fd9b0c-fdc6-49a3-afbb-1ea302c2a649
1
public boolean addToKit(T elem){ if(kit.add(elem)) return true; else return false; }
01178cb3-5a1f-4b31-b77e-076634442c67
2
@Override public int compare(Chromosome o1, Chromosome o2) { if(o1.getFitness() > o2.getFitness()) return -1; if(o1.getFitness() < o2.getFitness()) return 1; return 0; }
004cfe0d-e440-4199-8b1a-7d756f047589
6
public void out(String level, String msg) { // The messages level int severity = 0; // Send passed value to upper case String compare = level.toUpperCase(); // Set log level to passed parameters (if it can be mapped) if (compare.startsWith("INFO")) { // All messages severity = 4; } else if (compare.startsWith("WARN")) { // Less than info severity = 3; } else if (compare.startsWith("ERROR")) { // Less than warn severity = 2; } else { // Critical failures only (default) severity = 1; } if (severity <= SetLevel) { if (severity == 4) { // Log via info utility Log.info(msg); } else if (severity == 3) { // Log via warning utility Log.warn(msg); } else { // Log via error utility Log.error(msg); } } }
b167e3ff-312b-4902-afe1-7e30420f3bc9
1
public boolean isZeroVector(){ return x == 0 && y == 0; }
5ebc3d50-3c1e-4ba6-8b70-af3457ffcf97
5
public void analyse() { LexicalAnalyser lexicalAnalyser = CommandAnalyseFactory .createLexicalAnalyser(this.sentence); try { lexicalAnalyser.analyse(); } catch (AnalyseException e) { } if (!lexicalAnalyser.isComplete()) { this.errors = lexicalAnalyser.getErrorMsg(); return; } SyntaxAnalyser syntaxAnalyser = CommandAnalyseFactory .createSyntaxAnalyser(lexicalAnalyser); try { syntaxAnalyser.analyse(); } catch (GrammarCheckException e) { } catch (GrammarCreateException e) { } if (!syntaxAnalyser.isComplete()) { this.errors = syntaxAnalyser.getErrorMsg(); return; } this.result = syntaxAnalyser.getParserResult(); this.isSuccess = true; }
5207b3db-2f59-4c80-a272-d5691961cfda
8
public double getPerformance(int evaluation) { double result; result = Double.NaN; switch (evaluation) { case EVALUATION_CC: result = m_CC; break; case EVALUATION_RMSE: result = m_RMSE; break; case EVALUATION_RRSE: result = m_RRSE; break; case EVALUATION_MAE: result = m_MAE; break; case EVALUATION_RAE: result = m_RAE; break; case EVALUATION_COMBINED: result = (1 - StrictMath.abs(m_CC)) + m_RRSE + m_RAE; break; case EVALUATION_ACC: result = m_ACC; break; case EVALUATION_KAPPA: result = m_Kappa; break; default: throw new IllegalArgumentException("Evaluation type '" + evaluation + "' not supported!"); } return result; }
2eecd670-1cec-4e5a-a581-3201f56a661d
3
@Override public void update(Match obj) { PreparedStatement pst = null; try { pst = this.connect().prepareStatement("update Matches set equipeA=?, equipeB=?, scoreA=?, scoreB=?, datematch=? where id=? ;"); pst.setString(1, obj.getEquipeA()); pst.setString(2, obj.getEquipeB()); pst.setInt(3, obj.getScoreA()); pst.setInt(4, obj.getScoreB()); pst.setDate(5, obj.getDatematch()); pst.setInt(6, obj.getId()); pst.executeUpdate(); System.out.println("modification Match effectuée"); } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "requete modification echoué", ex); }finally{ try { if(pst != null) pst.close(); } catch (SQLException ex) { Logger.getLogger(MatchDao.class.getName()).log(Level.SEVERE, "liberation prepared statement échoué", ex); } } }
24a5230b-5b1c-4dd3-80c1-c4e5bf981553
8
private boolean readFeed() { try { // Set header values intial to the empty string String title = ""; String link = ""; // First create a new XMLInputFactory XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // Setup a new eventReader InputStream in = read(); if(in != null) { XMLEventReader eventReader = inputFactory.createXMLEventReader(in); // Read the XML document while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart().equals(TITLE)) { event = eventReader.nextEvent(); title = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart().equals(LINK)) { event = eventReader.nextEvent(); link = event.asCharacters().getData(); continue; } } else if (event.isEndElement()) { if (event.asEndElement().getName().getLocalPart().equals(ITEM)) { // Store the title and link of the first entry we get - the first file on the list is all we need versionTitle = title; versionLink = link; // All done, we don't need to know about older files. break; } } } return true; } else { return false; } } catch (XMLStreamException e) { plugin.getLogger().warning("Could not reach dev.bukkit.org for update checking. Is it offline?"); return false; } }
a93df292-22f0-4397-af72-8c4989e571a1
5
@Override public void tick(double dt) { this.dt = dt; super.move(dt); gravitate(); if (x > GameState.getInstance().getWidth() + 100 || x < -100 || y > GameState.getInstance().getHeight() + 100 || y < -1000) remove(); handleIntersects(); applyFriction(); liveTime += dt; if (liveTime >= explosionTime) { explode(); super.remove(); } }
5a8cf9ab-943f-4344-8447-734fe457cb54
2
public static void prePlay(String charType, Scanner scan, Random gen) { //Parameters: Character type, Scanner and a random number generator if (charType == "Mage") { Mage player = new Mage(); play(scan, player, gen, "Mage"); } else if (charType == "Necromancer") { Necromancer player = new Necromancer(); play(scan, player, gen, "Necromancer"); } else { Soldier player = new Soldier(); play(scan, player, gen, "Soldier"); } }
445d6f86-03f3-4e97-8cc9-fa90fa53a7c1
2
public void run() { while ( true ) { try { Socket newClient = sock.accept(); handler.handleNewConnection(newClient); } catch (IOException e) { System.exit(0); return; } } }
cfaacf36-75cd-4e5f-8460-0465031788fa
0
public String getMessage() { return this.message; }
f44c3542-8eed-4f99-bbee-59e6adc7d2e5
8
public static void main(String[] args) { Scanner dado = new Scanner(System.in); Agencia a = new Agencia(); int numero; String proprietario; float valor; boolean opcao = false; while (!opcao) { try { menu(); int operacao = dado.nextInt(); switch (operacao) { case 1: System.out.println("========================================"); System.out.println("1 - Criar conta"); System.out.print("Informe o numero: "); numero = dado.nextInt(); System.out.print("Informe o proprietario: "); proprietario = dado.next(); System.out.print("Informe o saldo: "); float saldo = dado.nextFloat(); a.criarConta(numero, proprietario, saldo); break; case 2: System.out.println("========================================"); System.out.println("2 - Cancelar conta"); System.out.print("Informe o numero: "); numero = dado.nextInt(); a.cancelarConta(numero); break; case 3: System.out.println("========================================"); System.out.println("3 - Sacar"); System.out.print("Informe o numero: "); numero = dado.nextInt(); System.out.print("Informe o valor de saque: "); valor = dado.nextFloat(); a.sacar(numero, valor); break; case 4: System.out.println("========================================"); System.out.println("4 - Depositar"); System.out.print("Informe o numero: "); numero = dado.nextInt(); System.out.print("Informe o valor de deposito: "); valor = dado.nextFloat(); a.depositar(numero, valor); break; case 5: System.out.println("========================================"); System.out.println("5 - Listar contas existentes"); System.out.println(a.listarContas()); break; case 6: opcao = true; break; default: throw new ExcecaoOpcaoInvalida("Opção Invalida."); } } catch (Exception e) { System.out.println("========================================"); System.out.print(e.getMessage()); } } }
c0bd4d55-9f71-4db6-a990-269218ef19af
7
public void update() { int xChange = 0, yChange = 0; if (anim < 7500) anim++; else anim = 0; if (input.up) yChange--; if (input.down) yChange++; if (input.left) xChange--; if (input.right) xChange++; if (xChange != 0 || yChange != 0) { move (xChange, yChange); moving = true; } else { moving = false; } updateShooting(); }
aef4c288-3477-4080-8d65-c9995970fa96
3
public synchronized void start(int... ports) { if (ports != null && ports.length > 3) { // TODO set ports gameSocketServerPort = ports[0]; chatSocketServerPort = ports[1]; managerSocketServerPort = ports[2]; } if (!listening) { listening = true; (new Thread(this)).start(); } }
766bef53-6e44-4ccc-9ed3-62365b376b23
1
public void updateUniforms(Matrix4f worldMatrix, Matrix4f projectedMatrix, Material material) { if (material.getTexture() != null) material.getTexture().bind(); else RenderUtil.unbindTextures(); setUniform("transform", projectedMatrix); setUniform("color", material.getColor()); }
48e127a0-a2f6-4f26-b388-d5ed2b4e9068
2
public void saveMetaRecords() throws IOException{ Metafile record; KeyFrame key; String metaFile = ""; primaryFileName = primaryFileName.split(".rgb")[0]; System.out.println("primary file name "+primaryFileName.split(".rgb")[0]); FileWriter fstream = new FileWriter(primaryFileName+".meta"); BufferedWriter out = new BufferedWriter(fstream); for(int i=0; i<metaRecords.size(); i++){ record = metaRecords.get(i); Collections.sort(record.kf, new customComparator()); metaFile += record.rectID+" "+record.rectName+ " "+record.numOfKeyFrames+"\r\n"; metaFile += record.linkedVideoName+" "+record.linkedVideoStartFrame+"\r\n"; for(int j=0; j<record.numOfKeyFrames; j++){ key = record.kf.get(j); metaFile += key.frameNum+" "+key.topLeftX+" "+key.topLeftY+" "+key.bottomRightX+" "+key.bottomRightY+"\r\n"; } } out.write(metaFile); out.close(); System.out.println("written to file"); }
80e42cf4-8cfb-4b5b-981a-8dc7cc4382b9
0
public void setFunTipo(String funTipo) { this.funTipo = funTipo; }
7a672e1b-c471-4765-b98d-01d413a02831
2
public static double acos(double a){ if(a<-1.0D || a>1.0D) throw new IllegalArgumentException("Fmath.acos argument (" + a + ") must be >= -1.0 and <= 1.0"); return Math.acos(a); }
7ead7975-2c4b-4bac-8d48-b2eadabba390
3
private void processEvent(Sim_event ev) { Object data = null; data = ev.get_data(); // get the event's data if (data != null && data instanceof Gridlet) { Gridlet gl = (Gridlet)data; completedJobs.add(gl); } else { // handle ping request if (ev.get_tag() == GridSimTags.INFOPKT_SUBMIT) { processPingRequest(ev); } } }
c1a58b0d-7e31-447c-aa79-f9399a3f1dda
9
private boolean r_combo_suffix() { int among_var; int v_1; // test, line 91 v_1 = limit - cursor; // (, line 91 // [, line 92 ket = cursor; // substring, line 92 among_var = find_among_b(a_2, 46); if (among_var == 0) { return false; } // ], line 92 bra = cursor; // call R1, line 92 if (!r_R1()) { return false; } // (, line 92 switch(among_var) { case 0: return false; case 1: // (, line 100 // <-, line 101 slice_from("abil"); break; case 2: // (, line 103 // <-, line 104 slice_from("ibil"); break; case 3: // (, line 106 // <-, line 107 slice_from("iv"); break; case 4: // (, line 112 // <-, line 113 slice_from("ic"); break; case 5: // (, line 117 // <-, line 118 slice_from("at"); break; case 6: // (, line 121 // <-, line 122 slice_from("it"); break; } // set standard_suffix_removed, line 125 B_standard_suffix_removed = true; cursor = limit - v_1; return true; }
3fa7bd6f-6c76-4935-9626-51afd17d73c5
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FieldListNode other = (FieldListNode) obj; if (node == null) { if (other.node != null) return false; } else if (!node.equals(other.node)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; }
ce1c840b-897c-4d65-bdac-922b1a959809
9
public int hashCode() { int hash = 0; if (foreground != null) hash ^= foreground.hashCode(); if (background != null) hash ^= background.hashCode(); if (font != null) hash ^= font.hashCode(); if (metrics != null) hash ^= metrics.hashCode(); if (underline) hash ^= (hash << 1); if (strikeout) hash ^= (hash << 2); hash ^= rise; if (underlineColor != null) hash ^= underlineColor.hashCode(); if (strikeoutColor != null) hash ^= strikeoutColor.hashCode(); if (borderColor != null) hash ^= borderColor.hashCode(); hash ^= underlineStyle; return hash; }
6b63a455-4d50-4990-b513-0b5e3e6b6d92
1
private void compute_pcm_samples12(Obuffer buffer) { final float[] vp = actual_v; //int inc = v_inc; final float[] tmpOut = _tmpOut; int dvp =0; // fat chance of having this loop unroll for( int i=0; i<32; i++) { final float[] dp = d16[i]; float pcm_sample; pcm_sample = (float)(((vp[12 + dvp] * dp[0]) + (vp[11 + dvp] * dp[1]) + (vp[10 + dvp] * dp[2]) + (vp[9 + dvp] * dp[3]) + (vp[8 + dvp] * dp[4]) + (vp[7 + dvp] * dp[5]) + (vp[6 + dvp] * dp[6]) + (vp[5 + dvp] * dp[7]) + (vp[4 + dvp] * dp[8]) + (vp[3 + dvp] * dp[9]) + (vp[2 + dvp] * dp[10]) + (vp[1 + dvp] * dp[11]) + (vp[0 + dvp] * dp[12]) + (vp[15 + dvp] * dp[13]) + (vp[14 + dvp] * dp[14]) + (vp[13 + dvp] * dp[15]) ) * scalefactor); tmpOut[i] = pcm_sample; dvp += 16; } // for }
94ca70ce-b2e9-4097-84dc-de82e00acc0f
1
public static InputStream getInputStreamByFilename(String filename) { File inputFile = new File(filename); InputStream inputStream = null; try { inputStream = inputFile.toURI().toURL().openStream(); } catch (IOException e) { System.out.println("Unable to create InputStream from file."); e.printStackTrace(); } return inputStream; }
55cbdf84-f704-4680-a350-a1997a6c33c6
6
private Map<Integer, Double> getAllUsages(List<Bookmark> bookmarks, double timestamp, boolean categories) { Map<Integer, Double> usageMap = new LinkedHashMap<Integer, Double>(); for (Bookmark data : bookmarks) { List<Integer> keys = (categories ? data.getCategories() : data.getTags()); double targetTimestamp = Double.parseDouble(data.getTimestamp()); Double rec = Math.pow(timestamp - targetTimestamp + 1.0, this.dValue * (-1.0)); if (!rec.isInfinite() && !rec.isNaN()) { for (int key : keys) { Double oldVal = usageMap.get(key); usageMap.put(key, (oldVal != null ? oldVal + rec : rec)); } } else { System.out.println("BLL - NAN"); } } return usageMap; }
0d90ce1a-8954-4908-aa33-fe8655028c02
2
public void actionPerformed(ActionEvent e) { for (int i = 0; i < t.getSize(); ++i) { t.TowerDefense_TransArray[i] .setX(t.TowerDefense_TransArray[i].getX() + 1); t.TowerDefense_TransArray[i] .setY(t.TowerDefense_TransArray[i].getY() + 1); t.TowerDefense_TransArray[i].setAction((t.TowerDefense_TransArray[i] .getAction() + 1) % 64); if (t.TowerDefense_TransArray[i].getY() > 600) t.TowerDefense_TransArray[i].setY(0); } mf.nextFrame(t); mf.turnOffRound(); }
ff52d38f-cc9d-4f78-bfc7-6d1f8581bd7a
1
@Test public void testAddFutureMeetingIDs() { // add several future dates all on one day Calendar date = (Calendar)futureDate.clone(); date.set(Calendar.HOUR, 8); cmInst.addFutureMeeting(testContactSet, date); date.set(Calendar.HOUR, 9); cmInst.addFutureMeeting(testContactSet, date); date.set(Calendar.HOUR, 10); cmInst.addFutureMeeting(testContactSet, date); date.set(Calendar.HOUR, 11); cmInst.addFutureMeeting(testContactSet, date); date.set(Calendar.HOUR, 12); cmInst.addFutureMeeting(testContactSet, date); // add a date in the past cmInst.addNewPastMeeting(testContactSet, pastDate, "some notes"); // add two more on different days date.add(Calendar.DATE, 1); cmInst.addFutureMeeting(testContactSet, date); date.add(Calendar.DATE, -2); cmInst.addFutureMeeting(testContactSet, date); for(Contact c: testContactSet) { List<Meeting> l = cmInst.getFutureMeetingList(c); Assert.assertEquals(l.size(), 7); } List<Meeting> l = cmInst.getFutureMeetingList(futureDate); Assert.assertEquals(l.size(), 5); Meeting m = cmInst.getFutureMeeting(1); Assert.assertEquals(9, m.getDate().get(Calendar.HOUR)); cmInst.flush(); }
d6b548b1-abce-4b03-9324-7998e4d42f1d
7
private void validarDatos(String nombre, String fecha_inicio, String fecha_fin) throws BusinessException { String mensaje = ""; if(nombre == null || nombre.isEmpty()) mensaje += "Fecha de pago no puede ser nula o vacia\n"; if(fecha_inicio == null || fecha_inicio.isEmpty()) mensaje += "Fecha de pago no puede ser nula o vacia\n"; if(fecha_fin == null || fecha_fin.isEmpty()) mensaje += "Fecha de pago no puede ser nula o vacia\n"; if (!mensaje.isEmpty()) throw new BusinessException(mensaje); }
920ebe15-6847-4e0f-adba-d086909a5288
6
public int getMachineIndexByName(String machineFileName){ ArrayList machines = getEnvironment().myObjects; if(machines == null) return -1; for(int k = 0; k < machines.size(); k++){ Object current = machines.get(k); if(current instanceof Automaton){ Automaton cur = (Automaton)current; if(cur.getFileName().equals(machineFileName)){ return k; } } else if(current instanceof Grammar){ Grammar cur = (Grammar)current; if(cur.getFileName().equals(machineFileName)){ return k; } } } return -1; }
088178ab-b03e-4183-8112-0aacb7613d41
1
private void printResults() { for (String result : results) { System.out.println(result); } }
e9d69915-4e14-44da-8b64-384f4ceb5851
1
@Override public void save() throws RemoteException { try (OutputStream os = new FileOutputStream(settingsFile)) { properties.storeToXML(os, "FTP File Manager Settings"); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
9aa0d9a1-b830-4ad4-9c4f-66afaa4684d9
4
public List<IGraph<N>> getMinimumGraphs() { return result != null && result.size() > 0 && result.get(0) instanceof IGraph<?> ? (List<IGraph<N>>) result : null; }
ffe92ca4-99f1-40ca-877f-4520c37677ef
0
public void setNom( String nom ) { this.nom = nom; }
f41bc9a1-e6b2-4924-ba89-d93945cd0ad7
7
public void read_dic(String dictionaryFileName, TagSet tagSet) throws IOException{ String str = ""; BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(dictionaryFileName))); INFO[] info_list = new INFO[255]; for (int i = 0; i < 255; i++) { info_list[i] = new INFO(); } while((str = in.readLine()) != null){ str.trim(); if(str.equals("")){ continue; } StringTokenizer tok = new StringTokenizer(str, "\t "); String word = tok.nextToken(); int isize = 0; while (tok.hasMoreTokens()) { String data = tok.nextToken(); StringTokenizer tok2 = new StringTokenizer(data, "."); String curt = tok2.nextToken(); int x = tagSet.getTagID(curt); if (x == -1) { System.err.println("read_dic:tag error"); continue; } if(tok2.hasMoreTokens()){ info_list[isize].phoneme = (short)tagSet.getIrregularID(tok2.nextToken()); }else{ info_list[isize].phoneme = TagSet.PHONEME_TYPE_ALL; } info_list[isize].tag = x; isize++; } info_list[isize].tag = 0; info_list[isize].phoneme = 0; char[] word3 = Code.toTripleArray(word); for(int i = 0; i < isize; i++){ store(word3, info_list[i]); } } }
ff5f44b9-4074-4a10-807d-525358e706a0
4
@Override public void setValueAt(Object value, int rowIndex, int columnIndex) { Problem problem = problems.get(rowIndex); switch (columnIndex) { case COLUMN_TITLE: problem.setProblemName(value.toString()); break; case COLUMN_FILE_NAME: problem.setFileName(value.toString()); break; case COLUMN_INPUT: problem.setInput(value.toString()); break; case COLUMN_OUTPUT: problem.setOutput(value.toString()); break; } DbAdapter.updateProblem(problem); this.fireTableDataChanged(); // update JTable }
c72c46c1-915f-412b-83e9-c8d65c4e10d4
4
private void loadPreferences() { print("Loading user preferences"); preferences = new Properties(); // Try and load from a file preferencesFile = new File(homeDir, "preferences.xml"); if (preferencesFile.isFile()) { try { preferences.loadFromXML(new FileInputStream(preferencesFile)); } catch (InvalidPropertiesFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
99b0401f-aed3-4328-8128-6ca66195c394
9
public boolean onBoard() { return (((col + row) % 2 == 0) && ((col + row) >= 6) && // northwest border ((col + row) <= 22) && // northeast border (col >= 1) && // west border (col <= 9) && // east border (row >= 1) && // north border (row <= 17) && // south border ((row - col) <= 12) && // southwest border ((col - row) <= 4) && // northeast border (! hole())); // not a hole in the board }
3dc69ae2-bb28-4ea2-a287-5524e3f64e10
2
public void addValueToHashes(String currState,String prevState,double totalValue, HashMap<String,String> bestToFrom,HashMap<String,Double> bestScoreTo) { Double myVal=bestScoreTo.get(currState); if (myVal==null || myVal<totalValue) { myVal=new Double(totalValue); bestToFrom.put(currState,prevState); bestScoreTo.put(currState,myVal); } }
fd8b58bf-f52a-4def-91b7-400b54d26938
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CompraPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CompraPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CompraPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CompraPeca.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CompraPeca().setVisible(true); } }); }
22e24791-b187-4b38-bb71-4584d4e268bd
6
@Override public CounterParty createNewChild(TreeMap<String, String> properties) { CounterParty counterParty = new CounterParty(); counterParty.setName(properties.get(NAME)); String aliasesString = properties.get(CounterParties.ALIAS); if(aliasesString!=null){ counterParty.setAliases(Utils.parseStringList(aliasesString)); } String accountNumberString = properties.get(CounterParties.ACCOUNTNUMBER); if(accountNumberString!=null){ ArrayList<String> numberList = Utils.parseStringList(accountNumberString); for(String s: numberList){ counterParty.addAccount(new BankAccount(s)); } } String addressLinesString = properties.get(CounterParties.ADDRESS); if(addressLinesString!=null){ counterParty.setAddressLines(Utils.parseStringList(addressLinesString)); } String bicString = properties.get(CounterParties.BIC); if(bicString!=null){ parseBicsString(counterParty, bicString); } String currenciesString = properties.get(CounterParties.CURRENCY); if(currenciesString!=null){ parseCurrenciesString(counterParty, currenciesString); } return counterParty; }
ffe69b81-6573-49a5-acc1-36528168c3d1
6
@Override public void hit(GameObject obj) { if (obj instanceof Bullet && !((Bullet)obj).enemy) { this.game.addScore(5); width = width / 2; height = height / 2; v = new Vector2D(Math.random() * MAX_SPEED, Math.random() * MAX_SPEED); if (width < 20 || height < 20) { dead = true; SoundManager.play(SoundManager.bangSmall); } else { Asteroid ast = new Asteroid(this.game, new Vector2D(s), new Vector2D(Math.random() * MAX_SPEED, Math.random() * MAX_SPEED)); ast.width = width; ast.height = height; this.game.add(ast); SoundManager.play(SoundManager.bangLarge); } game.explosion(s,200,100, Color.LIGHT_GRAY); } else if (obj instanceof EnergyShield && ((EnergyShield)obj).active) { Vector2D nV = new Vector2D(obj.game.getShip().v); obj.game.getShip().v = v; v = nV; } }
f0350faf-1e5d-404e-8fa6-c3be0c9209ad
8
public ArrayList<Edge> getEdges() { ArrayList<Edge> edges = new ArrayList<Edge>(); for (Integer u : adjList.keySet()) { for (Integer v : adjList.get(u)) { boolean found = false; for (Edge e : edges) { if ((e.u == u && e.v == v) || (e.v == u && e.u == v)) { found = true; break; } } if (!found) { edges.add(new Edge(u, v)); } } } return edges; }
d5d4431e-4728-40f9-80ef-74e15198bffc
4
private static void btxToXML_help(BTXParser in, XMLEventFactory ev, XMLEventWriter out) throws IOException, XMLStreamException { in.next(); // START_OBJECT ParseEventData d = in.getEventData(); if (d.objName.equals("<t")) { // Special for text type! // Single unnamed attribute for the text in.next(); // ATTRIBUTE out.add(ev.createCData(in.getEventData().getAttribute().asString())); in.next(); // END_OBJECT return; } int atCount = d.getRemainingAttributes(); Iterator<Attribute> theAttrs; if (atCount == 0) { theAttrs = null; } else { ArrayList<Attribute> attrs = new ArrayList<>(d.getRemainingAttributes()); do { in.next(); // ATTRIBUTE BTXAttribute attr = in.getEventData().getAttribute(); attrs.add(ev.createAttribute(attr.getName(), attr.asString())); atCount--; } while (atCount > 0); theAttrs = attrs.iterator(); } QName objName = new QName(d.objName); out.add(ev.createStartElement(objName, theAttrs, null)); atCount = d.getRemainingChildren(); while (atCount > 0) { atCount--; btxToXML_help(in, ev, out); } out.add(ev.createEndElement(objName, null)); in.next(); // END_OBJECT }
a6500595-f7c4-4793-940f-042f19fdb949
4
private static String searchEvent(String inputCommand) { String keyword = getParameter(inputCommand); if (keyword == null) return MESSAGE_INVALID_CMD; ArrayList<String> searchResults = new ArrayList<String>(); Iterator<String> eventIter = events.iterator(); while (eventIter.hasNext()) { String currentEvent = eventIter.next(); if (currentEvent.contains(keyword)) { searchResults.add(currentEvent); } } if (searchResults.isEmpty()) return MESSAGE_INVALID_EVENT; else return writeToString(searchResults); }
cfeee70f-28c0-4bac-b2fb-54c94368e57d
2
boolean isPalindrome(String str) { for (int i = 0; i < (str.length() / 2) + 1; ++i) { if (str.charAt(i) != str.charAt(str.length() - i - 1)) { return false; } } return true; }
c423420b-6193-406e-9e3c-cf92eb371440
9
public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException { // 读取配置文件 Properties config = new Properties(); config.load(new FileInputStream(GreatCustomerBak.class.getResource("/").getFile() + "config.properties")); // 读取代理列表文件地址 String proxyListFile = config.getProperty("proxylist.list"); // 读取最高延迟时间 int maxdelay = Integer.parseInt(config.getProperty("client.maxdelay", "5")); // 读取代理列表 System.out.println("开始读取代理文件"); BufferedReader reader = new BufferedReader(new FileReader(GreatCustomerBak.class.getResource("/").getFile() + proxyListFile)); String nextLine = null; List<Proxy> proxyList = new ArrayList<Proxy>(); while ((nextLine = reader.readLine()) != null) { try { if (!"".equals(nextLine.trim())) { Proxy proxyConfig = new Proxy(); // proxyConfig.setHost(nextLine.split("\\s")[0]); // proxyConfig.setPort(Integer.parseInt(nextLine.split("\\s")[1])); proxyConfig.setHost(nextLine.split("\\s")[0].split(":")[0]); proxyConfig.setPort(Integer.parseInt(nextLine.split("\\s")[0].split(":")[1])); proxyList.add(proxyConfig); } } catch (Exception e) { // 若处理中出现问题则跳过此行 continue; } } reader.close(); System.out.println("代理文件获取完毕,共获取代理[" + proxyList.size() + "]个"); // 连接流程 System.out.println("开始组装链接"); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); // 设置投票地址 String host = "http://r.gnavi.co.jp/enz725uz0000/menu4/"; HttpGet method = new HttpGet(host); System.out.println("目标[" + host + "]"); // 伪装头信息 method.setHeader("Accept", "*/*"); method.setHeader("Accept-Encoding", "gzip, deflate"); method.setHeader("Cache-Control", "no-cache"); method.setHeader("Connection", "keep-alive"); // method.setHeader("Content-Length", "18"); method.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); method.setHeader("Pragma", "no-cache"); method.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0"); method.setHeader("X-Requested-With", "XMLHttpRequest"); // 遍历代理列表进行发送 System.out.println("开始遍历请求过程"); int count = 0; for (int i = 0; i < proxyList.size(); i++) { // 设置代理 Proxy proxyConfig = proxyList.get(i); System.out.print((i + 1) + ".当前代理[" + proxyConfig + "]"); HttpHost proxy = new HttpHost(proxyConfig.getHost(), proxyConfig.getPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // 测试代理 boolean enable = false; try { HttpGet testMethod = new HttpGet("http://www.baidu.com"); HttpResponse testResponse = client.execute(testMethod); if (testResponse.getStatusLine().getStatusCode() == 200) { enable = true; } else { System.out.print("\t代理测试不可用"); } testMethod.releaseConnection(); } catch (Exception e) { System.out.print("\t代理测试不可用"); } // 测试通过后,开始发送 if (enable) { try { HttpResponse response = client.execute(method); // 打印输出 // System.out.println(response.getStatusLine().getStatusCode()); // 获取结果 if (response.getStatusLine().getStatusCode() == 200) { System.out.print("\t投票成功"); count++; } else { System.out.print("\t投票失败:" + response.getStatusLine().getStatusCode()); // if (response.getStatusLine().getStatusCode() == 500) { // System.out.println(response.getEntity().getContentType().getValue()); // System.out.println(EntityUtils.toString(response.getEntity(), "UTF-8")); // } } method.releaseConnection(); } catch (Exception e) { System.out.print("\t代理异常"); } // 计算伪装延迟 int delay = (int) (Math.random() * (maxdelay + 1)); System.out.print("\t[" + delay + "]秒后进行下一次请求"); Thread.sleep(delay * 1000); } System.out.println(); } // 处理结束,输出汇总信息 System.out.println("遍历请求完成,成功次数[" + count + "],实际增加可能小于此值"); }
9b306304-ee54-4ece-bae7-c0f79e9a1185
7
public static int dayToNum(String name) { int num; if (name.equals("Monday")) num = 1; else if (name.equals("Tuesday")) num = 2; else if (name.equals("Wednesday")) num=3; else if (name.equals("Thursday")) num = 4; else if (name.equals("Friday")) num=5; else if (name.equals("Saturday")) num = 6; else if (name.equals("Sunday")) num = 0; else num = -1; return num; }
4b3858d6-d850-423a-8e70-2c1a14fd180a
8
@Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) { final StringBuffer TBL=(StringBuffer)Resources.getResource("WEB SOCIALS TBL"); if(TBL!=null) return TBL.toString(); final List<String> socialVec=CMLib.socials().getSocialsList(); final StringBuffer msg=new StringBuffer("\n\r"); int col=0; int percent = 100/AT_MAX_COL; for(int i=0;i<socialVec.size();i++) { if (col == 0) { msg.append("<tr>"); // the bottom elements can be full width if there's // not enough to fill one row // ie. -X- -X- -X- // -X- -X- -X- // -----X----- // -----X----- if (i > socialVec.size() - AT_MAX_COL) percent = 100; } msg.append("<td"); if (percent == 100) msg.append(" colspan=\"" + AT_MAX_COL + "\""); //last element is width of remainder else msg.append(" width=\"" + percent + "%\""); msg.append(">"); msg.append(socialVec.get(i)); msg.append("</td>"); // finish the row if((percent == 100) || (++col)> (AT_MAX_COL-1 )) { msg.append("</tr>\n\r"); col=0; } } if (!msg.toString().endsWith("</tr>\n\r")) msg.append("</tr>\n\r"); Resources.submitResource("WEB SOCIALS TBL",msg); return clearWebMacros(msg); }
7ec83593-9266-4cc8-9ec9-37181b53ea14
7
static final public void Literal() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case NULL: jj_consume_token(NULL); break; case TRUE: jj_consume_token(TRUE); break; case FALSE: jj_consume_token(FALSE); break; case INTEGER: jj_consume_token(INTEGER); break; case CHARLITERAL: jj_consume_token(CHARLITERAL); break; case STRINGLITERAL: jj_consume_token(STRINGLITERAL); break; default: jj_la1[44] = jj_gen; jj_consume_token(-1); throw new ParseException(); } }
c5907da3-67af-4a2d-aa9d-83ee5f047f1d
3
public static Matrix getMatrix(int rows, int cols, DataType dataType) { Matrix matrix = null; switch (dataType) { case INTEGER: matrix = new MatrixInteger(rows, cols); break; case DOUBLE: matrix = new MatrixDouble(rows, cols); break; case ARRAY: matrix = new MatrixArray(rows, cols); break; } return matrix; }
8499a0df-024a-4d54-a5b1-57f72594af94
0
public void setFocused(boolean focus) { focused = focus; }
6311b598-299f-40c3-9a2b-5b111ae5e265
6
public Component getTableCellRendererComponent(JTable table, Object cell, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, cell, isSelected, hasFocus, row, column); setToolTipText(ToolTipHelper.makeToolTip((Card)table.getValueAt(row, DeckTable.getNameColumnNumber()))); if (!isSelected) { Color color = (Color)((DeckTableModel)table.getModel()).getRowColor(row); setBackground(color); if (color.equals(ColorCreator.BLUE) || color.equals(ColorCreator.RED)) { setForeground(Color.WHITE); } else { setForeground(Color.BLACK); } } if(cell instanceof Card) { setText(((Card)cell).getName()); } else if(cell instanceof Integer) { if ((Integer) cell == -1) { setText("--"); } else { setText(cell.toString()); } } else { setText(cell.toString()); } return this; }
f6057016-7908-49bf-9ed9-079bd53653f7
0
public VirtualReplayGainNode(Property property, PropertyTree parent) { super(property, parent); }
d47e2d1e-07f8-4b73-9000-80c327f5ce3c
8
public Suggestion createSuggestion(Set<Card> seenCards, Map <String, Card> cards, Map<Character, String> rooms){ Card rCard =new Card("Name", Card.CardType.ROOM); Random rand = new Random(); int randNum = rand.nextInt(cards.size()); ArrayList <Card> unseenC = new ArrayList <Card>(); for(String c : cards.keySet()){ unseenC.add(cards.get(c)); } for(Card c : seenCards){ for(int i = 0; i < unseenC.size(); i++) if(unseenC.get(i).getName().equals(c.getName())){ unseenC.remove(i); } } String pName=null; String wName=null; randNum = rand.nextInt(unseenC.size()); while(pName == null || wName == null){ if(unseenC.get(randNum).getCartype() == CardType.PERSON){ pName = unseenC.get(randNum).getName(); } if(unseenC.get(randNum).getCartype().equals(Card.CardType.WEAPON)){ wName = unseenC.get(randNum).getName(); } randNum = rand.nextInt(unseenC.size()); } rCard = cards.get(rooms.get(lastVisited)); Suggestion guess = new Suggestion(pName, wName, rCard.getName()); return guess; }
4a05d409-7c5f-43bd-a3e4-d56bc97c6a30
9
public Instances getDataSet() throws IOException { if (getDirectory() == null) throw new IOException("No directory/source has been specified"); String directoryPath = getDirectory().getAbsolutePath(); FastVector classes = new FastVector(); Enumeration enm = getStructure().classAttribute().enumerateValues(); while (enm.hasMoreElements()) classes.addElement(enm.nextElement()); Instances data = getStructure(); int fileCount = 0; for (int k = 0; k < classes.size(); k++) { String subdirPath = (String) classes.elementAt(k); File subdir = new File(directoryPath + File.separator + subdirPath); String[] files = subdir.list(); for (int j = 0; j < files.length; j++) { try { fileCount++; if (getDebug()) System.err.println( "processing " + fileCount + " : " + subdirPath + " : " + files[j]); double[] newInst = null; if (m_OutputFilename) newInst = new double[3]; else newInst = new double[2]; File txt = new File(directoryPath + File.separator + subdirPath + File.separator + files[j]); BufferedInputStream is; is = new BufferedInputStream(new FileInputStream(txt)); StringBuffer txtStr = new StringBuffer(); int c; while ((c = is.read()) != -1) { txtStr.append((char) c); } newInst[0] = (double) data.attribute(0).addStringValue(txtStr.toString()); if (m_OutputFilename) newInst[1] = (double) data.attribute(1).addStringValue(subdirPath + File.separator + files[j]); newInst[data.classIndex()] = (double) k; data.add(new Instance(1.0, newInst)); is.close(); } catch (Exception e) { System.err.println("failed to convert file: " + directoryPath + File.separator + subdirPath + File.separator + files[j]); } } } return data; }
e5feae7d-da24-4456-b077-df482f5e5cd9
5
public Collection<PearsonDictionaryEntry> filter() { List<PearsonDictionaryEntry> retVal = new ArrayList<PearsonDictionaryEntry>(); for (PearsonDictionaryEntry entry : entries) { if (entry.getHeadword() != null && headword != null) { if (entry.getHeadword().equals(headword)) { if (posTagConstrains.contains(entry.getPosTag())) { retVal.add(entry); } } else { retVal.add(entry); } } } return retVal; }
ec520705-53f8-46da-9929-412f5879d6ac
7
public void openDoors(Vector3f position, boolean playSound) { boolean worked = false; for(Door door : doors) { if(Math.abs(door.getTransform().getPosition().sub(position).length()) < 1.5f) { worked = true; door.open(0.5f, 3f); } } if(playSound) { for(int i = 0; i < exitPoints.size(); i ++) { if(Math.abs(exitPoints.get(i).sub(position).length()) < 1f) { Game.loadLevel(exitOffsets.get(i)); } } } if(!worked && playSound) AudioUtil.playAudio(misuseNoise, 0); }
65c2f515-96e9-4e47-ac8a-c7fc4a059e36
7
private void loadScene() { File stdSceneDir = new File("scenes"); if (!stdSceneDir.exists()) { stdSceneDir.mkdir(); } UIManager.put("FileChooser.cancelButtonText", LOCALIZER.getString(L_CANCEL)); UIManager.put("FileChooser.cancelButtonToolTipText", LOCALIZER.getString(L_CANCEL)); UIManager.put("FileChooser.openButtonText", LOCALIZER.getString(L_OPEN)); UIManager.put("FileChooser.openButtonToolTipText", LOCALIZER.getString(L_OPEN)); JFileChooser dlgOpen = new JFileChooser(); dlgOpen.setCurrentDirectory(stdSceneDir); dlgOpen.setSelectedFile(new File("scene.scnx")); // remove all standard filters while (dlgOpen.getChoosableFileFilters().length > 0) { dlgOpen.removeChoosableFileFilter(dlgOpen.getChoosableFileFilters()[0]); } dlgOpen.addChoosableFileFilter(new QuickFileFilter( "Scene Files (*.scnx)", ".scnx")); dlgOpen.addChoosableFileFilter(new QuickFileFilter("Animation Files (*.anix)", ".anix")); dlgOpen.setDialogTitle(LOCALIZER.getString(L_TITLE_OPEN)); if (dlgOpen.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { String extension = ((QuickFileFilter) dlgOpen.getFileFilter()).getFileExtension(); File file = dlgOpen.getSelectedFile(); switch (extension) { case ".scnx": Scene scene = sceneManager.loadScene(file); if (scene != null) { pModel.setProperty(PRP_CURRENT_FILE, file.getPath()); pModel.setScene(scene); pModel.fireEventListeners(EVT_SCENE_LOADED); pModel.fireRepaint(); } break; case ".anix": Recorder recorder = sceneManager.loadAnimation(file); if (recorder != null) { // TODO Recorder.overrideInstance(recorder); pModel.fireEventListeners(EVT_ANIMATION_LOADED); } break; default: // ignore } } }
6bb18bdc-4aa5-4830-8d91-b6627cf92059
8
public void parseParameters() throws IOException { int len = request.getContentLength(); if (len <= 0) { return; } if (len > this.maxPostSize) { log.warn("Parameters were not parsed because the size of the posted data was too big. " + "Use the maxPostSize attribute of the connector to resolve this if the " + "application should accept large POSTs."); return; } Parameters parameters = request.getParameters(); String enc = request.getCharacterEncoding(); parameters.setEncoding(enc != null ? enc : org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); if (useBodyEncodingForURI) { parameters .setQueryStringEncoding(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); } parameters.handleQueryParameters(); String contentType = request.getContentType(); if (contentType == null) contentType = ""; int semicolon = contentType.indexOf(';'); if (semicolon >= 0) { contentType = contentType.substring(0, semicolon).trim(); } else { contentType = contentType.trim(); } /* * if ("application/x-www-form-urlencoded".equals(contentType) || * "multipart/form-data".equals(contentType)) { * log.warn("The content type <" + contentType + "> is not supported"); * return; } */ int total = end + len; while (lastValid < total) { if (!fill()) { throw new EOFException(sm.getString("iib.eof.error")); } } // Processing parameters parameters.processParameters(buf, pos, len); }
30ab4975-2b1a-4382-863c-850217df5f04
3
public static void saveAccounts() { try { StringBuilder rawAccs = new StringBuilder(); File accountsFile = new File(Configuration.ACCOUNTS_DIR + File.separator + "Accounts.txt"); if (!accountsFile.exists()) { accountsFile.createNewFile(); } for (Account account : accounts) { rawAccs.append(account.toString()); } BufferedWriter bw = new BufferedWriter(new FileWriter(accountsFile)); bw.write(rawAccs.toString()); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
bab48204-0ddf-4416-a8a3-0a4d39388c83
5
static final void method159(int i) { if ((Class260.anInt3312 ^ 0xffffffff) < -1) { int i_1_ = 0; for (int i_2_ = 0; Class286_Sub1.consoleMessages.length > i_2_; i_2_++) { if (Class286_Sub1.consoleMessages[i_2_].indexOf("--> ") != -1 && ++i_1_ == Class260.anInt3312) { Class363.aString4461 = (Class286_Sub1.consoleMessages[i_2_].substring (2 + Class286_Sub1.consoleMessages[i_2_] .indexOf(">"))); break; } } } else Class363.aString4461 = ""; if (i != -615751774) aClass144_114 = null; anInt115++; }
95a881e7-daa3-47e6-9f21-1a19a3f8913d
5
@Override public List<Customer> searchCustomer(String term) { term = ".*" + term + ".*"; List<Customer> match = new ArrayList<Customer>(); for (Customer customer : getCustomers()) { if (customer.getAddress().matches(term) || new String(customer.getCustomerID() + "").matches(term) || customer.getName().matches(term) || customer.getSurname().matches(term)) match.add(customer); } return match; }
252a05b5-42b3-4823-b67e-28c08e7d2c99
7
public void run () { Socket s = null; try { String res; s = new Socket(Mailhost, 25); PrintStream p = new PrintStream(s.getOutputStream(),true); in = new DataInputStream(s.getInputStream()); expect("220", "greetings"); p.println("HELO " + "helohost"); expect("250", "helo"); int pos; p.println("MAIL FROM: " + From); expect("250", "mail from"); p.println("RCPT TO: " + To); expect("250", "rcpt to"); p.println("DATA"); expect("354", "data"); p.println("Subject: " + Subject); DataInputStream is = new DataInputStream(new StringBufferInputStream(Message)); try { while (true) { String ln = is.readLine(); if (ln==null) break; if (ln.equals(".")) ln = ".."; p.println(ln); } } catch (Exception e) {} p.println(""); p.println("."); expect("250","end of data"); p.println("QUIT"); expect("221", "quit"); } catch(Exception e) { result = e.getMessage(); CB.result(false,"Send error!"); return; } finally { try { if (s != null) s.close(); } catch(Exception e) { result = e.getMessage(); } } CB.result(true,"Mail sent successfully!"); }
97f41cad-858b-4208-98f1-93f8b44eace4
1
public void computerwins() { if(tie==true)//occupied[0][0]==occupied[0][1]&&occupied[0][1]==occupied[0][2]&&occupied[0][2]==occupied[1][0]&&occupied[1][0]==occupied[1][1]&&occupied[1][1]==occupied[1][2]&&occupied[1][2]==occupied[2][0]&&occupied[2][0]==occupied[2][1]&&occupied[2][1]==occupied[2][2]&&tie==true) System.out.println("It's a tie!"); else System.out.println("Computer Wins"); }
bc7c1eb7-7c45-42a3-bb77-2f7e85a50e70
9
@Override public Scorer scorer(LeafReaderContext context) throws IOException { assert termArrays.length != 0; final LeafReader reader = context.reader(); PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[termArrays.length]; final Terms fieldTerms = reader.terms(field); if (fieldTerms == null) { return null; } // TODO: move this check to createWeight to happen earlier to the user? if (fieldTerms.hasPositions() == false) { throw new IllegalStateException("field \"" + field + "\" was indexed without position data;" + " cannot run MultiPhraseQuery (phrase=" + getQuery() + ")"); } // Reuse single TermsEnum below: final TermsEnum termsEnum = fieldTerms.iterator(); float totalMatchCost = 0; for (int pos=0; pos<postingsFreqs.length; pos++) { Term[] terms = termArrays[pos]; List<PostingsEnum> postings = new ArrayList<>(); for (Term term : terms) { TermState termState = termContexts.get(term).get(context.ord); if (termState != null) { termsEnum.seekExact(term.bytes(), termState); postings.add(termsEnum.postings(null, PostingsEnum.POSITIONS)); totalMatchCost += PhraseQuery.termPositionsCost(termsEnum); } } if (postings.isEmpty()) { return null; } final PostingsEnum postingsEnum; if (postings.size() == 1) { postingsEnum = postings.get(0); } else { postingsEnum = new UnionPostingsEnum(postings); } postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, positions[pos], terms); } // sort by increasing docFreq order if (slop == 0) { ArrayUtil.timSort(postingsFreqs); } if (slop == 0) { return new ExactPhraseScorer(this, postingsFreqs, similarity.simScorer(stats, context), needsScores, totalMatchCost); } else { return new SloppyPhraseScorer(this, postingsFreqs, slop, similarity.simScorer(stats, context), needsScores, totalMatchCost); } }
043410dd-dfda-4cd3-b1ad-643ca6f8490d
9
public Tetrad(BoundedGrid<Block> grid) { blocks = new Block[4]; for (int i = 0; i < 4; i++) { blocks[i] = new Block(); } Color color = Color.WHITE; Location[] locs = new Location[4]; int shape = 0; shape = ((int) (Math.random() * 7)); switch (shape) { case 0: // I shape color = Color.RED; locs[1] = new Location(0, 4); locs[0] = new Location(1, 4); locs[2] = new Location(2, 4); locs[3] = new Location(3, 4); break; case 1: // T shape color = Color.GRAY; locs[0] = new Location(0, 4); locs[1] = new Location(1, 4); locs[2] = new Location(0, 3); locs[3] = new Location(0, 5); break; case 2: // O Shape color = Color.CYAN; locs[0] = new Location(0, 4); locs[1] = new Location(0, 3); locs[2] = new Location(1, 4); locs[3] = new Location(1, 3); break; case 3:// L Shape color = Color.YELLOW; locs[1] = new Location(0, 3); locs[0] = new Location(1, 3); locs[2] = new Location(2, 3); locs[3] = new Location(2, 4); break; case 4: // J Shape color = Color.MAGENTA; locs[1] = new Location(0, 4); locs[0] = new Location(1, 4); locs[2] = new Location(2, 4); locs[3] = new Location(2, 3); break; case 5: // S Shape color = Color.BLUE; locs[1] = new Location(1, 3); locs[0] = new Location(1, 4); locs[2] = new Location(0, 4); locs[3] = new Location(0, 5); break; case 6: // Z shape color = Color.GREEN; locs[1] = new Location(0, 3); locs[0] = new Location(0, 4); locs[2] = new Location(1, 4); locs[3] = new Location(1, 5); break; } for (int i = 0; i < 4; i++) { blocks[i].setColor(color); } addToLocations(grid, locs); }
c8faa86a-e426-478e-8132-fda00f9223f7
8
public String toStringExtended() { String info = (this.type + "-section named '" + this.name + "', id (" + this.reference + ") on level: " + level + "; complete path: " + this.getPath() + "\n\t- "); if (this.subsections != null && this.sectionCount() != 0 && this.getSections() != null) { info += (this.sectionCount() + " subsection(s) named: "); for (String name : this.subsectionsNames()) { info += name + ", "; } info = info.substring(0, info.lastIndexOf(", ")); } else { info += ("no subsections"); } info += ("\n\t- "); if (this.properties != null && this.propertyCount() != 0 && this.getProperties() != null) { info += (this.propertyCount() + " propertie(s) named: "); for (String name : this.getPropertyNames()) { info += name + ", "; } info = info.substring(0, info.lastIndexOf(", ")); } else { info += ("no properties appended"); } return info; }
9e4cdd47-f363-45aa-86e2-4f259a3abecb
4
private JLabel menuItem(String title, final String desc, final int index) { final JLabel btn = new JLabel(title); btn.setHorizontalAlignment(JLabel.CENTER); btn.setForeground(Color.WHITE); btn.setBackground(new Color(0, 0, 0, 0)); btn.setFont(new Font("Serif", 0, 40)); btn.setPreferredSize(new Dimension(1000, 60)); btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); final WinMenu that = this; btn.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent arg0) {} public void mouseClicked(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) { cliqueMenu(index); } public void mouseEntered(MouseEvent arg0) { if (desc != null && desc.length() > 0) { txInfo.setText("\n" + desc); panBottom.setVisible(true); } btn.setOpaque(true); btn.setBackground(new Color(0, 0, 0, 140)); that.repaint(); } public void mouseExited(MouseEvent arg0) { if (desc != null && desc.length() > 0) { panBottom.setVisible(false); } btn.setBackground(new Color(0, 0, 0, 0)); that.repaint(); } }); return btn; }
cbc77573-65d9-4897-ac68-614dd1bdd3d6
8
private PickResult pickGeomAny (PickShape pickShape) { Node obj = null; int i; SceneGraphPath[] sgpa = null; if (pickRootBG != null) { sgpa = pickRootBG.pickAll(pickShape); } else if (pickRootL != null) { sgpa = pickRootL.pickAll(pickShape); } if (sgpa == null) return null; // no match for(i=0; i<sgpa.length; i++) { obj = sgpa[i].getObject(); PickResult pr = new PickResult(sgpa[i], pickShape); if(obj instanceof Shape3D) { if(((Shape3D) obj).intersect(sgpa[i], pickShape)) { return pr; } } else if (obj instanceof Morph) { if(((Morph) obj).intersect(sgpa[i], pickShape)){ return pr; } } } return null; }
3a662685-993d-46f7-a633-3e9f990a2d41
5
private void agrupar() { Agrupamento agrupamento; switch(agrupamentoAtual){ case TODOS: agrupamento = criarAgrupamentoTodos(); break; case ANO: agrupamento = criarAgrupamentoPorAno(); break; case ATIVO: agrupamento = criarAgrupamentoPorAtividade(); break; case GRAU: agrupamento = criarAgrupamentoPorGrau(); break; case LINHADEPESQUISA: agrupamento = criarAgrupamentoPorLinhaDePesquisa(); break; default: throw new AssertionError(agrupamentoAtual.name()); } this.tblAgrupamentoAlunosViewer.setAgrupamento(agrupamento); }
911cc33f-14f0-4c1e-9425-ac1693b27494
6
private static byte[][] generateSubkeys(byte[] key) { byte[][] tmp = new byte[Nb * (Nr + 1)][4]; int i = 0; while (i < Nk) { tmp[i][0] = key[i * 4]; tmp[i][1] = key[i * 4 + 1]; tmp[i][2] = key[i * 4 + 2]; tmp[i][3] = key[i * 4 + 3]; i++; } i = Nk; while (i < Nb * (Nr + 1)) { byte[] temp = new byte[4]; for(int k = 0;k<4;k++) temp[k] = tmp[i-1][k]; if (i % Nk == 0) { temp = SubWord(rotateWord(temp)); temp[0] = (byte) (temp[0] ^ (Rcon[i / Nk] & 0xff)); } else if (Nk > 6 && i % Nk == 4) { temp = SubWord(temp); } tmp[i] = xor_func(tmp[i - Nk], temp); i++; } return tmp; }
6c7aea1d-9b66-461b-91f1-81f589e25684
2
public static boolean probarConexion(String url,String user , String pass){ java.sql.Connection con = null; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = java.sql.DriverManager.getConnection(url, user, pass); if (con != null) { return true; } } catch (ClassNotFoundException | SQLException e) { return false; } return false; }
cca922e4-6155-40ab-a637-1f2167a335e7
2
private SelectionTransition findFirstNonEmptyTransition() { for (SelectionTransition transition : transitions) { if(!transition.isEmpty()) return transition; } return null; }
2668d123-9585-4597-98ae-9fe672d9ef7d
2
public static int indexOf(int[] arr, int val){ for (int i = 0 ; i < arr.length; i++){ if (arr[i] == val) return i; } return -1; }
07f2665d-98cf-4055-b47b-9768f7d148a4
9
static final void method432(int i, int i_0_, int i_1_, int i_2_) { anInt619++; i = i * Class213.aNode_Sub27_2512.aClass320_Sub25_7274.method3776(false) >> 8; if ((i_1_ ^ 0xffffffff) != 0 || Class377_Sub1.aBoolean8775) { if ((i_1_ ^ 0xffffffff) != 0 && ((Class313.anInt4013 ^ 0xffffffff) != (i_1_ ^ 0xffffffff) || !Class36.method390(-122)) && (i ^ 0xffffffff) != -1 && !Class377_Sub1.aBoolean8775) { CacheNode_Sub14_Sub2.method2354(SeekableFile.index6, i, false, 0, i_1_, i_2_, false); EntityNode_Sub7.method979(17285); } } else { Class320_Sub2.method3685(-118); } if ((Class313.anInt4013 ^ 0xffffffff) != (i_1_ ^ 0xffffffff)) { EntityNode_Sub1.aNode_Sub9_Sub1_5929 = null; } if (i_0_ <= 112) { method432(-89, 11, 106, 125); } Class313.anInt4013 = i_1_; }
0ab69a6b-69cf-4ce9-a0cd-d79a64a62031
5
public static Consumable loadConsumable(int ID) { BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/consumables")); String line; while((line = reader.readLine()) != null) { final String[] temp = line.split(";"); if(Integer.parseInt(temp[0]) == ID) { reader.close(); return new Consumable() {{ setFlavorText(temp[1]); for(int x = 2; x<temp.length; x++) { addStat(Integer.parseInt(temp[x])); addEffect(Integer.parseInt(temp[x+1])); addValue(Float.parseFloat(temp[x+2])); addPercent(Boolean.parseBoolean(temp[x+3])); addDuration(Float.parseFloat(temp[x+4])); x += 4; } }}; } } reader.close(); } catch (FileNotFoundException e) { System.out.println("The consumable database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Consumable database failed to load!"); e.printStackTrace(); } return null; }
78db8769-3599-419d-bb4c-27ffa2a03999
4
private void checkUndeclaredVariable(ParseTree node) { if (node.attribute.equals("IDENTIFIER") && !containsVariable(node.value) && !undeclaredVariables.contains(node.value)) { System.out.println("Undeclared Variable: " + node.value); undeclaredVariables.add(node.value); } for (int i = 0; i < node.children.size(); i++) checkUndeclaredVariable(node.children.get(i)); }
62cbc004-f719-467a-a5c0-a87a2d610c45
6
private boolean setHoustonMap(String mapName){ Image mapImage = null; ImageIcon imageIcon; boolean hasFile = false; //for displaying message on the panel. startPanel.appendText(">> Connecting... \n" + ">> Destination: " + urlStr + " \n"); if (url_status){//If URL Internet connection is available, downloads the image. try { URL url = new URL(urlStr + mapName); //get the Houston map from a remote Server imageIcon = new ImageIcon(url); mapImage = imageIcon.getImage(); startPanel.appendText(">> Received Houston city Map... \n"); hasFile = true; }catch(MalformedURLException em) { try{ // If the network connection is not available, get the local image file. startPanel.appendText(">> Network resources are unavailable... \n" + ">> Use the local file instead \n"); mapImage = getLocalImage(mapName, startPanel); hasFile = true; }catch(Exception ex){ printError(startPanel, ex, mapName); return false; } }catch(Exception e){ printError(startPanel, e, mapName); } }else{//If URL connection is not available, use the local image file. try{ // Get the local image instead. startPanel.appendText(">> Network resource file are not available... \n" + ">> Use the local files instead \n"); mapImage = getLocalImage(mapName, startPanel); hasFile = true; }catch(Exception exc){ printError(startPanel, exc, mapName); } } if (hasFile){ mapCanvas = new MapCanvas(mapImage); return true; } return false; }
1571bad0-74f4-438d-bead-a0dfa4c1b46c
4
@Override public void sequence(String id, String sequence, String quality) { // Testing the strings (if some are null the method will stop here) if ((sequence == null) || (quality == null) || sequence.isEmpty() || quality.isEmpty()) { return; } super.addValue(sequence.length()); }
df9182a7-30e1-44b2-a691-699b51933457
2
@Override public int getAddress(Identifier var, int size) throws Exception { addressRecord a = usedMem.get(var); if(a != null) { if(a.size != size) { throw new Exception("varaible accessed as different size than expected"); } return a.address; } // Globals are allocated at negative offsets freeAddress = freeAddress - size; usedMem.put(var, new addressRecord(freeAddress, size)); return freeAddress; }
365b8092-22a4-4546-bbad-eb2223f2d3aa
8
SignatureInputStream(Hessian2Input in) throws IOException { try { _in = in; byte []fingerprint = null; String keyAlgorithm = null; String algorithm = null; byte []encKey = null; int len = in.readInt(); for (int i = 0; i < len; i++) { String header = in.readString(); if ("fingerprint".equals(header)) fingerprint = in.readBytes(); else if ("key-algorithm".equals(header)) keyAlgorithm = in.readString(); else if ("algorithm".equals(header)) algorithm = in.readString(); else if ("key".equals(header)) encKey = in.readBytes(); else throw new IOException("'" + header + "' is an unexpected header"); } Cipher keyCipher = Cipher.getInstance(keyAlgorithm); keyCipher.init(Cipher.UNWRAP_MODE, _cert); Key key = keyCipher.unwrap(encKey, algorithm, Cipher.SECRET_KEY); _bodyIn = _in.readInputStream(); _mac = Mac.getInstance(algorithm); _mac.init(key); } catch (RuntimeException e) { throw e; } catch (IOException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
ea0485e5-79d1-4b12-9ba6-01e4d70df1a0
0
@Override public String getName() { return name; }
0793f8aa-9981-4f4f-8868-056b3ab58908
5
public int size(int niveau){ int size = 0; switch(niveau){ case 1: size = beginner.size(); break; case 2: size = intermediate.size(); break; case 3: size = advanced.size(); break; case 4: size = expert.size(); break; case 5: size = grandmaster.size(); break; default: System.out.println("ERROR ! size = 0 !"); } return size; }
45126465-3738-425a-b2b4-53d9ca331571
2
public void execForAbonent(Abonent abonent) { Queue<Msg> messageQueue = messages.get(abonent.getAddress()); if (messageQueue == null) { return; } while (!messageQueue.isEmpty()) { Msg message = messageQueue.poll(); message.exec(abonent); } }
f99cc6a9-0251-4eb7-aa95-91d04079ddb8
7
protected static void initFilters(boolean loader, Vector<String> classnames) { int i; int n; String classname; Class cls; String[] ext; String desc; FileSourcedConverter converter; ExtensionFileFilter filter; if (loader) m_LoaderFileFilters = new Vector<ExtensionFileFilter>(); else m_SaverFileFilters = new Vector<ExtensionFileFilter>(); for (i = 0; i < classnames.size(); i++) { classname = (String) classnames.get(i); // get data from converter try { cls = Class.forName(classname); converter = (FileSourcedConverter) cls.newInstance(); ext = converter.getFileExtensions(); desc = converter.getFileDescription(); } catch (Exception e) { cls = null; converter = null; ext = new String[0]; desc = ""; } if (converter == null) continue; // loader? if (loader) { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_LoaderFileFilters.add(filter); } } else { for (n = 0; n < ext.length; n++) { filter = new ExtensionFileFilter(ext[n], desc + " (*" + ext[n] + ")"); m_SaverFileFilters.add(filter); } } } }
46b93bce-3849-4076-b3fd-d785cb48b3d0
8
public void merge(Iterable<? extends Player> updateDatabase) { for (Player rhs : updateDatabase) { boolean matched = false; boolean conflict = false; for(String key : rhs.getIds().all()) { String id = rhs.getIds().get(key); Map<String,Player> repo = index.get(key); if (null != repo) { Player original = repo.get(id); if (null != original) { matched = true; if (! match(rhs,original)) { conflict = true; } } } } if (conflict) { conflicts.add(rhs); } else if (matched) { // No-Op } else { missing.add(rhs); } } }
4b691403-2bcf-468b-87b3-6c523b4734db
7
public static boolean getStationsData(String pathName) { DocumentBuilderFactory docBuilderFactory; DocumentBuilder docBuilder; Document document = null; try { docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilder = docBuilderFactory.newDocumentBuilder(); document = docBuilder.parse(new File(pathName)); document.getDocumentElement().normalize(); } catch (ParserConfigurationException e) { System.err.println("XML Format error."); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Write/Read error."); e.printStackTrace(); return false; } catch (SAXException e) { System.err.println("SAXException."); e.printStackTrace(); return false; } NodeList names = document.getElementsByTagName("name"); NodeList coordinates = document.getElementsByTagName("coordinates"); NodeList state = document.getElementsByTagName("value"); ArrayList<String> sNames = new ArrayList<String>(); ArrayList<String[]> sCoordinates = new ArrayList<String[]>(); ArrayList<String> sStates = new ArrayList<String>(); String tempStr; int j = 0; for (int i = 0; i < names.getLength(); i++) { if (names.item(i).getParentNode().getNodeName() == "Placemark" || coordinates.item(i).getParentNode().getNodeName() == "Placemark") { sNames.add(names.item(i).getTextContent()); tempStr = coordinates.item(j).getTextContent() .replaceAll("0.0", ""); sCoordinates.add(tempStr.split(",")); tempStr = state.item(j).getTextContent(); if (tempStr.equals("1")) { sStates.add("true"); } else { sStates.add("false"); } j++; } } return IOFiles.writeStationsFile("cleanData/stationsData.txt", sNames, sCoordinates, sStates); }
205d9cf3-13df-42ff-8e83-ded4cfc3513f
8
public static void unjar(Path file, Path to) throws IOException { if (Files.notExists(to)) { Files.createDirectories(to); } try (JarFile jarFile = new JarFile(file.toFile())) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); Path entryPath = to.resolve(entry.getName()); if (!entry.isDirectory()) { if (Files.notExists(entryPath.getParent())) { Files.createDirectories(entryPath.getParent()); } if (Files.isRegularFile(entryPath)) { if (Files.size(entryPath) == entry.getSize()) { continue; } else { Files.delete(entryPath); } } Files.createFile(entryPath); try (OutputStream os = Files.newOutputStream(entryPath)) { InputStream is = jarFile.getInputStream(entry); byte[] ba = new byte[1024]; int read; while ((read = is.read(ba)) != -1) { if (read > 0) { os.write(ba, 0, read); } } } } } } }
2b3eea38-1572-4921-87fd-67115ee0d1b5
4
public Reservation modifyReservation(int reservationId, double startTime, int duration, int numPE) { Reservation currReservation = getReservation(reservationId); if(currReservation == null) { logger.info("Error modifying reservation, ID is invalid"); return null; } int resId = currReservation.getResourceID(); // check all the values first boolean success = validateValue(startTime, duration, numPE); if (!success) { return null; } Reservation newReservation = currReservation.clone(); try { newReservation.setStartTime(startTime); newReservation.setDurationTime(duration); newReservation.setNumPE(numPE); // creates the message to be sent to the grid resource ReservationMessage message = new ReservationMessage(super.get_id(), resId, newReservation); message.setMessageType(MessageType.MODIFY); // sends the message gets the reply from the grid resource ReservationMessage reply = sendReservationMessage(message); // If error code is NO_ERROR, the reservation has been successful. ErrorType error = reply.getErrorCode(); if(error == ErrorType.NO_ERROR) { reservations_.remove(newReservation.getID()); reservations_.put(newReservation.getID(), newReservation); return newReservation; } else { logger.info("Error modifying reservation."); } } catch (Exception ex) { logger.log(Level.WARNING,"Error modifying reservation.", ex); } return null; }
0c932d7d-18f0-454c-b2e8-b5bab353fd7f
6
private static void twoPlayers(int numOfCards) { frame.setLayout(new BorderLayout()); // If a game has already been started // cardHolderPanel has to be cleared before // it can be used properly again. cardHolderPanel.removeAll(); // Adds the cardHolderPanel to the frame. frame.add(cardHolderPanel, BorderLayout.CENTER); // The user is asked for his/her name. If "null" is given as name, a // new pop up window will appear and ask for the player's name again. // If cancel is pressed, null is returned and this method is ended. // Both players have to give their name. String playerOneName = JOptionPane .showInputDialog("What is your name, first player?"); if(playerOneName == null) { return; } while (playerOneName.equals("null")) { playerOneName = JOptionPane .showInputDialog("Not valid name. \n What is your name, first player?"); if(playerOneName == null) { return; } } String playerTwoName = JOptionPane .showInputDialog("What is your name, second player?"); if (playerTwoName == null) { return; } while (playerTwoName.equals("null")) { playerTwoName = JOptionPane .showInputDialog("Not valid name. \n What is your name, second player?"); if (playerTwoName == null) { return; } } // A new playerHolder with both players. PlayerHolder players = new PlayerHolder(playerOneName, playerTwoName); // A new cardHolder is created and with it all the cards, actionListeners // and the game is started. new CardHolder(numOfCards, players, cardHolderPanel); // Updates the cardHolderPanel and sets it visible cardHolderPanel.updateUI(); backgroundPanel.setVisible(false); cardHolderPanel.setVisible(true); }
2b93ace7-cedc-49b6-88d1-77fd1cf30a93
0
@Test public void testHasMatchedWord() { assertTrue(_dictionary.hasMatchedWord("356937")); }
75cd1e6c-db5b-47f9-94fd-8a809ff0d0e2
9
protected boolean isSubTypeOf(final Value value, final Value expected) { Type expectedType = ((BasicValue) expected).getType(); Type type = ((BasicValue) value).getType(); switch (expectedType.getSort()) { case Type.INT: case Type.FLOAT: case Type.LONG: case Type.DOUBLE: return type.equals(expectedType); case Type.ARRAY: case Type.OBJECT: if ("Lnull;".equals(type.getDescriptor())) { return true; } else if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) { return isAssignableFrom(expectedType, type); } else { return false; } default: throw new Error("Internal error"); } }
2dac3df4-677d-4886-8c06-3984c9e1c9a4
9
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if((tickID==Tickable.TICKID_MOB) &&(affected instanceof MOB) &&(affected != invoker)) { final MOB M=(MOB)affected; final MOB mob=invoker(); final Room R=CMLib.map().roomLocation(M); if((R==null)||(this.path==null)||(this.path.size()==0)) { unInvoke(); return false; } int direction = path.remove(0).intValue(); final Room nextR=R.getRoomInDir(direction); if(nextR==null) { unInvoke(); return false; } CMLib.tracking().walk(M, direction, false, true, false, true); if(M.location()==nextR) { final CMMsg msg2=CMClass.getMsg(mob,nextR,CMMsg.MSG_LOOK,null); nextR.executeMsg(mob,msg2); } else unInvoke(); } return true; }
14fef1fd-2142-46be-908f-786f9c5bf6fd
1
@Override public void run() { Loader loader = new Loader(); try { loader.setUrl(url); loader.load(); } catch (Exception e) { e.printStackTrace(); } }