text
stringlengths
14
410k
label
int32
0
9
public String showListInKind(){ if(page == 0) page = 1; size = 5; List<Problem> list = problemDAO.findKindPage(page, size, kind); problemList = new ProblemList(); problemList.setList(list); return SUCCESS; }
1
@RequestMapping("/{producto}/cantidad/{cantidad}") public ModelAndView agregarStockAProducto( @PathVariable String producto, @PathVariable Integer cantidad) { Stock stock = Stock.getInstance(); stock.agregarStock(producto, cantidad); Integer availableStock = stock.obtenerStockDisponible(producto); ModelMap model = new ModelMap(); model.put("producto", producto); model.put("stock", availableStock); return new ModelAndView("agregarStock", model); }
0
public String getNAME() { return name; }
0
@Override public boolean update(Object item) { conn = new SQLconnect().getConnection(); String sqlcommand = "UPDATE `Timeline_Database`.`Eventnodes` SET `description`='%s' WHERE `id`='%s';"; if(item instanceof Eventnode) { Eventnode newitem = new Eventnode(); newitem = (Eventnode)item; try { String sql = String.format(sqlcommand,newitem.getEvent_description(),newitem.getId()); Statement st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象 System.out.println(sql); int count = st.executeUpdate(sql); // 执行插入操作的sql语句,并返回插入数据的个数 System.out.println("insert " + count + " entries"); //输出插入操作的处理结果 conn.close(); //关闭数据库连接 return true; } catch (SQLException e) { System.out.println("插入数据失败 " + e.getMessage()); return false; } } return false; }
2
public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); }
6
public static Integer valueOf(Object o) { if (o == null) { return null; } else if (o instanceof Byte) { return (int)(Byte)o; } else if (o instanceof Integer) { return (Integer)o; } else if (o instanceof Double) { return (int)(double)(Double)o; } else if (o instanceof Float) { return (int)(float)(Float)o; } else if (o instanceof Long) { return (int)(long)(Long)o; } else { return null; } }
6
public Container load(InputStream is) throws FormatException, IOException { byte[] magic = new byte[4]; int bytesRead = is.read(magic); if (bytesRead < 4 || magic[0] != 0xF0 || magic[1] != 0x9F || magic[2] != 0x99 || magic[3] != 0x89) { throw new FormatException("MLA magic is missing"); } int version = is.read(); if (version == -1) { throw new FormatException("MLA version byte is missing"); } else { VersionLoader loader = versionLoaders.get(version); if (loader == null) { throw new FormatException("MLA version " + version + " is not supported by this library"); } else { return loader.load(is); } } }
7
public Gem removeGem() { tempGem = (Gem) Bag.get(0); this.Bag.remove(0); return tempGem; }
0
public static boolean attempt(BufferedReader input, BufferedWriter output, Scanner sc) throws IOException { output.write("HELLO\n"); output.flush(); String s, t; s=input.readLine(); if(!s.equals("HELLO. WHO ARE YOU?")){ System.out.println("PROTOCOL FAILED"); input.close(); output.close(); return false; } while(true) { System.out.println("login: "); s = sc.nextLine(); output.write("LOGIN: " + s + "\n"); output.flush(); s = input.readLine(); if(s.equals("LOGIN DOES NOT EXIST")) { System.out.println("LOGIN DOES NOT EXIST!"); continue; } Pattern pat = Pattern.compile("-?\\d+"); Matcher mat = pat.matcher(s); byte[] salt = new byte[8]; byte[] encPass = null; for (int j=0; j<8; j++) { if(!mat.find()) throw new IOException("salt table too short"); salt[j] = new Byte(mat.group()); } System.out.println("password: "); s = sc.nextLine(); try { encPass = PasswordEncryption.getEncryptedPassword(s, salt); } catch (Exception e){ e.printStackTrace(); } output.write("PASS: "); for (int j=0; j<encPass.length; j++) output.write(new Byte(encPass[j]).toString() + " "); output.write("\n"); output.flush(); s = input.readLine(); if(s.equals("LOGIN OK")){ return true; } System.out.println("WRONG PASSWORD!"); } }
8
public Contact getLeastRecentlySeenBucketContact() { final Contact[] leastRecentlySeen = new Contact[]{ null }; contacts.traverse( new Cursor<NodeId, Contact>() { public SelectStatus select(Map.Entry<? extends NodeId, ? extends Contact> entry) { Contact node = entry.getValue(); Contact lrs = leastRecentlySeen[0]; if (lrs == null || node.getLastContact() < lrs.getLastContact()) leastRecentlySeen[0] = node; return SelectStatus.CONTINUE; } } ); return leastRecentlySeen[0]; }
4
@FXML private void handleBtnNextAction(ActionEvent event) { move(1); }
0
public void setTab(GraphicsTab tab) { Control[] children = tabControlPanel.getChildren(); for (int i = 0; i < children.length; i++) { Control control = children[i]; control.dispose(); } if (this.tab != null) this.tab.dispose(); this.tab = tab; if (tab != null) { setDoubleBuffered(tab.getDoubleBuffered()); tab.createControlPanel(tabControlPanel); tabDesc.setText(tab.getDescription()); } else { tabDesc.setText(""); } FormData data = (FormData)tabControlPanel.getLayoutData(); children = tabControlPanel.getChildren(); if (children.length != 0) { data.top = null; } else { data.top = new FormAttachment(100, -MARGIN); } parent.layout(true, true); if (tab != null) { TreeItem[] selection = tabList.getSelection(); if (selection.length == 0 || selection[0].getData() != tab) { TreeItem item = findItemByData(tabList.getItems(), tab); if (item != null) tabList.setSelection(new TreeItem[]{item}); } } canvas.redraw(); }
8
@Override public Converter put(String key, Converter value) { Converter v = super.put(key, value); if (v != null) { throw new IllegalArgumentException("Duplicate Converter for " + key); } return v; }
2
public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java -cp .:sam.jar TabixReader <in.gz> [region]"); System.exit(1); } try { TabixReader tr = new TabixReader(args[0]); String s; if (args.length == 1) { // no region is specified; print the whole file while ((s = tr.readLine()) != null) System.out.println(s); } else { // a region is specified; random access TabixReader.TabixIterator iter = tr.query(args[1]); // get the iterator while (iter != null && (s = iter.next()) != null) System.out.println(s); } } catch (IOException e) { } }
6
private static void checkFeature (String id, XMLReader producer) { int state = 0; try { boolean value; // align to longest id... final int align = 35; for (int i = align - id.length (); i > 0; i--) System.out.print (' '); System.out.print (id); System.out.print (": "); id = FEATURE_URI + id; value = producer.getFeature (id); System.out.print (value); System.out.print (", "); state = 1; producer.setFeature (id, value); state = 2; producer.setFeature (id, !value); System.out.println ("read and write"); // changes value and leaves it } catch (SAXNotSupportedException e) { switch (state) { case 0: System.out.println ("(can't read now)"); break; /* bogus_1 means can't reassign the default; * probably intended to be read/write */ case 1: System.out.println ("bogus_1"); break; case 2: System.out.println ("readonly"); break; } } catch (SAXNotRecognizedException e) { if (state == 0) System.out.println ("(unrecognized)"); else /* bogus_2 means the wrong exception was thrown */ System.out.println ("bogus_2"); } }
7
private void evalNewObjectArray(int pos, CodeIterator iter, Frame frame) throws BadBytecode { // Convert to x[] format Type type = resolveClassInfo(constPool.getClassInfo(iter.u16bitAt(pos + 1))); String name = type.getCtClass().getName(); int opcode = iter.byteAt(pos); int dimensions; if (opcode == MULTIANEWARRAY) { dimensions = iter.byteAt(pos + 3); } else { name = name + "[]"; dimensions = 1; } while (dimensions-- > 0) { verifyAssignable(Type.INTEGER, simplePop(frame)); } simplePush(getType(name), frame); }
2
public State getCorrespondingStoppedState() { if(state == State.MOVE_DOWN) { return state.STOPPED_DOWN; } else if(state == State.MOVE_LEFT) { return state.STOPPED_LEFT; } else if(state == State.MOVE_RIGHT) { return state.STOPPED_RIGHT; } else { return state.STOPPED_UP; } }
3
@Override public String toString() { return "ModelFiledDesc [filedName=" + filedName + ", filedType=" + filedType + ", tableFiledName=" + tableFiledName + "]"; }
0
private int pathFind(Pos start, int danger) throws Exception { // ArrayList<String> sTypes; // for(int i = 1; i < 5; i++) // { // for(int j = 1; j < 5; j++) // { // //just debugging to see the map and how it is represented from prolog // sTypes = m_Logic.locateAllAt(j, i); // m_Map.add(sTypes); // } // } //If there exist a goal to be reached no need to search again. if(m_Path == null || m_Path.isEmpty()) { Pos goal = findGoalPos(); m_Path = aStarPath(start.x, start.y, goal.x, goal.y, danger); while(m_Path == null) { //if a route to a square was not reached, decrease the dangerlevel //and try again. m_Path = aStarPath(start.x, start.y, goal.x, goal.y, danger--); if(danger <= 0) break; } } return danger; }
4
@Test public void testAddBook() { Set<StockBook> booksToAdd = new HashSet<StockBook>(); Integer testISBN = 100; booksToAdd.add(new ImmutableStockBook(testISBN, "*@#&)%rdrrdjtIHH%^#)$&N 37874\n \t", "eurgqo 89274267^&#@&$%@&%$( \t", (float) 100, 5, 0, 0, 0, false)); List<StockBook> listBooks = null; try { storeManager.addBooks(booksToAdd); listBooks = storeManager.getBooks(); } catch (BookStoreException e) { e.printStackTrace(); fail(); } Boolean containsTestISBN = false; Iterator<StockBook> it = listBooks.iterator(); while (it.hasNext()) { Book b = it.next(); if (b.getISBN() == testISBN) containsTestISBN = true; } assertTrue("List should contain the book added!", containsTestISBN); Boolean exceptionThrown = false; booksToAdd.add(new ImmutableStockBook(-1, "BookName", "Author", (float) 100, 5, 0, 0, 0, false)); try { storeManager.addBooks(booksToAdd); } catch (BookStoreException e) { exceptionThrown = true; } assertTrue("Invlaid ISBN exception should be thrown!", exceptionThrown); List<StockBook> currentList = null; try { currentList = storeManager.getBooks(); assertTrue(currentList.equals(listBooks)); } catch (BookStoreException e) { e.printStackTrace(); fail(); } exceptionThrown = false; booksToAdd.add(new ImmutableStockBook(testISBN + 1, "BookName", "Author", (float) 100, 0, 0, 0, 0, false)); try { storeManager.addBooks(booksToAdd); } catch (BookStoreException e) { exceptionThrown = true; } assertTrue("Invalid number of copies exception should be thrown!", exceptionThrown); try { currentList = storeManager.getBooks(); assertTrue(currentList.equals(listBooks)); } catch (BookStoreException e) { e.printStackTrace(); fail(); } exceptionThrown = false; booksToAdd.add(new ImmutableStockBook(testISBN + 2, "BookName", "Author", (float) -100, 0, 0, 0, 0, false)); try { storeManager.addBooks(booksToAdd); } catch (BookStoreException e) { exceptionThrown = true; } assertTrue("Invlaid price exception should be thrown!", exceptionThrown); try { currentList = storeManager.getBooks(); assertTrue(currentList.equals(listBooks)); } catch (BookStoreException e) { e.printStackTrace(); fail(); } }
9
public int getId(){ return id; }
0
public SignatureVisitor visitParameterType() { endFormals(); if (!hasParameters) { hasParameters = true; buf.append('('); } return this; }
1
public static String cleanURL(String url) { if (isEmpty(url)) return ""; ArrayList<String> tmp=Functions.explode(", ",url); url=tmp.get(0); if (tmp.size() == 2 && Functions.strlen(tmp.get(1)) < 4) url = url + "," + tmp.get(1); ArrayList<String> replace = new ArrayList<String>(); replace.add("\n"); replace.add("\r"); replace.add("\\"); replace.add("\""); url=Functions.str_replace(replace,"",url); url=url.trim(); if (strlen(url)< 4) return ""; String prefix=url.substring(0,4); if (prefix.equals("wap.") || prefix.equals("uapr") || prefix.equals("www.")) url = new String("http://").concat(url); if (!Functions.substr(url,0,4).equals("http")) url=""; return url; }
8
public static void cppOutputAtomicExpression(Stella_Object atom) { { GeneralizedSymbol testValue000 = ((GeneralizedSymbol)(atom)); if (testValue000 == Stella.SYM_STELLA_NEWLINE) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.println(); } else if (testValue000 == Stella.SYM_STELLA_CPP_NULL_VALUE) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("NULL_VALUE"); } else if (testValue000 == Stella.SYM_STELLA_ASSIGN) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("="); } else if (testValue000 == Stella.SYM_STELLA_SCOLON) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(";"); } else if (testValue000 == Stella.SYM_STELLA_LPAREN) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print("("); } else if (testValue000 == Stella.SYM_STELLA_RPAREN) { ((OutputStream)(Stella.$CURRENT_STREAM$.get())).nativeStream.print(")"); } else { atom.cppOutputLiteral(); } } }
6
public void decode( ByteBuffer socketBuffer ) { if ( !socketBuffer.hasRemaining() || flushandclosestate ) return; if ( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if ( readystate == READYSTATE.OPEN ) { decodeFrames( socketBuffer ); } else { if ( decodeHandshake( socketBuffer ) ) { decodeFrames( socketBuffer ); } } assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() ); }
8
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntegerAggregate that = (IntegerAggregate) o; if (value != null ? !value.equals(that.value) : that.value != null) return false; return true; }
5
public static ListeDesMatchs getListeDesMatchs() { if(lm == null) { lm = new ListeDesMatchs(1); return lm; } return lm; }
1
public static void main(String[] args) { Scanner scan = new Scanner(System.in); String input = null; int[] count = new int[VOWELS.length]; int y = 0; try { System.out.print("Enter a string to check for vowels: "); input = scan.nextLine().toLowerCase(); } finally { scan.close(); } for (int i = 0; i < input.length(); i++) { try { if (isVowel(input, i, 0)) { char cur = input.charAt(i); if (cur != 'y') { count[inList(VOWELS, cur)] += 1; } else { y += 1; } } } catch (java.io.IOException err) { System.out.println(err.getMessage() + " Ignoring..."); } } int vowelCount = y; for (int i=0; i<VOWELS.length; i++) { System.out.printf("%s: %d\n", VOWELS[i], count[i]); vowelCount += count[i]; } System.out.println("y: " + y); System.out.println("spaces: " + (input.length() - input.replaceAll("\\s", "").length())); System.out.println("consonants: " + (input.length() - input.replaceAll("[a-z]", "").length() - vowelCount)); System.out.println("punctuation: " + (input.replaceAll("[a-z0-9\\s]", "").length())); }
5
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); DoubleSubmitSession annotation = method.getAnnotation(DoubleSubmitSession.class); if (annotation != null) { boolean needSaveSession = annotation.needSaveToken(); if (needSaveSession) { request.getSession(false).setAttribute(SUBMIT_TOKEN_NAME, UUID.randomUUID().toString()); LOG.warn("SaveSession:"+request.getSession().getAttribute(SUBMIT_TOKEN_NAME)); } boolean needRemoveSession = annotation.needRemoveToken(); if (needRemoveSession) { if (isRepeatSubmit(request)) { LOG.warn("RepeatSubmit!!"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "RepeatSubmit!"); return false; } request.getSession(false).removeAttribute(SUBMIT_TOKEN_NAME); } } return true; }
4
@Override public Auction bid(String username, int itemId) { searches.get(searches.get(itemId)); for(Auction auc : searches.values()){ if(searches.get(itemId) != null){ auc.setCurrentBid(auc.getCurrentBid()+1); auc.setOwner(username); return auc; } } return null; }
2
@Override public void run() { while(true) { try { System.out.println("Fps: " + fps); fps = 0; Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2
private void placeIdentityDiscNearPlayer() { for (Player p : grid.getAllPlayersOnGrid()) { boolean placed = false; int minX = (p.getPosition().xCoordinate > 1) ? p.getPosition().xCoordinate - 4 : 0; int maxX = (grid.width - p.getPosition().xCoordinate > 1) ? p.getPosition().xCoordinate + 4 : grid.width; int minY = (p.getPosition().yCoordinate > 1) ? p.getPosition().yCoordinate - 4 : 0; int maxY = (grid.height - p.getPosition().yCoordinate > 1) ? p.getPosition().yCoordinate + 4 : grid.height; while (!placed) { int randomX = minX + (int) Math.round(Math.random() * maxX); int randomY = minY + (int) Math.round(Math.random() * maxY); IdentityDisc idDisc = new IdentityDisc(new Position(randomX, randomY)); if (grid.validPosition(idDisc.getPosition()) && canHaveAsIdentityDisc(idDisc)) { grid.addElement(idDisc); factory.addObservable(idDisc); placed = true; } } } }
8
private static void collideFixed( Sprite A , Sprite B , float ddx , float ddy ) { // j - для "запрыгивания" на уступы if( ddx>ddy || (A.j>0 && ddy<A.j) ) { if( A.y>B.y ){ A.y+=ddy; } if( A.y<B.y ){ A.y-=ddy; } } else { if( A.x>B.x ){ A.x+=ddx; } if( A.x<B.x ){ A.x-=ddx; } } /* if( ddx<ddy ) { if( A.x>B.x ){ A.x+=ddx; } if( A.x<B.x ){ A.x-=ddx; } } else { if( A.y>B.y ){ A.y+=ddy; } if( A.y<B.y ){ A.y-=ddy; } } */ }
7
public void transformMouseEvent(MouseEvent event) { if (transformNeedsReform) reformTransform(new Rectangle(getSize())); Point point = new Point(), ePoint = event.getPoint(); try { // transform.transform(ePoint, point); transform.inverseTransform(ePoint, point); event.translatePoint(point.x - ePoint.x, point.y - ePoint.y); } catch (NoninvertibleTransformException e) { // Well, what CAN we do? } }
2
@SuppressWarnings("deprecation") @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(Match.getMatch().getState().equals(MatchState.PREMATCH)){ for(Player player : Bukkit.getOnlinePlayers()){ Match.getMatch().getSurvivors().add(player); } if(Match.getMatch().getSurvivors().size()<1){ sender.sendMessage(ChatColor.RED+"You need at least 2 players to start the game."); sender.sendMessage(ChatColor.RED+"You currently have: "+Match.getMatch().getSurvivors().size()+" survivors"); } else { Match.getMatch().loadLocations(); Match.getMatch().teleportPlayers(); Match.startMatchCountdown(); return true; } } return false; }
3
public Vector2 calculate(Vector2 target) { Vector2 steeringForce = new Vector2(0f, 0f); for(MovingEntity neighbor : minigame.birds) { if(neighbor != entity) { Vector2 toAgent = entity.position.minusOperator(neighbor.position); toAgent.normalize(); toAgent = toAgent.divideBy(toAgent.length()); steeringForce.add(toAgent); } } return steeringForce; }
2
private List<String[]> getCustomOutputsPropertyValue(final Properties properties) { List<String[]> customOutputs = new ArrayList<>(); String values = this.getPropertyValue(properties, CUSTOM_OUTPUTS_TAG, null); if (values == null) { return null; } String [] outputs = values.split(OUTPUT_SEPARATOR); for (String value: outputs) { customOutputs.add(value.split(PARAM_SEPARATOR)); } return customOutputs; }
2
public void run() { HttpURLConnection var1 = null; try { URL var2 = new URL(this.location); var1 = (HttpURLConnection)var2.openConnection(); var1.setDoInput(true); var1.setDoOutput(false); var1.connect(); if(var1.getResponseCode() / 100 == 4) { return; } if(this.buffer == null) { this.imageData.image = ImageIO.read(var1.getInputStream()); } else { this.imageData.image = this.buffer.parseUserSkin(ImageIO.read(var1.getInputStream())); } } catch (Exception var6) { var6.printStackTrace(); } finally { var1.disconnect(); } }
3
private static int[][] calculateDistances2(double[][] points,int N) { int[][] distanceMatrix= new int[N][N]; for(int i=0; i<N;i++){ for(int j=0;j<N;j++){ if(j==i){ distanceMatrix[i][j]=0; } else if(i<j){ distanceMatrix[i][j]=distance(points[0][i],points[0][j],points[1][i],points[1][j]); } else {//i>j distanceMatrix[i][j]=distanceMatrix[j][i]; } } } return distanceMatrix; }
4
public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int[] numbers = new int[3]; for (int i = 0; i < numbers.length; i++) { numbers[i] = (int) (Math.random() * 10); for (int j = 0; j < i; j++) { if (numbers[i] == numbers[j]) { i--; break; } } } System.out.println(numbers[0] + ", " + numbers[1] + ", " + numbers[2]); }
3
public ArrayList<BedFeature> getBedData(RPChromosomeRegion selectionRegion, boolean contained) { int itemNumber = 0; int chromID, chromStart, chromEnd; String restOfFields; int itemHitValue; // chromID + chromStart + chromEnd + rest 0 byte // 0 byte for "restOfFields" is always present for bed data int minItemSize = 3 * 4 + 1; // allocate the bed feature array list bedFeatureList = new ArrayList<BedFeature>(); // check if all leaf items are selection hits RPChromosomeRegion itemRegion = new RPChromosomeRegion( leafHitItem.getChromosomeBounds()); int leafHitValue = itemRegion.compareRegions(selectionRegion); try { for(int index = 0; remDataSize > 0; ++index) { itemNumber = index + 1; // read in BigBed item fields - BBFile Table I if(isLowToHigh){ chromID = lbdis.readInt(); chromStart= lbdis.readInt(); chromEnd = lbdis.readInt(); restOfFields = lbdis.readString(); } else{ chromID = dis.readInt(); chromStart= dis.readInt(); chromEnd = dis.readInt(); restOfFields = dis.readUTF(); } if(leafHitValue == 0) { // contained leaf region items always added String chromosome = chromosomeMap.get(chromID); BedFeature bbItem = new BedFeature(itemNumber, chromosome, chromStart, chromEnd, restOfFields); bedFeatureList.add(bbItem); } else { // test for hit itemRegion = new RPChromosomeRegion(chromID, chromStart, chromID, chromEnd); itemHitValue = itemRegion.compareRegions(selectionRegion); // abs(itemHitValue) == 1 for intersection; itemHitValue == 0 for contained if(!contained && Math.abs(itemHitValue) < 2 || itemHitValue == 0) { // add bed feature to item selection list String chromosome = chromosomeMap.get(chromID); BedFeature bbItem = new BedFeature(itemNumber, chromosome, chromStart, chromEnd, restOfFields); bedFeatureList.add(bbItem); } } // compute data block remainder from size of item read // todo: check that restOfFields.length() does not also include 0 byte terminator remDataSize -= minItemSize + restOfFields.length(); } }catch(IOException ex) { log.error("Read error for Bed data item " + itemNumber); // accept this as an end of block condition unless no items were read if(itemNumber == 1) throw new RuntimeException("Read error for Bed data item " + itemNumber); } return bedFeatureList; }
8
@Override public Provider matchClientProviders(Task task, List<Provider> providers) { Client ci = task.getClient(); Cluster cu = ci.getBelongingCluster(); Provider matched = null; double matchedScore = Double.NEGATIVE_INFINITY; // test providers randomly List<Provider> randomProviders = new LinkedList<Provider>(); for(Provider p : providers) { randomProviders.add(rnd.nextInt(randomProviders.size()+1), p); } // System.out.print(ci.getIdentifier() + " checks "); for(Provider p : randomProviders) { Double providerTrust = null; Double dt = ci.getProviderDirectTrust(p.getIdentifier()); Double rt = cu.getReputation(p.getIdentifier()); if(dt == null && rt == null) { providerTrust = 0.5; } else if(dt == null) { providerTrust = rt; } else if(rt == null) { providerTrust = dt; } else { final double w1 = 0.5, w2 = 0.5; Double t1 = dt * w1; Double t2 = rt * w2; providerTrust = t1 + t2; } // double price = ci.getSLO().summarize(); double price = p.getPrice(task); double score = -providerTrust / price; //double score = -sloImportances.divideTerms(providerTrust).summarize(); // System.out.print(p.getIdentifier() + "("+score+")"); if(p.isTaskFitting(task)) if(score > matchedScore || matched == null) { matchedScore = score; matched = p; task.setRevenueFunction(price); // System.out.print("*"); } // System.out.print(" "); } // System.out.println(""); return matched; }
9
public void drawPredator(Node to, Node from, Graphics g) { if (from != null) { Coordinates predatorCoords = from.getCoordinates(); int predPicX = predatorCoords.col * wallSize + padding + finalFormatX - (wallSize / 2) + 2; int predPicY = predatorCoords.row * wallSize + padding + finalFormatY - (wallSize / 2) + 2; int predPicThickness = wallSize - 4; g.fillRect(predPicX, predPicY, predPicThickness, predPicThickness); if (from.equals(Engine.controlNode)) { drawControlRoom(from, g); } } drawGridLines(g); Coordinates predatorCoords = to.getCoordinates(); int predPicX = predatorCoords.col * wallSize + padding + finalFormatX - (wallSize / 2) + 2; int predPicY = predatorCoords.row * wallSize + padding + finalFormatY - (wallSize / 2) + 2; int predPicThickness = wallSize - 4; g.drawImage(predatorImage, predPicX, predPicY, predPicThickness, predPicThickness, Color.BLACK, null); }
2
public final Object get(String key) throws JSONException { Object o = opt(key); if (o == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return o; }
1
@Override public int compareTo(Hand o) { currentType = Validator.getHandType(this); Hand h = new Hand(this); Collections.sort(h.getCards()); return currentType.getValue() > o.getCurrentType().getValue() ? -1 : currentType.getValue() < o.getCurrentType().getValue() ? 1 : 0; }
2
public void act(int timestamp) { //Do actions, then check fuel levels at end of tick if (currentLocation instanceof Hangar) { Simulation.getStatistics().incrementNumberOfTakeOffs(this); takeOff(timestamp); } else if (currentLocation instanceof Airspace) { Simulation.getStatistics().incrementNumberOfLandings(this); land(timestamp); //NB: Fuel assumed to last until the end of the tick checkFuelLevels(timestamp); } else if (currentLocation instanceof Workshop) { //TODO: Remove logging text System.out.println("The plane is in Workshop"); //TODO: If the aircraft is in the workshop for longer than an hour, complete repairs and move to hangar } else if (currentLocation instanceof Runway) { ((Runway)currentLocation).incrementTimeInUse(); if(status == departing) { System.out.println("" + this.getAircraftName() + " :: Currently taking off.."); System.out.println(this.toString()); //Check whether the aircraft should break down if(rand.nextDouble() < Simulation.BREAKDOWN_DURING_TAKEOFF_PROBABILITY ) { // throw new AircraftBreakDownException(); this.breakdown(timestamp); } //Check whether the aircraft may finish taking off if(waitingTimeInQueue >= this.timeNeededToTakeOff) { finaliseTakeOff(timestamp); } //NB: Fuel assumed to last until the end of the tick checkFuelLevels(timestamp); } else if(status == landing) { System.out.println(this.getAircraftName() + " :: Currently landing.. "); System.out.println(this.toString()); //Check whether the aircraft may finish landing if(waitingTimeInQueue >= this.timeNeededToLand) { finaliseLanding(timestamp); } } else { //Still waiting to take off / land. //Change nothing. //Continue to land/take off uninterrupted. } } else { System.out.println("Currently in an unknown location"); } this.incrementWaitTimeByTickSize(); }
9
public static void processDownlaod(ModInstance modInstance) throws IOException { File currentMod = new File(FileManager.dir + "/" + modInstance.type.output + "/", modInstance.modName); File storedMod = new File(FileManager.updaterDir + "/" + modInstance.type.storage + "/", modInstance.modName); if (!currentMod.exists() || !FileManager.installedMods.contains(currentMod)) { debug.add("File " + modInstance.modName + " not Found in mods folder"); if (storedMod.exists() && FileManager.modsStored.contains(storedMod)) { boolean ccMod = FileManager.copyFile(storedMod, currentMod); if (ccMod) { debug.add("File " + modInstance.modName + " copied to mods folder"); removeFromList(currentMod); } } else { File downloaded = Download.downloadFile(modInstance.url, FileManager.updaterDir + "/" + modInstance.type.storage+"/", modInstance.modName, "url"); if (downloaded != null && downloaded.exists()) { debug.add("Downloaded " + modInstance.modName + " to updater/mods"); boolean ctc = FileManager.copyFile(storedMod, currentMod); if (ctc) { removeFromList(currentMod); } } else { debug.add("Failed to download file " + modInstance.modName); debug.add("If you have this file you can manualy add it by placing it in the updater/mods folder and running installer again"); } } } else { removeFromList(currentMod); } }
8
public void dfs(Vertex<T> start) { //DFS uses Stack data structure Stack<Vertex<T>> stack =new Stack<Vertex<T>>(); start.visited=true; stack.push(start); printNode(start); while(!stack.isEmpty()) { Vertex<T> n= stack.peek(); Vertex<T> child=getUnvisitedChildren(n); if(child!=null) { child.visited=true; stack.push(child); printNode(child); } else { stack.pop(); } } }
2
public void removeChangeListener(ChangeListener listener) { changeListeners.remove(listener); }
0
public ListNode partition(ListNode head, int x) { ListNode p1 = null, p2 = head, p2Prev = null; while( p2 != null ) { if( p2.val < x ) { if( p1 == p2Prev ) { p1 = p2; p2 = p2.next; p2Prev = p1; } else { p2Prev.next = p2.next; if( p1 == null ) { p2.next = head; head = p2; } else { p2.next = p1.next; p1.next = p2; } p1 = p2; p2 = p2Prev.next; } } else { p2Prev = p2; p2 = p2.next; } } return head; }
4
private boolean onCommandRefresh(CommandSender sender, Command command, String label, String cmd, String[] args) { String queryPlayerName = getQueryPlayerName(sender, args, 1); if (!queryPlayerName.equals("CONSOLE")) { Hashtable<String, ReplicatedPermissionsContainer> playerMods = null; for (Entry<String, Hashtable<String, ReplicatedPermissionsContainer>> player : this.parent.getMonitor().getPlayerModInfo().entrySet()) { if (player.getKey().equalsIgnoreCase(queryPlayerName)) { playerMods = player.getValue(); queryPlayerName = player.getKey(); break; } } Player player = Bukkit.getPlayer(queryPlayerName); if (player != null && playerMods != null && (sender.hasPermission(ReplicatedPermissionsPlugin.ADMIN_PERMISSION_NODE) || sender.getName().equals(queryPlayerName))) { for (Map.Entry<String, ReplicatedPermissionsContainer> modEntry : playerMods.entrySet()) { this.parent.getPermissionsManager().replicatePermissions(player, modEntry.getValue()); } sender.sendMessage(ChatColor.GREEN + "Refreshed mod permissions for player: " + ChatColor.AQUA + queryPlayerName); } } else { sender.sendMessage(String.format(ChatColor.GREEN + "/%s %s " + ChatColor.AQUA + "<player>", label, cmd)); } return true; }
8
public void step() { double x0 = x, y0 = y, t0 = t; x += v * Math.cos(t) * dt; y += - v * Math.sin(t) * dt; t += vt * dt; while (t < - Math.PI) t += 2 * Math.PI; while (t >= Math.PI) t -= 2 * Math.PI; if (playfield.collision(this, true)) { x = x0; y = y0; t = t0; return; } v += a * dt; double drag = r * r * CDRAG; if (drag >= 0.95) { System.err.println("internal error: CDRAG too big"); System.exit(1); } v -= v * drag; }
4
public String getBlogContent() { return this.blogContent; }
0
private static int getBits(int i, Bzip2Block bzip2Block) { int dest; do { if (bzip2Block.bsLive >= i) { int tmp = bzip2Block.bsBuff >> bzip2Block.bsLive - i & (1 << i) - 1; bzip2Block.bsLive -= i; dest = tmp; break; } bzip2Block.bsBuff = bzip2Block.bsBuff << 8 | bzip2Block.input[bzip2Block.nextIn] & 0xff; bzip2Block.bsLive += 8; bzip2Block.nextIn++; bzip2Block.compressedSize--; bzip2Block.totalInLo32++; if (bzip2Block.totalInLo32 == 0) { bzip2Block.totalInHi32++; } } while (true); return dest; }
3
public boolean move() { // Don't let him move out of bounds. /*if ( (position.x + WIDTH + direction.x > Map.WIDTH) || (position.x + direction.x < 0) || (position.y + HEIGHT + direction.y > Map.HEIGHT) || (position.y + direction.y < 0)) return;*/ if (position.x + WIDTH + direction.x > Map.WIDTH) { position.x=0; room--; return false; } else if (position.x + direction.x < 0) { room++; position.x=Map.WIDTH-WIDTH; return false; } else if (position.y + HEIGHT + direction.y > Map.HEIGHT) { room-=3; position.y=Statusbar.Y_START_POSITION; return false; } else if (position.y + direction.y < Statusbar.Y_START_POSITION) { room+=3; position.y=Map.HEIGHT-HEIGHT; return false; } Rectangle newPosition = new Rectangle(position.x + direction.x, position.y + direction.y, WIDTH, HEIGHT); // Don't move if he's going to hit a wall for (int i=0; i<map.getWalls(quadrant).size(); i++) { if (newPosition.intersects(map.getWalls(quadrant).get(i))) return true; } // finally, move and figure out where he is changePosition(direction); determineQuadrant(); return true; }
6
@Override public boolean offer(T t) { boolean result = false; if (firstItem == null) { firstItem = new LinkedItem(t); result = true; } else { boolean searching = true; LinkedItem currentItem = firstItem; LinkedItem lastItem = null; while (searching) { if (currentItem.getNextItem() == null) { lastItem = currentItem; searching = false; } currentItem = currentItem.getNextItem(); } lastItem.setNextItem(new LinkedItem(t)); result = true; } return result; }
3
@Override public Set<List<A>> times(Set<List<A>> x, Set<List<A>> y) { Set<List<A>> product = new HashSet<>(); for (List<A> a : x) { for (List<A> b : y) { product.add(concat(a, b)); } } return product; }
2
public void run() { Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); String time = cal.get(Calendar.HOUR_OF_DAY) + ":" + roundUpToNearestFive(cal.get(Calendar.MINUTE)); System.out.println("COLLECTING RENT."); DBConnector dbc = _plugin.db; List<World> worlds = Bukkit.getWorlds(); ArrayList<Listing> tenants = new ArrayList<Listing>(); /* List<OfflinePlayer> players = new ArrayList<Player>(); for(World w : worlds) { tenants.addAll(dbc.getTenants(w)); } */ for(World w : worlds) { for(Listing l : _plugin.db.getTenants(w)) { tenants.add(l); } } if (tenants.isEmpty()) return; for(Listing plot : tenants) { if(plot.type.equals(time)) { if(!accounts.hasFunds(plot.owner, plot.price)) { //release plot from tenant's control System.out.println("TODO: Insufficient Funds"); _plugin.db.removeTenant(plot.name, plot.world); rfm.removeMember(plot.name, plot.owner, plot.world); } else if (dbc.daysRemaining(plot.name, plot.world) == 0) { //release plot from tenant's control System.out.println("TODO: Expired lease"); _plugin.db.removeTenant(plot.name, plot.world); rfm.removeMember(plot.name, plot.owner, plot.world); } else { accounts.chargeMoney(plot.owner, plot.price); accounts.addMoney(rfm.getOwnerName(plot.name, Bukkit.getWorld(plot.world.getName())), plot.price); dbc.subtractDay(plot.name, plot.world); System.out.println("Collected!"); } } } System.out.println("Finished collecting rents."); }
7
public SimpleRunCPE(String args[]) throws Exception { mStartTime = System.currentTimeMillis(); // check command line args if (args.length < 1) { printUsageMessage(); System.exit(1); } // parse CPE descriptor System.out.println("Parsing CPE Descriptor"); CpeDescription cpeDesc = UIMAFramework.getXMLParser().parseCpeDescription( new XMLInputSource(args[0])); // instantiate CPE System.out.println("Instantiating CPE"); mCPE = UIMAFramework.produceCollectionProcessingEngine(cpeDesc); // Create and register a Status Callback Listener mCPE.addStatusCallbackListener(new StatusCallbackListenerImpl()); // Start Processing System.out.println("Running CPE"); mCPE.process(); // Allow user to abort by pressing Enter System.out.println("To abort processing, type \"abort\" and press enter."); while (true) { String line = new BufferedReader(new InputStreamReader(System.in)).readLine(); if ("abort".equals(line) && mCPE.isProcessing()) { System.out.println("Aborting..."); mCPE.stop(); break; } } }
4
private void serveGet(List<String> request) throws IOException, ClassNotFoundException, WrongVersionNumber{ if (request.size() < 3){ return; } boolean zip = (request.get(0) != null) && (request.get(0).equals("get_zip")); String source = request.get(1); List<String> source2 = ServerUtils.parseName(source); String destination = request.get(2); Path destination2 = Paths.get(destination); Integer versionNumber = null; if (request.size() >= 4){ try { versionNumber = Integer.valueOf(request.get(3)); } catch (NumberFormatException ex){} } DItem item = getDItemFromServer(source2); if (!zip && !isCompatible(destination2, item)){ stdout.println(messages.getString("dir_into_file")); return; } boolean res; if (item != null){ if (item.isDir()){ res = receiveDirectory(source2, destination2, zip, true, item, null); } else { res = receiveVersion(destination2, source2, versionNumber, zip, null); } if (res) { stdout.println(messages.getString("download_finished")); } } }
9
protected final CodSigningInfo signers(final InputStream inputStream, final String fileName) { // Pre-condition: - inputStream is not null - inputStream is at the // beginning of the file // Post-condition: - inputStream is at the end of the file, but still // open DataInputStream inputFile; StringBuffer currentSigner = new StringBuffer(LENGTH_OF_SIGNER_ID); CodSigningInfo returnValue = new CodSigningInfo(fileName); inputFile = new DataInputStream(inputStream); try { int dataSize; // stores the sum of data size and code size int signLength; // stores the length of the signature checkValidity(inputFile, fileName); // Find out if the flashid is // correct and verify the ends if (getVersion(inputFile) <= MIN_VERSION) { logError("File version not above " + MIN_VERSION + "."); return null; } // code size: dataSize = readLittleEndianNibble(inputFile); // + data size: dataSize += readLittleEndianNibble(inputFile); // Skip two bytes for the COD flags. inputFile.skip(2 + dataSize); while (true) { // read until exception currentSigner.delete(0, currentSigner.length()); int temp = readLittleEndianNibble(inputFile); if (temp != 1) { logError("Sign_type is not 1. Sign_type = " + temp); return null; } signLength = readLittleEndianNibble(inputFile); char c; for (short i = 0; i < LENGTH_OF_SIGNER_ID; i++) { // read 4 char signer c = (char) inputFile.readByte(); if (c != 0) { currentSigner.append(c); } } // -4 because 4 characters of signer have already been read inputFile.skip(signLength - LENGTH_OF_SIGNER_ID); returnValue.addSigner(currentSigner.toString()); } } catch (EOFException e) { // EOF- return list of signers /* this is expected; we reached the end of the file. */ } catch (IOException e) { log(e, Project.MSG_WARN); logError("Failed to read file."); return new CodSigningInfo(fileName); } catch (BadCodException e) { log(e, Project.MSG_WARN); logError("Bad COD file."); return new CodSigningInfo(fileName); } return returnValue; }
8
@Override public Resource objectToJena(Model toAddTo, Investigation investigation) throws IllegalArgumentException { if (investigation.getResourceURL() == null) { throw new IllegalArgumentException(String.format(msg_ResourceWithoutURI, "investigations")); } Resource res = toAddTo.createResource(investigation.getResourceURL().toString()); toAddTo.add(res, RDF.type, TOXBANK_ISA.INVESTIGATION); addString(res, TOXBANK_ISA.HAS_ACCESSION_ID, investigation.getAccessionId()); addString(res, DCTerms.title, investigation.getTitle()); addString(res, DCTerms.abstract_, investigation.getAbstract()); addTimestamp(res, DCTerms.created, investigation.getSubmissionDate()); addTimestamp(res, DCTerms.modified, investigation.getLastModifiedDate()); addTimestamp(res, DCTerms.issued, investigation.getIssuedDate()); if (investigation.isPublished() != null) res.addLiteral(TOXBANK.ISPUBLISHED, investigation.isPublished()); if (investigation.isSearchable() != null) res.addLiteral(TOXBANK.ISSUMMARYSEARCHABLE, investigation.isSearchable()); for (Project project : investigation.getProjects()) { Resource projectRes = toAddTo.createResource( project.getResourceURL().toString() ); res.addProperty(TOXBANK.HASPROJECT, projectRes); } if (investigation.getOrganisation() != null) { if (investigation.getOrganisation().getResourceURL()==null) throw new IllegalArgumentException(String.format(msg_InvalidURI, "organisation",res.getURI())); Resource org = organisationIO.objectToJena(toAddTo, investigation.getOrganisation()); res.addProperty(TOXBANK.HASORGANISATION,org); } if (investigation.getOwner() != null) { if (investigation.getOwner().getResourceURL()==null) throw new IllegalArgumentException(String.format(msg_InvalidURI, "investigation owner",res.getURI())); Resource ownerRes = userIO.objectToJena(toAddTo, investigation.getOwner()); res.addProperty(TOXBANK.HASOWNER, ownerRes); } for (User author : investigation.getAuthors()) { Resource authorRes = toAddTo.createResource( author.getResourceURL().toString() ); res.addProperty(TOXBANK_ISA.HAS_OWNER, authorRes); } return res; }
9
public void writeToStream(PrintStream p) { // create definition string with first character 1 if the // mapping is character-defined, 0 otherwise String definition = "" + (characterDef ? 1 : 0); // add character or keycode definition += "\t"; if (characterDef) definition += (int) keyChar; else definition += keyCode; // add key location definition += "\t" + keyLocation; definition += "\t0x" + Integer.toHexString(scancode); // build and add modifiers as a set of flags in an integer value int modifiers = 0; modifiers |= (shiftDown ? FLAG_SHIFT : 0); modifiers |= (ctrlDown ? FLAG_CTRL : 0); modifiers |= (altDown ? FLAG_ALT : 0); modifiers |= (capslockDown ? FLAG_CAPSLOCK : 0); definition += "\t" + modifiers; // add additional information if available (and necessary) if (!characterDef) definition += "\t" + KeyEvent.getKeyText(this.keyCode); // output the definition to the specified stream p.println(definition); }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodePair nodePair = (NodePair) o; if (finish != null ? !finish.equals(nodePair.finish) : nodePair.finish != null) return false; if (start != null ? !start.equals(nodePair.start) : nodePair.start != null) return false; return true; }
7
public boolean containsValidLoginDetails() { return isValidPassword() && isValidEmail(); }
1
@Override public void run() { long previousTime = System.currentTimeMillis(); long currentTime = previousTime; if( soundSystem == null ) { errorMessage( "SoundSystem was null in method run().", 0 ); cleanup(); return; } // Start out asleep: snooze( 3600000 ); while( !dying() ) { // Perform user-specific source management: soundSystem.ManageSources(); // Process all queued commands: soundSystem.CommandQueue( null ); // Remove temporary sources every ten seconds: currentTime = System.currentTimeMillis(); if( (!dying()) && ((currentTime - previousTime) > 10000) ) { previousTime = currentTime; soundSystem.removeTemporarySources(); } // Wait for more commands: if( !dying() ) snooze( 3600000 ); } cleanup(); // Important! }
5
@Override public String toString() { String str = ""; if (isFlag(DRIVE_READY)) str += "DRIVE_READY "; if (isFlag(MOTOR_OFF)) str += "MOTOR_OFF "; if (isFlag(MOVING)) str += "MOVING "; if (isFlag(VOLTAGE_FAULT)) str += "VOLTAGE_FAULT "; if (isFlag(OVER_CURRENT)) str += "OVER_CURRENT "; if (isFlag(EXCESSIVE_TEMPERATURE)) str += "EXCESSIVE_TEMPERATURE "; if (isFlag(EXCESSIVE_POSITION)) str += "EXCESSIVE_POSITION "; if (isFlag(VELOCITY_LIMIT)) str += "VELOCITY_LIMIT "; return str; }
8
@Override public void windowClosing(WindowEvent e) { kaModel.saveToFile(dataFile); }
0
public void startPolling() { pollingActive = true; Runnable pollingTask = () -> { while(pollingActive) { //wait for a bit try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //ask server if it knows about any new moves try { Move newMove = myRemoteObject.getNewMove(myInformation.getPlayerId(), myInformation.getGameId(), myInformation.getServerId()); if (newMove != null) { char a = 'a'; int startingColumn = newMove.getStartingColumn() - a; int startingRow = 8 - newMove.getStartingRow(); int targetColumn = newMove.getTargetColumn() - a; int targetRow = 8 - newMove.getTargetRow(); networkMoveListener.onNewMove(startingColumn, startingRow, targetColumn, targetRow); } } catch (RemoteException e) { System.out.println("server disconnected"); e.printStackTrace(); try { System.out.println("trying to reconnect"); context = new InitialContext(); myRemoteObject = findWorkingServer(); System.out.println("reconnect successful"); } catch (NamingException ex) { ex.printStackTrace(); } } } }; Thread t = new Thread(pollingTask); t.start(); }
5
public void extractEmails(String input){ String emailRegex = "[A-z0-9_.]+@[A-z0-9_.]+([.com]|[.net]|[.edu])"; // String emails = "[email protected], that one guy, [email protected]"; //extracts email addresses from email message // [A-z0-9_.]+@[A-z0-9_.]+([.com]|[.net]|[.edu]) p = Pattern.compile(emailRegex); m = p.matcher(input); ArrayList<String> al = new ArrayList<String>(); while(m.find()){ al.add(m.group()); } System.out.println("Returned Emails"); System.out.println(al.toString()); }
1
public boolean conditionMatches(CombineableOperator combinable) { return (type == POSSFOR || cond.containsMatchingLoad(combinable)); }
1
public static void dswap_j (int n, double dx[], int incx, double dy[], int incy) { double dtemp; int i,ix,iy,m; if (n <= 0) return; if ((incx == 1) && (incy == 1)) { // both increments equal to 1 m = n%3; for (i = 0; i < m; i++) { dtemp = dx[i]; dx[i] = dy[i]; dy[i] = dtemp; } for (i = m; i < n; i += 3) { dtemp = dx[i]; dx[i] = dy[i]; dy[i] = dtemp; dtemp = dx[i+1]; dx[i+1] = dy[i+1]; dy[i+1] = dtemp; dtemp = dx[i+2]; dx[i+2] = dy[i+2]; dy[i+2] = dtemp; } return; } else { // at least one increment not equal to 1 ix = 0; iy = 0; if (incx < 0) ix = (-n+1)*incx; if (incy < 0) iy = (-n+1)*incy; for (i = 0; i < n; i++) { dtemp = dx[ix]; dx[ix] = dy[iy]; dy[iy] = dtemp; ix += incx; iy += incy; } return; } }
8
public VDGTransitionCreator(AutomatonPane parent) { super(parent); }
0
public int lengthOfLastWord(String s) { if (s == null || s.length() == 0) { return 0; } int lastWordEnd = -1; for (int i = s.length() - 1; i >= 0; i --) { char c = s.charAt(i); if (c == ' ') { if (lastWordEnd != -1) { return lastWordEnd - i; } } else { if (lastWordEnd == -1) { lastWordEnd = i; } } } if (lastWordEnd == -1) { return 0; } return lastWordEnd + 1; }
7
@Override public void setResource(String resource) { this.resource = resource; }
0
private XMLTools() {}
0
String multiplyHelper(String str1,int digit,int zeros){ if(digit==1){ for(int i=0;i<zeros;i++){ str1+="0"; } return str1; } if(digit==0||str1.equals("0")){ return "0"; } String str=""; int advance=0; for(int i=str1.length()-1;i>=0;i--){ int temp=(str1.charAt(i)-'0')*digit+advance; advance=temp/10; str=Integer.toString(temp%10)+str; } while(advance>0){ str=Integer.toString(advance%10)+str; advance/=10; } for(int i=0;i<zeros;i++){ str+="0"; } return str; }
7
public void generatePath(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> path, TreeNode root, int sum) { path.add(root.val); if(root.left==null&&root.right==null){ if(root.val==sum){ result.add(new ArrayList<Integer>(path)); return; } else { return; } } if(root.left !=null) { generatePath(result, path, root.left, sum-root.val); path.remove(path.size()-1); } if(root.right!=null) { generatePath(result, path, root.right, sum-root.val); path.remove(path.size()-1); } }
5
@SuppressWarnings({"ToArrayCallWithZeroLengthArrayArgument"}) public void testKeySet() { int element_count = 20; int[] keys = new int[element_count]; String[] vals = new String[element_count]; TIntObjectMap<String> raw_map = new TIntObjectHashMap<String>(); for (int i = 0; i < element_count; i++) { keys[i] = i + 1; vals[i] = Integer.toString(i + 1); raw_map.put(keys[i], vals[i]); } Map<Integer, String> map = TDecorators.wrap(raw_map); assertEquals(element_count, map.size()); Set<Integer> keyset = map.keySet(); for (int i = 0; i < keyset.size(); i++) { assertTrue(keyset.contains(keys[i])); } assertFalse(keyset.isEmpty()); Object[] keys_object_array = keyset.toArray(); int count = 0; Iterator<Integer> iter = keyset.iterator(); while (iter.hasNext()) { int key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_object_array[count], key); count++; } Integer[] keys_array = keyset.toArray(new Integer[0]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } keys_array = keyset.toArray(new Integer[keyset.size()]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } keys_array = keyset.toArray(new Integer[keyset.size() * 2]); count = 0; iter = keyset.iterator(); while (iter.hasNext()) { Integer key = iter.next(); assertTrue(keyset.contains(key)); assertEquals(keys_array[count], key); count++; } assertNull(keys_array[keyset.size()]); TIntSet raw_other = new TIntHashSet(keyset); Set<Integer> other = TDecorators.wrap(raw_other); assertFalse(keyset.retainAll(other)); other.remove(keys[5]); assertTrue(keyset.retainAll(other)); assertFalse(keyset.contains(keys[5])); assertFalse(map.containsKey(keys[5])); keyset.clear(); assertTrue(keyset.isEmpty()); }
6
public ArrayList<Rectangle2D> getAllBlockedBoxes() { if(noChildren()) { ArrayList<Rectangle2D> tempBoxes = new ArrayList<Rectangle2D>(); if(this.blocked) tempBoxes.add(this.box); return tempBoxes; } else { ArrayList<Rectangle2D> tempBoxes = new ArrayList<Rectangle2D>(); for(int x = 0; x < this.children.length; x++) { tempBoxes.addAll(children[x].getAllBlockedBoxes()); } //System.out.println(tempBoxes.size()); return tempBoxes; } }
3
private final void method549(byte[] bs, int[] is, int i, int i_62_, int i_63_, int i_64_, int i_65_, int i_66_, int i_67_, int i_68_, int i_69_, int i_70_, aa var_aa, int i_71_, int i_72_) { aa_Sub1 var_aa_Sub1 = (aa_Sub1) var_aa; int[] is_73_ = var_aa_Sub1.anIntArray5487; int[] is_74_ = var_aa_Sub1.anIntArray5488; int i_75_ = i_68_ - aPureJavaToolkit5571.anInt6767; int i_76_ = i_69_; if (i_72_ > i_76_) { i_76_ = i_72_; i_63_ += (i_72_ - i_69_) * aPureJavaToolkit5571.anInt6789; i_62_ += (i_72_ - i_69_) * i_70_; } int i_77_ = i_72_ + is_73_.length < i_69_ + i_65_ ? i_72_ + is_73_.length : i_69_ + i_65_; for (int i_78_ = i_76_; i_78_ < i_77_; i_78_++) { int i_79_ = is_73_[i_78_ - i_72_] + i_71_; int i_80_ = is_74_[i_78_ - i_72_]; int i_81_ = i_64_; if (i_75_ > i_79_) { int i_82_ = i_75_ - i_79_; if (i_82_ >= i_80_) { i_62_ += i_64_ + i_67_; i_63_ += i_64_ + i_66_; continue; } i_80_ -= i_82_; } else { int i_83_ = i_79_ - i_75_; if (i_83_ >= i_64_) { i_62_ += i_64_ + i_67_; i_63_ += i_64_ + i_66_; continue; } i_62_ += i_83_; i_81_ -= i_83_; i_63_ += i_83_; } int i_84_ = 0; if (i_81_ < i_80_) { i_80_ = i_81_; } else { i_84_ = i_81_ - i_80_; } for (int i_85_ = -i_80_; i_85_ < 0; i_85_++) { if (bs[i_62_++] != 0) { is[i_63_++] = i; } else { i_63_++; } } i_62_ += i_84_ + i_62_; i_63_ += i_84_ + i_66_; } }
9
@Override public List func_22176_b() { ArrayList var1 = new ArrayList(); File[] var2 = this.field_22180_a.listFiles(); for(File var3 : var2) { if(var3.isDirectory()) { String var7 = var3.getName(); WorldInfo var8 = this.getWorldInfo(var7); if(var8 != null) { boolean var9 = var8.getSaveVersion() != 19132; String var10 = var8.getWorldName(); if(var10 == null || MathHelper.stringNullOrLengthZero(var10)) { var10 = var7; } var1.add(new SaveFormatComparator(var7, var10, var8.getLastTimePlayed(), var8.getSizeOnDisk(), var9)); } } } return var1; }
5
public SignatureVisitor visitReturnType() { if (type != METHOD_SIGNATURE || (state & (EMPTY | FORMAL | BOUND | PARAM)) == 0) { throw new IllegalArgumentException(); } state = RETURN; SignatureVisitor v = sv == null ? null : sv.visitReturnType(); CheckSignatureAdapter cv = new CheckSignatureAdapter(TYPE_SIGNATURE, v); cv.canBeVoid = true; return cv; }
3
private JButton createConfirmButton() { JButton b = new JButton("Confirm"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { submitPurchaseButtonClicked(); } catch (ParseException e1) { e1.printStackTrace(); } } }); b.setEnabled(false); return b; }
1
private static String js_substr(String target, Object[] args) { if (args.length < 1) return target; double begin = ScriptRuntime.toInteger(args[0]); double end; int length = target.length(); if (begin < 0) { begin += length; if (begin < 0) begin = 0; } else if (begin > length) { begin = length; } if (args.length == 1) { end = length; } else { end = ScriptRuntime.toInteger(args[1]); if (end < 0) end = 0; end += begin; if (end > length) end = length; } return target.substring((int)begin, (int)end); }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestBox)) return false; TestBox testBox = (TestBox) o; if (depth != testBox.depth) return false; if (height != testBox.height) return false; if (width != testBox.width) return false; if (color != null ? !color.equals(testBox.color) : testBox.color != null) return false; return true; }
7
private void emitTableCRUD( Table table ) throws Exception { // Default array params for all rows ArrayList<String> params = new ArrayList<String>(); for ( Field row : table.fields ) { params.add( SqlUtil.getJavaTypeFor( row.type ) ); params.add( row.name ); } ArrayList<String> paramsWithUnique = new ArrayList<String>(); paramsWithUnique.add( SqlUtil.getJavaTypeFor( table.getPrimaryKey().type ) ); paramsWithUnique.add( table.getPrimaryKey().name ); ArrayList<String> updateParams = new ArrayList<String>(); // TODO : add unique id updateParams.addAll( params ); Iterator<Constraint> constraintiter; writer.emitEmptyLine(); writer.emitJavadoc( table.name + " OPERATIONS\nall operations require this client to first run start" ); writer.emitEmptyLine(); // Add through ContentProviderOperation writer.beginMethod( "void", "add" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC ), params.toArray( new String[params.size()] ) ); writer.emitStatement( "ContentProviderOperation.Builder operationBuilder = ContentProviderOperation.newInsert(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ")" ); for ( Field row : table.fields ) { writer.emitStatement( "operationBuilder.withValue(" + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + "," + row.name + ")" ); } insertAddOpBlock(); writer.endMethod(); // Removes writeRemoveWith( table, table.getPrimaryKey() ); constraintiter = table.constraints.iterator(); while ( constraintiter.hasNext() ) { Constraint constraint = constraintiter.next(); if ( constraint.type.equals( Constraint.Type.UNIQUE ) ) { final String[] fields = SqlUtil.getFieldsFromConstraint( constraint ); for ( int i = 0; i < fields.length; i++ ) { writeRemoveWith( table, table.getFieldByName( fields[i] ) ); } } } // Remove All results writer.emitEmptyLine(); writer.beginMethod( "void", "removeAll" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC ) ); writer.emitStatement( "ContentProviderOperation.Builder operationBuilder = ContentProviderOperation.newDelete(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ")" ); insertAddOpBlock(); writer.endMethod(); // Update through ContentProviderOperation writer.emitEmptyLine(); writer.beginMethod( "void", "update" + Util.capitalize( table.name ), EnumSet.of( Modifier.PUBLIC ), updateParams.toArray( new String[updateParams.size()] ) ); writer.emitStatement( "ContentProviderOperation.Builder operationBuilder = ContentProviderOperation.newUpdate(" + mModel.getContentProviderName() + "." + SqlUtil.URI( table ) + ")" ); for ( Field row : table.fields ) { writer.emitStatement( "operationBuilder.withValue(" + mModel.getDbClassName() + "." + SqlUtil.ROW_COLUMN( table, row ) + "," + row.name + ")" ); } insertAddOpBlock(); writer.endMethod(); }
6
public void stop_tunnel_in(final long milllis) { new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); stop_tunnel(); } catch (Exception e) { } } }).start(); }
1
@Override public void update() { switch(this){ case START_LEVEL: if(Game.level == null){ //game over... System.out.println("game over"); } Animation.START_LEVEL_ANIMATION.update(); break; case PLAY_LEVEL: Game.gameField.update(); break; case END_LEVEL: //keep the level playing in background Game.gameField.update(); //update complete animation Animation.END_LEVEL_ANIMATION.update(); break; case GAME_OVER: Animation.GAME_OVER_ANIMATION.update(); break; } }
5
public ArrayList<String> allowedActions(String asker,String type) { // access property looks like access_read = 'u(admin,daniel),a(euscreenpreview)' // where u=user,a=application etc etc. Any normal writes on 'access_ are forbidden. ArrayList<String> list = new ArrayList<String>(); // we do them one by one to be sure if (type.equals("user")) { if (readAllowedForUser(asker)) list.add("read"); if (writeAllowedForUser(asker)) list.add("write"); } else if (type.equals("application")) { if (readAllowedForAppliction(asker)) list.add("read"); if (writeAllowedForApplication(asker)) list.add("write"); } return list; }
6
public static boolean Checkkey (String s) { if ("fk".equals(s)||"Fk".equals(s)||"FK".equals(s)||"fK".equals(s)) { return true; } else { return false; } }
4
public SpellList() { setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); setTitle("Spell List"); setBounds(100, 100, 325, 500); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); { JScrollPane scrollPane = new JScrollPane(); contentPanel.add(scrollPane, BorderLayout.CENTER); { list = new JList<String>(); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2 && !e.isConsumed()) { makeSelection(); } } }); list.setModel(buildList()); scrollPane.setViewportView(list); } } { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { makeSelection(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } setModalityType(ModalityType.APPLICATION_MODAL); setVisible(true); }
2
protected boolean couldSwitch(Behaviour last, Behaviour next) { if (next == null) return false ; if (last == null) return true ; // // TODO: CONSIDER GETTING RID OF THIS CLAUSE? It's handy in certain // situations, (e.g, where completing the current plan would come at 'no // cost' to the next plan,) but may be more trouble than it's worth. final Target NT = targetFor(next) ; if (NT != null && targetFor(last) == NT && NT != actor.aboard()) { return false ; } final float lastPriority = last.priorityFor(actor), persist = ( Choice.DEFAULT_PRIORITY_RANGE + (actor.traits.relativeLevel(STUBBORN) * Choice.DEFAULT_TRAIT_RANGE) ), threshold = persist + lastPriority, /* threshold = Math.min( lastPriority + persist, lastPriority * (1 + (persist / 2)) ), //*/ nextPriority = next.priorityFor(actor) ; if (reactionsVerbose && I.talkAbout == actor) { I.say("Last/next priority is: "+lastPriority+"/"+nextPriority) ; I.say("Threshold is: "+threshold) ; } return nextPriority >= threshold ; }
7
private void botonMoverAdministrarCatalogoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonMoverAdministrarCatalogoActionPerformed if (this.campoOrigenAdministrarCatalogo.getText().equals("Origen") || this.campoDestinoAdministrarCatalogo.getText().equals("Destino")) { JOptionPane.showMessageDialog(this, "Debe seleccionar un [Origen] y un\n[Destino] para poder mover", "Seleccione los datos", JOptionPane.INFORMATION_MESSAGE); } else { if (this.campoOrigenAdministrarCatalogo.getText().equals(this.campoDestinoAdministrarCatalogo.getText())) { JOptionPane.showMessageDialog(this, "Campos [Origen] y [Destino] no pueden ser iguales", "Modifique seleción", JOptionPane.INFORMATION_MESSAGE); } else { String dato = this.campoOrigenAdministrarCatalogo.getText(); String nombre = this.campoDestinoAdministrarCatalogo.getText(); ItemCatalogo item = this.modeloApp.obtenerItemCatalogo(dato); Categoria categoria = this.modeloApp.obtenerCategoriaConNombre(nombre); if (item != null && categoria != null) { if (item.esProducto()) { Producto p = (Producto) item; this.modeloApp.moverProductoHaciaCategoria(p.getPadre(), categoria, p); } if (item.esCategoria()) { Categoria c = (Categoria) item; if (this.modeloApp.agregarCategoriaEnCategoria(c, categoria)) { } else { JOptionPane.showMessageDialog(this, "Verifique:\n-La categoría origen no puede ser el catálogo\n-Una categoria no puede ser padre de si misma\n-Una categoría no puede estar dentro de su propia rama", "Modifique seleción", JOptionPane.INFORMATION_MESSAGE); } } } else { JOptionPane.showMessageDialog(this, "No existe dato [Origen] o [Destino]", "Datos no encontrados", JOptionPane.INFORMATION_MESSAGE); } } } }//GEN-LAST:event_botonMoverAdministrarCatalogoActionPerformed
8
public static void main(String[] args) { if (args.length<2) { System.out.println("Usage: Echo <host> <port#>"); System.exit(1); } ss = new EchoObjectStub2(); //EJERCICIO: crear una instancia del stub ss.setHostAndPort(args[0],Integer.parseInt(args[1])); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); PrintWriter stdOut = new PrintWriter(System.out); String input,output; try { //EJERCICIO: el bucle infinito: //EJERCICIO: Leer de teclado for (int i=0;i<10000; i++){ int j; byte[] buffer = new byte[80]; //E/S con InputStream y OutputStream System.out.println("Teclee una cadena"); //j = System.in.read(buffer); //System.out.print("La cadena: "); //System.out.write(buffer,0,j); String tira=null; try{ BufferedReader in = new BufferedReader(new InputStreamReader ( System.in ) ) ; tira = in.readLine(); }catch(Exception e){ } //Convertimos cadenade bytes a cadena de caracteres (2 bytes) //String tira = new String(buffer,0,j); //EJERCICIO: Invocar el stub String tira2 = ss.echo(tira); //EJERCICIO: Imprimir por pantalla System.out.println("Devolución echo: " + tira2); } } catch (IOException e) { System.err.println("I/O failed for connection to host: "+args[0]); } }
4
public void back(int velocity) { controls.back(velocity); }
0
public static void main(String[] args) { ArrayList<Integer> results = new ArrayList<Integer>(); int number = 1; do { int result = number; do { String parse = Integer.toString(result); char[] cheat = parse.toCharArray(); int suma = 0; for (int i = 0; i < cheat.length; i++) suma += Math.pow(Character.getNumericValue(cheat[i]), 2); result = suma; } while (result != 1 && result != 4); if(result == 1) results.add(number); number++; } while (number != 500); for (int i = 1; i <= results.size(); i++) { if(i == results.size()){ System.out.println(results.get(i-1)); return; } System.out.print(results.get(i-1) + ", "); if(i == 0) {} else if(i % 15 == 0) System.out.println(); } }
9
@Override public void onCombatTick(int x, int y, Game game) { SinglePlayerGame spg = (SinglePlayerGame) game; List<Entity> neighbors = spg .getSquareNeighbors(x, y, 1); for (Entity entity : neighbors) { if (entity.id == zombie.id) { if (((MortalEntity) entity).damage(22)) { spg.addAnimation(Animation.hitAnimationFor(22, entity, spg)); juggernaut.damageDealt += 22; juggernaut.kills++; zombie.deaths++; } } else if (entity.id == wall.id) { ((MortalEntity) entity).damage(22); } } }
4
private void update(DocumentEvent event) { String newValue = ""; try { Document doc = event.getDocument(); newValue = doc.getText(0, doc.getLength()); } catch (BadLocationException e) { e.printStackTrace(); } if (newValue.length() > 0) { int index = targetList.getNextMatch(newValue, 0, Position.Bias.Forward); if (index < 0) { index = 0; } targetList.ensureIndexIsVisible(index); String matchedName = targetList.getModel().getElementAt(index).toString(); if (newValue.equalsIgnoreCase(matchedName)) { if (index != targetList.getSelectedIndex()) { SwingUtilities.invokeLater(new ListSelector(index)); } } } }
5
public PlanBeschreibung(JSONObject setup, Object obj) throws FatalError { super("Beschreibung"); if (obj == null || ! (obj instanceof String)) { throw new ConfigError("Beschreibung"); } else { content = (String) obj; } }
2