method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
61a71299-1b0e-4d67-9056-510dbfaf294f
0
public int getHeight() { return height; }
8eb492b9-c4bb-4786-b588-227291208b69
2
private boolean jj_3_36() { if (jj_3R_53()) return true; if (jj_3R_54()) return true; return false; }
4d02da4d-d26d-4da0-88b8-233d957684ae
5
private static boolean isPrimitiveOrString(Object target) { if (target instanceof String) { return true; } Class<?> classOfPrimitive = target.getClass(); for (Class<?> standardPrimitive : PRIMITIVE_TYPES) { if (standardPrimitive.isAssignableFrom(classOfPrimitive)) { return true; } } return false; }
2c74f4eb-ee2e-45de-a9d7-e10603dba38c
9
void ChangeSwitchTexture(line_t line, boolean useAgain) { int texTop; int texMid; int texBot; int i; int sound; if (!useAgain) line.special = 0; texTop = LL.sides[line.sidenum[0]].toptexture; texMid = LL.sides[line.sidenum[0]].midtexture; texBot = LL.sides[line.sidenum[0]].bottomtexture; sound = sfxenum_t.sfx_swtchn.ordinal(); // EXIT SWITCH? if (line.special == 11) sound = sfxenum_t.sfx_swtchx.ordinal(); for (i = 0; i < numswitches * 2; i++) { if (switchlist[i] == texTop) { S.StartSound(buttonlist[0].soundorg, sound); LL.sides[line.sidenum[0]].toptexture = (short) switchlist[i ^ 1]; if (useAgain) StartButton(line, bwhere_e.top, switchlist[i], BUTTONTIME); return; } else { if (switchlist[i] == texMid) { S.StartSound(buttonlist[0].soundorg, sound); LL.sides[line.sidenum[0]].midtexture = (short) switchlist[i ^ 1]; if (useAgain) StartButton(line, bwhere_e.middle, switchlist[i], BUTTONTIME); return; } else { if (switchlist[i] == texBot) { S.StartSound(buttonlist[0].soundorg, sound); LL.sides[line.sidenum[0]].bottomtexture = (short) switchlist[i ^ 1]; if (useAgain) StartButton(line, bwhere_e.bottom, switchlist[i], BUTTONTIME); return; } } } } }
7d38550c-2ace-4f0f-98cd-f7cc20b8565e
5
public void draw(Graphics2D g){ for(int h = 0; h < tiles.length; h++){ for(int w = 0; w < tiles[0].length; w++){ if(tiles[h][w] != null){ tiles[h][w].draw(g); } } } if(character != null){ character.draw(g); character.getFeetHitbox().draw(g); } for(Bullet b: bullets){ b.draw(g); } }
427479f4-b5bf-42cd-bf88-0b9bad4fb0d3
5
public static List <String> savedFiles(String prefix) { final List <String> allSaved = new List <String> () ; final File savesDir = new File("saves/") ; for (File saved : savesDir.listFiles()) { final String name = saved.getName() ; if (! name.endsWith(".rep")) continue ; if (prefix == null) { if (! name.endsWith(CURRENT_SAVE+".rep")) continue ; } else if (! name.startsWith(prefix)) continue ; allSaved.add(name) ; } return allSaved ; }
edd639b1-baad-4705-ba56-ec5b5ae5258b
9
private void connect() { if(server!=null) { stop(); return; } String ip=ipField.getText(); String port=portField.getText(); if(ip==null || ip.equals("")) { JOptionPane.showMessageDialog(SocketTestServer.this, "No IP Address. Please enter IP Address", "Error connecting", JOptionPane.ERROR_MESSAGE); ipField.requestFocus(); ipField.selectAll(); return; } if(port==null || port.equals("")) { JOptionPane.showMessageDialog(SocketTestServer.this, "No Port number. Please enter Port number", "Error connecting", JOptionPane.ERROR_MESSAGE); portField.requestFocus(); portField.selectAll(); return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if(!Util.checkHost(ip)) { JOptionPane.showMessageDialog(SocketTestServer.this, "Bad IP Address", "Error connecting", JOptionPane.ERROR_MESSAGE); ipField.requestFocus(); ipField.selectAll(); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } int portNo = 0; try { portNo=Integer.parseInt(port); } catch (Exception e) { JOptionPane.showMessageDialog(SocketTestServer.this, "Bad Port number. Please enter Port number", "Error connecting", JOptionPane.ERROR_MESSAGE); portField.requestFocus(); portField.selectAll(); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } try { InetAddress bindAddr=null; if(!ip.equals("0.0.0.0")) bindAddr = InetAddress.getByName(ip); else bindAddr = null; server = new ServerSocket(portNo,1,bindAddr); ipField.setEditable(false); portField.setEditable(false); connectButton.setText("Stop Listening"); connectButton.setMnemonic('S'); connectButton.setToolTipText("Stop Listening"); } catch (Exception e) { error(e.getMessage(), "Starting Server at "+portNo); setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return; } setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); messagesField.setText("> Server Started on Port: "+portNo+NEW_LINE); writeTrace("> Server Started on Port: "+portNo); append("> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); socketServer=SocketServer.handle(this,server); th = socketServer.getTh(); //sendField.requestFocus(); }
ebdba70e-d18f-457c-ae28-ee8ad6dd8487
3
public int[] _getChildInformation(int key) throws RegistryErrorException { try { return (int[])queryInfoKey.invoke(null, new Object[] {new Integer(key)}); } catch (InvocationTargetException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalArgumentException ex) { throw new RegistryErrorException(ex.getMessage()); } catch (IllegalAccessException ex) { throw new RegistryErrorException(ex.getMessage()); } }
ffb3200d-a0a0-462d-9145-c930c78d02aa
0
protected Icon getIcon() { java.net.URL url = getClass().getResource("/ICON/expand_group.gif"); return new ImageIcon(url); }
6a60bcd3-3272-4718-9d87-f6bd655522e9
9
public void updateEvt(){ xfond-=1; if(keysPressed[KeyEvent.VK_UP]) p.setDeplacement(Player.SAUT); p.update(); for(int i=0;i<plateformes.size();i++){ if(p.boundingBox.intersects(plateformes.get(i))){ switch(plateformes.get(i).PositionRelative(p)){ case Plateforme.DESSUS: p.finSaut(plateformes.get(i).y-p.spriteH); break; case Plateforme.DESSOUS: p.renvoieSaut(plateformes.get(i).y+plateformes.get(i).height+p.spriteH); break; case Plateforme.DROITE: p.renvoie(plateformes.get(i).x+plateformes.get(i).width+p.spriteW,4,-0.05); break; case Plateforme.GAUCHE: p.renvoie(plateformes.get(i).x-p.spriteW,-4,0.05); break; } } plateformes.get(i).translateX((int)-2); } if(p.boundingBox.x+p.boundingBox.width<0 || p.boundingBox.y+p.boundingBox.height>600) reset(); }
133fa417-600e-4925-9d1d-9e14be541f38
4
static private int jjMoveStringLiteralDfa7_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(5, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(6, active0); return 7; } switch(curChar) { case 99: return jjMoveStringLiteralDfa8_0(active0, 0x2000000L); case 111: return jjMoveStringLiteralDfa8_0(active0, 0x20000000000L); default : break; } return jjStartNfa_0(6, active0); }
4eb29fc8-106e-4763-a760-fb06dc2351a1
7
public void testPresent1() { try { TreeNode result = contains(new TreeNode("node"), mkChain(new String[]{ "node" })); assertTrue(null, "Failed to locate the only node of a leaf!", result != null && result.getData() != null && result.getData().equals("node") && result.getBranch() != null && result.getBranch().length == 0); } catch(NotFound exn) { fail(exn, "You can not locate the only node of a leaf!"); } catch(TreeException exn) { fail(exn, "An unexpected `TreeException` was thrown!"); } catch(Throwable exn) { fail(exn, "Unexpected exception thrown: " + exn.getClass().getName()); } // end of try-catch } // end of method testPresent1
fde79433-054c-42ae-997d-7d151d07f659
6
public void schreibeLevelRaeume(List<Raum> raumListe) { readRaeume(); //ID Liste der vorhandenen Räume List<Integer> idSammlung = new ArrayList<Integer>(); for(Raum raum : _sammlParser.getSammlung()) { idSammlung.add(raum.getId()); } // komplett neue Räume hinzufügen for(Raum raum : raumListe) { if(!idSammlung.contains(raum.getId())) { _sammlParser.getSammlung().add(raum); } } // vorhandene Räume ersetzen List<Raum> raeume = _sammlParser.getSammlung(); int l = raeume.size(); for(Raum raum : raumListe) // gehen neue räume durch { for(int i = 0; i < l; i++) // und vergleichen mit den vorhandenen { Raum r = raeume.get(i); if(raum.getId() == r.getId()) // wenn gleich, so solls überschreiben { _sammlParser.getSammlung().set(i, raum); break; } } } _sammlParser.schreibeXml(); }
1adfc269-7ca4-4db4-a40a-f52ae397a9d9
9
private static TreePath findPath(JTree tree, TreePath root, String[] nodes, int depth) { GenomeTreeNode node = (GenomeTreeNode)root.getLastPathComponent(); GenomeTreeNode child = null; TreePath parent = root; TreePath node_path = null; String cur_node_name = nodes[depth].trim().replaceAll(AppPaths.CHAR_TO_REPLACE, " "); boolean found; boolean first = true; if ((node.name.replaceAll(AppPaths.CHAR_TO_REPLACE, " ")).equals(cur_node_name)) { while(depth < nodes.length){ // If at end, return match if (depth == nodes.length-1) { node_path = parent.pathByAddingChild(node); break; }else if(node.getChildCount() > 0){ found = false; depth++; cur_node_name = nodes[depth].trim().replaceAll(AppPaths.CHAR_TO_REPLACE, " "); for(int i=0; !found && i < node.getChildCount(); ++i){ child = (GenomeTreeNode)node.getChildAt(i); if ((child.name.replaceAll(AppPaths.CHAR_TO_REPLACE, " ")).equals(cur_node_name)) { if(!first){ parent = parent.pathByAddingChild(node); }else{first = false;} node = child; found = true; break; } } if(!found){ break; } }else{ break; } } } return node_path; }
b3ee3281-05a3-4a1c-9b93-cbddb3e5398f
9
public List<Contato> buscaDocumentos(String condicao) { List<Contato> listaContatos = new ArrayList<Contato>(); JSONObject json, documento, dadosContato; JSONArray arrayDocumentos; String url = getHost() + ":" + getPorta() + "/" + getNomebanco() + "/" + getLocalBusca(); /* * Verifica a url usada para busca: - se url == * "_all_docs?include_docs=true", a condicao iniciará com & - se url == * "_design/listaContato/_view/todos", a condicao iniciará com ? */ if (getLocalBusca().contains("_all") && !condicao.equals("todos")) { String condicaoModificada = "&" + condicao.substring(1, condicao.length()); condicao = condicaoModificada; } if (!condicao.equals("todos")) url += condicao; String jsonString = getRegistro(url); /* * Se a busca falhou com uma visão que pode não estar criada, a url de * busca irá mudar para a padrão. A variável pegaDocumento altera de * acordo com a url de busca, pois é ela que contem todos os dados de um * registro de Contato. Caso a url seja usando a visão criada, essa * variável recebe o valor "value". Caso contrário, em que a url seja a * padrão, essa variável recebe o valor "doc". */ if (jsonString == null) { setLocalBusca("_all_docs?include_docs=true"); pegaDocumento = "doc"; url = getHost() + ":" + getPorta() + "/" + getNomebanco() + "/" + getLocalBusca(); if (!condicao.equals("todos")) url += condicao; jsonString = getRegistro(url); } try { json = new JSONObject(jsonString.toString()); arrayDocumentos = json.getJSONArray("rows"); for (int i = 0; i < arrayDocumentos.length(); i++) { try { Contato contato = new Contato(); documento = arrayDocumentos.getJSONObject(i); dadosContato = documento.getJSONObject(pegaDocumento); contato.setId(dadosContato.getString("_id")); contato.setNome(dadosContato.getString("nome")); contato.setApelido(dadosContato.getString("apelido")); contato.setDataNascimento(dadosContato .getString("datanascimento")); contato.setTelefoneResidencial(dadosContato .getString("telres")); contato.setTelefoneCelular(dadosContato.getString("telcel")); contato.setCidade(dadosContato.getString("cidade")); contato.setEstado(dadosContato.getString("estado")); listaContatos.add(contato); } catch (NumberFormatException e) { } } return listaContatos; } catch (JSONException e1) { System.out .println("Erro ao manipular JSON do registro! - buscaDocumentos()/AcessoBanco.java"); } catch (NullPointerException e2) { System.out .println("Erro na busca por documentos - formatação da URL - buscaDocumentos()/AcessoBanco.java"); } return listaContatos; }
a32f94e8-8bf3-41fb-b20a-784cc11662b1
1
public void testGetPartialConverter() { PartialConverter c = ConverterManager.getInstance().getPartialConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new TimeOfDay()); assertEquals(ReadablePartial.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPartialConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} }
79de8512-ec28-4771-996c-acbaa782fe89
8
public static void main(String[] args) { try { final Class<?> clazz = Class.forName("com.effectivejava.rtti.PrivateClass"); showPrivateFields(clazz); callPrivateMethods(clazz); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6ded8538-5754-4d68-b612-c84ed151e1d1
0
public void gamble() { }
528c2e27-a657-4006-bb08-4886fd440e62
6
@Override public String toString() { String result = getName() + ", average=" + getAverage() + ", " + getProgram() + ", Undergrad, "; if (this.universityOne != null) result += this.universityOne + "-" + (this.universityOneAccept ? "admitted" : "rejected") ; if (this.universityTwo != null) result += ", " + this.universityTwo + "-" + (this.universityTwoAccept ? "admitted" : "rejected") ; if (this.universityThree != null) result += ", " + this.universityThree + "-" + (this.universityThreeAccept ? "admitted" : "rejected") ; return result; }
e3811f92-9ece-41ab-ad7f-cce12fb49ecd
4
protected void addHandled(Handled h) { // Handled must be of the supported class if (!getSupportedClass().isInstance(h)) return; if (h != null && !this.handleds.contains(h)) { this.handleds.add(h); // Also starts the handler if it wasn't already if (!this.started) this.started = true; } }
3f97cc0b-d4e3-4b00-80b1-e19cd67ea857
5
public void kanondoda() { for(int i = 0;i < feedback.size();i++) { for(int j = 0;j < kp.size();j++) { for(int k = 0;k < robotar.size();k++) { if(kp.get(j).touches(robotar.get(k)) && kp.get(j).getID() != robotar.get(k).getID()) { kp.get(j).setLife(false); robotar.get(k).setLife(false); feedback.get(i).increaseKills(); } } } } }
12e8656e-6fed-4900-b232-09a492d7275f
6
public ResultSet preencherTabelaATividadeGESTAO(String codDepartamento) throws SQLException { Connection conexao = null; PreparedStatement comando = null; ResultSet resultado = null; try { conexao = BancoDadosUtil.getConnection(); comando = conexao.prepareStatement(SQL_SELECT_TABELA); comando.setString(1, codDepartamento); resultado = comando.executeQuery(); conexao.commit(); } catch (Exception e) { if (conexao != null) { conexao.rollback(); } throw new RuntimeException(e); } finally { if (comando != null && !comando.isClosed()) { comando.close(); } if (conexao != null && !conexao.isClosed()) { conexao.close(); } } return resultado; }
50ef502e-9ffa-4e7c-8955-3ca17ee86c74
4
public Transferable createTransferable(JComponent comp) { TreePath[] paths = cardTree.getSelectionPaths(); if (paths != null) { ArrayList<DefaultMutableTreeNode> copies = new ArrayList<DefaultMutableTreeNode>(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) paths[0].getLastPathComponent(); DefaultMutableTreeNode copy = (DefaultMutableTreeNode) node.clone(); copies.add(copy); for (int i = 1; i < paths.length; i++) { DefaultMutableTreeNode next = (DefaultMutableTreeNode)paths[i].getLastPathComponent(); if (next.getLevel() < node.getLevel()) { break; } else if(next.getLevel() > node.getLevel()) { copy.add((DefaultMutableTreeNode)next.clone()); } else { copies.add((DefaultMutableTreeNode)next.clone()); } } DefaultMutableTreeNode[] nodes = copies.toArray(new DefaultMutableTreeNode[copies.size()]); return new NodesTransferable(nodes); } return null; }
eee7f55b-b34a-4848-8eff-c390ef2ad081
6
@Test public void testLoadPeople() { //set up test variables HumanPlayer human = game.getHuman(); boolean equal = false; java.awt.Point testLocation; java.awt.Color testColor; ArrayList<ComputerPlayer> computers = game.getComputer(); ComputerPlayer testComp; //test human player //set to human name, starting location and color testLocation = new java.awt.Point(0,8); testColor = new java.awt.Color(255,0,0); Assert.assertEquals("Miss Scarlett", human.getName()); if(testLocation.equals(human.getLocation())) equal = true; Assert.assertEquals(equal, true); equal = false; if(testColor.equals(human.getColor())) equal = true; Assert.assertEquals(equal, true); equal = false; //test second computer //set to computer 2 name, starting location and color testComp = computers.get(1); testLocation = new java.awt.Point(24,8); testColor = new java.awt.Color(255,255,255); Assert.assertEquals("Mrs. White", testComp.getName()); if(testLocation.equals(testComp.getLocation())) equal = true; Assert.assertEquals(equal, true); equal = false; if(testColor.equals(testComp.getColor())) equal = true; Assert.assertEquals(equal, true); equal = false; //test fourth computer //set to computer 4 name, starting location and color testComp = computers.get(3); testLocation = new java.awt.Point(17,24); testColor = new java.awt.Color(0,0,255); Assert.assertEquals("Mrs. Peacock", testComp.getName()); if(testLocation.equals(testComp.getLocation())) equal = true; Assert.assertEquals(equal, true); equal = false; if(testColor.equals(testComp.getColor())) equal = true; Assert.assertEquals(equal, true); equal = false; }
e9ab4534-dfb8-4a57-bdf9-b48c94e111d7
4
private String urlEncode(Map<String, String> map) { StringBuilder sb = new StringBuilder(); for (String key : map.keySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(key); String value = map.get(key); if (value != null) { sb.append("="); try { sb.append(URLEncoder.encode(value, "utf8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("impossible to reach", e); } } } return sb.toString(); }
a4d38ee5-b387-4aec-ab04-9dc66c3c85b9
4
public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) { if (semiMajorAxis < 0) throw new RuntimeException("ellipse semimajor axis can't be negative"); if (semiMinorAxis < 0) throw new RuntimeException("ellipse semiminor axis can't be negative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*semiMajorAxis); double hs = factorY(2*semiMinorAxis); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); }
59b2145f-260f-4fce-b977-53067d9af911
7
public static void delete(JoeTree tree, OutlineLayoutManager layout, boolean deleteMode) { Node youngestNode = tree.getYoungestInSelection(); if (youngestNode == null) { return; } Node parent = youngestNode.getParent(); CompoundUndoableReplace undoable = new CompoundUndoableReplace(parent, deleteMode); int startDeleting = 0; if (tree.isWholeDocumentSelected()) { // Abort if the doc is empty. if (tree.isDocumentEmpty()) { return; } // Swap in a new node for the first node since a doc always has at least one child of root. Node newNode = new NodeImpl(tree,""); newNode.setDepth(0); undoable.addPrimitive(new PrimitiveUndoableReplace(parent, youngestNode, newNode)); startDeleting++; } // Iterate over the remaining selected nodes deleting each one JoeNodeList nodeList = tree.getSelectedNodes(); int deleteCount = 0; for (int i = startDeleting, limit = nodeList.size(); i < limit; i++) { Node node = nodeList.get(i); // Abort if node is not editable if (!node.isEditable()) { continue; } undoable.addPrimitive(new PrimitiveUndoableReplace(parent, node, null)); deleteCount++; } if (!undoable.isEmpty()) { if (deleteCount == 1) { undoable.setName("Delete Node"); } else { undoable.setName(new StringBuffer().append("Delete ").append(deleteCount).append(" Nodes").toString()); } tree.getDocument().getUndoQueue().add(undoable); undoable.redo(); } return; }
88461dac-42ca-4aea-a247-8392df39914f
8
protected synchronized void showCatPage(int page) { int pageStart = page * tabPageSize; if (pageStart > tabButtons.size()) { throw new IllegalArgumentException("Illegal tab page number: " + page); } int p = 0; for (GenericButton b : tabButtons) { if (p >= pageStart && p < pageStart + tabPageSize) { b.setEnabled(true).setVisible(true).setDirty(true); } else if (b.isVisible()) { b.setEnabled(false).setVisible(false).setDirty(true); } ++p; } if (page * tabPageSize >= tabButtons.size()) { btnTabRight.setEnabled(false).setVisible(false).setDirty(true); } else if (!btnTabRight.isVisible()) { btnTabRight.setEnabled(true).setVisible(true).setDirty(true); } if (page <= 0) { btnTabLeft.setEnabled(false).setVisible(false).setDirty(true); } else { btnTabLeft.setEnabled(true).setVisible(true).setDirty(true); } tabPage = page; }
94fef019-bd73-45dc-910b-34644c2ad523
3
static private int jjMoveStringLiteralDfa15_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(13, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(14, active0); return 15; } switch(curChar) { case 105: return jjMoveStringLiteralDfa16_0(active0, 0x2000000L); default : break; } return jjStartNfa_0(14, active0); }
b26aaaa5-621a-4973-b68c-22ca6d6e40eb
7
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); HashMap<Character, Character> hm = new HashMap<Character, Character>(); hm.put('(', ')'); hm.put('[', ']'); hm.put('{', '}'); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c=='(' || c=='[' || c=='{') stack.push(c); else{ if(stack.empty() || c!=hm.get(stack.pop())) return false; } } if(!stack.empty()) return false; return true; }
a96635a6-ef11-4320-862e-88aece657a79
0
public void loseHealth(double damage){ headArmorSlot.reduceDamage(damage); bodyArmorSlot.reduceDamage(damage); hero.applyDamage(damage); }
aa0e3422-c471-41d1-b632-22631b890afa
7
public Vector searchWidth(int id){ int visitados[][] = new int [thisVert.size()][2]; Vector<Integer> fila = new Vector<Integer>(); Vector<Integer> adjacents = new Vector<Integer> (); Vector<Integer> ordem = new Vector<Integer> (); int v; int aux = -1; for (int i=0;i<thisVert.size();i++) { if(thisVert.get(i).GetId()!=id) { visitados[i][1]=0; visitados[i][0]=thisVert.get(i).GetId(); } else { visitados[i][1]=1; visitados[i][0]=id; } } fila.add(id); while(!fila.isEmpty()) { v = fila.get(0); for (int i=0;i<getAdjacents(v).size();i++) { adjacents = getAdjacents(v); for (int j=0; j<thisVert.size();j++) { if(visitados[j][0]==adjacents.get(i)) { aux=j; } } if(visitados[aux][1]==0) { visitados[aux][1]=1; fila.add(visitados[aux][0]); } } ordem.add(fila.get(0)); fila.remove(0); } return ordem; }
5b7cad39-1324-421b-b34a-272b7876927b
4
public static long[] radixSort2(long[] a) { int w = 64; int d = 1; long[] b = null; for (int p = 0; p < w/d; p++) { long c[] = new long[1<<d]; // the next three for loops implement counting-sort b = new long[a.length]; for (int i = 0; i < a.length; i++) c[(int)(a[i] >> d*p)&((1<<d)-1)]++; for (int i = 1; i < 1<<d; i++) c[i] += c[i-1]; for (int i = a.length-1; i >= 0; i--) b[(int) --c[(int) ((a[i] >> d*p)&((1<<d)-1))]] = a[i]; a = b; } return b; }
3f0da744-1ffc-4696-a0c5-9e1fa5c860bb
6
protected void readSampleData() { boolean read_ready = false; boolean write_ready = false; int mode = header.mode(); int i; do { for (i = 0; i < num_subbands; ++i) read_ready = subbands[i].read_sampledata(stream); do { for (i = 0; i < num_subbands; ++i) write_ready = subbands[i].put_next_sample(which_channels,filter1, filter2); filter1.calculate_pcm_samples(buffer); if ((which_channels == OutputChannels.BOTH_CHANNELS) && (mode != Header.SINGLE_CHANNEL)) filter2.calculate_pcm_samples(buffer); } while (!write_ready); } while (!read_ready); }
e0703c13-e340-4f6c-b8e6-c5ec1e84a60f
4
public static CellHandle[] getCellHandlesFromSheet( String strRange, WorkSheetHandle sheet ) { CellHandle[] retCells; StringTokenizer cellTokenizer = new StringTokenizer( strRange, "," ); ArrayList cells = new ArrayList(); do { String element = (String) cellTokenizer.nextElement(); if( element.contains( ":" ) ) { CellRange aRange = new CellRange( sheet.getSheetName() + "!" + strRange, sheet.wbh, true ); cells.addAll( aRange.getCellList() ); } else { CellHandle aCell; try { aCell = sheet.getCell( element ); } catch( Exception ce ) { aCell = sheet.add( null, element ); } if( aCell != null ) { cells.add( aCell ); } } } while( cellTokenizer.hasMoreElements() ); retCells = new CellHandle[cells.size()]; retCells = (CellHandle[]) cells.toArray( retCells ); return retCells; }
792813ac-cff0-426a-b29b-72f13762f27f
9
public ArrayList<ArrayList<Course>> removeConflicts(ArrayList<ArrayList<Course>> list) { boolean[] switches = new boolean[list.size()]; int boolCounter = 0; boolean done = false; for(ArrayList<Course> temp: list) { for(int k = 0; k < temp.size() && done == false; k++) { for(int i = k+1; i <= temp.size()-1 && done == false; i++) { if(conflict(temp.get(k), temp.get(i))) { switches[boolCounter] = true; done = true; } } } done = false; boolCounter++; } //find the indexes of the switches ArrayList<Integer> indexOfConflicts = new ArrayList<Integer>(); for(int i = 0; i < switches.length; i++) { if(switches[i] == false) indexOfConflicts.add(i); //add the indexes of valid conflicts to the list } //make a new list of only valid combinations from the indexes of the valid switches ArrayList<ArrayList<Course>> validList = new ArrayList<ArrayList<Course>>(); for(int validIndex : indexOfConflicts) { validList.add(list.get(validIndex)); } return validList; }
b5d8d4d0-0c29-43d0-83a4-0ed286ad620b
4
@Override public String getOutput(int id) { switch (direction) { case "n": return "solid\n" + " {\n" + " \"id\" \" " + id++ + "\"\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y + ys) + " " + (z) + ") (" + (xs + x) + " " + (y) + " " + (z) + ") (" + (xs + x) + " " + (y + ys) + " " + (zs + z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y + ys) + " " + (z + zs) + ") (" + (x) + " " + (y) + " " + (z) + ") (" + (x) + " " + (ys + y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (ys + y) + " " + (zs + z) + ") (" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[-1 0 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+x + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (ys + y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ") (" + (xs + x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[-1 0 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+y + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (ys + y) + " " + (zs + z) + ") (" + (x) + " " + (ys + y) + " " + (z) + ") (" + (x + xs) + " " + (ys + y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " editor\n" + " {\n" + " \"color\" \"0 146 143\"\n" + " \"visgroupshown\" \"1\"\n" + " \"visgroupautoshown\" \"1\"\n" + " }\n" + " }"; case "s": return "solid\n" + " {\n" + " \"id\" \" " + id++ + "\"\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y + ys) + " " + (z) + ") (" + (x) + " " + (y) + " " + (zs + z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (z + zs) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ") (" + (x + xs) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (ys + y) + " " + (z) + ") (" + (x + xs) + " " + (y) + " " + (z + zs) + ") (" + (x) + " " + (y) + " " + (z + zs) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[-1 0 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+x + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ") (" + (x) + " " + (y + ys) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[-1 0 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+y + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (zs + z) + ") (" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " editor\n" + " {\n" + " \"color\" \"0 146 143\"\n" + " \"visgroupshown\" \"1\"\n" + " \"visgroupautoshown\" \"1\"\n" + " }\n" + " }"; case "e": return "solid\n" + " {\n" + " \"id\" \" " + id++ + "\"\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (z + zs) + ") (" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y + ys) + " " + (z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z + zs) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (ys + y) + " " + (z + zs) + ") (" + (x + xs) + " " + (y) + " " + (z + zs) + ") (" + (x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+x + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ") (" + (x) + " " + (y + ys) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+y + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (zs + z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z + zs) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " editor\n" + " {\n" + " \"color\" \"0 146 143\"\n" + " \"visgroupshown\" \"1\"\n" + " \"visgroupautoshown\" \"1\"\n" + " }\n" + " }"; case "w": return "solid\n" + " {\n" + " \"id\" \" " + id++ + "\"\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y + ys) + " " + (z + zs) + ") (" + (x) + " " + (y + ys) + " " + (z) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x + xs) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z + zs) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y) + " " + (z + zs) + ") (" + (x) + " " + (y + ys) + " " + (z + zs) + ") (" + (x + xs) + " " + (y + ys) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+x + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y + ys) + " " + (z) + ") (" + (x) + " " + (y) + " " + (z) + ") (" + (x + xs) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_BLENDMEASURE2\"\n" + " \"uaxis\" \"[1 0 0 0] 0.25\"\n" + " \"vaxis\" \"[0 -1 0 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" //+y + " side\n" + " {\n" + " \"id\" \"" + (id++) + "\"\n" + " \"plane\" \"(" + (x) + " " + (y + ys) + " " + (zs + z) + ") (" + (x) + " " + (y) + " " + (z + zs) + ") (" + (x) + " " + (y) + " " + (z) + ")\" \n" + " \"material\" \"DEV/DEV_MEASUREWALL01A\"\n" + " \"uaxis\" \"[0 1 0 0] 0.25\"\n" + " \"vaxis\" \"[0 0 -1 0] 0.25\"\n" + " \"rotation\" \"0\"\n" + " \"lightmapscale\" \"16\"\n" + " \"smoothing_groups\" \"0\"\n" + " }\n" + " editor\n" + " {\n" + " \"color\" \"0 146 143\"\n" + " \"visgroupshown\" \"1\"\n" + " \"visgroupautoshown\" \"1\"\n" + " }\n" + " }"; default: //bad parse return ""; } }
f61073ef-8acc-4c82-abd0-b7768fb4f088
2
public void writePlayers(String key, Iterable<? extends Player> players) throws KeyNotUpdatedException, KeyNotFoundException { List<? extends Player> sortedPlayers = Lists.newArrayList(players); Collections.sort(sortedPlayers, this.ordering); target.writePlayers(key,sortedPlayers); }
c9c62bae-cffe-41f7-b645-49bfb8fec566
1
public static final synchronized BundleInfo getDefault() { if (DEFAULT == null) { DEFAULT = new BundleInfo(BundleInfo.class); } return DEFAULT; }
580401ba-4783-47f9-9a16-447a9ccc9b4d
6
public static void agentmain(String agentArgs, Instrumentation inst) throws ClassNotFoundException, UnmodifiableClassException, InterruptedException { Class<?>[] allLoadedClasses = inst.getAllLoadedClasses(); inst.addTransformer(new HiroTransformer(), true); for (Class<?> clazz : allLoadedClasses) { try { for (Field f : clazz.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class)) { inst.retransformClasses(clazz); continue; } } } catch (UnmodifiableClassException e) { System.out.println("Unmodifiable " + clazz); } } }
88d47de3-d3aa-427d-85f9-fdc8e0601be4
2
public void buildMainPanel(List<MyFile> filesList) { if (filesList.isEmpty()) { buildInfoPanel("Le répertoire est vide"); } else { if (infoLabel != null) { infoLabel.setVisible(false); } tableau = new JTable(new MyJTableModel(filesList)); mainPanel.add(tableau.getTableHeader(), BorderLayout.NORTH); mainPanel.add(tableau, BorderLayout.CENTER); tableau.setVisible(true); this.pack(); } }
dbba7a2d-408c-4184-abae-5860e575a9eb
5
@Override public void saveArrayToFile(String path, List<Integer> list) { // checking input parameter for null if (path == null || list == null) { throw new IllegalArgumentException("ERROR: url is not specified!"); } try { File file = new File(path); PrintWriter printWriter = new PrintWriter(file); if (file.exists()) { for (int foo: list) { printWriter.print(String.valueOf(foo)); printWriter.print(" "); } } printWriter.close(); } catch (IOException e) { throw new RuntimeException("Error while saving to file: " + path); } }
0ca1222d-dd87-4dfb-ad6c-d9db8315e885
9
public String toString() { switch(this) { case HUMAN: return "Human"; case ELF: return "Elf"; case DWARROW: return "Dwarrow"; case GOBLIN: return "Goblin"; case ANCIENT: return "Ancient"; case CULTIST: return "Cultist"; case CRONK: return "Cronk"; case SORCEROR: return "Sorceror"; case ORC: return "Orc"; } assert false; return "ERROR"; }
56136505-243e-42d7-ad59-096a3876c151
5
public void obfuscateProject() { String obfuscatedContent; int totalSizeTransfert = 0; int numberOfFiles = 0; int fileSizeTransfert; createDestinationDirectories(); for (FileObfuscationStructure structure : projectFileObfuscationStructureList) { File obfuscatedFile = new File(destinationDir + "\\" + structure.getFileName()); obfuscatedContent = handler.replaceVariables(structure, commentRemover, whiteSpacesRemover); fileSizeTransfert = McbcFileUtils.putFileContent(obfuscatedFile, obfuscatedContent); totalSizeTransfert += fileSizeTransfert; numberOfFiles++; } if (!copyOnlySource) { for (File file : projectFiles) { String fileExtension = McbcFileUtils.getFilenameExtension(file.getName()); if (!Constants.PHP_EXTENSION_TABLE.contains(fileExtension) && file.isFile()) { File newFile = new File(destinationDir + "\\" + file.getAbsolutePath().substring( sourceDir.length())); fileSizeTransfert = McbcFileUtils.copyFile(file, newFile); numberOfFiles++; totalSizeTransfert += fileSizeTransfert; } } } }
ec2aa614-f7e9-4035-9e82-25d8b7e48db3
8
private Element verifyLicense(HttpServletRequest request, Element elResult) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Element elResponse = new Element ("response"); long now = (new Date()).getTime(); String method = request.getMethod(); logger.info("connection method is " + method); String license = request.getParameter("license"); String identifier = request.getParameter("identifier"); LicenseDAO ld = CommonCache.getLicense(license); if (license == null || identifier == null || "".equals(license) || "".equals(identifier)) { elResponse.setAttribute("success", "0"); elResponse.setAttribute("errmsg", "Verify license failed: Parameter(s) are not valid."); } else if (ld == null || ld.getIntVal("id") <= 0) { elResponse.setAttribute("success", "0"); elResponse.setAttribute("errmsg", "Verify license failed: The license is not valid."); } else { int maxNumber = ld.getIntVal("max_number"); HashMap<String, LicenseInUseDAO> liudList = CommonCache.getLicenseInUseList(ld.getIntVal("id")); LicenseInUseDAO liud = liudList.get(identifier); if (liud == null) { // the client is not in use if (liudList.size() >= maxNumber) { // no more valid license elResponse.setAttribute("success", "0"); elResponse.setAttribute("errmsg", "Verify license failed: The License has reached its limitation."); } else { liud = new LicenseInUseDAO(); liud.setField("license_id", ld.getIntVal("id")); liud.setField("client_identifier", identifier); liud.setField("last_access", dateFormat.format(now)); liud.save(); elResponse.setAttribute("license", license); elResponse.setAttribute("last_access", liud.getStrVal("last_access")); elResponse.setAttribute("success", "1"); } } else { liud.setField("last_access", dateFormat.format(now)); liud.save(); elResponse.setAttribute("license", license); elResponse.setAttribute("last_access", liud.getStrVal("last_access")); elResponse.setAttribute("success", "1"); } } /* String errMsg = ""; LicenseDAO ld = null; for(int i = 0; i < ll.size(); i ++) { ld = ll.get(i); String lastAccess = ld.getStrVal("last_access"); logger.info("last access is " + lastAccess); if (lastAccess == null) { // first time use ld.setField("last_access", now); ld.save(); elResponse.setAttribute("license", license); elResponse.setAttribute("last_access", ld.getStrVal("last_access")); elResponse.setAttribute("success", "1"); valid = true; break; } else { try { Date lastAccessD = dateFormat.parse(lastAccess); long lastAccessL = lastAccessD.getTime(); if ((now - lastAccessL) > (CommonAjax.DEFAULT_LICENSE_ACTIVE_TIME )) { ld.setField("last_access", dateFormat.format(now)); ld.save(); elResponse.setAttribute("license", license); elResponse.setAttribute("last_access", ld.getStrVal("last_access")); elResponse.setAttribute("success", "1"); valid = true; break; } } catch (Exception e) { logger.error("Verify license failed: " + e.getMessage(), e); } } } // end for loop if (!valid) { elResponse.setAttribute("success", "0"); elResponse.setAttribute("errmsg", "Verify license failed: The license is not valid."); } */ elResult.addContent(elResponse); return elResult; }
0b6c4442-4e0c-4026-aa73-bcc84bb814fb
1
@Override public void draw(Graphics page) { BulletImage.drawImage(page, xLocation, yLocation);//Draws the plane on the component //Draws the collision Border if(this.getBorderVisibility()) { drawCollisionBorder(page,xLocation,yLocation,BulletImage.getWidth(),BulletImage.getHeight()); } }
59624dac-6840-40a1-86a7-4db621120b82
8
@Override public SeekStatus seekCeil(BytesRef text) throws IOException { if (ord < numTerms && ord >= 0) { final int cmp = term().compareTo(text); if (cmp == 0) { return SeekStatus.FOUND; } else if (cmp > 0) { reset(); } } // linear scan while (true) { final BytesRef term = next(); if (term == null) { return SeekStatus.END; } final int cmp = term.compareTo(text); if (cmp > 0) { return SeekStatus.NOT_FOUND; } else if (cmp == 0) { return SeekStatus.FOUND; } } }
995a38b0-ec2a-4b5f-b2d6-beebbbff03f5
7
@Override public int read() throws IOException { // We still have data left from before if(currentIndex < inflatedBytes) { // convert signed byte to unsigned int int val = o[currentIndex] < 0 ? o[currentIndex] + 256 : o[currentIndex]; currentIndex++; return val; } // There is no more data to extract if(inflater.finished()) { return -1; } // Read data until we can provide new data do { if(-1 == Util.readBlocking(b, this.inputStream)) { return -1; } inflater.setInput(b); try { inflatedBytes = inflater.inflate(o, 0, o.length); } catch(DataFormatException e) { throw new IOException(e); } } while(inflatedBytes == 0); currentIndex = 1; // convert signed byte to unsigned int return o[0] < 0 ? o[0] + 256 : o[0]; }
21d76747-4123-4a8f-b0f7-8f2ce1a161b9
4
@Override public void handle(HttpExchange exchange) throws IOException { System.out.println("In build city handler"); String responseMessage = ""; if(exchange.getRequestMethod().toLowerCase().equals("post")) { try { //TODO verify cookie method String unvalidatedCookie = exchange.getRequestHeaders().get("Cookie").get(0); CookieParams cookie = Cookie.verifyCookie(unvalidatedCookie, translator); BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody())); String inputLine; StringBuffer requestJson = new StringBuffer(); while ((inputLine = in.readLine()) != null) { requestJson.append(inputLine); } in.close(); System.out.println(requestJson); BuildCityRequest request = (BuildCityRequest) translator.translateFrom(requestJson.toString(), BuildCityRequest.class); exchange.getRequestBody().close(); ServerModel serverModel = this.movesFacade.buildCity(request, cookie); System.out.println("Request Accepted!"); // create cookie for user List<String> cookies = new ArrayList<String>(); // send success response headers exchange.getResponseHeaders().put("Set-cookie", cookies); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); movesLog.store(new BuildCityCommand(movesFacade, request, cookie)); String name = serverModel.getPlayerByID(cookie.getPlayerID()).getName(); serverModel.getLog().addMessage(new LogEntry(name+ " built a city", serverModel.getPlayerByID(cookie.getPlayerID()).getName())); responseMessage = translator.translateTo(serverModel); // TODO join game in gameModels list } catch (InvalidCookieException | InvalidMovesRequest | ClientModelException e) { // else send error message System.out.println("unrecognized / invalid build city request"); responseMessage = e.getMessage(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } } else { // unsupported request method responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is no supported!"; exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); } //set "Content-Type: text/plain" header List<String> contentTypes = new ArrayList<String>(); String type = "text/plain"; contentTypes.add(type); exchange.getResponseHeaders().put("Content-type", contentTypes); if (!responseMessage.isEmpty()) { //send failure response message OutputStreamWriter writer = new OutputStreamWriter( exchange.getResponseBody()); writer.write(responseMessage); writer.flush(); writer.close(); } exchange.getResponseBody().close(); }
80c2fe6e-0e2c-42ef-9d71-57f47160706a
0
public void setjButtonQuitter(JButton jButtonQuitter) { this.jButtonQuitter = jButtonQuitter; }
c472c78f-dc1b-4694-8f6f-09d4de64a55a
1
@Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { getStageManager().setStatge(StageManager.STAGE_MENUE, null); } }
b156392f-a152-4c80-983d-e06325ce7175
1
public void draw() { for(int x = 0; x<downfall.size(); x++) { downfall.get(x).draw(); } }
26641a8d-fba1-4f38-8d22-3ab2ea17e852
6
public static ArrayList<Media> checkMediaReservation(ArrayList<MediaCopy> mediaList) { try { if(conn == null || conn.isClosed()){ conn = DatabaseConnection.getConnection(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ArrayList<Media> foundReservations = new ArrayList<Media>(); Statement stmnt = null; String sql = ""; ResultSet res = null; for(Media m : mediaList) { try { stmnt = conn.createStatement(); sql = "SELECT * FROM Reservations WHERE product_id = " + m.getMediaID() + " AND (type = 'DVD' OR type = 'CD')"; res = stmnt.executeQuery(sql); if(res.next()) foundReservations.add(m); } catch (SQLException e) { System.out.println(e); } } return foundReservations; }
ae4b769d-6f59-4a3c-8e01-1db49117bcd4
3
public static ArrayList<User> getUsers() { ArrayList<User> users = new ArrayList<User>(); File f = new File("users.txt"); try { FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String s = ""; while ((s = br.readLine()) != null) { if (s.trim().length() > 5) { User u = new User(); String[] comp = splitLine(s, 2); u.setUsername(comp[0]); //System.out.println(comp[0]); u.setBalance(Double.valueOf(comp[1])); u.setUserStock(getUserStocks()); users.add(u); } } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return users; }
2c50ce47-7658-46da-ba77-90d7edd1da92
3
private void save() { String path=""; try { path = SBStringUtils.getAppPath("data"); File file = new File(path, fileName); CSVWriter writer = new CSVWriter(new FileWriter(file)); for (int i=0;i<defaults.size();i++){ ArrayList<String> d = defaults.get(i); for (int j=0;j<d.size();j++) writer.put(d.get(j).toString()); writer.nl(); } writer.close(); } catch (Exception e){ e.printStackTrace(); } }
a1f5eb2a-133d-4a2d-ad44-62db0b981d17
4
public void printLevelOrder(Node x) { if (x != null) { LinkedList list = new LinkedList(x); Node nykyinen = list.getHeadNode(); while (list.getSize() != 0) { System.out.println(list.getHeadKey()); // Jos jonon päällä on vasen lapsi, laitetaan se jonoon if (nykyinen.left != null) { list.add(nykyinen.left); } // Jos jonon päällä on oikea lapsi, laitetaan se jonoon if (nykyinen.right != null) { list.add(nykyinen.right); } list.removeHead(); nykyinen = list.getHeadNode(); } } }
e5153832-bbe1-4a1b-a5f2-7092751b0553
9
public void acceptTrainingSet(final TrainingSetEvent e) { if (e.isStructureOnly()) { // no need to build a classifier, instead just generate a dummy // BatchClassifierEvent in order to pass on instance structure to // any listeners - eg. PredictionAppender can use it to determine // the final structure of instances with predictions appended BatchClassifierEvent ce = new BatchClassifierEvent(this, m_Classifier, new DataSetEvent(this, e.getTrainingSet()), new DataSetEvent(this, e.getTrainingSet()), e.getSetNumber(), e.getMaxSetNumber()); notifyBatchClassifierListeners(ce); return; } if (m_reject) { //block(true); if (m_log != null) { m_log.statusMessage(statusMessagePrefix() + "BUSY. Can't accept data " + "at this time."); m_log.logMessage("[Classifier] " + statusMessagePrefix() + " BUSY. Can't accept data at this time."); } return; } // Do some initialization if this is the first set of the first run if (e.getRunNumber() == 1 && e.getSetNumber() == 1) { // m_oldText = m_visual.getText(); // store the training header m_trainingSet = new Instances(e.getTrainingSet(), 0); m_state = BUILDING_MODEL; String msg = "[Classifier] " + statusMessagePrefix() + " starting executor pool (" + getExecutionSlots() + " slots)..."; if (m_log != null) { m_log.logMessage(msg); } else { System.err.println(msg); } // start the execution pool if (m_executorPool == null) { startExecutorPool(); } // setup output queues msg = "[Classifier] " + statusMessagePrefix() + " setup output queues."; if (m_log != null) { m_log.logMessage(msg); } else { System.err.println(msg); } m_outputQueues = new BatchClassifierEvent[e.getMaxRunNumber()][e.getMaxSetNumber()]; m_completedSets = new boolean[e.getMaxRunNumber()][e.getMaxSetNumber()]; m_currentBatchIdentifier = new Date(); } // create a new task and schedule for execution TrainingTask newTask = new TrainingTask(e.getRunNumber(), e.getMaxRunNumber(), e.getSetNumber(), e.getMaxSetNumber(), e.getTrainingSet()); String msg = "[Classifier] " + statusMessagePrefix() + " scheduling run " + e.getRunNumber() +" fold " + e.getSetNumber() + " for execution..."; if (m_log != null) { m_log.logMessage(msg); } else { System.err.println(msg); } // delay just a little bit /*try { Thread.sleep(10); } catch (Exception ex){} */ m_executorPool.execute(newTask); }
dc97dc70-20c8-4d2c-b897-6b276dfda4dc
7
public String purchaseOrderAdd(double total, int vendorno, ArrayList<PurchaseOrderLineItemDTO> items, DataSource ds) { PreparedStatement pstmt; Connection con = null; String msg = ""; Date date = new Date(); java.sql.Date sDate = new java.sql.Date(date.getTime()); int poNum = -1; String sql = "INSERT INTO purchaseorders (vendorno,podate,amount) VALUES(?,?,?)"; try { con = ds.getConnection(); con.setAutoCommit(false); pstmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.setInt(1, vendorno); pstmt.setDate(2, sDate); pstmt.setBigDecimal(3, BigDecimal.valueOf(total)); pstmt.execute(); ResultSet rs = pstmt.getGeneratedKeys(); rs.next(); poNum = rs.getInt(1); for( PurchaseOrderLineItemDTO item : items) { if ( item.getQty() > 0 ) { sql="INSERT INTO PurchaseOrderLineItems (PONumber,prodcd,QTY,Price) VALUES (?,?,?,?)"; pstmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.setInt(1,poNum); pstmt.setString(2, item.getProductcode()); pstmt.setInt(3, item.getQty()); pstmt.setBigDecimal(4, BigDecimal.valueOf(item.getCostprice())); pstmt.execute(); } } con.commit(); msg = Integer.toString(poNum); con.close(); }catch (SQLException se) { //Handle errors for JDBC System.out.println("SQL issue " + se.getMessage()); msg = "PO not added ! - " + se.getMessage(); try { con.rollback(); } catch (SQLException sqx) { System.out.println("Rollback failed - " + sqx.getMessage()); } } catch (Exception e) { //Handle other errors System.out.println("other issue " + e.getMessage()); } finally { //finally block used to close resources try { if (con != null) { con.close(); } } catch (SQLException se) { System.out.println("SQL issue on close " + se.getMessage()); }//end finally try } return msg; }
16be5633-a0fb-451b-8d7b-cab61b4a7654
3
public void clean(){ List<String> unuseds = new ArrayList<String>(); for(String path : expanded.keySet()){ if(! new File(ProjectMgr.getAssetsPath(), path).exists()){ unuseds.add(path); } } for(String unused : unuseds){ expanded.remove(unused); } }
e7d387be-4bea-40e4-a70d-fcdfb3d7325f
2
public void render(Graphics g) { g.setFont(new Font("Tahoma", Font.BOLD, 8)); level.render(g); for (Entity e : entities) { e.render(g); } player.render(g); inv.render(g); if (paused) { g.setColor(new Color(0, 0, 0, 155)); g.fillRect(0, 0, Main.getDrawableWidth(), Main.getDrawableHeight()); g.setColor(Color.WHITE); FontMetrics f = g.getFontMetrics(); int length = f.stringWidth("PAUSED"); g.drawString("PAUSED", Main.getScaledWidth() / 2 - length / 2, Main.getScaledHeight() / 2); } g.setColor(Color.WHITE); g.drawString("Entities: " + entities.size(), 10, 10); }
832920eb-af14-4f1b-9166-c93354dc2dc3
2
@Override public void setValueAt(Object uusi, int rivi, int sarake) { if (sarake >= 0 && sarake < sarakeNimet.length) { elokuvalista.paivita(uusi, rivi, sarake); // ilmoittaa datan muutoksesta JTable-komponentille fireTableCellUpdated(rivi, sarake); } }
41300826-b611-454a-87f4-2d6089e47d52
9
public void actionPerformed(ActionEvent arg0) { //find our super parent frame -- needed for dialogs Component c = this; while (null != c.getParent()) c = c.getParent(); if(arg0.getActionCommand().equalsIgnoreCase("SAVE")){ chooser.setCurrentDirectory(new File("boards")); int returnVal = chooser.showSaveDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try{ board.save(file); JOptionPane.showMessageDialog((Frame)c, "File saved successfully.", "Success", JOptionPane.INFORMATION_MESSAGE); }catch(Exception e){ JOptionPane.showMessageDialog( (Frame)c, e, "Save Error", JOptionPane.ERROR_MESSAGE); } } }else if(arg0.getActionCommand().equalsIgnoreCase("LOAD")){ chooser.setCurrentDirectory(new File("boards")); int returnVal = chooser.showOpenDialog(this); if(returnVal == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try{ loading = true; board.load(file); boardPanel.setBoard(board, true); JOptionPane.showMessageDialog((Frame)c, "File loaded successfully.", "Success", JOptionPane.INFORMATION_MESSAGE); loading = false; }catch(IOException e){ // e.printStackTrace(); JOptionPane.showMessageDialog( (Frame)c, e, "Load Error", JOptionPane.ERROR_MESSAGE); loading = false; } } }else if(arg0.getActionCommand().equalsIgnoreCase("RESET")){ board = new Board(20, 20); boardPanel.setBoard(board, true); this.repaint(); boardPanel.repaint(); }else if(arg0.getActionCommand().equalsIgnoreCase("REMOVE")){ boardPanel.removeSelectedLine(); } }
b83849e5-bc4b-4fd4-8bff-9a0526bf0805
0
@Basic @Column(name = "CTR_MOA_TIPO") public String getCtrMoaTipo() { return ctrMoaTipo; }
97ea07b1-962f-4c21-b90d-fcd8c69ea0fa
0
@Test public void test_static_replacer() throws Exception { stop_tunnel_in(1000); final String lipsum = StringUtils.lipsum(20); final long start = System.currentTimeMillis(); new StringTrafficker(getInt("static_replacer_local_port"), getInt("static_replacer_remote_port"), new String[][] { {"foo", "foo bar baz " + getProperty("static_replacer_search_term") + " foo bar baz"}}, new String[][] { {"foo", "foo bar baz " + getProperty("static_replacer_replacement") + " foo bar baz"}}).run(); final long duration = System.currentTimeMillis() - start; System.err.println("test_static_replacer duration: " + duration); Assert.assertTrue(duration < 5000); }
87c42f48-0b0d-4f03-a982-4efa7775cf4d
0
@Test public void testGroupWithEmptyDataCanBeCreated() throws Exception { GroupObject emptyDataGroup = new GroupObject("", "", ""); createGroup(emptyDataGroup); }
663977d5-ed69-4db0-b1ba-218d06ad430a
4
public synchronized void gridletResume(int gridletId, int userId, boolean ack) { boolean status = false; // finds the Gridlet in the execution list first int found = gridletPausedList_.indexOf(gridletId, userId); if (found >= 0) { // removes the Gridlet ResGridlet rgl = (ResGridlet) gridletPausedList_.remove(found); rgl.setGridletStatus(Gridlet.RESUMED); // update the Gridlets up to this point in time updateGridletProcessing(); status = true; // if there is an available PE slot, then allocate immediately boolean success = false; if ( gridletInExecList_.size() < super.totalPE_ ) { success = allocatePEtoGridlet(rgl); } // otherwise put into Queue list if (!success) { rgl.setGridletStatus(Gridlet.QUEUED); gridletQueueList_.add(rgl); } System.out.println(super.resName_ + "TimeShared.gridletResume():" + " Gridlet #" + gridletId + " with User ID #" + userId + " has been sucessfully RESUMED."); } else { System.out.println(super.resName_ + "TimeShared.gridletResume(): Cannot find " + "Gridlet #" + gridletId + " for User #" + userId); } // sends back an ack if required if (ack) { super.sendAck(GridSimTags.GRIDLET_RESUME_ACK, status, gridletId, userId); } }
39570b20-90a4-4fd7-b5a3-b8527bcccb5d
7
private void getEvidenceList(String actionType) { titleDLM.removeAllElements(); evidenceResultList = evidence.getEvideceList(fileName, actionType, teamType); if (evidenceResultList.size() != 0) { for (int i = 0; i < evidenceResultList.size(); i++) { titleDLM.addElement(evidenceResultList.get(i).getTitle()); } titleJlst.setSelectedIndex(0); if (!(evidenceResultList.get(0).getDescription() == null || evidenceResultList.get(0).getDescription().equals("null"))) { descriptionJtxa.setText(evidenceResultList.get(0).getDescription()); } // Exists patent claim evidenceCurrent = evidenceResultList.get(0); if (evidenceCurrent.getParentClaim() != null) { parentContentJlbl.setText(evidenceCurrent.getParentClaim().getTitle()); // Store parent title parentIdJlbl.setText(evidenceCurrent.getParentClaim().getId()); // Store Parent id } else { parentContentJlbl.setText("None"); } dialogContentJlbl.setText(evidenceCurrent.getDialogState()); playerContentJlbl.setText(evidenceCurrent.getName()); if (evidenceCurrent.getName().equals(userLogin.getName()) && evidenceCurrent.getDialogState().equals("Private")) { editDetailsJbtn.setEnabled(true); deleteActionJbtn.setEnabled(true); } else { editDetailsJbtn.setEnabled(false); deleteActionJbtn.setEnabled(false); } } }
492bcb01-30ed-4eea-9005-59fd87bc4872
8
protected void handleMouseClick(MouseEvent paramMouseEvent) { if (this.clear) { Position localPosition = getPosition(); getEnvironment().removeObject(this); if (this.state != null) { Robot localRobot = new Robot(GameApplet.thisApplet); try { localRobot.setChassis((Chassis)Class.forName("com.templar.games.stormrunner.chassis." + this.chassis).newInstance()); localRobot.setName(this.newName); Debug.println(this.parts); for (int i = 0; i < this.parts.length; i++) { if (this.parts[i] == null) continue; Class localClass = Class.forName("com.templar.games.stormrunner." + this.parts[i]); if (this.parts[i].startsWith("sensor.")) localRobot.addSensor((Sensor)localClass.newInstance()); else localRobot.addAssembly((Assembly)localClass.newInstance()); } this.state.activateRobot(localRobot, localPosition.getMapPoint()); localRobot.setOrientation(this.initialOrientation); localRobot.getEnvironment().getRenderer().setOffsetToCenter(localPosition.getMapPoint()); localRobot.updateAppearance(); localRobot.playSound("Robot-Alarm"); GameApplet.audio.play("RobotStart"); GameApplet.thisApplet.sendStatusMessage( "RCX:" + this.newName + " has been activated. Return it to the Cargo Bay for analysis of new parts."); return; } catch (ClassNotFoundException localClassNotFoundException) { localClassNotFoundException.printStackTrace(); return; } catch (InstantiationException localInstantiationException) { localInstantiationException.printStackTrace(); return; } catch (IllegalAccessException localIllegalAccessException) { localIllegalAccessException.printStackTrace(); return; } } Debug.println(this + " has no GameState set."); return; } GameApplet.audio.play("ButtonError"); GameApplet.thisApplet.sendStatusMessage( "RCX active but unable to initialize: RCX unable to move"); }
5b4af5bc-fcf4-46b9-abbf-fa066ca77ee1
6
private void updateViews() { // make sure our view of the model is up-to-date: for(Actor actor : model.actors) { if (!actorToView.containsKey(actor)) { actorToView.put(actor, new ActorView(actor)); } } for(Node node : model.nodes) { if (!nodeToView.containsKey(node)) { // TODO: come up with a halfway sane way to choose // locations for new nodes that are created raw: nodeToView.put(node, new NodeView(node, 0, 0, "")); } } for(Edge edge : model.edges) { if (!edgeToView.containsKey(edge)) { NodeView start = nodeToView.get(edge.start); NodeView end = nodeToView.get(edge.end); edgeToView.put(edge, new EdgeView(start, end)); } } }
5f04840e-a9a3-4f83-81bc-4d95db6b7f17
1
public static String convertToRepresentationString(BigInteger irepresentation,char[] alfabet){ String out = null; StringBuilder sb = new StringBuilder(); BigInteger leftNumber = irepresentation; BigInteger base = BigInteger.valueOf(alfabet.length); while(leftNumber.intValue() > 0){ BigInteger alfabetIndex = leftNumber.mod(base); leftNumber = leftNumber.divide(base); sb.append(alfabet[alfabetIndex.intValue()]); } out = sb.toString(); return out; }
2e41cebe-23af-429d-b85a-301dc226990b
1
public void laskeVaikeustasoa(){ if (this.alkutaso <= 1){ return; } this.alkutaso--; laskeTaso(); paivitaPisteetJaTaso(); }
c78dfca6-6f48-4c58-8d9f-ad95cb88e519
7
@Test public void testPartyStats() { TreeMap<String, PartyStat> partyStats = new TreeMap<>(); // setup parties determineParties(partyStats); // loop on all bills, including resolutions for ( String id: Bills.keySet() ) { Bill bill = Bills.get(id); if ( determinePassed(bill) ) { String legislatorId = determinePrincipalAuthor(bill); // a committee may be an author if ( legislatorId != null ) { Legislator legislator = Legislators.get(legislatorId); if ( legislator == null ) LOGGER.info("***: Bill legislatorId " + legislatorId + " references non-existant or inactive legislator for bill:" + bill); else if ( legislator.party == null ) LOGGER.info("***: Legislator Party is null:" + legislator); else partyStats.get(legislator.party).billsPassed++; } } } // determine the majority party PartyStat majorityParty = determineMajorityParty(partyStats); boolean majorityPartyPassedMoreBills = true; // show all bills passed for ( String party: partyStats.keySet() ) { PartyStat partyStat = partyStats.get(party); LOGGER.info("The " + party + " party has " + partyStat.memberCount + " members and passed " + partyStat.billsPassed + " bills."); if ( partyStat.billsPassed > majorityParty.billsPassed ) majorityPartyPassedMoreBills = false; } assertTrue( majorityPartyPassedMoreBills ); LOGGER.info("The majority party DID pass the most bills."); }
971e3597-50f9-42ef-a211-9f196c780318
7
@Override public void createSomeObjects() { this.addUser(new User("worker", "password", GroupType.WORKER)); this.addUser(new User("Gumby", "MyBrainHurts", GroupType.WORKER)); this.addUser(new User("manager", "password", GroupType.MANAGER)); ProductType pt = new ProductType("Skumbananer"), pt2 = new ProductType( "P-Taerter"); Stock semi = new Stock("Semi products - main room", StockType.SEMI, 100, 16, 10), cores = new Stock("Cores machine", StockType.MACHINE, 9, 16, 3), coat = new Stock( "Coating machine", StockType.MACHINE, 16, 16, 4), done = new Stock( "Finished", StockType.FINISHED, 64, 16, 8); SubProcess sp = null; pt.addSubProcess(sp = new SubProcess(0, "Core Production", 2, 4, 6)); sp.addStock(cores); pt.addSubProcess(sp = new SubProcess(1, "Core Drying", 2, 4, 6)); sp.addStock(semi); pt.addSubProcess(sp = new SubProcess(2, "Coating", 2, 4, 6)); sp.addStock(coat); pt.addSubProcess(sp = new SubProcess(3, "Drying", 2, 4, 6)); sp.addStock(semi); pt.addSubProcess(sp = new SubProcess(4, "Second Coating", 2, 4, 6)); sp.addStock(coat); pt.addSubProcess(sp = new SubProcess(5, "Last Drying", 2, 4, 6)); sp.addStock(done); pt2.addSubProcess(sp = new SubProcess(0, "Core Production", 2, 4, 6)); sp.addStock(cores); pt2.addSubProcess(sp = new SubProcess(1, "Core Drying", 2, 4, 6)); sp.addStock(semi); pt2.addSubProcess(sp = new SubProcess(2, "Coating", 2, 4, 6)); sp.addStock(coat); pt2.addSubProcess(sp = new SubProcess(3, "Drying", 2, 4, 6)); sp.addStock(semi); pt2.addSubProcess(sp = new SubProcess(4, "Second Coating", 2, 4, 6)); sp.addStock(coat); pt2.addSubProcess(sp = new SubProcess(5, "Last Drying", 2, 4, 6)); sp.addStock(done); sp = pt.getSubProcesses().get(0); for (int i = 0; i < 5; i++) { StorageUnit su = new StorageUnit(cores, i); int cap = (int) Math.ceil(Math.max(.75, Math.random()) * cores.getMaxTraysPerStorageUnit()); for (int j = 0; j < cap; j++) { Tray tray = new Tray(su, pt, 0); State s = new State(tray, new Date(System.currentTimeMillis())); s.setSubProcess(sp); tray.addState(s); su.addTray(tray); this.addTray(tray); } cores.addStorageUnit(su); } sp = pt2.getSubProcesses().get(0); for (int i = 5; i < 9; i++) { StorageUnit su = new StorageUnit(cores, i); int cap = (int) Math.ceil(Math.max(.75, Math.random()) * cores.getMaxTraysPerStorageUnit()); for (int j = 0; j < cap; j++) { Tray tray = new Tray(su, pt2, 0); State s = new State(tray, new Date(System.currentTimeMillis())); s.setSubProcess(sp); tray.addState(s); su.addTray(tray); this.addTray(tray); } cores.addStorageUnit(su); } for (int i = 0; i < done.getCapacity(); i++) { done.addStorageUnit(new StorageUnit(done, i)); } for (int i = 0; i < semi.getCapacity(); i++) { semi.addStorageUnit(new StorageUnit(semi, i)); } for (int i = 0; i < coat.getCapacity(); i++) { coat.addStorageUnit(new StorageUnit(coat, i)); } this.addProductType(pt); this.addProductType(pt2); this.addStock(done); this.addStock(semi); this.addStock(cores); this.addStock(coat); }
7e26a9c7-5dc8-4c86-a94f-375cbb3c69ab
0
public NewAttributeDialog() { super(Outliner.outliner, NEW_ATTRIBUTE, true); OK = GUITreeLoader.reg.getText("ok"); CANCEL = GUITreeLoader.reg.getText("cancel"); NEW_ATTRIBUTE = GUITreeLoader.reg.getText("new_attribute"); ATTRIBUTE = GUITreeLoader.reg.getText("attribute"); VALUE = GUITreeLoader.reg.getText("value"); ERROR_EXISTANCE = GUITreeLoader.reg.getText("error_att_key_existance"); ERROR_UNIQUENESS = GUITreeLoader.reg.getText("error_att_key_uniqueness"); ERROR_ALPHA_NUMERIC = GUITreeLoader.reg.getText("error_att_key_alpha"); buttonOK = new JButton(OK); buttonCancel = new JButton(CANCEL); attributeField = new JTextField(20); valueField = new JTextField(20); errorLabel = new JLabel(" "); // Create the Layout setSize(250,180); setResizable(false); // Adding window adapter to fix problem where initial focus won't go to the textfield. // Solution found at: http://forums.java.sun.com/thread.jsp?forum=57&thread=124417&start=15&range=15; addWindowListener( new WindowAdapter() { @Override public void windowOpened(WindowEvent e) { attributeField.requestFocus(); } } ); // Define the Bottom Panel JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new FlowLayout()); buttonOK.addActionListener(this); bottomPanel.add(buttonOK); buttonCancel.addActionListener(this); bottomPanel.add(buttonCancel); getContentPane().add(bottomPanel,BorderLayout.SOUTH); // Define the Center Panel JPanel centerPanel = new JPanel(); centerPanel.setLayout(new GridBagLayout()); AbstractPreferencesPanel.addPreferenceItem(ATTRIBUTE, attributeField, centerPanel); AbstractPreferencesPanel.addPreferenceItem(VALUE, valueField, centerPanel); AbstractPreferencesPanel.addSingleItemCentered(errorLabel, centerPanel); getContentPane().add(centerPanel, BorderLayout.CENTER); // Set the default button getRootPane().setDefaultButton(buttonOK); }
ffeaad01-9980-490e-92f5-357c9394935a
3
public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { String num = input.next(); if (num.equals("0")) return; int answer = 0; int pow = 2; for (int i = num.length() - 1; i >= 0; --i) { answer += (num.charAt(i) - '0') * (pow - 1); pow *= 2; } System.out.println(answer); } }
526cf658-d582-4abd-9806-88739deebb09
2
private static final byte[] encodeString(ByteBuffer string) { int length = string.array().length; int num_digits = 1; while((length /= 10) > 0) { num_digits++; } byte[] bencoded_string = new byte[length+num_digits+1]; bencoded_string[num_digits] = (byte)':'; System.arraycopy(string.array(), 0, bencoded_string, num_digits+1, length); for(int i = num_digits-1; i >= 0; i--) { bencoded_string[i] = (byte)((length % 10)+48); length /= 10; } return bencoded_string; }
663def43-7d77-441c-b783-04fa3949b570
3
public void write(String summaryOutputFile, String detailsOutputDirectory, List<CalendarObject> myCalendarObjects) throws IOException { mainHTML = new Html(); summaryPageHeader = new Head(); summaryPageBody = new Body(); dayToEventMap = new HashMap<String, ArrayList<Div>>(); for (CalendarObject co : myCalendarObjects) { Div div = new Div(); div.setId("eventDiv").setCSSClass("myclass"); DetailsPageWriter dpw = new DetailsPageWriter(); dpw.write(out, detailsOutputDirectory, co); A link = new A(); link.setHref(detailsOutputDirectory.replace("output/", "") + "/" + co.getURLString() + ".html").setTarget("_blank"); link.appendText(co.getName()); div.appendChild(link); if (!dayToEventMap.containsKey(co.getStartDay())) { dayToEventMap.put(co.getStartDay(), new ArrayList<Div>()); } dayToEventMap.get(co.getStartDay()).add(div); } List<String> allDivs = new ArrayList<String>(dayToEventMap.keySet()); Collections.sort(allDivs, new Comparator<Object>() { public int compare(Object o1, Object o2) { return reformat((String) o1).compareToIgnoreCase(reformat((String) o2)); } private String reformat(String time) { return time.substring(6,10) + time.substring(3,5) + time.substring(0,2); } }); for (String s : allDivs) { super.addDiv(s, dayToEventMap, summaryPageBody, "dayDiv", "Events on the day of " + s); } super.writeHTML(out, summaryOutputFile, mainHTML, summaryPageHeader, summaryPageBody); }
8229c331-d8fe-459b-ab0c-e38d02eb5bf4
8
public void reset() { for (JTextArea valueArea : wrappedLabelMap.values()) valueArea.setText(""); for (JLabel valueLbl : labelMap.values()) valueLbl.setText(""); for (JTextField valueField : stringMap.values()) valueField.setText(""); for (JTextField valueField : intMap.values()) valueField.setText(""); for (JCheckBox valueCheck : boolMap.values()) valueCheck.setSelected(false); for (JSlider valueSlider : sliderMap.values()) valueSlider.setValue(0); for (JComboBox valueSlider : comboMap.values()) valueSlider.removeAllItems(); for (JLabel valueReminder : reminderMap.values()) valueReminder.setText(""); }
0e572224-a8b6-45bb-b01a-e57f7471acbe
6
@Override public boolean run() { // Load config if (config == null) loadConfig(); // Load Db loadDb(); // Build db if (verbose) Timer.showStdErr("Building interval forest..."); snpEffectPredictor = config.getSnpEffectPredictor(); snpEffectPredictor.buildForest(); if (verbose) Timer.showStdErr("done"); // Annotate if (verbose) Timer.showStdErr("Reading file '" + inFile + "'"); if (bedFormat) bedIterate(); else vcfIterate(); if (verbose) Timer.showStdErr("done"); return true; }
353791aa-4a8e-4347-9063-4be7260ebf65
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(ConvexViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ConvexViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ConvexViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ConvexViewer.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 ConvexViewer().setVisible(true); } }); }
7e3a05ab-6040-439e-8ffd-561cc817c20f
1
public final void setShip(Ship ship) { this.ship = ship; if(ship != null) { setFieldState(eFieldState.Filled); ship.setFieldReference(this); } else setFieldState(eFieldState.Empty); }
0507fc07-d42a-47f4-bd06-b09b4afb5199
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(newTeamsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(newTeamsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(newTeamsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(newTeamsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ }
14cb5133-b9ef-4fc8-bfcf-d2b166c0aa4a
9
private void quickSort0(int[] a, int low, int high) { //the valid elements of the list are [low, high] if (high - low <= 1) return; if (high - low == 2) { //efficient! if (a[low] > a[low + 1]) swap(low, low + 1); return; } // if (high - low < 20) { // for (int i = low; i < high - 1; i++) { // focus(i, Color.BLUE); // int lowest = i; // for (int j = i + 1; j < high; j++) { // //focus(j, Color.yellow); // if (a[lowest] > a[j]) // lowest = j; // //focus(j, null); // } // swap(i, lowest); // focus(i, null); // } // } int n = high - low; //number of elements in the list. int p = pivot(a, low, high); //median of three; pivot's index. int pivot = a[p]; //p's value, the pivot value int i = low; int j = high - 2; swap(p, high - 1); //store the pivot at the end. while (i <= j) { while (a[i] < pivot && i < high - 2) { //don't run into the pivot we stored at index [high-1] i++; } while (a[j] > pivot && j > low) { j--; } if (i <= j) { swap(i, j); i++; j--; } } swap(i, high - 1); //put the pivot into its correct spot. focus(i, Color.BLUE); quickSort0(a, low, i); quickSort0(a, i + 1, high); focus(i, null); }
11443184-689c-46c8-b9ae-e298a11b47f2
6
public void receive(IPInterfaceAdapter iface, Datagram msg) throws Exception { // Raw listeners are called for any (IP) protocol, even if // the datagram's destination is not this node for (IPInterfaceListener l: rawListeners) l.receive(iface, msg); // Datagrams addressed to this node if (hasAddress(msg.dst) || msg.dst.isBroadcast()) { List<IPInterfaceListener> listeners= this.listeners.get(msg.getProtocol()); if (listeners != null) for (IPInterfaceListener l: listeners) l.receive(iface, msg); return; } // Datagram not addressed to this node. Forward if enabled... if (forwarding) forward(msg); }
29cc70bc-7918-4ba9-82d8-322dbb42fddb
1
@Override public int getPages(int intRegsPerPag, ArrayList<FilterBean> hmFilter, HashMap<String, String> hmOrder) throws Exception { int pages; try { oMysql.conexion(enumTipoConexion); pages = oMysql.getPages("usuario", intRegsPerPag, hmFilter, hmOrder); oMysql.desconexion(); return pages; } catch (Exception e) { throw new Exception("UsuarioDao.getPages: Error: " + e.getMessage()); } }
8b2aa9ab-2b31-49b7-bbe9-8ee2a36fd58f
2
private void load() { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixels[x + y * width] = spritesheet.getPixel((this.x + x) + (this.y + y) * spritesheet.getSize()); } } }
0cff4017-21c0-4fad-9fc2-c536db4b603c
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DimensionLevelPair other = (DimensionLevelPair) obj; if (dimensionOrderNo != other.dimensionOrderNo) return false; return true; }
76e6c4dd-6b39-4b32-a2fc-291fd1670287
4
public void insert( double addVal ) { if ( leftHeap.size() == 0 || addVal < leftHeap.peekMax() ) leftHeap.add( addVal ); else rightHeap.add( addVal ); //balance heaps if sizes differ by >1 element if ( leftHeap.size()-rightHeap.size() > 1 ) rightHeap.add( leftHeap.removeMax() ); else if ( rightHeap.size()-leftHeap.size() > 1 ) leftHeap.add( rightHeap.removeMin() ); }//O(logn)
ee116dcf-823e-4f09-aff7-a8c4713ffb90
6
private void splitAndFill(String[] trackPropertiesValues) { int valuesRead = 0; for (String propertyValue : trackPropertiesValues) { String[] trackValue = propertyValue.split("="); switch (trackValue[0].trim()) { case ("RaceLaps"): this.laps = trackValue[1].trim(); valuesRead++; break; case ("TrackName"): this.name = trackValue[1].trim(); valuesRead++; break; case ("GrandPrixName"): this.setGpName(trackValue[1].trim()); valuesRead++; break; case ("VenueName"): this.season = trackValue[1].trim(); valuesRead++; break; } if (valuesRead == 4) { this.setHeader(trackPropertiesValues[valuesRead]); this.body = trackPropertiesValues[valuesRead + 1]; this.setFilled(true); } } }
3a1f7cb0-e13d-4420-811c-f2ce730278d7
7
public static void main(String[] args) throws IOException { Scanner in = new Scanner(new File("wormhole.in")); PrintWriter out = new PrintWriter(new FileWriter("wormhole.out")); N = in.nextInt(); wormholes = new point[N + 1]; next_on_right = new int[N + 1]; wormholes[0] = new point(0, 0); Arrays.fill(next_on_right, 0); for (int i = 1; i <= N; i++) { in.nextLine(); int x = in.nextInt(); int y = in.nextInt(); wormholes[i] = new point(x, y); } for (int i=1; i<=N; i++) // set next_on_right[i]... for (int j=1; j<=N; j++) if (wormholes[j].x > wormholes[i].x && wormholes[j].y == wormholes[i].y) // j right of i... if (next_on_right[i] == 0 || wormholes[j].x - wormholes[i].x < wormholes[next_on_right[i]].x - wormholes[i].x) // j is the first one next_on_right[i] = j; out.println(pairing()); exit(in, out); }
2708babf-c672-4352-9074-cbb3d0d48ebf
6
public static List<String> unpackTIPP(String tippFile, String outputFolder) throws IOException { List<String> fileList = new ArrayList<String>(); byte[] buffer = new byte[1024]; try { //create output directory is not exists File folder = new File(OUTPUT_FOLDER); if (!folder.exists()) { folder.mkdir(); } //get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(tippFile)); //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); System.out.println("file unzip : " + newFile.getAbsoluteFile()); //add xliff file to list if (newFile.getAbsoluteFile().toString().contains(".xlf")) { fileList.add(newFile.getAbsoluteFile().toString()); } //check for zip file if (newFile.getAbsoluteFile().toString().contains("resources.zip")) { System.out.println("file is a zip file : " + newFile.getAbsoluteFile()); unpackTIPP(newFile.getAbsoluteFile().toString(), RESOURCE_OUTPUT_FOLDER); } //create all non exists folders //else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); System.out.println("Done"); } catch (IOException ex) { ex.printStackTrace(); } return fileList; }
7aadbdfe-3bbc-4804-9afe-909bb9faf3e6
5
private static final BigInteger RSADP(final RSAPrivateKey K, BigInteger c) { // 1. If the representative c is not between 0 and n - 1, output // "representative out of range" and stop. final BigInteger n = K.getModulus(); if (c.compareTo(ZERO) < 0 || c.compareTo(n.subtract(ONE)) > 0) { throw new IllegalArgumentException(); } // 2. The representative m is computed as follows. BigInteger result; if (!(K instanceof RSAPrivateCrtKey)) { // a. If the first form (n, d) of K is used, let m = c^d mod n. final BigInteger d = K.getPrivateExponent(); result = c.modPow(d, n); } else { // from [3] p.13 --see class docs: // The RSA blinding operation calculates x = (r^e) * g mod n before // decryption, where r is random, e is the RSA encryption exponent, and // g is the ciphertext to be decrypted. x is then decrypted as normal, // followed by division by r, i.e. (x^e) / r mod n. Since r is random, // x is random and timing the decryption should not reveal information // about the key. Note that r should be a new random number for every // decryption. final boolean rsaBlinding = Properties.doRSABlinding(); BigInteger r = null; BigInteger e = null; if (rsaBlinding) { // pre-decryption r = newR(n); e = ((RSAPrivateCrtKey) K).getPublicExponent(); final BigInteger x = r.modPow(e, n).multiply(c).mod(n); c = x; } // b. If the second form (p, q, dP, dQ, qInv) and (r_i, d_i, t_i) // of K is used, proceed as follows: final BigInteger p = ((RSAPrivateCrtKey) K).getPrimeP(); final BigInteger q = ((RSAPrivateCrtKey) K).getPrimeQ(); final BigInteger dP = ((RSAPrivateCrtKey) K).getPrimeExponentP(); final BigInteger dQ = ((RSAPrivateCrtKey) K).getPrimeExponentQ(); final BigInteger qInv = ((RSAPrivateCrtKey) K).getCrtCoefficient(); // i. Let m_1 = c^dP mod p and m_2 = c^dQ mod q. final BigInteger m_1 = c.modPow(dP, p); final BigInteger m_2 = c.modPow(dQ, q); // ii. If u > 2, let m_i = c^(d_i) mod r_i, i = 3, ..., u. // iii. Let h = (m_1 - m_2) * qInv mod p. final BigInteger h = m_1.subtract(m_2).multiply(qInv).mod(p); // iv. Let m = m_2 + q * h. result = m_2.add(q.multiply(h)); if (rsaBlinding) { // post-decryption result = result.multiply(r.modInverse(n)).mod(n); } } // 3. Output m return result; }
83e02e3b-2c9f-48b1-bbeb-66dade6cf796
4
public boolean addBuddy(String user, String buddy, int sentBy) { boolean retVal = db.addBuddies(user, buddy); if((sentBy == ServerInterface.CLIENT) && (backupServer != null) && (retVal == true)) { try { backupServer.ping(); backupServer.addBuddy(user, buddy, ServerInterface.SERVER); } catch(Exception ex) { System.out.println("backup Server not responding"); resetBackupServer(); } } notifyUserListChanged(); return retVal; }
8442c0a9-b402-4d09-abe0-72f677230da4
6
@SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if(sender instanceof ConsoleCommandSender) { sender.sendMessage("§cThis command can only be run in game!"); return true; } if(args.length==1) return false; else { Player p = (Player) sender; Player target = Bukkit.getPlayer(args[1]); if(target== null) { p.sendMessage("§cThat player isn't online!"); return true; } if(GameManager.isPlaying(p)) { p.sendMessage("§cYou can't spectate another game while you're playing!"); return true; } if(GameManager.isPlaying(target)) { Game game = GameManager.getGame(target); if(GameManager.getGame(p)!= null) GameManager.getGame(p).removeSpectator(p); game.addSpectator(p); p.sendMessage(Main.tag+"§7Teleporting..."); p.teleport(target); } else { p.sendMessage("§cThat player isn't in a game!"); } } return true; }
d6b92be6-d44b-4e2b-b3de-22a12fc102d7
4
protected static boolean isUSASummer(int date) throws Exception { int[] USADSTSequence = {20070101, 20070311, 20071104, 20080309, 20081102, 20090308, 20091101, 20100314, 20101107, 20110313, 20111106, 20120311, 20121104, 20130310, 20131103, 20140309, 20141102, 20150308, 20151101, 20160313, 20161106, 20170312, 20171105, 20180311, 20181104, 20190310, 20191103, 20200308, 20201101, 20210314, 20211107, 20220313, 20221106, 20230312, 20231105, 20240310, 20241103, 20250309, 20251102, 20251231}; boolean isSummer = true; if(date < 20070101 || date > 20251231) //error if date value is outside our table throw new Exception("DST module only works from 2007 to 2025."); //Iterate through DST sequence, toggling isSummer each value. When the wheel stops, isSummer will be correct. for (int i = 0; i < USADSTSequence.length && date >= USADSTSequence[i]; i++) { isSummer = !isSummer; //System.out.println(i % 2 + " " + isSummer + " " + date + " " + USADSTSequence[i]); } //System.out.println(isSummer); return isSummer; }
f5053ae9-6de3-455b-af2d-19d8ec4a93c4
1
public boolean getPasteEnabled() { return this instanceof ClipboardInterface && pasteEnabled; }
03273a54-3266-4fb3-bea3-1de17553c91b
8
public boolean equals(final Object ref) { if(ref instanceof GRect) { final GRect r = (GRect)ref; final boolean isempty1 = isEmpty(); final boolean isempty2 = r.isEmpty(); return ((isempty1 || isempty2) && isempty1 && isempty2) || ((xmin == r.xmin) && (xmax == r.xmax) && (ymin == r.ymin) && (ymax == r.ymax)); } return false; }
e9861344-90e8-41a1-9478-021e424f095e
2
public static PeerSession newSession (PeerConnection conn, ExecutorService eventExec, ExecutorService connExec) { boolean shutdownEvent = false; ExecutorService ee = eventExec; ExecutorService ce = connExec; if (ee == null) { ee = Executors.newSingleThreadExecutor(); shutdownEvent = true; } boolean shutdownConn = false; if (ce == null) { ce = Executors.newFixedThreadPool(2); shutdownConn = true; } return new PeerSession(conn, ee, shutdownEvent, ce, shutdownConn); }
29e9c884-c4da-4cd5-8096-6f71f8ed2501
1
@Override public void mouseReleased(MouseEvent event) { mouseDragged(event); mShowBorder = mPressed; mInMouseDown = false; MouseCapture.stop(this); if (mPressed) { mPressed = false; click(); } repaint(); }
07e64e31-052b-4062-b481-49e7773a8620
6
@SuppressWarnings("unchecked") public void load() { //Load markets, revenue and deliveries //If they cannot be loaded set them to null and they can be constructed by onEnable //Load markets try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Conf.dataFolder + "markets.bin")); Object result = ois.readObject(); ois.close(); markets = (HashMap<Material, Market>)result; for( Market market : markets.values() ) market.setPlugin(this); //If new materials were added since we last loaded we need to give them markets or we might crash! for( Material material : materials.values() ) { Market market = markets.get(material); if(market == null) { market = new Market(this, material); markets.put(material, market); } } getLogger().info("Loaded markets.bin"); } catch(Exception e) { getLogger().info("markets.bin not found, generating blank markets instead"); markets = null; } try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Conf.dataFolder + "revenue.bin")); Object result = ois.readObject(); ois.close(); revenue = (HashMap<String, Double>)result; getLogger().info("Loaded revenue.bin"); }catch(Exception e){ getLogger().info("revenue.bin not found, assuming clean slate."); revenue = null; } try{ ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Conf.dataFolder + "deliveries.bin")); Object result = ois.readObject(); ois.close(); deliveries = (HashMap<String, List<EEItemStack>>)result; getLogger().info("Loaded deliveries.bin"); }catch(Exception e){ getLogger().info("deliveries.bin not found, assuming clean slate."); deliveries = null; } }