method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
49bb29be-ab3c-4b46-856c-9fa55ec2d921
1
public static void listManagersWith2Projects(EntityManager entityManager) { TypedQuery<Employee> query = entityManager.createQuery( "select m from Manager m where m.projects.size > 1", Employee.class); List<Employee> resultList = query.getResultList(); entityManager.close(); for (Employee employee : resultList) { System.out.println(employee); } }
5512b384-2204-47bf-8c5b-e6dd41f0eb9a
9
private void colorNeighboringO(int row, int column) { ArrayList<int[]> list = new ArrayList<int[]>(); int[] start = {row, column}; list.add(start); // int[] tmp = {0, 0}; int[] cPosition = {-1 , -1}; int cRow, cColumn; while (list.size() > 0) { cPosition = list.get(0); cRow = cPosition[0]; cColumn = cPosition[1]; if (cRow > 0 && board[cRow - 1][cColumn] == 'O') { int[] tmp = {cRow - 1, cColumn}; list.add(tmp); } if (cRow < rows - 1 && board[cRow + 1][cColumn] == 'O') { int[] tmp = {cRow + 1, cColumn}; list.add(tmp); } if (cColumn > 0 && board[cRow][cColumn - 1] == 'O') { int[] tmp = {cRow, cColumn - 1}; list.add(tmp); } if (cColumn < columns - 1 && board[cRow][cColumn + 1] == 'O') { int[] tmp = {cRow, cColumn + 1}; list.add(tmp); } board[cRow][cColumn] = 'T'; list.remove(0); } }
f163fec7-6bd9-47b2-878a-f5343424ff11
7
private String GetWordsTwentyAndAbove(int number) { if (number % 10 == 0 && number < 100) return GetDoubleDigitWord(number); if (number < 100) return GetDoubleDigitWord(number - (number % 10)) + GetWordOneThroughTwenty(number % 10); if (number < 1000) { String currentNumber = GetTripleDigitWord(number - (number % 100)); if (number % 100 != 0) currentNumber = currentNumber + "and"; if ((number % 100) < 20) currentNumber = currentNumber + GetWordOneThroughTwenty(number % 100); else currentNumber = currentNumber + GetDoubleDigitWord((number % 100) - (number % 10)) + GetWordOneThroughTwenty(number % 10); return currentNumber; } if (number == 1000) { return "onethousand"; } return ""; }
eae9a492-3765-4320-a039-31e2cfbcf646
1
public Color getColor() { if(color != null) return color; return defaultColor; }
4f5b266e-10e1-4d8a-9ccc-9ec830957ff7
1
public static void insertLigneCommandeFournisseur( int idcommandefournisseur, int idarticle, int quantite, Float prixht, Float prixttc, Float remise) throws SQLException { String query = ""; try { query = "INSERT INTO LIGNE_COMMANDE_FOURNISSEUR (ID_CMDFOUR,ID_ARTICLE,LGCOMFOUQTE,LGCOMFOUPXHT,LGCOMFOUPXTTC,LGCOMFOUREMISE) VALUES (?,?,?,?,?,?); "; PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query); pStatement.setInt(1, idcommandefournisseur); pStatement.setInt(2, idarticle); pStatement.setInt(3, quantite); pStatement.setFloat(4, prixht); pStatement.setFloat(5, prixttc); pStatement.setFloat(6, remise); pStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(RequetesLigneCommandeClient.class.getName()).log(Level.SEVERE, null, ex); } }
0b2bd62d-ee01-4be0-82ed-3d3ddafe5d16
0
@Test public void isEmptyRetunsTrueWhenEmptyTest() { BinaryHeap b = new BinaryHeap(); assertTrue(b.isEmpty()); }
a83f0425-5fa7-4b03-a38c-cbe91562c92c
9
void readMotif() { if (verbose) Timer.showStdErr("Loading Motifs and PWMs"); //--- // Sanity checks //--- String pwmsFileName = config.getDirDataVersion() + "/pwms.bin"; if (!Gpr.exists(pwmsFileName)) fatalError("Warning: Cannot open PWMs file " + pwmsFileName); String motifBinFileName = config.getBaseFileNameMotif() + ".bin"; if (!Gpr.exists(motifBinFileName)) fatalError("Warning: Cannot open Motifs file " + motifBinFileName); //--- // Load all PWMs //--- if (verbose) Timer.showStdErr("\tLoading PWMs from : " + pwmsFileName); Jaspar jaspar = new Jaspar(); jaspar.load(pwmsFileName); //--- // Read motifs //--- if (verbose) Timer.showStdErr("\tLoading Motifs from file '" + motifBinFileName + "'"); MarkerSerializer markerSerializer = new MarkerSerializer(); Markers motifsDb = markerSerializer.load(motifBinFileName); // Add (only) motif markers. The original motifs has to be serialized with Chromosomes, Genomes and other markers (otherwise it could have not been saved) SnpEffectPredictor snpEffectPredictor = config.getSnpEffectPredictor(); int countAddded = 0; for (Marker m : motifsDb) if (m instanceof Motif) { Motif motif = (Motif) m; // Connect motifs to their respective PWMs Pwm pwm = jaspar.getPwm(motif.getPwmId()); if (pwm != null) { // Set PWM and add to snpEffPredictor motif.setPwm(pwm); snpEffectPredictor.add(motif); countAddded++; } else Timer.showStdErr("Cannot find PWM for motif '" + motif.getId() + "'"); } if (verbose) Timer.showStdErr("\tMotif database: " + countAddded + " markers loaded."); }
b27075de-dddb-4b32-9e33-ce04b2369d62
0
public void setStatus(Status status) { this.status = status; }
17c8e5eb-879d-4ffb-9417-4d071753719b
2
public int maxSubArray2(int[] A) {// O(1) space if (A == null) return 0; int last = A[0]; int max = last; for (int i = 1; i < A.length; i++) { last = Math.max(A[i], last + A[i]); max = Math.max(last, max); // keep track of the largest sum } return max; }
c9d99905-349c-48f6-9479-c12fabee2d82
5
public final BooleanProperty selectedProperty() { if (null == selected) { selected = new BooleanPropertyBase() { @Override protected void invalidated() { if (null != getToggleGroup()) { if (get()) { getToggleGroup().selectToggle(OnOffSwitch.this); } else if (getToggleGroup().getSelectedToggle() == OnOffSwitch.this) { getToggleGroup().selectToggle(null); } } if (selected.get()) { fireSelectionEvent(new SelectionEvent(this, null, SelectionEvent.SELECT)); } else { fireSelectionEvent(new SelectionEvent(this, null, SelectionEvent.DESELECT)); } pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, get()); } @Override public Object getBean() { return this; } @Override public String getName() { return "on"; } }; } return selected; }
57b66c44-cdd5-446c-87e1-817aadd92a4a
0
@Test public void testSetPostition() throws IOException { System.out.println("setPostition"); int[] newPos = new int[2]; newPos[0] = 1; newPos[1] = 1; AntBrain ab = new AntBrain("cleverbrain1.brain"); Ant instance = new Ant(ab,true,0); instance.setPostition(newPos); // check getter to ensure setter works int[] result = instance.getPosition(); assertArrayEquals(newPos, result); }
78f9627a-9a15-4140-bb72-0dcbf6e86209
8
@Override protected ArrayList<PossibleTile> getLazyTiles(Board b) { ArrayList<PossibleTile> possibleTiles = new ArrayList<PossibleTile>(); int i = 1; boolean canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() - i, this.getY() - i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() - i, this.getY() + i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() + i, this.getY() - i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() + i, this.getY() + i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() - i, this.getY(), this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX() + i, this.getY(), this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX(), this.getY() - i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } i = 1; canSearch = true; while (canSearch) { PossibleTile pt = new PossibleTile(this.getX(), this.getY() + i, this); canSearch = decideToAddTile(b, possibleTiles, pt); i++; } return possibleTiles; }
23c25380-8080-471a-bfc6-5e3b23ead45b
5
private Element generateLiteral(Document document, Literal literal, Tag xmlRootTag) { Element literalEle = document.createElement(xmlRootTag.getXmlTag()); Element atomEle = document.createElement(Tag.ATOM.getXmlTag()); atomEle.appendChild(document.createTextNode(literal.getName())); if (literal.isNegation()) { Element negEle = document.createElement(Tag.NOT.getXmlTag()); negEle.appendChild(atomEle); atomEle = negEle; } literalEle.appendChild(atomEle); StringBuilder sb = new StringBuilder(); for (int i = 0; i < literal.getPredicatesSize(); i++) { if (i > 0) sb.append(DomConst.Literal.LITERAL_SEPARATOR); sb.append(literal.getPredicate(i)); } if (!DomConst.Literal.DEFAULT_PREDICATE_VALUE.equals(sb.toString())) { Element elePredicate = document.createElement(Tag.PREDICATE.getXmlTag()); elePredicate.appendChild(document.createTextNode(sb.toString())); literalEle.appendChild(elePredicate); } Element modeEle = generateMode(document, literal.getMode()); if (null != modeEle) literalEle.appendChild(modeEle); return literalEle; }
49e8df0e-7a25-441c-b864-70aabd55b40e
7
private static boolean multithread(final Option option) throws InterruptedException { Log.info("Using several threads: " + option.getNbThreads()); final ExecutorService executor = Executors.newFixedThreadPool(option.getNbThreads()); final AtomicBoolean errors = new AtomicBoolean(false); for (String s : option.getResult()) { final FileGroup group = new FileGroup(s, option.getExcludes(), option); for (final File f : group.getFiles()) { final Future<?> future = executor.submit(new Runnable() { public void run() { if (errors.get()) { return; } try { final boolean error = manageFileInternal(f, option); if (error) { errors.set(true); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); return errors.get(); }
de6bb2fd-8296-4245-9871-a1163fce9a47
4
private static <T> Optional<T> loadOpt( Map<String, Object> map, String mapKey, String envVar, String javaProp, Function<String, T> fromString) { if (System.getenv(envVar) != null) { return Optional.fromNullable(fromString.apply(System.getenv(envVar))); } if (System.getProperty(javaProp) != null) { return Optional.fromNullable(fromString.apply(System.getProperty(javaProp))); } if (map != null && map.containsKey(mapKey)) { return Optional.fromNullable((T)map.get(mapKey)); } return Optional.absent(); }
b6838c1f-6d81-4916-9faf-16ebf63b1e72
8
public void openTray(DialogTray tray) throws IllegalStateException, UnsupportedOperationException { if (tray == null) { throw new NullPointerException("Tray was null"); //$NON-NLS-1$ } if (getTray() != null) { throw new IllegalStateException("Tray was already open"); //$NON-NLS-1$ } if (!isCompatibleLayout(getShell().getLayout())) { throw new UnsupportedOperationException("Trays not supported with custom layouts"); //$NON-NLS-1$ } final Shell shell = getShell(); Control focusControl = shell.getDisplay().getFocusControl(); if (focusControl != null && isContained(shell, focusControl)) { nonTrayFocusControl = focusControl; } leftSeparator = new Label(shell, SWT.SEPARATOR | SWT.VERTICAL); leftSeparator.setLayoutData(new GridData(GridData.FILL_VERTICAL)); sash = new Sash(shell, SWT.VERTICAL); sash.setLayoutData(new GridData(GridData.FILL_VERTICAL)); rightSeparator = new Label(shell, SWT.SEPARATOR | SWT.VERTICAL); rightSeparator.setLayoutData(new GridData(GridData.FILL_VERTICAL)); trayControl = tray.createContents(shell); Rectangle clientArea = shell.getClientArea(); final GridData data = new GridData(GridData.FILL_VERTICAL); data.widthHint = trayControl.computeSize(SWT.DEFAULT, clientArea.height).x; trayControl.setLayoutData(data); int trayWidth = leftSeparator.computeSize(SWT.DEFAULT, clientArea.height).x + sash.computeSize(SWT.DEFAULT, clientArea.height).x + rightSeparator.computeSize(SWT.DEFAULT, clientArea.height).x + data.widthHint; Rectangle bounds = shell.getBounds(); shell.setBounds(bounds.x - ((getDefaultOrientation() == SWT.RIGHT_TO_LEFT) ? trayWidth : 0), bounds.y, bounds.width + trayWidth, bounds.height); sash.addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { if (event.detail != SWT.DRAG) { Rectangle clientArea = shell.getClientArea(); int newWidth = clientArea.width - event.x - (sash.getSize().x + rightSeparator.getSize().x); if (newWidth != data.widthHint) { data.widthHint = newWidth; shell.layout(); } } } }); shellWidth = shell.getSize().x; resizeListener = new ResizeListener(data, shell); shell.addControlListener (resizeListener); this.tray = tray; }
720580ff-03e4-4a30-96fe-07902271a17b
3
public static int GetLargestKeyInHashMap(HashMap<Integer, Boolean> map) { int num = 0; for(int i = 1; i <= map.keySet().size() + 1; i++) { System.out.println(i); if(map.containsKey(i)) { if(i > num) { num = i; } System.out.println(num); } } return num; }
0c980a1f-3f01-45ed-861f-15aac98e69d4
1
public void setSaveOperand(final Block block, final boolean flag) { final int blockIndex = cfg.preOrderIndex(block); saveOperand[blockIndex] = flag; if (SSAPRE.DEBUG) { System.out.println(this); } }
18b6cd09-9f0c-4179-9870-6b23d5d596c5
0
public int getCost() { return cost; }
2b9335d5-e595-4360-9389-f0095596404d
7
private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; }
b8cf2749-c708-42fe-8fb5-595a2deb8c93
0
public String value() { return value; }
04ad7a1a-4c99-430a-b014-cc1fad16baac
8
@Override public void init() { /* 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(SCAdministrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SCAdministrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SCAdministrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SCAdministrador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> hmp.LoadList(); System.out.println("Entra"); /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); try { loadDataToTableAula(); addItemsComoboxAulas(); } catch (SQLException ex) { Logger.getLogger(SCAdministrador.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (Exception ex) { ex.printStackTrace(); } }
da025eae-e109-40e6-81ca-6cc8c421043e
1
public void update(Avatar player,Map map,long gameTime) { for (MovingSquare movingSquare : movingSquares) { movingSquare.update(player,map,gameTime); } }
7373930f-f604-46dd-a635-0ccea52998ab
2
public FileSystemReplaceFileContentsHandler( String query, String replacement, FindReplaceResultsModel results, boolean isRegexp, boolean ignoreCase, boolean makeBackups, String lineEnding ) { super(lineEnding, false, FileContentsHandler.MODE_ARRAYS, Preferences.getPreferenceString(Preferences.OPEN_ENCODING).cur, Preferences.getPreferenceString(Preferences.SAVE_ENCODING).cur); this.results = results; this.isRegexp = isRegexp; this.ignoreCase = ignoreCase; this.makeBackups = makeBackups; if (!isRegexp && ignoreCase) { this.query = query.toLowerCase(); } else { this.query = query; } this.replacement = replacement; }
df7cd287-75da-417f-bc35-2849d85d4fd6
9
public static void writeFile(Preferences pref, File f, String content, boolean isBackup) { String fName = f.getAbsolutePath(); if (f.exists()) { if (!isBackup) { writeLog("File '" + f + "' already exists - not overwriting due to config option"); return; } File backup = new File(fName + ".bak"); if (backup.exists()) { if (backup.delete()) writeLog("Backup file " + backup + " exists and was deleted"); else { writeLog("Error deleting backup file " + backup); return ; } } File renameIt = new File(fName); if (renameIt.renameTo(backup)) { writeLog("File " + f + " is being backed up to " + backup); } else { writeLog("Error backing up file " + f); writeLog("No Backup exists for the file - be careful"); return ; } } if (f.exists()) { writeLog("File " + f +" still exist, writing failed!"); return; } BufferedReader in = null; BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(f)); in = new BufferedReader(new StringReader(content)); while (true) { String line = in.readLine(); if (line == null) break; out.write(line); out.write(Utilities.lineEnding); } writeLog("Successfully written to " + f); in.close(); out.flush(); out.close(); } catch (IOException e) { writeLog("Failed written to" + f + ": " + e.toString()); } }
d49de71a-d321-4d5b-a4df-8c2db577fb5d
4
private void colorHighTemp(int i, int j, long temp) { if (temp == MAX_TEMP) { drawing.setRGB(i, j, maxPoint); return; } if (temp == HIGH_TEMP) { drawing.setRGB(i, j, highPoint); return; } for (int k = 0; k < tempRangesHigh.length; k++) { if (temp < tempRangesHigh[k]) { drawing.setRGB(i, j, colorRangesHigh[k]); break; } } }
33dfe85a-c693-4b4c-ad46-f2ea9ded7055
8
private void buy(String type, int id) throws DataBaseConnectorException { if(type != null){ int cost = -1; if(type.equals("$tank$")){ cost = dataBaseConnector.getTankCost(id); } else if(type.equals("$armor$")){ cost = dataBaseConnector.getArmorCost(id); }else if(type.equals("$engine$")){ cost = dataBaseConnector.getEngineCost(id); }else if(type.equals("$first_weapon$")){ cost = dataBaseConnector.getFirstWeaponCost(id); }else if(type.equals("$second_weapon$")){ cost = dataBaseConnector.getSecondWeaponCost(id); } if(money >= cost && cost != -1){ garage.addPurchase(dataBaseConnector.makePurchase(userId, cost, type,id)); money -= cost; }else { close(); } }else{ close(); } }
a9ae32bd-e738-4835-87e4-739c36f032a4
8
private static String escapeJSON(String text) { StringBuilder builder = new StringBuilder(); builder.append('"'); for (int index = 0; index < text.length(); index++) { char chr = text.charAt(index); switch (chr) { case '"': case '\\': builder.append('\\'); builder.append(chr); break; case '\b': builder.append("\\b"); break; case '\t': builder.append("\\t"); break; case '\n': builder.append("\\n"); break; case '\r': builder.append("\\r"); break; default: if (chr < ' ') { String t = "000" + Integer.toHexString(chr); builder.append("\\u" + t.substring(t.length() - 4)); } else { builder.append(chr); } break; } } builder.append('"'); return builder.toString(); }
7b7e9bc6-89db-49d0-88b3-d375162bfc03
3
public boolean clientCom(String IP, String portNumber){ Integer port = Integer.parseInt(portNumber); if(!IP.isEmpty()){ try { InetAddress IPAddress = InetAddress.getByName(IP); clientTCPSocket = new Socket(IPAddress, port); System.out.println("Success connection"); return true; } catch (UnknownHostException ue) { System.err.println("ERROR: IP addres could not be determined. Exception caused by: " + ue); } catch (IOException ioe){ System.err.println("ERROR: Socket connection failed. Exception caused by: " + ioe); } } return false; }
dd3b2eb4-d20e-4a3d-bea8-d61b2c08a838
5
static ArrayList<Pair> surround(Pair start) { // System.out.printf("start is (%d, %d)", start.x, start.y); ArrayList<Pair> prlist = new ArrayList<Pair>(); for (int i=0; i<4; i++) { Pair tmp0 = new Pair(start); Pair tmp; if (i==0) { //if (start.x>0) { tmp = new Pair(tmp0.x-1,tmp0.y); // if (!PairtoPoint(tmp).water) prlist.add(tmp); // } } if (i==1) { //if (start.x<size-1) { tmp = new Pair(tmp0.x+1,tmp0.y); // if (!PairtoPoint(tmp).water) prlist.add(tmp); //} } if (i==2) { //if (start.y>0) { tmp = new Pair(tmp0.x, tmp0.y-1); //if (!PairtoPoint(tmp).water) prlist.add(tmp); //} } if (i==3) { //if (start.y<size-1) { tmp = new Pair(tmp0.x, tmp0.y+1); //if (!PairtoPoint(tmp).water) prlist.add(tmp); //} } } return prlist; }
5a0a7ca6-3329-4a1f-8e59-28b98c99be15
9
public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[34]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 0; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 34; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = (int[])jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); }
d20c4a82-96b7-4aa2-83c7-a09d367d3388
7
private boolean r_Step_1c() { int v_1; int v_2; // (, line 93 // [, line 94 ket = cursor; // or, line 94 lab0: do { v_1 = limit - cursor; lab1: do { // literal, line 94 if (!(eq_s_b(1, "y"))) { break lab1; } break lab0; } while (false); cursor = limit - v_1; // literal, line 94 if (!(eq_s_b(1, "Y"))) { return false; } } while (false); // ], line 94 bra = cursor; if (!(out_grouping_b(g_v, 97, 121))) { return false; } // not, line 95 { v_2 = limit - cursor; lab2: do { // atlimit, line 95 if (cursor > limit_backward) { break lab2; } return false; } while (false); cursor = limit - v_2; } // <-, line 96 slice_from("i"); return true; }
1da83e35-a6d3-4c3f-aff1-866abda9f943
0
@FXML private void handleButtonAction(ActionEvent event) { System.out.println("Attack clicked"); handleAttack(); }
b1c98808-bc9c-4a85-812a-7afc7a713b29
9
private boolean isDestinationNode(int node, Network network) { boolean returned_value = false; Path fFilePath = network.getPath(); //Search for arterial links coming to this node File file_network = new File(fFilePath + "\\network.dat"); try (Scanner scanner_net = new Scanner(file_network)){ scanner_net.nextLine(); for (int k=0; k<network.getNoOfNodes(); k++) scanner_net.nextLine(); do { if (node == scanner_net.nextInt()) { //Check if it is "start" of a link scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); int linkType = scanner_net.nextInt(); if ((linkType != 5) && (linkType!=7)) { /*It is not a destination node if it is connected to other types of links rather than arterial link (5)*/ return false; } } else if (node == scanner_net.nextInt()) { //Check if it is "end" of a link scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); scanner_net.nextInt(); int linkType = scanner_net.nextInt(); if ((linkType != 5) && (linkType!=7)) { /*It is not a destination node if it is connected to other types of links rather than arterial link (5)*/ return false; } else returned_value = true; } scanner_net.nextLine(); } while (scanner_net.hasNextLine()); } catch (IOException x) { network.log("IOException: " + x); return false; } return returned_value; }
eb622cd6-3b2f-426e-a308-a672d19eaf15
9
private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); }
00d44a34-f2d2-465f-bf21-6a31d04d4bbe
1
public static PeerReference serializeHost(Host host) { if (host == null) { throw new NullPointerException("Cannot transform a null value to a CORBA object"); } return new PeerReference( host.getAddress().getHostAddress(), host.getPort(), host.getHostPath().toString(), host.getTimestamp(), host.getUUID().toString() ); }
17079300-63df-4739-94b4-0fdc7ac11c1c
6
public static void DrawOddsRatioImage() { System.out.println("face vs non-face odds ratio image:"); for(int i = 0; i < FACE_HEIGHT; i++) { for(int j = 0; j < FACE_WIDTH; j++) { double odds = Math.log(isFaceProbilities[i][j]/nonFaceProbilities[i][j]); String denote = "#"; if(odds >= -0.05 && odds <= 0.05) { denote = " "; }else if(odds > 0) { denote = "+"; }else if(odds < 0) { denote = "-"; } System.out.print(denote); } System.out.println(); } }
67da9571-11e2-4cf9-aa3a-37e303debb41
7
public boolean initEncrypt(String password) { if (password == null || password.length() < 1) { Application.getController().displayError(Application.getResourceBundle().getString("password_not_null_title"), Application.getResourceBundle().getString("password_not_null_message")); return false; } try { cipher = Cipher.getInstance(getCipherInitString()); Key k = new SecretKeySpec(PasswordUtil.getKeyWithRightLength(password, getKeyLength()).getBytes(), algName); if (!algName.equalsIgnoreCase("RC4")) { IvParameterSpec ivs = new IvParameterSpec(getIV()); cipher.init(Cipher.ENCRYPT_MODE, k, ivs); } else { cipher.init(Cipher.ENCRYPT_MODE, k); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } catch (NoSuchPaddingException e) { e.printStackTrace(); return false; } catch (InvalidKeyException e) { e.printStackTrace(); return false; } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); return false; } return true; }
7cd68a4d-f47c-4c49-9302-8c8b8e1617fc
0
public Consultar() { initComponents(); }
24ce0fdc-9fba-4139-9c7d-f65b22117dd1
1
public boolean canHaveAsCreditLimit(BigInteger creditLimit) { return (creditLimit != null) && (creditLimit.compareTo(BigInteger.ZERO) <= 0); }
9b1cb1a5-9e26-490b-8856-80f2cf2e2053
3
public void setEngine( CoreEngine engine ) { if ( this.engine != engine ) { this.engine = engine; for ( GameComponent component : components ) component.addToEngine( engine ); for ( GameObject child : children ) child.setEngine( engine ); } }
c48cb8b6-60b4-466a-9e7f-59121adde36b
8
public boolean matches(String id, String aclExpr) { String parts[] = aclExpr.split("/", 2); byte aclAddr[] = addr2Bytes(parts[0]); if (aclAddr == null) { return false; } int bits = aclAddr.length * 8; if (parts.length == 2) { try { bits = Integer.parseInt(parts[1]); if (bits < 0 || bits > aclAddr.length * 8) { return false; } } catch (NumberFormatException e) { return false; } } mask(aclAddr, bits); byte remoteAddr[] = addr2Bytes(id); if (remoteAddr == null) { return false; } mask(remoteAddr, bits); for (int i = 0; i < remoteAddr.length; i++) { if (remoteAddr[i] != aclAddr[i]) { return false; } } return true; }
1ff3908c-b48c-4a9f-86d0-ede350992c01
2
public boolean isEnabled() { return comp.isEnabled() && comp.getSelectedText()!=null; }
44a45978-ce88-471c-a3c1-24ea42bc2e44
0
public int getPersonid() { return personid; }
b5565236-78e2-4c4b-999c-268d8dcdefaf
2
public void parse(String line) { init(); // Check record type if( !line.startsWith("@" + recordTypeCode) ) throw new RuntimeException("Header line is not type '" + recordTypeCode + "': " + line); // Split fields String fields[] = line.split("\t"); recordTypeCode = fields[0].substring(1); // Parse each field for( int i = 1; i < fields.length; i++ ) { String tag = fields[i].substring(0, 2); String value = fields[i].substring(3); parseField(tag, value); } }
611ec1c7-f03d-428b-aadf-72ca68939074
2
private ItemStack[] importInventory(CompoundTag tag) { ItemStack[] inv = new ItemStack[36]; for (Tag t : ((ListTag) tag.getValue().get("Inventory")).getValue()) { int slot = ((ByteTag) ((CompoundTag) t).getValue().get("Slot")).getValue(); if (slot < 36) { inv[slot] = CraftItemStack.asBukkitCopy(net.minecraft.server.v1_7_R1.ItemStack.createStack(((CompoundTag) t).toNBTTag())); } } Inventory = inv; return inv; }
9b0457bd-4cc2-4f19-ae10-e8a4f042a02a
9
public void loadData(){ try { Files.lines(path).forEachOrdered(new Consumer<String>() { boolean headerDone = false; @Override public void accept(String t) { if(!headerDone && t.startsWith("----")){ headerDone = true; } else if(t.startsWith("date: ")){ try { date = dateSaveFormat.parse(t.substring("date: ".length())); } catch (ParseException e) { date = new Date(); e.printStackTrace(); } } else if(t.startsWith("title: ")){ title = t.substring("title: ".length()); } else if(t.startsWith("author: ")){ author = t.substring("author: ".length()); } else if(t.startsWith("tags: ")){ tags = t.substring("tags: ".length()); } else if(headerDone){ data.append(t+"\n"); } } }); } catch (IOException e) { e.printStackTrace(); } }
85a01a16-6ce3-4777-87ed-7a4a1414e6e5
2
public boolean allOffersHaveStatus(String status) { List<String> services = this.getUserServiceList(); for (String service : services) { if (!hasStatus(service, status)) return false; } return true; }
91f9f507-5c31-4150-bb86-baaee14a709b
1
public static void main(String[] args) throws Exception { URL url = new URL("http://www.infoq.com"); // URLConnection conn = url.openConnection(); // // InputStream is = conn.getInputStream(); InputStream is = url.openStream(); OutputStream os = new FileOutputStream("info.txt"); byte[] buffer = new byte[2048]; int length = 0; while(-1 != (length = is.read(buffer,0,buffer.length))) { os.write(buffer, 0, length); } is.close(); os.close(); }
aa48219a-3e95-4df6-a2e0-86abbf500f52
0
@AfterClass //Onde estava o erro @AfterClass e estava @After public static void tearDownAfterClass() throws Exception { //Prints.msg("AfterClass <--> Passei pelo tearDownAfterClass - Depois da Classe"); }
08ecaa31-998d-49ad-9a59-049f99706700
9
@Override public void mousePressed(MouseEvent e) { textArea = (OutlinerCellRendererImpl) e.getComponent(); // Shorthand Node currentNode = textArea.node; JoeTree tree = currentNode.getTree(); OutlineLayoutManager layout = tree.getDocument().panel.layout; // This is detection for Solaris, I think mac does this too. if (e.isPopupTrigger() && (currentNode.isAncestorSelected() || (tree.getEditingNode() == currentNode))) { //Outliner.macroPopup.show(e.getComponent(),e.getX(), e.getY()); e.consume(); return; } // This is to block clicks when a right click is generated in windows. if ((PlatformCompatibility.isWindows()) && e.getModifiers() == InputEvent.BUTTON3_MASK) { return; } // Clear the selection int selectionSize = tree.getSelectedNodes().size(); tree.clearSelection(); // Clear any text selection in the node that was being edited if ((selectionSize == 0) && (currentNode != tree.getEditingNode())) { OutlinerCellRendererImpl renderer = layout.getUIComponent(tree.getEditingNode()); // [srk] bug trap // renderer being null has caused a crash here if (renderer != null) { renderer.setCaretPosition(0); renderer.moveCaretPosition(0); } } // Store the preferred caret position tree.getDocument().setPreferredCaretPosition(textArea.getCaretPosition()); // Record the EditingNode and CursorPosition and ComponentFocus tree.setEditingNode(currentNode); tree.setCursorPosition(textArea.getCaretPosition()); tree.setComponentFocus(OutlineLayoutManager.TEXT); // Redraw only if there is a current selection if (selectionSize > 0) { // This doesn't use redraw() becuase it's important to do a full draw if the node // is partially visible. tree.getDocument().panel.layout.draw(currentNode,OutlineLayoutManager.TEXT); } // Freeze Undo Editing UndoableEdit.freezeUndoEdit(currentNode); }
0a977537-4c21-494a-9f23-3ca53ed851ee
4
public static void compile(String fileName, boolean opt) throws IOException { Program program = null; FileReader file = new FileReader(fileName); SFECompiler compiler = new SFECompiler(file); try { program = compiler.compileProgram(); } catch (ParseException pe) { System.err.println("Error in line " + pe.getErrorOffset() + ": " + pe.getMessage()); System.exit(1); } file.close(); System.out.println("Program compiled."); // transformations program.multi2SingleBit(); // unique vars transformations program.uniqueVars(); //Optimization if (opt) { program.optimize(); } // write circuit PrintWriter circuit = new PrintWriter(new FileWriter(fileName + ((opt) ? ".Opt" : ".NoOpt") + ".circuit")); program.toCircuit(circuit, opt); circuit.close(); // write Format file PrintWriter fmt = new PrintWriter(new FileWriter(fileName + ((opt) ? ".Opt" : ".NoOpt") + ".fmt")); fmt.println(program.toFormat()); fmt.close(); }
bfea72c7-f1ed-446a-94fd-c2cc28eff0ae
4
public String result(String string) { if (list.contains(string)) { return ""; } if (string.length() <= 2) return ""; if ((matcher = Pattern.compile(reg2).matcher(string)).find()) return ""; if ((matcher = Pattern.compile(reg1).matcher(string)).find()) return ""; /*if(string.equals("-lrb-")||string.equals("-rrb-")) return "";*/ else return string; }
e69cf65d-eef2-4d4b-bade-df90a6c06aa6
4
private ArrayList<Layer> createNodes(int numberOfInputs, int[] numberOfHiddenNodes, int numberOfOutputs){ ArrayList<Layer> layers = new ArrayList<Layer>(); Layer inputLayer = new Layer(); for(int i = 0; i<numberOfInputs;i++){ inputLayer.addNode(new Node()); } layers.add(inputLayer); Layer hiddenLayer; for(int i: numberOfHiddenNodes){ hiddenLayer = new Layer(); for(int j = 0; j<i; j++){ hiddenLayer.addNode(new Node()); } layers.add(hiddenLayer); } Layer outputLayer = new Layer(); for(int i = 0; i<numberOfOutputs;i++){ Node tmpNode = new Node(); tmpNode.setFunctionType(0); outputLayer.addNode(tmpNode); } layers.add(outputLayer); return layers; }
8b732925-41cb-412f-a6a5-223c3e1156d6
2
public IDataLayer getDataLayer() { SettingsManager sm = SettingsManager.getInstance(); if (sm.getPersistenceType().equalsIgnoreCase("sqlite")) { System.out.println("Initialize Sqlite Datalayer..."); DataLayerSqlite dls = new DataLayerSqlite(); dataLayer = dls; } else if (sm.getPersistenceType().equalsIgnoreCase("xml")) { System.out.println("Initialize Xml Datalayer..."); DataLayerXml dls = new DataLayerXml(); dataLayer = dls; } return dataLayer; }
ba57bb50-dd27-4825-b21e-49a8fb0f636f
0
public static void addLastItem(JComponent component, Container container) { GridBagLayout gridbag = (GridBagLayout) container.getLayout(); component.setMaximumSize(component.getPreferredSize()); c.weighty = 1; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.NORTH; c.gridwidth = GridBagConstraints.REMAINDER; //end row gridbag.setConstraints(component, c); container.add(component); }
13979e26-3bf3-4cac-92b1-9bf3ea66132f
3
public Pawn getSquareContent(final int x, final int y) { for (Pawn p : pawns) { if ((p.getX() == x) &&(p.getY() == y)) { return p; } } return null; }
ea30a515-1655-4023-86da-d2f611f92431
8
@Override protected boolean parseCliValue() { if (("true".equals(cliValue)) || ("enable".equals(cliValue)) || ("1".equals(cliValue)) || ("yes".equals(cliValue))) { value = true; return true; } if (("false".equals(cliValue)) || ("disable".equals(cliValue)) || ("0".equals(cliValue)) || ("no".equals(cliValue))) { value = false; return true; } this.errorMessage = "Value '" + cliValue + "' is not a valid boolean (enable|disable|1|0|true|false)."; return false; }
c3d76b3b-13c3-4153-992c-65d6c639d8a5
1
public static void main(String[] args) { for(char c : "Java SE".toCharArray() ) System.out.print(c + " "); }
6dc6ff79-e7f5-4233-b845-9164641a53f4
1
public boolean update(Administrador admin){ PreparedStatement ps; try { ps = mycon.prepareStatement( "UPDATE Administradores "+ "SET passwd=?, dni=? "+ "WHERE userName=?" ); ps.setString(1, admin.getPassword()); ps.setString(2, admin.getDNI()); ps.setString(3, admin.getNombre()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(AdministradorCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
38dbb8e4-6219-4755-a9ba-99db37fee55e
2
private void doreport(Report r) throws IOException { if(!status.goterror(r.t)) return; URLConnection c = errordest.openConnection(); status.connecting(); c.setDoOutput(true); c.addRequestProperty("Content-Type", "application/x-java-error"); c.connect(); ObjectOutputStream o = new ObjectOutputStream(c.getOutputStream()); status.sending(); o.writeObject(r); o.close(); InputStream i = c.getInputStream(); byte[] buf = new byte[1024]; while(i.read(buf) >= 0); i.close(); status.done(); }
00ab4042-c875-43f5-81f3-d7acd0bf0d7f
5
public static void openConnection() { try { DB_URL = loader.getDbConnection(); USER = loader.getDbUser(); PASSWORD = loader.getDbPass(); } catch (Exception e) { e.printStackTrace(); } try { Class.forName( DRIVER_PATH ).newInstance(); conn = DriverManager.getConnection( DB_URL, USER, PASSWORD ); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
7c824dfd-3afb-4f2f-8794-760537ef2a8e
5
public int[] getNearestNeighboursElementIds(long[] key, int beamRadius) { ReferenceBlock containingBlock = getBlockFor(key); ReferenceBlock lowerBlock = null; ReferenceBlock higherBlock = null; IntList neighbours = new IntArrayList(3 * blockSize); if (containingBlock == null) { higherBlock = firstBlock; } else { neighbours.addElements(neighbours.size(), containingBlock.getElements()); lowerBlock = containingBlock.getPreviousBlock(); higherBlock = containingBlock.getNextBlock(); } int fetchSmallerElements = beamRadius, fetchGreaterElements = beamRadius; while (lowerBlock != null && fetchSmallerElements > 0) { neighbours.addElements(neighbours.size(), lowerBlock.getElements()); fetchSmallerElements -= lowerBlock.getSize(); lowerBlock = lowerBlock.getPreviousBlock(); } while (higherBlock != null && fetchGreaterElements > 0) { neighbours.addElements(neighbours.size(), higherBlock.getElements()); fetchGreaterElements -= higherBlock.getSize(); higherBlock = higherBlock.getNextBlock(); } return neighbours.toArray(new int[neighbours.size()]); }
b9a53b62-3991-4299-a868-c93edc38c739
1
public boolean matchFirst(char a, char b){ return (b == '.' || a == b); }
6d87395a-be27-49e0-8b36-9d17cccf7f14
2
public void write(String chaine) throws IOException { for (int i = 0; i<chaine.length(); i++) { this.writeBit(Character.getNumericValue(chaine.charAt(i))); } if (this.bits != 0) { this.ecrire.write(this.bits); } this.ecrire.close(); }
6f4fddb7-83ce-49ce-998b-66b8a3de5d7c
7
private boolean saveInternal(File file, boolean isInternal) { if (!isInternal && readOnly) { // unexpected situation, yet it's better // to back it up System.err.println("Attempt to save read-only map."); return false; } try { // Generating output Stream if (timerForAutomaticSaving != null) { timerForAutomaticSaving.cancel(); } BufferedWriter fileout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file))); getXml(fileout); if (!isInternal) { setFile(file); setSaved(true); } scheduleTimerForAutomaticSaving(); return true; } catch (FileNotFoundException e) { String message = Tools.expandPlaceholders(getText("save_failed"), file.getName()); if (!isInternal) getFrame().getController().errorMessage(message); else getFrame().out(message); } catch (Exception e) { logger.severe("Error in MindMapMapModel.save(): "); freemind.main.Resources.getInstance().logException(e); } scheduleTimerForAutomaticSaving(); return false; }
a83db223-9054-4bc9-ba2a-f29e7da2699b
8
FetchData fetchData(FetchRequest request) throws IOException { long arcStep = getArcStep(); long fetchStart = Util.normalize(request.getFetchStart(), arcStep); long fetchEnd = Util.normalize(request.getFetchEnd(), arcStep); if (fetchEnd < request.getFetchEnd()) { fetchEnd += arcStep; } long startTime = getStartTime(); long endTime = getEndTime(); String[] dsToFetch = request.getFilter(); if (dsToFetch == null) { dsToFetch = parentDb.getDsNames(); } int dsCount = dsToFetch.length; int ptsCount = (int) ((fetchEnd - fetchStart) / arcStep + 1); long[] timestamps = new long[ptsCount]; double[][] values = new double[dsCount][ptsCount]; long matchStartTime = Math.max(fetchStart, startTime); long matchEndTime = Math.min(fetchEnd, endTime); double[][] robinValues = null; if (matchStartTime <= matchEndTime) { // preload robin values int matchCount = (int) ((matchEndTime - matchStartTime) / arcStep + 1); int matchStartIndex = (int) ((matchStartTime - startTime) / arcStep); robinValues = new double[dsCount][]; for (int i = 0; i < dsCount; i++) { int dsIndex = parentDb.getDsIndex(dsToFetch[i]); robinValues[i] = robins[dsIndex].getValues(matchStartIndex, matchCount); } } for (int ptIndex = 0; ptIndex < ptsCount; ptIndex++) { long time = fetchStart + ptIndex * arcStep; timestamps[ptIndex] = time; for (int i = 0; i < dsCount; i++) { double value = Double.NaN; if (time >= matchStartTime && time <= matchEndTime) { // inbound time int robinValueIndex = (int) ((time - matchStartTime) / arcStep); assert robinValues != null; value = robinValues[i][robinValueIndex]; } values[i][ptIndex] = value; } } FetchData fetchData = new FetchData(this, request); fetchData.setTimestamps(timestamps); fetchData.setValues(values); return fetchData; }
20b3069b-075b-41a1-b052-9b89b47fb1a3
1
private String extractHead(String idref) throws IDrefNotInSentenceException { String headIDref = sentence.getNode(idref).getHeadIDref(); if (headIDref != null) return sentence.getNode(headIDref).getAttributes().get("lemma"); return "NOHEAD"; }
73ce40d2-2781-47c4-8fb1-5a930877407c
6
public void onBlockRemoval(World par1World, int par2, int par3, int par4) { byte var5 = 4; int var6 = var5 + 1; if (par1World.checkChunksExist(par2 - var6, par3 - var6, par4 - var6, par2 + var6, par3 + var6, par4 + var6)) { for (int var7 = -var5; var7 <= var5; ++var7) { for (int var8 = -var5; var8 <= var5; ++var8) { for (int var9 = -var5; var9 <= var5; ++var9) { int var10 = par1World.getBlockId(par2 + var7, par3 + var8, par4 + var9); if (var10 == Block.leaves.blockID) { int var11 = par1World.getBlockMetadata(par2 + var7, par3 + var8, par4 + var9); if ((var11 & 8) == 0) { par1World.setBlockMetadata(par2 + var7, par3 + var8, par4 + var9, var11 | 8); } } } } } } }
eab54cff-10a3-4e1d-b011-dfee9ab77957
8
public void setLabels(String value) { int i; String label; boolean quoted; boolean add; m_Labels.clear(); label = ""; quoted = false; add = false; for (i = 0; i < value.length(); i++) { // quotes? if (value.charAt(i) == '"') { quoted = !quoted; if (!quoted) add = true; } // comma else if ( (value.charAt(i) == ',') && (!quoted) ) { add = true; } // normal character else { label += value.charAt(i); // last character? if (i == value.length() - 1) add = true; } if (add) { if (label.length() != 0) m_Labels.add(label); label = ""; add = false; } } }
1598af58-493e-4458-9aae-093c46c37c42
1
private void MergeSort(int low, int high) { if (low < high) { int mid = low + (high - low) / 2; // Sorting lower end of array MergeSort(low, mid); // Upper lower end of array MergeSort(mid + 1, high); // Merging both ends of the array MergeSortParts(low, mid, high); } }
82cd612a-bf4b-4fef-a6f1-495aa47a3b04
3
private void renderFocusNagger() { String msg = "Click to focus!"; int xx = (WIDTH - msg.length() * 8) / 2; int yy = (HEIGHT - 8) / 2; int w = msg.length(); int h = 1; //screen.render(xx - 8, yy - 8, 0 + 13 * 32, Color.get(-1, 1, 5, 445), 0); //screen.render(xx + w * 8, yy - 8, 0 + 13 * 32, Color.get(-1, 1, 5, 445), 1); //screen.render(xx - 8, yy + 8, 0 + 13 * 32, Color.get(-1, 1, 5, 445), 2); //screen.render(xx + w * 8, yy + 8, 0 + 13 * 32, Color.get(-1, 1, 5, 445), 3); for (int x = 0; x < w; x++) { // screen.render(xx + x * 8, yy - 8, 1 + 13 * 32, Color.get(-1, 1, 5, 445), 0); // screen.render(xx + x * 8, yy + 8, 1 + 13 * 32, Color.get(-1, 1, 5, 445), 2); } for (int y = 0; y < h; y++) { // screen.render(xx - 8, yy + y * 8, 2 + 13 * 32, Color.get(-1, 1, 5, 445), 0); // screen.render(xx + w * 8, yy + y * 8, 2 + 13 * 32, Color.get(-1, 1, 5, 445), 1); } if ((tickCount / 20) % 2 == 0) { // Font.draw(msg, screen, xx, yy, Color.get(5, 333, 333, 333)); } else { // Font.draw(msg, screen, xx, yy, Color.get(5, 555, 555, 555)); } }
173149cd-4a67-4559-9f6b-7bfbda44f1ea
8
static void updateaudiostream() { bytesCopiedToStream = 0; short[] data = stream_cache_data; int stereo = stream_cache_stereo; int len = stream_cache_len; int buflen; int start, end; if (stream_playing == 0) { return; /* error */ } buflen = audio_buffer_length; start = voice_pos; end = voice_pos + len; if (end > buflen) { end -= buflen; // IS this intended to wrap-around ? } if (stereo!=0) { /*int p = start; int bi = 0; int di = 0; while (p != end) { if (p >= buflen) { p -= buflen; } soundInstance.WriteSample(2 * bi, (short) ((data[p++] * master_volume / 256))); bi += 2; soundInstance.WriteSample(2 * bi + 1, (short) ((data[p++] * master_volume / 256))); bi += 2; bytesCopiedToStream += 4; }*/ int p = start; int d=0; while (p != end) { if (p >= buflen) p -= buflen; soundInstance.WriteSample(2*d, (short)(data[p] * master_volume / 256)); soundInstance.WriteSample(2*d+1, (short)(data[p+1] * master_volume / 256)); p++;// ??? d+=2; bytesCopiedToStream += 4; } } else { int p = start; int bi = 0; while (p != end) { if (p >= buflen) { p -= buflen; } soundInstance.WriteSample(bi, (short) ((data[p++] * master_volume / 256))); bytesCopiedToStream += 2; bi += 2; } } voice_pos = end; if (voice_pos == buflen) { voice_pos = 0; } }
610e2032-7a7f-4381-89fe-75fb0c81b69a
7
public static void main(String[] args) { // Validate that one argument is passed if (args.length == 0) { System.out.println("Please provide a search string to search."); System.exit(0); } else if (args.length > 1) { System.out.println("Only one argument should be passed."); System.exit(0); } // Search string String searchString = args[0]; // Index Directory String indexStorageDirectory = LearchCommon.getIndexStorageDirectory(); Directory dir; IndexSearcher is = null; try { dir = FSDirectory.open(new File(indexStorageDirectory)); is = new IndexSearcher(dir); QueryParser parser = new QueryParser( Version.LUCENE_34, "contents", new StandardAnalyzer(Version.LUCENE_34)); Query query = parser.parse(searchString); TopDocs results = is.search(query, 3000); for (ScoreDoc scoreDoc : results.scoreDocs) { Document doc = is.doc(scoreDoc.doc); System.out.println(doc.get("fullpath")); } } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) {} } } }
7fb3a44d-05d6-48aa-ad26-1f57a0f86332
3
public String toStandard(){ return String.format("%d:%02d:%02d %s", ((hour == 0 || hour == 12 ?12 : hour%12)), minute, second,(hour < 12 ? "AM": "PM")); }
c19e35c7-7998-491d-91ee-88dda8e49c87
9
private void initComponents() { setLayout(new BorderLayout()); final List<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(TallyDialog.class.getResource("/icons/calc16.png")).getImage()); setIconImages(icons); setModalityType(ModalityType.MODELESS); setPreferredSize(new Dimension(150, 274)); setTitle("Quick Tally"); setDefaultCloseOperation(DISPOSE_ON_CLOSE); totalLabel = new JLabel("Total: $0.00"); //totalLabel.setHorizontalAlignment(JLabel.CENTER); add(totalLabel, BorderLayout.SOUTH); final JPanel middle = new JPanel(new BorderLayout()); tallyTable = new TallyTable(); tallyTable.getModel().addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent event) { updateTotal(); } }); tallyTable.setEnabled(false); final JScrollPane scrollPane = new JScrollPane(tallyTable); scrollPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); middle.add(scrollPane, BorderLayout.CENTER); valueField = new CurrencyFormattedTextField(true); valueField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { if (KeyEvent.VK_ENTER == event.getKeyCode() || KeyEvent.VK_ADD == event.getKeyCode()) { final String value = valueField.getText(); try { final double doubleValue = NumberFormat.getNumberInstance().parse(value).doubleValue(); if (doubleValue != 0.0) { tallyTable.addValue(new BigDecimal(doubleValue)); } } catch (ParseException e) { } valueField.setText(""); } else if (KeyEvent.VK_SUBTRACT == event.getKeyCode() || KeyEvent.VK_MINUS == event.getKeyCode()) { final String value = valueField.getText(); try { final double doubleValue = NumberFormat.getNumberInstance().parse(value).doubleValue(); if (doubleValue != 0.0) { tallyTable.addValue(new BigDecimal(doubleValue)); valueField.setText("-"); } } catch (ParseException e) { } } else if (KeyEvent.VK_ESCAPE == event.getKeyCode()) { clearData(); } } }); valueField.requestFocusInWindow(); valueField.setText("0.00"); valueField.setSelectionStart(0); valueField.setSelectionEnd(valueField.getText().length()-1); middle.add(valueField, BorderLayout.SOUTH); add(middle, BorderLayout.CENTER); invalidate(); pack(); }
5ee40a6c-842f-41c0-945e-66fd7749a012
6
private boolean addFaultyFrame() { String name; boolean ret = false; Faculty faculty = new Faculty(); // Цыкл необходим для того, что бы было несколько попыток у пользователя do { name = SMS.input(this, "Введите название факультета:"); if (name != null) { if (name.trim().length() > 0) { faculty.setNameFaculty(name); try { // Заносим этот объект в базу int res = faculty.insertInto(); if (res >= 0) { // все успешно updateTable(); ret = true; break; } else { if (SMS.query(this, "Такое значение уже есть.\n" + "Хотете еще раз ввести значение?")) { continue; } else { break; } } } catch (SQLException ex) { SMS.error(ex.toString()); Logger.getLogger(FacultyInternalFrame.class.getName()).log(Level.SEVERE, null, ex); break; } } else { SMS.warning(this, "Вы ничего не ввели"); } } } while (name != null); return ret; }
0480c28c-0e59-4d53-bb45-e4f4e50e6dec
5
public boolean accept(File pathname) { if (pathname.isDirectory()) return recurse; String name = pathname.getName(); if (! name.endsWith(extension)) return false; int lastNumberIndex = getLastNumberIndex(name); if (lastNumberIndex == -1) return false; int numEndLoc = lastNumberIndex+1; int numStartLoc = getLastNonNumberIndex(name, lastNumberIndex)+1; int fileNum = Integer.parseInt(name.substring(numStartLoc, numEndLoc)); if (fileNum >= lowFileNum && fileNum <= highFileNum) return true; return false; }
6fcfd2c3-11ba-49c8-8a4b-85d6ab6e9b42
1
public void onTick() { resultant = getResultant(); acceleration = Vector.multiply(resultant,1D/mass); try { velocity = Vector.add(velocity,Vector.multiply(acceleration, 0.05)); position = Vector.add(position, Vector.add(Vector.multiply(velocity, 0.05), Vector.multiply(acceleration, -0.5*Math.pow(0.05, 2)))); } catch (DimensionMismatchException e) { e.printStackTrace(); } momentumL = Vector.multiply(velocity, mass); energyK = 0.5 * mass * Math.pow(velocity.getMod(), 2); }
0fe570ad-aada-4d60-85c7-46d1d4533684
1
private void processFileAction() { try { log.info("Processing from: " + reportFolder.getText()); sourceProcessing.processExcelFiles(reportFolder.getText()); } catch (Exception e) { log.log(Level.SEVERE,e.getMessage(),e); Run.showErrorDialog(this.getSelfRef(), "An error occurred processing the music actions: " + e.getMessage()); } }
11e5c7e8-0378-4d5d-be44-de679799e5c1
0
public BST getTermIndex() { return termIndex; }
d35fa1b7-1263-4828-9f9b-d7b02faddf91
0
@Override public SkillsMain[] getSkillNames() { return Constants.priestSkillSkills; }
18caaf9b-a7be-4616-a314-f253a8c35db0
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(UI_Importar_Arquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(UI_Importar_Arquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(UI_Importar_Arquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(UI_Importar_Arquivo.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 UI_Importar_Arquivo().setVisible(true); } }); }
f9aeba0a-1d8d-4fa4-9e22-67e3610d049b
6
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode p = head; while(l1 != null && l2 != null) { if(l1.val < l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } if(l1 != null) { p.next = l1; } if(l2 != null) { p.next = l2; } return head==null?null:head.next; }
930c760b-0db1-47e7-b5c4-09b679dfab2a
3
private void itmMnuGerenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itmMnuGerenteActionPerformed // Menu - Cadastro > ItemMenu - Gerente DepartamentoBO depBO = new DepartamentoBO(); Departamento DEPexistente = null; try { DEPexistente = depBO.SelectDepartamentos(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, "Erro ao selecionar o departamento", "Cadastro de Gerente", JOptionPane.ERROR_MESSAGE); } if (DEPexistente == null) { JOptionPane.showMessageDialog(null, "Não existe departamentos cadastrados\n" + "É necessário cadastrar no minimo um Departamento !!!", "Cadastro de Usuários", JOptionPane.ERROR_MESSAGE); } else { //Instancia uma tela de cadastro de Gerente se o usuario que esta logado for Um diretor; //caso não seja um diretor é exibida uma mensagem ao usuario do sistema. //Obs: Somente diretor pode cadastrar Gerente String Gerente = "Gerente"; if (usuarioLogado.getTipo().equals("Diretor")) { CadastroUserForm cadastroUserForm = null; cadastroUserForm = new CadastroUserForm(Gerente, usuarioLogado); cadastroUserForm.setVisible(true); centralizaForm(cadastroUserForm); cadastroUserForm.toFront(); JDP1.add(cadastroUserForm); } else { JOptionPane.showMessageDialog(null, "Você não possui previlégios para acessar \n " + "a Tela de Cadastros de Gerente!!!", "Cadastro de Gerente", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_itmMnuGerenteActionPerformed
b2926ee7-c59d-4e1a-b0ef-570b91a9a604
4
public String getStrategy() { if (strategy == null) { throw new RuntimeException("Missing strategy."); } if (!strategy.equals(SimConst.MEAN) && !strategy.equals(SimConst.INDIVIDUAL) && !strategy.equals(SimConst.BINARY)) { throw new RuntimeException("Strategy " + strategy + "unsupported."); } return strategy; }
ba9e8f2d-0ebf-4ab3-bfac-dc5597f2dd91
8
public String toString() { StringBuilder sb = new StringBuilder(HawkContext.SCHEME); char delim = BLANK; if (id != null) { sb.append(delim).append("id=\"").append(id).append(ESCDQUOTE); delim = COMMA; } if (mac != null) { sb.append(delim).append("mac=\"").append(mac).append(ESCDQUOTE); delim = COMMA; } if (hash != null) { sb.append(delim).append("hash=\"").append(hash).append(ESCDQUOTE); delim = COMMA; } if (ts != 0) { sb.append(delim).append("ts=\"").append(ts).append(ESCDQUOTE); delim = COMMA; } if (nonce != null) { sb.append(delim).append("nonce=\"").append(nonce).append(ESCDQUOTE); delim = COMMA; } if (ext != null) { // Regarding escaping see https://github.com/algermissen/hawkj/issues/1 String escaped = ext.replace(ESCDQUOTE, "\\\""); sb.append(delim).append("ext=\"").append(escaped).append(ESCDQUOTE); delim = COMMA; } if (app != null) { sb.append(delim).append("app=\"").append(app).append(ESCDQUOTE); delim = COMMA; } if (dlg != null) { sb.append(delim).append("dlg=\"").append(dlg).append(ESCDQUOTE); } return sb.toString(); }
1f9f44ee-cd44-4e62-9248-1ea1a881ff62
1
@Override public JSONObject getValueForOutput() { try { return this.user.toJson(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return new JSONObject(); } }
103fc962-cef4-488d-8c97-12055e768656
4
public boolean canMove(int direction) { Grid<GridActor> gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(direction); if (!gr.isValid(next)) return false; GridActor neighbor = gr.get(next); return (neighbor == null) || (neighbor instanceof Item) || (neighbor instanceof OpenDoor); // ok to move into empty location or onto item // not ok to move onto any other actor }
7f5dbe6c-cf9e-45e8-8c3c-63731080535b
2
public ReceptDTO getRecept(int receptId) throws DALException { ResultSet rs = Connector.doQuery("SELECT * FROM recept WHERE recept_id = " + receptId); try { if (!rs.first()) throw new DALException("Recepten " + receptId + " findes ikke"); return new ReceptDTO (rs.getInt(1), rs.getString(2)); } catch (SQLException e) {throw new DALException(e); } }
ff4762d6-5f94-4db4-b469-8d24cb6446dc
8
private static Map<String,String> initializeSTR2CODE() { int num = 0; int asciibase = 'A'; Map<String, String> retval = new HashMap<String, String>(); for (int xi = 0; xi < codechars.length; xi++) { retval.put(codechars[xi], Character.toString((char) (num + asciibase))); num++; for (int yi = 0; yi < codechars.length; yi++) { retval.put(codechars[xi] + codechars[yi], Character.toString((char) (num + asciibase))); num++; } } for (int xi = 0; xi < codechars.length; xi++) { for (int yi = 0; yi < codechars.length; yi++) { String m = retval.get(codechars[xi] + codechars[yi]); for (int zi = 0; zi < codechars.length; zi++) { retval.put(codechars[xi]+codechars[yi]+codechars[zi], m + retval.get(codechars[zi])); for (int wi = 0; wi < codechars.length; wi++) { retval.put(codechars[xi]+codechars[yi]+codechars[zi]+codechars[wi], m+retval.get(codechars[zi]+codechars[wi])); //\\\\ for(int ui =0; ui < codechars.length; ui++){ retval.put(codechars[xi]+codechars[yi]+codechars[zi]+codechars[wi]+codechars[ui], m+retval.get(codechars[zi]+codechars[wi])+retval.get(codechars[ui])); for(int vi=0; vi < codechars.length; vi++){ retval.put(codechars[xi]+codechars[yi]+codechars[zi]+codechars[wi]+codechars[ui]+codechars[vi], m+retval.get(codechars[zi]+codechars[wi])+retval.get(codechars[ui]+codechars[vi])); } } //\\\ } } } } return retval; }
b2198222-633c-4761-9146-6e8ea6a21b4a
6
@Override public void saveSettings(HashMap<String, String> settingsToSave) { Set<String> keys = settingsToSave.keySet(); Iterator<String> keysIterator = keys.iterator(); String key; while(keysIterator.hasNext()) { key = keysIterator.next(); if(key.equals("minimizeToTray")) { System.out.println("minimizeToTray"); Boolean minimizeToTray = Boolean.parseBoolean(settings.getProperty("minimizeToTray")); Boolean minimizeToTrayNew = Boolean.parseBoolean(settingsToSave.get(key)); System.out.println("minimizeToTray: " + minimizeToTray); System.out.println("minimizeToTrayNew: " + minimizeToTrayNew); if(minimizeToTray != minimizeToTrayNew) { if(minimizeToTrayNew) { addIconToTrayBar(); } else { removeIconFromTrayBar(); } } } if(key.equals("name")) { String name = settings.getProperty("name"); String nameNew = settingsToSave.get(key); if(!name.equals(nameNew)) { chatCore.changeMyName(nameNew); } } settings.setProperty(key, settingsToSave.get(key)); } settings.saveSettings(); }
f07bdf19-9d57-4a0a-a919-80ba28898377
0
private boolean hasMatchedWord(String phoneNum) { return dictionary.hasMatchedWord(phoneNum); }
d9e24d8d-01a3-485f-b06a-2f08f0570f0f
3
public ReadResponse(InternalResponse resp) { super(resp); try{ JSONObject rootJsonObj = new JSONObject(resp.getContent()); Response.withMeta(this, rootJsonObj); JSONObject respJson = rootJsonObj.getJSONObject(Constants.RESPONSE); Object dataObj = respJson.get(Constants.QUERY_DATA); if (dataObj instanceof JSONArray) { data = JsonUtil.data(respJson.getJSONArray(Constants.QUERY_DATA)); } else if (dataObj instanceof JSONObject) { data.add(JsonUtil.toMap((JSONObject) dataObj)); } } catch (JSONException e) { throw new RuntimeException(e); } }
5ceb203d-09c1-4f34-b556-a0487b0b4e20
1
protected void sendConnectionHeaderIfNotAlreadyPresent(PrintWriter pw, Map<String, String> header) { if (!headerAlreadySent(header, "connection")) { pw.print("Connection: keep-alive\r\n"); } }
ad4c7658-37ba-40ee-a94b-770332f7d14d
5
public LawnMowersController(final String fileName) throws IOException,FileFormatException, NoMowerFoundException { lawnMowerControllers = new ArrayList<LawnMowerController>(); String lawnConfiguration = null; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String currentLine = null; currentLine = reader.readLine(); if (currentLine != null) { lawnConfiguration = new String(currentLine); } int mowersCount = 0; while ((currentLine = reader.readLine()) != null) { String mowerPositionAndDirection = new String(currentLine); currentLine = reader.readLine(); if (currentLine == null) { reader.close(); throw new FileFormatException(); } String mowerCommandList = new String(currentLine); try { lawnMowerControllers.add(new LawnMowerController(mowerPositionAndDirection,mowerCommandList,lawnConfiguration)); } catch (Exception e){ reader.close(); throw new FileFormatException(); } mowersCount++; } if (mowersCount ==0 ){ reader.close(); throw new NoMowerFoundException(); } reader.close(); }
6b47ede3-5df0-4c15-b757-1762d02c5c2f
1
public Decoder() { for (int i = 0; i < 4; i++) m_PosSlotDecoder[i] = new BitTreeDecoder(6); }
00457631-0ddf-48e9-957c-bb0d3647296f
9
public void doBackup(File directory) throws Exception { if (!directory.exists()) { directory.mkdir(); } RequestContext rc = RequestContext.getRequestContext(); if (this.authStore != null) { Auth auth = this.authStore.retrieve(this.nsid); if (auth == null) { this.authorize(); } else { rc.setAuth(auth); } } PhotosetsInterface pi = flickr.getPhotosetsInterface(); PhotosInterface photoInt = flickr.getPhotosInterface(); Map<String, Collection> allPhotos = new HashMap<String, Collection>(); Iterator sets = pi.getList(this.nsid).getPhotosets().iterator(); while (sets.hasNext()) { Photoset set = (Photoset) sets.next(); PhotoList photos = pi.getPhotos(set.getId(), 500, 1); allPhotos.put(set.getTitle(), photos); } int notInSetPage = 1; Collection notInASet = new ArrayList(); while (true) { Collection nis = photoInt.getNotInSet(50, notInSetPage); notInASet.addAll(nis); if (nis.size() < 50) { break; } notInSetPage++; } allPhotos.put("NotInASet", notInASet); Iterator allIter = allPhotos.keySet().iterator(); while (allIter.hasNext()) { String setTitle = (String) allIter.next(); String setDirectoryName = makeSafeFilename(setTitle); Collection currentSet = allPhotos.get(setTitle); Iterator setIterator = currentSet.iterator(); File setDirectory = new File(directory, setDirectoryName); setDirectory.mkdir(); while (setIterator.hasNext()) { Photo p = (Photo) setIterator.next(); String url = p.getLargeUrl(); URL u = new URL(url); String filename = u.getFile(); filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length()); System.out.println("Now writing " + filename + " to " + setDirectory.getCanonicalPath()); BufferedInputStream inStream = new BufferedInputStream(photoInt.getImageAsStream(p, Size.LARGE)); File newFile = new File(setDirectory, filename); FileOutputStream fos = new FileOutputStream(newFile); int read; while ((read = inStream.read()) != -1) { fos.write(read); } fos.flush(); fos.close(); inStream.close(); } } }
71a21fb4-731d-453e-8b9f-f25deb1b4de2
9
private int aslW(int dest, int n) { clearFlags(SR_N, SR_Z, SR_V, SR_C); boolean hibitSet = msbSetW(dest); boolean hasOverflow = false; int result = dest; boolean msbSet; for (int i = 0; i < n; i++) { msbSet = msbSetW(result); if (msbSet) setFlags(SR_X, SR_C); else clearFlags(SR_X, SR_C); if (hibitSet && !msbSet) hasOverflow = true; else if (!hibitSet && msbSet) hasOverflow = true; result <<= 1; } if (n == 0) clearFlag(SR_C); if (msbSetW(result)) setFlags(SR_N); if (isZeroW(result)) setFlags(SR_Z); return result; }
fc254c02-9297-4824-b160-7d935578775d
6
public RandomArgument(Program p, ArgumentType type, String labelName, Condition condition) { super(p, type, labelName, condition); switch (type) { case REGISTER: value_register = p.getRandomRegister(false); break; case VREGISTER: value_register = p.getRandomRegister(true); break; case IMMEDIATE4: value_immediate = (short)(Math.random() * (1 << 3)); break; case IMMEDIATE8: value_immediate = (short)(Math.random() * (1 << 7)); break; case LABEL: value_label = labelName; break; case CONDITION: value_condition = condition; break; default: throw new RuntimeException("Unknown argument type."); } }