text
stringlengths
14
410k
label
int32
0
9
public static void determineWinners() { System.out.printf("%s has %d points.\n", dealer.getName(), dealer.getHand().getPoints()); for (Player p : playerList) { for (int i = p.getNumberOfHands() - 1; i >= 0; i--) { System.out.printf("%s has %d points for hand%d.\n", p.getName(), p.getHand(i).getPoints(), i + 1); if (p.getHand(i).getPoints() > 21) { System.out.printf("%s loses hand%d! \n", p.getName(), i + 1); p.takeFromWallet(p.getBet()); } else if (dealer.getHand().getPoints() > 21) { System.out.printf("%s wins hand%d! \n", p.getName(), i + 1); p.addToWallet(p.getBet()); } else if (p.getHand(i).getPoints() > dealer.getHand().getPoints()) { System.out.printf("%s wins hand%d! \n", p.getName(), i + 1); if (p.getHand(i).getPoints() == 21 && p.getHand(i).sizeOfHand() == 2) { p.addToWallet(p.getBet() * 1.5); } else p.addToWallet(p.getBet()); } else if (p.getHand(i).getPoints() == dealer.getHand().getPoints()) { System.out.printf("%s pushes hand%d! \n", p.getName(), i + 1); } else { System.out.printf("%s loses hand%d! \n", p.getName(), i + 1); p.takeFromWallet(p.getBet()); } } } }
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(usuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(usuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(usuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(usuario.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 usuario().setVisible(true); } }); }
6
public static boolean getKeyDown(int keyCode) { return getKey(keyCode) && !lastKeys[keyCode]; }
1
public void load(String file) { // when we load a new file, stop playback of other file. stop(); // Don't try all this if the sequencer is not open. if ( !sequencer.isOpen() ) { System.err.println("Cannot load a midiFile. The sequencer is not open."); return; } try { // Open a midi file // Get the midi file as a URL URL url = getClass().getClassLoader().getResource("" + file); // Get a midi sequence from the midi system and url Sequence sequence = MidiSystem.getSequence(url); // Now set this midi file to the sequencer sequencer.setSequence(sequence); // Now set isFileOpen to true, since we successfully opened it. isFileOpen = true; // Also, set the midiFile variable midiFile = file; // Print a success message to the console System.out.println("Loaded " + midiFile + "."); } catch ( IOException e) { System.err.println("IO Exception opening midi file: " + midiFile); System.err.println(e); isFileOpen = false; } catch ( InvalidMidiDataException e) { System.err.println("Invalid Midi Data"); System.err.println(e); isFileOpen = false; } } // End load()
3
@Override public void actionPerformed(ActionEvent e) { if(e.getSource() instanceof Timer){ int s = rand.nextInt(aliens.size()); if (s%3 ==0 && s%5 ==0){ fireAlien(s); } if(!reverse) { for (int i = 0; i < aliens.size(); i++) { Alien a = aliens.remove(i); int x = a.getX(); if (x + xDir + a.getWidth() > GameData.GAME_BOARD_WIDTH*4-a.getWidth()) { xDir = -xDir; reverse = true; aliens.add(i, new Alien(x, a.getY(), a.getWidth(), a.getHeight())); break; } x += xDir; aliens.add(i, new Alien(x, a.getY(), a.getWidth(), a.getHeight())); } } if(reverse){ for(int i = 0; i < aliens.size(); i++){ Alien a = aliens.remove(i); int x = a.getX(); if(x + xDir < 0 - a.getWidth()) { xDir = 50; reverse = false; aliens.add(i, new Alien(x, a.getY(), a.getWidth(), a.getHeight())); break; } x += xDir; aliens.add(i, new Alien(x, a.getY(), a.getWidth(), a.getHeight())); } } } repaint(); }
9
public String getAge() { return age; }
0
private boolean collision(Rectangle future, Rectangle[] walls){ for(int i = 0; i< walls.length; i++){ if(future.intersects(walls[i])){ return true; } } return false; }
2
public void setAppletContext(String htmlName, URL documentBase, URL codeBase, String appletProxyOrCommandOptions) { this.htmlName = htmlName; isApplet = (documentBase != null); String str = appletProxyOrCommandOptions; if (!isApplet) { // not an applet -- used to pass along command line options if (str.indexOf("-i") >= 0) { setLogLevel(3); // no info, but warnings and errors isSilent = true; } if (str.indexOf("-x") >= 0) { autoExit = true; } if (str.indexOf("-n") >= 0) { haveDisplay = false; } writeInfo = null; if (str.indexOf("-w") >= 0) { int i = str.indexOf("\1"); int j = str.lastIndexOf("\1"); writeInfo = str.substring(i + 1, j); } mustRender = (haveDisplay || writeInfo != null); } /* * Logger.info("jvm11orGreater=" + jvm11orGreater + "\njvm12orGreater=" + jvm12orGreater + "\njvm14orGreater=" + * jvm14orGreater); */ if (!isSilent) { Logger.info(JmolConstants.copyright + "\nJmol Version " + getJmolVersion() + "\njava.vendor:" + strJavaVendor + "\njava.version:" + strJavaVersion + "\nos.name:" + strOSName + "\n" + htmlName); } if (isApplet) fileManager.setAppletContext(documentBase, codeBase, appletProxyOrCommandOptions); zap(); // here to allow echos }
8
public static final Rectangle inset(int amount, Rectangle bounds) { bounds.x += amount; bounds.y += amount; bounds.width -= amount * 2; bounds.height -= amount * 2; if (bounds.width < 0) { bounds.width = 0; } if (bounds.height < 0) { bounds.height = 0; } return bounds; }
2
private void ConnectionButtonClicked(MouseEvent evt) { if(Settings.activatePremium){ if(!UsernameField.getText().trim().equals("")){ if(!passwordField.getPassword().toString().trim().equals("")){ login(UsernameField.getText().trim(), new String(passwordField.getPassword())); } else { notificationLabel.setText("Inserisci Password!"); } } else { notificationLabel.setText("Inserisci username!"); } } else { if(UsernameField.getText().trim().equals("")){ notificationLabel.setText("Inserisci username!"); } else { GameLauncher.username = UsernameField.getText().trim(); GameLauncher.Xmx = RamCombobox.getSelectedItem().toString().trim(); OptionsFrame.OptionsFrame.setVisible(false); Downloader.startThread(); } } }
4
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String t; t = x.nextToken(); if (t.toUpperCase().startsWith("HTTP")) { // Response o.put("HTTP-Version", t); o.put("Status-Code", x.nextToken()); o.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request o.put("Method", t); o.put("Request-URI", x.nextToken()); o.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); o.put(name, x.nextTo('\0')); x.next(); } return o; }
2
@Override public synchronized int readBit() throws BitStreamException { int res = this.delegate.readBit(); this.current <<= 1; this.current |= res; this.out.print((res & 1) == 1 ? "1" : "0"); this.lineIndex++; if (this.mark == true) this.out.print("r"); if (this.width != -1) { if ((this.lineIndex-1) % this.width == this.width-1) { if (this.showByte()) this.printByte(this.current); this.out.println(); this.lineIndex = 0; } else if ((this.lineIndex & 7) == 0) { this.out.print(" "); if (this.showByte()) this.printByte(this.current); } } else if ((this.lineIndex & 7) == 0) { this.out.print(" "); if (this.showByte()) this.printByte(this.current); } return res; }
9
private boolean calculateWindowSize() { boolean sizeIsOkay = true; int outsideFrameWidth = this.getWidth(); int outsideFrameHeight = this.getHeight(); if (outsideFrameWidth < MIN_WINDOW_WIDTH) { outsideFrameWidth = MIN_WINDOW_WIDTH; sizeIsOkay = false; } if (outsideFrameHeight < MIN_WINDOW_HEIGHT) { outsideFrameHeight = MIN_WINDOW_HEIGHT; sizeIsOkay = false; } if (outsideFrameHeight > outsideFrameWidth) { outsideFrameHeight = outsideFrameWidth; sizeIsOkay = false; } if (outsideFrameWidth > outsideFrameHeight * 2) { outsideFrameWidth = outsideFrameHeight * 2; sizeIsOkay = false; } Insets inset = this.getInsets(); windowPixelWidth = outsideFrameWidth - inset.left - inset.right; windowPixelHeight = outsideFrameHeight - inset.top - inset.bottom; if (!sizeIsOkay) { this.setSize(outsideFrameWidth, outsideFrameHeight); return false; } Library.setWindowPixelSize(windowPixelWidth, windowPixelHeight); Library.U_VALUE = windowPixelHeight; return true; }
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 SampleAttribute)) { return false; } SampleAttribute other = (SampleAttribute) object; if ((this.sampleAttributePK == null && other.sampleAttributePK != null) || (this.sampleAttributePK != null && !this.sampleAttributePK.equals(other.sampleAttributePK))) { return false; } return true; }
5
public boolean accept(File dir, String name) { boolean isAcceptable = false; for (int i = 0; i < m_extensionList.size(); i++) { String ext = m_extensionList.get(i); if (!ext.startsWith(".")) ext = "." + ext; isAcceptable = name.endsWith(ext); if (isAcceptable) break; } return isAcceptable; }
3
@Override public void setNull(int intId, String strTabla, String strCampo) throws Exception { Statement oStatement; try { oStatement = (Statement) oConexionMySQL.createStatement(); String strSQL = "UPDATE " + strTabla + " SET " + strCampo + " = null WHERE id = " + Integer.toString(intId); oStatement.executeUpdate(strSQL); } catch (SQLException e) { throw new Exception("mysql.setNull: Error al modificar el registro: " + e.getMessage()); } }
1
public GUIViewPanel(Grid initGame){ super(); game = initGame; dx = 50; dy = 50; try { floor = ImageIO.read(getClass().getResource("/WumpusImages/Ground.png")); blood = ImageIO.read(getClass().getResource("/WumpusImages/Blood.png")); goop = ImageIO.read(getClass().getResource("/WumpusImages/Goop.png")); slime = ImageIO.read(getClass().getResource("/WumpusImages/Slime.png")); pit = ImageIO.read(getClass().getResource("/WumpusImages/SlimePit.png")); hunter = ImageIO.read(getClass().getResource("/WumpusImages/TheHunter.png")); wumpus = ImageIO.read(getClass().getResource("/WumpusImages/Wumpus.png")); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); } setBackground(Color.BLACK); this.setFont(new Font(Font.MONOSPACED, Font.BOLD, 22)); repaint(); }
1
public static void bstTest() { for (int i = 0; i < 100; i++) { BST tree = new BST(); Make make = new Make(); ArrayList<Integer> list = make.list(); for (int n = 0; n < list.size(); n++) { tree.insert(list.get(n)); if (n % 10 == 0) { statsInsBST.add(new Stats(n, tree.getComparisonsIns())); } tree.setComparisonsIns(0); } //System.out.println(list.toString()); list = make.shuffleList(list); //System.out.println(list.toString()); for (int n = 0; n < list.size(); n++) { tree.remove(list.get(n)); if (n % 10 == 0) { statsDelBST.add(new Stats(n, tree.getComparisonsDel())); } tree.setComparisonsDel(0); } //if (tree.isEmpty()) { // System.out.println(i + ": is empty"); //} } System.out.println("Completed BST"); }
5
public ConvertCFGLL(GrammarEnvironment environment) { super("Convert CFG to PDA (LL)", null); this.environment = environment; }
0
@Override public void itemStateChanged(ItemEvent e) { if (textEntryField == null) { // We we're unable to find a JTextField component that was a decendant of this // JFileChooser so we need to abort. return; } String filename = textEntryField.getText(); if (filename == null || filename.equals("")) { return; } // Get the file format FileFormat format; if (e.getSource() == saveFormatComboBox) { format = Outliner.fileFormatManager.getSaveFormat(getSaveFileFormat()); } else if (e.getSource() == exportFormatComboBox) { format = Outliner.fileFormatManager.getExportFormat(getExportFileFormat()); } else { // Unknown source; System.out.println("Unknown source for itemStateChanged in OutlinerFileChooser."); return; } if (format == null) { System.out.println("Format is null for itemStateChanged in OutlinerFileChooser."); return; } // Get extension String extension = format.getDefaultExtension(); // Abort if we don't have an extension. if (extension == null || extension.equals("")) { return; } // trim any extension off the file name String newFileName = StringTools.trimExtension(filename, Preferences.EXTENSION_SEPARATOR); // Set the filename in the Chooser textEntryField.setText(new StringBuffer().append(newFileName).append(Preferences.EXTENSION_SEPARATOR).append(extension).toString()); }
8
public String getName() { return this.name; }
0
public static void send() { while (true) { Socket socket = null; byte[] readInput = new byte[80]; DatagramPacket packett = null; byte[] m = null; byte[] input = null; try { input = new byte[80]; packett = new DatagramPacket(input, input.length); m = getPacket(packett, input); serverThread st = new serverThread(socket); Thread thread = new Thread(st); thread.run(); } catch (Exception e) { } } }
2
public void finish(UQuest plugin, Player player, boolean showText){ Quester quester = plugin.getQuestInteraction().getQuester(player); int id = quester.getQuestID(); //For the event to know which quest id the player had //set them to having no active quest quester.setQuestID(-1); //set them to having no quest progress thingy stored quester.clearTracker(); //Increase player's finished quests meter thing if(showText == true) player.sendMessage(ChatColor.WHITE + " *Your total completed quests has increased by 1!"); quester.setQuestsCompleted(quester.getQuestsCompleted() + 1); //Consume the number of items used //for(Objective objective : this.objectives) //objective.done(player); //Reward Stuff for(Reward reward : this.rewards) reward.giveReward(plugin, player); //save them to file if(!(plugin.isUseSQLite())) plugin.saveQuesterToFile(quester); if(plugin.isUseSQLite()) plugin.getDB().put(player.getName(), quester); //finish info if(showText == true){ player.sendMessage(ChatColor.LIGHT_PURPLE + "**** Quest finished! ****"); player.sendMessage(ChatColor.GOLD + this.name); player.sendMessage(ChatColor.GREEN + this.finishInfo); } //call event plugin.getServer().getPluginManager().callEvent(new QuestFinishEvent(plugin.getServer().getPlayer(quester.getTheQuestersName()), quester, id)); }
5
public static int diferencaMatriz(int[][] matriz){ int[][] original = {{1, 2, 3},{4, 5, 6},{7, 8, 0}}; int dif = 0; int a; int b; int N = 3; for (a=0; a<3; a++){ for(b=0; b<3; b++){ if (original[a][b] != matriz[a][b]){ if (matriz[a][b]==0){ continue; } else{ if(matriz[a][b]!=original[a][b]){ dif++; } } } } } return dif; }
5
public Causa eliminacionImputadoPorTeclado(){ @SuppressWarnings("resource") Scanner scanner = new Scanner (System.in); String texto; int expediente; Long dni; Causa causa = new Causa(); try { System.out.println("Eliminar Imputado de Causa"); System.out.println("--------------------------"); while (true) { try { System.out.print("Ingrese Numero de Expediente: "); expediente = scanner.nextInt(); causa = this.getCausaByNumero(expediente); if (causa == null) { System.out.println("No existe ninguna Causa con Expediente " + expediente + ".Intente nuevamente"); } else { break; } } catch (RangeException e) { System.out.println(e.getMessage()); } } System.out.println("Datos de la Causa"); System.out.println("-----------------"); System.out.println(causa); scanner = new Scanner (System.in); while (true) { try { System.out.print("Ingrese el DNI del Imputado a eliminar de la Causa o presione [ENTER] para continuar: "); texto = scanner.nextLine(); if (texto.length()>0) { dni=Long.parseLong(texto); if (dni>0) causa.removeImputado(dni); } break; } catch (NumberFormatException e) { System.out.println("El DNI del imputado debe ser numerico"); } catch (ExcepcionValidacion e) { System.out.println(e.getMessage()); } } return causa; } catch (Exception e) { System.out.printf("ERROR EN EL SISTEMA: %s",e); return null; } }
9
private String getFormatedChange(String change) { StringBuilder sb = new StringBuilder("<font color=\""); final String typePattern = "[{].+[}]"; Pattern pattern = Pattern.compile(typePattern); Matcher matcher = pattern.matcher(change); List<String> matchList = new ArrayList<>(); while(matcher.find()) matchList.add(matcher.group(0)); if(matchList.size() < 1) return change; if(matchList.get(0).contains("+")) sb.append("green"); else if(matchList.get(0).contains("-")) sb.append("red"); else if(matchList.get(0).contains("*") || matchList.get(0).contains(".")) sb.append("orange"); else if(matchList.get(0).contains("/")) sb.append("yellow"); else if(matchList.get(0).contains("$")) sb.append("blue"); else sb.append("black"); return sb.append("\">").append(change.replaceFirst(typePattern, "")).append("</font>").toString(); }
8
public void setId(Long id) { this.id = id; }
0
public int[][] resetMatrix() { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { row[i] = true; col[j] = true; } } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (row[i] || col[j]) { matrix[i][j] = 0; } } } return matrix; }
7
public String handleCommand(String stp) { if(stp.toLowerCase().startsWith("tenable")){ if(enabled){ enabled = false; return "Commands Disabled."; }else{ enabled = true; return "Commands Enabled."; } } if(enabled){ //cannot be a switch case, it wont recognise .startsWith, which means commands couldnt take arguments. if(stp.toLowerCase().startsWith("help") || stp.toLowerCase().startsWith("?")){ return " Command list:\n \n" + " tEnable - Toggles command recognition. \n" + " say - Says something from the server. \n" + " clear - clears the screen. \n" + " history - gets the command history \n" + " exit - shuts down the server correctly. \n \n"; }else if(stp.toLowerCase().startsWith("say ")){ String s2 = stp.substring(stp.indexOf(" ")).trim(); return "Server: "+ s2; }else if(stp.toLowerCase().startsWith("history")){ StringBuilder SB = new StringBuilder(); for(int i = 0; i < prevInput.size(); i++){ SB.append(prevInput.get(i) + " \n"); } String returnMe = SB.toString(); System.out.println(returnMe + " history command!"); return returnMe; }else{ return "No such command."; } }else{ return "Commands disabled."; } }
8
public int length() { return this.myArrayList.size(); }
0
@Override public void run() { ServerSocket socket; boolean isRefreshRequest = false; System.out.println("Webserver starting up on port "+ SERVER_PORT); System.out.println("(press ctrl-c to exit)"); try { // create the main server socket socket = new ServerSocket(SERVER_PORT); } catch (Exception e) { System.out.println("Error: " + e); return; } System.out.println("Waiting for connection"); while (!WebThread.interrupted()) { try { isRefreshRequest = false; // wait for a connection Socket remote = socket.accept(); // remote is now the connected socket System.out.println("Connection, sending data."); BufferedReader in = new BufferedReader(new InputStreamReader( remote.getInputStream())); PrintWriter out = new PrintWriter(remote.getOutputStream()); // read the data sent. We basically ignore it, // stop reading once a blank line is hit. This // blank line signals the end of the client HTTP // headers. String str = "."; while (!str.equals("")) { str = in.readLine(); if (str.contains("/refresh")) { isRefreshRequest = true; } else if (str.contains("/restart")) { Main.restartGame(); } } // Send the response // Send the headers out.println("HTTP/1.0 200 OK"); if (isRefreshRequest) { out.println("Content-Type: text/json"); } else { out.println("Content-Type: text/html"); } // this blank line signals the end of the headers out.println(""); // Send the HTML page String result; if (isRefreshRequest) { result = makeRefreshJson(); } else { result = makeHtmlString(); } out.println(result); out.flush(); remote.close(); } catch (Exception e) { System.out.println("Error: " + e); } } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } }
9
@Override public IStatementObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); Class<?> klass = null; try { if (obj.has(OBJECT_TYPE)) { String objectType = obj.get(OBJECT_TYPE).getAsJsonPrimitive() .getAsString().toLowerCase(); if (objectType.equals(Agent.AGENT.toLowerCase())) { klass = Class.forName(Agent.class.getCanonicalName()); } else if (objectType.equals(Group.GROUP.toLowerCase())) { klass = Class.forName(Group.class.getCanonicalName()); } else if (objectType.equals(Activity.ACTIVITY.toLowerCase())) { klass = Class.forName(Activity.class.getCanonicalName()); } else if (objectType.equals(StatementReference.STATEMENT_REFERENCE.toLowerCase())) { klass = Class.forName(StatementReference.class.getCanonicalName()); } else if (objectType.equals(SubStatement.SUB_STATEMENT.toLowerCase())) { klass = Class.forName(SubStatement.class.getCanonicalName()); } } else { klass = Class.forName(Activity.class.getCanonicalName()); } } catch (ClassNotFoundException e) { throw new JsonParseException(e.getMessage()); } return context.deserialize(json, klass); }
8
public void giveItems() { Client o = (Client) Server.playerHandler.players[c.tradeWith]; if(o == null) { return; } try{ for(GameItem item : o.getTradeAndDuel().offeredItems){ if (item.id > 0) { c.getItems().addItem(item.id, item.amount); } } c.getPA().removeAllWindows(); c.tradeResetNeeded = true; CycleEventHandler.getSingleton().addEvent(this, new CycleEvent() { public void execute(CycleEventContainer container) { if(c.inTrade && c.tradeResetNeeded){ Client o = (Client) PlayerHandler.players[c.tradeWith]; if(o != null){ if(o.tradeResetNeeded){ c.getTradeAndDuel().resetTrade(); o.getTradeAndDuel().resetTrade(); container.stop(); } else { container.stop(); } } else { container.stop(); } } else { container.stop(); } } @Override public void stop() { c.tradeResetNeeded = false; } }, 1); PlayerSave.saveGame(c); } catch(Exception e){ } }
8
public DirectScrollPanelArea checkAndConvertToArea(Point where) { DirectScrollPanelArea area; if (mContentBounds.contains(where)) { area = DirectScrollPanelArea.CONTENT; } else { if (mHeaderBounds.contains(where)) { area = DirectScrollPanelArea.HEADER; } else { area = DirectScrollPanelArea.NONE; } } area.convertPoint(this, where); return area; }
2
@SuppressWarnings("serial") private void vali() throws NoSuchAlgorithmException, IOException { List<String> list = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); final String token = mainForm.getInputToken().getText(); final String timestamp = sdf.format(new Date()); Double non = Math.random()*99999; final String nonce = String.valueOf(non.intValue()); list.add(token); list.add(timestamp); list.add(nonce); Collections.sort(list); StringBuilder joinstr = new StringBuilder(); for (String string : list) { joinstr.append(string); } MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(joinstr.toString().getBytes()); byte[] digest = md.digest(); StringBuilder sha = new StringBuilder(); for (byte b : digest) { String hexValue = Integer.toHexString(b >= 0 ? b : 256 + b); if(hexValue.length()<2){ hexValue = "0" + hexValue; } sha.append(hexValue); } final String signature = sha.toString(); List<UrlConnectionUtil.Parameter> params = new ArrayList<UrlConnectionUtil.Parameter>(){{ add(Parameter.newInstance("token", token)); add(Parameter.newInstance("timestamp", timestamp)); add(Parameter.newInstance("nonce", nonce)); add(Parameter.newInstance("signature", signature)); add(Parameter.newInstance("echostr", "vali ok")); }}; URL url = new URL(this.mainForm.getInputUrl().getText() + "?" + UrlConnectionUtil.buildParameterStr(params)); URLConnection con = url.openConnection(); con.connect(); StringBuilder resp = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader( con.getInputStream())); try { for (String line = reader.readLine(); line != null; line = reader .readLine()) { resp.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) reader.close(); } this.mainForm.appendNewLine("result = " + resp.toString()); }
7
private void stopAllMunitions() { for (EnemyLauncher el : enemyLauncherArr) { try { if (el.getCurrentMissile() != null) { el.getCurrentMissile().join(); } el.stopRunning(); el.interrupt(); el.join(); } catch (InterruptedException e) { e.printStackTrace(); } } for (LauncherDestructor ld : launcherDestractorArr) { try { if (ld.getCurrentMissile() != null) { ld.getCurrentMissile().join(); } ld.stopRunning(); ld.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } for (IronDome ironDome : ironDomeArr) { try { if (ironDome.getCurrentMissile() != null) { ironDome.getCurrentMissile().join(); } ironDome.stopRunning(); ironDome.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }// endAllmunitions
9
public void userCraft(long id, String recipeId) { User user = getUser(id); Recipe recipe = getRecipe(recipeId); List<ItemTemplate> ingredients = recipe.getIngredients(); List<String> ingrNames = new ArrayList<String>(); for (ItemTemplate item : ingredients) { ingrNames.add(item.getId()); } // check that user has all ingredients Set<String> itemKeys = user.getItems().keySet(); if (!itemKeys.containsAll(ingrNames)) { return; } // apply craft Map<String, Long> items = user.getItems(); for (ItemTemplate ingr : ingredients) { Long cnt = items.get(ingr.getId()); cnt--; if (cnt == 0L) { items.remove(ingr.getId()); } else { items.put(ingr.getId(), cnt); } } ItemTemplate res = recipe.getResult(); if (items.containsKey(res.getId())) { items.put(res.getId(), items.get(res.getId()) + 1); } else { items.put(res.getId(), 1L); } user.setItems(items); updateUser(user); }
5
public void testGetFieldType() throws Throwable { MockPartial mock = new MockPartial(); assertEquals(DateTimeFieldType.year(), mock.getFieldType(0)); assertEquals(DateTimeFieldType.monthOfYear(), mock.getFieldType(1)); try { mock.getFieldType(-1); fail(); } catch (IndexOutOfBoundsException ex) {} try { mock.getFieldType(2); fail(); } catch (IndexOutOfBoundsException ex) {} }
2
public List<Contact> getContact(Contact c) { List<Contact> list = new ArrayList<Contact>(); for(Contact contact : plateforme) { if(!c.getNom().isEmpty()) { if(c.getNom().equalsIgnoreCase(contact.getNom())) list.add(contact); } if(!c.getPrenom().isEmpty()) { if(c.getPrenom().equalsIgnoreCase(contact.getPrenom())) list.add(contact); } if(!c.getAdresseMail().isEmpty()) { if(c.getAdresseMail().equalsIgnoreCase(contact.getAdresseMail())) list.add(contact); } if(!c.getDateNaissance().isEmpty()) { if(c.getDateNaissance().equalsIgnoreCase(contact.getDateNaissance())) list.add(contact); } } return list; }
9
public void parsedAimAvailable(AimParseEvent event) { AimParser aimParser = (AimParser)event.getSource(); String tumorID = aimParser.getTumorID(); String tumorName = aimParser.getTumorName(); Tumor tumor = new Tumor(tumorID, tumorName); String raterID = aimParser.getRaterID(); String raterName = aimParser.getRaterName(); Rater rater = new Rater(raterID, raterName); if(this.contains(tumor) == false){ rater.setAIMDescription(aimParser.getAIMDescription()); rater.setAIMStringXML(aimParser.getXMLString()); if (sopInstanceUIDPrev.contains(aimParser.getRefSOPInstanceUID()) && aimParser.getRaterName().equalsIgnoreCase("A")) { rater.setAsPreviousReport(true); aimGroupPrev.add(aimParser.getAIMFile()); tumor.addBaseRater(rater); tumors.add(tumor); } else if (sopInstanceUIDCurr.contains(aimParser.getRefSOPInstanceUID())) { rater.setAsPreviousReport(false); aimGroupCurr.add(aimParser.getAIMFile()); tumor.addRater(rater); tumors.add(tumor); } }else{ //Tumor foundTumor = getTumor(tumor.getTumorID()); Tumor foundTumor = getTumor(tumor.getTumorName()); rater.setAIMDescription(aimParser.getAIMDescription()); rater.setAIMStringXML(aimParser.getXMLString()); if (sopInstanceUIDPrev.contains(aimParser.getRefSOPInstanceUID()) && aimParser.getRaterName().equalsIgnoreCase("A")) { rater.setAsPreviousReport(true); aimGroupPrev.add(aimParser.getAIMFile()); foundTumor.addBaseRater(rater); } else if (sopInstanceUIDCurr.contains(aimParser.getRefSOPInstanceUID())) { rater.setAsPreviousReport(false); aimGroupCurr.add(aimParser.getAIMFile()); foundTumor.addRater(rater); } } }
7
public void fullReset(){ int i; gold = 0; for(i = 0; i < backpack.length; i++){ backpack[i] = null; } for(i = 0; i < equipment.length; i++){ equipment[i] = null; } }
2
private void waitForConnection() { // retrieve the local Bluetooth device object LocalDevice local = null; StreamConnectionNotifier notifier; StreamConnection connection = null; // setup the server to listen for connection try { local = LocalDevice.getLocalDevice(); local.setDiscoverable(DiscoveryAgent.GIAC); System.out.println( LocalDevice.getLocalDevice().getFriendlyName()); UUID uuid = new UUID("04c6093b00001000800000805f9b34fb", false); System.out.println(uuid.toString()); String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth"; notifier = (StreamConnectionNotifier)Connector.open(url); } catch (BluetoothStateException e) { System.out.println("Bluetooth is not turned on."); e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } // waiting for connection while(true) { try { Thread.sleep(100); System.out.println("waiting for connection..."); conex=1; Status(conex); main.setBluetooth("Bluetooth Device: \n"+LocalDevice.getLocalDevice().getFriendlyName()); connection = notifier.acceptAndOpen(); Thread processThread = new Thread(new ProcessConnectionThread(connection)); processThread.start(); } catch (Exception e) { e.printStackTrace(); return; } } }
4
public void setDateEmbauche(String dateEmbauche) { this.dateEmbauche = dateEmbauche; }
0
@Transactional @RequestMapping(value = {"/app/saveIssue"}, method = RequestMethod.POST) public ModelAndView saveIssue(HttpServletRequest request, @RequestParam(required = false) Long id, @RequestParam String title, @RequestParam String description, @RequestParam Long assignee, @RequestParam String priority, @RequestParam String status, Principal principal) { User visitor = usersRepository.findByLogin(principal.getName()); boolean newIssue = Utils.isEmpty(id); IssueForm issueForm; if (newIssue) { issueForm = new IssueForm(); issueForm.setCreator(visitor); issueForm.setCreationDate(new Date()); } else { issueForm = new IssueForm(issuesRepository.findOne(id)); } issueForm.setTitle(title); issueForm.setDescription(description); issueForm.setAssignee(assignee != null ? usersRepository.findOne(assignee) : null); issueForm.setPriority(Priority.valueOf(priority)); issueForm.setStatus(Status.valueOf(status)); MessageCollector collector = new MessageCollector(); IssueFormValidator validator = new IssueFormValidator(visitor, newIssue); ModelAndView modelAndView; if (validator.validate(collector, issueForm)) { Issue issue = newIssue ? new Issue() : issuesRepository.findOne(id); issueForm.apply(issue); issuesRepository.save(issue); if (!newIssue) { IssuesSearchForm searchForm = (IssuesSearchForm) request.getSession().getAttribute(Constants.BEAN_SEARCH_ISSUES_FORM); if (searchForm != null) { List<Issue> issues = searchIssues( visitor, searchForm.getCreator(), searchForm.getAssignee(), searchForm.getTitle(), searchForm.getPriority(), searchForm.getStatus() ); modelAndView = new ModelAndView("issues"); modelAndView.addObject(Constants.ISSUES, issues); } else { modelAndView = new ModelAndView("index"); } } else { modelAndView = new ModelAndView("index"); } modelAndView.addObject(Constants.USERS, usersRepository.findAll()); } else { modelAndView = new ModelAndView("edit_issue"); modelAndView.addObject(Constants.ISSUE, issueForm); modelAndView.addObject(Constants.USERS, usersRepository.findAll()); modelAndView.addObject(Constants.MESSAGE_COLLECTOR, collector); } return modelAndView; }
6
private void preserveRemainingInboundData() { if (mInboundData.hasRemaining()) { mUnderflowData = ByteBuffer.allocate(mInboundData.remaining()); mUnderflowData.put(mInboundData); mUnderflowData.flip(); } }
1
private void handlePublicQueue() { HospitalPart hp = HospitalPart.PUBLIC; Sector sec = sectors.get(hp); LinkedBlockingDeque<Patient> q = doc_queues.get(hp); if (sec.hasBusyDoc()) { int[] tmp = sec.getFinishTimes(); for (int i = 0; i < sec.getDocCount(); i++) { if (tmp[i] == clock) { Patient p = sec.goOut(i, "Public", q.size()); } } } if (!sec.isBusy() && q.size() > 0) { Patient p = q.poll(); PublicWorkType part = random.getPublicWorkType(); int docId = 0; switch (part) { case PRESCRIBE: Hospital.log("biya tooo Public", clock, p, hp.toString(), q.size()); docId = sec.setPatient(p); sec.setFinish_time(15 + clock, docId); break; case HOSPTILIZE: Hospital.log("biya tooo Public", clock, p, hp.toString(), q.size()); docId = sec.setPatient(p); sec.setFinish_time(25 + clock, docId); break; case REFER: Hospital.log("biya tooo Public", clock, p, hp.toString(), q.size()); doSpecialistStuff(p); break; default: System.out.println("never2"); } } }
8
public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Number of strings to follow:"); int numberOfStringsToFollow = s.nextInt(); s.nextLine(); String[] strings = new String[numberOfStringsToFollow]; int maxStringLength = 0; for(int i = 0; i < numberOfStringsToFollow; i++) { strings[i] = s.nextLine(); if(strings[i].length() > maxStringLength) { maxStringLength = strings[i].length(); } } for(int k = 0; k < maxStringLength; k++) { StringBuffer sb = new StringBuffer(); for(int j = 0; j < numberOfStringsToFollow; j++) { if(k < strings[j].length()) { sb.append(strings[j].charAt(k)); } else { sb.append(' '); } } System.out.println(sb); } }
5
public int inCityDefenseBonus(Hero hero) { if (buildings.contains(CastleBuilding.CASTLE)) { return 12; } else if (buildings.contains(CastleBuilding.CITADEL)) { return 8; } else if (buildings.contains(CastleBuilding.FORT)) { return 4; } return 0; }
3
@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 DatasetAttribute)) { return false; } DatasetAttribute other = (DatasetAttribute) object; if ((this.datasetAttributePK == null && other.datasetAttributePK != null) || (this.datasetAttributePK != null && !this.datasetAttributePK.equals(other.datasetAttributePK))) { return false; } return true; }
5
static public CTTrajectory<Double> cutTrajectory(CTTrajectory<Double> trj, double cutPercentage) //? TODO test throws IllegalArgumentException { if( trj == null) throw new IllegalArgumentException("Error: null trajectory"); if( trj.getTransitionsNumber() == 0) throw new IllegalArgumentException("Error: empty trajectory (name = " + trj.getName() + ")"); if( cutPercentage <= 0 || cutPercentage > 1) throw new IllegalArgumentException("Error: the cutting percentage must be in (0,1]"); // Searching of the last transition to keep double tMax = trj.getTransitionTime( trj.getTransitionsNumber() - 1) * cutPercentage; int iMin = 0; int iMax = trj.getTransitionsNumber() - 1; while( iMin <= iMax) { int i = iMin + (iMax - iMin)/2; CTTransition<Double> trans = trj.getTransition(i); if( trans.getTime() < tMax) iMin = i + 1; else if( trans.getTime() > tMax) iMax = i - 1; else { iMax = i; iMin = i+1; } } CTTransition<Double> lastTrans = trj.getTransition(iMax); // Transition of the new trajectory List<CTTransition<Double>> trjList = trj.transitions.subList(0, iMax + 1); if( lastTrans.getTime() != tMax) { // define the termination point String[] values = new String[trj.nodeIndexing.getNodesNumber()]; for(int i = 0; i < trj.nodeIndexing.getNodesNumber(); ++i) values[i] = lastTrans.getNodeValue(i); trjList.add(new CTTransition<Double>(trj.nodeIndexing, tMax, values)); } // New trajectory generation CTTrajectory<Double> newTrj = new CTTrajectory<Double>(trj.nodeIndexing); newTrj.setTransisions( trjList); newTrj.setName( trj.getName()); return newTrj; }
9
private void initGUI() { int position; this.setLayout( new BorderLayout() ); this.setOpaque( false ); // attributes ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ panelInven = new JPanel( new GridLayout( 4, 10 ) ); panelInven.setBorder( GUI.setupAreaBorder( "Inventory" ) ); panelInven.setOpaque( false ); panelCoinArmorAccess = new JPanel( new GridLayout( 1, 5 ) ); panelCoinArmorAccess.setOpaque( false ); panelCoin = new JPanel( new GridLayout( 4, 1 ) ); panelCoin.setBorder( GUI.setupAreaBorder( "Coins" ) ); panelCoin.setOpaque( false ); panelArmor = new JPanel( new GridLayout( 4, 1 ) ); panelArmor.setBorder( GUI.setupAreaBorder( "Armor" ) ); panelArmor.setOpaque( false ); panelAccess = new JPanel( new GridLayout( 5, 1 ) ); panelAccess.setBorder( GUI.setupAreaBorder( "Accss" ) ); panelAccess.setOpaque( false ); // adds ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this.add( panelInven, BorderLayout.CENTER ); for ( position = 0; position < Data.INVEN_SLOTS; position++ ) { if ( position == 10 ) { // #10 is Buildaria trash slot panelInven.add( new ItemPanel( this, ItemTypes.ALL, GUI.colorDisabled ) ); } // if else { panelInven.add( new ItemPanel( this, ItemTypes.ALL, GUI.colorInvenInv ) ); } // else } // for this.add( panelCoinArmorAccess, BorderLayout.EAST ); panelCoinArmorAccess.add( panelCoin ); for ( position = 0; position < Data.COIN_SLOTS; position++ ) { panelCoin.add( new ItemPanel( this, ItemTypes.COIN, GUI.colorInvenCoin ) ); } // for panelCoinArmorAccess.add( panelArmor ); panelArmor.add( new ItemPanel( this, ItemTypes.ARMOR_HEAD, GUI.colorEquipArmor ) ); panelArmor.add( new ItemPanel( this, ItemTypes.ARMOR_BODY, GUI.colorEquipArmor ) ); panelArmor.add( new ItemPanel( this, ItemTypes.ARMOR_LEGS, GUI.colorEquipArmor ) ); panelCoinArmorAccess.add( panelAccess ); for ( position = 0; position < Data.ACCESS_SLOTS; position++ ) { panelAccess.add( new ItemPanel( this, ItemTypes.ACCESSORY, GUI.colorEquipAcces ) ); } // for } // initGUI -----------------------------------------------------------------
4
@Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { metronome.update(container, delta); player.update(container, delta); if (metronome.isNewBeat()) { processBeat(container); } prompts.update(container, delta); for (GameObject o : gameObjectList) { o.update(container, delta); } for (int i = gameObjectList.size() - 1; i >= 0; i--) { if (gameObjectList.get(i).dead) { gameObjectList.remove(i); } } if (InputChecker.isInputPressed(container, KeyBindings.RESTART)) { init(container, game); } if (InputChecker.isInputDown(container, KeyBindings.QUIT)) { container.exit(); } }
6
private boolean isBorderBiomes(Tile tile, Point[] surrPoints) { boolean out = false; for (Point p : surrPoints) { Tile t = MyzoGEN.getOutput().getTile(p); if (t != null && t.tile != tile.tile && Tiles.getPrecedence(t.tile) > Tiles.getPrecedence(tile.tile)) { out = true; break; } } return out; }
4
public Instance(String[] args) throws FatalError, IOException { // configure plans PlanBoeseBeute.initiate(); PlanBoeseKrieg.initiate(); PlanBoeseRespekt.initiate(); PlanAngriff.initiate(); // reset config new Config(); // reset user new User(); this.parseArguments(args); if (this.modus.equals(Modus.help)) { Output.help(); } // read config file try { File f = new File(Config.getConfigFile()); FileInputStream fstream = new FileInputStream(f.getAbsoluteFile()); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine, configString = ""; // Read File Line By Line while ((strLine = br.readLine()) != null) { // Kommentare werden ausgelassen if (strLine.length() > 0 && strLine.substring(0, 1).equals("#")) { configString += "\n"; continue; } configString += strLine + "\n"; } // Close the input stream in.close(); try { JSONObject config = new JSONObject( new JSONTokener(configString)); Config.parseJsonConfig(config); } catch (JSONException e) { int lines = configString.substring(0, e.getIndex()).replaceAll("[^\n]", "").length(); throw new FatalError("Die Struktur der Konfigurationsdatei " + "stimmt nicht. Versuche den Inhalt der " + "Datei mit einem externen Werkzeug zu " + "reparieren. Dafür gibt es Webseiten, " + "die JSON-Objekte validieren können. Vermutlich in der Zeile " + lines + "." + "\n\nAls Hinweis hier noch die Fehlerausgabe:\n" + e.getMessage() + "\n\nEingabe war:\n" + e.getInputString()); } } catch (FileNotFoundException e) { throw new FatalError( "Die Konfigurationsdatei konnte nicht gefunden/geöffnet werden.\n Datei: " + Config.getConfigFile() + "\n Fehler: " + e.getMessage()); } if (Config.getUserName() == null || Config.getUserPassword() == null || Config.getHost() == null) { throw new FatalError( "Die Konfigurationsdatei ist nicht vollständig. " + "Es wird mindestens der Benutzername, das " + "Passwort und der Hostname benötigt."); } }
9
public static char[] build_keyed_alphabet(String k) { char[] result=new char[26]; String k_u=k.toUpperCase(); boolean[] filled=new boolean[26]; int pos=0; for(int i=0;i<k_u.length();i++) { char cur_c=k_u.charAt(i); int char_pos=cur_c-'A'; if(filled[char_pos]) { continue; } result[pos]=cur_c; filled[char_pos]=true; pos++; } for(int i=0;i<26;i++) { if(!filled[i]) { char cur_c=(char)('A'+i); result[pos]=cur_c; pos++; filled[i]=true; } } return result; }
4
public void lengthReturn() { if (length != FRAME_HEIGHT / 5) { duration++; if (duration == 1000) { length = FRAME_HEIGHT / 5; duration = 0; } } }
2
protected static byte[] getCertificateBytes() { if (certificateBytes == null) { InputStream certifacteStream = getCertificateStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; try { int bytesRead = 0; while ((bytesRead = certifacteStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { Logger.getLogger(Configuration.class.getCanonicalName()) .log(Level.SEVERE, "Error reading the certificate", e); } certificateBytes = outputStream.toByteArray(); } return certificateBytes; }
3
void select_imagesource(String direction) { if (this.image_file != null) { File file = null; File folder = image_file.getParentFile(); File[] listOfFiles = folder.listFiles(); HashMap<String, File> imageFiles = new HashMap<String, File>(); for (int i = 0; i < listOfFiles.length; i++) { file = listOfFiles[i]; if (file.isFile() && ( file.getName().toLowerCase().endsWith(".jpg") || file.getName().toLowerCase().endsWith(".png"))) { imageFiles.put(file.getName(), file); } } Object[] keys = imageFiles.keySet().toArray(); // Sort the keys so the files are ordered Arrays.sort(keys); int index = Arrays.asList(keys).indexOf(image_file.getName()); int next_index = (direction == "prev" ? index-1: index+1); if (next_index >= keys.length) next_index = 0; else if (next_index < 0) next_index = keys.length-1; String nextfile = null; try { image_file = imageFiles.get(keys[next_index]); nextfile = image_file.getCanonicalPath(); updateImageSource(new ImageSource(nextfile)); statusBar.setText("Opened " + image_file.getName()); this.imageMap.setSrc(image_file.getName()); //jTabbedPane1.setTitleAt(0, image_file.getName()); // currentFile.setText(image_file.getName()); } catch (Exception ex) { statusBar.setText("Exception getting "+direction+" image"); } } else statusBar.setText("no image file is currently open"); }
9
public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { List<String> incidents = new ArrayList<String>(); //compile the individual incident dates into a list while (values.hasNext()) { incidents.add(values.next().toString()); } if (incidents.size() > 0) { // sort that list by date Collections.sort(incidents); java.util.Map<Integer, Integer> weekSummary = new HashMap<Integer, Integer>(); for (int i=0; i<16; i++) { weekSummary.put(i, 0); } // aggregate each incident into weekly buckets for (String incidentDay : incidents) { try { Date d = getDate(incidentDay); Calendar cal = Calendar.getInstance(); cal.setTime(d); int week = cal.get(Calendar.WEEK_OF_MONTH); int month = cal.get(Calendar.MONTH); int bucket = (month * 5) + week; if (weekSummary.containsKey(bucket)) { weekSummary.put(bucket, new Integer(weekSummary.get(bucket).intValue() + 1)); } else { weekSummary.put(bucket, new Integer(1)); } } catch (ParseException pe) { log.warning(MessageFormat.format("Invalid date {0}", new Object[]{incidentDay})); } } // generate the output report line StringBuffer rpt = new StringBuffer(); boolean first = true; for (int week : weekSummary.keySet()) { if (first) { first = false; } else { rpt.append(","); } rpt.append(new Integer(weekSummary.get(week)).toString()); } String list = rpt.toString(); Text tv = new Text(); tv.set(list); output.collect(key, tv); } }
8
private void addSong() //tilføjer en sang { clear(); System.out.println("Add Song:"); System.out.println(); try { Scanner sc = new Scanner(System.in, "ISO-8859-1"); System.out.print("Title: "); String title = sc.nextLine(); System.out.print("Artist: "); String artistName = sc.nextLine(); System.out.print("Category: "); String categoryName = sc.nextLine(); System.out.print("Filename: "); String fileName = sc.nextLine(); System.out.print("Duration: "); int duration = sc.nextInt(); Artist a = amgr.getArtistByName(artistName); if (a == null) { a = amgr.addArtist(new Artist(-1, artistName)); } Category c = cmgr.getCategoryByName(categoryName); if (c == null) { c = cmgr.addCategory(new Category(-1, categoryName)); } Song song = new Song(-1, title, a, c, fileName, duration); song = smgr.AddSong(song); System.out.println(); System.out.println("Song added with ID : " + song.getId()); } catch (InputMismatchException e) { System.out.println("ERROR - Duration must be number"); } catch (Exception ex) { System.out.println("ERROR - " + ex.getMessage()); } pause(); }
4
public static void main(String[] args) throws IOException { // System.out.println( // Thread.currentThread().getContextClassLoader().getResource("")); // System.out.println(FileUtil.class.getClassLoader().getResource("")); // System.out.println(ClassLoader.getSystemResource("")); // System.out.println(FileUtil.class.getResource("")); // System.out.println(FileUtil.class.getResource("/")); // System.out.println(new File("").getAbsolutePath()); // System.out.println(System.getProperty("user.dir")); File directory = new File("");//参数为空 String courseFile = directory.getCanonicalPath(); System.out.println(courseFile); String filePath = FileUtil.class.getResource("/").getPath() + "\\data\\setting.properties"; File f = new File(FileUtil.class.getResource("/").getPath()); System.out.println(f); // File f = new File(filePath); if (f.exists()) { Properties prop = new Properties(); FileInputStream fis; try { fis = new FileInputStream(filePath); try { prop.load(fis); } catch (IOException ex) { } if (!prop.getProperty("queueDeep", "").isEmpty()) { System.out.println("queueDeep:" + prop.getProperty("queueDeep")); } if (!prop.getProperty("corePoolSize", "").isEmpty()) { System.out.println("corePoolSize:" + prop.getProperty("corePoolSize")); } if (!prop.getProperty("maximumPoolSize", "").isEmpty()) { System.out.println("maximumPoolSize:" + prop.getProperty("maximumPoolSize")); } if (!prop.getProperty("keepAliveTime", "").isEmpty()) { System.out.println("keepAliveTime:" + prop.getProperty("keepAliveTime")); } if (!prop.getProperty("totalTaskSize", "").isEmpty()) { String t = prop.getProperty("totalTaskSize"); int totalTaskSize = Integer.valueOf(t); System.out.println("totalTaskSize:" + totalTaskSize); } } catch (FileNotFoundException ex) { } } }
8
protected String InferLangFromCookie(HttpServletRequest httpRequest) { // Try to locate a cookie that states the user's language preference. // Calling applications should use this name when setting the cookie. // Cookie name: "language-preference" // Permissible values: "fr" or "en" try { for (Cookie cookie : httpRequest.getCookies()) if (cookie.getName().equals("language-preference")) { String lang = cookie.getValue(); log.debug("Found language preference in cookie: " + lang); return lang; } } catch (Exception ex) { log.error("Unable to infer a lang parameter from cookie: " + ex.getMessage()); } return null; }
3
public DisplayObject addChildAt(DisplayObject child, int index) { DisplayObjectImpl impl = ((ContainerImpl) overlay).addChildAt(child.getOverlay(), index); if (impl != null) { children.add(index, child); } return (impl != null ? child : null); }
2
@Override public void start(ExecutorTask executorTask) { if(ImageManager.imagesFinder.getRandomFilename(WaterMarkModel.isJpgTreatment(),WaterMarkModel.isPngTreatment(),WaterMarkModel.isGifTreatment()) == null){ return; } Rectangle panelRect=ArtiMarkFrame.panelWatermarkView.getBounds(); int leftSpare=Math.min(ArtiMarkFrame.watermarkImgComp.getX(),ArtiMarkFrame.figureImgComp.getX()); int widthRequed=Math.max(ArtiMarkFrame.watermarkImgComp.getX()+ArtiMarkFrame.watermarkImgComp.getWidth(),ArtiMarkFrame.figureImgComp.getX()+ArtiMarkFrame.figureImgComp.getWidth()); int topSpare=Math.min(ArtiMarkFrame.watermarkImgComp.getY(),ArtiMarkFrame.figureImgComp.getY()); int heightRequed=Math.max(ArtiMarkFrame.watermarkImgComp.getY()+ArtiMarkFrame.watermarkImgComp.getHeight(),ArtiMarkFrame.figureImgComp.getY()+ArtiMarkFrame.figureImgComp.getHeight()); widthRequed-=leftSpare; heightRequed-=topSpare; ArtiMarkFrame.watermarkImgComp.setLocation(ArtiMarkFrame.watermarkImgComp.getX()-leftSpare ,ArtiMarkFrame.watermarkImgComp.getY()-topSpare); ArtiMarkFrame.figureImgComp.setLocation(ArtiMarkFrame.figureImgComp.getX()-leftSpare ,ArtiMarkFrame.figureImgComp.getY()-topSpare); ArtiMarkFrame.panelWatermarkView.setSize(widthRequed, heightRequed); /*-------------------------------------------------------------------------*/ BufferedImage panelImg = (BufferedImage)ImageManager.getImageFromComponent(ArtiMarkFrame.panelWatermarkView); ArtiMarkFrame.panelWatermarkView.setBounds(panelRect); ArtiMarkFrame.watermarkImgComp.setLocation(ArtiMarkFrame.watermarkImgComp.getX()+leftSpare ,ArtiMarkFrame.watermarkImgComp.getY()+topSpare); ArtiMarkFrame.figureImgComp.setLocation(ArtiMarkFrame.figureImgComp.getX()+leftSpare ,ArtiMarkFrame.figureImgComp.getY()+topSpare); // ArtiMarkFrame.transBackofPanel.setVisible(true); // ArtiMarkFrame.switchXslider.setVisible(true); // ArtiMarkFrame.switchYslider.setVisible(true); Marker marker = new Marker(panelImg); /*-------------------------------------------------------------------------*/ Image imgStorage; int left; int top; double widthStrech=1,heightStrech=1,stratchWaterMarkFactor; if(WaterMarkModel.isJpgTreatment() ){ for(String filename:ImageManager.imagesFinder.getJPGfiles()){ imgStorage=ImageManager.open(ImageManager.fromFileOpener, ImageManager.imagesFinder.getDirectory()+filename); imgStorage = marker.convertImage(imgStorage); ImageManager.save( ImageManager.jpgSaver, ImageManager.imagesFinder.getDirectory()+WaterMarkModel.getImageOutputDirectoryName()+"art"+filename, imgStorage); } } if(WaterMarkModel.isPngTreatment() ){ for(String filename:ImageManager.imagesFinder.getPNGfiles()){ imgStorage=ImageManager.open(ImageManager.fromFileOpener, ImageManager.imagesFinder.getDirectory()+filename); imgStorage = marker.convertImage(imgStorage); ImageManager.save( ImageManager.pngSaver, ImageManager.imagesFinder.getDirectory()+WaterMarkModel.getImageOutputDirectoryName()+"art"+filename, imgStorage); } } if(WaterMarkModel.isGifTreatment() ){ for(String filename:ImageManager.imagesFinder.getGIFfiles()){ imgStorage=ImageManager.open(ImageManager.fromFileOpener, ImageManager.imagesFinder.getDirectory()+filename); imgStorage = marker.convertImage(imgStorage); ImageManager.save( ImageManager.gifSaver, ImageManager.imagesFinder.getDirectory()+WaterMarkModel.getImageOutputDirectoryName()+"art"+filename, imgStorage); } } ArtiMarkFrame.butBeginWMarking.setEnabled(false); executorTask.run(); }
7
public double mageDefTest() { double defenceBonus = c.playerBonus[8] == 0 ? 1 : c.playerBonus[8]; if(defenceBonus < 50)//1 defenceBonus = 50;//1 double defenceCalc = defenceBonus * c.playerLevel[1]; if (c.prayerActive[0]) defenceCalc *= 1.05; else if (c.prayerActive[3]) defenceCalc *= 1.10; else if (c.prayerActive[9]) defenceCalc *= 1.15; else if (c.prayerActive[18]) defenceCalc *= 1.20; else if (c.prayerActive[19]) defenceCalc *= 1.25; return defenceCalc; }
7
public void testPropertySetMonth() { YearMonth test = new YearMonth(1972, 6); YearMonth copy = test.monthOfYear().setCopy(12); check(test, 1972, 6); check(copy, 1972, 12); try { test.monthOfYear().setCopy(13); fail(); } catch (IllegalArgumentException ex) {} try { test.monthOfYear().setCopy(0); fail(); } catch (IllegalArgumentException ex) {} }
2
public byte[] scanForSpeech(byte[] dataBuffer) { ByteArrayOutputStream speechData = new ByteArrayOutputStream(); boolean isSpeech = false; int tailIndex = 0; for (int headIndex = 9; headIndex < dataBuffer.length; headIndex= headIndex+10) { // process this segment byte[] currentBuffer = Arrays.copyOfRange(dataBuffer, tailIndex, headIndex); int energy = this.sumEnergyInSingleSegment(currentBuffer); // check if we currently detect speech if (false == isSpeech) { if (this.getITL() < energy) { try { speechData.write(currentBuffer); } catch (IOException e) { System.out.println("Failed to write data to ByteArrayOutputStream"); e.printStackTrace(); } isSpeech = true; } } else { // check the buffer for the end of current word if (energy > this.getITU()){ try { speechData.write(currentBuffer); } catch (IOException e) { System.out.println("Failed to write data to ByteArrayOutputStream"); e.printStackTrace(); } } else { isSpeech = false; } } tailIndex = headIndex; } return speechData.toByteArray(); }
6
String[] countWords(String sentence, int returnWordCount) { // check input parameter if (sentence == null || sentence.isEmpty()) { System.out.println("Sentence not defined"); return null; } // check input parameter if (returnWordCount <= 0) { System.out.println("Return Words must be greater than zero"); return null; } // store count for each word discovered, indexed by word HashMap<String, Integer> wordFreq = new HashMap<>(); // remove all characters that are not spaces, letters, or digits final String regex = "[^a-zA-Z\\d\\ ]"; sentence = sentence.replaceAll(regex, ""); // parse string by space StringTokenizer token = new StringTokenizer(sentence); // count the word frequency in the sentence. This operation is O(n) while (token.hasMoreElements()) { String word = (String) token.nextElement(); if (wordFreq.containsKey(word)) { // existing word found. Increment word count Integer count = wordFreq.get(word) + 1; wordFreq.put(word, count); } else { // new word found, initial count is 1 wordFreq.put(word, 1); } } // Construct a heap from the hashmap sorted so that most frequent words are at the nodes // are at the head of the queue ReverseWordComparitor rComparator = new ReverseWordComparitor(); PriorityQueue<Node> sortedWords = new PriorityQueue<>(wordFreq.size(), rComparator); // Add items to the heap. Insertion takes O(n) for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) { sortedWords.add(new Node(entry.getKey(), entry.getValue())); } // check if return size is valid for number of words. If number of words less than return size, // adjust return size. if (returnWordCount > sortedWords.size()) { returnWordCount = sortedWords.size(); System.out.println("Return words size " + returnWordCount + " too high. Setting to " + sortedWords.size()); } // pop off the top number of entries until returnWordCount satisfied String[] returnList = new String[returnWordCount]; // add the words to the return list. Worst case is O(n) where returnWordCount equals n. for (int i = 0; i < returnList.length; i++) { returnList[i] = sortedWords.remove().word; } return returnList; }
8
public static List<Throwable> getVerificationFailures() { List<Throwable> verificationFailures = verificationFailuresMap.get(Reporter.getCurrentTestResult()); return verificationFailures == null ? new ArrayList<Throwable>() : verificationFailures; }
1
public double calculatePlatformAndOtherConsuptionsW(SoftwareSystem system) { double consumption = 0; for (HardwareSetAlternative hardwareSetAlternative : system.getHardwareSystem().getHardwareSetAlternatives()) if (system.getActuallyUsedHardwareSets().contains(hardwareSetAlternative.getHardwareSet())) { double consumptionOther = Utils.consumptionOther((Other) hardwareSetAlternative.getOtherAlternative().getHardwareComponents().toArray()[0], hardwareSetAlternative.getTime()); double consumptionPlatform = Utils.consumptionPlatform((Platform) hardwareSetAlternative.getPlatformAlternative().getHardwareComponents().toArray()[0], hardwareSetAlternative.getTime()); consumption += consumptionOther + consumptionPlatform; } return consumption; }
2
public void send(Object oo){ try { if(this.running){ out.writeObject(oo); out.flush(); } } catch (IOException e) { e.printStackTrace(); } }
4
public List<Class<? extends Peuple>> getPeuplesPris() { return peuplesPris; }
1
public TurnOff(){ super(Color.OFF); }
0
private boolean connectWithServer() { //Hacemos una comprobacion rápida de la ip. JLabel label = autConnectPane.isVisible() ? autInfo : connInfo; label.setText("Comprobando..."); if (URI.isWellFormedAddress(serverIP.getText())) { try { //Comprobamos que la direccion y el puerto son validos Inet4Address.getByName(serverIP.getText()); } catch (UnknownHostException ex) { label.setText("La dirección IP no es correcta."); serverIP.setForeground(Color.red); return false; } //Avisamos al usuario de que vamos a intentar conectarnos label.setText("Intentando realizar la conexión..."); //Intentamos conectarnos try { if (!con.conectar(serverIP.getText(), ec)) { JOptionPane.showMessageDialog(this, "<html>Se ha producido un error al establecer la conexión con el servidor<br>" + "La causa de este error puede haber sido:<br>" + "<ul><li>Ya hay una conexión abierta</li>" + "<li>El servidor no ha podido responder</li>" + "<li>El servidor está escuchando por otro puerto</li></ul>" + "Por favor, intentelo más tarde...</html>", "Error al realizar la conexión.", JOptionPane.OK_OPTION); label.setText("Error al conectar con el servidor."); return false; } showInterface(); return true; } catch (IOException ex) { //Si ocurre alguna excepcion, avisamos al usuario. JOptionPane.showMessageDialog(this, "<html>Se ha producido un error al establecer la conexión con el servidor<br>" + "La causa de este error puede haber sido:<br>" + "<ul><li>Ya hay una conexión abierta</li>" + "<li>El servidor no ha podido responder</li>" + "<li>El servidor está escuchando por otro puerto</li></ul>" + "Por favor, intentelo más tarde...</html>", "Error al realizar la conexión.", JOptionPane.OK_OPTION); label.setText("Error al conectar con el servidor."); return false; } } else { //Si la ip no es valida, avisamos al usuario serverIP.setForeground(Color.red); label.setText("La dirección IP no es válida."); return false; } }
5
public static void main(String args[]) { String encryptedPassword = encrypt("user"); System.out.println("The encrypted password for user is - " + encryptedPassword); }
0
public FromIterator(Iterable<T> source, Selector<T, Iterable<T2>> selector) { this._source = source.iterator(); this._selector = selector; }
0
public void create(Args args) throws IOException { //根据autoCodeConfig中的配置,调用coder生成代码 AutoCodeConfig config = AutoCodeConfig.loadConfig(args); if(args.getOptions() == null || args.getOptions().size() <= 0){ throw new RuntimeException("options is empty"); } if(args.getOptions().contains("a")){ createAll(config); }else { for(String option : args.getOptions()){ createComponent(option,config); } } }
4
private void VM_Parse(Element vms) { vect_vms = new ArrayList(); ArrayList<String> atts = new ArrayList<>(Arrays.asList("mips","cpu","ram", "bw", "size", "vmm")); List liste_vm = vms.getChildren(); int nb_vm = liste_vm.size(); System.out.println("There is"+ nb_vm + " VM(s)" ); for(int i = 0 ; i < nb_vm ; i++) { VmDatas tmp_vm_datas = new VmDatas(); Element One_vm = (Element)liste_vm.get(i); Iterator iterator = One_vm.getChildren().iterator(); while(iterator.hasNext()) { Element tmp_e = (Element)iterator.next(); String tmp_name =tmp_e.getName(); String tmp_value = tmp_e.getValue(); int ind = atts.indexOf(tmp_name); System.out.println(tmp_name + " "+ tmp_value + " // " + ind); switch(ind) { case 0: tmp_vm_datas.setMips(Integer.valueOf(tmp_value));break; case 1: tmp_vm_datas.setCpu(Integer.valueOf(tmp_value));break; case 2: tmp_vm_datas.setRam(Integer.valueOf(tmp_value));break; case 3: tmp_vm_datas.setBw(Integer.valueOf(tmp_value));break; case 4: tmp_vm_datas.setSize(Integer.valueOf(tmp_value));break; case 5: tmp_vm_datas.setVmm(tmp_value);break; } } vect_vms.add(tmp_vm_datas); } }
8
public void testDateConverter() { System.out.println("** testDateConverter **"); final int year = 2008; final int dayOfMonth = 22; final int hour = 7; final int minute = 3; final CycNaut cycDate = new CycNaut(DateConverter.MINUTE_FN, minute, new CycNaut(DateConverter.HOUR_FN, hour, new CycNaut(DateConverter.DAY_FN, dayOfMonth, new CycNaut(DateConverter.MONTH_FN, DateConverter.APRIL, new CycNaut(DateConverter.YEAR_FN, year))))); final Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(year, Calendar.APRIL, dayOfMonth, hour, minute); final Date javaDate = calendar.getTime(); try { assertTrue(DateConverter.isCycDate(cycDate)); assertEquals(javaDate, DateConverter.parseCycDate(cycDate)); assertEquals(cycDate, DateConverter.toCycDate(javaDate)); assertEquals(cycDate, DataType.DATE.convertJavaToCyc(javaDate)); assertEquals(javaDate, DataType.DATE.convertCycToJava(cycDate)); } catch (Exception e) { Assert.fail(e.getMessage()); } System.out.println("** testDateConverter OK **"); }
1
public void volcarDatos(ArrayList<Usuarios> libros){ DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); while(model.getRowCount()>0)model.removeRow(0); for(Usuarios u : libros){ Object[] fila = { u.getCodigo(), u.getNombre(), u.getDNI(), u }; model.addRow(fila); } }
2
public int DondeJugar() { if (MesaIsNull()) { return 1; } else { if ((Mesa.getAux().info.C1 == Ftemp.C1 || Mesa.getAux().info.C1 == Ftemp.C2) && (Mesa.getAux().info.C2 == Ftemp.C1 || Mesa.getAux().info.C2 == Ftemp.C2)) { return 0; } else { if (Mesa.getAux().info.C1 == Ftemp.C1 || Mesa.getAux().info.C1 == Ftemp.C2) { return 1; } else { ///Evalúa las dos caras de la fichas para ver si se puede insertar en la Cola de la lista if (Mesa.getAux().info.C2 == Ftemp.C1 || Mesa.getAux().info.C2 == Ftemp.C2) { return 2; } else { ///Sino se puede insertar en la cola ni en la cabeza, la Ficha no sirve //JOptionPane.showMessageDialog(null,"Ficha no sirve: "+Ftemp.C1+","+Ftemp.C2); return -1; } } } ///Evalúa las dos caras de la fichas para ver si se puede insertar en la cabeza de la lista } }
9
public void clearKeys(Class c) { if (modelManager.frame == null) return; Atom[] atoms = modelManager.frame.atoms; for (int i = 0; i < modelManager.frame.atomCount; i++) { if (SiteAnnotation.class == c) atoms[i].annotationKey = false; else if (InteractionCenter.class == c) atoms[i].interactionKey = false; } Bond[] bonds = modelManager.frame.bonds; for (int i = 0; i < modelManager.frame.bondCount; i++) { if (SiteAnnotation.class == c) bonds[i].annotationKey = false; else if (InteractionCenter.class == c) bonds[i].interactionKey = false; } }
7
public void setColor(String color) { this.color = color; }
0
public void deal() { if (deck.getDeck().size() >= 4) { deck.deal(player); deck.deal(dealer); dealer.getHand().get(0).flip(); dealer.refreshImage(); info.update(deck); dealButton.setEnabled(false); hitButton.setEnabled(true); standButton.setEnabled(true); if (player.getMoney() >= bet) doubleButton.setEnabled(true); } }
2
static public String openOrder( int orderId, Contract contract, Order order, OrderState orderState) { String msg = "open order: orderId=" + orderId + " action=" + order.m_action + " quantity=" + order.m_totalQuantity + " symbol=" + contract.m_symbol + " exchange=" + contract.m_exchange + " secType=" + contract.m_secType + " type=" + order.m_orderType + " lmtPrice=" + order.m_lmtPrice + " auxPrice=" + order.m_auxPrice + " TIF=" + order.m_tif + " localSymbol=" + contract.m_localSymbol + " client Id=" + order.m_clientId + " parent Id=" + order.m_parentId + " permId=" + order.m_permId + " outsideRth=" + order.m_outsideRth + " hidden=" + order.m_hidden + " discretionaryAmt=" + order.m_discretionaryAmt + " triggerMethod=" + order.m_triggerMethod + " goodAfterTime=" + order.m_goodAfterTime + " goodTillDate=" + order.m_goodTillDate + " faGroup=" + order.m_faGroup + " faMethod=" + order.m_faMethod + " faPercentage=" + order.m_faPercentage + " faProfile=" + order.m_faProfile + " shortSaleSlot=" + order.m_shortSaleSlot + " designatedLocation=" + order.m_designatedLocation + " ocaGroup=" + order.m_ocaGroup + " ocaType=" + order.m_ocaType + " rule80A=" + order.m_rule80A + " allOrNone=" + order.m_allOrNone + " minQty=" + order.m_minQty + " percentOffset=" + order.m_percentOffset + " eTradeOnly=" + order.m_eTradeOnly + " firmQuoteOnly=" + order.m_firmQuoteOnly + " nbboPriceCap=" + order.m_nbboPriceCap + " auctionStrategy=" + order.m_auctionStrategy + " startingPrice=" + order.m_startingPrice + " stockRefPrice=" + order.m_stockRefPrice + " delta=" + order.m_delta + " stockRangeLower=" + order.m_stockRangeLower + " stockRangeUpper=" + order.m_stockRangeUpper + " volatility=" + order.m_volatility + " volatilityType=" + order.m_volatilityType + " deltaNeutralOrderType=" + order.m_deltaNeutralOrderType + " deltaNeutralAuxPrice=" + order.m_deltaNeutralAuxPrice + " continuousUpdate=" + order.m_continuousUpdate + " referencePriceType=" + order.m_referencePriceType + " trailStopPrice=" + order.m_trailStopPrice + " scaleInitLevelSize=" + Util.IntMaxString(order.m_scaleInitLevelSize) + " scaleSubsLevelSize=" + Util.IntMaxString(order.m_scaleSubsLevelSize) + " scalePriceIncrement=" + Util.DoubleMaxString(order.m_scalePriceIncrement) + " account=" + order.m_account + " settlingFirm=" + order.m_settlingFirm + " clearingAccount=" + order.m_clearingAccount + " clearingIntent=" + order.m_clearingIntent + " notHeld=" + order.m_notHeld + " whatIf=" + order.m_whatIf ; if ("BAG".equals(contract.m_secType)) { if (contract.m_comboLegsDescrip != null) { msg += " comboLegsDescrip=" + contract.m_comboLegsDescrip; } if (order.m_basisPoints != Double.MAX_VALUE) { msg += " basisPoints=" + order.m_basisPoints; msg += " basisPointsType=" + order.m_basisPointsType; } } if (contract.m_underComp != null) { UnderComp underComp = contract.m_underComp; msg += " underComp.conId =" + underComp.m_conId + " underComp.delta =" + underComp.m_delta + " underComp.price =" + underComp.m_price ; } if (!Util.StringIsEmpty(order.m_algoStrategy)) { msg += " algoStrategy=" + order.m_algoStrategy; msg += " algoParams={"; if (order.m_algoParams != null) { Vector algoParams = order.m_algoParams; for (int i = 0; i < algoParams.size(); ++i) { TagValue param = (TagValue)algoParams.elementAt(i); if (i > 0) { msg += ","; } msg += param.m_tag + "=" + param.m_value; } } msg += "}"; } String orderStateMsg = " status=" + orderState.m_status + " initMargin=" + orderState.m_initMargin + " maintMargin=" + orderState.m_maintMargin + " equityWithLoan=" + orderState.m_equityWithLoan + " commission=" + Util.DoubleMaxString(orderState.m_commission) + " minCommission=" + Util.DoubleMaxString(orderState.m_minCommission) + " maxCommission=" + Util.DoubleMaxString(orderState.m_maxCommission) + " commissionCurrency=" + orderState.m_commissionCurrency + " warningText=" + orderState.m_warningText ; return msg + orderStateMsg; }
8
boolean formula(){ char ch = get(); if(ch=='('){ boolean f1 = formula(); ch = get(); if(ch=='*'){ boolean f2 = formula(); get(); return f1&&f2; } else if(ch=='+'){ boolean f2 = formula(); get(); return f1||f2; } else{ get(); boolean f2 = formula(); get(); return !f1||f2; } } else if(ch=='-'){ return !formula(); } else if(ch=='T'){ return true; } else if(ch=='F'){ return false; } else return assign[ch-'a']; }
9
public Location getAdjacentLocation(int direction) { // reduce mod 360 and round to closest multiple of 45 int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE; if (adjustedDirection < 0) adjustedDirection += FULL_CIRCLE; adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT; int dc = 0; int dr = 0; if (adjustedDirection == EAST) dc = 1; else if (adjustedDirection == SOUTHEAST) { dc = 1; dr = 1; } else if (adjustedDirection == SOUTH) dr = 1; else if (adjustedDirection == SOUTHWEST) { dc = -1; dr = 1; } else if (adjustedDirection == WEST) dc = -1; else if (adjustedDirection == NORTHWEST) { dc = -1; dr = -1; } else if (adjustedDirection == NORTH) dr = -1; else if (adjustedDirection == NORTHEAST) { dc = 1; dr = -1; } return new Location(getRow() + dr, getCol() + dc); }
9
public boolean trainCanMove() { if (train.size() == 0) return true; else { int totalWeight = 0; for (int i = 0; i < train.size(); i++) { switch (train.get(i).getClass().getSimpleName()) { case LOCOMOTIVE: totalWeight += ((Locomotive) train.get(i)).getGrossWeight(); break; case PASSENGERCAR: totalWeight += ((PassengerCar) train.get(i)) .getGrossWeight(); break; case FREIGHTCAR: totalWeight += ((FreightCar) train.get(i)).getGrossWeight(); break; } } if (((Locomotive) train.get(0)).power() >= totalWeight) return true; else return false; } }
6
private static File[] createFileArray(BufferedReader bReader, PrintStream out) { try { java.util.List list = new java.util.ArrayList(); java.lang.String line = null; while ((line = bReader.readLine()) != null) { try { // kde seems to append a 0 char to the end of the reader if (ZERO_CHAR_STRING.equals(line)) continue; java.io.File file = new java.io.File(new java.net.URI(line)); list.add(file); } catch (Exception ex) { log(out, "Error with " + line + ": " + ex.getMessage()); } } return (java.io.File[]) list.toArray(new File[list.size()]); } catch (IOException ex) { log(out, "FileDrop: IOException"); } return new File[0]; }
4
public TreeNode sortedArrayToBSTRec(int[] num, int s, int e){ if(s > e) return null; if(s == e) { return new TreeNode(num[s]); } int mid = (s+e) >> 1; TreeNode t1 = sortedArrayToBSTRec(num, s, mid - 1); TreeNode t2 = sortedArrayToBSTRec(num, mid + 1, e); TreeNode t = new TreeNode(num[mid]); t.left = t1; t.right = t2; return t; }
2
public static Battlefield create(){ if(battleField == null ){ battleField = new Battlefield(); } return battleField; }
1
public static void cartesianToPolar(Graph graph, ArrayList vertices) { double theta, r; Point2D cartesian; for (int i=0; i<vertices.size(); i++) { cartesian = graph.pointForVertex(vertices.get(i)); if (cartesian.getY() != 0) theta = Math.atan(cartesian.getY() / cartesian.getX()); else theta = Math.PI / 2; r = Math.sqrt(Math.pow(cartesian.getX(), 2) + Math.pow(cartesian.getY(), 2)); graph.moveVertex(vertices.get(i), new Point2D.Double(r, theta)); } }
2
@Override public long readVLong() { byte b = bytes[pos++]; if (b >= 0) return b; long i = b & 0x7FL; b = bytes[pos++]; i |= (b & 0x7FL) << 7; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 14; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 21; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 28; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 35; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 42; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 49; if (b >= 0) return i; b = bytes[pos++]; i |= (b & 0x7FL) << 56; if (b >= 0) return i; throw new RuntimeException("Invalid vLong detected (negative values disallowed)"); }
9
public DisplayMode findFirstCompatibleMode( DisplayMode modes[]) { DisplayMode goodModes[] = device.getDisplayModes(); for (int i = 0; i < modes.length; i++) { for (int j = 0; j < goodModes.length; j++) { if (displayModesMatch(modes[i], goodModes[j])) { return modes[i]; } } } return null; }
3
public static int getMax(int intArr[], int len){ int max = intArr[0]; for (int i=1; i<len; i++){ if (intArr[i]>max) max = intArr[i]; } return max; }
2
public void actionPerformed( ActionEvent evento ) { String comando = evento.getActionCommand( ); if( BOTON_INICIAR.equals( comando ) ) { ventanaPrincipal.iniciar( ); } else if( BOTON_STEP.equals( comando ) ) { ventanaPrincipal.avanzar(); } else if( BOTON_EDITAR.equals( comando ) ) { ventanaPrincipal.editar(); } }
3
public void delete() throws SQLException { if(this.isNew()) { return; } PreparedStatement statement = connect.prepareStatement(" delete from `" + tableName + "` where `id` = " + id ); statement.executeUpdate(); this.id = 0; }
1
private double[] initProbability() { double[] prob = new double[langlist.size()]; if (priorMap != null) { for(int i=0;i<prob.length;++i) prob[i] = priorMap[i]; } else { for(int i=0;i<prob.length;++i) prob[i] = 1.0 / langlist.size(); } return prob; }
3
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof LightNode)) { return false; } LightNode other = (LightNode) obj; if (!color.equals(other.color)) { return false; } if (Float.floatToIntBits(intensity) != Float .floatToIntBits(other.intensity)) { return false; } return true; }
5
@Test public void determineHighestFlush_ifFourOfSameSuit_returnNull() { assertNull(getAllFlushCards(fourFlushWithStraight())); }
0