method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
d159c176-e707-481f-ae2d-2b072b2332bc
2
public void addLongBranch(final Label label) { if (ClassEditor.DEBUG || CodeArray.DEBUG) { System.out.println(" " + codeLength + ": " + "long branch to " + label); } branchInsts.put(new Integer(codeLength), new Integer(lastInst)); longBranches.put(new Integer(codeLength), label); addByte(0); addByte(0); addByte(0); addByte(0); }
b19f5f47-776e-45c9-94bb-3ee489dc34d7
7
public static float findSumOfAction(float sum, int action, float dataValue){ if (action == 0){ sum = sum + dataValue; } if (action == 1){ sum = sum - dataValue; } if (action == 2 && sum != 0){ sum = sum * dataValue; } if (action == 3 && sum != 0 && dataValue != 0){ sum = sum / dataValue; } return sum; }
efe2cf93-4e05-4d30-bb76-7d21cc0370a4
6
public Set<String> getRulesToDerive(Set<Literal> literals) { Set<Literal> literalsChecked = new TreeSet<Literal>(); Set<Literal> literalsToCheck = new TreeSet<Literal>(); Set<Literal> literalsToAdd = new TreeSet<Literal>(); Set<String> rulesExtracted = new TreeSet<String>(); literalsToAdd.addAll(getLiteralsToCheck(literals)); do { literalsChecked.addAll(literalsToAdd); literalsToCheck.addAll(literalsToAdd); literalsToAdd.clear(); for (Literal literalToCheck : literalsToCheck) { for (Rule rule : getRulesWithHead(literalToCheck)) { if (!rulesExtracted.contains(rule.getLabel())) { rulesExtracted.add(rule.getLabel()); for (Literal bodyLiteral : rule.getBodyLiterals()) { if (!literalsToAdd.contains(bodyLiteral)) { literalsToAdd.addAll(getLiteralsToCheck(bodyLiteral)); } } } } } } while (literalsToAdd.size() > 0); return rulesExtracted; }
67b7db9c-7a35-47bb-90c3-67b858706019
5
public void keyPressed(int k) { if(k == KeyEvent.VK_LEFT) player.setLeft(true); if(k == KeyEvent.VK_RIGHT) player.setRight(true); if(k == KeyEvent.VK_UP) player.setUp(true); if(k == KeyEvent.VK_DOWN) player.setDown(true); if(k == KeyEvent.VK_Z) player.setPummeling(); }
553eeaa8-8ee4-42a3-bbcb-ce2acf78a432
9
public void paint(Graphics g) { for (Element<?> e : _lightElements) { if (((Light)e.x).getColor() == LightColor.GREEN) { g.setColor(Color.GREEN); } else if (((Light)e.x).getColor() == LightColor.YELLOW) { g.setColor(Color.YELLOW); } else { g.setColor(Color.RED); } XGraphics.fillOval(g, e.t, 0.0D, 0.0D, MP.carLength, VP.elementWidth); } g.setColor(Color.BLACK); for (Element<?> e : _roadElements) { XGraphics.fillRect(g, e.t, 0.0D, 0.0D, MP.roadDrawLength, VP.elementWidth); } for (Element<?> e : _roadElements) { for (Car d : (Car[])((Road)e.x).getCars().toArray(new Car[0])) { g.setColor(d.getColor()); XGraphics.fillOval(g, e.t, d.getPosition() / (d.getOberver().getLength() / MP.roadDrawLength), 0.0D, d.getCarLength() / (d.getOberver().getLength() / MP.roadDrawLength), VP.elementWidth); } } }
d37b6a4a-7c48-4627-9417-0c0a35c08e32
3
public V doit() { PreparedStatement stmt = null; V out = null; con = null; try { con = connectionPool.getConnection(); stmt = con.prepareStatement(mSQL); out = process(stmt); } catch( SQLException e ) { e.printStackTrace(); logger.warning(e.toString()); } finally { try { stmt.close(); } catch( SQLException e ) { e.printStackTrace(); logger.warning(e.toString()); } try { con.close(); } catch( SQLException e ) { e.printStackTrace(); logger.warning(e.toString()); } } return out; }
6ff32817-9741-4819-9bc2-2156995a6545
4
private Factor parseFactor() { //System.out.println("parseFactor"); Factor factor = null; switch (showNext().getKind()){ case "ident": factor = new IdentSelector(); ((IdentSelector) factor).setIdent(new Identifier(acceptIt())); ((IdentSelector) factor).setSelector(parseSelector()); break; case "integer": factor = new Number(acceptIt()); break; case "lp": factor = new ExprFactor(); acceptIt(); ((ExprFactor) factor).setExpr(parseExpression()); expect("rp"); break; case "tilde": factor = new TildeFactor(); acceptIt(); ((TildeFactor) factor).setExpr(parseFactor()); break; default: this.console.setText(this.console.getText() + "<br> Error at: L" +showNext().getPos()[0] +"c"+showNext().getPos()[1]+" expecting : identifier number '(' or '~' got " + showNext().getKind()); break; } return factor; }
200c86bd-b786-40af-b8f2-ceadf5e7a31b
2
@Override public void handleOutputCommand(SoarBeanOutputContext context, DriveCommand driveCommand) { if (shuttingDown) { return; } short velocity = (short) driveCommand.velocity; short radius = (short) driveCommand.radius; context.setStatus("complete");//place a ^status complete annotation on the command System.out.println(); System.out.println("Received a drive command: "); System.out.println(" Velocity: " + velocity); System.out.println(" Radius: " + radius); try { roomba.driveCommand(velocity, radius); } catch (RoombaIFException ex) { System.err.println(ex); } }
9d8e8ce1-a2f7-4219-b1e9-d72902263e7e
4
@Override public boolean equals(Object other) {//@formatter:off return (other == this) ? true : (other == null) ? false : (other instanceof Cell) ? equal(((Cell) other).x, x) && equal(((Cell) other).y, y) : false; }//@formatter:on
2ab18f23-d4e1-415f-aa58-3e0b4cd5caa7
6
private void sortEntities(){ int square; //Go through every row and sorts the entityRows list for(int i = 0; i < Constants.TILE_AMOUNT_Y; i++){ square = (i)*32; for(Entity e: entities){ if(e.getY() >= square && e.getY() < square+32){ entityRows.get(i).add(e); } } } //Removes all entities then adds them in the correct order entities.removeAll(entities); for(int j = 0; j < Constants.TILE_AMOUNT_Y; j++){ for(int i=0;i< entityRows.size(); i++){ Collections.sort(entityRows.get(i)); } entities.addAll(entityRows.get(j)); entityRows.get(j).removeAll(entityRows.get(j)); } }
1cb95f5c-0d14-4b3f-a746-328f7fa5bad7
1
public void testConstructor_ObjectStringEx4() throws Throwable { try { new MonthDay("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) { // expected } }
5f99434d-1051-4cff-a98e-2dccae7536a1
7
@Override public void executeMsg(final Environmental myHost, final CMMsg msg) { if((msg.amITarget(littlePlantsI)) &&(!processing) &&((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_PUSH)||(msg.targetMinor()==CMMsg.TYP_PULL))) { processing=true; final Ability A=littlePlantsI.fetchEffect(ID()); if(A!=null) { CMLib.threads().deleteTick(A,-1); littlePlantsI.delEffect(A); littlePlantsI.setSecretIdentity(""); } if(littlePlantsI.fetchBehavior("Decay")==null) { final Behavior B=CMClass.getBehavior("Decay"); B.setParms("min="+CMProps.getIntVar(CMProps.Int.TICKSPERMUDMONTH)+" max="+CMProps.getIntVar(CMProps.Int.TICKSPERMUDMONTH)+" chance=100"); littlePlantsI.addBehavior(B); B.executeMsg(myHost,msg); } processing=false; } }
3820a433-0191-4005-90fe-e384c9f4488d
4
public int dxLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; if( optInTimePeriod > 1 ) return optInTimePeriod + (this.unstablePeriod[FuncUnstId.Dx.ordinal()]) ; else return 2; }
ba1ba5d5-4f7f-4df3-b786-d106e5b3580a
0
public void setRequestMethod(Method requestMethod) { this.requestMethod = requestMethod; }
d9c39738-48a8-4966-adb5-43c931ebde34
3
void mapInVal(Object val, Object to, String to_in) { if (val == null) { throw new ComponentException("Null value for " + name(to, to_in)); } if (to == ca.getComponent()) { throw new ComponentException( "field and component ar ethe same for mapping :" + to_in); } ComponentAccess ca_to = lookup(to); Access to_access = ca_to.input(to_in); checkFA(to_access, to, to_in); ca_to.setInput(to_in, new FieldValueAccess(to_access, val)); if (log.isLoggable(Level.CONFIG)) { log.config(String.format("Value(%s) -> @In(%s)", val.toString(), to_access.toString())); } }
bf88798c-da42-44b1-8af3-8b03ff3eae0c
2
@Override public void paint(Graphics g) { super.paint(g); this.setBackground(Color.BLACK); this.setDoubleBuffered(true); g.setColor(gameOverColor); drawLists(g); drawHints(g); drawScore(g); if (isTeleport) { teleport.draw(g); } if (isBlackHole) { blackHole.draw(g); } g.dispose(); //If paint() is overriden, g must be disposed in overriding method }
d966ddf8-ec9a-4fb1-84d6-a1667162ecd8
2
public void receiveMessage(String msg) { mailbox.add(msg); if (myWindow != null) { while (hasMessages()) { myWindow.showMessage(mailbox.remove()); } } }
1d32eb03-8dd2-4e33-b699-26e489378c73
8
public static void main(String[] args) { List<List<Scheduler>> all_schedulers = new LinkedList<List<Scheduler>>(); int as_time=4, as_period=10; System.out.println("Aperiodic Server (c="+as_time+",p="+as_period+")\t\t\t\t i=Number of aperiodic tasks where start=0, c=2"); System.out.println("i\tFinish Time\t\t\tResponse Time\t\t\tExecution time\t\t\tLatency"); System.out.println("\tBackground\tPolling\tDeferrable\tBackground\tPolling\tDeferrable\tBackground\tPolling\tDeferrable\tBackground\tPolling\tDeferrable"); // Repeat test for all schedulers, incrementing i each time for(int i = 0; i <= 1000; i++) { List<Scheduler> schedulers = new LinkedList<Scheduler>(); all_schedulers.add(schedulers); schedulers.add(new BackgroundScheduler()); schedulers.add(new PollingScheduler(as_time, as_period)); schedulers.add(new DeferrableScheduler(as_time, as_period)); for (Scheduler scheduler : schedulers) { // Insert tasks scheduler.addPeriodicTask("PT 1", 2, 10); for(int j = 0; j < i; j++) { scheduler.addAperiodicTask("AT ", i*10 + (new Random().nextInt(10)), (new Random().nextInt(10))); } scheduler.initialize(); if (!scheduler.isScheduleable()) { System.out.println(scheduler.getName() + " is not scheduleable."); //System.exit(0); } scheduler.runToCompletion(); /* System.out.println(scheduler.getName()); for (String s : scheduler.getOutput()) { System.out.print(s + ", "); } System.out.println(); */ int num_of_tasks = scheduler.getAperiodicTasks().size(); /* for (AperiodicTaskQueue.AperiodicTask at : scheduler.getAperiodicTasks()) { System.out.println(at.getName() + ":"); System.out.println(("\tStart time: " + at.getArrivalTime())); System.out.println(("\tTime Started: " + at.getTimeStarted())); System.out.println(("\tTime Ended: " + at.getTimeEnded())); System.out.println("\tResponse Time: " + at.getAvgResponseTime()); System.out.println("\tExecution Time: " + at.getAvgExecutionTime()); System.out.println("\tCompletion Time: " + at.getAvgCompletionTime()); } System.out.println(); */ /* System.out.println("Aperiodic Finish Time: " + scheduler.finishAperiodicTime()); System.out.println("Average Response Time of " + num_of_tasks + " A_tasks: " + scheduler.avgAperiodicResponse()); //(total_response_time/(double)num_of_tasks)); System.out.println("Average Execution Time of " + num_of_tasks + " A_tasks: " + scheduler.avgAperiodicExecution()); //(total_execution_time/(double)num_of_tasks)); System.out.println("Average Completion Time of " + num_of_tasks + " A_tasks: " + scheduler.avgAperiodicCompletion()); //(total_completion_time/(double)num_of_tasks)); System.out.println(); */ } System.out.print(i); for(Scheduler s : schedulers) { System.out.printf("\t" + s.finishAperiodicTime()); } for(Scheduler s : schedulers) { System.out.printf("\t%.2f", s.avgAperiodicResponse()); } for(Scheduler s : schedulers) { System.out.printf("\t%.2f", s.avgAperiodicExecution()); } for(Scheduler s : schedulers) { System.out.printf("\t%.2f", s.avgAperiodicResponse() + s.avgAperiodicExecution()); } System.out.println(); } /* ps.addPeriodicTask("PT 1", 1, 4); ps.addPeriodicTask("PT 2", 3, 8); ps.addAperiodicTask("AT 1", 7, 2); ps.addAperiodicTask("AT 2", 11, 5); ps.initialize(); ds.addPeriodicTask("PT 1", 1, 4); ds.addPeriodicTask("PT 2", 3, 8); ds.addAperiodicTask("AT 1", 7, 2); ds.addAperiodicTask("AT 2", 11, 5); ds.initialize(); ArrayList<String> backgroundSchedule = new ArrayList<String>(); ArrayList<String> pollingSchedule = new ArrayList<String>(); ArrayList<String> deferrableSchedule = new ArrayList<String>(); while (bs.isDone() == false || ps.isDone() == false || ds.isDone() == false) { backgroundSchedule.add(bs.getNextTask()); pollingSchedule.add(ps.getNextTask()); deferrableSchedule.add(ds.getNextTask()); } System.out.println("Background Schedule:"); for (String s : backgroundSchedule) { System.out.print(s + ", "); } System.out.println(); for (AperiodicTaskQueue.AperiodicTask at : bs.getAperiodicTasks()) { System.out.println(at.getName() + ":"); System.out.println(("\tStart time: " + at.getArrivalTime())); System.out.println(("\tTime Started: " + at.getTimeStarted())); System.out.println(("\tTime Ended: " + at.getTimeEnded())); System.out.println("Response Time: " + (at.getTimeStarted() - at.getArrivalTime())); System.out.println("Execution Time: " + (at.getTimeEnded() - at.getTimeStarted())); } System.out.println(); System.out.println(); System.out.println("Polling Schedule:"); for (String s : pollingSchedule) { System.out.print(s + ", "); } System.out.println(); for (AperiodicTaskQueue.AperiodicTask at : ps.getAperiodicTasks()) { System.out.println(at.getName() + ":"); System.out.println(("\tStart time: " + at.getArrivalTime())); System.out.println(("\tTime Started: " + at.getTimeStarted())); System.out.println(("\tTime Ended: " + at.getTimeEnded())); System.out.println("Response Time: " + (at.getTimeStarted() - at.getArrivalTime())); System.out.println("Execution Time: " + (at.getTimeEnded() - at.getTimeStarted())); } System.out.println(); System.out.println(); System.out.println("Deferrable Schedule:"); for (String s : deferrableSchedule) { System.out.print(s + ", "); } System.out.println(); for (AperiodicTaskQueue.AperiodicTask at : ds.getAperiodicTasks()) { System.out.println(at.getName() + ":"); System.out.println(("\tStart time: " + at.getArrivalTime())); System.out.println(("\tTime Started: " + at.getTimeStarted())); System.out.println(("\tTime Ended: " + at.getTimeEnded())); System.out.println("Response Time: " + (at.getTimeStarted() - at.getArrivalTime())); System.out.println("Execution Time: " + (at.getTimeEnded() - at.getTimeStarted())); } System.out.println(); */ }
c7d1c99f-93f0-431b-bcb0-6bf1ba209e0e
0
public DiskMgrException(Exception e, String name) { super(e, name); }
494de1b3-1f90-404e-900e-f5c3775abd91
1
public void createDecal(SimpleVector pos, SimpleVector normal) { Decal decal=getFreeDecal(); if (decal!=null) { Matrix m=normal.getRotationMatrix(); decal.place(pos); decal.rotate(m); } }
179dd5e1-883e-4014-bd6b-110da0cef3b0
2
public void start() { try { Display.setDisplayMode(new DisplayMode(800, 600)); Display.create(); } catch (LWJGLException e) { e.printStackTrace(); System.exit(0); } //Init Open GL here while (!Display.isCloseRequested()) { //Render Open GL here Display.update(); } Display.destroy(); }
d3fd5f5e-8f26-4641-b1c7-42a179db0ebf
7
public void addLegalValue(String value, String desc, String mapto) throws MaltChainedException { if (value == null || value.equals("")) { throw new OptionException("The legal value is missing for the option "+getName()+"."); } else if (legalValues.contains(value.toLowerCase())) { throw new OptionException("The legal value "+value+" already exists for the option "+getName()+". "); } else { legalValues.add(value.toLowerCase()); if (desc == null || desc.equals("")) { legalValueDesc.put(value.toLowerCase(), "Description is missing. "); } else { legalValueDesc.put(value.toLowerCase(), desc); } if (mapto == null || mapto.equals("")) { throw new OptionException("A mapto value is missing for the option "+getName()+". "); } else { valueMapto.put(value, mapto); maptoValue.put(mapto, value); } } }
207a511b-da24-43d6-babe-d4fa5afa73bb
2
public Vector<Camera> getCamerasByTag(String Tag) { Vector<Camera> cams = new Vector<Camera>(); for(Camera camera : this.Cameras) { if(camera.getTag().equals(Tag)) { cams.add(camera); } } return cams; }
70131307-5a5c-4e34-b50c-1390f982678f
8
public ArrayList<ISuggestionWrapper> addCharacter() { ArrayList<ISuggestionWrapper> suggestions = new ArrayList<ISuggestionWrapper>(); initiateFromExhaustedNodes(); Link nextLink = getNextLink(); currentNodeVisitations = 1; while(neededSuggestions - suggestions.size() > 0 && nextLink != null){ FastActiveNode currentNode = nextLink.UseLink(linkQueue); if(currentNode.isNew()){ currentNodeVisitations++; } if(currentNode.isExhausted()){ double thresholdRank = 0; Link thresholdLink = linkQueue.peek(); if(thresholdLink != null){ thresholdRank = thresholdLink.getRank(); } currentNode.getSuggestions( suggestions, neededSuggestions - suggestions.size(), thresholdRank); SuggestionLink suggestionLink = currentNode.getSuggestionLink(); if(suggestionLink != null){ linkQueue.add(suggestionLink); } if(!exhaustedNodes.contains(currentNode)){ exhaustedNodes.add(currentNode); } } else{ currentNode.extractLinks(linkQueue); } if(suggestions.size() >= neededSuggestions){ break; } nextLink = getNextLink(); } totalNodeVisitations += currentNodeVisitations; //System.out.println("Done in " + currentNodeVisitations); return suggestions; }
647d1b7a-828c-4b22-8a7a-dd620ae55508
6
public void initialize() { textField.setColumns(10); frame = new JFrame(); frame.getContentPane().setBackground(SystemColor.control); frame.setTitle("MFB"); frame.setBounds(100, 100, 366, 564); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JButton btnStop = new JButton("Stop"); btnStop.setBounds(259, 74, 89, 20); frame.getContentPane().add(btnStop); btnStart = new JButton("Start"); btnStart.setBounds(0, 11, 358, 23); frame.getContentPane().add(btnStart); JLabel lblSpoil = new JLabel("Sp"); lblSpoil.setBounds(10, 78, 46, 14); frame.getContentPane().add(lblSpoil); JLabel lblSweep = new JLabel("S"); lblSweep.setBounds(10, 103, 46, 14); frame.getContentPane().add(lblSweep); JLabel lblAttack = new JLabel("At"); lblAttack.setBounds(10, 128, 46, 14); frame.getContentPane().add(lblAttack); JLabel lblNexttarget = new JLabel("NT"); lblNexttarget.setBounds(10, 153, 61, 14); frame.getContentPane().add(lblNexttarget); JLabel lblSkill = new JLabel("Skl"); lblSkill.setBounds(10, 178, 46, 14); frame.getContentPane().add(lblSkill); JList<?> list = new JList<Object>(); list.setBounds(80, 88, 53, -15); frame.getContentPane().add(list); list.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null)); list.setToolTipText(""); list.setBackground(Color.WHITE); final JComboBox<?> comboBox_1 = new JComboBox<Object>(items); comboBox_1.setBounds(76, 75, 65, 20); frame.getContentPane().add(comboBox_1); final JComboBox<?> comboBox_2 = new JComboBox<Object>(items); comboBox_2.setBounds(76, 100, 65, 20); frame.getContentPane().add(comboBox_2); final JComboBox<?> comboBox_3 = new JComboBox<Object>(items); comboBox_3.setBounds(76, 125, 65, 20); frame.getContentPane().add(comboBox_3); final JComboBox<?> comboBox_4 = new JComboBox<Object>(items); comboBox_4.setBounds(76, 150, 65, 20); frame.getContentPane().add(comboBox_4); final JComboBox<?> comboBox_5 = new JComboBox<Object>(items); comboBox_5.setBounds(76, 175, 65, 20); frame.getContentPane().add(comboBox_5); final JLabel label = new JLabel(""); label.setBounds(10, 45, 338, 14); frame.getContentPane().add(label); final JTextArea textArea = new JTextArea(); textArea.setBackground(SystemColor.control); textArea.setBounds(259, 103, 89, 20); frame.getContentPane().add(textArea); textArea.setText(" "); // btnStop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { textArea.setText(""); ShareData.znachTextArea1 = textArea.getText(); } }); ShareData.znachTextArea1 = textArea.getText(); ShareData.returnLabelSP = "-"; ShareData.returnLabelS = "-"; ShareData.returnLabelAt = "-"; ShareData.returnLabelNt = "-"; ShareData.returnLabelSKL = "-"; btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textArea.setText(""); String item1 = (String) comboBox_1.getSelectedItem(); String item2 = (String) comboBox_2.getSelectedItem(); String item3 = (String) comboBox_3.getSelectedItem(); String item4 = (String) comboBox_4.getSelectedItem(); String item5 = (String) comboBox_5.getSelectedItem(); // TODO String znachComboBox1 = (String) CheckItem.checkKeys(item1, items); String znachComboBox2 = (String) CheckItem.checkKeys(item2, items); String znachComboBox3 = (String) CheckItem.checkKeys(item3, items); String znachComboBox4 = (String) CheckItem.checkKeys(item4, items); String znachComboBox5 = (String) CheckItem.checkKeys(item5, items); String textAreaText = (String) textArea.getText(); ShareData.znachTextArea1 = textAreaText; ShareData.returnLabelSP = znachComboBox1; ShareData.returnLabelS = znachComboBox2; ShareData.returnLabelAt = znachComboBox3; ShareData.returnLabelNt = znachComboBox4; ShareData.returnLabelSKL = znachComboBox5; } }); }
9d808205-f9d5-4ee5-8e1b-fb35cc9c9255
8
public void definePerBal(int sem) { String grandTotal = Integer.toString(0); DataBase.sem_SWPerBal_data[sem][DataBase.schoolGradeCount][DataBase.sem_SWPerBal_data[sem][0].length - 1] = Integer .toString(0); for (int colNum = 0; colNum < sem_SWPerBal_headers[sem].length; colNum++) {// Iterates // through every column if (colNum == 0) {// First column header is "P" sem_SWPerBal_headers[sem][colNum] = "Grade"; } else if (colNum == sem_SWPerBal_headers[sem].length - 1) {// Final column header is "Total" sem_SWPerBal_headers[sem][colNum] = "Total"; } else {// Else Period number is set as column header sem_SWPerBal_headers[sem][colNum] = "Prd " + Integer.toString(colNum); } DataBase.sem_SWPerBal_data[sem][DataBase.schoolGradeCount][colNum] = Integer .toString(0); } for (int rowNum = 0; rowNum <= DataBase.schoolGradeCount; rowNum++) {// Iterates through each row DataBase.sem_SWPerBal_data[sem][rowNum][DataBase.sem_SWPerBal_data[sem][rowNum].length - 1] = Integer .toString(0); for (int colNum = 0; colNum <= DataBase.schoolPeriodCount; colNum++) {// Iterates through each row if (colNum == 0) {// Place Grade Number to first column if (rowNum < DataBase.schoolGradeCount)// Not bottom row DataBase.sem_SWPerBal_data[sem][rowNum][colNum] = "Gr " + Integer .toString(9 + rowNum); else // if bottom row DataBase.sem_SWPerBal_data[sem][rowNum][colNum] = "Total"; } else if (rowNum < DataBase.schoolGradeCount) {// Count total for the grade and period DataBase.sem_SWPerBal_data[sem][rowNum][colNum] = Integer .toString(countSections(sem, rowNum, colNum - 1)); DataBase.sem_SWPerBal_data[sem][rowNum][DataBase.sem_SWPerBal_data[sem][rowNum].length - 1] = // And to gradeWide total Integer.toString(Integer .parseInt(DataBase.sem_SWPerBal_data[sem][rowNum][DataBase.sem_SWPerBal_data[sem][rowNum].length - 1]) + Integer .parseInt(DataBase.sem_SWPerBal_data[sem][rowNum][colNum])); DataBase.sem_SWPerBal_data[sem][DataBase.schoolGradeCount][colNum] = // Add to periodWide total Integer.toString(Integer .parseInt(DataBase.sem_SWPerBal_data[sem][DataBase.schoolGradeCount][colNum]) + Integer .parseInt(DataBase.sem_SWPerBal_data[sem][rowNum][colNum])); grandTotal = Integer .toString(Integer.parseInt(grandTotal) + Integer .parseInt(DataBase.sem_SWPerBal_data[sem][rowNum][colNum])); //System.out.println("TOTAL is now: " + grandTotal); } } } DataBase.sem_SWPerBal_data[sem][DataBase.schoolGradeCount][DataBase.sem_SWPerBal_data[sem][0].length - 1] = grandTotal; sem_SWPerBalTables[sem] .setModel(new UneditableTableModel( DataBase.sem_SWPerBal_data[sem], sem_SWPerBal_headers[sem])); }
38bc2b97-7d99-4824-84b6-dcbf9130a667
6
public void registerCustomer(String cid, String cname, String cadd, String password, String cphone) throws Exception{ con = ConnectionService.getConnection(); try { PreparedStatement ps = con.prepareStatement("INSERT INTO customer VALUES (?,?,?,?,?)"); if (cid.length() == 0) { cid = null; ps.setString(1, null); } else { ps.setString(1, cid); } ps.setString(2, cname); ps.setString(3, cadd); if (password.length() == 0) { password = null; ps.setString(4, null); } else { ps.setString(4, password); } ps.setString(5, cphone); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { // undo the insert con.rollback(); e.printStackTrace(); } catch (SQLException e1) { System.out.println("Message: " + e1.getMessage()); System.exit(-1); } if (cid == null || password == null) { throw new Exception("ERROR: Please fill in all fields!"); } else { throw new Exception( "ERROR: User ID has already been taken. Try another!"); } } }
a6933309-9620-4d3e-87c3-6a4843866c35
3
public double dameGananciaMedia(Nodo n) { int ganancia = 0; int num = 0; for (Nodo ady : memoria.getAdjacents(n)) { if (!ady.isEstimacion()) { ganancia += ady.ganancia; num++; } } if (num != 0) { return ganancia / num; } return 0; }
d669ae76-f2e5-4759-a4b3-46929c307de2
4
private Method findMethod(String beanName, Class type, String methodName, MethodParameter[] parameters) { Method[] declaredMethods = type.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { if (methodName.equals(declaredMethod.getName())) { if (declaredMethod.getParameterTypes().length == parameters.length) { return declaredMethod; } } } if (Object.class.equals(type)) { throw Exceptions.runtime("Could not find method %s::%s", beanName, methodName); } return findMethod(beanName, type.getSuperclass(), methodName, parameters); }
d9abf6ed-68b1-4bd0-b34d-e8d7cec7d8f8
7
public void tick() { for (int i=0; i<this.chunkLoadPerTick; i++) { if (this.requests.isEmpty()) break; ChunkAddress req = this.requests.poll(); EntityChunk chunk = search(req); if (chunk == null) { chunk = loadChunk(req); } if (chunk != null) OpenCraftServer.instance().getWorldManager().getWorld(req.world).getChunkManager().receiveChunk(chunk); } for (int i=0; i<(this.buffer.size()/this.chunkSaveDelay) +1; i++) { if (!this.buffer.isEmpty()) { EntityChunk chunk = this.buffer.poll(); try { EntityLoader.saveEntity(chunk, new File(new File(OpenCraft.worldDir, chunk.address.world), chunk.address.coord.toString())); } catch (IOException e) { e.printStackTrace(); } } } }
ee0dce91-e334-4391-8bc1-a8b409b6000d
5
public static boolean itemHasEnchantment(ItemStack item, String enchantmentName) { ItemMeta meta = item.getItemMeta(); if (meta == null) return false; if (!meta.hasLore()) return false; for (String lore : meta.getLore()) { if ((lore.contains(enchantmentName)) && (ENameParser.parseLevel(lore) > 0)) { return true; } } return false; }
8f768cdf-d593-4e8b-bff5-f5ed454dba94
3
private void CheckButtons(ActionEvent evt) { int num = bRowNum * bColNum; if(isOdd) num--; //System.out.println(evt.getActionCommand()); for(int i = 0; i <num; i++) { if(objectButtons[i].getActionCommand().equals(evt.getActionCommand())) { drwpnl.SetTexture(i); mainPanel.setFocusable(true); } } }
abf3ca44-d78a-4562-8e95-b7b4669a9167
2
public void _send(DataLine rq, Object callback) { rq.set("msgid", self._msgId); rq.set("clientid", self.clientId); rq.set("userid", self.userid); rq.set("userauth", self.auth); String msg = rq.toString(); if (debug) { System.out.println("< " + rq.toString()); } this.ws.send("~m~" + msg.length() + "~m~" + msg); try { this._cmds.add(new Object[] { self._msgId, rq.parse(), callback }); } catch (Exception ex) { ex.printStackTrace(); } this._msgId++; }
598cb57e-5502-47f4-aac4-cd8103890f65
3
public static void main(String[] args) { // list of fibonnaci numbers calculated so far ArrayList<BigInteger> fibs = new ArrayList<BigInteger>(); // want a one based array, first two values are one fibs.add(BigInteger.ZERO); fibs.add(BigInteger.ONE); fibs.add(BigInteger.ONE); Scanner input = new Scanner(System.in); while (input.hasNext()) { int in = input.nextInt(); // answer exists if (in < fibs.size()) { System.out.println(fibs.get(in)); } // have to get the answer else { while (fibs.size() <= in) { fibs.add(fibs.get(fibs.size() - 1).add(fibs.get(fibs.size() - 2))); } // now output the answer System.out.println(fibs.get(in)); } } }
1d9b087e-843c-4171-a83f-0c534a44083c
3
public void updateUI() { super.updateUI(); setFont(Font.decode("Dialog Plain 11")); if (weekPanel != null) { weekPanel.updateUI(); } if (initialized) { if ("Windows".equals(UIManager.getLookAndFeel().getID())) { setDayBordersVisible(false); setDecorationBackgroundVisible(true); setDecorationBordersVisible(false); } else { setDayBordersVisible(true); setDecorationBackgroundVisible(decorationBackgroundVisible); setDecorationBordersVisible(decorationBordersVisible); } } }
ea09a494-b5d2-4050-8f52-9d05499d739b
6
public void copyDataTo(String playername) { try { if(!playername.equalsIgnoreCase(this.player)) { Player to = Bukkit.getPlayerExact(playername); Player from = Bukkit.getPlayerExact(this.player); if(from != null) { from.saveData(); } Files.copy(this.file, new File(this.file.getParentFile(), playername + ".dat")); if(to != null) { to.teleport(from == null ? getLocation() : from.getLocation()); to.loadData(); } } else { Player player = Bukkit.getPlayerExact(this.player); if(player != null) { player.saveData(); } } } catch(Exception e) { e.printStackTrace(); } }
c7d408fd-7dca-4c58-a745-a7159b4b9207
9
public void multiSpellEffect(int playerId, int damage) { switch(c.MAGIC_SPELLS[c.oldSpellId][0]) { case 13011: case 13023: if(System.currentTimeMillis() - Server.playerHandler.players[playerId].reduceStat > 35000) { Server.playerHandler.players[playerId].reduceStat = System.currentTimeMillis(); Server.playerHandler.players[playerId].playerLevel[0] -= ((Server.playerHandler.players[playerId].getLevelForXP(Server.playerHandler.players[playerId].playerXP[0]) * 10) / 100); } break; case 12919: // blood spells case 12929: int heal = (int)(damage / 4); if(c.constitution + heal >= c.maxConstitution) { c.constitution = c.maxConstitution; } else { c.constitution += heal; } break; case 12891: case 12881: if (Server.playerHandler.players[playerId].freezeTimer < -4) { Server.playerHandler.players[playerId].freezeTimer = getFreezeTime(); Server.playerHandler.players[playerId].stopMovement(); } break; } }
39236c39-756b-4fd9-b51f-d449c84e776d
5
public static int getIntBE(final byte[] array, final int index, final int size) { switch (size) { case 0: return 0; case 1: return Bytes.getInt1(array, index); case 2: return Bytes.getInt2BE(array, index); case 3: return Bytes.getInt3BE(array, index); case 4: return Bytes.getInt4BE(array, index); default: throw new IllegalArgumentException(); } }
83bd796a-3bf9-4f59-adf5-60444c8a011d
3
private int getDistance(Vertex node, Vertex target) { for (Edge edge : edges) { if (edge.getSource().equals(node) && edge.getDestination().equals(target)) { return edge.getWeight(); } } throw new RuntimeException("Should not happen"); }
00c56a4e-51e1-421e-9852-ac89e4690219
1
public void writeCompleteConstant(CycConstant cycConstant) throws IOException { if (trace == API_TRACE_DETAILED) { Log.current.println("writeCompleteConstant = " + cycConstant.toString()); } write(CFASL_EXTERNALIZATION); write(CFASL_COMPLETE_CONSTANT); writeGuid(cycConstant.getGuid()); writeString(cycConstant.getName()); }
0db8686f-a3dd-42ab-99f5-09fed8bdac56
8
public Activity[] list () { Connection con = null; PreparedStatement statement = null; ResultSet rs = null; List<Activity> activities = new ArrayList<Activity>(); try { con = ConnectionManager.getConnection(); String searchQuery = "SELECT * FROM activities"; statement = con.prepareStatement(searchQuery); rs = statement.executeQuery(); while (rs.next()) { Activity activity = new Activity(); activity.setId( rs.getInt("id") ); activity.setName( rs.getString("name") ); activity.setInstallationScriptLocation( rs.getString("installationScriptLocation") ); activity.setStatus( rs.getString("status") ); activities.add(activity); } } catch (SQLException e) { error = e.toString(); e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { System.err.println(e); } rs = null; } if (statement != null) { try { statement.close(); } catch (Exception e) { System.err.println(e); } statement = null; } if (con != null) { try { con.close(); } catch (Exception e) { System.err.println(e); } con = null; } } return activities.toArray( new Activity [activities.size()] ); }
b9de0b52-46e3-4c01-8aee-641c46f0733d
4
public void setupVaultPermissions() { if (!hasVaultPlugin() || !manager.isPluginEnabled("Vault") || permHook != null) { return; } RegisteredServiceProvider<Permission> rsp = plugin.getServer().getServicesManager().getRegistration(Permission.class); if (rsp != null) { permHook = rsp.getProvider(); plugin.getLogger().info("Successfully hooked into Vault for permissions"); } }
3131eb2f-2ddf-47aa-a816-687cfaae0249
2
private IPlanTicketFilter[] createFilters() throws Exception { ServiceContainer site = new ServiceContainer(); site.initializeServices(this.getSite(), new Object[]{this}); IPlanTicketFilter[] rs = new IPlanTicketFilter[_filterTypes.length]; for(int i = 0; i < _filterTypes.length; i ++) { rs[i] = (IPlanTicketFilter)_filterTypes[i].newInstance(); if(rs[i] instanceof IObjectWithSite) { ((IObjectWithSite)rs[i]).setSite(site); } } return rs; }
09ad0105-913f-4577-89da-a9e05a22f03b
2
public void add(Node n) { // Valeur à ajouter LinkSimpleNode newValue = new LinkSimpleNode(); newValue.setNode(n); newValue.setNext(null); if (linkSimple == null) { linkSimple = newValue; } else { LinkSimpleNode actual = linkSimple; while (actual.getNext() != null) { actual = (LinkSimpleNode) actual.getNext(); } actual.setNext(newValue); } listCount++; }
fbeaf103-cda4-4a1f-9f3c-0456e6dea229
1
private void gameRender() { // clear back buffer... g2d = bi.createGraphics(); g2d.setColor( background ); g2d.fillRect( 0, 0, WIDTH - 1, HEIGHT - 1 ); /*================================================================== * GAME RENDERING METHODS *===================================================================*/ render(g2d); //================================================================== /*================================================================== * FRAMES PER SECOND / UPDATES PER SECOND *===================================================================*/ g2d.setFont(font); fps.registerTick(); fps.draw(g2d, "FPS: ", 90, 20); if (fps.fps < low){ low = fps.fps; } g2d.drawString("Lowest FPS: " + low, 50, 500); ups.draw(g2d, "UPS: ", 160, 20); clock.draw(g2d, 240, 20); g2d.drawString("mX:" + (int)mousey.getPosition().getX() + " mY:" + (int)mousey.getPosition().getY(), 270, 20); //================================================================= paintOnScreen(); // Render the back buffer on screen }
9c2eb518-6db0-4138-a0bf-944505591fa5
4
public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) { Assert.notNull(clazz, "Class must not be null"); Assert.notNull(methodName, "Method name must not be null"); try { Method method = clazz.getMethod(methodName, args); return Modifier.isStatic(method.getModifiers()) ? method : null; } catch (NoSuchMethodException ex) { return null; } }
37737268-7617-4350-b7e7-af07de080b33
6
@SuppressWarnings("unused") public String execute() { String returnVal = SUCCESS; if (getSubmit() != null && SUBMIT.equals(getSubmit())) { validate(); LibraryManagementFacade libraryManagementFacade = new LibraryManagementFacade(); try { UserVO validUserVO = libraryManagementFacade .authenticate(getUserVO()); if (validUserVO != null) { Map<String, Object> sessionAttribute = new HashMap<String, Object>(); getSession().setAttribute("user", validUserVO); if ("operator".equals(validUserVO.getUserType())) { returnVal = "operatorpanel"; } else if ("student".equals(validUserVO.getUserType())) { returnVal = "studentpanel"; } } } catch (LibraryManagementException e) { addActionError(e.getExceptionCategory().getMessage()); returnVal = ERROR; } } else { returnVal = "login"; // when comes first time } return returnVal; }
bbada1f6-2dd8-467a-847c-f80e24a35c72
9
private void tressMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tressMouseClicked // TODO add your handling code here: try { if (conexion == true && enviando == 0) { enviando = 1; int opciones; if (esinicio != 0 && 3 <= esinicio) { opciones = c.mensajeconexion("3"); menuopciones = opciones; if (opciones == 0) { esfinal = menuopciones = 0; LeeTexto.Lee("Gracias por utilizar nuestro servicio. ¿Le hemos resuelto su duda?. Si. marque 1. No marque 2"); } esinicio = 0; variables.menu = variables.menu + 3; } else if (esfinal == -1 && 3 <= menuopciones) { variables.menu = variables.menu + 3; opciones = c.mensajeconexion(variables.menu); menuopciones = opciones; if (opciones == 0) { esfinal = menuopciones = 0; LeeTexto.Lee("Gracias por utilizar nuestro servicio. ¿Le hemos resuelto su duda?. Si. marque 1. No marque 2"); } } else { LeeTexto.Lee("Opcion no valida."); } enviando = 0; } } catch (Exception e) { } }//GEN-LAST:event_tressMouseClicked
8bce08ad-ca27-40e3-a7ca-d2e7be454357
4
public static void insertEvents (EventsBean event){ PreparedStatement pst = null; Connection conn=null; boolean result = false; try { conn=ConnectionPool.getConnectionFromPool(); pst = conn .prepareStatement("INSERT INTO EVENTS (NAME, DESCRIPTION, EVENT_DATE, VENUE, TOTAL_SEATS, BOOKED_SEATS, TICKET_PRICE, CATEGORYID, DEPARTMENTID) " + "VALUES (?,?,?,?,?,?,?,?,?)"); pst.setString(1, event.getEventName()); pst.setString(2, event.getDescription()); pst.setTimestamp(3, new Timestamp(event.getEventDate().getTime())); pst.setString(4, event.getVenue()); pst.setInt(5, event.getTotalNoOfSeats()); pst.setInt(6, event.getBookedSeats()); pst.setDouble(7, event.getTicketPrice()); pst.setInt(8, event.getCategoryId()); pst.setInt(9, event.getDepartmentId()); result = pst.execute(); //insertAlerts(event); }catch (Exception e) { System.out.println(e); } finally { if(conn!=null){ ConnectionPool.addConnectionBackToPool(conn); } if (pst != null) { try { pst.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
9a7506ed-a514-4af4-8394-eb820e2fed49
6
public static String find(String line) { line = StringUtility.removeNewLine(line); if (line.contains("דרך תצורה=|נטיות=}")) { return ""; } if (line.contains("דרך תצורה=")) { String[] arr = line.split("\\|נטיות="); if (arr.length > 1) { arr[1] = arr[1].replaceAll("<[^>]*>", ""); arr[1] = arr[1].replaceAll("'''|''", ""); arr[1] = arr[1].replaceAll("\\ \\ ", " "); arr[1] = arr[1].replaceAll("[\\[\\{\\}\\|\\]#]*", ""); if (arr[1].length() >= 3) { return arr[1].trim(); } return ""; } } line = line.replace("נטיות=", ""); line = line.replaceAll("[\\[\\{\\}\\|\\]#]*", ""); line = line.replaceAll("<[^>]*>", ""); line = line.replaceAll("'''|''", ""); line = line.replaceAll("\\ \\ ", " "); if (line.equals("אין")) { return "אין"; } if (line.trim().length() <= 3) { return ""; } return line.trim(); }
1b7a0946-db4b-4bd0-8104-29674e3c6d0b
0
public String getNum() { return num; }
f7fd5d4c-3e77-4286-aef7-3ecc682e2850
1
public static String StringtoDate(String timestamp){ try { SimpleDateFormat sdfToDate = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS"); Date date = sdfToDate.parse(timestamp); SimpleDateFormat sdfTranslated = new SimpleDateFormat( "EEEE dd.MMM yyyy HH:mm:ss", Locale.getDefault()); timestamp = sdfTranslated.format(date).toString(); } catch (ParseException e) { Error_Frame.Error(e.toString()); } return timestamp; }
1948d675-e6dd-48ee-9477-46b58f679662
4
public int compareTo(Object o){ if(!(o instanceof ByteArray)) return this.toString().compareTo(o.toString()); int thisbound=bytes.length; ByteArray cmp=(ByteArray)o; int obound=cmp.bytes.length; int bound=thisbound>obound?obound:thisbound; for(int i=0;i<bound;i++){ if(bytes[i]==cmp.bytes[i]) continue; return (int)bytes[i]-(int)cmp.bytes[i]; } return bound-obound; }
441126c4-6b54-47e0-8ee5-feb018547419
1
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I just crashed a bunch of magic at the enemy, Yo!"); return random.nextInt((int) agility) * 3; } return 0; }
477bf931-8c7e-42aa-a252-6a3770827ccb
4
private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", Updater.USER_AGENT); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin.getLogger().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating."); this.plugin.getLogger().severe("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } this.plugin.getLogger().log(Level.SEVERE, null, e); return false; } }
95789fb2-3922-448c-88d3-88d2e013bf89
6
private static void keyCreation() { boolean kc_loop = true; // makes sure key creation loops do { System.out.println("\n\n\n+==+ KEY CREATION +==+ \n\n"+ "-- 1 - Create public & private keys -- \n"+ "-- 2 - Change prime numbers' bit length (current: "+length+" bits) -- \n"+ "-- 3 - Go back --"); // take input layer_2 = user_input.next(); switch(layer_2) { // Key creation case "1": KeyGen.keyCreation(length); System.out.println("\nPublic & Private keys have been created and saved."); break; // Key bit length case "2": boolean kbl_loop; // loops until valid input is given System.out.println("Enter required bit length: "); do{ try { length = Integer.parseInt(user_input.next()); kbl_loop = false; } catch(Exception excptn) { System.out.println("Error: not an integer!\n"+ "Try again: "); kbl_loop = true; } }while(kbl_loop); System.out.println("Primes' bit length changed to "+length+"."); break; // Quit case "3": kc_loop = false; break; default: System.out.println("Invalid input."); break; } }while(kc_loop); }
f60ea29b-e75e-4f62-8946-8b3a36906789
5
public String toXMLString() { // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Implement this method. Hint: You will need to do a // combination of pre-Order and post-Order. That is, at each // level you will need to call the label's "preString()" // method before any recursive calls and then call the // label's "postString()" method afterward. preString() and // postString() have already been implemented for you in // FileNode.java. // // IMPORTANT: make sure you use indenting, increasing the // indent by 3 at each new level. You may use a helper method. // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Hint: Return a string that starts with the following: String header = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"; if(parent == null){ //clear stringBuilder stringBuilder.delete(0, stringBuilder.length()); //set indent back to 0 indent = 0; //begin with the header stringBuilder.append(header); } //set indent to 3 spaces stringBuilder.append("\n"); for(int i=0; i< indent ; i++){ stringBuilder.append(" "); } //add the root label stringBuilder.append(label.preString()); //increase indent by 3 spaces indent++; Tree<T> N = firstChild; //while there is a child while(N!= null){ //call recursively N.toXMLString(); //if N is not a leaf if(!N.Leaf()){ //new line, decrease indent, and add the postString indent--; stringBuilder.append("\n"); for(int i=0; i< indent ; i++){ stringBuilder.append(" "); } stringBuilder.append(N.label.postString()); } else{ //if N is a leaf, add the post string to the same line indent--; stringBuilder.append(N.label.postString()); } //continue to traverse by setting N to next sibling and calling the while loop N = N.getNextSibling(); } //loop ends return the stringBuilder in string form //append new line and the last postString return (stringBuilder.toString()+ "\n" + label.postString()); }
dcc7f86a-e7c3-4349-8351-6be4a815f352
0
public BehaviourType decideBehaviourType(Stats s) { return BehaviourType.CARNIVORE; }
b13b0446-f8ac-4fa5-941b-c1ef2462d84d
5
private void reheapify() { E root = array.get(1); int lastIndex = array.size() - 1; int index = 1; boolean more = true; while (more) { int childIndex = getLeftChildIndex(index); if (childIndex <= lastIndex) { E child = getLeftChild(index); // Use right child instead if it is smaller. if (getRightChildIndex(index) <= lastIndex && comp.compare(getRightChild(index), child) < 0) { childIndex = getRightChildIndex(index); child = getRightChild(index); } // Check if larger child is smaller than root. if (comp.compare(child, root) < 0) { array.set(index, child); index = childIndex; } else more = false; } else more = false; } // Store root element. array.set(index, root); }
805f6382-cf6f-4a18-a296-c40b31cf1d0b
0
@Bean public DataSource dataSource() { BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource(); ds.setDriverClassName("org.apache.derby.jdbc.ClientDriver"); ds.setUrl("jdbc:derby://localhost:1527/sample"); ds.setUsername("app"); ds.setPassword("app"); return ds; }
0d841f0a-69af-4aed-8801-650c2242379e
6
public void click(int column, int row) { if (!selected) { if (pieces[column][row] != null && pieces[column][row].getColor() == activePlayer) { selected = true; selectedColumn = column; selectedRow = row; possibleMoves.addAll(pieces[column][row].getPossibleMoves(this, new BoardPosition(column, row))); //filter out moves that endanger the king filterMovesCausingCheck(possibleMoves, new BoardPosition(selectedColumn, selectedRow)); } } else { if (selectedColumn == column && selectedRow == row) { selected = false; possibleMoves.clear(); } else if (possibleMoves.contains(new BoardPosition(column, row))) { performMove(column, row); } } }
164e984a-dadd-46c6-bf05-5898d318b7d5
6
public Boundsheet getFirstSheet() { if( parent_rec != null ) { WorkBook wb = parent_rec.getWorkBook(); if( sheetname != null ) { try { return wb.getWorkSheetByName( sheetname ); } catch( WorkSheetNotFoundException e ) { ; // fall thru -- see sheet copy operations -- appears correct } } if( (wb != null) && (wb.getExternSheet() != null) ) { Boundsheet[] bsa = wb.getExternSheet().getBoundSheets( ixti ); if( bsa != null ) { return bsa[0]; } } } return null; }
62c86cff-5b23-4b06-a606-afa087f76519
3
protected TableModel createModel(Transition transition) { final TMTransition t = (TMTransition) transition; return new AbstractTableModel() { public Object getValueAt(int row, int column) { return s[row][column]; } public void setValueAt(Object o, int r, int c) { s[r][c] = (String) o; } public boolean isCellEditable(int r, int c) { if (!blockTransition) return true; else if (c == 0) return true; else return false; } public int getRowCount() { return machine.tapes(); } public int getColumnCount() { if (!blockTransition) return 3; else return 1; } public String getColumnName(int c) { return name[c]; } String s[][] = arraysForTransition(t); String name[] = { "Read", "Write", "Direction" }; }; }
b5d1fc6c-9456-411f-b683-2a06335942b4
5
@Override public DataTable generateDataTable (Query query, HttpServletRequest request) throws DataSourceException { DataTable dataTable = null; try (final Reader reader = new FilterCsv (new BufferedReader (new InputStreamReader (new URL (this.urlYahoo).openStream())))) { TableRow row = new TableRow (); dataTable = CsvDataSourceHelper.read(reader, this.column, false); dataTable.addColumn(new ColumnDescription(FieldIndice.NASDAQ.toString(), ValueType.TEXT, FieldIndice.NASDAQ.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.SP500.toString(), ValueType.TEXT, FieldIndice.SP500.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.FTSE100.toString(), ValueType.TEXT, FieldIndice.FTSE100.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.TSX100.toString(), ValueType.TEXT, FieldIndice.TSX100.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.CAC40.toString(), ValueType.TEXT, FieldIndice.CAC40.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.DAX30.toString(), ValueType.TEXT, FieldIndice.DAX30.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.NIKKEI225.toString(), ValueType.TEXT, FieldIndice.NIKKEI225.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.HKSE.toString(), ValueType.TEXT, FieldIndice.HKSE.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.VIX.toString(), ValueType.TEXT, FieldIndice.VIX.toString())); dataTable.addColumn(new ColumnDescription(FieldIndice.GOLD.toString(), ValueType.TEXT, FieldIndice.GOLD.toString())); row.addCell(this.getTime()); row.addCell(this.getDowJonesValue()); for (int i = 0; i < dataTable.getNumberOfRows(); i++) { String lastPriceDataTable = dataTable.getCell(i, 0).toString(); String changePercentDataTable = dataTable.getCell(i, 1).toString(); if (! lastPriceDataTable.matches(".*\\d.*")) lastPriceDataTable = "0"; if (! changePercentDataTable.matches(".*\\d.*")) changePercentDataTable = "0"; String lastPriceString = this.formatter.format(Double.parseDouble(lastPriceDataTable)); String changePercentString = this.formatter.format(Double.parseDouble(changePercentDataTable)); row.addCell(lastPriceString + " (" + changePercentString + "%)"); } dataTable.addRow(row); } catch (MalformedURLException e) { System.out.println("TableIndiceValue generateDataTable() MalformedURLException " + "URL : " + this.urlYahoo + " " + e); } catch (IOException e) { System.out.println("TableIndiceValue generateDataTable() IOException " + e); } return dataTable; }
6526a7ff-1835-448c-8d21-45a28254b75e
3
private void setFieldsForEditing() { subjectTextField.setText(this.proposal.getSubject()); descriptionTextField.setText(this.proposal.getDescription()); String options = ""; for (Iterator<String> it = this.proposal.getOptions().iterator(); it.hasNext();) { String o = it.next(); options += o + ", "; } optionTextField.setText(options); SimpleDateFormat format = new SimpleDateFormat("MM"); monthComboBox.setSelectedIndex(Integer.parseInt( format.format(this.proposal.getExpirationDate())) + 1); monthComboBox.setSelectedIndex(Integer.parseInt( format.format(this.proposal.getExpirationDate()))); format = new SimpleDateFormat("dd"); dayComboBox.setSelectedIndex(Integer.parseInt( format.format(this.proposal.getExpirationDate()))); format = new SimpleDateFormat("yyyy"); String thisYear = format.format(this.proposal.getExpirationDate()); int numOfOptions = yearComboBox.getItemCount(); for (int i = 0; i < numOfOptions; i++) { if (yearComboBox.getItemAt(i).equals(thisYear)) { yearComboBox.setSelectedIndex(i); } } priorityComboBox.setSelectedIndex(5 - this.proposal.getPriority()); }
f86cac63-8ec0-4a21-8fa5-8b78e6f27843
8
public static boolean isRightButton(MouseEvent e, Boolean ctrlDown, Boolean shiftDown, Boolean altDown) { return (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0 && (e.getModifiersEx() & MouseEvent.BUTTON2_DOWN_MASK) == 0 && (e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) != 0 && (ctrlDown == null || e.isControlDown() == ctrlDown) && (shiftDown == null || e.isShiftDown() == shiftDown) && (altDown == null || e.isAltDown() == altDown); }
9d224a14-b198-4964-b19f-c432ebe5bcb3
3
public int mfiLookback( int optInTimePeriod ) { if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) ) optInTimePeriod = 14; else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) ) return -1; return optInTimePeriod + (this.unstablePeriod[FuncUnstId.Mfi.ordinal()]) ; }
5cb2ee32-dd81-4731-bb1e-2c5f9c02599b
8
private void split(DoublyLinkedNode curr, int red, int green, int blue, int previousRunLength, int nextRunLength) { DoublyLinkedNode previousRun, nextRun; previousRun = previousRunLength <= 0 ? curr.getPrevious() : new DoublyLinkedNode(new Run((int) curr.getValue().getRed(), (int) curr.getValue().getGreen(), (int) curr.getValue().getBlue(), previousRunLength)); nextRun = nextRunLength <= 0 ? curr.getNext() : new DoublyLinkedNode(new Run((int) curr.getValue().getRed(),(int) curr.getValue().getGreen(), (int) curr.getValue().getBlue(), nextRunLength)); curr.getValue().setValue(red, green, blue, 1); if (previousRunLength > 0) { if (curr.getPrevious() != null) curr.getPrevious().setNext(previousRun); previousRun.setPrevious(curr.getPrevious()); previousRun.setNext(curr); } if (nextRunLength > 0) { nextRun.setPrevious(curr); nextRun.setNext(curr.getNext()); if (curr.getNext() != null) curr.getNext().setPrevious(nextRun); } curr.setPrevious(previousRun); curr.setNext(nextRun); if (curr == runs.head && curr.getPrevious() != null) runs.head = curr.getPrevious(); }
a8b53603-ed01-46eb-bf5a-f349be3c9271
5
public void checkRutor() { for(int i = 0;i < rutor.length && rutor[i] != null;i++) { if(rutor[i].inside(BoJMouseListener.getX(),BoJMouseListener.getY())) { rutor[i].increaseAntalTryck(); } } if(BoJMouseListener.getX() != BoJMouseListener.DEAD && BoJMouseListener.getY() != BoJMouseListener.DEAD) { actRutor(); BoJMouseListener.setX(BoJMouseListener.DEAD); BoJMouseListener.setY(BoJMouseListener.DEAD); } }
f8d542e6-9751-48a5-9020-2f0f9349adb9
7
@Override public boolean execute(CommandSender par1Sender, Command par2Command, String par3Args, String[] par4Args) { int page; try { page = Integer.parseInt(par4Args.length > 0 ? par4Args[0] : "0") * 10; } catch (NumberFormatException e) { page = 0; } ArgsParser ap = new ArgsParser(); ParseCommand view = new ParseCommand("view"); view.addOption("p", "page", 1, Converters.getStringConverter()); view.addOption("l", "location", 3, Converters.getIntegerConverter()); view.addOption("t", "type", 1, Converters.getIntegerConverter()); ParseCommand rollback = new ParseCommand("rollback"); rollback.addOption("p", "player", 1, Converters.getStringConverter()); rollback.addOption("i", "id", 1, Converters.getIntegerConverter()); rollback.addOption("l", "location", 3, Converters.getIntegerConverter()); rollback.addOption("t", "type", 1, Converters.getIntegerConverter()); ap.addCommandParser(view); ap.addCommandParser(rollback); ap.parse(par3Args); Map<String, List<Entry<String, List<?>>>> args = ap.getValue(); System.out.println(args); ResultSet rs = null; try { rs = DatabaseManager.executeQuery(String.format(SQL.SELECT_LOG_DATA, page)); while(rs.next()) { Object[] params = { rs.getInt("id"), rs.getDate("date"), rs.getInt("x"), rs.getInt("y"), rs.getInt("z"), rs.getString("world"), rs.getString("player"), getAction(rs.getInt("action")), rs.getString("description"), }; Util.Message(par1Sender, String.format("ID: %s %s | x: %s y: %s z:%s World: %s Player: %s Action: %s | %s", params), null); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if(rs != null) DatabaseManager.closeResultSet(rs); } catch (SQLException e) { e.printStackTrace(); } } return true; }
2af44774-11fa-4baf-bad0-b02d98926bbd
0
public int getMinimum() {return bar.getMinimum();}
bec05919-78d4-4587-8b97-d408addb8b34
5
public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT) { Magnus.moveDirection = 2; Magnus.dx = -1; System.out.println("Left key pressed"); } if (key == KeyEvent.VK_RIGHT) { Magnus.moveDirection = 1; Magnus.dx = 1; System.out.println("Right key pressed"); } if (key == KeyEvent.VK_UP || key == KeyEvent.VK_SPACE) { if (Platform.jumpLimit < 2) { Magnus.dy = -5; } Platform.jumpLimit ++; System.out.println("Up key or Space bar pressed"); } }
8e5a0bb4-ad9b-40ea-880a-335e53c6113e
0
private void initButtonBar(){ menuBarWithButtons = new JToolBar(); menuBarWithButtons.setSize(this.getWidth(), MENU_BAR_WITH_BUTTONS_HEIGHT); menuBarWithButtons.setBorderPainted(true); menuBarWithButtons.setBorder(BorderFactory.createLineBorder(Color.gray, 1)); JToggleButton mBarButtonOpen = new JToggleButton(); ImageIcon iconButtonOpen = new ImageIcon(Main.ICO_PATH + "folder.png"); mBarButtonOpen.setIcon(iconButtonOpen); mBarButtonOpen.setBorderPainted(false); mBarButtonOpen.setContentAreaFilled(false); mBarButtonOpen.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { openDialog(); } }); JToggleButton mBarButtonNew = new JToggleButton(); ImageIcon iconButtonNew = new ImageIcon(Main.ICO_PATH + "page_white.png"); mBarButtonNew.setIcon(iconButtonNew); mBarButtonNew.setBorderPainted(false); mBarButtonNew.setContentAreaFilled(false); mBarButtonNew.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { newWorkSpace(); } }); JToggleButton mBarButtonViewResult = new JToggleButton(); ImageIcon iconButtonViewResult = new ImageIcon(Main.ICO_PATH + "document_inspector.png"); mBarButtonViewResult.setIcon(iconButtonViewResult); mBarButtonViewResult.setBorderPainted(false); mBarButtonViewResult.setContentAreaFilled(false); mBarButtonViewResult.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { selResultRows = resultTable.getSelectedRows(); Main.runResultView(); Main.transferDataToResultView(listDataOut, selResultRows); } }); JToggleButton mBarButtonEditDataBase = new JToggleButton(); ImageIcon iconButtonEditDataBase = new ImageIcon(Main.ICO_PATH + "database_edit.png"); mBarButtonEditDataBase.setIcon(iconButtonEditDataBase); mBarButtonEditDataBase.setBorderPainted(false); mBarButtonEditDataBase.setContentAreaFilled(false); mBarButtonEditDataBase.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Main.runDataWindow(); } }); mBarButtonStop = new JToggleButton(); ImageIcon iconButtonStop = new ImageIcon(Main.ICO_PATH + "stop.png"); mBarButtonStop.setIcon(iconButtonStop); mBarButtonStop.setBorderPainted(false); mBarButtonStop.setContentAreaFilled(false); mBarButtonStop.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { TestRunner.stopTest(); } }); mBarButtonStop.setEnabled(false); final JToggleButton mBarButtonRun = new JToggleButton(); ImageIcon iconButtonRun = new ImageIcon(Main.ICO_PATH + "resultset_next.png"); mBarButtonRun.setIcon(iconButtonRun); mBarButtonRun.setBorderPainted(false); mBarButtonRun.setContentAreaFilled(false); mBarButtonRun.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e){ mBarButtonStop.setEnabled(true); } @Override public void mouseClicked(MouseEvent e) { runTest(); } }); menuBarWithButtons.add(mBarButtonOpen); menuBarWithButtons.add(mBarButtonNew); menuBarWithButtons.addSeparator(); menuBarWithButtons.add(mBarButtonRun); menuBarWithButtons.add(mBarButtonStop); menuBarWithButtons.add(mBarButtonViewResult); menuBarWithButtons.addSeparator(); menuBarWithButtons.add(mBarButtonEditDataBase); }
475ed9d1-541b-4bd0-87f4-ed13c43a74b4
9
private String readString() throws JSONException { Kim kim; int from = 0; int thru = 0; int previousFrom = none; int previousThru = 0; if (bit()) { return getAndTick(this.stringkeep, this.bitreader).toString(); } byte[] bytes = new byte[65536]; boolean one = bit(); this.substringkeep.reserve(); while (true) { if (one) { from = thru; kim = (Kim) getAndTick(this.substringkeep, this.bitreader); thru = kim.copy(bytes, from); if (previousFrom != none) { this.substringkeep.registerOne(new Kim(bytes, previousFrom, previousThru + 1)); } previousFrom = from; previousThru = thru; one = bit(); } else { from = none; while (true) { int c = this.substringhuff.read(this.bitreader); if (c == end) { break; } bytes[thru] = (byte) c; thru += 1; if (previousFrom != none) { this.substringkeep.registerOne(new Kim(bytes, previousFrom, previousThru + 1)); previousFrom = none; } } if (!bit()) { break; } one = true; } } if (thru == 0) { return ""; } kim = new Kim(bytes, thru); this.stringkeep.register(kim); this.substringkeep.registerMany(kim); return kim.toString(); }
ce331a48-e87a-44b8-8a12-9a6ca1820a7a
7
public static boolean[] nextPosition(boolean switches[], int numTrue){ String value = ""; boolean retSwitches[] = new boolean [switches.length]; for(int i = 0; i < switches.length; i++){ value += switches[i] == true ? 1 : 0; } value = value.replaceAll( "[^\\d]", "" ); int currentValue = Integer.parseInt(value,2); int count = 0; do{ currentValue += 1; //System.err.println("currentValue = " + currentValue); String test = new String(Integer.toBinaryString(currentValue) + ""); //System.err.println("currentValue = " + test); int length = test.length(); test = test.replaceAll("1", ""); if(length - test.length() == numTrue) break; }while(count < 100); //System.out.println("Next value is " + Integer.toBinaryString(currentValue)); String reverseSwitch = Integer.toBinaryString(currentValue) + ""; int j = switches.length-1; for(int i = reverseSwitch.length()-1; i >= 0; i--){ //System.err.println("i" + i + " revSw:" + reverseSwitch + " value =" + (reverseSwitch.charAt(i) == '1' ? true: false) + " char = " + reverseSwitch.charAt(i)); retSwitches[j] = (reverseSwitch.charAt(i) == '1' ? true: false); j--; } for(; j >=0 ; j--) retSwitches[j] =false; // System.out.println("results : " ); // for(boolean i : retSwitches){ // System.out.print( i == true ? "1" : "0"); // } //System.out.println("Value:" + Integer.toBinaryString(Integer.parseInt(value,2)) + " from " + value + " from " + Integer.parseInt(value,2)); return retSwitches; }
1d231bb2-b960-410c-b52c-09e0241db667
0
public ZipUnpacker(String inputZip) { this.inputZip=inputZip; outputFolder="temp"; }
9b775ab2-2f5a-42ea-b9a6-6cabadb3ce84
7
public void exploreDirectory(File f,String path, int linesNumber) { //one file object is created with the directory path File directory =new File(path); BufferedWriter bw = null; //Check if the path exists if (!directory.exists()) { System.out.println("The path " + directory.getAbsolutePath() + " does not exist."); return; } //It checks if a directory if (!directory.isDirectory()) { System.out.println("The path " + directory.getAbsolutePath() + " is not a directory"); return; } //get the content of the directory File[] lista = directory.listFiles(); String read=path+"\\read.txt"; String hour=new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z").format(new Date()); try { bw = new BufferedWriter(new FileWriter(read, true)); bw.write("-------------------------------- " + hour + " ---------------------------------\n\n"); bw.write("In the directory " + directory.getName().toUpperCase() + " have generated the following files \n\n"); bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } //walking the directory and files are listed first for (File s : lista){ if(s.isFile()){ try { if (s.getName().equals("read.txt")) {} else{ bw = new BufferedWriter(new FileWriter(path+"\\read.txt",true)); bw.write(" * File Created -> "+" "+ s.getName()+ " ===> "+"Number of stars : "+linesNumber+" \n\n"); bw.flush(); bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
ccd6c4d9-82e3-44b4-96e6-81cff9145af2
4
public String readBinary(Key key, String valueName) throws RegistryErrorException { if(key == null) throw new NullPointerException("Registry key cannot be null"); if(valueName == null) throw new NullPointerException("Valuename cannot be null, because the default value is always a STRING! If you want to read a String use readValue"); String ret = extractAnyValue(key.getPath(), valueName); //if it is not null and it starts with hex: it is hopefully a binary entry if(ret != null && ret.startsWith(BINARY_KEY)) { return ret.substring(4); } return null; }
5b6b2b70-4c54-4ce9-896a-307aae531392
5
private String[] getCustomFilterNodeValue(final Document doc) { List<String> values = new ArrayList<>(); Node filterNode = this.getFirstLevelNodeByTag(doc, FILTER_TAG); if (filterNode == null) { return null; } Node customFilterNode = this.getNodeByTagInNode(filterNode, CUSTOM_TAG); if (customFilterNode == null) { return null; } Node implementorNode = this.getNodeByTagInNode(customFilterNode, IMPLEMENTOR_TAG); if (implementorNode == null) { return null; } String implementorValue = this.getNodeValue(implementorNode); if (implementorValue.isEmpty()) { return null; } values.add(implementorValue); NodeList paramNodes = this.getNodeListByTagInNode(customFilterNode, PARAM_TAG); for (int j = 0; j < paramNodes.getLength(); j++) { String paramValue = this.getNodeValue(paramNodes.item(j)); values.add(paramValue); } return values.toArray(new String[values.size()]); }
3db66ebd-cbbf-474a-9316-7c6ddcb9e1df
6
private void Drink() { thirst = ps.getThirst(); waterAmount = ps.getWaterCollected(); waterLimit = ps.getWaterLimit(); hasSolarUpgrade = ps.getHasSolarUpgrade(); if (!hasSolar) { Dialog.message("I don't have a source of water to consume!"); Dialog.message("I should build a Solar Still.", 2500); } else { waterAmount = ps.getWaterCollected(); if(!hasSolarUpgrade) { Dialog.message("You check the collected water in your small solar still."); } else { Dialog.message("You check the collected water in your upgraded solar still."); } Dialog.message("Water amount - " + waterAmount + "/" + waterLimit + "\n"); valid = false; while(!valid) { Dialog.message("Actions -- DRINK, LEAVE"); choice = Input.getStringInput(sc); if (choice.equalsIgnoreCase("DRINK")) { if(waterAmount > 0) { Dialog.message("You kneel down to grab the container"); Dialog.message("full of clean water.\n", 2000); Dialog.message("You drink the entire container and place"); Dialog.message("it in the solar still to re-collect water.\n", 2000); thirst += waterAmount; waterAmount = 0; ps.setThirst(thirst); ps.setWaterCollected(waterAmount); } else { Dialog.message("Not a drop of water to drink...\n", 2000); } } else if (choice.equalsIgnoreCase("LEAVE")) { Dialog.message("You step away from the solar still."); } else { Dialog.message("I dont understand what that is.\n"); continue; } valid = true; } } }
f859dd5b-d60f-42ee-a028-6871dd83fb86
2
public static void showCannotOpenMsg(Component comp, String name, Throwable throwable) { if (throwable instanceof NewerDataFileVersionException) { WindowUtils.showError(comp, MessageFormat.format(UNABLE_TO_OPEN_WITH_EXCEPTION, name, throwable.getMessage())); } else { if (throwable != null) { Log.error(throwable); } WindowUtils.showError(comp, MessageFormat.format(UNABLE_TO_OPEN, name)); } }
eb06a222-1df3-4066-9e0b-16dae2319661
7
@Override public boolean perform(final Context context) { // Example: /<command> timezone[ get][ <Player>] int position = 2; if (context.arguments.size() >= 2 && !context.arguments.get(1).equalsIgnoreCase(this.name)) position = 1; OfflinePlayer target = Parser.parsePlayer(context, position); if (target == null && context.sender instanceof OfflinePlayer) target = (OfflinePlayer) context.sender; if (target == null) { Main.messageManager.send(context.sender, "Unable to determine player", MessageLevel.SEVERE, false); return false; } // Parse target player name String targetName = target.getName(); if (target.getPlayer() != null) targetName = target.getPlayer().getName(); // Verify requester has permission for player if (!Timestamp.isAllowed(context.sender, this.permission, targetName)) { Main.messageManager.send(context.sender, "You are not allowed to use the " + this.getNamePath() + " action of the " + context.label + " command for " + target.getName(), MessageLevel.RIGHTS, false); return true; } final Recipient recipient = Timestamp.getRecipient(target); Main.messageManager.send(context.sender, "Timestamp time zone for " + targetName + ": " + TimestampTimeZoneGet.message(recipient), MessageLevel.STATUS, false); return true; }
c018b8ab-8284-4e2d-8814-d6abf78cd601
8
private HashMap<ArrayList<Integer>, Integer> parseInputFile(String inputFile) { try { HashMap<ArrayList<Integer>, Integer> data = new HashMap<ArrayList<Integer>, Integer>(); // read file input BufferedReader in = new BufferedReader (new FileReader(inputFile)); // read the first line to initialize the max and min list String line; if ( (line=in.readLine()) != null) { ArrayList<Integer> points = parseLine(line); // put in the data map, with counter=1 data.put(points, 1); // first point, put in max and min list for (int i=0; i<numDimension; i++) { maxList[i]=points.get(i); minList[i]=points.get(i); } } // continue read for the next data while ((line=in.readLine())!=null) { ArrayList<Integer> points = parseLine(line); // put in the data map, increase the counter if ( data.containsKey(points) ) { int count = data.get(points); data.put(points, count+1); } else { data.put(points, 1); } // update max and min list for (int i=0; i<numDimension; i++) { if ( points.get(i) > maxList[i] ) { maxList[i] = points.get(i); } else if ( points.get(i) < minList[i] ) { minList[i] = points.get(i); } } } in.close(); return data; } catch (IOException e) { e.printStackTrace(); } // if there is something fail return null; }
b7bad03f-8d66-495d-aabd-585571a9c2ce
9
public void handleLogin(){ User u = loginView.getModel(); // Check if username is empty, if so then show a message. if (u.getUsername().isEmpty()) { JOptionPane .showMessageDialog( null, "U moet een gebruikersnaam invoeren om in te kunnen loggen.", "Fout!", JOptionPane.ERROR_MESSAGE); } // Check if password is empty, if so then show a message. else if (u.getPassword().length == 0) { JOptionPane .showMessageDialog( null, "U moet een wachtwoord invoeren om in te kunnen loggen.", "Fout!", JOptionPane.ERROR_MESSAGE); } // If the user has filled in a username and a password, then // check if the username and password are valid. else { try { // Create a new user controller. User user = new User(); // Check if user is legit. boolean autheticated = user.login( u.getUsername(), u.getPassword()); // If user is legit. if (autheticated) { UserRole role = user.role(u.getUsername()); // Store user information in user object to pass // through. user.setUsername(u.getUsername()); user.setRole(role.toString()); CustomerController customerController = new CustomerController(); RentalController rentalController = new RentalController(); if (role == UserRole.BALIE) { rentalController.showRentalView(); } else if (role == UserRole.ADMIN) { AdminController adminController = new AdminController(); adminController.showAdminView(); loginView.setVisible(false); } else if (role == UserRole.GARAGE) { DamageController damageController = new DamageController(); damageController.showGarageView(); } else if (role == UserRole.KLANT) { customerController.showCustomerView(); } else if (role == UserRole.NONE) { JOptionPane .showMessageDialog( null, "U inloggegevens kloppen wel, maar u heeft nog geen rol toegewezen gekregen. Neem contact op met uw systeembeheerder.", "Fout!", JOptionPane.ERROR_MESSAGE); } } // If user is not legit. else { JOptionPane .showMessageDialog( null, "Uw inloggegevens kloppen niet, probeer het later opnieuw.", "Fout!", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { e1.printStackTrace(); } } }
8858e47d-47ae-4a26-ba1a-7ac99876b003
3
public ClientThread(int id, CyclicBarrier barrier) { this.id = id; // determine where to push/pull info: if(id == 0) { req = new int[1]; req[0] = 1; res = new int[1]; res[0] = 0; } else if(id == 1) { req = new int[2]; req[0] = 0; req[1] = 3; res = new int[2]; res[0] = 1; res[1] = 2; } else if(id == 2) { req = new int[2]; req[0] = 2; req[1] = 5; res = new int[2]; res[0] = 3; res[1] = 4; } else { req = new int[1]; req[0] = 4; res = new int[1]; res[0] = 5; } // Set up the barrier for synchronization: this.barrier = barrier; }
656731dd-1a86-4041-ae90-304ecf87a6be
5
public Node getPayloadNode() throws Exception { Node result = null; Node payloadNode = Utilities.selectSingleNode(this.getDocument(), "/dc:DCTransaction/*/dc:Payload", XMLLabels.STANDARD_NAMESPACES); if(payloadNode != null) { Node first = payloadNode.getFirstChild(); if(first != null) { switch(first.getNodeType()) { case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: { result = Utilities.parseXml(payloadNode.getTextContent()); break; } case Node.ELEMENT_NODE: { result = first; break; } default: { throw new IllegalArgumentException(); } } } } return result; }
b936be82-f49c-4a54-acc3-cedceb2fe1dc
7
private void renderEntities() { for(Entity ent: entities) { if(ent==null) continue; ent.render(); int[] pix = ent.getPixels(); for(int x = 0; x < ent.getImageWidth(); x++) { for(int y = 0; y < ent.getImageHeight(); y++) { int yy = (((y + ent.getLocation().getY()) - yOffset) - ((ent.getImageHeight() - ent.getHeight()) / 2)); int xx = ((x + ent.getLocation().getX()) - xOffset - ((ent.getImageWidth() - ent.getWidth()) / 2)); if(pix[ent.getImageWidth() * y + x] != ScreenManager.getInstance().getOmmitColor() && yy < height && xx < width) { pixels[width * yy + xx] = pix[ent.getImageWidth() * y + x]; } } } } }
88ac5c11-8012-4270-920d-859bc4c3e389
3
@Override public void run() { Player[] players = plugin.getServer().getOnlinePlayers(); Player player; long MarkerTime = System.currentTimeMillis() - (plugin.getConfig().getInt("AFK_TIMER") * 60 * 1000); for (int i = 0; (players.length - 1) >= i; i++) { long afkTime = 0; player = players[i]; UserTable ut = plugin.getDatabase().find(UserTable.class).where() .ieq("userName", player.getName()).findUnique(); afkTime = plugin.users.get(player.getName()); if (afkTime < MarkerTime) { if (!ut.isAfk()) { ut.setAfk(true); ut.setAfkTime(System.currentTimeMillis()); plugin.getDatabase().save(ut); plugin.getServer().broadcastMessage(ChatColor.YELLOW + player.getDisplayName() + " has been flaged afk"); } } } }
51fee026-53d9-4857-91e2-c6e2fa8d3000
7
void writeData(short fid, short file_offset, byte[] data, short data_offset, short length) { byte[] file = getFile(fid); short fileSize = getFileSize(fid); if (file == null) { ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND); } if (fileSize < (short) (file_offset + length)) ISOException.throwIt(ISO7816.SW_FILE_FULL); Util.arrayCopyNonAtomic(data, data_offset, file, file_offset, length); // Extract the pointers to where the Root and Alternate root CVCA certificate // identifiers are stored. Properly this should be done with a BERTLVScanner or // similar. if(fid == EF_COM_FID) { short cvcaRootIndex = -1; short cvcaAltIndex = -1; for(short i = 0; i<length ; i++) { if(data[i] == 0x04 && data[(short)(i+1)] == 0x11) { if(cvcaRootIndex == -1) { cvcaRootIndex = (short)((short)(file_offset + i) + 2); }else{ cvcaAltIndex = (short)((short)(file_offset + i) + 2); } } } SmartIDApplet.certificate.setCOMFileData(file, cvcaRootIndex, cvcaAltIndex); } }
a53fd446-ee9c-4eb6-8315-23e69690b154
2
public String getMusic(String scene) { if(scene.equalsIgnoreCase("main menu")) { return "assets/audio/testi.wav"; } if(scene.equalsIgnoreCase("gameplay")) { return "assets/audio/background.wav"; } return null; }
07491b51-c6a4-4a6d-9c9c-f690e1891fda
9
public boolean keyDown(Event e, int key) { if (key == Event.LEFT) { player.setDirection(Player.LEFT); player.setFacing(Player.LEFT); } if (key == Event.RIGHT) { player.setDirection(Player.RIGHT); player.setFacing(Player.RIGHT); } if (key == Event.UP) { player.setDirection(Player.UP); player.setFacing(Player.UP); } if (key == Event.DOWN) { player.setDirection(Player.DOWN); player.setFacing(Player.DOWN); } // user presses space bar if (key == 32) { // Bullet gets added to the outside of the box to avoid accidental hits if (player.getFacing() == Player.LEFT) { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y, Player.LEFT, true)); } else if (player.getFacing() == Player.RIGHT) { bullets.add(new Bullet( player.getPosition().x + Player.WIDTH, player.getPosition().y, Player.RIGHT, true)); } else if (player.getFacing() == Player.UP) { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y, Player.UP, true)); } else { bullets.add(new Bullet( player.getPosition().x, player.getPosition().y + Player.HEIGHT, Player.DOWN, true)); } } if (key == Event.ENTER) { bar.switchDebug(); bar.updateStatus(); } return true; }
5d1656f0-5304-4ddc-bc46-51443b26ff5a
5
@Override public SecurityChallenge getUserSecurityChallenge(String username) { for(LdapServer server : ldapServers) { try { SecurityChallenge challenge = server.getUserSecurityChallenge(username); if(logger.isDebugEnabled()) { if(challenge != null) { logger.debug("Successfully got security challenge for " + username + " at " + server.getDescription()); } else { logger.debug("Got null security challenge for " + username + " at " + server.getDescription()); } } return challenge; } catch(NameNotFoundException ex) { logger.debug("Didn't find " + username + " in " + server.getDescription()); // ignore it... try the next server } catch(ObjectRetrievalException ex) { logger.debug("Multiple results found for " + username); // ignore it... try the next server } } throw new NameNotFoundException("Couldn't find username " + username + " in any of provided servers."); }
f0ee68df-15cc-464b-9f4a-393fba7fc5ae
0
public String toString() { return "waiting for items to be chosen"; }
d0145d2c-5ded-4881-be60-62e5151450f7
9
public static String find(File file) { RandomAccessFile fileHandler = null; try { fileHandler = new RandomAccessFile(file, "r"); long fileLength = fileHandler.length() - 1; StringBuilder sb = new StringBuilder(); for (long filePointer = fileLength; filePointer != -1; filePointer--) { fileHandler.seek(filePointer); int readByte = fileHandler.readByte(); if (readByte == 0xA) { if (filePointer == fileLength) { continue; } break; } else if (readByte == 0xD) { if (filePointer == fileLength - 1) { continue; } break; } sb.append((char) readByte); } String lastLine = sb.reverse().toString(); return lastLine; } catch (java.io.FileNotFoundException e) { e.printStackTrace(); return null; } catch (java.io.IOException e) { e.printStackTrace(); return null; } finally { if (fileHandler != null) { try { fileHandler.close(); } catch (IOException e) { e.printStackTrace(); return null; } } } }
cb9e7d61-d13d-4bfc-be9f-ba08fb550b35
7
@Override public void execute() { boolean partyFull = curGb.readMemory(curGb.pokemon.numPartyMonAddress) >= 6; seq(new EflSkipTextsSegment(1)); // wild mon seq(new EflBallSuccessSegment()); seq(new EflSkipTextsSegment(4)); // cought, new dex data seqEflButton(Move.A); // skip dex seqEflButton(Move.B); // skip dex if (bufferSize >= 0 && !partyFull) StateBuffer.pushBufferSize(bufferSize); seq(new EflTextSegment(Move.A)); if (extraSkips > 0) seqEflSkipInput(extraSkips); seqEflButtonUnboundedNoDelay(Move.B); seq(new EflSkipTextsSegment(1, name != null)); // nickname? if (name != null) { seq(new NamingSegment(name)); seqEflButton(Move.START); } if (partyFull) { if (bufferSize >= 0) StateBuffer.pushBufferSize(bufferSize); seq(new EflSkipTextsSegment(2)); // transferred to PC } if (bufferSize >= 0) StateBuffer.popBufferSize(); }
4c11973f-25f3-47c0-b2de-73a2edd89000
6
@Override public boolean removeAll(Collection<?> c) { if (c == null || c.isEmpty()) { return false; } boolean removedAll = true; for (Object element : c) { if (element == null) { removedAll = false; } } return removedAll && listWrapper.removeAll(c); }
6e760b6c-6129-4710-a2b5-b22f4b419b63
8
private int searchIndex(int numero, boolean activa){ int index = -1; if(activa){ for (int i = 0; i<cuentas.length; i++) { if(cuentas[i] != null && cuentas[i].validarCuenta(numero) && cuentas[i].isActiva()){ index=i; break; } } }else{ for (int i = 0; i<cuentas.length; i++) { if(cuentas[i] != null && cuentas[i].validarCuenta(numero)){ index=i; break; } } } return index; }
1be19eb7-4818-4614-82d2-37e832011300
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(ComSupContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ComSupContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ComSupContactUs.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ComSupContactUs.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 ComSupContactUs().setVisible(true); } }); }
11808801-5a67-43e3-adf7-73c46b95db1f
7
private static boolean isSimpleReturnType(Method method, Object object) { Class<?> returnType = getActualReturnType(method, object); return returnType.equals(Integer.TYPE) || returnType.equals(Integer.class) || returnType.equals(Double.TYPE) || returnType.equals(Double.class) || returnType.equals(Float.TYPE) || returnType.equals(Float.class) || returnType.equals(String.class); }
47668ca9-da6b-42b7-a6ff-9cf11fd80cb6
7
public void setValueAt(Object o, int row, int col) { if (row != newRow) { if (col == 1 || o.toString().length() > 0) { int rowInModel = row < newRow ? row : row - 1; nodeAttributeModel.setValueAt(o, rowInModel, col); } return; } else { newRow = AFTER_LAST_ROW; fireTableRowsDeleted(row, row); if (col == 0 && o != null && o.toString().length() > 0) { nodeAttributeModel.insertRow(row, o.toString(), ""); } return; } }