method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
989ff214-959d-469b-ad75-34122eabc18e
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(HomeFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HomeFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HomeFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HomeFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HomeFrm(usr).setVisible(true); } }); }
e32ebf78-acaf-47c9-be83-dc99919db6c4
5
public void buyStock(String symbol, int quantity) throws BalanceException, StockNotExistException { boolean buyStockSucsses = false; int stockSymbolIndex = 0; if (balance <= 0) { throw new StockNotExistException(symbol); } // find the index of symbol for (int i = 0; i < portfolioSize; i++) { if (symbol.equals(this.stocksStatus[i].getSymbol())) { buyStockSucsses = true; stockSymbolIndex = i; } } // if the stock's name dosen't exists if (buyStockSucsses == false) { throw new StockNotExistException(symbol); } if (quantity == -1) { int numOfStocks = (int) (Math .floor((double) (balance / stocksStatus[stockSymbolIndex].ask))); this.stocksStatus[stockSymbolIndex].stockQuantity += numOfStocks; updateBalance(-numOfStocks * stocksStatus[stockSymbolIndex].ask); } updateBalance(-quantity * this.stocksStatus[stockSymbolIndex].ask); this.stocksStatus[stockSymbolIndex].stockQuantity += quantity; }
772a5c7d-dc8c-4200-83d2-d512495590b1
4
private String timeToString(long seconds) { long minutes = seconds / 60; seconds = seconds - minutes*60; if (minutes == 0 && seconds == 0) return "zero seconds"; else if (minutes == 0) return secondsToString(seconds); else if (seconds == 0) return minutesToString(minutes); else return minutesToString(minutes) + " and " + secondsToString(seconds); }
c9445969-ab89-41e0-bdb4-a9d38c5eb7ab
6
@Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; Neuron neur; g2.setColor(Color.WHITE); g2.fillRect(0, 0, getWidth(), getHeight()); g2.setPaint(Color.lightGray); for(int i=0;i<Data.getData().size();i+=2){ Ellipse2D.Double d = new Ellipse2D.Double(Data.getData().get(i).getPoids().get(0)*echelle, Data.getData().get(i).getPoids().get(1)*echelle,.5,.5); g2.draw(d); } if(world.getNet() != null && world.getNet().size() != 0){ for(int i=0;i<world.getNet().getNeurons().size();i++){ for(int k=0;k<world.getNet().getNeurons().get(i).size();k++){ g2.setPaint(Color.red); neur = world.getNet().getNeurons().get(i).get(k); //System.out.print("("+neur.getPoids().get(0)*echelle+";"+neur.getPoids().get(1)*echelle+")"+"|"); g2.fillOval ((int)(neur.getPoids().get(0)*echelle), (int)(neur.getPoids().get(1)*echelle), 5,5) ; g2.setPaint(Color.BLUE); for(int j=0;j<neur.getNeighbors().size();j++){ Line2D.Double l = new Line2D.Double(new Point2D.Double(neur.getPoids().get(0)*echelle, neur.getPoids().get(1)*echelle), new Point2D.Double(neur.getNeighbors().get(j).getPoids().get(0)*echelle, neur.getNeighbors().get(j).getPoids().get(1)*echelle) ); g2.draw(l); } } } } revalidate(); }
8e7040a2-3abc-476e-baad-7f6abfdf9623
5
public void unzip(String zipFile, String id) throws Exception { downloadPack.passwordLbl.setText("Extracting Files"); Console.log("Extracting " + id.replace("_", " ") ); downloadPack.progress.setValue(0); int BUFFER = 2048; File file = new File(zipFile); ZipFile zip = new ZipFile(file); String newPath = zipFile.substring(0, zipFile.length() - 4); Enumeration zipFileEntries = zip.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry)zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(file.getParentFile(), currentEntry); File destinationParent = destFile.getParentFile(); int fileSize = zip.size(); destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); Throwable localThrowable3 = null; try { byte[] data = new byte[BUFFER]; FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); Throwable localThrowable4 = null; try { int currentByte; while ((currentByte = is.read(data, 0, BUFFER)) != -1) { downloadPack.progress.setValue( (int)(currentByte * 100L / fileSize) ); dest.write(data, 0, currentByte); } dest.flush(); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1; throw localThrowable1; } finally { is.close(); dest.close(); fos.close(); } } catch (Throwable localThrowable2) { localThrowable3 = localThrowable2; throw localThrowable2; } } } zip.close(); file.delete(); downloadPack.passwordLbl.setText("Finnished!"); downloadMC(); }
e51420d6-e2bf-4301-89dd-2f8d141547cb
5
public static File downloadFileTo(String urlString, String ext, File dir) throws IOException { InputStream in = null; OutputStream out = null; File file = null; if (!dir.exists()) { // If the download directory does not exist, we create it. dir.mkdirs(); } try { in = openURLStream(urlString, null); file = File.createTempFile("web", ext, dir); // Creates a new empty file. out = new FileOutputStream(file); byte[] buffer = new byte[2048]; int length; // Copy every input into the output. while ((length = in.read(buffer, 0, 2048)) > 0) { out.write(buffer, 0, length); } Log.d("HTTPGet", "Download " + urlString + " to " + file.getAbsolutePath()); // Debug /* * This catch/finally is because we need to log what happened in this class and because * we need to close all streams (if we had thrown an exception without catching it, * we wouldn't have been able to close the streams properly). */ } catch (IOException e) { // Allows to close Streams Log.e("HTTPGet", "Error while downloading " + urlString + " to " + file.getAbsolutePath() + "\n\t" + e.getMessage()); throw e; } finally { // Closes all Streams if (in != null) in.close(); if (out != null) out.close(); } return file; }
9904b048-a49a-4c7a-be2c-302b5ff92edb
7
@Override public void run() { System.out.println("\tNew connection handler thread is running"); while (true) { HttpContext context = new BasicHttpContext(null); try { while (!Thread.interrupted() && this.conn.isOpen()) { this.httpservice.handleRequest(this.conn, context); } } catch (ConnectionClosedException ex) { System.err.println("Client closed connection"); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage()); } catch (HttpException ex) { System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage()); } finally { try { this.conn.shutdown(); } catch (IOException ignore) {} } } }
5d9210f2-ac93-4ced-92f3-117e0c1c58ed
0
@Override public Sala clone() { return new Sala(this); }
a5a723fb-efd3-404a-8d08-bed25939c3c8
5
private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; }
2765e524-59c8-46c0-bcca-bd6a753ac03d
0
public void setZip(String zip) { this.zip = zip; }
194a6de5-0d7d-4042-8dfa-fe0a631a7127
6
public Shape createStrokedShape( Shape shape ) { GeneralPath result = new GeneralPath(); shape = new BasicStroke( 10 ).createStrokedShape( shape ); PathIterator it = new FlatteningPathIterator( shape.getPathIterator( null ), FLATNESS ); float points[] = new float[6]; float moveX = 0, moveY = 0; float lastX = 0, lastY = 0; float thisX = 0, thisY = 0; int type = 0; @SuppressWarnings("unused") boolean first = false; float next = 0; while ( !it.isDone() ) { type = it.currentSegment( points ); switch( type ){ case PathIterator.SEG_MOVETO: moveX = lastX = randomize( points[0] ); moveY = lastY = randomize( points[1] ); result.moveTo( moveX, moveY ); first = true; next = 0; break; case PathIterator.SEG_CLOSE: points[0] = moveX; points[1] = moveY; // Fall into.... case PathIterator.SEG_LINETO: thisX = randomize( points[0] ); thisY = randomize( points[1] ); float dx = thisX-lastX; float dy = thisY-lastY; float distance = (float)Math.sqrt( dx*dx + dy*dy ); if ( distance >= next ) { float r = 1.0f/distance; //float angle = (float)Math.atan2( dy, dx ); while ( distance >= next ) { float x = lastX + next*dx*r; float y = lastY + next*dy*r; result.lineTo( randomize( x ), randomize( y ) ); next += detail; } } next -= distance; first = false; lastX = thisX; lastY = thisY; break; } it.next(); } return result; }
7fbf79e6-2a72-4059-94d1-6a752edaa6e9
2
public double rawAllResponsesMinimum(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawAllResponsesMinimum; }
a98b3d3d-152e-4d68-9825-ba119fa0b762
6
@Override public Object getItem(){ parent.zoomSlider.setValueIsAdjusting(true); String editorText = editor.getText(); int newVal =0; if(editorText!=null){ if(editorText.toLowerCase().endsWith("fit")) parent.zoomSlider.setValue(0); else{ StringBuffer numbers = new StringBuffer(); char c; for (int i=0;i<editorText.length();i++) { c = editorText.charAt(i); if (Character.isDigit(c)) { numbers.append(c); } } try{ newVal=Integer.parseInt(numbers.toString()); parent.zoomSlider.setValue(newVal); } catch (Exception e){ //fail silently if invalid } } } if(parent.zoomSlider.getValue()<300) { parent.zoomSlider.setValueIsAdjusting(false); return parent.zoomSlider.getValue(); } mainGUI.zoomTo(newVal); return newVal; } } class RefreshableComboBoxModel extends DefaultComboBoxModel{ RefreshableComboBoxModel(Object[] itmes){ super(itmes); } public void refresh(){ this.fireContentsChanged(this, 0, 2); }
ca8411a9-15aa-4ca1-b022-6d06ed478f41
1
public String toString() { StringBuilder s = new StringBuilder(); for (Planet p : planets) { // We can't use String.format here because in certain locales, the , // and . get switched for X and Y (yet just appending them using the // default toString methods apparently doesn't switch them?) s.append("P " + p.X() + " " + p.Y() + " " + p.Owner() + " " + p.NumShips() + " " + p.GrowthRate() + "\n"); } return s.toString(); }
462f12c4-e3ba-4204-a03f-08807f9895c5
1
private boolean isBecomeFull() { // Was ready, but become not boolean wasReady = ready; ready = isReady(); return (wasReady && !ready); }
249815ed-26a0-4c21-9d41-8a738d5207fc
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Listas)) { return false; } Listas other = (Listas) object; if ((this.iLista == null && other.iLista != null) || (this.iLista != null && !this.iLista.equals(other.iLista))) { return false; } return true; }
59942976-0007-4272-8e48-f3dae67363d4
8
protected boolean collision(int xa, int ya) { boolean solid = false; if (getDir() == 0) { if (level.getTile((x + xa) / 16, (y + ya) / 16).solid()) solid = true; } if (getDir() == 1) { if (level.getTile(((x + xa) / 16) + 1, (y + ya) / 16).solid()) solid = true; } if (getDir() == 2) { if (level.getTile((x + xa) / 16, ((y + ya) / 16) + 1).solid()) solid = true; } if (getDir() == 3) { if (level.getTile(((x + xa) / 16) - 1, (y + ya) / 16).solid()) solid = true; } return solid; }
aaccde9b-bdfd-450b-9c8d-44befaef70da
8
public static void unhideNeighborEmptyCells(BoardModel boardModel, Cell currentCell) { currentCell.setVisible(true); for (int i = currentCell.getPositionX() - 1; i <= currentCell.getPositionX() + 1; i++) { for (int j = currentCell.getPositionY() - 1; j <= currentCell.getPositionY() + 1; j++) { if (i == currentCell.getPositionX() && j == currentCell.getPositionY()) { continue; } if (!checkLimits(i, j, boardModel) || boardModel.getBoard()[i][j].isVisible()) { continue; } if (boardModel.getBoard()[i][j].isEmpty() || boardModel.getBoard()[i][j].isNumber()) { boardModel.getBoard()[i][j].setVisible(true); unhideCell(boardModel, new Point(i, j)); } } } }
80c8862a-620e-4605-b97f-cac599d56104
5
public static void main(String[] args){ // création des deux listes int i=0; List<AR> AR = new ArrayList<AR>(); List<AS> AS = new ArrayList<AS>(); Calcul.RepriseTableau(AR, AS); Saisie saisie = new Saisie(AR); boolean saisieOK = false; do { i =0; boolean trouve= false; while (!trouve && i < AR.size()) { // si le departement correspond à celui saisie lors de la fonction if(AR.get(i).getDept() == saisie.getDept()) trouve=true; else i++; } if (!trouve) { Scanner saisies = new Scanner(System.in); System.out.print("Veuillez saisir un bon numero de departement (21 - 25 - 39 - 44 - 72 - 73 - 74 - 75 - 85 - 90 : "); saisie.setDept(saisies.nextInt()); } else saisieOK=true; } while (!saisieOK); System.out.println("résultat : " + String.valueOf(Calcul.CalculTarifDepl(i, saisie, AR, AS)) + "€"); }
c0047e46-20e2-46a3-b39e-56a7e7498e74
7
public void doGet(HttpServletRequest req, HttpServletResponse resp) { resp.setContentType("text/plain"); AppIdentityCredential credential = new AppIdentityCredential( AnalysisConstants.SCOPES); String bigqueryProjectId = AnalysisUtility.extractParameterOrThrow(req, AnalysisConstants.BIGQUERY_PROJECT_ID_PARAM); String jobId = AnalysisUtility.extractParameterOrThrow(req, AnalysisConstants.BIGQUERY_JOB_ID_PARAM); String queueName = AnalysisUtility.extractParameterOrThrow(req, AnalysisConstants.QUEUE_NAME_PARAM); Bigquery bigquery = new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( SystemProperty.applicationId.get()).build(); boolean shouldRetry = false; try { Job j = bigquery.jobs().get(bigqueryProjectId, jobId).execute(); j.getConfiguration().getLoad().getSourceUris(); if ("DONE".equals(j.getStatus().getState())) { FileService fs = FileServiceFactory.getFileService(); List<AppEngineFile> filesForJob = new ArrayList<AppEngineFile>(); for (String f : j.getConfiguration().getLoad().getSourceUris()) { if (f.contains("gs://")) { String filename = f.replace("gs://", "/gs/"); AppEngineFile file = new AppEngineFile(filename); filesForJob.add(file); AppEngineFile schemaFile = new AppEngineFile(filename + ".schema.json"); filesForJob.add(schemaFile); log.info("Deleting: " + f + ", appengine filename: " + filename); } } fs.delete(filesForJob.toArray(new AppEngineFile[0])); } else { log.info("Status was not DONE, it was " + j.getStatus().getState() + ", retrying."); shouldRetry = true; } } catch (IOException e) { shouldRetry = true; } // check again in 5 mins if the job is done (and not too many retries String retryCountStr = req .getParameter(AnalysisConstants.RETRY_COUNT_PARAM); int retryCount = -1; if (AnalysisUtility.areParametersValid(retryCountStr)) { retryCount = Integer.parseInt(retryCountStr); } retryCount++; if (retryCount > 15) { log.warning("Tried too many times, aborting"); shouldRetry = false; } if (shouldRetry) { Queue taskQueue = QueueFactory.getQueue(queueName); taskQueue.add(Builder .withUrl( AnalysisUtility.getRequestBaseName(req) + "/deleteCompletedCloudStorageFilesTask") .method(Method.GET) .param(AnalysisConstants.BIGQUERY_JOB_ID_PARAM, jobId) .param(AnalysisConstants.QUEUE_NAME_PARAM, queueName) .param(AnalysisConstants.RETRY_COUNT_PARAM, String.valueOf(retryCount)) .etaMillis(System.currentTimeMillis() + 5 * 60 * 1000) .param(AnalysisConstants.BIGQUERY_PROJECT_ID_PARAM, bigqueryProjectId)); } }
30368100-8587-4903-a677-e2064df7f407
6
public static boolean hitPlane(SpaceRegion region, Direction plane, Vec3 position, Vec3 direction) { Vec3 normal = null; Vec3 p0; Vec3 p1; float D; //because math. Vec3 pointInPlane; //Extracting each plane can, for once, be done with some trickery. //also, notice how N and S have the same plane, with only the normal switched around. switch ( plane ) { case N: normal = new Vec3( 0.0f, 0.0f, -1.0f ); pointInPlane = region.localPosition; break; case S: normal = new Vec3( 0.0f, 0.0f, 1.0f ); pointInPlane = region.localPosition.add( region.size ); break; case W: normal = new Vec3( 1.0f, 0.0f, 0.0f ); pointInPlane = region.localPosition; break; case E: normal = new Vec3( -1.0f, 0.0f, 0.0f ); pointInPlane = region.localPosition.add( region.size ); break; case FLOOR: normal = new Vec3( 0.0f, 1.0f, 0.0f ); pointInPlane = region.localPosition; break; case CEILING: default: normal = new Vec3( 0.0f, -1.0f, 0.0f ); pointInPlane = region.localPosition.add( region.size ); break; } D = normal.scaled( -1.0f ).dotProduct( pointInPlane ); float t = Math.max( 0.0f, ( - ( normal.dotProduct( position ) + D )) / ( normal.dotProduct( direction ) ) ); Vec3 projection = getParametricVecFromRay(position, direction, t); return region.isInside( projection ); }
8cd46db2-9d6c-4923-920a-0d8c0b471c44
0
public int getBiome() {return biome;}
6f7994a4-ebd3-4414-8ec6-b95c5e7b2970
3
public void draw(Graphics2D g) { drawAura(g); Shape ellipse = new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius); if (getInitial() != 0) { ellipse = new Rectangle2D.Double(x - radius, y - radius, 2 * radius, 2 * radius); } g.setColor(color); g.fill(ellipse); g.setColor(Canvas.contrastColor(color, Constrast.borderbw)); g.draw(ellipse); if (!GUI.player.model.settings.isProperty(Property.anonym)) { g.setColor(Canvas.contrastColor(color, Constrast.textbw)); g.setFont(new Font(Font.DIALOG, Font.PLAIN, (int) (13 * Math.sqrt(1)))); String caption = Canvas.shorten(g, ((Integer) ID).toString(), (int) (radius * 2), Preference.begin); if (caption.endsWith("..")) caption = "V"; g.drawString(caption, (float) (x - g.getFontMetrics().stringWidth(caption) / 2), (float) (y + g.getFontMetrics().getAscent() / 2)); } }
2fd6d84a-2126-428a-930e-18bb83e53b59
1
public V remove(K key) { V val = get(key); if (val == null) { return null; } // removeAt(keys, currentIndex); // removeAt(values, currentIndex); checkEnoughCapacity(1); // Switch the chosen element and the last one exchangeWithLast(keys, currentIndex); exchangeWithLast(values, currentIndex); // Remove links to the chosen element keys[currentSize - 1] = null; values[currentSize - 1] = null; currentSize--; return val; }
cbbe0bd9-0728-4ac9-8e4d-342527e84ff0
0
public void start() { timer.start(); }
08d0f6b4-99a6-4eac-a149-6daf11f29541
4
@Override public Event next() { try { input = br.readLine(); } catch (IOException e1) { } if(input == null || input.equals("")) { return new UserHomeState(as, name); } else{ try{ as.bid(name, Long.parseLong(input)); } catch(Exception e){ return new SearchResultsState(as, name, input); } return new UserHomeState(as, name); } }
1bfffa1a-50ed-48fc-9dd7-3e52053ceb28
6
@Override public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) { String staffChatMessage = ""; if (!isPlayer) { sender.sendMessage(ChatColor.RED + "Run this command from ingame."); return; } if (!player.hasPermission("mymessages.staffchat")) { player.sendMessage(ChatColor.RED + "Access denied."); return; } if (args.length < 1) { player.sendMessage(ChatColor.RED + "Usage: /" + commandName + " <message>"); return; } staffChatMessage += this.plugin.combineSplit(0, args, " "); staffChatMessage = this.plugin.format(staffChatMessage); if (staffChatMessage != null) { for (Player plr : this.plugin.getServer().getOnlinePlayers()) { if (plr.hasPermission("mymessages.staffchat")) { plr.sendMessage(ChatColor.GOLD + "[Staff Chat] " + ChatColor.RESET + player.getDisplayName() + ": " + staffChatMessage); } } } else { player.sendMessage(ChatColor.RED + "Error: Could not send message."); } }
8279f0d8-4f1c-4096-848a-8fae36fee5c2
6
public void blink() { if (getWorld().getObjects(Dolphin.class).size() != 0) { getXD = ((Dolphin) getWorld().getObjects(Dolphin.class).get(0)).getX(); getYD = ((Dolphin) getWorld().getObjects(Dolphin.class).get(0)).getY(); setLocation(getXD - 15 ,getYD - 25); } if (shocked > 0) { if (blinks <= 30) { setImage(a1); } else if (blinks > 30 && blinks < 60) { setImage(a2); } } else if (shocked == 0) { getWorld().removeObject(this); } }
d8ad78bf-9e2a-4849-ac4d-b5de3d157bfe
5
public void propagateValues(List<String> cliValues) { int argValueIdx = 0; int valueIdx = 0; while (argValueIdx < cliValues.size()) { if (argValueIdx >= values.size()) { // more data then values ... abort break; } else { IValue<?> value = values.get(valueIdx); if (!value.isMultiValued()) { value.setCurrentValueFromCli(cliValues.get( argValueIdx ) ); argValueIdx++; valueIdx++; } else { String t = ""; for (int i = argValueIdx; i < cliValues.size(); i++) { t += cliValues.get( argValueIdx ) + " "; argValueIdx++; } value.setCurrentValueFromCli(t); break; } } } // end while }
e3d35f37-b38b-4d50-8965-b4f7aa7e29f9
1
private void loadPreferences() { Preferences preferences = BrainPreferences.getPreferences(); if (preferences != null) { String leftName = preferences.get(PreferencesNames.LEFT_NAME, ""); String rightName = preferences.get(PreferencesNames.RIGHT_NAME, ""); String maxRounds = preferences.get(PreferencesNames.MAX_SCORE, "0"); leftNameField.setText(leftName); rightNameField.setText(rightName); roundsCountField.setText(maxRounds); dataSourceCombo.setSelectedIndex(Integer.parseInt(preferences.get(PreferencesNames.DATASOURCE, "0"))); hostnameTextField.setText(preferences.get(PreferencesNames.HOSTNAME, "localhost")); databaseNameTextField.setText(preferences.get(PreferencesNames.MYSQL_DATABASE, "")); usernameTextField.setText(preferences.get(PreferencesNames.MYSQL_USERNAME, "")); passwordTextField.setText(preferences.get(PreferencesNames.MYSQL_PASSWORD, "")); selectDataSource(); NamesManager.getInstance().setNames(leftName, rightName); RoundManager.getInstance().setMaxRound(Integer.parseInt(maxRounds)); } }
104c379d-522b-4577-adbc-58886e19137a
4
private static void checkAndDeleteDir(FileSystem fileSystem, String directory) throws TestFailedException { try { if (fileSystem.pathExists(directory)) fileSystem.deleteDirectoryRecursively(directory); if (fileSystem.pathExists(directory)) throw new TestFailedException("I deleted the directory " + directory + " recursively, but pathExists says it does exist"); } catch (PathNotFoundException e) { throw new TestFailedException("deleteDirectoryRecursively(" + directory + ")", e); } catch (AccessDeniedException e) { throw new TestFailedException(e); } }
337a8dc9-39c4-4220-b19f-45c4e71c79e3
9
private static boolean isAssignable(Class<?>[] formal, Class<?>[] actual) { if (formal.length != actual.length) { return false; } for (int i = 0; i < formal.length; i++) { if (actual[i] == null) { if ((formal[i].equals(int.class)) || (formal[i].equals(double.class)) || (formal[i].equals(boolean.class))) { return false; } continue; } if (!formal[i].isAssignableFrom(actual[i])) { return false; } } return true; }
2fa6f9ea-0d05-4db8-a4a3-a13c9c2a13c6
8
private void processBody(HttpURLConnection conn) throws Exception{ if(type == HttpResponseType.RAW){ data = conn.getInputStream(); }else{ final BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream())); switch(type){ //return raw input stream. case RAW: assert false : HttpResponseType.RAW; data = conn.getInputStream(); break; //do nothing case NULL: data = null; break; //return input lines as Strings. case SOURCE: ArrayList<String> ret = new ArrayList<>(); String line; while ((line = input.readLine()) != null){ ret.add(line); } data = ret; break; //return JSON. case JSON: Parser<?> parser = getParser(); if(parser!=null){ data = parser.parse(input); }else{ data = JsonParser.qucikParse(input); } break; //DAFUQ ?! default: throw new IllegalArgumentException("Invalid type : "+type); } } }
a59ba84d-6d61-49fb-a822-5eff7a39f207
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Parameter that = (Parameter) obj; if (key == null) { if (that.key != null) return false; } else if (!key.equals(that.key)) return false; if (value == null) { if (that.value != null) return false; } else if (!value.equals(that.value)) return false; return true; }
04e0abfe-02af-4afa-8346-68d39949b98e
9
protected boolean writeClass(ClassWriter classWriter, String className) throws IOException, ConstantPoolException { JavaFileObject fo = open(className); if (fo == null) { reportError("err.class.not.found", className); return false; } ClassFileInfo cfInfo = read(fo); if (!className.endsWith(".class")) { String cfName = cfInfo.cf.getName(); if (!cfName.replaceAll("[/$]", ".").equals(className.replaceAll("[/$]", "."))) reportWarning("warn.unexpected.class", className, cfName.replace('/', '.')); } write(cfInfo); if (options.showInnerClasses) { ClassFile cf = cfInfo.cf; Attribute a = cf.getAttribute(Attribute.InnerClasses); if (a instanceof InnerClasses_attribute) { InnerClasses_attribute inners = (InnerClasses_attribute) a; try { boolean ok = true; for (int i = 0; i < inners.classes.length; i++) { int outerIndex = inners.classes[i].outer_class_info_index; ConstantPool.CONSTANT_Class_info outerClassInfo = cf.constant_pool.getClassInfo(outerIndex); String outerClassName = outerClassInfo.getName(); if (outerClassName.equals(cf.getName())) { int innerIndex = inners.classes[i].inner_class_info_index; ConstantPool.CONSTANT_Class_info innerClassInfo = cf.constant_pool.getClassInfo(innerIndex); String innerClassName = innerClassInfo.getName(); classWriter.println("// inner class " + innerClassName.replaceAll("[/$]", ".")); classWriter.println(); ok = ok & writeClass(classWriter, innerClassName); } } return ok; } catch (ConstantPoolException e) { reportError("err.bad.innerclasses.attribute", className); return false; } } else if (a != null) { reportError("err.bad.innerclasses.attribute", className); return false; } } return true; }
c3a6280e-9f45-49fc-bba5-d6b6c5ce45cc
4
private static void writeMapObject(MapObject mapObject, XMLWriter w, String wp) throws IOException { w.startElement("object"); w.writeAttribute("name", mapObject.getName()); if (mapObject.getType().length() != 0) w.writeAttribute("type", mapObject.getType()); w.writeAttribute("x", mapObject.getX()); w.writeAttribute("y", mapObject.getY()); if (mapObject.getWidth() != 0) w.writeAttribute("width", mapObject.getWidth()); if (mapObject.getHeight() != 0) w.writeAttribute("height", mapObject.getHeight()); writeProperties(mapObject.getProperties(), w); if (mapObject.getImageSource().length() > 0) { w.startElement("image"); w.writeAttribute("source", getRelativePath(wp, mapObject.getImageSource())); w.endElement(); } w.endElement(); }
3ec5d277-a702-440b-9aa2-70abea959137
7
private List<String> verifyBracketTokens(List<String> tokens) throws ParserException { List<String> newTokens = new ArrayList<String>(); int bracketType = -1; String[] brackets = null; for (int i = 2; i < tokens.size() && bracketType < 0; i++) { if (!"".equals(tokens.get(i))) bracketType = i; } switch (bracketType) { case 2: brackets = new String[] { "$", "$" }; break; case 3: brackets = new String[] { "(", ")" }; break; case 4: brackets = new String[] { "[", "]" }; break; case 5: brackets = new String[] { "{", "}" }; break; default: return null; } String tokenString = tokens.get(bracketType); newTokens.add(brackets[0]); newTokens.add(tokenString); newTokens.add(brackets[1]); return newTokens; }
d13777ac-8061-4d02-b1cf-81da59b7290c
6
private static void closeConnection() { try { if (resultSet != null) resultSet.close(); if (preparedStatement != null) preparedStatement.close(); if (preparedStatement2 != null) preparedStatement2.close(); if (preparedStatement3 != null) preparedStatement3.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } }
d346131c-bca8-427c-a3dd-fe49c4cd1b40
7
private static Object findJarServiceProvider(String factoryId) throws ConfigurationException { String serviceId = "META-INF/services/" + factoryId; InputStream is = null; // First try the Context ClassLoader ClassLoader cl = ClassLoaderSupport.getContextClassLoader(); if (cl != null) { is = ClassLoaderSupport.getResourceAsStream(cl, serviceId); // If no provider found then try the current ClassLoader if (is == null) { cl = FactoryFinder.class.getClassLoader(); is = ClassLoaderSupport.getResourceAsStream(cl, serviceId); } } else { // No Context ClassLoader, try the current ClassLoader cl = FactoryFinder.class.getClassLoader(); is = ClassLoaderSupport.getResourceAsStream(cl, serviceId); } if (is == null) { // No provider found return null; } LOG.debug("found jar resource [{}], using ClassLoader [{}]", serviceId, cl); BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(is, "UTF-8")); } catch (java.io.UnsupportedEncodingException e) { rd = new BufferedReader(new InputStreamReader(is)); } String factoryClassName = null; try { // XXX Does not handle all possible input as specified by the // Jar Service Provider specification factoryClassName = rd.readLine(); rd.close(); } catch (IOException x) { // No provider found return null; } if (factoryClassName != null && !"".equals(factoryClassName)) { LOG.debug("found provider [{}] in resource", factoryClassName); // Note: here we do not want to fall back to the current // ClassLoader because we want to avoid the case where the // resource file was found using one ClassLoader and the // provider class was instantiated using a different one. return newInstance(factoryClassName, cl, false); } // No provider found return null; }
da758682-fc45-4737-a593-56fc15b4eed4
8
public static void main(String args[]) throws Throwable{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); for(int N;(N=parseInt(in.readLine().trim()))!=0;){ TreeMap<int[],Integer> mapa=new TreeMap<int[],Integer>(new Comparator<int[]>(){ public int compare(int[] o1,int[] o2){ for(int i=0;i<o1.length;i++)if(o1[i]!=o2[i])return o1[i]-o2[i]; return 0; } }); int max=0; for(int i=0;i<N;i++) { int[] s=new int[5]; StringTokenizer st=new StringTokenizer(in.readLine()); for(int j=0;j<5;j++)s[j]=parseInt(st.nextToken()); Arrays.sort(s); Integer a=mapa.get(s); if(a==null)a=0; a++; max=max(max,a); mapa.put(s,a); } int sol=0; for(Entry<int[],Integer> entry:mapa.entrySet()) if(entry.getValue()==max) sol+=entry.getValue(); System.out.println(sol); } System.out.print(new String(sb)); }
7a955ea3-8d4f-4cdb-98fd-5ddb777d8d1b
9
public static List<Inaugurador> listaDeInauguradores() { ResultSet tr = null; String select = "SELECT * FROM cargo_inaugura"; ArrayList<Inaugurador> listaInaugurador = new ArrayList<Inaugurador>(); Connection conexion = null; Statement statement = null; try { conexion = DataSourceFactory.getMySQLDataSource().getConnection(); } catch (SQLException sqle) { System.out.println("Error: " + sqle); } try { statement = conexion.createStatement(); tr = statement.executeQuery(select); while (tr.next()) { Inaugurador inaugurador = new Inaugurador(); inaugurador.setIdCargoInaugura(tr.getString("idCargoInaugura")); inaugurador.setNombreCargoInaugura(tr.getString("nombreCargoInaugura")); listaInaugurador.add(inaugurador); } } catch (SQLException sqle) { System.out.println(sqle); } finally { if (tr != null) try { tr.close(); } catch (SQLException e) { e.printStackTrace(); } if (statement != null) try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } if (conexion != null) try { conexion.close(); } catch (SQLException e) { e.printStackTrace(); } } return listaInaugurador; }
34b2d7a5-cb5b-4922-becb-df745c635be1
2
@Override public void shoot(){ for(Weapon<? extends actor.ship.projectile.Projectile> weapon : weapons){ weapon.shoot(this, Vector3f.newRandom(1)); } }
9718a773-cf14-40b4-a1df-aa9f449e6906
1
public Vector2D unitVector(){ float mag = magnitude(); if (mag == 0) return new Vector2D(0,0); float newX = x/mag; float newY = y/mag; return new Vector2D(newX,newY); }
10965c97-c0ef-4baa-abd0-efecc10d4dd3
4
public void loadSprite(String ref) { BufferedReader reader; try { reader = new BufferedReader(new FileReader(System.getProperty("resources") + "/database/sprites")); String line; while((line = reader.readLine()) != null) { final String[] temp = line.split(";"); if(temp[0].matches(ref)) { this.maxDir = Integer.parseInt(temp[1]); this.maxFrame = Integer.parseInt(temp[2]); } } } catch (FileNotFoundException e) { System.out.println("The sprite database has been misplaced!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Sprite database failed to load!"); e.printStackTrace(); } }
4756f574-f0db-42ec-ae1e-201c0750085f
8
public final Instances resampleWithWeights(Instances data, Random random, boolean[] sampled) { double[] weights = new double[data.numInstances()]; for (int i = 0; i < weights.length; i++) { weights[i] = data.instance(i).weight(); } Instances newData = new Instances(data, data.numInstances()); if (data.numInstances() == 0) { return newData; } double[] probabilities = new double[data.numInstances()]; double sumProbs = 0, sumOfWeights = Utils.sum(weights); for (int i = 0; i < data.numInstances(); i++) { sumProbs += random.nextDouble(); probabilities[i] = sumProbs; } Utils.normalize(probabilities, sumProbs / sumOfWeights); // Make sure that rounding errors don't mess things up probabilities[data.numInstances() - 1] = sumOfWeights; int k = 0; int l = 0; sumProbs = 0; while ((k < data.numInstances() && (l < data.numInstances()))) { if (weights[l] < 0) { throw new IllegalArgumentException("Weights have to be positive."); } sumProbs += weights[l]; while ((k < data.numInstances()) && (probabilities[k] <= sumProbs)) { newData.add(data.instance(l)); sampled[l] = true; newData.instance(k).setWeight(1); k++; } l++; } return newData; }
30eaffad-aab2-4e9c-a243-b29b2497a5ad
7
public static List<CDDFeature> removeOverlaps(List<CDDFeature> features) { List<CDDFeature> newFeatures = new ArrayList<CDDFeature>(); CDDFeature lastFeature = null; Collections.sort(features); for (CDDFeature feature: features) { // System.out.println("Looking at "+hit); if (lastFeature == null || feature.getFrom() > lastFeature.getTo()) { // System.out.println("Adding "+hit); newFeatures.add(feature); lastFeature = feature; } else { // They overlap. Figure out which one to show. int index = newFeatures.size()-1; // Is it a complete overlap? if (lastFeature.getFrom() == feature.getFrom() && lastFeature.getTo() == feature.getTo()) { // Yes, we're done continue; } else { // Is the second feature within the first feature? if (feature.getTo() <= lastFeature.getTo()) { // System.out.println("Splitting "+lastFeature.getName()); // Yes, insert it and split lastFeature CDDFeature truncatedFeature = new CDDFeature(lastFeature.getProteinId(),lastFeature.getAccession(), lastFeature.getFeatureType(), lastFeature.getFrom(), feature.getFrom()); // System.out.println("Updating "+truncatedFeature); newFeatures.set(index,truncatedFeature); // System.out.println("Adding "+hit); newFeatures.add(feature); lastFeature = feature; if (lastFeature.getTo() > feature.getTo()) { truncatedFeature = new CDDFeature(lastFeature.getProteinId(),lastFeature.getAccession(), lastFeature.getFeatureType(), feature.getTo(), lastFeature.getTo()); // System.out.println("Adding "+truncatedFeature); newFeatures.add(truncatedFeature); lastFeature = truncatedFeature; } continue; } // More complicated. We need to truncate the first one CDDFeature truncatedFeature = new CDDFeature(lastFeature.getProteinId(),lastFeature.getAccession(), lastFeature.getFeatureType(), lastFeature.getFrom(), feature.getFrom()); // System.out.println("Updating "+truncatedFeature); newFeatures.set(index,truncatedFeature); // System.out.println("Adding "+feature); newFeatures.add(feature); lastFeature = feature; } } } return newFeatures; }
1753742e-51bb-48c3-b8f8-66b149a7730b
2
public static void seq_e(CompList<?> t) { for (Compound c : t) { c.execute(); } }
2f8d1346-222c-4925-b7f8-89c188833b6d
6
public void open() { System.out.println(WELCOME); System.out.println(USE_HELP); request = getCommand(); while (!request.equals(EXIT_COMMAND)) { if (request.equals(HELP_COMMAND)) { for(int i = 0; i < COUNT_OF_COMMANDS; i++) { System.out.println(COMMANDS_DESCRIPTION[i]); } request = getCommand(); continue; } if (request.equals(START_GAME_WITH_MAN_COMMAND)) { System.out.println(REQUEST_FIELD_SIZE); game = new Game(getFieldSize()); game.startWithHuman(); request = getCommand(); continue; } if (request.equals(START_GAME_WITH_COMPUTER_COMMAND)) { System.out.println(REQUEST_FIELD_SIZE); game = new Game(getFieldSize()); game.startWithComputer(); request = getCommand(); continue; } if (request.trim().equals(ABOUT_COMMAND)) { System.out.println(ABOUT_DEVELOPER); request = getCommand(); continue; } else { System.out.println(ERROR_IN_COMMAND); request = getCommand(); continue; } } }
2fe766f7-8372-4e47-a4a1-3766942c984a
1
public String retrieveTemplate(String catalogLink, String templateName) throws Exception{ String response = doGet(catalogLink); String catalogItemLink = findElement(response, Constants.CATALOGITEM, Constants.CATALOGITEM_LINK, templateName); response = doGet(catalogItemLink); String element = findElement(response, Constants.ENTITY, Constants.TEMPLATE_LINK, templateName); if( element == null){ throw new Exception("No vApp template found that matches the given name: " + templateName); } return element; }
6d5f3144-5283-44ce-858b-b2e3ac107aa0
7
public ListNode reverseBetween(ListNode head, int m, int n) { if(m==n) return head; ListNode start = null; ListNode beforestart = null; ListNode curr = null; for(int i=0; i<m-1; i++) { beforestart = beforestart==null?head:beforestart.next; } start = beforestart==null?head:beforestart.next; ListNode end = start; curr = start.next; ListNode oldNext = curr.next; for(int i=0; i<n-m; i++) { oldNext = curr.next; curr.next = start; start = curr; curr = oldNext; } end.next = oldNext; if(beforestart!= null) beforestart.next = start; return (beforestart== null?start:head); }
b256d1fd-8252-48b2-becf-fe79283aa7be
8
protected String compute() { if (element == null) return null; switch (element.getType()) { case OBJECT: return serializeObject(); case ARRAY: return serializeArray(); case STRING: return serializeString((String)element.getData()); case NUMBER: return serializeNumber((Number)element.getData()); case BOOLEAN: return serializeBoolean((Boolean)element.getData()); case DATE: return serializeDate((Date)element.getData()); case NULL: default: return "null"; } }
067f5254-a8f8-4015-93b3-1e7d89810788
0
private static File initMap() throws IOException { String map = "...?????...\n" + ".#.#?#?#.#.\n" + "..???????..\n" + "?#?#?#?#?#?\n" + "????.$.????\n" + "?#?#$$$#?#?\n" + "????.$.????\n" + "?#?#?#?#?#?\n" + "..???????..\n" + ".#.#?#?#.#.\n" + "...?????..."; // File located to the root folder of this project. // File mapFile = new File("map1.txt"); File mapFile = File.createTempFile("map", "txt"); FileWriter fw = new FileWriter(mapFile); fw.write("11 11\n"); fw.append(map); fw.append("\n"); fw.flush(); fw.close(); return mapFile; }
00b77863-ffda-4b67-bfe4-267f28f53ed9
6
public static float[][] getSecondCenter(float[][] X, int min, int max) { int i = max - min + 1; float tempX[][] = new float[i][X[0].length]; float tempY[][] = new float[i][X[0].length]; // float temp = 0; for (int t = 0; t < i; t++) { for (int k = 0; k < X.length; k++) { // decide whether the point belong to a cluster if ((min + t) == X[k][0]) { tempX[t][0] = min + t; for (int j = 1; j < X[0].length; j++) { tempX[t][j] = X[k][j] + tempX[t][j]; tempY[t][j] = tempY[t][j] + 1; } } } } // calculate virtual centroid in a cluster for (int k = 0; k < tempX.length; k++) { for (int j = 1; j < tempX[0].length; j++) { tempX[k][j] = tempX[k][j] / (tempY[k][j]); } } return tempX; }
015d3aa9-e2b8-48a5-9c26-f233b7f1fdda
7
@Override public void actionPerformed(ActionEvent e) { Response response = null; if (messageForm.getFromTextField().trim().length() < 1 || messageForm.getToTextField().trim().length() < 1 || messageForm.getSubjectTextField().trim().length() < 1 || messageForm.getContentTextArea().trim().length() < 1) { JOptionPane.showMessageDialog(messageForm, "One or more fields is missing.", "Missing Field(s)", JOptionPane.ERROR_MESSAGE); }else{ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm ' on' MMMM dd yyyy", Locale.ENGLISH); String dateAsString = simpleDateFormat.format(new Date()); MailBox mailBox = new MailBox(null, dateAsString, messageForm.getSubjectTextField(), messageForm.getContentTextArea(), messageForm.getFromTextField(), messageForm.getToTextField()); List<Object> mailList = new ArrayList<Object>(); mailList.add(mailBox); Request request = (new Request(RequestCriteria.SEND_LETTER, null)); request.setObjList(mailList); try { response = ServerConnect.connect(request); } catch (IOException e1) { e1.printStackTrace(); } if (response != null && response.getSuccess()==true) { System.out.println("Ok"); } } }
18c85411-abcf-41e1-bb35-13943ffb41ff
8
private void grabSequenceAndOutput() throws IOException{ BufferedWriter out = new BufferedWriter(new FileWriter(outputDirectory + "/" + "SEQ_" + annotationFile.substring(annotationFile.lastIndexOf('/') + 1, annotationFile.lastIndexOf('.')) + ".fasta")); Sequence_DNA seq = null; int currentSequence = 0; //Loop through the functGroups for(int j = 0; j < functGroups.size(); j++){ ArrayList<Integer> currentGroup = functGroups.get(j); //Load up the appropriate chromosome to get DNA from if(currentSequence != GTFlist.get(currentGroup.get(0)).getChromosomeName()){ currentSequence = GTFlist.get(currentGroup.get(0)).getChromosomeName(); U.p("Sequencing chromsome file: " + genomeFiles.get(currentSequence - 1).substring(genomeFiles.get(currentSequence -1).lastIndexOf('/') + 1, genomeFiles.get(currentSequence -1 ).lastIndexOf('.'))); seq = new Sequence_DNA(genomeFiles.get(currentSequence - 1)); } //Calculate the header information for the current group String header = getHeader(currentGroup); //Write out each lines header to the results file out.write(header + "\n"); //Grab this genes sequence StringBuffer sequence = new StringBuffer(); if(GTFlist.get(currentGroup.get(0)).getGenomicStrand() == Definitions.genomicStrandPOSITIVE){ sequence.append(seq.getNucleotideSequences().get(0).getSequence().substring(GTFlist.get(currentGroup.get(0)).getStartLocation() - 1, GTFlist.get(currentGroup.get(0)).getStopLocation() - 1)); } //If the strand is negative if(GTFlist.get(currentGroup.get(0)).getGenomicStrand() == Definitions.genomicStrandNEGATIVE){ sequence = new StringBuffer(); //The reverse strand requires a index off by one sequence.append(seq.getNucleotideSequences().get(0).getSequence().substring(GTFlist.get(currentGroup.get(0)).getStartLocation() , GTFlist.get(currentGroup.get(0)).getStopLocation())); //Reverse and compliment the negative strand so it will be accurate sequence.reverse(); //Compliment the sequence StringBuffer temp = new StringBuffer(); for(int k = 0; k < sequence.length(); k++){ temp.append(DNACompliment(sequence.charAt(k))); } sequence = temp; }//Negative //Only write the sequence if this is the last occurrence of this gene if(j + 1 < functGroups.size()){ if(GTFlist.get(functGroups.get(j+1).get(0)).getGene_Name().equals(GTFlist.get(currentGroup.get(0)).getGene_Name())){ if(GTFlist.get(functGroups.get(j+1).get(0)).getGene_Type().equals(GTFlist.get(currentGroup.get(0)).getGene_Type())){ continue; } } } //Write hte sequence out out.write(sequence.toString() + "\n"); }//for //Ensure that the BufferedWriter flushes the pipeline and writes the data to disk. out.flush(); out.close(); }//grabSequenceAndOutput
7ef3ccb2-b191-45d2-a4cb-4a94f3a16bb0
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainVentana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainVentana().setVisible(true); } }); }
1bf05394-d7a3-43a9-a4de-e77987d039e7
6
private Client(int port) { String input = null; int inputOption = 0; boolean validInput = false; System.out .println("Wählen sie zwischen Host(1), Verbindung(2) oder Computergegner(3)."); while (!validInput) { try { input = Eingabe.getEingabe().getUserInput(); } catch (Exception e) { // Nothing } try { inputOption = Integer.parseInt(input); } catch (Exception e) { Ausgabe.getAusgabe().printFalscheEingabe(); continue; } switch (inputOption) { case 1: beTheHost(port); setIsHost(true); validInput = true; break; case 2: connectToHost(port); validInput = true; break; case 3: setIsLocal(true); setIsHost(true); validInput = true; break; default: Ausgabe.getAusgabe().printFalscheEingabe(); break; } } }
bc582a3d-d6d1-48be-a4cf-1f0d1330d015
4
public int getFlag(final OffsetPoint n) { final int x = n.getX() - offset.getX(); final int y = n.getY() - offset.getY(); if (x >= 0 && y >= 0 && x < flags.length && y < flags[x].length) { return flags[x][y]; } else { return -1; } }
79b29b2d-71ff-4339-a8c8-8d89bc0b6460
8
public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); StringBuilder out = new StringBuilder(); int times = in.nextInt(); for (int i = 0; i < times; i++) { int nCoins = in.nextInt(); int[] c = new int[nCoins]; for (int j = 0; j < c.length; j++) c[j] = in.nextInt(); Arrays.sort(c); int sum = 0, ans = 0; for (int j = 0; j < c.length; j++) sum += c[j]; ans = sum; boolean[][] cr = new boolean[nCoins][sum + 1]; for (int j = 0; j < c.length; j++) { ans = Math.min(Math.abs(c[j] * 2 - sum), ans); cr[j][0] = true; if (j == 0) cr[j][c[j]] = true; else for (int k = 0; k <= sum; k++) { cr[j][k] |= cr[j - 1][k]; if (k >= c[j] && cr[j - 1][k - c[j]]) { ans = Math.min(Math.abs(k * 2 - sum), ans); cr[j][k] = true; } } } out.append(ans + "\n"); } System.out.print(out); }
e16ba637-7ddc-4c1b-b299-5e7223967d0c
6
@Override public void mouseClicked(MouseEvent e) { Point mouseGridPosition = board.getPosOnGrid(new Point(e.getPoint())); for (Enemy currentEnemy : board.getAllEnemiesInCurrentWave()) { if( currentEnemy.isWithinObject(new Point(e.getPoint())) && currentEnemy.isAlive()) { graphicalInformationViewer.currentObject(currentEnemy); graphicalViewer.higlight(currentEnemy); return; } } // this part handels where to build towers for (Tower currentTower : board.getAllTowers()) { if (currentTower.getPosition().getX() == mouseGridPosition.getX() && currentTower.getPosition().getY() == mouseGridPosition.getY() ) { graphicalInformationViewer.currentObject(currentTower); graphicalViewer.higlight(currentTower); lastClickedPosition = mouseGridPosition; return; } } graphicalViewer.higlightPoint(mouseGridPosition); lastClickedPosition = mouseGridPosition; }
d9259012-17ea-430f-a3bf-317d74cc3eca
7
* @return Returns true if the given edge may be splitted by the given * cell. */ public boolean isSplitTarget(Object target, Object[] cells) { if (target != null && cells != null && cells.length == 1) { Object src = model.getTerminal(target, true); Object trg = model.getTerminal(target, false); return (model.isEdge(target) && isCellConnectable(cells[0]) && getEdgeValidationError(target, model.getTerminal(target, true), cells[0]) == null && !model.isAncestor(cells[0], src) && !model.isAncestor( cells[0], trg)); } return false; }
3ce1c9f5-4919-41bf-be60-9f19275c1e6e
2
public static void trackRemove(String tag) { if(!trackedTags.containsKey(tag) && !trackedTags.remove(tag)) { System.out.println("[Debugger] Tag " + tag + " was not being tracked."); } else { trackedTags.remove(tag); System.out.println("[Debugger] Tag " + tag + " is no longer tracked."); } }
9fd21ee4-899f-409b-b892-0919b8aca9ad
1
protected static Integer parseInteger(final Object obj, final String type) throws ParseException { final Integer result; try { result = Integer.valueOf(obj.toString()); } catch (NumberFormatException nfe) { throw new ParseException(obj + " is not a valid " + type + "."); } return result; }
69bf2a98-a13e-4da4-99ac-f7092bf0bd4a
4
public byte[] readBinaryFromFile( String filename ) { RandomAccessFile f = null; try { f = new RandomAccessFile( new File( filename ),"r"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } byte[] b = null; try { b = new byte[ (int) f.length() ]; } catch (IOException e) { e.printStackTrace(); } try { f.read(b); } catch (IOException e) { e.printStackTrace(); } try { f.close(); } catch (IOException e) { e.printStackTrace(); } return b; }
ee1c8cd6-bfd7-42a9-af9e-4ebb0e2b0d3d
7
public static MapaTuberias fromElement(Node tuberias, Mapa mapa, Dinero d) throws NoSeCumplenLosRequisitosException, FondosInsuficientesException, SuperficieInvalidaParaConstruir, CoordenadaInvalidaException { MapaTuberias mapaTuberias = new MapaTuberias(mapa); NodeList hijosDeRed = tuberias.getChildNodes(); for (int i = 0; i < hijosDeRed.getLength(); i++) { Node hijoDeRed = hijosDeRed.item(i); if (hijoDeRed.getNodeName().equals("mapa")) { NodeList hijosDeMapa = hijoDeRed.getChildNodes(); for (int j = 0; j < hijosDeMapa.getLength(); j++) { Node hijoDeMapa = hijosDeMapa.item(j); if (hijoDeMapa.getNodeName().equals("Nodo")) { NodeList hijosDeNodo = hijoDeMapa.getChildNodes(); String stringPunto = ""; Coordenada puntoAAgregar = new Coordenada(); for (int k = 0; k < hijosDeNodo.getLength(); k++) { Node hijoDeNodo = hijosDeNodo.item(k); if (hijoDeNodo.getNodeName().equals("Coordenada")) { stringPunto = hijoDeNodo.getTextContent(); String[] arrayPunto = stringPunto.split(","); puntoAAgregar = new Coordenada( Integer.valueOf(arrayPunto[0]), Integer.valueOf(arrayPunto[1])); } else if (hijoDeNodo.getNodeName().equals( "Tuberia")) { Tuberia tb = new Tuberia(mapa, d, puntoAAgregar); tb.fromElement(hijoDeNodo); mapaTuberias.agregar(tb); d.add(tb.costo()); } } } } } } return mapaTuberias; }
2048342b-dc6e-4d1c-9383-71fc947494e4
6
private static String cut_the_pattern(String lemma_sentence) { String[] lemma_sentence_tokens = lemma_sentence.split(" "); String final_pattern = ""; Boolean found = false; for(int i = 0; i < lemma_sentence_tokens.length; i++){ if(i+1 < lemma_sentence_tokens.length && lemma_sentence_tokens[i+1].equals("<S>")){ found = true; } if(i-1 > 0 && lemma_sentence_tokens[i-1].equals("<O>")){ final_pattern += lemma_sentence_tokens[i]; break; } if(found){ final_pattern += lemma_sentence_tokens[i] + " "; } } return final_pattern; }
82211f27-3d29-40eb-9e76-e3088caf4561
1
public boolean testValue(double val) { return (mmin <= val && val <= mmax); }
bf33eeb3-51e1-498c-8d00-94afbdcb7431
5
public static int min (int[] element) throws IllegalArgumentException { if (element.length == 0) { throw new IllegalArgumentException ("tom samling"); } int[] sekvens = element; int antaletPar = sekvens.length / 2; int antaletOparadeElement = sekvens.length % 2; int antaletTankbaraElement = antaletPar + antaletOparadeElement; int[] delsekvens = new int[antaletTankbaraElement]; int i= 0; int j = 0; while(sekvens.length > 1) { // skilj ur en delsekvens med de tänkbara elementen i = 0; i = 0; j = 0; // Skriver ut sekvensen System.out.println(Arrays.toString(sekvens)); // Jämför de två talen parvis och behåller det minsta för en ny sekvens while (j < antaletPar) { delsekvens[j++] = (sekvens[i] < sekvens[i + 1]) ? sekvens[i] : sekvens[i + 1]; i += 2; } // Går igenom det oparade elementet, om det finns. if(antaletOparadeElement == 1) { delsekvens[j] = sekvens[sekvens.length - 1]; } sekvens = delsekvens; antaletPar = sekvens.length / 2; antaletOparadeElement = sekvens.length % 2; antaletTankbaraElement = antaletPar + antaletOparadeElement; // Måste fixa en ny delsekvens/mängd annars jobbar den med samma mängd delsekvens = new int[antaletTankbaraElement]; } return sekvens[0]; }
44010e85-d050-4fb3-967a-61e4d8dab218
3
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub ArrayStack<Integer> temp = new ArrayStack<Integer>(15); Integer[] h= new Integer[3]; h[0]=8; h[1]=9; h[2]=10; System.out.println("Add elements:"); for(int i = 0; i <8; i++) temp.add(i); temp.addAll(h); System.out.println(temp.toString()); System.out.println("Delete last element:"); temp.remove(); System.out.println(temp.toString()); System.out.println("Empty? "+temp.isEmpty()); System.out.println("Size: "+temp.size()); System.out.println("Get element with index 3: "+temp.get(3)); Iterator iter = temp.iterator(); System.out.println("Print array after deleting seventh element:"); for (int i=0; i<6; i++) { System.out.println(iter.next()); } iter.remove(); while (iter.hasNext()) { System.out.println(iter.next()); } System.out.println("Size: "+temp.size()); System.out.println("First element: "+temp.peek()); System.out.println("Clear array"); temp.clear(); System.out.println("Empty? "+temp.isEmpty()); System.out.println(temp.toString()); System.out.println("Size: "+temp.size()); System.out.println("The attempt to remove last element:"); temp.remove(); }
f28231a2-c6da-49f3-9d48-5cc7d1b6423a
5
public static double getOperationDiscount(EditOperation editOperation, int previousEdits) { double discount = 1; if(previousEdits > 0){ int edits = previousEdits; switch (editOperation){ case Insert: discount = 0.33/ edits; break; case Delete: discount = 0.33 / edits; break; case Match: discount = 1; break; case Substitution: discount = 0.33 / edits; break; } } return discount; }
bdb78651-50df-4807-8a5a-df08fbadd8ef
7
private void readAbilities(String path, DataModel dataModel) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(path)); // normalize text representation doc.getDocumentElement().normalize(); NodeList listOfStats = doc.getElementsByTagName("ability"); for (int s = 0; s < listOfStats.getLength(); s++) { Node statNode = listOfStats.item(s); if (statNode.getNodeType() == Node.ELEMENT_NODE) { Element abilityElement = (Element) statNode; String className = getTagValue("class", abilityElement); Ability ability = null; String tagValue = getTagValue("tag", abilityElement); if (className == null) { ability = new Ability(tagValue, LanguageTools.translate(getTagValue("name", abilityElement))); } else { String classPath = "dss.abilities." + className; @SuppressWarnings("unchecked") Class<Ability> abilityClass = (Class<Ability>) Class.forName(classPath); Constructor<Ability> constructor = abilityClass.getConstructor(String.class, String.class); ability = constructor.newInstance(tagValue, LanguageTools.translate(getTagValue("name", abilityElement))); } ability.setIconName(getTagValue("icon", abilityElement)); ability.setCooldown((int) (1000 * Double.parseDouble(getTagValue("cooldown", abilityElement)))); ability.setCasttime(Integer.parseInt(getTagValue("cast", abilityElement))); ability.setCost(Integer.parseInt(getTagValue("cost", abilityElement))); dataModel.getAvailableAbilities().add(tagValue, ability); } } } catch (SAXParseException err) { System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); System.out.println(" " + err.getMessage()); } catch (SAXException e) { Exception x = e.getException(); ((x == null) ? e : x).printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } }
6efc70ec-a6c8-409e-a2d8-d62327bdc5b9
3
public void checkCollision() { for (int i = 0; i < people.length; i++) for (int j = i+1; j < people.length; j++) if (people[i].colliding(people[j])) people[i].collide(people[j]); }
1fbc28b7-1025-48cc-9577-11c69476228a
6
* @param unit The <code>Unit</code> to unload. * @param goods The <code>Goods</code> to unload. * @return An <code>Element</code> encapsulating this action. */ public Element unloadCargo(ServerPlayer serverPlayer, Unit unit, Goods goods) { ChangeSet cs = new ChangeSet(); Location loc; Settlement settlement = null; if (unit.isInEurope()) { // Must be a dump of boycotted goods loc = null; } else if (unit.getTile() == null) { return DOMMessage.clientError("Unit not on the map."); } else if (unit.getSettlement() != null) { settlement = unit.getTile().getSettlement(); loc = settlement; } else { // Dump of goods onto a tile loc = null; } goods.adjustAmount(); moveGoods(goods, loc); boolean moved = false; if (unit.getInitialMovesLeft() != unit.getMovesLeft()) { unit.setMovesLeft(0); moved = true; } if (settlement != null) { cs.add(See.only(serverPlayer), settlement.getGoodsContainer()); cs.add(See.only(serverPlayer), unit.getGoodsContainer()); if (moved) cs.addPartial(See.only(serverPlayer), unit, "movesLeft"); } else { cs.add(See.perhaps(), (FreeColGameObject) unit.getLocation()); } // Others might see a capacity change. sendToOthers(serverPlayer, cs); return cs.build(serverPlayer); }
59e493ae-5127-43ee-80c5-ecd883b5e4fa
0
public Point3 multiply(double multiplier) { x *= multiplier; y *= multiplier; z *= multiplier; return this; }
b365a04b-a705-4e69-ab3b-2f0cb274b938
1
public void run() { Object[] i = this.getCars().toArray(); for(Object o: i) { Vehicle v = (Vehicle)o; remove(v); v.setDisposed(); v = null; } _ts.enqueue(_ts.currentTime() + MP.simulationTimeStep, this); }
26d21aec-b3fb-4b12-8323-837abab27066
8
private void mainRequest(){ final JSONHandler webHandle = new JSONHandler( this.MCAC ); final HashMap<String, String> url_items = new HashMap<String, String>(); url_items.put( "maxPlayers", String.valueOf( this.MCAC.getServer().getMaxPlayers() ) ); url_items.put( "version", this.MCAC.getDescription().getVersion() ); url_items.put( "exec", "callBack" ); final HashMap<String, String> response = webHandle.mainRequest(url_items); if(response.containsKey("oldVersion")){ String oldVersion = response.get("oldVersion"); if(!oldVersion.equals("")){ // Version replies can be: // 3.3imp, 3.3 // The former being the update is important and should be downloaded ASAP, the latter is that the update does not contain a critical fix/patch if (oldVersion.endsWith("imp")) { oldVersion = oldVersion.replace("imp", ""); this.MCAC.broadcastView( ChatColor.BLUE + "A newer version of MCAC (" + oldVersion + ") is now available!"); this.MCAC.broadcastView( ChatColor.RED + "This is an important/critical update."); } else { this.MCAC.broadcastView( ChatColor.BLUE + "A newer version of MCAC (" + oldVersion + ") is now available!"); } if (response.containsKey("patchNotes")) { final String patchNotes = response.get("patchNotes"); if(!patchNotes.equals("")){ this.MCAC.broadcastView( ChatColor.BLUE + "Patch Notes v" + oldVersion); this.MCAC.broadcastView(patchNotes); } } } } if(response.containsKey("hasNotices")) { for(final String cb : response.keySet()) { if (cb.contains("notice")) { this.MCAC.broadcastView( ChatColor.GOLD + "Notice: " + ChatColor.WHITE + response.get(cb)); } } } this.MCAC.hasErrored(response); }
150975d8-c7fa-4bc2-b9ad-89c71012b374
2
public LoginViewHelper getLoginViewHelper(HttpServletRequest req) throws UnsupportedEncodingException { LoginViewHelper loginViewHelper = new LoginViewHelper(); if (req.getParameter("email") != null) { loginViewHelper.setEmail(new String(req.getParameter("email") .getBytes("iso-8859-1"), "UTF-8")); } if (req.getParameter("password") != null) { loginViewHelper.setPassword(new String(req.getParameter("password") .getBytes("iso-8859-1"), "UTF-8")); } return loginViewHelper; }
6915eea2-6da6-4097-853f-847c9f8aaf3c
8
public static int test(Object channel, long action, Object ... args) { System.out.println("Sending action:" + action + " across channel:'" + channel.toString() + "'"); int returnCode = 0; if(args.length > 0) { System.out.println(" Arguments:"); for(Object arg:args) System.out.println(" " + arg.getClass().getName() + ": " + arg.toString()); } else { System.out.println(" No Arguments"); } EventActionSendResult sendResult = EventRouter.send(channel, action, args); if(sendResult.getResults() != null && sendResult.getResults().size() > 0) { System.out.println(" Results:"); for(EventActionResult result:sendResult.getResults()) { System.out.println(" Got: " + result.getResult()); System.out.println(" by calling: " + result.getMethod().getName()); System.out.println(" on: " + result.getObjectInvoked().toString()); } } else { returnCode++; System.out.println(" No Results"); } if(sendResult.getErrors() != null && sendResult.getErrors().size() > 0) { System.out.println(" Errors:"); for(EventActionError error:sendResult.getErrors()) { System.out.println(" Exception: " + error.getException().getClass().getName()); System.out.println(" with message: " + error.getException().getMessage()); System.out.println(" by calling: " + error.getMethod().getName()); System.out.println(" on: " + error.getReceivingObject().toString()); } } else { returnCode++; System.out.println(" No Errors"); } System.out.println(); return returnCode; }
f52466c7-f50e-4342-afea-1e8c7275f332
5
private static void lisaaOliotListoihin(HashMap<String, Kayttaja> kayttajat, String nimimerkki, Kayttaja kayttaja, HashMap<String, KenttaProfiili> profiilit, String kenttaProfiiliNimi, KenttaProfiili profiili) { if (!nimimerkki.equals("Anon") &&!kayttajat.containsKey(nimimerkki)) { kayttajat.put(nimimerkki, kayttaja); } if (!profiilit.containsKey(kenttaProfiiliNimi)) { profiilit.put(kenttaProfiiliNimi, profiili); } if (!nimimerkki.equals("Anon") && !kayttajat.get(nimimerkki).getKaikkiProfiilit().containsKey(kenttaProfiiliNimi)){ kayttajat.get(nimimerkki).addProfiili(profiili); } }
8dc031c4-f367-4cbe-b858-4ae83cdfa156
1
private void updateEntities(double deltaTime) { for (Entity entity : entities) { entity.update(deltaTime); } }
2c477d2a-0ced-4cfa-9581-8a4082a64e1d
0
public void setDepartureEnd(int value) { this._departureEnd = value; }
02e06138-baf6-4d23-a13d-ecda27ca84b2
0
public static void main(String[] args) { // TODO code application logic here }
316d1814-0123-4cab-be82-9b7ecbc7f35b
3
public static File[] save(Saveable saveable) { if (saveable == null) { return new File[0]; } File file = saveable.getBackingFile(); if (file != null) { File[] files = saveable.saveTo(file); for (File one : files) { RecentFilesMenu.addRecent(one); } return files; } return SaveAsCommand.saveAs(saveable); }
86fbdaee-7384-434d-a357-606fee627ce5
7
public MOB getAnyElligibleOfficer(Law laws, Area myArea, MOB criminal, MOB victim) { final Room R=criminal.location(); if(R==null) return null; if((myArea!=null)&&(!myArea.inMyMetroArea(R.getArea()))) return null; MOB M=getElligibleOfficerHere(laws,myArea,R,criminal,victim); if((M==null)&&(myArea!=null)) { for(final Enumeration e=myArea.getMetroMap();e.hasMoreElements();) { final Room R2=(Room)e.nextElement(); M=getElligibleOfficerHere(laws,myArea,R2,criminal,victim); if(M!=null) break; } } return M; }
72c9f615-a8f2-4312-8094-9dff0e742b8b
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(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); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NewJFrame().setVisible(true); } }); }
a0e7b458-7fbd-429d-bfad-e940eee52d8e
0
@Basic @Column(name = "FES_ID_FUNCIONARIO") public Integer getFesIdFuncionario() { return fesIdFuncionario; }
1a85f9ff-0f7e-4ba5-bdaf-e1169d597cbe
0
@Test @TestLink(externalId="testCreateTimeStamp") public void testCreateTimeStamp() { final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC"); TimeZone.setDefault(timeZoneUTC); final Calendar calendar = Calendar.getInstance(timeZoneUTC, Locale.US); calendar.setTimeInMillis(0); final InTestLinkXmlRunListener inTestLinkStrategy = new InTestLinkXmlRunListener("noone"); Xpp3Dom timeStamp = inTestLinkStrategy.createTimeStamp(calendar.getTime()); assertEquals(XML_HEADER + "<timestamp>1970-01-01 00:00:00</timestamp>", timeStamp.toString()); }
d4b4e090-b448-4b52-a62c-4c0ca1329503
7
static PortWatcher getPort(Session session, String address, int lport) throws JSchException{ InetAddress addr; try{ addr=InetAddress.getByName(address); } catch(UnknownHostException uhe){ throw new JSchException("PortForwardingL: invalid address "+address+" specified.", uhe); } synchronized(pool){ for(int i=0; i<pool.size(); i++){ PortWatcher p=(PortWatcher)(pool.elementAt(i)); if(p.session==session && p.lport==lport){ if(/*p.boundaddress.isAnyLocalAddress() ||*/ (anyLocalAddress!=null && p.boundaddress.equals(anyLocalAddress)) || p.boundaddress.equals(addr)) return p; } } return null; } }
fa449693-e9e6-4900-9d20-505465537fb0
0
public Submit getSubmit() { return submit; }
c84bf718-1df0-41b8-9c0d-e99fc3f1b170
5
private static <T> String makePrimitiveStrings(String className, T value) { StringBuilder result = new StringBuilder(); if (className.equals("java.lang.Short")) return result + value.toString() + "S"; else if (className.equals("java.lang.Long")) return result + value.toString() + "L"; else if (className.equals("java.lang.Float")) return result + value.toString() + "F"; else if (className.equals("java.math.BigInteger")) return result + value.toString() + "BigInteger"; else if (className.equals("java.math.BigDecimal")) return result + value.toString() + "BigDecimal"; else /* * (className.equals("java.lang.Integer") || * className.equals("java.lang.Double") || * className.equals("java.lang.Character") || * className.equals("java.lang.Byte") || * className.equals("java.lang.Boolean")) */ return result + value.toString(); }
420ab22b-0842-4bf3-a23a-71324b20d80f
9
protected void computeFloor(final float[] vector) { int n=vector.length; final int values=xList.length; final boolean[] step2Flags=new boolean[values]; final int range=RANGES[multiplier-1]; for(int i=2; i<values; i++) { final int lowNeighbourOffset=lowNeighbours[i];//Util.lowNeighbour(xList, i); final int highNeighbourOffset=highNeighbours[i];//Util.highNeighbour(xList, i); final int predicted=Util.renderPoint( xList[lowNeighbourOffset], xList[highNeighbourOffset], yList[lowNeighbourOffset], yList[highNeighbourOffset], xList[i]); final int val=yList[i]; final int highRoom=range-predicted; final int lowRoom=predicted; final int room=highRoom<lowRoom?highRoom*2:lowRoom*2; if(val!=0) { step2Flags[lowNeighbourOffset]=true; step2Flags[highNeighbourOffset]=true; step2Flags[i]=true; if(val>=room) { yList[i]=highRoom>lowRoom? val-lowRoom+predicted: -val+highRoom+predicted-1; } else { yList[i]=(val&1)==1? predicted-((val+1)>>1): predicted+(val>>1); } } else { step2Flags[i]=false; yList[i]=predicted; } } final int[] xList2=new int[values]; System.arraycopy(xList, 0, xList2, 0, values); sort(xList2, yList, step2Flags); int hx=0, hy=0, lx=0, ly=yList[0]*multiplier; float[] vector2=new float[vector.length]; float[] vector3=new float[vector.length]; Arrays.fill(vector2, 1.0f); System.arraycopy(vector, 0, vector3, 0, vector.length); for(int i=1; i<values; i++) { if(step2Flags[i]) { hy=yList[i]*multiplier; hx=xList2[i]; Util.renderLine(lx, ly, hx, hy, vector); Util.renderLine(lx, ly, hx, hy, vector2); lx=hx; ly=hy; } } final float r=DB_STATIC_TABLE[hy]; for(; hx<n/2; vector[hx++]=r); }
78800db9-675e-4518-aa36-c02086b161c8
9
public static void normalizeExistsProposition(Proposition self) { { Proposition whereproposition = ((Proposition)((self.arguments.theArray)[0])); { Object old$Evaluationmode$000 = Logic.$EVALUATIONMODE$.get(); try { Native.setSpecial(Logic.$EVALUATIONMODE$, Logic.KWD_DESCRIPTION); Proposition.normalizeProposition(whereproposition); } finally { Logic.$EVALUATIONMODE$.set(old$Evaluationmode$000); } } if (whereproposition.kind == Logic.KWD_EXISTS) { { Cons combinedargs = Stella.NIL; { PatternVariable vbl = null; Vector vector000 = ((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null))); int index000 = 0; int length000 = vector000.length(); Cons collect000 = null; for (;index000 < length000; index000 = index000 + 1) { vbl = ((PatternVariable)((vector000.theArray)[index000])); if (collect000 == null) { { collect000 = Cons.cons(vbl, Stella.NIL); if (combinedargs == Stella.NIL) { combinedargs = collect000; } else { Cons.addConsToEndOfConsList(combinedargs, collect000); } } } else { { collect000.rest = Cons.cons(vbl, Stella.NIL); collect000 = collect000.rest; } } } } { PatternVariable vbl = null; Vector vector001 = ((Vector)(KeyValueList.dynamicSlotValue(whereproposition.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null))); int index001 = 0; int length001 = vector001.length(); Cons collect001 = null; for (;index001 < length001; index001 = index001 + 1) { vbl = ((PatternVariable)((vector001.theArray)[index001])); if (collect001 == null) { { collect001 = Cons.cons(vbl, Stella.NIL); if (combinedargs == Stella.NIL) { combinedargs = collect001; } else { Cons.addConsToEndOfConsList(combinedargs, collect001); } } } else { { collect001.rest = Cons.cons(vbl, Stella.NIL); collect001 = collect001.rest; } } } } KeyValueList.setDynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, Logic.copyConsListToVariablesVector(combinedargs), null); self.arguments = whereproposition.arguments; whereproposition.deletedPSetter(true); } } if (((Vector)(KeyValueList.dynamicSlotValue(self.dynamicSlots, Logic.SYM_LOGIC_IO_VARIABLES, null))).emptyP() || (whereproposition.kind == Logic.KWD_CONSTANT)) { Proposition.overlayProposition(self, whereproposition); } } }
b2409f49-e0f3-4673-89ee-194045e0369f
5
private double doNamedVal(int beg, int end) { while(beg<end && Character.isWhitespace(expression.charAt(end))) { end--; } // since a letter triggers a named value, this can never reduce to beg==end String nam=expression.substring(beg,(end+1)); Double val; if ((val=constants.get(nam))!=null) { return val.doubleValue(); } else if((val=variables.get(nam))!=null) { isConstant=false; return val.doubleValue(); } else if(relaxed ) { isConstant=false; return 0.0; } throw exception(beg,"Unrecognized constant or variable \""+nam+"\""); }
3b870791-ce50-45c5-a97c-ddb707388829
9
@Override public boolean tick(Tickable ticking, int tickID) { if((affected!=null)&&(affected instanceof Room)) { final Room R=(Room)affected; if((R.myResource()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_VEGETATION) for(int m=0;m<R.numInhabitants();m++) { final MOB M=R.fetchInhabitant(m); if(M!=null) { Ability A=M.fetchEffect("Farming"); if(A==null) A=M.fetchEffect("Foraging"); if(A==null) A=M.fetchEffect("MasterFarming"); if(A==null) A=M.fetchEffect("MasterForaging"); if(A!=null) A.setAbilityCode(3); } } } return super.tick(ticking,tickID); }
e76de267-c425-4cce-ae11-409dc4f13182
6
public void run() { //this will be ran every 10 seconds //get difference in area //update hitpoints //if print count is 6 then print scores and set to 0 //if hitpoints = 0 or 100i am //declare a winner //else //set to call again another 10 seconds //set printcount to 0 int[] res = plugin.countInCapturableArea(area, defendingTeam, attackingTeam); hitpoints += res[0]; //System.out.println(hitpoints); if(res[1] == 0 && res[2] == 0) timeout++; if(timeout >= 12) plugin.declareWinner(area, defendingTeam, attackingTeam, defendingTeam); else if(hitpoints <= 0) //attackers win { //declare attackers plugin.declareWinner(area, defendingTeam, attackingTeam, attackingTeam); } else if (hitpoints >= 100) //defenders win { //declare defenders plugin.declareWinner(area, defendingTeam, attackingTeam, defendingTeam); } else { //continue plugin.continueSiege(area, defendingTeam, attackingTeam); printCount++; printTotal += res[0]; } if(printCount >= 6) { //print current core plugin.printSiegeProgress(area, defendingTeam, attackingTeam, res[2], res[1], hitpoints, printTotal); printCount = 0; printTotal = 0; } }
141a79b7-9765-46a7-a3ae-f5575b1396ba
9
private static Cell construct(Sequence s1, Sequence s2, float[][] matrix, float o, float e, byte[] pointers, int[] lengths) { logger.info("Started..."); char[] a1 = s1.toArray(); char[] a2 = s2.toArray(); int m = s1.length() + 1; // number of rows in similarity matrix int n = s2.length() + 1; // number of columns in similarity matrix float[] v = new float[n]; float vDiagonal = 0;// Float.NEGATIVE_INFINITY; // best score in cell float f = Float.NEGATIVE_INFINITY; // score from diagonal float h = Float.NEGATIVE_INFINITY; // best score ending with gap from // left float[] g = new float[n]; // best score ending with gap from above // Initialization of v and g g[0] = Float.NEGATIVE_INFINITY; for (int j = 1; j < n; j++) { v[j] = 0;// -o - (j - 1) * e; g[j] = Float.NEGATIVE_INFINITY; } int lengthOfHorizontalGap = 0; int[] lengthOfVerticalGap = new int[n]; float similarityScore; float maximumScore = Float.NEGATIVE_INFINITY; int maxi = 0; int maxj = 0; // Fill the matrices for (int i = 1, k = n; i < m; i++, k += n) { // for all rows v[0] = -o - (i - 1) * e; for (int j = 1, l = k + 1; j < n; j++, l++) { // for all columns similarityScore = matrix[a1[i - 1]][a2[j - 1]]; f = vDiagonal + similarityScore;// from diagonal // Which cell from the left? if (h - e >= v[j - 1] - o) { h -= e; lengthOfHorizontalGap++; } else { h = v[j - 1] - o; lengthOfHorizontalGap = 1; } // Which cell from above? if (g[j] - e >= v[j] - o) { g[j] = g[j] - e; lengthOfVerticalGap[j] = lengthOfVerticalGap[j] + 1; } else { g[j] = v[j] - o; lengthOfVerticalGap[j] = 1; } vDiagonal = v[j]; v[j] = maximum(f, g[j], h); // best one if (v[j] > maximumScore) { maximumScore = v[j]; maxi = i; maxj = j; } // Determine the traceback direction if (v[j] == f) { pointers[l] = Directions.DIAGONAL; } else if (v[j] == g[j]) { pointers[l] = Directions.UP; lengths[l] = lengthOfVerticalGap[j]; } else if (v[j] == h) { pointers[l] = Directions.LEFT; lengths[l] = lengthOfHorizontalGap; } } // loop columns // Reset h = Float.NEGATIVE_INFINITY; vDiagonal = 0;// -o - (i - 1) * e; lengthOfHorizontalGap = 0; } // loop rows Cell cell = new Cell(); cell.set(maxi, maxj, v[n - 1]); logger.info("Finished."); return cell; }
6debc367-7b8b-4241-afbf-e34583a2581b
6
public boolean nextMove(int row, int col) { HashMap<Integer, Coords> choices = new HashMap<Integer, Coords>(); //Returns true for a valid and successful move boolean result = false; int r = game.getBoard().board_row; int c = game.getBoard().board_col; int highest_flips = 0; for(int i = 0 ; i < r; i++) { for(int j = 0; j < c; j++) { Coords current_coords = new Coords(i, j); Chip current_chip = this.game.getBoard().getChip(i, j); ChipColor current_color = current_chip.getChipColor(); if(current_chip.getStatus() == false && this.game.getBoard().isValid(current_coords, this, false)) { int total_flips = game.getBoard().countFlips(current_coords, this); choices.put(total_flips, current_coords); if(total_flips > highest_flips) highest_flips = total_flips; } } } if(!choices.isEmpty()) { Coords final_choice; final_choice = choices.get(highest_flips); this.game.getBoard().isValid(final_choice, this, true); result = true; } return result; }
cf88b317-ced6-4df5-9159-687cd9c72f7c
4
public static boolean validarLogin(Usuario[] usuarios) { Scanner sc = new Scanner(System.in); String user = ""; String password = ""; System.out.println("Digite seu login: "); user = sc.nextLine(); System.out.println("Digite sua senha: "); password = sc.nextLine(); for (Usuario usuario : usuarios) { if (usuario != null) { if (usuario.login.equals(user) && usuario.senha.equals(password)) { System.out.println("Seja bem vindo " + usuario.nome + " !"); return true; } } else { break; } } System.out.println("Usuário não encontrado."); return false; }
7e10518b-ed74-44fa-943b-67fbd8da85cf
5
public static String formatOutput(JSONObject obj) { String ausgabe = ""; JSONObject result = new JSONObject(); try { result = obj.getJSONObject("result"); // result ist unser Referenz // JSON-Objekt. von da aus // erreichen wir alle Daten ausgabe = getStringOutputLine("Produktname", "name", result) + getStringOutputLine("Revision", "revision", result) + getStringOutputLine("Rabattfähig", "discountable", result) + getStringOutputLine("Preisänderbarkeit", "priceChangable", result) + getStringOutputLine("Gelöscht", "deleted", result) + getStringOutputLine("Type", "@xsi.type", result) + getStringOutputLine("Warengruppe", "commodityGroup", result) + getStringOutputLine("Sektor", "sector", result); if (result.has("prices")) // nicht jedes Produkt besitzt einen Preis { // und falls kann es ein einzelner Preis oder eine Preisliste sein Object price = result.get("prices"); if (price instanceof JSONObject) { ausgabe = ausgabe + "Preis: " + ((JSONObject) price).get("value") + " €"; } if (price instanceof JSONArray) { ausgabe = ausgabe + "Preis: " + ((JSONObject) ((JSONArray) price).get(0)).get("value") + " €"; } } } catch (JSONException e) { // UI.throwPopup("Kein Produkt unter dieser Nummer",JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } catch (IOException e) { } return ausgabe; }
30a919ca-2b0e-4b01-9ea2-55e70f63a465
8
public void tick(double time) { if (activationTime <= time && alive) { setActive(true); for (GameAction currentAction : getGameActions()) { currentAction.tick(this); } moveEnemy(enemyPixelMovement(enemyPathing.getCurrentPixelGoal())); if (enemyPathing.getCurrentPixelGoal().equals(getPixelPosition())) { enemyPathing.updateGoal(); } } if (getHitpoints() <= 0 && alive) { setToDead(); return; } if (alive && board.isWithinCastlePixelPos(this)) { // if enemy is on castle board.getPlayer().subtractLives(dmgToBase); board.getPlayer().subtractGold(gold); setToDead(); } }