method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
e41ae629-6130-47f9-bbe6-b30d3796cb2d
9
@Override public void start(Map<String, List<String>> incAttributes, String incUrl, Socket socket) { System.out.println("Starting NavigationSystem Plugin"); ResponseHandler respHandle = new ResponseHandler(socket); if (incAttributes.isEmpty()) { try { respHandle.startStream(); } catch (IOException ex) { System.out.println("Could not start stream: " + ex); } showStarterScreen(respHandle); respHandle.closeStream(); } else { for (Map.Entry<String, List<String>> entry : incAttributes.entrySet()) { String key = entry.getKey(); System.out.println(key); if (key.equals("action")) { try { respHandle.startStream(); } catch (IOException ex) { System.out.println("Could not start stream: " + ex); } System.out.println("Key: " + key); for (String value : entry.getValue()) { switch (value) { case "reloadMap": reloadMap(respHandle); respHandle.closeStream(); break; case "findLocation": try { findLocation(respHandle, incAttributes); respHandle.closeStream(); } catch (ParserConfigurationException | SAXException ex) { System.out.println("SAX Error: " + ex); } break; default: System.out.println("Unknown action"); showStarterScreen(respHandle); respHandle.closeStream(); break; } } } else { showStarterScreen(respHandle); respHandle.closeStream(); } } } }
4ed97f11-37b7-41b2-98c6-74fecdbf9008
3
@Override protected void mine(Player p) { //oven can not be destroyed with items in it if(inventory[0] == null && inventory[1] == null && inventory[2] == null){ super.mine(p); }else{ System.out.println("Oven can not be recovered while it has items stocked !"); resetHealth(); } }
6c38653f-2775-4c39-a4f0-8c074862936e
0
public DigestMethodType getDigestMethod() { return digestMethod; }
4aa3bca8-3651-4a61-8dd5-8eed6be6be94
1
public List<Material> Wastage(int ME) { List<Material> wastage; wastage = new ArrayList<Material>(); for (int i = 0; i < Materials.size(); i++) { Material mat; mat = new Material(); mat.ProductID = Materials.get(i).ProductID; mat.ProductName = Materials.get(i).ProductName; mat.MaterialID = Materials.get(i).MaterialID; mat.MaterialName = Materials.get(i).MaterialName; mat.PerfectAmount = round(Materials.get(i).PerfectAmount * (WasteFactor / 100.0f) * (1.0f / (1.0f + ME))); wastage.add(mat); } return wastage; }
6e0e5957-1c6c-4918-8081-6ccd87982a95
9
public static void main(String[] args) { logger.setLevel(Level.SEVERE); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.SEVERE); logger.addHandler(handler); if (args.length == 0) { logger.warning("Invalid arguments count."); return; } try { System.out.println(Arrays.toString(args)); String skey = args[0]; int key[] = new int[skey.length()]; int pos = 1; for (int k = 0; k < 256; k++) { for (int n = 0; n < skey.length(); n++) { if (skey.charAt(n) == k) { key[n] = pos++; } } } System.out.println(Arrays.toString(key)); String file = args[1]; String dir = args[2]; BufferedReader in = new BufferedReader(new FileReader(file)); while (in.ready()) { if (dir.equals("0")) { String ret = encrypt(key, in.readLine()); System.out.println(ret); } else if (dir.equals("1")){ String ret = decrypt(key, in.readLine()); System.out.println(ret); } else{ String ret = encrypt(key, in.readLine()); System.out.println(ret); ret = decrypt(key, ret); System.out.println(ret); } } } catch (NumberFormatException | FileNotFoundException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } }
4d9a874e-6077-47d2-81a9-8a0e32901b82
6
public static Set<Player> run(GameState state, GameSettings gSettings) { //Setup global game settings settings = gSettings; //Launch the GUIs state.launchGUIs(); //Hello! state.log("The game is starting!\nLook for a log of game events here"); //get the list of all the drawable cards ArrayList<Integer> availibleCards = state.getDeck().allCards(); for(int week = state.getWeek(); week < settings.weekAmt(); week++) { state.setWeek(week); if(!state.checkDraw()) { state.getBag().resetBag(); placeTreasures(state); distributeInitialGold(state, settings.initialGold()); //this section either draws the initial hand (at the start of the game) //or adds six cards to the existing hands drawCards(state, availibleCards, settings.cardAmt(week)); } state.updateGUIs(); state = weekLoop(state); } int max = Integer.MIN_VALUE; HashSet<Player> winners = new HashSet<Player>(); //determine the winners of the game! for(Player p : state.getPlayerList()) { if(p.getScore() == max) { winners.add(p); } else if(p.getScore() > max) { winners.clear(); winners.add(p); max = p.getScore(); } } for(Player p : winners) { state.log((Faction.getPirateName(p.getFaction()) + " won with a score of " + p.getScore() + "!")); } return winners; }
87e8cb63-13a5-410a-8040-b63eaa22c9b9
9
public static String reverseVowels(String s) { if (s == null) return ""; char chars[] = new char[s.length()]; int i = 0, j = s.length() - 1; while (i <= j) { while (i < s.length() - 1 && !isvowel(s.charAt(i))) { chars[i] = s.charAt(i); i++; } while (j >= 0 && !isvowel(s.charAt(j))) { chars[j] = s.charAt(j); j--; } if (i < s.length() && j >= 0) { chars[i] = s.charAt(j); chars[j] = s.charAt(i); i++; j--; } } StringBuilder sb = new StringBuilder(); for (i = 0; i < chars.length; i++) { sb.append(chars[i]); } return sb.toString(); }
2e96c9ad-cd56-44e4-b345-8bc474976d2c
5
public double standardError_as_double() { boolean hold = Stat.nFactorOptionS; if (nFactorReset) { if (nFactorOptionI) { Stat.nFactorOptionS = true; } else { Stat.nFactorOptionS = false; } } double standardError = 0.0D; switch (type) { case 1: double[] dd = this.getArray_as_double(); standardError = Stat.standardError(dd); break; case 12: BigDecimal[] bd = this.getArray_as_BigDecimal(); standardError = Stat.standardError(bd); bd = null; break; case 14: throw new IllegalArgumentException("Complex cannot be converted to double"); default: throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!"); } Stat.nFactorOptionS = hold; return standardError; }
bc3ee56a-c5e0-4a4d-bd1c-d20183d62837
7
private DecisionTreeNode parseNode(XMLStreamReader reader, String[] labels) throws XMLStreamException { DecisionTreeNode result = null; //Put reader on the next node goToNext(reader, "node"); //Leaf or not ? if(reader.getAttributeValue(null, "type").equals("leaf")) { //Create decision Decision d = new Decision(); //Read population values goToNext(reader, "population"); if(reader.getEventType() == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("population")) { //For each LX attribute, associate value to label in decision for(int i=0; i < reader.getAttributeCount(); i++) { int labelIndex = Integer.parseInt(reader.getAttributeLocalName(i).substring(1)); d.addPopulation(labels[labelIndex], Integer.parseInt(reader.getAttributeValue(i))); } } else { throw new XMLStreamException("The given tree isn't well structured (no <population>)"); } //Put it in result result = d; } else { //Create rule Rule r; //Read question goToNext(reader, "question"); if(reader.getEventType() == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("question")) { //If value is numeric if(reader.getAttributeValue(null, "type").equals("numeric")) { r = new Rule( reader.getAttributeValue(null, "name"), Double.parseDouble(reader.getAttributeValue(null, "patron")) ); } //Else (value is a string) else { r = new Rule( reader.getAttributeValue(null, "name"), reader.getAttributeValue(null, "patron") ); } } else { throw new XMLStreamException("The given tree isn't well structured (no <question>)"); } //Read population goToNext(reader, "population"); //Read left son goToNext(reader, "node"); r.setLeftSon(parseNode(reader, labels)); //Read right son goToNext(reader, "node"); r.setRightSon(parseNode(reader, labels)); //Put it in result result = r; } return result; }
77ac38f1-f2ef-49e2-bc53-bb5047e12361
4
public Log_record(String one_line_rec) { //14/03/09 13:41:36.852 subsys event print_job_start user_name=operator1; file_name=default; sizeX=1200; sizeY=600; inkC=678; inkM=756; inkY=456; inkK=789; data = new Date(); data.setTime(0); subsystem = record_subsystems.Unknown; message_type = record_type.Unknown; name = record_name.Unknown; params = new ArrayList<RecParametr>(); //SimpleDateFormat sdf = new SimpleDateFormat("yy/mm/dd hh/m"); String[] strs = one_line_rec.split("\t"); //System.out.println("strs_len=" + strs.length); if(strs.length < 4) return; String stringDateFormat = "yy/MM/dd HH:mm:ss.SSS"; SimpleDateFormat format = new SimpleDateFormat(stringDateFormat, Locale.US); try { data = format.parse(strs[0]); //System.out.println(strs[0] + " d= " + data); } catch (ParseException e) { e.printStackTrace(); } //System.out.println(strs[0] + " d2= " + data); subsystem = record_subsystems.GetByName(strs[1]); message_type = record_type.GetByName(strs[2]); str_value = ""; str_value = strs[3]; for(int i = 4; i < strs.length; i++) str_value += "\t" + strs[i]; //System.out.println("str3 = " + strs[3]); name = record_name.GetByName(strs[3]); //System.out.println("str3 = " + name.name()); if(strs.length>4) params = RecParametr.StringToParams(strs[4]); //System.out.println("record"); }
0d8d39d6-43c5-4425-b91b-acf91a10916d
2
@Override protected void process(List<RuleTaskState> chunks) { for (RuleTaskState chunk : chunks) { int progressValue = chunk.i; String stringToLog = chunk.s; if (progressValue == -1) { rd.addToMatchesList(stringToLog); continue; } rd.setTestingProgress(progressValue); rd.addToLog(stringToLog); } }
cd882615-cfdc-4f3b-9fcd-3fd5a594469a
8
private boolean rekAble(int x, int y) { for (int i=1;i<this.rekAbleR;i++) { for (int j=1;j<this.rekAbleR;j++) { if (y-j>=0 && x-i>=0) if (this.P[x-i][y-j].rek==1) return false; if (y+j<this.tabSizeY && x+i<this.tabSizeX) if (this.P[x+i][y+j].rek==1) return false; }//j }//i return true; }//--
03a94880-72f6-4ffe-9c27-4714a2ac9212
0
public String[] GetData() { return dataPieces; }
8bcffe87-1747-4a61-aed7-133650b95ea5
8
@SuppressWarnings("unchecked") private void updateIncomingReferences(ModelElementInstance oldInstance, ModelElementInstance newInstance) { String oldId = oldInstance.getAttributeValue("id"); String newId = newInstance.getAttributeValue("id"); if (oldId == null || newId == null) { return; } Collection<Attribute<?>> attributes = ((ModelElementTypeImpl) oldInstance.getElementType()).getAllAttributes(); for (Attribute<?> attribute : attributes) { if (attribute.isIdAttribute()) { for (Reference<?> incomingReference : attribute.getIncomingReferences()) { ((ReferenceImpl<ModelElementInstance>) incomingReference).referencedElementUpdated(newInstance, oldId, newId); } } } }
7783b74e-8101-4f08-8747-c85aa1ee92c6
0
public void setjCheckBoxComptesRendus(JCheckBox jCheckBoxComptesRendus) { this.jCheckBoxComptesRendus = jCheckBoxComptesRendus; }
78df4007-b1e2-4de5-9cfd-06cd3a007074
1
private void deleteFolder_fileManagerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteFolder_fileManagerButtonActionPerformed try { selectedDevice.getFileSystem().delete(directoryLabel_fileManagerLabel.getText() + jList1.getSelectedValue()); } catch (IOException | DeleteFailedException ex) { logger.log(Level.ERROR, "An error occurred while deleting a folder (" + jList1.getSelectedValue() + ") on device " + selectedDevice.getSerial() + "\n" + "The error stack trace will be printed to the console..."); ex.printStackTrace(System.err); } }//GEN-LAST:event_deleteFolder_fileManagerButtonActionPerformed
693c542e-b286-41d4-a9f6-224dca96ba11
4
private void dealtDamage(int getX, int getY, int getWidth, int getLength, int getTime, int getDelay, double getDamage,int applyForce) { if (character.equals("P1")) // player 1 { if (moveDirection) { // add new object (player 1) into the world at the correction orientation getWorld().addObject(new P1AttackArea(x + getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,moveDirection),x + getX, y + getY); } else { // add new object (player 2) into the world at the opposite orientation getWorld().addObject(new P1AttackArea(x - getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,moveDirection),x - getX, y + getY); } } else if (character.equals("P2")) // player 2 { if (moveDirection) { // add new object (player 1) into the world at the correction orientation getWorld().addObject(new P2AttackArea(x + getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,moveDirection),x + getX, y + getY); } else { // // add new object (player 2) into the world at the opposite orientation getWorld().addObject(new P2AttackArea(x - getX, y + getY,getWidth,getLength,getTime,getDelay,getDamage,applyForce,moveDirection),x - getX, y + getY); } } }
601dbf7b-82b5-4f53-92d6-4f011cd75f28
1
public int getXAxisValue() { if (xaxis == -1) { return 127; } return getAxisValue(xaxis); }
9b6f6094-2918-4c65-a641-7f6b392f61e6
9
@Override public void endElement(String uri, String localName, String qName) throws SAXException { currentLevel--; currentElement = false; String name = null; if (localName != null && localName.length() != 0 && !elementsHandled.contains(localName)) { name = localName; } else if (qName != null && qName.length() != 0 && !elementsHandled.contains(qName)) { name = qName; } if(name != null && name.length() != 0) { elementsHandled.add(name); currentObject.close(name, currentValue); if(name.equalsIgnoreCase(currentObject.className)) currentObject = null; } currentValue = ""; }
769cbdb1-e49d-408c-b02b-7831effa42da
6
public void updateGenerator() { if (generatorCoolDown == 0) { int structGenWeight; Random structGenRdm = new Random(); structGenWeight = structGenRdm.nextInt(15); if (structGenWeight == 11) { int valueWeight; Random valueWeightRdm = new Random(); valueWeight = valueWeightRdm.nextInt(42); if (valueWeight == 7) { generate(EnumGenerationType.experienceStruct); } else if ((valueWeight > 30) && (valueWeight < 37)) { generate(EnumGenerationType.cashStruct); } else { generate(EnumGenerationType.coinStruct); } } generatorCoolDown = 60; } if (generatorCoolDown > 0) { generatorCoolDown--; } }
7c9c9b2a-64ac-4480-ac25-1d1050f0894e
2
private void fullCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fullCBActionPerformed tablespaceT.clearSelection(); if(fullCB.isSelected()){ for(int i=0;i<tablespaceT.getRowCount();i++){ tablespaceT.getModel().setValueAt(false,i,1); } tablespaceT.setEnabled(false); } else{ tablespaceT.setEnabled(true); } }//GEN-LAST:event_fullCBActionPerformed
4c7664e6-29ac-41b5-a096-bcea5925b649
9
public static void ClockLoop(int duration) { // GUI_NB.GCO("Clock time is now " + DisplayTimeFull() + " with time rate " + ClockControl.PrintTimeScale()); GlobalFuncs.ticksStable++; if (GlobalFuncs.runtoEq || GlobalFuncs.updateVapor) { GlobalFuncs.maxDelta = 0; GlobalFuncs.scenMap.updateVaporSS(); // Calculates maximum DV at sources and sinks //GUI_NB.GCO("Num sources: " + GlobalFuncs.scenMap.vaporSourceList.size() + " and sinks: " + GlobalFuncs.scenMap.vaporSinkList.size()); if (GlobalFuncs.fixSlowRate && GlobalFuncs.updateVapor && time % 100 == 1) GlobalFuncs.scenMap.UpdateExactDVNorm(); GlobalFuncs.scenMap.recalcFlowRate(); GlobalFuncs.scenMap.calcAllVapor(); GlobalFuncs.scenMap.updateAllVapor(); if (GlobalFuncs.runtoEq) { if (Math.abs(GlobalFuncs.totalVaporDelta) <= GlobalFuncs.dvTolerance && GlobalFuncs.ticksStable > 100) { ClockControl.SetTimeScale((byte) 4); if (!ClockControl.paused) ClockControl.Pause(); GlobalFuncs.runtoEq = false; GUI_NB.GCODTG("Reached desired DV threshold."); } } GlobalFuncs.gui.repaint(); } else { moveAllUnits(duration); } GlobalFuncs.gui.BasicInfoPane.repaint(); }
8e8ec4aa-d8b1-4211-ba88-46f5947725eb
4
public boolean collide(Block block) { if (this.hasPoint(block.getX() - block.getWidth() / 2, block.getY() - block.getHeight() / 2) || this.hasPoint(block.getX() - block.getWidth() / 2, block.getY() + block.getHeight() / 2) || this.hasPoint(block.getX() + block.getWidth() / 2, block.getY() - block.getHeight() / 2) || this.hasPoint(block.getX() + block.getWidth() / 2, block.getY() + block.getHeight() / 2)) { return true; } return false; }
0e494327-19b6-4ad5-ab20-9ea88a50fde9
3
public int matchScore(Person p, Person q){ set.forEach(k -> engine.put(k, p.match(q, k))); Object ret = null; try{ ret = ((Invocable)engine).invokeFunction(FUNC_NAME); } catch (ScriptException | NoSuchMethodException ex){ throw new RuntimeException(ex); } if (ret == null) { throw new RuntimeException("null return"); } else if (ret instanceof Number) { return ((Number)ret).intValue(); } throw new RuntimeException("unknown return type : " + ret.getClass()); }
ee29cf23-e863-4ed3-89a5-9c1c146f038a
2
private void Jornada_ComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_Jornada_ComboBox2ItemStateChanged // TODO add your handling code here: int i = 0; if (Jornada_ComboBox2.getSelectedIndex() > -1) { int p = Integer.parseInt(Jornada_ComboBox2.getSelectedItem().toString()) - 1; Collection<Jogo> jogos = calendario.get("Escalao." + Escalao_ComboBox2.getSelectedItem().toString() + Integer.toString(p)); for (Jogo j : jogos) { Jornadas_Table.setValueAt(j.getEquipa1(), i, 0); Jornadas_Table.setValueAt(j.getGolo1() + " x " + j.getGolo2(), i, 1); Jornadas_Table.setValueAt(j.getEquipa2(), i, 2); i++; } } }//GEN-LAST:event_Jornada_ComboBox2ItemStateChanged
f382980a-6294-44b6-ab1d-4c6b7a5cb8b4
5
public static void sort(Comparable[] a){ int N = a.length, h = 1; // while(h < N/3) h = 3*h + 1; while(h < N/3) h = 3*h ; while(h>=1){ for(int i = h; i < N; i++){ for(int j = i; j>=h; j-=h){ if(a[j].compareTo(a[j-h]) < 0){ Comparable tmp = a[j-h]; a[j-h] = a[j]; a[j] = tmp; } } } h /= 3; } }
57de4b76-fdac-45a5-80d1-3b403d3b53e7
6
protected boolean isValidLocation(UnitMover mover, int sx, int sy, int x, int y) { boolean invalid = (x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles()); if ((!invalid) && ((sx != x) || (sy != y))) { invalid = map.blocked(mover, x, y); } return !invalid; }
c9b92763-8d6b-4389-8809-c50c55a59aac
5
public void run() { Debug.println("PhysicsEngine.run()"); synchronized (workQueue) { while (true) { if (workQueue.peek() == null) { try { workQueue.wait(); } catch (InterruptedException e) { continue; } } else { int doWhat = workQueue.poll(); switch (doWhat) { case 0: controlPanel.updateSliders(); power = controlPanel.getPower(); direction = -controlPanel.getDirection(); spin = -controlPanel.getSpin(); throwBall(); break; case 1: resetPins(); break; } } } } }
45828d45-b483-4b29-957b-daa936efd30f
2
private static void handleDropOfferReq(SerializableDropOfferReq pack) { //List<String> sellers = pack.commandInfo; Server.loggerServer.info("[Server] drop auction"); List<String> sellers = new ArrayList<String>(); SelectionKey key; sellers.addAll(pack.commandInfo); // reset list in pack (no longer needed) pack.commandInfo = null; // send "drop offer" packet to each seller still logged in for (String seller : sellers) { key = Server.registeredUsersChannels.get(seller); if (key == null) { Server.loggerServer.info("[Server] User " + seller + " is no longer" + " logged in => no 'drop offer' message sent to him"); continue; } Server.loggerServer.info("[Server] sending drop offer announce to seller " + seller + " (from buyer " + pack.userName + ", service " + pack.serviceName + ")"); Server.sendData(key, pack); } }
98aeddab-f030-4624-924e-e02c1e07078b
8
protected void findBounds(int w,int h) { // top line for ( int y=0;y<h;y++ ) { if ( !hLineClear(y) ) { downSampleTop=y; break; } } // bottom line for ( int y=h-1;y>=0;y-- ) { if ( !hLineClear(y) ) { downSampleBottom=y; break; } } // left line for ( int x=0;x<w;x++ ) { if ( !vLineClear(x) ) { downSampleLeft = x; break; } } // right line for ( int x=w-1;x>=0;x-- ) { if ( !vLineClear(x) ) { downSampleRight = x; break; } } }
1be75eab-2b4f-4412-a029-897dd8e7f5c3
7
public static void anotherWatcher() { try { WatchService watchService = FileSystems.getDefault().newWatchService(); Path dir = Paths.get("/home/xander/test/"); dir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); FileTime lastModified = null; while (true) { WatchKey key = watchService.take(); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { FileTime time = Files.getLastModifiedTime(dir.resolve(Paths.get("file.txt"))); if (lastModified == null) { lastModified = time; } if (lastModified.compareTo(time) < 0) { System.out.println("reload"); lastModified = time; Calendar date = Calendar.getInstance(); date.setTimeInMillis(time.toMillis()); System.out.println("time is " + date.getTime() + "\n"); } else { System.out.println("reload skipped"); } } } key.reset(); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
6d9c889c-a74f-40f6-881e-cb6657f954da
6
private static void loadComponents(AutoCodeConfig autoCodeConfig,Map variables) throws InvalidPropertiesFormatException { if(variables == null || variables.get("component") == null){ throw new InvalidPropertiesFormatException("Can't find any component!"); } if(!(variables.get("component") instanceof Map)){ throw new InvalidPropertiesFormatException("Component config error!"); } Map componentMap = (Map)variables.get("component"); for(Map.Entry<String,Map> entry : (Set<Map.Entry<String,Map>>)componentMap.entrySet()){ if(entry.getValue()!= null &&(entry.getValue() instanceof Map)){ autoCodeConfig.addComponent(entry.getKey(),buildComponent(entry.getKey(),entry.getValue())); //把component加入根结构中,方便模板调用 variables.put(entry.getKey(),entry.getValue()); } } }
e2e534a1-1486-4834-a1a8-72d912550dac
6
@Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Save")) { // Saves the current values in an existing notice model.edit(view.getNotice(), view.getSubject(), view.getText(), view.getPriority()); view.actualizeList(model.getSubjects()); view.revalidate(); view.repaint(); view.pack(); } if(e.getActionCommand().equals("New")) { // Adds a new notice or does nothing, if the notice already exists model.add(new SSNotice(view.getSubject(), view.getText(), view.getPriority())); model.arraying(); view.actualizeList(model.getSubjects()); view.init(model.getDate(-1)); view.revalidate(); view.repaint(); view.pack(); } if(e.getActionCommand().equals("Delete")) { // Deletes an existing notice or does nothing, if there is no notice model.remove(view.getNotice()); model.arraying(); view.actualizeList(model.getSubjects()); view.init(model.getDate(-1)); view.revalidate(); view.repaint(); view.pack(); } if(e.getActionCommand().equals("Notices")) { // Loads the values from an existing notice view.setSubject(model.getSubject(view.getNotice())); view.setText(model.getText(view.getNotice())); view.setDate(model.getDate(view.getNotice())); view.setPriority(model.getPriority(view.getNotice())); } if(e.getActionCommand().equals("Sorting")) { // Sort based on given mechanism and list again. if(view.getSort().equals("Prioritize")) { model.sort(new SSNotice()); }else{ model.sort(null); } view.actualizeList(model.getSubjects()); } }
47f7ce08-1511-47d6-a650-1ec80299cd35
3
@Test public void timer() { final List<Long> expecteds=Arrays.asList(1L,2L,3L,4L,5L); final List<Long> actuals=new ArrayList<Long>(); final Timer timer = new Timer(1000, 5); timer.addEventListener(TimerEvent.TIMER, new EventListener() { @Override public void handleEvent(Event event) { System.out.println("timer tick " + timer.getCurrentCount()); System.out.println(JSON.toJSONString(timer, true)); actuals.add(timer.getCurrentCount()); } }); timer.addEventListener(TimerEvent.TIMER, new EventListener() { @Override public void handleEvent(Event event) { if (timer.getCurrentCount() == 3) { System.out.println("timer stop"); timer.stop(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("timer start"); timer.start(); } } }); timer.addEventListener(TimerEvent.TIMER_COMPLETE, new EventListener() { @Override public void handleEvent(Event event) { System.out.println("timer complete"); System.out.println(JSON.toJSONString(timer, true)); lock.countDown(); } }); System.out.println("timer beforestart"); System.out.println(JSON.toJSONString(timer, true)); timer.start(); try { lock.await(10000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Arrays.toString(expecteds.toArray())); System.out.println(Arrays.toString(actuals.toArray())); Assert.assertArrayEquals(expecteds.toArray(), actuals.toArray()); }
be08ed1b-a1eb-4e2f-adb0-04da38c7bb4a
3
public boolean remove(String sana) { if (etsiSana(sana) == false) { return false; } Node poistettava = getChild(sana.charAt(0)); if (sana.length() > 1) { String loput = sana.substring(1); poistettava.remove(loput); } if (poistettava.size() > 1) { poistettava.decreaseSize(); } else { juuri.remove(poistettava); } return true; }
d7d83bac-a81d-4ca7-a8ef-3c24c5d55f95
2
@Override public void run() { while (true) { try { String data = blockingDeque.takeFirst(); System.out.println(Thread.currentThread().getName() + " take(): " + data); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
f4bea69a-2858-4328-acb5-7af1e0c1853a
9
public String convertInitial(char initial){ String name = null; if(initial == 'C'){ name = "Conservatory"; } if(initial == 'K'){ name = "Kitchen"; } if(initial == 'B'){ name = "Ballroom"; } if(initial == 'R'){ name = "Billiard room"; } if(initial == 'L'){ name = "Library"; } if(initial == 'S'){ name = "Study"; } if(initial == 'D'){ name = "Dining room"; } if(initial == 'O'){ name = "Lounge"; } if(initial == 'H'){ name = "Hall"; } return name; }
a826b07e-0f7a-42fc-a222-47ba0daca3bc
3
public void appendSamples(int channel, float[] f) { int pos = bufferp[channel]; short s; float fs; for (int i=0; i<32;) { fs = f[i++]; fs = (fs>32767.0f ? 32767.0f : (fs < -32767.0f ? -32767.0f : fs)); s = (short)fs; buffer[pos] = s; pos += channels; } bufferp[channel] = pos; }
d71aa70d-5145-46f5-8c75-07275d12d1c6
9
@Override public void executeMove(ChessBoard board) { promoted_coin = null; if (option == NOT_DEFINED) { // PromotionDialog temp = new PromotionDialog(null, true); // temp.setVisible(true); // option = temp.getOption(); } switch (option) { case QUEEN: { promoted_coin = (color == CoinColor.WHITE) ? new WhiteQueen() : new BlackQueen(); break; } case ROOK: { promoted_coin = (color == CoinColor.WHITE) ? new WhiteRook() : new BlackRook(); break; } case KNIGHT: { promoted_coin = (color == CoinColor.WHITE) ? new WhiteKnight() : new BlackKnight(); break; } case BISHOP: { promoted_coin = (color == CoinColor.WHITE) ? new WhiteBishop() : new BlackBishop(); break; } } board.setCoinAt(Coin.Empty, start); board.setCoinAt(promoted_coin, end); moved.Moved(); promoted_coin.Moved(); }
b301203d-4b11-40a0-a376-262bb4753bbc
8
public boolean either24(int[] nums) { boolean is22 = false; boolean is44 = false; for (int i = 0; i < nums.length-1; i++) { if (nums[i] == 2 && nums[i+1] == 2) { is22 = true; } else if (nums[i] == 4 && nums[i+1] == 4) { is44 = true; } } return (is22 && !is44) || (!is22 && is44); }
5691e3f4-d385-4cd9-a5d3-1e5d37d2fab3
6
public void createFromXML(NodeList attributes) { Node n = attributes.item(0); while(n != null) { if(n.getNodeType() == Node.ELEMENT_NODE) { if(n.getNodeName().equals("rateOfFire")) { rateOfFire = Float.parseFloat(n.getFirstChild().getNodeValue()); timeBetweenShots = (long)(1000 / rateOfFire); timeSinceLastShot = timeBetweenShots-1; } else if(n.getNodeName().equals("damage")) { damage = Integer.parseInt(n.getFirstChild().getNodeValue()); } else if(n.getNodeName().equals("bullet")) { bullet = n.getFirstChild().getNodeValue(); } else if(n.getNodeName().equals("range")) { range = Float.parseFloat(n.getFirstChild().getNodeValue()); } } n = n.getNextSibling(); } }
3f55ce66-d195-4017-8acb-f49794e4d634
8
private void findOutAboutFriends() { //Friend names String alexName; alexName = JOptionPane.showInputDialog("What is your name"); alexFriend.setName(alexName); String alexHumorStyle; alexHumorStyle = JOptionPane.showInputDialog("What is your humor style"); alexFriend.setHumorStyle(alexHumorStyle); int alexAge; String alexTemp; alexTemp = JOptionPane.showInputDialog("How old are you?"); alexAge = Integer.parseInt(alexTemp); alexFriend.setAge(alexAge); String alexInterest; alexInterest = JOptionPane.showInputDialog("What is one of your interests?"); alexFriend.setInterest(alexInterest); boolean alexLikesPineapple; String alexPineapple; alexPineapple = JOptionPane.showInputDialog("Do you like pineapple? type yes or no"); if(alexPineapple.equalsIgnoreCase("yes")) { alexLikesPineapple = true; alexFriend.setLikesPineapple(alexLikesPineapple); } else if(alexPineapple.equals("no")) { alexLikesPineapple = false; alexFriend.setLikesPineapple(alexLikesPineapple); } double alexWeight; String temp = JOptionPane.showInputDialog("How much do you weigh?"); alexWeight = Double.parseDouble(temp); alexFriend.setWeight(alexWeight); String taylorName; taylorName = JOptionPane.showInputDialog("What is your name"); spencerFriend.setName(taylorName); String taylorHumorStyle; taylorHumorStyle = JOptionPane.showInputDialog("What is your humor style"); taylorFriend.setHumorStyle(taylorHumorStyle); int taylorAge; String taylorTemp; taylorTemp = JOptionPane.showInputDialog("How old are you?"); taylorAge = Integer.parseInt(taylorTemp); spencerFriend.setAge(taylorAge); String taylorInterest; taylorInterest = JOptionPane.showInputDialog("What is one of your interests?"); taylorFriend.setInterest(taylorInterest); boolean taylorLikesPineapple; String taylorPineapple; taylorPineapple = JOptionPane.showInputDialog("Do you like pineapple? type yes or no"); if(taylorPineapple.equalsIgnoreCase("yes")) { taylorLikesPineapple = true; taylorFriend.setLikesPineapple(taylorLikesPineapple); } else if(taylorPineapple.equals("no")) { taylorLikesPineapple = false; taylorFriend.setLikesPineapple(taylorLikesPineapple); } double taylorWeight; String temp1 = JOptionPane.showInputDialog("How much do you weigh?"); taylorWeight = Double.parseDouble(temp1); taylorFriend.setWeight(taylorWeight); String spencerName; spencerName = JOptionPane.showInputDialog("What is your name"); spencerFriend.setName(spencerName); String spencerHumorStyle; spencerHumorStyle = JOptionPane.showInputDialog("What is your humor style"); spencerFriend.setHumorStyle(spencerHumorStyle); int spencerAge; String spencerTemp; spencerTemp = JOptionPane.showInputDialog("How old are you?"); spencerAge = Integer.parseInt(spencerTemp); spencerFriend.setAge(spencerAge); String spencerInterest; spencerInterest = JOptionPane.showInputDialog("What is one of your interests?"); spencerFriend.setInterest(spencerInterest); boolean spencerLikesPineapple; String spencerPineapple; spencerPineapple = JOptionPane.showInputDialog("Do you like pineapple? type yes or no"); if(spencerPineapple.equalsIgnoreCase("yes")) { spencerLikesPineapple = true; spencerFriend.setLikesPineapple(spencerLikesPineapple); } else if(spencerPineapple.equals("no")) { spencerLikesPineapple = false; spencerFriend.setLikesPineapple(spencerLikesPineapple); } double spencerWeight; String temp2 = JOptionPane.showInputDialog("How much do you weigh?"); spencerWeight = Double.parseDouble(temp2); spencerFriend.setWeight(spencerWeight); String tristinName; tristinName = JOptionPane.showInputDialog("What is your name"); tristinFriend.setName(tristinName); String tristinHumorStyle; tristinHumorStyle = JOptionPane.showInputDialog("What is your humor style"); tristinFriend.setHumorStyle(tristinHumorStyle); int tristinAge; String tristinTemp; tristinTemp = JOptionPane.showInputDialog("How old are you?"); tristinAge = Integer.parseInt(tristinTemp); spencerFriend.setAge(tristinAge); String tristinInterest; tristinInterest = JOptionPane.showInputDialog("What is one of your interests?"); tristinFriend.setInterest(tristinInterest); boolean tristinLikesPineapple; String tristinPineapple; tristinPineapple = JOptionPane.showInputDialog("Do you like pineapple? type yes or no"); if(tristinPineapple.equalsIgnoreCase("yes")) { tristinLikesPineapple = true; tristinFriend.setLikesPineapple(tristinLikesPineapple); } else if(tristinPineapple.equals("no")) { tristinLikesPineapple = false; tristinFriend.setLikesPineapple(tristinLikesPineapple); } double tristinWeight; String temp3 = JOptionPane.showInputDialog("How much do you weigh?"); tristinWeight = Double.parseDouble(temp3); tristinFriend.setWeight(tristinWeight); }
50090526-e5cc-4878-bb6c-8ce84741363f
9
static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } }
dccfdd99-cb6f-4c46-bd6f-893be31774ca
4
public boolean isBlockAlreadyInRoulette(Block block) { Set<Integer> tilesKeys = tilesLocations.keySet(); for(Integer key : tilesKeys) { SerializableLocation blockLocation = new SerializableLocation(block.getLocation()); if(tilesLocations.get(key).contains(blockLocation)) return true; } Set<Integer> spinnersKeys = spinnersLocations.keySet(); for(Integer key : spinnersKeys) { SerializableLocation blockLocation = new SerializableLocation(block.getLocation()); if(spinnersLocations.get(key).equals(blockLocation)) return true; } return false; }
e6bbafce-6585-4eb2-b143-425f053ef145
8
@Override public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) { final java.util.Map<String,String> parms=parseParms(parm); final String last=httpReq.getUrlParameter("SOCIAL"); if(parms.containsKey("RESET")) { if(last!=null) httpReq.removeUrlParameter("SOCIAL"); return ""; } String lastID=""; for(int s=0;s<CMLib.socials().getSocialsList().size();s++) { final String name=CMLib.socials().getSocialsList().get(s); if((last==null)||((last.length()>0)&&(last.equals(lastID))&&(!name.equalsIgnoreCase(lastID)))) { httpReq.addFakeUrlParameter("SOCIAL",name); return ""; } lastID=name; } httpReq.addFakeUrlParameter("SOCIAL",""); if(parms.containsKey("EMPTYOK")) return "<!--EMPTY-->"; return " @break@"; }
a0bea7d8-d37f-4f43-936a-3f9d80e649de
3
void kvpExpand(StringBuilder b, List<KVP> l, String method) { for (KVP c : l) { String[] from = c.getKey().split("\\."); String tos = c.getValue().toString().trim(); String[] t = tos.split("\\s+"); // multiple @In for (String kvp : t) { String to_obj = kvp; // default target is just object name String to_field = from[1]; // same as @Out if (kvp.indexOf('.') > 0) { String[] to = kvp.split("\\."); to_obj = to[0]; to_field = to[1]; } b.append(" " + method + "(" + from[0] + ", \"" + from[1] + "\", " + to_obj + ", \"" + to_field + "\");\n"); } } }
44f79769-b396-4133-8436-1205c0dab289
3
public byte[] decrypt(byte[] in) { int iterations = 1; if(in.length > 128) { iterations = (int)Math.ceil(in.length/128); } int messageLen = 0; byte[] message = new byte[iterations * 117]; try { for(int i = 0; i < iterations; i++){ byte[] toBeDecrypted = new byte[128]; System.arraycopy(in, i*128, toBeDecrypted, 0, 128); Cipher rsa; rsa = Cipher.getInstance("RSA/ECB/NoPadding"); rsa.init(Cipher.DECRYPT_MODE, myKeys.getPrivate()); byte[] tempMessage = rsa.doFinal(toBeDecrypted); System.arraycopy(tempMessage, 0, message, messageLen, tempMessage.length); messageLen += tempMessage.length; } byte[] finalMessage = new byte[messageLen]; System.arraycopy(message, 0, finalMessage, 0, messageLen); return finalMessage; } catch (Exception e) { e.printStackTrace(); } return null; }
89476ac8-2a01-4545-8884-7f5146fa284a
1
public static ClassLoader getClassLoader() { ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader loader = contextCL == null ? ClassHelper.class.getClassLoader() : contextCL; return loader; }
07ee42b4-b249-4334-9af4-8bbc0f727af4
6
private Map makeRequest(HttpGet httpGet) { InputStream inputStream = null; for (int i = 0; i < 15; i++) { // try some times try { HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { inputStream = entity.getContent(); String resposneAsString = null; resposneAsString = IOUtils.toString(inputStream); Map result = new Gson().fromJson(resposneAsString, Map.class); Map error = (Map) result.get("error"); if (error == null || (Double) error.get("error_code") != ERROR_CODE_TOO_MANY_REQUESTS) { return result; } else { System.out.println("* got too many requests error try sleep two seconds"); TimeUnit.SECONDS.sleep(2); } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { try { assert inputStream != null; inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; //so bad :( }
bef8974c-65d9-4992-bdb1-b727cd72d3db
9
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (target == null) { sb.append(BeansUtils.NULL); } else { Class<?> clazz = target.getClass(); sb.append(clazz == String.class ? BeansUtils.QUOTE : BeansUtils .idOfClass(clazz)); } sb.append('.' + methodName + '('); if (arguments != null) { Class<?> clazz; for (int index = 0; index < arguments.length; index++) { if (index > 0) { sb.append(", "); //$NON-NLS-1$ } if (arguments[index] == null) { sb.append(BeansUtils.NULL); } else { clazz = arguments[index].getClass(); sb.append(clazz == String.class ? '"' + (String) arguments[index] + '"' : BeansUtils.idOfClass(clazz)); } } } sb.append(')'); sb.append(';'); return sb.toString(); }
d05f726b-6dc1-47e6-8db6-9bc8c0936607
3
@Test public void peekingDoesntChangeHeap() { heap.insert(1); for (int i = 0; i < 1336; i++) heap.insert((int)(2 + Math.random() * 10000)); int j = -1; for (int i = 0; i < 1337; i++) j = heap.peek(); assertTrue(j == 1 && heap.size() == 1337); }
34acf9ed-0f2b-48d8-a862-e9463f99b740
2
private String encryptString(String str) { StringBuffer sb = new StringBuffer (str); int lenStr = str.length(); int lenKey = key.length(); for (int i=0, j=0; i < lenStr; i++, j++ ) { if (j >= lenKey) j = 0; sb.setCharAt(i, (char)(str.charAt(i) ^ key.charAt(j))); } return sb.toString(); }
75e797fd-67e1-41a8-b40e-0a487bc115b6
5
public static void deleteDir(String path){ File f =new File(path); if(f.exists() && f.isDirectory()) { if(f.listFiles().length == 0) { f.delete(); } else { File delFile[] = f.listFiles(); int i = f.listFiles().length; for(int j=0;j<i;j++) { if(delFile[j].isDirectory()){ deleteDir(delFile[j].getAbsolutePath()); } delFile[j].delete(); } } deleteDir(path); } }
6f91a8e1-7d37-4503-a537-2dde0567a864
1
public void deleteTeacher(int id) { try { PreparedStatement ps = con.prepareStatement( "DELETE FROM teacher WHERE id=?" ); ps.setInt( 1, id ); ps.executeUpdate(); ps.close(); } catch( SQLException e ) { e.printStackTrace(); } }
2e00fcbc-4dde-4a0c-b408-fd410ecd7ac1
5
public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 1){ Transition trans = getDrawer().transitionAtPoint(event.getPoint()); if (trans != null){ if (trans.isSelected){ trans.isSelected = false; selectedTransition = null; } else{ if (selectedTransition != null) selectedTransition.isSelected = false; trans.isSelected = true; selectedTransition = trans; } return; } } Transition trans = getDrawer().transitionAtPoint(event.getPoint()); if (trans == null){ Rectangle bounds; bounds = new Rectangle(0, 0, -1, -1); getView().getDrawer().getAutomaton().selectStatesWithinBounds(bounds); getView().repaint(); return; } creator.editTransition(trans, event.getPoint()); }
8f252a4a-b2c5-47c2-99aa-55b4fa71e6ae
3
public Component getComponentWithCard(Card card) { for(Component comp : this.getComponents()) { if(comp instanceof CardInHand) { if(((CardInHand) comp).getName().toLowerCase().equals(card.getName().toLowerCase())) { return comp; } } } return null; }
c0894517-95f5-4068-8931-0f06798810b2
4
static void resampleProcess(int newR) throws IOException{ /* * Determine the threshold for resampling */ long indexsize = index.size(); int threshold = -1; long c = 0; estiRatio = getEstimateRatio(); measuredRatio = (double)dup/total/estiRatio; resultRecord.println("Total chunks are: " + totalChunkNum + "\nOriginal samplingrate is: " + (double)1/migratePara/newR +"\nCurrent sampling rate is: " + (double)1/newR + "\nEstimated ratio is: " + estiRatio +"\nMeasured rate is " + (double)dup/total + "\nRequired normalized ratio is: " + requiredRatio + "\nCurrent normalized ratio is: " + measuredRatio ); resultRecord.println("\nThe amount of evicted chunks is: " +(double)1/migratePara/newR*totalChunkNum*estiRatio*(requiredRatio - measuredRatio)); System.out.println("Total chunks are: " + totalChunkNum + "\nsamplingrate is: " + (double)1/newR + "\nEstimated ratio is: " + estiRatio + "\nRequired normalized ratio is: " + requiredRatio + "\nCurrent normalized ratio is: " + measuredRatio); System.out.println("The amount of evicted chunks is: " +(double)1/newR*totalChunkNum*estiRatio*(requiredRatio - measuredRatio)); double evict = (double)1/newR*totalChunkNum*estiRatio*(requiredRatio - measuredRatio); while(c<(double)1/newR*totalChunkNum* estiRatio*(requiredRatio - measuredRatio)){ threshold+=1 ; Iterator<Entry<String, long[]>> iter = index.entrySet().iterator(); while(iter.hasNext()){ Entry<String, long[]> entry= iter.next(); long meta[] = new long[M+2]; meta = entry.getValue(); if(meta[0] == threshold){ c++; // System.out.println("Picking the qualified index entries " + c); } } } resultRecord.println("The threshold for resampling is: " + threshold); System.out.println("The threshold for resampling is: " + threshold); resample RdP = new resample(index,M,cache,containerRecord,newR*migratePara,newR,threshold ,chunksize, segsize, bf, bloomfilterRecord,storageFileFolder ,reSampleStorageFolder,hashRecord,evict); RdP.resampleProcess(); RdP.reDedup(); extraDup+=RdP.getExtradup(); dup += extraDup; resultRecord.println("The total data is: "+total+"\nThe extra duplicates are: "+RdP.getExtradup()+ "\nCurrent dup is: " + (double)(dup)+ "\nThe duplication rate is : " + (double)(dup)/total*100 +"%\n" +RdP.getLowhit()+" entries are picked out, " +RdP.getSpaceReclaimed()+ " entries in the index have been removed" +"\nOriginal index size is: "+ indexsize +"\nCurrent index size is; "+ (RdP.getNewIndexSize()+RdP.getIndexSize()-RdP.getSpaceReclaimed())); /*adjust trigger value*/ if((double)dup/total < requiredRatio*getEstimateRatio()){ requiredRatio = (double)dup/total/getEstimateRatio(); } System.out.println("The total data is: "+total+"\nThe extra duplicates are: "+RdP.getExtradup()+ "\nThe duplication rate is : " + (double)(dup)/total*100 +"%\n" + RdP.getLowhit()+" entries are picked out, "+RdP.getSpaceReclaimed() + " entries in the index have been removed\nCurrent index size is; " + (RdP.getNewIndexSize()+RdP.getIndexSize()-RdP.getSpaceReclaimed())); // System.out.println("The current BloomFilter size is: " + bf.size()); }
ee363090-a218-41e5-9e72-cf68f11a4102
5
public Object getAnswers(ClientRequest clientRequest) { Question question = (Question) clientRequest.getObject(); Random random = new Random(); GameDBLogic bLogic = new GameDBLogic(); List<Answer> allAnswers = null; try { allAnswers = bLogic.getAnswers(question); } catch (Exception ex) { return null; } List<Answer> answers = new ArrayList<>(); //adding 3 wrong answers int i = 0; while (i < 3) { int number = random.nextInt(allAnswers.size()); if (!allAnswers.get(number).isCorrect()) { answers.add(allAnswers.get(number)); allAnswers.remove(number); } else { i++; } } //adding correct answer for (Answer answer : allAnswers) { if (answer.isCorrect()) { answers.add(answer); } } //shuffle answers so the correct one won't be last Collections.shuffle(answers); return answers; }
994c25fa-09cd-4bb2-ab3c-303aadf9de7b
3
public boolean Save() { String filename = m_fileTitle.getText(); //Stop saving if no filename is given. if (filename.isEmpty()) { JOptionPane.showMessageDialog(null, "No filename"); return false; } int width; int height; String str_width = m_chartWidth.getText().toString(); String str_height = m_chartHeight.getText().toString(); try { width = Integer.valueOf(str_width); height = Integer.valueOf(str_height); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Width and Height entered not numbers"); return false; } try { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics g = bi.createGraphics(); m_ChartPanel.paint(g); //this == JComponent g.dispose(); ImageIO.write(bi,"png",new File(filename + ".png")); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Save unsuccessful"); return false; } JOptionPane.showMessageDialog(null, "Save successful"); m_Frame.setVisible(false); return true; }
234280fd-82fa-41d7-bd85-e5bf33835d27
8
public void renderScreen() { if (buffer == null) { // create the buffer buffer = createImage(PWIDTH, PHEIGHT); dbg = buffer.getGraphics(); } // Render campus dbg.setColor(Color.LIGHT_GRAY); for (int i=0; i<TILESX; i++) for (int j=0; j<TILESY; j++) { if (tiles[i][j]!=null) dbg.drawImage(tiles[i][j], i*TILE, j*TILE, TILE, TILE, this);// tiles[i][j].paintIcon(this, g, i*TILE, j*TILE); else dbg.fillRect(i*TILE, j*TILE, TILE, TILE); } // Render player dbg.drawImage(player, playerX*TILE, playerY*TILE, TILE, TILE, this); //player.paintIcon(this, g, playerX, playerY); // Render pedestrians try { for (Pedestrian p : pedestrians) { if (p.hasMove()) { int pedX = p.getLocation().x-screenX; int pedY = p.getLocation().y-screenY; dbg.drawImage(p.getImage(), pedX*TILE, pedY*TILE, TILE, TILE, this); } } } catch (Exception e) {} // Arrow angle calculation double a = (playerY+screenY) - destination.y; double b = (playerX+screenX) - destination.x; double c = Math.pow(Math.pow(a,2) + Math.pow(b,2), .5); if (a <= 0) angle = Math.toRadians(180) + Math.asin(b/c); else angle = Math.toRadians(0) - Math.asin(b/c); // Rotate arrow image and draw AffineTransform tx = AffineTransform.getRotateInstance(angle, TILE/2, TILE/2); AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); ((Graphics2D)dbg).drawImage(op.filter(arrow, null),(PWIDTH/2 - TILE), 5, null); // draw arrow // GUI labels dbg.setColor(Color.RED); dbg.setFont(dbg.getFont().deriveFont(14)); dbg.drawString("Day: "+day.getDay(), 25, TILE/2); dbg.drawString("Class: "+day.getNextCourseName(), PWIDTH-130, TILE/2); }
094af0b7-37a3-4462-ab44-8603135c0b8c
9
public static Direction getPlayerDirection(int x, int y) { if (x != 0) { if (x > 0) { if (y > 0) { return Direction.DOWNRIGHT; } else if (y < 0) { return Direction.UPRIGHT; } else { return Direction.RIGHT; } } else { if (y > 0) { return Direction.DOWNLEFT; } else if (y < 0) { return Direction.UPRIGHT; } else { return Direction.LEFT; } } } else if (y != 0 && x == 0) { if (y > 0) { return Direction.DOWN; } else { return Direction.UP; } } else { return Direction.IDLE; } }
f61efd07-2025-4d73-8089-467d89cbf47d
8
public static void main(String[] args) throws Exception { String env = null; if (args != null && args.length > 0) { env = args[0]; } if (! "dev".equals(env)) if (! "prod".equals(env)) { System.out.println("Usage: $0 (dev|prod)\n"); System.exit(1); } // Topology config Config conf = new Config(); // Load parameters and add them to the Config Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml"); conf.putAll(configMap); log.info(JSONValue.toJSONString((conf))); // Set topology loglevel to DEBUG conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug")); // Create Topology builder TopologyBuilder builder = new TopologyBuilder(); // if there are not special reasons, start with parallelism hint of 1 // and multiple tasks. By that, you can scale dynamically later on. int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint"); int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks"); // Create Stream from RabbitMQ messages // bind new queue with name of the topology // to the main plan9 exchange (from properties config) // consuming only CBT-related events by using the rounting key 'cbt.#' String badgeName = DeludedKittenRobbersTopology.class.getSimpleName(); String rabbitQueueName = badgeName; // use topology class name as name for the queue String rabbitExchangeName = JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.rabbitmq.exchange"); String rabbitRoutingKey = JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.rabbitmq.routing_key"); // Get JSON deserialization scheme Scheme rabbitScheme = new SimpleJSONScheme(); // Setup a Declarator to configure exchange/queue/routing key RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey); // Create Configuration for the Spout ConnectionConfig connectionConfig = new ConnectionConfig( (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"), (String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"), (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat")); ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig) .queue(rabbitQueueName) .prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")) .requeueOnFail() .build(); // add global parameters to topology config - the RabbitMQSpout will read them from there conf.putAll(spoutConfig.asMap()); // For production, set the spout pending value to the same value as the RabbitMQ pre-fetch // see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md if ("prod".equals(env)) { conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch")); } // Add RabbitMQ spout to topology builder.setSpout("incoming", new RabbitMQSpout(rabbitScheme, rabbitDeclarator), parallelism_hint) .setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks")); // construct command to invoke the external bolt implementation ArrayList<String> command = new ArrayList(15); // Add main execution program (php, hhvm, zend, ..) and parameters command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params")); // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.) command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main")); command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params")); // Add main route to be invoked and its parameters command.add((String) JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.main")); List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.params"); if (boltParams != null) command.addAll(boltParams); // Log the final command log.info("Command to start bolt for Deluded Kitten Robbers: " + Arrays.toString(command.toArray())); // Add constructed external bolt command to topology using MultilangAdapterTickTupleBolt builder.setBolt("badge", new MultilangAdapterTickTupleBolt( command, (Integer) JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.attack_frequency_secs"), "badge" ), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("incoming"); builder.setBolt("rabbitmq_router", new Plan9RabbitMQRouterBolt( (String) JsonPath.read(conf, "$.deck36_storm.DeludedKittenRobbersBolt.rabbitmq.target_exchange"), "DeludedKittenRobbers" // RabbitMQ routing key ), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("badge"); builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint) .setNumTasks(num_tasks) .shuffleGrouping("rabbitmq_router"); if ("dev".equals(env)) { LocalCluster cluster = new LocalCluster(); cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology()); Thread.sleep(2000000); } if ("prod".equals(env)) { StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology()); } }
aeed67aa-34cb-4448-b0e9-dd2c75da0559
4
private boolean hasEveryIdentityDiscPositionOnlyOneIdentityDisc(Grid grid) { List<IdentityDisc> identityDiscs = getIdentityDiscsOfGrid(grid); for (IdentityDisc idDisc : identityDiscs) { final Position idDiscPos = grid.getElementPosition(idDisc); for (Element e : grid.getElementsOnPosition(idDiscPos)) if (e instanceof IdentityDisc && e != idDisc) return false; } return true; }
27db7179-b1b7-4312-98a9-98de9954f4ec
7
public void pack() { boolean isrunestone = cap.text.equals("Runestone"); Coord max = new Coord(0, 0); for (Widget wdg = child; wdg != null; wdg = wdg.next) { if ((wdg == cbtn) || (wdg == fbtn)) continue; if ((isrunestone) && (wdg instanceof Label)) { Label lbl = (Label) wdg; lbl.settext(GoogleTranslator.translate(lbl.texts)); } Coord br = wdg.c.add(wdg.sz); if (br.x > max.x) max.x = br.x; if (br.y > max.y) max.y = br.y; } ssz = max; checkfold(); placecbtn(); }
b6a150a1-6ec2-4114-b0a3-8330a50ab8d8
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Requests)) { return false; } Requests other = (Requests) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
4dadda7e-ef6c-4297-9472-02c123d475d1
0
public Date getFecha() { //no pongas mierda en mi codigo return fecha; }
f76de2d0-0988-425b-b813-2f95152c7b66
0
public int getHeight() { return height; }
0c166576-2ef2-4680-8b70-dffbe05e5216
3
public Coord getMaxCoord(){ int max = 0; Coord res = new Coord(); for(int i = 0 ; i < taille ; i++){ for(int j = 0 ; j < taille ; j++){ if(getValue(i,j)> max){ max = getValue(i,j) ; res.x = i; res.y = j; } } } return res; }
268d1626-8546-43db-94d3-9b8c6abc8aab
8
public void gameUpdated(GameUpdateType type) { // find our super parent frame -- needed for dialogs Component c = this; while (null != c.getParent()) c = c.getParent(); switch (type) { case ERROR: boardFrame.bp.repaint(); boardPanel.repaint(); controlPanel.play.setEnabled(false); controlPanel.step.setEnabled(false); controlPanel.pause.setEnabled(false); controlPanel.stop.setEnabled(false); controlPanel.begin.setEnabled(true); configPanel.setEnabled(true); JOptionPane.showMessageDialog((Frame) c, errorMessage, "Game Over", JOptionPane.INFORMATION_MESSAGE); boardFrame.bp.repaint(); boardPanel.repaint(); break; case GAMEOVER: if(!is_recursive) { fast = false; controlPanel.play.setEnabled(false); controlPanel.step.setEnabled(false); controlPanel.pause.setEnabled(false); controlPanel.stop.setEnabled(false); controlPanel.begin.setEnabled(true); configPanel.setEnabled(true); String s = "All flights reached destination at time " + (engine.getCurrentRound()) + "; power used=" + engine.getBoard().powerUsed + "; delay=" + engine.getBoard().delay; JOptionPane.showMessageDialog((Frame) c, s, "Game Over", JOptionPane.INFORMATION_MESSAGE); } break; case MOVEPROCESSED: controlPanel.roundText.setText("" + engine.getCurrentRound()); controlPanel.powerText.setText("" + engine.getPower()); controlPanel.delayText.setText("" + engine.getDelay()); boardFrame.round.setText("Round: " + engine.getCurrentRound()); boardFrame.bp.repaint(); boardPanel.repaint(); break; case STARTING: controlPanel.roundText.setText("0"); controlPanel.powerText.setText("0"); controlPanel.delayText.setText("0"); break; case MOUSEMOVED: configPanel.setMouseCoords(BoardPanel.MouseCoords); case REPAINT: boardFrame.bp.repaint(); boardPanel.repaint(); default: // nothing. } }
2d84fed7-ebdb-4e01-a5f9-9f7466843519
8
static long LCA(int p, int q) { int tmp, log, i; // if p is situated on a higher level than q then we swap them if (L[p] < L[q]) { tmp = p; p = q; q = tmp; } // we compute the value of [log(L[p)] for (log = 1; 1 << log <= L[p]; log++) ; // ---- log--; long sum = 0; // we find the ancestor of node p situated on the same level // with q using the values in P for (i = log; i >= 0; i--) if (L[p] - (1 << i) >= L[q]) { sum += D[p][i]; p = P[p][i]; } if (p == q) // [return p; LCA] [return max; MAX] return sum; // SUM // we compute LCA(p, q) using the values in P for (i = log; i >= 0; i--) if (P[p][i] != -1 && P[p][i] != P[q][i]) { sum += D[p][i] + D[q][i]; p = P[p][i]; q = P[q][i]; } sum += D[p][0] + D[q][0]; // [return T[p]; LCA] [return max; MAX] return sum; // SUM }
e4dc7c82-3a95-4e4c-a3f2-e99aed21b10e
1
public static void main(String[] args) { StudentList students = new StudentList(10000); //System.out.println(students); SeparateChainingHashST sc = new SeparateChainingHashST(97); for (int i = 0; i < 10000; i++) { sc.put(students.getList()[i].getLdap(), students.getList()[i].getEcts()); } }
89546642-4014-43a1-884b-17537d569074
9
private boolean r_postlude() { int among_var; int v_1; // repeat, line 75 replab0: while(true) { v_1 = cursor; lab1: do { // (, line 75 // [, line 77 bra = cursor; // substring, line 77 among_var = find_among(a_1, 4); if (among_var == 0) { break lab1; } // ], line 77 ket = cursor; switch(among_var) { case 0: break lab1; case 1: // (, line 78 // <-, line 78 slice_from("i"); break; case 2: // (, line 79 // <-, line 79 slice_from("u"); break; case 3: // (, line 80 // <-, line 80 slice_from("y"); break; case 4: // (, line 81 // next, line 81 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; }
bc09c33a-e2e3-4830-86db-3adb3fe9d414
4
public void or(BitSet set) { if (this == set) return; int wordsInCommon = Math.min(wordsInUse, set.wordsInUse); if (wordsInUse < set.wordsInUse) { ensureCapacity(set.wordsInUse); wordsInUse = set.wordsInUse; } // Perform logical OR on words in common for (int i = 0; i < wordsInCommon; i++) words[i] |= set.words[i]; // Copy any remaining words if (wordsInCommon < set.wordsInUse) System.arraycopy(set.words, wordsInCommon, words, wordsInCommon, wordsInUse - wordsInCommon); // recalculateWordsInUse() is unnecessary checkInvariants(); }
a4a4c7a0-e762-420b-b4e4-ea81cc34e933
3
public void simpan(Mahasiswa k) { try { Connection c = koneksi.connect(); long myId = 0; String sqlIdentifier = "select * from mahasiswa"; PreparedStatement pst = c.prepareStatement(sqlIdentifier); synchronized (this) { ResultSet rs = pst.executeQuery(); if (rs.next()) { myId = rs.getLong(1); } } try { String sql = "insert into mahasiswa (npm, nama, tempatLahir, tanggalLahir, jenisKelamin, alamat) values (?,?,?,?,?,?)"; PreparedStatement ps = c.prepareStatement(sql); ps.setString(1, k.getNpm()); ps.setString(2, k.getNama()); ps.setString(3, k.getTempatLahir()); ps.setString(4, k.getTglLahir()); ps.setString(5, k.getJenisKelamin()); ps.setString(6, k.getAlamat()); ps.executeUpdate(); koneksi.disconnect(c); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } } catch (SQLException ex) { Logger.getLogger(MahasiswaDao.class.getName()).log(Level.SEVERE, null, ex); } }
61235b7a-11b5-4498-b8b3-57042322f61c
2
public void updateSocialVelocity() { for(int i = velocities.length / 2; i < velocities.length; i++){ for(int k = 0; k < velocities[i].length; k++){ int socialBest = neighbourhood.neighbourhoodBest(i); double normDevDist = calculateNormalisedDeviationDistance(k, positions[i][k], personalBest[socialBest]); velocities[i][k] = weight * velocities[i][k] + normDevDist; } } }
8a9e9d57-7ac6-4809-b726-370860744d5a
7
public Msg process(Msg msg) { System.out.println("MSG TYPE:"+msg.get_msg_tp()); Msg ret_msg = new Msg(); if (msg.get_msg_tp() == MESSAGE_TYPE.LOOKUP) { String name = msg.getObj_name(); // suppose the remote object is in the registry if (reg.get(name) != null) { ret_msg.setRemote_ref(reg.get(name)); ret_msg.set_msg_tp(MESSAGE_TYPE.RET_LOOKUP); return ret_msg; } } else if (msg.get_msg_tp() == MESSAGE_TYPE.REBIND) { String host = msg.getIp() + ":" + Integer.toString(msg.getPort()); reg.put(msg.getObj_name(), msg.getRemote_ref()); reg_server.put(msg.getObj_name(), host); System.out.println(" > Rebinding remote object "+msg.getObj_name()); ret_msg.set_msg_tp(MESSAGE_TYPE.RET_REBIND); } else if (msg.get_msg_tp() == MESSAGE_TYPE.BIND) { String host = msg.getIp() + ":" + Integer.toString(msg.getPort()); reg.put(msg.getObj_name(), msg.getRemote_ref()); reg_server.put(msg.getObj_name(), host); System.out.println(" > Binding remote object "+msg.getObj_name()); ret_msg.set_msg_tp(MESSAGE_TYPE.RET_BIND); } else if (msg.get_msg_tp() == MESSAGE_TYPE.LIST) { Vector<String> list = new Vector<String>(); for (String key : reg.keySet()) { list.add(key); } ret_msg.set_list(list); ret_msg.set_msg_tp(MESSAGE_TYPE.RET_BIND); } else if (msg.get_msg_tp() == MESSAGE_TYPE.UNBIND) { String url = msg.getObj_name(); this.reg.remove(url); this.reg_server.remove(url); ret_msg.set_msg_tp(MESSAGE_TYPE.RET_UNBIND); } return ret_msg; }
fc9111b2-cb59-4a2a-9c48-39945a8e2c2c
7
public void run() { mainFrame.lock(true); final String osMinecraftName = profile.getOs().getMinecraftName(); LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "Debug infos :"); LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "OS : " + profile.getOs().getName()); LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "Architecture : " + profile.getArch()); LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "Java version : " + System.getProperty("java.version")); // final File gameDirectory = Main.system.getMinewildDirectory(); final File assetsDirectory = new File(gameDirectory.getPath() + Constants.ASSETS_SUFFIX); final File versionsDirectory = new File(gameDirectory.getPath() + Constants.VERSIONS_SUFFIX); final File librariesDirectory = new File(gameDirectory.getPath() + Constants.LIBS_SUFFIX); final File nativesDir = new File(versionsDirectory.getPath() + Constants.NATIVES_SUFFIX); final File gameFile = new File(versionsDirectory.getPath() + File.separator + profile.getVersion() + File.separator + profile.getVersion() + ".jar"); // //check pswd if(profile.getPassword() != null)//if premium { mainFrame.btnPlaySetText("Vérification du mot de passe ..."); } //check whitelist if(!profile.isWhiteListed() && ConnectionUtils.getServerStatus()) mainFrame.dispFiveSecMessageOnPlayButton("Vous n'êtes pas whitelisté sur Minewild"); LastLoginSaveManager.saveContents(profile.getUsername(), profile.getPassword()!=null); mainFrame.btnPlaySetText("Vérification des fichiers de jeu ..."); //TODO: il faudrait s'assurer que tous les fichiers de jeux soient téléchargées pour pouvoir passer à la suite //boucle qui dl les games files //verifier que la version requise existe (dossier + fichiers) mainFrame.btnPlaySetText("Lancement du jeu" + (profile.isWhiteListed() ? "" : " en solo") + " ..."); final Gson gson = new Gson(); MinecraftVersionJsonObject versionObj = null; try { versionObj = gson.fromJson(Utils.getFileContent(new File(versionsDirectory.getPath() + File.separator + profile.getVersion() + File.separator + profile.getVersion() + ".json"), null), MinecraftVersionJsonObject.class); } catch(JsonSyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } List<String> libraries = new ArrayList<String>(); for(Library lib : versionObj.libraries) { libraries.add(lib.toString()); } LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "Done."); final String pathSeparator = System.getProperty("path.separator"); final List<String> command = new ArrayList<String>(); command.add(Utils.getJavaDir()); command.add("-Djava.library.path=" + nativesDir.getAbsolutePath()); command.add("-cp"); command.add(StringUtils.join(libraries, pathSeparator) + pathSeparator + gameFile.getAbsolutePath()); command.add(versionObj.mainClass); command.addAll(ArgumentsManager.getMinecraftArgs(profile, versionObj.assets, gameDirectory, assetsDirectory)); LogUtils.log(Level.INFO, "Executing command: " + StringUtils.join(command, ' ')); try { final Process process = new ProcessBuilder(command.toArray(new String[command.size()])).directory(gameDirectory).start(); } catch(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } LogUtils.log(Level.INFO, Constants.PLAY_TASK_PREFIX + "Done."); mainFrame.setVisible(false);//TODO waring }
91c8b93c-8a0b-41e8-8938-964bcda18e7b
2
@Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(Color.GREEN); ArrayList frame = synth.outputHistory; //we cannot use frame.size() here because it is (briefly) oversized before //it removed the first element and will give an ArrayIndexOutOfBounds sooner or later int[] xs = new int[Synthesizer.HISTORY_LENGTH], ys = new int[Synthesizer.HISTORY_LENGTH]; //try { for (int i = 0; i < Synthesizer.HISTORY_LENGTH; i++) { xs[i] = i * this.getWidth() / (Synthesizer.HISTORY_LENGTH - 1); //this needs to be tried because the frame is empty until the first keystroke occurs //and will throw an IndexOutOfBounds until then try { ys[i] = (this.getHeight() / 2) - (byte) frame.get(i) * 2; //subtract because y axis starts at top and goes down } catch (Exception e) { ys[i] = 0; } } //} catch (NullPointerException npe) { //System.out.println("bad things"); //} g.drawPolyline(xs, ys, Synthesizer.HISTORY_LENGTH); }
c6d343eb-2634-457b-8788-6b6f4228b76f
4
protected String getUrlForPath(final String path) { if (path.startsWith("http://") || (path.startsWith("https://"))) { return path; } else if (getHostname().startsWith("http://") || (getHostname().startsWith("https://"))) { return getHostname() + path; } else { return "http://" + getHostname() + path; } }
e33fe425-4176-4fa8-a4b0-78cf902f5276
5
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!sender.hasPermission("under50.kick")) { sender.sendMessage(ChatColor.RED + "No access"); return true; } if (args.length < 1) { sender.sendMessage(ChatColor.RED + "Improper usage."); return true; } Player target = Bukkit.getServer().getPlayer(args[0]); if (target == null) { sender.sendMessage(ChatColor.RED + args[0] + " is not online"); return true; } String reason = ""; for (int i=1;i<args.length;i++) { reason += " " + args[i]; } if (reason.equals("")) { reason = " No reason given"; } reason = reason.substring(1); target.kickPlayer(ChatColor.YELLOW + "You've been kicked by " + ChatColor.RED + sender.getName() + "\n" + ChatColor.YELLOW + reason); sender.sendMessage(ChatColor.GREEN + "Kicked " + target.getName()); return true; }
26d166e7-206b-4a03-888e-7c2ea15c8a0a
4
@Override public void onNodeCreate(DataSourceEvent event) throws ResourceException { DataNode node = event.getNode(); DataNode parentNode = event.getParent(); if (node.getName().equals(ResourceDefinition.RESOURCE_TAG)) { String id = node.getAttribute(ResourceDefinition.ID); String parentId = parentNode.getAttribute(ResourceDefinition.ID); ResourceDefinition definition = getElement(id); definition = computeDefinition(definition, node); if (parentNode != null) { if (parentNode.getName() .equals(ResourceDefinition.RESOURCE_TAG)) { ResourceDefinition parentDefinition = getElement(parentId); parentDefinition = computeDefinition(parentDefinition, parentNode); parentDefinition.addChild(definition); } else if (parentNode.getName().equals( ResourceGroup.RESOURCE_TAG)) { ResourceGroup group = manager.getElement(parentId); group = manager.computeGroup(group, parentNode); group.addResourceDefinition(definition); } else { // Create root group DataNode rootNode = new BasicDataNode( ResourceGroup.RESOURCE_TAG); rootNode.addAttribute(ResourceGroup.ID, ResourceGroup.DEFAULT_ID); ResourceGroup root = manager .getElement(ResourceGroup.DEFAULT_ID); root = manager.computeGroup(root, parentNode); root.addResourceDefinition(definition); } } } }
9c145902-9856-4765-a9d0-ee0f03a2cc26
3
private void readTableHeader() throws IOException { long columnCount = nraf.readUnsignedInt(); long l = 0; StringBuilder sb; Set<String> row = new LinkedHashSet<String>(); while(l < columnCount) { sb = new StringBuilder(); long charCount = nraf.readUnsignedInt(); long m = 0; while(m < charCount) { sb.append(nraf.readUTF16()); m++; } row.add(sb.toString()); l++; } // The column count is written twice. The first one at the beginning // of the table header and the second at the end(or at the beginning of the data type table). if(columnCount != nraf.readUnsignedInt()) throw new IOException("Table header mismatch with the column count."); this.columnCount = columnCount; writeCSVRow(row); }
bb20697d-567f-4d94-97ce-c65c7de0be22
6
public int largestRectangleArea(int[] height) { Stack<Integer> stack = new Stack<Integer>(); int top ; int length = height.length; int max = 0; int i=0; while(i < length){ if(stack.empty() || height[stack.peek()] <= height[i]) stack.push(i++); else{ top = stack.pop(); max = Math.max(max, height[top]*(stack.empty() ? i : i-stack.peek()-1)); } } while(!stack.empty()){ top = stack.pop(); max = Math.max(max, height[top]*(stack.empty() ? i : i-stack.peek()-1)); } return max; }
30b86be8-50eb-43f6-8ae1-489bc0222b8c
9
private static AckResponse generateResponse(Request req, String userID, String type, String groupID) { if (req instanceof ReadRequest) { Journal jurre = db.getJournal(req.getID(), userID, groupID, type); if (jurre == null) return new AckResponse(false, "\"access denied\"... ?"); return new AckResponse(true, jurre.toString()); } else if (req instanceof ListRequest) { String journals = "\n"; for (Journal j : db.getMyJournals(userID, groupID, type)) journals += j.getMetaData() + "\n"; return new AckResponse(false, "Retrieved journals:"+journals); } else if (req instanceof DeleteRequest) { return new AckResponse(true, "Attempted delete of: " + req.getID() + " result: " + db.deleteJournal(req.getID(), userID, type)); } else if (req instanceof AddRequest) { AddRequest addRequest = (AddRequest) req; Journal inJourn = addRequest.getJournal(); Journal journ = new Journal(userID, inJourn.getNurse(), inJourn.getPatient(), groupID, inJourn.getContent()); return new AckResponse(true, "Requesting to add from: " + userID + " Containing: \n" + journ + "\n" + "result : " + db.insertJournal(journ, userID, type)); } else if (req instanceof EditRequest) { EditRequest eReq = (EditRequest) req; return new AckResponse(true, "Requesting to edit: " + eReq.getID() + " result: " + db.updateJournal(eReq.getID(), eReq.getContent(), userID, type)); } else if (req instanceof LogRequest) { try { LogDatabase db2 = new LogDatabase(); return new AckResponse(true, "Requesting log: \n" + db2.printLog(groupID)); } catch (Exception e) { return new AckResponse(false, "ClassNotFounde"); } } else { return new AckResponse(false, "Don't know wtf recieved from: " + userID); } }
839cff93-62ce-42c0-8dc0-c17172bdae11
1
private static void shuffle(int[] arr, Random gen) { for (int i = 0 ; i != arr.length ; ++i) { int j = gen.nextInt(arr.length - i) + i; int t = arr[i]; arr[i] = arr[j]; arr[j] = t; } }
a3ef13d1-d2bb-4295-8871-ae1715b46c2e
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(JDNuevaTarea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JDNuevaTarea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JDNuevaTarea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JDNuevaTarea.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JDNuevaTarea dialog = new JDNuevaTarea(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
47c08e15-2273-4776-9284-ab139d478a76
2
@Override protected Object doGet(final String key) { Element element = null; try { element = cache.get(key); } catch (Throwable e) { CacheErrorHandler.handleError(e); } if (element != null) { return element.getObjectValue(); } else { return null; } }
5c55ef95-bc98-4840-b547-5b0e8b0666da
2
private synchronized void doParse(String systemId, String publicId, Reader reader, InputStream stream, String encoding) throws java.lang.Exception { basePublicId = publicId; baseURI = systemId; baseReader = reader; baseInputStream = stream; initializeVariables(); // Set the default entities here. setInternalEntity(intern("amp"), "&#38;"); setInternalEntity(intern("lt"), "&#60;"); setInternalEntity(intern("gt"), "&#62;"); setInternalEntity(intern("apos"), "&#39;"); setInternalEntity(intern("quot"), "&#34;"); if (handler != null) { handler.startDocument(); } pushURL("[document]", basePublicId, baseURI, baseReader, baseInputStream, encoding); parseDocument(); if (handler != null) { handler.endDocument(); } cleanupVariables(); }
ff309ee8-15d1-41f6-afaa-ebbf7dcd7c71
5
@Test public void depthest02opponent5() { for(int i = 0; i < BIG_INT; i++) { int numPlayers = 6; //assume/require > 1, < 7 Player[] playerList = new Player[numPlayers]; ArrayList<Color> factionList = Faction.allFactions(); playerList[0] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[1] = new Player(chooseFaction(factionList), new DepthEstAI(0,2, new StandardEstimator())); playerList[2] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[3] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[4] = new Player(chooseFaction(factionList), new SimpleAI()); playerList[5] = new Player(chooseFaction(factionList), new SimpleAI()); Color check = playerList[1].getFaction(); GameState state = new GameState(playerList, new Board(), gameDeck, gameBag, score); Set<Player> winners = Game.run(state, new StandardSettings()); boolean won = false; for(Player p : winners) { if(p.getFaction().equals(check)) { won = true; wins++; if(winners.size() > 1) { tie++; } } } if(!won) { loss++; } } assertEquals(true, wins/(wins+loss) > .8); }
b8e3e7d7-0e97-4235-94be-eeb68d7fbb17
7
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { int rounds, i, j; int cdata[] = (int[])bf_crypt_ciphertext.clone(); int clen = cdata.length; byte ret[]; if (log_rounds < 4 || log_rounds > 31) throw new IllegalArgumentException ("Bad number of rounds"); rounds = 1 << log_rounds; if (salt.length != BCRYPT_SALT_LEN) throw new IllegalArgumentException ("Bad salt length"); init_key(); ekskey(salt, password); for (i = 0; i < rounds; i++) { key(password); key(salt); } for (i = 0; i < 64; i++) { for (j = 0; j < (clen >> 1); j++) encipher(cdata, j << 1); } ret = new byte[clen * 4]; for (i = 0, j = 0; i < clen; i++) { ret[j++] = (byte)((cdata[i] >> 24) & 0xff); ret[j++] = (byte)((cdata[i] >> 16) & 0xff); ret[j++] = (byte)((cdata[i] >> 8) & 0xff); ret[j++] = (byte)(cdata[i] & 0xff); } return ret; }
1a374ca9-656c-46ac-9fe9-847d7aa3a97e
0
public Timestamp getSumbitTime() { return this.sumbitTime; }
4179c8bc-6d39-437d-a4be-0c22319ec42a
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target==null) return false; if(target.fetchEffect(ID())!=null) { mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> protection from elements.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) elemental protection."):L("^S<S-NAME> @x1 for elemental protection.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for elemental protection, but nothing happens.",prayWord(mob))); // return whether it worked return success; }
ebb4c95c-f65a-4fe0-942f-5efa9454b799
5
public static Car create(String className, Map<String, Object> content) throws Exception { Class<?> inputClass = Class.forName(className); Class<? extends Car> currentCarClass = inputClass.asSubclass(Car.class); Car car = currentCarClass.newInstance(); for (Entry<String, Object> entry : content.entrySet()) { String nameOfmethod = "set" + Character.toString(entry.getKey().charAt(0)) .toUpperCase() + entry.getKey().substring(1); if (entry.getValue() instanceof String) { Method setter = inputClass.getDeclaredMethod(nameOfmethod,String.class); setter.setAccessible(true); setter.invoke(car, entry.getValue()); } else if (entry.getValue() instanceof Data){ Method setter = inputClass.getDeclaredMethod(nameOfmethod,Data.class); setter.setAccessible(true); setter.invoke(car, entry.getValue()); } else { Method setter = inputClass.getDeclaredMethod(nameOfmethod,Integer.class); setter.setAccessible(true); setter.invoke(car, entry.getValue()); } } return car; }
c02908fe-03fa-40ff-a5ac-3187165866c6
1
public boolean addUnit(Unit u) { if (unit == null) { unit = u; //System.out.println("Unit added at: (" + x + ", " + y + ")"); return true; } return false; }
5f3392a7-12b6-46d6-9f34-c81999c55ced
4
public OperationExpression simplify() { if (((PrimitiveOperator) op).isComplexIDOfLeft()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP), left); } if (((PrimitiveOperator) op).isComplexNotOfLeft()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.NOT_OP), left); } if (((PrimitiveOperator) op).isComplexIDOfRight()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.ID_OP), right); } if (((PrimitiveOperator) op).isComplexNotOfRight()) { return new UnaryOpExpression(new PrimitiveOperator(PrimitiveOperator.NOT_OP), right); } return this; //dammy }
fe4c4e59-28ac-4106-9b02-8e6062f26cea
4
public double[] processWindow(double[] window, int start) throws IllegalArgumentException { //number of unique coefficients, and the rest are symmetrically redundant int fftSize = (windowSize / 2) + 1; //check start if(start < 0) throw new IllegalArgumentException("start must be a positve value"); //check window size if(window == null || window.length - start < windowSize) throw new IllegalArgumentException("the given data array must not be a null value and must contain data for one window"); //just copy to buffer for (int j = 0; j < windowSize; j++) buffer[j] = window[j + start]; //perform power fft normalizedPowerFFT.transform(buffer, null); //use all coefficient up to the nequist frequency (ceil((fftSize+1)/2)) Matrix x = new Matrix(buffer, windowSize); x = x.getMatrix(0, fftSize-1, 0, 0); //fftSize-1 is the index of the nyquist frequency //apply mel filter banks x = melFilterBanks.times(x); //to db double log10 = 10 * (1 / Math.log(10)); // log for base 10 and scale by factor 10 x.thrunkAtLowerBoundary(1); x.logEquals(); x.timesEquals(log10); //compute DCT x = dctMatrix.times(x); return x.getColumnPackedCopy(); }
e7259a86-e2c2-4b17-b9f9-7a5da426b800
5
public static int findLIS(int size) { int[] dp = new int[size]; Arrays.fill(dp, 1); int ans = 1; for (int i = 0; i < dp.length; i++) for (int j = 0; j < i; j++) if (match(j, i) && dp[i] + 1 > dp[j]) dp[i] = Math.max(dp[i], dp[j] + 1); for (int i = 0; i < dp.length; i++) ans = Math.max(ans, dp[i]); return ans; }
85b0fe6f-3797-4691-a3d1-16e0d904a8bf
3
@SuppressWarnings("unchecked") @EventHandler public void onPlayerDeath(EntityDeathEvent e){ if(e instanceof PlayerDeathEvent){ if(this.plugin.getConfig().getBoolean("show_death") && !this.privatePlayers.contains(e.getEntity()) ){ JSONObject json = new JSONObject(); json.put("message",((PlayerDeathEvent) e).getDeathMessage()); json.put("time",new Date().toString()); json.put("player","Humiliator"); json.put("source", "in"); this.plugin.getFileMan().write(this.plugin.chatFile(), json); } } }
0ae24ae3-a685-401a-ba94-5ba7fa019c37
6
private boolean registraUsuario(HttpServletRequest request, HttpServletResponse response) throws IOException { ConexionBD bd = new ConexionBD(); String categoria = request.getParameter("categoria"); String nombre = request.getParameter("nombre"); String login = request.getParameter("login"); String correo = request.getParameter("correo"); String contraseniaUno = request.getParameter("contraseniaUno"); String contraseniaDos = request.getParameter("contraseniaDos"); Boolean validacion = true; validacion = validacion && Validacion.valida_nombre(nombre); validacion = validacion && Validacion.valida_login(login); validacion = validacion && Validacion.valida_mail(correo); validacion = validacion && Validacion.valida_contrasenia(contraseniaUno, contraseniaDos); if (validacion && bd.insertaUsuario(login, contraseniaUno, nombre, categoria)) { return true; } else { return false; } }
ff2a206e-ff4d-4541-8141-26d22d27ab2c
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ /* 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()) { System.out.println(info); if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Home().setVisible(true); } }); }