text
stringlengths
14
410k
label
int32
0
9
public ArrayList<GameObject> createGame() { BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader(path)); while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); if(sCurrentLine.indexOf("<GO>") != -1) parseGameObject(sCurrentLine + " "); else if(sCurrentLine.indexOf("<GC>") != -1) parseGameComponent(sCurrentLine + " "); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } return Objects; }
6
private void newGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newGameActionPerformed long pop = Long.valueOf(population.getValue().toString()); Economy e = new Economy(pop * Long.valueOf(gdpPerCapita.getValue().toString()), Double.valueOf(governmentDebt.getValue().toString())); Currency cur = new Currency(currencyName.getText(), currencyShortName.getText(), currencyShort.getText(), currencyISO.getText(), Double.valueOf(usdExchangeRate.getValue().toString())); ArrayList<AdministrativeDivisionLevel> levels = new ArrayList(); if (admStep1.isSelected()) { levels.add(new AdministrativeDivisionLevel(admStep1Name.getText(), Integer.parseInt(admStep1Count.getValue().toString()))); } if (admStep2.isSelected()) { levels.add(new AdministrativeDivisionLevel(admStep2Name.getText(), Integer.parseInt(admStep2Count.getValue().toString()))); } if (admStep3.isSelected()) { levels.add(new AdministrativeDivisionLevel(admStep3Name.getText(), Integer.parseInt(admStep3Count.getValue().toString()))); } if (admStep4.isSelected()) { levels.add(new AdministrativeDivisionLevel(admStep4Name.getText(), Integer.parseInt(admStep4Count.getValue().toString()))); } if (admStep5.isSelected()) { levels.add(new AdministrativeDivisionLevel(admStep5Name.getText(), Integer.parseInt(admStep5Count.getValue().toString()))); } AdministrativeDivision ad = new AdministrativeDivision(); ad.addLevels(levels.toArray(new AdministrativeDivisionLevel[0])); Country c = new Country(fullCountryName.getText(), shortCountryName.getText(), pop, Long.valueOf(area.getValue().toString()), ad); Game.game = new Game(c, e, cur); this.dispose(); }//GEN-LAST:event_newGameActionPerformed
5
public void updateUI(SimulateurUI ui) { addObserver(ui); for (VoieInterne voie : voiesInternes) { ui.ajouterVoie(voie); ui.ajouterAccidentListener(voie); } for (VoieExterne voie : voiesExternes) { ui.ajouterVoie(voie); ui.ajouterAccidentListener(voie); } }
2
private void addButtonListener(JButton b) { b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { if (ev.getActionCommand().equals("Choose Source Folder")) { srcF = fileChooser(); if (srcF == null) { src.setText("no Source Folder selected"); } else src.setText(srcF); } else if (ev.getActionCommand().equals( "Choose Destination Folder")) { desF = fileChooser(); if (desF == null) { des.setText("no Destination Folder selected"); } else des.setText(desF); } else if (ev.getActionCommand().equals("Start")) { if (srcF == null) { println("no source choosed!"); return; } if (desF == null) { println("no destination choosed!"); return; } ArrayList<File> liste = new ArrayList<File>(); liste = scanforRDF(srcF); if (liste.isEmpty()) { println("There are no RDF files in directory"); return; } if (liste.size() == 1) { println("There is one RDF element."); } else println("There are " + liste.size() + " RDF elements."); println("Started!"); execution(liste); println("finished!"); info.setText("finished!"); } } }); }
9
public boolean ColliderWithPodiumUp(){ if((x>=0 && x<=Podium.WIDTH-25) && (y<=GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp - HEIGHT/1.2 && y>= GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp - HEIGHT)){ return true; } if((x>=GameMain.GAME_WIDTH+25 - Podium.WIDTH - Character.WIDTH && x<=GameMain.GAME_WIDTH) && (y<=GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp - HEIGHT/1.2 && y>= GameMain.GAME_HEIGHT_ASSUM - GameMain.DistanceBottomAndPodiumUp - HEIGHT)){ return true; } return false; }
8
public Graphics2D getGraphics() { Window window = device.getFullScreenWindow(); if (window != null) { BufferStrategy strategy = window.getBufferStrategy(); return (Graphics2D)strategy.getDrawGraphics(); } else { return null; } }
1
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Vector2D vector2D = (Vector2D) o; if (Double.compare(vector2D.x, x) != 0) return false; if (Double.compare(vector2D.y, y) != 0) return false; return true; }
5
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String serverID = null; if (jComboBox1.getSelectedIndex() > -1) { serverID = ((String[]) serverMap.get((Integer) jComboBox1.getSelectedIndex()))[1]; } System.out.println("In registerNym Dialog, server ID:" + serverID + " nymID:" + nymID); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); int status = new NYM().registerNym(serverID, nymID); if (status == 0) { JOptionPane.showMessageDialog(this, "Nym registered sucessfully on the server", "NYM registration success", JOptionPane.INFORMATION_MESSAGE); // Refresh Market NYM list MainPage.refreshMarketNym(serverID); this.serverID = serverID; } else if (status == 1) { JOptionPane.showMessageDialog(this, "Nym is already registered on server " + serverID, "Already registered", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Cannot register nym on server", "Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException ex) { ex.printStackTrace(); } finally { setCursor(Cursor.getDefaultCursor()); dispose(); } }//GEN-LAST:event_jButton1ActionPerformed
4
protected mxCellState[] getPreviewStates() { mxGraph graph = graphComponent.getGraph(); Collection<mxCellState> result = new LinkedList<mxCellState>(); for (Object cell : movingCells) { mxCellState cellState = graph.getView().getState(cell); if (cellState != null) { result.add(cellState); // Terminates early if too many cells if (result.size() >= threshold) { return null; } if (isContextPreview()) { Object[] edges = graph.getAllEdges(new Object[] { cell }); for (Object edge : edges) { if (!graph.isCellSelected(edge)) { mxCellState edgeState = graph.getView().getState( edge); if (edgeState != null) { // Terminates early if too many cells if (result.size() >= threshold) { return null; } result.add(edgeState); } } } } } } return result.toArray(new mxCellState[result.size()]); }
8
public void startConnection() { try { if ((con == null) || (con.isClosed())) { con = DriverManager.getConnection( "jdbc:postgresql://java.is.uni-due.de/ws1011", "ws1011", "ftpw10"); System.out.println("Datenbankverbindung hergestellt"); } } catch (SQLException e) { e.printStackTrace(); } }
3
protected int setArmorModel(EntityPlayer par1EntityPlayer, int par2, float par3) { ItemStack itemstack = par1EntityPlayer.inventory.armorItemInSlot(3 - par2); if (itemstack != null) { Item item = itemstack.getItem(); if (item instanceof ItemArmor) { ItemArmor itemarmor = (ItemArmor)item; loadTexture((new StringBuilder()).append("/armor/").append(armorFilenamePrefix[itemarmor.renderIndex]).append("_").append(par2 != 2 ? 1 : 2).append(".png").toString()); ModelBiped modelbiped = par2 != 2 ? modelArmorChestplate : modelArmor; modelbiped.bipedHead.showModel = par2 == 0; modelbiped.bipedHeadwear.showModel = par2 == 0; modelbiped.bipedBody.showModel = par2 == 1 || par2 == 2; modelbiped.bipedRightArm.showModel = par2 == 1; modelbiped.bipedLeftArm.showModel = par2 == 1; modelbiped.bipedRightLeg.showModel = par2 == 2 || par2 == 3; modelbiped.bipedLeftLeg.showModel = par2 == 2 || par2 == 3; setRenderPassModel(modelbiped); return !itemstack.isItemEnchanted() ? 1 : 15; } } return -1; }
8
public HantoBasePiece(HantoPlayerColor playerColor, HantoPieceType type, HantoMove moveType, int moveDistance){ color = playerColor; this.type = type; switch(type) { case BUTTERFLY: this.moveType = moveType; this.moveDistance = moveDistance; break; case CRAB: this.moveType = moveType; this.moveDistance = moveDistance; break; case SPARROW: this.moveType = moveType; this.moveDistance = moveDistance; break; case HORSE: this.moveType = moveType; this.moveDistance = moveDistance; break; default: break; } }
4
public int GetCLStrength(int ItemID) { if (ItemID == 10707) { return 100; } if (ItemID == 6528) { return 60; } if (ItemID == 10707) { return 100; } if (ItemID == 10709) { return 100; } if (ItemID == -1) { return 1; } String ItemName = GetItemName(ItemID); if (ItemName.startsWith("Granite")) { return 50; } else if (ItemName.startsWith("Torags hammers") || ItemName.endsWith("Dharoks greataxe")) { return 70; } else if (ItemName.startsWith("Strength Cape")) { return 100; } return 1; }
9
static int getNumber(char l) { l = Character.toUpperCase(l); if(l<='C') return 2; else if(l<='F') return 3; else if(l<='I') return 4; else if(l<='L') return 5; else if(l<='O') return 6; else if(l<='S') return 7; else if(l<='V') return 8; return 9; }
7
public void trim(int newSize) { if (newSize > size || newSize < 0) { throw new IndexOutOfBoundsException("Index: " + newSize + ", Size: " + size); } while (size > newSize) { attributeLists[--size] = null; } }
3
public int getLeftScore() { return leftScore; }
0
@Override public String toString(){ return super.toString()+ " in category : Axes" + " with attack " + this.attackScore; }
0
public String toString() { StringBuffer s = new StringBuffer(); if (this.vorzeichen) s.append('-'); for (int i = this.mantisse.getSize() - 1; i >= 0; i--) { if (i == this.mantisse.getSize() - 2) s.append(','); if (this.mantisse.bits[i]) s.append('1'); else s.append('0'); } s.append(" * 2^("); s.append(this.exponent.toString()); s.append("-"); s.append(expOffset); s.append(")"); return s.toString(); }
4
private void initLoadingstatusFontMenu(Color bg) { this.loadingstatusPanel = new JPanel(); this.loadingstatusPanel.setBackground(bg); this.loadingstatusPanel.setLayout(new VerticalLayout(5, VerticalLayout.LEFT)); String initFontTmp = this.skin.getLoadingStatusFont(); int initFontSizeTmp = this.skin.getLoadingStatusFontsize(); Color initFontColorTmp = new Color(this.skin.getLoadingStatusFontcolor()[1], this.skin.getLoadingStatusFontcolor()[2], this.skin.getLoadingStatusFontcolor()[3]); boolean boldTmp = this.skin.getLoadingStatusFonttype() == Fonttype.BOLD; boolean underlineTmp = (this.skin.getLoadingStatusFontstyle() == Fontstyle.UNDERLINE) || (this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOWUNDERLINE); boolean shadowTmp = (this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOW) || (this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOWUNDERLINE); this.loadingstatusFontfield = new FontField(bg, strFontFieldTitle, initFontTmp, initFontSizeTmp, initFontColorTmp, boldTmp, underlineTmp, shadowTmp) { private final long serialVersionUID = 1L; @Override public void fontChosen(String input) { if (!input.equals("")) { FontChangesMenu.this.skin.setLoadingStatusFont(input); updateFont(FontChangesMenu.this.skin.getLoadingStatusFont()); } else { FontChangesMenu.this.skin.setLoadingStatusFont(null); } } @Override public void sizeTyped(String input) { if (input != null) { FontChangesMenu.this.skin.setLoadingStatusFontsize(parseInt(input)); updateSize(FontChangesMenu.this.skin.getLoadingStatusFontsize()); } else { FontChangesMenu.this.skin.setLoadingStatusFontsize(-1); } } @Override public void colorBtnPressed(int[] argb) { FontChangesMenu.this.skin.setLoadingStatusFontcolor(argb); updateColor(new Color(FontChangesMenu.this.skin.getLoadingStatusFontcolor()[1], FontChangesMenu.this.skin.getLoadingStatusFontcolor()[2], FontChangesMenu.this.skin.getLoadingStatusFontcolor()[3])); } @Override public void boldPressed(boolean selected) { FontChangesMenu.this.skin.setLoadingStatusFonttype(selected ? Fonttype.BOLD : Fonttype.NORMAL); updateBold(FontChangesMenu.this.skin.getLoadingStatusFonttype() == Fonttype.BOLD); } @Override public void underlinePressed(boolean selected) { FontChangesMenu.this.skin.setLoadingStatusFontstyle(getUnderlineFontstyle(selected, FontChangesMenu.this.skin.getLoadingStatusFontstyle())); updateUnderline((FontChangesMenu.this.skin.getLoadingStatusFontstyle() == Fontstyle.UNDERLINE) || (FontChangesMenu.this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOWUNDERLINE)); } @Override public void shadowPressed(boolean selected) { FontChangesMenu.this.skin.setLoadingStatusFontstyle(getShadowFontstyle(selected, FontChangesMenu.this.skin.getLoadingStatusFontstyle())); updateShadow((FontChangesMenu.this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOW) || (FontChangesMenu.this.skin.getLoadingStatusFontstyle() == Fontstyle.SHADOWUNDERLINE)); } }; this.loadingstatusPanel.add(this.loadingstatusFontfield); }
7
private void computeClusterCentroids() { HashMap<Integer, ArrayList<Double>> sumClusterCentroids = new HashMap<Integer, ArrayList<Double>>(); HashMap<Integer, Integer> memberCount = new HashMap<Integer, Integer>(); for (Map.Entry<ArrayList<Integer>, Integer> entry : gridLabel.entrySet()) { // get the grid Index ArrayList<Integer> gridIdx = entry.getKey(); // get the cluster Id Integer clusterId = entry.getValue(); // find in the clusterCentroids if ( sumClusterCentroids.containsKey(clusterId) ) { // if found... // get the previous cluster centroids ArrayList<Double> oldCentroids = sumClusterCentroids.get(clusterId); int oldCount = memberCount.get(clusterId); // get the new grid centroid if ( gridCentroids.containsKey(gridIdx) ) { ArrayList<Double> gridCentroid = gridCentroids.get(gridIdx); int countPoints = gridCount.get(gridIdx); sumClusterCentroids.put(clusterId, Util.additionArrayListDouble(oldCentroids, Util.multiplicationArrayListDouble(gridCentroid, countPoints))); memberCount.put(clusterId, oldCount + countPoints); } } else { // if not found, put this as the first time // multiply the gridCentroids with the gridCount if ( gridCentroids.containsKey(gridIdx) ) { ArrayList<Double> gridCentroid = gridCentroids.get(gridIdx); int countPoints = gridCount.get(gridIdx); memberCount.put(clusterId, countPoints); sumClusterCentroids.put(clusterId, Util.multiplicationArrayListDouble(gridCentroid, countPoints)); } } } // end for clusterCentroids = new HashMap<Integer, ArrayList<Double>>(); for (Map.Entry<Integer, ArrayList<Double>> entry : sumClusterCentroids.entrySet()) { int clusterId = entry.getKey(); ArrayList<Double> sumCentroid = entry.getValue(); int count = memberCount.get(clusterId); clusterCentroids.put(clusterId, Util.divisionArrayListDouble(sumCentroid, count)); } }
5
public DistributedQuery(Statement s, ArrayList dbList) { this.tempDB = s; this.dbList = dbList; String os = System.getProperty("os.name").toLowerCase(); if (!ServicesParser.isInitialized()) { String servicesFile; if (os.indexOf("windows") > -1) servicesFile = System.getProperty("user.home") + "\\system32\\drivers\\etc\\services"; else servicesFile = "/etc/services"; try { new ServicesParser(new FileInputStream(new File(servicesFile))); ServicesParser.Start(); } catch (FileNotFoundException e) { return; } catch (ParseException e) { return; } } tcpServices = ServicesParser.getTcpServices(); udpServices = ServicesParser.getUdpServices(); portMap = ServicesParser.getPortHash(); if (!ProtocolsParser.isInitialized()) { String protocolsFile; if (os.indexOf("windows") > -1) protocolsFile = System.getProperty("user.home") + "\\system32\\drivers\\etc\\protocols"; else protocolsFile = "/etc/protocols"; try { new ProtocolsParser(new FileInputStream(new File(protocolsFile))); ProtocolsParser.Start(); } catch (FileNotFoundException e) { return; } catch (ParseException e) { return; } } protocols = ProtocolsParser.getProtocols(); protocolMap = ProtocolsParser.getProtoHash(); System.setProperty("java.awt.headless", "true"); }
8
@Override public void genOperationComment(StringBuffer buff, Map<String, String> simpleToPrimitiveTypeMap, Operation o) { genBeginSeperator(buff); buff.append(String.format("#' @title %s\n", o.name)); String description = o.description.replaceAll("[\\t\\n]", " "); description = description.replaceAll("\\s+", " "); description = description.replaceAll("^ ", ""); description = WordUtils.wrap(description, 77, "\n#' ", false); if (description.trim().length() > 0) { buff.append("#' @description ").append(description).append("\n"); } if (o.parameters != null) { Request r = o.parameters.request; if (r.parameter != null) { for (Parameter p : r.parameter) { String t = convertValidateRTypes(p.type); if ((simpleToPrimitiveTypeMap.containsKey(t))) { t = convertValidateRTypes(simpleToPrimitiveTypeMap .get(t)); } String mandatory = "optional"; if (p.mandatory != null && p.isMandatory()) { mandatory = "mandatory"; } String pdescription = p.description.replaceAll("[\\t\\n]", " "); pdescription = pdescription.replaceAll("\\s+", " "); pdescription = pdescription.replaceAll("^ ", ""); pdescription = pdescription.replaceAll("@", ""); pdescription = WordUtils.wrap(pdescription, 70, "\n#' ", false); buff.append(String.format( "#' @param %s is %s of type %s.\n", p.name, mandatory, t)); buff.append(String.format("#' %s\n", pdescription)); } } SimpleResponse s = o.parameters.simpleResponse; if (s.description != null) { String sdescription = s.description.replaceAll("[\\t\\n]", " "); sdescription = sdescription.replaceAll("\\s+", " "); sdescription = sdescription.replaceAll("^ ", ""); if (sdescription.trim().length() > 0) { sdescription = WordUtils.wrap(sdescription, 70, "\n#' ", false); buff.append(String.format("#' @return %s\n", sdescription)); } } } genEndSeperator(buff); }
9
private static Move ForwardRightForWhite(int r, int c, Board board){ Move forwardRight = null; if(r<Board.rows-1 && c<Board.cols-1 && board.cell[r+1][c+1] == CellEntry.empty ) { forwardRight = new Move(r,c, r+1, c+1); } return forwardRight; }
3
public void close() { try { if (rs != null && !rs.isClosed()) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null && !conn.isClosed()) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
9
public boolean isItemSent() { if (itemSentInt == "1") { return true; } else { return false; } }
1
@Override public void handleIt(Object... args) { Scanner inputReader = new Scanner(System.in); System.out.print("Are you sure you want to quit? (y/n): "); String userInput = inputReader.next(); if (userInput.equals("y") || userInput.equals("Y")) { Socket sock = (Socket) args[0]; try { sock.close(); System.exit(0); } catch (IOException e) { System.exit(0); } } else if(!userInput.equals("n") && !userInput.equals("N")) { System.out.println("Unrecognized Option: assuming NO"); } }
5
@Override public String getTitle() { Document doc = this.viewer.getDocument(); return (String) doc.getProperty(Document.TitleProperty); }
0
public static String getln() { StringBuffer s = new StringBuffer(100); char ch = readChar(); while (ch != '\n') { s.append(ch); ch = readChar(); } return s.toString(); }
1
@Override public StringBuffer getOOXML( String catAxisId, String valAxisId, String serAxisId ) { StringBuffer cooxml = new StringBuffer(); // chart type: contains chart options and series data cooxml.append( "<c:line3DChart>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:grouping val=\"" ); if( is100PercentStacked() ) { cooxml.append( "percentStacked" ); } else if( isStacked() ) { cooxml.append( "stacked" ); } // } else if (this.isClustered()) // grouping="clustered"; else { cooxml.append( "standard" ); } cooxml.append( "\"/>" ); cooxml.append( "\r\n" ); // vary colors??? // *** Series Data: ser, cat, val for most chart types cooxml.append( getParentChart().getChartSeries().getOOXML( getChartType(), false, 0 ) ); // chart data labels, if any //TODO: FINISH //cooxml.append(getDataLabelsOOXML(cf)); //dropLines ChartLine cl = cf.getChartLinesRec( ChartLine.TYPE_DROPLINE ); if( cl != null ) { cooxml.append( cl.getOOXML() ); } // gapDepth int gapdepth = getGapDepth(); if( gapdepth != 0 ) { cooxml.append( "<c:gapDepth val=\"" + gapdepth + "\"/>" ); } // axis ids - unsigned int strings cooxml.append( "<c:axId val=\"" + catAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:axId val=\"" + valAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "<c:axId val=\"" + serAxisId + "\"/>" ); cooxml.append( "\r\n" ); cooxml.append( "</c:line3DChart>" ); cooxml.append( "\r\n" ); return cooxml; }
4
private String getFechaSQL(String fecha){//01/02/2013 if (fecha!=null) { if (fecha.length() > 8) { return fecha.replace("/", "-"); } } return "1900-01-01"; }
2
private ChatConnection getDestinationUserConnection(String destinationUser) { for (ChatConnection connection : connections.values()) { if (destinationUser.equals(connection.getUserName())) { return connection; } } return null; }
2
public static boolean[] string2BooleanArray(@NotNull String convertable) throws IkszorConvertException { boolean[] result = new boolean[convertable.length() * 8]; try { int real = 0; for(byte b : convertable.getBytes()) { int val = b; for(int i = 0; i < 8; i++) { result[real+i] = (val & 128) == 0 ? false : true; val <<= 1; } real += 8; } } catch(Exception e) { throw new IkszorConvertException(e); } return result; }
4
public void explicitFitness() { for (int i = 0; i < getSpecies().size(); i++) { for (int j = 0; j < getSpecies().get(i).getNumberOrganisms(); j++) { double newFitness = getSpecies().get(i).getOrganism(j).getFitness() / (double) sumSharingFunc(getSpecies().get(i).getOrganism(j), i, j); getSpecies().get(i).getOrganism(j).setFitness(newFitness); } } }
2
*/ private void recListPopup(MouseEvent e) { JTable tbl = null; JScrollPane pane = null; try { tbl = (JTable)e.getSource(); } catch (ClassCastException cce) { pane = (JScrollPane)e.getSource(); if (pane.equals(queryDbPane)) { tbl = queryDbTable; } else if (pane.equals(resultPane)) { tbl = resultTable; } if (pane.equals(queryFilePane)) { tbl = queryFileTable; } } int rowCnt = tbl.getSelectedRows().length; JMenuItem item1 = new JMenuItem("Show Record"); item1.addActionListener(new PopupShowRecordListener(tbl)); JMenuItem item2 = new JMenuItem("Multiple Display"); item2.addActionListener(new PopupMultipleDisplayListener(tbl)); // 可視設定 if (tbl.equals(queryFileTable)) { item1.setEnabled(false); item2.setEnabled(false); } else if (rowCnt == 0) { item1.setEnabled(false); item2.setEnabled(false); } else if (rowCnt == 1) { item1.setEnabled(true); item2.setEnabled(false); } else if (rowCnt > 1) { item1.setEnabled(false); item2.setEnabled(true); } // ポップアップメニュー表示 JPopupMenu popup = new JPopupMenu(); popup.add(item1); if (tbl.equals(resultTable)) { popup.add(item2); } popup.show(e.getComponent(), e.getX(), e.getY()); }
9
public static void main(String[] args) throws IOException { File inputFile = new File("entrada"); if (inputFile.exists()) System.setIn(new FileInputStream(inputFile)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line; HashMap<Character, Integer> map = new HashMap<>(); map.put('W', 64); map.put('H', 32); map.put('Q', 16); map.put('E', 8); map.put('S', 4); map.put('T', 2); map.put('X', 1); while ((line = in.readLine()) != null) { if (line.trim().equals("*")) break; String[] v = line.trim().split("/"); int count = 0; for (int i = 0; i < v.length; i++) { if (v[i].length() > 0) { char[] l = v[i].toCharArray(); int sum = 0; for (int j = 0; j < l.length; j++) sum += map.get(l[j]); if (sum == 64) count++; } } out.append(count + "\n"); } System.out.print(out); }
7
public static void makeSimple() { removeList.clear(); for (RoadGraph i : JMaps.getRoadGraphList()) { if (!i.isImportant() && !i.isSocket()) { int curve1, curve2; curve1 = i.getList().get(0); curve2 = i.getList().get(1); for (RoadGraph k : JMaps.getRoadGraphList()) { if (k.getNumber() == curve1) { k.getList().remove(k.getList().indexOf(i.getNumber())); k.getList().addAll(i.getList()); k.getList().remove(k.getList().indexOf(k.getNumber())); } } for (RoadGraph k : JMaps.getRoadGraphList()) { if (k.getNumber() == curve2) { k.getList().remove(k.getList().indexOf(i.getNumber())); k.getList().addAll(i.getList()); k.getList().remove(k.getList().indexOf(k.getNumber())); } } removeList.add(i); } } JMaps.getRoadGraphList().removeAll(removeList); JMaps.getRoadGraphList().trimToSize(); }
7
private void setHealth(int newHealth, boolean notifyListeners) { int previousHealth = health; health = newHealth; if(notifyListeners){ for (EntityHealthListener listener : healthListeners) { listener.healthChanged(this, previousHealth, newHealth); } } if (health <= 0 && alive) { die(true); } }
4
@Override public boolean onMouseDown(int mX, int mY, int button) { if(super.onMouseDown(mX, mY, button)) { return true; } for(WeaponLocationDisplay wld : weaponLocDisplays) { if(wld.onMouseDown(mX, mY, button)) { return true; } } return false; }
3
public void FollowPlayerCB(int NPCID, int playerID) { int playerX = server.playerHandler.players[playerID].absX; int playerY = server.playerHandler.players[playerID].absY; npcs[NPCID].RandomWalk = false; if(server.playerHandler.players[playerID] != null) { if(playerY < npcs[NPCID].absY) { npcs[NPCID].moveX = GetMove(npcs[NPCID].absX, playerX); npcs[NPCID].moveY = GetMove(npcs[NPCID].absY, playerY+1); } else if(playerY > npcs[NPCID].absY) { npcs[NPCID].moveX = GetMove(npcs[NPCID].absX, playerX); npcs[NPCID].moveY = GetMove(npcs[NPCID].absY, playerY-1); } else if(playerX < npcs[NPCID].absX) { npcs[NPCID].moveX = GetMove(npcs[NPCID].absX, playerX+1); npcs[NPCID].moveY = GetMove(npcs[NPCID].absY, playerY); } else if(playerX > npcs[NPCID].absX) { npcs[NPCID].moveX = GetMove(npcs[NPCID].absX, playerX-1); npcs[NPCID].moveY = GetMove(npcs[NPCID].absY, playerY); } npcs[NPCID].getNextNPCMovement(); npcs[NPCID].updateRequired = true; } }
5
protected boolean isElementoEnHechosPreguntados(String elemento) { if (null != hechosPreguntados) { for (String s : hechosPreguntados) { if (elemento.equals(s)) { return true; } } } return false; }
3
public void start() { ImageLoader.init(); Game.init(); game = Game.getInstance(); final int DELTA_TARGET_NANOS = DELTA_TARGET * 1000 * 1000; while (true) { long timeStart = System.nanoTime(); BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); continue; } tick(); graphics2d.setGraphics(bs.getDrawGraphics()); render(); if (bs != null) bs.show(); long timePassed = System.nanoTime() - timeStart; if (timePassed < DELTA_TARGET_NANOS) { long sleepTime = DELTA_TARGET_NANOS - timePassed; long millis = sleepTime / (1000 * 1000); int nano = (int) (sleepTime % (1000 * 1000)); // System.out.println(millis + " : " + nano); try { Thread.sleep(millis, nano); } catch (InterruptedException e) { } } cpuWorkload = (float) timePassed / DELTA_TARGET_NANOS; } }
5
private void indexFromRequests(List<Order> orders, Map<String, Product> productMap, OrderHistory history) { for (Order order : orders) { Indexed<Product> x = search.get(order.getSku()); if (x == null) { Product product = productMap.get(order.getSku()); if (product == null) { product = new Product(order.getSku(), order.getSku(), Product.NO_DATE, Product.NO_RANK); productMap.put(order.getSku(), product); } x = new Indexed<Product>(product); search.put(order.getSku(), x); } BagOfWords bag = getBag(order, history); x.count(bag.getWords()); } }
3
private String[] getIDsToArrays(final String stringView) { StringTokenizer st = new StringTokenizer(stringView,","); int number = st.countTokens(); int i = 0; String[] strings = new String[number]; while (st.hasMoreTokens()) { strings[i] = st.nextToken(); i++; } return strings; }
1
@Override public void analyzeLine(String line, int lineNumber, RequireJsModule module) { String varName = null; String dependencyId = null; Matcher match = NAMED_REQUIRE_REGEX.matcher(line); if(match.find()) { varName = match.group(1); String tentativeDependency = match.group(2); if(!tentativeDependency.startsWith("text!") && !tentativeDependency.startsWith("i18n!")) { dependencyId = tentativeDependency; } } else { match = ANON_REQUIRE_REGEX.matcher(line); if(match.find()) { String tentativeDependency = match.group(1); if(!tentativeDependency .startsWith("text!") && !tentativeDependency.startsWith("i18n!")) { dependencyId = tentativeDependency; } } } if(dependencyId != null) { RequireJsModule dependency = new RequireJsModule(dependencyId); if(varName == null) module.addDependency(dependency); else module.addDependency(varName, dependency); } }
8
public void setjTextFieldNum(JTextField jTextFieldNum) { this.jTextFieldNum = jTextFieldNum; }
0
@Override protected Integer doInBackground() { Logger.getLogger(ReportGenerator.class.getName()).entering(ReportGenerator.class.getName(), "doInBackground"); try { nbrOfAlbums = 0; nbrOfProcessedAlbums = 0; findNbrOfAlbums(); try { pageXWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(reportFolder + "index.html")), "UTF-8")); cssFileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(reportFolder + "style.css")), "UTF-8")); createCss(); copyImages(); createHeader(pageXWriter); createContent(); if (cancelAsked) { Logger.getLogger(ReportGenerator.class.getName()).exiting(ReportGenerator.class.getName(), "doInBackground", 7); return 7; } createFooter(); } catch (FileNotFoundException | UnsupportedEncodingException ex) { Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, "Error with the files during the reporting", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "report-files"); } catch (IOException ex) { Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, "IO error during the reporting", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "report-IO"); } try { pageXWriter.close(); cssFileWriter.close(); } catch (IOException ex) { Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, "IO error while closing the report files", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "report-IO"); } if (cancelAsked) { Logger.getLogger(ReportGenerator.class.getName()).exiting(ReportGenerator.class.getName(), "doInBackground", 7); return 7; } OSBasics.openFile(reportFolder); OSBasics.openURI("file://" + reportFolder.replace('\\', '/').concat("index.html")); } catch (Exception ex) { Logger.getLogger(ReportGenerator.class.getName()).log(Level.SEVERE, "Unknown exception", ex); new InfoInterface(InfoInterface.InfoLevel.ERROR, "unknown"); } Logger.getLogger(ReportGenerator.class.getName()).exiting(ReportGenerator.class.getName(), "doInBackground", 0); return 0; }
6
public Elevator callUp(Rider r){ int startFloor = r.getFrom(); while(true) { for(Elevator e : elevators) { synchronized(e){ if(e.isGoingUp() && e.getFloor()<startFloor) { e.addRequest(r); return e; } else if(!e.isInTransit()) { e.addRequest(r); return e; } } } } }
5
private void updateLights() { switch (_state) { case GreenNS_RedEW: _ewLight.setColor(LightColor.Green); _nsLight.setColor(LightColor.Red); break; case YellowNS_RedEW: _ewLight.setColor(LightColor.Yellow); _nsLight.setColor(LightColor.Red); break; case RedNS_GreenEW: _ewLight.setColor(LightColor.Red); _nsLight.setColor(LightColor.Green); break; case RedNS_YellowEW: _ewLight.setColor(LightColor.Yellow); _nsLight.setColor(LightColor.Green); break; default: break; } }
4
private void Show() { Game.gui.removeAll(); Point size = MenuHandler.PrepMenu(260,140); Prev.setBounds(size.x+190, size.y+100, 60, 24); Next.setBounds(size.x+10, size.y+100, 60, 24); Return.setBounds(size.x+80, size.y+100, 100, 24); if (Game.edit.owner > 0) { for (int i = 0; i < Game.displayU.size(); i++) { Units[i] = new JButton(ButtonImage(i,0,Type.UNIT)); Units[i].addActionListener(this); Units[i].setBounds(size.x+10+32*i, size.y+10, 32, 32); Game.gui.add(Units[i]); } } for (int i = 0; i < Game.displayB.size(); i++) { Cities[i] = new JButton(ButtonImage(i,0,Type.CITY)); Cities[i].addActionListener(this); Cities[i].setBounds(size.x+10+32*i, size.y+40, 32, 32); Game.gui.add(Cities[i]); } int use = 0;//Hack so people can't place cities. for (int i = 0; i < Game.map.tiles.size(); i++) { if (!Game.map.tiles.get(i).building()) { Tiles[i] = new JButton(ButtonImage(Game.map.tiles.get(i).x,Game.map.tiles.get(i).y,Type.TILE)); Tiles[i].addActionListener(this); Tiles[i].setBounds(size.x+10+32*use, size.y+70, 32, 32); Game.gui.add(Tiles[i]); use++; } } Game.gui.add(Prev); Game.gui.add(Next); Game.gui.add(Return); }
5
private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzPushbackPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead < 0) { return true; } else { zzEndRead+= numRead; return false; } }
3
public void visitMethodInsn( final int opcode, final String owner, final String name, final String desc) { buf.setLength(0); buf.append(tab2).append(OPCODES[opcode]).append(' '); appendDescriptor(INTERNAL_NAME, owner); buf.append('.').append(name).append(' '); appendDescriptor(METHOD_DESCRIPTOR, desc); buf.append('\n'); text.add(buf.toString()); if (mv != null) { mv.visitMethodInsn(opcode, owner, name, desc); } }
1
private static void solve_c_svc(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si, double Cp, double Cn) { int l = prob.l; double[] minus_ones = new double[l]; byte[] y = new byte[l]; int i; for(i=0;i<l;i++) { alpha[i] = 0; minus_ones[i] = -1; if(prob.y[i] > 0) y[i] = +1; else y[i] = -1; } Solver s = new Solver(); s.Solve(l, new SVC_Q(prob,param,y), minus_ones, y, alpha, Cp, Cn, param.eps, si, param.shrinking); double sum_alpha=0; for(i=0;i<l;i++) sum_alpha += alpha[i]; if (Cp==Cn) svm.info("nu = "+sum_alpha/(Cp*prob.l)+"\n"); for(i=0;i<l;i++) alpha[i] *= y[i]; }
5
public void RemoveFront() { if (getHead() == null) { return; } if (size == 1) { setHead(tail = null); size = 0; return; } --size; setHead(getHead().next); }
2
public CheckResultMessage check19(int day) { int r1 = get(33, 5); int c1 = get(34, 5); int r2 = get(39, 5); int c2 = get(40, 5); BigDecimal b = new BigDecimal(0); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); b = getValue(r1 + 2, c1 + day, 8).add( getValue(r2 + 11, c2 + day - 1, 10)); if (0 != getValue(r1 + 2, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">未达账项核对 J03:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); b = getValue1(r1 + 2, c1 + day, 8).add( getValue1(r2 + 11, c2 + day - 1, 10)); if (0 != getValue1(r1 + 2, c1 + 1 + day, 8).compareTo(b)) { return error("支付机构汇总报表<" + fileName + ">未达账项核对 J03:" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">未达账项核对 J03:" + day + "日正确"); }
5
public static final BigInteger LCD(BigInteger... ints) { BigInteger lcd = BigInteger.ONE; for (BigInteger n : ints) { if (lcd.mod(n).equals(BigInteger.ZERO)) continue; for (BigInteger i = BigInteger.valueOf(2); i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) { if (n.mod(i).equals(BigInteger.ZERO)) { BigInteger fact = BigInteger.ONE; while (n.mod(i).equals(BigInteger.ZERO)) { n = n.divide(i); fact = fact.multiply(i); } if (!lcd.mod(fact).equals(BigInteger.ZERO)) { while (lcd.mod(i).equals(BigInteger.ZERO)) { lcd = lcd.divide(i); } lcd = lcd.multiply(fact); } } } } return lcd; }
7
public void setOptions(String[] options) throws Exception { String tmpStr; String[] spec; String classname; tmpStr = Utils.getOption('W', options); if (tmpStr.length() > 0) { spec = Utils.splitOptions(tmpStr); if (spec.length == 0) throw new IllegalArgumentException("Invalid classifier specification string"); classname = spec[0]; spec[0] = ""; setClassifier((Classifier) Utils.forName(Classifier.class, classname, spec)); } else { throw new Exception("No classifier (classname + options) provided!"); } tmpStr = Utils.getOption('S', options); if (tmpStr.length() > 0) { spec = Utils.splitOptions(tmpStr); if (spec.length != 1) throw new IllegalArgumentException("Invalid source code specification string"); classname = spec[0]; spec[0] = ""; setSourceCode((Classifier) Utils.forName(Classifier.class, classname, spec)); } else { throw new Exception("No source code (classname) provided!"); } tmpStr = Utils.getOption('t', options); if (tmpStr.length() != 0) setDataset(new File(tmpStr)); else throw new Exception("No dataset provided!"); tmpStr = Utils.getOption('c', options); if (tmpStr.length() != 0) { if (tmpStr.equals("first")) setClassIndex(0); else if (tmpStr.equals("last")) setClassIndex(-1); else setClassIndex(Integer.parseInt(tmpStr) - 1); } else { setClassIndex(-1); } }
8
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(IntegerParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(IntegerParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(IntegerParameterWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(IntegerParameterWindow.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 IntegerParameterWindow().setVisible(true); } }); }
6
private String convert(String[] words, int start, int end, int L) { StringBuilder sb = new StringBuilder(); // if this line only contains one word if (start == end) { sb.append(words[start]); for (int i = 0; i < L - words[start].length(); i++) { sb.append(" "); } return sb.toString(); } // if the line is the last line, the space distribution rule is // different else if (end == words.length - 1) { int curLen = 0; for (int i = start; i < end; i++) { sb.append(words[i]); sb.append(" "); curLen += words[i].length() + 1; } sb.append(words[end]); curLen += words[end].length(); for (int i = 0; i < L - curLen; i++) { sb.append(" "); } return sb.toString(); } // calculate the lengths of padding space int totalLen = 0, numOfSpaces = end - start; for (int i = start; i <= end; i++) totalLen += words[i].length(); int lenOfPaddingSpace = (L - totalLen) / numOfSpaces; int numOfExtraSpaces = (L - totalLen) % numOfSpaces; // construct the line int count = 0; // count of the extra spaces for (int i = start; i < end; i++) { sb.append(words[i]); for (int j = 0; j < lenOfPaddingSpace; j++) sb.append(" "); if (count < numOfExtraSpaces) sb.append(" "); count++; } sb.append(words[end]); return sb.toString(); }
9
public static boolean writeFile(String[] values, String archivo) { FileWriter fichero = null; PrintWriter pw = null; try { boolean isDeleted = deleteFile(archivo); if (isDeleted) { fichero = new FileWriter(archivo, false); pw = new PrintWriter(fichero); for (String cadena : values) { pw.println(cadena); } fichero.close(); return true; } return false; } catch (IOException ex) { return false; } }
3
public int getSize() { return nodes.size(); }
0
protected void setColorScheme(String colorScheme) { switch (colorScheme) { case "Standard": //set Standard ColorScheme this.activeColorScheme = new ColorScheme("Standard", Color.white, Color.black, new Color(100, 100, 100), Color.orange, new Color(230, 140, 0), Color.gray, new Color(90, 90, 90), Color.gray, new Color(90, 90, 90), new Color(0, 230, 30), new Color(0, 170, 10), Color.blue, Color.black); break; case "Night": // set Night ColorScheme this.activeColorScheme = new ColorScheme("Night", Color.black, Color.orange, new Color(155, 100, 0), Color.gray, new Color(200, 200, 200), Color.cyan, new Color(30, 100, 75), Color.cyan, new Color(30, 100, 75), Color.magenta, new Color(100, 25, 65), Color.blue, Color.white); break; case "Colorblind": // set Colorblind ColorScheme this.activeColorScheme = new ColorScheme("Standard", Color.white, Color.black, new Color(100, 100, 100), Color.orange, new Color(230, 140, 0), new Color(82, 82, 82), new Color(50, 50, 50), new Color(82, 82, 82), new Color(50, 50, 50), new Color(190, 190, 190), new Color(150, 150, 150), Color.blue, Color.black); break; default: // default to Standard ColorScheme setColorScheme("Standard"); break; } repaint(); }
3
@GET @Path("{food}") @Produces(MediaType.APPLICATION_JSON ) public PhotoBean getFoodPictureFromTag(@PathParam("food") String food) { Flickr f = FlickrDao.instance.getFlickr(); PhotosInterface photosInterface = f.getPhotosInterface(); Photo photo = null; Boolean visited[] = new Boolean[items_per_page]; Arrays.fill(visited,false); try { SearchParameters parameters = new SearchParameters(); parameters.setTags(new String[]{food,"food"}); parameters.setSort(SearchParameters.RELEVANCE); parameters.setText(food); PhotoList<Photo> list = photosInterface.search(parameters,items_per_page,1); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getTitle()+" "+list.get(i).getLargeUrl()+"\n"); } Random rmd = new Random(); int count = 0; do { int photo_index = rmd.nextInt(list.size()); if(visited[photo_index]) continue; photo = list.get(photo_index); count++; //Ths will prevent an infinite loop if there are no valid images. } while ((photo.getLargeUrl() == null || photo.getLargeUrl().equals("")) && count < 100); //There must be at least one element with a valid url, I hope! } catch (FlickrException ex){ System.out.println(ex.getMessage()); } return PhotoBean.createBeanFromPhoto(photo); }
6
private GroupNode<K, V> getGroupNodeInstance( G group ) { GroupNode<K, V>[] buckets = mGroupBuckets; final int hash = (group == null ? 0 : rehash( group.hashCode() )); final int idx = hash & (buckets.length - 1); GroupNode<K, V> g = buckets[idx]; while( g != null ) { if( hash == g.mHash && (group == g.mGroup || group != null && group.equals( g.mGroup )) ) { return g; } g = g.mNext; } g = new GroupNode<K, V>( group, hash, buckets[idx] ); buckets[idx] = g; if( mGroupCount++ >= mGroupThreshold ) { resizeGroups( 2 * buckets.length ); } return g; }
7
public boolean tagAudioFile(boolean force) throws IOException { AudioFile theFile = fixTag(force); if (null != theFile) { try { theFile.commit(); } catch (CannotWriteException e) { throw new IOException(e); } return true; } return false; }
2
@Override public boolean equals(Object obj) { User other = (User) obj; if (getClass() == obj.getClass() && userId.equals(other.getUserId()) && firstName.equals(other.getFirstName()) && lastName.equals(other.getLastname())) return true; else return false; }
4
public void testConstructor_ObjectStringEx7() throws Throwable { try { new LocalDate("10:20:30.040+14:00"); fail(); } catch (IllegalArgumentException ex) {} }
1
public RegistrantList getRegistrantViewBy(String asViewById, String asLastModified, int aiMaxSize) { String lsParam = ""; if (aiMaxSize > 0) { lsParam += "&max_size=" + Integer.toString(aiMaxSize); } if (UtilityMethods.isValidString(asLastModified)) { lsParam += "&last_modified=" + asLastModified; } if (UtilityMethods.isValidString(lsParam)) { lsParam = lsParam.replaceFirst("&", "?"); } return get(RegistrantList.class, REST_URL_REGISTRATION_VIEW_BY + "/" + asViewById + lsParam); }
3
public static void merge(File f, TreeMap<String, ArrayList<String>> map) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { File outfile = new File(fileoutname); BufferedWriter bw = new BufferedWriter(new FileWriter(outfile, false)); Set<String> mapwords = map.keySet(); Iterator<String> mapit = mapwords.iterator(); String line = ""; String fileword = ""; String mapword = mapit.next(); while (mapit.hasNext()) { line = br.readLine(); if (line == null) { break; } // System.out.println("Line "+line); int loc = line.indexOf(TagName.equal); fileword = line.substring(0, loc); int flag = mapword.compareTo(fileword); if (flag < 0) { StringBuffer sb = createValueString(mapword, map.get(mapword)); sb.append(TagName.newline); bw.append(sb); mapword = mapit.next(); } else if (flag > 0) { bw.append(line); line = br.readLine(); } else if (flag == 0) { StringBuffer sb = new StringBuffer(); sb.append(line); sb.append(createValue(map.get(mapword))); sb.append(TagName.newline); bw.append(sb); line = br.readLine(); mapword = mapit.next(); } } while (mapit.hasNext()) { mapword = mapit.next(); StringBuffer sb = createValueString(mapword, map.get(mapword)); sb.append(TagName.newline); bw.append(sb); // mapit.next(); } line = br.readLine(); while (line != null) { bw.append(line); bw.newLine(); line = br.readLine(); } bw.close(); String temp = filein; // filein = fileout; // fileout = temp; } catch (Exception e) { e.printStackTrace(); } }
9
@Override public Class<?> getColumnClass(int columnIndex) { // Returns the class of each column if (columnIndex == columnNames.indexOf("Name")) { return String.class; } else if (columnIndex == columnNames.indexOf("Description")) { return String.class; } else { return Object.class; } }
3
public static ArrayList<ArrayList<String>> gettopiclist() throws SQLException { String sql="select TopicName,Path from Topics"; ArrayList<ArrayList<String>> feedback = new ArrayList<ArrayList<String>>(); ArrayList<String> feed = null; try { ResultSet rs = st.executeQuery(sql); ResultSetMetaData rsm = rs.getMetaData(); feed = new ArrayList<String>(); for(int y = 1;y<rsm.getColumnCount();y++){ feed.add(rsm.getColumnName(y)); } feedback.add(feed); while(rs.next()){ feed = new ArrayList<String>(); for(int i=1;i<=rsm.getColumnCount();i++){ feed.add(rs.getString(i)); } feedback.add(feed); } } catch (SQLException e) { //handler } return feedback; }
4
public void defuse() { if (bombActive && user.equals(bombHolder)) { if (wire(cmdArgs) == true) { connection.msgChannel(config.getChannel(), MircColors.WHITE + "Bomb defused."); bombActive = false; } else { connection.msgChannel(config.getChannel(), MircColors.BROWN + " ,_=~~:-" + MircColors.YELLOW + ")" + MircColors.BROWN + ",, "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " (" + MircColors.BROWN + "==?,::,:::::" + MircColors.YELLOW + ")" + MircColors.BROWN + "=:=" + MircColors.YELLOW + ") "); connection.msgChannel(config.getChannel(), MircColors.BROWN + " ?:=" + MircColors.YELLOW + "(" + MircColors.BROWN + ",~:::::::" + MircColors.YELLOW + ")" + MircColors.BROWN + "~+=:I" + MircColors.YELLOW + ") "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " (" + MircColors.BROWN + "=:" + MircColors.YELLOW + "(" + MircColors.BROWN + ",=:~++" + MircColors.YELLOW + "=:" + MircColors.BROWN + "::~,:~:" + MircColors.YELLOW + "))" + MircColors.BROWN + "~~~." + MircColors.YELLOW + ") "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " (" + MircColors.BROWN + "+~" + MircColors.YELLOW + "(" + MircColors.BROWN + ",:" + MircColors.YELLOW + "(==:" + MircColors.BROWN + ":~~+~~" + MircColors.YELLOW + ")" + MircColors.BROWN + ",$,I?" + MircColors.YELLOW + ")) "); connection.msgChannel(config.getChannel(), MircColors.BROWN + " `` ```" + MircColors.YELLOW + "~~" + MircColors.BROWN + "?" + MircColors.YELLOW + "~=" + MircColors.BROWN + "$.~~~ `` "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " :" + MircColors.BROWN + "S" + MircColors.YELLOW + "Z= "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " .-~~" + MircColors.BROWN + "?=:=" + MircColors.YELLOW + "``~-_ "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " `--=~=+~++=~` "); connection.msgChannel(config.getChannel(), MircColors.YELLOW + " ." + MircColors.BROWN + "~" + MircColors.YELLOW + ":" + MircColors.BROWN + "~ "); connection.msgChannel(config.getChannel(), MircColors.BROWN + " ((.(\\.!/.):?) "); connection.msgChannel(config.getChannel(), MircColors.DARK_GREEN + " .?~:?.?7::,::::+,,~+~=:... "); connection.kickFromChannel(config.getChannel(), user + " KABOOM!!!"); bombActive = false; } } else { connection.msgChannel(config.getChannel(), "Invalid."); } }
3
public static byte[] loadFile(final String path) { Preconditions.checkNotNull(path); InputStream fis = null; try { System.out.println(path); fis = new FileInputStream(path); BufferedInputStream bis = new BufferedInputStream(fis); byte[] byteArray = new byte[5121]; bis.read(byteArray, 0, byteArray.length); return byteArray; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3
public int evalRPN(String[] tokens) { //assume the length is greater than 3 final int len = tokens.length; Integer result = new Integer(0); Stack stack = new Stack(); for(int i = 0; i < len; i++){ if(!isOperator(tokens[i])) stack.push(Integer.valueOf(tokens[i])); else{ Integer operand2 = stack.pop(); Integer operand1 = stack.pop(); switch(tokens[i]){ case "+" : result = operand1 + operand2; break; case "-" : result = operand1 - operand2; break; case "*" : result = operand1 * operand2; break; case "/" : result = operand1 / operand2; break; default : break; } stack.push(result); } } return stack.pop(); }
6
private void openSerialPort() { Boolean foundPort = false; //Ist schon ein Port geoeffnet wird nichts gemacht if (serialPortOpen != false) { System.out.println("Serialport already opened"); return; } String selectedPort = (String) comPortComboBox.getSelectedItem(); if(!selectedPort.contentEquals("Select port")){ System.out.println("Open serialport"); try { // get COM Port Identifier CommPortIdentifier commPortID = CommPortIdentifier.getPortIdentifier(selectedPort); // open COM Port serialPort = (SerialPort) commPortID.open("serial " + selectedPort, 2000); // SerialSend und SerialReceive erzeugen serialSend = new SerialSend(serialPort, this); serialRecv = new SerialRecv(serialPort, this); Map<String, Integer> serialConfigurationMap = getConfigurationMap(); // System.out.println(Integer.parseInt((String) baudrateComboBox.getSelectedItem())); // System.out.println((String) dataBitsComboBox.getSelectedItem()); // System.out.println((String) stopBitComboBox.getSelectedItem()); // System.out.println((String) parityBitComboBox.getSelectedItem()); serialPort.setSerialPortParams(Integer.parseInt((String) baudrateComboBox.getSelectedItem()) , serialConfigurationMap.get((String) dataBitsComboBox.getSelectedItem()), serialConfigurationMap.get((String) stopBitComboBox.getSelectedItem()), serialConfigurationMap.get((String) parityBitComboBox.getSelectedItem())); serialPort.addEventListener(serialRecv); serialPort.notifyOnBreakInterrupt(false); serialPort.notifyOnCarrierDetect(false); serialPort.notifyOnCTS(false); serialPort.notifyOnDataAvailable(true); serialPort.notifyOnDSR(false); serialPort.notifyOnFramingError(false); serialPort.notifyOnOutputEmpty(false); serialPort.notifyOnOverrunError(false); serialPort.notifyOnParityError(false); serialPort.notifyOnRingIndicator(false); } catch (NoSuchPortException e) { e.printStackTrace(); } catch (PortInUseException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } serialPortOpen = true; } else{ System.out.println("Please select a port"); } }
5
private static String GonCalculate(int[] nodes) { int gonCount = nodes.length / 2; int[] result = new int[gonCount * gonCount]; ArrayList<Integer> nodeList = new ArrayList<Integer>(); for (int i = 0; i < nodes.length; i++) { nodeList.add(nodes[i]); } for (int gon = 0; gon < gonCount; gon++) { result[gon * 3] = nodeList.remove(0); result[gon * 3 + 1] = gon == 0 ? nodeList.remove(0) : result[(gon - 1) * 3 + 2]; result[gon * 3 + 2] = gon == gonCount - 1 ? result[1] : nodeList.remove(0); } boolean isOK = true; int sum = result[0] + result[1] + result[2]; for (int gon = 1; gon < gonCount; gon++) { if (sum != result[gon * 3] + result[gon * 3 + 1] + result[gon * 3 + 2] || result[gon * 3] < result[0]) { isOK = false; break; } } if (isOK) { StringBuilder stringBuilder = new StringBuilder(); for (int gon = 0; gon < gonCount; gon++) { stringBuilder.append(result[gon * 3]); stringBuilder.append(", "); stringBuilder.append(result[gon * 3 + 1]); stringBuilder.append(", "); stringBuilder.append(result[gon * 3 + 2]); stringBuilder.append("; "); } return stringBuilder.toString(); } else { return null; } }
9
public void addKeyDefinition(KeyDefinition keyDef) throws XPathException { if (keyDefinitions.isEmpty()) { collationName = keyDef.getCollationName(); } else { if ((collationName == null && keyDef.getCollationName() != null) || (collationName != null && !collationName.equals(keyDef.getCollationName()))) { XPathException err = new XPathException("All keys with the same name must use the same collation"); err.setErrorCode("XTSE1220"); throw err; } // ignore this key definition if it is a duplicate of another already present List v = getKeyDefinitions(); for (int i=0; i<v.size(); i++) { KeyDefinition other = (KeyDefinition)v.get(i); if (keyDef.getMatch().equals(other.getMatch()) && keyDef.getBody().equals(other.getBody())) { return; } } } if (keyDef.isBackwardsCompatible()) { backwardsCompatible = true; } keyDefinitions.add(keyDef); }
9
public void dispose(){ for(Texture texture : name2texture.values()){ texture.dispose(); } this.spriteBatch.dispose(); }
1
public static LinkedListNode partition ( LinkedListNode head, int x ) { int listSize = getListSize(head); LinkedListNode nd = head; LinkedListNode pre = new LinkedListNode(-1); pre.next = head; LinkedListNode dum = pre; for ( int i=0; i != listSize; ++i ) { LinkedListNode cur = nd; if ( cur.data >= x ) { nd = nd.next; // 1. delete any element that is bigger than x. pre.next = cur.next; cur.next = null; // 2. append such element to the tail. pre.appendToTail( cur ); } else { pre = nd; nd = nd.next; } System.out.println( dum.next.toString() ); } return dum.next; }
2
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYDifferenceRenderer)) { return false; } if (!super.equals(obj)) { return false; } XYDifferenceRenderer that = (XYDifferenceRenderer) obj; if (!PaintUtilities.equal(this.positivePaint, that.positivePaint)) { return false; } if (!PaintUtilities.equal(this.negativePaint, that.negativePaint)) { return false; } if (this.shapesVisible != that.shapesVisible) { return false; } if (!ShapeUtilities.equal(this.legendLine, that.legendLine)) { return false; } if (this.roundXCoordinates != that.roundXCoordinates) { return false; } return true; }
8
private void constructTree(TreeElement<TreeValue> place, TreeValue value, int id) throws AlreadyExistException{ // choose right or left way if (place.getId() > id) { // add if empty if (place.hasLeftSon()) { constructTree(place.getLeftSon(), value, id); } else { TreeElement<TreeValue> help = new TreeElement<>(value, id); place.setLeftSon(help); } } else { if (place.getId() < id) { // add if empty if (place.hasRightSon()) { constructTree(place.getRightSon(), value, id); } else { TreeElement<TreeValue> help = new TreeElement<>(value, id); place.setRightSon(help); } } else { throw new AlreadyExistException("You've tried to add an element, with wrong id"); } } }
4
public void addOffset(int bhw,int p,int val,int[] encoding) { p=p-1; String o=Integer.toBinaryString(val); if(val>(Math.pow(2, p)*bhw-1) || val<-(Math.pow(2, p)*bhw)) { System.out.println("!---------- ERROR: Offset out of range ----------!"); System.exit(0); } for(int i=o.length()-1;i>=0;i--) { if(o.charAt(i)=='1') encoding[i]=1; } }
4
@Override public void actionPerformed(ActionEvent actionEvent) { Object src = actionEvent.getSource(); for (JButton bt : colorButtons) { if (src == bt) { currentColorButton.setText(bt.getText()); currentColorButton.setForeground(bt.getForeground()); return; } } for (JButton bt : buttons) { if (src == bt) { bt.setText(currentColorButton.getText()); bt.setForeground(currentColorButton.getForeground()); return; } } if (src == ok) { if (cubeBehavior != null) { Command command = new Command(CommandType.COLOR, makeColorString()); //cubeBehavior.stop(); cubeBehavior.addCommand(command); //cubeBehavior.start(); } setVisible(false); } else if (src == cancel) { setVisible(false); } }
7
@Override public StateBuffer execute(StateBuffer in) { StateBuffer curBuffer = new StateBuffer(); for(State s : in.getStates()) skipToStart(curBuffer, s); StateBuffer goalBuffer = new StateBuffer(); // boolean first = true; TreeMap<Integer, StateBuffer> next = new TreeMap<Integer, StateBuffer>(); if (curBuffer.size() > 0) next.put(0, curBuffer); while(!next.isEmpty()) { Integer fewestSkips = next.firstKey(); curBuffer = next.get(fewestSkips); // System.out.println("EflTextSegment2: fewestSkips="+fewestSkips+" curBuffer="+curBuffer.size()+" goalBuffer="+goalBuffer.size()); next.remove(fewestSkips); for(State s : curBuffer.getStates()) progress(s, fewestSkips, next, goalBuffer); // first = false; } return goalBuffer; }
4
private void loadAllSuitesAndCases() throws InstantiationException, IllegalAccessException { Set<Class<? extends TestCase>> caseClases = getAllTestCaseClasses(); for (Class<? extends TestCase> caseClass : caseClases) { if (isIgnore(caseClass)) { continue; } String packageName = caseClass.getPackage().getName(); TestCase testCase = caseClass.newInstance(); if (packageName == mainPackage.getName()) { addCase(testCase); } else { TestSuite suite = suites.get(packageName); if (suite == null) { String[] packageNames = packageName.split("\\."); StringBuilder sb = new StringBuilder(packageNames[0]); for (int i = 1, len = packageNames.length-1; i < len;++i) { sb.append("."); sb.append(packageNames[i]); } String parentSuiteName = sb.toString(); String suiteName = packageNames[packageNames.length-1]; suite = new TestSuite(suiteName); suites.get(parentSuiteName).addSuite(suite); suites.put(packageName,suite); } suite.addCase(testCase); } } }
7
* @return The row, or <code>null</code> if none is found. */ public Row overRow(int y) { List<Row> rows = mModel.getRows(); int pos = getInsets().top; int last = getLastRowToDisplay(); for (int i = getFirstRowToDisplay(); i <= last; i++) { Row row = rows.get(i); if (!mModel.isRowFiltered(row)) { pos += row.getHeight() + (mDrawRowDividers ? 1 : 0); if (y < pos) { return row; } } } return null; }
4
public void setCutOffMatrix(float cutoff) { if (cutoff <= 0) throw new IllegalArgumentException("cutoff<=0"); rCutOff = cutoff; double[] sig = new double[Element.NMAX]; sig[ID_NT] = nt.getSigma(); sig[ID_PL] = pl.getSigma(); sig[ID_WS] = ws.getSigma(); sig[ID_CK] = ck.getSigma(); sig[ID_MO] = mo.getSigma(); sig[ID_SP] = sp.getSigma(); for (int i = ID_ALA; i <= ID_VAL; i++) sig[i] = aminoAcidElement[i - ID_ALA].getSigma(); for (int i = ID_A; i <= ID_U; i++) sig[i] = nucleotideElement[i - ID_A].getSigma(); int n = sig.length; int scale = 1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (isComplementary(i, j)) { // the following is used to extend the interaction range between A-T and C-G so that they // can attract slightly more strongly. However, if cutoff is set short, we mean to turn off // all attractions, I think. if (cutoff > 1.5) scale = 4; } cutOffSquareMatrix[j][i] = cutOffSquareMatrix[i][j] = sig[j] * sig[i] * cutoff * cutoff * scale; } } for (int i = 0; i < n; i++) { cutOffSquareMatrix[i][i] = sig[i] * sig[i] * cutoff * cutoff; } setShiftMatrix(cutoff); }
8
public static int dajTrenutniBrojGostiju() { Session session = HibernateUtil.getSessionFactory().openSession(); Query q = session.createQuery("from " + Boravak.class.getName()); List<Boravak> sviBoravci = (List<Boravak>)q.list(); session.close(); Date today = new Date(); int trBroj = 0; for(Boravak boravak : sviBoravci) { if(today.after(boravak.getVrijemeDolaska()) && today.before(boravak.getVrijemeOdlaska())) { trBroj++; } } return trBroj; }
3
@Override public void act() { robot.setAhead(1000); if ((new Random().nextInt(3) + 1) == 1) { robot.turnRight((new Random().nextInt(3) + 1) * 30); } if ((new Random().nextInt(5) + 1) == 1) { randomColor(); } }
2
private static boolean insertDrug(Drug bean, PreparedStatement stmt) throws SQLException{ stmt.setString(1, bean.getDrugName()); stmt.setString(2, bean.getDescription()); stmt.setInt(3, bean.getQuantity()); stmt.setBoolean(4, bean.isControlFlag()); stmt.setString(5, bean.getSideEffect()); int affected = stmt.executeUpdate(); if(affected == 1){ System.out.println("new drug added successfully"); }else{ System.out.println("error adding drug"); return false; } return true; }
1
private DefaultTableModel makeModel() { DefaultTableModel model = new DefaultTableModel(null ,columnNames){ private static final long serialVersionUID = 1L; public boolean isCellEditable(int row, int col) { if (col!=6) return false; return true; } }; return model; }
1
@FXML private void handleMenuReportItems(ActionEvent event) { File file = new File("商品情報一覧.txt"); try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) { bw.write(String.format("%s\t%s\t%s\t%s\t%s\r\n", "バーコード", "商品名", "単価", "仕入先", "部門")); try (PreparedStatement ps = getConnection().prepareStatement(Sql.get("report-item-list.sql"))) { ResultSet rs = ps.executeQuery(); while (rs.next()) { bw.write(String.format("%s\t%s\t%s\t%s\t%s\r\n", rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5))); } showMessageBar("レポートを作成しました"); } catch (SQLException e) { throw new RuntimeException(e); } } catch (IOException e) { throw new RuntimeException(e); } }
3
public boolean isBalancedNoStorage(treeNode root) { if (root == null) return true; if (!isBalancedNoStorage(root.leftLeaf)) return false; if (!isBalancedNoStorage(root.rightLeaf)) return false; int depthLeft = depthOfNodeNoStorage(root.leftLeaf); int depthRight = depthOfNodeNoStorage(root.rightLeaf); if (depthLeft + 1 <= depthRight || depthLeft - 1 >= depthRight) return true; else return false; }
5
private void equipCommand(String input, Player hero) { boolean pass = false; Equipment original = null; //The original equipment that was on the player Equipment temp = null; //The equipment found in the players inventory for (Item i : hero.getInventory()) { for (String s : i.getTags()) { if (s.equalsIgnoreCase(input)) { if (i.getClass().getSuperclass().equals(Equipment.class) || i.getClass().getSuperclass().equals(Weapon.class)) { pass = true; temp = (Equipment) i; //Sets the current item to a temp variable int equipType = temp.getEquipmentType(); if (equipType > 7) { equipType = equipType - 1; //For index mapping purposes, look at docs } original = hero.getEquipment()[equipType - 1]; //Gets the current players equipment, semi chance of bug but none so far hero.setEquipment(temp); //Sets the equipment from the inventory System.out.println("Equiped " + temp.getName()); } else { System.out.println("You can't equip that!"); pass = true; } } } } hero.getInventory().remove(temp); //removes the item from the inventory if (!pass) { System.out.println("There's no item here called that."); } else if (temp != null && !original.getName().equals("None")) { //Switch the equipment from inventory, all empty slots have a "None" equipment in them hero.addItemToInventory(original); } }
9
private Dimension layoutSize(Container target, boolean preferred) { synchronized (target.getTreeLock()) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the // container // has not yet been calculated so lets ask for the maximum. int targetWidth = target.getSize().width; if (targetWidth == 0) targetWidth = Integer.MAX_VALUE; int hgap = getHgap(); int vgap = getVgap(); Insets insets = target.getInsets(); int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2); int maxWidth = targetWidth - horizontalInsetsAndGap; // Fit components into the allowed width Dimension dim = new Dimension(0, 0); int rowWidth = 0; int rowHeight = 0; int nmembers = target.getComponentCount(); for (int i = 0; i < nmembers; i++) { Component m = target.getComponent(i); if (m.isVisible()) { Dimension d = preferred ? m.getPreferredSize() : m .getMinimumSize(); // Can't add the component to current row. Start a new row. if (rowWidth + d.width > maxWidth) { addRow(dim, rowWidth, rowHeight); rowWidth = 0; rowHeight = 0; } // Add a horizontal gap for all components after the first if (rowWidth != 0) { rowWidth += hgap; } rowWidth += d.width; rowHeight = Math.max(rowHeight, d.height); } } addRow(dim, rowWidth, rowHeight); dim.width += horizontalInsetsAndGap; dim.height += insets.top + insets.bottom + vgap * 2; // When using a scroll pane or the DecoratedLookAndFeel we need to // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. Container scrollPane = SwingUtilities.getAncestorOfClass( JScrollPane.class, target); if (scrollPane != null) { dim.width -= (hgap + 1); } return dim; } }
7
@Override public void propertyChange(PropertyChangeEvent evt) { if(evt.getPropertyName().equals(GameModel.EVENT_ADDED_SCORE)) { if((Integer)evt.getNewValue() > 1) { addedScore = (Integer)evt.getNewValue(); timerOn = true; timerStart = Calendar.getInstance().getTimeInMillis(); } } }
2
private int opPrecedence(Operator opr, int sid) { if (opr==null) { return Integer.MIN_VALUE; } // not an operator else if(opr.unary==NO_SIDE || opr.unary!=sid) { return (sid==LEFT_SIDE ? opr.precedenceL : opr.precedenceR); } // operator is binary or is unary and bound to the operand on the other side else { return Integer.MAX_VALUE; } // operator is unary and associates with the operand on this side }
4
private DensityMap createDensityMap(int numRateBoxes, int numTimeBoxes) { double maxTreeHeight = 0; double minRate = 1; double maxRate = 1; for (RootedTree tree : treeList) { double thisHeight = tree.getHeight(tree.getRootNode()); if (thisHeight > maxTreeHeight) maxTreeHeight = thisHeight; Set<Node> nodeList = tree.getNodes(); for (Node node : nodeList) { if (node != tree.getRootNode()) { double rate = getRate(node); if (rate < minRate) minRate = rate; if (rate > maxRate) maxRate = rate; } } } maxTreeHeight *= 1.0 + edgeFraction; double rateSpread = maxRate - minRate; minRate -= rateSpread * edgeFraction; if (minRate < 0) minRate = 0; System.out.println("real max = " + maxRate); maxRate += rateSpread * edgeFraction; System.out.println("new max = " + maxRate); // System.out.println("max treeheight = "+maxTreeHeight); // System.out.println("min rate = "+minRate); // System.out.println("max rate = "+maxRate); // System.exit(-1); DensityMap densityMap = new DensityMap(numTimeBoxes, numRateBoxes, 0, minRate, maxTreeHeight, maxRate); for (RootedTree tree : treeList) { addTreeToDensityMap(densityMap, tree); } return densityMap; }
8
private void timeStep(){ for (int i = 0; i < beings.size(); i++) { fight(i); } for (int i = 0; i < beings.size(); i++){ move(i); } }
2
private void dealTag(Tag tag, WebPage srb) throws Exception { NodeList list = tag.getChildren(); if (list != null) { NodeIterator it = list.elements(); while (it.hasMoreNodes()) { parserNode(it.nextNode(), srb); } it = null; } list = null; }
2
public void render(GameContainer gc, Graphics g) throws SlickException { for (Ray r : rays) { r.render(gc, g); } }
1