text
stringlengths
14
410k
label
int32
0
9
public void buildForest() { intervalForest = new IntervalForest(); // Add all chromosomes to forest if (useChromosomes) { for (Chromosome chr : genome) intervalForest.add(chr); } // Add all genes to forest for (Gene gene : genome.getGenes()) intervalForest.add(gene); //--- // Create (and add) up-down stream, splice sites, intergenic, etc //--- markers.add(createGenomicRegions()); // Add all 'markers' to forest (includes custom intervals) intervalForest.add(markers); // Build interval forest intervalForest.build(); }
3
public String execute(LogInObject logInObject) throws SQLException{ String answer = ""; String result = authenticateUser(logInObject.getAuthUsername(), logInObject.getAuthPassword(), logInObject.getIsAdmin()); switch (result){ case "1": logInRO.setLogOn(false); logInRO.setExplanation("The email or password is incorrect."); break; case "2": logInRO.setLogOn(false); logInRO.setExplanation("The user is inactive; contact an admin to resolve the issue."); break; case "3": logInRO.setLogOn(false); logInRO.setOverallID("brugertype ikke stemmer overens med loginplatform."); break; case "0": logInRO.setLogOn(true); logInRO.setExplanation("Logon succesfull."); break; default: logInRO.setLogOn(false); logInRO.setExplanation("System error."); break; } answer = gson.toJson(logInRO); return answer; }
4
int insertKeyRehash(float val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
public Point move(Point[] pipers, // positions of dogs Point[] rats) { // positions of the rats npipers = pipers.length; System.out.println(initi); Point gate = new Point(dimension/2, dimension/2); if (!initi) { this.init();initi = true; } Point current = pipers[id]; // Where the pipers are right now double ox = 0, oy = 0; // direction of the piper //nrats = rats.length; if (getSide(current) == 0 && !sweep) { // if on the left side - starting point this.music = false; // this is the change in movement towards the gate double dist = distance(current, gate); assert dist > 0; ox = (gate.x - current.x) / dist * pspeed; oy = (gate.y - current.y) / dist * pspeed; System.out.println("move toward the right side"); } else if (!closetoWall(current) && !sweep) { // on the right side and hasn't bounced back yet // this is the change in movement based on the angle this.music = false; ox = pspeed * Math.sin(thetas[id] * Math.PI / 180); oy = pspeed * Math.cos(thetas[id] * Math.PI / 180); } else { // after bounced and turns on music; this.music = true; // music turns on once pipers have reached close to wall if(!this.sweep){ this.sweep = true; // sweeping begins once the pipers have reached close to wall assignRats(rats); } ArrayList<Integer> missingRatsIDs = ratsToCollect(pipers, rats); // rats that have to get collected System.out.println("number of missing rats = " + missingRatsIDs.size()); if(missingRatsIDs.size() > 0){ /* String print = "rats to collect are: "; for(int i = 0; i < missingRats.size(); i++) print += missingRats.get(i) + ", "; System.out.println(print); */ System.out.println("hasResponsibility for id=" + id + ":" + hasResponsibility(assignedRats.get(id), missingRatsIDs)); if(hasResponsibility(assignedRats.get(id), missingRatsIDs)){ current = toRat(current, missingRatsIDs, rats); } else current = toGate(current); } else current = toGate(current); } current.x += ox; current.y += oy; return current; }
8
final public DBAccess open(final String connectionString) throws ClassNotFoundException { String user = null; String password = null; String driver = null; String url = null; // Split the connection string into commands. final String[] commands = connectionString.split(";"); for(final String command: commands) { final Matcher m = _commandPattern .matcher(command); if(m.matches()) { switch (m.group(1)) { case "user": user = m.group(2); break; case "password": password = m.group(2); break; case "driver": driver = m.group(2); break; case "url": url = m.group(2); break; } } else { System.out.println(String.format( "The command: %s in the connection " + "string isn't valid.", command)); } } return new DBAccess( driver, url, user, password); }
6
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 5; }
0
public KeyStroke getKey() { return KeyStroke.getKeyStroke('u'); }
0
@Override public void run() { if (!Inventory.isFull()) { fish(); } else { Item[] bob = Inventory.getItems(); for (int c = 0; inventoryCheck(); c++) { bob[c].getWidgetChild().interact("Drop"); Time.sleep(100); if (c == 29 && inventoryCheck()) { c = 0; } } } }
4
public P371E() { Scanner sc = new Scanner(System.in); // because we will deal with segments N = sc.nextInt() - 1; Pos[] pos = new Pos[N+1]; for (int i = 0; i < N+1; i++) { int x = sc.nextInt(); pos[i] = new Pos(x, i+1); } Arrays.sort(pos); d = new int[N]; for (int i = 1; i < N+1; i++) { d[i-1] = pos[i].x - pos[i-1].x; } k = sc.nextInt() - 1; long D1 = 0; long D2 = 0; for (int i = k-1; i >= 0; i--) { D1 += d[i]; D2 += (2*k - 2*i) * (long)d[i]; } long T = 0; long Tmin = 0; int posMin = k-1; java.util.Deque<Integer> deque = new ArrayDeque<Integer>(); for (int i = 0; i < k; i++) { deque.add(d[i]); } for (int i = k; i < N; i++) { int d0 = deque.pollFirst(); int dn = d[i]; deque.add(dn); T = T + k*(D1 + dn) - D2; D1 = D1 - d0 + dn; D2 = D2 - 2*k*(long)d0 + 2*D1; if (T < Tmin) { Tmin = T; posMin = i; } } for (int i = posMin - k + 1; i <= posMin + 1; i++) { System.out.printf("%d ", pos[i].id); } System.out.println(); }
7
public BufferedImage getImage() { BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB); bi.setRGB(0,0,width,height,pixels,0,width); return bi; }
0
public static Calendar jauJd2cal(double dj1, double dj2) throws JSOFAIllegalParameter { /* Minimum and maximum allowed JD */ final double djmin = -68569.5; final double djmax = 1e9; long jd, l, n, i, k; double dj, d1, d2, f1, f2, f, d; /* Verify date is acceptable. */ dj = dj1 + dj2; if (dj < djmin || dj > djmax) throw new JSOFAIllegalParameter("input julian date out of range", -1); /* Copy the date, big then small, and re-align to midnight. */ if (dj1 >= dj2) { d1 = dj1; d2 = dj2; } else { d1 = dj2; d2 = dj1; } d2 -= 0.5; /* Separate day and fraction. */ f1 = fmod(d1, 1.0); f2 = fmod(d2, 1.0); f = fmod(f1 + f2, 1.0); if (f < 0.0) f += 1.0; d = floor(d1 - f1) + floor(d2 - f2) + floor(f1 + f2 - f); jd = (long) floor(d) + 1L; /* Express day in Gregorian calendar. */ l = jd + 68569L; n = (4L * l) / 146097L; l -= (146097L * n + 3L) / 4L; i = (4000L * (l + 1L)) / 1461001L; l -= (1461L * i) / 4L - 31L; k = (80L * l) / 2447L; int id = (int) (l - (2447L * k) / 80L); l = k / 11L; int im = (int) (k + 2L - 12L * l); int iy = (int) (100L * (n - 49L) + i + l); return new Calendar(iy, im, id, f); }
4
public void testForFields_datetime_DM() { DateTimeFieldType[] fields = new DateTimeFieldType[] { DateTimeFieldType.dayOfMonth(), DateTimeFieldType.minuteOfHour(), }; int[] values = new int[] {25, 20}; List types = new ArrayList(Arrays.asList(fields)); DateTimeFormatter f = ISODateTimeFormat.forFields(types, true, false); assertEquals("---25T-20", f.print(new Partial(fields, values))); assertEquals(0, types.size()); types = new ArrayList(Arrays.asList(fields)); f = ISODateTimeFormat.forFields(types, false, false); assertEquals("---25T-20", f.print(new Partial(fields, values))); assertEquals(0, types.size()); types = new ArrayList(Arrays.asList(fields)); try { ISODateTimeFormat.forFields(types, true, true); fail(); } catch (IllegalArgumentException ex) {} types = new ArrayList(Arrays.asList(fields)); try { ISODateTimeFormat.forFields(types, false, true); fail(); } catch (IllegalArgumentException ex) {} }
2
public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); String line = ""; BigInteger n = new BigInteger("0"); BigInteger aux = new BigInteger("0"); d: do { line = buf.readLine(); if (line == null || line.length() == 0) break d; aux = new BigInteger(line); n = n.add(aux); if(aux.compareTo(new BigInteger("0"))==0){ System.out.println(n); break d; } } while (line != null && line.length() != 0); }
5
@RequestMapping(value="/{tripID}/detailsTravelTrip", method=RequestMethod.GET) public String detailsTravelTrip(@PathVariable("tripID") String tripID, Model model){ TravelTrip tempTravelTrip = travelTripService.findById(Integer.parseInt(tripID)); model.addAttribute("detailsTravelTrip", tempTravelTrip); return "detailsTravelTrip"; }
0
public Parser(String pathname) { this.file = new File(pathname); try { readFile(); } catch(FileNotFoundException e) { System.err.println("File: " + pathname + " not found!"); e.printStackTrace(); } extractAssemblercode(); }
1
private static boolean handleIsValidUser(Integer u) { if (u < 0) { System.err.println("Not a valid user"); return false; } else { UserModel userModel = new UserModel(); Iterable<Entry> userQuery = userModel.query("{id:" + u + "}"); if (!userQuery.iterator().hasNext()) { System.err.println("Not a valid user"); return false; } } return true; }
2
public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Map<String, Integer> map = new HashMap<>(); while (true) { try { int id = Integer.parseInt(reader.readLine()); String name = reader.readLine(); if (name.equals("")) { break; } map.put(name, id); } catch ( NumberFormatException | IOException e ) { break; } } for (Map.Entry<String, Integer> pair : map.entrySet()) { System.out.println(pair.getValue() + " " + pair.getKey()); } }
4
public int GetNpcListHP(int NpcID) { for (int i = 0; i < maxListedNPCs; i++) { if (NpcList[i] != null) { if (NpcList[i].npcId == NpcID) { return NpcList[i].npcHealth; } } } return 0; }
3
@Override public void update(Level level, int x, int y, int z, Random rand) { boolean var8 = false; boolean var6; do { --y; if (level.getTile(x, y, z) != 0 || !canFlow(level, x, y, z)) { break; } if (var6 = level.setTile(x, y, z, movingId)) { var8 = true; } } while (var6 && type != LiquidType.lava); ++y; if (type == LiquidType.water || !var8) { var8 = var8 | flow(level, x - 1, y, z) | flow(level, x + 1, y, z) | flow(level, x, y, z - 1) | flow(level, x, y, z + 1); } if (!var8) { level.setTileNoUpdate(x, y, z, stillId); } else { level.addToTickNextTick(x, y, z, movingId); } }
8
public static HealthColorPixelType healthColorPixelTypeFor(Color color, int id) { HealthColorPixelType type = healthColorPixels.get(color); if (type == null) { type = new HealthColorPixelType(id, color); healthColorPixels.put(color, type); } return type; }
1
private boolean doOp (NodeOps op, double threshold, double input) { switch (op) { case GREATER_THAN: return input > threshold; case LESS_THAN: return input < threshold; case GREATER_THAN_OR_EQUAL_TO: return input >= threshold; case LESS_THAN_OR_EQUAL_TO: return input <= threshold; case ADDITION: _totalInput = _totalInput + (threshold / NeuralNets.MAX_INPUT); return true; case SUBTRACTION: _totalInput = _totalInput - (threshold / NeuralNets.MAX_INPUT); return true; case MULTIPLICATION: _totalInput = _totalInput * (threshold / NeuralNets.MAX_INPUT); return true; case DIVISION: _totalInput = _totalInput / (threshold / NeuralNets.MAX_INPUT); return true; default: return false; } }
8
private boolean touchRobotMov(int pos) { boolean toca = false; for (SimulatorRobot robot : Board.robots) { if (robot != this) { ArrayList<Line2D.Double> linies = this.getBoundLines(); ArrayList<Line2D.Double> liniest2 = robot.getBoundLines(); Line2D.Double nxtline = nextLine(linies.get(pos)); for (int j = 0; j < 4; j++) { if (nxtline.intersectsLine(liniest2.get(j))) { toca = true; } } } } return toca; }
4
public ParametricEquation(String equ_x, String equ_y, double tstart, double tend, double dt){ this.tstart = tstart; this.tend = tend; this.dt = dt; equx = new Equation(equ_x); equy = new Equation(equ_y); Vector<Variable> variables = equx.getVariables(); if(variables.size()!=1) throw new EquationException("Invalid X Equation: " + equ_x); tx = variables.firstElement(); if(!tx.getName().equals("t")) throw new EquationException("Invalid X Equation: " + equ_x); variables = equy.getVariables(); if(variables.size()!=1) throw new EquationException("Invalid Y Equation: " + equ_y); ty = variables.firstElement(); if(!ty.getName().equals("t")) throw new EquationException("Invalid Y Equation: " + equ_y); }
4
public GrabAbility(String name, String trigger) { super(name, trigger); }
0
public AttributeInfo copy(ConstPool newCp, Map classnames) { AnnotationsAttribute.Copier copier = new AnnotationsAttribute.Copier(info, constPool, newCp, classnames); try { copier.memberValue(0); return new AnnotationDefaultAttribute(newCp, copier.close()); } catch (Exception e) { throw new RuntimeException(e.toString()); } }
1
private double getBulletPower() { if (power != null) { return power; } double bulletPower = 1.95; if (state.targetDistance < 140) { bulletPower = 2.95; } bulletPower = Math.min(state.robotEnergy / 4.0, bulletPower); bulletPower = Math.min(state.targetEnergy / 4.0, bulletPower); bulletPower = Math.max(0.1, bulletPower); return bulletPower; }
2
private void transformTree(TreeNode node) { TreeNode left = node.left; TreeNode right = node.right; reverse(node); if(left != null) transformTree(left); if(right != null) transformTree(right); mergeToRight(node); }
2
public int getFieldLineIndex() { return fieldLineIndex; }
0
private static void runclient(String[] args) throws FileNotFoundException, IOException { //Get the addresses of machines from the property file Properties prop = new Properties(); FileInputStream fis = new FileInputStream("./boltdb.prop"); prop.load(fis); fis.close(); ClientArgs clientArgs = new ClientArgs(); //Create an object to store the key,value and other grep options StringBuilder options = new StringBuilder(); for (int j = 0; j < args.length; j++) { if (args[j].equals("-key")) { clientArgs.setKeyRegExp(args[++j]); } else if (args[j].equals("-value")) { clientArgs.setValRegExp(args[++j]); } else { options.append(args[j]); options.append(" "); } } clientArgs.addOption(options.toString()); if (clientArgs.getKeyRegExp().isEmpty() && clientArgs.getValRegExp().isEmpty()) { System.out.println("ERROR : Both key and value parameters missing"); } String[] addresses = prop.getProperty("machines.address").split(","); //Create and start a list of client threads. Each thread takes server address and port as input. LinkedList<Thread> clientThreads = new LinkedList<Thread>(); for (int i = 0; i < addresses.length; i++) { String[] hostPort = addresses[i].split(":"); InetAddress address = InetAddress.getByName(hostPort[0]); Thread newThread = new LogQuerierClientThread(address, Integer.parseInt(hostPort[1]), clientArgs); newThread.start(); clientThreads.add(newThread); } //Each thread would create a temp file to store the grep output //from the server it talked to. This part of the code keeps track //completed threads. Once a thread completes,we open up the temp file //and print it out to the console. int completedThreads = 0; while (completedThreads != addresses.length) { for (int i = 0; i < clientThreads.size(); i++) { if (!clientThreads.get(i).isAlive()) { completedThreads++; printOutput(clientThreads.get(i)); clientThreads.remove(i); } } } }
9
public static MessageHandler getMessageHandler(Message message, ChatView chatView, ChatModel chatModel) throws UnknownMessageException { if (message instanceof ServerErrorMessage) { if (message instanceof FatalErrorMessage) { return new ServerErrorMessageHandler(message, chatView, chatModel); } else { return new RuntimeServerErrorMessageHandler(message, chatView, chatModel); } } if (message instanceof ChatMessage) { if (message instanceof ConnectEventMessage) { return new ConnectEventMessageHandler(message, chatView, chatModel); } else { if (message instanceof DisconnectEventMessage) { return new DisconnectEventMessageHandler(message, chatView, chatModel); } else { return new ChatMessageHandler(message, chatView, chatModel); } } } if (message instanceof ServerInfoMessage) { if (message instanceof ConnectionInterruptInfoMessage) { return new ServerInfoMessageHandler(message, chatView, chatModel); } else { return new RuntimeServerInfoMessageHandler(message, chatView, chatModel); } } if (message instanceof UsersOnlineServerMessage) { return new UsersOnlineServerMessageHandler(message, chatView, chatModel); } if (message instanceof ChatHistoryMessage) { return new ChatHistoryMessageHandler(message, chatView, chatModel); } throw new UnknownMessageException("Unknown message"); }
9
public static boolean isValueCode(char ch) { return ch == '@' || ch == ':' || ch == '%' || ch == '+' || ch == '#' || ch == '<' || ch == '>' || ch == '*' || ch == '/' || ch == '!'; }
9
private void writeToFile(double value) { /*we assume the file doesn't already exist*/ boolean newlyCreated = true, alreadyWritten = false; /*we count the number of lines in the file*/ int count = 0; try { File file = new File("/users/cristioara/workspace/CN_Tema06/out.txt"); /*if file doesn't exists, then create it*/ if (!file.exists()) { file.createNewFile(); } BufferedReader br = null; try { String sCurrentLine; br = new BufferedReader(new FileReader(file)); int startIndex = 0; double currentValue; while ((sCurrentLine = br.readLine()) != null) { newlyCreated = false; //the file already exists count++; startIndex = sCurrentLine.indexOf(">"); currentValue = Double.parseDouble(sCurrentLine.substring(startIndex + 2)); if (Math.abs(currentValue - value) <= Math.pow(10, -1)) alreadyWritten = true; } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null)br.close(); } catch (IOException ex) { ex.printStackTrace(); } } count++; FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); if (newlyCreated == true) bw.write("Solutia 1 --> " + String.valueOf(value)); else { if (alreadyWritten == false) { bw.newLine(); bw.append("Solutia " + count + " --> " + String.valueOf(value)); } } bw.flush(); fw.close(); bw.close(); } catch (IOException e) { e.printStackTrace(); } }
9
private void addGlobalSearchMenuItems(Menu submenu) { MenuItem pageSearchItem = new MenuItem(submenu, SWT.PUSH); pageSearchItem.addListener(SWT.Selection, new Listener () { public void handleEvent(Event e) { if (globalSearch.globalSearchAction()) { pageSearch.setSearchParameters(globalSearch.getLastSearchText(), -1, globalSearch.isCaseSensitive()); pageSearch.pageReSearchAction(false); } } }); pageSearchItem.setText ("Global Find.. \tCtrl + H"); pageSearchItem.setAccelerator(SWT.MOD1 | 'H'); MenuItem pageReSearchItem = new MenuItem (submenu, SWT.PUSH); pageReSearchItem.addListener(SWT.Selection, new Listener () { public void handleEvent(Event e) { if (globalSearch.globalReSearchAction()) { pageSearch.setSearchParameters(globalSearch.getLastSearchText(), -1, globalSearch.isCaseSensitive()); pageSearch.pageReSearchAction(false); } } }); pageReSearchItem.setText ("Global Find Next\tF4"); pageReSearchItem.setAccelerator(SWT.F4); }
2
@Override public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals(VentanaPrincipal.COMANDO_ABRIR_REPRODUCCION)) { ventanaPrincipal.manejoVentanaReproduccion('a'); }else if (event.getActionCommand().equals(VentanaReproduccion.COMANDO_CERRAR_REPRODUCCION)) { ventanaPrincipal.manejoVentanaReproduccion('c'); }else if (event.getActionCommand().equals(PanelGuardarNuevoArchivo.COMANDO_GUARDAR_CANCION)) { ventanaPrincipal.guardarCancion(); }else if (event.getActionCommand().equals(PanelGuardarNuevoArchivo.COMANDO_BOX_GENERO)) { ventanaPrincipal.actualizaBoxAutores((Genero) ((JComboBox)event.getSource()).getSelectedItem());; }else if (event.getActionCommand().equals(PanelGuardarNuevoArchivo.COMANDO_NUEVO_ARTIST)) { ventanaPrincipal.crearArtistaOCancion('a'); }else if (event.getActionCommand().equals(PanelGuardarNuevoArchivo.COMANDO_GUARDAR_CANCION)) { ventanaPrincipal.crearArtistaOCancion('c'); } }
6
protected void processSkipBlocks(List<String> skipBlocks) { if(generateStatistics) { for(String block : skipBlocks) { statistics.setPreservedSize(statistics.getPreservedSize() + block.length()); } } }
2
@Override public List<Role> findRoleByAccountId(int accountId) { List<Role> list = new ArrayList<Role>(); Connection cn = null; PreparedStatement ps = null; ResultSet rs = null; try { cn = ConnectionHelper.getConnection(); ps = cn.prepareStatement(QTPL_SELECT_BY_ACCOUNT_ID); ps.setInt(1, accountId); rs = ps.executeQuery(); while (rs.next()) { list.add(processResultSet(rs)); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } try { cn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; }
5
public void update() { float newX = x + moveAmountX; float newY = y + moveAmountY; moveAmountX = 0; moveAmountY = 0; ArrayList<GameObject> objects = Game.rectangleCollide(newX, newY, newX + SIZE, newY + SIZE); ArrayList<GameObject> items = new ArrayList<GameObject>(); boolean move = true; for(GameObject go : objects) { if(go.getType() == ITEM_ID) items.add(go); if(go.getSolid()) move = false; } if(!move) return; x = newX; y = newY; for(GameObject go : items) { System.out.println("You just picked up "+((Item)go).getName()+"!"); go.remove(); addItem((Item)go); } }
5
public static double getDouble(String prompt, double low, double high) { final int ALLOWABLE_INPUT_FAILURES = 3; // Avoid leaving a user stuck in here infinitely. If they fail to enter an int after 3 tries, bail out anyway. String response; int inputFailureCount = 0; while (true) { // use an infinite loop. Exit will occur on return if they enter a valid <i>int</i> or after exhausting the attempt limit. // try-block used to manage an interaction where there may be a failure: in particular, a user might enter something other than a parseable <i>int</i> value try { response = JOptionPane.showInputDialog(prompt); // no possible failure here, since we can pick up any pattern of characters // Possible failure on following line, since non-<i>double</i> characters will generate an exception in the <i>Double.parseDouble()</i> method // If a failure occurs in the <i>Double.parseDouble()</i> method call, then program execution will <i>throw</i> an exception that will immediately // abandon the <i>try</i>-block and jump to the closest matching <i>catch</i>-block. double convertedResponse = Double.parseDouble(response); // we can only arrive here if the <i>Integer.parseInt()</i> method returned normally, that is, it did not <i>throw</i> an exception. if (convertedResponse < low || convertedResponse > high) { if (++inputFailureCount > ALLOWABLE_INPUT_FAILURES) { showErrorGUI("Too many unsuccessful attempts. Setting to 0"); return 0.0; // exits on failure to complete input operation } showErrorGUI("Number must be between " + low + " and " + high + " (inclusive)."); } else return convertedResponse; // exits on successful completion of input operation } catch (NumberFormatException | NullPointerException exception) { // only arrive here if there was a failure in the <i>Double.parseInt()</i> method or <Esc> at dialog if (++inputFailureCount < ALLOWABLE_INPUT_FAILURES) { showErrorGUI("You must enter an integer."); } else { showErrorGUI("Too many unsuccessful attempts. Setting to 0"); return 0.0; // exits on failure to complete input operation } } } } // end public static double getDouble()
6
@Override public int hashCode() { if (hashCode == 0) { int result = fromViewId != null ? fromViewId.hashCode() : 0; result = 31 * result + (fromAction != null ? fromAction.hashCode() : 0); result = 31 * result + (fromOutcome != null ? fromOutcome.hashCode() : 0); result = 31 * result + (condition != null ? condition.hashCode() : 0); result = 31 * result + (toViewId != null ? toViewId.hashCode() : 0); result = 31 * result + (toFlowDocumentId != null ? toFlowDocumentId.hashCode() : 0); result = 31 * result + (redirect ? 1 : 0); result = 31 * result + (parameters != null ? parameters.hashCode() : 0); hashCode = result; } return hashCode; }
9
private synchronized int count_servers(int numberOfUsers, int thrPerEngine) { int servers; if (thrPerEngine == 0) { servers = 0; } else { servers = numberOfUsers / thrPerEngine; if (numberOfUsers % thrPerEngine > 0) { servers++; } } return servers; }
2
private ArrayList<String[]> splitPacketsFromStream(String message){ ArrayList<String[]> packets = new ArrayList<>(); ArrayList<String> tempPacket = new ArrayList<>(); int i = 1; int j = 1; if(!Character.isDigit(message.charAt(1))){ tempPacket.add(PacketTypes.INVALID.toString()); packets.add(tempPacket.toArray(new String[tempPacket.size()])); //toarray orginally returns array of objects return packets; } for(i = 1; i < message.length(); i++){ char c = message.charAt(i); if(!Character.isDigit(c)){ try{ int typeLength = Integer.parseInt(message.substring(j,i)) + 1; //check if is the escape character notifying the end of a packet if(typeLength == 2 && message.substring(i+1, i + typeLength).equals(";")){ String[] subpacket = tempPacket.toArray(new String[tempPacket.size()]); packets.add(subpacket); tempPacket.clear(); }else{ //build up on our packet tempPacket.add(message.substring(i+1, i + typeLength)); //add 1 to i to skip the : } //great we've found a number so lets next part of the string as that will contain the //the argument i += typeLength + 1; i = i >= message.length() ? message.length()-1 : i; j = i; }catch(NumberFormatException e){ return packets; } } } return packets; }
7
@Override public void actionPerformed(ActionEvent e) { // Get selected action. final String action = (String) comboBox.getSelectedItem(); // Get all panels that are drawn. Component[] panels = pane.getComponents(); // Selected panels. final ArrayList<GElement> elementPanels = new ArrayList<GElement>(); for (Component panel : panels) { // Selected panels. if (((GElement) panel).getToolTipText() != null && ((GElement) panel).getToolTipText() .compareTo("selected") == 0) { elementPanels.add((GElement) panel); } } Thread actionThread = new Thread() { @Override public void run() { try { if (elementPanels.size() == 0) { ErrorMessage.show("Nu a fost selectat niciun element", false); } else if (action.compareTo(ElementsActions.S_OCR .toString()) == 0) { new OCRComponents(elementPanels, layoutGUI); } else if (action.compareTo(ElementsActions.S_GLUE .toString()) == 0) { new GlueElements(elementPanels, layoutGUI); } } catch (Exception e) { ErrorMessage.show("Eroare la rularea analizei OCR", false); } } }; actionThread.start(); }
7
public static ArrayList getOpOp(String arg_op) throws SQLException, ClassNotFoundException, NumberFormatException { ArrayList sts = new ArrayList(); Connection conPol = conMgr.getConnection("PD"); ResultSet rs; if (conPol == null) { throw new SQLException("Numero Maximo de Conexoes Atingida!"); } try { call = conPol.prepareCall("{call sp_op_resumo_reg3(?)}"); call.setInt(1, Integer.valueOf(arg_op)); rs = call.executeQuery(); while (rs.next()) { sts.add("<a href=consultaServ?acao=opsConsultaOp&txt_op=" + rs.getInt("op") + ">" + rs.getInt("op") + "</a> \t" + rs.getDate("data_op") + "\t" + rs.getString("nroserieini") + "\t" + rs.getString("nroseriefim") + "\t" + formatt.format(rs.getTimestamp("dt_min")) + "\t" + formatt.format(rs.getTimestamp("dt_max")) + "\t" + rs.getInt("qtd_op") + "\t" + rs.getInt("cont") + "\t" + rs.getString("item") + " \t" + formatt.format(rs.getTimestamp("dt_prevista")) + "\t- " + rs.getInt("media") + " \t" + rs.getFloat("yield") + "%" ); } } finally { if (conPol != null) { conMgr.freeConnection("PD", conPol); } } return sts; }
3
public void dumpInstruction(alterrs.jode.decompiler.TabbedPrintWriter writer) throws java.io.IOException { writer.closeBraceContinue(); writer.print("catch ("); writer.printType(exceptionType); writer.print(" " + (exceptionLocal != null ? exceptionLocal.getName() : "PUSH") + ")"); writer.openBrace(); writer.tab(); catchBlock.dumpSource(writer); writer.untab(); }
1
private String postprocessing(String world) { // TODO Auto-generated method stub boolean cond; cond = "".equals(world) || "zeus".equals(world) || world.endsWith("a") || world.endsWith("e") || world.endsWith("i") || world.endsWith("o") || world.endsWith("u") || world.endsWith("r") || world.endsWith("S"); if(!cond) return world.substring(0, world.length()-1) ; else return world; }
9
public static void killme(int num) { if (num==1){ if (server1 != null) {server1.interrupt();} }else{ if (server2 != null) {server2.interrupt();} } }
3
public String getAmount(){ String result = ""; if(gold < 1000) result = Integer.toString(gold); if(gold >= 1000) result = Integer.toString(gold / 1000) + "k"; if(gold >= 1000000) result = Integer.toString(gold / 1000000) + "m"; if(gold >= 1000000000) result = Integer.toString(gold / 1000000000) + "b"; return result; }
4
private void pasteText(){ if(activField.equals("textArea")) textArea.insert(pasteFromClipboard(),textArea.getCaretPosition()); if(activField.equals("fieldNameFile")) fieldNameFile.setText(pasteFromClipboard()); if(activField.equals("fieldCommandLine")) fieldCommandLine.setText(pasteFromClipboard()); }
3
@Override public boolean removeAll(Collection<?> c) { boolean removed = false; for (Object o : c) { removed |= remove(o); } return removed; }
2
@Test public void hahmoPutoaaKorkealta() { pe.siirra(0, -50); int hahmonKoordinaattiAlussa = pe.getY(); t.lisaaEste(e); for (int i = 0; i < 100; i++) { pe.eksistoi(); } assertTrue("Hahmo ei pysähtynyt esteesen vaan jatkoi y = " + pe.getY(), pe.getY() <= 10); }
1
public void evaluateStack(){ validateEvaluateStack(); while(!operatorStack.empty()){ operandStack.push( op.performOperation(operandStack.pop(), operandStack.pop(), operatorStack.pop()) ); } }
1
private void unfilterPaeth(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += prevLine[i]; } for(int n=curLine.length ; i<n ; ++i) { int a = curLine[i - bpp] & 255; int b = prevLine[i] & 255; int c = prevLine[i - bpp] & 255; int p = a + b - c; int pa = p - a; if(pa < 0) pa = -pa; int pb = p - b; if(pb < 0) pb = -pb; int pc = p - c; if(pc < 0) pc = -pc; if(pa<=pb && pa<=pc) c = a; else if(pb<=pc) c = b; curLine[i] += (byte)c; } }
8
public void setOutline(Color outline) { this.outline = outline; }
0
public int pointToSymbol(int midCount, ByteSet exclusions) { int sum = 0; for (int mid = 0; ; ++mid) { if (mid != EOF_INDEX && exclusions.contains(mid)) continue; sum += _count[mid]; if (sum > midCount) return (mid == EOF_INDEX) ? ArithCodeModel.EOF : mid; } }
5
public void setTipoMovimiento(String tipoMovimiento) { this.tipoMovimiento = tipoMovimiento; }
0
@Override public AlgorithmResult<V, E> start(final V vertex, final V startVertex, final V endVertex) throws IllegalGraphException { if (startVertex == null) { throw new IllegalArgumentException("The start vertex can not be null"); } if (endVertex == null) { throw new IllegalArgumentException("The end vertex can not be null"); } if (startVertex == endVertex) { throw new IllegalArgumentException("The start and end vertices could not be the same"); } final AlgorithmResult<V, E> algorithmResult = algorithmExecutor.start("breadthfirst", vertex); final List<E> edges = algorithmResult.getBreadthFirstResult().getEdges(); for (final E edge : edges) { addResidualEdge(algorithmExecutor.retrieveStartVertex(edge), algorithmExecutor.retrieveEndVertex(edge), algorithmExecutor.retrieveEdgeWeight(edge), 0); } Set<ResidualEdge<V>> path = findPath(startVertex, endVertex); while (path != null) { double minFlow = Double.MAX_VALUE; for (ResidualEdge e : path) { minFlow = Math.min(minFlow, e.residualCapacity); } for (ResidualEdge<V> e : path) { flow.put(e, flow.get(e) + minFlow); flow.put(e.reverseEdge, flow.get(e.reverseEdge) - minFlow); } path = findPath(startVertex, endVertex); } double maxFlow = 0; for (ResidualEdge residualEdge : adj.get(startVertex)) { maxFlow += flow.get(residualEdge); } return new AlgorithmResult<>(new MaxFlowResult(maxFlow)); }
8
public void generateSearchResults(){ irLists = new ArrayList<IRList>(); q = queryParser.nextQuery(); // while (q != null){ // ArrayList<DocScore> docScores = iRmodel.getRanking(q.toQueryHash()); // PageRank pageRank = new PageRank(); // pageRank.setNSeed(nSeed); // pageRank.setNPointed(nPointed); // pageRank.setIndex(index); // pageRank.setNIteration(nIteration); // pageRank.setDocScores(docScores); // pageRank.run(); // System.out.println("Done!"); // docScores = pageRank.getRanking(); // // ArrayList<Integer> docs = new ArrayList<Integer>(); // for (DocScore docScore : docScores) { // docs.add((int) docScore.doc); // } // irLists.add(new IRList(q, docs)); // q = queryParser.nextQuery(); // } // Multi-thread ArrayList<Thread> threads = new ArrayList<Thread>(); final ArrayList<Query> queries = new ArrayList<Query>(); while (q != null){ queries.add(q); q = queryParser.nextQuery(); } final ArrayList<RandomWalk> randomWalks = new ArrayList<RandomWalk>(); for (int i = 0; i < queries.size(); i++){ RandomWalk randomWalk; if (randomWalkMode == 0) randomWalk = new PageRank(); else randomWalk = new HITS(); randomWalk.setNSeed(nSeed); randomWalk.setNPointed(nPointed); randomWalk.setIndex(index); randomWalk.setNIteration(nIteration); randomWalks.add(randomWalk); } for (int i = 0; i < queries.size(); i++){ final int finalI = i; Thread t = new Thread(){ public void run(){ ArrayList<DocScore> docScores = iRmodel.getRanking(queries.get(finalI).toQueryHash()); if (randomWalkMode != -1){ RandomWalk randomWalk = randomWalks.get(finalI); randomWalk.setDocScores(docScores); randomWalk.run(); docScores = randomWalk.getRanking(); } ArrayList<Integer> docs = new ArrayList<Integer>(); for (DocScore docScore : docScores) { docs.add((int) docScore.doc); } irLists.add(new IRList(queries.get(finalI), docs)); } }; threads.add(t); t.start(); } for (Thread t : threads){ try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } saveResults(); }
8
public ArrayList<ArrayList<Float>> ArraytoArrayList(float[][] arr){ ArrayList<ArrayList<Float>> arrayL = new ArrayList<ArrayList<Float>>(); for (int j = 0; j < arr[0].length; j++) { ArrayList<Float> tempL = new ArrayList<Float>(); for (int i = 0; i < arr.length; i++) { tempL.add(arr[i][j]); } arrayL.add(tempL); } return arrayL; }
2
private static int[] LastNWLine(int m, int n, String A, String B) { int[][] K = new int[2][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 0; j <= n; j++) K[0][j] = K[1][j]; for (int j = 1; j <= n; j++) { if (A.charAt(i - 1) == B.charAt(j - 1)) K[1][j] = K[0][j - 1] + 1; else K[1][j] = Math.max(K[1][j - 1], K[0][j]); if (i == m && j == n) return K[1]; } } return null; }
6
@Override public void encode() throws IOException { System.out.println("Starting compression of file \"" + sourceFile.getFileName() + "\" to \"" + destinationFile.getFileName() + "\""); totalTimer = new Timer().start(); // Count the number of occurences of each character in the file printMessage("Counting characters in file " + sourceFile.getFileName() + "... "); countCharactersInFile(); printTime(); // Build the tree from this count printMessage("Building Huffman Tree from character count... "); buildTree(); printTime(); // Get the character codes from the tree printMessage("Generating character codes from tree... "); sortedCodes = huffmanTree.getCharacterCodes(); printTime(); if (sortedCodes.size() == 0) { throw new IllegalArgumentException("Why do you want to compress an empty file ?"); } else if (sortedCodes.size() == 1) { handleOneCharFile(sortedCodes.pollFirst().getChar()); } // Write the Tree to the file printMessage("Writing tree string representation as output file header... "); writeTree(); printTime(); // Create the codesArray for encoding createCodeArray(); // Encode source file printMessage("Encoding source file... "); try (final BufferedReader reader = Files.newBufferedReader(sourceFile, CHARSET); final FileOutputStream writer = new FileOutputStream(destinationFile.toFile(), true)) { final char[] readBuffer = new char[8192]; // Char size = 1 byte // CharacterCodes max length : 256 differents chars, max length = 256 // So a buffer with a size equals to the char buffer is enough final BitArray writeBuffer = new BitArray(8192); int length; do { length = reader.read(readBuffer); for (int i = 0; i < length; i++) { writeBuffer.add(codesArray[readBuffer[i]]); } writer.write(writeBuffer.pollByteArray()); //pollByteArray removes the bytes it returns } while (length == readBuffer.length); if (writeBuffer.hasRemainingByte()) { // Last byte does not contain 8 interesting bits final int lastByteLength = writeBuffer.getLastByteLength(); writer.write(writeBuffer.getLastByte()); //write the last byte writer.write((byte) Byte.SIZE - lastByteLength);//write the number of interesting bits in the last byte } else { // Last byte is full writer.write(0x00); } } printTime(); System.out.println("Compression successful !\n Time: " + totalTimer.stop().diffString() + "\n Compression rate: " + new DecimalFormat("#0.00").format(100 - 100.0 * Files.size(destinationFile) / Files.size(sourceFile)) + "%"); }
5
private static void parseConfig(StyleConfig styleConfig, Element doc) { NodeList childs = doc.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { Node node = childs.item(i); if ("is-fix-size".equals(node.getNodeName())) { styleConfig.setIsFixSize(Boolean.parseBoolean(node .getTextContent())); } else if ("canvas-width".equals(node.getNodeName())) { styleConfig.setCanvasWidth(Integer.parseInt(node .getTextContent())); } else if ("canvas-height".equals(node.getNodeName())) { styleConfig.setCanvasHeight(Integer.parseInt(node .getTextContent())); } else if ("background-color".equals(node.getNodeName())) { styleConfig .setBackgroundColor(parseColor(node.getTextContent())); } else if ("background-image".equals(node.getNodeName())) { String url = node.getTextContent(); InputStream is = ConfigParser.class.getResourceAsStream(url); try { styleConfig.setBackgroundImage(IOUtils.toByteArray(is)); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(is); } } } }
7
@Override public int[] batchUpdate(String... sql) { try { Connection connection = getConnection(); Statement stmt = connection.createStatement(); for (String string : sql) { stmt.addBatch(string + ';'); } int[] out = stmt.executeBatch(); JdbcUtil.closeStatement(stmt); JdbcUtil.closeConnection(connection); return out; } catch (SQLException e) { throw new RuntimeException(e.getSQLState() + "\nCaused by\n" + e.getCause(), e); } }
2
Item newInvokeDynamicItem(final String name, final String desc, final Handle bsm, final Object... bsmArgs) { // cache for performance ByteVector bootstrapMethods = this.bootstrapMethods; if (bootstrapMethods == null) { bootstrapMethods = this.bootstrapMethods = new ByteVector(); } int position = bootstrapMethods.length; // record current position int hashCode = bsm.hashCode(); bootstrapMethods.putShort(newHandle(bsm.tag, bsm.owner, bsm.name, bsm.desc)); int argsLength = bsmArgs.length; bootstrapMethods.putShort(argsLength); for (int i = 0; i < argsLength; i++) { Object bsmArg = bsmArgs[i]; hashCode ^= bsmArg.hashCode(); bootstrapMethods.putShort(newConst(bsmArg)); } byte[] data = bootstrapMethods.data; int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments) hashCode &= 0x7FFFFFFF; Item result = items[hashCode % items.length]; loop: while (result != null) { if (result.type != BSM || result.hashCode != hashCode) { result = result.next; continue; } // because the data encode the size of the argument // we don't need to test if these size are equals int resultPosition = result.intVal; for (int p = 0; p < length; p++) { if (data[position + p] != data[resultPosition + p]) { result = result.next; continue loop; } } break; } int bootstrapMethodIndex; if (result != null) { bootstrapMethodIndex = result.index; bootstrapMethods.length = position; // revert to old position } else { bootstrapMethodIndex = bootstrapMethodsCount++; result = new Item(bootstrapMethodIndex); result.set(position, hashCode); put(result); } // now, create the InvokeDynamic constant key3.set(name, desc, bootstrapMethodIndex); result = get(key3); if (result == null) { put122(INDY, bootstrapMethodIndex, newNameType(name, desc)); result = new Item(index++, key3); put(result); } return result; }
9
public void parse(HttpParams params) { if (params.exists("swLat")) { swLat = Double.parseDouble(params.getFirst("swLat")); } if (params.exists("swLon")) { swLon = Double.parseDouble(params.getFirst("swLon")); } if (params.exists("neLat")) { neLat = Double.parseDouble(params.getFirst("neLat")); } if (params.exists("neLon")) { neLon = Double.parseDouble(params.getFirst("neLon")); } for (String filterName : filterNames) { if (params.exists(filterName)) { List<String> values = new ArrayList<String>(); String[] arr = StringUtils.split(params.getFirst(filterName), ","); for (String value : arr) { values.add(value); } if (values.size() > 0) { filterMap.put(filterName, values); } } } }
8
private boolean validMovesExist(){ List<Integer> diceOptions = diceRoll; //Check bar Location barOfPlayerInTurn = getBarOfPlayerInTurn(); int barCount = getCount(barOfPlayerInTurn); if(barCount > 0){ for(int j = 0; j < diceOptions.size(); j++){ Location to = getToLocationFromBar(diceOptions.get(j)); if(moveValidator.isValid(barOfPlayerInTurn, to)){ return true; } } } //Check Rest of Locations if Bar is empty else{ for(Location frmLoc : Location.values()){ if(getCount(frmLoc) > 0 && getColor(frmLoc) == playerInTurn){ for(int j = 0; j < diceOptions.size(); j++){ Location to = Location.findLocation(playerInTurn, frmLoc, diceOptions.get(j)); if(moveValidator.isValid(frmLoc, to)){ return true; } } } } } //No valid moves: return false; }
8
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FormularioProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormularioProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormularioProducto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormularioProducto.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 FormularioProducto().setVisible(true); } }); }
6
@Override public String execute() throws Exception { if (cid == 0 || account ==null) return ERROR; System.out.println("have the account:" + account + " cid:" + cid); HttpSession session=ServletActionContext.getRequest().getSession(); User host = (User) session.getAttribute(com.ccf.action.user.UserLoginAction.USER_SESSION); if (host == null) return LOGIN; if (!this.service.verifyLeader(cid, host.getUid())) { //the host is not the leader of this club this.addFieldError("account", "U r not the leader,SUCKER"); return "limited"; //that's mean authority limited, it's U r not the fucking leader } User guest = this.service.findUserByAccount(account); if (guest == null) { //invalid account this.addFieldError("account", "No Such User Exist!"); System.out.println("invite result no user existed"); return "reinvite"; } if (guest.getUid() == host.getUid()) return "sb"; // don't invite yourself if (this.service.tryInviteNewMember(account, cid).equals("OK")) { this.service.invite(cid, host.getUid(), guest.getUid()); return SUCCESS; } System.out.println(this.service.tryInviteNewMember(account, cid)); return this.service.tryInviteNewMember(account, cid); }
7
public GTFSPlugin getPlugin(){ if (plugin == null){ synchronized (this) { String pluginName = properties.getProperty("plugin"); if (pluginName == null){ plugin = new DefaultPlugin(); }else{ try{ Class<?> pluginClass = Class.forName(pluginName); boolean validPlugin = false; for (Class<?> c : pluginClass.getInterfaces()) { if (c.equals(GTFSPlugin.class)) { validPlugin = true; } } if (validPlugin) plugin = (GTFSPlugin) pluginClass.newInstance(); else throw new IllegalArgumentException("The specified plugin is not found or not valid"); }catch (Exception e) { throw new IllegalArgumentException("The specified plugin is not found or not valid"); } } } } return plugin; }
8
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0) &&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS)) &&((msg.amITarget(affected))) &&(CMLib.flags().isAnimalIntelligence(msg.source()))) { final MOB target=(MOB)msg.target(); if((!target.isInCombat()) &&(msg.source().location()==target.location()) &&(msg.source().getVictim()!=target)) { msg.source().tell(L("You feel too friendly towards @x1",target.name(msg.source()))); if(target.getVictim()==msg.source()) { target.makePeace(true); target.setVictim(null); } return false; } } return super.okMessage(myHost,msg); }
8
public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) { return 0; } int[] left = new int[prices.length]; int[] right = new int[prices.length]; int maxSofar = 0, minSofar = 0; for (int i = 0; i < prices.length; i++) { if (i == 0) { minSofar = prices[i]; } else { if (prices[i] >= minSofar) { maxSofar = Math.max(maxSofar, prices[i] - minSofar); left[i] = maxSofar; } else { minSofar = prices[i]; left[i] = maxSofar; } } } maxSofar = 0; int maxPrice = 0; for (int i = prices.length - 1; i >= 0; i--) { if (i == prices.length - 1) { maxPrice = prices[i]; } else { if (prices[i] >= maxPrice) { maxPrice = prices[i]; right[i] = maxSofar; } else { maxSofar = Math.max(maxSofar, maxPrice - prices[i]); right[i] = maxSofar; } } } int max = 0; for (int i = 0; i != left.length; i++) { max = Math.max(max, left[i] + right[i]); } return max; }
9
private void clearPath() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if(lab.getWalkways()[i][j] == null) lab.getWalkways()[i][j] = true; } } }
3
private boolean recoverRequest(Request request) { if (request.site == null) { System.out.println("error: recovery request have no site"); return false; } if (request.site != null) if (!this.siteMap.containsKey(request.site)) { System.out.println("error: recovery request site [" + request.site + "] does not exists"); return false; } if (this.siteMap.get(request.site).isRunning()) { System.out.println("error: recovery request site [" + request.site + "] is running"); return false; } this.siteMap.get(request.site).recover(); return true; }
4
private String extractImageID(final String leaseDescription) { assert leaseDescription.startsWith("api services lease granted by "); String currentImageID = leaseDescription.substring(30); final int firstSpaceIndex = currentImageID.indexOf(" "); if (firstSpaceIndex > 0) { currentImageID = currentImageID.substring(0, firstSpaceIndex); } return currentImageID; }
1
public PaymentEntity() { setId(System.nanoTime()); }
0
public void seeking() { if (getDistanceToTarget() < SEEKING_TO_ATTACKING_DISTANCE) { setState(STATE_ATTACKING, "distance to " + target + " is within attacking distance while seeking"); return; } else if (getDistanceToTarget() > IDLING_TO_SEEKING_DISTANCE) { setState(STATE_IDLING, "distance to target is outside seeking distance while seeking"); return; } moveTowardTarget(); }
2
@Override public boolean mayICraft(final Item I) { if(I==null) return false; if(!super.mayBeCrafted(I)) return false; if((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN) return false; if(CMLib.flags().isDeadlyOrMaliciousEffect(I)) return false; if(!(I instanceof Container)) return false; final Container C=(Container)I; if((C.containTypes()==Container.CONTAIN_CAGED) ||(C.containTypes()==(Container.CONTAIN_BODIES|Container.CONTAIN_CAGED))) return true; if(isANativeItem(I.Name())) return true; return false; }
8
@Override public void update() { if (Physics.checkCollisions(this, ball)) ball.paddleBounce(getCenterY()); float speed = (ball.getCenterY() - getCenterY()) * DAMPING; if (speed > MAX_SPEEDY) speed = MAX_SPEEDY; else if (speed < -MAX_SPEEDY) speed = -MAX_SPEEDY; yPos += speed; }
3
@Override public HeightMap applyTo(HeightMap... heightMaps){ double[][] finalHeights = heightMaps[0].getHeights(); int xSize = finalHeights.length; int ySize = finalHeights[0].length; for(int iteration = 0; iteration<numIterations; iteration++) { if (iteration % 10 == 0) System.out.println("AverageFilter " + 100 * iteration / numIterations + "% complete"); for (int x = 0; x < xSize; x++) { for (int y = 0; y < ySize; y++) { //for non-reversed, move a quantity equal to (maxDifference-tAngle)/2 double heightDifference = maxDifference( finalHeights[x][y], finalHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize], finalHeights[(x+xSize-1)%xSize][(y+1)%ySize], finalHeights[(x+1)%xSize][(y+ySize-1)%ySize], finalHeights[(x+1)%xSize][(y+1)%ySize] ); //if the maximum difference is less than the talus angle, //find the neighbor with the most difference and give it some of the center's soil if(heightDifference>tAngle){ //System.out.println("\nHeight difference: "+heightDifference); //System.out.println("Height before: "+finalHeights[x][y]); if(abs(finalHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize] - finalHeights[x][y]) == heightDifference){ finalHeights[x][y] -= (heightDifference-tAngle)*solubility/2; finalHeights[(x+xSize-1)%xSize][(y+ySize-1)%ySize]+=(heightDifference-tAngle)*solubility/2; } else if(abs(finalHeights[(x+xSize-1)%xSize][(y+ySize+1)%ySize] - finalHeights[x][y]) == heightDifference){ finalHeights[x][y] -= (heightDifference-tAngle)*solubility/2; finalHeights[(x+xSize-1)%xSize][(y+1)%ySize]+=(heightDifference-tAngle)*solubility/2; } else if(abs(finalHeights[(x+xSize+1)%xSize][(y+ySize-1)%ySize] - finalHeights[x][y]) == heightDifference){ finalHeights[x][y] -= (heightDifference-tAngle)*solubility/2; finalHeights[(x+1)%xSize][(y+ySize-1)%ySize]+=(heightDifference-tAngle)*solubility/2; } else if(abs(finalHeights[(x+xSize+1)%xSize][(y+ySize+1)%ySize] - finalHeights[x][y]) == heightDifference){ finalHeights[x][y] -= (heightDifference-tAngle)*solubility/2; finalHeights[(x+1)%xSize][(y+1)%ySize]+=(heightDifference-tAngle)*solubility/2; } //System.out.println("Height after: "+finalHeights[x][y]); } } } } return new HeightMap(finalHeights); }
9
public Limbs getLimbs() { return limbs; }
0
public LowerTilter() { requires(Robot.tilter); }
0
public static int loadTexture(BufferedImage image) { int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); // 4 for RGBA, 3 for RGB for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component buffer.put((byte) (pixel & 0xFF)); // Blue component buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. // Only for RGBA } } buffer.flip(); // FOR THE LOVE OF GOD DO NOT FORGET THIS // You now have a ByteBuffer filled with the color data of each pixel. // Now just create a texture ID and bind it. Then you can load it using // whatever OpenGL method you want, for example: int textureID = glGenTextures(); // Generate texture ID glBindTexture(GL_TEXTURE_2D, textureID); // Bind texture ID // Setup wrap mode glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); // Setup texture scaling filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Send texel data to OpenGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); // Return the texture ID so we can bind it later again return textureID; }
2
private void evalNewArray(int pos, CodeIterator iter, Frame frame) throws BadBytecode { verifyAssignable(Type.INTEGER, simplePop(frame)); Type type = null; int typeInfo = iter.byteAt(pos + 1); switch (typeInfo) { case T_BOOLEAN: type = getType("boolean[]"); break; case T_CHAR: type = getType("char[]"); break; case T_BYTE: type = getType("byte[]"); break; case T_SHORT: type = getType("short[]"); break; case T_INT: type = getType("int[]"); break; case T_LONG: type = getType("long[]"); break; case T_FLOAT: type = getType("float[]"); break; case T_DOUBLE: type = getType("double[]"); break; default: throw new BadBytecode("Invalid array type [pos = " + pos + "]: " + typeInfo); } frame.push(type); }
8
public void test_DateTime_setHourZero_Gaza() { DateTime dt = new DateTime(2007, 4, 1, 8, 0, 0, 0, MOCK_GAZA); assertEquals("2007-04-01T08:00:00.000+03:00", dt.toString()); try { dt.hourOfDay().setCopy(0); fail(); } catch (IllegalFieldValueException ex) { // expected } }
1
public void method353(int i, double d, int l1) { // all of the following were parameters int j = 15; int k = 20; int l = 15; int j1 = 256; int k1 = 20; // all of the previous were parameters try { int i2 = -k / 2; int j2 = -k1 / 2; int k2 = (int) (Math.sin(d) * 65536D); int l2 = (int) (Math.cos(d) * 65536D); k2 = k2 * j1 >> 8; l2 = l2 * j1 >> 8; int i3 = (l << 16) + (j2 * k2 + i2 * l2); int j3 = (j << 16) + (j2 * l2 - i2 * k2); int k3 = l1 + i * RSDrawingArea.width; for (i = 0; i < k1; i++) { int l3 = k3; int i4 = i3; int j4 = j3; for (l1 = -k; l1 < 0; l1++) { int k4 = myPixels[(i4 >> 16) + (j4 >> 16) * myWidth]; if (k4 != 0) RSDrawingArea.pixels[l3++] = k4; else l3++; i4 += l2; j4 -= k2; } i3 += k2; j3 += l2; k3 += RSDrawingArea.width; } } catch (Exception _ex) { } }
4
public void makeMove(Piece piece) { if(validMove(piece)) { ArrayList<Piece> captured = piece.getCapturedPieces(this); for(Piece p : captured) { p.setColor(p.getColor().getOpposite()); } addPiece(piece); } }
2
public boolean getvar2(String stat) { StringTokenizer str = new StringTokenizer(stat, ","); while (str.hasMoreTokens()) { String line = str.nextToken(); String first = "", second = "", relation = ""; boolean check = false; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '=' || line.charAt(i) == '>' || line.charAt(i) == '<') { check = true; relation += line.charAt(i); continue; } if (check) { second += line.charAt(i); } else { first += line.charAt(i); } } if (!check) { return false; } entries.add(new Field(first, second, relation.charAt(0))); } return true; }
7
private String parseDuration(String time){ if (time != null){ double number = Double.parseDouble(time)/60; return String.format("%.2f", number)+ " mins"; } return "NA"; }
1
public void sortColors(int[] A) { if(A == null || A.length == 0) return; int first = 0; int end = A.length -1; while (first <= end &&A[first] == 0) first++; first--; while (end >= 0 && A[end] == 2) end--; end++; int i = first+1; while (i < end){ if(A[i] == 2){ swap(A,i,--end); } else if(A[i] == 0){ swap(A, i++, ++first); } else { i++; } } }
9
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { //GEN-FIRST:event_jButton1ActionPerformed list = new LunchDao(); } catch (SAXException ex) { Logger.getLogger(addItemToLunchMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(addItemToLunchMenu.class.getName()).log(Level.SEVERE, null, ex); } Name = getItemName(); Description = getItemDescriptionName(); Price = getItemPrice(); PictureName = getPictureName(); if(Name.equals("") || Description.equals("") || Price.equals("") || PictureName.equals("")){ JOptionPane.showMessageDialog(this, "YOU MUST ENTER ALL INFORMATION", "CHECK VALUES AGAIN", JOptionPane.ERROR_MESSAGE); } else{ list.addLunch(Name,Description, 1,Price,PictureName); System.out.println(getItemName()+' '+getItemDescriptionName()+" " + getItemPrice()+" "+getPictureName()); JOptionPane.showMessageDialog(this, "YOUR ITEM HAS BEEN ADDED!!!", "CONFIRMATION DIALOG", JOptionPane.WARNING_MESSAGE); itemNameValue.setText(""); itemDescriptionValue.setText(""); itemPriceValue.setText("0"); itemPictureValue.setText("Click Here To Select Image"); adminLogInDialog.lunchMenu.removeAll(); try { adminLogInDialog.lunchMenu.setUpComponents(); } catch (SAXException ex) { Logger.getLogger(addItemToLunchMenu.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(addItemToLunchMenu.class.getName()).log(Level.SEVERE, null, ex); } adminLogInDialog.lunchEditPane.revalidate(); } }//GEN-LAST:event_jButton1ActionPerformed
8
public Table (String filePath){ super(); this.filePath = filePath; robot = new Robot(); robot.X = 200; robot.Y = 150; robot.teta = 0; }
0
public void putAll( Map<? extends K, ? extends Short> map ) { Iterator<? extends Entry<? extends K,? extends Short>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends K,? extends Short> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
public Player waitForServerPlayer() throws IOException { // TODO Send server our player info this.send("JOIN " + this.ourPlayer.getName() + " " + this.ourPlayer.getSignature()); while (true) { String[] tokens = this.inStream.readLine().split(" "); if (tokens[0].equals("JOIN")) { remotePlayer = new Player(tokens[1]); return remotePlayer; } } }
2
public void actionPerformed(ActionEvent e) { JButton currentButton = (JButton) e.getSource(); final int index = (int) currentButton.getClientProperty("index"); day = (index < COL) ? 0 : 1; time = index % COL; if (selectMany) { Color btnBack = currentButton.getBackground(); if (btnBack.equals(Color.white)) { if ((int) currentButton.getClientProperty("availability") == 0) setColor(currentButton, 1); else setColor(currentButton, 3); availability[day][time] = !availability[day][time]; } else if (btnBack.equals(Color.orange)) { setColor(currentButton, 0); availability[day][time] = !availability[day][time]; } else if (obeyConflict()) { currentButton.setEnabled(true); currentButton.setBackground(Color.white); availability[day][time] = !availability[day][time]; } } else if (obeyConflict()) { for (JButton btn : button) { if ((boolean) btn.getClientProperty("original")) { btn.setBackground(Color.darkGray); btn.setEnabled(true); } else { setColor(btn, (int) btn.getClientProperty("availability")); } } currentButton.setBackground(Color.green); currentButton.setEnabled(false); } }
9
static final private HashMap<String,ProcedureDefinition> procedureRecur(HashMap<String,ProcedureDefinition> procedures) throws ParseException, CompilationException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case TO: procedure(procedures); procedureRecur(procedures); {if (true) return procedures;} break; default: jj_la1[1] = jj_gen; {if (true) return procedures;} } throw new Error("Missing return statement in function"); }
4
private static List<Appointment> findDailyByDaySpan(long uid, long startDay, long endDay) throws SQLException { List<Appointment> aAppt = new ArrayList<Appointment>(); // select * from Appointment where frequency = $DAILY // and startTime <= $(endDay+DateUtil.DAY_LENGTH) // and lastDay >= $startDay PreparedStatement statement = connect.prepareStatement("select * from (" + makeSqlSelectorForUser(uid) + ") as Temp where frequency = ? " + "and startTime <= ? " + "and lastDay >= ? "); statement.setInt(1, Frequency.DAILY); statement.setLong(2, endDay + DateUtil.DAY_LENGTH); statement.setLong(3, startDay); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { aAppt.add(Appointment.createOneFromResultSet(resultSet)); } return aAppt; }
1
public void changeTeamTemplate(String username, int newTemplateNumber) { PreparedStatement newData = null; PreparedStatement studentFinder = null; int studentID = -1; try { studentFinder = connect.prepareStatement( " select userID from User " + " where username = ?; "); studentFinder.setString(1, username); ResultSet id = studentFinder.executeQuery(); if (id.next()) { studentID = id.getInt(1); } newData = connect.prepareStatement( " update Student set teamTemplate = ? " + " where studentID = ? ; "); newData.setInt(1, newTemplateNumber); newData.setInt(2, studentID); newData.executeUpdate(); connect.commit(); } catch (SQLException sqex) { try { connect.rollback(); System.err.println(sqex.toString()); } catch (SQLException sqex2) { System.err.println("Dammit\n" + sqex2.toString()); } } finally { if (newData != null) { try { newData.close(); } catch (SQLException sqex) { System.err.println(sqex.toString()); } } if (studentFinder != null) { try { studentFinder.close(); } catch (SQLException sqex) { System.err.println(sqex.toString()); } } } }
7
private void addLabyrinth(int height, int length) { for (int i = 1; i < height; i++) { for (int j = 1; j < length; j++) { if (border(i,j,length,height)) { super.addBricks(new Point(i, j)); } else if (everyFourthLine(i,j,length, height)) { super.addBricks(new Point(i, j)); } else if (threeColumns(i,j,length, height)) { super.addBricks(new Point(i, j)); } else if (someBricksInTheFrame(i,j,length,height)) { super.addBricks(new Point(i, j)); } } } }
6
public static void query(String tagFile, String[] rpnQuery) { Expression expression = null; try { expression = Querior.parse(rpnQuery); } catch(ParseException e) { System.out.println("Problem parsing expression: " + e); return; } if (expression == null) return; TagState state = null; try { FileInputStream fis = new FileInputStream(tagFile); BufferedInputStream bis = new BufferedInputStream(fis, 4096*4); ObjectInputStream tagInput = new ObjectInputStream(bis); state = (TagState) tagInput.readObject(); tagInput.close(); } catch(IOException e) { System.out.println("Problem reading from tagFile: " + e); e.printStackTrace(); return; } catch(ClassNotFoundException e) { System.out.println("Problem reading TagState from tagFile: " + e); return; } List documentResults = Querior.search(state, expression); if (documentResults == null || documentResults.size() == 0) { System.out.println("No results"); return; } for (int i = 0; i < documentResults.size(); i++) { DocumentResult docRes = (DocumentResult) documentResults.get(i); System.out.println(docRes.getDocument().getOrigin()); List images = docRes.getImages(); System.out.println(" Matching images: " + images.size()); for (int j = 0; j < images.size(); j++) { TaggedImage ti = (TaggedImage) images.get(j); System.out.println(" Image: " + (ti.getReference() != null ? ti.getReference().toString() : "<unreferenced>") + " Inline: " + ti.isInlineImage() + " Pages: " + ti.describePages()); } } }
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; if((!auto) &&(!mob.isMonster()) &&(!disregardsArmorCheck(mob)) &&(!CMLib.utensils().armorCheck(mob,CharClass.ARMOR_LEATHER)) &&(mob.isMine(this)) &&(mob.location()!=null) &&(CMLib.dice().rollPercentage()<50)) { mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> fumble(s) @x1 due to <S-HIS-HER> clumsy armor!",name())); return false; } return true; }
8
public boolean isInside(int x1, int y1, int x2, int y2) { int tmp = x1; if (x2 < x1) { x1 = x2; x2 = tmp; } tmp = y1; if (y2 < y1) { y1 = y2; y2 = tmp; } return (x1 < x && x < x2) && (y1 < y && y < y2) && (x1 < x+width && x+width < x2) && (y1 < y+height && y+height < y2); }
9