text
stringlengths
14
410k
label
int32
0
9
public void use(ArrayList<Choice> choices, Game game) { Player p = game.getCurrentPlayer(); boolean found = false; for (int i = 0; i < p.hand.size(); i++) { if (p.hand.get(i) instanceof Wound && !found) { p.hand.remove(i); this.draw += 1; for (int j = 0; j < game.getOpponents().size(); j++) { Player opp = (Player) game.getOpponentsObj().get(j); opp.gemPile[0]++; } found = true; } } if (!found) { for (int i = 0; i < p.discard.size(); i++) { if (p.discard.get(i) instanceof Wound && !found) { p.discard.remove(i); this.draw += 1; for (int j = 0; j < game.getOpponents().size(); j++) { Player opp = (Player) game.getOpponentsObj().get(j); opp.gemPile[0]++; } found = true; } } } super.use(choices, game); found = false; }
9
public void addID(MusicObject obj) { if (!this.duplicateID.containsKey(obj.getUid())) { duplicateID.put(obj.getUid(), obj); } }
1
public void update(){ if (life.isOver()){ dead = true; } }
1
public NoInterference() { super(false); if(firstTime && Configuration.interference && Configuration.showOptimizationHints) { Main.warning("At least some nodes use the 'NoInterference' interfernce model. " + "If you do not consider interference at all in your project, you can " + "considerably improve performance by turning off interference in the " + "XML configuration file." ); firstTime = false; // important to only have one message. } }
3
@Test public void string_test() { try{ double []vec1= {1.0,2.0}; String result= Vector.toString(vec1); String expected=" 1.0\n 2.0\n"; Assert.assertEquals(result,expected); } catch (Exception e) { // TODO Auto-generated catch block fail("Not yet implemented"); } }
1
public void onDisable() { if (abm != null) { abm.setGo(false); } if (fc != null) { fc.setGo(false); } if (pg != null) { pg.setGo(false); } if (ss != null) { ss.setGo(false); } log.info(name + "DISABLED!"); }
4
@Override public void onStringInput(String input) { System.out.println("Your name is: " + input); }
0
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Customer customer = (Customer) o; if (zip != customer.zip) return false; if (city != null ? !city.equals(customer.city) : customer.city != null) return false; if (!name.equals(customer.name)) return false; if (!street.equals(customer.street)) return false; if (!surname.equals(customer.surname)) return false; return true; }
9
private static int extractReminder(int number, int divisor, ArrayList<Integer> resultByDigits, ArrayList<String> pseudographics) { int integerDivision; int reminder; int subtrahend; integerDivision = number / divisor; resultByDigits.add(integerDivision); subtrahend = integerDivision * divisor; pseudographics.add(" " + subtrahend); reminder = number - subtrahend; pseudographics.add(" " + signPerDigits(howMuchDigits(subtrahend), "¯")); return reminder; }
0
private Method findMethod(Object base, String name, Class<?>[] types, int paramCount) { if (types != null) { try { return findAccessibleMethod(base.getClass().getMethod(name, types)); } catch (NoSuchMethodException e) { return null; } } Method varArgsMethod = null; for (Method method : base.getClass().getMethods()) { if (method.getName().equals(name)) { int formalParamCount = method.getParameterTypes().length; if (method.isVarArgs() && paramCount >= formalParamCount - 1) { varArgsMethod = method; } else if (paramCount == formalParamCount) { return findAccessibleMethod(method); } } } return varArgsMethod == null ? null : findAccessibleMethod(varArgsMethod); }
9
protected void updateCapabilitiesFilter(Capabilities filter) { Instances tempInst; Capabilities filterClass; if (filter == null) { m_ClustererEditor.setCapabilitiesFilter(new Capabilities(null)); return; } if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) tempInst = new Instances(m_Instances, 0); else tempInst = new Instances(m_Instances); tempInst.setClassIndex(-1); try { filterClass = Capabilities.forInstances(tempInst); } catch (Exception e) { filterClass = new Capabilities(null); } m_ClustererEditor.setCapabilitiesFilter(filterClass); // check capabilities m_StartBut.setEnabled(true); Capabilities currentFilter = m_ClustererEditor.getCapabilitiesFilter(); Clusterer clusterer = (Clusterer) m_ClustererEditor.getValue(); Capabilities currentSchemeCapabilities = null; if (clusterer != null && currentFilter != null && (clusterer instanceof CapabilitiesHandler)) { currentSchemeCapabilities = ((CapabilitiesHandler)clusterer).getCapabilities(); if (!currentSchemeCapabilities.supportsMaybe(currentFilter) && !currentSchemeCapabilities.supports(currentFilter)) { m_StartBut.setEnabled(false); } } }
8
@RequestMapping(value = "addTask", method = RequestMethod.POST) public @ResponseBody TodoTask addTask(@RequestParam String title, @RequestParam String content, @RequestParam String targetTime, @RequestParam Integer priority, @RequestParam Integer list, WebRequest webRequest) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication.isAuthenticated() && (authentication.getPrincipal() instanceof User)) { TodoTask task = new TodoTask(); TodoList todoList = todoListsDAO.findListById(list); if (todoList == null) return null; TodoUser todoUser = (TodoUser) webRequest.getAttribute("user", WebRequest.SCOPE_SESSION); task.setAuthor(todoUser); task.setList(todoList); if (todoList.getAuthor().getId().intValue() != todoUser.getId().intValue() && !"ROLE_ADMIN".equals(todoUser.getRole()) && todoList.getPubStatus() != TodoList.STATUS_PUBLIC_EDIT) return null; try { Date target = TodoController.DATE_FORMAT.parse(targetTime); task.setTargetTime(target); } catch (ParseException ex) { return null; } task.setTitle(title); task.setContent(content); task.setPriority(priority); todoTasksDAO.addTask(task); return task; } return null; }
7
private boolean vaikuttaaOlevanOikeassaMestassa() { Tetrimino aave = aavetetrimino.tetrimino(); ArrayList<Palikka> palikat = new ArrayList<Palikka>( tetrimino.palikkakokoelma().palikat() ); Iterator<Palikka> alkuperaisesta = palikat.iterator(); for(Palikka aaveesta : aave.palikkakokoelma().palikat()) while(alkuperaisesta.hasNext()) { Palikka alkuperainen = alkuperaisesta.next(); if(alkuperainen.sijainti().x() == aaveesta.sijainti().x() && alkuperainen.sijainti().y() <= aaveesta.sijainti().y()) { alkuperaisesta.remove(); break; } } return palikat.isEmpty(); }
4
@Override public void service(AgiRequest request, AgiChannel channel) throws AgiException { try { // Answer the channel... this.answer(); // retrieve a non-existent filename String fileName; int name; do { name = Math.abs(this.random.nextInt()); fileName = EPursuit.properties.getProperty("recordPath") + name; } while (new File(fileName).exists()); // Call all listeners for (AgiCallListener listener : this.listeners) { listener.callStarted(String.valueOf(name)); } // ...play the introduction... this.streamFile(EPursuit.properties.getProperty("mrxIntro")); // ..record the file. this.recordFile(fileName, "gsm", "brauchkeinschwein", new Integer(EPursuit.properties.getProperty("maxTalkTime")), 0, new Boolean(EPursuit.properties.getProperty("beep")), new Integer(EPursuit.properties.getProperty("maxWaitTime"))); this.recordMap.put(channel.getName(), String.valueOf(name)); // Call all listeners for (AgiCallListener listener : this.listeners) { listener.callFinished(channel.getName()); } } catch (AgiHangupException e) { for (AgiCallListener listener : this.listeners) { listener.callNotSuccessful(channel.getName()); } } }
5
private boolean isInheritable(int mod, CtClass superclazz) { if (Modifier.isPrivate(mod)) return false; if (Modifier.isPackage(mod)) { String pname = getPackageName(); String pname2 = superclazz.getPackageName(); if (pname == null) return pname2 == null; else pname.equals(pname2); } return true; }
3
public void run() { while (r != null && !this.isInterrupted()) { try { StringBuilder sb = new StringBuilder(); String pac = r.readUTF(); if (pac != null && pac.startsWith("pac")) { sb.append(pac); if (!pac.endsWith("ket")) { String stack; do { stack = r.readUTF(); sb.append(stack); } while (!stack.endsWith("ket")); } String data = sb.toString(); String json = data.substring(3, data.length() -3); Packet packet = gson.fromJson(json, Packet.registry.getPacketClass(json)); OpenCraft.log.debug(data); pr.emit(packet); } } catch (IOException e) { OpenCraft.log.debug("Client connection closed"); this.pr.emit(new PacketPartServer("Connection closed")); this.interrupt(); } } }
7
private String getTerm(ActivityType activity) { switch(activity) { case BREAK: return termBreak; case PLACE: return termPlace; case TRAVEL: return termTravel; case CHAT: return termChat; case ANIMAL: return termAnimal; case MONSTER: return termMonster; case PLAYER: return termPlayer; } return termActivity; }
7
private static int hexValue(char c) { if ((c >= '0') && (c <= '9')) return (int) (c - '0'); if ((c >= 'A') && (c <= 'F')) return ((int) (c - 'A')) + 0x0A; throw new NumberFormatException(); }
4
@SuppressWarnings("unchecked") public static void writeLinesSorted(String file, ArrayList<?> uniWordMap, ArrayList<?> uniWordMapCounts, int flag) { // flag = 0 decreasing order otherwise increasing HashMap map = new HashMap(); if (uniWordMap.size() != uniWordMapCounts.size()) { System.err.println("Array sizes are not equal!!! Function returned."); } else { for (int i = 0; i < uniWordMap.size(); i++) { map.put(uniWordMap.get(i), uniWordMapCounts.get(i)); } map = (HashMap<String, Integer>) ComUtil.sortByValue(map, flag); writeLines(file, map); map.clear(); } }
4
private void renderItemList() { for (int i = 0; i < items.size(); i++) renderItemOption(i, items.get(i), new Position(10, 50 + (i * 60))); }
1
public String getNthSegment(int n){ if(n == 0){ return operator; } else if(segments.size() < n){ return null; } else { return segments.get(n-1); } }
2
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Frm_CadParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Frm_CadParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Frm_CadParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Frm_CadParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Frm_CadParcela().setVisible(true); } }); }
6
public static void cantPlace(String place) { System.out.printf("\"%s\"には置けません!\n", place); }
0
public void setBranchLeaderList(final List<BranchLeader> branchLeaderList) { this.branchLeaderList = branchLeaderList; }
0
public void testConstructor_int_int_int_int_int_int_int() throws Throwable { LocalDateTime test = new LocalDateTime(2005, 6, 9, 10, 20, 30, 40); assertEquals(ISO_UTC, test.getChronology()); assertEquals(2005, test.getYear()); assertEquals(6, test.getMonthOfYear()); assertEquals(9, test.getDayOfMonth()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(40, test.getMillisOfSecond()); try { new LocalDateTime(Integer.MIN_VALUE, 6, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(Integer.MAX_VALUE, 6, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 0, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 13, 9, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 0, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} try { new LocalDateTime(2005, 6, 31, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} new LocalDateTime(2005, 7, 31, 10, 20, 30, 40); try { new LocalDateTime(2005, 7, 32, 10, 20, 30, 40); fail(); } catch (IllegalArgumentException ex) {} }
7
public String[] getAvailableStyle() { if (fontList != null) { String[] availableStyles = new String[fontList.size()]; Iterator nameIterator = fontList.iterator(); Object[] fontData; int decorations; String style = ""; for (int i = 0; nameIterator.hasNext(); i++) { fontData = (Object[]) nameIterator.next(); decorations = (Integer) fontData[2]; if ((decorations & BOLD_ITALIC) == BOLD_ITALIC) { style += " BoldItalic"; } else if ((decorations & BOLD) == BOLD) { style += " Bold"; } else if ((decorations & ITALIC) == ITALIC) { style += " Italic"; } else if ((decorations & PLAIN) == PLAIN) { style += " Plain"; } availableStyles[i] = style; style = ""; } return availableStyles; } return null; }
6
public Node(String data){ this.data = data; }
0
public final void setWrapWidth(double wrapWidth) { this.wrapWidth.set(wrapWidth); }
0
public String getDescription() { return description; }
0
public int reverse(int x) { int abs = x < 0 ? -x : x; long result = 0; while (abs > 0) { result = result * 10 + abs % 10; abs = abs / 10; } result = x < 0 ? result * -1 : result; if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) { return 0; } return (int) result; }
5
private void showBoard(boolean activate) { for (int row = 0; row < 8; row++) for (int column = 0; column < 8; column++){ Position position = new Position(row,column); if (board.isEmpty(position)) add(new EmptyTile((row+column)%2==0 ? Board.BLACK : Board.WHITE)); else if(board.isMarker(position)) addMarker(new MarkerTile(board.getMarker(position).getRelatedPlay())); else addPiece(new BusyTile( board.getPiece(position)),position,activate); } }
5
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // If the NamespaceManager state is already set up from the // context of the task creator the current namespace will not // be null. It's important to check that the current namespace // has not been set before setting it for this request. if (NamespaceManager.get() == null) { switch (strategy) { case SERVER_NAME : { NamespaceManager.set(request.getServerName()); break; } case GOOGLE_APPS_DOMAIN : { NamespaceManager.set(NamespaceManager.getGoogleAppsNamespace()); break; } case EMPTY : { NamespaceManager.set(""); } } } // chain into the next request chain.doFilter(request, response) ; }
4
@Override public void run() { int fillPerLoop = 256; for (int i=0; i<BUFFER_LENGTH; i+=fillPerLoop) { mInput.read(backupBuffer, i, fillPerLoop); } double[] temp = new double[BUFFER_LENGTH]; for (int i=0; i<BUFFER_LENGTH; i++) { temp[i] = backupBuffer[i]; } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] transformed = fft.transform(temp, TransformType.FORWARD); for (int i=0; i<BUFFER_LENGTH; i++) { double energy = transformed[i].abs(); if (energy < 20000 || i > 2000 || i < 30) { transformed[i] = new Complex(0); } } Complex[] inverted = fft.transform(transformed, TransformType.INVERSE); for (int i=0; i<BUFFER_LENGTH; i++) { backupBuffer[i] = (int) inverted[i].getReal(); } backupReady = true; unblock(); }
7
public Gui(){ picLabel=new JLabel(new ImageIcon("img/bg.jpg")); this.add(picLabel); picLabel.setLayout(new GridBagLayout()); loginPanel = new JPanel(new GridBagLayout()); loginPanel.setPreferredSize(new java.awt.Dimension(800, 600)); GridBagConstraints c = new GridBagConstraints(); if (shouldFill){ c.fill=GridBagConstraints.HORIZONTAL; } JLabel username; username = new JLabel("Username:"); username.setFont(new Font("Comic Sans",Font.BOLD, 14)); c.fill=GridBagConstraints.HORIZONTAL; c.gridx=0; c.insets= new Insets(0,20,0,20); c.gridy=0; picLabel.add(username,c); JLabel password; password = new JLabel("Password:"); password.setFont(new Font("Comic Sans",Font.BOLD, 14)); c.fill=GridBagConstraints.HORIZONTAL; c.gridx=0; c.insets= new Insets(0,20,0,20); c.gridy=1; picLabel.add(password, c); loginPanel.setBackground(Color.gray); userField =new JTextField("manager",15); c.fill=GridBagConstraints.HORIZONTAL; c.gridx=1; c.insets= new Insets(0,0,0,0); c.gridy=0; picLabel.add(userField, c); passField =new JPasswordField("manager",10); c.fill=GridBagConstraints.HORIZONTAL; c.gridx=1; c.gridy=1; picLabel.add(passField, c); //Hey it's Kenny, I have no clue what you want with this warning so I just put it under the Login button for now //Right now I just made it say warning so you can see where it'll be on the login page //Change it however you like // warning = new JLabel(" "); password.setFont(new Font("Comic Sans",Font.BOLD, 14)); c.fill=GridBagConstraints.HORIZONTAL; c.insets= new Insets(0,0,0,0); c.gridx=0; c.gridy=5; c.gridwidth=2; picLabel.add(warning, c); warning.setForeground(Color.red); login = new JButton("Login"); login.setFont(new Font("Comic Sans",Font.BOLD, 16)); c.fill=GridBagConstraints.HORIZONTAL; c.ipady=20; c.insets= new Insets(10,0,0,0); c.gridwidth=2; c.gridx=0; c.gridy=3; picLabel.add(login,c); exit = new JButton ("Exit"); exit.setFont(new Font("Comic Sans",Font.BOLD, 16)); c.gridx=0; c.gridy=4; c.anchor=GridBagConstraints.LAST_LINE_END; picLabel.add(exit,c); login.addActionListener(this); exit.addActionListener(this); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setPreferredSize(new Dimension(1280, 800)); pack(); setVisible(true); }
1
@EventHandler public void onTagApi(PlayerReceiveNameTagEvent event){ Player player = event.getNamedPlayer(); String[] groups = ApiLayer.getGroups("world", CalculableType.USER, player.getName()); if(groups.length == 0){ return; } if(groups[0].equalsIgnoreCase("New")){ return; }else if(groups[0].equalsIgnoreCase("Member")){ event.setTag(ChatColor.DARK_PURPLE + player.getName()); }else if(groups[0].equalsIgnoreCase("VIP")){ event.setTag(ChatColor.GOLD + player.getName()); }else if(groups[0].equalsIgnoreCase("Admin")){ event.setTag(ChatColor.AQUA + player.getName()); }else if(groups[0].equalsIgnoreCase("Adminoffduty")){ event.setTag(ChatColor.BLUE + player.getName()); } }
6
public synchronized boolean add(Object obj) { boolean retVal = false; if (!isFull()) { queue.addElement(obj); retVal = true; } return retVal; }
1
public String toString() { final StringBuffer buf; Class<?> target; buf = new StringBuffer(); buf.append(this.getClass().getName()); buf.append("\n"); target = this.getClass(); while (target != Object.class) { Field[] fields; int i; fields = target.getDeclaredFields(); for (i = 0; i < fields.length; i++) { String name; Object value; // There's something weird about a few extra Class objects // showing up. if (fields[i].getType() == Class.class) { continue; } buf.append("\t"); name = fields[i].getName(); buf.append(name); buf.append(": "); try { value = fields[i].get(this); } catch (IllegalArgumentException e) { // huh? e.printStackTrace(); continue; } catch (IllegalAccessException e) { // go figure. e.printStackTrace(); continue; } if (name.equals("parameters")) { buf.append("\n"); String[][] p = (String[][]) value; for (int j = 0; j < p.length; j++) { buf.append("\t\t"); buf.append(p[j][0]); buf.append(" "); buf.append(p[j][1]); buf.append("\n"); } } else { buf.append(value); buf.append("\n"); } } target = target.getSuperclass(); } return buf.toString(); }
8
public void checkCbolOriginalDir() { Path dir = Paths.get(CBOL_HOME); // //http://docs.oracle.com/javase/tutorial/essential/io/dirs.html try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { for (Path file : stream) { System.out.println(file.getFileName()); } } catch (IOException | DirectoryIteratorException x) { // IOException can never be thrown by the iteration. // In this snippet, it can only be thrown by newDirectoryStream. System.err.println(x); } }
2
public OSCByteArrayToJavaConverter() { }
0
public String toString() { //Print the Process ID and process state (READY, RUNNING, BLOCKED) String result = "Process id " + processId + " "; if (isBlocked()) { result = result + "is BLOCKED for "; //Print device, syscall and address that caused the BLOCKED state if (blockedForOperation == SYSCALL_OPEN) result += "OPEN"; else result += "WRITE @" + blockedForAddr; for(DeviceInfo di : m_devices) { if (di.getDevice() == blockedForDevice) { result += " on device #" + di.getId(); break; } } result += ": "; } else if (this == m_currProcess) result += "is RUNNING: "; else result += "is READY: "; //Print the register values stored in this object. These don't //necessarily match what's on the CPU for a Running process. if (registers == null) return result + "<never saved>"; for(int i = 0; i < CPU.NUMGENREG; i++) result += ("r" + i + "=" + registers[i] + " "); //Print the starve time statistics for this process return result + ("PC=" + registers[CPU.PC] + " ") + ("SP=" + registers[CPU.SP] + " ") + ("BASE=" + registers[CPU.BASE] + " ") + ("LIM=" + registers[CPU.LIM] + " ") + "\n\t\t\t" + " Max Starve Time: " + maxStarve + " Avg Starve Time: " + avgStarve; }//toString
7
public void setLightValue(EnumSkyBlock par1EnumSkyBlock, int par2, int par3, int par4, int par5) { if (par3 >> 4 >= storageArrays.length || par3 >> 4 < 0) { return; } ExtendedBlockStorage var6 = this.storageArrays[par3 >> 4]; if (var6 == null) { var6 = this.storageArrays[par3 >> 4] = new ExtendedBlockStorage(par3 >> 4 << 4); this.generateSkylightMap(); } this.isModified = true; if (par1EnumSkyBlock == EnumSkyBlock.Sky) { if (!this.worldObj.worldProvider.hasNoSky) { var6.setExtSkylightValue(par2, par3 & 15, par4, par5); } } else { if (par1EnumSkyBlock != EnumSkyBlock.Block) { return; } var6.setExtBlocklightValue(par2, par3 & 15, par4, par5); } }
6
public static File findMinecraftFolder() { final String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("win") >= 0) { return new File(System.getenv("APPDATA"), ".minecraft"); } else if (os.indexOf("mac") >= 0) { return new File(System.getProperty("user.home"), "Library/Application Support/.minecraft"); } else if (os.indexOf("nux") >= 0 || os.indexOf("nix") >= 0 || os.indexOf("aix") >= 0) { return new File(System.getProperty("user.home"), ".minecraft"); } else { LOGGER.log(Level.INFO, Localization.translate( "Config.findMinecraftFolder.unkownOS", os)); return new File("."); } }
5
private boolean r_mark_suffix_with_optional_n_consonant() { int v_1; int v_2; int v_3; int v_4; int v_5; int v_6; int v_7; // (, line 132 // or, line 134 lab0: do { v_1 = limit - cursor; lab1: do { // (, line 133 // (, line 133 // test, line 133 v_2 = limit - cursor; // literal, line 133 if (!(eq_s_b(1, "n"))) { break lab1; } cursor = limit - v_2; // next, line 133 if (cursor <= limit_backward) { break lab1; } cursor--; // (, line 133 // test, line 133 v_3 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { break lab1; } cursor = limit - v_3; break lab0; } while (false); cursor = limit - v_1; // (, line 135 // (, line 135 // not, line 135 { v_4 = limit - cursor; lab2: do { // (, line 135 // test, line 135 v_5 = limit - cursor; // literal, line 135 if (!(eq_s_b(1, "n"))) { break lab2; } cursor = limit - v_5; return false; } while (false); cursor = limit - v_4; } // test, line 135 v_6 = limit - cursor; // (, line 135 // next, line 135 if (cursor <= limit_backward) { return false; } cursor--; // (, line 135 // test, line 135 v_7 = limit - cursor; if (!(in_grouping_b(g_vowel, 97, 305))) { return false; } cursor = limit - v_7; cursor = limit - v_6; } while (false); return true; }
9
protected void importInput(String section, Engine engine) throws Exception { BufferedReader reader = new BufferedReader(new StringReader(section)); reader.readLine(); //ignore first line [InputX] InputVariable inputVariable = new InputVariable(); engine.addInputVariable(inputVariable); String line; while ((line = reader.readLine()) != null) { List<String> keyValue = Op.split(line, "="); if (keyValue.size() != 2) { throw new RuntimeException(String.format( "[syntax error] expected a property of type " + "'key=value', but found <%s>", line)); } String key = keyValue.get(0).trim(); String value = keyValue.get(1).trim(); if ("Name".equals(key)) { inputVariable.setName(Op.makeValidId(value)); } else if ("Enabled".equals(key)) { inputVariable.setEnabled(Op.isEq(Op.toDouble(value), 1.0)); } else if ("Range".equals(key)) { Op.Pair<Double, Double> minmax = extractRange(value); inputVariable.setMinimum(minmax.first); inputVariable.setMaximum(minmax.second); } else if (key.startsWith("MF")) { inputVariable.addTerm(prepareTerm(extractTerm(value), engine)); } else if ("NumMFs".equals(key)) { //ignore } else { throw new RuntimeException(String.format( "[import error] token <%s> not recognized", key)); } } }
7
@Test public void testGetMessageNoUnexpectedMessages() { try { int noOfMessages = 2; final String message = "TestMessage-testGetMessage_OneSubscriber"; final CountDownLatch gate = new CountDownLatch(1); final AtomicInteger msgCount = new AtomicInteger(0); final Message expected = new MockMessage(message); AsyncMessageConsumer testSubscriber = new MockTopicSubscriber() { public void onMessage(Message received) { assertNotNull("Received Null Message", received); assertEquals("Message values are not equal", message, received.getMessage()); msgCount.incrementAndGet(); gate.countDown(); } }; destination.addSubscriber(testSubscriber); for (int i = 0; i < noOfMessages; i++) destination.put(expected); boolean messageReceived = gate.await(100, TimeUnit.MILLISECONDS); assertTrue("Did not receive message in 100ms", messageReceived); Callable<Integer> wait = new Callable<Integer>() { public Integer call() throws Exception { Thread.sleep(500); return msgCount.get(); } }; FutureTask<Integer> future = new FutureTask<Integer>(wait); future.run(); assertEquals("Unexpected number of messages received", noOfMessages, future.get().intValue()); } catch (InterruptedException e) { fail("Wait InterruptedException " + e.getMessage()); } catch (ExecutionException e) { fail("Wait ExecutionException " + e.getMessage()); e.printStackTrace(); } catch (DestinationClosedException e) { fail("DestinationClosedException" + e.getMessage()); } }
4
public static String escape(String text, char escapeChar, char[] reserved) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); // Is the char reserved boolean isReserved = false; if (reserved != null) { for (int j = 0; j < reserved.length; j++) { if (c == reserved[j]) { isReserved = true; break; } } } // Deal with the type of char if (c == escapeChar) { buf.append(escapeChar).append(escapeChar); } else if (isReserved) { buf.append(escapeChar).append(c); } else { buf.append(c); } } return buf.toString(); }
6
public boolean contains(int index, int val) { if (adj[index].contains(val)) { return true;} else return false; }
1
private void checkForPrompt() { // Text has been entered, remove the prompt if (document.getLength() > 0) { setVisible( false ); return; } // Prompt has already been shown once, remove it if (showPromptOnce && focusLost > 0) { setVisible(false); return; } // Check the Show property and component focus to determine if the // prompt should be displayed. if (component.hasFocus()) { if (show == Show.ALWAYS || show == Show.FOCUS_GAINED) setVisible( true ); else setVisible( false ); } else { if (show == Show.ALWAYS || show == Show.FOCUS_LOST) setVisible( true ); else setVisible( false ); } }
8
public void setPcaSubgru(Integer pcaSubgru) { this.pcaSubgru = pcaSubgru; }
0
public static boolean isMaskActive( InputMask mask ) { switch ( mask ) { case CONTROL_MASK: return Keyboard.isKeyDown( Keyboard.KEY_LCONTROL ) || Keyboard.isKeyDown( Keyboard.KEY_RCONTROL ); case MENU_MASK: return Keyboard.isKeyDown( Keyboard.KEY_LMENU ) || Keyboard.isKeyDown( Keyboard.KEY_RMENU ); case META_MASK: return Keyboard.isKeyDown( Keyboard.KEY_LMETA ) || Keyboard.isKeyDown( Keyboard.KEY_RMETA ); default: return !( isMaskActive( InputMask.CONTROL_MASK ) || isMaskActive( InputMask.MENU_MASK ) || isMaskActive( InputMask.META_MASK ) ); } }
8
public void testWithDurationBeforeEnd3() throws Throwable { Duration dur = new Duration(-1); Interval base = new Interval(TEST_TIME_NOW, TEST_TIME_NOW); try { base.withDurationBeforeEnd(dur); fail(); } catch (IllegalArgumentException ex) {} }
1
* @return */ public Condfmt createCondfmt( String location, WorkBookHandle wbh ) { Condfmt cfx = (Condfmt) Condfmt.getPrototype(); int insertIdx = win2.getRecordIndex() + 1; BiffRec rec = (BiffRec) SheetRecs.get( insertIdx ); while( (rec.getOpcode() != HLINK) && (rec.getOffset() != DVAL) && (rec.getOpcode() != 0x0862) && (rec.getOpcode() != 0x0867) && (rec.getOpcode() != 0x0868) && (rec.getOpcode() != EOF) ) { rec = (BiffRec) SheetRecs.get( ++insertIdx ); } SheetRecs.add( insertIdx, cfx ); cfx.setStreamer( streamer ); cfx.setWorkBook( getWorkBook() ); cfx.resetRange( location ); addConditionalFormat( cfx ); cfx.setSheet( this ); return cfx; }
6
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); if (!updaterFile.exists()) { updaterFile.mkdir(); } boolean createFile = !updaterConfigFile.exists(); try { if (createFile) { updaterConfigFile.createNewFile(); this.config.options().copyDefaults(true); this.config.save(updaterConfigFile); } else { this.config.load(updaterConfigFile); } } catch (final Exception e) { if (createFile) { plugin.getLogger().severe("The updater could not create configuration at " + updaterFile.getAbsolutePath()); } else { plugin.getLogger().severe("The updater could not load configuration at " + updaterFile.getAbsolutePath()); } plugin.getLogger().log(Level.SEVERE, null, e); } if (this.config.getBoolean("disable")) { this.result = UpdateResult.DISABLED; return; } String key = this.config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().log(Level.SEVERE, "The project ID provided for updating, " + id + " is invalid.", e); this.result = UpdateResult.FAIL_BADID; } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); }
8
private static void Mergeforcemethod(int i, int n) { // TODO Auto-generated method stub if((n-i)<100000){ int il=0; int j=0; for(il=i;il<n;il++){ for(j=il;j<n;j++){ if (array[il]>array[j]){ total++; } } } Arrays.sort(array, i, n); }else{ Mergeforcemethod(i, n/2); Mergeforcemethod((n/2)+1, n); Countsplit(i,n); System.out.print(total); System.out.print("\n Final total"); } }
4
@Test public void transferInstrMOVE_testInvalidDestinationRegisterRef() { //Checks MOVE instr. not created with invalid register ref. try { instr = new TransferInstr(Opcode.MOVE, 5, -1); } catch (IllegalStateException e) { System.out.println(e.getMessage()); } assertNull(instr); }
1
private int one(String num) { switch(num) { case "one": return 1; case "two": return 2; case "three": return 3; case "four": return 4; case "five": return 5; case "six": return 6; case "seven": return 7; case "eight": return 8; case "nine": return 9; default: return 0; } }
9
public void addClientToDialog(String clientId, ClientDialog dialog) { System.out.println("Ajout d'un client a un dialog"); try { boolean alreadyKnow = false; ClientServerData clientAdd = null; System.out.println("On recherche le client"); for (ClientServerData client : this.getClients()) { if (client.getId().equals(clientId)) { alreadyKnow = true; clientAdd = client; } } if (!alreadyKnow) { System.out.println("On ne le connais pas, donc on le recherche au serveur"); this.launchThread(); Thread.sleep(500); // On demande les informations du client this.threadComunicationClient.getClientConnection(clientId); int cpt = 0; int sizeClients = this.getClients().size(); // On attent de les recevoir while (cpt < 500 && this.getClients().size() == sizeClients) { Thread.sleep(200); cpt++; } clientAdd = this.getClients().get(this.getClients().size() - 1); } if (clientAdd != null) { System.out.println("On envoie les messages de dialog au nouveau client"); protocol.sendMessage("dialog:newDialog:" + dialog.getIdDialog(), clientAdd.getIp(), clientAdd.getPortUDP()); protocol.sendMessage("dialog:newDialog:clients:" + dialog.getIdDialog() + ":" + this.id, clientAdd.getIp(), clientAdd.getPortUDP()); String listClient = this.id; for (ClientServerData client : dialog.getClients()) { listClient += "," + client.getId(); protocol.sendMessage("dialog:clients:" + dialog.getIdDialog() + ":" + clientAdd.getId(), client.getIp(), client.getPortUDP()); // A garder, ancienne méthode de groupe, en cas d'erreur // protocol.sendMessage("dialog:clients:" + // dialog.getIdDialog() + ":" + client.getId(), // clientAdd.getIp(), clientAdd.getPort()); } dialog.addClient(clientAdd); protocol.sendMessage("dialog:clients:" + dialog.getIdDialog() + ":" + listClient, clientAdd.getIp(), clientAdd.getPortUDP()); } } catch (InterruptedException e) { getLogger().severe("Erreur d'ajout d'un client, message : " + e.getMessage()); } }
8
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed // TODO add your handling code here: liceu.Administrator admin = new liceu.Administrator(usernameProfesor.getText(), parolaProfesor.getText(),ncProfesor.getText(),cnpProfesor.getText(),"Profesor"); admin.addUser(); usernameProfesor.setText(""); parolaProfesor.setText(""); ncProfesor.setText(""); cnpProfesor.setText(""); int i; BufferedReader fisier; try { fisier = new BufferedReader(new FileReader("credentials")); listModelProfesori.clear(); ArrayList<String> vector = new ArrayList<>(); for(String line; (line = fisier.readLine())!= null;){ vector.add(line); } for(i=0;i<vector.size();i=i+5){ if(vector.get(i+4).equals("Profesor")) listModelProfesori.addElement(vector.get(i)); } } catch (FileNotFoundException ex) { Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton13ActionPerformed
5
private DeclarationList declaration_list(int fallbackLineNumber, int fallbackCharPosition) throws RequiredTokenException { enterRule(NonTerminal.DECLARATION_LIST); ArrayList<Declaration> declarations = new ArrayList<Declaration>(); while(firstSetSatisfied(NonTerminal.DECLARATION)) { declarations.add(declaration()); } require(Token.Kind.EOF); exitRule(); return new DeclarationList( declarations.size() > 0 ? ((Command)declarations.get(0)).lineNumber() : fallbackLineNumber, declarations.size() > 0 ? ((Command)declarations.get(0)).charPosition() : fallbackCharPosition, declarations); }
3
public int getIntValue() { if (this.slider != null) { return this.slider.getValue(); } return ((Number) this.spinner.getValue()).intValue(); }
1
public static int direction(int dx, int dy) { if (dx < 0) { if (dy < 0) return 5; else if (dy > 0) return 0; else return 3; } else if (dx > 0) { if (dy < 0) return 7; else if (dy > 0) return 2; else return 4; } else { if (dy < 0) return 6; else if (dy > 0) return 1; else return -1; } }
8
private void halfFruits(int nfruits) { int r; int subset[] = new int[6]; boolean filled = false; for(int i=0; i < 6; i++) { boolean unique; do { unique = true; r = (int)(Math.random()*12); for(int j=0; j < i; j++) { if(subset[j] == r) unique = false; } }while(!unique); subset[i] = r; } while(nfruits > 0) { r = (int)(Math.random()*subset.length); dist[subset[r]]++ ; nfruits--; } }
5
public byte getMemory(int address, boolean shouldNotify) { if (shouldNotify && _readObserver != null) { _readObserver.updateReadMemory(address); } if (isCPUMapped(address)) { return getCPUMappedMemory(address); } else if (_ppu.isReadMapped(address)) { return _ppu.getMappedMemory(address); } else if (_controllers.isReadMapped(address)) { return _controllers.getMappedMemory(address); } else if (_apu.isReadMapped(address)) { return _apu.getMappedMemory(address); } else if (_mapper.isReadMapped(address)) { return _mapper.getMappedMemory(address); } else { return _memoryData[address]; } }
7
public ArrayList<Integer> postorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); if (root == null) return result; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); TreeNode prev = null; while (!stack.empty()) { TreeNode curNode = stack.peek(); if (prev == null || prev.left == curNode || prev.right == curNode) { if (curNode.left != null) stack.push(curNode.left); else if (curNode.right != null) stack.push(curNode.right); } else if (curNode.left == prev) { if (curNode.right != null) stack.push(curNode.right); } else { result.add(curNode.val); stack.pop(); } prev = curNode; } return result; }
9
public DMatrix(int dim, int cls, int num){ samplenum = num; dimension = dim; groundcls = new int[samplenum]; knewcls = new int[samplenum]; nnnewcls = new int[samplenum]; test = new int[samplenum]; for(int i = 0; i < samplenum; i++){ groundcls[i] = cls; knewcls[i] = -1; nnnewcls[i] = -1; test[i] = 0; } XMatrix = new Matrix[samplenum]; for(int i = 0; i < samplenum; i++){ XMatrix[i] = new Matrix(dim,1); } }
2
public static void main(String[] args) { interactInput(); new TwitterCrawler(); }
0
static public Mantenimiento_Modulos instancia() { if (UnicaInstancia == null) { UnicaInstancia = new Mantenimiento_Modulos(); } return UnicaInstancia; }
1
private void loadDates() { SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); HashMap<String, String> dates = new HashMap<>(); try { String query = "select startdatum,releasedatum from spelprojekt where sid=" + selectedSpelprojekt; dates = DB.fetchRow(query); } catch (InfException e) { e.getMessage(); } Date sdate = java.sql.Date.valueOf(dates.get("STARTDATUM")); Date rdate = java.sql.Date.valueOf(dates.get("RELEASEDATUM")); if (sdate != null && rdate != null) { lblStartDate.setText(sdf.format(sdate)); lblReleaseDate.setText(sdf.format(rdate)); } }
3
public void run() { if (list.isEmpty()) { return; } Collection<ProxiedPlayer> players = ProxyServer.getInstance().getPlayers(); if (players.isEmpty()) { return; } for(ProxiedPlayer player: players){ for ( String line : list.get(count).split( "\n" ) ) { player.sendMessage(line); } } count++; if((count+1)>list.size()){ count=0; } }
5
@Override public void addPoint(double distance, int index) { if (distance >= worstDistance) return; if (count < capacity) count++; int i; for (i = count-1; i > 0; i--) { if (distanceIndexArray.get(i-1).distance > distance || (distanceIndexArray.get(i-1).distance == distance && distanceIndexArray.get(i-1).index > index)) { distanceIndexArray.set (i, distanceIndexArray.get (i-1)); } else { break; } } distanceIndexArray.set (i, new DistanceIndex (distance, index)); if (full()) { worstDistance = distanceIndexArray.get(capacity-1).distance; } }
7
private boolean disjointSquare(MoveNode[][] b) { for(int i = 0; i < boardSize; i++){ for(int j = 0; j < boardSize; j++){ if(!b[i][j].isVisited() && !b[i][j].anyUnvisitedNeghbours()) return true; } } return false; }
4
private final long method1865(int i) { long l = System.nanoTime(); long l_0_ = -aLong6169 + l; if (i != 10) return -56L; aLong6169 = l; if (4999999999L > (l_0_ ^ 0xffffffffffffffffL) && -5000000001L < (l_0_ ^ 0xffffffffffffffffL)) { aLongArray6171[anInt6170] = l_0_; if ((anInt6168 ^ 0xffffffff) > -2) anInt6168++; anInt6170 = (1 + anInt6170) % 10; } long l_1_ = 0L; for (int i_2_ = 1; i_2_ <= anInt6168; i_2_++) l_1_ += aLongArray6171[(-i_2_ + anInt6170 - -10) % 10]; return l_1_ / (long) anInt6168; }
5
private void writeROM() { DataOutputStream out = null; // Used to write out the data to the ROM file try { out = new DataOutputStream( // Create output stream used to write the ROM file new FileOutputStream(game)); } catch (FileNotFoundException e) { Error.fatalError(1); } // 1 -- Cannot write to the designated file if (iNESWrite) { // Only write the iNES header if instructed try { out.write(iNES, 0, iNES.length); } // Write the iNES header to the ROM catch (IOException e) { Error.fatalError(1); } // 1 -- Cannot write to the designated file } try { out.write(ROM, 0, ROM.length); } // Write the ROM file catch (IOException e) { Error.fatalError(1); } // 1 -- Cannot write to the designated file try { out.close(); } catch (IOException e) { Error.fatalError(1); } // 1 -- Cannot write to the designated file }
5
public static void evalAUC(Dataset dataset) { double trainArea = 0, trainPosi = 0, trainRank = dataset.trainCount; double testArea = 0, testPosi = 0, testRank = dataset.testCount; double quizArea = 0, quizPosi = 0, quizRank = dataset.quizCount; Collections.sort(dataset.data, new InstanceComparator()); for(Instance inst : dataset.data) { if(inst.type == InstanceType.Train) { if(inst.target == 1.0) { trainPosi++; trainArea += trainRank; } trainRank--; } else if(inst.type == InstanceType.Test) { if(inst.target == 1.0) { testPosi++; testArea += testRank; } testRank--; } else { if(inst.target == 1.0) { quizPosi++; quizArea += quizRank; } quizRank--; } } if(dataset.trainCount > 0) { double auc = (trainArea - trainPosi * (trainPosi + 1) / 2) / (trainPosi * (dataset.trainCount - trainPosi)); System.out.print(String.format("Train: %.4f %d\t", auc, dataset.trainCount)); } if(dataset.testCount > 0) { double auc = (testArea - testPosi * (testPosi + 1) / 2) / (testPosi * (dataset.testCount - testPosi)); System.out.print(String.format("Test: %.4f %d\t", auc, dataset.testCount)); } if(dataset.quizCount > 0) { double auc = (quizArea - quizPosi * (quizPosi + 1) / 2) / (quizPosi * (dataset.quizCount - quizPosi)); System.out.print(String.format("Quiz: %.4f %d\t", auc, dataset.quizCount)); } System.out.println(); }
9
static String demandeIntermediare(String ip, int port, String question, boolean attCrochets, int nombreMot, int nbIteration, int tmpAttente ) throws UnknownServiceException { String reponse = ""; int tmp = 0; while (tmp < nbIteration){ try { reponse = demanderQuestion(ip, port, question, attCrochets, nombreMot); tmp = nbIteration*2; } catch (IOException ioe) { tmp++; if (tmpAttente>0) try{Thread.sleep(tmpAttente);} catch(InterruptedException ite){ ite.printStackTrace(); } } } if (tmp <= nbIteration) throw new UnknownServiceException(ip + " " + port); return reponse; }
5
@Override public void run() { while((client.isConnected()) && !client.isLogged()) { client.println(welcomeMessage); String nick = client.readLine(); if ((nick != null) && (!farewellMessage.equals(nick))) { if (client.setNick(nick)) { queueOfMessages.addLast(client.getNick() + " connected"); } } else { closeConnection(); } } while(client.isConnected() && client.isLogged()) { String s = client.readLine(); if ((s != null) && (!farewellMessage.equals(s))) { queueOfMessages.addLast(client.getNick() + ">>" + s); } else { closeConnection(); } } }
9
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: Connection cx = null; cx = Conexion.getConexion(); if(cx != null){ JOptionPane.showMessageDialog(null , "exito"); } }//GEN-LAST:event_jButton1ActionPerformed
1
public double getData(String ticker) { try { URL interWebs = new URL(baseURL + ticker + baseURLend); // create a URL instance of the API Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("149.89.1.30", 3128)); // the proxy in the Stuy computer lab URLConnection interwebConnect = interWebs.openConnection(proxy); // make a URL connection out of the URL // make way to choose lab settings InputStreamReader isr = new InputStreamReader(interwebConnect.getInputStream()); // Retrieve the csv into a InputStreamReader BufferedReader in = new BufferedReader(isr); // For efficiency, thank you oracle API String data = in.readLine(); // retrieve the data int cuttingPoint = data.indexOf(','); // this will be the price String ret = data.substring(0, cuttingPoint); try{ return Double.parseDouble(ret); } catch(Exception excep){ return 100.72; } } catch (IOException e) { try { URL interWebs = new URL(baseURL + ticker + baseURLend); // create a URL instance of the API URLConnection interwebConnect = interWebs.openConnection(); InputStreamReader isr = new InputStreamReader(interwebConnect.getInputStream()); // Retrieve the csv into a InputStreamReader BufferedReader in = new BufferedReader(isr); // For efficiency, thank you oracle API String data = in.readLine(); // retrieve the data int cuttingPoint = data.indexOf(','); // this will be the price String ret = data.substring(0, cuttingPoint); try{ return Double.parseDouble(ret); } catch(Exception excep){ return 100.72; } } catch (Exception excep) { return 100.72; } } }
4
private void HandleLogin() throws IOException { String line; String[] parts; while (true) { line = in.readLine(); parts = line.split(" "); if (parts[0].equals("USER")) { uid = parts[1]; UserControl.addUserIfNotExist(uid); out.println("OK"); return; } else { out.println("INV"); } } }
2
public Expression simplify() { if (local.getExpression() != null) return local.getExpression().simplify(); return super.simplify(); }
1
public boolean isOptOut() { synchronized (optOutLock) { try { // Reload the metrics file configuration.load(getConfigFile()); } catch (IOException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } catch (InvalidConfigurationException ex) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); } return true; } return configuration.getBoolean("opt-out", false); } }
4
@Override public void actionPerformed(ActionEvent arg0) { if(arg0.getActionCommand().equals("file")){ JFileChooser chooser = new JFileChooser(); int retval = chooser.showOpenDialog(null); if(retval == JFileChooser.APPROVE_OPTION){ chooser.setVisible(false); fileDir = chooser.getSelectedFile().getAbsolutePath(); } else{ chooser.setVisible(false); } } else if (arg0.getActionCommand().equals("yes")){ pruning = true; }else if (arg0.getActionCommand().equals("no")){ pruning = false; }else if(arg0.getActionCommand().equals("ok")){ mainWindow.setVisible(false); Node result = null; try { SampleSet instances = createInstancesX(fileDir); if(pruning){ SampleSet[] newSets = randomSplitForPrunning(instances); Node root = Node.createDT(newSets[0]); System.out.println("Before Pruning:"); root.prettyPrint(0); Pruner pruner = new Pruner(newSets[1], root); result = pruner.prune(); System.out.println("After pruning:"); result.prettyPrint(0); }else{ result = Node.createDT(instances); result.prettyPrint(0); } result.createOutputFile(fileDir); System.exit(0); } catch (IOException e) { JOptionPane.showMessageDialog(mainWindow, e.getMessage()+"\nPlease choose another file!"); mainWindow.setVisible(true); } }else if (arg0.getActionCommand().equals("cancel")){ mainWindow.setVisible(false); System.exit(0); } }
8
public ArrayList<Company> getCompanies() { return Companies; }
0
private void executeForwardJob(ForwardJob job) throws IOException, JSchException { updateable.send(new StatusUpdate("VM " + id + " Executing ForwardJob", id, VMState.EXECUTING, JobType.FORWARD)); HashMap<Integer, String> files = new HashMap<Integer, String>(); String sessionName = job.getRemoteFileName(); // We highjack te session // name to communicate // the output file name if (job.isTarForwarder()) { String file = FileLocations.pathForTar(job.getIP(), job.getFileName()); files.put(-2, file); // We highjack the fileid to communicate a // ".tar.gz" with sessionName output } else { String file = FileLocations.pathForOutput(job.getIP(), job.getFileName()); files.put(-1, file); // We highjack the fileid to communicate // sessionName output } FTPService.offer(sessionName, files); FTPService.invokeRemote(job.getIP(), sessionName); FTPService.waitForOffer(sessionName, 120000); // Now that we have completed our business, clear up all the resources // associated with // this set of jobs. if (job.isTarForwarder()) new File(FileLocations.pathForTar(job.getIP(), job.getFileName())) .delete(); new File(FileLocations.pathForOutput(job.getIP(), job.getFileName())) .delete(); HashMap<Integer, String> fileMapping = null; synchronized (fileSystem) { fileMapping = fileSystem.remove(job.getIP()); } for (String path : fileMapping.values()) new File(path).delete(); }
3
void entityDestroyCheck(DownlinkState linkState) { if(linkState != null) { if(packetId == 0x1D && linkState.entityIds != null) { Integer entityId = (Integer)fields[0].getValue(); linkState.entityIds.remove(entityId); } else if (packetId == 0x32) { Integer x = (Integer)fields[0].getValue(); Integer z = (Integer)fields[1].getValue(); Boolean mode = (Boolean)fields[2].getValue(); if(mode) { if(linkState.contains(x, z)) { System.out.println("Chunk " + x + " " + z + " added " + linkState.contains(x, z)); } linkState.addChunk(x, z); } else { if(!linkState.contains(x, z)) { System.out.println("Chunk " + x + " " + z + " removed " + linkState.contains(x, z)); } linkState.removeChunk(x, z); } } else if (packetId == 0x33) { Integer x = ((Integer)fields[0].getValue()) >> 4; Integer z = ((Integer)fields[2].getValue()) >> 4; if(!linkState.contains(x, z)) { System.out.println("Chunk " + x + " " + z + " updated " + linkState.contains(x, z)); } linkState.addChunk(x, z); } } }
9
public static boolean methodInlinableP(MethodSlot method) { if (StandardObject.voidP(method.type()) || ((method.methodReturnTypeSpecifiers().length() > 1) || ((BooleanWrapper)(KeyValueList.dynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue)) { return (false); } if (method.methodFunctionP || MethodSlot.mostSpecificMethodP(method)) { return (MethodSlot.inlinableMethodBody(method) != null); } else { { Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get(); try { Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true); Stella.signalTranslationNote(); if (!(Stella.suppressWarningsP())) { Stella.printErrorContext(">> NOTE: ", Stella.STANDARD_OUTPUT); { System.out.println(); System.out.println(" Cannot inline method `" + Stella_Object.deUglifyParseTree(method) + "', since there are"); System.out.println(" one or more methods that specialize it."); } ; } } finally { Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000); } } return (false); } }
6
public String getValue() { return _value; }
0
public int getPointFromPos(Double x, Double y) { int point; if (y > HEIGHT/2) { // flip logic point = 24 - (int) (x / baseUnit); point += 2; if (point > 18) { point--; } } else { point = (int) (x / baseUnit); if (point > 6) { point --; } } return point; }
3
public static Router getRouter(String name, LinkedList routerList) { if (name == null || routerList == null || name.length() == 0) { return null; } Router router = null; try { Iterator it = routerList.iterator(); while ( it.hasNext() ) { router = (Router) it.next(); if (router.get_name().equals(name)) { break; } else { router = null; } } } catch (Exception e) { router = null; } return router; }
6
@Override public double bonusDefense(Territoire t, Peuple attaquant) { if( t.has(SallePartiel.class) ) return 1.0; return 0.0; }
1
public boolean hasError() { if (value instanceof ErrorMessage == false) { return false; } ErrorMessage probableError = (ErrorMessage) value; switch (probableError) { case EMPTY_STRUCTURE: case INDEX_OUT_OF_BOUNDS: case INVALID_ARGUMENT: return true; default: return false; } }
4
public LambdaPane(AutomatonPane ap) { super(new BorderLayout()); add(ap, BorderLayout.CENTER); add(new JLabel(Universe.curProfile.getEmptyString()+"-transitions are highlighted."), BorderLayout.NORTH); ArrowDisplayOnlyTool tool = new ArrowDisplayOnlyTool(ap, ap .getDrawer()); ap.addMouseListener(tool); }
0
public static void revalidateImmediately(Component comp) { if (comp != null) { RepaintManager mgr = RepaintManager.currentManager(comp); mgr.validateInvalidComponents(); mgr.paintDirtyRegions(); } }
1
public static Boolean compareArgLists(Map<String, Object> args1, Map<String, Object> args2) { if (args1 == null && args2 == null) return true; if (args1 != null) { for (Map.Entry<String, Object> arg : args1.entrySet()) { if (args2 != null) { if (!args2.containsKey(arg.getKey())) return false; } } return true; } return false; }
6
public Integer kthToLast(int k) { if (k <= 0 || head == null) throw new IllegalArgumentException("There is no such element."); Node runner = head; Node pointer = head; int counter = 1; for (; runner.next != null && counter < k; counter++) { runner = runner.next; } if (counter < k && runner.next == null) return null; while (runner.next != null) { runner = runner.next; pointer = pointer.next; } return pointer.data; }
7
public void setIndirizzo(Address indirizzo) { this.address = indirizzo; }
0
@Override public String toString() { StringBuilder info = new StringBuilder(); info.append("GameScreen :: ") .append(getName()) .append("\n"); // Iterate over all of the registered game layers and append their // toString values for (GameLayer gameLayer : gameLayers.values()) { info.append(gameLayer.toString()); } return info.toString(); }
1
private void accept(SelectionKey key,Boolean isClusters) throws IOException { // For an accept to be pending the channel must be a server socket channel. ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); // Accept the connection and make it non-blocking SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false);// 设置为非阻塞式 socketChannel.socket().setReceiveBufferSize(this.sockectReceiveBufferSize * 1024);// 设置接收缓存 socketChannel.socket().setSendBufferSize(this.sockectSendBufferSize * 1024);// 设置发送缓存 socketChannel.socket().setSoTimeout(0); socketChannel.socket().setTcpNoDelay(true); if(keepConnect){//使用长连接,保持连接状态 socketChannel.socket().setKeepAlive(true); } // 将客户端sockect通道注册到指定的输入监听线程上 if(isClusters){// 集群请求通道注册 this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement()) % this.readWriteMonitors.size()).registeClusters(socketChannel); }else{// 业务请求通道注册 this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement()) % this.readWriteMonitors.size()).registe(socketChannel); } }
2
public void checkSideCollision(Rectangle rleft, Rectangle rright, Rectangle leftfoot, Rectangle rightfoot) { if (type != 5 && type != 2 && type != 0){ if (rleft.intersects(r)) { robot.setCenterX(tileX + 102); robot.setSpeedX(0); }else if (leftfoot.intersects(r)) { robot.setCenterX(tileX + 85); robot.setSpeedX(0); } if (rright.intersects(r)) { robot.setCenterX(tileX - 62); robot.setSpeedX(0); } else if (rightfoot.intersects(r)) { robot.setCenterX(tileX - 45); robot.setSpeedX(0); } } }
7
private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed try{ if (nameOutlet.getText().isEmpty() || codeOutlet.getText().isEmpty() || priceAOutlet.getText().isEmpty() || priceBOutlet.getText().isEmpty()) { JOptionPane.showMessageDialog(null, tools.Utilities.incompleteFormMessage, "Fout!", JOptionPane.WARNING_MESSAGE); return; } if (!database.Database.driver().isArticleCodeUnique(codeOutlet.getText(), model)) { JOptionPane.showMessageDialog(null, "Deze artikelcode is niet uniek!", "Fout!", JOptionPane.WARNING_MESSAGE); return; } /* * Set values on the model */ model.setName(nameOutlet.getText()); model.setCode(codeOutlet.getText()); model.setPriceA(Double.parseDouble(priceAOutlet.getText())); model.setPriceB(Double.parseDouble(priceBOutlet.getText())); model.setUnit(unitOutlet.getText()); model.setTaxes(Double.parseDouble(taxesOutlet.getText())); // set comments FunctionResult<Article> res = model.update(); if (res.getCode() == 0) { delegate.editArticle(defaultModel, model); disposeLater(); } else { String msg; switch(res.getCode()){ case 1: case 2: msg = res.getMessage(); break; default: msg = "Er is een fout opgetreden bij het opslaan van dit artikel in de databank (code "+res.getCode()+"). Contacteer de ontwikkelaars met deze informatie."; } JOptionPane.showMessageDialog(null, msg, "Fout!", JOptionPane.ERROR_MESSAGE); } } catch (Exception e){ System.err.println("Error: \n"+e.getMessage()); JOptionPane.showMessageDialog(null, tools.Utilities.incorrectFormMessage, "Fout!", JOptionPane.WARNING_MESSAGE); } }//GEN-LAST:event_saveActionPerformed
9