text
stringlengths
14
410k
label
int32
0
9
public static String kuvaFormaatti(String kuvanNimi) { String teksti = kuvanNimi; teksti.toLowerCase(); if (teksti.endsWith(".png")) { return "png"; } if (teksti.endsWith(".gif")) { return "gif"; } if (teksti.endsWith(".jpg")) { return "jpg"; } return "jpg"; }
3
private void setupListeners() { saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent click) { Game tempGame = baseController.makeGameFromInput(titleField.getText(), rankingField.getText(), rulesArea.getText()); if (tempGame != null) { baseController.saveGameInformation(tempGame); gameCountLabel.setText("Number of Games: " + baseController.getProjectGames().size()); } else { JOptionPane.showMessageDialog(null, "Not a valid number"); } } }); loadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent click) { Game tempGame = baseController.readGameInformation(); if (tempGame != null) { titleField.setText(tempGame.getGameTitle()); rankingField.setText(Integer.toString((tempGame.getFunRanking()))); String tempRules = ""; for (String currentRule : tempGame.getGameRules()) { tempRules += currentRule + "\n"; } rulesArea.setText(tempRules); } else { JOptionPane.showMessageDialog(null, "Check the file, make sure it is in order."); } } }); }
3
private boolean executaComando(char comando, String parametros) throws MVNException{ switch(comando){ case CMD_INICIALIZA: initialize(); break; case CMD_ASCII: loadTextFiletoMemory(parametros); break; case CMD_EXECUTA: executa(ExtractArguments(parametros)); break; case CMD_DEBUG: switchDebugMode(); break; case CMD_DISPOSITIVOS: dispositivos(); break; case CMD_REGISTRADORES: showRegisters(); break; case CMD_MEMORIA: dumpMemory(ExtractArguments(parametros)); break; case CMD_AJUDA: ajuda(); break; case CMD_FINALIZA: return false; default: throw new MVNException(ERR_INVALID_COMMAND, comando); } return true; }
9
public void create() { frame = new JFrame(TITLE); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE)); frame.pack(); frame.setLocationRelativeTo(null); frame.add(this); frame.setVisible(true); }
0
public int[] calculateDragDistance() { int[] distances = new int[2]; int startX = clickX; int startY = clickY; int currentX = mouseX; int currentY = mouseY; if (startX < currentX) { distances[0] = +(currentX - startX); } if (startX > currentX) { distances[0] = -(startX - currentX); } if (startY < currentY) { distances[1] = +(currentY - startY); } if (startY > currentY) { distances[1] = -(startY - currentY); } return distances; }
4
public boolean pickAndExecuteAnAction() { synchronized(marketbills) { for (MyMarketBill mb : marketbills) { if (mb.state == mbState.unpaid) { payMarketBill(mb); } } } synchronized(uncomputedChecks) { for(Check c: uncomputedChecks) { if(c.state == CheckState.uncomputed) { c.state = CheckState.unpaid; computeCheck(c); return true; } } } synchronized(computedChecks) { for(MyCheck c: computedChecks) { if(c.check.state == Check.CheckState.paid) { processCheck(c); return true; } } } if(person.cityData.hour >= restPanel.CLOSINGTIME && !restPanel.isOpen() && restPanel.justCashier()) { LeaveRestaurant(); return true; } return false; }
9
@Override public void run(){ try{ say(s,""); say(s, "Sorry, there are too many users."); say(s, "Server message: too many users"); } catch(Exception e){ e.printStackTrace(); } }
1
private JLabel getLblSongName() { if (lblSongName == null) { lblSongName = new JLabel("Song name :"); lblSongName.setBounds(10, 81, 86, 14); } return lblSongName; }
1
public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); }
6
@Override public void updateCourses(List<Integer> mainCourseList, List<Integer> additionalCourseList, int userId) throws SQLException { Connection connect = null; PreparedStatement statement = null; try { Class.forName(Params.bundle.getString("urlDriver")); connect = DriverManager.getConnection(Params.bundle.getString("urlDB"), Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB")); String getTeacherId = "select student.id from student " + "where student.user_id = ?"; statement = connect.prepareStatement(getTeacherId); statement.setInt(1, userId); ResultSet studentIdSet = statement.executeQuery(); studentIdSet.next(); int studentId = studentIdSet.getInt("student.id"); String selectMarks = "update student set main_course_1_id = ?, main_course_2_id = ?, main_course_3_id = ?, main_course_4_id = ?," + "add_course_1_id = ?,add_course_2_id = ? where student.id = ?"; statement = connect.prepareStatement(selectMarks); int i = 0; for(; i < mainCourseList.size(); i++) statement.setInt(i + 1, mainCourseList.get(i)); for(; i < additionalCourseList.size() + mainCourseList.size(); i++) statement.setInt(i + 1, additionalCourseList.get(i - mainCourseList.size())); statement.setInt(i+1, studentId); statement.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(connect != null) connect.close(); if(statement != null) statement.close(); } }
6
public void run() { // Set colors setBodyColor(new Color(128, 128, 50)); setGunColor(new Color(50, 50, 20)); setRadarColor(new Color(200, 200, 70)); setScanColor(Color.white); setBulletColor(Color.blue); // Prepare gun trackName = null; // Initialize to not tracking anyone setAdjustGunForRobotTurn(true); // Keep the gun still when we turn gunTurnAmt = 10; // Initialize gunTurn to 10 // Loop forever while (true) { // turn the Gun (looks for enemy) turnGunRight(gunTurnAmt); // Keep track of how long we've been looking count++; // If we've haven't seen our target for 2 turns, look left if (count > 2) { gunTurnAmt = -10; } // If we still haven't seen our target for 5 turns, look right if (count > 5) { gunTurnAmt = 10; } // If we *still* haven't seen our target after 10 turns, find another target if (count > 11) { trackName = null; } } }
4
private void generateHardwareSystemAlternativesEP() { int alternatives = 1; int possibilities[] = new int[project.getHardwareSets().size()]; int repetitions[] = new int[project.getHardwareSets().size()]; int i = 0; for (HardwareSet hws : project.getHardwareSets()) { alternatives *= hws.getHardwareSetCheapestAlternatives().size(); possibilities[i] = hws.getHardwareSetCheapestAlternatives().size(); repetitions[i++] = alternatives / hws.getHardwareSetCheapestAlternatives().size(); } generateHardwareSystemsEP(alternatives, possibilities, repetitions); }
1
@Override public HandshakeState acceptHandshakeAsClient( ClientHandshake request, ServerHandshake response ) { if( failed ) { return HandshakeState.NOT_MATCHED; } try { if( !response.getFieldValue( "Sec-WebSocket-Origin" ).equals( request.getFieldValue( "Origin" ) ) || !basicAccept( response ) ) { return HandshakeState.NOT_MATCHED; } byte[] content = response.getContent(); if( content == null || content.length == 0 ) { throw new IncompleteHandshakeException(); } if( Arrays.equals( content, createChallenge( request.getFieldValue( "Sec-WebSocket-Key1" ), request.getFieldValue( "Sec-WebSocket-Key2" ), request.getContent() ) ) ) { return HandshakeState.MATCHED; } else { return HandshakeState.NOT_MATCHED; } } catch ( InvalidHandshakeException e ) { throw new RuntimeException( "bad handshakerequest", e ); } }
7
public String returnInsertColumnsDefine() { StringBuilder sb = new StringBuilder(); List<String> list = columnMap.get(this.getClass()); int i = 0; for (String column : list) { if (isNull(column)) continue; if (i++ != 0) sb.append(','); sb.append("#{").append(column).append('}'); } return sb.toString(); }
3
private void sendAsChunked(OutputStream outputStream, PrintWriter pw) throws IOException { pw.print("Transfer-Encoding: chunked\r\n"); pw.print("\r\n"); pw.flush(); int BUFFER_SIZE = 16 * 1024; byte[] CRLF = "\r\n".getBytes(); byte[] buff = new byte[BUFFER_SIZE]; int read; while ((read = data.read(buff)) > 0) { outputStream.write(String.format("%x\r\n", read).getBytes()); outputStream.write(buff, 0, read); outputStream.write(CRLF); } outputStream.write(String.format("0\r\n\r\n").getBytes()); }
1
@Override public int hashCode() { return isAlive ? 1231 : 1237; }
1
private void loadWorlds() throws DynmapInitException { for (DynmapWorld world : dynmapConfig.getWorlds()) { logger.info("Checking World " + world.getName()); AbstractFile dynmapWorldConfig = null; try { dynmapWorldConfig = getFile("standalone/dynmap_" + world.getName() + ".json"); } catch (IOException e) { throw new DynmapInitException(e); } if (!dynmapWorldConfig.exists()) { throw new DynmapInitException("World " + world.getName() + " has no config in Dynmap"); } if (!dynmapWorldConfigs.containsKey(world.getName())) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(dynmapWorldConfig.getInputStream()))) { DynmapWorldConfig dynmapWorldConfig1 = gson.fromJson(reader, DynmapWorldConfig.class); dynmapWorldConfigs.put(world.getName(), dynmapWorldConfig1); logger.info("Loaded World " + world.getName()); } catch (FileNotFoundException e) { logger.error("Error in reading in the Worldfile", e); } catch (IOException e) { logger.error("Error in closing in the Worldfile", e); } } } }
6
public void loadAlphabets(String filename) { try { File f = new File(filename); Scanner s = new Scanner(f); String line = null; List<String> dot_mat_alpha = new ArrayList<String>(); if(s.hasNext()) characters = s.nextLine(); int i = 0; while (s.hasNext() && (line = s.nextLine()) != null && i < characters.length()) { char c = line.charAt(0); if (c == '#') { String alpha = Character.toString(characters.charAt(i++)); this.dm.put(alpha, dot_mat_alpha); dot_mat_alpha = new ArrayList<String>(); } else dot_mat_alpha.add(line); } //Dot Matrix representation for the blank character dot_mat_alpha = new ArrayList<String>(); for(int j = 0; j < 7; j++) { dot_mat_alpha.add(" "); } this.dm.put(" ", dot_mat_alpha); } catch (FileNotFoundException e) { System.out.println(" Dot Matrix Alphabets file not found"); System.exit(1); } }// End of loadAlphabets method
7
public static void decTrigger() { idTrigger--; }
0
private boolean r_verb_suffix() { int among_var; int v_1; int v_2; int v_3; int v_4; // (, line 175 // setlimit, line 176 v_1 = limit - cursor; // tomark, line 176 if (cursor < I_pV) { return false; } cursor = I_pV; v_2 = limit_backward; limit_backward = cursor; cursor = limit - v_1; // (, line 176 // [, line 176 ket = cursor; // substring, line 176 among_var = find_among_b(a_8, 96); if (among_var == 0) { limit_backward = v_2; return false; } // ], line 176 bra = cursor; limit_backward = v_2; switch(among_var) { case 0: return false; case 1: // (, line 179 // try, line 179 v_3 = limit - cursor; lab0: do { // (, line 179 // literal, line 179 if (!(eq_s_b(1, "u"))) { cursor = limit - v_3; break lab0; } // test, line 179 v_4 = limit - cursor; // literal, line 179 if (!(eq_s_b(1, "g"))) { cursor = limit - v_3; break lab0; } cursor = limit - v_4; } while (false); // ], line 179 bra = cursor; // delete, line 179 slice_del(); break; case 2: // (, line 200 // delete, line 200 slice_del(); break; } return true; }
8
public void close(){ try { List<User> f = pod.getFriendList(); //récupère la liste d'ami //on la stocke dans un JSONArray JSONArray t = new JSONArray(); for(int i = 0 ; i < f.size() ; i++) t.put(i, f.get(i).getLocation()); //On récupère les amis qui était dans l'ancien fichier stocker la liste d'ami mais qui n'ont pas répondu. File oldFile = new File(pod.getOwner().getName() + ".ami.social "); //on récupère le fichier if(oldFile.isFile()){ //s'il existe try { //on récupère son contenu FileInputStream fileReader= new FileInputStream(oldFile); byte[] tmp = new byte[fileReader.available()]; fileReader.read(tmp); fileReader.close(); JSONArray oldFriend = new JSONArray( new String(tmp) ); for(int i = 0 ; i < oldFriend.length() ; i++) { String[] infoFriendTrie = ((String) oldFriend.get(i)).split(":"); infoFriendTrie[0] = (infoFriendTrie[0].split("/"))[1]; PodLocation friendLocation = new PodLocation(InetAddress.getByName(infoFriendTrie[0]), Integer.parseInt(infoFriendTrie[1])); if(pod.hasPendingFriend(friendLocation)) t.put(t.length()+1, friendLocation); } }catch(Exception e) { e.printStackTrace(); } } // On crée le fichier FileWriter fstream = new FileWriter(pod.getOwner().getName() + ".ami.social "); BufferedWriter out = new BufferedWriter(fstream); out.write(t.toString()); out.close(); //On sauvegarde les messages List<Message> svgMsg = pod.getMessages();//on les récupère //on la stocke dans un JSONArray JSONArray tMsg = new JSONArray(); for(int i = 0 ; i < svgMsg.size() ; i++) tMsg.put(i, svgMsg.get(i).toJSON()); // On crée le fichier FileWriter msgStream = new FileWriter(pod.getOwner().getName() + ".messages.social "); BufferedWriter outMsg = new BufferedWriter(msgStream); outMsg.write(tMsg.toString()); outMsg.close(); //On indique la déconnexion à tous nos amis. Iterator<User> i = f.iterator(); while(i.hasNext()) { User tmp = i.next(); pod.sendCommand(tmp.getLocation().getAddress(), tmp.getLocation().getPort(), "DEL", pod.getOwner().toJSON()); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } }
9
public void singlePlayerMove(Object source, int indexPosition) { boolean legalMove = false; legalMove = singlePlayerGame.selectSquare(indexPosition); if (legalMove) { // Draw board moves on board setOpponentsMove(singlePlayerGame.getComputersMostRecentMove()); ((AbstractButton) source).setText(team); String status = singlePlayerGame.checkStatus(); // TODO make enum try { if ("WON".equals(status)) { endOfGame("You win!!"); } else if ("LOSE".equals(status)) { endOfGame("Sorry you lose."); } else if ("DRAW".equals(status)) { endOfGame("Cat's game... it's a draw!"); } } catch (IOException e) { e.printStackTrace(); } } }
5
public void test_getValue_long() { assertEquals(0, iField.getValue(0L)); assertEquals(12345, iField.getValue(12345678L)); assertEquals(-1, iField.getValue(-1234L)); assertEquals(INTEGER_MAX, iField.getValue(LONG_INTEGER_MAX * 1000L + 999L)); try { iField.getValue(LONG_INTEGER_MAX * 1000L + 1000L); fail(); } catch (ArithmeticException ex) {} }
1
@Override public MapObject doNextAction(MapEngine engine, double s_elapsed) { if (is_cloaked && cloak_time_left < 0.0) { is_cloaked = false; is_visible = true; playPublicSound("effects/cloakoff.wav"); } MultipleObject created_objects = new MultipleObject(); if (!death_spin_started) { if (!death_spin_started) { if (firing_cannon) { firing_cannon = false; created_objects.addObject(fireCannon()); } if (firing_secondary) { firing_secondary = false; created_objects.addObject(fireSecondary()); } if (dropping_bomb) { dropping_bomb = false; created_objects.addObject(dropBomb()); } } } created_objects.addObject(super.doNextAction(engine, s_elapsed)); if (!is_in_map && shields < 0) { room.doSplashDamage(this, DEATH_SPLASH_DAMAGE, DEATH_SPLASH_DAMAGE_RADIUS, this); ((PyroPilot) pilot).prepareForRespawn(); engine.respawnPyroAfterDeath(this); } return created_objects; }
9
public static void load(int track) { // TODO Auto-generated constructor stub switch (track) { case 0: splash = loadMusic("splash.ogg"); break; case 1: game = loadMusic("game.ogg"); break; case 2: kill = loadMusic("kill.ogg"); break; } }
3
public Hole getHole(int holeNumber) { for (Hole hole : holes) { if (hole.getHoleNumber() == holeNumber) { return hole; } } return null; }
2
public void setColorArray(String id, Color[] color) { int count = 0; for(int i=0;i<identity.size();i++) { if(identity.get(i).contains(id)) { attrib_colors = new Color[2]; attrib_colors[0] = color[count]; //Color attrib_colors[1] = colors.get(i)[1]; //Textcolor colors.set(i, attrib_colors); count++; } } }
2
@Override public void signalEndOfData() { taskAcceptor.signalEndOfData(); }
0
public void stripFunction(){ //set validness of filename to false as initialization and other general initialization boolean valid=false; //if inputs are valid String inFileName=_curDir; //input filename String outFileName=_saveDir; //output file name int overrideChoice=-1; //for override button choice String path=""; //variable for path //get output file if(FileChecker.validInFile(inFileName,Constants.VIDEO_AUDIO_TYPE)){ valid=false; //set correctness of output file path to false if (outFileName==null){ JOptionPane.showMessageDialog(null, "You have not entered a destination to save to. Please input a valid file name."); }else if(outFileName.equals("")){ //error message of empty file name JOptionPane.showMessageDialog(null, "You have entered an empty file name. Please input a valid file name."); }else{ Matcher m =Pattern.compile(".mp3$").matcher(outFileName); if (_curDir.equals(_saveDir)){ //error message need to not be the same name as input file JOptionPane.showMessageDialog(null, "Your input file and output file cannot be the same. Please input a valid file name that is not the same."); }else if (m.find()){ if (FileChecker.fileExist(outFileName)){ //file exist ask if override Object[] option= {"Override","New output file name"}; //check if the file exist locally //note 0 is override ie first option chosen and 1 is new name overrideChoice=JOptionPane.showOptionDialog(null, "File " +outFileName +" already exist. Do you wish to override or input new file name?", "Override?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,option,option[0]); if(overrideChoice==0){ valid=true;//out file valid } }else{ valid=true;//out file valid } }else{ //error message need to end with mp3 JOptionPane.showMessageDialog(null, "You have entered a file name that does not end with .mp3 \nPlease input a valid file name that ends with .mp3"); } } } if(valid){ //delete to be override file if(overrideChoice==0){ File file=new File(outFileName); file.delete(); } //create the gui of extract which consist of cancel and progress bar JFrame stripAudioFrame=new JFrame("Strip audio"); Container pane=stripAudioFrame.getContentPane(); pane.setLayout(new GridLayout(2,0)); JButton cancelButton =new JButton("Cancel Strip Audio"); JProgressBar dlProgressBar=new JProgressBar(); stripAudioFrame.setSize(300, 100); //set size of frame cancelButton.addActionListener(new ActionListener() { //setup cancel button listener @Override public void actionPerformed(ActionEvent e) { saWork.cancel(true); } }); //add window listener to close button (cross hair) so it cancel as well stripAudioFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ saWork.cancel(true); } }); stripAudioFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); stripAudioFrame.add(cancelButton,pane); //add cancel button to new frame stripAudioFrame.add(dlProgressBar,pane); //add progress bar to new frame stripAudioFrame.setVisible(true); //set visibility of frame on stripAudioFrame.setResizable(false); //set frame so it can't be resize //create swing worker object and run it saWork=new StripAudioWorker(path+inFileName,outFileName,stripAudioFrame,dlProgressBar); saWork.execute(); } }
9
public void mutate(int strandIndex, int mutatorKind, int index, Nucleotide nucleotideTo) { Strand strand = getStrand(strandIndex); if (strand == null) return; Mutator mutator = strand.getMutator(mutatorKind); if (mutator == null) return; if ((mutator instanceof SubstitutionMutator) || (mutator instanceof InsertionMutator)) { if (nucleotideTo == null) mutator.setMutationParam(null); else { String nucleoString = new String(new char[] { nucleotideTo.getName() }); mutator.setMutationParam(new Object[] { nucleoString }); } } else if (mutator instanceof MixedMutator) { Object[] mutatorParams = new Object[probabilities.length]; for (int i = 0; i < mutatorParams.length; i++) { mutatorParams[i] = new Integer(probabilities[i]); } mutator.setMutationParam(mutatorParams); } mutator.mutate(this, strandIndex, index); mutator.setMutationParam(null); verifyFragments(); }
7
public void setLives(int a){ lives = a; }
0
public void fusionWithAddFullAlpha(CPLayer fusion, CPRect rc) { CPRect rect = new CPRect(0, 0, width, height); rect.clip(rc); for (int j = rect.top; j < rect.bottom; j++) { int off = rect.left + j * width; for (int i = rect.left; i < rect.right; i++, off++) { int color1 = data[off]; int alpha1 = (color1 >>> 24) * alpha / 100; int color2 = fusion.data[off]; int alpha2 = (color2 >>> 24) * fusion.alpha / 100; int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255; if (newAlpha > 0) { /* * // this version seems slower than the Math.min one int r = (alpha2 * (color2 >>> 16 & 0xff) + * alpha1 * (color1 >>> 16 & 0xff)) / newAlpha; r |= ((~((r & 0xffffff00) - 1) >> 16) | r) & 0xff; * int g = (alpha2 * (color2 >>> 8 & 0xff) + alpha1 * (color1 >>> 8 & 0xff)) / newAlpha; g |= ((~((g & * 0xffffff00) - 1) >> 16) | g) & 0xff; int b = (alpha2 * (color2 & 0xff) + alpha1 * (color1 & * 0xff)) / newAlpha; b |= ((~((b & 0xffffff00) - 1) >> 16) | b) & 0xff; */ int r = Math.min(255, (alpha2 * (color2 >>> 16 & 0xff) + alpha1 * (color1 >>> 16 & 0xff)) / newAlpha); int g = Math.min(255, (alpha2 * (color2 >>> 8 & 0xff) + alpha1 * (color1 >>> 8 & 0xff)) / newAlpha); int b = Math.min(255, (alpha2 * (color2 & 0xff) + alpha1 * (color1 & 0xff)) / newAlpha); fusion.data[off] = newAlpha << 24 | r << 16 | g << 8 | b; } } } fusion.alpha = 100; }
3
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { Physical target=mob; if((auto)&&(givenTarget!=null)) target=givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(mob,target,null,L("<T-NAME> <T-IS-ARE> already affected by @x1.",name())); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> attain(s) opaque eyes!"):L("^S<S-NAME> @x1 for divine revelation, and <S-HIS-HER> eyes become opaque.^?",prayWord(mob))); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> @x1 for divine revelation, but <S-HIS-HER> prayer is not heard.",prayWord(mob))); // return whether it worked return success; }
7
public static String getJailer(String playerName){ String banner = "Not Jailed"; if(isJailed(playerName)){ try { SQL_STATEMENT = SQL_CONNECTION.createStatement(); SQL_RESULTSET = SQL_STATEMENT.executeQuery("SELECT * FROM jails WHERE username='" + playerName + "'"); // This loop checks all bans on record for the user to see if any tempbans are still active // Note tempbans are done in DAYS, the argument is a Double // For example 0.5 would be 0.5(1 day)=12hours // .1 -> 2.4 hours // 7 = 7 days, etc. while (SQL_RESULTSET.next()) { if(SQL_RESULTSET.getLong("expire") > System.currentTimeMillis()){ banner = SQL_RESULTSET.getString("jailer"); } } SQL_RESULTSET.close(); SQL_STATEMENT.close(); } catch(SQLException e){ e.printStackTrace(); } } return banner; }
4
@Override public void updateItem(Boolean item, boolean empty) { super.updateItem(item, empty); if(item!=null){ chkCell.setSelected(item); setGraphic(chkCell); chkCell.setOnKeyPressed( new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent t) { { if (t.getCode() == KeyCode.ENTER) { commitHelper(false); } else if (t.getCode() == KeyCode.ESCAPE) { cancelEdit(); } else if (t.getCode() == KeyCode.TAB) { commitHelper(false); TableColumn nextColumn = getNextColumn(!t.isShiftDown()); if (nextColumn != null) { getTableView().edit(getTableRow().getIndex(), nextColumn); } } } } } ); chkCell.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue && chkCell!= null) { commitHelper(true); } } }); // chkCell.focusedProperty().addListener(new ChangeListener<Boolean>() { // @Override // public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // //This focus listener fires at the end of cell editing when focus is lost // //and when enter is pressed (because that causes the text field to lose focus). // //The problem is that if enter is pressed then cancelEdit is called before this // //listener runs and therefore the text field has been cleaned up. If the // //text field is null we don't commit the edit. This has the useful side effect // //of stopping the double commit. // if (!newValue && chkCell!= null) { // commitEdit(chkCell.isSelected() ); // } // } // }); } else{ setGraphic(null); } }
8
public ModelAppResponse handleRequest(HTTPRequest request, BufferedReader is) { ModelUser user = authenticateUser(request); if (isExcludedSecurity(request)) { user = (user == null) ? ModelUser.annonymous() : user; } if (isLoginRequest(request)) { return routeLogin(request, user); } else if (user == null) { return redirectLogin(request); } else if (isParametrizedRequest(request)) { return routeParametrizedRequest(request, user); } else if (isStaticRequest(request)) { return routeStatic(request); } else if (isRESTRequest(request)) { return routeREST(request, user, is); } // else return ModelAppResponse.responseError(new WebServerBadRequestException("Unknown ")); }
7
public void cliqueFinRedeploiement() { if( joueurEnCours.getPeuple().getNbUniteEnMain() == 0 ){ if ((etape == 2 || etape == 3)) { if (Game.getInstance().askConf("Confirmer la fin du redéploiement ?")) { if (etape == 2) { if (tempEnDeclin) { joueurEnCours.getPeuple().decliner(); tempEnDeclin = false; } /* on passe à l'étape redéploiement des autres joueurs */ setEtape(3); /* et on indique que le joueur passe au tour suivant pour après ne pas le faire rejouer */ indexSauvJoueurEnCours = indexJoueurEnCours; indexJoueurEnCours = 0; } if (! deploiementSuivant()) { joueurSuivant(); } Game.getInstance().majInfos(); } } }else{ new WinWarn("Il vous reste des unités en main, placez-les !"); } }
7
@Override public void mouseClicked(MouseEvent e) { }
0
private String getExtension(String f) { // get extension of a file String ext = ""; int i = f.lastIndexOf('.'); if (i > 0 && i < f.length() - 1) { ext = f.substring(i + 1); } return ext; }
2
private boolean isInBounds(int var1, int var2, int var3) { return var1 >= 0 && var2 >= 0 && var3 >= 0 && var1 < this.width && var2 < this.depth && var3 < this.height; }
5
protected void pack(byte[] src, int[] dest, int destOffset) { assert destOffset + (src.length / 4) <= dest.length; int i = 0, shift = 24; int j = destOffset; dest[j] = 0; while (i < src.length) { dest[j] |= ((src[i] & 0xff) << shift); if (shift == 0) { shift = 24; j++; if (j < dest.length) { dest[j] = 0; } } else { shift -= 8; } i++; } }
3
public static Cons mostGeneralCollections(Cons descriptions) { if (descriptions.rest == null) { return (descriptions); } { Cons cursor1 = descriptions; Cons cursor2 = null; Stella_Object value1 = null; Stella_Object value2 = null; while (!(cursor1 == Stella.NIL)) { value1 = ((LogicObject)(cursor1.value)); if (value1 != null) { cursor2 = cursor1.rest; loop001 : while (!(cursor2 == Stella.NIL)) { value2 = cursor2.value; if (value2 != null) { if (LogicObject.collectionImpliesCollectionP(((LogicObject)(value2)), ((LogicObject)(value1)))) { cursor2.value = null; } else { if (LogicObject.collectionImpliesCollectionP(((LogicObject)(value1)), ((LogicObject)(value2)))) { cursor1.value = null; break loop001; } } } cursor2 = cursor2.rest; } } cursor1 = cursor1.rest; } } descriptions = descriptions.remove(null); return (descriptions); }
7
private Direction getDirection(){ List<Direction> directionList = new ArrayList<Direction>(); //Determine if //Calculate the distances from all possible directions for(int i = 0; i < Direction.Orientation.values().length; i++){ int[] relativeCoordinate = (Direction.Orientation.values()[i]).direction(); double distance = Math.sqrt(Math.pow((this.endCoord[0] - relativeCoordinate[0]), 2) + Math.pow((this.endCoord[1] - relativeCoordinate[1]), 2)); try{ directionList.add(new Direction( Direction.Orientation.values()[i], distance, relativeCoordinate )); } catch(Exception e){ System.out.println("A direction class could not be generated."); } } //Determine shortest route(s) double shortestDistance = directionList.get(0).distance; for(int i = 0; i < directionList.size(); i++){ if(directionList.get(i).distance < shortestDistance){ shortestDistance = directionList.get(i).distance; } } Iterator<Direction> iterator = directionList.iterator(); while(iterator.hasNext()){ if(iterator.next().distance != shortestDistance){ iterator.remove(); } } //Choose one of direction(s) Direction value = directionList.get(RandomGenerator.RandomInteger(0, directionList.size() - 1)); return value; }
6
public String getOpiskellutAsiat(){ String palautettava = ""; ArrayList<String> opiskellut = ajastimenTiedot.getOpiskellutAiheet(); for (String opiskeltu : opiskellut) { palautettava += opiskeltu + " "; } return palautettava.substring(0, palautettava.length()-1); //poistaa välilyönnin lopusta }
1
protected void renderContinuousSegment() { /* A lazy but effective line drawing algorithm */ final int dX = points[1].x - points[0].x; final int dY = points[1].y - points[0].y; int absdX = Math.abs(dX); int absdY = Math.abs(dY); if ((dX == 0) && (dY == 0)) return; if (absdY > absdX) { final int incfpX = (dX << 16) / absdY; final int incY = (dY > 0) ? 1 : -1; int fpX = points[0].x << 16; // X in fixedpoint format while (--absdY >= 0) { points[0].y += incY; points[0].x = (fpX += incfpX) >> 16; render(points[0]); } if (points[0].x == points[1].x) return; points[0].x = points[1].x; } else { final int incfpY = (dY << 16) / absdX; final int incX = (dX > 0) ? 1 : -1; int fpY = points[0].y << 16; // Y in fixedpoint format while (--absdX >= 0) { points[0].x += incX; points[0].y = (fpY += incfpY) >> 16; render(points[0]); } if (points[0].y == points[1].y) return; points[0].y = points[1].y; } render(points[0]); }
9
public void print(){ for (String index : cache.keySet()) { for(String tag : cache.get(index).records.keySet()){ for(String offset: cache.get(index).records.get(tag).words.keySet()){ System.out.print(" " + index + " " + tag + " " + offset + " " + cache.get(index).records.get(tag).words.get(offset)); } } System.out.println(" "); } }
3
public void createVehicles(int numVehicles){ ArrayList<Vehicle> v= Vehicle.getVehicleArray(); for(int k=0; k<numVehicles; k++){ double number= Math.random()*4; if(number>=0 && number<1) v.add(new Car(this)); if(number>=1 && number<2) v.add(new Ambulance(this)); if(number>=2 && number<3) v.add(new Bus(this)); if(number>=3 && number<=4) v.add(new Bicycle(this)); } }
9
public int getLineIdByNameAndPassword(String name, String password) { try { if(name.equals("D1") && password.equals("dev_password1")) return -11; else if(name.equals("D2") && password.equals("dev_password2")) return -12; Scanner scan = new Scanner(this); int num = -1; while(scan.hasNextLine()) { num++; String line = scan.nextLine(); if(line.startsWith(name)) { if(line.contains(password)) return num; else return -1; } } }catch(FileNotFoundException ex) { BaseUtils.warn(ex, true); } return -1; }
8
private synchronized void calcSimilarity(ArrayList<CompareResult> compareResults) { for (CompareResult result : compareResults) { if (_similarity < result.getSimilarity()) { _similarity = result.getSimilarity(); } } }
2
public void run() { try { log.debug(this.taskName + " : is started."); Thread.sleep(10000); log.debug(this.taskName + " : is completed."); } catch (InterruptedException e) { log.error(this.taskName + " : is not completed!"); e.printStackTrace(); } }
1
private static boolean isLanguageModelCreated(String grammar, boolean deleteOnExit){ boolean isLanguageModelCreated = false; // Ensure that the files were created successfully File lm = new File(grammar + ".lm"); File dmp = new File(grammar + ".DMP"); // Check if the files exists if(lm.exists() && lm.isFile() && dmp.exists() && dmp.isFile()){ // Delete files when the program exists if(deleteOnExit){ lm.deleteOnExit(); dmp.deleteOnExit(); } // The Language Model was created successfully isLanguageModelCreated = true; } return isLanguageModelCreated; }
5
public Controller(View _view, ActionDispatch a) { }
0
private PhongShader() { super(); addVertexShaderFromFile("phongVertex.vs"); addFragmentShaderFromFile("phongFragment.fs"); compileShader(); addUniform("transform"); addUniform("transformProjected"); addUniform("baseColor"); addUniform("ambientLight"); addUniform("specularIntensity"); addUniform("specularPower"); addUniform("eyePos"); addUniform("directionalLight.base.color"); addUniform("directionalLight.base.intensity"); addUniform("directionalLight.direction"); for(int i = 0; i < MAX_POINT_LIGHTS; i++) { addUniform("pointLights[" + i + "].base.color"); addUniform("pointLights[" + i + "].base.intensity"); addUniform("pointLights[" + i + "].atten.constant"); addUniform("pointLights[" + i + "].atten.linear"); addUniform("pointLights[" + i + "].atten.exponent"); addUniform("pointLights[" + i + "].position"); addUniform("pointLights[" + i + "].range"); } for(int i = 0; i < MAX_SPOT_LIGHTS; i++) { addUniform("spotLights[" + i + "].pointLight.base.color"); addUniform("spotLights[" + i + "].pointLight.base.intensity"); addUniform("spotLights[" + i + "].pointLight.atten.constant"); addUniform("spotLights[" + i + "].pointLight.atten.linear"); addUniform("spotLights[" + i + "].pointLight.atten.exponent"); addUniform("spotLights[" + i + "].pointLight.position"); addUniform("spotLights[" + i + "].pointLight.range"); addUniform("spotLights[" + i + "].direction"); addUniform("spotLights[" + i + "].cutoff"); } }
2
private void moveShuffled(){ shuffling = new HashMap<String, Multimap<String, Double>>(); HashMap<String, Multimap<String, Double>> lastCore = combinedShuffling.get(combinedShuffling.size()-1); for (String str : lastCore.keySet()){ Multimap<String, Double> mhsd = ArrayListMultimap.create(); for (String hs : lastCore.get(str).keySet()){ for (Double d : lastCore.get(str).get(hs)){ mhsd.put(hs, d); } } shuffling.put(str, mhsd); } for (int i=1; i<combinedShuffling.size(); i++){ HashMap<String, Multimap<String, Double>> thisCore = combinedShuffling.get(i); for (String s : thisCore.keySet()){ for (String hs : thisCore.get(s).keySet()){ for (Double d : thisCore.get(s).get(hs)){ shuffling.get(s).put(hs, d); } } } } }
7
protected void scaleNumericPredictions() { double maxErr; double minErr; double err; int i; Double errd; double temp; maxErr = Double.NEGATIVE_INFINITY; minErr = Double.POSITIVE_INFINITY; // find min/max errors for (i = 0; i < m_PlotSizes.size(); i++) { errd = (Double) m_PlotSizes.elementAt(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (err < minErr) minErr = err; if (err > maxErr) maxErr = err; } } // scale errors for (i = 0; i < m_PlotSizes.size(); i++) { errd = (Double) m_PlotSizes.elementAt(i); if (errd != null) { err = Math.abs(errd.doubleValue()); if (maxErr - minErr > 0) { temp = (((err - minErr) / (maxErr - minErr)) * (m_MaximumPlotSizeNumeric - m_MinimumPlotSizeNumeric + 1)); m_PlotSizes.setElementAt(new Integer((int) temp) + m_MinimumPlotSizeNumeric, i); } else { m_PlotSizes.setElementAt(new Integer(m_MinimumPlotSizeNumeric), i); } } else { m_PlotSizes.setElementAt(new Integer(m_MinimumPlotSizeNumeric), i); } } }
7
public static void main( String[] args ) { final RobotState rs = new RobotState(); final RayCaster rc = new RayCaster( 32, 32 ); for( int i=0; i<1024; ++i ) rc.walls[i] = true; Random r = new Random(); int tx = 16, ty = 16; for( int i=0; i<1024; ++i ) { rc.putWallAt( tx, ty, false ); //ty += 1; if( r.nextBoolean() ) { tx += (r.nextBoolean() ? 1 : -1); } else { ty += (r.nextBoolean() ? 1 : -1); } } rc.cast( rs.px, rs.py, 0, Math.PI*2/360, rs.distanceReadings ); /* for( int i=0; i<dist.length; ++i ) { dist[i] = Math.sqrt(dist[i]); //Math.sqrt(dist[i]); } */ final Frame window = new Frame("Robot Client"); final ZoomDrawCanvas zdCanvas = new ZoomDrawCanvas(); zdCanvas.setPreferredSize( new Dimension(512,384) ); zdCanvas.setBackground( Color.BLACK ); RadarDisplay rd = new RadarDisplay(); rd.points = rs.distanceReadings; zdCanvas.zds.add(rd); zdCanvas.zds.add(new CenterMarker()); zdCanvas.zoom = 64; zdCanvas.addKeyListener( new KeyListener() { @Override public void keyPressed( KeyEvent kevt ) { switch( kevt.getKeyCode() ) { case( KeyEvent.VK_UP ): rs.py -= 1; break; case( KeyEvent.VK_DOWN ): rs.py += 1; break; case( KeyEvent.VK_LEFT ): rs.px -= 1; break; case( KeyEvent.VK_RIGHT ): rs.px += 1; break; default: System.err.println(kevt.getKeyCode()); } rc.cast( rs.px, rs.py, 0, Math.PI*2/360, rs.distanceReadings ); zdCanvas.repaint(); } @Override public void keyReleased( KeyEvent kevt ) { } @Override public void keyTyped( KeyEvent kevt ) { } }); window.add(zdCanvas); window.pack(); window.addWindowListener( new WindowAdapter() { @Override public void windowClosing( WindowEvent e ) { window.dispose(); } }); window.setVisible(true); zdCanvas.requestFocus(); }
9
public static Parser rulesParserFromReader( BufferedReader src ) { try { StringBuffer result = new StringBuffer(); String line; Map prefixes = new Map(); // List preloadedRules = new ArrayList(); List preloadedRules = new List(); while ((line = src.readLine()) != null) { if (line.startsWith("#")) continue; // Skip comment lines line = line.trim(); if (line.startsWith("//")) continue; // Skip comment lines if (line.startsWith("@prefix")) { line = line.substring("@prefix".length()); String prefix = nextArg(line); String rest = nextAfterArg(line); if (prefix.endsWith(":")) prefix = prefix.substring(0, prefix.length() - 1); String url = extractURI(rest); prefixes.put(prefix, url); } else if (line.startsWith("@include")) { // Include referenced rule file, either URL or local special case line = line.substring("@include".length()); String url = extractURI(line); // Check for predefined cases // J2ME Version: removed // if (url.equalsIgnoreCase("rdfs")) { // preloadedRules.addAll( RDFSFBRuleReasoner.loadRules() ); // // } else if (url.equalsIgnoreCase("owl")) { // preloadedRules.addAll( OWLFBRuleReasoner.loadRules() ) ; // // } else if (url.equalsIgnoreCase("owlmicro")) { // preloadedRules.addAll( OWLMicroReasoner.loadRules() ) ; // // } else if (url.equalsIgnoreCase("owlmini")) { // preloadedRules.addAll( OWLMiniReasoner.loadRules() ) ; // // } else { // // Just try loading as a URL // preloadedRules.addAll( rulesFromURL(url) ); // } } else { result.append(line); if(line.length() != 0) result.append("\n"); } } // result is the whole read rule set Parser parser = new Parser(result.toString()); parser.registerPrefixMap(prefixes); parser.addRulesPreload(preloadedRules); return parser; } catch (IOException e) { throw new WrappedIOException( e ); } }
8
public void AddInputPacket(RouterPacket dPacket, int bufferNumber) { //put a packet in the chosen buffer inputBuffer[bufferNumber].add(dPacket); System.out.println("Time: "+GetTime()+" --> Delivered packet#: "+dPacket.GetSequenceNumber()+" to InputBuffer: "+bufferNumber+" PacketTIME: "+dPacket.GetTimeCreated()); }
0
public int getWidth() { return (this.getHeight() < 1) ? 0 : this.pic[0].length(); }
1
@Override public final Configuration get() { try { XmlConfigurationReader xmlConfigReader = new XmlConfigurationReader(componentName); return new MojoConfiguration(authorUrl, publishUrl, dispatcherUrl, xmlConfigReader); } catch (Exception e) { throw new ProvisionException("Impossible to provide configuration for component " + componentName, e); } }
1
public static void helpInsertACsValue(KvCons kvcons, Stella_Object newvalue, Context target, boolean overwriteP) { { int contextnumber = target.contextNumber; for (;;) { if ((!Stella.$CONTEXT_BACKTRACKING_MODE$) && (Stella.$UNLINK_DISCARDED_CONTEXTS_ON_WRITEp$ && (((((Context)(kvcons.key)).contextNumber) % 2) == 1))) { if (kvcons.rest != null) { { KvCons nextkvcons = kvcons.rest; kvcons.key = nextkvcons.key; kvcons.value = nextkvcons.value; kvcons.rest = nextkvcons.rest; nextkvcons.free(); } } else { { kvcons.key = target; kvcons.value = newvalue; return; } } } if (kvcons.key == target) { if (overwriteP) { kvcons.value = newvalue; } return; } else if (((Context)(kvcons.key)).contextNumber < contextnumber) { kvcons.rest = KvCons.kvCons(kvcons.key, kvcons.value, kvcons.rest); kvcons.key = target; kvcons.value = newvalue; return; } else if (kvcons.rest == null) { kvcons.rest = KvCons.kvCons(target, newvalue, null); return; } else { kvcons = kvcons.rest; } } } }
9
@Override public void update(int mouseX, int mouseY, boolean pressed) { super.update(mouseX, mouseY, pressed); if(this.btnBack.wasClicked()) Game.instance.setCurrentGui(this.parent); if(this.btnNext.wasClicked() && this.page < 2) this.page++; if(this.btnPrev.wasClicked() && this.page > 0) this.page--; }
5
private static Node deleteNode(Node h, int value){ if(h==null) return null; if(h.v==value) return h.next; Node curr = h.next; Node prev = h; while(curr!=null){ if(curr.v == value){ prev.next = curr.next; break; } prev = curr; curr = curr.next; } return h; }
4
public static boolean arrayEqual(char[] a, char[] b, int aStart, int bStart, int length) { for(int i=0;i<length;i++) { if(a[aStart+i] != b[bStart+i]) { return false; } } return true; }
2
int getB(String s1, String s2) { int b = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) { // this situation has handled by getA. continue; } if (s1.charAt(i) == s2.charAt(j)) { // if their digit matched, but their position must be different. b++; } } } return b; }
4
public static void processTriple(String subject, String verb, String object, String inputDir, String outDir){ //expansion ArrayList<String> subject_words = expanded_object_list.get(subject); ArrayList<String> verb_words = expanded_verb_list.get(verb); ArrayList<String> object_words = expanded_object_list.get(object); try{ File output_file_subject_verb = new File(outDir+"/subject_verb.txt"); FileWriter fstream_subject_verb = new FileWriter(output_file_subject_verb); BufferedWriter out_subject_verb = new BufferedWriter(fstream_subject_verb); File output_file_object_verb = new File(outDir+"/object_verb.txt"); FileWriter fstream_object_verb = new FileWriter(output_file_object_verb); BufferedWriter out_object_verb = new BufferedWriter(fstream_object_verb); File output_file_verb_subject = new File(outDir+"/verb_subject.txt"); FileWriter fstream_verb_subject = new FileWriter(output_file_verb_subject); BufferedWriter out_verb_subject = new BufferedWriter(fstream_verb_subject); File output_file_verb_object = new File(outDir+"/verb_object.txt"); FileWriter fstream_verb_object = new FileWriter(output_file_verb_object); BufferedWriter out_verb_object = new BufferedWriter(fstream_verb_object); File dir = new File(inputDir); File[] files = dir.listFiles(); for (int i = 0 ; i<files.length;i++){ System.out.println("file name" + files[i].getName()); FileInputStream fis = new FileInputStream(files[i]); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); while (dis.available() != 0) { String line = dis.readLine(); //System.out.println("line" + line); String pattern = "[\\s]+"; Pattern splitter = Pattern.compile(pattern); String[] words = splitter.split(line); String first = words[0]; String second = words[1]; String last = words[words.length-2]; //System.out.println(" first " + first + " last "+ last); if ((subject_words.contains(first) || subject_words.contains(second)) && verb_words.contains(last)){ subject_verb.add(line); out_subject_verb.write(line+"\n"); } /* if ((object_words.contains(first) || object_words.contains(second)) && verb_words.contains(last)){ object_verb.add(line); out_object_verb.write(line+"\n"); } if (verb_words.contains(first) && subject_words.contains(last)){ ArrayList<String> value = verb_subject.get(first); if (value == null) value = new ArrayList<String>(); value.add(line); verb_subject.put(first, value); out_verb_subject.write(line+"\n"); }*/ if (verb_words.contains(first) && object_words.contains(last)){ ArrayList<String> value = verb_object.get(first); if (value == null) value = new ArrayList<String>(); value.add(line); verb_object.put(first, value); out_verb_object.write(line+"\n"); } } } out_subject_verb.close(); out_object_verb.close(); out_verb_subject.close(); out_verb_object.close(); }catch(Exception e){System.out.println("exception" +e);} }
9
public void loadRepositoryFromGraphXML(String graphXML) { try { String result=graphXML.replaceAll("&#x","---"); Document document = builder.parse(new InputSource(new StringReader(result))); // SBModel is sign of SystemBiology XML document, which equals to GraphData of PathCase. NodeList graphroots = document.getElementsByTagName("SBModel"); Node graphroot = graphroots.item(0); NodeList graphElements = graphroot.getChildNodes(); for (int i = 0; i < graphElements.getLength(); i++) { Node graphElement = graphElements.item(i); // GraphData/Molecules if (graphElement.getNodeName().equals("Model")) { loadModelFromXMLNode(graphElement); } // GraphData/GenericProcesses else if (graphElement.getNodeName().equals("Compartments")) { loadCompartmentFromXMLNode(graphElement); } // // GraphData/Pathways else if (graphElement.getNodeName().equals("Reactions")) { loadReactionsFromXMLNode(graphElement); } else if (graphElement.getNodeName().equals("Pathways")) { loadMappingPWsFromXMLNode(graphElement); } } } catch (SAXException sxe) { // Error generated during parsing Exception x = sxe; if (sxe.getException() != null) x = sxe.getException(); //x.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } }
8
public File getCsvData() { List<DataLead> leads = selectAll(); if(leads == null) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Can't get data. "); return null; } File tmp = createCsvFile(); if(tmp == null) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Can't create tmp file. "); return null; } try { /** * Create an output stream with UTF-8 encoding. */ FileOutputStream fos = new FileOutputStream(tmp); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); /** * Write file line by line. */ for (DataLead l : leads) { for (int i = 0; i < l.size(); ++i) { /** * If the value is null, use 'wu' instead. */ String t = l.get(i); if(t == null) { t = "无"; } osw.write(t); if (i < l.size() - 1) { osw.write(","); } } /** * Windows line delimiter. */ osw.write("\r\n"); } osw.flush(); osw.close(); return tmp; } catch (FileNotFoundException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. File ont found. " + e.getMessage()); return null; } catch (UnsupportedEncodingException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. Unsupported encoding." + e.getMessage()); return null; } catch (IOException e) { this.errorLogFile.log(LoggingProxy.ERROR, "[---]CsvProxy error. IO exception." + e.getMessage()); return null; } }
9
public String openMana(Player player) { // Currently only considers basic lands. String mana = ""; for (Card perm : this.permanents) { if (perm.getTypes().contains("Land") && perm.getController().equals(player) && !perm.isTapped()) { String cardName = perm.getName(); switch (cardName) { case "Forest": mana += "G"; break; case "Mountain": mana += "R"; break; case "Plains": mana += "W"; break; case "Swamp": mana += "B"; break; case "Island": mana += "U"; break; default: break; } } } return mana; }
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,mob,auto),auto?"":L("^S<S-NAME> incant(s), feeling <S-HIS-HER> body split in two.^?")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); final MOB myMonster = determineMonster(mob); Behavior B=CMClass.getBehavior("CombatAbilities"); myMonster.addBehavior(B); B.startBehavior(myMonster); if(CMLib.dice().rollPercentage()<50) { if(CMLib.flags().isGood(mob)) { B=CMClass.getBehavior("MobileGoodGuardian"); myMonster.addBehavior(B); B.startBehavior(myMonster); myMonster.copyFactions(mob); } else if(CMLib.flags().isEvil(mob)) { B=CMClass.getBehavior("MobileAggressive"); myMonster.addBehavior(B); B.startBehavior(myMonster); myMonster.copyFactions(mob); } else { B=CMClass.getBehavior("Mobile"); myMonster.addBehavior(B); B.startBehavior(myMonster); B=CMClass.getBehavior("Guard"); myMonster.addBehavior(B); B.startBehavior(myMonster); myMonster.copyFactions(mob); } myMonster.setVictim(mob); } else { B=CMClass.getBehavior("Mobile"); myMonster.addBehavior(B); B.startBehavior(myMonster); myMonster.setVictim(mob.getVictim()); CMLib.commands().postFollow(myMonster,mob,true); if(myMonster.amFollowing()!=mob) mob.tell(L("@x1 seems unwilling to follow you.",myMonster.name())); } invoker=mob; beneficialAffect(mob,myMonster,asLevel,0); } } else return beneficialWordsFizzle(mob,null,L("<S-NAME> attempt(s) to clone <S-HIM-HERSELF>, but fails.")); // return whether it worked return success; }
8
public synchronized void adicionar() { try { new PesquisaView(this); } catch (Exception e) { } }
1
public static String nullSafeClassName(Object obj) { return (obj != null ? obj.getClass().getName() : NULL_STRING); }
1
@Override public Set<String> keySet() { return new Set<String>() { @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean contains( Object o ) { return get( (String) o ) != null; } @Override public Iterator<String> iterator() { return new Iterator<String>() { private final Iterator<WrappedString> topLevelIterator = store.keySet().iterator(); private Iterator<String> currentIterator = topLevelIterator.hasNext()? store.get( topLevelIterator.next()).getValue().keySet().iterator() : null; @Override public void remove() { throw new UnsupportedOperationException("Read only data set"); } @Override public boolean hasNext() { return currentIterator != null; } @Override public String next() { String toReturn; toReturn = currentIterator.next(); if ( currentIterator.hasNext() ) { return toReturn; } while ( topLevelIterator.hasNext() && !( currentIterator = store.get( topLevelIterator.next() ).getValue().keySet().iterator() ).hasNext() ); if ( !currentIterator.hasNext() ) { currentIterator = null; } return toReturn; } }; } @Override public Object[] toArray() { throw new UnsupportedOperationException( "Not yet" ); } @Override public <T> T[] toArray( T[] a ) { throw new UnsupportedOperationException( "Not yet" ); } @Override public boolean add( String e ) { throw new UnsupportedOperationException("Read only data set"); } @Override public boolean remove( Object o ) { throw new UnsupportedOperationException("Read only data set"); } @Override public boolean containsAll( Collection<?> c ) { throw new UnsupportedOperationException( "Not yet" ); } @Override public boolean addAll( Collection<? extends String> c ) { throw new UnsupportedOperationException("Read only data set"); } @Override public boolean retainAll( Collection<?> c ) { throw new UnsupportedOperationException("Read only data set"); } @Override public boolean removeAll( Collection<?> c ) { throw new UnsupportedOperationException("Read only data set"); } @Override public void clear() { throw new UnsupportedOperationException("Read only data set"); } }; }
9
private static void wordquiz() { for (int i = 0; i < 40; ++i) System.out.println(); int max = database.size() - 1; success = new SList(); failure = new SList(); total = new SList(); String guess; sc = new Scanner(System.in); System.out.println("Random word's deffinition is displayed below. You have to guess the word."); if(max > 0){ while(true){ int randomInt = randomGenerator.nextInt(max); String takeWord = database.getWord(randomInt); System.out.println(); System.out.println(database.getDeffinition(takeWord)); //System.out.println(takeWord); total.insertFront(takeWord); System.out.print("Enter your guess: "); guess = sc.nextLine(); guess = guess.toLowerCase(); if(guess.equals(takeWord.toLowerCase())){ System.out.println("Congratulations! Your guess is correct!"); success.insertFront(takeWord); } else { System.out.println("You failed :("); failure.insertFront(takeWord); } System.out.println(); System.out.print("Do you want to continue? y or n: "); String answer = sc.nextLine(); if(answer.equals("n"))break; } } else { System.out.println("Error! Dictionary is not loaded or created!"); } System.out.println("Your result is:"); int t = total.length(); int s = success.length(); int f = failure.length(); System.out.println("Total words played: " + t); System.out.println("Guessed correctly: " + s); System.out.println("Failed: " + f); }
5
public void setjTextFieldPrenom(JTextField jTextFieldPrenom) { this.jTextFieldPrenom = jTextFieldPrenom; }
0
public boolean replace(String key, int ttlSec, Object value, long timeoutMiliSec) throws TimeoutException { try { StringBuilder sb = new StringBuilder(); byte valueBytes[] = null; int flag = -1; if (value instanceof String) { String arg = (String) value; valueBytes = arg.getBytes(charset); flag = FLAGS_GENRIC_STRING; } else { valueBytes = getObjectBytes(value); flag = FLAGS_GENRIC_OBJECT; } validateKey(key); validateValue(key, valueBytes); //<command name> <key> <flags> <exptime> <bytes> [noreply]\r\n sb.append("replace ").append(key).append(" ").append(flag); sb.append(" ").append(ttlSec).append(" ").append(valueBytes.length); sb.append("\r\n"); sb.append(new String(valueBytes, charset)); sb.append("\r\n"); String res = sendDataOut(key, sb.toString()); if (res == null) { throw new TimeoutException("we got a null reply!"); } if (res.equals("STORED") == false) { return false; } else { return true; } } catch (TimeoutException ex) { throw ex; } catch (Exception ex) { throw new TimeoutException("We had error " + ex); } }
5
@Override public void actionPerformed(ActionEvent e) { if(e.getSource()==logOut){ frameRef.setContentPane(new Login(frameRef)); } if(e.getSource()==addBook){ contentPanelLayout.show(panel, "ADD_BOOK"); } if(e.getSource()==addItem){ contentPanelLayout.show(panel, "ADD_ITEM"); } if(e.getSource() == manageItems){ contentPanelLayout.show(panel, "MANAGE_ITEMS"); } if(e.getSource() == manageBooks){ contentPanelLayout.show(panel, "MANAGE_BOOKS"); } if(e.getSource() == checkOutItem){ contentPanelLayout.show(panel, "ITEM_CHECKOUT"); } if(e.getSource() == checkOutBook){ contentPanelLayout.show(panel, "BOOK_CHECKOUT"); } if(e.getSource() == returnItem){ contentPanelLayout.show(panel, "ITEM_RETURN"); } if(e.getSource() == returnBook){ contentPanelLayout.show(panel, "BOOK_RETURN"); } }
9
@XmlElementDecl(namespace = "urn:ietf:params:xml:ns:keyprov:pskc", name = "KeyContainer") public JAXBElement<KeyContainerType> createKeyContainer(KeyContainerType value) { return new JAXBElement<KeyContainerType>(_KeyContainer_QNAME, KeyContainerType.class, null, value); }
0
public void run(){ System.out.println("in run method "); synchronized(this){ try { for(int i = 0; i < 100; i++){ total += i; System.out.println("total: "+total); wait(100); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notify(); }
2
public int getIndexFrom(){ int numOfOptions=_map.mygraph.getCurr(); if(numOfOptions==0){ JOptionPane.showMessageDialog(null,"There isn't any location on the map!","Directions",JOptionPane.ERROR_MESSAGE,null); return -1; } String[] options=new String[numOfOptions]; for(int i=0;i<numOfOptions;i++){ options[i]=i+": ID:"+_map.mygraph.locations[i].getID()+" Name:"+_map.mygraph.locations[i].getName(); } String s=(String)JOptionPane.showInputDialog(null,"Choose a location to start from:", "Choose the start point", JOptionPane.PLAIN_MESSAGE,null,options,options[0]); if(s==null){ return -1; } int index=0; for(int i=0;s.charAt(i)!=':';i++){ index=10*index+(s.charAt(i)-'0'); } return index; }
4
public String format(Alignment alignment) { char[] sequence1 = alignment.getSequence1(); char[] sequence2 = alignment.getSequence2(); char[] markup = alignment.getMarkupLine(); int length = sequence1.length > sequence2.length ? sequence2.length : sequence1.length; String name1 = adjustName(alignment.getName1()); String name2 = adjustName(alignment.getName2()); StringBuffer buffer = new StringBuffer ( ); StringBuffer preMarkup = new StringBuffer ( ); for (int j = 0; j < NAME_WIDTH + 1 + POSITION_WIDTH + 1; j++) { preMarkup.append(BLANK); } int oldPosition1, position1 = 1 + alignment.getStart1(); int oldPosition2, position2 = 1 + alignment.getStart2(); char[] subsequence1; char[] subsequence2; char[] submarkup; int line; char c1, c2; for (int i = 0; i * SEQUENCE_WIDTH < length; i++) { oldPosition1 = position1; oldPosition2 = position2; line = ((i + 1) * SEQUENCE_WIDTH) < length ? (i + 1) * SEQUENCE_WIDTH: length; subsequence1 = new char[line - i * SEQUENCE_WIDTH]; subsequence2 = new char[line - i * SEQUENCE_WIDTH]; submarkup = new char[line - i * SEQUENCE_WIDTH]; for (int j = i * SEQUENCE_WIDTH, k = 0; j < line; j++, k++) { subsequence1[k] = sequence1[j]; subsequence2[k] = sequence2[j]; submarkup[k] = markup[j]; c1 = subsequence1[k]; c2 = subsequence2[k]; if (c1 == c2) { position1++; position2++; } else if (c1 == Alignment.GAP) { position2++; } else if (c2 == Alignment.GAP) { position1++; } else { position1++; position2++; } } buffer.append(name1); buffer.append(BLANK); buffer.append(adjustPosition(new Integer(oldPosition1).toString())); buffer.append(BLANK); buffer.append(subsequence1); buffer.append(BLANK); buffer.append(adjustPosition(new Integer(position1 - 1).toString())); buffer.append(Commons.getLineSeparator()); buffer.append(preMarkup); buffer.append(submarkup); buffer.append(Commons.getLineSeparator()); buffer.append(name2); buffer.append(BLANK); buffer.append(adjustPosition(new Integer(oldPosition2).toString())); buffer.append(BLANK); buffer.append(subsequence2); buffer.append(BLANK); buffer.append(adjustPosition(new Integer(position2 - 1).toString())); buffer.append(Commons.getLineSeparator()); buffer.append(Commons.getLineSeparator()); } return buffer.toString(); }
8
public ShapeModels(String path) throws BadModelFormatException{ models = new HashSet<ShapeModel>(); Integer length = 0; Integer height = 0; Integer lineNumber = 0; Integer modelScore = 0; Set<Position> model = null; List<String> lines = null; try { lines = Files.readAllLines(Paths.get(path)); } catch (IOException e) { e.printStackTrace(); } for (String line : lines) { lineNumber++; if (isNumeric(line)) { if (model != null) { models.add(new ShapeModel(length, height, modelScore, model)); model = new HashSet<Position>(); length = 0; height = 0; } else model = new HashSet<Position>(); modelScore = Integer.parseInt(line); } else{ for (Integer i = 0; i < line.length(); i++) { if (line.charAt(i) == MODEL_TOKEN || line.charAt(i) == ' ') { if (line.charAt(i) == MODEL_TOKEN) { model.add(new Position(i, height)); } } else throw new BadModelFormatException(lineNumber, line, i); } length = Math.max(length, line.length()); height++; } } if (model != null) { models.add(new ShapeModel(length, height, modelScore, model)); model = new HashSet<Position>(); length = 0; height = 0; } }
9
@Override public String[] getClientAliases(String keyType, Principal[] issuers) { if (CacHookingAgent.DEBUG) { System.out.println("getClientAliases: "); } try { KeyStore ks = getKeyStore(); if (ks == null) { return new String[0]; } ArrayList<String> asList = new ArrayList<String>(); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { // TODO filter by keyType/issuers? asList.add(aliases.nextElement()); } return asList.toArray(new String[asList.size()]); } catch (KeyStoreException e) { throw reportAndConvert(e); } }
4
public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } PriorityQueue<ListNode> priorityQueue = new PriorityQueue<ListNode>(new Comparator<ListNode>() { @Override public int compare(ListNode o1, ListNode o2) { return o1.val - o2.val; } }); // start with a dummy node ListNode resultHead = new ListNode(0); ListNode resultIter = resultHead; /** * Insert the head nodes. This is the first level of prioritization / sorting. */ for (ListNode list : lists) { if (null != list) { priorityQueue.offer(list); } } /** * This is the second level of insertion. Pull each member of each list and put in the * priority queue. */ while (!priorityQueue.isEmpty()) { ListNode temp = priorityQueue.poll(); resultIter.next = temp; resultIter = resultIter.next; if (null != temp.next) { priorityQueue.offer(temp.next); } } return resultHead.next; }
6
@EventHandler public void IronGolemFastDigging(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.FastDigging.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getIronGolemConfig().getBoolean("IronGolem.FastDigging.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, plugin.getIronGolemConfig().getInt("IronGolem.FastDigging.Time"), plugin.getIronGolemConfig().getInt("IronGolem.FastDigging.Power"))); } }
6
public static void main(String[] args) { int[] tipsArr = new int[] { 1, 10, 1, 5, 5, 10, 10, 5, 10, 5 }; Random random = new Random(); for (int i = 1; i < tipsArr.length; i++) { int j = random.nextInt(i); int temp = tipsArr[i]; tipsArr[i] = tipsArr[j]; tipsArr[j] = temp; } for (int i = 0; i < tipsArr.length; i++) { System.out.print("\t "+tipsArr[i]); } int l = 0; int r = tipsArr.length-1; int b = 0; int a = 0; System.out.println("\nShare distribution"); while(l < r){ if(tipsArr[r-1] >= tipsArr[l+1]){ if((tipsArr[r] - tipsArr[l]) >= (tipsArr[r-1] - tipsArr[l+1]) ){ a += tipsArr[r]; System.out.println("Alice took share from right at the index: "+(r--)); }else{ a += tipsArr[l]; System.out.println("Alice took share from left at the index: "+(l++)); } }else{ if((tipsArr[r] - tipsArr[l]) <= (tipsArr[r-1] - tipsArr[l+1]) ){ a += tipsArr[r]; System.out.println("Alice took share from right at the index: "+(r--)); }else{ a += tipsArr[l]; System.out.println("Alice took share from left at the index: "+(l++)); } } if(tipsArr[r] >= tipsArr[l]){ b += tipsArr[r]; System.out.println("Bob took share from right at the index: "+(r--)); }else{ b += tipsArr[l]; System.out.println("Bob took share from left at the index: "+(l++)); } } System.out.println("\n Alice share: "+a); System.out.println("\n Bob share: "+b); }
7
boolean checkPassword(String password, String confirmPassword) { if(password.length() < 8 || password.length() > 16) { JOptionPane.showMessageDialog(null, "Password must be between 8 to 16 characters long", "Error", JOptionPane.ERROR_MESSAGE); return false; } if(!password.equals(confirmPassword)) { JOptionPane.showMessageDialog(null, "Passwords do not match", "Error", JOptionPane.ERROR_MESSAGE); return false; } return true; }
3
static void printAngle(double theta, PrintStream ps, String posPrefix, String negPrefix) { int pd, pm; double phi = RtoD(Math.abs(theta)); pd = (int) phi; phi = 60.0 * (phi - pd); pm = (int) phi; phi = 60.0 * (phi - pm); if (theta < 0.0) { ps.print((negPrefix == null) ? "-" : negPrefix); } else { ps.print((posPrefix == null) ? "+" : posPrefix); } ps.print(pd + "\u00b0 " + pm + "\' " + angleFormat.format(phi) + "\""); }
3
public void sendDebugFile(final String errorid) throws IOException { this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, new Runnable() { @SuppressWarnings("resource") @Override public void run() { try { URL url = new URL("http://report.ibhh.de/logs/send.php?plugin=" + FileSend.this.plugin.getName() + "&ID=" + errorid); Date now = new Date(); String path = FileSend.this.plugin.getDataFolder().toString() + File.separator + "debugfiles" + File.separator; SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd 'at' HH"); File file = new File(path + "debug-" + ft.format(now) + ".txt"); if (file.exists()) { // Construct data String data = URLEncoder.encode("file", "UTF-8") + "="; BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); try { String line = null; while ((line = reader.readLine()) != null) { data += URLEncoder.encode(line, "UTF-8") + "\n"; } } catch (Exception e) { } // Send data URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.contains("Successfully")) { System.out.println(line); } } wr.close(); rd.close(); } } catch (Exception e) { plugin.getLoggerUtility().log("cannot send debugfile because the linking of some resources failed.", LoggerUtility.Level.ERROR); plugin.getLoggerUtility().log("May you used /reload and therefore it doesnt work.", LoggerUtility.Level.ERROR); } } }); }
6
protected void ushortLoop(RasterAccessor src, RasterAccessor dst, int filterSize) { int dwidth = dst.getWidth(); int dheight = dst.getHeight(); int dnumBands = dst.getNumBands(); short dstDataArrays[][] = dst.getShortDataArrays(); int dstBandOffsets[] = dst.getBandOffsets(); int dstPixelStride = dst.getPixelStride(); int dstScanlineStride = dst.getScanlineStride(); short srcDataArrays[][] = src.getShortDataArrays(); int srcBandOffsets[] = src.getBandOffsets(); int srcPixelStride = src.getPixelStride(); int srcScanlineStride = src.getScanlineStride(); int medianValues[] = new int[filterSize]; int tmpValues[] = new int[filterSize]; int wp = filterSize; int tmpBuffer[] = new int[filterSize*dwidth]; int tmpBufferSize = filterSize*dwidth; for (int k = 0; k < dnumBands; k++) { short dstData[] = dstDataArrays[k]; short srcData[] = srcDataArrays[k]; int srcScanlineOffset = srcBandOffsets[k]; int dstScanlineOffset = dstBandOffsets[k]; int revolver = 0; for (int j = 0; j < filterSize-1; j++) { int srcPixelOffset = srcScanlineOffset; for (int i = 0; i < dwidth; i++) { int imageOffset = srcPixelOffset; for (int v = 0; v < wp; v++) { tmpValues[v] = srcData[imageOffset] & 0xfff; imageOffset += srcPixelStride; } tmpBuffer[revolver+i] = medianFilter(tmpValues); srcPixelOffset += srcPixelStride; } revolver += dwidth; srcScanlineOffset += srcScanlineStride; } // srcScanlineStride already bumped by // filterSize-1*scanlineStride for (int j = 0; j < dheight; j++) { int srcPixelOffset = srcScanlineOffset; int dstPixelOffset = dstScanlineOffset; for (int i = 0; i < dwidth; i++) { int imageOffset = srcPixelOffset; for (int v = 0; v < wp; v++) { tmpValues[v] = srcData[imageOffset] & 0xffff; imageOffset += srcPixelStride; } tmpBuffer[revolver + i] = medianFilter(tmpValues); int a = 0; for (int b = i; b < tmpBufferSize; b += dwidth) { medianValues[a++] = tmpBuffer[b]; } int val = medianFilter(medianValues); dstData[dstPixelOffset] = (short)val; srcPixelOffset += srcPixelStride; dstPixelOffset += dstPixelStride; } revolver += dwidth; if (revolver == tmpBufferSize) { revolver = 0; } srcScanlineOffset += srcScanlineStride; dstScanlineOffset += dstScanlineStride; } } }
9
@Override public void paint(Graphics g) { super.paint(g); map.paint(g, this); for (Tower tower : towerList) { tower.paintBase(g, this); } enemyHandler.paint(g, this); for (Tower tower : towerList) { tower.paintProjectiles(g, this); } for (Tower tower : towerList) { tower.paintTurret(g, this); } Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); //g2d.drawString(mouseCoords.x + " " + mouseCoords.y + " " + mode, 0, 15); if (!gameOver) { paintCursor(g); } else { paintGameOverScreen(g); } Toolkit.getDefaultToolkit().sync(); g.dispose(); }
4
public void train(String listofFiles,String output) { CountsCollection bag1=new CountsCollection(); HashSet<String> IdsVisible=new HashSet<String>(); loadList(listofFiles,DataHalf.ODD,Visibility.VISIBLE,bag1,IdsVisible); loadList(listofFiles,DataHalf.EVEN,Visibility.BLIND,bag1,IdsVisible); // Do some sort of reset or model keeping IdsVisible.clear(); loadList(listofFiles,DataHalf.EVEN,Visibility.VISIBLE,bag1,IdsVisible); loadList(listofFiles,DataHalf.ODD,Visibility.BLIND,bag1,IdsVisible); bag1.prepareWeightsForBackoff(); System.out.println("BAG1::"); bag1.printBag(); // Dump the bags try { FileOutputStream fos = new FileOutputStream(output); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(bag1); oos.close(); } catch (Exception ex) { System.err.println("Dumping problems"); } CountsCollection bag3=new CountsCollection(); try { FileInputStream fis = new FileInputStream(output); ObjectInputStream ois = new ObjectInputStream(fis); bag3=(CountsCollection) ois.readObject(); ois.close(); } catch (Exception ex) { System.err.println("Loading problems"); } }
2
public void run() { long lastTime = System.nanoTime(); long timer = System.currentTimeMillis(); double ns = 1000000000.0 / 60.0; double unprocessed = 0; int ticks = 0; int frames = 0; requestFocus(); while (running) { long now = System.nanoTime(); unprocessed += (now - lastTime) / ns; lastTime = now; while (unprocessed >= 1) { tick(); ticks++; unprocessed--; } { render(); frames++; } if (System.currentTimeMillis() - timer > 1000) { timer += 1000; FPS.ticks = ticks; FPS.frames = frames; ticks = 0; frames = 0; } } screen.renderArea(0x00A9FF, 0, screen.w, 0, screen.h, false); screen.renderText("Exiting Game!", 50, (HEIGHT - 8) / 2, 0, false); screen.copy(pixels); getGraphics().drawImage(img, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); }
4
private void pullData() { File tmp = new File(backup); tmp.mkdirs(); tmp.delete(); info("Your device will ask you for permission to backup files. Do NOT enter a password, just accept."); String messages = ""; try { Process p = Runtime.getRuntime().exec(new String[] {"adb", "backup", "-f", tmp.getPath(), "-noapk", "-noshared", "-nosystem", app}); messages = Util.streamToString(p.getErrorStream()) + " " + Util.streamToString(p.getInputStream()); p.waitFor(); } catch(Exception e) { messages += " " + e.getMessage(); } if(!tmp.exists() || tmp.length() <= 0) { error("Something went wrong, we didn't get the backup: " + messages); return; } else { info("Successfully downloaded a backup."); } }
3
public boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]|\\."); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; }
1
@Override public void addChoices(Player player, List<Choice> choices) { super.addChoices(player, choices); if (player.isNextTo(ConnectionType.boat)) { if (player.lastChoice() != null && (player.lastChoice().equals(doNothing) || (player.lastChoice().equals(this) && player.getAt().getType().equals(MarkType.boat)))) { isFree = true; } else { isFree = false; } if (isFree || player.hasAtLeast(COST)) choices.add(this); } }
7
public void update(float delta, Level level) { move(delta, level, false); if (collision(level)) { level.entities.remove(this); } for (int i = 0; i < level.entities.size(); i++) { if (level.entities.get(i) instanceof Player && collision(level.entities.get(i))) { level.resetLevel(); Sound.DEATH.play(); if (level.currentLevel > 5) { level.score--; if (level.currentLevel == 10) level.score--; level.lives--; } break; } else if (level.entities.get(i) instanceof Turret && collision(level.entities.get(i)) && !level.entities.get(i).equals(host)) { level.entities.remove(i); level.entities.remove(this); break; } } }
9
public void act(XmlAction pAction) { if (pAction instanceof ChangeRootNodeAction) { ChangeRootNodeAction rootNodeAction = (ChangeRootNodeAction) pAction; NodeAdapter focussed = controller.getNodeFromID(rootNodeAction .getNode()); if (focussed.isRoot()) { // node is already root. Everything ok. return; } /* * moving the hooks: 1. new interface method: movehook 2. change * root node from old to new node copying text, decoration, etc. * 3. deactivate all root hooks. this is possibly the best * solution as it is consequent. Method 3 is chosen. */ MindMapNode oldRoot = mMap.getRootNode(); oldRoot.removeAllHooks(); // change the root node: mMap.changeRoot(focussed); // remove all viewers: Vector nodes = new Vector(); nodes.add(focussed); while (!nodes.isEmpty()) { MindMapNode child = (MindMapNode) nodes.firstElement(); logger.fine("Removing viewers for " + child); nodes.remove(0); nodes.addAll(child.getChildren()); Collection viewers = new Vector(child.getViewers()); for (Iterator it = viewers.iterator(); it.hasNext(); ) { NodeView viewer = (NodeView) it.next(); child.removeViewer(viewer); } } MapView mapView = controller.getView(); for (int i = mapView.getComponentCount() - 1; i >= 0; i--) { Component comp = mapView.getComponent(i); if (comp instanceof NodeView || comp instanceof NodeMotionListenerView) { mapView.remove(comp); } } mapView.initRoot(); mapView.add(mapView.getRoot()); mapView.doLayout(); controller.nodeChanged(focussed); logger.fine("layout done."); controller.select(focussed, Tools.getVectorWithSingleElement(focussed)); controller.centerNode(focussed); controller.obtainFocusForSelected(); } }
7
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ( "tag".equals(qName) ) { String name = attributes.getValue("name"); String content = attributes.getValue("content"); String section = attributes.getValue("section"); String deprecated = attributes.getValue("deprecated"); String unique = attributes.getValue("unique"); String ignorePermitted = attributes.getValue("ignore-permitted"); ContentType contentType = ContentType.toValue(content); BelongsTo belongsTo = BelongsTo.toValue(section); tagInfo = new TagInfo(name, contentType, belongsTo, deprecated != null && "true".equals(deprecated), unique != null && "true".equals(unique), ignorePermitted != null && "true".equals(ignorePermitted), CloseTag.required, Display.any ); if (generateCode) { String s = "tagInfo = new TagInfo(\"#1\", #2, #3, #4, #5, #6);"; s = s.replaceAll("#1", name); s = s.replaceAll("#2", ContentType.class.getCanonicalName()+"."+contentType.name()); s = s.replaceAll("#3", BelongsTo.class.getCanonicalName()+"."+belongsTo.name()); s = s.replaceAll("#4", Boolean.toString(deprecated != null && "true".equals(deprecated))); s = s.replaceAll("#5", Boolean.toString(unique != null && "true".equals(unique))); s = s.replaceAll("#6", Boolean.toString(ignorePermitted != null && "true".equals(ignorePermitted))); System.out.println(s); } } else if ( !"tags".equals(qName) ) { dependencyName = qName; } }
9
public String getColor() { return color; }
0