text
stringlengths
14
410k
label
int32
0
9
private void find(int opened, int closed, int n, String validPath) { //finish if(opened == n && closed == n) { if(!validCombinations.contains(validPath)) validCombinations.add(validPath); return; } //first pass or can we add a "(" ? if(opened == 0 || opened<n) { validPath += "("; find(++opened,closed, n, validPath); } //can we add a ")" ? if(opened>=closed && closed<n) { validPath += ")"; find(opened,++closed, n, validPath); } }
7
private void reshapeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reshapeButtonActionPerformed try { JViewport viewport = spriteSheetScrollPane.getViewport(); SpriteSheetPane ssPane = (SpriteSheetPane) viewport.getView(); ButtonModel selectedModel = rsAnchorGroup.getSelection(); SpriteClip.AnchorType anchor; if (selectedModel == tlRadioButton.getModel()) { anchor = SpriteClip.AnchorType.TL; }else if (selectedModel == tcRadioButton.getModel()) { anchor = SpriteClip.AnchorType.TC; }else if (selectedModel == trRadioButton.getModel()) { anchor = SpriteClip.AnchorType.TR; }else if (selectedModel == clRadioButton.getModel()) { anchor = SpriteClip.AnchorType.CL; }else if (selectedModel == crRadioButton.getModel()) { anchor = SpriteClip.AnchorType.CR; }else if (selectedModel == blRadioButton.getModel()) { anchor = SpriteClip.AnchorType.BL; }else if (selectedModel == bcRadioButton.getModel()) { anchor = SpriteClip.AnchorType.BC; }else if (selectedModel == brRadioButton.getModel()) { anchor = SpriteClip.AnchorType.BR; }else { anchor = SpriteClip.AnchorType.CC; } spriteClipper.reshapeSprites(ssPane.getSelectedClips(), anchor); } catch (Exception e) { exceptionDialog(e); } }//GEN-LAST:event_reshapeButtonActionPerformed
9
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String line = null; StringBuilder sb = new StringBuilder(); StringBuilder alertDiv = new StringBuilder(); String advisory = ""; try { URL url = new URL("http://www3.septa.org/hackathon/Alerts/get_alert_data.php?req1=rr_route_bsl"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); JsonReader readerd = new JsonReader(reader); readerd.beginArray(); while (readerd.hasNext()) { readerd.beginObject(); while (readerd.hasNext()) { String name = readerd.nextName(); if (name.equals("route_name")) { log.warning(readerd.nextString()); } else if (name.equals("advisory_message")) { advisory = readerd.nextString(); log.warning(advisory); } else { readerd.skipValue(); // avoid some unhandle events } } readerd.endObject(); } readerd.endArray(); } catch (MalformedURLException e) { } catch (IOException e) { } //writeHead(out, "BSL Alerts"); //writeConnectPrompt(out); if(advisory.length() > 1){ writeAdvisory(out, advisory); } // log.warning(alertDiv.toString()); //writeFoot(out, null, null); }
7
public int getPlayerIndexByID(int id) { for (Player player : players) { if (player.getPlayerID() == id) return player.getPlayerIndex(); } return -1; }
2
@Override public void actionPerformed(ActionEvent event) { if (event.getSource()== m_generateBarButton){ generateBarChart(); } else if (event.getSource()== m_generatePieButton){ generatePieChart(); } else if (event.getSource() == m_generateLineButton) { generateLineChart(); } else if (event.getSource() == m_generateRingButton) { generateRingChart(); } else if (event.getSource() == m_generateAreaButton) { generateAreaChart(); } else if (event.getSource() == m_generateBubbleButton) { generateBubbleChart(); } else if (event.getSource() == m_generateScatterButton) { generateScatterChart(); } }
7
public int firstMissingPositive(int[] a) { if (a == null || a.length==0){ return 1; } int i=0; while(i<a.length){ if(a[i] >0 && a[i]<a.length && a[a[i]-1] != a[i] && a[i] != i+1){ swap(a, i, a[i]-1); } else{ i++; } } i=0; while (i<a.length){ if (a[i] != i+1){ return i+1; } ++i; } return a.length +1; }
9
private boolean isValidNumber(final int aNumber) { boolean res = false; return !(Integer.toString(aNumber).endsWith("5")); }
0
public int threeSumClosest(int[] num, int target) { Arrays.sort(num); int min = Math.abs(num[0] + num[1] + num[2] - target); int rst = num[0] + num[1] + num[2]; for (int i = 0 ; i < num.length - 2; i++ ) { int k = num.length -1; for ( int j = i +1; j< num.length -1; j++) { if (Math.abs(num[i] + num[j] + num[k] -target) < min) { min = Math.abs(num[i] + num[j] + num[k] -target); rst = num[i] + num[j] + num[k]; } while (k > j + 1 && num[i] + num[j] + num[k-1] > target ) { k -- ; if (Math.abs(num[i] + num[j] + num[k] -target) < min) { min = Math.abs(num[i] + num[j] + num[k] -target); rst = num[i] + num[j] + num[k]; } } if (k > j +1 && Math.abs(num[i] + num[j] + num[k-1] -target) < min) { min = Math.abs(num[i] + num[j] + num[k-1] -target); rst = num[i] + num[j] + num[k-1]; } } } return rst; }
8
public String comparer(Carte carteAdverse){ if (puissance > carteAdverse.puissance){ return "gagne"; } else if (puissance < carteAdverse.puissance){ return "perdu"; } else return "bataille"; }
2
private Socket connect () { Socket s = null; int attempts = 0; do { attempts ++; try { s = new Socket(host, port); s.setKeepAlive(true); s.setSoTimeout(0); } catch (Exception e) { String msg = String.format("Warning: connection attempt %d to %s failed.", attempts, getInfo()); System.err.println(msg); System.err.println(e.getMessage()); try { Thread.sleep(random.nextInt(100) + 1); /* [0..100] + 1 > 0.*/ } catch (InterruptedException ignored) {} } } while (s == null); return s; }
3
public void rotarAdelante() { if (direccion.equals(Direccion.derecha)) { rotar(tipoTrans.enZ, 90); } else if (direccion.equals(Direccion.izquierda)) { rotar(tipoTrans.enZ, -90); } else if (direccion.equals(Direccion.atras)) { rotar(tipoTrans.enZ, 180); } else if (direccion.equals(Direccion.adDer)) { rotar(tipoTrans.enZ, 45); } else if (direccion.equals(Direccion.adIzq)) { rotar(tipoTrans.enZ, -45); } else if (direccion.equals(Direccion.atDer)) { rotar(tipoTrans.enZ, 135); } else if (direccion.equals(Direccion.atIzq)) { rotar(tipoTrans.enZ, -135); } direccion = Direccion.adelante; }
7
private void writeToFile( final MultiProcessor executor, final Map<String, ByteClass> byteClasses, final List<Pair<ZipEntry, byte[]>> fileEntries, final BiMap<String, String> nameMaps, final BiMap<Signature, Signature> signatureMaps, final Map<Signature, Integer> flags ) throws IOException, FileNotFoundException, InterruptedException, ExecutionException { final Collection<Future<Pair<ZipEntry, byte[]>>> classWrites = newArrayList(); for (final ByteClass clazz : byteClasses.values()) { classWrites.add(executor.submit(clazz.callable(signatureMaps, nameMaps, byteClasses, flags, correctEnums))); } FileOutputStream fileOut = null; JarOutputStream jar = null; try { jar = new JarOutputStream(fileOut = new FileOutputStream(output)); for (final Pair<ZipEntry, byte[]> fileEntry : fileEntries) { jar.putNextEntry(fileEntry.getLeft()); jar.write(fileEntry.getRight()); } for (final Future<Pair<ZipEntry, byte[]>> fileEntryFuture : classWrites) { final Pair<ZipEntry, byte[]> fileEntry = fileEntryFuture.get(); jar.putNextEntry(fileEntry.getLeft()); jar.write(fileEntry.getRight()); } } finally { if (jar != null) { try { jar.close(); } catch (final IOException ex) { } } if (fileOut != null) { try { fileOut.close(); } catch (final IOException ex) { } } } }
7
public String getDescription() { StringBuffer result = new StringBuffer(String.valueOf(addr)) .append('_').append(Integer.toHexString(hashCode())) .append(": ").append(opcodeString[opcode]); if (opcode != opc_lookupswitch) { if (hasLocalSlot()) result.append(' ').append(getLocalSlot()); if (succs != null) result.append(' ').append(((Instruction) succs).addr); if (objData != null) result.append(' ').append(objData); if (opcode == opc_multianewarray) result.append(' ').append(getDimensions()); } else { int[] values = getValues(); Instruction[] succs = getSuccs(); for (int i = 0; i < values.length; i++) { result.append(' ').append(values[i]).append("->") .append(((Instruction) succs[i]).addr); } result.append(' ').append("default: ") .append(((Instruction) succs[values.length]).addr); } return result.toString(); }
6
@Override public void run() { if (bot.hasMessage()) { message = bot.getMessage(); channel = bot.getChannel(); sender = bot.getSender(); } if (this.message.startsWith("~vote")) { tokenize(false, 5, this.message); try { if ((voters != null) && (((Integer) voters.get(this.sender)).intValue() == 1)) { return; } } catch (NullPointerException ex) { ex.printStackTrace(); } if (this.parameters.equalsIgnoreCase(" y")) { voteYes += 1; voters.put(this.sender, Integer.valueOf(1)); } else if (this.parameters.equalsIgnoreCase(" n")) { voteNo += 1; voters.put(this.sender, Integer.valueOf(1)); } Main.bot.sendMessage(this.channel, voteYes + " " + voteNo); } }
7
@Test public void getContactsWithIdsNormalTest() { contacts3 = generateListOfContacts3(); Contact steve = null; Contact jane = null; Contact tim = null; int idSteve = 0; int idJane = 0; int idTim = 0; for (Contact curr : contacts3) { if (curr.getName().equals("Steve Austin")) { steve = curr; idSteve = steve.getId(); } else if (curr.getName().equals("Jane Smith")) { jane = curr; idJane = jane.getId(); } else if (curr.getName().equals("Tim Davies")) { tim = curr; idTim = tim.getId(); } else { throw new RuntimeException("unexpected name"); } } assertNotNull(steve); assertNotNull(jane); assertNotNull(tim); Assert.assertEquals(contacts3, contactManager.getContacts(idSteve, idJane, idTim)); }
4
public void setCoordinate(Coordinate a) { boolean test = false; if (test || m_test) { System.out.println("Grid :: setCoordinate() BEGIN"); } m_Grid[a.getX()][a.getY()] = a.getValue(); if (test || m_test) { System.out.println("Grid :: setCoordinate() END"); } }
4
private static boolean isUnique(String input) { if(input==null || input.isEmpty()) return false; HashSet<Character> uniqueChars = new HashSet<Character>(); char[] inputStrArray = input.toCharArray(); for(char c: inputStrArray) { if(uniqueChars.contains(c)) { return false; } else { uniqueChars.add(c); } } return true; }
4
@Test public void storeTestInvalidUserId() { try { assertFalse(new Transaction().store(123, 56342)); } catch (IOException e) { System.out.println("Invalid data"); } }
1
public static int calcularFatorial(int numero){ if (numero <= 0) { return 1; }else{ return (numero * calcularFatorial(numero-1)); } }
1
@Override boolean accepts(A value) { switch (polarity) { case Pos: return this.value.equals(value); case Neg: return !this.value.equals(value); } throw new IllegalStateException(); }
2
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { dx = -1; } if (key == KeyEvent.VK_RIGHT) { dx = 1; } if (key == KeyEvent.VK_UP) { dy = -1; } if (key == KeyEvent.VK_DOWN) { dy = 1; } if (key == KeyEvent.VK_SPACE) { move(); } }
5
void frameControl(Token token, boolean isSubCmd) throws ScriptException { switch (token.tok) { case Token.playrev: viewer.reverseAnimation(); case Token.play: case Token.resume: viewer.resumeAnimation(); return; case Token.pause: viewer.pauseAnimation(); return; case Token.next: viewer.setAnimationNext(); return; case Token.prev: viewer.setAnimationPrevious(); return; case Token.rewind: viewer.rewindAnimation(); return; default: evalError(GT._("invalid {0} control keyword", "frame") + ": " + token.toString()); } }
7
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(RegistroEmpleadoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegistroEmpleadoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegistroEmpleadoForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(RegistroEmpleadoForm.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 RegistroEmpleadoForm().setVisible(true); } }); }
6
private void valid(int depth50m, int depth10m, int depth1m) throws AxisWithoutMeaningErrorException { if (depth50m < min50m || depth50m > max50m) { throw new AxisWithoutMeaningErrorException(); } if (depth10m < min10m || depth10m > max10m) { throw new AxisWithoutMeaningErrorException(); } if (depth1m < min1m || depth1m > max1m) { throw new AxisWithoutMeaningErrorException(); } }
6
public boolean containsMatchingLoad(CombineableOperator comb) { Operator combOp = (Operator) comb; if (comb.getLValue().matches(this)) { if (subsEquals((Operator) comb.getLValue())) return true; } for (int i = 0; i < subExpressions.length; i++) { if (subExpressions[i].containsMatchingLoad(comb)) return true; } return false; }
4
public boolean impacto(Disparo pDisparo) { boolean impactado = false; if((pDisparo.getX() >= x && pDisparo.getX() <= x + 90.0) && (pDisparo.getY() >= y && pDisparo.getY() <= y+90.0)) { impactado = true; } if(impactado) { toquesRecibidos++; } return impactado; }
5
LeagueError valid() { // check for lock if (!teamDivVector.isLocked()) { return LeagueError.NOTHING_EDITED; } // check nof teams for (int div = 1; div <= modus.getNofDivisions(); div++) { if (modus.getNofTeams() != teamDivVector.getNofTeams(div)) { // wrong nof teams for division teams (but don't check transfer // teams) return LeagueError.WRONG_NOF_TEAMS; } } // completeness of teams (nof players) for (int div = 1; div <= modus.getNofDivisions() + 1; div++) { int nofTeams = teamDivVector.getNofTeams(div); for (int i = 0; i < nofTeams; i++) { Team team = teamDivVector.getTeam(div, i); if (team.getNofPlayers() != Team.TEAM_MUSTBEINITPLAYER) { return LeagueError.WRONG_NOF_PLAYERS; } } } return LeagueError.OK; }
6
public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) { return head; } ListNode firstHead = new ListNode(Integer.MIN_VALUE); ListNode lastDistinct = firstHead; ListNode slow = head; ListNode fast = head.next; boolean inDuplicated = false; while(fast != null) { if(slow.val == fast.val) { inDuplicated = true; slow = slow.next; fast = fast.next; }else { if(inDuplicated) { inDuplicated =false; }else { lastDistinct.next = slow; lastDistinct = slow; } slow = slow.next; fast = fast.next; } lastDistinct.next = null; } if(!inDuplicated) { lastDistinct.next = slow; } return firstHead.next; }
6
public boolean equals(Object obj) { if(obj instanceof Element) if(protons == ((Element)obj).protons && quantity == ((Element)obj).quantity) return true; return false; }
3
@Override public List<Student> getStudent(int courseId) throws SQLException { List<Student> studentList = new ArrayList<>(); Connection connect = null; PreparedStatement statement = null; try { Class.forName(Params.bundle.getString("urlDriver")); connect = DriverManager.getConnection(Params.bundle.getString("urlDB"), Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB")); String selectCourse = "select user.id, user.first_name, user.last_name, user.patronymic from student inner join user on student.user_id=user.id where " + "student.main_course_1_id = ? or student.main_course_2_id = ? or student.main_course_3_id = ? or student.main_course_4_id = ?"; statement = connect.prepareStatement(selectCourse); statement.setInt(1, courseId); statement.setInt(2, courseId); statement.setInt(3, courseId); statement.setInt(4, courseId); ResultSet resultStudent = statement.executeQuery(); while (resultStudent.next()){ Student student = new Student(); student.setId(resultStudent.getInt("user.id")); student.setFirstName(resultStudent.getString("user.first_name")); student.setLastName(resultStudent.getString("user.last_name")); student.setPatronymic(resultStudent.getString("user.patronymic")); studentList.add(student); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(connect != null) connect.close(); if(statement != null) statement.close(); return studentList; } }
5
public void setText(String text) { Assert.isNotNull(text); this.text = LegacyActionTools.escapeMnemonics(text); if (label != null && !label.isDisposed()) { label.setText(this.text); } if (this.text.length() == 0) { if (isVisible()) { setVisible(false); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } else { // Always update if using 'CALC_TRUE_WIDTH' if (!isVisible() || charWidth == CALC_TRUE_WIDTH) { setVisible(true); IContributionManager contributionManager = getParent(); if (contributionManager != null) { contributionManager.update(true); } } } }
8
@Override public boolean equals (Object obj) { if (!(obj instanceof PollItem)) return false; PollItem target = (PollItem) obj; if (socket != null && socket == target.socket) return true; if (getRawSocket () != null && getRawSocket () == target.getRawSocket ()) return true; return false; }
5
public UpdateFrame getFrame() { return frame; }
0
public void getRollInfo(gamelogic.PublicGameBoard pub, boolean exp) { List<Integer> data = pub.rollData(); for (int i = 0; i < data.size(); i++) { Tile active = (exp)? getTileByIntExp(i):getTileByInt(i); if (active == null) return; if (active.resource() == TileType.Desert || data.get(i) < 2 || data.get(i) > 12) continue; active.setRoll(data.get(i)); } }
6
public void ackRecieved(UtpTimestampedPacketDTO pair) { int seqNrToAck = pair.utpPacket().getAckNumber() & 0xFFFF; // log.debug("Recieved ACK " + pair.utpPacket().toString()); timeStampNow = timeStamper.timeStamp(); lastAckRecieved = timeStampNow; int advertisedWindo = pair.utpPacket().getWindowSize() & 0xFFFFFFFF; updateAdvertisedWindowSize(advertisedWindo); statisticLogger.ackRecieved(seqNrToAck); int packetSizeJustAcked = buffer.markPacketAcked(seqNrToAck, timeStampNow, UtpAlgConfiguration.AUTO_ACK_SMALLER_THAN_ACK_NUMBER); if (packetSizeJustAcked > 0) { updateRtt(timeStampNow, seqNrToAck); updateWindow(pair.utpPacket(), timeStampNow, packetSizeJustAcked, pair.utpTimeStamp()); } // TODO: With libutp, sometimes null pointer exception -> investigate. // log.debug("utpPacket With Ext: " + pair.utpPacket().toString()); SelectiveAckHeaderExtension selectiveAckExtension = findSelectiveAckExtension(pair.utpPacket()); if (selectiveAckExtension != null) { // if a new packed is acked by selectiveAck, we will // only update this one. if more than one is acked newly, // ignore it, because it will corrupt our measurements boolean windowAlreadyUpdated = false; // For each byte in the selective Ack header extension byte[] bitMask = selectiveAckExtension.getBitMask(); for (int i = 0; i < bitMask.length; i++) { // each bit in the extension, from 2 to 9, because least significant // bit is ACK+2, most significant bit is ack+9 -> loop [2,9] for (int j = 2; j < 10; j++) { if (SelectiveAckHeaderExtension.isBitMarked(bitMask[i], j)) { // j-th bit of i-th byte + seqNrToAck equals our selective-Ack-number. // example: // ack:5, sack: 8 -> i = 0, j =3 -> 0*8+3+5 = 8. // bitpattern in this case would be 00000010, bit_index 1 from right side, added 2 to it equals 3 // thats why we start with j=2. most significant bit is index 7, j would be 9 then. int sackSeqNr = i*8 + j + seqNrToAck; // sackSeqNr can overflow too !! if (sackSeqNr > UnsignedTypesUtil.MAX_USHORT) { sackSeqNr -= UnsignedTypesUtil.MAX_USHORT; } statisticLogger.sAck(sackSeqNr); // dont ack smaller seq numbers in case of Selective ack !!!!! packetSizeJustAcked = buffer.markPacketAcked(sackSeqNr, timeStampNow, false); if (packetSizeJustAcked > 0 && !windowAlreadyUpdated) { windowAlreadyUpdated = true; updateRtt(timeStampNow, sackSeqNr); updateWindow(pair.utpPacket(), timeStampNow, packetSizeJustAcked, pair.utpTimeStamp()); } } } } } statisticLogger.next(); }
8
public static boolean generateItemFile(String fileName, Set<String> set, List<Set> listTree) { boolean ret = false; BufferedWriter bw = null; FileWriter fw = null; File file = null; PrintWriter pw = null; OutputStreamWriter osw = null; FileOutputStream fo = null; try { file = new File(fileName); fw = new FileWriter(file); fo = new FileOutputStream(file); osw = new OutputStreamWriter(fo, code); bw = new BufferedWriter(osw); //fi=new FileInputStream(fileName); //isr=new InputStreamReader(fi,"UTF-8"); //reader = new BufferedReader(isr); int number = 1; String str=null; if (listTree != null) { for (Set s : listTree) { str=s.toString().substring(1,s.toString().length()-1); str=str.replaceAll(", "," "); bw.write(str); bw.newLine(); } } if (set != null) { for (String s : set) { //System.out.println(s + "-" + map.get(s)); bw.write(number++ + ","); bw.write(s); bw.newLine(); } } bw.flush(); ret = true; } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } if (fw != null) { try { fw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } return ret; }
9
public List<TipoCultivo> ObtenerTipoCultivo(String consulta){ List<TipoCultivo> lista=new ArrayList<TipoCultivo>(); if (!consulta.equals("")) { lista=cx.getObjects(consulta); }else { lista=null; } return lista; }
1
public Timenode getnode(int id, ArrayList<Object> list) { Timenode node = new Timenode(); for (Object tmp : list) { node = (Timenode) tmp; if (node.getId() == id) return node; } return node; }
2
public String nextToken() throws Exception { // Skip blanks. while (Character.isWhitespace(ch)) { nextChar(); } while (ch == ';') { line = reader.readLine(); nextChar(); } // At EOF? if (ch == 0) { return null; } //build the string StringBuilder buffer = new StringBuilder(); if ("'()".contains(Character.toString(ch))) { buffer.append(ch); nextChar(); return buffer.toString(); } while (!(" )".contains(Character.toString(ch)))) { buffer.append(ch); // build token string nextChar(); } return buffer.toString(); }
5
public Set<String> getPermissions() { return this.permissions; }
0
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
4
public void rotarDerecha() { if (direccion.equals(Direccion.izquierda)) { rotar(tipoTrans.enZ, 180); } else if (direccion.equals(Direccion.adelante)) { rotar(tipoTrans.enZ, -90); } else if (direccion.equals(Direccion.atras)) { rotar(tipoTrans.enZ, 90); } else if (direccion.equals(Direccion.adDer)) { rotar(tipoTrans.enZ, -45); } else if (direccion.equals(Direccion.adIzq)) { rotar(tipoTrans.enZ, -135); } else if (direccion.equals(Direccion.atDer)) { rotar(tipoTrans.enZ, 45); } else if (direccion.equals(Direccion.atIzq)) { rotar(tipoTrans.enZ, 135); } direccion = Direccion.derecha; }
7
public void setEffects() { switch(type) { case 0: typeString = "Splash"; splashRadius = 50*level; phrase1 = "Splash Radius: " + splashRadius; range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 1: typeString = "Gold"; extraGold = 50*level; phrase1 = "Gold/Kill: " + extraGold; range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 2: typeString = "Range"; extraRange = 70*level; phrase1 = "Extra Range: " + extraRange; range = 300+(50*level); damage = 2*level; reloadCount = 200-5*level; break; case 3: typeString = "Poison"; poisonDmg = 1*level;//poison damage per second poisonTime = 5000;//duration in milliseconds phrase1 = "Poison Dmg: " + poisonDmg; phrase2 = "Poison Time: " + (int)(poisonTime/1000); range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 4: typeString = "Slow"; slowPercent = 1-0.12*level; slowTime = 1500 + 400*level; phrase1 = "Slow Amount: " + (int)((100-(slowPercent*100))) + "%"; phrase2 = "Slow Time: " + (double)((double)slowTime/1000); range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 5: typeString = "Freeze"; freezeChance = 30; freezeTime = 500*level; phrase1 = "Freeze Chance: " + freezeChance + "%"; phrase2 = "Freeze Time: " + (double)((double)freezeTime/1000); range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 6: typeString = "Rapid"; reloadCount = 150-20*level; phrase1 = "Reload Time: " + (double)reloadCount/1000; range = 300; damage = 2*level; break; case 7: typeString = "Sight"; trueSightRange = 300+100*level; phrase1 = "Sight Range: " + trueSightRange; range = 300; damage = 2*level; reloadCount = 200-5*level; break; case 8: typeString = "Dizzy"; confusionChance = 30; confusionTime = 600*level; phrase1 = "Dizzy Chance: " + confusionChance + "%"; phrase2 = "Dizzy Time: " + (double)((double)confusionTime/(double)1000); range = 300; damage = 2*level; reloadCount = 200-5*level; break; } }
9
public short getType(String name) { name = String.valueOf(name).toUpperCase(); if (name.equals("HUFFMAN")) return HUFFMAN_TYPE; if (name.equals("ANS")) return ANS_TYPE; if (name.equals("FPAQ")) return FPAQ_TYPE; if (name.equals("PAQ")) return PAQ_TYPE; if (name.equals("RANGE")) return RANGE_TYPE; if (name.equals("CM")) return CM_TYPE; if (name.equals("NONE")) return NONE_TYPE; if (name.equals("TPAQ")) return TPAQ_TYPE; throw new IllegalArgumentException("Unsupported entropy codec type: " + name); }
8
private static QuoteOrigin getOrigin(String text) { if (text.contains("/אונקלוס")) { return QuoteOrigin.ONKELOS; } if (text.contains("/בבלי")) { return QuoteOrigin.BAVLI; } if (text.contains("/ירושלמי")) { return QuoteOrigin.YERUSHALMI; } if (text.contains("/ירושלמי הלכה")) { return QuoteOrigin.YERUSHALMI_HALACHA; } if (text.contains("/רבה")) { return QuoteOrigin.RABBAH; } if (text.contains("/תנ\"ך")) { return QuoteOrigin.TANAKH; } if (text.contains("/ללא")) { return QuoteOrigin.WITHOUT; } return QuoteOrigin.EMPTY; }
7
private void init() { for (int x = 0; x < 10; x++) { int randx = random.nextInt(10); int randy = random.nextInt(10); addActor(ActorType.chicken, new Point(25000 + randx, 25000 + randy));//THis should add chickens } // for (int x = 0; x < 10; x++) { // int randx = random.nextInt(10); // int randy = random.nextInt(10); // addActor(ActorType.fox, // new Point(25000 + randx, 25000 + randy)); // } }
1
public void startServer(){ ServerSocket server=null; try { try{ fetchUsers(); } catch (FileManagerException e){ FileManager.placeToLog(e.getMessage()); users=new ConcurrentLinkedDeque<>(); } server = new ServerSocket(PORT); server.setSoTimeout(TIMEOUT_DELAY); while(working){ try{ InteractionThread interactionThread = new InteractionThread(server.accept()); interactionThread.start(); } catch (SocketTimeoutException e) { System.out.println("Timeout..."); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (server!=null) server.close(); } catch (IOException e) { e.printStackTrace(); } FileManager.saveUsersToFile(users); } }
6
public void dropNew() { // Get all available items String[] playerItems = player.getInventory().getItemTexts(); if (playerItems.length == 0) { log.println("You have nothing to drop."); } else { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 1)); final JCheckBox[] checkBoxes = new JCheckBox[playerItems.length]; final String idsString = descriptionsToIDString(playerItems); ButtonGroup buttons = new ButtonGroup(); // Set up actions for every ID to toggle the appropriate checkbox Action charAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { int index = idsString.indexOf(e.getActionCommand()); if (index != -1) { JCheckBox box = checkBoxes[index]; box.setSelected(!box.isSelected()); } else { println(e.getActionCommand() + " is not a valid ID, do you have capslock on?"); } } }; int itemCount = 0; panel.add(new JLabel("INVENTORY")); for (String f : playerItems) { JCheckBox newBox = new JCheckBox(f); newBox.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(idsString.substring(itemCount, itemCount+1).toUpperCase()), f); newBox.getActionMap().put(f, charAction); checkBoxes[itemCount] = newBox; panel.add(newBox); itemCount++; } JOptionPane.showMessageDialog(null, panel, "What would you like to drop?", JOptionPane.PLAIN_MESSAGE); for (JCheckBox box : checkBoxes) { if (box.isSelected()) { // Get the selected item Character id = box.getText().charAt(0); Holdable item; try { item = player.getInventory().getItem(id); if (item.isStackable()) item = player.getInventory().removeStackedItem(id, 1); else item = player.getInventory().removeItem(id); player.getLocation().addItem(item); println("You drop the " + item.properName() + " on the floor."); } catch (InvalidKeyException e) { log.println("The item you picked was invalid"); } } } } updateTile(player.getLocation().getColumn(), player.getLocation().getRow()); }
7
private String prevediIzLatiniceUCirilicu(String rec) { String recLatinica = ""; String slovo = ""; char c; niz: for (int i = 0; i < rec.length(); i++) { //provera da li su u pitanju dvoslovna slova if ((i != rec.length() - 1 && String.valueOf(rec.charAt(i + 1)).equalsIgnoreCase("j") && dvoslovnaSlova.indexOf(String.valueOf(rec.charAt(i)).toLowerCase()) != -1) || (i != rec.length() - 1 && String.valueOf(rec.charAt(i + 1)).equalsIgnoreCase("ž") && String.valueOf(rec.charAt(i)).equalsIgnoreCase("d"))) { slovo = slovo + String.valueOf(rec.charAt(i)); continue niz; } if (slovo.length() < 1) { slovo = (String) latinicaCirilica.get(String.valueOf(rec.charAt(i))); } else { slovo = (String) latinicaCirilica.get(slovo + String.valueOf(rec.charAt(i))); } if (slovo != null) { recLatinica = recLatinica + slovo; } else { recLatinica = recLatinica + rec.charAt(i); } slovo = ""; } return recLatinica; }
9
public double[] columnVariances(){ double[] variances = new double[this.numberOfColumns]; for(int i=0; i<this.numberOfColumns; i++){ double[] hold = new double[this.numberOfRows]; for(int j=0; j<this.numberOfRows; j++){ hold[i] = this.matrix[j][i]; } Stat st = new Stat(hold); variances[i] = st.variance(); } return variances; }
2
public String getStrada() { return strada; }
0
public void manger(Aliment mange, int quantite, Loft plateau){ if (plateau.plateauCase.get(this.getPosition()).contenuNeuneu.size() >1){ int k=0; for (Neuneu neuneu : plateau.plateauCase.get(this.getPosition()).contenuNeuneu ){ while (k==0){ if (neuneu.getId_joueur() != this.getId_joueur()){ // position ddu neuneu dans la liste d'aliment que contient la case // augmenter energie du cannibale this.energie=this.energie + neuneu.getEnergie(); // supprimer le neuneu mange de la partie plateau.plateauCase.get(this.position).contenuNeuneu.remove(neuneu); plateau.population.remove(neuneu); k+=1; } } } } //boolean existe=false; for (Aliment nouri : plateau.plateauCase.get(this.getPosition()).contenuAliment ){ // Si l'element a manger est contenu dans la case // A voir : condition sur le droit de manger un aliment ou pas ? if ((nouri.getNom() == mange.getNom())&&(this.nourriture==mange.getNom())) { // si la quantite dans la case est suffisante if (nouri.quantite >= quantite){ int i=0; // position de l'aliement dans la liste d'aliment que contient la case i = plateau.plateauCase.get(this.position).contenuAliment.indexOf(nouri); plateau.plateauCase.get(this.getPosition()).contenuAliment.get(i).setQuantite(plateau.plateauCase.get(this.getPosition()).contenuAliment.get(i).getQuantite()-quantite); //on augmente l energie this.energie=this.energie + (quantite)*(plateau.plateauCase.get(this.getPosition()).contenuAliment.get(i).getEnergie()); } // sinon, on consomme tout et on supprime l'aliment de la liste dans la case else { int i = plateau.plateauCase.get(this.getPosition()).contenuAliment.indexOf(nouri); this.energie=this.energie + (plateau.plateauCase.get(this.getPosition()).contenuAliment.get(i).getQuantite())*(plateau.plateauCase.get(this.getPosition()).contenuAliment.get(i).getEnergie()); plateau.plateauCase.get(this.getPosition()).contenuAliment.remove(i); } } } }
8
public void setPersonId(int personId) { this.personId = personId; }
0
public static void saveToFile(String fileName, InputStream in) { FileOutputStream fos = null; BufferedInputStream bis = null; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; bis = new BufferedInputStream(in); try { fos = new FileOutputStream(fileName); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } } catch (Exception e) { LogUtil.exception(logger, e); } finally { try { if (fos != null) { fos.close(); } } catch (IOException e) { LogUtil.exception(logger, e); } try { if (bis != null) { bis.close(); } } catch (IOException e) { LogUtil.exception(logger, e); } try { if (in != null) { in.close(); } } catch (IOException e) { LogUtil.exception(logger, e); } } }
8
private static List<Cards> choose2(Cards cards) { // Given a list of cards, give me back a list of the // complete list of subsets of size num int size = cards.size(); List<Cards> subsets = new ArrayList<Cards>(); for (int i1 = 0; i1 < size - 1; i1++) { Cards subset = new Cards(); subset.add(cards.get(i1)); for (int i2 = i1 + 1; i2 < size; i2++) { Cards subset1 = new Cards(subset); subset1.add(cards.get(i2)); subsets.add(subset1); } } return subsets; }
2
@Override protected void parseSelf(Document doc) throws ProblemsReadingDocumentException { List<?> result = queryXPathList(TITLE_XPATH, doc); if ((result != null) && (result.size()>0)) setTitle(((Element) result.get(0)).getText()); else throw new ProblemsReadingDocumentException("Can't read discography title"); // now detect type of Discography result = queryXPathList(SIDEBAR_DIV_XPATH, doc); if (result.size()>0) { variant = DiscographyListVariant.SIDEBAR; return; } result = queryXPathList(INDEX_DIV_XPATH, doc); if (result.size()>0) { variant = DiscographyListVariant.CENTRAL_INDEX; return; } throw new ProblemsReadingDocumentException("Can't detect discography type"); }
5
private boolean register(String id) { ConnectionConfiguration config = new ConnectionConfiguration( XMPP_SERVER, XMPP_PORT); Connection connection = new XMPPConnection(config); if (registeredLastTime && REGISTRATION_DELAY > 0) { System.out.println("Sleeping for " + REGISTRATION_DELAY + " minutes. Need to wait for " + XMPP_SERVER); try { // macjabber.de allows new account creation only every x // minutes Thread.sleep(REGISTRATION_DELAY * 60000 + 10); } catch (InterruptedException e1) { System.err.println("Can't sleep"); } } try { connection.connect(); } catch (XMPPException e) { e.printStackTrace(); return false; } if (!connection.isAuthenticated()) { AccountManager acManager = connection.getAccountManager(); try { acManager.createAccount(id, XMPP_PASSWORD); } catch (XMPPException e) { e.printStackTrace(); return false; } finally { registeredLastTime = true; connection.disconnect(); } } else { connection.disconnect(); } return true; }
6
private void parseCommand(String command) { // Commands: // !new-bid <description> // !auction-ended <winner> <amount> <description> String cmdRegex = "![a-zA-Z-]+"; String tmp; Scanner sc = new Scanner(command); sc.useDelimiter("\\s+"); sc.skip("\\s*"); if (!sc.hasNext(cmdRegex)) return; tmp = sc.next(); if (tmp.equalsIgnoreCase("!new-bid")) { if (!sc.hasNext()) return; String description = sc.skip("\\s*").nextLine(); if (listener != null) listener.newBid(description); } else if (tmp.equalsIgnoreCase("!auction-ended")) { if (!sc.hasNext()) return; String winner = sc.next(); if (!sc.hasNextDouble()) return; double amount = sc.nextDouble(); if (!sc.hasNext()) return; String description = sc.skip("\\s*").nextLine(); if (listener != null) listener.auctionEnded(winner, amount, description); } }
9
@Override public void Area(double dx) { this.hight+=dx; this.rad+=dx; this.area = 2*Math.PI*rad*(rad+hight); }
0
public static void stop() { try { System.out.println("main: stop the program"); // eventually write the statistics if (!win) { Gui.writeStatus(); } System.out.println("main: statistics written"); // Wait for the images to complete while (Gui.pro.size() != 0) { Gui.pro.get(0).join(); Gui.pro.remove(0); } System.out.println("main: all images written"); // Disconect the bricks while (BrickGame.bricks.size() != 0) { System.out.println(BrickGame.bricks.get(0).name + ": disconnect"); BrickGame.bricks.get(0).shutdown(); BrickGame.bricks.remove(0); } System.out.println("main: all bricks disconnected, end..."); // Close it System.exit(0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(0); } }
4
public void set_order_to() { if(Idx!=null) { if(Idx.fidx!=null) { try { Idx.fidx.close(); } catch (IOException e) { e.printStackTrace(); } } Idx = null; } order = ""; if(Cdx!=null) Cdx.I = -1; }
4
private int neighbors(int row, int col) { int count = 0; for(int r = row-1; r <= row+1; r++) for(int c = col-1; c <= col+1; c++) { if(r < 0 || r >= map.length || c < 0 || c >= map[0].length) continue; if(map[r][c] == true) count++; } if(map[row][col] == true) count--; return count; }
8
public MBB3D getMBB() { // Dag if (size() > 0) { Iterator<Point3D> it = this.iterator(); it.hasNext(); Point3D p = it.next(); double xMin = p.getX(); double yMin = p.getY(); double zMin = p.getZ(); double xMax = xMin; double yMax = yMin; double zMax = zMin; double value; while (it.hasNext()) { p = it.next(); value = p.getX(); if (xMin > value) xMin = value; else if (xMax < value) xMax = value; value = p.getY(); if (yMin > value) yMin = value; else if (yMax < value) yMax = value; value = p.getZ(); if (zMin > value) zMin = value; else if (zMax < value) zMax = value; } Point3D pMin = new Point3D(xMin, yMin, zMin); Point3D pMax = new Point3D(xMax, yMax, zMax); return new MBB3D(pMin, pMax); } return null; }
8
String classToType(Class cls) { if (cls==Point.class) { return "int2"; } else if (cls==Integer.TYPE || cls==Integer.class ) { return "int"; } else if (cls==Double.TYPE || cls==Double.class ) { return "double"; } else if (cls==String.class) { return "String"; } else if (cls==Boolean.TYPE || cls==Boolean.class ) { return "boolean"; } else { return null; } }
8
private void validate(Match match) { if (match == null) { throw new ValidationException("match is null"); } if (match.getHomeTeam() == null || match.getAwayTeam() == null) { throw new ValidationException("match team is null"); } if (match.getResult() == null) { throw new ValidationException("match result null"); } if (match.getDatePlayed() == null) { throw new ValidationException("match date null"); } if (match.getResult() == null) { throw new ValidationException("match result null"); } }
6
public String get(String path,String fsxml,String mimetype) { if (auth==null) { auth = getAuth(); } String url = "http://"+ipnumber+":"+port+"/"+name+"/proxy/"+path; if (url.indexOf("?")!=-1) { url+= "&spw="+auth; } else { url+= "?spw="+auth; } System.out.println("PROXY URL: " + url); Response result = HttpHelper.sendRequest("GET",url,fsxml); if (result!=null) { int status = result.getStatusCode(); if (status==200) return result.getResponse(); if (status==410) { auth = getAuth(); // get the new auth ! url = "http://"+ipnumber+":"+port+"/"+name+"/proxy/"+path; if (url.indexOf("?")!=-1) { url+= "&spw="+auth; } else { url+= "?spw="+auth; } result = HttpHelper.sendRequest("GET",url,fsxml); if (result!=null) { if (status==200) return result.getResponse(); } } } return null; }
8
private void delete() throws SQLException { if (gui.connected) { int row = table.getSelectedRow(); if (row != -1) { rslt.absolute(++row); try { rslt.deleteRow(); reload(); } catch (SQLException e) { state("cant delete insert row"); gui.handleSQLException(e); } } else { state("can't delete --> no row selected"); } } else state("can't delete --> not connected"); }
3
public void run() { String s; try { System.out.println(timeStamp.getCurrentTime() + "::" +"Starting Status thread"); statusSocket = new ServerSocket(statusPort); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } while (true) { try { statusAcceptSocket = statusSocket.accept(); System.out.println(timeStamp.getCurrentTime() + "::" + "Incoming connection from Loadbalancer"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { lbIn = new DataInputStream(statusAcceptSocket.getInputStream()); lbOut = new DataOutputStream(statusAcceptSocket.getOutputStream()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { lbOut.writeUTF("Server Status OK"); s = lbIn.readUTF(); System.out.println(timeStamp.getCurrentTime() + "::" +"Load balancer says " + s); lbOut.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4
@RequestMapping("/startQuiz") public ModelAndView startQuiz(@ModelAttribute QuizQuestion question, HttpServletRequest request) { System.out.println("In startQuiz"); ModelAndView mv = new ModelAndView("viewQuizQuestion"); String courseId = request.getParameter("courseId"); String quizId = request.getParameter("quizId"); int questionNum = Integer.parseInt(request.getParameter("questNum")); String studentResponse = question.getAnswer(); //System.out.println(request.getSession().getAttribute("currRole")); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml"); courseDAO courseDAO = ctx.getBean("courseDAO", courseDAO.class); List<QuizQuestion> questions = courseDAO.getQuizQuestions(courseId, quizId); //mv.addObject("questionList", questions); //System.out.println(questions.get(questionNum).getQuestionNum()); mv.addObject("courseId", courseId); mv.addObject("quizId", quizId); mv.addObject("totalQuestions", questions.size()); float one = 1; float percForOneAnswer = one/questions.size() * 100; if(questionNum <= questions.size() +1 ){ System.out.println(questionNum); String correctAnswer = null; if(questionNum != 1) correctAnswer = questions.get(questionNum-2).getAnswer(); System.out.println("Correct answer: "+ correctAnswer); System.out.println("Response: " + studentResponse); if(studentResponse != null){ if(studentResponse.equalsIgnoreCase(correctAnswer)) { System.out.println("Correct Answer"); System.out.println(request.getSession().getAttribute("score")); Object sessionScore = request.getSession().getAttribute("score"); if(sessionScore == null)// || Integer.parseInt(request.getSession().getAttribute("score").toString()) == 0) { request.getSession().setAttribute("score", percForOneAnswer); } else { float prevScore = Float.parseFloat(request.getSession().getAttribute("score").toString()); request.getSession().setAttribute("score", prevScore + percForOneAnswer ); } } } } System.out.println("Current score is: " + request.getSession().getAttribute("score")); if(questionNum <= questions.size()) mv.addObject("question", questions.get(questionNum-1)); mv.addObject("currQues",questionNum); mv.addObject("role", request.getSession().getAttribute("currRole")); return mv; }
6
@Test(expected = ParkException.class) public void out_a_car_when_park_is_empty() { Park park = new Park(10); park.out(new Ticket()); }
0
Class318_Sub7(AbstractToolkit var_ha, Class129 class129, Class318_Sub10 class318_sub10, long l) { ((Class318_Sub7) this).aClass284_6444 = new Class284(); aClass284_6449 = new Class284(); aBoolean6453 = false; try { aLong6435 = l; ((Class318_Sub7) this).aClass129_6436 = class129; ((Class318_Sub7) this).aClass318_Sub10_6439 = class318_sub10; ((Class318_Sub7) this).aClass181_6441 = ((Class318_Sub7) this).aClass129_6436.method1125((byte) 59); if (!var_ha.method3644() && ((((Class181) ((Class318_Sub7) this).aClass181_6441) .anInt2387) ^ 0xffffffff) != 0) ((Class318_Sub7) this).aClass181_6441 = AbstractMouseListener.method3591((((Class181) (((Class318_Sub7) this) .aClass181_6441)) .anInt2387), 0); ((Class318_Sub7) this).aClass243_6433 = new Class243(); anInt6434 += 64.0 * Math.random(); method2507(true); ((Class284) aClass284_6449).anInt3680 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3680; ((Class284) aClass284_6449).anInt3669 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3669; ((Class284) aClass284_6449).anInt3668 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3668; ((Class284) aClass284_6449).anInt3675 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3675; ((Class284) aClass284_6449).anInt3670 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3670; ((Class284) aClass284_6449).anInt3678 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3678; ((Class284) aClass284_6449).anInt3666 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3666; ((Class284) aClass284_6449).anInt3672 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3672; ((Class284) aClass284_6449).anInt3679 = ((Class284) ((Class318_Sub7) this).aClass284_6444).anInt3679; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929 (runtimeexception, ("rba.<init>(" + (var_ha != null ? "{...}" : "null") + ',' + (class129 != null ? "{...}" : "null") + ',' + (class318_sub10 != null ? "{...}" : "null") + ',' + l + ')')); } }
6
protected void getClosePlants() { Thread radarThread = new Thread(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { // True if this creature is alive while (isAlive()) { // clone the Grid.plants, the centralised repository of // plants, so there will less concurrent conflict Vector<Plant> pla; synchronized (Grid.plants) { pla = (Vector<Plant>) Grid.plants.clone(); for (Iterator<Plant> iterator = pla.iterator(); iterator .hasNext();) { Plant plant = iterator.next(); Point pos = plant.getPosition(); try { if (isPlantInRange(pos)) { if (plants.size() < PLANT_LIMIT) { setPosition(pos); plant.take(); plants.add(plant); iterator.remove(); synchronized (Grid.plants) { // assigns the remaining plants to // the // main // plant repository Grid.plants = pla; } } } } catch (ConcurrentModificationException e2) { continue; } } } } } }); radarThread.setDaemon(true); radarThread.start(); }
5
public static void updateFonts() { font = new Font(Preferences.getPreferenceString(Preferences.FONT_FACE).cur, Font.PLAIN, Preferences.getPreferenceInt(Preferences.FONT_SIZE).cur); readOnlyFont = new Font(Preferences.getPreferenceString(Preferences.FONT_FACE).cur, Font.ITALIC, Preferences.getPreferenceInt(Preferences.FONT_SIZE).cur); immoveableFont = new Font(Preferences.getPreferenceString(Preferences.FONT_FACE).cur, Font.BOLD, Preferences.getPreferenceInt(Preferences.FONT_SIZE).cur); immoveableReadOnlyFont = new Font(Preferences.getPreferenceString(Preferences.FONT_FACE).cur, Font.BOLD + Font.ITALIC, Preferences.getPreferenceInt(Preferences.FONT_SIZE).cur); }
0
private void createRootWindowProperties(GradientTheme theme) { rootProperties.getTabWindowProperties().getTabbedPanelProperties().addSuperObject(theme.getTabbedPanelProperties()); rootProperties.getTabWindowProperties().getTabProperties().getTitledTabProperties().addSuperObject( theme.getTitledTabProperties()); rootProperties.getTabWindowProperties().getCloseButtonProperties().setVisible(false); if (!shadowEnabled) rootProperties.getWindowAreaProperties().setInsets(new Insets(6, 6, 6, 6)); rootProperties.getWindowAreaShapedPanelProperties().setComponentPainter(new GradientComponentPainter( UIManagerColorProvider.DESKTOP_BACKGROUND, new ColorMultiplier(UIManagerColorProvider.DESKTOP_BACKGROUND, 0.9f), new ColorMultiplier(UIManagerColorProvider.DESKTOP_BACKGROUND, 0.9f), new ColorMultiplier(UIManagerColorProvider.DESKTOP_BACKGROUND, 0.8f))); rootProperties.getWindowAreaProperties().setBorder(new LineBorder(Color.BLACK)); if (tabAreaBackgroundColor != null) rootProperties.getComponentProperties().setBackgroundColor(tabAreaBackgroundColor); if (!shadowEnabled) rootProperties.getSplitWindowProperties().setDividerSize(6); TitledTabProperties tabProperties = rootProperties.getTabWindowProperties().getTabProperties() .getTitledTabProperties(); tabProperties.getNormalProperties().setIconVisible(false); tabProperties.getHighlightedProperties().setIconVisible(true); if (!highlightedBold) tabProperties.getHighlightedProperties(). getComponentProperties().getMap(). createRelativeRef(ComponentProperties.FONT, tabProperties.getNormalProperties().getComponentProperties().getMap(), ComponentProperties.FONT); if (focusHighlighterEnabled) { tabProperties.getHighlightedProperties().getComponentProperties() .setBorder(new CompoundBorder(opaqueTabArea ? (Border) new TabAreaLineBorder(false, false, true, true) : new TabAreaLineBorder(borderColor), theme.getTabAreaComponentsGradientBorder())); rootProperties.getTabWindowProperties().getTabProperties().getFocusedProperties().getComponentProperties() .setBorder(new CompoundBorder(opaqueTabArea ? (Border) new TabAreaLineBorder(false, false, true, true) : new TabAreaLineBorder(borderColor), theme.getHighlightedTabGradientBorder())); } rootProperties.getTabWindowProperties().getTabbedPanelProperties().getTabAreaComponentsProperties() .getComponentProperties().setInsets(opaqueTabArea ? new Insets(0, 3, 0, 3) : new Insets(1, 3, 1, 3)); rootProperties.getTabWindowProperties().getTabProperties().getHighlightedButtonProperties() .getCloseButtonProperties() .setVisible(false); rootProperties.getTabWindowProperties().getTabProperties().getHighlightedButtonProperties() .getMinimizeButtonProperties() .setVisible(true); rootProperties.getTabWindowProperties().getTabProperties().getHighlightedButtonProperties() .getRestoreButtonProperties() .setVisible(true); }
8
private String getVersionfinal (Class classe) { String version = ""; try { ClassLoader cl = this.getClass().getClassLoader(); String threadContexteClass = classe.getName().replace('.', '/'); URL url = cl.getResource(threadContexteClass + ".class"); if ( url != null ) { String path = url.getPath(); String jarExt = ".jar"; int index = path.indexOf(jarExt); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm"); if (index != -1) { String jarPath = path.substring(0, index + jarExt.length()); File file = new File(jarPath); JarFile jarFile = new JarFile(new File(new URI(jarPath))); JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF"); version = sdf.format(new Date(entry.getTime())); } else { File file = new File(path); version = sdf.format(new Date(file.lastModified())); } } } catch (URISyntaxException ex) { Logger.getLogger(JAboutDialog.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JAboutDialog.class.getName()).log(Level.SEVERE, null, ex); } return version; }
4
public RoomEventType(final String name) { super(name); }
0
public void remover(long pesquisaId) throws Exception { String sql = "DELETE FROM Pesquisainstituicoes_cooperadoras WHERE id1 = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setLong(1, pesquisaId); stmt.execute(); } catch (SQLException e) { throw e; } }
1
public List<AngularBond> getBends() { if (model == null) return null; if (model.bends == null || model.bends.isEmpty()) return null; List<AngularBond> list = null; AngularBond aBond = null; synchronized (model.bends.getSynchronizationLock()) { for (Iterator it = model.bends.iterator(); it.hasNext();) { aBond = (AngularBond) it.next(); if (contains(aBond.getAtom1()) && contains(aBond.getAtom2()) && contains(aBond.getAtom3())) { if (list == null) list = new ArrayList<AngularBond>(); list.add(aBond); } } } return list; }
8
public void setOrderList() { listModel.clear(); for (Order order : driver.getOrderDB().getCustomerOrderList()) { if(order.isStatus()) listModel.addElement(textAlignment(" " + order.getId(), "" + order.getDateString(), "" +order.getPerson().getName(), "" +order.getCurrentlyLoggedInStaff().getName(), "\u2713")); else listModel.addElement(textAlignment(" " + order.getId(), "" + order.getDateString(), "" + order.getPerson().getId(), "" + order.getCurrentlyLoggedInStaff().getId(), "")); } scrollBar = listSroll.getVerticalScrollBar(); scrollBar.setValue(listSroll.getVerticalScrollBar().getMaximum()); }
2
@EventHandler public void SlimeSpeed(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getSlimeConfig().getDouble("Slime.Speed.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getSlimeConfig().getBoolean("Slime.Speed.Enabled", true) && damager instanceof Slime && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, plugin.getSlimeConfig().getInt("Slime.Speed.Time"), plugin.getSlimeConfig().getInt("Slime.Speed.Power"))); } }
6
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Dataset)) { return false; } Dataset other = (Dataset) object; if ((this.key == null && other.key != null) || (this.key != null && !this.key.equals(other.key))) { return false; } return true; }
5
public InferenceIdentifier getInferenceIdentifier() { if (inferenceWorker != null) { return inferenceWorker.getInferenceIdentifier(); } return null; }
1
public String getPartnerName() { if(conProt == null && internetCon == null) return ""; if(conProt != null) { if(conProt.getConnectedName().equals("null") && getLANConnections()) return "Unidentified System"; if(!conProt.getConnectedName().equals("")) return conProt.getConnectedName(); } if(internetCon != null) { if(!internetCon.getPartner().equals("")) return internetCon.getPartner(); } return ""; }
8
public void setPrice(String price) { this.price = price; }
0
private void trySetUTFEncoding() { try { setEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { System.err.println("Cannot set UTF-8 encoding."); } }
1
public SessionListPanel() { final SessionTableModel dm = new SessionTableModel(); final JTable t = new JTable(dm); dm.setTable(t); t.getColumnModel().getColumn(1).setCellRenderer( new DefaultTableCellRenderer() { /** * */ private static final long serialVersionUID = -6163179793076760086L; @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (((Boolean) value)) { this.setIcon(new ImageIcon(OpenRayServer.class .getResource("/thinclient.png"))); } else { this.setIcon(null); } value = ""; return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }); t.getColumnModel().getColumn(1).setMaxWidth(17); t.getColumnModel().getColumn(1).setMaxWidth(17); t.getColumnModel().getColumn(1).setPreferredWidth(17); t.getColumnModel().getColumn(2).setCellRenderer( new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (((Integer) value) == 1) { this.setIcon(new ImageIcon(OpenRayServer.class .getResource("/card.png"))); } else if (((Integer) value) == 2) { this.setIcon(new ImageIcon(OpenRayServer.class .getResource("/card_red.png"))); } else { this.setIcon(null); } value = ""; return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } }); t.getColumnModel().getColumn(2).setMaxWidth(17); t.getColumnModel().getColumn(2).setMaxWidth(17); t.getColumnModel().getColumn(2).setPreferredWidth(17); this.setLayout(new BorderLayout()); JPanel tools = new JPanel(); tools.setOpaque(false); tools.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(2, 2, 3, 2); c.gridx = 0; c.gridy = 0; final JButton removeSessionButton = new JButton("Remove"); tools.add(removeSessionButton, c); c.gridx++; final JButton addSessionButton = new JButton("Add"); tools.add(addSessionButton, c); JPanel blank = new JPanel(); blank.setOpaque(false); c.weightx = 1; c.gridx++; tools.add(blank, c); this.add(tools, BorderLayout.NORTH); split = new JSplitPane(); JScrollPane comp = new JScrollPane(t); comp.setMinimumSize(new Dimension(200, 200)); comp.setPreferredSize(new Dimension(200, 200)); split.setLeftComponent(comp); split.setRightComponent(new JPanel()); this.add(split, BorderLayout.CENTER); t.getSelectionModel().setSelectionMode( ListSelectionModel.SINGLE_SELECTION); t.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int first = t.getSelectedRow(); if (first >= 0) { Session c = dm.getSession(first); if (split.getRightComponent() instanceof SessionPropertiesPanel) { SessionPropertiesPanel up = (SessionPropertiesPanel) split .getRightComponent(); if (up.getCurrentSession().equals(c)) { return; } } if (c != null) { split .setRightComponent(new SessionPropertiesPanel( c)); } else { System.err .println("SessionListPanel: First index:" + first); } } } } }); addSessionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Session u = new Session("New session"); SessionManager.getInstance().addOrUpdate(u); } }); removeSessionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int first = t.getSelectedRow(); if (first >= 0) { Session c = dm.getSession(first); SessionManager.getInstance().remove(c); } } }); }
9
private int berekenIndex(boolean top, boolean right, boolean bottom, boolean left){ int index = 0; if(top) index += 1; if(right) index += 2; if(bottom) index += 4; if(left) index += 8; return index; }
4
@Override public List<IllnessDTO> getAllIllnesses() throws SQLException { Session session = null; List<IllnessDTO> illnesses = new ArrayList<IllnessDTO>(); try { session = HibernateUtil.getSessionFactory().openSession(); illnesses = session.createCriteria(IllnessDTO.class).list(); } catch (Exception e) { System.err.println("Error while getting all the medTypes!"); } finally { if (session != null && session.isOpen()) { session.close(); } } return illnesses; }
3
private String padTo(String padee, int length) { if (padee.length() >= length) return padee; StringBuilder builder = new StringBuilder(); for (int i = padee.length(); i < length; i++) { builder.append(" "); } builder.append(padee); return builder.toString(); }
2
public static long getDate(String buffer) { if (buffer != null) { buffer = buffer.trim(); for (int i = DateFormat.FULL; i <= DateFormat.SHORT; i++) { try { return DateFormat.getDateInstance(i).parse(buffer).getTime(); } catch (Exception exception) { // Ignore } } } return System.currentTimeMillis(); }
3
protected Name parseName(String contents) { int firstSlash = contents.indexOf('/'); int lastSlash = contents.indexOf('/', firstSlash + 1); String surname = null; String givenname = null; if (firstSlash >= 0 && lastSlash > firstSlash) { surname = contents.substring(firstSlash + 1, lastSlash); surname = surname.trim(); if (firstSlash > 0) { givenname = contents.substring(0, firstSlash); } else { givenname = contents.substring(lastSlash + 1); } if (givenname != null) { givenname = givenname.trim(); } } else { givenname = contents.trim(); } return new Name(givenname, surname); }
4
public void log(String message) { //skip if no writer if (this.bufferedWriter == null) return; try { //write message String logMessage = String.format("[%s] %s", Logger.FORMATTER.format(LocalDateTime.now()), message); this.bufferedWriter.write(logMessage + System.lineSeparator()); this.bufferedWriter.flush(); } catch (IOException ioException) { } }
2
private static ArrayList<NumberToken> toTokens(ArrayList<String> in){ assert (in != null); ArrayList<NumberToken> toReturn = new ArrayList<NumberToken>(in.size()-1); for (String s : in){ NumberToken toAdd = new NumberToken(s); // If we couldn't create a valid token, return failure if (toAdd.type == null){ return null; } assert(toAdd.value != 0) : "No value should be zero - it should be -1 if N/A"; toReturn.add(toAdd); } if (toReturn.size() == 0){ em.error("No tokens."); return null; } return toReturn; }
3
public List<Cineplex> getCineplexes(int month) { cineplexes = new ArrayList<Cineplex>(); for(Cineplex cineplex : cineplexDAO.getCineplexes()) { for(Cinema c : cineplex.getCinemas()) { for(ShowTime st : c.getShowTimes()) { calendar.setTime(st.getTime()); int sMonth = calendar.get(Calendar.MONTH); if(sMonth == month && !cineplexes.contains(cineplex)) { cineplexes.add(cineplex); break; } } } } return cineplexes; }
5
protected boolean isValidDrop(GameState state, int x, int y) { boolean nifu = true; for (int i = 0; nifu && i < 9; i++) { nifu = !(state.getPieceAt(x, i) instanceof Pawn && state.getPieceAt(x, i).getAllegiance() == this.getAllegiance()); } Piece tempRep = state.getPieceAt(x, y); state.mockDropPieceFromTable(this.allegiance, x, y, this); boolean uchifuzume = !state.isKingCheckmated(-this.allegiance); state.mockAddPieceToDropTable(this.allegiance, this); state.setPieceAt(x, y, tempRep); int space = -1; for (int i = 0; i < state.getCorrectDropTable(this.getAllegiance()).size(); i++) { if (state.getCorrectDropTable(this.getAllegiance()).get(i) == this) { space = i; } } return nifu && uchifuzume && state.getPieceAt(x, y) instanceof EmptyPiece && y != 4+4*this.allegiance && !state.willKingBeInCheckAfterDrop(x, y, this.getAllegiance(), space); }
9
private static ArrayList<String[]> makeGeneration(int poolSize) { ArrayList<String[]> decks = new ArrayList<String[]>(); for (int i = 0; i < poolSize; i++) { decks.add(Game.makeDeck()); } return decks; }
1
public void filter(byte[] samples, int offset, int length) { if (source == null || listener == null) { // nothing to filter - return return; } // calculate the listener's distance from the sound source float dx = (source.getX() - listener.getX()); float dy = (source.getY() - listener.getY()); float distance = (float)Math.sqrt(dx * dx + dy * dy); // set volume from 0 (no sound) to 1 float newVolume = (maxDistance - distance) / maxDistance; if (newVolume <= 0) { newVolume = 0; } // set the volume of the sample int shift = 0; for (int i=offset; i<offset+length; i+=2) { float volume = newVolume; // shift from the last volume to the new volume if (shift < NUM_SHIFTING_SAMPLES) { volume = lastVolume + (newVolume - lastVolume) * shift / NUM_SHIFTING_SAMPLES; shift++; } // change the volume of the sample short oldSample = getSample(samples, i); short newSample = (short)(oldSample * volume); setSample(samples, i, newSample); } lastVolume = newVolume; }
5
public void sincronizaClientes(){ PhpposAppConfigEntity appConfig = getAppConfig("id_pos"); if (appConfig != null) { List<VPosFuncionarios> vPosFuncionarios = facOracleDAO.getVPosFuncionarios( Integer.parseInt(appConfig.getValue())); for(VPosFuncionarios funcionario: vPosFuncionarios){ try { char c = funcionario.getFesEstado().toCharArray()[0]; logger.info("c = " + c+"\tfuncionario: " + funcionario.getFunNombres()+" " + funcionario.getFunApellidos()); switch (c){ case 'N': saveNewCustomer(funcionario); break; case 'U': updateCustomer(funcionario); break; case 'S': inactiveCustormer(funcionario); break; } } catch (DataAccessException e) { // e.printStackTrace(); logger.info("e.getMessage() = " + e.getMessage()); } catch (Exception e){ e.printStackTrace(); logger.info("e.getMessage() = " + e.getMessage()); } } } }
7
@Override protected boolean perform(final CommandSender sender, final Command command, final String label, final List<String> args, final Region region) { String access = RegionExecutor.parse(args, 0, "<Access>", sender); if (access == null) return false; if (region.access.contains(access)) { Main.courier.send(sender, "grant-already", access, RegionExecutor.formatName(region), RegionExecutor.formatWorld(region)); return true; } access = Bukkit.getOfflinePlayer(access).getName(); region.access.add(access); this.catalog.repository.saveRegion(region, false); Main.courier.send(sender, "grant", access, RegionExecutor.formatName(region), RegionExecutor.formatWorld(region)); final Player added = Bukkit.getServer().getPlayerExact(access); if (region.active && added != null) Main.courier.send(added, "grant-notify", sender.getName(), RegionExecutor.formatName(region), RegionExecutor.formatWorld(region)); return true; }
4