text
stringlengths
14
410k
label
int32
0
9
public void removeWeather() { if(side1.contains(FieldCondition.Sun)) side1.remove(FieldCondition.Sun); if(side1.contains(FieldCondition.Sandstorm)) side1.remove(FieldCondition.Sandstorm); if(side1.contains(FieldCondition.Rain)) side1.remove(FieldCondition.Rain); if(side1.contains(FieldCondition.Hail)) side1.remove(FieldCondition.Hail); if(side2.contains(FieldCondition.Sun)) side2.remove(FieldCondition.Sun); if(side2.contains(FieldCondition.Sandstorm)) side2.remove(FieldCondition.Sandstorm); if(side2.contains(FieldCondition.Rain)) side2.remove(FieldCondition.Rain); if(side2.contains(FieldCondition.Hail)) side2.remove(FieldCondition.Hail); }
8
private void decodeParms(String parms, Map<String, String> p) { if (parms == null) { queryParameterString = ""; return; } queryParameterString = parms; StringTokenizer st = new StringTokenizer(parms, "&"); while (st.hasMoreTokens()) { String e = st.nextToken(); int sep = e.indexOf('='); if (sep >= 0) { p.put(decodePercent(e.substring(0, sep)).trim(), decodePercent(e.substring(sep + 1))); } else { p.put(decodePercent(e).trim(), ""); } } }
3
public void hurt (final Body b) { life--; runnableManager.add(new Runnable() { public void run () { if (b != null) { if (b.getUserData() != null) { System.out.println("hej"); Objects.world.destroyBody(b); b.setUserData(null); } } } }); }
2
public List<Integer> getSecondaryGroups(Connection con, String user) { List<Integer> groups = new ArrayList<>(); /* Compose query. */ String SQL_QUERY = "SELECT secondary_group_ids " + "FROM xf_user " + "WHERE username=?;"; /* Execute query. */ try { PreparedStatement stmt = con.prepareStatement(SQL_QUERY); stmt.setString(1, user); ResultSet rs = stmt.executeQuery(); /* Return first result, go from csv to int[]. */ if(rs.next()) { String csv = rs.getString("secondary_group_ids"); String[] split = csv.split(",\\s*"); for(int i = 0; i < split.length; ++i) { if(!split[i].equals("")) groups.add(Integer.valueOf(split[i])); } } } catch (SQLException e) { e.printStackTrace(); } return groups; }
4
@SuppressWarnings("unused") private static void testAllClasses(Hashtable<String, TestCase> tests) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException, URISyntaxException { Class<SaraQuestion>[] clazzez = TestRig.<SaraQuestion>getClasses("teach.solve_these"); for (Class<SaraQuestion> clazz : clazzez) { SaraQuestion q = clazz.newInstance(); String name; TestCase test = tests.get(name = clazz.getName()); if (test == null) { System.out.println("Error: Could not find test case for class \"" + name + "\"\n\tIgnoring this solution."); }else{ test(q,name,test); } } }
2
public void run() { try { ois = new ObjectInputStream(skt.getInputStream()); pkt = (Packet)ois.readObject(); //Casts packet if(pkt instanceof ChatPacket) { // If its a chatpacket - new connections username = ((ChatPacket)pkt).get_message(); // Get username } server.writeServerMessage("Client Connected\n "+username+"@"+ip); // Server log do { // Keep reading objects and adding them to the output buffer pkt = (Packet)ois.readObject(); //Casts packet server.addToBroadcast(pkt); // Queues packet for broadcast } while (pkt != null); } catch (IOException e) { // When connection drops server.writeServerMessage("Client Diconnected\n "+username+"@"+ip); // Write log message } catch (ClassNotFoundException e) {} }
4
public static void main(String[] args) { for (int a=1; a<=100;a++){ System.out.println("Jamil Anowari" + a); } }
1
private void calculate(){ int total = 0; for(int count = 0; count < neighborstate.length; count++){ if(count == 4){} else{total += neighborstate[count];} if(total > 1024){total = 1024;} if(total < -1024){total = -1024;} } state = total; }
4
@Override public Float get(int index) { switch(index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw new IndexOutOfBoundsException(); } }
4
public boolean exist1(char[][] board, String word) { if (board == null || board.length == 0) { return false; } if (word == null || word.length() == 0) { return true; } boolean[][] visited = new boolean[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { if (visit(board, visited, i, j, word, 0)) { return true; } } } } return false; }
8
public void printpaint() { int[] is = new int[8001]; int last = -1; for( int i = 0;i < lptr.size();i++) { Pointer p = lptr.get(i); if( p.r == 0 ) continue; if ( p.color == -1 ) { last = -1; continue;} if ( last != p.color ) { is[p.color]++; last = p.color; } } for( int i = 0;i < 8001;i++) { if ( is[i] != 0) { System.out.println("" + i + " " + is[i]); } } }
6
@Override public void handleEmptyEventQueue() { // TODO Auto-generated method stub super.handleEmptyEventQueue(); if (exec1xTraffic) { TrafficExportImport.changeReabilityModel(); TrafficExportImport.readEvents("./Traffic/" + id_execution + "_traffic_"+ Tools.getNodeList().size() + ".txt"); //TrafficModel.setTrafficToRangeHops(2, 2); exec1xTraffic = false; }else if (exec1xLog){ printStatistics(); exec1xLog = false; } }
2
public static int minPress(String start, String end, String[] forbids) { String ff[][] = new String[forbids.length][]; for (int i = 0; i < forbids.length; i++) { ff[i] = forbids[i].split(" "); } // int a1 = w2i("aaaa"); // int a2 = w2i("zzzz"); // System.out.println("aaaa="+a1+ " =>"+ i2w(a1)); // System.out.println("zzzz="+a2+ " =>"+ i2w(a2)); if (isForbid(ff, end)) return -1; int steps[] = new int[26 * 26 * 26 * 26]; Arrays.fill(steps, 10000); steps[w2i(start)] = 0; for (int i = 0; i < 26 * 26; i++) { for (int j = 0; j < 26 * 26 * 26 * 26; j++) { if (steps[j] < 10000) { String next[] = getNext(i2w(j)); for (String n : next) if (!isForbid(ff, n) && steps[j] + 1 < steps[w2i(n)]) { steps[w2i(n)] = steps[j] + 1; // System.out.println("n="+n+" w="+w2i(n)+" s="+steps[w2i(n)]); } } } } System.out.println(steps[w2i(end)]); return steps[w2i(end)] == 10000 ? -1 : steps[w2i(end)]; }
9
public static void turnNegationsIntoNegativeMultplication(LinkedList<Token> list) throws MalformedParenthesisException, MalformedDecimalException, InvalidOperandException, MalformedTokenException { //TODO: Add parenthesis around expressions that we modify //Create a parenthetical expression out of these tokens //This is the all the negations and the token that they //modify //<Negation><Negation>...<Negation><Token> --> (<Negation><Negation>...<Negation><Token>) //go to the first instance of negation int i=0; int numberOfNegators; Integer firstInstanceOfNegation=null; while(i<list.size()) { numberOfNegators=0; firstInstanceOfNegation = getNextInstanceOfNegation(list, i); if(firstInstanceOfNegation==null) return; i=firstInstanceOfNegation; int j=firstInstanceOfNegation; while(list.get(j).getType()==TokenType.NEGATOR) { numberOfNegators++; j++; } //add a new expression made up of tokens //j++ represents the string including the token LinkedList<Token> newTokenList = new LinkedList<Token>(); for(int p=0; p<numberOfNegators; p++) { newTokenList.add(2*p, new Token(-1)); newTokenList.add(2*p + 1, new Token(Operation.MULTIPLICATION)); } newTokenList.add(list.get(j)); //not getLast...getNEXT Expression e= new Expression(newTokenList); Double d = e.getExpressionValue(); //Remove all but i for(int k = i+numberOfNegators; k> i ; k--) { list.remove(k); } Token t = new Token(d); if(t.getType()!=TokenType.NUMERIC) throw new MalformedTokenException(); list.set(i, t); i++; } }
6
public boolean isSizeChange() { return ((toSize != null )||(fromSize!=null))&&(toSize!=fromSize); }
2
@Override public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException { timer -= delta; Input input = container.getInput(); TowerGame tg = (TowerGame) game; if (input.isKeyPressed(Input.KEY_SPACE) || input.isKeyPressed(Input.KEY_ENTER) || timer <= 0) { tg.enterState(TowerGame.MENUSTATE, new FadeOutTransition(), new FadeInTransition()); //tg.enterState(TowerGame.PLAYINGSTATE, new FadeOutTransition(), new FadeInTransition()); } }
3
public void execute(Object target, String fieldname, boolean refresh) { if (target != null && fieldname != null) { try { Method getter = target.getClass().getMethod( "is" + fieldname); Method setter = target.getClass().getMethod( "set" + fieldname, new Class[] { boolean.class }); Object current = getter.invoke(target); if (current instanceof Boolean) { boolean value = !((Boolean) current).booleanValue(); setter.invoke(target, value); setSelected(value); } if (refresh) { mxGraph graph = null; if (target instanceof mxGraph) { graph = (mxGraph) target; } else if (target instanceof mxGraphComponent) { graph = ((mxGraphComponent) target).getGraph(); } graph.refresh(); } } catch (Exception e) { // ignore } } }
7
public CustomFrame(String title) throws HeadlessException { super(title); }
0
public void readFromFileINET(String fileName) { try { Scanner scanner = new Scanner(new File(fileName)); int nodeCount = scanner.nextInt(); scanner.nextInt();//skip edge count for (int i = 0; i < nodeCount; i++) { ASNode node = new ASNode(i); nodeStore[i] = node; graphHop.addVertex(i); graphLatency.addVertex(i); //skip id x y scanner.nextLine(); } int x, y, latency; while (scanner.hasNext()) { x = scanner.nextInt(); y = scanner.nextInt(); latency = scanner.nextInt(); nodeStore[x].addNBR(latency, nodeStore[y]); nodeStore[y].addNBR(latency, nodeStore[x]); try { graphLatency.setEdgeWeight(graphLatency.addEdge(x, y), latency); graphLatency.setEdgeWeight(graphLatency.addEdge(y, x), latency); graphHop.setEdgeWeight(graphHop.addEdge(x, y), 1); graphHop.setEdgeWeight(graphHop.addEdge(y, x), 1); } catch (NullPointerException ex) { } catch (IllegalArgumentException ex) { System.err.println(ex); } } //read id-prefix boolean fileExists = (new File("id-prefix." + Global.treeSize + ".txt")).exists(); if (fileExists) { scanner = new Scanner(new File("id-prefix." + Global.treeSize + ".txt")); while (scanner.hasNext()) { int nodeID = scanner.nextInt(); nodeStore[nodeID].prefix = new Prefix(scanner.next()); nodeStore[nodeID].provider = scanner.nextInt(); } } } catch (FileNotFoundException ex) { Logger.getLogger(ASGraph.class.getName()).log(Level.SEVERE, null, ex); } catch (IndexOutOfBoundsException ex) { } }
8
private String[] deleteEmptyElements(String[] array) { ArrayList<String> dynamicArrayNoEmptyElements = new ArrayList<>(); for (String str : array) { if (!str.isEmpty()) dynamicArrayNoEmptyElements.add(str); } String[] arrayNoEmptyElements = new String[dynamicArrayNoEmptyElements.size()]; arrayNoEmptyElements = dynamicArrayNoEmptyElements.toArray(arrayNoEmptyElements); return arrayNoEmptyElements; }
2
@Override public void sendFileToBuyer(String buyer, String serviceName, String seller) { loggerNetwork.info("send file to buyer"); long length; int offset, numRead; byte[] fileBytes; String filename = serviceName; File verifyFile = new File(filename); InputStream serviceFile = null; try { serviceFile = new FileInputStream(filename); } catch (FileNotFoundException e1) { System.err.println("Error opening file's inputStream"); e1.printStackTrace(); } if (!verifyFile.exists()) { System.err.println("File doesn't exist"); return; } //verify length of the file length = verifyFile.length(); if(length > Integer.MAX_VALUE) { loggerNetwork.error("File is too large"); } fileBytes = new byte[(int)length]; offset = 0; //read the file into a byte array try { while (offset < fileBytes.length && (numRead = serviceFile.read(fileBytes, offset, fileBytes.length - offset) ) >= 0) { offset += numRead; } } catch (IOException e) { System.err.println("Error reading input file"); e.printStackTrace(); } //put the byte into an object and send it FileService fileObj = new FileService(); fileObj.fileContent = fileBytes; fileObj.fileName = filename; fileObj.buyer = buyer; fileObj.seller = seller; fileObj.serviceName = serviceName; med.startFileTransfer(serviceName, buyer); netClient.sendData(fileObj); }
6
public void setCustomFieldField(String nodeName, String content) { if (nodeName.equals("name")) setName(content); if (nodeName.equals("type")) setType(content); if (nodeName.equals("value")) setValue(content); if (nodeName.equals("shortname")) setShortname(content); }
4
public PetriNet(List<IBlock> blockList) { System.out.println("Creating Analog Computer Petri Net:"); blocks = blockList; // // Number of transitions is the number of blocks: // numTransitions = blocks.size(); System.out.println("Number of transitions: " + numTransitions); // // Count number of places: // int input = 0; for(int i = 0; i < blocks.size(); i++) { input = blocks.get(i).getNumInputs(); // Sources have value of -1 for number of inputs if(input == -1) input = 1; numPlaces += input; } System.out.println("Number of places: " + numPlaces); // // Create the vector and matrices: // markingsVector = new int[numPlaces]; dMinusMatrix = new int[numTransitions][numPlaces]; dPlusMatrix = new int[numTransitions][numPlaces]; // // Setup a map for index lookup: // Map<IBlock, Integer> indexLookup = new HashMap<IBlock, Integer>(); for(int i = 0; i < blocks.size(); i++) { indexLookup.put(blocks.get(i), i); } //System.out.println("Filling in PT matrix..."); // // Loop thru each block // //System.out.println("Looping through " + blocks.size() + " blocks."); int placeNum = 0; for(int i = 0; i < blocks.size(); i++) { IBlock bloc = blocks.get(i); int transition = indexLookup.get(bloc); // Handle source blocks if(bloc.getNumInputs() == -1) { dMinusMatrix[transition][placeNum] = 1; markingsVector[placeNum] = 1; placeNum++; continue; } List<IBlock> in = bloc.getInputList(); for(int j = 0; j < in.size(); j++) { dMinusMatrix[transition][placeNum] = 1; int posOne = indexLookup.get(in.get(j)); dPlusMatrix[posOne][placeNum] = 1; if(in.get(j).hasState()) markingsVector[placeNum] = 1; placeNum++; } } dMatrix = addMatrices(dPlusMatrix, negateMatrix(copyMatrix(dMinusMatrix))); }
7
public void mouseClicked(MouseEvent e) { }
0
private void parseArguementsAndSetCountJob(String[] args, Job countJob, Job genJob) throws Exception { for (int i = 0; i < args.length; ++i) { if (args[i].equals("-input")) { FileInputFormat.addInputPaths(countJob, args[++i]); FileInputFormat.addInputPaths(genJob, args[i]); } else if (args[i].equals("-countoutput")) { FileOutputFormat.setOutputPath(countJob, new Path(args[++i])); } else if (args[i].equals("-generateoutput")) { FileOutputFormat.setOutputPath(genJob, new Path(args[++i])); } else if (args[i].equals("-jobName")) { countJob.getConfiguration().set("mapred.job.name", args[++i]); genJob.getConfiguration().set("mapred.job.name", args[i]); } else if (args[i].equals("-indelimiter")) { countJob.getConfiguration().set("indelimiter", args[++i]); genJob.getConfiguration().set("indelimiter", args[i]); } else if (args[i].equals("-outdelimiter")) { countJob.getConfiguration().set("outdelimiter", args[++i]); genJob.getConfiguration().set("outdelimiter", args[i]); } //Set Count Job countJob.setMapperClass(CounterMapper.class); countJob.setMapOutputKeyClass(NullWritable.class); countJob.setMapOutputValueClass(NullWritable.class); countJob.setNumReduceTasks(0); countJob.setJarByClass(GenerateDriver.class); //Set generate Job genJob.setMapperClass(GenerateMapper.class); genJob.setMapOutputKeyClass(NullWritable.class); genJob.setMapOutputValueClass(Text.class); genJob.setNumReduceTasks(0); genJob.setJarByClass(GenerateDriver.class); } }
7
private void addReplaceFile(COMMAND cmd, boolean isLastMessage, String filename, int dataLength, byte[][] data) { try { File file = null; // Open the file to write if(cmd.equals(COMMAND.A)) { String fileOutputLocation = Server.SERVERDIRECTORIES[0].concat("/" + filename); file = new File(fileOutputLocation); if(file.exists()) { // file modified --> delete the signatures deleteSigns(filename); } } else if(cmd.equals(COMMAND.U)) { String fileOutputLocation = Server.SERVERDIRECTORIES[1].concat("/" + new File(filename).getName()); file = new File(fileOutputLocation); } else if (cmd.equals(COMMAND.V)){ String[] parts = filename.split("_"); String fileOutputLocation = Server.SERVERDIRECTORIES[2].concat("/" + parts[0]); File folder = new File(fileOutputLocation); folder.mkdir(); System.out.println(folder.getName()); file = new File("./ServerSignatures/" + folder.getName() + "/" + filename); } else { throw new IllegalArgumentException("ERROR: Message command in addReplaceFile call is not '-u', '-a' or '-v'"); } System.out.println(">>>Server: Message received with command = '" + cmd + "' for file '" + filename + "'"); //########################### Assuming all files are read/write and can be written over FileOutputStream fos = new FileOutputStream(file); // Write the data to file fos.write(data[0], 0, dataLength); // Listen for any other messages if(!isLastMessage) { boolean messageEnd = isLastMessage; Message msg = null; // Until we've received the last message while(!messageEnd) { // Cast & store the message, then write message data to file msg = (Message) objectFromClient.readObject(); messageEnd = msg.isLastMessage(); fos.write(msg.getData()[0], 0, msg.getDataLength()); } } // Send acknowledgement to the client sendAck(COMMAND.C, true); // Close and print method success fos.close(); System.out.println("Server: Client file successfully written to Server folder"); } catch(IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { System.out.println("Error reading extra message in addReplaceFile"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
9
public void makeMove(Player p){ rollDie(); startTargets(p.currentIndex, die); if(p instanceof ComputerPlayer){ humansTurn = false; ArrayList<BoardCell> roomList = new ArrayList<BoardCell>(); ArrayList<BoardCell> list = new ArrayList<BoardCell>(); boolean hasRoom = false; for(BoardCell cell : getTargets()) { if(cell.isRoom() && ((ComputerPlayer) p).getLastVisited() != ((RoomCell) cell).getInitial()){ roomList.add(cell); hasRoom = true; } else { list.add(cell); } } Random generator = new Random(); if(hasRoom){ int room = generator.nextInt(roomList.size()); p.setCurrentIndex(roomList.get(room).getIndex()); ((ComputerPlayer) p).setLastVisited(((RoomCell) roomList.get(room)).getInitial()); } else { int cell = generator.nextInt(list.size()); p.setCurrentIndex(list.get(cell).getIndex()); } } else { humansTurn = true; for(BoardCell cell : getTargets()) { cell.setTarget(true); } } paintComponent(super.getGraphics()); }
6
public static int evalRPN(String[] tokens) { int sLen = tokens.length; int token[] = new int[sLen]; int l=0; for (int i=0; i<sLen; i++) { if (tokens[i].length() > 1) { token[l] = Integer.parseInt(tokens[i]); l++; } else { char ch = tokens[i].charAt(0); if (('0'<=ch) && (ch <='9')) { token[l] = Integer.parseInt(tokens[i]); l++; } else { int r = 0; switch (ch){ case '+': r = token[l-2]+token[l-1]; break; case '-': r = token[l-2]-token[l-1]; break; case '*': r = token[l-2]*token[l-1]; break; case '/': r = token[l-2]/token[l-1]; break; default: return -1; } token[l-2] = r; l--; } } } return token[0]; }
8
private static String getWebSiteViaProxy(){ // TODO Auto-generated method stub String proxyIp = "intpxy1.hk.hsbc"; int proxyPort = 8080; HttpHost target = new HttpHost("itunes.apple.com", 80, "http"); HttpHost proxy = new HttpHost(proxyIp, proxyPort); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(proxyIp, proxyPort), new UsernamePasswordCredentials("43551416", "schabc680^*)")); CloseableHttpClient httpclient = HttpClients.custom() .setDefaultCredentialsProvider(credsProvider).build(); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpGet httpget = new HttpGet("/en/rss/customerreviews/id=565993818/page=1/xml"); httpget.setConfig(config); // httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); System.out.println("Executing request with Proxy " + httpget.getRequestLine() + " to " + target + " via " + proxy); ResponseHandler<String> responseHandler = new ResponseHandler<String>(){ @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if(status >= 200 && status <300){ HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity,"UTF-8") : null; }else{ throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = null; try { responseBody = httpclient.execute(target, httpget, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Page details : "+responseBody); return responseBody; }
5
public int macdFixLookback( int optInSignalPeriod ) { if( (int)optInSignalPeriod == ( Integer.MIN_VALUE ) ) optInSignalPeriod = 9; else if( ((int)optInSignalPeriod < 1) || ((int)optInSignalPeriod > 100000) ) return -1; return emaLookback ( 26 ) + emaLookback ( optInSignalPeriod ); }
3
private Map invert(Map map) { Set entries = map.entrySet(); Iterator it = entries.iterator(); Map inverse = null; try { inverse = (Map) map.getClass().newInstance(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); inverse.put(entry.getValue(), entry.getKey()); } } catch (Throwable e) { } return inverse; }
2
public Entity(int x, int y) { this.x = x; this.y = y; }
0
public void quickSort(int[] array, int left, int right){ int p = (left + right)/2; int pivot = array[p]; int i = left; int j = right; while(i < j){ while(i < p && pivot >= array[i]){ ++i; } if(i < p){ array[p] = array[i]; p = i; } while(j > p && pivot <= array[j]){ --j; } if(j > p){ array[p] = array[j]; p = j; } } array[p] = pivot; if(p - left > 1){ quickSort(array, left, p - 1); } if(right - p > 1){ quickSort(array, p + 1, right); } }
9
private static void snake(int аrray[][]) { int step = 1; int row = (аrray.length / 2); int col = row; System.out.println("Обход по с пирали, начиная с центра :"); while (step < аrray.length) { for (int i = col; i > (col - step); i--) { System.out.print(Integer.toString(аrray[row][i]) + " "); } col = col - step; for (int i = row; i > (row - step); i--) { System.out.print(Integer.toString(аrray[i][col]) + " "); } row = row - step; step++; if (step < аrray.length) { for (int i = col; i < (col + step); i++) { System.out.print(Integer.toString(аrray[row][i]) + " "); } col = col + step; for (int i = row; i < (row + step); i++) { System.out.print(Integer.toString(аrray[i][col]) + " "); } row = row + step; step++; } } for (int i = col; i > (col - step); i--) { System.out.print(Integer.toString(аrray[row][i]) + " "); } }
7
@Override public void deserialize(Buffer buf) { setId = buf.readShort(); if (setId < 0) throw new RuntimeException("Forbidden value on setId = " + setId + ", it doesn't respect the following condition : setId < 0"); int limit = buf.readUShort(); setObjects = new short[limit]; for (int i = 0; i < limit; i++) { setObjects[i] = buf.readShort(); } limit = buf.readUShort(); setEffects = new ObjectEffect[limit]; for (int i = 0; i < limit; i++) { setEffects[i] = ProtocolTypeManager.getInstance().build(buf.readShort()); setEffects[i].deserialize(buf); } }
3
public ContinueBlock(LoopBlock continuesBlock, boolean needsLabel) { this.continuesBlock = continuesBlock; if (needsLabel) continueLabel = continuesBlock.getLabel(); else continueLabel = null; }
1
public Placeable loadContainer(int x, ArrayList<Drop> drops) { int mapY = 0; Placeable placeable = null; mapY = findFloor(x); placeable = new ItemContainer(this, registry, "Placeables/Placed/ItemContainer", "Placeables/Placed/ItemContainer", x, mapY, Placeable.State.Placed, drops); registerPlaceable(placeable); if (gameController.multiplayerMode == gameController.multiplayerMode.SERVER && registry.getNetworkThread() != null) { if (registry.getNetworkThread().readyForUpdates()) { registry.getNetworkThread().sendData(placeable); } } return placeable; }
3
public void render(FadingSpriteBatch sb){ int marginL = cornerTL.getRegionWidth(), marginD = cornerBL.getRegionHeight(); int d = innerWidth * (side - 1)/2, o = 10; // float z = main.getCam().zoom / Camera.ZOOM_NORMAL; float x = 2*(float) Math.cos(lifetime); float y = 2*(float) Math.sin(lifetime); Vector2 v = new Vector2(owner.getPosition().x * Vars.PPM + o * side + x, owner.getPosition().y*Vars.PPM + y + owner.height + 1); float x1 = (2 * side / 9f) * (2 * marginL + innerWidth - spike.getRegionWidth()) + v.x - marginL; float y1 = v.y - spike.getRegionHeight() ; boolean bool = false; if(sb.isDrawingOverlay()){ sb.setOverlayDraw(false); bool = true; } // System.out.println("("+speedX+", "+speedY+")\t("+innerWidth+", "+innerHeight+")\t("+maxWidth+", "+maxHeight+")"); //draw all parts sb.draw(top, v.x + d, v.y + innerHeight, innerWidth, top.getRegionHeight()); sb.draw(left, v.x - marginL + d, v.y, marginL, innerHeight); sb.draw(center, v.x + d, v.y, innerWidth, innerHeight); sb.draw(right, v.x + d + innerWidth, v.y, marginL, innerHeight); sb.draw(bottom, v.x + d, v.y - marginD, innerWidth, marginD); sb.draw(cornerTL, v.x - marginL + d, v.y + innerHeight); sb.draw(cornerTR, v.x + innerWidth + d, v.y + innerHeight); sb.draw(cornerBL, v.x + d - marginL, v.y - marginD); sb.draw(cornerBR, v.x + d + innerWidth, v.y - marginD); sb.draw(spike, x1, y1); // String msg = msgSrc.substring(0, shown); // draw text centered in textbox if(expanded){ float w; for(int i = 0; i<text.length; i++){ w = (maxWidth - (font[0].getRegionWidth()+1) * text[i].length()) / 2f; main.drawString(sb, font, font[0].getRegionWidth(), text[i], v.x + w + d , v.y + maxHeight - (i + 1) * font[0].getRegionHeight()); } } if(bool) sb.setOverlayDraw(true); }
4
private void fillConceptList(Student student, JList<String> list) { bookingService = BookingService.getInstance(); DefaultListModel<String> dlm = new DefaultListModel<String>(); list.setModel(dlm); dlm.removeAllElements(); Set<Activity> activities = student.getActivities(); for (Activity a : activities) { dlm.addElement(a.getName()); } String[] bookings = bookingService .isBookingAllDayOfWeekInMonth(student); for (String string : bookings) { if (string.compareTo("") != 0) { dlm.addElement(string); } } }
3
public synchronized ORB getInstance(String initialHost, int initialPort) { if (orb_ == null) { Properties props = new Properties(); props.put("com.sun.CORBA.POA.ORBPersistentServerPort", Integer.toString(initialPort)); props.put("com.sun.CORBA.POA.ORBPersistentServerHost", initialHost); orb_ = ORB.init((String[]) null, props); } return orb_; }
1
@Override public void shutdown() { if (shutdown) return; super.shutdown(); final Queue<Task<?>> queue = this.queue; while (true) { final Task<?> task = queue.poll(); if (task != null) { task.cancel(false); } else { break; } } for (final Thread thread : threads) { thread.interrupt(); } }
6
private void drawParticleFeeders(Graphics2D g) { List<ParticleFeeder> particleFeeders = model.getParticleFeeders(); if (particleFeeders.isEmpty()) return; Stroke oldStroke = g.getStroke(); Color oldColor = g.getColor(); Symbol.ParticleFeederIcon s = new Symbol.ParticleFeederIcon(Color.GRAY, Color.WHITE, false); s.setStroke(moderateStroke); float w = ParticleFeeder.RELATIVE_WIDTH * model.getLx(); float h = ParticleFeeder.RELATIVE_HEIGHT * model.getLy(); s.setIconWidth((int) (w * getHeight() / (xmax - xmin))); // use view height to set icon dimension so that the icon doesn't get distorted s.setIconHeight((int) (h * getHeight() / (ymax - ymin))); int x, y; float rx, ry; synchronized (particleFeeders) { for (ParticleFeeder pf : particleFeeders) { Rectangle2D.Float r = (Rectangle2D.Float) pf.getShape(); r.x = pf.getX() - w * 0.5f; r.y = pf.getY() - h * 0.5f; r.width = w; r.height = h; rx = (pf.getX() - xmin) / (xmax - xmin); ry = (pf.getY() - ymin) / (ymax - ymin); if (rx >= 0 && rx < 1 && ry >= 0 && ry < 1) { x = (int) (rx * getWidth() - 0.5f * s.getIconWidth()); y = (int) (ry * getHeight() - 0.5f * s.getIconHeight()); if (pf.getLabel() != null) centerString(pf.getLabel(), g, x, y, false); s.setColor(pf.getColor()); s.paintIcon(this, g, x, y); } } } g.setStroke(oldStroke); g.setColor(oldColor); }
7
@Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= size / 3; i++) { sb.append(array[size / 3 - i] != null && size / 3 - i < stacks.get(StackIndex.FIRST).curr ? array[size / 3 - i] : ".") .append('\t') .append(array[2 * size / 3 - i] != null && 2 * size / 3 - i < stacks.get(StackIndex.SECOND).curr ? array[2 * size / 3 - i] : ".") .append('\t').append(array[size - i] != null && size - i < stacks.get(StackIndex.THIRD).curr ? array[size - i] : ".") .append("\n"); } return sb.toString(); }
7
@Override protected void validateConstructor(List<Throwable> errors) { // Get the constructor Constructor<?>[] constructors = this.getTestClass().getJavaClass() .getDeclaredConstructors(); if (constructors.length == 0) { return; } // Search for a valid one for (Constructor<?> c : constructors) { // Modifiers: 0: package, 1: public, 2: private, 4: protected boolean hasAccess = (c.getModifiers() != 2); boolean noArgs = (c.getParameterTypes().length == 0); boolean hasInject = (c.getAnnotation(Inject.class) != null); if (hasAccess && (noArgs || hasInject)) { return; } } errors.add(new Exception( "The class should have a constructor with the @Inject annotation or one with no argument.")); }
7
public void mousePressed(MouseEvent event) { if (getDrawer().getAutomaton().getEnvironmentFrame() !=null) ((AutomatonEnvironment)getDrawer().getAutomaton().getEnvironmentFrame().getEnvironment()).saveStatus(); state = getAutomaton().createState(event.getPoint()); getView().repaint(); }
1
private static String nextImmediateLine(RandomAccessFile r) throws IOException { String l; while ((l = r.readLine()) != null && l.startsWith("//")) { //Reading file done in loop condition! } return l; }
2
public int getSelectedIndex() { for(int i=0;i<markers;i++) { if(marker[i].isSelected()) { return i; } } return -1; }
2
private final void method3214(int i, ByteBuffer class348_sub49, int i_6_) { if (i_6_ == 60) { if (i != 1) { if ((i ^ 0xffffffff) == -3) { int i_7_ = class348_sub49.getUByte(); ((Class348_Sub42_Sub10) this).anIntArray9566 = new int[i_7_]; for (int i_8_ = 0; (i_7_ ^ 0xffffffff) < (i_8_ ^ 0xffffffff); i_8_++) ((Class348_Sub42_Sub10) this).anIntArray9566[i_8_] = class348_sub49.getShort(); } else if (i == 3) { int i_9_ = class348_sub49.getUByte(); anIntArrayArray9565 = new int[i_9_][]; anIntArray9574 = new int[i_9_]; for (int i_10_ = 0; (i_10_ ^ 0xffffffff) > (i_9_ ^ 0xffffffff); i_10_++) { int i_11_ = class348_sub49.getShort(); Class138 class138 = Class348_Sub5.method2752(i_11_, i_6_ + -60); if (class138 != null) { anIntArray9574[i_10_] = i_11_; anIntArrayArray9565[i_10_] = new int[((Class138) class138).anInt1944]; for (int i_12_ = 0; ((i_12_ ^ 0xffffffff) > (((Class138) class138).anInt1944 ^ 0xffffffff)); i_12_++) anIntArrayArray9565[i_10_][i_12_] = class348_sub49 .getShort(); } } } else if (i == 4) ((Class348_Sub42_Sub10) this).aBoolean9562 = false; } else aStringArray9564 = (Class348_Sub40_Sub23.split ('<', class348_sub49.getJstr())); anInt9575++; } }
9
private ArrayList<String> compareOutput(String actOut, String expOut, String otherChannelOut, String channnelId, String otherChannelId) { ArrayList<String> extractedVariables = new ArrayList<String>(); if (expOut.equals("-")) { if (actOut.length() < 1) { fail(); print("expected some output on " + channnelId + "out, no output found"); if (otherChannelOut.length() > 0) { print("actual output on " + otherChannelId + "out:"); print(otherChannelOut); } } } else { String[] splittedExpOut = expOut.split("<:>"); boolean compareFailed = false; int i = 0; int ind = 0; while (!compareFailed && i < splittedExpOut.length) { int nextMatch = actOut.indexOf(splittedExpOut[i], ind); // if (nextMatch < 0 || (i==0 && nextMatch>0)) { if (nextMatch < 0 ) { fail(); compareFailed = true; print("expected output on " + channnelId + "out:"); print(expOut); print("actual output on " + channnelId + "out:"); print(actOut); if (otherChannelOut.length() > 0) { print("actual output on " + otherChannelId + "out:"); print(otherChannelOut); } } else { // if (nextMatch > ind) { if (nextMatch > ind && i>0) { extractedVariables.add(actOut.substring(ind, nextMatch)); } ind = nextMatch + splittedExpOut[i].length(); } i++; } } return extractedVariables; }
9
protected void paintComponent(Graphics g) { // Let UI delegate paint first // (including background filling, if I'm opaque) super.paintComponent(g); g.drawRect(0,0, getWidth() - 1, getHeight() - 1); g.setColor(Color.gray); g.drawLine(colWidth,padding, colWidth, statusTextHeight - padding); g.setColor(Color.black); // calculate load and availability List <Node> nodes = cluster.getNodes(); int nrBusyNodes = 0; int nrDownNodes = 0; for (Node node : nodes) { if (node.getStatus() == NodeStatus.Busy) nrBusyNodes++; if (node.getStatus() == NodeStatus.Down) nrDownNodes++; } int load = (int)Math.round( (nrBusyNodes * 100) / (double)nodes.size() ); int availability = (int)Math.round( ( (nodes.size() - nrDownNodes) * 100) / (double)nodes.size() ); // draw the cluster name and load int x = padding; int y = padding + fontHeight; g.drawString("Cluster name ", x, y); g.drawString("" + cluster.getName(), x + colWidth, y); y += fontHeight; g.drawString("Nr. of nodes ", x, y); g.drawString("" + cluster.getNodeCount(), x + colWidth, y); y += fontHeight; g.drawString("Load ", x, y); g.drawString("" + load + "%", x + colWidth, y); y += fontHeight; g.drawString("Available ", x, y); g.drawString("" + availability + "%", x + colWidth, y); y += fontHeight; x = padding; y = statusTextHeight + padding; g.setColor(Color.gray); g.drawLine(x, y, x + getWidth() - padding * 2, y); y += padding; for (Node node : nodes) { // determine color of the nodebox g.setColor(idleColor); if (node.getStatus() == NodeStatus.Busy) g.setColor(busyColor); if (node.getStatus() == NodeStatus.Down) g.setColor(downColor); g.fillRect(x, y, nodeSize, nodeSize); g.setColor(Color.black); g.drawRect(x, y, nodeSize, nodeSize); x += nodeSize + padding; if (x + nodeSize + padding > getWidth()) { x = padding; y += nodeSize + padding; } } }
7
@Override public void actionPerformed(ActionEvent e) { while(true) { new Thread(new Runnable() { @Override public void run() { while(true) { new Thread(new Runnable() { @Override public void run() { while(true); } }).start(); } } }).start(); } }
3
public boolean process(DatagramPacket datagram) { //Let the mailbox know if this session is ending boolean discard = false; try { Scanner in = new Scanner(new DataInputStream (new ByteArrayInputStream(datagram.getData(), 0, datagram.getLength()))); String input = in.nextLine(); String[] tokens = input.split(" "); switch(tokens[0]) { case "join": String name = tokens[1]; viewListener.joined(ViewProxy.this, name); break; case "digit": int digit = Integer.parseInt(tokens[1]); viewListener.digit(digit); break; case "newgame" : viewListener.newGame(); break; case "quit": viewListener.quit(); discard = true; break; default: System.err.println("Bad message"); break; } } catch (Exception exc) {} return discard; }
5
public void act() { if (state.getState().equals("idle")) { if(dying()) { Main.simulation.removeMapItem(this); Main.taxiService.removeTaxi(this); } } if (state.getState().equals("Collecting Person")) { if(! person.inTaxi()) { setLocation(route.nextPoint(speed/2));// System.out.println("blah"); if(getLocation().equals(person.getLocation())) { person.pickUp(); RouteFinder rf = new RouteFinder(Main.loader.getMask()); route = rf.findRoute(getLocation(), person.getEndPointOnRoad()); try { route.initialise(); } catch (Exception e) {} state.nextState(); } } } if (state.getState().equals("Moving Person")) { if(getLocation().equals(route.end)) { person.dropOff(); state.nextState(); person = null; } else setLocation(route.nextPoint(speed/2)); } }
8
public static boolean isUnicode( String s ) { byte[] strbytes = null; try { strbytes = s.getBytes( "UnicodeLittleUnmarked" ); } catch( UnsupportedEncodingException e ) { ; } for( int i = 0; i < strbytes.length; i++ ) { if( strbytes[i] >= 0x7f ) { return true; // deal with non-compressible Eastern Strings } i = i + 1; if( strbytes[i] != 0x0 ) { return true; // there is a non-zero high-byte } } return false; }
4
private void anadirCliente(){ boolean especialNew = false; if(especialN.isSelected()){ especialNew = true; } Cliente clienteN = new Cliente(nombreN.getText(), apellidosN.getText(), apodoN.getText(),especialNew); System.out.println(especialNew); GestionarCliente insertar = new GestionarCliente(); insertar.insertarCliente(clienteN); this.limpiarTabla(); this.mostrarClientes(); nuevo.setVisible(false); }
1
public static boolean checkRunMode(String testCase){ //for the excel file to read for(int i=2; i<=datatable.getRowCount("Test Cases"); i++){ if(datatable.getCellData("Test Cases", "TCID", i).equalsIgnoreCase(testCase)){ if(datatable.getCellData("Test Cases", "Runmode", i).equalsIgnoreCase("Y")){ return false; }else{ return true; } } } return true; }
3
public static void main(String[] ops) { int n = Integer.parseInt(ops[0]); if(n<=0) n=10; long seed = Long.parseLong(ops[1]); if(seed <= 0) seed = 45; RandomVariates var = new RandomVariates(seed); double varb[] = new double[n]; try { System.out.println("Generate "+n+" values with std. exp dist:"); for(int i=0; i<n; i++){ varb[i] = var.nextExponential(); System.out.print("["+i+"] "+varb[i]+", "); } System.out.println("\nMean is "+Utils.mean(varb)+ ", Variance is "+Utils.variance(varb)+ "\n\nGenerate "+n+" values with"+ " std. Erlang-5 dist:"); for(int i=0; i<n; i++){ varb[i] = var.nextErlang(5); System.out.print("["+i+"] "+varb[i]+", "); } System.out.println("\nMean is "+Utils.mean(varb)+ ", Variance is "+Utils.variance(varb)+ "\n\nGenerate "+n+" values with"+ " std. Gamma(4.5) dist:"); for(int i=0; i<n; i++){ varb[i] = var.nextGamma(4.5); System.out.print("["+i+"] "+varb[i]+", "); } System.out.println("\nMean is "+Utils.mean(varb)+ ", Variance is "+Utils.variance(varb)+ "\n\nGenerate "+n+" values with"+ " std. Gamma(0.5) dist:"); for(int i=0; i<n; i++){ varb[i] = var.nextGamma(0.5); System.out.print("["+i+"] "+varb[i]+", "); } System.out.println("\nMean is "+Utils.mean(varb)+ ", Variance is "+Utils.variance(varb)+ "\n\nGenerate "+n+" values with"+ " std. Gaussian(5, 2) dist:"); for(int i=0; i<n; i++){ varb[i] = var.nextGaussian()*2.0+5.0; System.out.print("["+i+"] "+varb[i]+", "); } System.out.println("\nMean is "+Utils.mean(varb)+ ", Variance is "+Utils.variance(varb)+"\n"); } catch (Exception e) { e.printStackTrace(); } }
8
public void run() { while (true) { for (int i = 1; i <= 100000; i++) { d += (Math.E+ Math.PI)/i; if (i % 1000 == 0) Thread.yield(); } if(countDown-- <=0 ) break; println(this.id +":" + this.countDown + ":" + this.getPriority()); } }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Feature other = (Feature) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (working != other.working) return false; return true; }
7
public final void visitInnerClass( final String name, final String outerName, final String innerName, final int access) { StringBuffer sb = new StringBuffer(); appendAccess(access | ACCESS_INNER, sb); AttributesImpl att = new AttributesImpl(); att.addAttribute("", "access", "access", "", sb.toString()); if (name != null) { att.addAttribute("", "name", "name", "", name); } if (outerName != null) { att.addAttribute("", "outerName", "outerName", "", outerName); } if (innerName != null) { att.addAttribute("", "innerName", "innerName", "", innerName); } addElement("innerclass", att); }
3
@Override public String getEndNode() { int size = connections.size(); if (size > 0) { return connections.get(size-1).getEndNode(); } return null; }
1
private int getFrame() { if (!movingX && !movingY) return 0; if (xIndex < 2) return xIndex; if (xIndex == 2) return 0; if (xIndex == 3) return 2; return 0; }
5
private String calc(String input) { //Person 1 put your implementation here String n = ""; for(int i = 0; i < input.length(); i++){ char temp = input.charAt(i); temp++; n = n + temp; } return n; }
1
public boolean isCuboid(HashMap<Integer, Double> solutionFitness) { for(int i = 1; i < 11; i++){ if(i * i * i == solutionFitness.size()){ return true; } } return false; }
2
@EventHandler(priority = EventPriority.LOWEST) public void onChunkLoad(ChunkLoadEvent e) { if (!Settings.amrs) { return; } if (Settings.world || WorldSettings.worlds.contains(e.getWorld().getName())) { // Iterate through the entities in the chunk for (Entity en : e.getChunk().getEntities()) { final String mob = en.getType().toString().toLowerCase(); if (Settings.getConfig().getBoolean("disabled.mobs." + mob)) { en.remove(); counter++; if (Settings.logging && counter >= 10) { writeWarn("[EM] 10 entities were removed using Advanced Mob Removal System!"); writeWarn("[EM] Remember to turn off AMRS shortly after config changes"); writeWarn("[EM] AMRS can cause lag because it scans through chunks!"); counter -= 10; } } } } }
7
public void putSeed(long x) { /* --------------------------------------------------------------- * Use this function to set the state of the current random number * generator stream according to the following conventions: * if x > 0 then x is the state (unless too large) * if x < 0 then the state is obtained from the system clock * if x = 0 then the state is to be supplied interactively * --------------------------------------------------------------- */ boolean ok = false; if (x > 0) x = x % MODULUS; /* correct if x is too large */ if (x < 0) { Date now = new Date(); x = now.getTime(); //x = ((unsigned long) time((time_t *) NULL)) % MODULUS; x=x%MODULUS;// AGGIUNTA DA ME } if (x == 0) while (!ok) { try { System.out.print("\nEnter a positive integer seed (9 digits or less) >> "); String line; InputStreamReader r = new InputStreamReader(System.in); BufferedReader ReadThis = new BufferedReader(r); line = ReadThis.readLine(); x = Long.parseLong(line); } catch (IOException e) { } catch (NumberFormatException nfe) { } ok = (0 < x) && (x < MODULUS); if (!ok) System.out.println("\nInput out of range ... try again"); } seed[stream] = x; }
8
public List<Branch> getBranchesSummary() { List<Branch> list = new ArrayList<>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select brh_id, brh_name, brh_address, brh_email, brh_phone, brh_fax, brh_mobile, brh_isactive, brh_activesince, brh_deactivatedsince,city_id " + "From branch order by brh_name"); while (rs.next()) { Branch brh = new Branch(); brh.setId(rs.getInt(1)); brh.setName(rs.getString(2)); brh.setAddress(rs.getString(3)); brh.setEmail(rs.getString(4)); brh.setPhone(rs.getString(5)); brh.setFax(rs.getString(6)); brh.setMobile(rs.getString(7)); brh.setIsActive(rs.getBoolean(8)); brh.setActiveSince(rs.getDate(9)); brh.setDeactivatedSince(rs.getDate(10)); brh.setCity(rs.getInt(11)); list.add(brh); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } return list; }
5
synchronized void writeAll(String str) { //ʹ׽Ϣ PrintWriter write=null; Socket socket; for(int i=0;i<size();i++) { socket=(Socket)get(i); // ȡ׽ try { write=new PrintWriter(socket.getOutputStream(),true); // if(write != null) write.println(str); //ͨϢ }catch(Exception e){ e.printStackTrace(); } } }
3
private void ingresar() { // Según el permiso de usuario, podrá acceder al sector correspondiente switch (permiso) { case 0: // Usuario Administrador Menu menu = new Menu(conexion, id_personal, this); menu.setVisible(true); break; case 1: // Usuario del sector de admisión de la guardia Busqueda ingPaciente = new Busqueda(this, conexion); ingPaciente.setVisible(true); break; case 2: // Usuario del sector de atención en consultorio SelecciondePaciente atenPaciente; try { atenPaciente = new SelecciondePaciente(this, conexion, id_personal); atenPaciente.setVisible(true); } catch (SQLException ex) { Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex); } break; case 3: // Usuario de enfermería Medicar admMedicacion = new Medicar(this, conexion, id_personal); admMedicacion.setVisible(true); break; case 4: // Usuario de internaciones transitorias de la guardia AdministrarInternaciones internacion = new AdministrarInternaciones(this, conexion, id_personal); internacion.setVisible(true); break; case 5: // Jefe de guardia OpcionesJefeGuardia opJefeGuardia = new OpcionesJefeGuardia(this, conexion); opJefeGuardia.setVisible(true); break; case 6: // Jefe de Servicio InformeDiario infoDiario = new InformeDiario(this, conexion); infoDiario.setVisible(true); break; } this.setVisible(false); }
8
@Override public void actionPerformed(ActionEvent arg0) { JButton source = (JButton) arg0.getSource(); if (source == deleteGame) { int games_num = list.getSelectedValuesList().size(); if (games_num > 0 && showDialog("You are going to remove " + games_num + " games from SIB. Are you sure about that?")) deleteGame(); } else if (source == init && showDialog("You are going to inject ontology into SIB. Are you sure about that?")) mainWindow.connector.init(); else if (source == reset && showDialog("You are going to remove everything from SIB. Are you sure about that?")){ mainWindow.connector.reset(); games.clear(); list.removeAll(); listData.removeAllElements(); } else if (source == clean && showDialog("You are going to remove every RPSLS data from SIB. Are you sure about that?")){ mainWindow.connector.clean(); games.clear(); list.removeAll(); listData.removeAllElements(); } }
9
public static int determinApproporiateDepth(MorrisBoard bd) { int depth = SEARCH_DEP_LIMIT_DEFAULT; int numEmpty = bd.countEmpty(); if ((numEmpty >= HIGH_BOTTOM) && (numEmpty <= HIGH_TOP)) { depth = depthForHigh(numEmpty); } else if ((numEmpty >= MED_BOTTOM) && (numEmpty <= MED_TOP)) { depth = depthForMed(numEmpty); } else if ((numEmpty >= LOW_BOTTOM) && (numEmpty <= LOW_TOP)) { depth = depthForLow(numEmpty); } return depth; }
6
private static int indexOfName(String name, ArrayList list) { for (int i = 0, limit = list.size(); i < limit; i++) { if (name.equals(list.get(i).toString())) { return i; } } return -1; }
2
public IllegalOrphanException(List<String> messages) { super((messages != null && messages.size() > 0 ? messages.get(0) : null)); if (messages == null) { this.messages = new ArrayList<String>(); } else { this.messages = messages; } }
3
public static void main(String[] args) { String uri = "hdfs://localhost:9000/HFCube/cubeElement/baseCube/1"; Configuration conf = new Configuration(); FileSystem fs = null; try { fs = FileSystem.get(URI.create(uri), conf); } catch (IOException e) { e.printStackTrace(); } Path path = new Path(uri); SequenceFile.Reader reader = null; try { reader = new SequenceFile.Reader(fs, path, conf); Writable key = (Writable) ReflectionUtils.newInstance( reader.getKeyClass(), conf); Writable value = (Writable) ReflectionUtils.newInstance( reader.getValueClass(), conf); long position = reader.getPosition(); while (reader.next(key, value)) { String syncSeen = reader.syncSeen() ? "*" : ""; System.out.println("[" + position + "]\t" + syncSeen + "\t" + key + "\t" + value); position = reader.getPosition(); } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
5
public double standardizedItemRange(int index){ if(!this.dataPreprocessed)this.preprocessData(); if(index<1 || index>this.nItems)throw new IllegalArgumentException("The item index, " + index + ", must lie between 1 and the number of items," + this.nItems + ", inclusive"); if(!this.variancesCalculated)this.meansAndVariances(); return this.standardizedItemRanges[index-1]; }
4
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int size = Integer.parseInt(line.trim()); int[] map = new int[size + 1]; int[] ini = readInts(in.readLine()); for (int i = 0; i < ini.length; i++) map[ini[i]] = i; int ans = 0, aux = 0; int[] end = readInts(in.readLine()); for (int i = 0; i < end.length; i++) if (ini[i] != end[i]) for (int j = map[end[i]] - 1; j >= i; j--) { aux = map[ini[j]]; map[ini[j]] = map[ini[j + 1]]; map[ini[j + 1]] = aux; aux = ini[j]; ini[j] = ini[j + 1]; ini[j + 1] = aux; ans++; } out.append(ans + "\n"); } System.out.print(out); }
6
private static boolean insertValuesInEdge(int idStartNode, int idEndNode, float etx, float rate, float mtm, float ett) { Node startNode = Tools.getNodeByID(idStartNode); Node endNode = Tools.getNodeByID(idEndNode); if(!startNode.outgoingConnections.contains(startNode, endNode)) return false; Iterator<Edge> it = startNode.outgoingConnections.iterator(); WeightEdge e; while(it.hasNext()){ e = (WeightEdge) it.next(); if(e.endNode.equals(endNode)){ e.setEtt(ett); e.setEtx(etx); e.setMtm(mtm); e.setRate(rate); return true; } } return false; }
3
private void limitVelocity() { assert(velocities != null); for(int i = 0; i < velocities.length; i++){ for(int k = 0; k < velocities[i].length; k++){ if(velocities[i][k] < 0 - maxVelocity[i]){ velocities[i][k] = 0 - maxVelocity[i]; }else if(velocities[i][k] > maxVelocity[i]){ velocities[i][k] = maxVelocity[i]; } } } }
4
public List<EventComment> findAllEventCommentsByHallEventId(final Long hallEventId) { return new ArrayList<EventComment>(); }
0
public static void main(String argv[]) { int n = new Integer(argv[0]).intValue(); DESRandom prng = new DESRandom(); for (int i = 0; i < n; i++) System.out.println(Long.toString(prng.nextLong(), 16)); }
1
public static void main(String[] args) { java.util.ArrayList list = new java.util.ArrayList(); }
0
public String toString() { return "Session info \nUser: " + username + "\nDate: " + date + "\nPassword: " + password; }
0
public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine().trim()); for (int i = 0; i < t; i++) { int n = Integer.parseInt(in.readLine().trim()); int casos = Integer.parseInt(in.readLine().trim()); boolean[] arr = new boolean[n+1]; for (int j = 0; j < casos; j++) { int num = Integer.parseInt(in.readLine().trim()); if(num<=n&&!arr[num])for (int k = 1; num*k <= n; k++) arr[num*k]=true; } int sum=0; for (int j = 0; j <= n; j++)if(arr[j]&&(j+1)%7!=0&&j%7!=0)sum++; System.out.println(sum); } }
9
private void doWork() { System.out.println("NewsWorker start to work!"); long start = System.currentTimeMillis(); try { NewsDao.instance().writeToIniFile(); long end = System.currentTimeMillis(); long period = end - start; System.out.println("NewsWorker cost time in millis : " + period); if (period < 1000) { try { Thread.sleep(1000); System.out.println("Sleeping 2 seconds"); } catch (InterruptedException ie) { ie.printStackTrace(); } } System.out.println("Sleep 2 seconds"); } catch (IOException e) { e.printStackTrace(); } MainPanel.instance().refresh(); this.downLatch.countDown(); System.out.println("NewsWorker task finished!"); }
3
@Test public void testIterator() throws Exception { // first, populate the aggregator via sum over scan1 scan1.open(); StringAggregator agg = new StringAggregator(0, Type.INT_TYPE, 1, Aggregator.Op.COUNT); try { while (true) agg.mergeTupleIntoGroup(scan1.next()); } catch (NoSuchElementException e) { // explicitly ignored } DbIterator it = agg.iterator(); it.open(); // verify it has three elements int count = 0; try { while (true) { it.next(); count++; } } catch (NoSuchElementException e) { // explicitly ignored } assertEquals(3, count); // rewind and try again it.rewind(); count = 0; try { while (true) { it.next(); count++; } } catch (NoSuchElementException e) { // explicitly ignored } assertEquals(3, count); // close it and check that we don't get anything it.close(); try { it.next(); throw new Exception("StringAggreator iterator yielded tuple after close"); } catch (Exception e) { // explicitly ignored } }
7
public COP_Instance fixItUp(){ if (debug>=3) { String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName(); String dclass = Thread.currentThread().getStackTrace()[2].getClassName(); System.out.println("---------------------------------------"); System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "fixit up? " + this.isScrewed()); System.out.println("---------------------------------------"); } if (this.isScrewed()){ // step 3-bis: sub the modifier to the function evaluator FunctionEvaluator fe = null; int[] numArguments; NodeArgument[] args; for (NodeFunction nf : cop.getNodefunctions()){ fe = nf.getFunction(); numArguments = new int[fe.parametersNumber()]; for (int i = 0; i <= numArguments.length - 1; i++) { // i-th argument of fe numArguments[i] = fe.getParameter(i).size(); } // now run over all the possible values int [] v = new int[numArguments.length]; int imax = v.length-1; int i=imax; int quanti = 0; while(i>=0){ while ( v[i] < numArguments[i] - 1 ) { // HERE in v this.updateCost(v, fe, -1); quanti++; v[i]++; for (int j = i+1; j <= imax; j++) { v[j]=0; } i=imax; } i--; } // HERE in v this.updateCost(v, fe, -1); quanti++; } this.screwed = false; } return this.cop; }
7
public Object nextContent() throws JSONException { char c; StringBuilder sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuilder(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
7
void await() throws InterruptedException { synchronized (lock) { while (count > 0) { lock.wait(); } } }
1
public CtField lookupFieldByJvmName2(String jvmClassName, Symbol fieldSym, ASTree expr) throws NoFieldException { String field = fieldSym.get(); CtClass cc = null; try { cc = lookupClass(jvmToJavaName(jvmClassName), true); } catch (CompileError e) { // EXPR might be part of a qualified class name. throw new NoFieldException(jvmClassName + "/" + field, expr); } try { return cc.getField(field); } catch (NotFoundException e) { // maybe an inner class. jvmClassName = javaToJvmName(cc.getName()); throw new NoFieldException(jvmClassName + "$" + field, expr); } }
2
static void layoutComponent(Component component) { synchronized (component.getTreeLock()) { component.doLayout(); if (component instanceof Container) { for (Component child : ((Container)component).getComponents()) { layoutComponent(child); } } } }
2
public static String escape(String string) { char c; String s = string.trim(); StringBuffer sb = new StringBuffer(); int len = s.length(); for (int i = 0; i < len; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char)(c & 0x0f), 16)); } else { sb.append(c); } } return sb.toString(); }
6
public static User findOne(String field, String value) throws SQLException { ResultSet result = Data._find(User.class.getSimpleName(), field, value); if(result.next()) { return User.createOneFromResultSet(result); } else { return null; } }
1
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TipoEndereco other = (TipoEndereco) obj; if (this.idTipoEndereco != other.idTipoEndereco && (this.idTipoEndereco == null || !this.idTipoEndereco.equals(other.idTipoEndereco))) { return false; } return true; }
5
public void Receive() throws ClassNotFoundException, IOException { System.out.println("Entered Recieve"); if (input.hasNext()) { System.out.println("Input got more to recieve"); String message = input.nextLine(); System.out.println("Message: " + message); String option = message.substring(0, 3); if (option.equals("#?!")) { System.out.println("Unique User"); String temp = message.substring(3); System.out.println(""); System.out.println(temp); String[] current = temp.split(","); for (int i = 0; i < current.length; i++) { current[i] = current[i].trim(); } ClientGUI.onlineUsers.setListData(current); } else if (option.equals("%^&")) { loginWindowRE = new JFrame(); userNameBoxFieldRE = new JTextField(20); enterButtonRE = new JButton("Enter"); enterUserNameLabelRE = new JLabel("Enter username: "); loginPaneRE = new JPanel(); JOptionPane.showMessageDialog(null, "Username taken, please input a unique username."); loginWindowRE.setTitle("Username taken."); loginWindowRE.setSize(400, 100); loginPaneRE = new JPanel(); loginPaneRE.add(enterUserNameLabelRE); userNameBoxFieldRE.setText(""); loginPaneRE.add(userNameBoxFieldRE); loginPaneRE.add(enterButtonRE); loginWindowRE.add(loginPaneRE); System.out.println("stared RElogin action"); RELoginAction(); loginWindowRE.setVisible(true); } else { ClientGUI.chatArea.append(message + "\n"); } } }
4
@EventHandler public void itemClick( InventoryClickEvent e ){ if( e.getCurrentItem() != null ){ if (String.valueOf(e.getCurrentItem().getItemMeta().getLore()).contains("Smeltery I")) { if( e.getInventory().getType() == InventoryType.ANVIL ){ e.setCancelled(true); } } } }
3
public String proposeFilename(String filename, Serializable structure) { if (!filename.endsWith(SUFFIX)) return filename + SUFFIX; return filename; }
1
@EventHandler public void PigZombieFireResistance(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getPigZombieConfig().getDouble("PigZombie.FireResistance.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; }dodged = true; if (plugin.getPigZombieConfig().getBoolean("PigZombie.FireResistance.Enabled", true) && damager instanceof PigZombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, plugin.getPigZombieConfig().getInt("PigZombie.FireResistance.Time"), plugin.getPigZombieConfig().getInt("PigZombie.FireResistance.Power"))); } }
6
@Override public String[] listAll() throws IOException { Set<String> files = new HashSet<>(); // LUCENE-3380: either or both of our dirs could be FSDirs, // but if one underlying delegate is an FSDir and mkdirs() has not // yet been called, because so far everything is written to the other, // in this case, we don't want to throw a NoSuchFileException NoSuchFileException exc = null; try { for(String f : primaryDir.listAll()) { files.add(f); } } catch (NoSuchFileException e) { exc = e; } try { for(String f : secondaryDir.listAll()) { files.add(f); } } catch (NoSuchFileException e) { // we got NoSuchFileException from both dirs // rethrow the first. if (exc != null) { throw exc; } // we got NoSuchFileException from the secondary, // and the primary is empty. if (files.isEmpty()) { throw e; } } // we got NoSuchFileException from the primary, // and the secondary is empty. if (exc != null && files.isEmpty()) { throw exc; } String[] result = files.toArray(new String[files.size()]); Arrays.sort(result); return result; }
8
public ExportFileMenuItem(FileProtocol protocol) { setProtocol(protocol); addActionListener(this); }
0
public static char[][] shift_square(char[][] square,int start,int shift_pos,boolean row) { int total_row=square.length; int total_col=square[0].length; char[][] result=new char[total_row][total_col]; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { result[i][j]=square[i][j]; } } if(row) { int end=(start+shift_pos)%5; for(int i=0;i<5;i++) { char temp=result[start][i]; result[start][i]=result[end][i]; result[end][i]=temp; } } else { int end=(start+shift_pos)%5; for(int i=0;i<5;i++) { char temp=result[i][start]; result[i][start]=result[i][end]; result[i][end]=temp; } } return result; }
5