method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
ccbb0d63-1783-4d08-a878-09294dff5b23
6
public void moveLeft() { Boolean ableToMove = true; for (Block b : currentTetromino.getBlocks()) { if ((b.getMapIndexX() == 0) || (tetrisMap[b.getMapIndexX() - 1][b.getMapIndexY()] == 1)) { ableToMove = false; } } if (ableToMove) { for (Block b : currentTetromino.getBlocks()) { tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = 0; } for (Block b : currentTetromino.getBlocks()) { b.translateLeft(); tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = currentTetromino .getKey(); } } notifyObservers(); }
4f9807b0-eb6e-4434-bb4b-d40b6489cf26
1
public void setStatic(final boolean flag) { int modifiers = classInfo.modifiers(); if (flag) { modifiers |= Modifiers.STATIC; } else { modifiers &= ~Modifiers.STATIC; } classInfo.setModifiers(modifiers); this.setDirty(true); }
f1ab6466-f260-4974-a4a7-853eab6b49cb
9
@SuppressWarnings("unchecked") public static ValuesReader createValuesReader(ValuesEntry valuesEntry){ Properties unisensProperties = UnisensProperties.getInstance().getProperties(); String readerClassName = unisensProperties.getProperty(Constants.VALUES_READER.replaceAll("format", valuesEntry.getFileFormat().getFileFormatName().toLowerCase())); if(readerClassName != null){ try{ Class<ValuesReader> readerClass = (Class<ValuesReader>)Class.forName(readerClassName); Constructor<ValuesReader> readerConstructor = readerClass.getConstructor(ValuesEntry.class); return readerConstructor.newInstance(valuesEntry); } catch (ClassNotFoundException e) { System.out.println("Class (" + readerClassName + ") could not be found!"); e.printStackTrace(); } catch (InstantiationException e) { System.out.println("Class (" + readerClassName + ") could not be instantiated!"); e.printStackTrace(); } catch (IllegalAccessException e) { System.out.println("Class (" + readerClassName + ") could not be accessed!"); e.printStackTrace(); } catch (ClassCastException ec) { ec.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; }
0c437853-599d-4dc9-84e5-0f80c7aac6ed
0
public void setErrorLog(LogFile errorLog) {this.errorLog = errorLog;}
c534b9b3-dcab-4461-bbc7-408788ffb582
4
private boolean setupSQL() { if (config.getSQLValue().equalsIgnoreCase("MySQL")) { dop = new MySQLOptions(config.getHostname(), config.getPort(), config.getDatabase(), config.getUsername(), config.getPassword()); } else if (config.getSQLValue().equalsIgnoreCase("SQLite")) { dop = new SQLiteOptions(new File(getDataFolder() + "/game_data.db")); } else { sendErr("Enders Game cannot enable because the SQL is set to " + config.getSQLValue()); return false; } sql = new SQL(this, dop); try { if (!sql.open()) return false; sql.createTable("CREATE TABLE IF NOT EXISTS signs (gameid INT(10), coordX INT(15), coordY INT(15), coordZ INT(15), world VARCHAR(255))"); sql.createTable("CREATE TABLE IF NOT EXISTS games (gameid INT(10), lobbyid INT(10), x1 INT(15), y1 INT(15), z1 INT(15), x2 INT(15), y2 INT(15), z2 INT(15), world VARCHAR(255), gamestage VARCHAR(50))"); sql.createTable("CREATE TABLE IF NOT EXISTS lobbies (lobbyid INT(10), x1 INT(15), y1 INT(15), z1 INT(15), x2 INT(15), y2 INT(15), z2 INT(15), world VARCHAR(255))"); sql.createTable("CREATE TABLE IF NOT EXISTS gamespawns (gameid INT(10), x1 INT(15), y1 INT(15), z1 INT(15), x2 INT(15), y2 INT(15), z2 INT(15), world VARCHAR(255))"); sql.createTable("CREATE TABLE IF NOT EXISTS lobbyspawns (lobbyid INT(10), coordX INT(15), coordY INT(15), coordZ INT(15), world VARCHAR(255))"); } catch (SQLException e) { e.printStackTrace(); return false; } return true; }
98b0fa82-22ff-4a93-b742-c649bfbf9266
9
public static boolean scrapeInfo(String url) { String[][] table = null; int firstRealRow = 0; boolean firstRealRowInitialized = false; try { Document doc = Jsoup.connect(url).get(); Elements tableElements = doc.select("table"); Elements tableRowElements = tableElements.select(":not(thead) tr"); System.out.println("Rows: " + tableRowElements.size()); table = new String[tableRowElements.size()][8]; for (int r = 0; r < tableRowElements.size(); r++) { System.out.println("Row loop: " + r); Element row = tableRowElements.get(r); Elements rowItems = row.select("td"); if (rowItems.get(1).text().contains("AM") || rowItems.get(1).text().contains("PM")) { if (!firstRealRowInitialized) { firstRealRow = r; table = new String[tableRowElements.size() - firstRealRow][9]; firstRealRowInitialized = true; } table[r - firstRealRow][0] = rowItems.get(0).text(); table[r - firstRealRow][1] = rowItems.get(2).text(); table[r - firstRealRow][2] = rowItems.get(3).text(); table[r - firstRealRow][3] = rowItems.get(4).text(); table[r - firstRealRow][4] = rowItems.get(5).text(); table[r - firstRealRow][5] = rowItems.get(6).text(); table[r - firstRealRow][6] = rowItems.get(7).text(); String s = rowItems.get(1).text(); String time = s.substring(s.indexOf(":") - 3, s.indexOf(":") + 6); time = time.replaceAll("-", " "); time = time.trim(); table[r - firstRealRow][7] = time; } } csvSchedule.delete(); csvSchedule.createNewFile(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvSchedule))) { System.out.println(writer); for (String[] row : table) { for (int i = 0; i < row.length; i++) { if (row[i] == null) { break; } writer.write(row[i]); if (i < 8) { writer.write(","); } } writer.newLine(); } writer.flush(); } } catch (IOException ex) { Logger.getLogger(StartupSequence.class.getName()).log(Level.SEVERE, null, ex); return false; } return true; }
3f0129cd-f97a-48b4-b32d-70199a0bf5d1
0
public void setH(float h) { this.h = h; }
27fb0613-28c0-41eb-a526-56d6cd2e3e70
2
public void addNewScore(Score newScore) { int newScorePoints = newScore.getPoints(); // jesli ostatni wynik jest lepszy, na pewno nie dodajemy if (!isHighScore(newScorePoints)) { return; } // wynik na pewno wyzszy niz ostatni int i = 0; // znajdywanie pierwszego mniejszego wyniku while (newScorePoints <= listaWynikow.get(i).getPoints()) { ++i; // indeksu nie pilnujemy bo na pewno miescimy sie w tabeli } listaWynikow.add(i, newScore); }
b92b5f37-1382-4bda-ac5d-10a23d619a93
4
public BildanalysGUI(final IARDrone drone) { super("YADrone Paper Chase"); this.imageAnalyser = new ImageAnalyser(); this.drone = drone; setSize(TagAlignment.IMAGE_WIDTH, TagAlignment.IMAGE_HEIGHT); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //drone.stop(); //System.exit(0); } }); contentPane = new JPanel() { public void paint(Graphics g) { if (image != null) { g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); g.setColor(Color.RED); // g.setColor(Color.RED); // g.drawRect(test[0], test[1], test[2] - test[0], test[3] - test[1]); // draw tolerance field // g.setColor(Color.RED); int imgCenterX = TagAlignment.IMAGE_WIDTH / 2; int imgCenterY = TagAlignment.IMAGE_HEIGHT / 2; int tolerance = TagAlignment.TOLERANCE; /*g.drawPolygon(new int[] {imgCenterX-tolerance, imgCenterX+tolerance, imgCenterX+tolerance, imgCenterX-tolerance}, new int[] {imgCenterY-tolerance, imgCenterY-tolerance, imgCenterY+tolerance, imgCenterY+tolerance}, 4); */ if (result != null) { ResultPoint[] points = result.getResultPoints(); ResultPoint a = points[1]; // top-left ResultPoint b = points[2]; // top-right ResultPoint c = points[0]; // bottom-left ResultPoint d = points.length == 4 ? points[3] : points[0]; // alignment point (bottom-right) g.setColor(Color.GREEN); g.drawPolygon(new int[] {(int)a.getX(),(int)b.getX(),(int)d.getX(),(int)c.getX()}, new int[] {(int)a.getY(),(int)b.getY(),(int)d.getY(),(int)c.getY()}, 4); g.setColor(Color.RED); g.setFont(font); g.drawString(result.getText(), (int)a.getX(), (int)a.getY()); g.drawString(orientation, (int)a.getX(), (int)a.getY() + 20); if ((System.currentTimeMillis() - result.getTimestamp()) > 1000) { result = null; } } } else { g.drawString("Waiting for Video ...", 10, 20); } } }; setContentPane(contentPane); }
b32f3a13-715d-4632-8e0a-414466ce751d
1
public MainWindow(int sizeX, int sizeY) throws Exception{ if(!frameCount){ this.sizeX = 3*sizeX; this.sizeY = 3*sizeY; frameCount = true; } else throw new Exception("Apllication is already started!"); }
59bdb7be-9588-4c71-9537-0fce378c4669
1
@Override public void update(GameContainer gc, int d) throws SlickException { for (TileMapLayer tileMapLayer : getLayersOrderedByImportance()) { tileMapLayer.update(gc, d); } }
a8084f7b-deef-4a7d-8d26-1dedb6e36127
1
public CompareToIntOperator(Type type, boolean greaterOnNaN) { super(Type.tInt, 0); compareType = type; this.allowsNaN = (type == Type.tFloat || type == Type.tDouble); this.greaterOnNaN = greaterOnNaN; initOperands(2); }
e7fb7991-28be-4da3-8b5b-c23162bf2dc1
8
public void buildClassifier(Instances data) throws Exception{ //heuristic to avoid cross-validating the number of LogitBoost iterations //at every node: build standalone logistic model and take its optimum number //of iteration everywhere in the tree. if (m_fastRegression && (m_fixedNumIterations < 0)) m_fixedNumIterations = tryLogistic(data); //Need to cross-validate alpha-parameter for CART-pruning Instances cvData = new Instances(data); cvData.stratify(m_numFoldsPruning); double[][] alphas = new double[m_numFoldsPruning][]; double[][] errors = new double[m_numFoldsPruning][]; for (int i = 0; i < m_numFoldsPruning; i++) { //for every fold, grow tree on training set... Instances train = cvData.trainCV(m_numFoldsPruning, i); Instances test = cvData.testCV(m_numFoldsPruning, i); buildTree(train, null, train.numInstances() , 0); int numNodes = getNumInnerNodes(); alphas[i] = new double[numNodes + 2]; errors[i] = new double[numNodes + 2]; //... then prune back and log alpha-values and errors on test set prune(alphas[i], errors[i], test); } //build tree using all the data buildTree(data, null, data.numInstances(), 0); int numNodes = getNumInnerNodes(); double[] treeAlphas = new double[numNodes + 2]; //prune back and log alpha-values int iterations = prune(treeAlphas, null, null); double[] treeErrors = new double[numNodes + 2]; for (int i = 0; i <= iterations; i++){ //compute midpoint alphas double alpha = Math.sqrt(treeAlphas[i] * treeAlphas[i+1]); double error = 0; //compute error estimate for final trees from the midpoint-alphas and the error estimates gotten in //the cross-validation for (int k = 0; k < m_numFoldsPruning; k++) { int l = 0; while (alphas[k][l] <= alpha) l++; error += errors[k][l - 1]; } treeErrors[i] = error; } //find best alpha int best = -1; double bestError = Double.MAX_VALUE; for (int i = iterations; i >= 0; i--) { if (treeErrors[i] < bestError) { bestError = treeErrors[i]; best = i; } } double bestAlpha = Math.sqrt(treeAlphas[best] * treeAlphas[best + 1]); //"unprune" final tree (faster than regrowing it) unprune(); //CART-prune it with best alpha prune(bestAlpha); cleanup(); }
50d32fc4-fbbb-4acf-b642-6e8419caa909
4
public void newBoard() { hlight = new boolean[8][8]; int[] back = {2, 3, 4, 6, 5, 4, 3, 2}; int[] pawns = {1, 1, 1, 1, 1, 1, 1, 1}; Piece[] wback, wpawns, bpawns, bback; wback = new Piece[8]; wpawns = new Piece[8]; bpawns = new Piece[8]; bback = new Piece[8]; for (int i = 0; i < board[0].length; i++) { bback[i] = create_piece(back[i], false, 0, i); } for (int i = 0; i < board[0].length; i++) { bpawns[i] = create_piece(pawns[i], false, 1, i); } for (int i = 0; i < board[0].length; i++) { wpawns[i] = create_piece(pawns[i], true, 6, i); } for (int i = 0; i < board[0].length; i++) { wback[i] = create_piece(back[i], true, 7, i); } Pwhite = concat(wback, wpawns); Pblack = concat(bback, bpawns); board[0] = bback; board[1] = bpawns; board[6] = wpawns; board[7] = wback; }
4ba8c2a2-3e76-42a3-93e8-7ac00a4369ce
9
private float getFloat(byte[] b) { float sample = 0.0f; int ret = 0; int length = b.length; for (int i = 0; i < b.length; i++, length--) { ret |= ((int) (b[i] & 0xFF) << ((((bigEndian) ? length : (i + 1)) * 8) - 8)); } switch (sampleSize) { case 1: if (ret > 0x7F) { ret = ~ret; ret &= 0x7F; ret = ~ret + 1; } sample = (float) ((float) ret / (float) Byte.MAX_VALUE); break; case 2: if (ret > 0x7FFF) { ret = ~ret; ret &= 0x7FFF; ret = ~ret + 1; } sample = (float) ((float) ret / (float) Short.MAX_VALUE); break; case 3: if (ret > 0x7FFFFF) { ret = ~ret; ret &= 0x7FFFFF; ret = ~ret + 1; } sample = (float) ((float) ret / 8388608f); break; case 4: sample = (float) ((double) ret / (double) Integer.MAX_VALUE); break; default: System.err.println("Format not accepted"); } return sample; }
2909e9ca-42a6-4cb4-afa3-a5f27a2422cc
1
@Override protected void finalize() throws Throwable { try { this.stop(); } catch (Exception exc) { } finally { super.finalize(); } }
bd5268bb-0c26-4ed6-b8f6-bc43f3d132eb
3
public void setPan( float p ) { // Make sure there is a pan control if( panControl == null ) return; float pan = p; // make sure the value is valid (between -1 and 1) if( pan < -1.0f ) pan = -1.0f; if( pan > 1.0f ) pan = 1.0f; // Update the pan: panControl.setValue( pan ); }
6dcb997f-df42-4517-b0cd-93b1c8355f0d
6
protected void startRelease(){ while(true){ if(this.count > this.singleConfig.getMinConns()){ Conn conn = this.pool.poll(); if(conn.getCurrentMinis() !=null && this.singleConfig.getMaxFreeInterval() != null && (System.currentTimeMillis() - conn.getCurrentMinis() > this.singleConfig.getMaxFreeInterval())){ } } try{ this.releaseThread.sleep(200); }catch(InterruptedException e){ e.printStackTrace(); } } }
6fb5dc14-7cfa-4925-9f23-c85c497c4b3a
4
public Properties load() { final Properties settings = new Properties(); FileReader fr = null; try { fr = new FileReader(settingsFile); settings.load(fr); } catch (FileNotFoundException ignored) { } catch (IOException e) { e.printStackTrace(); } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } return settings; }
4ec8dfc5-ec2d-4232-9d68-e4e99200568d
5
public Packet unpackPacket(SocketAddress address, short id, byte[] data) { if (!packets.containsKey(id)) { throw new IllegalArgumentException("Received unknown packet with id: " + id); } Class<? extends Packet> packetClass = packets.get(id); Constructor<? extends Packet> constructor; try { constructor = packetClass.getConstructor(SocketAddress.class, byte[].class); } catch (NoSuchMethodException e) { throw new RuntimeException("Packet " + packetClass.toString() + " does not implement a correct constructor!", e); } Packet packet; try { packet = constructor.newInstance(address, data); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new InternalError("Error while instantiating packet " + packetClass.toString() + ": " + e.getMessage()); } return packet; }
62d02e0e-6535-4d26-afb6-65b2336ed40a
9
protected static Ptg calcComplex( Ptg[] operands ) { if( operands.length < 2 ) { return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "Complex" ); int real = operands[0].getIntVal(); int imaginary = operands[1].getIntVal(); String suffix = "i"; if( operands.length > 2 ) { suffix = operands[2].getString().trim(); if( !(suffix.equals( "i" ) || suffix.equals( "j" )) ) { return new PtgErr( PtgErr.ERROR_VALUE ); } } String complexString = ""; // result: real + imaginary suffix // real - imaginary suffix // real (if imaginary==0) // real + suffix (if imaginary==1) // imaginary suffix (if (real==0) if( real != 0 ) { complexString = String.valueOf( real ); if( imaginary > 0 ) { complexString += " + "; } } if( imaginary != 0 ) { complexString += ((Math.abs( imaginary ) != 1) ? String.valueOf( imaginary ) : "") + suffix; } if( complexString.equals( "" ) ) { complexString = "0"; } PtgStr pstr = new PtgStr( complexString ); log.debug( "Result from COMPLEX= " + pstr.getString() ); return pstr; }
95d80700-da13-438e-a031-97187f468f8d
0
@Override public void add(String word) { internalStorage.add(word); }
2781fdb3-a28f-4dec-9cfe-caa4b2816b71
0
public InvalidBEncodingException(String message) { super(message); }
4ad7e91a-0ded-4c02-bb6e-81907efdb5d2
6
@EventHandler public void WitchHunger(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getWitchConfig().getDouble("Witch.Hunger.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getWitchConfig().getBoolean("Witch.Hunger.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getWitchConfig().getInt("Witch.Hunger.Time"), plugin.getWitchConfig().getInt("Witch.Hunger.Power"))); } }
4ceb7611-b56e-411a-b04b-302b61b572a9
1
public static void main(String[] args) throws Exception { String tmp = "abcdef"; char[] ch = new char[tmp.length()]; tmp.getChars(0, tmp.length(), ch,0); CharArrayReader input = new CharArrayReader(ch); int i; while (-1 != (i = input.read())) { System.out.println((char)i); } }
62188070-57ad-4e3c-b728-4eeebdaed971
1
public void Open() throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } }
27f2fda4-d828-441d-9e9a-e00cfc76098a
1
@RequestMapping(value = "/createEntity", method = RequestMethod.POST) public ModelAndView saveEntity( final HttpServletRequest request, final HttpServletResponse response, @Valid @ModelAttribute("entityForm") final EntityForm entityForm, final BindingResult bindingResult) { if (bindingResult.hasErrors()) { ModelAndView model = new ModelAndView("create-entity"); model.addObject("entityForm", entityForm); return model; } entityMapper.create(entityForm.fillModel()); return new ModelAndView("success"); }
a7d5744d-f39b-439c-a415-9535ea8f3284
3
private void scanArchives() throws IOException { for(File temp : LOLFOLDER.listFiles()) { ArrayList<RAFFile> list = new ArrayList<RAFFile>(); for(File file : temp.listFiles()) { if(file.getName().endsWith(".raf")) { list.add(new RAFFile(file.getAbsolutePath())); } } archives.put(temp.getName(),list); } }
b1a2c897-7d7a-486f-ad6c-21b5c98ddbbf
0
public SimpleThread() { super(Integer.toString(++threadCount)); start(); }
518090cf-3724-4343-b4a5-70022dae76b0
7
private void splitIrreducibleLoops() { db(" Splitting irreducible loops"); final List removeEdges = new LinkedList(); Iterator iter = nodes().iterator(); // Iterate over all the blocks in this cfg. If a block could be // the header of a reducible loop (i.e. it is the target of a // "reducible backedge", a backedge for which its destination // dominates its source), the block is to be split. All // "irreducible backedges" are placed in a list and will be used // to insert an empty block so that the number of reducible loop // headers is maximize. while (iter.hasNext()) { final Block w = (Block) iter.next(); boolean hasReducibleBackIn = false; final Set otherIn = new HashSet(); final Iterator preds = preds(w).iterator(); while (preds.hasNext()) { final Block v = (Block) preds.next(); if (w.dominates(v)) { // (v,w) is a reducible back edge. hasReducibleBackIn = true; } else { otherIn.add(v); } } if (hasReducibleBackIn && (otherIn.size() > 1)) { final Iterator e = otherIn.iterator(); while (e.hasNext()) { final Block v = (Block) e.next(); removeEdges.add(new Block[] { v, w }); } } } // Split the irreducible back edges. iter = removeEdges.iterator(); while (iter.hasNext()) { final Block[] edge = (Block[]) iter.next(); splitEdge(edge[0], edge[1]); } }
fccab4d3-9eb8-4223-b6ec-d7a61ef58ae3
3
public boolean isCaveBG(int blockTypeId) { boolean isCave = false; if(blockTypeId > 0) { BlockType bt = blockManager.getBlockTypeById((short)blockTypeId); if(bt != null && bt.isBackground()) { isCave = true; } } return isCave; }
fb5b1756-a629-48a4-bf87-fe42e45b8c29
3
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((age == null) ? 0 : age.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }
054906b5-104c-4320-8066-6770e6478277
7
public double computePartialTruth(QueryIterator query) { { IncrementalPartialMatch self = this; { ControlFrame baseframe = query.baseControlFrame; PartialMatchFrame partialmatchframe = query.partialMatchStrategy; FloatWrapper minimumscore = ((FloatWrapper)(query.options.lookup(Logic.KWD_MINIMUM_SCORE))); boolean maximizescoreP = !Stella_Object.eqlP(query.options.lookup(Logic.KWD_MAXIMIZE_SCOREp), Stella.FALSE_WRAPPER); double epsilon = 0.001; double latestscore = 0.0; double highestscore = 0.0; Justification bestjustification = null; if (partialmatchframe == null) { partialmatchframe = self; query.partialMatchStrategy = self; } partialmatchframe.dynamicCutoff = ((minimumscore != null) ? minimumscore.wrapperValue : epsilon); { Object old$Queryiterator$000 = Logic.$QUERYITERATOR$.get(); Object old$GenerateAllProofsP$000 = Logic.$GENERATE_ALL_PROOFSp$.get(); Object old$Inferencelevel$000 = Logic.$INFERENCELEVEL$.get(); Object old$ReversepolarityP$000 = Logic.$REVERSEPOLARITYp$.get(); try { Native.setSpecial(Logic.$QUERYITERATOR$, query); Native.setBooleanSpecial(Logic.$GENERATE_ALL_PROOFSp$, true); Native.setSpecial(Logic.$INFERENCELEVEL$, Logic.currentInferenceLevel()); Native.setBooleanSpecial(Logic.$REVERSEPOLARITYp$, false); loop000 : for (;;) { if (!(query.nextP())) { break loop000; } latestscore = partialmatchframe.positiveScore; if (latestscore <= highestscore) { break loop000; } bestjustification = ((Justification)(KeyValueList.dynamicSlotValue(baseframe.dynamicSlots, Logic.SYM_LOGIC_JUSTIFICATION, null))); highestscore = latestscore; partialmatchframe.dynamicCutoff = highestscore + epsilon; if ((!maximizescoreP) || TruthValue.knownTruthValueP(baseframe.truthValue)) { break loop000; } } } finally { Logic.$REVERSEPOLARITYp$.set(old$ReversepolarityP$000); Logic.$INFERENCELEVEL$.set(old$Inferencelevel$000); Logic.$GENERATE_ALL_PROOFSp$.set(old$GenerateAllProofsP$000); Logic.$QUERYITERATOR$.set(old$Queryiterator$000); } } KeyValueList.setDynamicSlotValue(baseframe.dynamicSlots, Logic.SYM_LOGIC_JUSTIFICATION, bestjustification, null); return (highestscore); } } }
8fa9b3db-9d92-4862-8a05-1f0e825ed29d
6
public EasyDate beginOf(int field) { switch (field) { case Calendar.YEAR: calendar.set(Calendar.MONTH, 0); case Calendar.MONTH: calendar.set(Calendar.DAY_OF_MONTH, 1); case Calendar.DAY_OF_MONTH: calendar.set(Calendar.HOUR_OF_DAY, 0); case Calendar.HOUR_OF_DAY: calendar.set(Calendar.MINUTE, 0); case Calendar.MINUTE: calendar.set(Calendar.SECOND, 0); case Calendar.SECOND: calendar.set(Calendar.MILLISECOND, 0); break; default: throw new IllegalArgumentException("无法识别的日期字段:" + field); } return this; }
5c96d128-4d31-490d-8e73-8adf1a56766b
2
public static void loadSpawns() throws SQLException{ @SuppressWarnings("unused") boolean newspawn = SpawnConfig.newspawn; ResultSet res =SQLManager.sqlQuery("SELECT * FROM BungeeSpawns WHERE spawnname='ProxySpawn'"); while( res.next() ){ ProxySpawn = new Location(res.getString("server"), res.getString("world"), res.getDouble("x"), res.getDouble("y"), res.getDouble("z"), res.getFloat("yaw"), res.getFloat("pitch")); } res.close(); res =SQLManager.sqlQuery("SELECT * FROM BungeeSpawns WHERE spawnname='NewPlayerSpawn'"); while( res.next() ){ NewPlayerSpawn = new Location(res.getString("server"), res.getString("world"), res.getDouble("x"), res.getDouble("y"), res.getDouble("z"), res.getFloat("yaw"), res.getFloat("pitch")); } res.close(); }
ee92b28d-b46d-4480-8364-6aed07804657
2
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeath(PlayerDeathEvent event) { if(plugin.playerIsAffected(event.getEntity().getPlayer())) // TODO this will trigger, regardless of the death cause. Should be checking if player died from coldDamage! { // TODO make maxJailDuration function. Finally there will be more than one jail! // duration will become higher when a player dies more often. if(Arctica.minJailDuration > 0) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), "tjail " + event.getEntity().getPlayer().getName() + " " + Arctica.jailName + " " + Arctica.minJailDuration + "m"); } } }
b453e30c-bea8-419d-86eb-f7eb41fe91cb
2
private void doCheckUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String userName = StringUtil.toString(request.getParameter("userName")); ObjectMapper mapper = new ObjectMapper(); Map result = new HashMap(); try { User user = manager.findUserByColumnName(userName,"name"); result.put("success",true); if(user == null) { result.put("success",false); } } catch (SQLException e) { result.put("success",false); logger.error("check user 失败", e); }finally { String out =mapper.writeValueAsString(result); PrintWriter pw = response.getWriter(); pw.print(out); } }
046ad596-2891-4080-bd86-8f8da0e32130
1
public static void setPointLight(PointLight[] pointLights) { if(pointLights.length > MAX_POINT_LIGHTS) { System.err.println("Error: You passed in too many point lights. Max allowed is " + MAX_POINT_LIGHTS + ", you passed in " + pointLights.length); new Exception().printStackTrace(); System.exit(1); } PhongShader.pointLights = pointLights; }
64f90a8a-8c09-48e2-bca0-6a64b128cdb3
9
public static void main(String[] args) { /* Set up configuration */ Utility.configure(); jobTrackerComm = new Communication(Utility.JOBTRACKER.ipAddress, Utility.JOBTRACKER.port); /* Register this task tracker */ System.out.println("Registering on job tracker..."); Message msg = new Message(Utility.TASKTRACKERREG); jobTrackerComm.sendMessage(msg); msg = jobTrackerComm.readMessage(); if (msg.getMsgType() == Utility.REGACK) { taskTrackerID = msg.getTaskTrackerID(); System.out.println("Successfully registered."); } /* Wait for incoming commands */ while (isRunning) { msg = jobTrackerComm.readMessage(); if (msg.getMsgType() == Utility.NEWJOB) { JobContext jobContext = msg.getJobContext(); String jobID = jobContext.getJobID().getID(); System.out.println("Receiced new job from job[" + jobID + "] tracker"); if (!jobContexts.containsKey(jobID)) { jobContexts.put(jobID, jobContext); } msg = new Message(Utility.NEWJOBACK); jobTrackerComm.sendMessage(msg); } else if (msg.getMsgType() == Utility.RUNMAPPER) { System.out.println("Received RUNMAPPER command from job tracker."); List<MapBasicContext> mapBasicContexts = msg.getMapContexts(); if (mapBasicContexts.size() != 0) { String jobID = mapBasicContexts.get(0).getJobID().getID(); JobContext jobContext = jobContexts.get(jobID); numMappers = mapBasicContexts.size(); launchMappers(jobContext, mapBasicContexts); } } else if (msg.getMsgType() == Utility.RUNREDUCER) { System.out.println("Received RUNREDUCER command from job tracker."); List<ReduceBasicContext> reduceBasicContexts = msg.getReduceContexts(); if (reduceBasicContexts.size() != 0) { String jobID = reduceBasicContexts.get(0).getJobID().getID(); JobContext jobContext = jobContexts.get(jobID); numReducers = reduceBasicContexts.size(); launchReducers(jobContext, reduceBasicContexts); } } else if (msg.getMsgType() == Utility.CLOSE) { isRunning = false; } } jobTrackerComm.close(); }
c39140df-30e6-4201-afb0-1e48e593940b
9
protected void handleSwitchEvent(SelectionKey key) { SocketChannel channel = (SocketChannel) key.channel(); OFSwitch sw = _channel2Switch.get(channel); OFMessageAsyncStream stream = sw.getStream(); try { // read events from the switches if(key.isReadable()) { List<OFMessage> messages = stream.read(); if(messages == null) { key.cancel(); _channel2Switch.remove(channel); return; } for(OFMessage message : messages) { switch(message.getType()) { case PACKET_IN: // leave to subclasses handlePacketIn(sw, (OFPacketIn) message); break; // simple events are handled here case HELLO: // System.out.println("GOT HELLO from " + sw); break; case ECHO_REQUEST: OFEchoReply reply = (OFEchoReply) stream.getMessageFactory() .getMessage(OFType.ECHO_REPLY); reply.setXid(message.getXid()); stream.write(reply); break; default: // System.out.println("Unhandled OF message: " + // message.getType() + " from " + // channel.socket().getInetAddress()); break; } } } // write if (key.isWritable()) { stream.flush(); } // Only register for R OR W, not both, to avoid stream deadlock key.interestOps(stream.needsFlush() ? SelectionKey.OP_WRITE : SelectionKey.OP_READ); } catch (IOException e) { // if we have an exception, disconnect the switch key.cancel(); _channel2Switch.remove(channel); } }
4286bd37-980b-47eb-bc77-6063fd701f7a
4
private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed try{ int numero = Integer.parseInt(txt1.getText()); if(numero>0){ Statement consulta = conexion(); try{ ResultSet resultado = consulta.executeQuery("SELECT * FROM tblproductos " + "WHERE Codigo="+numero); if(resultado.next()==true){ JOptionPane.showMessageDialog(null, "El archivo del Código " +numero+" fue eliminado correctamente"); consulta.executeQuery("DELETE FROM tblproductos " + "WHERE Codigo="+numero); }else{ JOptionPane.showMessageDialog(null, "El archivo del Codigo "+numero+" no se encontran datos"); } }catch(Exception e){} }else{ JOptionPane.showMessageDialog(null, "El valor deber ser un numero mayor a cero"); } }catch(NumberFormatException e){ JOptionPane.showMessageDialog(null, "Debe escribir un numero"); } }//GEN-LAST:event_btnEliminarActionPerformed
0e6c7a07-6f74-40ab-859c-e40a62b0f451
2
public void testgetPrefixWordsBadIndices() { Lexicon lex = new Lexicon(true, false, false, false, false, 0.0, 0.0, null); try { lex.getPrefixWords(iUtt, -1); fail("Should not allow negative indices"); } catch (RuntimeException e) {} try { lex.getPrefixWords(iUtt, 1); fail("Should not allow too high indices."); } catch (RuntimeException e) {} }
1ae3c8ce-d871-4b11-9238-f2c3344179c3
9
public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; _hashCode += getBatchFileId(); _hashCode += getBatchId(); if (getContent() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getContent()); i++) { Object obj = java.lang.reflect.Array.get(getContent(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } if (getContentType() != null) { _hashCode += getContentType().hashCode(); } if (getExt() != null) { _hashCode += getExt().hashCode(); } if (getFilePath() != null) { _hashCode += getFilePath().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } _hashCode += getSize(); _hashCode += getErrorCount(); __hashCodeCalc = false; return _hashCode; }
74c7359f-f54a-4b49-9f1a-5504b96208f1
0
public void register(TravelTrip travelTrip){ em.persist(travelTrip); return; }
b984fa7b-6b8c-4f43-ad93-b90080cc8277
4
public void CheckWildrange(int pcombat) { if(((combat + WildyLevel >= pcombat) && (pcombat >= combat)) || ((combat - WildyLevel <= pcombat) && (pcombat <= combat))) { InWildrange = true; } else { InWildrange = false; } }
da2d42f8-a7da-418e-8286-bef40b2b6727
9
private void btn_calculateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_calculateActionPerformed // declare the two main variables used in exponuntiation float base = Float.parseFloat(txt_base.getText()); float exponent = Float.parseFloat(txt_exponent.getText()); txt_output.setText(""); // clear the output area // if exponent is positive go from an exponent of 0 to the exponent entered if(exponent >= 0){ if(Math.round(exponent) == exponent){ for (int n = 0; n <= exponent; n++){ txt_output.append(base + " to the exponent " + n + " = " + pow(base, n) + "\n"); } } else { String t = Float.toString(exponent); String[] tA = t.split("\\."); /*for (int a = 0; a < tA.length; a++) System.out.println(tA[a]);*/ float i = (float) (0.1 / pow(10, tA[tA.length-1].length() - 1)); String n_last = ""; String n_out; for(float n = 0; n <= exponent; n = n + i){ n = (int)(n * pow(10, tA[tA.length-1].length()) + 0.5); n = (float) (n / pow(10, tA[tA.length-1].length())); n_out = Float.toString(n); if (n_last.length() > n_out.length()) n_out = n_out + "0"; txt_output.append(base + " to the exponent " + n_out + " = " + pow(base, n) + "\n"); n_last = n_out; } } } else { // if the exponent is < 0 then go from the 0 to the enterred exponent if(Math.round(exponent) == exponent){ for (int n = 0; n >= exponent; n--){ txt_output.append(base + " to the exponent " + n + " = " + pow(base, n) + "\n"); } } else { String t = Float.toString(exponent); String[] tA = t.split("\\."); /*for (int a = 0; a < tA.length; a++) System.out.println(tA[a]);*/ float i = (float) (0.1 / pow(10, tA[tA.length-1].length() - 1)); String n_last = ""; String n_out; for(float n = 0; n >= exponent; n = n - i){ n = (int)(n * pow(10, tA[tA.length-1].length()) - 0.5); n = (float) (n / pow(10, tA[tA.length-1].length())); n_out = Float.toString(n); if (n_last.length() > n_out.length()) n_out = n_out + "0"; txt_output.append(base + " to the exponent " + n_out + " = " + pow(base, n) + "\n"); n_last = n_out; } } } }//GEN-LAST:event_btn_calculateActionPerformed
a13a2ae5-37a3-4884-9be4-1302bcf45706
0
public getAvailableTimeSlot() { this.addParamConstraint("aUserId"); }
485bb3ad-5117-49ed-a9e0-bf8e8f2d9404
7
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); HttpSession sesionOk = request.getSession(); String usuario = ""; int id_cuenta = 0; if (sesionOk.getAttribute("usuario") != null && sesionOk.getAttribute("Id_cuenta") != null) { usuario = sesionOk.getAttribute("usuario").toString(); id_cuenta = Integer.parseInt(sesionOk.getAttribute("Id_cuenta").toString()); } else { response.sendRedirect("index.jsp"); } out.write("\r\n"); out.write("\r\n"); java.util.Date Fecha = new java.util.Date(); SimpleDateFormat Formato = new SimpleDateFormat("yyyy-MM-dd"); out.write("\r\n"); out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<!DOCTYPE>\r\n"); out.write("<html>\r\n"); out.write(" <head>\r\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); out.write(" <meta name=\"keywords\" content=\"jquery,ui,easy,easyui,web\">\r\n"); out.write(" <meta name=\"description\" content=\"easyui help you build your web page easily!\">\r\n"); out.write(" <meta http-equiv=\"Cache-control\" content=\"no-cache\">\r\n"); out.write(" <meta http-equiv=\"Cache-control\" content=\"no-store\">\r\n"); out.write(" <title>IEGAMAR</title>\r\n"); out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"css/easyui.css\">\r\n"); out.write(" <link rel=\"stylesheet\" type=\"text/css\" href=\"css/icon.css\">\r\n"); out.write(" <link href=\"bootstrap/css/bootstrap.min.css\" rel=\"stylesheet\">\r\n"); out.write(" <link href=\"css/dashboard.css\" rel=\"stylesheet\">\r\n"); out.write(" <link href=\"css/select2.css\" rel=\"stylesheet\" type=\"text/css\"/>\r\n"); out.write(" <link href=\"css/select2-bootstrap.css\" rel=\"stylesheet\" type=\"text/css\"/>\r\n"); out.write(" <link href=\"css/formulario.css\" rel=\"stylesheet\" type=\"text/css\"/>\r\n"); out.write(" <link href=\"css/style_light.css\" rel=\"stylesheet\" type=\"text/css\"/>\r\n"); out.write("\r\n"); out.write(" </head>\r\n"); out.write(" <body onload=\"mueveReloj()\">\r\n"); out.write("\r\n"); out.write(" <nav class=\"navbar navbar-default navbar-fixed-top\" role=\"navigation\">\r\n"); out.write(" <div class=\"container\">\r\n"); out.write(" <div class=\"navbar-header\">\r\n"); out.write(" <a class=\"navbar-brand\" >IEGAMAR</a>\r\n"); out.write(" </div>\r\n"); out.write(" <div id=\"navbar\" class=\"navbar-collapse collapse\">\r\n"); out.write(" <ul class=\"nav navbar-nav\"> \r\n"); out.write("\r\n"); out.write(" "); out.write("\r\n"); out.write("\r\n"); out.write(" "); ControladorElemento crt = new ControladorElemento(); out.println(crt.anomaliacont()); out.write("\r\n"); out.write("\r\n"); out.write(" <li><a href=\"consultarcuentas.jsp\">Administar Cuentas</a></li>\r\n"); out.write(" <li><a href=\"registargradoygrupo.jsp\">Grados</a></li>\r\n"); out.write(" <li><a href=\"consultarestudiante.jsp\">Estudiantes</a></li>\r\n"); out.write(" <li><a href=\"consultarprofesores.jsp\">Profesores</a></li>\r\n"); out.write(" <li><a href=\"consultarelemento.jsp\">Elementos</a></li>\r\n"); out.write(" <li class=\"active\"><a href=\"consultarprestamo.jsp\">Préstamo</a></li>\r\n"); out.write(" <li><a href=\"consultarreserva.jsp\">Reserva</a></li> \r\n"); out.write(" <li ><a href=\"consultarcontrol.jsp\">Control de llegadas</a></li> \r\n"); out.write(" </ul>\r\n"); out.write(" <ul class=\"nav navbar-nav navbar-right\">\r\n"); out.write("\r\n"); out.write(" <li class=\"active\"><a href=\"CerrarSesion.jsp\">Cerrar Sesión</a></li>\r\n"); out.write("\r\n"); out.write(" </ul>\r\n"); out.write(" </div><!--/.nav-collapse -->\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" <div hidden class=\"notification-list-wrapper\" id=\"objetivo\" style=\"top: 65px; left: 100px; opacity: 1;\">\r\n"); out.write("\r\n"); out.write(" <ul class=\"notification-list-menu\">\r\n"); out.write(" </ul>\r\n"); out.write("\r\n"); out.write(" <ul class=\"notification-list\" data-type=\"unread\">\r\n"); out.write("\r\n"); out.write(" <table id=\"tblArea\" class=\"table2 table-hover\" cellspacing=\"0\" width=\"100%\">\r\n"); out.write(" <thead>\r\n"); out.write(" <tr>\r\n"); out.write(" <th class=\"text-center\">Seriales</th>\r\n"); out.write(" <th class=\"text-center\">Anomalia</th>\r\n"); out.write(" </tr>\r\n"); out.write(" </thead>\r\n"); out.write(" <tbody id=\"traer1\">\r\n"); out.write(" "); out.println(crt.listaranom()); out.write("\r\n"); out.write(" </tbody>\r\n"); out.write(" </table>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" </ul>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <div class=\"modal fade bs-example-modal-sm\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\" aria-hidden=\"true\">\r\n"); out.write(" <div class=\"modal-dialog modal-sm\">\r\n"); out.write(" <div class=\"modal-content\">\r\n"); out.write(" <div class=\"modal-header\" >\r\n"); out.write(" <button type=\"button\" class=\"close\" data-dismiss=\"modal\"><span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>\r\n"); out.write(" <h4 class=\"modal-title\" id=\"myModalLabel\">Anomalia</h4>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <div class=\"modal-body\" >\r\n"); out.write(" <div class=\"form-group\">\r\n"); out.write(" <label for=\"disabledSelect\">Serial</label>\r\n"); out.write(" <input type=\"text\" class=\"form-control\" name=\"Serial\" id=\"Serial\" readonly=\"readonly\" placeholder=\"\">\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"form-group\">\r\n"); out.write(" <label for=\"disabledSelect\">Descripción</label>\r\n"); out.write("\r\n"); out.write(" <textarea rows=\"4\" name=\"Anomalia\" id=\"Anomalia\" cols=\"50\" class=\"form-control\" readonly=\"readonly\">\r\n"); out.write("\r\n"); out.write(" </textarea>\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"modal-footer\">\r\n"); out.write(" <button type=\"button\" data-dismiss=\"modal\" onclick=\"list_anomalias();\" class=\"btn btn-success\">Guardar</button>\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" </nav>\r\n"); out.write("\r\n"); out.write(" <div class=\"container-fluid\" id=\"formulario\">\r\n"); out.write(" <div class=\"row\">\r\n"); out.write(" <div class=\"col-sm-3 col-md-2 sidebar\">\r\n"); out.write(" <ul class=\"nav nav-sidebar\">\r\n"); out.write(" <li class=\"active\"><a href=\"registarprestamo.jsp\">Registar Préstamo</a></li>\r\n"); out.write(" <li><a href=\"consultarprestamo.jsp\">Consutar Préstamo</a></li>\r\n"); out.write(" </ul>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <section class=\"container\">\r\n"); out.write(" <form role=\"form\" action=\"RegistarPrestamo\" method=\"POST\" name=\"form_reloj\" class=\"payment-form\">\r\n"); out.write(" <div class=\"container-page\"> \r\n"); out.write(" <div class=\"col-md-6\">\r\n"); out.write(" <h3 class=\"dark-grey\">Registro De Prestamo</h3>\r\n"); out.write("\r\n"); out.write(" <div class=\"radio col-lg-6\">\r\n"); out.write(" <label>\r\n"); out.write(" <input type=\"radio\" name=\"opciones\" value=\"Estudiante\" onchange=\"recibir()\" checked=\"recibir()\">\r\n"); out.write(" Estudiante\r\n"); out.write(" </label>\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"radio col-lg-6\">\r\n"); out.write(" <label>\r\n"); out.write(" <input type=\"radio\" name=\"opciones\" value=\"Profesores\" onchange=\"recibir()\">\r\n"); out.write(" Profesores \r\n"); out.write(" </label>\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <div class=\"form-group col-lg-12\">\r\n"); out.write(" <label for=\"disabledSelect\" >Nombre</label>\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"form-group col-lg-12\" id=\"traer\" >\r\n"); out.write(" </div>\r\n"); out.write(" <div class=\"form-group col-lg-6\">\r\n"); out.write(" <label for=\"disabledSelect\">Fecha Del Prestamo</label>\r\n"); out.write(" <input type=\"text\" id=\"disabledTextInput\" class=\"form-control\" placeholder=\"\" name=\"Fecha\" readonly=\"readonly\" value=\""); out.print(Formato.format(Fecha)); out.write("\">\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <div class=\"form-group col-lg-6\">\r\n"); out.write(" <label for=\"disabledSelect\">Hora</label>\r\n"); out.write(" <input type=\"text\" id=\"disabledTextInput\" class=\"form-control\" placeholder=\"\" name=\"Hora\" readonly=\"readonly\" >\r\n"); out.write(" </div>\r\n"); out.write("\r\n"); out.write(" <div class=\"form-group col-lg-12\">\r\n"); out.write(" <label for=\"disabledSelect\">Seriales</label>\r\n"); out.write(" <select id=\"selectSerial\" name=\"Seriales\">\r\n"); out.write(" "); RegistarPrestamo vergrados = new RegistarPrestamo(); out.println(vergrados.Seriales()); out.write("\r\n"); out.write(" </select>\r\n"); out.write(" <button type=\"button\" class=\"btn btn-default preview-add-button\">\r\n"); out.write(" <span class=\"glyphicon glyphicon-plus\"></span>Mas\r\n"); out.write(" </button> \r\n"); out.write(" </div> \r\n"); out.write(" <div class=\"form-group col-lg-12\">\r\n"); out.write(" <table class=\"table2 preview-table\" id=\"tbl\">\r\n"); out.write(" <thead>\r\n"); out.write(" <tr>\r\n"); out.write(" <th>Seriales</th>\r\n"); out.write(" </tr>\r\n"); out.write(" </thead>\r\n"); out.write(" <tbody></tbody> <!-- preview content goes here-->\r\n"); out.write(" </table>\r\n"); out.write(" </div>\r\n"); out.write(" <button type=\"submit\" name=\"guardar\" value=\"insertar\" onclick=\"xd();\" class=\"btn btn-success\" style=\"margin-left: 360px;\">Guardar</button>\r\n"); out.write(" <input type=\"hidden\" class=\"form-control2\" id=\"serial\" name=\"serial\" placeholder=\"\">\r\n"); out.write(" <button type=\"Reset\" class=\"btn btn-default\">Cancelar</button>\r\n"); out.write(" </div>\r\n"); out.write(" </div>\r\n"); out.write(" </form>\r\n"); out.write(" </section>\r\n"); out.write(" </div>\r\n"); out.write(" <script type=\"text/javascript\" src=\"js/jquery-1.6.min.js\"></script>\r\n"); out.write(" <script src=\"bootstrap/js/bootstrap.js\"></script>\r\n"); out.write(" <script src=\"js/select2.js\" type=\"text/javascript\"></script>\r\n"); out.write(" <script src=\"js/ajax.js\" type=\"text/javascript\"></script>\r\n"); out.write(" <script src=\"js/mapeomod.js\" type=\"text/javascript\"></script>\r\n"); out.write("\r\n"); out.write(" <script>\r\n"); out.write(" $(\"#selectSerial\").select2({\r\n"); out.write(" minimumInputLength: 2\r\n"); out.write(" });\r\n"); out.write(" </script>\r\n"); out.write("\r\n"); out.write(" <script language=\"JavaScript\">\r\n"); out.write(" function mueveReloj() {\r\n"); out.write(" momentoActual = new Date()\r\n"); out.write(" hora = momentoActual.getHours()\r\n"); out.write(" minuto = momentoActual.getMinutes(\"mm\")\r\n"); out.write(" \r\n"); out.write(" horaImprimible = hora + \" : \" + minuto\r\n"); out.write("\r\n"); out.write(" document.form_reloj.Hora.value = horaImprimible\r\n"); out.write("\r\n"); out.write(" setTimeout(\"mueveReloj()\", 1000)\r\n"); out.write(" }\r\n"); out.write(" </script> \r\n"); out.write("\r\n"); out.write(" <script>\r\n"); out.write("\r\n"); out.write(" var actualizacion = setInterval(function () {\r\n"); out.write(" actualizar_anomalias()\r\n"); out.write(" }, 3000);\r\n"); out.write("\r\n"); out.write(" function actualizar_anomalias() {\r\n"); out.write("\r\n"); out.write(" var serial = $(\"#Serial\").val();\r\n"); out.write("\r\n"); out.write(" $.ajax({\r\n"); out.write(" dataType: \"html\",\r\n"); out.write(" data: {\r\n"); out.write(" proceso: \"actualizar_anom\"\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" },\r\n"); out.write(" type: \"POST\",\r\n"); out.write(" url: \"ControladorElemento\",\r\n"); out.write(" statusCode: {\r\n"); out.write(" 404: function () {\r\n"); out.write(" alert(\"page not found\");\r\n"); out.write(" }\r\n"); out.write(" }\r\n"); out.write(" }).done(function (datos) {\r\n"); out.write(" $(\"#actualizar\").empty();\r\n"); out.write(" $(\"#actualizar\").append(datos);\r\n"); out.write(" });\r\n"); out.write(" }\r\n"); out.write("\r\n"); out.write(" function list_anomalias() {\r\n"); out.write("\r\n"); out.write(" var serial = $(\"#Serial\").val();\r\n"); out.write("\r\n"); out.write(" $.ajax({\r\n"); out.write(" dataType: \"html\",\r\n"); out.write(" data: {\r\n"); out.write(" proceso: \"listar_anom\",\r\n"); out.write(" Serial: serial\r\n"); out.write("\r\n"); out.write(" },\r\n"); out.write(" type: \"POST\",\r\n"); out.write(" url: \"ControladorElemento\",\r\n"); out.write(" statusCode: {\r\n"); out.write(" 404: function () {\r\n"); out.write(" alert(\"page not found\");\r\n"); out.write(" }\r\n"); out.write(" }\r\n"); out.write(" }).done(function (datos) {\r\n"); out.write(" $(\"#traer1\").empty();\r\n"); out.write(" $(\"#traer1\").append(datos);\r\n"); out.write(" });\r\n"); out.write(" }\r\n"); out.write("\r\n"); out.write(" var x;\r\n"); out.write(" x = $(document);\r\n"); out.write(" x.ready(inicializar);\r\n"); out.write("\r\n"); out.write(" function inicializar() {\r\n"); out.write(" var x = $(\"#mostrar\");\r\n"); out.write(" x.click(muestrame);\r\n"); out.write("\r\n"); out.write(" }\r\n"); out.write("\r\n"); out.write(" function muestrame() {\r\n"); out.write(" var x = $(\"#objetivo\");\r\n"); out.write(" x.slideToggle(\"slow\");\r\n"); out.write(" }\r\n"); out.write("\r\n"); out.write(" $(document).on('click', '.input-remove-row', function () {\r\n"); out.write(" var tr = $(this).closest('tr');\r\n"); out.write(" tr.fadeOut(200, function () {\r\n"); out.write(" tr.remove();\r\n"); out.write("\r\n"); out.write(" });\r\n"); out.write(" });\r\n"); out.write("\r\n"); out.write(" $(function () {\r\n"); out.write(" recibir();\r\n"); out.write("\r\n"); out.write(" $('.preview-add-button').click(function () {\r\n"); out.write(" var form_data = {};\r\n"); out.write("\r\n"); out.write(" if ($('.payment-form select[name=\"Seriales\"]').val() != \"\")\r\n"); out.write(" {\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" form_data[\"Seriales\"] = $('.payment-form select[name=\"Seriales\"]').val();\r\n"); out.write("\r\n"); out.write(" form_data[\"remove-row\"] = '<span class=\"glyphicon glyphicon-remove\"></span>';\r\n"); out.write(" var row = $('<tr></tr>');\r\n"); out.write(" $.each(form_data, function (type, value) {\r\n"); out.write("\r\n"); out.write(" $('<td class=\"input-' + type + '\"></td>').html(value).appendTo(row);\r\n"); out.write("\r\n"); out.write(" });\r\n"); out.write(" $('.preview-table > tbody:last').append(row);\r\n"); out.write(" }\r\n"); out.write(" document.getElementById(\"Seriales\").value = \"\";\r\n"); out.write(" });\r\n"); out.write("\r\n"); out.write(" });\r\n"); out.write("\r\n"); out.write(" function xd() {\r\n"); out.write(" var textos = '';\r\n"); out.write(" for (var i = 0; i < document.getElementById('tbl').rows.length; i++) {\r\n"); out.write(" for (var j = 0; j < document.getElementById('tbl').rows[i].cells.length; j++)\r\n"); out.write(" {\r\n"); out.write(" if (j == 0 && i != 0) {\r\n"); out.write(" textos = textos + document.getElementById('tbl').rows[i].cells[j].innerHTML + '-';\r\n"); out.write(" }\r\n"); out.write(" }\r\n"); out.write(" textos = textos;\r\n"); out.write(" }\r\n"); out.write(" $(\"#serial\").val(textos);\r\n"); out.write(" }\r\n"); out.write("\r\n"); out.write("\r\n"); out.write(" </script> \r\n"); out.write(" </body>\r\n"); out.write("</html>\r\n"); out.write("\r\n"); out.write("\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
f75cc80e-e9cc-4d20-93bb-0af44b794355
8
private static String whoAmI(Registry registry) throws AccessException, RemoteException { String name = null; String[] boundServers = registry.list(); if (boundServers == null || boundServers.length == 0) { //Just return 1 if there are no other 0's return String.valueOf(1); } ArrayList<Integer> serverNames = new ArrayList<Integer>(boundServers.length); for (String s : boundServers) { //Convert all strings to ints serverNames.add(Integer.parseInt(s)); } //Sorted list of server names Collections.sort(serverNames); //If the first entry isn't 1, then use it if (serverNames.get(0) != 1) return String.valueOf(1); //For everything else for (int i = 0; i < serverNames.size(); i++) { if (i == serverNames.size() -1) { //If we're at the end and we still have more server slots free if (i < ICoreServer.maxServerNumber -1) { //Make one return String.valueOf(serverNames.get(i) + 1); } else { //Else the list is full and no more server slots free return null; } } //Find gaps and return the first free index in said gap if (serverNames.get(i + 1) - serverNames.get(i) > 1) { return String.valueOf(serverNames.get(i) + 1); } } return name; }
0ccaeb04-eac9-4bdf-afb0-e220dc085292
8
public List<Integer> getRow(int rowIndex) { if (rowIndex == 0) { return Arrays.asList(1); } int[] odd = new int[rowIndex / 2 + 1]; int[] even = new int[rowIndex / 2 + 1]; odd[0] = 1; even[0] = 1; for (int i = 0; i < rowIndex / 2; i++) { for (int j = 1; j < i + 1; j++) { even[j] = odd[j - 1] + odd[j]; } even[i + 1] = even[i]; for (int j = 1; j < i + 2; j++) { odd[j] = even[j - 1] + even[j]; } } Integer[] ret = new Integer[rowIndex + 1]; if (rowIndex % 2 == 0) { for (int i = 0; i < rowIndex / 2; i++) { ret[i] = odd[i]; ret[rowIndex - i] = odd[i]; } ret[rowIndex / 2] = odd[rowIndex / 2]; } else { for (int j = 1; j < rowIndex / 2 + 1; j++) { even[j] = odd[j - 1] + odd[j]; } for (int i = 0; i < rowIndex / 2 + 1; i++) { ret[i] = even[i]; ret[rowIndex - i] = even[i]; } } return Arrays.asList(ret); }
5117ebdd-6f84-4606-b3da-8e61b2c4d43c
8
public boolean onCommand (CommandSender sender, Command cmd, String lable, String[] args) { Player p = (Player) sender; PluginDescriptionFile pdf = this.getDescription(); try { if(sender instanceof Player) { if(lable.equalsIgnoreCase("gp")) { if (args[0].toLowerCase().equalsIgnoreCase("reload") && p.hasPermission("glitchpatcher.reload")) { File conf = new File(getDataFolder(), "config.yml"); this.getConfig().load(conf); p.sendMessage(gplogo + "Config is now reloaded :)"); } } } else if (sender instanceof ConsoleCommandSender) { if(lable.equalsIgnoreCase("gp")) { if (args[0].toLowerCase().equalsIgnoreCase("reload")) { File conf = new File(getDataFolder(), "config.yml"); this.getConfig().load(conf); log.info("[GlitchPatcher] Config is now reloaded :)"); } } } } catch(Exception e) { e.getStackTrace(); } return true; }
872d7075-4fa4-426b-954d-390ec3faa10f
7
public static void testSet() { SeqnoRange range=new SeqnoRange(10, 15); range.set(11, 12, 13, 14); System.out.println("range=" + print(range)); assert range.size() == 6; assert range.getNumberOfReceivedMessages() == 4; assert range.getNumberOfMissingMessages() == 2; Collection<Range> xmits=range.getMessagesToRetransmit(); assert xmits.size() == 2; Iterator<Range> it=xmits.iterator(); Range r=it.next(); assert r.low == 10 && r.high == 10; r=it.next(); assert r.low == 15 && r.high == 15; range=new SeqnoRange(10, 15); range.set(10,11,12,13,14); System.out.println("range=" + print(range)); assert range.size() == 6; assert range.getNumberOfReceivedMessages() == 5; assert range.getNumberOfMissingMessages() == 1; xmits=range.getMessagesToRetransmit(); assert xmits.size() == 1; it=xmits.iterator(); r=it.next(); assert r.low == 15 && r.high == 15; range=new SeqnoRange(10, 15); range.set(11,12,13,14,15); System.out.println("range=" + print(range)); assert range.size() == 6; assert range.getNumberOfReceivedMessages() == 5; assert range.getNumberOfMissingMessages() == 1; xmits=range.getMessagesToRetransmit(); assert xmits.size() == 1; it=xmits.iterator(); r=it.next(); assert r.low == 10 && r.high == 10; range=new SeqnoRange(10, 15); range.set(10,11,12,13,14,15); System.out.println("range=" + print(range)); assert range.size() == 6; assert range.getNumberOfReceivedMessages() == 6; assert range.getNumberOfMissingMessages() == 0; xmits=range.getMessagesToRetransmit(); assert xmits.isEmpty(); range=new SeqnoRange(10, 15); range.set(11,12,14,15); System.out.println("range=" + print(range)); assert range.size() == 6; assert range.getNumberOfReceivedMessages() == 4; assert range.getNumberOfMissingMessages() == 2; xmits=range.getMessagesToRetransmit(); assert xmits.size() == 2; it=xmits.iterator(); r=it.next(); assert r.low == 10 && r.high == 10; r=it.next(); assert r.low == 13 && r.high == 13; range.set(13); assert range.getNumberOfReceivedMessages() == 5; assert range.getNumberOfMissingMessages() == 1; xmits=range.getMessagesToRetransmit(); it=xmits.iterator(); r=it.next(); assert r.low == 10 && r.high == 10; range.set(10); System.out.println("range=" + print(range)); assert range.getNumberOfReceivedMessages() == 6; assert range.getNumberOfMissingMessages() == 0; xmits=range.getMessagesToRetransmit(); assert xmits.isEmpty(); }
ae151069-5b6c-469f-baba-fd34b294f6c6
9
public static boolean insertCurriculum(UserBean bean){ Statement stmt = null; Curriculum curriculum=((AlumnoBean)bean).getCurriculum(); // OJO CON ESTA LINEA, DEBERIA FUNCIONAR String query= "Insert into curriculums values ("+curriculum.getId()+","+bean.getRut()+",NOW())"; System.out.println(query); try { currentCon = ConnectionManager.getConnection(); stmt=currentCon.createStatement(); stmt.executeUpdate(query); System.out.println("Curriculum Agregado"); List<DatoAcademico> academicos =curriculum.getDatosAcademicos(); if (!academicos.isEmpty()) { PreparedStatement ps; for (DatoAcademico datoAcademico : academicos) { String query2 = "Insert into datos_academicos values (NULL,?,?,?,?,?,?)"; ps=currentCon.prepareStatement(query2); ps.setInt(1, bean.getRut()); ps.setInt(2, curriculum.getId()); ps.setString(3, datoAcademico.getEstablecimiento()); ps.setString(4, datoAcademico.getInicio()); ps.setString(5, datoAcademico.getFin()); ps.setString(6, datoAcademico.getDescripcion()); ps.execute(); } } List<HistorialLaboral> laborales=curriculum.getLaborales(); if (!laborales.isEmpty()) { PreparedStatement ps; for (HistorialLaboral historial : laborales) { String query2 = "Insert into historial_laboral values (NULL,?,?,?,?,?,?,?)"; ps=currentCon.prepareStatement(query2); ps.setInt(1, bean.getRut()); ps.setInt(2, curriculum.getId()); ps.setString(3, historial.getEstablecimiento()); ps.setString(4, historial.getCargo()); ps.setString(5, historial.getInicio()); ps.setString(6, historial.getFin()); ps.setString(7, historial.getDescripcion()); ps.execute(); } } List<Idioma> idiomas= curriculum.getIdiomas(); if (!idiomas.isEmpty()) { PreparedStatement ps; for (Idioma idioma : idiomas) { String query2 = "Insert into manejo_idiomas values (?,?,?,?)"; ps=currentCon.prepareStatement(query2); ps.setInt(1, bean.getRut()); ps.setInt(2, curriculum.getId()); ps.setString(3, idioma.getIdioma()); ps.setString(4, idioma.getNivel()); ps.execute(); } } List<AreaInteres> areas = curriculum.getIntereses(); if(!areas.isEmpty()){ PreparedStatement ps; for(AreaInteres area : areas){ String query2 = "Insert into curriculums_areas_interes values (?,?,?)"; ps=currentCon.prepareStatement(query2); ps.setInt(1, bean.getRut()); ps.setInt(2, curriculum.getId()); ps.setString(3, area.getArea()); ps.execute(); } // FALTA INGRESAR AREA DE INTERES } }catch (Exception ex) { System.out.println("InsertCurriculum failed: An Exception has occurred! " + ex); return false; } return true; }
d145641a-8a05-4548-9dc6-b63049af1ab3
6
private ArrayList<Integer> generateActions(LongBoard state) { ArrayList<Integer> result = new ArrayList<Integer>(); int middle = x/2; //TODO choose random when x is even if (state.isPlayable(middle)) { result.add(middle); } for (int i=1; i <= x/2; i++) { if(middle + i < x) { if (state.isPlayable(middle + i)) { result.add(middle + i); } } if(middle - i > -1) { if (state.isPlayable(middle - i)) { result.add(middle - i); } } } return result; }
2465d438-c1e1-4f2a-89c7-15a025286915
3
public Player(float x, float y,GBGame game, TiledMapTileLayer layer) { this.game = game; this.collisionLayer = layer; // Load up the stuff try { currentSprite = new Sprite(Art.player[0][0]); } catch (Exception e) { System.out.println("SPRITE NOT LOADING! TRY AGAIN!"); } bounds = new Rectangle(); currentPosition = new Vector2(); position = new Vector2(); // Set it up yo position.set(x, y); currentPosition.set(x, y); currentSprite.setBounds(position.x, position.y, 16, 16); bounds.set(position.x, position.y, 16, 16); if (collisionLayer == null) { try { collisionLayer = layer; System.out.println("Layer was null. Loaded the passed layer."); } catch (Exception e) { System.out.println("Layer was null. Tried to fix it. It didn't work."); } } }
4faa5f31-295c-49d0-a772-aa97cac89d0f
8
public DirectedEulerianCycle(Digraph G) { // create local view of adjacency lists Iterator<Integer>[] adj = (Iterator<Integer>[]) new Iterator[G.V()]; for (int v = 0; v < G.V(); v++) adj[v] = G.adj(v).iterator(); // find vertex with nonzero degree as start of potential Eulerian cycle int s = 0; for (int v = 0; v < G.V(); v++) { if (adj[v].hasNext()) { s = v; break; } } // greedily add to cycle, depth-first search style Stack<Integer> stack = new Stack<Integer>(); stack.push(s); while (!stack.isEmpty()) { int v = stack.pop(); cycle.push(v); int w = v; while (adj[w].hasNext()) { stack.push(w); w = adj[w].next(); } if (w != v) isEulerian = false; } // check if all edges have been used for (int v = 0; v < G.V(); v++) if (adj[v].hasNext()) isEulerian = false; }
a2389aa7-5390-4d91-8f74-0807bedc6ec3
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TabelOutletChain other = (TabelOutletChain) obj; if (!Objects.equals(this.kodeChain, other.kodeChain)) { return false; } return true; }
05020ac9-596e-4c46-a2fa-3c3a5607e5b6
8
public static Object escape(Object original) { if (original instanceof Character) { char u = (char) ((Character)original); int idx = "\b\t\n\f\r\"\'\\".indexOf(u); if (idx >= 0) return "\\"+"btnfr\"\'\\".charAt(idx); if (u < 32) return "\\"+Integer.toOctalString(u); if (u > 126) return "\\u"+String.format("%04X", (int)u); return original; } else if (original instanceof String) { StringBuilder result = new StringBuilder(); for (char c : ((String)original).toCharArray()) result.append(escape(c)); return "\"" + result.toString() + "\""; } else if (original.getClass().isArray()) { StringBuilder result = new StringBuilder("["); int len = Array.getLength(original); for (int i=0; i<len; i++) result.append(" ").append(escape(Array.get(original, i))); return result.append("]").toString(); } return original; }
9bcb1c93-6fdb-4b46-8857-d0a1772ecd7f
9
@Override public void broadcast(final FacesEvent event) throws AbortProcessingException { super.broadcast(event); FacesContext context = getFacesContext(); if (!(event instanceof ActionEvent)) { throw new IllegalArgumentException(); } // OPEN QUESTION: should we consider a navigation to the same view as a // no-op navigation? // only proceed if the response has not been marked complete and // navigation to another view has not occurred if (!context.getResponseComplete() && (context.getViewRoot() == getViewRootOf(event))) { ActionListener listener = context.getApplication().getActionListener(); if (listener != null) { boolean hasMoreViewActionEvents = false; UIViewRoot viewRootBefore = context.getViewRoot(); assert(null != viewRootBefore); InstrumentedFacesContext instrumentedContext = null; try { instrumentedContext = new InstrumentedFacesContext(context); setIsProcessingUIViewActionBroadcast(context, true); // defer the call to renderResponse() that happens in // ActionListener#processAction(ActionEvent) instrumentedContext.disableRenderResponseControl().set(); listener.processAction((ActionEvent) event); hasMoreViewActionEvents = !decrementEventCountAndReturnTrueIfZero(context); } finally { setIsProcessingUIViewActionBroadcast(context, false); if (null != instrumentedContext) { instrumentedContext.restore(); } } // if the response is marked complete, the story is over if (!context.getResponseComplete()) { UIViewRoot viewRootAfter = context.getViewRoot(); assert(null != viewRootAfter); // if the view id changed as a result of navigation, // then execute the JSF lifecycle for the new view // id String viewIdBefore = viewRootBefore.getViewId(); String viewIdAfter = viewRootAfter.getViewId(); assert(null != viewIdBefore && null != viewIdAfter); boolean viewIdsSame = viewIdBefore.equals(viewIdAfter); if (viewIdsSame && !hasMoreViewActionEvents) { // apply the deferred call (relevant when immediate is true) context.renderResponse(); } } } } }
0bb948c9-0e63-4599-b919-6d64b0ae1cf3
3
private int getStep() { LayoutManager layout = getLayout(); if (layout instanceof ColumnLayout) { return ((ColumnLayout) layout).getColumns(); } else if (layout instanceof FlexLayout && ((FlexLayout) layout).getRootCell() instanceof FlexGrid) { int columns = ((FlexGrid) ((FlexLayout) layout).getRootCell()).getColumnCount(); return columns - columns / 2; } return 1; }
74920592-b0f9-4e3c-b988-80b5b29074fa
8
private StringBuilder getGallery() throws ClassNotFoundException, SQLException { StringBuilder sb = new StringBuilder(); Reference r = References.createReference(this.id); List<Gallery> galleries; galleries = r.getGalleries(); if (galleries.size() > 0) { sb.append("<div class=\"row\">"); Utils.appendNewLine(sb); sb.append("<div class=\"large-12 columns\">"); Utils.appendNewLine(sb); sb.append("<hr>"); Utils.appendNewLine(sb); sb.append("<h3>Fotogaléria</h3>"); Utils.appendNewLine(sb); Connection connect = this.getDbConnection(); for (Gallery gallery : galleries) { if (gallery.getName().length() > 0) { sb.append("<h5>"); sb.append(gallery.getName()); sb.append("</h5>"); Utils.appendNewLine(sb); } if (gallery.hasPhotos()) { sb.append("<ul class=\"clearing-thumbs\" data-clearing>"); Utils.appendNewLine(sb); Statement statement; ResultSet resultSet; //TODO change to prepared statement statement = connect.createStatement(); resultSet = statement .executeQuery("SELECT f.file, f.title FROM foto f WHERE f.id_dom = " + this.id.toString() + " AND f.poradie = " + gallery.getId().toString() + " ORDER BY f.file"); while (resultSet.next()) { String file = resultSet.getString("file"); String title2 = resultSet.getString("title"); sb.append("<li><a href=\""); sb.append(gallery.getUrl()); sb.append(file); sb.append(".jpg\" class=\"th\"><img src=\""); sb.append(gallery.getUrl()); sb.append(file); sb.append("-th.jpg\" alt=\"\" data-caption=\""); sb.append(title2); sb.append("\"></a></li>"); Utils.appendNewLine(sb); } resultSet.close(); statement.close(); sb.append("</ul>"); Utils.appendNewLine(sb); } // zobrazíme aj subgalérie tejto galérie, ak nejaké sú List<SubGallery> subGalleries; subGalleries = gallery.getSubGalleries(); if (subGalleries.size() > 0) { for (SubGallery subGallery : subGalleries) { sb.append("<p>"); sb.append(subGallery.getName()); sb.append("</p>"); Utils.appendNewLine(sb); sb.append("<ul class=\"clearing-thumbs\" data-clearing>"); Utils.appendNewLine(sb); Statement statement2; ResultSet resultSet2; //TODO change to prepared statement statement2 = connect.createStatement(); resultSet2 = statement2 .executeQuery("SELECT f.file, f.title FROM foto2 f WHERE f.id_dom = " + this.id.toString() + " AND f.galeria = " + gallery.getId().toString() + " AND f.galeria2 = " + subGallery.getId().toString() + " ORDER BY f.file"); while (resultSet2.next()) { String file = resultSet2.getString("file"); String title2 = resultSet2.getString("title"); sb.append("<li><a href=\""); sb.append(gallery.getUrl()); sb.append(subGallery.getUrl()); sb.append(file); sb.append(".jpg\" class=\"th\"><img src=\""); sb.append(gallery.getUrl()); sb.append(subGallery.getUrl()); sb.append(file); sb.append("-th.jpg\" alt=\"\" data-caption=\""); sb.append(title2); sb.append("\"></a></li>"); Utils.appendNewLine(sb); } resultSet2.close(); statement2.close(); sb.append("</ul>"); Utils.appendNewLine(sb); } } } connect.close(); sb.append("</div>"); Utils.appendNewLine(sb); sb.append("</div>"); Utils.appendNewLine(sb); } return sb; }
e00351db-0e36-447a-9f4c-e459fc92cd38
4
private void showGezin(Gezin gezin) { // todo opgave 3 if (gezin == null) { clearTabGezin(); } else { tfGezinNr.setText(gezin.getNr() + ""); tfOuder1.setText(gezin.getOuder1().standaardgegevens()); if(gezin.getOuder2() != null) tfOuder2.setText(gezin.getOuder2().standaardgegevens()); if(gezin.getHuwelijksdatum() != null) tfHuwelijk.setText(StringUtilities.datumString(gezin.getHuwelijksdatum())); if(gezin.getScheidingsdatum() != null) tfScheiding.setText(StringUtilities.datumString(gezin.getScheidingsdatum())); this.kinderen = FXCollections.observableArrayList(gezin.getKinderen()); lvKinderen.setItems(this.getKinderen()); } }
d7545105-55ff-41cc-b5b9-79ae191c3145
1
private String chooseFile() { if (chooser.showDialog(org.analyse.main.Main.analyseFrame, null) == JFileChooser.APPROVE_OPTION) { return chooser.getSelectedFile().getAbsolutePath(); } return null; }
7f5a5623-bb99-4aa1-bba3-c3a4f506c70f
3
public void copySources(HashMap<String, Source> srcMap) { if (srcMap == null) return; Set<String> keys = srcMap.keySet(); Iterator<String> iter = keys.iterator(); String sourcename; Source srcData; // remove any existing sources before starting: sourceMap.clear(); // loop through and copy all the sources: while (iter.hasNext()) { sourcename = iter.next(); srcData = srcMap.get(sourcename); if (srcData != null) { loadSound(srcData.filenameURL); sourceMap.put(sourcename, new Source(srcData, null)); } } }
569c39b0-8cdb-4dee-a1a4-26e29d72a3fb
9
final boolean method810(int i, int i_2_, boolean bool, GraphicsToolkit graphicstoolkit) { anInt11104++; if (aNpcDefinition11122 == null || !method875(131072, true, graphicstoolkit)) { return false; } Class336 class336 = graphicstoolkit.A(); int i_3_ = aClass99_10893.method1086(16383); class336.method3860(i_3_); class336.method3863(anInt5934, anInt5937, anInt5940); boolean bool_4_ = bool; for (int i_5_ = 0; (i_5_ ^ 0xffffffff) > (aDrawableModelArray10909.length ^ 0xffffffff); i_5_++) { if (aDrawableModelArray10909[i_5_] != null) { boolean bool_6_ = (aNpcDefinition11122.anInt2831 ^ 0xffffffff) < -1 || ((aNpcDefinition11122.anInt2803 ^ 0xffffffff) == 0 ? aNpcDefinition11122.anInt2811 == 1 : (aNpcDefinition11122.anInt2803 ^ 0xffffffff) == -2); boolean bool_7_; if (Node_Sub15_Sub10.aBoolean9850) { bool_7_ = aDrawableModelArray10909[i_5_].method621(i_2_, i, class336, bool_6_, aNpcDefinition11122.anInt2831, Class308.anInt3912); } else { bool_7_ = aDrawableModelArray10909[i_5_].method624(i_2_, i, class336, bool_6_, aNpcDefinition11122.anInt2831); } if (bool_7_) { bool_4_ = true; break; } } } for (int i_8_ = 0; (i_8_ ^ 0xffffffff) > (aDrawableModelArray10909.length ^ 0xffffffff); i_8_++) aDrawableModelArray10909[i_8_] = null; return bool_4_; }
dd48c4d5-886e-4243-a5bc-203c812c7848
0
public void setStartCity(String startCity) { this.startCity = startCity; }
69b287ec-329e-40a0-a5c3-b810615cacfd
6
private void isCorner() { if (localMap.getPosition().getCorridor(0).getWeight() == 1 && (localMap.getPosition().getCorridor(1).getWeight() == 1 || localMap .getPosition().getCorridor(3).getWeight() == 1)) { corner = true; } else if (localMap.getPosition().getCorridor(2).getWeight() == 1 && (localMap.getPosition().getCorridor(1).getWeight() == 1 || localMap .getPosition().getCorridor(3).getWeight() == 1)) corner = true; }
aee4c7af-6ec6-489b-ab43-d371efddb3e4
3
@Override public void broadcast(String flName, TreeMap<Long, String> mapValues) throws RemoteException { if (!fileLock.containsKey(flName)) fileLock.put(flName, new ReentrantReadWriteLock()); // lock fileLock.get(flName).writeLock().lock(); try { System.out.println("Broadcasting to : " + replicaPath + "/replica" + this.replicaID + "/" + flName); PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter(replicaPath + "/replica" + this.replicaID + "/" + flName, true))); for (Iterator<String> iterator = mapValues.values().iterator(); iterator .hasNext();) { out.print((iterator.next())); } out.close(); } catch (Exception e) { System.err.println("Error in broadcast method: " + e.getMessage()); } }
7e8bf99b-527c-4230-a313-c7f5057171d8
6
public void run(double frac) { TupleSet ts = m_vis.getFocusGroup(Visualization.FOCUS_ITEMS); counter = (counter + 1) % 9; if (ts.getTupleCount() == 0) return; if (counter == 8) { int xbias = 0, ybias = 0; switch (m_orientation) { case Constants.ORIENT_LEFT_RIGHT: xbias = m_bias; break; case Constants.ORIENT_RIGHT_LEFT: xbias = -m_bias; break; case Constants.ORIENT_TOP_BOTTOM: ybias = m_bias; break; case Constants.ORIENT_BOTTOM_TOP: ybias = -m_bias; break; } VisualItem vi = (VisualItem) ts.tuples().next(); m_cur.setLocation(getWidth() / 2, getHeight() / 2); getAbsoluteCoordinate(m_cur, m_start); m_end.setLocation(vi.getX() + xbias, vi.getY() + ybias); } else { m_cur.setLocation(m_start.getX() + frac * (m_end.getX() - m_start.getX()), m_start.getY() + frac * (m_end.getY() - m_start.getY())); panToAbs(m_cur); } }
ef60c457-efc5-459d-a6ac-24ba8a8f0093
2
public void sendReplyFlooding(){ //Dispara o flooding das respostas dos nodos com papel BORDER e RELAY if ((getRole() == NodeRoleOldBetEtx.BORDER) || (getRole() == NodeRoleOldBetEtx.RELAY)) { this.setColor(Color.GRAY); //Pack pkt = new Pack(this.hops, this.pathsToSink, this.ID, 1, this.sBet, TypeMessage.BORDER); PackReplyOldBetEtx pkt = new PackReplyOldBetEtx(hops, pathsToSink, this.ID, sinkID, nextHop, neighbors, etxPath, sBet, this.ID); broadcast(pkt); setSentMyReply(true); } }
2057960f-740a-4460-bae8-2a9a9af1607b
6
@Test public void testReceiveMultipleWithBound() { int noOfMessages = 5; int queueSize = 2; try { consumer = new AbstractMessageConsumer(mockTopic, queueSize) { }; assertNotNull(mockTopic.getTopicSubscriber()); HashSet<Message> messages = new HashSet<Message>(); for (int i = 0; i < noOfMessages; i++) { Message msg = new MockMessage("TestMessage" + i); // Insert only two messages, first two if (i < queueSize) messages.add(msg); mockTopic.getTopicSubscriber().onMessage(msg); } for (int i = 0; i < noOfMessages; i++) { FutureTask<Message> future = getMessageFuture(consumer, 100); Message received = future.get(115, TimeUnit.MILLISECONDS); // First two messages should expected messages, first two if (i < queueSize) { assertNotNull("Received message is null ", received); assertTrue("Unexpected message found", messages.remove(received)); } else { // Rest should be null assertNull("Unexpected message found, message not null", received); } } } catch (TimeoutException e) { fail("Timeout did not happen on receive method"); } catch (Exception e) { logger.error("Error while calling receiving message", e); fail("Error while calling onMessage:" + e.getMessage()); } }
2bb697fc-13c3-4aaf-9cb7-e15cc634bc8c
2
public void removeRestriction(String restrictionIdentifier) { for(Restriction r: restrictions){ if(r.getIdentifier().equals(identifier)) restrictions.remove(r); } }
e0633e87-5241-46f1-b44a-65a9c32663f4
0
public static Color getColor(int c, int r) { int x = (int) (firstPick.getX() + c * (cellWidth + cellPadding)); int y = (int) (firstPick.getY() - r * (cellWidth + cellPadding)); return Main.fenrir.getColor(x, y); }
1ad213b7-0700-4a21-bf7a-8625d0ddf670
2
@Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Bearing)) { return false; } return this.getBearingInDecimalDegrees().equals(((Bearing) other).getBearingInDecimalDegrees()); }
86b65f46-1c24-45a5-b12b-1a6247e29da0
0
public String getMsgID() { return MsgID; }
94d5376f-6cbc-43d1-bfa2-4fc0a832e23e
0
public LocQueue() { init(); }
93125004-5547-4c2d-a001-5df626b28498
9
@Override public void unInvoke() { if((trapType()==Trap.TRAP_PIT_BLADE) &&(affected instanceof Exit) &&(myPit!=null) &&(canBeUninvoked()) &&(myPitUp!=null)) { final Room R=myPitUp.getRoomInDir(Directions.UP); if((R!=null)&&(R.getRoomInDir(Directions.DOWN)==myPitUp)) { R.rawDoors()[Directions.DOWN]=null; R.setRawExit(Directions.DOWN,null); } /** don't do this, cuz someone might still be down there. myPitUp.rawDoors()[Directions.UP]=null; myPitUp.getRawExit(Directions.UP]=null; myPitUp.rawDoors()[Directions.DOWN]=null; myPitUp.getRawExit(Directions.DOWN]=null; myPit.rawDoors()[Directions.UP]=null; myPit.getRawExit(Directions.UP]=null; */ if(myPit!=null) myPit.destroy(); if(myPitUp!=null) myPitUp.destroy(); } super.unInvoke(); }
7f938dde-8d85-4bd0-bcb9-f72ea7986795
7
@Override public Success<Import> parse(String s, int p) { // Parse the "import" keyword. Success<String> resImport = IdentifierParser.singleton.parse(s, p); if (resImport == null || !resImport.value.equals("import")) return null; p = resImport.rem; p = optWS(s, p); // Parse the module name. Success<String> resModule = IdentifierParser.singleton.parse(s, p); if (resModule == null) throw new NiftyException("missing module name after 'import'."); String module = resModule.value; p = resModule.rem; p = optWS(s, p); // Parse the '.'. if (s.charAt(p++) != '.') throw new NiftyException("Missing '.' after module name in import."); p = optWS(s, p); // Parse the type name. String type; if (s.charAt(p) == '*') { ++p; type = null; } else { Success<String> resType = IdentifierParser.singleton.parse(s, p); if (resType == null) throw new NiftyException("missing type name after 'import %s.'.", module); type = resType.value; p = resType.rem; } p = optWS(s, p); // Parse the ';'. if (s.charAt(p++) != ';') throw new NiftyException("Missing ';' at end of import."); Import result = new Import(module, type); return new Success<Import>(result, p); }
7f31ddbb-6c7d-40a3-97c3-459dbb95372c
6
private Status.TermVectorStatus testTermVectors(SegmentInfo info, SegmentReader reader, NumberFormat format) { final Status.TermVectorStatus status = new Status.TermVectorStatus(); try { if (infoStream != null) { infoStream.print(" test: term vectors........"); } for (int j = 0; j < info.docCount; ++j) { if (!reader.isDeleted(j)) { status.docCount++; TermFreqVector[] tfv = reader.getTermFreqVectors(j); if (tfv != null) { status.totVectors += tfv.length; } } } msg("OK [" + status.totVectors + " total vector count; avg " + format.format((((float) status.totVectors) / status.docCount)) + " term/freq vector fields per doc]"); } catch (Throwable e) { msg("ERROR [" + String.valueOf(e.getMessage()) + "]"); status.error = e; if (infoStream != null) { e.printStackTrace(infoStream); } } return status; }
39be1188-e5d5-4714-bcce-fad30cfc48eb
9
@Override public boolean onCommand(final CommandSender sender, Command cmd, String label, String[] args) { if (label.equalsIgnoreCase("oreevent")) { if (sender instanceof Player) { plugin.reloadConfig(); if (plugin.getConfig().getString("orex") == null) { plugin.getConfig().set("orex", 0); plugin.saveConfig(); } if (plugin.getConfig().getString("orez") == null) { plugin.getConfig().set("orez", 0); plugin.saveConfig(); } if (plugin.getConfig().getString("maxrange") == null) { plugin.getConfig().set("maxrange", 1000); plugin.saveConfig(); } if (plugin.getConfig().getString("oresec") == null) { plugin.getConfig().set("oresec", 10); plugin.saveConfig(); } if (plugin.getConfig().getString("orestart") == null) { plugin.getConfig().set("orestart", 3); plugin.saveConfig(); } sender.sendMessage("Ore-Eventを開始しました。"); Player player = (Player) sender; final World w = player.getWorld(); Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { public void run() { Location loc = new Location((World) w, plugin.getConfig().getDouble("orex"), 0, plugin.getConfig().getDouble("orez")); loc.setX( loc.getX() + Math.random() * plugin.getConfig().getDouble("maxrange") * 2 - plugin.getConfig().getDouble("maxrange")); loc.setZ( loc.getZ() + Math.random() * plugin.getConfig().getDouble("maxrange") * 2 - plugin.getConfig().getDouble("maxrange")); loc.setY(256); w.spawnFallingBlock(loc, Material.DIAMOND_BLOCK, (byte) 0); sender.getServer().broadcastMessage(ChatColor.GOLD + "以下の座標にダイアモンドブロックが落下した!"); sender.getServer().broadcastMessage(ChatColor.GREEN + "X: " + loc.getX() + " Z: " + loc.getZ()); } }, 20*plugin.getConfig().getInt("orestart"), 20*plugin.getConfig().getInt("oresec")); return true; } else { sender.sendMessage("このコマンドはプレイヤーのみ使用できます。"); } } if (label.equalsIgnoreCase("oreconfig")) { if (sender instanceof Player) { sender.sendMessage(ChatColor.AQUA + "###コンフィグの情報###"); sender.sendMessage(ChatColor.GREEN + "orex: " + plugin.getConfig().getDouble("orex")); sender.sendMessage(ChatColor.GREEN + "orez: " + plugin.getConfig().getDouble("orez")); sender.sendMessage(ChatColor.GREEN + "maxrange: " + plugin.getConfig().getDouble("maxrange")); sender.sendMessage(ChatColor.AQUA + "#################"); } else { sender.sendMessage("このコマンドはプレイヤーのみ使用できます。"); } } return true; }
95b8a71e-1c81-4659-9663-098ca36414f8
6
public boolean move(Location from, Location to) { if (to != Location.B3 && to != Location.R3) { System.out.println("GAME: moving from " + from + " to " + to); if ( from == loneRiderHere1 ) { loneRiderHere1 = to; } else if ( from == loneRiderHere2 ) { loneRiderHere2 = to; } } else { System.out.println("GAME: Moving to B3/R3 is illegal (testing purposes)"); //Notify Observers for( GameObserver gO : this.observers ){ gO.checkerMove(from, from); } return false; } movesLeft--; //Notify Observers for( GameObserver gO : this.observers ){ gO.checkerMove(from, to); } return true; }
f52a9757-4478-43b5-ae84-81f0f26eab9c
0
public Capteur(int date1, int id1, int taille1) { super(date1, id1, taille1); }
21a8eb79-6f6c-4916-a46b-9a7ce97714a5
5
public static String getSelectString(Dictionary dictionary, Class c){ StringBuilder stringBuilder = new StringBuilder(); ArrayList <Dictionary> dictionaries = null; Field field; Object val = new Object(); try { field = c.getField("TABLE"); val = field.get(val); dictionaries = Dictionary.getItems(val.toString()); } catch (NoSuchFieldException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IllegalAccessException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } for(Dictionary d : dictionaries){ stringBuilder.append("[_] " + d.getName() + "; "); } if(dictionary == null){ return stringBuilder.toString(); }else if(dictionary.getId() == 0){ return stringBuilder.toString(); } else{ int i = stringBuilder.lastIndexOf(dictionary.getName()) - 3; stringBuilder.replace(i, i+1, "X"); } return stringBuilder.toString(); }
d17c3025-5da1-41d4-a36f-58af18a84c8b
4
private TreeNode successor(TreeNode predecessorNode) { TreeNode successorNode = null; if (predecessorNode.left != null) { successorNode = predecessorNode.left; while (successorNode.right != null) { successorNode = successorNode.right; } } else { successorNode = predecessorNode.parent; while (successorNode != null && predecessorNode == successorNode.left) { predecessorNode = successorNode; successorNode = predecessorNode.parent; } } return successorNode; }
e9a8c916-d66a-49d6-89cd-6ae6e30aefae
8
protected SSLServerSocketFactory createFactory() throws Exception { _keystore = System.getProperty( KEYSTORE_PROPERTY,_keystore); log.info(KEYSTORE_PROPERTY+"="+_keystore); if (_password==null) _password = Password.getPassword(PASSWORD_PROPERTY,null,null); log.info(PASSWORD_PROPERTY+"="+_password.toStarString()); if (_keypassword==null) _keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, null, _password.toString()); log.info(KEYPASSWORD_PROPERTY+"="+_keypassword.toStarString()); KeyStore ks = null; log.info(KEYSTORE_TYPE_PROPERTY+"="+_keystore_type); if (_keystore_provider_class != null) { // find provider. // avoid creating another instance if already installed in Security. java.security.Provider[] installed_providers = Security.getProviders(); java.security.Provider myprovider = null; for (int i=0; i < installed_providers.length; i++) { if (installed_providers[i].getClass().getName().equals(_keystore_provider_class)) { myprovider = installed_providers[i]; break; } } if (myprovider == null) { // not installed yet, create instance and add it myprovider = (java.security.Provider) Class.forName(_keystore_provider_class).newInstance(); Security.addProvider(myprovider); } log.info(KEYSTORE_PROVIDER_CLASS_PROPERTY+"="+_keystore_provider_class); ks = KeyStore.getInstance(_keystore_type,myprovider.getName()); } else if (_keystore_provider_name != null) { log.info(KEYSTORE_PROVIDER_NAME_PROPERTY+"="+_keystore_provider_name); ks = KeyStore.getInstance(_keystore_type,_keystore_provider_name); } else { ks = KeyStore.getInstance(_keystore_type); log.info(KEYSTORE_PROVIDER_NAME_PROPERTY+"=[DEFAULT]"); } ks.load( new FileInputStream( new File( _keystore ) ), _password.toString().toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance( "SunX509","SunJSSE"); km.init( ks, _keypassword.toString().toCharArray() ); KeyManager[] kma = km.getKeyManagers(); TrustManagerFactory tm = TrustManagerFactory.getInstance("SunX509","SunJSSE"); if (_useDefaultTrustStore) { tm.init( (KeyStore)null ); } else { tm.init( ks ); } TrustManager[] tma = tm.getTrustManagers(); SSLContext sslc = SSLContext.getInstance( "SSL" ); sslc.init( kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); log.info("SSLServerSocketFactory="+ssfc); return ssfc; }
b18c0864-89e0-458e-a8d8-87ca7ca30207
6
public static void main(String args[]) { 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(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(newJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new newJFrame().setVisible(true); } }); }
b80dafdd-f39f-42db-84f2-1f247a9b9f22
8
* @param input */ public static void writeHtmlEscapingUrlSpecialCharacters(PrintableStringWriter stream, String input) { { char ch = Stella.NULL_CHARACTER; String vector000 = input; int index000 = 0; int length000 = vector000.length(); for (;index000 < length000; index000 = index000 + 1) { ch = vector000.charAt(index000); if ((Stella.$CHARACTER_TYPE_TABLE$[(int) ch] == Stella.KWD_LETTER) || (Stella.$CHARACTER_TYPE_TABLE$[(int) ch] == Stella.KWD_DIGIT)) { stream.print(ch); } else { switch (ch) { case '-': case '_': case '.': case '~': stream.print(ch); break; default: { int code = (int) ch; if (code < 16) { stream.print("%0" + Native.integerToHexString(((long)(code)))); } else { stream.print("%" + Native.integerToHexString(((long)(code)))); } } break; } } } } return; }
ed4e041d-bb71-4f73-ae83-2137c4f83076
0
public void addSettingsGuiListener(SettingsGuiListener listener_) { settingsGuiListener.add(listener_); }
573cd886-6254-4c05-989d-cbc81692b94f
4
public static void buildGroup(ContactGroupEntry group, List<String> parameters) { for (String string : parameters) { if (!string.startsWith("--")) { throw new IllegalArgumentException("unknown argument: " + string); } String param = string.substring(2); String params[] = param.split("=", 2); if (params.length != 2) { throw new IllegalArgumentException("badly formated argument: " + string); } ElementHelper helper = find(params[0]); if (helper == null) { throw new IllegalArgumentException("unknown argument: " + string); } helper.parseGroup(group, new ElementParser(params[1])); } }
57a94b9d-1b51-49c9-ac3f-0d61c23293dc
3
public Link<T> getUnvisitedLink(Summit<T> summit) { for (Link<T> link : links) { if ( link.visited==false && link.start.label.equals(summit.label) ) { link.visited=true; return link; } } return null; }
870e1921-72e9-41b5-9676-92f266fab874
4
void checkNewVersion(Config config) { // Download command checks for versions, no need to do it twice if ((config != null) && !command.equalsIgnoreCase("download")) { // Check if a new version is available VersionCheck versionCheck = VersionCheck.version(SnpEff.SOFTWARE_NAME, SnpEff.VERSION_SHORT, config.getVersionsUrl(), verbose); if (!quiet && versionCheck.isNewVersion()) { System.err.println("\n\nNEW VERSION!\n\tThere is a new " + this.getClass().getSimpleName() + " version available: " // + "\n\t\tVersion : " + versionCheck.getLatestVersion() // + "\n\t\tRelease date : " + versionCheck.getLatestReleaseDate() // + "\n\t\tDownload URL : " + versionCheck.getLatestUrl() // + "\n" // ); } } }
1bd4d288-36b0-494b-a941-9d63528f4960
8
public FixtureBuilder() { fileParser = new FileParser(KEYS); List<File> files = FileUtils.getFiles("fixtures/"); for (File file : files) { try { Fixture fixture = buildFixture((FileUtils.readFile(file))); String missingKey = FileValidator.isValid(fixture, REQUIRED_KEYS); if (missingKey == null) { allFixtures.add(fixture); } else { System.out.println("Fixture file " + file.getName() + " missing key " + missingKey + ". Failed to create object"); } } catch (IOException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } for (Fixture fixture : allFixtures) { if (fixture.getRarity().equals(Rarity.COMMON)) { commonFixtures.add(fixture); } if (fixture.getRarity().equals(Rarity.UNCOMMON)) { uncommonFixtures.add(fixture); } if (fixture.getRarity().equals(Rarity.RARE)) { rareFixtures.add(fixture); } if (fixture.getRarity().equals(Rarity.EXTREMELY_RARE)) { extremelyRareFixtures.add(fixture); } } }
aec43faa-5b0d-43bb-96b7-90a610bc0256
3
@Override public void mouseClicked(MouseEvent e) { if (PlayerTypes.values()[raceSelectionPointer].getColors() != null) for (int i = 0; i < PlayerTypes.values()[raceSelectionPointer].getColors().length; i++) if (new Rectangle(getWidth() / 2 - getWidth() / 8 + getWidth() / 32 + i % 2 * getWidth() / 8, getHeight() / 8 + (i / 2 + 1) * getWidth() / 32, getWidth() / 16, getWidth() / 16) .intersects(e.getX(), e.getY(), 1, 1)) colorSelectionPointer = i; }
1b3098b4-d50b-4d0b-a1cc-35b41f93b5fd
8
private boolean bfs() { Queue<Integer> q = new ArrayDeque<Integer>(); //initialize distances for(int i = 1; i < n; i++) { if(match[i] == NIL) { dist[i] = 0; q.add(i); } else dist[i] = INF; } dist[NIL] = INF; while(!q.isEmpty()) { int u = q.poll(); if(DEBUG) System.out.format("Exploring %d\n", u); for(Edge e : G.edgesOf(u)) { int v = e.other(u); //if the matching is not visited, visit it //note that if v has no match, it is a free vertex in R if(dist[match[v]] == INF) { if(DEBUG) System.out.format("%d->%d->%d\n", u, v, match[v]); dist[match[v]] = dist[u] + 1; if(match[v] != NIL) q.add(match[v]); } } } //did we visit a free vertex in R? return dist[NIL] != INF; }
b3060e65-7ca7-46c2-8712-f054ef1d5490
1
private void onFirstStatChanged(Stat newStat) { for (StatProcessorListener listener: listeners) { listener.onFirstStat(newStat); } }
3903f880-18d6-40c2-86a7-72f607c5dfcf
7
@POST @Path("/Login") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response Login (UserResponse data) { if (data == null || data.password == null || data.username == null) return Response .status(400) // Bad request .entity(new ErrorResponse("No data supplied!")) .build(); try { if (UserInterface.getInstance().authenticateUser(data.username, data.password)) { // TODO: HMAC long userToken = UserInterface.setUser(data.username); NewCookie authCookie = new NewCookie( /* name: */ "token" /* value: */ , Long.toString(userToken) /* path: */ , "/UROP_1" /* domain: */ , null /* comment: */ , "Authentication token" /* maxAge: */ , NewCookie.DEFAULT_MAX_AGE /* secure: */ , false ); return Response.status(200) .cookie(authCookie) .build(); } else return Response .status(401) .entity(new ErrorResponse("Failed to log in!")) .build(); } catch (NoSuchAlgorithmException e) { // TODO: Log String error = "Not able to use SHA-512!"; System.err.println(error); return Response.status(501).entity(new ErrorResponse(error)).build(); } catch (UnknownHostException e) { // TODO: Log String error = "Not able to connect to MongoDB!\n" + e.getMessage(); System.err.println(error); return Response.status(503).entity(new ErrorResponse(error)).build(); } catch (MongoTimeoutException e) { // TODO: Log String error = "Connection to database timed out!"; System.err.println(error); return Response.status(503).entity(new ErrorResponse(error)).build(); } }
09dddba6-982c-499d-9eb4-71987c5032d2
4
private int readAndCheckInput(int low, int high) throws IOException { BufferedReader move = new BufferedReader(new InputStreamReader(System.in)); boolean bool; int in = 0; do { try { in = Integer.parseInt(move.readLine()); bool = false; } catch (NumberFormatException e) { System.out.print("Enter a number between " + low + " and " + high + " >> "); bool = true; } } while (bool); while (in < low || in > high) { in = Integer.parseInt(move.readLine()); } return in; }
a06f4074-9791-4da0-bf59-54e5f901eb52
8
public void addComponent(Component component, Location location){ switch(location){ case TOP: add(component,BorderLayout.PAGE_START); components.add("TopComponent", component); break; case BOTTOM: if(components.get("TopComponent") != null){ remove(components.get("TopComponent")); components.removeBykey("TopComponent"); }else{ throw(new NoComponentException()); } break; case LEFT: if(components.get("TopComponent") != null){ remove(components.get("TopComponent")); components.removeBykey("TopComponent"); }else{ throw(new NoComponentException()); } break; case RIGHT: if(components.get("TopComponent") != null){ remove(components.get("TopComponent")); components.removeBykey("TopComponent"); }else{ throw(new NoComponentException()); } break; case CENTER: add(component,BorderLayout.CENTER); components.add("CenterComponent", component); break; default: throw new InvalidPositionException(); } updateWindow(); }
e423e7b1-6a24-45c3-95cc-fcd8acc9d40b
0
public void setStartUrl(String startUrl) { this.startUrl = startUrl; }
2aed8a5f-ee1c-45bd-a820-035b9957f0d6
7
static void test2() { try { Reader in = new StringReader( "<INPUT TYPE=HIDDEN NAME=\"MfcISAPICommand\" VALUE = \"MailBox\">\n"+ "<applet code=\"htmlstreamer.class\" codebase=\"/classes/demo/parser\"\nalign=\"baseline\" width=\"500\" height=\"800\"\nid=\"htmlstreamer\">\n"+ "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML//EN\" id=foo disabled>"+ "" ); HtmlStreamTokenizer tok = new HtmlStreamTokenizer(in); HtmlTag tag = new HtmlTag(); while (tok.nextToken() != HtmlStreamTokenizer.TT_EOF) { StringBuffer buf = tok.getWhiteSpace(); if (buf.length() > 0) System.out.print(buf.toString()); if (tok.getTokenType() == HtmlStreamTokenizer.TT_TAG) { try { tok.parseTag(tok.getStringValue(), tag); if (tag.getTagType() == HtmlTag.T_UNKNOWN) throw new HtmlException("unkown tag"); System.out.print(tag.toString()); } catch (HtmlException e) { // invalid tag, spit it out System.out.print("\ninvalid: "); System.out.print("<" + tok.getStringValue() + ">"); System.out.println(""); } } else { buf = tok.getStringValue(); if (buf.length() > 0) System.out.print(buf.toString()); } } // hang out for a while System.in.read(); } catch (Exception e) { System.out.println(e.getMessage()); } }