method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
f3044239-2037-41e8-ae74-3bea9e6a47ae
4
@Override public int hashCode() { int result = firstName != null ? firstName.hashCode() : 0; result = 31 * result + (secondName != null ? secondName.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (phone != null ? phone.hashCode() : 0); return result; }
683787ce-458f-41b4-92c3-7d2bc706a486
8
public List<Product> viewProduct(int offSet, int noOfRecords, String category){ List<Product> productList = new ArrayList<Product>(); Product product = null; connMyDB = new ConnectDatabase(); try { connMyDB.connect(); productDataset = connMyDB.query(getQuery(category, offSet, noOfRecords)); while(productDataset.next()){ String code = productDataset.getString("productID"); String categories = productDataset.getString("category"); String description = productDataset.getString("decription"); String price = productDataset.getString("price"); product = new Product(code, categories ,description, price); productList.add(product); } productDataset.close(); productDataset = connMyDB.query("SELECT FOUND_ROWS()"); if(productDataset.next()) setResultRecord(productDataset.getInt(1)); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(connMyDB != null) connMyDB.close(); } catch (SQLException e) { e.printStackTrace(); } } return productList; }
11abb5ca-0497-44ee-a814-431426e1e0e7
7
protected LoginResult loginEmailPassword(final LoginSessionImpl loginObj, final Session session) throws IOException { final String input=loginObj.lastInput.toUpperCase().trim(); if(input.startsWith("Y")) { String password=loginObj.player.password; if(CMProps.getBoolVar(CMProps.Bool.HASHPASSWORDS)) { if(loginObj.acct!=null) { password=CMLib.encoder().generateRandomPassword(); loginObj.acct.setPassword(password); loginObj.player.password=loginObj.acct.getPasswordStr(); CMLib.database().DBUpdateAccount(loginObj.acct); } else { final MOB playerM=CMLib.players().getLoadPlayer(loginObj.player.name); if((playerM!=null)&&(playerM.playerStats()!=null)) { password=CMLib.encoder().generateRandomPassword(); playerM.playerStats().setPassword(password); loginObj.player.password=playerM.playerStats().getPasswordStr(); CMLib.database().DBUpdatePassword(loginObj.player.name, loginObj.player.password); } } } CMLib.smtp().emailOrJournal(CMProps.getVar(CMProps.Str.SMTPSERVERNAME), loginObj.player.name, "noreply@"+CMProps.getVar(CMProps.Str.MUDDOMAIN).toLowerCase(), loginObj.player.name, "Password for "+loginObj.player.name, "Your password for "+loginObj.player.name+" at "+CMProps.getVar(CMProps.Str.MUDDOMAIN)+" is: '"+password+"'."); session.stopSession(false,false,false); loginObj.reset=true; loginObj.state=LoginState.LOGIN_START; return LoginResult.NO_LOGIN; } else if((input.length()>0)&&(!input.startsWith("N"))) { session.promptPrint(L(RECONFIRMSTR)); return LoginResult.INPUT_REQUIRED; } loginObj.state=LoginState.LOGIN_START; return null; }
52b47bc8-029d-40ac-84a2-f741c756ba29
8
private int optional (int optional) throws KryoException { int remaining = limit - position; if (remaining >= optional) return optional; optional = Math.min(optional, capacity); int count; // Try to fill the buffer. count = fill(buffer, limit, capacity - limit); if (count == -1) return remaining == 0 ? -1 : Math.min(remaining, optional); remaining += count; if (remaining >= optional) { limit += count; return optional; } // Was not enough, compact and try again. System.arraycopy(buffer, position, buffer, 0, remaining); total += position; position = 0; while (true) { count = fill(buffer, remaining, capacity - remaining); if (count == -1) break; remaining += count; if (remaining >= optional) break; // Enough has been read. } limit = remaining; return remaining == 0 ? -1 : Math.min(remaining, optional); }
899db1ef-aa1d-4b41-8a86-3fe00cc2dbed
7
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
c169b246-8bf9-4e6e-aa07-d94e21a112ed
8
public static NumberWrapper divideComputation(NumberWrapper x, NumberWrapper y) { try { { double floatresult = Stella.NULL_FLOAT; { Surrogate testValue000 = Stella_Object.safePrimaryType(x); if (Surrogate.subtypeOfIntegerP(testValue000)) { { IntegerWrapper x000 = ((IntegerWrapper)(x)); { Surrogate testValue001 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue001)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); if (((x000.wrapperValue) % (y000.wrapperValue)) == 0) { return (IntegerWrapper.wrapInteger(((x000.wrapperValue) / (y000.wrapperValue)))); } else { floatresult = ((double)(x000.wrapperValue)) / ((double)(y000.wrapperValue)); } } } else if (Surrogate.subtypeOfFloatP(testValue001)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue / y000.wrapperValue; } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue001 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } } else if (Surrogate.subtypeOfFloatP(testValue000)) { { FloatWrapper x000 = ((FloatWrapper)(x)); { Surrogate testValue002 = Stella_Object.safePrimaryType(y); if (Surrogate.subtypeOfIntegerP(testValue002)) { { IntegerWrapper y000 = ((IntegerWrapper)(y)); floatresult = x000.wrapperValue / y000.wrapperValue; } } else if (Surrogate.subtypeOfFloatP(testValue002)) { { FloatWrapper y000 = ((FloatWrapper)(y)); floatresult = x000.wrapperValue / y000.wrapperValue; } } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue002 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } } } else { { OutputStringStream stream002 = OutputStringStream.newOutputStringStream(); stream002.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream002.theStringReader()).fillInStackTrace())); } } } return (FloatWrapper.wrapFloat(floatresult)); } } catch (java.lang.Exception e000) { return (null); } }
e660e0b6-ae27-4c0f-83ce-d535967bd979
5
public CheckResultMessage check24(int day) { int r1 = get(2, 5); int c1 = get(3, 5); int r2 = get(39, 5); int c2 = get(40, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r1 + 1 + day, c1 + 9, 0).subtract( getValue(r1 + 1 + day, c1 + 10, 0) .add(getValue(r1 + 1 + day, c1 + 11, 0)) .add(getValue(r1 + 1 + day, c1 + 12, 0)) .add(getValue(r1 + 1 + day, c1 + 13, 0))); if (0 != getValue(r2 + 10, c2 + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">本期支付机构已减少客户资金余额,备付金银行未减少备付金银行余额 :" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); b = getValue1(r1 + 1 + day, c1 + 9, 0).subtract( getValue1(r1 + 1 + day, c1 + 10, 0) .add(getValue1(r1 + 1 + day, c1 + 11, 0)) .add(getValue1(r1 + 1 + day, c1 + 12, 0)) .add(getValue1(r1 + 1 + day, c1 + 13, 0))); if (0 != getValue1(r2 + 10, c2 + day, 10).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">本期支付机构已减少客户资金余额,备付金银行未减少备付金银行余额 :" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">本期支付机构已减少客户资金余额,备付金银行未减少备付金银行余额 :" + day + "日正确"); }
3e141a46-2818-424b-b9e7-cc98eaee61dd
8
@Test public void testPlayersQueriedInOrder() { // This tests that the players are surveyed in order to see if they hold the cards. ArrayList<Player> playersTest = board.getPlayers(); ArrayList<Card> hold3 = playersTest.get(3).getCards(); ArrayList<Card> newHand = new ArrayList<Card>(); newHand.add(new Card(type.WEAPON, "MiniGun")); playersTest.get(3).setCards(newHand); Player accuser = playersTest.get(0); String room = "Some Place"; String person = "A Person"; String weapon = "Minigun"; int playerCounter = 0; String info = null; ArrayList<String> dissapprovals = new ArrayList<String>(); Boolean cardShown = false; for (int i = 0; i < playersTest.size(); i++ ) { if (cardShown) break; if (playersTest.get(i).getName().equalsIgnoreCase(accuser.getName())) continue; else { for (int j = 0; j < playersTest.get(i).getCards().size(); j++) { if (playersTest.get(i).getCards().get(j).getContent().equalsIgnoreCase(room) || playersTest.get(i).getCards().get(j).getContent().equalsIgnoreCase(person) || playersTest.get(i).getCards().get(j).getContent().equalsIgnoreCase(weapon)) { dissapprovals.add(playersTest.get(i).revealCard(playersTest.get(i).getCards().get(j)).getContent()); cardShown = true; } } } playerCounter++; } if (dissapprovals.size() > 0) { Random generator = new Random(); info = dissapprovals.get(generator.nextInt(dissapprovals.size())); } Assert.assertTrue(info.equalsIgnoreCase("MiniGun")); Assert.assertTrue(playerCounter == 3); board.getPlayers().get(3).setCards(hold3); }
6d20caea-8421-4f21-bdc6-ca21cc143c51
2
public FlowBlock getNextFlowBlock(StructuredBlock subBlock) { if (subBlock == subBlocks[0]) { if (subBlocks[1].isEmpty()) return subBlocks[1].getNextFlowBlock(); else return null; } return getNextFlowBlock(); }
80947ee9-ce56-4956-8af5-0f384c4427f8
4
public boolean canMove(int oldX, int oldY, int newX, int newY, boolean isNewSpotEmpty) { int deltaX; int deltaY; deltaX = Math.abs(newX-oldX); deltaY = Math.abs(newY-oldY); if (deltaX == 2 && deltaY == 1){ return true; } else if (deltaX == 1 && deltaY == 2) { return true; } return false; }
6588cbea-c8a9-4865-9824-b6fac1eb40d9
3
private int read() throws IOException{ if(re){ re = false; }else if(un){ current = unBuffer[uni--]; if(uni==-1){ uni = 0; un = false; } }else{ current = input.read(); } return current; }
72390326-57b3-4b83-8f38-9e51cd01e40c
7
public static void main(String[] args) { // Create Display try { Display.setDisplayMode (new DisplayMode(800, 600)); Display.create (); Display.setTitle("Hello!!"); } catch (LWJGLException ex) { Logger.getLogger(LWJGL_Example1.class.getName()) .log(Level.SEVERE, null, ex); } glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, 800, 600, 0, 1, -1); glMatrixMode(GL_MODELVIEW); int p1x = 150, p1y = 150; int p2x = 200, p2y = 150; int p3x = 200, p3y = 200; int p4x = 150, p4y = 200; // Game Loop while (!Display.isCloseRequested()) { // Borra la pantalla glClear(GL_COLOR_BUFFER_BIT); if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) { Display.destroy(); System.exit(0); } else if (Keyboard.isKeyDown(Keyboard.KEY_UP)) { p1y += -20; p2y += -20; p3y += -20; p4y += -20; } else if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { p1y += 20; p2y += 20; p3y += 20; p4y += 20; } else if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { p1x += -20; p2x += -20; p3x += -20; p4x += -20; } else if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { p1x += 20; p2x += 20; p3x += 20; p4x += 20; } /* * Render */ glColor3f(0f, 0f, 1f); // Line glBegin(GL_QUADS); glVertex2i(p1x, p1y); // upper-left glVertex2i(p2x, p2y); // upper-right glVertex2i(p3x, p3y); // bottom-rigth glVertex2i(p4x, p4y); // bottom-left glEnd(); Display.update(); Display.sync(60); } Display.destroy(); }
213c4aee-4dfb-4d84-abf0-cd3a2f14fddb
7
private String getPartOfDate(Integer hourOfDay){ if(hourOfDay >= 7 && hourOfDay <= 12){ return "morning"; } else if(hourOfDay > 12 && hourOfDay <= 18){ return "afternoon"; } else if(hourOfDay > 18 && hourOfDay <= 23 || hourOfDay == 0){ return "evening"; } else { return "night"; } }
05fac63d-bd27-4bba-a52a-59c54e3c03e8
7
public String CaptureStillImage(String UrlParameter) { if (Parent.GetNoCameraParameter()) { return ""; } String ReturnValue = ""; try { String param_url = ""; URLConnection conn = null; BufferedReader data = null; String line; String result; StringBuffer buf = new StringBuffer(); URL ParamURL = null; param_url = "http://" + this.IP + "/ElphelVision/savestill.php?" + UrlParameter; try { ParamURL = new URL(param_url); } catch (MalformedURLException e) { System.out.println("Bad URL: " + param_url); } conn = ParamURL.openConnection(); conn.connect(); data = new BufferedReader(new InputStreamReader(conn.getInputStream())); buf.delete(0, buf.length()); while ((line = data.readLine()) != null) { buf.append(line + "\n"); } result = buf.toString(); data.close(); // try to extract data from XML structure /* <SaveStill> <path>/var/hdd/stills/still_00034.jpg</path> <size>50390</size> <save_duration>0.343< </save_duration> </SaveStill> * */ try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(result.getBytes())); doc.getDocumentElement().normalize(); NodeList nodeLst = doc.getElementsByTagName("SaveStill"); for (int s = 0; s < nodeLst.getLength(); s++) { Node fstNode = nodeLst.item(s); if (fstNode.getNodeType() == Node.ELEMENT_NODE) { Element fstElmnt = (Element) fstNode; NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("path"); Element fstNmElmnt = (Element) fstNmElmntLst.item(0); NodeList fstNm = fstNmElmnt.getChildNodes(); String response = ((Node) fstNm.item(0)).getNodeValue(); ReturnValue = "saved " + response; } } } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { Parent.WriteErrortoConsole("CaptureStillImage IO Error: " + e.getMessage()); } return ReturnValue; }
9bfa6fe0-ffbb-4e94-964d-fcdc14e17b5c
7
public int sortHardwareAlternatives() { int maxDepth = 1; for (HardwareSet hardwareSet : hardwareSets) { maxDepth = hardwareSet.getCpuAlternatives().size() > maxDepth ? hardwareSet.getCpuAlternatives().size() : maxDepth; maxDepth = hardwareSet.getHddAlternatives().size() > maxDepth ? hardwareSet.getHddAlternatives().size() : maxDepth; maxDepth = hardwareSet.getMemoryAlternatives().size() > maxDepth ? hardwareSet.getMemoryAlternatives().size() : maxDepth; maxDepth = hardwareSet.getNetworkAlternatives().size() > maxDepth ? hardwareSet.getNetworkAlternatives().size() : maxDepth; maxDepth = hardwareSet.getPlatformAlternatives().size() > maxDepth ? hardwareSet.getPlatformAlternatives().size() : maxDepth; maxDepth = hardwareSet.getOtherAlternatives().size() > maxDepth ? hardwareSet.getOtherAlternatives().size() : maxDepth; hardwareSet.setCpuAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getCpuAlternatives())); hardwareSet.setHddAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getHddAlternatives())); hardwareSet.setMemoryAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getMemoryAlternatives())); hardwareSet.setNetworkAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getNetworkAlternatives())); hardwareSet.setPlatformAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getPlatformAlternatives())); hardwareSet.setOtherAlternatives(Utils.sortHardwareAlternatives(hardwareSet.getOtherAlternatives())); } return maxDepth; }
9c9861a9-f682-419e-9e0f-3ec27312e1a2
8
public void paint(Graphics2D g2) { if ( nd_gc.powered && nd_gc.mode_map ) { // only in map modes, not in PLAN, APP CTR, VOR CTR //float current_altitude = this.aircraft.indicated_altitude(); float current_altitude = this.aircraft.altitude_ind(); float target_altitude = this.avionics.autopilot_altitude(); //float vertical_velocity = this.aircraft.indicated_vv(); float vertical_velocity = this.aircraft.vvi(); float groundspeed = this.aircraft.ground_speed(); // dont't bother if we are almost there, or vv is too small if ( ( Math.abs(target_altitude - current_altitude) > 100.0f ) && ( Math.abs(vertical_velocity) > 100.0f ) ) { float distance = ( target_altitude - current_altitude ) / vertical_velocity / 60.0f * groundspeed; if ( ( distance > 0.0f ) && ( distance < nd_gc.max_range ) ) { // OK, we are climbing or descending as intended, and our distance is within the map range float arc_radius = distance * nd_gc.pixels_per_nm; // keep the width +/- constant float arc = ARC * nd_gc.max_range / distance; if ( nd_gc.map_zoomin ) arc /= 100.0f; // but never more than 45 degs if ( arc > 45.0f ) arc = 45.0f; g2.setColor(nd_gc.altitude_arc_color); // yellowgreen or lime g2.draw(new Arc2D.Float( (float)nd_gc.map_center_x - arc_radius, (float)nd_gc.map_center_y - arc_radius, arc_radius * 2.0f, arc_radius * 2.0f, 90.0f - arc, 2.0f * arc, Arc2D.OPEN)); } } } }
ff38acb3-01cc-49a7-8d8d-c0d97d02c472
3
@Override public void onEnable() { if (!this.loaded) { this.getLogger().log(Level.SEVERE, "Disabling plugin; Dependencies not met during plugin load"); this.setEnabled(false); return; } this.reloadConfig(); Main.courier = ConfigurationCourier.Factory.create(this).setBase(this.loadConfig("language.yml")).setFormatCode("format-code").build(); final ConfigurationSection switches = this.getConfig().getConfigurationSection("switches"); final List<MessageSwitch> headers = this.parseSwitches(switches, "headers"); final List<MessageSwitch> arguments = this.parseSwitches(switches, "arguments"); Long grace = this.getConfig().getLong("declaration-grace", -1); if (grace != -1) grace = TimeUnit.SECONDS.toMillis(grace); Date worldStart; try { worldStart = Main.DATE_FORMAT.parse(this.getConfig().getString("world-start")); } catch (final ParseException e) { this.getLogger().log(Level.WARNING, "Unable to parse world-start: {0}; {1}", new Object[] { this.getConfig().getString("world-start"), e }); worldStart = new Date(); } final RecordKeeper records = new RecordKeeper(this); final Doorman doorman = new Doorman(this, records, grace, headers, arguments, worldStart); this.getLogger().log(Level.CONFIG, "History: {0}; Grace: {1}; Headers: {2}; Arguments: {3}; worldStart: {4}", new Object[] { records.getHistory().size(), grace, headers.size(), arguments.size(), worldStart }); this.getCommand("doorman:history").setExecutor(new History(records)); this.getCommand("doorman:show").setExecutor(new Show(doorman, records)); this.getCommand("doorman:add").setExecutor(new Add(doorman, records)); this.getCommand("doorman:edit").setExecutor(new Edit(doorman, records)); this.getCommand("doorman:reload").setExecutor(new Reload(this)); }
8a8c3936-6557-447b-bf5c-96863b9a7221
1
public void atualizar(AreaConhecimento areaconhecimento) throws Exception { String sql = "UPDATE areaconhecimento SET nome = ?, ciencia = ?, areaAvaliacao = ? WHERE id = ?"; try { PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql); stmt.setString(1, areaconhecimento.getNome()); stmt.setString(2, areaconhecimento.getCiencia()); stmt.setString(3, areaconhecimento.getAreaAvaliacao()); stmt.setLong(4, areaconhecimento.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw e; } }
a346ce99-854a-4130-b83a-a86206c9af8e
0
@Test public void testIncrementWins() { assertNotNull(_underTest); int x = _underTest.getNumberOfWins(); // current count of wins, expected // to be 0 _underTest.incrementWins(); assertEquals(x + 1, _underTest.getNumberOfWins()); }
6ed6e7f5-f0fc-4d2a-97cf-055d9b95a8db
5
private void tarkistaJaToimi(int miinojaInteger, int kentanKokoInteger) { if (miinojaInteger < kentanKokoInteger*kentanKokoInteger){ String profiiliNimiString = this.profiiliNimi.getText(); if (profiiliNimiString.length()<11 && profiiliNimiString.length() >0 && !this.nakyma.getPeliProfiilit().keySet().contains(profiiliNimiString) && !profiiliNimiString.contains(" ")){ luoProfiiliJaPalaaPaavalikkoon(profiiliNimiString, kentanKokoInteger, miinojaInteger); } else { viestikentta.setText("Profiilinimi ei kelpaa: on jo käytössä tai väärän pituinen."); } } else { viestikentta.setText("Liikaa miinoja valitussa kentän koossa, valitse toinen kombinaatio!"); } }
9aa81f74-71fa-4131-839e-59fc2921d99b
3
@Override public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!contains(o)) { return false; } } return true; }
395a3ba6-1a0a-49cc-a58f-33408a494795
5
public void archiveQueueFailures(int time) throws VehicleException, SimulationException { int maxTime = Constants.MAXIMUM_QUEUE_TIME; for(int i =0; i < queue.size(); i++){ int arrivalTime = queue.get(i).getArrivalTime(); if(!(queue.get(i).isQueued()) || time > Constants.CLOSING_TIME || time < 0){ throw new VehicleException("Vehicle not in correct state or timing constraints violated"); } arrivalTime = queue.get(i).getArrivalTime(); // if vehicle stayed for too long send to archive if ((arrivalTime + maxTime) < time) { numDissatisfied++; status += setVehicleMsg(queue.get(i), "Q", "A"); past.add(queue.get(i)); exitQueue(queue.get(i), time); i--; } } }
fc115e5b-65ca-41bc-89c2-ecca450d0e1a
8
@Override public void startElement (String uri, String localName, String qName, Attributes attributes) { logger.info ("startElement, qName = " + qName); if ("events".equals (qName)) { startEventsElement (attributes); } else if ("event".equals (qName)) { startEventElement (attributes); } else if ("comment".equals (qName)) { startCommentElement (attributes); } else if ("body".equals (qName)) { startBodyElement (attributes); } else if ("subject".equals (qName)) { startSubjectElement (attributes); } else if ("date".equals (qName)) { startDateElement (attributes); } else if ("props".equals (qName)) { startPropsElement (attributes); } else if ("prop".equals (qName)) { startPropElement (attributes); } }
8c87b864-268b-4d7f-be8b-a553682537a8
9
public void run(String arg) { // 1 - Obtain the currently active image if necessary: ImagePlus imp = IJ.getImage(); if (null == imp) return; int stackSize = imp.getStackSize(); if (imp.getBitDepth()!=8) { IJ.showMessage("Error", "Only 8-bit images are supported"); return; } ImageStatistics stats = imp.getStatistics(); if (stats.histogram[0] + stats.histogram[255] != stats.pixelCount){ IJ.error("8-bit binary image (0 and 255) required."); return; } // 2 - Ask for parameters: boolean whiteParticles =Prefs.blackBackground, killTop = true, killRight = true, killBottom, killLeft = true, connect4 = false, doIstack = false; GenericDialog gd = new GenericDialog("Binary Kill Borders"); gd.addMessage("Binary Kill Borders v 1.1"); gd.addMessage("Delete particles touching:"); gd.addCheckbox("Top border", true); gd.addCheckbox("Right border", true); gd.addCheckbox("Bottom border", true); gd.addCheckbox("Left border", true); gd.addCheckbox("White particles on black background", whiteParticles); gd.addCheckbox("4 connected", connect4); if (stackSize>1) gd.addCheckbox("Stack",false); gd.showDialog(); if (gd.wasCanceled()) return ; // 3 - Retrieve parameters from the dialog killTop = gd.getNextBoolean(); killRight = gd.getNextBoolean(); killBottom = gd.getNextBoolean(); killLeft = gd.getNextBoolean(); whiteParticles = gd.getNextBoolean(); connect4 = gd.getNextBoolean(); if (stackSize>1) doIstack = gd.getNextBoolean (); // 4 - Execute! if (stackSize>1 && doIstack){ for (int j=1; j<=stackSize; j++){ imp.setSlice(j); Object[] result = exec(imp, killTop, killRight, killBottom, killLeft, whiteParticles, connect4); } imp.setSlice(1); } else { Object[] result = exec(imp, killTop, killRight, killBottom, killLeft, whiteParticles, connect4); } // 5 - If all went well, show the image: imp.updateAndDraw(); }
57a326b6-c09f-4780-95f9-ac0e465898d8
8
public static Texture getDudeImage(int dir){ Image dude = null; if(dir == 0){ dude = textures.getSubImage(0, 0, 25, 49); }else if(dir == 1){ //dude = textures.getSubImage(0, 25, 25, 49); }else if(dir == 2){ }else if(dir == 3){ }else if(dir == 4){ }else if(dir == 5){ }else if(dir == 6){ }else if(dir == 7){ } return dude.getTexture(); }
2c61d05d-9e6d-447d-8a84-48f748604e7b
9
private static final boolean isClassnamePart(char c) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return true; switch (c) { case '.': case '$': case '_': return true; default: return false; } }
29bf7a9c-62d1-4e98-8b86-16aba6086c81
7
@Override public ReturnStruct parse(String[] lines) { int i = 0; int c = 1; ArrayList<String> code = new ArrayList<String>(); while (i < lines.length) { String line = Parser.clean(lines[i]); if (line.startsWith("if ") || line.startsWith("for ") || line.startsWith("while ") || line.startsWith("function ")) { c++; } else if (line.equals("end")) { c--; } if (c == 0) { code_ = code.toArray(new String[code.size()]); return new ReturnStruct(this, i + 1); } code.add(line); i++; } return new ReturnStruct(this, i + 1); }
0e0da287-64be-42ef-8ee4-9e3a237d7113
4
public static void main(String[] args) { Scanner entrada = new Scanner(System.in); int opcao; int valor; Personagem personagem = new Personagem(); Personagem sistema = new Personagem(); do{ System.out.println("************"); System.out.println("*** MENU ***"); System.out.println("************\n"); System.out.println("1 - Criar personagem"); System.out.println("2 - Listar ja Criados"); System.out.println("3 - Atacar"); System.out.print("Opcao => "); opcao = entrada.nextInt(); switch (opcao){ case 1: personagem.addProtagonista(personagem, opcao); sistema.addSistema(sistema, personagem); System.out.println("\n\nAdicionar:\n"); System.out.println("1) Protagonista\n"); System.out.println("Jogador:"); System.out.println("Nome: " + personagem.getNome()); System.out.println("Quantidade de vida:" + personagem.getQuantidadeVida()); System.out.println("Taxa de Ataque: " + personagem.getTaxaAtaque()); System.out.println("Taxa de Resistencia: " + personagem.getTaxaResistencia()); System.out.println("\nSistema:"); System.out.println("Nome: " + sistema.getNome()); System.out.println("Quantidade de vida:" + sistema.getQuantidadeVida()); System.out.println("Taxa de Ataque: " + sistema.getTaxaAtaque()); System.out.println("Taxa de Resistencia: " + sistema.getTaxaResistencia()); break; case 2: System.out.println("Jogador:"); System.out.println("Nome: " + personagem.getNome()); System.out.println("Quantidade de vida:" + personagem.getQuantidadeVida()); System.out.println("Taxa de Ataque: " + personagem.getTaxaAtaque()); System.out.println("Taxa de Resistencia: " + personagem.getTaxaResistencia()); System.out.println("\nSistema:"); System.out.println("Nome: " + sistema.getNome()); System.out.println("Quantidade de vida:" + sistema.getQuantidadeVida()); System.out.println("Taxa de Ataque: " + sistema.getTaxaAtaque()); System.out.println("Taxa de Resistencia: " + sistema.getTaxaResistencia()); break; case 3: personagem.atacar(sistema,personagem); System.out.println("Vida do adversario" + sistema.getQuantidadeVida()); break; default: System.out.println("Valor Invalido"); } System.out.println("Deseja de nv ? <1> SIM <2> NAO"); valor = entrada.nextInt(); } while (valor == 1); }
0491a816-2950-4b50-a096-29f4db46e309
9
public String dumpCircuit() { int i; int f = (showCurrent) ? 1 : 0; f |= (smallGrid) ? 2 : 0; f |= (showVoltage) ? 0 : 4; f |= (showPowerDissipation) ? 8 : 0; f |= (showValues) ? 0 : 16; // 32 = linear scale in afilter String dump = "$ " + f + " " + timeStep + " " + getIterCount() + " " + currentBarValue + " " + voltageRange + " " + powerBarValue + "\n"; for (i = 0; i != elmList.size(); i++) { dump += getElm(i).dump() + "\n"; } for (i = 0; i != scopeCount; i++) { String d = scopes[i].dump(); if (d != null) { dump += d + "\n"; } } if (hintType != -1) { dump += "h " + hintType + " " + hintItem1 + " " + hintItem2 + "\n"; } return dump; }
1aaa54b5-81e3-4aed-9de1-70bee93aca44
3
public void actionPerformed(ActionEvent ev) { try { PalavraChave objt = classeView(); if (obj == null) { long x = new PalavraChaveDAO().inserir(objt); objt.setId(x); JOptionPane.showMessageDialog(null, "Os dados foram inseridos com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE); if (tabela != null) tabela.adc(objt); else autocp.adicionar(objt); } else { new PalavraChaveDAO().atualizar(objt); JOptionPane.showMessageDialog(null, "Os dados foram atualizados com sucesso", "Sucesso", JOptionPane.INFORMATION_MESSAGE); tabela.edt(objt); } view.dispose(); } catch (Exception e) { JOptionPane .showMessageDialog( null, "Verifique se os campos estão preenchidos corretamente ou se estão repetidos", "Alerta", JOptionPane.WARNING_MESSAGE); } }
9ef6355d-5197-4757-935a-be1a3217f5f9
9
public void removeDraggableComponent(DraggableComponent component) { if (component != null && draggableComponentList.contains(component)) { //component.abortDrag(); int index = layoutOrderList.indexOf(component.getComponent()); component.removeListener(draggableComponentListener); if (component == topComponent) topComponent = null; if (layoutOrderList.size() > 1 && selectedComponent != null) { if (selectedComponent == component) { if (autoSelect) { int selectIndex = findSelectableComponentIndex(index); if (selectIndex > -1) selectDraggableComponent(findDraggableComponent((Component) layoutOrderList.get(selectIndex))); else selectedComponent = null; } else { selectDraggableComponent(null); } } } else { if (selectedComponent != null) { DraggableComponent oldSelected = selectedComponent; selectedComponent = null; fireSelectedEvent(selectedComponent, oldSelected); } } draggableComponentList.remove(component); layoutOrderList.remove(component.getComponent()); componentBox.remove(component.getComponent()); componentBox.revalidate(); //componentBox.validate(); component.setLayoutOrderList(null); sortComponentList(!descendingSortOrder); updateScrollButtons(); fireRemovedEvent(component); } }
9f8ecb58-b8a9-4603-8c1e-9ec5ef214212
8
public static void needHelp(CommandSender sender, String cmd, String label, String[] args) { // command String command = cmd.toLowerCase(); // player Player player = (Player) sender; // root command split for public and moderator access! if (command.equalsIgnoreCase("help")) { try { showHelpPage(player, publicPath + "help.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (command.equalsIgnoreCase("vote")) { try { showHelpPage(player, publicPath + "vote.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (command.equalsIgnoreCase("banneditems")) { try { showHelpPage(player, publicPath + "banneditems.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (command.equalsIgnoreCase("rules")) { try { showHelpPage(player, publicPath + "rules.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { // Unknown help page errMessage(player, "Unknown help page!"); } }
47ab0def-f97b-4ebb-9cfe-c6de1981c60d
4
private void getImageTest(String asImageType, String asLastMod, int aiMaxSize, boolean abIncludeEncodedData) { ArrayList<Image> laImages = null; System.out.println("Running for LastMod: " + asLastMod + " and MaxSize: " + aiMaxSize); ImageList laImageList = laClient.getImages("Registrant Photo", abIncludeEncodedData, aiMaxSize, asLastMod); Assert.assertNotNull(laImageList); Assert.assertNotNull(laImageList.getImageList()); System.out.println(laImageList.getImageList().size() + " Image(s) returned."); asLastMod = laImageList.getLastModified(); laImages = laImageList.getImageList(); int liRun = 1; while (laImages != null && laImages.size() > 0) { System.out.println("Run " + (liRun++) + ":"); for (Image laImage : laImages) { System.out.println(laImage.toString()); } // If we get back less than the max size then we are done. if (laImageList.getImageList().size() < aiMaxSize) { laImages = null; } // We still have work to do. else { System.out.println("Running for LastMod: " + asLastMod + " and MaxSize: " + aiMaxSize); laImageList = laClient.getImages(asImageType, abIncludeEncodedData, aiMaxSize, asLastMod); Assert.assertNotNull(laImageList); Assert.assertNotNull(laImageList.getImageList()); System.out.println(laImageList.getImageList().size() + " Image(s) returned."); asLastMod = laImageList.getLastModified(); laImages = laImageList.getImageList(); } } }
079794ac-7d1d-44e6-bd51-f8019e030b4a
3
static boolean schrikkelJaar(int jaar) { boolean schrikkel; if(jaar % 4 == 0) schrikkel = true; else if(jaar % 100 == 0) schrikkel = true; else if(jaar % 400 == 0) schrikkel = true; else schrikkel = false; return schrikkel; }
3e95fcaf-2133-40d2-867d-c7f5b076d880
9
private void map(Map<?, ?> map) { add("{"); Iterator<?> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<?, ?> e = (Map.Entry<?, ?>) it.next(); value(e.getKey()); add(":"); value(e.getValue()); if (it.hasNext()) add(','); } add("}"); }
4857c253-b1ed-4cb0-bf0b-9a55ae7ee931
8
private void updateDisplayString(){ PlayerBattleState playerState = null; TargetableState targetState = null; ObjectState pState = Directory.profile.getPlayer().getState(); //Get the player's state if(pState != null && pState instanceof PlayerBattleState) { playerState = (PlayerBattleState) pState; ObjectState tState = null; //Get the player's current target's state if(playerState.getCurrentTarget() != null){ tState = playerState.getCurrentTarget().getState(); } if(tState != null && tState instanceof TargetableState){ targetState = (TargetableState)playerState.getCurrentTarget().getState(); } } //IF the target's state is null set the string to nothing if(targetState == null){ if(playerState == null){ displayString = ""; } else displayString = playerState.getAnswerString(); } else{ if(targetState.holdsEquation()){ //Write the targetstate's equation first them the player's answer string! displayString = targetState.getEquation().toString() + " = " + playerState.getAnswerString(); } else{ //Wrte the player's answer string followed by the equation of the target displayString = playerState.getAnswerString() + " = " + targetState.getEquation().toString(); } } }
8f59ca9f-726a-43ec-8098-67877bc3a9b5
0
public List<TravelTrip> findType(boolean typeBusiness){ //Query travelTripByType = em.createNamedQuery("TravelTrip.findByTripType"); TypedQuery<TravelTrip> travelTripByType = em.createNamedQuery("TravelTrip.findByTripType", TravelTrip.class); travelTripByType.setParameter("business", typeBusiness); return travelTripByType.getResultList(); }
b103cb2e-f9fe-4cd5-9969-82bb80189917
3
@Override public int compareTo(Joueur o) { SimpleDateFormat formater=new SimpleDateFormat("dd/MM/yy HH:mm:ss"); Date dateO1 = null,dateO2 = null; try { dateO1=formater.parse(this.getDateJeu()); dateO2=formater.parse(o.getDateJeu()); } catch (ParseException e) { JOptionPane.showMessageDialog(null, e.getMessage(),"Erreur",JOptionPane.ERROR_MESSAGE); } if(dateO1.compareTo(dateO2)==-1) return 1; else if(dateO1.compareTo(dateO2)==1) return -1; else return 0; }
dae4fb5d-047b-4c1c-bcfc-4fb893e62933
3
public static void main(String[] args) { try { if (args.length != 2) { System.err.println("USAGE: java RenderMap map.txt image.png"); System.exit(1); } Game game = new Game(args[0], 100, 0, null); if (game.Init() == 0) { System.err.println("Error while loading map " + args[0]); System.exit(1); } ArrayList<Color> colors = new ArrayList<Color>(); colors.add(new Color(106, 74, 60)); colors.add(new Color(74, 166, 60)); colors.add(new Color(204, 51, 63)); colors.add(new Color(235, 104, 65)); colors.add(new Color(237, 201, 81) ); Color bgColor = new Color(188, 189, 172); Color textColor = Color.BLACK; Font planetFont = new Font("Sans Serif", Font.BOLD, 11); Font fleetFont = new Font("Sans serif", Font.PLAIN, 7); GraphicsConfiguration gc = GraphicsEnvironment .getLocalGraphicsEnvironment().getDefaultScreenDevice() .getDefaultConfiguration(); BufferedImage image = gc.createCompatibleImage(640, 480); Graphics2D _g = (Graphics2D)image.createGraphics(); // Turn on AA/Speed _g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); _g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); _g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); //game.Render(640, 480, 0.0, null, colors, bgColor, textColor, planetFont, fleetFont, _g); game.Render(640, 480, 0.0, null, colors, _g); File file = new File(args[1]); ImageIO.write(image, "png", file); } catch (Exception e) { System.err.println(e); } }
e7158b76-17f3-458b-aa18-f294b9fc1d4e
1
public CurrentPlayerRenderer(Game game, JPanel panel, JLabel actions) { super(game, panel); if (actions == null) throw new IllegalArgumentException("The given actions left panel is invalid!"); this.actionsLeft = actions; }
cc10de9f-cd8a-4bb6-a5ea-521900d0e347
5
private void initialize() { frame = new JFrame(); frame.setTitle("The Dungeon of Zelda"); frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Menu.class.getResource("/background/icon.jpg"))); frame.setBounds(100, 100, 600, 400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Adds the layout : a layered layout to display the background (layer 0) and the components (layer 1) JLayeredPane layeredPane = new JLayeredPane(); frame.getContentPane().add(layeredPane, BorderLayout.CENTER); //Plays the background music. sound = new SoundPlayer("Adventure_Title"); sound.playSound(); //Displays the background JLabel lblNewLabel = new JLabel(""); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setIcon(new ImageIcon(Menu.class.getResource("/background/Menu.jpg"))); lblNewLabel.setBounds(0, 0, 638, 415); layeredPane.add(lblNewLabel); //Displays "Game Mode" JTextPane txtpnGameMode = new JTextPane(); txtpnGameMode.setForeground(Color.WHITE); txtpnGameMode.setFont(new Font("Dialog", Font.BOLD, 14)); txtpnGameMode.setOpaque(false); txtpnGameMode.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); txtpnGameMode.setBackground(UIManager.getColor("Button.background")); txtpnGameMode.setEditable(false); txtpnGameMode.setText("Game mode"); layeredPane.setLayer(txtpnGameMode, 1); // -> layer 1 txtpnGameMode.setBounds(12, 135, 100, 22); layeredPane.add(txtpnGameMode); //choice of game mode : solo or multiplayer final Choice gameMode = new Choice(); gameMode.setForeground(Color.BLACK); gameMode.addItemListener(new ItemListener() { //ItemListener game Mode config public void itemStateChanged(ItemEvent e) { switch(gameMode.getSelectedItem()){ case "Solo" : GameManager.multiplayer = false; // System.out.println("Mode solo choisi"); // Test Line, to print what you chose. break; case "Multiplayer": GameManager.multiplayer = true; // System.out.println("Mode multijoueur choisi"); // Test Line, to print what you chose. break; } } }); gameMode.add(""); gameMode.add("Solo"); gameMode.add("Multiplayer"); gameMode.setFont(new Font("Dialog", Font.BOLD, 12)); gameMode.setBackground(Color.WHITE); layeredPane.setLayer(gameMode, 1); gameMode.setBounds(119, 135, 111, 21); layeredPane.add(gameMode); //Display "Difficulty" JTextPane txtDifficulty = new JTextPane(); txtDifficulty.setFont(new Font("Dialog", Font.BOLD, 14)); txtDifficulty.setName(""); txtDifficulty.setForeground(Color.WHITE); txtDifficulty.setEditable(false); txtDifficulty.setToolTipText(""); txtDifficulty.setSelectedTextColor(Color.WHITE); txtDifficulty.setBackground(UIManager.getColor("Button.background")); layeredPane.setLayer(txtDifficulty, 1); txtDifficulty.setText("Difficulty"); txtDifficulty.setBounds(12, 197, 83, 22); txtDifficulty.setOpaque(false); layeredPane.add(txtDifficulty); // Choice of the game difficulty : Novice, Normal or Expert final Choice difficulty = new Choice(); difficulty.setForeground(Color.BLACK); difficulty.setFont(new Font("Dialog", Font.BOLD, 12)); difficulty.setBackground(Color.WHITE); difficulty.addItemListener(new ItemListener() { //ItemListener difficulty config @Override public void itemStateChanged(ItemEvent arg0) { switch(difficulty.getSelectedItem()){ case "Novice" : GameManager.difficulty = 1; // System.out.println("Difficulty : Novice"); // Test Line, to print what you chose. break; case "Normal" : GameManager.difficulty = 2; // System.out.println("Difficulty : Normal"); // Test Line, to print what you chose. break; case "Expert" : GameManager.difficulty = 3; // System.out.println("Difficulty : Expert"); // Test Line, to print what you chose. break; } //System.out.println("difficulty " + GameManager.difficulty); } }); difficulty.add(""); difficulty.add("Novice"); difficulty.add("Normal"); difficulty.add("Expert"); layeredPane.setLayer(difficulty, 1); difficulty.setBounds(119, 197, 111, 21); layeredPane.add(difficulty); // Display "Enter the server name" JTextPane txtpnEnterTheServer = new JTextPane(); txtpnEnterTheServer.setForeground(Color.WHITE); txtpnEnterTheServer.setFont(new Font("Dialog", Font.BOLD, 14)); txtpnEnterTheServer.setOpaque(false); txtpnEnterTheServer.setBackground(UIManager.getColor("Button.background")); txtpnEnterTheServer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); txtpnEnterTheServer.setEditable(false); txtpnEnterTheServer.setText("Enter the server name :"); layeredPane.setLayer(txtpnEnterTheServer, 1); txtpnEnterTheServer.setBounds(440, 63, 132, 44); layeredPane.add(txtpnEnterTheServer); // Edition zone for the server name serverName = new JTextField(); serverName.setDropMode(DropMode.INSERT); layeredPane.setLayer(serverName, 1); serverName.setBounds(440, 119, 132, 20); layeredPane.add(serverName); serverName.setColumns(10); //Display "Enter the port number" JTextPane txtpnPleaseEnterThe = new JTextPane(); txtpnPleaseEnterThe.setOpaque(false); txtpnPleaseEnterThe.setForeground(Color.WHITE); txtpnPleaseEnterThe.setFont(new Font("Dialog", Font.BOLD, 14)); txtpnPleaseEnterThe.setText("Enter the server port : "); txtpnPleaseEnterThe.setEditable(false); txtpnPleaseEnterThe.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); txtpnPleaseEnterThe.setBackground(UIManager.getColor("Button.background")); layeredPane.setLayer(txtpnPleaseEnterThe, 1); txtpnPleaseEnterThe.setBounds(440, 160, 132, 44); layeredPane.add(txtpnPleaseEnterThe); // Edition zone for the port number serverPort = new JTextField(); layeredPane.setLayer(serverPort, 1); serverPort.setBounds(440, 216, 132, 20); layeredPane.add(serverPort); serverPort.setColumns(10); //Button for starting the game //For Solo mode / multiplayer server Button startGame = new Button("Start game"); startGame.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { frame.setVisible(false); // Closes the menu window sound.stopSound(); // Stops the sound new GameManager().start(); } }); layeredPane.setLayer(startGame, 1); startGame.setBounds(73, 290, 76, 23); layeredPane.add(startGame); //For multiplayer client Button joinGame = new Button("Join a game"); joinGame.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { frame.setVisible(false); // Closes the menu window sound.stopSound(); // Stops the sound new GameManager(serverName.getText(), Integer.parseInt(serverPort.getText())).start(); } }); layeredPane.setLayer(joinGame, 1); joinGame.setBounds(459, 290, 76, 23); layeredPane.add(joinGame); }
48ce0cd4-6d76-4ba6-87f1-f4a1c628e3c2
9
public void useDice(int itemId, boolean clan){ if (System.currentTimeMillis() - c.diceDelay >= 3000) { c.sendMessage("Rolling..."); c.startAnimation(11900); c.diceDelay = System.currentTimeMillis(); c.cDice = itemId; c.clanDice = clan; switch (itemId) { //Gfx's case 15086: c.gfx0(2072); break; case 15088: c.gfx0(2074); break; case 15090: c.gfx0(2071); break; case 15092: c.gfx0(2070); break; case 15094: c.gfx0(2073); break; case 15096: c.gfx0(2068); break; case 15098: c.gfx0(2075); break; case 15100: c.gfx0(2069); break; } } }
a9a70b98-b2cb-4ac8-9d87-46ace132635f
2
@Test public void testViewDetailsForAllQueues() throws LuaScriptException { List<String> noKeys = new ArrayList<String>(); List<String> args = Arrays.asList(JQlessClient.getCurrentSeconds()); String json = (String) _luaScript.callScript(this.scriptName(), noKeys, args); List<Map<String, Object>> queueDetails = JsonHelper.parseList(json); for (Map<String, Object> queue : queueDetails) { if (queue.get("name").equals(TEST_QUEUE)) { assertEquals("1", queue.get("running").toString()); assertEquals("1", queue.get("waiting").toString()); } else { assertEquals("0", queue.get("running").toString()); assertEquals("1", queue.get("waiting").toString()); } assertEquals("0", queue.get("scheduled").toString()); } }
031f26d6-921b-4855-b31a-df03b04110fc
5
private void highlightButton(Graphics g) { Rectangle bounds = null; g.setColor(Color.red); // check which button is selected if (selected == ButtonSelected.NEW) { bounds = getButtonBounds(BUTTON_X_START_PROPORTION, NEW_PLAYER_Y_PROPORTION); } else if (selected == ButtonSelected.LOAD) { bounds = getButtonBounds(BUTTON_X_START_PROPORTION, LOAD_PLAYER_Y_PROPORTION); } else if (selected == ButtonSelected.SERVER) { bounds = getButtonBounds(BUTTON_X_START_PROPORTION, START_SERVER_Y_PROPORTION); } else if (selected == ButtonSelected.CONTROLS) { bounds = getButtonBounds(BUTTON_X_START_PROPORTION, CONTROLS_Y_PROPORTION); } // if there is a selected button if (bounds != null) { // draw three adjacent rectangles around it g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height); g.drawRect(bounds.x - 1, bounds.y - 1, bounds.width + 2, bounds.height + 2); g.drawRect(bounds.x + 1, bounds.y + 1, bounds.width - 2, bounds.height - 2); // now repaint repaint(); } }
2c3373fa-eda1-4bae-963f-fc543f8fa9f0
9
public boolean onCommand(CommandSender sender, Command cmd, String label,String[] args){ if(sender instanceof Player && cmd.getName().equals("public")){ Player p = (Player) sender; if(this.listener.isPrivate(p)){ this.listener.removePrivate(p); p.sendMessage(ChatColor.DARK_PURPLE+"[Chat]"+ChatColor.WHITE+" Your messages will be broadcast externally."); }else{ p.sendMessage(ChatColor.DARK_PURPLE+"[Chat]"+ChatColor.WHITE+" Your messages were already broadcast externally"); } return true; } if(sender instanceof Player && cmd.getName().equals("private")){ Player p = (Player) sender; if(!this.listener.isPrivate(p)){ this.listener.addPrivate(p); p.sendMessage(ChatColor.DARK_PURPLE+"[Chat]"+ChatColor.WHITE+" Your messages will not be broadcast externally."); }else{ p.sendMessage(ChatColor.DARK_PURPLE+"[Chat]"+ChatColor.WHITE+" Your messages were already not broadcast externally."); } return true; } if(!(sender instanceof Player) && (cmd.getName().equals("public") || cmd.getName().equals("private"))){ this.logMessage("Internal / External chat may only be controlled by players"); return false; } return false; }
937023f8-a554-488b-babe-4d6e321d12f2
5
public void performStepp(int Stepps, Vector2 Position) { for(int i = 0; i < Stepps; i++) { if(Position.getX() > this.TargetLocation.getX()) { Position.addX(- 1); } else if(Position.getX() < this.TargetLocation.getX()) { Position.addX(+ 1); } if(Position.getY() > this.TargetLocation.getY()) { Position.addY(- 1); } else if (Position.getY() < this.TargetLocation.getY()) { Position.addY(+ 1); } } }
d584f57d-2660-4fb0-a22f-5d1341cc0424
2
public Type getType(Identifier id) { // traverse the list of types backwards for(int i = types.size() - 1; i >= 0; i--) { Type rval = types.get(i).get(id); if(rval != null) { return rval; } } // exited the search without finding the Identifier, return null return null; }
a898ba29-5e41-4be9-8811-5b33b93f8b6b
6
public static Surrogate verifyType(Surrogate self) { if ((self.surrogateValue != null) && (!Stella_Object.stellaClassP(self.surrogateValue))) { { Stella.STANDARD_WARNING.nativeStream.println("Warning: Illegal object `" + self.surrogateValue + "' found"); Stella.STANDARD_WARNING.nativeStream.println(" where STELLA class expected"); Stella.STANDARD_WARNING.nativeStream.println(); } ; self.surrogateValue = ((Stella_Class)(Stella.SGT_STELLA_UNKNOWN.surrogateValue)); } if (Stella.translatingCodeP() && ((((Stella_Class)(self.surrogateValue)) == null) || (((Stella_Class)(self.surrogateValue)) == ((Stella_Class)(Stella.SGT_STELLA_UNKNOWN.surrogateValue))))) { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationWarning(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> WARNING: ", Stella.STANDARD_WARNING); { Stella.STANDARD_WARNING.nativeStream.println(); Stella.STANDARD_WARNING.nativeStream.println(" Reference to undefined class `" + self.symbolName + "'."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } self.surrogateValue = ((Stella_Class)(Stella.SGT_STELLA_UNKNOWN.surrogateValue)); } return (self); }
b6169971-e3d9-4b49-a03a-438014301978
2
public PDAStepByStateSimulator(Automaton automaton) { super(automaton); /** default acceptance is by final state. */ Object[] possibleValues = {"Final State", "Empty Stack"}; Object selectedValue = JOptionPane.showInputDialog(null, "Accept by", "Input", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]); if(selectedValue.equals(possibleValues[0])){ myAcceptance = FINAL_STATE; //EDebug.print("fstate"); }else if(selectedValue.equals(possibleValues[1])){ myAcceptance = EMPTY_STACK; //EDebug.print("estack"); } //myAcceptance = FINAL_STATE; //myAcceptance=selectedValue; }
b0b5d50a-3571-47b6-be59-ee982d96c603
2
private static boolean isNumber(String s) { if (s == null) return false; try { Double.parseDouble(s); return true; } catch (NumberFormatException e) { return false; } }
276f42aa-3400-4f0f-a3ed-41ea36a8bd38
7
static final void method2092(int i, int i_25_, int[] is, int i_26_, Object[] objects) { try { int i_27_ = -92 / ((i_26_ - -55) / 57); if ((i ^ 0xffffffff) < (i_25_ ^ 0xffffffff)) { int i_28_ = (i + i_25_) / 2; int i_29_ = i_25_; int i_30_ = is[i_28_]; is[i_28_] = is[i]; is[i] = i_30_; Object object = objects[i_28_]; objects[i_28_] = objects[i]; objects[i] = object; int i_31_ = i_30_ != 2147483647 ? 1 : 0; for (int i_32_ = i_25_; (i ^ 0xffffffff) < (i_32_ ^ 0xffffffff); i_32_++) { if (is[i_32_] < (i_31_ & i_32_) + i_30_) { int i_33_ = is[i_32_]; is[i_32_] = is[i_29_]; is[i_29_] = i_33_; Object object_34_ = objects[i_32_]; objects[i_32_] = objects[i_29_]; objects[i_29_++] = object_34_; } } is[i] = is[i_29_]; is[i_29_] = i_30_; objects[i] = objects[i_29_]; objects[i_29_] = object; method2092(-1 + i_29_, i_25_, is, 9, objects); method2092(i, i_29_ - -1, is, -127, objects); } anInt3594++; } catch (RuntimeException runtimeexception) { throw Class348_Sub17.method2929(runtimeexception, ("cba.K(" + i + ',' + i_25_ + ',' + (is != null ? "{...}" : "null") + ',' + i_26_ + ',' + (objects != null ? "{...}" : "null") + ')')); } }
16a0d4e4-12bd-421c-a242-3bb5c649035f
0
public ServerListener(int port) { serverPort = port; list = new ClientListManager(); }
ca3d42d5-4675-4d8c-b9fd-0b30e7801495
0
public PartnerListResponse( final Boolean success, final String errorMessage, final List<Partner> partnerList ) { super(success, errorMessage); this.partnerList = partnerList; }
3c7bcea2-a202-4055-b726-4a861e719950
1
public boolean equals(Point o) { return o.x == x && o.y == y ; }
51caeb92-29e9-440d-b027-f63838908831
3
public void use(int slot) { if (slot < 0 || slot > 2) return; if (equipped[slot] != null) { equipped[slot].use(player); } }
a125545a-509f-43cf-b8b1-54da8a149b92
4
public static void main(String[] args) { // TODO code application logic here String palabra=""; int brin=0; char letra = 0; int cantidad=0; int opcion; Scanner teclado=new Scanner(System.in); do{ System.out.println("Digite la opcion del ejercicio a evaluar"); System.out.println("Ejercicio 1"); System.out.println("Ejercicio 2"); System.out.println("Salir"); opcion=teclado.nextInt(); switch(opcion){ case 1: Examen oExamen= new Examen(); oExamen.CrearMatriz(); oExamen.CrearMatrizMayu(); oExamen.CrearMatriz2(); oExamen.guardarAlfa(); System.out.println("Digite una palabra"); teclado= new Scanner(System.in); palabra=teclado.next(); System.out.println("Digite el numero de bricos que desea"); teclado= new Scanner(System.in); brin=teclado.nextInt(); oExamen.cambio(palabra, brin); System.out.println("El cambio de la palabra es"+oExamen.cambio(palabra, brin)); break; case 2: Examen2 oExamen2= new Examen2(); System.out.println("Digite una cantidad"); teclado= new Scanner(System.in); cantidad=teclado.nextInt(); System.out.println(oExamen2.impresion(cantidad)); System.out.println(oExamen2.Imprimir(cantidad)); break; case 3: break; } }while(opcion!=3); }
3db4ae14-a7e6-4f1b-bf2c-95959cfe6d7f
4
protected static Ptg calcAverageA( Ptg[] operands ) { Ptg[] alloperands = PtgCalculator.getAllComponents( operands ); double total = 0; for( Ptg p : alloperands ) { try { Object ov = p.getValue(); if( ov != null ) { if( String.valueOf( ov ) == "true" ) { total++; } else { total += Double.parseDouble( String.valueOf( ov ) ); } } } catch( NumberFormatException e ) { } ; } double result = total / alloperands.length; PtgNumber pnum = new PtgNumber( result ); return pnum; }
c0df5151-f125-438e-8ba0-814442070cb0
5
@Override public List<MetaObject> getGroupMetaData() { List<MetaObject> list = new ArrayList<MetaObject>(); Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_GROUP_META); rs = ps.executeQuery(); while (rs.next()) { list.add(processResultSet(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
ab13e694-4dd4-4b2b-af4e-dda1976d0937
9
final public void exportDiagram(OutputStream os, StringBuilder cmap, int index, FileFormatOption fileFormatOption) throws IOException { List<BufferedImage> flashcodes = null; try { if ("split".equalsIgnoreCase(getSkinParam().getValue("flashcode")) && fileFormatOption.getFileFormat() == FileFormat.PNG) { final String s = getSource().getPlainString(); flashcodes = exportSplitCompress(s); } else if ("compress".equalsIgnoreCase(getSkinParam().getValue("flashcode")) && fileFormatOption.getFileFormat() == FileFormat.PNG) { final String s = getSource().getPlainString(); flashcodes = exportFlashcodeCompress(s); } else if (getSkinParam().getValue("flashcode") != null && fileFormatOption.getFileFormat() == FileFormat.PNG) { final String s = getSource().getPlainString(); flashcodes = exportFlashcodeSimple(s); } } catch (WriterException e) { Log.error("Cannot generate flashcode"); e.printStackTrace(); flashcodes = null; } if (fileFormatOption.getFileFormat() == FileFormat.PDF) { exportDiagramInternalPdf(os, cmap, index, flashcodes); return; } if (fileFormatOption.getFileFormat() == FileFormat.MJPEG) { // exportDiagramInternalMjpeg(os); // return;* throw new UnsupportedOperationException(); } lastInfo = exportDiagramInternal(os, cmap, index, fileFormatOption, flashcodes); }
1f31dc1e-841f-4bb3-b46d-02e310e263f9
4
public Boolean subTaskDateChecker(Date supTaskStartDate, Date supTaskEndDate, Date parentStartDate, Date parentEndDate) { Boolean result = true; if (supTaskStartDate.before(parentStartDate) || supTaskStartDate.after(parentEndDate) || supTaskStartDate.after(supTaskEndDate) || supTaskEndDate.after(parentEndDate)) { result = false; } return result; }
ad7995e7-7a85-4ac1-b924-066bc5ff2b78
9
public void paintComponent(Graphics g) { g.setColor(Color.black); g.fillRect(0, 0, getHeight(), getWidth()); g.setColor(Color.white); int[][] joints = moc.joints; if (joints != null) { try { for (int skelIndex = 1; skelIndex <= 2; skelIndex++) { int[][] segments = new int[19][5]; // head to shoulder center segments[0][0] = joints[3][1]; segments[0][1] = joints[3][2]; segments[0][2] = joints[2][1]; segments[0][3] = joints[2][2]; segments[0][4] = joints[3][0] * joints[2][0]; //shoulder center to shoulder right segments[1][0] = joints[8][1]; segments[1][1] = joints[8][2]; segments[1][2] = joints[2][1]; segments[1][3] = joints[2][2]; segments[1][4] = joints[8][0] * joints[2][0]; //shoulder right to elbow right segments[2][0] = joints[8][1]; segments[2][1] = joints[8][2]; segments[2][2] = joints[9][1]; segments[2][3] = joints[9][2]; segments[2][4] = joints[8][0] * joints[9][0]; //elbow right to wrist right segments[3][0] = joints[10][1]; segments[3][1] = joints[10][2]; segments[3][2] = joints[9][1]; segments[3][3] = joints[9][2]; segments[3][4] = joints[10][0] * joints[9][0]; //wrist right to hand right segments[4][0] = joints[10][1]; segments[4][1] = joints[10][2]; segments[4][2] = joints[11][1]; segments[4][3] = joints[11][2]; segments[4][4] = joints[10][0] * joints[11][0]; // //shoulder center to shoulder left segments[5][0] = joints[4][1]; segments[5][1] = joints[4][2]; segments[5][2] = joints[2][1]; segments[5][3] = joints[2][2]; segments[5][4] = joints[2][0] * joints[4][0]; //shoulder left to elbow left segments[6][0] = joints[4][1]; segments[6][1] = joints[4][2]; segments[6][2] = joints[5][1]; segments[6][3] = joints[5][2]; segments[6][4] = joints[4][0] * joints[5][0]; //elbow left to wrist left segments[7][0] = joints[5][1]; segments[7][1] = joints[5][2]; segments[7][2] = joints[6][1]; segments[7][3] = joints[6][2]; segments[7][4] = joints[6][0] * joints[5][0]; //wrist left to hand left segments[8][0] = joints[6][1]; segments[8][1] = joints[6][2]; segments[8][2] = joints[7][1]; segments[8][3] = joints[7][2]; segments[8][4] = joints[7][0] * joints[6][0]; // spine segments[9][0] = joints[2][1]; segments[9][1] = joints[2][2]; segments[9][2] = joints[1][1]; segments[9][3] = joints[1][2]; segments[9][4] = joints[1][0] * joints[2][0]; segments[10][0] = joints[1][1]; segments[10][1] = joints[1][2]; segments[10][2] = joints[0][1]; segments[10][3] = joints[0][2]; segments[10][4] = joints[0][0] * joints[1][0]; //right leg segments[11][0] = joints[16][1]; segments[11][1] = joints[16][2]; segments[11][2] = joints[0][1]; segments[11][3] = joints[0][2]; segments[11][4] = joints[0][0] * joints[16][0]; segments[12][0] = joints[16][1]; segments[12][1] = joints[16][2]; segments[12][2] = joints[17][1]; segments[12][3] = joints[17][2]; segments[12][4] = joints[17][0] * joints[16][0]; segments[13][0] = joints[17][1]; segments[13][1] = joints[17][2]; segments[13][2] = joints[18][1]; segments[13][3] = joints[18][2]; segments[13][4] = joints[18][0] * joints[17][0]; segments[14][0] = joints[18][1]; segments[14][1] = joints[18][2]; segments[14][2] = joints[19][1]; segments[14][3] = joints[19][2]; segments[14][4] = joints[19][0] * joints[18][0]; //left leg segments[15][0] = joints[12][1]; segments[15][1] = joints[12][2]; segments[15][2] = joints[0][1]; segments[15][3] = joints[0][2]; segments[15][4] = joints[0][0] * joints[12][0]; segments[16][0] = joints[12][1]; segments[16][1] = joints[12][2]; segments[16][2] = joints[13][1]; segments[16][3] = joints[13][2]; segments[16][4] = joints[13][0] * joints[12][0]; segments[17][0] = joints[13][1]; segments[17][1] = joints[13][2]; segments[17][2] = joints[14][1]; segments[17][3] = joints[14][2]; segments[17][4] = joints[14][0] * joints[13][0]; segments[18][0] = joints[14][1]; segments[18][1] = joints[14][2]; segments[18][2] = joints[15][1]; segments[18][3] = joints[15][2]; segments[18][4] = joints[15][0] * joints[14][0]; if (skelIndex == 1) { g.setColor(Color.red); } else { g.setColor(Color.green); } int w = getWidth() / 2; int h = getHeight() / 2; double s = 1.8 / 1800 * h; for (int i = 0; i < segments.length; i++) { if (segments[i][4] != 0) { int x1 = (int) (segments[i][0] * s + w); int y1 = (int) (-segments[i][1] * s + h); int x2 = (int) (segments[i][2] * s + w); int y2 = (int) (-segments[i][3] * s + h); g.drawLine(x1, y1, x2, y2); } } } } catch (Exception e) { //System.out.println(e.getMessage()); } } g.setColor(Color.black); g.fillRect(0, 0, 55, 15); g.setColor(Color.green); String s = ""; if (moc.state == moc.STOP) { s = "STOP"; } if (moc.state == moc.PLAY) { s = "PLAY, Frame = "+moc.frameCnt; } if (moc.state == moc.RECORD) { g.setColor(Color.red); s = "RECORD, Frame = "+moc.frameCnt; } g.drawString(s, 5, 10); }
ba35f00a-82c8-4786-ad90-82e6cbcacaf8
1
private void drawRestOfJPanelDisplay(Graphics g) { userCard.drawCard(g, this); int numberLeftInPack = cardStack.size(); if (numberLeftInPack > 0) { aFaceDownCard.drawCard(g, this); drawNumberInsideCardArea(g, aFaceDownCard); } drawGameInformation(g); }
1123456f-c86d-4d4d-aeea-162b86a1125c
5
public static String longestPalindromeByMid(String s, int i, int j) { if (i != j && i != j - 1) { return null; } int l = i, r = j; while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--;r++; } return s.substring(l+1, r); }
7d84e45c-e5df-4c56-b46d-ee6cd394ba56
6
@Override public Color getDominantClusterInNeighbourhood(Node node) { Set<Node> neighbors = IteratorUtils.toSet(this.LPAClusteringEngine.getGraph().getNeighbors(node).iterator()); Color currentNodeCluster = this.LPAClusteringEngine.getNodeClusterMapping().get(node); if (neighbors.isEmpty()) return currentNodeCluster; // no clusters in neighbourhood, a disconnected node. Map<Color, Double> neighborClusterWeights = new HashMap<Color, Double>(); // Calculating the clusters' weights in the neighbourhood of the processed node. for(Node currentNeighbor:neighbors){ if (this.LPAClusteringEngine.getIsCancelled()) break; Color neighboringCluster = this.LPAClusteringEngine.getNodeClusterMapping().get(currentNeighbor); // Calculating the cluster weight according to the rule (A_u - lambda*k_v*k_u + lambda*k²_v) where lambda // is the resolution parameter, v the processed node and u is the current neighbor. double clusterWeight = this.LPAClusteringEngine.getGraph().getEdge(node, currentNeighbor).getWeight(); clusterWeight -= ResolutionParameter * this.LPAClusteringEngine.getGraph().getDegree(node) * this.LPAClusteringEngine.getGraph().getDegree(currentNeighbor); clusterWeight += ResolutionParameter * Math.pow(this.LPAClusteringEngine.getGraph().getDegree(node), 2); // summing over same community neighbors if (neighborClusterWeights.containsKey(neighboringCluster)) { clusterWeight += neighborClusterWeights.get(neighboringCluster); } // updating the cluster weight neighborClusterWeights.put(neighboringCluster, clusterWeight); } // picking the cluster with the heighest weight. In case two or more clusters exhibit the same weight, the LPA rule must pick a random one from the dominant group. // Shuffling the clusters list and picking the cluster with the highest weight. neighborClusterWeights = MapUtils.shuffle(neighborClusterWeights, this.LPAClusteringEngine.getRandomizer()); double maxWeight = Collections.max(neighborClusterWeights.values()); Color prevailingClusterColor = MapUtils.getKeyByValue(neighborClusterWeights, maxWeight); // Check whether the current node's cluster is already a dominant one. if (neighborClusterWeights.containsKey(currentNodeCluster)) { // if it is the case, then keep it. if (neighborClusterWeights.get(currentNodeCluster) == maxWeight) prevailingClusterColor = currentNodeCluster; } return prevailingClusterColor; }
51123e44-28a4-44ca-9ca0-1037bc9e3436
9
public String sample_frequency_string() { switch (h_sample_frequency) { case THIRTYTWO: if (h_version == MPEG1) return "32 kHz"; else if (h_version == MPEG2_LSF) return "16 kHz"; else // SZD return "8 kHz"; case FOURTYFOUR_POINT_ONE: if (h_version == MPEG1) return "44.1 kHz"; else if (h_version == MPEG2_LSF) return "22.05 kHz"; else // SZD return "11.025 kHz"; case FOURTYEIGHT: if (h_version == MPEG1) return "48 kHz"; else if (h_version == MPEG2_LSF) return "24 kHz"; else // SZD return "12 kHz"; } return(null); }
1ec0a668-94b9-41a0-898c-554a2449505b
1
@Override public int getRow() { ensureOpen("getRow"); //return cursor; return (cursor < 0) ? 0 : cursor + 1; }
f446dae1-20e1-4e41-bc76-88646335f44b
2
private static int partition(int[] array, int start, int end) { int pivot = array[end]; int smallerIndex = start - 1; for (int i = start; i < end; i++) { if (array[i] <= pivot) { smallerIndex++; swap(array, smallerIndex, i); } } smallerIndex++; swap(array, smallerIndex, end); return smallerIndex; }
1c65bc49-e882-4fd0-b61c-659ff46ece2d
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 Orders)) { return false; } Orders other = (Orders) object; if ((this.orderId == null && other.orderId != null) || (this.orderId != null && !this.orderId.equals(other.orderId))) { return false; } return true; }
c2274678-1bbf-4fcd-b548-e1dc1f6a9160
4
public static String getTimestamp(int format) { switch(format) { case SHORT: return shortFormat.format(new Date()); case MEDIUM: return mediumFormat.format(new Date()); case LONG: return longFormat.format(new Date()); case FULL: return fullFormat.format(new Date()); default: return null; } }
6f53eeb4-4d01-4593-a211-defc112226ac
1
public void acquirePacketsTimed(final List<Packet> buffer, final int count, long milliseconds) { Thread sniffer = acquirePackets(buffer, count); try { Thread.sleep(milliseconds); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } done = true; }
3a0e1506-43fe-49c6-be3f-19b62e04a093
7
boolean validateMove(movePair movepr, Pair pr) { // This is also from dumbPlayer, and seems like something we won't have to use Point src = movepr.src; Point target = movepr.target; boolean rightposition = false; if (Math.abs(target.x-src.x)==Math.abs(pr.p) && Math.abs(target.y-src.y)==Math.abs(pr.q)) { rightposition = true; } if (Math.abs(target.x-src.x)==Math.abs(pr.q) && Math.abs(target.y-src.y)==Math.abs(pr.p)) { rightposition = true; } if (rightposition && src.value == target.value && src.value >0) { return true; } else { return false; } }
6a70eaa7-bdd3-4786-ac86-555c6fc0cdd6
6
public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; }
b353ed84-63e3-4bf5-9177-ae5fdde75970
9
public static String stringFor_cl_program_info(int n) { switch (n) { case CL_PROGRAM_REFERENCE_COUNT: return "CL_PROGRAM_REFERENCE_COUNT"; case CL_PROGRAM_CONTEXT: return "CL_PROGRAM_CONTEXT"; case CL_PROGRAM_NUM_DEVICES: return "CL_PROGRAM_NUM_DEVICES"; case CL_PROGRAM_DEVICES: return "CL_PROGRAM_DEVICES"; case CL_PROGRAM_SOURCE: return "CL_PROGRAM_SOURCE"; case CL_PROGRAM_BINARY_SIZES: return "CL_PROGRAM_BINARY_SIZES"; case CL_PROGRAM_BINARIES: return "CL_PROGRAM_BINARIES"; case CL_PROGRAM_NUM_KERNELS: return "CL_PROGRAM_NUM_KERNELS"; case CL_PROGRAM_KERNEL_NAMES: return "CL_PROGRAM_KERNEL_NAMES"; } return "INVALID cl_program_info: " + n; }
f314f0bc-5e18-4552-b293-431cb8d46770
7
final static public char[] trim(char[] chars) { if (chars == null) return null; int start = 0, length = chars.length, end = length - 1; while (start < length && chars[start] == ' ') { start++; } while (end > start && chars[end] == ' ') { end--; } if (start != 0 || end != length - 1) { return subarray(chars, start, end + 1); } return chars; }
7ec5726c-e60b-4f3d-a5fd-b9bebe8e40ea
6
public void setGain(float gain) { if (gain != -1) { if ((gain < 0) || (gain > 2)) { throw new IllegalArgumentException("Volume must be between 0.0 and 2.0"); } } this.gain = gain; if (outputLine == null) { return; } try { FloatControl control = (FloatControl) outputLine.getControl(FloatControl.Type.MASTER_GAIN); if (gain == -1) { control.setValue(0); } else { /*float max = control.getMaximum(); float min = control.getMinimum(); // negative values all seem to be zero? float range = max - min; control.setValue(min+(range*gain));*/ float dB = (float) (Math.log10(gain) * 20.0f); control.setValue(dB); } } catch (IllegalArgumentException e) { // gain not supported e.printStackTrace(); } }
81ab2550-48ff-41a8-bc6f-1429bf1dedf8
2
public void testPropertySetMinute() { LocalTime test = new LocalTime(10, 20, 30, 40); LocalTime copy = test.minuteOfHour().setCopy(12); check(test, 10, 20, 30, 40); check(copy, 10, 12, 30, 40); try { test.minuteOfHour().setCopy(60); fail(); } catch (IllegalArgumentException ex) {} try { test.minuteOfHour().setCopy(-1); fail(); } catch (IllegalArgumentException ex) {} }
72147177-19fe-44ca-bd43-601600a62047
8
public void startGameForClients(MiniServer player[]) { this.clientPlayersPlaying = player; //Disallow the player array from having nulls in between players: //TODO: test this loop this.numberOfPlayers = 0; for(int i=0; i<this.clientPlayersPlaying.length; i++) { if(this.clientPlayersPlaying[i] == null) { for(int j=i+1; j<this.clientPlayersPlaying.length; j++) { if(this.clientPlayersPlaying[j] != null) { this.clientPlayersPlaying[i] = this.clientPlayersPlaying[j]; this.clientPlayersPlaying[j] = null; break; } } } else { numberOfPlayers++; } } //end TODO if(numberOfPlayers >= NUM_PLAYERS_IN_MELLOW) { this.clientPlayer = new ClientPlayerDecider[player.length]; for(int i=0; i<NUM_PLAYERS_IN_MELLOW; i++) { this.clientPlayer[i] = new ClientPlayerDecider( player[i].getClientName() ); } //TODO: create output files here! //TODO: create cmd output file here! this.playGame(this.clientPlayer); if(this.commandFile != null) { this.commandFile.close(); } if(this.outputFile != null) { this.outputFile.close(); } } else { sendMessageToGroup("ERROR: not enough players to player mellow. You need 4 players!"); } }
8ac5e9fd-d617-4905-b344-a434b1516996
4
public Main() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost:3306/coffeebreak"; conn = DriverManager.getConnection(url, "root", ""); //doInsert("chocolat", 5); //doInsert("capuccino", 6); //doUpdate(); //doDelete(); doDeleteAll(); conn.close(); } catch (ClassNotFoundException ex) { System.err.println(ex.getMessage()); } catch (IllegalAccessException ex) { System.err.println(ex.getMessage()); } catch (InstantiationException ex) { System.err.println(ex.getMessage()); } catch (SQLException ex) { System.err.println(ex.getMessage()); } }
fdd2bf1f-c713-4750-aab0-cd420a89424a
3
public void setEntryText(String text, int pos) { int current = 0; for (Widget i = wdg().child; i != null; i = i.next) { if (i instanceof TextEntry) { current++; if (current == pos) { TextEntry te = (TextEntry) i; te.settext(text); return; } } } }
f19b5ac0-aef5-49bf-9643-410b54965b15
3
public static void main(String[] args) { // TODO Auto-generated method stub DataModel model = null; try { model = new FileDataModel(new File("/home/naren/projects/minhash/user_brands.csv")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } UserSimilarity similarity; try { similarity = new PearsonCorrelationSimilarity(model); UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model); Recommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity); List<RecommendedItem> recommendations = recommender.recommend(1, 1); for (RecommendedItem recommendation : recommendations) { System.out.println(recommendation); } } catch (TasteException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
27db1c29-b8cd-4da9-9e7e-9890ed62fd32
1
public static void main(String[] args) { ExecutorService ctp = Executors.newCachedThreadPool(new ThreadFactory() { private AtomicInteger count = new AtomicInteger(); public Thread newThread(Runnable r) { int c = count.incrementAndGet(); System.out.println("create no " + c + " Threads"); return new WorkThread(r, count); } }); ctp.execute(new MyThread()); ctp.execute(new MyThread()); ctp.execute(new MyThread()); ctp.execute(new MyThread()); ctp.execute(new MyThread()); ctp.execute(new MyThread()); ctp.shutdown(); try { ctp.awaitTermination(1200, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }
bac1b93d-a497-462a-b22a-4789fa6d19b2
3
public static Matrix3D getRotationMatrix(double angle, int axis) { double cos = Math.cos(angle); double sin = Math.sin(angle); switch (axis) { case AXIS_X: return new Matrix3D(1, 0, 0, 0, cos, -sin, 0, sin, cos); case AXIS_Y: return new Matrix3D(cos, 0, sin, 0, 1, 0, -sin, 0, cos); case AXIS_Z: return new Matrix3D(cos, -sin, 0, sin, cos, 0, 0, 0, 1); default: throw new IllegalArgumentException( "Illegal Axis, must be AXIS_X, AXIS_Y or AXIS_Z"); } }
a5158256-ca25-46ed-8688-93bdc4b76b2f
7
private static void test2_4() throws FileNotFoundException { String test1 = "new game\n"+"examine room\n"+"quit\n"+"yes\n"; HashMap<Integer, String> output = new HashMap<Integer, String>(); boolean passed = true; try { in = new ByteArrayInputStream(test1.getBytes()); System.setIn(in); out = new PrintStream("testing.txt"); System.setOut(out); Game.main(null); } catch (ExitException se) { } catch (Exception e) { System.setOut(stdout); System.out.println("Error: "); e.printStackTrace(); passed = false; } finally { System.setOut(stdout); @SuppressWarnings("resource") Scanner sc = new Scanner(new File("testing.txt")); ArrayList<String> testOutput = new ArrayList<String>(); while (sc.hasNextLine()) { testOutput.add(sc.nextLine()); } output.put(testOutput.size() - 6, ">> The prison cell is a cold, dirty place."); output.put(testOutput.size() - 5, "The only light in the room filters through the bars in the cell door."); output.put(testOutput.size() - 4, "On the ground there is a: cell key."); output.put(testOutput.size() - 3, "The guard walks toward your cell."); output.put(testOutput.size() - 2, ">> Are you sure you want to quit? (y/n)"); output.put(testOutput.size() - 1, ">>"); if (passed) { for (Map.Entry<Integer, String> entry : output.entrySet()) { if (!testOutput.get(entry.getKey()) .equals(entry.getValue())) { passed = false; System.out.println("test2_4 failed: Line " + entry.getKey()); System.out.println("\tExpected: " + entry.getValue()); System.out.println("\tReceived: " + testOutput.get(entry.getKey())); } } if (passed) { System.out.println("test2_4 passed"); } } else { System.out.println("test2_4 failed: error"); } } }
23e72260-b1ca-4e50-b8da-e40b48f682e5
3
public ButtonPanel () { super (null); try { background = ImageIO.read (new File ("LoLTeamBuilder" + File.separator + "images" + File.separator + "button_background.png")); } catch (IOException e) { e.printStackTrace(); } Dimension size = new Dimension (1000, 94); setPreferredSize (size); setMaximumSize (size); lockButton = new LockButton(); lockButton.setBounds (777, 24, 177, 48); add (lockButton); for (Strategy s : Strategy.values()) { TacticButton tb = new TacticButton (s.toString(), s.getIcon (false)); tacticButtons [s.ordinal()] = tb; tb.setBounds (46 + 127 * s.ordinal(), 27, 120, 41); add (tb); } for (TacticButton tb : tacticButtons) { add (tb); } setBorder (new EmptyBorder (5, 5, 5, 5)); }
4e779409-3c49-4fe0-b2c5-641d6b7e3b63
3
public void update() { for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { Tile current = board[row][col]; if (current == null) continue; current.update(); resetPosition(current, row, col); } } }
617e65ab-f770-4777-9085-b3e8aebe149c
3
private ArrayList methodParams(final MethodEditor method) { final ArrayList locals = new ArrayList(); int index = 0; if (!method.isStatic()) { // Add the this pointer to the locals. final Type type = method.declaringClass().type(); final LocalVariable var = method.paramAt(index++); locals.add(new LocalExpr(var.index(), type)); } final Type[] paramTypes = method.type().indexedParamTypes(); for (int i = 0; i < paramTypes.length; i++) { if (paramTypes[i] != null) { final LocalVariable var = method.paramAt(index); locals.add(new LocalExpr(var.index(), paramTypes[i])); } index++; } return locals; }
374c25f4-1d8c-4570-beec-e023d6d596a0
4
@Override public void itemStateChanged(ItemEvent e) { if (e.getSource() == easy && e.getStateChange() == ItemEvent.SELECTED) { whatIsDifficulty = 0; } if (e.getSource() == hard && e.getStateChange() == ItemEvent.SELECTED) { whatIsDifficulty = 1; } }
4f030f91-f769-405d-9be8-17eeb9776d91
9
private void initTimeline() { timeline = new Timeline(); timeline.setCycleCount(Timeline.INDEFINITE); KeyFrame kf = new KeyFrame(Config.ANIMATION_TIME, new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { if (state == STATE_SHOW_TITLE) { stateArg++; int center = Config.SCREEN_WIDTH / 2; int offset = (int)(Math.cos(stateArg / 4.0) * (40 - stateArg) / 40 * center); brick.setTranslateX(center - brick.getImage().getWidth() / 2 + offset); breaker.setTranslateX(center - breaker.getImage().getWidth() / 2 - offset); if (stateArg == 40) { stateArg = 0; state = STATE_SHOW_STRIKE; } return; } if (state == STATE_SHOW_STRIKE) { if (stateArg == 0) { strike.setTranslateX(breaker.getTranslateX() + brick.getImage().getWidth()); strike.setScaleX(0); strike.setScaleY(0); strike.setVisible(true); } stateArg++; double coef = stateArg / 30f; brick.setTranslateX(breaker.getTranslateX() + (breaker.getImage().getWidth() - brick.getImage().getWidth()) / 2f * (1 - coef)); strike.setScaleX(coef); strike.setScaleY(coef); strike.setRotate((30 - stateArg) * 2); if (stateArg == 30) { stateArg = 0; state = STATE_SUN; } return; } // Here state == STATE_SUN if (pressanykey.getOpacity() < 1) { pressanykey.setOpacity(pressanykey.getOpacity() + 0.05f); } stateArg--; double x = SUN_AMPLITUDE_X * Math.cos(stateArg / 100.0); double y = SUN_AMPLITUDE_Y * Math.sin(stateArg / 100.0); if (y < 0) { for (Node node : NODES_SHADOWS) { // Workaround RT-1976 node.setTranslateX(-1000); } return; } double sunX = Config.SCREEN_WIDTH / 2 + x; double sunY = Config.SCREEN_HEIGHT / 2 - y; sun.setTranslateX(sunX - sun.getImage().getWidth() / 2); sun.setTranslateY(sunY - sun.getImage().getHeight() / 2); sun.setRotate(-stateArg); for (int i = 0; i < NODES.length; i++) { NODES_SHADOWS[i].setOpacity(y / SUN_AMPLITUDE_Y / 2); NODES_SHADOWS[i].setTranslateX(NODES[i].getTranslateX() + (NODES[i].getTranslateX() + NODES[i].getImage().getWidth() / 2 - sunX) / 20); NODES_SHADOWS[i].setTranslateY(NODES[i].getTranslateY() + (NODES[i].getTranslateY() + NODES[i].getImage().getHeight() / 2 - sunY) / 20); } } }); timeline.getKeyFrames().add(kf); }
b7b94846-8bf2-4916-9900-0c8158ba57b4
3
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Plan other = (Plan) obj; /* * Not sure why, but the favourite flag differs between raw plan and expanded plan. * That is, "plan/DMW-MOBILEMAGICSERVICES" yields isFavourite = false, * but same key via "project?favourite&expand=projects.project.plans.plan" yields isFavourite = true. */ return new EqualsBuilder() .append(this.key, other.key) .append(this.name, other.name) .append(this.avgBuildTime, other.avgBuildTime) .append(this.active, other.active) .append(this.building, other.building) .append(this.enabled, other.enabled) .append(this.expandType, other.expandType) // .append(this.favourite, other.favourite) .append(this.stages, other.stages) .isEquals(); }
7c1dc2f7-e151-4fe2-8e3f-20cbf52fc3c2
1
private void start() { player.playTrack(TrackType.START); while (player.isPlaying()) { } timer = new Timer(TURN_DURATION, this); timer.start(); }
054af135-751b-4e13-b41c-c86a7fb620b8
3
@Override public boolean isCompleteMatch(List<Character> currentMatching) { if(currentMatching.size() != 2) return false; if(currentMatching.get(0) != KeyMappingProfile.ESC_CODE) return false; if(currentMatching.get(1).charValue() > 26) return false; return true; }
b0844372-e019-4335-a9f7-8debd7a0b0b7
1
private void copyRandom(RandomListNode headNew, RandomListNode head) { while(head != null){ headNew.random = (RandomListNode) map.get(head.random); head = head.next; headNew = headNew.next; } }
6b19272f-140b-459f-a244-dcf289827915
1
public String getNumberFormatParse() { NumberFormat nf = NumberFormat.getInstance(); Object obj = null; try { obj = nf.parse("1234,56"); } catch (Exception e) { System.out.println(e.getMessage()); } return (obj.toString()); }
fcba1ea4-3d51-4486-a01c-03662e93ad88
1
public static UsersReader getInstance() throws IOException { if (instance == null) instance = new UsersReader(); return instance; }
477e97a1-e41c-4ec1-a7d6-35bca5c5b334
4
@Test public void getFutureMeetingListPerContactSortedTest() { contacts2 = generateListOfContacts2(); Contact c = null; Calendar may25_1430=Calendar.getInstance(); Calendar may25=Calendar.getInstance(); may25_1430.set(2014, Calendar.MAY, 25, 14, 30); may25.set(2014, Calendar.MAY, 25); contactManager.addFutureMeeting(contacts2, may252014); contactManager.addFutureMeeting(contacts2, april302014); contactManager.addFutureMeeting(contacts2,may25_1430); for (Contact curr : contacts2) { if (curr.getName().equals("Jamie Jones")) { c = curr; } } List<Meeting> meetingsJamie = contactManager.getFutureMeetingList(c); Meeting prev = null; for (Meeting curr : meetingsJamie) { if (prev != null) { assertTrue(curr.getDate().compareTo(prev.getDate()) > 0); } prev = curr; } }
ede5070e-0305-4177-a5c8-3b596f6100d5
8
@Override public void serialize(T t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { jg.writeStartObject(); if (t.getId() != null) { jg.writeStringField("id", t.getId().toString()); } Set<TKey<?, ?>> keys = t.getAvailableKeys(); for (TKey<?, ?> key : keys) { List<QualifiedValue<?>> values = t.getQualifiedValues(key); if (factory.getRegistry().isUniqueValueKey(key)) { serializeUniqueNode(jg, key, values, sp); } else { serializeArrayNode(jg, key, values, sp); } } jg.writeEndObject(); }
0c1cac53-b657-4084-8aa5-4fea1d7adea2
4
protected void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String error = "Unsuccessful purchase"; HttpSession session = req.getSession(true); if (session.getAttribute("currentSessionUser") == null) { res.sendRedirect("login"); } else { try { String card = (String)req.getParameter("cardNumber"); card = card.replace(" ", ""); card = card.replace("-", ""); // Simple card check if the length of the card is 16 digits if ( card.length() != 16 ) { req.setAttribute("result", error); throw new NumberFormatException(); } else { // Also checks if the string is actually a number Long.parseLong(card); int uid = (int)((User)session.getAttribute("currentSessionUser")).getId(); List<Order> cart = new ArrayList<Order>(OrderDAO.list(uid)); for (Order l : cart) { SaleDAO.add((long)uid, (long)ProductDAO.find("name", l.getName()).getId(), l.getAmount(), (int)l.getPrice()); } req.setAttribute("Descartes", cart); /*HashMap<Product,Integer> map = (HashMap<Product,Integer>)session.getAttribute("cart"); for (Map.Entry<Product, Integer> cartList : map.entrySet()) { User current = (User)session.getAttribute("currentSessionUser"); SaleDAO.add(current.getId(),cartList.getKey().getId(),cartList.getValue(),cartList.getKey().getPrice()); }*/ //session.setAttribute("cart", null); OrderDAO.delete(uid); req.getRequestDispatcher("buyConfirm.jsp").forward(req, res); } } catch (NumberFormatException | SQLException e) { e.printStackTrace(); req.setAttribute("result", error); req.getRequestDispatcher("buyConfirm.jsp").forward(req, res); } } }
e7436290-3150-4cd4-b7dd-7a1b3bb46b33
8
public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox) { if (averageGroundLevel < 0) { averageGroundLevel = getAverageGroundLevel(par1World, par3StructureBoundingBox); if (averageGroundLevel < 0) { return true; } boundingBox.offset(0, (averageGroundLevel - boundingBox.maxY) + 3, 0); } fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 1, 4, 12, 4, Block.cobblestone.blockID, Block.waterMoving.blockID, false); placeBlockAtCurrentPosition(par1World, 0, 0, 2, 12, 2, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, 0, 0, 3, 12, 2, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, 0, 0, 2, 12, 3, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, 0, 0, 3, 12, 3, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 1, 13, 1, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 1, 14, 1, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 4, 13, 1, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 4, 14, 1, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 1, 13, 4, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 1, 14, 4, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 4, 13, 4, par3StructureBoundingBox); placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, 4, 14, 4, par3StructureBoundingBox); fillWithBlocks(par1World, par3StructureBoundingBox, 1, 15, 1, 4, 15, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false); for (int i = 0; i <= 5; i++) { for (int j = 0; j <= 5; j++) { if (j == 0 || j == 5 || i == 0 || i == 5) { placeBlockAtCurrentPosition(par1World, Block.gravel.blockID, 0, j, 11, i, par3StructureBoundingBox); clearCurrentPositionBlocksUpwards(par1World, j, 12, i, par3StructureBoundingBox); } } } return true; }
63eb9878-e833-40ee-bed4-622a77d332f0
1
private void calculatePrefixCode(PrefixTreeNode t, String s) { if (t instanceof PrefixTreeLeaf) { code.put(((PrefixTreeLeaf)t).letter, s); return; } calculatePrefixCode(((PrefixTreeNode) t).left, s + '0'); calculatePrefixCode(((PrefixTreeNode) t).right, s + '1'); }
a2dc89d4-ee52-4081-93f9-7052348ebd05
3
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf8"); InvertedIndex.tryInit(getServletContext()); String userRequest = req.getParameter("q"); ArrayList<String> urs = tokenize(userRequest); try { SearchResponse sr = InvertedIndex.getInstance().search(urs); int found = sr.getWordIndex() == null ? 0 : sr.getWordIndex().getTotalOccurrencesAmount(); req.setAttribute("q", userRequest); req.setAttribute("chw", sr.getWordIndex()); if (found > 0) { logger.info(String.format(fmtSucc, userRequest, sr.getWordIndex().getTotalOccurrencesAmount())); } else { logger.warn(String.format(fmtNotFound, userRequest)); } } catch (Exception e) { logger.error(String.format(fmtError, userRequest, e.getMessage())); e.printStackTrace(); } req.getRequestDispatcher("search.jsp").forward(req, resp); }