text
stringlengths
14
410k
label
int32
0
9
* @return the given api command string with the binding environment for bookkeeping assertions */ public String wrapBookkeeping(String command) { final String projectName = (project == null) ? "nil" : project.stringApiValue(); final String cyclistName = (cyclist == null) ? "nil" : cyclist.stringApiValue(); String wrappedCommand = "(with-bookkeeping-info (new-bookkeeping-info " + cyclistName + " (the-date) " + projectName + " (the-second))\n" + wrapCyclistAndPurpose(command, cyclistName, projectName) + "\n)"; return wrappedCommand; }
2
public ArrayList<Token> tokenize(char[] array){ ArrayList<Token> tokens = new ArrayList<Token>(); StringBuilder cur = new StringBuilder(); for(int i=0;i<array.length;i++){ if(CharUtil.isNumber(array[i])){ cur.append(array[i]); } else { if(cur.length() > 0 ){ tokens.add(new Token(cur.toString())); cur = new StringBuilder(); } if(array[i] == '(' ){tokens.add(new Token("("));} if(array[i] == ')' ){tokens.add(new Token(")"));} if(array[i] == '+' ){tokens.add(new PlusToken("+"));} if(array[i] == '-' ){tokens.add(new MinusToken("-"));} } } if(cur.length() > 0 ) tokens.add(new Token(cur.toString())); return tokens; }
8
public static void main (String[] args) { int accumulator = 0; String choice = "y"; while (choice.equalsIgnoreCase("y")) { //Welcome statement to the user. System.out.println("Welcome to the Guess Number Game"); System.out.println("+++++++++++++++++++++++++++++++++"); System.out.println(); System.out.println("I'm thinking of a number from 1 to 100."); System.out.println("Try to guess it."); System.out.println(); //Generate the computer's random guess. int cg = 1 + (int) (Math.random() * 100); //System.out.println(cg); Used for testing only. //Have the user enter guesses. Scanner sc = new Scanner(System.in); System.out.println("Enter number: "); int y = -1; while (y != cg) { y = getInt(sc, y); if (y > cg + 10) { System.out.println("Way too high! Guess again."); } else if (y < cg) { System.out.println("Too low! Guess again."); } else System.out.println("Too high! Guess again."); accumulator += 1; } if (accumulator <= 3) { System.out.println("Great work! You are a mathematical wizard."); } else if (accumulator > 7) { System.out.println("What took you so long? Maybe you should take some lessons."); } else { System.out.println("Not too bad! You've got some potential."); } System.out.println("Would you like to play again? (y/n): "); choice = sc.next(); } System.out.println(); System.out.println("Thanks for playing!"); }
6
public static void testThis(String[] args) { boolean decode = false; if (args.length == 0) { System.out.println("usage: java Base64 [-d[ecode]] filename"); System.exit(0); } for (int i=0; i<args.length; i++) { if ("-decode".equalsIgnoreCase(args[i])) decode = true; else if ("-d".equalsIgnoreCase(args[i])) decode = true; } String filename = args[args.length-1]; File file = new File(filename); if (!file.exists()) { System.out.println("Error: file '" + filename + "' doesn't exist!"); System.exit(0); } if (decode) { char[] encoded = readChars(file); byte[] decoded = decode(encoded); writeBytes(file, decoded); } else { byte[] decoded = readBytes(file); char[] encoded = encode(decoded); writeChars(file, encoded); } }
6
public static ArraysDataBase getStructureBase(){ return structuresBase; }
0
@Override public boolean execute(SimpleTowns plugin, CommandSender sender, String commandLabel, String[] args) { final Localisation localisation = plugin.getLocalisation(); if (!(sender instanceof Player)) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_PLAYER_ONLY_COMMAND)); return true; } final String townname; final String leadername; switch (args.length) { case 0: { sender.sendMessage(localisation.get(LocalisationEntry.ERR_SPECIFY_TOWN_NAME)); return false; } case 1: { // ... townname townname = args[0]; leadername = sender.getName(); break; } case 2: { // ... townname leader townname = args[0]; leadername = args[1]; break; } default: { sender.sendMessage(localisation.get(LocalisationEntry.ERR_TOWN_NAMES_MUST_BE_A_SINGLE_WORD)); return false; } } // Validate town name if (!TownUtils.isValidName(townname)) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_INVALID_TOWN_NAME, townname)); return true; } // Validate leader name if (!new NameValidityChecker(leadername).isValidName()) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_INVALID_PLAYER_NAME, leadername)); return true; } // Check town doesn't already exist if (plugin.getTown(townname) != null) { sender.sendMessage(localisation.get(LocalisationEntry.ERR_TOWN_ALREADY_EXISTS, townname)); return true; } // Check there isn't already a town in that chunk final Player player = (Player) sender; final Chunk chunk = player.getLocation().getChunk(); final Town town = plugin.getTown(chunk); if (town != null) { sender.sendMessage(localisation.get(LocalisationEntry.MSG_CHUNK_ALREADY_CLAIMED, town.getName())); return true; } //Create and call TownCreateEvent final TownCreateEvent event = new TownCreateEvent(town, sender); plugin.getServer().getPluginManager().callEvent(event); // Check event has not been cancelled by event listeners if (event.isCancelled()) { return true; } final int chunkX = chunk.getX(); final int chunkZ = chunk.getZ(); final String worldname = chunk.getWorld().getName(); final TownChunk townchunk = new TownChunk(chunk); // Create town final String path = "Towns."; plugin.getConfig().set(path + townname + ".Leaders", Arrays.asList(leadername)); // Log to file final Logger logger = new Logger(plugin); logger.log(localisation.get(LocalisationEntry.LOG_TOWN_CREATED, townname, player.getName())); logger.log(localisation.get(LocalisationEntry.LOG_TOWN_LEADER_ADDED, townname, leadername, player.getName())); // Add first chunk to town plugin.getConfig().set(path + townname + ".Chunks." + worldname, Arrays.asList(chunkX + "," + chunkZ)); plugin.getTowns().put(townname.toLowerCase(), new Town(townname, leadername, townchunk)); // Log to file logger.log(localisation.get(LocalisationEntry.LOG_CHUNK_CLAIMED, townname, player.getName(), worldname, chunkX, chunkZ)); // Save config plugin.saveConfig(); // Send confimation message to sender sender.sendMessage(localisation.get(LocalisationEntry.MSG_TOWN_CREATED, townname)); // Broadcast to server plugin.getServer().broadcastMessage(localisation.get(LocalisationEntry.MSG_TOWN_CREATED_BROADCAST, townname)); return true; }
9
public static Preferences creerPrefConsole(){ String[] basePrefs = {"Conversation", "Musique", "Animaux", "Fumeur"}; Preferences listePrefs = new Preferences(); Scanner sc = new Scanner(System.in); System.out.println("Répondez avec 'o' ou 'n'."); for(String s : basePrefs){ System.out.print(s+" ? "); String se = sc.nextLine(); while(!(se.equals("o")||se.equals("n"))){ System.out.println("Répondre avec 'o' ou 'n'."); System.out.print(s+" "); se = sc.nextLine(); } if(se.charAt(0)=='o'){ listePrefs.put(s, true); } else{ listePrefs.put(s, false); } } return listePrefs; }
4
public void actionPerformed(ActionEvent e) { if (e.getSource() == Cancel) { this.dispose(); } else if (e.getSource() == Ok) { updateArgs(); this.dispose(); } }
2
@Action(name = "hcomponent.handler.onclick.param", args = {}) public void onClickAction(Updates updates, String param) { HComponent<?> html = (HComponent<?>) Session.getCurrent().get( "_hcomponent.object." + param); if (html.getOnClickListener() != null) ContentManager.requestParams( "hcomponent.handler.onclick.invoke", Session.getCurrent().gethActionManager() .getHAction(html.getOnClickListener()) .getArguments(), param); }
3
private Response handleRequest(String url) { Response r = new Response(); try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { System.err.println(conn.getURL()); throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } System.out.println(conn.getURL()); BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output = ""; String jsonString = ""; while ((output = br.readLine()) != null) { jsonString += output; } conn.disconnect(); Gson gson = new Gson(); r = gson.fromJson(jsonString, Response.class); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return r; }
5
private GlobalTimes() { }
0
private JTextArea getTextAreaMain() { if (textAreaMain == null) { textAreaMain = new JTextArea(); } return textAreaMain; }
1
public returnTypes deleteFile(byte[] fileID) { String recID = Packet.bytesToHex(fileID); for(BackupFile file : files) { String comID = Packet.bytesToHex(file.getFileID()); if(comID.equals(recID)) { new File (file.getFilename()).delete(); boolean success = files.remove(file); if(success) { updateLog(); return returnTypes.SUCCESS; } } } return returnTypes.FILE_DOES_NOT_EXIST; }
3
public IPokemon getCorrectPokemon(boolean isPlayer) { return isPlayer ? getPlayer().getPokemon() : enemy; }
1
@Override public void propertyChange(PropertyChangeEvent pce) { String propName = pce.getPropertyName(); if (propName.equals("progress")){ int value = ((Integer)pce.getNewValue()).intValue(); if (value >= minValue && value <= maxValue){ setValue(value); label.setText(" Выполнено :" + value + "%"); } else{ //close(); } } if (propName.equals("status") ){ int value = ((Integer)pce.getNewValue()).intValue(); if (value > minValue && value <= maxValue){ close(); } } }
6
public TasoTest() { }
0
@Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Save")) { finish(); } else if (e.getActionCommand().equals("Undo")) { undoredo(e.getActionCommand()); setFocusOnTxtArea(); } else if (e.getActionCommand().equals("Redo")) { undoredo(e.getActionCommand()); setFocusOnTxtArea(); } else if (e.getActionCommand().equals("Next")) { // getNext(); wasLastInsertNext = true; moveInsert(1); setFocusOnTxtArea(); } else if (e.getActionCommand().equals("Prev")) { // getPrev(); wasLastInsertNext = false; moveInsert(0); setFocusOnTxtArea(); } else if (e.getActionCommand().contains("Append")) { //call appendText function on the chars after 'append' //in the action command string to add that stuff } }
6
public Book getBook(long id) { Book book = null; 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 * From Book Where bok_id=" + id); book = new Book(); if (rs.next()) { book = new Book(); book.setId(rs.getLong(1)); book.setTitle(rs.getString(2)); book.setSubtitle(rs.getString(3)); book.setIsbn(rs.getString(4)); book.setPublisher(rs.getString(5)); book.setPublishDate(rs.getDate(6)); book.setPagesNb(rs.getInt(7)); book.setBookCategory_id(rs.getLong(8)); book.setLanguage_id(rs.getLong(9)); book.setAuthor_id(rs.getLong(10)); book.setItem_id(rs.getLong(11)); book.setBookStatus_id(rs.getLong(12)); } } 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 book; }
5
public void drawGrid(Graphics g) { g.setColor(Color.black); for (Point p: this.maze.cells) { p = this.imagify(p); g.drawRect(p.x, p.y, this.cellWidth, this.cellWidth); } }
1
private int getLargestList(List<ArrayList<CellState>> lists){ int i = -1; for(ArrayList<?> list: lists){ if(i == -1){ i = list.size(); }else{ if(i < list.size()) i = list.size(); } } return i; }
4
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed this.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed
0
public Class getTypeClass() { switch (((IntegerType) getHint()).possTypes) { case IT_Z: return Boolean.TYPE; case IT_C: return Character.TYPE; case IT_B: return Byte.TYPE; case IT_S: return Short.TYPE; case IT_I: default: return Integer.TYPE; } }
5
private static int getStart( String string ) { for ( int i = 0; i < string.length(); ++i ) { if ( isBreaker( string.charAt( i ) ) == false ) { return i; } } return -1; }
2
@Override public void mouseClicked(MouseEvent arg0) { if( arg0.getSource()==botonJugar){ this.dispose(); vJuego juego= new vJuego(null,JTBlancas.getText(),JTNegras.getText()); juego.setVisible(true); } if(arg0.getSource()==botonVolver) { this.dispose(); vInicio inicio= new vInicio(); inicio.setVisible(true); } }
2
@Override public boolean allowSource( ConnectionableCapability item, ConnectionFlavor flavor ) { if( item == this ){ return false; } return isComment( flavor ); }
1
private JButton getBtnClear() { if (btnClear == null) { btnClear = new JButton("Clear"); btnClear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { textAreaMain.setText(""); } }); btnClear.setBounds(10, 222, 89, 23); } return btnClear; }
1
public static void setPageSize(PrintService service, PrintRequestAttributeSet set, double[] size, LengthUnits units) { PageOrientation orientation = getPageOrientation(service, set); if (orientation == PageOrientation.LANDSCAPE || orientation == PageOrientation.REVERSE_LANDSCAPE) { size = new double[] { size[1], size[0] }; } setPaperSize(service, set, size, units); }
2
public String getCityCode() { return cityCode.get(); }
0
@Override public int compareTo(Object ob){ Event e = (Event) ob; if(this.time < e.getTime()){ return -1; } if(this.time > e.getTime()){ return 1; } return 0; }
2
public static String concatenateUsingStringBuffer(String[] stringArray, String delimiter) { if (delimiter == null || stringArray == null || stringArray.length == 0) { return null; } StringBuffer result = new StringBuffer().append(stringArray[0]); for (int i = 1; i < stringArray.length ;i++) { result.append(delimiter).append(stringArray[i]); } return result.toString(); }
4
public void test_convertText() { BaseDateTimeField field = new MockPreciseDurationDateTimeField(); assertEquals(0, field.convertText("0", null)); assertEquals(29, field.convertText("29", null)); try { field.convertText("2A", null); fail(); } catch (IllegalArgumentException ex) {} try { field.convertText(null, null); fail(); } catch (IllegalArgumentException ex) {} }
2
public void updateID() { if(ID == 0) { int x = 1; while(Item.validID(Integer.parseInt((itemTypeCombo.getSelectedIndex() + 1) + "" + x))) { x++; } IDText.setText((itemTypeCombo.getSelectedIndex() + 1) + "" + x); } }
2
public List<Aim> getDirections(Tile t1, Tile t2) { List<Aim> directions = new ArrayList<Aim>(); if (t1.getRow() < t2.getRow()) { if (t2.getRow() - t1.getRow() >= rows / 2) { directions.add(Aim.NORTH); } else { directions.add(Aim.SOUTH); } } else if (t1.getRow() > t2.getRow()) { if (t1.getRow() - t2.getRow() >= rows / 2) { directions.add(Aim.SOUTH); } else { directions.add(Aim.NORTH); } } if (t1.getCol() < t2.getCol()) { if (t2.getCol() - t1.getCol() >= cols / 2) { directions.add(Aim.WEST); } else { directions.add(Aim.EAST); } } else if (t1.getCol() > t2.getCol()) { if (t1.getCol() - t2.getCol() >= cols / 2) { directions.add(Aim.EAST); } else { directions.add(Aim.WEST); } } return directions; }
8
private static URI removeDotSegments(URI uri) { String path = uri.getPath(); if ((path == null) || (path.indexOf("/.") == -1)) { // No dot segments to remove return uri; } String[] inputSegments = path.split("/"); Stack<String> outputSegments = new Stack<String>(); for (int i = 0; i < inputSegments.length; i++) { if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) { // Do nothing } else if ("..".equals(inputSegments[i])) { if (!outputSegments.isEmpty()) { outputSegments.pop(); } } else { outputSegments.push(inputSegments[i]); } } StringBuilder outputBuffer = new StringBuilder(); for (String outputSegment : outputSegments) { outputBuffer.append('/').append(outputSegment); } try { return new URI(uri.getScheme(), uri.getAuthority(), outputBuffer.toString(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
9
protected void keyTyped(char par1, int par2) { this.serverName.textboxKeyTyped(par1, par2); this.serverAddress.textboxKeyTyped(par1, par2); if (par1 == 9) { if (this.serverName.getIsFocused()) { this.serverName.setFocused(false); this.serverAddress.setFocused(true); } else { this.serverName.setFocused(true); this.serverAddress.setFocused(false); } } if (par1 == 13) { this.actionPerformed((GuiButton)this.controlList.get(0)); } ((GuiButton)this.controlList.get(0)).enabled = this.serverAddress.getText().length() > 0 && this.serverAddress.getText().split(":").length > 0 && this.serverName.getText().length() > 0; if (((GuiButton)this.controlList.get(0)).enabled) { String var3 = this.serverAddress.getText().trim(); String[] var4 = var3.split(":"); if (var4.length > 2) { ((GuiButton)this.controlList.get(0)).enabled = false; } } }
7
private String indexToMsg(int i) { switch (i){ case 0: return "bid"; case 1: return "password"; case 2: return "name"; case 3: return "address"; case 4: return "phone"; case 5: return "email address"; case 6: return "sin or student #"; case 7: return "expiry date (yyyy/mm/dd)"; case 8: return "type"; } return ""; }
9
public int pop() { while (!isEmpty()) { temp.push(super.pop()); } int ret = temp.pop(); while (!temp.isEmpty()) { push(temp.pop()); } return ret; }
2
public AudioInfo(DataInputStream f) throws Exception { byte [] buffer; if (f.readInt() != 779248125) //['.', 'r', 'a', 0xfd] throw new InvalidSequenceException("AudioCodec info has wrong header"); version = f.readShort(); //word Version (3, 4 or 5) if (version < 3 || version > 5) throw new UnsupportedException("Wrong or unsupported version"); if (version == 3) { f.readShort(); // headerSize not including first 8 bytes buffer = new byte[10]; f.read(buffer); // byte[10] Unknown f.readInt(); // Data size tag = new RealTag(); buffer = new byte[f.read()]; f.read(buffer); tag.addTitle(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.addArtist(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.setCopyright(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.addComment(new String(buffer)); f.read(); // Unknown * buffer = new byte[f.read()]; f.read(buffer); if (!new String(buffer).equals("lpcJ")) throw new InvalidSequenceException("AudioInfo sequence corrupted"); } else { codecInfo = new CodecInfo(); f.readShort(); // Unused (always 0) buffer = new byte[4]; f.read(buffer); // byte[4] ra signature (".ra4" or ".ra5", depending on version) f.readInt(); // possible data size - 0x27 f.readShort(); // Version2 (always equal to version) f.readInt();// Header size - 16 codecInfo.setcodecFlavor(f.readShort()); codecInfo.setcodecFrameSize(f.readInt()); buffer = new byte[12]; f.read(buffer); //Unknow codecInfo.setsubpacketH(f.readShort()); codecInfo.setframeSize(f.readShort()); codecInfo.setsubpacketSize(f.readShort()); f.readShort(); // Unknown if (version == 5) { buffer = new byte[6]; f.read(buffer); //Unknow } codecInfo.setsampleRate(f.readShort()); f.readShort(); // Unknow codecInfo.setsampleSize(f.readShort()); codecInfo.setchannels(f.readShort()); if (version == 4) { buffer = new byte[f.read()]; f.read(buffer); //Interleaver ID string // always 4 bytes buffer = new byte[f.read()]; f.read(buffer); //FourCC string // always 4 bytes } else { f.readInt(); // Interleaver ID / maybe need convert value to string f.readInt(); // FourCC // FourCC is four character constant / maybe need convert value to string } buffer = new byte[3]; f.read(buffer); //Unknow if (version == 5) f.read(); //Unknow //TODO: Check exist of next block for version 4 if (version == 4) { tag = new RealTag(); buffer = new byte[f.read()]; f.read(buffer); tag.addTitle(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.addArtist(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.setCopyright(new String(buffer)); buffer = new byte[f.read()]; f.read(buffer); tag.addComment(new String(buffer)); } //TODO: Check exist of next inclusions (maybe only for 5 version) buffer = new byte[(int)f.readInt()]; f.read(buffer); codecInfo.setcodecExtraData(buffer); } }
9
public void contract(Edge edge) { if (Debug.ON) { System.out.println("Contracting "); System.out.println("Choosing Edge " + edge.tail.id + " -- " + edge.head.id); } // THE FOLLOWING CODES MUST BE CHANGED WHEN DEALING WITH DIRECTED GRAPH int group = -1; if (edge.tail.gid != -1) { group = edge.tail.gid; if (edge.head.gid != -1) mergeGroups(edge.tail.gid, edge.head.gid); else edge.head.gid = group; } else if (edge.head.gid != -1) { group = edge.head.gid; if (edge.tail.gid != -1) mergeGroups(edge.head.gid, edge.tail.gid); else edge.tail.gid = group; } else { group = gid; gid++; groups.put(group, new HashSet<Integer>()); edge.tail.gid = group; edge.head.gid = group; } if (groups.get(group).add(edge.tail.id) == true) nodesNum--; if (groups.get(group).add(edge.head.id) == true) nodesNum--; if (nodesNum < 0) nodesNum = 0; // contract edges from its tail's adjacency list contractEdge(edge.tail, group); // contract edges from its head's adjacency list contractEdge(edge.head, group); if (Debug.ON) { System.out.println("Edges " + edgesNum + " Groups " + groups.size() + " Nodes " + nodesNum); System.out.println(); } }
9
public void initPF() { int allowed_width = winwidth + crop_left + crop_right; int allowed_height = winheight + crop_top + crop_bottom; // these came from the canvas constructor viewnrtilesx=nrtilesx; viewnrtilesy=nrtilesy; if (prescale) { scaledtilex = allowed_width / nrtilesx; scaledtiley = allowed_height / nrtilesy; double aspectratio = (scaledtilex / (double)scaledtiley) / (tilex / (double)tiley); if (aspectratio < min_aspect) { // y is too large scaledtiley = (int)(scaledtilex / min_aspect); } else if (aspectratio > max_aspect) { // x is too large scaledtilex = (int)(max_aspect * scaledtiley); } width = scaledtilex*nrtilesx; height = scaledtiley*nrtilesy; } else { scaledtilex = tilex; scaledtiley = tiley; // XXX aspect ratio is not constrained yet in this case! width = winwidth; height = winheight; } x_scale_fac = width / (double)(tilex*nrtilesx); y_scale_fac = height / (double)(tiley*nrtilesy); min_scale_fac = Math.min( x_scale_fac, y_scale_fac ); initBGTiles(nrtilesx, nrtilesy, ""); // now, calculate the offsets. if (prescale) { int x_excess = width-winwidth; int y_excess = height-winheight; // balance is a number between -1 (shift left) and 1 (shift right) double xbalance=0,ybalance=0; if (crop_left+crop_right>0 && x_excess>0) xbalance = (crop_right-crop_left)/(crop_left+crop_right); if (crop_top+crop_bottom>0 && y_excess>0) ybalance = (crop_bottom-crop_top)/(crop_top+crop_bottom); canvas_xofs = (int)(-x_excess*(0.5 - 0.5*xbalance)); canvas_yofs = (int)(-y_excess*(0.5 - 0.5*ybalance)); } // else use default offsets of 0.0 }
8
public int func_27371_a(StatCrafting var1, StatCrafting var2) { int var3 = var1.func_25072_b(); int var4 = var2.func_25072_b(); StatBase var5 = null; StatBase var6 = null; if(this.slotStatsItemGUI.field_27271_e == 0) { var5 = StatList.objectBreakStats[var3]; var6 = StatList.objectBreakStats[var4]; } else if(this.slotStatsItemGUI.field_27271_e == 1) { var5 = StatList.objectCraftStats[var3]; var6 = StatList.objectCraftStats[var4]; } else if(this.slotStatsItemGUI.field_27271_e == 2) { var5 = StatList.objectUseStats[var3]; var6 = StatList.objectUseStats[var4]; } if(var5 != null || var6 != null) { if(var5 == null) { return 1; } if(var6 == null) { return -1; } int var7 = GuiStats.getStatsFileWriter(this.slotStatsItemGUI.field_27275_a).writeStat(var5); int var8 = GuiStats.getStatsFileWriter(this.slotStatsItemGUI.field_27275_a).writeStat(var6); if(var7 != var8) { return (var7 - var8) * this.slotStatsItemGUI.field_27270_f; } } return var3 - var4; }
8
protected HttpParams getParams() { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT); HttpConnectionParams.setSoTimeout(params, TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, BUFFER_SIZE); ConnManagerParams.setMaxTotalConnections(params, MAX_TOTAL_CONNECTIONS); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // fix contributed by Bjorn Roche XXX check if still needed params.setBooleanParameter("http.protocol.expect-continue", false); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute httpRoute) { if (env.isApiHost(httpRoute.getTargetHost())) { // there will be a lot of concurrent request to the API host return MAX_TOTAL_CONNECTIONS; } else { return ConnPerRouteBean.DEFAULT_MAX_CONNECTIONS_PER_ROUTE; } } }); // apply system proxy settings final String proxyHost = System.getProperty("http.proxyHost"); final String proxyPort = System.getProperty("http.proxyPort"); if (proxyHost != null) { int port = 80; try { port = Integer.parseInt(proxyPort); } catch (NumberFormatException ignored) { } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port)); } return params; }
3
static boolean fillEmptyCell (Cell[][] board) { boolean flag = false; for (int x = 0; x < 9; x++) { for (int y = 0; y < 9; y++) { if (board[x][y].getCellValue() == 0 && board[x][y].possibleValues.size() == 1) { board[x][y].setCellValue(board[x][y].possibleValues.get(0)); flag = true; } } } return flag; }
4
public final byte getBiomeID(){ if(currentChunk == null)return -1; return currentChunk.getBiomeID((int)getX(), (int)getZ()); }
1
@Override public void render() { Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); spriteBatch.setProjectionMatrix(camera.combined); if (!assetManagerController.update()) { }else { if (once) { once = false; } camera.update(); if (debugState) { box2DDebugRenderer.render(world, camera.combined); characterController.shapeRender(shapeRenderer); cameraController.shapeRender(); } SCORE = LevelController.getSCORE(); cameraController.cameraControl(); platformResolver.inputHandler(); worldController.render(); spriteBatch.begin(); levelController.render(spriteBatch); characterController.render(spriteBatch); enemyFactory.render(spriteBatch); for(Bullet bullet: bullets) { bullet.render(spriteBatch); } if (levelController.levelFinished()) { bitmapFont.setScale(4); bitmapFont.draw(spriteBatch,"YOU WIN, SCORE: " + SCORE, camera.position.x - (Gdx.graphics.getWidth() / 3), camera.position.y); }else{ bitmapFont.setScale(2); bitmapFont.draw(spriteBatch,"SCORE: " + SCORE,camera.position.x - (Gdx.graphics.getWidth() / 2), camera.position.y + (Gdx.graphics.getHeight() / 2) - 50); } spriteBatch.end(); } }
5
public JTextField getjTextFieldDateRapport() { return jTextFieldDateRapport; }
0
private void pickChecker(int player, int column) { if ((column < -1) || (column > NUM_POINTS)) { System.err.println("Error, out of range."); } else { // column -1 means the table! // So if a checker is transfered from the column -1, it is simply put in the game. if (column == BAR_LOC1 || column == BAR_LOC0) { if (on_bar[player] < 1) System.err.println("Error, no pieces on bar."); else on_bar[player]--; } else { int p_type = pType(player); if (((p_type) * board[column]) >= p_type) { board[column] -= p_type; } else { System.err.println("Error, no pieces at this location."); } } } }
6
public static void main(String[] args) { BigInteger bi = new BigInteger("2"); bi = bi.pow(1000); String s = bi.toString(); ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i = 0; i < s.length(); i++) { arr.add((int) (s.charAt(i) - '0')); } int res = 0; for(int i : arr) { res += i; } System.out.println(res); }
2
public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } }
9
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
5
public void update() { long time = System.currentTimeMillis(); float delta = time - lastupdate; lastupdate = time; if (position.getX() > GAME_WIDTH || position.getX() < 0 || position.getY() > GAME_HEIGHT || position.getY() < 0 || schritte >= projectileMaxDistace) { Server.projectiles.remove(this); } else { this.schritte += -xschritt * delta; float x = position.getX() - (projectileSpeed * delta) * xschritt; float y = x * m + b; position.setLocation(x, y); } }
5
private DataBase getDataBaseByKey(String key) throws DBUnavailabilityException { for (Pattern regexp : databases.keySet()) { Matcher matcher = regexp.matcher(key); if (matcher.find()) { return databases.get(regexp); } } throw new DBUnavailabilityException("database is unavailable"); }
2
public boolean disconnect(){ try { con.close(); } catch( SQLException e ){ if( debug ) System.out.println("Error in DataBaseConnection.disconnect(): "+e.getMessage()); return false; } return true; }
2
@Override public void downloadPlaylist(final String playlistUrl, final String destinationFolder, final Mp3Metadata metadata) { String playlistString = null; try { final long setId = getApi().resolve(playlistUrl); final HttpResponse setResponse = getApi().get(new Request(String.format(Constants.PLAYLIST_URL, setId, Constants.CLIENT_ID))); playlistString = EntityUtils.toString(setResponse.getEntity()); } catch (final Exception e) { e.printStackTrace(); } final JSONObject obj = new JSONObject(playlistString); final JSONArray array = obj.getJSONArray("tracks"); for (int i = 0; i < array.length(); i++) { final JSONObject obj2 = array.getJSONObject(i); downloadSong(obj2.getString("permalink_url"), destinationFolder, metadata); } }
2
@Override public void run() { synchronized (numberOfActiveProducersLock) { numberOfActiveProducers++; } Random rnd = new Random(); try { for (int i=1; i<=maxItemsToProduce; i++) { if (warehouse.isFull()) { break; //stop producing when warehouse is full } int producedItem = rnd.nextInt(100); System.out.println("producer['" + name + "'] >>> producing '" + producedItem + "' (producedCount: " + i + ")"); warehouse.addItem(producedItem); Thread.sleep(rnd.nextInt(50)); } } catch (InterruptedException ex) { System.out.println("Producer '" + name + "' process killed"); } synchronized (numberOfActiveProducersLock) { numberOfActiveProducers--; } }
3
public int getAttributeType(String name, String aname) { Object attribute[] = getAttribute(name, aname); if (attribute == null) { return ATTRIBUTE_UNDECLARED; } else { return ((Integer) attribute[0]).intValue(); } }
1
private void addToTextArea() { if (!(jTextField1.getText().equalsIgnoreCase("") || jTextField1.getText() == null)) { jTextArea1.append(jTextField1.getText() + "\n"); } control.sendMessage(jTextField1.getText()); jTextField1.setText(null); }
2
public void setGridSize(int rows, int columns, boolean preserveData) { if (rows > 0 && columns > 0) { Color[][] newGrid = new Color[rows][columns]; if (preserveData) { int rowMax = Math.min(rows,this.rows); int colMax = Math.min(columns,this.columns); for (int r = 0; r < rowMax; r++) for (int c = 0; c < colMax; c++) newGrid[r][c] = grid[r][c]; } grid = newGrid; this.rows = rows; this.columns = columns; forceRedraw(); } }
5
public void removeVertex(Vertex v) { vertices.delete(v); adjacencyList.removeVertex(v); }
0
private void maj_pos_robot(int x, int y, double teta) { //mm vers pixel -> *119/600 terrain.robot.X = x*119/600; terrain.robot.Y = y*119/600; terrain.robot.teta = teta; terrain.repaint(); }
0
public MainFrame(String username, String ip, int port) { super("Chat - " + username + " [" + ip + ":" + port + "]"); this.username = username; this.ip = ip; this.port = port; packetFactory = new PacketFactory(ip, port); doAesthetics(); setVisible(true); establishConnection(); initializeThread(); }
0
@Override public boolean equals(final Object obj) { if(!(obj instanceof Edge)) { return false; } final Edge o = (Edge) obj; return start == o.start && end == o.end && dot == o.dot && lhs.equals(o.lhs) && Arrays.equals(rhs, o.rhs) && children.equals(o.children); }
6
public IRegion getDamageRegion( ITypedRegion partition, DocumentEvent event, boolean documentPartitioningChanged) { if (!documentPartitioningChanged) { try { IRegion info = fDocument.getLineInformationOfOffset(event.getOffset()); int start = Math.max(partition.getOffset(), info.getOffset()); int end = event.getOffset() + (event.getText() == null ? event.getLength() : event.getText().length()); if (info.getOffset() <= end && end <= info.getOffset() + info.getLength()) { // optimize the case of the same line end = info.getOffset() + info.getLength(); } else end = endOfLineOf(end); end = Math.min( partition.getOffset() + partition.getLength(), end); return new Region(start, end - start); } catch (BadLocationException x) { } } return partition; }
5
@Override public boolean equals(Object aObject) { if (this == aObject) return true; if (aObject == null || getClass() != aObject.getClass()) return false; Vector4d vector4d = (Vector4d) aObject; if (Double.compare(vector4d.w, w) != 0) return false; if (Double.compare(vector4d.x, x) != 0) return false; if (Double.compare(vector4d.y, y) != 0) return false; if (Double.compare(vector4d.z, z) != 0) return false; return true; }
7
public List<User> getFollowers(String email) { Connection connection = null; List<User> followerList = new ArrayList<User>(); String query = null; PreparedStatement statement = null; try { connection = dataSource.getConnection(); query = "SELECT users.email, users.username FROM follows INNER JOIN users ON follows.follower = users.email WHERE follows.following = ?;"; statement = (PreparedStatement)connection.prepareStatement(query); statement.setString(1, email); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { User follower = new User(); follower.setEmail(resultSet.getString("email")); follower.setUsername(resultSet.getString("username")); followerList.add(follower); } } catch (SQLException sqle) { sqle.printStackTrace(); } finally { try { statement.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } return followerList; }
3
public void recieveCommand(Commands command) { if (command == null) { return; } switch (command.getType()) { case Commands.LOGIN: logon((LoginCommand)command); break; case Commands.LOGOUT: logout(); break; case Commands.WHISPER: whisper((WhisperCommand)command); break; case Commands.BROADCAST: broadcast((BroadcastCommand)command); break; case Commands.REGISTER: register((RegisterCommand)command); break; case Commands.CHECKUSERS: getUsers((CheckUsersCommand)command); break; } }
7
public int getInitialHeight() { return initialHeight; }
0
public void pressbutton() { Timetable_main_RWRAF.read(Homework_database_edit_1.getn()); int ID = (Timetable_main_RWRAF.getID()); String subject = (String)Subject.getSelectedItem(); String desc = DescField.getText(); String difficulty = (String)DiffField.getSelectedItem(); int time = Integer.parseInt((String)Timef1.getSelectedItem()); if(desc.length() < 501) { int delete = Timetable_main_RWRAF.checkDelete(); edit(ID, subject, desc, difficulty, time, delete); this.setVisible(false); } else { JOptionPane.showMessageDialog(null,"Your description is too big, please cut it to 500 words.", "Timetable Management Program", JOptionPane.INFORMATION_MESSAGE); } }
1
private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { int rounds, i, j; int cdata[] = (int[]) bf_crypt_ciphertext.clone(); int clen = cdata.length; byte ret[]; if (log_rounds < 4 || log_rounds > 31) throw new IllegalArgumentException("Bad number of rounds"); rounds = 1 << log_rounds; if (salt.length != BCRYPT_SALT_LEN) throw new IllegalArgumentException("Bad salt length"); init_key(); ekskey(salt, password); for (i = 0; i < rounds; i++) { key(password); key(salt); } for (i = 0; i < 64; i++) { for (j = 0; j < (clen >> 1); j++) encipher(cdata, j << 1); } ret = new byte[clen * 4]; for (i = 0, j = 0; i < clen; i++) { ret[j++] = (byte) ((cdata[i] >> 24) & 0xff); ret[j++] = (byte) ((cdata[i] >> 16) & 0xff); ret[j++] = (byte) ((cdata[i] >> 8) & 0xff); ret[j++] = (byte) (cdata[i] & 0xff); } return ret; }
7
public static boolean findPath(int[][] maze, int x, int y, int targetx, int targety) { // base case or exit condition : reached the target if(x == targetx && y == targety) { return true; } else { // check if x and y are in the limits && x,y does not hit a wall if((x >=0 && x < maze[0].length && y >=0 && y < maze.length) && maze[x][y] != 0) { System.out.println("x :" +x+ " y: "+ y ); //recurse on left and right and return result of both by logical OR return findPath(maze, x+1,y, targetx, targety) || findPath(maze, x, y + 1, targetx, targety); } } return false; }
8
private void quicksort(Integer menor, Integer maior) throws NaoOrdenavel { Integer i = menor, j = maior; Elemento pivo = elementos[menor + (maior - menor) / 2]; try { while (i <= j) { while (pivo.compareTo(elementos[i]) > 0) { i++; } while (pivo.compareTo(elementos[j]) < 0) { j--; } if (i <= j) { trocar(i, j); i++; j--; } } } catch (Exception e) { throw new NaoOrdenavel("Conjunto não ordenável!"); } if (menor < j) { quicksort(menor, j); } if (i < maior) { quicksort(i, maior); } }
7
protected static boolean checkResource(Resource resource) { boolean isValid; if (isValid = resource != null) { isValid = TYPES.contains(resource.getType()); isValid = isValid && resource.getProperty(HOST_PROPERTY) != null; isValid = isValid && resource.getProperty(USERNAME_PROPERTY) != null; isValid = isValid && resource.getProperty(PASSWORD_PROPERTY) != null; } return isValid; }
4
@Override public Path compute(TSPInstance tsp, Path beginPath, ComputationCallback callback) { final int count = tsp.count(); if (count <= paramP) { throw new IllegalArgumentException( "Impossible to solve the tsp: tsp.count <= paramP! tsp.count = " + count + ", paramP = " + paramP); } Path path = beginPath; // calculate path's cost double cost = path.cost(tsp); boolean pathChanged = true; // margins of area around vertex to look for swap int deltaLeft, deltaRight; // looking for path improvements while possible while (pathChanged) { pathChanged = false; // going through all the points in path for (int i = 0; i < Math.max(count - paramP, 1) && !pathChanged; i++) { // and trying to swap with points that are no further than // paramP from current deltaLeft = i + 1;// optimized from Math.max(i - paramP, 0); deltaRight = Math.min(i + paramP, count - 1); for (int j = deltaLeft; j <= deltaRight && !pathChanged; j++) { if (i != j) { // create a copy of path final Path copy = path.clone(); // swap two points in path and measure cost copy.swap(i, j); final double copyCost = copy.cost(tsp); if (copyCost < cost) { // update cost if found better cost = copyCost; // also change the path itself to operate with // updated one on next step path = copy; pathChanged = true; callback.onComputation(tsp, path); } } } } } return path; }
8
public static void loadImage(String url, String galleryName) { try { String src = prefixSrc; src += galleryName; src += "\\"; String imgName = getFileName(url); src += getFileName(url); addImgToXmlData(imgName, galleryName); BufferedImage img = ImageIO.read(new URL(url)); File file = new File(src); if (!file.exists()) { file.createNewFile(); } ImageIO.write(img, "jpg", file); } catch (Exception e) { e.printStackTrace(); } }
2
public InputStream stream(String url) throws IOException { int redirects = 0; URLConnection conn; do { conn = LLHttpClient.connect(proxy(), "GET", url, connectTimeOut, readTimeOut, headers()); url = check(cookies(conn)); redirects++; } while (follow && url != null && redirects < 5); if (follow && redirects >= 5 && conn != null && conn instanceof HttpURLConnection) { if (((HttpURLConnection) conn).getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException( "Detected recursive redirecting: " + url); } } return LLHttpClient.getInputStream(conn); }
8
public List getAxiom() { return axiom; }
0
public static boolean initNetworkType(int networkType) { boolean result = true; switch(networkType) { case GridSimTags.NET_PACKET_LEVEL: GridSimCore.NETWORK_TYPE = GridSimTags.NET_PACKET_LEVEL; break; case GridSimTags.NET_FLOW_LEVEL: GridSimCore.NETWORK_TYPE = GridSimTags.NET_FLOW_LEVEL; break; case GridSimTags.NET_BUFFER_PACKET_LEVEL: GridSimCore.NETWORK_TYPE = GridSimTags.NET_BUFFER_PACKET_LEVEL; break; default: result = false; break; } return result; }
3
private void cmd_take(final String arg, final Client client) { final Player player = getPlayer(client); final Room room = getRoom( player.getLocation() ); final String[] args = arg.split(" "); debug("" + args.length); // if there is no argument, report command syntax if (arg.equals("")) { send("Syntax: take <item>", client); } // if there are three arguments, implying the following syntax: // TAKE <thing> FROM <container> else if ( arg.matches("(take)(\\s+)((?:[a-z][a-z]+))(\\s+)(from)(\\s+)((?:[a-z][a-z]+))") ) { debug("take from"); String itemName = args[1]; String container = args[3]; final Item item = MudUtils.findItem(itemName, room.getItems()); // this probably won't work... } else if (arg.equalsIgnoreCase("all")) { // TODO problem if getItems() returns an unmodifiable list? // all implies stuff on the ground. since all the stuff on the ground is in the room, // we should evaluate the room to get it's stuff // basically we want to evaluate all the items, then take the one with the largest value, // one at a time. the evaluation scheme needs to take what's usable and what's not // as well monetary value into account // if we have room for everything, then just take it all // - an item is usable if, given restrictions, you meet all // the requirements (class, race, level, skill) final List<Item> items = new ArrayList<Item>( room.getItems() ); for (final Item item : items) { take(player, room, item); } } else { // assuming one argument Item item = null; // get the integer value, if there is one, as the argument final int dbref = Utils.toInt(arg, -1); // look for specified item in the player's current room if (dbref != -1) item = MudUtils.findItem(dbref, room.getItems()); if (item == null) item = MudUtils.findItem(arg, room.getItems()); if (item != null) { take(player, room, item); } else { Thing thing = getThing(arg, room); if (thing != null) { final String msg = thing.getProperty("_game/msgs/take-fail"); if ( msg != null ) { send(msg, client); } send("You can't pick that up.", client); } else { send("You can't find that.", client); } } } }
9
public Obstacle(String key, int x, int y) { genObstacle tmp; try { tmp = (genObstacle) genObstacle.obsMapping.get(key); } catch (IllegalArgumentException e) { tmp = new genObstacle(-1,false,false,0); // ID = 0 collision, visible, hurting } if (tmp != null) { super.n = tmp.getID(); super.collisionTop = tmp.CollisionTop(); super.collisionBot = tmp.CollisionBot(); super.collisionSide = tmp.CollisionSide(); super.visible = tmp.visible(); super.hurting = tmp.getDmg(); } this.x = x; this.y = y; }
2
@Override public void restoreTemporaryToDefault() {tmp = def;}
0
@Override public void spring(MOB target) { if(target.location()!=null) { if((!invoker().mayIFight(target)) ||(isLocalExempt(target)) ||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target)) ||(target==invoker()) ||(doesSaveVsTraps(target))) target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) the explosive!")); else if(target.location().show(invoker(),target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,(affected.name()+" explodes all over <T-NAME>!")+CMLib.protocol().msp("explode.wav",30))) { super.spring(target); CMLib.combat().postDamage(invoker(),target,null,CMLib.dice().roll(trapLevel()+abilityCode(),10,1),CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,L("The blast <DAMAGE> <T-NAME>!")); } } }
7
@Override public void mouseReleased(MouseEvent arg0) { this.drag = false; if(curTool == 3) { hp.apply(); } hp.setDrag(null); view.updateHeightmap(hp.getTexture()); }
1
public void setAccessToken(String accessToken) { this.accessToken = accessToken; }
0
public static void build() { Plugin larvikGaming = Bukkit.getServer().getPluginManager().getPlugin("LarvikGaming"); list.plugin = Bukkit.getServer().getPluginManager().getPlugins(); list.pos = Bukkit.getServer().getPluginManager().getPlugins().length; String fileDest = larvikGaming.getConfig().getString("FileDir", "plugins/dynmap/web/admin") + "/"; boolean exception = false; if (!larvikGaming.getConfig().getBoolean("PluginsList", true)) { return; } Line[] lines = new Line[list.pos]; for (int i = 0; i < lines.length; i++) { lines[i] = new Line(list.plugin[i].getDescription().getName(), list.plugin[i].getDescription().getVersion()); } Arrays.sort(lines); FileOutputStream plugins = null; try { plugins = new FileOutputStream(fileDest + "misc/plugins.html"); } catch (FileNotFoundException e) { exception = true; } if (exception) { log.warning(LarvikGaming.name + "FileDir: " + fileDest + "misc/" + " do not excist!"); log.warning(LarvikGaming.name + "Plugins.html will not be created!"); return; } PrintStream build = new PrintStream(plugins); build.println("<html>"); build.println("<body bgcolor='#cccccc'>"); for (Line line : lines) { build.println(""); build.println("<font size='3' color='#0BA613' face='verdana'>"); build.println("<br /><b>" + line.name + "</b></font>"); build.println("<font size='2' color='#0BA613' face='verdana'>"); build.println("<br />Version: " + line.version + "</font>"); build.println("<br />"); } build.println(""); build.println("<br />"); build.println("<br />"); build.println("<font size='3' color='#0BA613' face='verdana'>"); build.println("Number of Plugins: "); build.println("<b>" + list.pos + "</b></font>"); build.println(""); build.println("<br />"); build.println("<br />"); build.println("<font size='1' color='#0BA613' face='verdana'>"); build.println("Created by Kiwz</font>"); build.println(""); build.println("</body>"); build.println("</html>"); build.close(); }
5
public void send() { String msg = msg_box.getText(); if (msg == null || msg.equals("") || msg.equals("\n")){ msg_box.setText(""); return; } if(enterIsSend){ msg = msg.substring(0, msg.length()-1); } if (msg.startsWith("@")) { String to = msg.split(" ")[0].substring(1); msg = msg.substring(to.length()+2); update("["+name+"] > ["+to+"] "+msg); chatClient.sendWhisper(to, msg); } else { chatClient.sendBroadcast(msg); } msg_box.setText(""); msg_box.grabFocus(); }
5
public String getGestureName() { return gestureName; }
0
@SuppressWarnings("resource") static Fraction[][] getMatrix ( String filename ){ int rowBuffer = 30; int columnBuffer = 30; Fraction[][] matrixBuffer = new Fraction[rowBuffer][columnBuffer]; int rowCt = 0; int columnCt = 0; try { Scanner sc = new Scanner( new File( filename )); sc.useDelimiter( System.getProperty( "line.separator" ) ); while ( sc.hasNext() ) { Scanner lineScanner = new Scanner( sc.next() ); columnCt = 0; while ( lineScanner.hasNextInt() ){ Fraction input = new Fraction( lineScanner.nextInt(), 1 ); matrixBuffer[rowCt][columnCt] = input; columnCt++; // Transfer into bigger array if necessary. // **THIS HASN'T BEEN TESTED** if ( columnBuffer-2==columnCt ){ rowBuffer *= 2; columnBuffer *= 2; Fraction[][] bigger = new Fraction[rowBuffer][columnBuffer]; for ( int i = 0; i < rowBuffer/2; i++ ){ for ( int j = 0; j < columnBuffer/2; j++ ){ bigger[i][j] = matrixBuffer[i][j]; } } matrixBuffer = bigger; } } rowCt++; } } catch ( FileNotFoundException e ) { System.err.println( e.getMessage() ); Usage(); } // I won't use the 0 positions in the array for easier coordinates. // For example, the first position on the top left is (1,1) not (0,0) // Remember a matrix is (row, column). For reference, generally "i"'s // correspond to the row, and "j"'s to columns, throughout this program. // For example matrix[i][j] is the same as (i,j) or row i, column j. Fraction[][] matrix = new Fraction[rowCt+1][columnCt+1]; // Put matrixBuffer contents into newer, better fitting matrix. for ( int i = 0; i < rowCt; i++ ){ for ( int j = 0; j < columnCt; j++ ){ matrix[i+1][j+1] = matrixBuffer[i][j]; } } rows = rowCt; columns = columnCt; return matrix; }
8
public Double[] getYVal() { return yVal; }
0
List<byte[]> getPasswordBytes(boolean unicodeConversion) { // TODO - handle unicodeConversion when we support version 5 if (this.passwordBytes != null || this.passwordString == null) { return Collections.singletonList(this.passwordBytes); } else { if (isAlphaNum7BitString(this.passwordString)) { // there's no reasonthat this string would get encoded // in any other way return Collections.singletonList( PDFStringUtil.asBytes(passwordString)); } else { return generatePossiblePasswordBytes(passwordString); } } }
3
public void setBLXElement(BLXElement blxElement) { super.setBLXElement(blxElement); Element _myElement = blxElement.getDataElement(); //MasterTile Element not found set Defaults if(_myElement == null) { setGridLocation(TOP_LEFT); setClosed(false); setIsDirty(true); return; } //Embedded Components //Only a TileSet and a Launch Panel can be embedded into the Master Tile //All other BLX Components will be ignored. boolean successful = true; int count = 0; NodeList _nodes = _myElement.getChildNodes(); for(int i=0;i<_nodes.getLength();i++) { //Only process Elements if(_nodes.item(i).getNodeType()!=Node.ELEMENT_NODE) continue; Element _element = (Element)_nodes.item(i); //BLX Components try { Component _comp = componentFactory.getComponent(new BLXElement(_element, blxElement.getContextURL()), null); //Master TileSet if(_comp instanceof TileSet) { masterTileSet = (TileSet)_comp; count++; } //Launch Panel if(_comp instanceof LaunchPanel) { //Remove current LaunchPanel launchPanel.removeComponentListener(this); remove(launchPanel); _comp.setLocation(launchPanel.getLocation()); launchPanel = (LaunchPanel)_comp; launchPanel.addComponentListener(this); launchPanel.addLaunchListener(this); add(launchPanel); count++; } //If we loaded both the Launch panel and the TitleSet then we can Break. if(count == 2) break; } catch(Exception _exp) { //Could be ClassNotFound or InstantiationException //Ignore error the Component will just be skipped. successful = false; _exp.printStackTrace(); } }//End For Loop //Setup MasterTile Specific Stuff //Location Attribute setGridLocation(convertGridLocFromString(_myElement.getAttribute(LOCATION_ATTR))); //Closed Attribute if(_myElement.getAttribute(CLOSED_ATTR).equals("true")) setClosed(true); else setClosed(false); if(successful) setIsDirty(false); }
9
private Method_GetDebugInfo(VirtualMachineImpl vm, PacketStream ps) { maxIndex = ps.readInt(); final SourceFile[] sourceFiles; if(vm.isAtLeastVersion(2, 13)) { int count = ps.readId(); sourceFiles = new SourceFile[count]; for(int i = 0; i < count; i++) { sourceFiles[i] = new SourceFile(); sourceFiles[i].name = ps.readString(); if(vm.isAtLeastVersion(2, 14)) { for(int j = 0; j < sourceFiles[i].hash.length; j++) { sourceFiles[i].hash[j] = ps.readByte(); } } } } else { sourceFiles = new SourceFile[] {new SourceFile()}; sourceFiles[0].name = ps.readString(); } int count = ps.readInt(); entries = new Entry[count]; for(int i = 0; i < count; i++) { entries[i] = new Entry(); entries[i].offset = ps.readInt(); entries[i].line = ps.readInt(); if(vm.isAtLeastVersion(2, 13)) { int idx = ps.readInt(); entries[i].sourceFile = idx >= 0 ? sourceFiles[idx] : null; } else { entries[i].sourceFile = sourceFiles[0]; } if(vm.isAtLeastVersion(2, 19)) { entries[i].column = ps.readInt(); } } }
8
private void PageRedirect(String itemID, String itemType, String query, boolean DisplayGO, boolean organismdependentquery) { if (applet == null || configuration == null) return; String wholeredirectionString = getRedirectionString(itemID, itemType, query, DisplayGO, organismdependentquery); Boolean rightClickQueryingEnabled = (Boolean) configuration.get("rightClickQueryingEnabled"); try { final URL redirectURL = new URL(wholeredirectionString); // if (checkAppletContext()) { if (rightClickQueryingEnabled) { pool.submit(new Thread() { public void run() { while (true) { System.out.println("Trying to redirect to: " + redirectURL); if (applet != null && applet.getAppletContext() != null) { applet.getAppletContext().showDocument(redirectURL); System.out.println("Redirection is done"); break; } try { Thread.sleep(2000); } catch (InterruptedException e) { //e.printStackTrace(); } } } }); } else { applet.getAppletContext().showDocument(redirectURL, "_blank"); } //} } catch (MalformedURLException murle) { System.out.println("Could not recognise redirect URL"); } }
8
private void getParameters(Keyword method, String[] argument) throws Exception { parameters.put(Keyword.METHOD, method.toString().toLowerCase()); startType = TimeType.NONE; endType = TimeType.NONE; String key, value; Keyword argType; for (int i = 0; i < argument.length; ++i) { if (i == 0) { key = "content"; value = argument[0].trim(); if (value.length() > 29) { throw new Exception(EXCEEDED_CHAR_LIMIT); } } else { argument[i] = argument[i].trim() + " "; String[] tmp = argument[i].split(" ", 2); key = tmp[0].trim(); value = tmp[1].trim(); } argType = Keyword.getMeaning(key); if (!Keyword.isProperArgument(method, argType)) { throw new Exception(IMPROPER_ARGUMENT); } if (argType.equals(Keyword.START) || argType.equals(Keyword.END)) { value = parseTimeArg(argType, value); } parameters.put(argType, value); } if (method.equals(Keyword.CREATE)) { configCreate(); } if (method.equals(Keyword.EMPTYSLOT)) { configEmptySlot(); } }
8
public ClientOutputThread(Socket socket) { this.socket = socket; }
0
@Override public String getHouseNumber() { return super.getHouseNumber(); }
0
private void JoinTuples (Tuple tuple1 ,Tuple tuple2) { //increase count outcome tuples because this join produces a tuple this.countOutcomeTuples++ ; //Constructing a new bitmap for new integrated tuple //==========================NEW READY BITS======================================= int newReadyBits ; int xorT1T2ReadyBits = tuple1.getReadyBits() ^ tuple2.getReadyBits() ; int andT1T2ReadyBits =tuple1.getReadyBits() & tuple2.getReadyBits() ; //Integration of 2 tuple ready bits newReadyBits =xorT1T2ReadyBits | andT1T2ReadyBits; //This tuple maybe ready for new operators int newAvailableReadyBits =0 ; ArrayList<Byte> joinsOnSameVar = Eddy.getInstance().getJoinVarTojoinMapper().get(this.joinVariable) ; int joinReadyBitSetter = 0; for (Byte joinId: joinsOnSameVar) { joinReadyBitSetter = (1 << joinId) ; newAvailableReadyBits = newAvailableReadyBits | joinReadyBitSetter ; } int xorAvailableAndIntegration = newReadyBits ^ newAvailableReadyBits ; int andAvailableAndIntegration = newReadyBits & newAvailableReadyBits ; newReadyBits = xorAvailableAndIntegration | andAvailableAndIntegration ; //Don't Forget this again //Set ready bit for the current join to 0 //newBitMap.put(this.joinId, JoinStatus.Done); int readyBitMasker = 1 << this.joinId ; readyBitMasker = ~readyBitMasker; //Final Operation for Ready Bits newReadyBits = newReadyBits & readyBitMasker; //====================================END NEW READY BITS========================================= //====================================NEW DONE BITS============================================ int newDoneBits ; int xorT1T2DoneBits = tuple1.getDoneBits() ^ tuple2.getDoneBits() ; int andT1T2DoneBits =tuple1.getDoneBits() & tuple2.getDoneBits() ; //Integration of 2 tuple Done bits newDoneBits =xorT1T2DoneBits | andT1T2DoneBits; //Setting done bit 1 for this join id int doneBitSetter = 0 ; doneBitSetter = 1<< this.joinId ; //Final operation for done bits newDoneBits =newDoneBits | doneBitSetter ; //==================================END NEW DONE BITS========================================= // for (Byte joinId:tuple1.getBitMap().keySet()) // { // JoinStatus newBitMapStatus =newBitMap.get(joinId) ; // if (newBitMapStatus==null) // newBitMapStatus=JoinStatus.NotReady ; // JoinStatus MaximumStatus =Maximum (tuple1.getBitMap().get(joinId),tuple2.getBitMap().get(joinId),newBitMapStatus) ; // newBitMap.put(joinId, MaximumStatus); // } //Constructing a new subquerynamelist for new integrated tuple //badan check kon ke duplicate insert nashe dar subquery list yek tuple . ArrayList<String> newSubQueryNameList =new ArrayList<String>(); for (String subQueryNameItem :tuple1.getSubQueryList()) { newSubQueryNameList.add(subQueryNameItem); } for (String subQueryNameItem :tuple2.getSubQueryList()) { newSubQueryNameList.add(subQueryNameItem); } //Constructing a new binding set for new integrated tuple QueryBindingSet newqbSet =new QueryBindingSet(); newqbSet.addAll(tuple1.getBindingSet()) ; newqbSet.addAll(tuple2.getBindingSet()) ; //new tuple priority= randomCeiling+1 or +2,+3,.... int newPriority =1 ; if (tuple1.getPriority()>=tuple2.getPriority()) newPriority=tuple1.getPriority() ; else newPriority=tuple2.getPriority() ; if (newPriority>this.randomCeiling) newPriority++ ; else newPriority=this.randomCeiling+1; //and finaly create a new tuple from tuple1 , tuple2 Tuple finalNewTuple =new Tuple(newqbSet,newReadyBits,newDoneBits,newSubQueryNameList,newPriority); //DEBUG //putTupleToFile2(finalNewTuple) ; //=====================HoooraY one Result Tuple ==========================// if (finalNewTuple.getDoneBits() == (Math.pow(2, numberOfJoinOperators)-1)) { try { this.resultTuples.put(finalNewTuple); } catch (InterruptedException e) { e.printStackTrace(); } this.coutResultTuples++ ; // System.out.println("Join "+joinId+" Count Results Tuples= "+coutResultTuples); //System.out.println(finalNewTuple.getBindingSet().toString()); //System.out.println("There is "+workQueue.size()+" tuples in working quee of join "+joinId); //DEBUG //putTupleToFile(finalNewTuple) ; } else { try { tupleHeap.put(finalNewTuple) ; //Because this is not a final tuple this.countIntermeidateTuplesGenerated++ ; } catch (InterruptedException e) { throw new OptimizerException(e) ; } } }
8
@Override public boolean matches(Object argument) { if (argument instanceof PropertyChangeEvent) { PropertyChangeEvent event = (PropertyChangeEvent) argument; return propertyName.equals(event.getPropertyName()) && ((oldValue == null && event.getOldValue() == null) || (oldValue.equals(event.getOldValue()))) && ((newValue == null && event.getNewValue() == null) || (newValue.equals(event.getNewValue()))); } return false; }
7
public void go() { int index = 0; try { while(index < 1330) { new Thread(new Crawler(index)).start(); index++; } } catch(Exception ex) {} }
2
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IDs)) return false; IDs iDs = (IDs) o; if (!Arrays.equals(ids, iDs.ids)) return false; return true; }
3
public static void printLCS(int[][] c, int[] x, int i, int j) { if(i == 0 || j == 0){ return; } if(c[i][j] != c[i - 1][j] && c[i][j] != c[i][j - 1]){ printLCS(c, x, i - 1, j - 1); System.out.print(x[i - 1] +","); }else if(c[i][j] == c[i - 1][j]){ printLCS(c, x, i - 1, j); }else{ printLCS(c, x,i, j - 1); } }
5