text
stringlengths
14
410k
label
int32
0
9
private void handle(Resource res) { InputStream in = null; try { res.error = null; res.source = src; try { try { in = src.get(res.name); res.load(in); res.loading = false; res.notifyAll(); return; } catch (IOException e) { throw (new LoadException(e, res)); } } catch (LoadException e) { if (next == null) { res.error = e; res.loading = false; res.notifyAll(); } else { next.load(res); } } catch (RuntimeException e) { throw (new LoadException(e, res)); } } finally { try { if (in != null) in.close(); } catch (IOException e) { } } }
6
public static String GetDzienNoc() { String dziennoc; Calendar cal = Calendar.getInstance(); int s = cal.get(Calendar.HOUR_OF_DAY); int p; int dn; dn = 0; if (s>=19) { p = 5; dn = 0; } else { if (s>=13) { p = 4; dn = 1; } else { if (s>=11) { p = 3; dn = 1; } else { if (s>=5) { p = 2; dn = 1; } else { if (s>=0) { p = 1; dn = 0; } } }} } switch(dn) { case 1: dziennoc = "dzien"; break; case 0: dziennoc = "noc"; break; default: dziennoc ="błąd - nie pobrano"; break; } return dziennoc; }
7
@Override public void execute() { SceneObject rock = SceneEntities.getNearest(Main.getRockIDs()); if (Inventory.isFull()) { if (BANK_AREA.contains(Players.getLocal().getLocation())) { if (Bank.isOpen()) { Bank.deposit(Main.oreID, 28); } else { Bank.open(); } } else if (MINE_AREA.contains(Players.getLocal().getLocation())) { Path path = Walking.findPath(BANK_TILE); path.traverse(); } } else { if (BANK_AREA.contains(Players.getLocal().getLocation())) { Path path = Walking.findPath(MINE_TILE); path.traverse(); } else if (MINE_AREA.contains(Players.getLocal().getLocation())) { if (rock != null) { if (rock.isOnScreen()) { rock.interact("Mine"); } else { Camera.turnTo(rock); } } } } }
8
public boolean insert(int index, E newItem) { if (index < 0 || index > size) return false; Node newNode = new Node(newItem); size++; if (index == 0) { // insert node at head newNode.next = head; head = newNode; if (end == null) // if only item end = newNode; return true; } if (index == size) { // insert node at tail end.next = newNode; end = newNode; return true; } Node cursor = head; int counter = 0; while (counter < index - 1) { // shuttle the cursor to the node before the index to be inserted cursor = cursor.next; counter++; } newNode.next = cursor.next; cursor.next = newNode; return true; }
6
public boolean addLink(Link l) { if (this.classes.containsKey(l.getField()) && this == l.getGroup() && this.links.getLinks(l.getField()).size() == 0) { this.links.add(l); l.getTeacher().addLink(l); return true; } return false; }
3
@Transactional public Task getById(Integer taskId) { return tasksDao.getById(taskId); }
0
public void supprimeCombiImp(Ligne proposition, LigneMarqueur marqueurVerif){ Iterator<Ligne> it = listeCombi.iterator(); Ligne tmpLigne; // Variable tempororaire qui récupèra une lgne pour la comparée for(int i=0; it.hasNext(); i++){ tmpLigne = it.next(); if(!marqueurVerif.equals(tmpLigne.compare(proposition))){ // Si la combinaison ne correspond pas à la proposition, on la suporime it.remove(); // On supprime avec l'iterateur, car c'est plus rapide } } }
2
@SuppressWarnings({ "unchecked", "rawtypes" }) public Combo_Box_View_All_Groups() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { //MAIN FRAME super("Team J's Scheduler | View All Groups"); setBounds(50,50,500,300); setResizable(false); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLayout(null); setVisible(true); //LISTBOX //READ APPOINTMENTS AND DISPLAY THEM Class.forName("com.mysql.jdbc.Driver").newInstance(); Statement s = GUI.con.createStatement(); //CHANGE FUNCTION BASED ON HIERARCHY if(GUI.Level == 1) { s.executeQuery ("SELECT * FROM groups;"); } else if(GUI.Level == 2) { s.executeQuery ("SELECT * FROM groups WHERE G_Name = \'"+GUI.ugn+"\';"); } ResultSet rs = s.getResultSet(); int g_id = 0, m_count = 0, t = 0; String g_name = ""; while (rs.next()) { g_id = rs.getInt("G_ID"); g_name = rs.getString("G_Name"); m_count = rs.getInt("Member_Count"); apps[t] = g_id + " " + g_name + " " + m_count; t++; } rs.close(); s.close(); //-------------------------------------|| list = new JList(); list.setLocation(0, 0); list.setSize(460,260); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setListData(apps); list.setVisible(true); add(list); }
3
private void acao114Declaracao(Token token) throws SemanticError { try { Identificador idVariavel = new Identificador(token.getLexeme()); tabela.add(idVariavel, nivelAtual); if (analisandoRegistro) listaIdsCamposRegistroTemp.add(idVariavel); else listaIdsVariaveis.add(idVariavel); } catch (IdentificadorJaDefinidoException ex) { throw new SemanticError(ex.getMessage(), token.getPosition()); } }
2
public Player GetPlayer1() { boolean test = false; if (test || m_test) { System.out.println("GameBoardGraphics :: GetPlayer1() BEGIN"); } if (test || m_test) { System.out.println("GameBoardGraphics :: GetPlayer1() END"); } return m_player1; }
4
private void loadState(int state) { if(state == MENUSTATE) gameStates[state] = new MenuState(this); if(state == LEVEL1STATE) try { gameStates[state] = new Level1State(this); } catch (IOException e) { e.printStackTrace(); } if(state == MPSTATE){ try { gameStates[state] = new MPState(this); } catch (IOException e) { e.printStackTrace(); } } }
5
public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); //This is the line that makes the hadoop run locally //conf.set("mapred.job.tracker", "local"); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: ImageDuplicatesRemover <in> <out>"); System.exit(2); } Job job = new Job(conf, "image dups remover"); job.setJarByClass(ImageDuplicatesRemover.class); job.setInputFormatClass(SequenceFileInputFormat.class); job.setMapperClass(ImageMd5Mapper.class); job.setReducerClass(ImageDupsReducer.class); //job.setNumReduceTasks(2); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); }
2
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JDK other = (JDK) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (path == null) { if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; }
9
private AppenderDto parseAppender(String initLine, BufferedReader br) throws IOException { AppenderDto appenderDto = new AppenderDto(); Parameter param = new Parameter(); Matcher matcher; String currentLine = initLine; while ((currentLine = br.readLine()) != null && currentLine.contains("appender") && !currentLine.contains(".id=")) { matcher = keyValPattern.matcher(currentLine); if (matcher.matches()){ String key = matcher.group(1); String value = matcher.group(2); if (key.contains("class")){ appenderDto.implementation = value; } else if (key.contains("param.type")){ param.type = value; } else if (key.contains("param.value")){ param.value = value; appenderDto.params.add(param); param = new Parameter(); } } } return appenderDto; }
7
public static void question12() { /* QUESTION PANEL SETUP */ questionLabel.setText("What about the music volume?"); questionNumberLabel.setText("12"); /* ANSWERS PANEL SETUP */ //resetting radioButton1.setSelected(false); radioButton2.setSelected(false); radioButton3.setSelected(false); radioButton4.setSelected(false); radioButton5.setSelected(false); radioButton6.setSelected(false); radioButton7.setSelected(false); radioButton8.setSelected(false); radioButton9.setSelected(false); radioButton10.setSelected(false); radioButton11.setSelected(false); radioButton12.setSelected(false);; radioButton13.setSelected(false); radioButton14.setSelected(false); //enability radioButton1.setEnabled(true); radioButton2.setEnabled(true); radioButton3.setEnabled(true); radioButton4.setEnabled(true); radioButton5.setEnabled(false); radioButton6.setEnabled(false); radioButton7.setEnabled(false); radioButton8.setEnabled(false); radioButton9.setEnabled(false); radioButton10.setEnabled(false); radioButton11.setEnabled(false); radioButton12.setEnabled(false); radioButton13.setEnabled(false); radioButton14.setEnabled(false); //setting the text radioButton1.setText("Keep it down."); radioButton2.setText("Perfect place between silence and noise."); radioButton3.setText("I like it...loud!"); radioButton4.setText("Doesn't matter to me."); radioButton5.setText("No used"); radioButton6.setText("No used"); radioButton7.setText("No used"); radioButton8.setText("No used"); radioButton9.setText("No used"); radioButton10.setText("No used"); radioButton11.setText("No used"); radioButton12.setText("No used"); radioButton13.setText("No used"); radioButton14.setText("No used"); // Calculating the best guesses and showing them. Knowledge.calculateAndColorTheEvents(); }
0
private void setXAxis(int type) { switch (type) { case BookData.TITLE: xAxisLabel = searchMatch.getTitleAxis(); return; case BookData.AUTHOR: xAxisLabel = searchMatch.getAuthorAxis(); return; case BookData.PAGES: xAxisLabel = searchMatch.getPageAxis(); return; case BookData.YEAR: xAxisLabel = searchMatch.getYearAxis(); return; case BookData.REVIEW: xAxisLabel = searchMatch.getReviewAxis(); return; default: return; } }
5
public int getRows() { return rows; }
0
private static boolean containsFuncCode(int[] funcCodeClass) { assert(_opCode == 0 || _opCode == 28 || _opCode == 16 || _opCode == 17); for (int i = 0; i < funcCodeClass.length; i++) { if (_funcCode == funcCodeClass[i]) { return true; } } return false; }
5
void sortSequence() { if (size() < 3) return; Atom[] end = getTermini(); if (end.length != 2) return; clear(); addAtom(end[0]); Atom[] at = model.bonds.getBondedPartners(end[0], true); boolean b; while (at.length == 1 || at.length == 2) { b = false; if (!contains(at[0])) { addAtom(at[0]); at = model.bonds.getBondedPartners(at[0], true); b = true; } if (at.length == 2) { if (!contains(at[1])) { addAtom(at[1]); at = model.bonds.getBondedPartners(at[1], true); b = true; } } if (!b) break; } model.notifyModelListeners(new ModelEvent(this, ModelEvent.MODEL_CHANGED, null, new Integer(model.molecules .indexOf(this)))); }
8
private PreparedStatement buildDeleteStatement(Connection conn_loc, String tableName, String whereField) throws SQLException { final StringBuffer sql = new StringBuffer("DELETE FROM "); sql.append(tableName); // delete all records if whereField is null if (whereField != null) { sql.append(" WHERE "); (sql.append(whereField)).append(" = ?"); } final String finalSQL = sql.toString(); // System.out.println(finalSQL); return conn_loc.prepareStatement(finalSQL); }
1
public Cardapio getCardapioDoDiaGson(){ Cardapio cardapio = null; URL serverAddress; try { serverAddress = new URL(ServiceResources.URL_RESOURCE+"/cardapio/hoje"); HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod("GET"); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuilder sb = new StringBuilder(); String temp = rd.readLine(); while(temp != null){ sb.append(temp); temp = rd.readLine(); } Gson gson = new Gson(); cardapio = gson.fromJson(sb.toString(), Cardapio.class); /*cardapio = (Cardapio) JSONObject.toBean(JSONObject.fromObject(sb), Cardapio.class); JSONObject json_obj = new JSONObject(sb); cardapio = new Cardapio(); cardapio.setCafeDaManha((Refeicao) json_obj.get("cafeDaManha")); cardapio.setAlmocoCarnivoro((Refeicao) json_obj.get("almocoCarnivoro")); cardapio.setAlmocoVegetariano((Refeicao) json_obj.get("almocoVegetariano")); cardapio.setJantaVegetariana((Refeicao) json_obj.get("jantaVegetariana")); cardapio.setJantaCarnivora((Refeicao) json_obj.get("jantaCarnivora")); */ } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cardapio; }
4
public static int tensionUnitStringToIndex(String unit) { switch (unit) { case "N": return 0; case "lbf": return 1; case "kgf": return 2; case "daN": return 3; default: return 0; } }
4
public Object get() { size--; return super.get(); }
0
public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof SecurityHeader)) return false; SecurityHeader other = (SecurityHeader) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.usernameToken==null && other.getUsernameToken()==null) || (this.usernameToken!=null && this.usernameToken.equals(other.getUsernameToken()))); __equalsCalc = null; return _equals; }
8
public beansAdministrador buscarAdmin(String nick){ for(beansAdministrador admin : admins){ if(admin.getNick().equals(nick)) return admin; } return null; }
2
public void actionPerformed(ActionEvent e) { ArrayList b = craft.getBullets(); for (int i = 0; i < b.size(); i++) { PlayerBullet m = (PlayerBullet) b.get(i); if (m.isVisible()) m.move(); else b.remove(i); } for (int i = 0; i < invaders.size(); i++){ Invaders inv = (Invaders) invaders.get(i); if (inv.isVisible()) inv.move(); else invaders.remove(i); } craft.move(); repaint(); }
4
public String process(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); //Validate the Input //for(String name: new String[] {"name", "manufacturer_name", "manufacturer_part_id", "tag", "location_name", "depreciation", "installdate", "note"}){ //if(request.getParameter(name) == null || request.getParameter(name).equals("")){ // request.setAttribute("message", "Please enter a value for " + name); // return "server_info.jsp"; // } //} String name = request.getParameter("name"); String manufacturerName = request.getParameter("manufacturer_name"); String manufacturerPartId = request.getParameter("manufacturer_part_id"); String tag = request.getParameter("tag"); String locationName = request.getParameter("location_name"); String depreciated = request.getParameter("depreciated"); String installdate = request.getParameter("installdate"); String note = request.getParameter("note"); //asset asset1 = BusinessObjectDAO.getInstance().create("asset"); // //asset1.setId(GUID.generate()); //asset1.setName(name); //asset1.setManufacturer_part_id(manufacturerPartId); //asset1.setInstallDate(installdate); //asset1.setDate_depreciated_by(depreciated); //asset1.setTag(tag); //asset1.setNotes(note); //asset1.setLocation_id("hi"); asset asset1 = BusinessObjectDAO.getInstance().create("asset"); //location.save(); // //asset1.setId(GUID.generate()); //asset1.setName(name); //asset1.setManufacturer_part_id(manufacturerPartId); //asset1.setInstallDate(installdate); //asset1.setDate_depreciated_by(depreciated); //asset1.setTag(tag); //asset1.setNotes(note); //asset1.setLocation_id("hi"); //Send an email StringBuilder body = new StringBuilder(); body.append("Welcome to My Stuff! To finish your registration, please click the link below. You'll love our great products.\n\n"); System.out.println("sent!"); return "server_info.jsp"; }
0
public Menu(){ // Set up areas setBounds(0,0,Main.WIDTH,Main.HEIGHT); setLayout(null); this.setBackground(new Color(30,30,30)); // Load in graphics ImageIcon loginTextField = new ImageIcon("res/Images/loginTextField.png"); ImageIcon loginButtonImg = new ImageIcon("res/Images/loginButton.png"); ImageIcon loadingGifImg = new ImageIcon("res/Images/loader.gif"); try { image = ImageIO.read(new File("res/Images/loginBackground.png")); } catch (IOException ex) { ex.printStackTrace(); } // Generate login pane loginPane.setBounds(0,Main.HEIGHT-250,280,250); loginPane.setLayout(null); loginPane.setOpaque(false); add(loginPane); // Generate signup pane - need to do JPanel signupPane = new JPanel(); signupPane.setBounds((int)((float)Main.WIDTH/2f)-120,(int)((float)Main.HEIGHT/2f)+65,240,30); signupPane.setLayout(null); signupPane.setOpaque(false); add(signupPane); // Generate username label usernameLBL.setForeground(new Color(36,36,36)); usernameLBL.setBounds(30,5,241,45); usernameLBL.setFont(new Font("Arial", Font.PLAIN, 16)); loginPane.add(usernameLBL); // Generate password label passwordLBL.setForeground(new Color(36,36,36)); passwordLBL.setBounds(30,45,241,85); passwordLBL.setFont(new Font("Arial", Font.PLAIN, 16)); loginPane.add(passwordLBL); // Generate unsuccessful label loginUnsuccessfulLBL.setBounds(50,75,241,85); loginUnsuccessfulLBL.setVisible(false); loginUnsuccessfulLBL.setForeground(new Color(58,0,0)); loginPane.add(loginUnsuccessfulLBL); // Text Field Capture Key JTextField captureKeyTF = new JPasswordField(); captureKeyTF.setOpaque(false); captureKeyTF.setBounds(-10,-10,0,0); loginPane.add(captureKeyTF); // Text Field username usernameTF.setBounds(30,5,241,45); usernameTF.setForeground(new Color(255,255,255)); usernameTF.setBorder(javax.swing.BorderFactory.createEmptyBorder()); usernameTF.setFont(new Font("Arial", Font.PLAIN, 16)); usernameTF.setOpaque(false); usernameTF.addFocusListener(new FocusListener(){ @Override public void focusGained(FocusEvent e) { usernameLBL.setVisible(false); } @Override public void focusLost(FocusEvent e) { if(usernameTF.getText().length() == 0){ usernameLBL.setVisible(true); } } }); usernameTF.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { tryLogin(); } }); loginPane.add(usernameTF); // generate username button backing JLabel usernameButtonLBL = new JLabel("", loginTextField, JLabel.LEFT); usernameButtonLBL.setBounds(20,5,271,45); loginPane.add(usernameButtonLBL); // text field password passwordTF.setBounds(30,45,241,85); passwordTF.setForeground(new Color(255,255,255)); passwordTF.setBorder(javax.swing.BorderFactory.createEmptyBorder()); passwordTF.setFont(new Font("Arial", Font.PLAIN, 16)); passwordTF.setOpaque(false); passwordTF.addFocusListener(new FocusListener(){ @Override public void focusGained(FocusEvent e) { passwordLBL.setVisible(false); } @Override public void focusLost(FocusEvent e) { if(passwordTF.getText().length() == 0){ passwordLBL.setVisible(true); } } }); passwordTF.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { tryLogin(); } }); loginPane.add(passwordTF); // generate password button backing JLabel passwordButtonLBL = new JLabel("", loginTextField, JLabel.LEFT); passwordButtonLBL.setBounds(20,45,271,85); loginPane.add(passwordButtonLBL); // Generate login button JLabel loginButton = new JLabel("", loginButtonImg, JLabel.LEFT); loginButton.setBounds(150,80,270,120); loginButton.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent e){ tryLogin(); } }); loginPane.add(loginButton); // Loading Gif loadingGif = new JLabel("", loadingGifImg, JLabel.CENTER); loadingGif.setBounds(0,Main.HEIGHT-300,280,250); loadingGif.setVisible(false); add(loadingGif); // Try and load details in from file Object[] fileReadData = FileConnector.readGameFiles("userDetails.dat"); if(fileReadData[0] != null && Util.isValid(fileReadData[0].toString()) && Util.isValid(fileReadData[1].toString())){ usernameTF.setText(fileReadData[0].toString()); passwordTF.setText(fileReadData[1].toString()); usernameLBL.setVisible(false); passwordLBL.setVisible(false); } // generate sign up button //signupBTN.setBounds(70,5,100,20); //signupPane.add(signupBTN); //signupBTN.addActionListener(this); usernameTF.requestFocusInWindow(); }
6
public static void main(String args[]) throws IOException{ // String studentName = Compiler.studentName; String studentID = Compiler.studentID; String uciNetID = Compiler.uciNetID; int publicTestcaseNum = 15; int privateTestcaseNum = 5; int publicPass = 0; for (int i=1; i<=publicTestcaseNum; ++i){ try{ if (testPublic(i) == PASS){ ++ publicPass; }else{ System.out.println("failed:" + i); } }catch (Exception e){ e.printStackTrace(); } } int privatePass = 0; for (int i=1; i<=privateTestcaseNum; ++i){ try{ if (testPrivate(i) == PASS){ ++ privatePass; }else{ System.out.println("failed:" + i); } }catch (Exception e){ e.printStackTrace(); } } System.out.print(studentID); System.out.print("\t"); System.out.print(uciNetID); System.out.print("\t"); System.out.print(" Passed Public Cases: "); System.out.print(publicPass); System.out.print("/"); System.out.print(publicTestcaseNum); System.out.print(" Passed Private Cases: "); System.out.print(privatePass); System.out.print("/"); System.out.println(privateTestcaseNum); }
6
private boolean needshift() { if (parent instanceof Window) { Window wnd = (Window) parent; if (wnd.cap != null) { String str = wnd.cap.text; if (str.equals("Oven") || str.equals("Finery Forge") || str.equals("Steel Crucible")) { return true; } } } return false; }
5
@Override public void mountSharedFolder(VirtualMachine virtualMachine, String shareName, String hostPath, String guestPath) throws Exception { if (status(virtualMachine) == VirtualMachineStatus.POWERED_OFF) { throw new Exception("Unable to mount shared folder. Machine is not started."); } if (guestPath == null) { throw new IllegalArgumentException("Shared folder [" + shareName + "] does not exist."); } String password = virtualMachine.getProperty(VirtualMachineConstants.GUEST_PASSWORD); String user = virtualMachine.getProperty(VirtualMachineConstants.GUEST_USER); if (HypervisorUtils.isWindowsGuest(virtualMachine)) { HypervisorUtils.checkReturnValue( exec(virtualMachine, "net use " + guestPath + " \\\\vboxsvr\\" + shareName)); } else if (HypervisorUtils.isLinuxGuest(virtualMachine)) { File mountFile = File.createTempFile("mount-", ".sh"); String mountScriptPathOnGuest = "/tmp/" + mountFile.getName(); FileWriter mountFileWriter = new FileWriter(mountFile); mountFileWriter.write( "/bin/mkdir -p " + guestPath + "; " + "sudo mount -t vboxsf -o uid=" + user + ",gid=" + user + " " + shareName + " " + guestPath + "; " + "rm " + mountScriptPathOnGuest); mountFileWriter.close(); try { ProcessBuilder copyMountScriptBuilder = getProcessBuilder( "guestcontrol " + virtualMachine.getName() + " copyto \"" + mountFile.getCanonicalPath() + "\" /tmp/" + " --username " + user + " --password " + password); ExecutionResult executionResult = HypervisorUtils.runProcess( copyMountScriptBuilder); if (executionResult.getReturnValue() != ExecutionResult.OK && !executionResult.getStdErr().toString().contains(VBoxStrategy.COPY_ERROR)) { //We are checking if COPY_ERROR was sent because of a bug where the copy is done //properly although it still spawns this error message with exit value different than 0 throw new Exception(executionResult.getStdErr().toString()); } HypervisorUtils.checkReturnValue( exec(virtualMachine, "/bin/bash " + mountScriptPathOnGuest)); } finally { mountFile.delete(); } } else { throw new Exception("Guest OS not supported"); } }
6
public void insertEdge(String startKey, String endKey, int weight) { Vertex startVertex = getVertex(startKey); Vertex endVertex = getVertex(endKey); if (startVertex == null) { insertVertex(startKey); startVertex = getVertex(startKey); } if (endVertex == null) { insertVertex(endKey); endVertex = getVertex(endKey); } Edge edge = new Edge(startVertex, endVertex, weight); EdgeListObject elo = new EdgeListObject(edge); if (this.edgeList == null) this.edgeList = new ArrayList<EdgeListObject>(); this.edgeList.add(elo); edge.setEdgeListObject(elo); if (graphType == Type.DIRECTED) { if (startVertex.getOutEdges() == null) startVertex.setOutEdges(new ArrayList<EdgeListObject>()); startVertex.getOutEdges().add(elo); if (endVertex.getInEdges() == null) endVertex.setInEdges(new ArrayList<EdgeListObject>()); endVertex.getInEdges().add(elo); } EdgeListObject startAugmentedEdgeObject = new EdgeListObject(edge); if (startVertex.getIncidenceList() == null) startVertex.setIncidenceList(new ArrayList<EdgeListObject>()); startVertex.getIncidenceList().add(startAugmentedEdgeObject); edge.setStartAugmentedEdgeObject(startAugmentedEdgeObject); EdgeListObject endAugmentedEdgeObject = new EdgeListObject(edge); if (endVertex.getIncidenceList() == null) endVertex.setIncidenceList(new ArrayList<EdgeListObject>()); endVertex.getIncidenceList().add(endAugmentedEdgeObject); edge.setEndAugmentedEdgeObject(endAugmentedEdgeObject); System.out.println("Inserted edge: " + startKey + "--" + weight + "--" + endKey); }
8
private void updateFalling() { int nextPlayerPositionY = theModel.getPlayerPositionY() + theModel.getVerticalStep(); int nextPlayerPositionX = theModel.getPlayerPositionX() + theModel.getHorizontalStep(); if (boardController.collidesWith(nextPlayerPositionX, nextPlayerPositionY, theModel.getPlayerHeight())) { ObstacleTypes obstacleType= boardController.getIntersectedObstacle(); if (obstacleType == ObstacleTypes.TRIANGLE) { gameOver = true; } else if (obstacleType == ObstacleTypes.SQUARE){ finishJumping(); } else if (obstacleType == ObstacleTypes.OVAL) { finishJumping(); jump(); } } else{ theModel.setPlayerPositionY(nextPlayerPositionY); } notifyBoardListener(); }
4
public Encoder getEncoder() { return encoder; }
0
@Override public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (isVisible() && (e.getSource() == optionPane) && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) { Object value = optionPane.getValue(); if (value == JOptionPane.UNINITIALIZED_VALUE) { //ignore reset return; } optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE); if (OK_BUTTON.equals(value)) { typedText = textField.getText(); if (nameValidator.isValid(typedText.toUpperCase())) { clearAndHide(); } else { textField.selectAll(); JOptionPane.showMessageDialog( CustomDialog.this, "Имя \"" + typedText + "\" использовать нельзя. Пожалуйста введите другое имя.", "Ошибка", JOptionPane.ERROR_MESSAGE); typedText = null; textField.requestFocusInWindow(); } } else { typedText = null; clearAndHide(); } } }
7
static private float[] load_d() { String s = "0,-0.000442504999227821826934814453125,0.0032501220703125,-0.0070037841796875,0.0310821533203125,-0.0786285400390625,0.100311279296875,-0.5720367431640625,1.144989013671875,0.5720367431640625,0.100311279296875,0.0786285400390625,0.0310821533203125,0.0070037841796875,0.0032501220703125,0.000442504999227821826934814453125,-0.0000152590000652708113193511962890625,-0.0004730219952762126922607421875,0.003326416015625,-0.007919312454760074615478515625,0.030517578125,-0.0841827392578125,0.0909271240234375,-0.6002197265625,1.144287109375,0.5438232421875,0.108856201171875,0.07305908203125,0.0314788818359375,0.0061187739484012126922607421875,0.00317382789216935634613037109375,0.00039672901039011776447296142578125,-0.0000152590000652708113193511962890625,-0.0005340580246411263942718505859375,0.00338745093904435634613037109375,-0.0088653564453125,0.02978515625,-0.0897064208984375,0.0806884765625,-0.6282958984375,1.1422119140625,0.5156097412109375,0.1165771484375,0.0675201416015625,0.03173828125,0.0052947998046875,0.0030822749249637126922607421875,0.0003662109957076609134674072265625,-0.0000152590000652708113193511962890625,-0.000579833984375,0.0034332280047237873077392578125,-0.0098419189453125,0.0288848876953125,-0.0951690673828125,0.0695953369140625,-0.656219482421875,1.138763427734375,0.4874725341796875,0.12347412109375,0.0619964599609375,0.0318450927734375,0.004486083984375,0.00299072288908064365386962890625,0.00032043500686995685100555419921875,-0.0000152590000652708113193511962890625,-0.000625610002316534519195556640625,0.00346374488435685634613037109375,-0.0108489990234375,0.027801513671875,-0.1005401611328125,0.0576171875,-0.6839141845703125,1.1339263916015625,0.45947265625,0.12957763671875,0.0565338134765625,0.0318145751953125,0.0037231449969112873077392578125,0.002899169921875,0.0002899169921875,-0.0000152590000652708113193511962890625,-0.0006866459734737873077392578125,0.00347900390625,-0.0118865966796875,0.0265350341796875,-0.1058197021484375,0.0447845458984375,-0.7113189697265625,1.12774658203125,0.4316558837890625,0.1348876953125,0.0511322021484375,0.0316619873046875,0.0030059809796512126922607421875,0.0027923579327762126922607421875,0.0002593990066088736057281494140625,-0.0000152590000652708113193511962890625,-0.000747681013308465480804443359375,0.00347900390625,-0.012939453125,0.02508544921875,-0.1109466552734375,0.0310821533203125,-0.738372802734375,1.1202239990234375,0.404083251953125,0.1394500732421875,0.04583740234375,0.0313873291015625,0.00233459495939314365386962890625,0.00268554710783064365386962890625,0.00024414100334979593753814697265625,-0.000030518000130541622638702392578125,-0.0008087159949354827404022216796875,0.00346374488435685634613037109375,-0.0140228271484375,0.0234222412109375,-0.1159210205078125,0.016510009765625,-0.7650299072265625,1.1113739013671875,0.376800537109375,0.1432647705078125,0.0406341552734375,0.031005859375,0.0016937260515987873077392578125,0.0025787348859012126922607421875,0.000213623003219254314899444580078125,-0.000030518000130541622638702392578125,-0.00088500999845564365386962890625,0.00341796898283064365386962890625,-0.0151214599609375,0.021575927734375,-0.120697021484375,0.00106811500154435634613037109375,-0.7912139892578125,1.1012115478515625,0.3498687744140625,0.1463623046875,0.035552978515625,0.0305328369140625,0.00109863304533064365386962890625,0.0024566650390625,0.00019836399587802588939666748046875,-0.000030518000130541622638702392578125,-0.0009613040019758045673370361328125,0.0033721919171512126922607421875,-0.0162353515625,0.01953125,-0.1252593994140625,-0.015228270553052425384521484375,-0.816864013671875,1.08978271484375,0.3233184814453125,0.148773193359375,0.030609130859375,0.029937744140625,0.0005493159987963736057281494140625,0.0023498539812862873077392578125,0.00016784699982963502407073974609375,-0.000030518000130541622638702392578125,-0.001037598005495965480804443359375,0.0032806401140987873077392578125,-0.0173492431640625,0.0172576904296875,-0.1295623779296875,-0.032379150390625,-0.841949462890625,1.077117919921875,0.297210693359375,0.1504974365234375,0.02581787109375,0.0292816162109375,0.000030518000130541622638702392578125,0.0022430419921875,0.000152588007040321826934814453125,-0.00004577599975164048373699188232421875,-0.001113891950808465480804443359375,0.00317382789216935634613037109375,-0.018463134765625,0.014801025390625,-0.1335906982421875,-0.05035400390625,-0.866363525390625,1.0632171630859375,0.2715911865234375,0.1515960693359375,0.02117919921875,0.028533935546875,-0.000442504999227821826934814453125,0.00212097191251814365386962890625,0.000137328999699093401432037353515625,-0.00004577599975164048373699188232421875,-0.001205443986691534519195556640625,0.00305175804533064365386962890625,-0.0195770263671875,0.012115479446947574615478515625,-0.137298583984375,-0.0691680908203125,-0.8900909423828125,1.04815673828125,0.2465057373046875,0.152069091796875,0.0167083740234375,0.0277252197265625,-0.0008697509765625,0.00201415992341935634613037109375,0.0001220699996338225901126861572265625,-0.00006103499981691129505634307861328125,-0.001296996953897178173065185546875,0.00288391089998185634613037109375,-0.02069091796875,0.0092315673828125,-0.1406707763671875,-0.088775634765625,-0.913055419921875,1.0319366455078125,0.22198486328125,0.1519622802734375,0.012420654296875,0.0268402099609375,-0.0012664790265262126922607421875,0.001907348982058465480804443359375,0.0001068119963747449219226837158203125,-0.00006103499981691129505634307861328125,-0.00138855003751814365386962890625,0.00270080589689314365386962890625,-0.02178955078125,0.006134033203125,-0.1436767578125,-0.109161376953125,-0.9351959228515625,1.014617919921875,0.19805908203125,0.15130615234375,0.0083160400390625,0.025909423828125,-0.001617431989870965480804443359375,0.001785277971066534519195556640625,0.0001068119963747449219226837158203125,-0.0000762940035201609134674072265625,-0.0014801030047237873077392578125,0.0024871830828487873077392578125,-0.022857666015625,0.0028228759765625,-0.1462554931640625,-0.13031005859375,-0.95648193359375,0.996246337890625,0.1747894287109375,0.150115966796875,0.0043945307843387126922607421875,0.024932861328125,-0.00193786597810685634613037109375,0.0016937260515987873077392578125,0.0000915530035854317247867584228515625,-0.0000762940035201609134674072265625,-0.001586913946084678173065185546875,0.00222778297029435634613037109375,-0.0239105224609375,-0.0006866459734737873077392578125,-0.1484222412109375,-0.1522064208984375,-0.9768524169921875,0.9768524169921875,0.1522064208984375,0.1484222412109375,0.0006866459734737873077392578125,0.0239105224609375,-0.00222778297029435634613037109375,0.001586913946084678173065185546875,0.0000762940035201609134674072265625,-0.0000915530035854317247867584228515625,-0.0016937260515987873077392578125,0.00193786597810685634613037109375,-0.024932861328125,-0.0043945307843387126922607421875,-0.150115966796875,-0.1747894287109375,-0.996246337890625,0.95648193359375,0.13031005859375,0.1462554931640625,-0.0028228759765625,0.022857666015625,-0.0024871830828487873077392578125,0.0014801030047237873077392578125,0.0000762940035201609134674072265625,-0.0001068119963747449219226837158203125,-0.001785277971066534519195556640625,0.001617431989870965480804443359375,-0.025909423828125,-0.0083160400390625,-0.15130615234375,-0.19805908203125,-1.014617919921875,0.9351959228515625,0.109161376953125,0.1436767578125,-0.006134033203125,0.02178955078125,-0.00270080589689314365386962890625,0.00138855003751814365386962890625,0.00006103499981691129505634307861328125,-0.0001068119963747449219226837158203125,-0.001907348982058465480804443359375,0.0012664790265262126922607421875,-0.0268402099609375,-0.012420654296875,-0.1519622802734375,-0.22198486328125,-1.0319366455078125,0.913055419921875,0.088775634765625,0.1406707763671875,-0.0092315673828125,0.02069091796875,-0.00288391089998185634613037109375,0.001296996953897178173065185546875,0.00006103499981691129505634307861328125,-0.0001220699996338225901126861572265625,-0.00201415992341935634613037109375,0.0008697509765625,-0.0277252197265625,-0.0167083740234375,-0.152069091796875,-0.2465057373046875,-1.04815673828125,0.8900909423828125,0.0691680908203125,0.137298583984375,-0.012115479446947574615478515625,0.0195770263671875,-0.00305175804533064365386962890625,0.001205443986691534519195556640625,0.00004577599975164048373699188232421875,-0.000137328999699093401432037353515625,-0.00212097191251814365386962890625,0.000442504999227821826934814453125,-0.028533935546875,-0.02117919921875,-0.1515960693359375,-0.2715911865234375,-1.0632171630859375,0.866363525390625,0.05035400390625,0.1335906982421875,-0.014801025390625,0.018463134765625,-0.00317382789216935634613037109375,0.001113891950808465480804443359375,0.00004577599975164048373699188232421875,-0.000152588007040321826934814453125,-0.0022430419921875,-0.000030518000130541622638702392578125,-0.0292816162109375,-0.02581787109375,-0.1504974365234375,-0.297210693359375,-1.077117919921875,0.841949462890625,0.032379150390625,0.1295623779296875,-0.0172576904296875,0.0173492431640625,-0.0032806401140987873077392578125,0.001037598005495965480804443359375,0.000030518000130541622638702392578125,-0.00016784699982963502407073974609375,-0.0023498539812862873077392578125,-0.0005493159987963736057281494140625,-0.029937744140625,-0.030609130859375,-0.148773193359375,-0.3233184814453125,-1.08978271484375,0.816864013671875,0.015228270553052425384521484375,0.1252593994140625,-0.01953125,0.0162353515625,-0.0033721919171512126922607421875,0.0009613040019758045673370361328125,0.000030518000130541622638702392578125,-0.00019836399587802588939666748046875,-0.0024566650390625,-0.00109863304533064365386962890625,-0.0305328369140625,-0.035552978515625,-0.1463623046875,-0.3498687744140625,-1.1012115478515625,0.7912139892578125,-0.00106811500154435634613037109375,0.120697021484375,-0.021575927734375,0.0151214599609375,-0.00341796898283064365386962890625,0.00088500999845564365386962890625,0.000030518000130541622638702392578125,-0.000213623003219254314899444580078125,-0.0025787348859012126922607421875,-0.0016937260515987873077392578125,-0.031005859375,-0.0406341552734375,-0.1432647705078125,-0.376800537109375,-1.1113739013671875,0.7650299072265625,-0.016510009765625,0.1159210205078125,-0.0234222412109375,0.0140228271484375,-0.00346374488435685634613037109375,0.0008087159949354827404022216796875,0.000030518000130541622638702392578125,-0.00024414100334979593753814697265625,-0.00268554710783064365386962890625,-0.00233459495939314365386962890625,-0.0313873291015625,-0.04583740234375,-0.1394500732421875,-0.404083251953125,-1.1202239990234375,0.738372802734375,-0.0310821533203125,0.1109466552734375,-0.02508544921875,0.012939453125,-0.00347900390625,0.000747681013308465480804443359375,0.0000152590000652708113193511962890625,-0.0002593990066088736057281494140625,-0.0027923579327762126922607421875,-0.0030059809796512126922607421875,-0.0316619873046875,-0.0511322021484375,-0.1348876953125,-0.4316558837890625,-1.12774658203125,0.7113189697265625,-0.0447845458984375,0.1058197021484375,-0.0265350341796875,0.0118865966796875,-0.00347900390625,0.0006866459734737873077392578125,0.0000152590000652708113193511962890625,-0.0002899169921875,-0.002899169921875,-0.0037231449969112873077392578125,-0.0318145751953125,-0.0565338134765625,-0.12957763671875,-0.45947265625,-1.1339263916015625,0.6839141845703125,-0.0576171875,0.1005401611328125,-0.027801513671875,0.0108489990234375,-0.00346374488435685634613037109375,0.000625610002316534519195556640625,0.0000152590000652708113193511962890625,-0.00032043500686995685100555419921875,-0.00299072288908064365386962890625,-0.004486083984375,-0.0318450927734375,-0.0619964599609375,-0.12347412109375,-0.4874725341796875,-1.138763427734375,0.656219482421875,-0.0695953369140625,0.0951690673828125,-0.0288848876953125,0.0098419189453125,-0.0034332280047237873077392578125,0.000579833984375,0.0000152590000652708113193511962890625,-0.0003662109957076609134674072265625,-0.0030822749249637126922607421875,-0.0052947998046875,-0.03173828125,-0.0675201416015625,-0.1165771484375,-0.5156097412109375,-1.1422119140625,0.6282958984375,-0.0806884765625,0.0897064208984375,-0.02978515625,0.0088653564453125,-0.00338745093904435634613037109375,0.0005340580246411263942718505859375,0.0000152590000652708113193511962890625,-0.00039672901039011776447296142578125,-0.00317382789216935634613037109375,-0.0061187739484012126922607421875,-0.0314788818359375,-0.07305908203125,-0.108856201171875,-0.5438232421875,-1.144287109375,0.6002197265625,-0.0909271240234375,0.0841827392578125,-0.030517578125,0.007919312454760074615478515625,-0.003326416015625,0.0004730219952762126922607421875,0.0000152590000652708113193511962890625"; String[] ss = s.split(","); float[] ff = new float[ss.length]; for (int i = 0; i < ff.length; i++) { ff[i] = new BigDecimal(ss[i]).floatValue(); } return ff; }
1
public E getElement(int index) { if (indexOK(index)) { return (E) array[index]; } return null; }
1
public static Boolean save(Entry entry, String collectionName) { if(entry == null) return false; MongoCollection collection = getJongo().getCollection(collectionName); Boolean dirty = false; Integer id = entry.getId(); IdTracker tracker = null; if(id == -1) { tracker = getNextId(collection); entry.setId(tracker.getNextId()); dirty = true; } Long now = System.currentTimeMillis(); entry.setUpdateDate(new Date(now)); WriteResult result = collection.save(entry); if(!result.getLastError().ok()) return false; if(dirty) result = updateId(tracker,collection); return result.getLastError().ok(); }
4
*/ public void setPayload(byte[] payload) { this.payload = new byte[payload.length]; this.payload = payload; //if protocols used, get additional information if(protocols){ //check dispatch header for any 6lowpan-type packet //if 10xxxxxxxx or 11000xxx or 11100xxx or 011xxxxx ---> create a 6lowpan-Packet byte firstByte = payload[0]; int meshAddressingMaskedByte = (firstByte&(byte)192) & 0xFF; int fragmentationMaskedByte = (firstByte&(byte)248) & 0xFF; int iphcMaskedByte = (firstByte&(byte)224) & 0xFF; //check for any matching mask if(meshAddressingMaskedByte == 128 || fragmentationMaskedByte == 192 || fragmentationMaskedByte == 224 || iphcMaskedByte == 96){ sixLoWPANpacket = new SixLoWPANPacket(payload); } } }
5
private boolean read() { try { final URLConnection conn = this.url.openConnection(); conn.setConnectTimeout(5000); if (this.apiKey != null) { conn.addRequestProperty("X-API-Key", this.apiKey); } conn.addRequestProperty("User-Agent", "Updater (by Gravity)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.plugin.getLogger().warning( "The updater could not find any files for the project id " + this.id); this.result = UpdateResult.FAIL_BADID; return false; } this.versionName = (String) ((JSONObject) array .get(array.size() - 1)).get(Updater.TITLE_VALUE); this.versionLink = (String) ((JSONObject) array .get(array.size() - 1)).get(Updater.LINK_VALUE); this.versionType = (String) ((JSONObject) array .get(array.size() - 1)).get(Updater.TYPE_VALUE); this.versionGameVersion = (String) ((JSONObject) array.get(array .size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.plugin .getLogger() .warning( "dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); this.plugin .getLogger() .warning( "Please double-check your configuration to ensure it is correct."); this.result = UpdateResult.FAIL_APIKEY; } else { this.plugin .getLogger() .warning( "The updater could not contact dev.bukkit.org for updating."); this.plugin .getLogger() .warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); this.result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
4
@Test public void insertLastHandlesTailCorrectly() { l.insertLast(a); for (int i = 1; i < 10; i++) { l.insertLast(new Vertex(i)); } int i = 0; Vertex test = l.min(); while (test != null) { test = l.succ(test); i++; if (i > 300) { break; } } assertTrue("Endless loop!", i < 300); }
3
final int[][] method1094(byte i) { anInt1864++; int[] is = new int[256]; int i_10_ = 0; for (int i_11_ = 0; i_11_ < ((Model) this).triangles; i_11_++) { int i_12_ = ((Model) this).anIntArray1824[i_11_]; if ((i_12_ ^ 0xffffffff) <= -1) { if (i_10_ < i_12_) i_10_ = i_12_; is[i_12_]++; } } int[][] is_13_ = new int[i_10_ - -1][]; if (i <= 13) method1102(-65, (byte) -8, (byte) 94, (short) -89, (byte) 6, (short) -117, 21, (byte) 21, -31); for (int i_14_ = 0; (i_14_ ^ 0xffffffff) >= (i_10_ ^ 0xffffffff); i_14_++) { is_13_[i_14_] = new int[is[i_14_]]; is[i_14_] = 0; } for (int i_15_ = 0; (((Model) this).triangles ^ 0xffffffff) < (i_15_ ^ 0xffffffff); i_15_++) { int i_16_ = ((Model) this).anIntArray1824[i_15_]; if ((i_16_ ^ 0xffffffff) <= -1) is_13_[i_16_][is[i_16_]++] = i_15_; } return is_13_; }
7
private String getDowJones () { String dowJones = "0"; try (final Scanner dowJonesWebPage = new Scanner (new URL (FieldGoogleFinance.URL.toString()).openStream())) { boolean lastPriceHasFind = false; boolean changePercentHasFind = false; while (dowJonesWebPage.hasNext() && ((! lastPriceHasFind) || (! changePercentHasFind))) { String value = dowJonesWebPage.next(); if (value.contains(FieldGoogleFinance.LAST_PRICE_PATTERN.toString())) { dowJones = value.replaceFirst(FieldGoogleFinance.LAST_PRICE_PATTERN.toString(), "").replaceFirst("</span>", ""); dowJones = dowJones + " "; lastPriceHasFind = true; } else if (value.contains(FieldGoogleFinance.CHANGE_PERCENT_PATTERN.toString())) { dowJones = dowJones + value.replaceFirst(FieldGoogleFinance.CHANGE_PERCENT_PATTERN.toString(), "").replaceFirst("</span>", ""); changePercentHasFind = true; } } } catch (MalformedURLException e) { System.out.println("TableIndiceUS getDowJones() MalformedURLException " + "URL : " + FieldGoogleFinance.URL.toString() + " " + e); } catch (IOException e) { System.out.println("TableIndiceUS getDowJones() IOException " + e); } return dowJones; }
7
@Override public void addAgent() { Random rand = new Random(); int x; int y; lab(environment); do { x = rand.nextInt(environment.taille_envi); y = rand.nextInt(environment.taille_envi); } while (environment.grille[x][y] != null); pacMan = new Point(x, y); environment.grille[x][y] = new PacMan("PacMan", x, y); agents.add(environment.grille[x][y]); for (int i = 0; i < ((EnvironnementPacMan) environment).nbAgent; i++) { do { x = rand.nextInt(environment.taille_envi); y = rand.nextInt(environment.taille_envi); } while (environment.grille[x][y] != null); environment.grille[x][y] = new Gost("Gost" + i, x, y); agents.add(environment.grille[x][y]); } ((EnvironnementPacMan) environment).goDijkstra(pacMan.x, pacMan.y); }
3
private void stop() { try { for (Clip c : clips) { c.stop(); c.setFramePosition(0); } } catch (Exception e) { e.printStackTrace(); } }
2
Power(String name, int properties, String imgFile, String helpInfo) { this.name = name ; this.helpInfo = helpInfo ; this.buttonTex = Texture.loadTexture(IMG_DIR+imgFile) ; this.properties = properties ; }
4
public byte getValueAsByte() throws IllegalArgumentException { if (!isOptionAsByte(code)) { throw new IllegalArgumentException("DHCP option type (" + this.code + ") is not byte"); } if (this.value == null) { throw new IllegalStateException("value is null"); } if (this.value.length != 1) { throw new DHCPBadPacketException("option " + this.code + " is wrong size:" + this.value.length + " should be 1"); } return this.value[0]; }
3
private void performOpen() { JFileChooser chooser = new JFileChooser(lastSave); chooser.setFileFilter(getFileFilter()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.showOpenDialog(this); File file = chooser.getSelectedFile(); String errorMessage = null; if (file != null && file.isFile() && file.exists()) { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { Object o = ois.readObject(); if (o instanceof GameData) { GameData d = (GameData) o; gcp.setContents(d.general); scp.setContents(d.shop); lcp.setContents(d.levels); tcp.setContents(d.towers); ecp.setContents(d.enemies); pcp.setContents(d.projectiles); lastSave = file; } else { errorMessage = "The file does not contain valid game data."; } } catch (IOException ie) { errorMessage = "The file could not be read from the drive."; } catch (ClassNotFoundException e) { errorMessage = "The contents of the file are incompatible with this computer."; } finally { if (errorMessage != null) { JOptionPane.showMessageDialog(this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE); } } } }
7
public void applyPrefixes(LinkedList<Prefix> pre){ //Apply prefix in graph name if (name.startsWith("<")){ //Apply prefix for (Prefix p:pre){ if (name.startsWith("<"+p.getIriContent())){ name=p.getPrefix()+name.substring(p.getIriContent().length()+1,name.length()-1); break; } } } //Apply prefixes in triples for (Triple t:triples){ t.applyPrefixes(pre); } //Apply prefixes in MSGs if (msgs!=null){ for (MSG msg:msgs){ for (Triple t:msg.getTriples()){ t.applyPrefixes(pre); } } } //Apply prefixes in sub graphs for (NamedGraph subG:children){ subG.applyPrefixes(pre); } }
8
public synchronized void receive (Message m) { long t__recv, dt; double rate; long d; double average, deviation; count += 1; if (count == 1) _t_recv = System.currentTimeMillis(); d = (System.currentTimeMillis() - Long.parseLong(m.getPayload())); /* Accumulate */ delay += d; delaysquared += (double) (d * d); if (count % Utils.STEP == 0) { t__recv = System.currentTimeMillis(); dt = t__recv - _t_recv; if (dt > 0) rate = (double) (Utils.STEP * 1000) / (double) dt; else rate = 0.0; /* Calculate average delay */ average = (double) delay / (double) Utils.STEP; /* Calculate std deviation */ deviation = Math.sqrt( (delaysquared - (double) (delay * delay) / (double) Utils.STEP) / (double) (Utils.STEP - 1) ); Utils.out(pid, String.format("[RECV] %06d\trate %10.1f m/s\tavg. delay %10.1f\tstddev %10.1f", count, rate, average, deviation)); _t_recv = t__recv; /* Reset delay */ delay = 0; delaysquared = 0.0; } }
3
public void preencherTabela() throws Exception { ArrayList<String> colunas = new ArrayList<String>(); colunas.add("id"); colunas.add("nome"); colunas.add("nomeCientifico"); colunas.add("email"); colunas.add("sexo"); colunas.add("classe"); colunas.add("titulacao"); colunas.add("cursoVinculado"); colunas.add("areaformacao"); Object linhas[][] = new Object[list.size()][]; int i = 0; for (Pesquisador pesquisador : list) { linhas[i] = formatoTabela(pesquisador); i++; } view.getTabela().setModel( new DefaultTableModel(linhas, colunas.toArray())); if (view.getOpcoes().getModel().getSize() == 0) view.getOpcoes().setModel( new DefaultComboBoxModel(colunas.toArray())); for (int x = 0; x < view.getTabela().getColumnCount(); x++) { String columnName = view.getTabela().getColumnName(x); TableColumn col = view.getTabela().getColumnModel().getColumn(x); col.setMinWidth(new JLabel(columnName).getPreferredSize().width + 10); } }
3
protected static String processUnicode(String text) { boolean big = false; text = text.replace("|הגדלה=ללא", ""); text = text.replace("|הגדלה=לא", ""); text = text.replace("יוניקוד|", ""); if (text.contains("הגדלה")) { big = true; } if (text.contains("מוגדל")) { big = true; } text = text.replace("|מוגדל", ""); text = text.replace("|הגדלה", ""); if (big == true) { text = "<span class=\"unicode unicode-big\">" + text + "</span>"; } else { text = "<span class=\"unicode\">" + text + "</span>"; } return text; }
3
public CheckResultMessage check34(int day) { int r = get(47, 5); int c = get(48, 5); if (checkVersion(file).equals("2003")) { try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if (0 != getValue(r + day, c, 12).compareTo( getValue(r + day - 1, c + 5, 12))) { return error("支付机构汇总报表<" + fileName + ">备付金账户中押金余额延续性 N1:" + day + "日错误"); } } catch (Exception e) { } } else { try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if (0 != getValue1(r + day, c, 12).compareTo( getValue1(r + day - 1, c + 5, 12))) { return error("支付机构汇总报表<" + fileName + ">备付金账户中押金余额延续性 N1:" + day + "日错误"); } } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">备付金账户中押金余额延续性 N1:" + day + "日正确"); }
5
@Override public List<WeightedEdge<N, W>> edgesFrom(N... fromList) { LinkedList<WeightedEdge<N, W>> list = new LinkedList<WeightedEdge<N, W>>(); if(fromList.length == 1) { N from = fromList[0]; if(containsNode(from)) { list.addAll(nodes.get(from)); } } else if(fromList.length > 1) { for(int i = 0; i < fromList.length; i++) { list.addAll(edgesFrom(fromList[i])); } } return list; }
4
@Override public HashMap<String, Sprite> loadAll() { //First get a hashmap of all images ImageLoader loader = new ImageLoader(); HashMap<String, BufferedImage> imageMap = loader.loadAll(); //Create a hashmap of sprites HashMap<String, Sprite> spriteMap = new HashMap<String, Sprite>(); //Declare a bufferedReader to read file from BufferedReader inputStream = null; //Create an arraylist of lines in each file ArrayList<String> lines = new ArrayList<String>(); //For each file in the array of valid files for this loader for(File f : getValidFiles()){ //Clear the list of lines from previous file lines.clear(); String imgKey; //Point the buffered reader to the file try { inputStream = new BufferedReader(new FileReader(f)); //First store the image key this file is defining as a sprite String imgName = f.getName(); //imgKey is the name without the file extension imgKey = imgName.substring(0, imgName.length() - ext.length()); //Read the next line String line; while((line = inputStream.readLine()) != null){ //Add it to the arraylist of lines lines.add(line); } } catch (FileNotFoundException e) { // If opening the stream breaks, print stack trace, file that caused //It to break and the exception message. e.printStackTrace(); System.out.println("Failed to load sbp:" + f.getName() + ", the file was not found."); System.out.println(e.getMessage()); //Then continue looping through files continue; } catch (IOException e) { // If opening the stream breaks, print stack trace, file that caused //It to break and the exception message. e.printStackTrace(); System.out.println("Failed to load sbp:" + f.getName() + ", the file contains unexpected formatting."); System.out.println(e.getMessage()); //Then continue looping through files continue; } //Once all the lines have been read we must parse them and create a sprite Sprite s = parseBlueprint(imageMap.get(imgKey), lines); //Add sprite to the map spriteMap.put(imgKey, s); } return spriteMap; }
4
private void checkCollision() { if (r.intersects(StartingClass.hb.r)){ visible = false; if (StartingClass.hb.health > 0){ StartingClass.hb.health -= 1; } if (StartingClass.hb.health == 0){ StartingClass.hb.setCenterX(-100); StartingClass.score += 5; } } if (r.intersects(StartingClass.hb2.r)){ visible = false; if (StartingClass.hb2.health > 0){ StartingClass.hb2.health -= 1; } if (StartingClass.hb2.health == 0){ StartingClass.hb2.setCenterX(-100); StartingClass.score += 5; } } }
6
public void openAlgorithm() { int value = programLoader.showOpenDialog(null); if (value == JFileChooser.APPROVE_OPTION) { File file = programLoader.getSelectedFile(); AlgReader algReader = null; try { algReader = new AlgReader(file); } catch (FileNotFoundException e) { e.printStackTrace(); } try { read(algReader); } catch (Exception e) { settings.clear(); } GUI.controls.refresh(); GUI.gRepaint(); program.compile(); } GUI.controls.refresh(); GUI.gRepaint(); }
3
void loadProfile(int profile) { try { switch (profile) { case 1: { String text = openFile(TextEditor.class.getResourceAsStream("text.txt")); //$NON-NLS-1$ StyleRange[] styles = getStyles(TextEditor.class.getResourceAsStream("styles.txt")); //$NON-NLS-1$ styledText.setText(text); if (styles != null) styledText.setStyleRanges(styles); break; } case 2: { styledText.setText(getResourceString("Profile2")); //$NON-NLS-1$ break; } case 3: { String text = openFile(TextEditor.class.getResourceAsStream("text4.txt")); //$NON-NLS-1$ styledText.setText(text); break; } case 4: { styledText.setText(getResourceString("Profile4")); //$NON-NLS-1$ break; } } updateToolBar(); } catch (Exception e) { showError(getResourceString("Error"), e.getMessage()); //$NON-NLS-1$ } }
6
protected void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); desktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) {} }
1
public void setUsertilePosition(Position position) { if (position == null) { this.usertilePosition = UIPositionInits.USERTILE.getPosition(); } else { if (position.equals(Position.NONE)) { IllegalArgumentException iae = new IllegalArgumentException("Position none is not allowed!"); Main.handleUnhandableProblem(iae); } this.usertilePosition = position; } somethingChanged(); }
2
private String individualMonsterDetails() { String string = ""; string = string.concat("Monster HP:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getHealth()); } string = string.concat("\nMonster AP:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getActionPoints()); } string = string.concat("\nMonster MP:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getMana()); } string = string.concat("\nMonster isAlive:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getIsAlive()); } string = string.concat("\nMonster isWaiting:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).isWaiting()); } string = string.concat("\nMonster LVL:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getLevel()); } string = string.concat("\nMonster DMG:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getDamage(0) + "-" + stage.getMonsters().get(i).getDamage(1)); } string = string.concat("\nMonster HITDMG:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getHitDamage()); } string = string.concat("\nMonster randomWait:"); for (int i = 0; i < stage.getMonsters().size(); i++) { string = string.concat(" " + stage.getMonsters().get(i).getRandomWait()); } return string; }
9
@Override public Token getToken(MPFile file) { Token t = null; int state = 1; String lexeme = ""; char current = 0; while (state != 3) { if (!file.hasNextChar() && state == 2) { state = 3; } else { switch (state) { case 1: current = file.getNextCharacter(); if (WhiteSpace.isWhitespace(current)) { state = 2; lexeme += current; } break; case 2: current = file.getCurrentCharacter(); if (WhiteSpace.isWhitespace(current)) { current = file.getNextCharacter(); state = 2; lexeme += current; } else { state = 3; } break; } } } t = new Token(TokenType.MP_WHITESPACE, lexeme, file.getLineIndex(), file.getColumnIndex() - lexeme.length()); return t; }
7
public BSTNode getRoot() { return root; }
0
@Override public boolean getPoint(int mouseX, int mouseY){ int newX = -1; int newY = -1; if (mouseX < 800){ int cx = Boot.getPlayer().getX(); int cy = Boot.getPlayer().getY(); newX = cx + (mouseX / Standards.TILE_SIZE) - 12; newY = cy + ((Standards.W_HEIGHT - mouseY) / Standards.TILE_SIZE) - 12; } if (newX != -1 && newY != -1){ switch(picks){ default: break; case 0: this.x1 = newX; this.y1 = newY; picks = 1; break; case 1: this.x2 = newX; this.y2 = newY; picks = 0; break; case 3: spawnBox(24, newX, newY); break; case 4: loadPrefab(newX, newY); break; case 5: loadRandomPrefab(newX, newY); break; } } return true; }
8
@Override public String toString(){ String s = "List of Buttons\n"; for (int i=0;i<bHandler.length;i++){ if (bHandler[i] != null) s += bHandler[i].getEntity().getName() + "\n"; } s += "END OF LIST\n-----------------\n\n"; return s; }
2
@Override public void actionPerformed(InputEvent event) { super.actionPerformed(event); if (event.key.id == input.down.id && event.type == InputEventType.PRESSED) { selectedEntry++; } if (event.key.id == input.up.id && event.type == InputEventType.PRESSED) { selectedEntry--; } if (selectedEntry < 0) { selectedEntry = 0; } if (selectedEntry >= worlds.length) { selectedEntry = worlds.length - 1; } if (event.key.id == input.action.id && event.type == InputEventType.PRESSED) { game.setWorld(new World(game, worldFiles[selectedEntry])); close(); } }
8
public boolean PieceNotInWay(int targetX, int targetY, boolean color, Board chessBoard, Game game) { int incrementX = 0, incrementY = 0; int curX = this.curX, curY = this.curY; if (targetX == this.curX) { if (targetY > this.curY) { incrementY = 1; } else { incrementY = -1; } } else if (targetY == this.curY) { if (targetX > this.curX) { incrementX = 1; } else { incrementX = -1; } } while (Math.abs(curX - targetX) > 0 && Math.abs(curY - targetY) > 0) { curX += incrementX; curY += incrementY; if (chessBoard.board[curX][curY].occupant.color == this.color) { return false; } else if (chessBoard.board[curX][curY].occupant.color != this.color) { game.movePieces(this, curX, curY); return false; } } return true; }
8
public static void enviarMensajes(String factoriaConexiones, String colaMensajes, String nombreProductor, int numMensajes) { Context contextoInicial; ConnectionFactory factoria; Connection conexion = null; Session sesion = null; Queue cola; MessageProducer productorMensajes = null; TextMessage mensajeJMS; String mensaje; try { // Busca los recursos proporcionados por el servidor en el árbol // JNDI que contiene los objetos // Ver los parámetros de conexión en el fichero jndi.properties contextoInicial = new InitialContext(); factoria = (ConnectionFactory) contextoInicial.lookup(factoriaConexiones); cola = (Queue) contextoInicial.lookup(colaMensajes); // Crea los objetos que dan soporte al envío conexion = factoria.createConnection(); sesion = conexion.createSession(false, Session.AUTO_ACKNOWLEDGE); productorMensajes = sesion.createProducer(cola); // Envía los mensajes mensajeJMS = sesion.createTextMessage(); for (int i = 1; i <= numMensajes; i++) { mensaje = nombreProductor + ": mensaje numero " + i; mensajeJMS.setText(mensaje); productorMensajes.send(mensajeJMS); bitacora.info(mensaje + " --> enviado"); } } catch (NamingException ex) { bitacora.error(ex.getMessage(), ex); } catch (JMSException ex) { bitacora.error(ex.getMessage(), ex); } finally { // Libera los recursos try { if (productorMensajes != null) { productorMensajes.close(); } } catch (Exception ignorar) { } try { if (sesion != null) { sesion.close(); } } catch (Exception ignorar) { } try { if (conexion != null) { conexion.close(); } } catch (Exception ignorar) { } } }
9
@Test public void testGetCuenta() { System.out.println("getCuenta"); Cuenta instance = new Cuenta(); String expResult = ""; String result = instance.getCuenta(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); }
0
public Map<RedisBigTableKey, byte[]> getAll(byte[] table) throws RedisForemanException { if (tableExists(table)) { Map<byte[], byte[]> map = instance.hgetAll(table); Map<RedisBigTableKey, byte[]> toReturn = new HashMap<RedisBigTableKey, byte[]>(); for (Entry<byte[], byte[]> ent : map.entrySet()) { toReturn.put(RedisBigTableKey.inflate(ent.getKey()), ent.getValue()); } return toReturn; } else { throw new RedisForemanException(MessageFactory.objective("Grab all entries").issue("Table does not exist").objects(new String(table))); } }
2
@Override public String getToolTipText(MouseEvent event, Rectangle bounds, Row row, Column column) { if (getPreferredWidth(row, column) - H_MARGIN > column.getWidth() - row.getOwner().getIndentWidth(row, column)) { return getData(row, column, true); } return null; }
1
public CycSymbol getIntermediateStepValidationLevel() { Object rawValue = get(INTERMEDIATE_STEP_VALIDATION_LEVEL); if (rawValue instanceof CycSymbol) { return (CycSymbol) rawValue; } else { rawValue = getDefaultInferenceParameterDescriptions().getDefaultInferenceParameters().get(INTERMEDIATE_STEP_VALIDATION_LEVEL); return (rawValue instanceof CycSymbol) ? (CycSymbol) rawValue : CycObjectFactory.nil; } }
2
private static void postProcessConfig() { createDirAtHome(); normalizeVariableContent("UrbanoSHPPath"); normalizeVariableContent("RusticoSHPPath"); try { CatExtractor.extract(Config.get("UrbanoSHPPath")); CatExtractor.extract(Config.get("RusticoSHPPath")); } catch (IOException ioe){ ioe.printStackTrace(); } String proyeccion = configuration.getProperty("Proyeccion", ""); String directorio = Config.get("UrbanoSHPPath"); if (StringUtils.isBlank(directorio)){ directorio = Config.get("RusticoSHPPath"); } if (!StringUtils.isBlank(directorio) && (StringUtils.isBlank(proyeccion) || "auto".equals(proyeccion))){ configuration.setProperty( "Proyeccion", CatProjectionReader.autodetectProjection(directorio) ); } configureGrid(); }
5
public int binarySearchPredictable(T[] a, int from, int limit, T query, BSTYPE type) { if (from >= limit) { return from; } int mid = (from + limit) / 2; int compared = comparator == null ? query.compareTo(a[mid]) : comparator.compare(query, a[mid]); if (compared == 0 && type == BSTYPE.LEFTMOST || compared < 0) { return binarySearchPredictable(a, from, mid, query, type); } if (compared == 0 && type == BSTYPE.RIGHTMOST || compared > 0) { return binarySearchPredictable(a, mid + 1, limit, query, type); } // compared == 0 && type == BSTYPE.FAST return mid; }
8
public void initTableau() { tableau = new ArrayList<>(); for(int i=0 ; i<256 ; i++) tableau.add(i); }
1
private void jButtonSourceNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSourceNextActionPerformed try{ MultiSyntaxDocument syntax = new MultiSyntaxDocument(); if(sourceCurrentPosition==(sourceMatchOffsets.length-1)){ JOptionPane optionPane = new JOptionPane(); int selection = optionPane.showConfirmDialog(this, "Reached end of file, continue from begining?", "Continue Search?",JOptionPane.YES_NO_OPTION); if(selection == 0){ //remove previous highlighting syntax.setSearchHighlighting(sourceDoc, sourceMatchOffsets[sourceCurrentPosition][0], sourceMatchOffsets[sourceCurrentPosition][1]); //set new highlighting sourceCurrentPosition = 0; jTextPaneSource.setCaretPosition(0);//reset the textPane jTextPaneSource.setCaretPosition(sourceMatchOffsets[sourceCurrentPosition][0]); syntax.setSelectedSearchHighlighting(sourceDoc, sourceMatchOffsets[sourceCurrentPosition][0], sourceMatchOffsets[sourceCurrentPosition][1]); } return; } //remove previous highlighting syntax.setSearchHighlighting(sourceDoc, sourceMatchOffsets[sourceCurrentPosition][0], sourceMatchOffsets[sourceCurrentPosition][1]); //set new highlighting ++sourceCurrentPosition; jTextPaneSource.setCaretPosition(0);//reset the textPane jTextPaneSource.setCaretPosition(sourceMatchOffsets[sourceCurrentPosition][0]); syntax.setSelectedSearchHighlighting(sourceDoc, sourceMatchOffsets[sourceCurrentPosition][0], sourceMatchOffsets[sourceCurrentPosition][1]); }//end try catch(Exception x){ JOptionPane.showMessageDialog(this, "Error: " + x, "Applet Error", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_jButtonSourceNextActionPerformed
3
public static int doSevenLoop(Deck deck, PlayerHuman playerHuman, PlayerCPU playerCPU, int plCount) { Card card; int n = 2; // number of cards will be pulled int cp; // current player while (true) { cp = plCount % 2; if (cp == 0) card = playerCPU.chooseSeven(); else card = playerHuman.chooseSeven(); if (card == null) { break; } else { deck.setDowncard(card); n += 2; } plCount++; } cp = (plCount + 1) % 2; if (cp == 0) { System.out.printf("CPU played a 7. You pull %d cards.%n", n); } else { System.out.print("\nYou played a 7. "); System.out.printf("CPU will pull %d cards.%n", n); } for (int i = 0; i < n; i++) { if (cp == 0) playerHuman.cards.add(deck.dealOneCard( playerHuman, playerCPU)); else playerCPU.cards.add(deck.dealOneCard( playerHuman, playerCPU)); } return n; }
6
public static void countWithStateless() throws NamingException, InterruptedException { int i, lostTimes = 0; long threadId = Thread.currentThread().getId(); RemoteSLSB slb = lookupRemoteSLSB(); boolean lost = false; System.out.println(threadId + ": Obtained a remote stateless bean for invocation."); long time = System.nanoTime(); for (i = 1; i <= Variables.repeat; i++) { try { slb.getMessage(); } catch (Exception ex) { System.out.println("Exception " + ex.getClass().getCanonicalName() + " was thrown. Call to stateless bean was unsuccessful."); lost = true; lostTimes++; } if (Variables.verbose) { System.out.println(threadId + ": " + i); } while (lost) { if (Variables.verbose) { System.out.println("Retrying call to stateless bean."); } try { slb.getMessage(); } catch (Exception ex) { System.out.println("Exception " + ex.getClass().getCanonicalName() + " was thrown. Call to stateless bean was unsuccessful."); continue; } lost = false; Thread.sleep(100); } Thread.sleep(Variables.sleep); } time = System.nanoTime() - time; System.out.println(threadId + ": Number of stateless invocations: " + (i - 1) + ", elapsed time: " + ((double) time / 1000000000.0) + " seconds. Calls were lost " + lostTimes + " times."); }
6
public static boolean getChoice () { String message = ""; boolean chosen = false; Scanner sc = new Scanner (System.in); boolean inputOK = false; while (! inputOK) { String choice = sc.nextLine(); choice = choice.toUpperCase(); if (choice != null) { if ( choice.equals("Y") || choice.equals("N")) { inputOK = true; if (choice.equals("Y")) { chosen = true; } } else { message = "ongeldige ingave (Y/y of N/n)"; } } else { message = "niets ingegeven"; } if (! message.isEmpty()) { System.out.println(message); } } return chosen; }
6
public void drawEdges(Graphics2D g, Edge[] edges) { if (edges == null) return; for (Edge e : edges) { if (e != null) g.drawLine(e.from.x, e.from.y, e.to.x, e.to.y); } }
3
private static void test2_1() throws FileNotFoundException { String test1 = "new game\n"+"examine cell key\n"+"quit\n"+"yes\n"; HashMap<Integer, String> output = new HashMap<Integer, String>(); boolean passed = true; try { in = new ByteArrayInputStream(test1.getBytes()); System.setIn(in); out = new PrintStream("testing.txt"); System.setOut(out); Game.main(null); } catch (ExitException se) { } catch (Exception e) { System.setOut(stdout); System.out.println("Error: "); e.printStackTrace(); passed = false; } finally { System.setOut(stdout); @SuppressWarnings("resource") Scanner sc = new Scanner(new File("testing.txt")); ArrayList<String> testOutput = new ArrayList<String>(); while (sc.hasNextLine()) { testOutput.add(sc.nextLine()); } output.put(testOutput.size() - 4, ">> You can't find a cell key."); output.put(testOutput.size() - 3, "The guard walks toward your cell."); output.put(testOutput.size() - 2, ">> Are you sure you want to quit? (y/n)"); output.put(testOutput.size() - 1, ">>"); if (passed) { for (Map.Entry<Integer, String> entry : output.entrySet()) { if (!testOutput.get(entry.getKey()) .equals(entry.getValue())) { passed = false; System.out.println("test2_1 failed: Line " + entry.getKey()); System.out.println("\tExpected: " + entry.getValue()); System.out.println("\tReceived: " + testOutput.get(entry.getKey())); } } if (passed) { System.out.println("test2_1 passed"); } } else { System.out.println("test2_1 failed: error"); } } }
7
private static void inputCustomerChoice() { if (scanner.hasNext()) { beverageChoice = scanner.nextLine(); } }
1
public boolean equals(Object other) { if ( (this == other ) ) return true; if ( (other == null ) ) return false; if ( !(other instanceof TrabajaderaId) ) return false; TrabajaderaId castOther = ( TrabajaderaId ) other; return (this.getIdtrabajadera()==castOther.getIdtrabajadera()) && (this.getIdpaso()==castOther.getIdpaso()); }
4
public void setInOut(String[] command) { int id = Integer.parseInt(command[0]); boolean bool = Boolean.parseBoolean(command[1]); for (int i = 0; i < entradas.getLength(); i++) { Entrada entrada = entradas.get(i); if (entrada.equals(id)) entrada.change(bool); } check(); }
2
public static Right get(String value) throws IllegalArgumentException { if (value.equalsIgnoreCase("read")) { return read; } else if (value.equalsIgnoreCase("write")) { return write; } else if (value.equalsIgnoreCase("exec")) { return exec; } else if (value.equalsIgnoreCase("inherit")) { return inherit; } else { throw new IllegalArgumentException("Right not supported"); } }
4
protected void showContent(String name) { toolBarName = ""; TitledBorder nameBorder = BorderFactory.createTitledBorder( name); MainView.contentPanel.setBorder(nameBorder); mainView.getCardLayout().show(mainView.getContentPanel(), name); // refresh visible card panel JPanel card = null; for (Component comp : mainView.getContentPanel().getComponents()) { if (comp.isVisible() == true) { card = (JPanel) comp; card.repaint(); } if(comp instanceof CategoryView) { ((CategoryView)comp).refreshCategoryTable(); } if(comp instanceof MemberView) { ((MemberView)comp).refreshMemberTable(); } if(comp instanceof ProductView) { ((ProductView)comp).refreshProductTable(); } if(comp instanceof DiscountView) { ((DiscountView)comp).refreshDiscountTable(); } if(comp instanceof VendorView) { ((VendorView)comp).refreshVendorTable(); } if(comp instanceof PurchaseOrderView) { ((PurchaseOrderView)comp).refreshPurchaseOrderTable(); } } /** * @author sakthi */ if (name.equals(Utility.getPropertyValue(Constants.logout))) { LoginPopupView.userNameTxtField.setText(""); LoginPopupView.passwordField.setText(""); label.setText(""); label.setVisible(false); toolBarName = Utility.getPropertyValue(Constants.logout); getToolbarName(); LoginPopupView.showLoginDialog(mainView); } }
9
public static void main(String[] args) { final int length = 10; int intArray[] = new int[length]; Random generator; generator = new Random(); for (int i = 0; i < intArray.length; i++) { intArray[i] = generator.nextInt(9) + 1; } System.out.print("Original array : "); ShowArray(intArray); for (int i = 0; i < intArray.length; i++) { //BubbleSort for (int j = 1; j < intArray.length - i; j++) { if (intArray[j - 1] > intArray[j]) { int help = intArray[j - 1]; intArray[j - 1] = intArray[j]; intArray[j] = help; } } } System.out.print("Sorted array : "); ShowArray(intArray); }
4
public void clickChooseCharacters(Scanner scanchoice, ArrayList<MainMenuHeroSlot> heroies) { state.clickChooseCharacters(scanchoice, heroies); }
0
public Object next() { Object o = null; // Block if the Queue is empty. synchronized (_queue) { if (_queue.size() == 0) { try { _queue.wait(); } catch (InterruptedException e) { return null; } } // Return the Object. try { o = _queue.firstElement(); _queue.removeElementAt(0); } catch (ArrayIndexOutOfBoundsException e) { throw new InternalError("Race hazard in Queue object."); } } return o; }
3
public static void decompressFile(String input, String output){ byte[] data = new byte[0];//All the bytes from the input //Read the input try{ data = Files.readAllBytes(Paths.get(input)); }catch(Exception e){ e.printStackTrace(); } ArrayList<Character> unique = new ArrayList<Character>();//Local unique character list MapList<Character, Integer> frequencies = new MapList<Character, Integer>();//Local frequency map int i;//need indexing for later //Create the frequency map for(i = 0; i < data.length; i+= 5){ int freq = data[i+1] + data[i+2] + data[i+3] + data[i+4]; if(freq == 0) break;//If reach a frequency of zero, we know this character does not exist so this is the end of header frequencies.put((char) data[i], freq); unique.add((char)data[i]); } i+=5;//Shift the index to the start of the code translate = buildTrie(frequencies, unique);//Create the Huffman Trie StringBuilder sb = new StringBuilder();//StringBuilder for the binary representation int a; for(; i<data.length; i++){ a = data[i] & 0xFF;//Fixes negative integers to be representable as a byte String binaryString = Integer.toBinaryString(a); StringBuilder binaryStringBuilder = new StringBuilder(binaryString);//Builder for byte length //Extends ensures that the binary String is 8 bits long while(binaryStringBuilder.length() < 8){ binaryStringBuilder.insert(0, '0'); } sb.append(binaryStringBuilder.toString()); } char[] decypher = sb.toString().toCharArray();//Character array of all the bits Node temp = root;//Temporary Node for traversal StringBuilder result = new StringBuilder();//String builder for the final result for(int j = 0; j < decypher.length; j++){ temp = temp.traverse(Integer.parseInt(decypher[j] + ""));//Traverse either 1 or 0 //If we are at a leaf then this is a character and we reset the pointer to the root if(temp instanceof Leaf){ result.append(((Leaf) temp).getChar()); temp = root; } } //Write the translation to the file try{ FileWriter fw = new FileWriter(output); fw.write(result.toString()); fw.close(); System.out.println(input + " was decompressed successfully!"); }catch(Exception e){ System.out.println(input + " was decompressed unsuccessfully!"); } }
8
@Test public void testSubClauses() throws Exception { PersistenceManager pm = new PersistenceManager(driver,database,login,password); ConnectionWrapper cw = pm.getConnectionWrapper(); //add data with two sortable fields for(int x = 0;x<100;x++) { long dec = x/10; double rem = x%10; SimpleObject so = new SimpleObject(); so.setAge(dec); so.setScale(rem); pm.saveObject(cw,so); } cw.commitAndDiscard(); SimpleObject sortAge=new SimpleObject(); sortAge.setAge(1l); SimpleObject sortScale=new SimpleObject(); sortScale.setScale(1.0); List<SimpleObject> list = pm.getObjects(SimpleObject.class,new All(),new Order(new Ascending(sortAge),new Descending(sortScale))); for(int x = 0;x<list.size()-1;x++) { SimpleObject curr = list.get(x); SimpleObject next = list.get(x+1); if(curr.getAge().longValue()==next.getAge().longValue()) { //we sorted scale descending assertTrue(curr.getScale()>next.getScale()); } else { //we sorted age ascending assertEquals((long)curr.getAge()+1,(long)next.getAge()); assertEquals((double)curr.getScale()+9,(double)next.getScale(),0.00001); } } list = pm.getObjects(SimpleObject.class,new All(),new Order(new Ascending(sortAge),new Ascending(sortScale))); for(int x = 0;x<list.size()-1;x++) { SimpleObject curr = list.get(x); SimpleObject next = list.get(x+1); if(curr.getAge().longValue()==next.getAge().longValue()) { //we sorted scale descending assertTrue(curr.getScale()<next.getScale()); } else { //we sorted age ascending assertEquals((long)curr.getAge()+1,(long)next.getAge()); assertEquals((double)curr.getScale()-9,(double)next.getScale(),0.00001); } } pm.close(); }
5
@Override public void input( float delta ) { Vector2f centerPosition = new Vector2f( Window.getWidth() / 2, Window.getHeight() / 2 ); if ( Input.getKey( unlockMouseKey ) ) { Input.setCursor( true ); mouseLocked = false; } if ( Input.getMouseDown( 0 ) ) { Input.setMousePosition( centerPosition ); Input.setCursor( false ); mouseLocked = true; } if ( mouseLocked ) { Vector2f deltaPos = Input.getMousePosition().sub( centerPosition ); boolean rotY = deltaPos.getX() != 0; boolean rotX = deltaPos.getY() != 0; if ( rotY ) getTransform().rotate( yAxis, (float) Math.toRadians( deltaPos.getX() * sensitivity ) ); if ( rotX ) getTransform().rotate( getTransform().getRot().getRight(), (float) Math.toRadians( -deltaPos.getY() * sensitivity ) ); if ( rotY || rotX ) Input.setMousePosition( centerPosition ); } }
7
private void toggleRemoveSelection(TreePath path){ Stack<TreePath> stack = new Stack<TreePath>(); TreePath parent = path.getParentPath(); while(parent!=null && !isPathSelected(parent)){ stack.push(parent); parent = parent.getParentPath(); } if(parent!=null) stack.push(parent); else{ _removeSelectionPath(path); return; } while(!stack.isEmpty()){ TreePath temp = (TreePath)stack.pop(); TreePath peekPath = stack.isEmpty() ? path : (TreePath)stack.peek(); Object node = temp.getLastPathComponent(); Object peekNode = peekPath.getLastPathComponent(); int childCount = model.getChildCount(node); for(int i = 0; i<childCount; i++){ Object childNode = model.getChild(node, i); if(childNode!=peekNode) super.addSelectionPaths(new TreePath[]{temp.pathByAddingChild(childNode)}); } } super.removeSelectionPaths(new TreePath[]{parent}); }
7
public static void main(String[] args) throws Exception { Document document = new Document(); //同时修改多个变量 Alt + shift + r Element root = new Element("学生手册"); document.addContent(root); Attribute attr = new Attribute("班级","2"); Element student = new Element("学生").setAttribute("学号", "1").setAttribute(attr); Comment comment = new Comment("这是学生手册的XML"); root.addContent(comment); //方法链的编程风格, 可以set后返回的是对象本身 可以实现多次set root.addContent(student); student.addContent(new Element("姓名").setText("张三")).addContent(new Element("性别").setText("女")) .addContent(new Element("地址").setText("北京市海淀区")).addContent(new Element("年龄").setText("20")); //XMl输出格式的控制 Format format = Format.getPrettyFormat(); format.setEncoding("gbk"); //输入到文件 XMLOutputter out = new XMLOutputter(); out.setFormat(format); out.output(document, new FileOutputStream("jdom.xml")); //out.output(document, new FileWriter("jdom.xml")); }
0
static public jlp createInstance(String[] args) { jlp player = new jlp(); if (!player.parseArgs(args)) player = null; return player; }
1
private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, org.codehaus.classworlds.ClassRealm containerRealm) throws ComponentConfigurationException { Set<String> runtimeClasspathElements = new HashSet<String>(); try { runtimeClasspathElements.addAll((List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}")); } catch (ExpressionEvaluationException e) { throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e); } Collection<URL> urls = buildURLs(runtimeClasspathElements); urls.addAll(buildAritfactDependencies(expressionEvaluator)); for (URL url : urls) { containerRealm.addConstituent(url); } }
2
public int largestRectangleArea(int[] height) { int len = height.length; if( len <= 0){ return 0; } if( len == 1){ return height[0]; } Comparator<Integer> OrderIsdn = new Comparator<Integer>(){ public int compare(Integer o1, Integer o2) { int numbera = o1.intValue(); int numberb = o2.intValue(); if(numberb > numbera) { return -1; } else if(numberb<numbera) { return 1; } else { return 0; } } }; Queue<Integer> q = new PriorityQueue<Integer>(len,OrderIsdn); for(int i=0;i<len;i++){ q.add(i); } int min_level=0; int tmp_area = 0; int max_area = 0; for(int i=0;i<len;i++){ if( height[i] > max_area){ max_area = height[i]; } for(int j=i;j<len;j++){ min_level = height[j]; } } return max_area; }
8
public NoClaimReason canClaimForSettlementReason(Tile tile) { int price; NoClaimReason reason = canOwnTileReason(tile); return (reason != NoClaimReason.NONE) ? reason : (tile.getSettlement() != null) ? NoClaimReason.SETTLEMENT : (tile.getOwner() == null) ? NoClaimReason.NONE : (tile.getOwner() == this) ? ((tile.isInUse()) ? NoClaimReason.WORKED : NoClaimReason.NONE) : ((price = getLandPrice(tile)) < 0) ? NoClaimReason.EUROPEANS : (price > 0) ? NoClaimReason.NATIVES : NoClaimReason.NONE; }
7
public void shift(Direction direction, int i) { switch (direction) { case UP: pos1 = pos1.addY(-1); pos2 = pos2.addY(-1); break; case DOWN: pos1 = pos1.addY(1); pos2 = pos2.addY(1); break; case LEFT: pos1 = pos1.addX(-1); pos2 = pos2.addX(-1); break; case RIGHT: pos1 = pos1.addX(1); pos2 = pos2.addX(1); break; } }
4
public final void switchStmt() throws RecognitionException { AST ast1 = null, ast2 = null; try { // CPP.g:415:3: ( 'switch' '(' expr ')' stmt ) // CPP.g:415:5: 'switch' '(' expr ')' stmt { this.match(this.input, 50, FOLLOW_50_in_switchStmt1678); if (this.state.failed) { return; } this.match(this.input, 42, FOLLOW_42_in_switchStmt1684); if (this.state.failed) { return; } this.pushFollow(FOLLOW_expr_in_switchStmt1690); this.expr(); this.state._fsp--; if (this.state.failed) { return; } if (this.state.backtracking == 0) { ast1 = this.out; this.out = null; } this.match(this.input, 43, FOLLOW_43_in_switchStmt1698); if (this.state.failed) { return; } this.pushFollow(FOLLOW_stmt_in_switchStmt1704); this.stmt(); this.state._fsp--; if (this.state.failed) { return; } if (this.state.backtracking == 0) { ast2 = this.out; this.out = null; } if (this.state.backtracking == 0) { this.out = new SwitchStmtAST((ExprAST) ast1, (OneStmtAST) ast2); } } } catch (RecognitionException re) { this.reportError(re); this.recover(this.input, re); } finally { } return; }
9