text
stringlengths
14
410k
label
int32
0
9
public boolean equals( Object other ) { if ( ! ( other instanceof TObjectCharMap ) ) { return false; } TObjectCharMap that = ( TObjectCharMap ) other; if ( that.size() != this.size() ) { return false; } try { TObjectCharIterator iter = this.iterator(); while ( iter.hasNext() ) { iter.advance(); Object key = iter.key(); char value = iter.value(); if ( value == no_entry_value ) { if ( !( that.get( key ) == that.getNoEntryValue() && that.containsKey( key ) ) ) { return false; } } else { if ( value != that.get( key ) ) { return false; } } } } catch ( ClassCastException ex ) { // unused. } return true; }
8
public void saveAll() { FileConfiguration f = getPlayerF(); String path = "players."; for (UUID uuid : balance.keySet()) { f.set(path + uuid.toString() + ".coins", balance.get(uuid)); } for (UUID uuid : currentKit.keySet()) { f.set(path + uuid.toString() + ".selected", currentKit.get(uuid).getName()); } for (UUID uuid : allKit.keySet()) { List<String> owned = new ArrayList<String>(); for (Kit kit : allKit.get(uuid)) { owned.add(kit.getName()); } f.set(path + uuid.toString() + ".owned", owned); } // COOLDOWNS CooldownManager cm = new CooldownManager(Main.getMain()); for (UUID uuid : cooldowns.keySet()) { List<String> newlist = new ArrayList<String>(cooldowns.get(uuid)); List<String> tosave = new ArrayList<String>(); for (String cdname : newlist) { if (cm.isInCooldown(uuid, cdname)) { tosave.add(cm.getTimeLeft(uuid, cdname) + "@" + cdname); } } f.set(path + uuid.toString() + ".cooldowns", tosave); } savePlayerF(); }
7
* @see LocalExpr * @see StoreExpr */ public void visit_astore(final Instruction inst) { final LocalVariable operand = (LocalVariable) inst.operand(); Expr expr = stack.peek(); if (expr.type().isAddress()) { Assert.isTrue(sub != null); Assert.isTrue(!saveValue); expr = stack.pop(Type.ADDRESS); sub.setReturnAddress(operand); addStmt(new AddressStoreStmt(sub)); } else { expr = stack.pop(Type.OBJECT); final LocalExpr target = new LocalExpr(operand.index(), expr.type()); addStore(target, expr); } }
1
public void closeConnection() { try { if (con != null) { con.close(); } con = null; } catch (Exception e) { System.out.println(e.getMessage()); } }
2
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (internalID == null) { if (other.internalID != null) return false; } else if (!internalID.equals(other.internalID)) return false; return true; }
6
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((diagnosisComment == null) ? 0 : diagnosisComment.hashCode()); result = prime * result + ((diagnosisDate == null) ? 0 : diagnosisDate.hashCode()); result = prime * result + ((diagnosisName == null) ? 0 : diagnosisName.hashCode()); result = prime * result + ((doctor == null) ? 0 : doctor.hashCode()); result = prime * result + ((patientCard == null) ? 0 : patientCard.hashCode()); result = prime * result + ((patientHistoryId == null) ? 0 : patientHistoryId.hashCode()); return result; }
6
@Override public void handleLeftClick(double x, double y, SUIComponent concerned){ if(concerned == null) return; if(play.equals(concerned)){ frame.goTo(new PlayConfigPanel(frame)); } else if(skin_editor.equals(concerned)){ frame.goTo(new SkinEditorPanel(frame)); } else if(map_editor.equals(concerned)){ frame.goTo(new MapEditorPanel(frame)); } else if(settings.equals(concerned)){ frame.goTo(new SettingsPanel(frame)); } }
5
public void setDirection(int direction){ if(direction >= 360){ direction = direction % 360; } if(direction < 0){ while(direction < 0){ direction+=360; } } this._direction = direction; }
3
public void changePlayerDirection(int d) { setDirection(d); switch (d) { case 1:// down playerR.setRegion(0, 0 + (currentStep * 42), 37, 42); currentDirection = Direction.DOWN; break; case 2:// up playerR.setRegion(37, 0 + (currentStep * 42), 37, 42); currentDirection = Direction.UP; break; case 3:// right playerR.setRegion(74, 0 + (currentStep * 42), 37, 42); currentDirection = Direction.RIGHT; break; case 4:// left playerR.setRegion(111, 0 + (currentStep * 42), 37, 42); currentDirection = Direction.LEFT; break; } this.setRegion(playerR); }
4
@Override public int attack(double agility, double luck) { if(random.nextInt(100) < luck) { System.out.println("I set the monster on fire!"); return random.nextInt((int) agility) * 4; } return 0; }
1
public static void main(String[] args) { int option; double distance, speed, time; Scanner keyboard = new Scanner(System.in); DecimalFormat formatter = new DecimalFormat("#0.0000"); System.out.println(); System.out.println("Choose a medium through which a sound wave will travel"); System.out.print("(1 = air, 2 = water, 3 = steel): "); option = keyboard.nextInt(); if(option < 1 || option > 3){ System.out.println(); System.out.println("You have to enter either a 1, 2, or 3. Try again."); // This if statement just makes user enter correct value System.exit(0); } System.out.print("How far will the sound wave travel, in feet: "); distance = keyboard.nextFloat(); System.out.println(); if(option == 1){ // could have also used a switch statement...but I prefer this. time = distance/1100; // The if statements are same structure, they make one calculation then output System.out.println("The time it will take for the wave to travel " + formatter.format(distance)); // DecimalFormat not needed, and can lower accuracy, but 4 digits is plenty for this problem System.out.println("feet in air is about " + formatter.format(time) + " seconds."); } else if(option == 2){ // else if not necesary, if would work too, I just prefer else if time = distance/4900; System.out.println("The time it will take for the wave to travel " + formatter.format(distance)); System.out.println("feet in water is about " + formatter.format(time) + " seconds."); } else if(option == 3){ time = distance/16400; System.out.println("The time it will take for the wave to travel " + formatter.format(distance)); System.out.println("feet in steel is about " + formatter.format(time) + " seconds."); } }
5
@Override public boolean isFull() { for (int i = 0; i < chairs.length; ++i) { if (chairs[i] == null) { return false; } } return true; }
2
private void addOccupant(T occupant) { Class cl = occupant.getClass(); do { if ((cl.getModifiers() & Modifier.ABSTRACT) == 0) occupantClasses.add(cl); cl = cl.getSuperclass(); } while (cl != Object.class); }
2
public boolean equals(Object other) { if (other instanceof Type) { Type type2 = (Type) other; return typeSig.equals(type2.typeSig) && instr == type2.instr; } return false; }
2
@Override public void debuterTransaction() throws SQLException { getConnexion().setAutoCommit(false); }
0
private SelectableCapability getSelectable( int x, int y ) { float best = 0.f; SelectableCapability result = null; for( SelectableCapability selectable : site.getCapabilities() ) { float contains = selectable.contains( x, y ); if( contains >= best && contains > 0 ) { best = contains; result = selectable; } } return result; }
3
@Override public boolean decrementLives() { if (lives > 0) { lives--; return true; } return false; }
1
public HexLocation getNeighborLoc(EdgeDirection dir) { switch (dir) { case NorthWest: return new HexLocation(x - 1, y); case North: return new HexLocation(x, y - 1); case NorthEast: return new HexLocation(x + 1, y - 1); case SouthWest: return new HexLocation(x - 1, y + 1); case South: return new HexLocation(x, y + 1); case SouthEast: return new HexLocation(x + 1, y); default: assert false; return null; } }
6
@Override public int hashCode() { int hash = 5; hash = 37 * hash + (this.normalTextFont != null ? this.normalTextFont.hashCode() : 0); hash = 37 * hash + (this.boldTextFont != null ? this.boldTextFont.hashCode() : 0); hash = 37 * hash + (this.colorPalette != null ? this.colorPalette.hashCode() : 0); hash = 37 * hash + (this.useBrightColorsOnBold ? 1 : 0); return hash; }
4
public String diff() throws IOException { String answer = ""; answer += " Difference between the current Project-Directory and the latest version (ID: " + HEAD.ID +") \n \n"; File directory = new File(ProjectDirectory); File[] fileList = directory.listFiles(); if (fileList.length-index.size() != 2) { for (File projectfile : fileList) { String projectfileName = projectfile.getName(); String extension = projectfileName.substring(projectfileName.lastIndexOf(".") + 1, projectfileName.length()); if (projectfile.isFile() && (!projectfileName.equals(".DS_Store")) && (!extension.equals("key"))) { answer += "\t" + projectfile.getName() + ": \n"; File versionfile = new File(HeadFilesDirectory + File.separator + projectfile.getName()); if (versionfile.isFile()) { SHA1 projectfileHash = new SHA1(Utilities.FileToByteArray(projectfile)); SHA1 versionfileHash = new SHA1(Utilities.FileToByteArray(versionfile)); if (!versionfileHash.getSHA1().equals(projectfileHash.getSHA1())) { //if a file in the project directory was already in the latest version: show the difference List<String> original = Utilities.fileToLines(versionfile.getAbsolutePath()); List<String> revised = Utilities.fileToLines(projectfile.getAbsolutePath()); DiffRowGenerator.Builder builder = new DiffRowGenerator.Builder(); boolean sideBySide = true; //default -> inline builder.showInlineDiffs(!sideBySide); builder.columnWidth(120); DiffRowGenerator dfg = builder.build(); List<DiffRow> rows = dfg.generateDiffRows(original, revised); int rowNumber = 0; for (DiffRow row: rows) { rowNumber++; if (!row.toString().equals("")) { answer += "\t Line " + rowNumber +": " + row + "\n"; } } answer += "\n"; } else { answer += "\t #There are no changes in this file \n \n"; } } else { //if a file in the project directory was not in the latest version: file is recently added answer += "\t #This file is recently added to the project \n \n"; } } } } else { answer += "\t there are no files in the repository to diff with the latest version \n"; } return answer; }
9
public static ArrayList<Post> getPage(int page) throws SQLException, NamingException { Connection conn = null; Statement stmt = null; ResultSet rs = null; ArrayList<Comment> comment = new ArrayList<Comment>(); ArrayList<Graffiti> graffiti = new ArrayList<Graffiti>(); if (page <= 0) { page = 1; } DataSource ds = getDataSource(); ArrayList<Post> result = new ArrayList<Post>(); int startPos = (page - 1) * 20; try { conn = ds.getConnection(); // 전체 글 테이블 SELECT.. startPos부터 numItems까지 stmt = conn.createStatement(); rs = stmt.executeQuery("select DISTINCT * from member,article where member.userid = article.userid order by article.postdate desc limit " + startPos + ", 20"); // 먼저 글의 목록을 받아온다 while(rs.next()) { result.add(new Post(new Member( rs.getString("userid"), rs.getString("userpassword"), rs.getTimestamp("registerdate"), rs.getString("lastname"), rs.getString("firstname"), rs.getString("nickname"), rs.getString("profilephoto"), rs.getString("gender"), rs.getString("email"), rs.getString("introduce"), rs.getString("website"), rs.getString("info"), rs.getInt("level")), new Article(rs.getInt("postid"), rs.getString("userid"), rs.getInt("albumid"), rs.getString("photo"), rs.getString("content"), rs.getTimestamp("postdate"), rs.getString("category"), rs.getInt("hits"), rs.getInt("likehits"), rs.getInt("postip")), new ArrayList<Comment>(), new ArrayList<Graffiti>())); } // 글의 목록에 코멘트 리스트를 채워준다. for(int i=0; i < result.size(); i++) { comment = CommentDAO.getCommentList(result.get(i).getArticle().getPostid()); result.get(i).setComment(comment); graffiti = GraffitiDAO.getGraffitiList(result.get(i).getArticle().getPostid()); result.get(i).setGraffiti(graffiti); } } finally { // 무슨 일이 있어도 리소스를 제대로 종료 if (rs != null) try{rs.close();} catch(SQLException e) {} if (stmt != null) try{stmt.close();} catch(SQLException e) {} if (conn != null) try{conn.close();} catch(SQLException e) {} } return result; }
9
public static boolean isValid(List<Integer> index, int n) { int len = index.size(); for (int i = 0; i < index.size(); i++) { if (index.get(i) == n || Math.abs(n - index.get(i)) == Math.abs(len - i)) return false; } return true; }
3
public void draw() { for (GameElement gameElement : gameElements) { gameElement.draw(); } }
1
public void separateTrainTest4Spam() { int cvFold = 10; ArrayList<String> parentFakeList = new ArrayList<String>(); String parentFakeString = "448 348 294 329 317 212 327 127 262 148 307 139 40 325 224 234 233 430 357 78 191 150 424 206 125 484 293 73 456 111 141 68 106 183 215 402 209 159 34 156 280 265 458 65 32 118 352 105 404 66"; String[] parentFakeStringArray = parentFakeString.split(" "); for (String parentName : parentFakeStringArray) { parentFakeList.add(parentName); System.out.println("parent Name\t" + parentName); } ArrayList<_Doc> parentTrainSet = new ArrayList<_Doc>(); double avgCommentNum = 0; m_trainSet = new ArrayList<_Doc>(); m_testSet = new ArrayList<_Doc>(); for (_Doc d : m_corpus.getCollection()) { if (d instanceof _ParentDoc) { String parentName = d.getName(); if (parentFakeList.contains(parentName)) { m_testSet.add(d); avgCommentNum += ((_ParentDoc) d).m_childDocs.size(); } else { parentTrainSet.add(d); } } } System.out.println("avg comments for parent doc in testSet\t" + avgCommentNum * 1.0 / m_testSet.size()); for (_Doc d : parentTrainSet) { _ParentDoc pDoc = (_ParentDoc) d; m_trainSet.add(d); for (_ChildDoc cDoc : pDoc.m_childDocs) { m_trainSet.add(cDoc); } } System.out.println("m_testSet size\t" + m_testSet.size()); System.out.println("m_trainSet size\t" + m_trainSet.size()); }
6
private JFileChooser getFileChooser(String mode) { initFileFilter(mode); if ( mode.equals ( Constantes.SAVE ) || mode.equals ( Constantes.RAPPORT ) ) { chooser.setDialogType(JFileChooser.SAVE_DIALOG); } else { chooser.setDialogType(JFileChooser.OPEN_DIALOG); } return chooser; }
2
@Override public boolean blocked(final Node n) { if (n == null) { return true; } else if (n.getPrev() == null || objectTiles.contains(n) || objectTiles.contains(n.getPrev())) { return false; } else { return super.blocked(n); } }
4
public Branch(String name) { this.name = name; this.branchs = new ArrayList<Root>(); }
0
void write(int b) { try { text[tsize++]=(byte)b; } catch (ArrayIndexOutOfBoundsException exc) { byte[] new_text=new byte[text.length<<1]; System.arraycopy(text, 0, new_text, 0, tsize-1); text=new_text; text[tsize-1]=(byte)b; }; };
1
private static void DownloadNewLauncher( ) { try { //progressCurr.setValue(0); String strPath = Utils.getWorkingDirectory() + File.separator+GlobalVar.LauncherFileName; File AppPath = new File(LauncherUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath()); URL connection = new URL(GlobalVar.DownloadClientRootURL+"/"+GlobalVar.LauncherFileName); HttpURLConnection urlconn; urlconn = (HttpURLConnection) connection.openConnection(); urlconn.setRequestMethod("GET"); urlconn.connect(); int fileSize = urlconn.getContentLength(); //Сверяем размер файла на сервере и локальную запись, не совпали? качаем новую версию if(urlconn.getResponseCode() != 404) { if(fileSize != readMD5File(strPath)) { JOptionPane.showMessageDialog( null, "Лаунчер будет автоматически обновлен", "Обновлене", JOptionPane.WARNING_MESSAGE); InputStream in = null; in = urlconn.getInputStream(); OutputStream writer = new FileOutputStream(AppPath.getAbsolutePath()); byte buffer[] = new byte[55000]; int c = in.read(buffer); int dwnloaded =0; while (c > 0) { writer.write(buffer, 0, c); dwnloaded +=c; try{ //progressCurr.setValue((int)((dwnloaded/1024)*100/fileSize)); //progressCurr.setString("Скачивается "+GlobalVar.LauncherFileName + " "+progressCurr.getValue()+"% " +(dwnloaded/1024)+"/"+(fileSize/1024)+"Kb"); }catch(ArithmeticException ae){ //И такое тоже бывает } c = in.read(buffer); } writer.flush(); writer.close(); in.close(); JOptionPane.showMessageDialog( null, "Лаунчер успешно обновлен\nПосле закрытия этого окна лаунчер будет закрыт", "Обновлене успешно", JOptionPane.INFORMATION_MESSAGE); writeMD5File(strPath, fileSize); //Записываем новый размер лаунчера т.к. обновились успешно System.exit(1); } }else{ } } catch (IOException e) { JOptionPane.showMessageDialog( null, "Ошибка обновления лаунчера\nПосле закрытия этого окна будет запущена текущая версия лаунчера", "Обновлене не удалось", JOptionPane.ERROR_MESSAGE); System.out.println(e); } }
5
public boolean sentientAttack(Sentient attacker, Sentient attackee) { int attackRoll = MapRand.randInt(20) + attacker.getAttack(); String attackerUppercase = attacker.getPronoun().substring(0, 1).toUpperCase() + attacker.getPronoun().substring(1); if (attackRoll >= attackee.getAC()) { int damage = attacker.getMeleeDamage(); attackee.takeDamage(damage, attacker); if (attacker.equals(player) && player.getEquippedWeapon() != null) { Weapon w = player.getEquippedWeapon(); messenger.println("Your " + w.properName() + " " + w.getDamageMsg() + " " + attackee.getPronoun() + " for " + damage + " damage!"); } else { if(attacker.isInSight() || attacker.equals(player)) messenger.println(attackerUppercase + " " + attacker.getBaseMeleeDescription() + " " + attackee.getPronoun() + " for " + damage + " damage!"); } return true; } else { if (attackerUppercase.contains("The")) { if(attacker.isInSight()) messenger.println(attackerUppercase + " misses " + attackee.getPronoun()); } else { messenger.println(attackerUppercase + " miss " + attackee.getPronoun()); } return false; } }
7
private boolean processSpecialKeysPressed(KeyEvent e) { int code = e.getKeyCode(); if(KeyEvent.VK_V == code && (e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) { // ctrl-v copyRequest(KeyEvent.VK_CONTROL, KeyEvent.VK_V); return true; } if(KeyEvent.VK_INSERT == code && (e.getModifiers() & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) { // shift-insert copyRequest(KeyEvent.VK_SHIFT, KeyEvent.VK_INSERT); return true; } if(KeyEvent.VK_UP == code && (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK) { configureDelay(+1); return true; } if(KeyEvent.VK_DOWN == code && (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK) { configureDelay(-1); return true; } return false; }
8
public Image drawZBuffer() throws IOException { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); double denominateur = abs(zmax - zmin); System.out.println("denominateur : "+denominateur); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { double value = model.zbufferAt(x, y); assert(value <= zmax):"zbufferAt(x, y) > zmax : "+value+" > "+zmax; // System.out.println("(abs(zmin) + abs(value)) : "+(abs(zmin) + abs(value))); double rate = value == -Double.MAX_VALUE ? 0 : (abs(zmin) + abs(value)) / (double)denominateur; int intensite = (int) (rate * 255.); assert(rate <=1 && rate >=0):"rate incorrect : "+rate; Color c = new Color(intensite,intensite,intensite); // System.out.println("c : "+c); image.setRGB(x, height-1- y, c.getRGB()); } } return image; }
4
public void setCodes(final Hashtable<String, K> codes) { this.codes = codes; }
0
public static void main(String[] args) { FlyweightFactory ff = new FlyweightFactory(); Flyweight ccfw = ff.factory("ubuntu"); ccfw.func(); ff.checkFlyweight(); }
0
protected boolean out_grouping_b(char [] s, int min, int max) { if (cursor <= limit_backward) return false; char ch = current.charAt(cursor - 1); if (ch > max || ch < min) { cursor--; return true; } ch -= min; if ((s[ch >> 3] & (0X1 << (ch & 0X7))) == 0) { cursor--; return true; } return false; }
4
@Override public Object execute(TransitionSystem ts, Unifier un, Term[] terms) throws Exception { WorldModel model = ((MartianArch) ts.getUserAgArch()).getModel(); Graph graph = model.getGraph(); Vertex myPosition = model.getMyVertex(); List<Vertex> notProbedNeighbors = graph.returnNotProbedNeighbors(myPosition); if (null == notProbedNeighbors || notProbedNeighbors.isEmpty()) { // go to the least visited vertex int nextMove = graph.returnLeastVisitedNeighbor(myPosition.getId()); if (nextMove == -1) { return un.unifies(terms[0], ASSyntax.createString("none")); } String vertex = "vertex" + nextMove; return un.unifies(terms[0], ASSyntax.createString(vertex)); } else { for (Vertex notProbedNeighbor : notProbedNeighbors) { if (notProbedNeighbor.getTeam().equals(WorldModel.myTeam) && !model.hasActiveOpponentOnVertex(notProbedNeighbor)) { String vertex = "vertex" + notProbedNeighbor.getId(); return un.unifies(terms[0], ASSyntax.createString(vertex)); } } for (Vertex notProbedNeighbor : notProbedNeighbors) { if (!model.hasActiveOpponentOnVertex(notProbedNeighbor)) { String vertex = "vertex" + notProbedNeighbor.getId(); return un.unifies(terms[0], ASSyntax.createString(vertex)); } } // go to the least visited vertex int nextMove = graph.returnLeastVisitedNeighbor(myPosition.getId()); if (nextMove == -1) { return un.unifies(terms[0], ASSyntax.createString("none")); } String vertex = "vertex" + nextMove; return un.unifies(terms[0], ASSyntax.createString(vertex)); } }
9
@Override public void emitCode(GluonOutput code) { if (variable != null){ String varName = variable.getLabelName(); assignmentExp.emitCode(code); switch (assignmentOp){ case ASSIGN: break; case ASSIGN_ADD: code.code("MOV EBX, " + varName); code.code("ADD EAX, EBX"); break; case ASSIGN_SUBTRACT: code.code("MOV EBX, EAX"); code.code("MOV EAX, " + varName); code.code("SUB EAX, EBX"); break; case ASSIGN_MULTIPLY: code.code("MOV EBX, " + varName); code.code("IMUL EAX, EBX"); break; case ASSIGN_DIVIDE: code.code("MOV EBX, EAX"); code.code("XOR EDX, EDX"); code.code("MOV EAX, " + varName); code.code("IDIV EBX"); break; } code.code("MOV " + varName + ", EAX"); } else { expression.emitCode(code); } }
6
private static InetAddress parseInetAddress(String strIn) { InetAddress iaOut = null; String[] strBytes = null; byte[] arrBytes = null; if ( strIn.matches(EzimNetwork.regexpIPv4) || strIn.matches(EzimNetwork.regexpIPv6) ) { try { iaOut = InetAddress.getByName(strIn); } catch(Exception e) { // this should NEVER happen EzimLogger.getInstance().severe(e.getMessage(), e); iaOut = null; } } return iaOut; }
3
public HashMap<String,ArrayList<String>> getMessages(String receiver){ HashMap<String,ArrayList<String>> messages = new HashMap<String,ArrayList<String>>(); Statement st; ResultSet rs; String query; ArrayList<String> temp = new ArrayList<String>(); String sender=null; String oldsender; try { st = conn.createStatement(); query="SELECT sender,message FROM messages WHERE receiver='"+receiver+"' ORDER BY sender ASC" ; rs = st.executeQuery(query); while (rs.next()){ oldsender = sender; sender=rs.getString(1).trim(); if(oldsender!=null && !oldsender.equals(sender)){ messages.put(oldsender, temp); temp = new ArrayList<String>(); } temp.add(rs.getString(2)); } rs.close(); messages.put(sender, temp); } catch (SQLException e) { e.printStackTrace(); } return messages; }
4
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Vechicle ICT project by Cyborgs"); Coordinate c1 = new Coordinate(1, 9.2); c1.print(); Node firstNode = new Node(c1, "Starting Node"); firstNode.print(); Node secondNode = new Node(new Coordinate(7, 4), "Other Node"); secondNode.print(); Edge firstEdge = new Edge(firstNode, secondNode, "MyWay"); firstEdge.print(); System.out.println("Length of " + firstEdge.getName() + ": " + firstEdge.getLength()); System.out.println("--- Graph ---"); Graph myCity = new Graph(); // Locations Node gellert = new Node(new Coordinate(0, -12), "Szent Gellért Tér"); Node moricz = new Node(new Coordinate(-2, -14), "Móricz"); Node ujbuda = new Node(new Coordinate(-2, -16), "Újbuda Központ"); Node kosztolanyi = new Node(new Coordinate(-4, -15), "Kosztolányi tér"); myCity.addBidirectionalEdge(new Edge(gellert, moricz, "Bartók Béla út")); myCity.addBidirectionalEdge(new Edge(moricz, ujbuda, "Fehérvári út")); myCity.addBidirectionalEdge(new Edge(ujbuda, kosztolanyi, "Bocskai út")); myCity.addBidirectionalEdge(new Edge(moricz, kosztolanyi, "Bartók Béla út+")); myCity.print(); ArrayList<String> path = Dijkstra.shortestPath(myCity, "Szent Gellért Tér", "Újbuda Központ"); System.out.println("\r\n--Your shortest path:"); for (String road : path) { System.out.println(road); } }
1
public static Predicate.Op getOp(String s) throws simpledb.ParsingException { if (s.equals("=")) return Predicate.Op.EQUALS; if (s.equals(">")) return Predicate.Op.GREATER_THAN; if (s.equals(">=")) return Predicate.Op.GREATER_THAN_OR_EQ; if (s.equals("<")) return Predicate.Op.LESS_THAN; if (s.equals("<=")) return Predicate.Op.LESS_THAN_OR_EQ; if (s.equals("LIKE")) return Predicate.Op.LIKE; if (s.equals("~")) return Predicate.Op.LIKE; if (s.equals("<>")) return Predicate.Op.NOT_EQUALS; if (s.equals("!=")) return Predicate.Op.NOT_EQUALS; throw new simpledb.ParsingException("Unknown predicate " + s); }
9
protected Location resolveLocationUsingUserLocation(Map<String,Object> tweet) { String tweetLocation = Utils.getLocationFromTweet(tweet); if (tweetLocation != null) { String location = tweetLocation.replaceAll("\\p{Punct}", " ").replaceAll("\\s+", " ").toLowerCase().trim(); // Check if this is a known location if (this.locationNameToLocation.containsKey(location)) { return this.locationNameToLocation.get(location); } // Look for patterns in the location. Replace punctuation but keep "," String locationWithComma = tweetLocation.replaceAll("[!\\\"#$%&'\\(\\)\\*\\+-\\./:;<=>\\?@\\[\\\\]^_`\\{\\|\\}~]", " ").replaceAll("\\s+", " ").toLowerCase().trim(); Matcher matcher = this.statePattern .matcher(locationWithComma); if (matcher.matches()) { // extracting the state name or country name of location strings, if available String matchedString = matcher.group(1).toLowerCase(); String stateOrCountryName = null; if (stateFullNames.contains(matchedString) || countryFullNames.contains(matchedString)) stateOrCountryName = matchedString; else if (stateAbbreviationToFullName.containsKey(matchedString)) stateOrCountryName = stateAbbreviationToFullName.get(matchedString); else if (countryAbbreviationToFullName.containsKey(matchedString)) stateOrCountryName = countryAbbreviationToFullName.get(matchedString); if (stateOrCountryName != null && this.locationNameToLocation.containsKey(stateOrCountryName)) { return this.locationNameToLocation.get(stateOrCountryName); } } } return null; }
9
final void method1716(boolean bool) { if (bool != false) method1716(false); anInt5962++; if (((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub25_7271.method1830((byte) -119) && !Node.method2714(7351, ((Class348_Sub51) ((Class239) this).aClass348_Sub51_3136) .aClass239_Sub25_7271 .method1829(-32350))) ((Class239) this).anInt3138 = 0; if (((Class239) this).anInt3138 < 0 || (((Class239) this).anInt3138 ^ 0xffffffff) < -2) ((Class239) this).anInt3138 = method1710(20014); }
5
public void setPath(String path) { this.path = path; }
0
public static ArrayList<String> getAllSenses(String line){ String sense = ""; ArrayList<String> words = getWords(line); for(int i = 1; i < words.size(); i++){ if(!words.get(i).equals("@")) sense += words.get(i); else break; } ArrayList<String> senses = new ArrayList<String>(); int count = countOccurrences(sense, '1'); if(count > 1 ){ for(int i = 0; i < sense.length(); i ++){ String newSense = ""; for (int k = 0; k < sense.length(); k++){ if(sense.charAt(i) == '1'){ if(i == k) newSense += "1"; else newSense += "0"; } } if(!newSense.equals("")) senses.add(newSense); } }else senses.add(sense); return senses; }
8
@Override public boolean allowTarget( ConnectionableCapability item, ConnectionFlavor flavor ) { return item != this || allowSelfReference( flavor ); }
1
public void Login() throws SQLException { try { Conexion.GetInstancia().Conectar(); ResultSet rs = Conexion.GetInstancia().EjecutarConsulta ("SELECT User_Empleado, Clave_Empleado, Tip_Empleado FROM Empleado WHERE User_Empleado ='"+ObEmpleado.getUser_Empleado()+"'"); while(rs.next()) { ObEmpleado.setUser_Empleado(rs.getString("User_Empleado")); ObEmpleado.setClave_Empleado(rs.getString("Clave_Empleado")); ObEmpleado.setTip_Empleado(rs.getString("Tip_Empleado")); } } catch(SQLException ex) { throw ex; } finally { Conexion.GetInstancia().Desconectar(); } }
2
public int getNowDay() { return Integer.parseInt(sysNowTime[2]); }
0
public boolean isPalindrome(String s) { s = s.trim().toLowerCase(); if (s.length() == 0) return true; int l = 0, r = s.length() - 1; while (l <= r) { while (l < r && !isAlpha(s.charAt(l))) { l++; } while (r > l && !isAlpha(s.charAt(r))) { r--; } if (s.charAt(l) != s.charAt(r)) return false; l++; r--; } return true; }
7
private void init() { try { // Setup Parser factory = SAXParserFactory.newInstance(); factory.setValidating(false); parser = factory.newSAXParser(); reader = parser.getXMLReader(); reader.setContentHandler(this); reader.setErrorHandler(new SimpleSAXErrorHandler()); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
2
private static Object valueOfField(Object obj, String fieldName) { Class<?> clazz = obj.getClass(); Field field = null; while (clazz != null) { for (Field declaredField : clazz.getDeclaredFields()) { if (fieldName.equals(declaredField.getName())) { field = declaredField; break; } } clazz = clazz.getSuperclass(); } if (field != null) { if (!field.isAccessible()) { field.setAccessible(true); } try { return field.get(obj); } catch (Exception e) { // Ignored } } return null; }
7
public String getSenha() { return senha; }
0
public boolean getVSycn() { return this.vSync; }
0
public void encodage() { //Ajout de la position du mot de depart //code.add(String.valueOf(positionChaine).charAt(0)); leCode = positionChaine +""; //Ajout de chaque dernier caractere de chaque ligne du tableur for(ArrayList<Character> mot : tableurTrie) { leCode += mot.get(TAILLEMOT-1); code.add(mot.get(TAILLEMOT-1)); } System.out.println("Mot encodée : " + leCode); System.out.println("Code : " + code); }
1
public Tree<String> traverseAnnotatedTree(Tree<String> tree) { if (tree.isLeaf()) { return tree; } List<Tree<String>> childrenList = tree.getChildren(); if (childrenList.size() == 1) { Tree<String> child = childrenList.get(0); String[] params0 = new String[4]; params0[0] = tree.getLabel(); params0[1] = child.getLabel(); params0[2] = "1"; params0[3] = String.valueOf(grammar.getUnScore(tree.getLabel(), child.getLabel())); if (child.isLeaf()) { params0[2] = "lexicon"; params0[3] = String.valueOf(Math.log(lexicon.scoreTagging( child.getLabel(), tree.getLabel()))); } word_tokens.add(params0); traverseAnnotatedTree(child); } else if (childrenList.size() == 2) { Tree<String> leftChild = childrenList.get(0); Tree<String> rightChild = childrenList.get(1); String[] params1 = new String[4]; params1[0] = tree.getLabel(); params1[1] = leftChild.getLabel(); params1[2] = "2"; params1[3] = String.valueOf(grammar.getBiScore(tree.getLabel(), leftChild.getLabel(), rightChild.getLabel())); word_tokens.add(params1); traverseAnnotatedTree(leftChild); String[] params2 = new String[4]; params2[0] = tree.getLabel(); params2[1] = rightChild.getLabel(); params2[2] = "2"; params2[3] = "0"; word_tokens.add(params2); traverseAnnotatedTree(rightChild); } return tree; }
4
public synchronized void start() throws Exception { if (thread != null) { throw new Exception("ServerSocket already started."); } server = new ServerSocket(port, backlog); thread = new Thread(new Runnable() { /** run() * * Accepts connections and adds it to the managed list */ @Override public void run() { running = true; while(running) { try { sockets.add(new SocketWrapper(server.accept())); } catch (IOException e) { } } } }); thread.start(); }
3
public void PlayGame() { while(!Game.board.CheckGameComplete()) { if(Game.board.CheckGameDraw(Player.white)){ break; } White.Move(); if(Game.board.CheckGameComplete()){ UserInteractions.DisplayGreetings(Player.white); Game.board.Display(); break; } if(Game.board.CheckGameDraw(Player.black)){ break; } ///////////////////////////////////////// //System.out.println("Black ="+Game.board.blackPieces+", White="+Game.board.whitePieces); ///////////////////////////////////////// Game.board.Display(); Black.Move(); if(Game.board.CheckGameComplete()){ UserInteractions.DisplayGreetings(Player.black); Game.board.Display(); break; } // Game.board.Display(); ///////////////////////////////////////// // System.out.println("Black ="+Game.board.blackPieces+", White="+Game.board.whitePieces); ///////////////////////////////////////// } }
5
public String toString(){ String s; Exemplar cur = m_Exemplars; int i; if (m_MinArray == null) { return "No classifier built"; } int[] nbHypClass = new int[m_Train.numClasses()]; int[] nbSingleClass = new int[m_Train.numClasses()]; for(i = 0; i<nbHypClass.length; i++){ nbHypClass[i] = 0; nbSingleClass[i] = 0; } int nbHyp = 0, nbSingle = 0; s = "\nNNGE classifier\n\nRules generated :\n"; while(cur != null){ s += "\tclass " + m_Train.attribute(m_Train.classIndex()).value((int) cur.classValue()) + " IF : "; s += cur.toRules() + "\n"; nbHyp++; nbHypClass[(int) cur.classValue()]++; if (cur.numInstances() == 1){ nbSingle++; nbSingleClass[(int) cur.classValue()]++; } cur = cur.next; } s += "\nStat :\n"; for(i = 0; i<nbHypClass.length; i++){ s += "\tclass " + m_Train.attribute(m_Train.classIndex()).value(i) + " : " + Integer.toString(nbHypClass[i]) + " exemplar(s) including " + Integer.toString(nbHypClass[i] - nbSingleClass[i]) + " Hyperrectangle(s) and " + Integer.toString(nbSingleClass[i]) + " Single(s).\n"; } s += "\n\tTotal : " + Integer.toString(nbHyp) + " exemplars(s) including " + Integer.toString(nbHyp - nbSingle) + " Hyperrectangle(s) and " + Integer.toString(nbSingle) + " Single(s).\n"; s += "\n"; s += "\tFeature weights : "; String space = "["; for(int ii = 0; ii < m_Train.numAttributes(); ii++){ if(ii != m_Train.classIndex()){ s += space + Double.toString(attrWeight(ii)); space = " "; } } s += "]"; s += "\n\n"; return s; }
7
public static int findLIS(int size) { int[] dp = new int[size]; Arrays.fill(dp, 1); int ans = 1; for (int i = 0; i < dp.length; i++) for (int j = 0; j < i; j++) if (match(j, i) && dp[i] + 1 > dp[j]) dp[i] = Math.max(dp[i], dp[j] + 1); for (int i = 0; i < dp.length; i++) ans = Math.max(ans, dp[i]); return ans; }
5
public int getColumn(Object element) { if( element instanceof Tree ) { Tree tree = (Tree) element; element = tree.getNode(); } if ((this.contextClass != null) && (this.contextClass.isInstance(element))) { try { return ((Integer)this.contextClass.getMethod("columnStart", new Class[0]).invoke(element, new Object[0])).intValue(); } catch (InvocationTargetException localInvocationTargetException) {}catch (Exception ex) { ex.printStackTrace(); } } return 0; }
5
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("stream")) { try{ if(args[0].equalsIgnoreCase("debug")){ if(Main.Debug == true){ Main.Debug = false; sender.sendMessage(prefix + "Disabled debug mode."); }else{ Main.Debug = true; sender.sendMessage(prefix + "Enabled debug mode."); } }else if (channels.containsKey(args[0]) || channels.containsKey(args[0].toLowerCase())) { sender.sendMessage(prefix + "Click to view: http://twitch.tv/" + args[0].toLowerCase()); return true; } else { sender.sendMessage(prefix + "Channel not found! Valid channels: " + channels.keySet()); return true; } }catch(ArrayIndexOutOfBoundsException ae){ sender.sendMessage(prefix+" Incorrect syntax! /stream <Channel> "); return true; } } return false; }
6
@Override public void updateLot(List<String> optPlayerList) { final Environmental EV=affected; if(!(EV instanceof Room)) return; Room R=(Room)EV; boolean didAnything=false; try { List<Runnable> postWork=new ArrayList<Runnable>(); synchronized(("SYNC"+R.roomID()).intern()) { R=CMLib.map().getRoom(R); lastItemNums=updateLotWithThisData(R,this,true,scheduleReset,optPlayerList,lastItemNums); if(getOwnerName().length()==0) { didAnything = retractRooms(R,postWork) || didAnything; } else if(canGenerateAdjacentRooms(R)) { didAnything = expandRooms(R,postWork) || didAnything; } } for(Runnable run : postWork) run.run(); scheduleReset=false; } finally { if(didAnything) getConnectedPropertyRooms(); // recalculates the unique id for this lot of rooms } }
7
public final int partitionByName(int lb, int ub) { Person pivotElement = allPersons[lb]; // store the left most value as the pivot element int max = logicalSize; int left = lb, right = ub; // store left and right as the unchanging values of lb and ub respectively. This is used for the final move of this method Person temp; // create a temp for swapping thing around. while (left < right) { while ((allPersons[left].getName().compareToIgnoreCase(pivotElement.getName()) <= 0) && left + 1 < max) { // test the order of the persons on left side left++; } while ((allPersons[right].getName().compareToIgnoreCase(pivotElement.getName()) > 0) && right - 1 >= 0) { // test the order of the persons on right side right--; } if (left < right) // swap the left and right persons, remember that temp variable, this is where it shines. { temp = allPersons[left]; allPersons[left] = allPersons[right]; allPersons[right] = temp; } } for (left = lb; left <= right && left + 1 < max; left++) { //move the persons one place to the left for all persons after the pivot element allPersons[left] = allPersons[left + 1]; } allPersons[right] = pivotElement; // move the pivot element to its place at right, where it is now in the correct order. return right; // return the new pivot (see quick sort) }
8
public com.actuate.schemas.SelectFilesResponse selectFiles( com.actuate.schemas.FileSearch fileSearch, String name, ArrayOfString nameList) { if (null == authenticationId) login(); com.actuate.schemas.ArrayOfString resultDef = newArrayOfString( new String[] { "Description", "FileType", "Id", "Name", "Owner", "PageCount", "Size", "TimeStamp", "UserPermissions", "Version", "VersionName" }); com.actuate.schemas.SelectFiles selectFiles = new com.actuate.schemas.SelectFiles(); selectFiles.setResultDef(resultDef); if (fileSearch != null) selectFiles.setSearch(fileSearch); else if (name != null) selectFiles.setName(name); else if (nameList != null) selectFiles.setNameList(nameList); com.actuate.schemas.SelectFilesResponse selectFilesResponse = null; try { selectFilesResponse = proxy.selectFiles(selectFiles); com.actuate.schemas.ArrayOfFile itemList = selectFilesResponse.getItemList(); com.actuate.schemas.File[] files = itemList.getFile(); if (files != null) { for (int i = 0; i < files.length; i++) { printFile(System.out, files[i]); } } } catch (RemoteException e) { System.out.println("error !!!"); e.printStackTrace(); } return selectFilesResponse; }
7
public boolean fillChampion(Champion champion, Region region) throws RiotApiException { List<Champion> champions = getAllChampions(region); Champion newChampion = null; for(Champion c : champions) if((champion.getId() >= 0 && c.getId() == champion.getId()) || (c.getName() != null && c.getName().equals(champion.getName()))) { newChampion = c; break; } //Fill if required if(newChampion != null) { champion.setId(newChampion.getId()); champion.setActive(newChampion.isActive()); champion.setFreeToPlay(newChampion.isFreeToPlay()); champion.setBotMatchMadeEnabled(newChampion.isBotMatchMadeEnabled()); champion.setBotCustomEnabled(newChampion.isBotCustomEnabled()); champion.setRankedEnabled(newChampion.isRankedEnabled()); return true; } return false; }
6
protected AbstractParserFactory makeParserFactory() throws MaltChainedException { Class<?> clazz = (Class<?>)manager.getOptionValue("singlemalt", "parsing_algorithm"); try { Class<?>[] params = new Class<?>[1]; params[0] = org.maltparserx.parser.Algorithm.class; Object[] arguments = new Object[params.length]; arguments[0] = this; Constructor<?> constructor = clazz.getConstructor(params); return (AbstractParserFactory)constructor.newInstance(arguments); } catch (NoSuchMethodException e) { throw new ConfigurationException("The parser factory '"+clazz.getName()+"' cannot be initialized. ", e); } catch (InstantiationException e) { throw new ConfigurationException("The parser factory '"+clazz.getName()+"' cannot be initialized. ", e); } catch (IllegalAccessException e) { throw new ConfigurationException("The parser factory '"+clazz.getName()+"' cannot be initialized. ", e); } catch (InvocationTargetException e) { throw new ConfigurationException("The parser factory '"+clazz.getName()+"' cannot be initialized. ", e); } }
9
private void determineX(int r, int s, double teta, Matrice bBarre) { for(int i = 0; i<this.X.getNbColumns(); i++) { if(i == r) { this.X.setValueAt(0, i, 0); } else if(i == s) { this.X.setValueAt(0, i, teta); } else { if(i > this.Abarre.getNbLines()-1) { this.X.setValueAt(0, i, 0); } else { this.X.setValueAt(0, i, (bBarre.getValueAt(i, 0) - (this.Abarre.getValueAt(i, s)*teta))); } } } }
4
public double Dvn(double v[], double uv[]) { double w1, w2, vm; TRACE("Dvn"); /* Modulus */ w1 = 0.0; for (int i = 0; i < 3; i++) { w2 = v[i]; w1 += w2 * w2; } w1 = Math.sqrt(w1); vm = w1; /* Normalize the vector */ w1 = (w1 > 0.0) ? w1 : 1.0; for (int i = 0; i < 3; i++) { uv[i] = v[i] / w1; } ENDTRACE("Dvn"); return vm; }
3
public int[] revealedBox() { int minR = 1000, minC = 1000, maxR = 0, maxC = 0; for (int r = 0; r < revealed.length; r++) { for (int c = 0; c < revealed[0].length; c++) { if (revealed[r][c] != 0) { if (r < minR) minR = r; else if (r > maxR) maxR = r; if (c < minC) minC = c; else if (c > maxC) maxC = c; } } } return new int[]{minR, minC, maxR-minR, maxC-minC}; }
7
@Override public void run() { while (!isStop) { try { Socket clientSocket = listener.accept(); ServerHandler serverHandler = new ServerHandler(clientSocket, records); handlers.add(serverHandler); threadPool.start(serverHandler); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(1); } } if (!listener.isClosed()) { try { listener.close(); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(1); } } }
4
@Override protected void updateStronglyConnectedComponents_addConclusions(Literal literal) { Set<Rule> rules = theory.getRulesWithHead(literal); for (Rule rule : rules) { switch (rule.getRuleType()) { case STRICT: if (isLogInferenceProcess) getInferenceLogger().updateRuleInferenceStatus(rule.getOriginalLabel(), RuleType.STRICT, ConclusionType.DEFINITE_NOT_PROVABLE, literal, RuleInferenceStatus.DISCARDED); newLiteralFind_definiteNotProvable(literal, true); break; case DEFEASIBLE: if (isLogInferenceProcess) getInferenceLogger().updateRuleInferenceStatus(rule.getOriginalLabel(), RuleType.DEFEASIBLE, ConclusionType.DEFEASIBLY_NOT_PROVABLE, literal, RuleInferenceStatus.DISCARDED); newLiteralFind_defeasiblyNotProvable(literal, true); break; default: } // add the positively support record to the record set addRecord(new Conclusion(ConclusionType.POSITIVELY_SUPPORT, literal)); } }
5
public void setAllocPolicy(int allocPolicy) { if ((allocPolicy < 0) || (allocPolicy > 1)) { throw new AssertionError((allocPolicy >= 0) && (allocPolicy <= 1)); } _allocPolicy = allocPolicy; }
3
public HashMap<String, Map<String, Integer>> GetOutRelation(int id) { ResultSet set = sqLconnection.Query(query + id); String author, subauthor; int count; String[] info, outauthors; boolean flag = false; HashMap<String, Integer> authorMap = new HashMap<>(); try { while (set.next()) { author = set.getString("name"); outauthors = set.getString("outauthors").split(","); if (!flag) { for (String obj : outauthors) { info = obj.split("#"); subauthor = info[0]; count = Integer.parseInt(info[1]); if (!authorMap.containsKey(subauthor)) { authorMap.put(subauthor, count); } } flag=true; } if(!outauthorMap.containsKey(author)) { outauthorMap.put(author, authorMap); } } } catch (SQLException e) { e.printStackTrace(); } return outauthorMap; }
6
@Override public void keyReleased(KeyEvent e){ int code = e.getKeyCode(); if (code == KeyEvent.VK_LEFT || code == KeyEvent.VK_A || code == KeyEvent.VK_D || code == KeyEvent.VK_RIGHT){ player.stop(code); } }
4
public EigenvalueDecomposition (Matrix Arg) { double[][] A = Arg.getArray(); n = Arg.getColumnDimension(); V = new double[n][n]; d = new double[n]; e = new double[n]; issymmetric = true; for (int j = 0; (j < n) & issymmetric; j++) { for (int i = 0; (i < n) & issymmetric; i++) { issymmetric = (A[i][j] == A[j][i]); } } if (issymmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i][j] = A[i][j]; } } // Tridiagonalize. tred2(); // Diagonalize. tql2(); } else { H = new double[n][n]; ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i][j] = A[i][j]; } } // Reduce to Hessenberg form. orthes(); // Reduce Hessenberg to real Schur form. hqr2(); } }
7
public static boolean isAllUnique(String s) { if ( s.length() > 256 ) return false; // by default, all values in boolean array are set to #f boolean[] charSet = new boolean[256]; for (int i=0 ; i != s.length(); ++i ) { int c = s.charAt(i); if ( charSet[c] ) { return false; } charSet[ c ] = true; } return true; }
3
public static Stella_Object yieldHardcodedCaseSymbolIdOrIds(Stella_Object casetest) { if (casetest == Stella.SYM_STELLA_OTHERWISE) { return (casetest); } { Symbol symbol = null; { Surrogate testValue000 = Stella_Object.safePrimaryType(casetest); if (testValue000 == Stella.SGT_STELLA_CONS) { { Cons casetest000 = ((Cons)(casetest)); { ConsIterator it = casetest000.allocateIterator(); while (it.nextP()) { symbol = ((Symbol)(it.value)); if (!(symbol.symbolId != Stella.NULL_INTEGER)) { symbol = Symbol.internPermanentSymbol(symbol.symbolName); } it.valueSetter(IntegerWrapper.wrapInteger(symbol.symbolId)); GeneralizedSymbol.registerSymbol(symbol); } } return (casetest000); } } else if (Surrogate.subtypeOfSymbolP(testValue000)) { { Symbol casetest000 = ((Symbol)(casetest)); symbol = casetest000; if (!(symbol.symbolId != Stella.NULL_INTEGER)) { symbol = Symbol.internPermanentSymbol(symbol.symbolName); } GeneralizedSymbol.registerSymbol(casetest000); return (IntegerWrapper.wrapInteger(symbol.symbolId)); } } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } } }
6
public void testPrint_writerMethods() throws Exception { DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC); CharArrayWriter out = new CharArrayWriter(); f.printTo(out, dt); assertEquals("Wed 2004-06-09T10:20:30Z", out.toString()); out = new CharArrayWriter(); f.printTo(out, dt.getMillis()); assertEquals("Wed 2004-06-09T11:20:30+01:00", out.toString()); out = new CharArrayWriter(); ISODateTimeFormat.yearMonthDay().printTo(out, dt.toYearMonthDay()); assertEquals("2004-06-09", out.toString()); out = new CharArrayWriter(); try { ISODateTimeFormat.yearMonthDay().printTo(out, (ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} }
1
public void addEvent(String s){ if(events[events.length-1]==null){ for(int index=0;index<events.length-1;index++){ if(events[index]!=null){ events[index]=s; return; } } } else{ for(int index=0;index<events.length-2;index++){ events[index]=events[index+1]; } events[events.length-1]=s; } }
4
public boolean bottomConnect(int[][] currentBlockArray, int[][] pixels, int x, int z) { boolean connects = false; for(int i = 3; i < pixels.length && !connects; i++) { if( isCaveBG(currentBlockArray[x+i][z-1]) && isCaveBG(currentBlockArray[x+i-1][z-1]) && isCaveBG(currentBlockArray[x+i-2][z-1]) && isCaveBG(getBlockTypeIdFromPixel(pixels[i][0])) && isCaveBG(getBlockTypeIdFromPixel(pixels[i-1][0])) && isCaveBG(getBlockTypeIdFromPixel(pixels[i-2][0])) ) { connects = true; } } return connects; }
8
public void setStartingPosition() { int randomCorner = (int) (Math.random() * 4); switch (randomCorner) { case 0: this.x = 0; this.y = 0; break; case 1: this.x = 450; this.y = 0; break; case 2: this.x = 0; this.y = 350; break; case 3: this.x = 450; this.y = 350; break; } }
4
@Override public boolean retainAll(Collection<?> arg0) { boolean result = list.retainAll(arg0); if (result) try { save(); } catch (IOException ex) { System.err.println("Autosave failed - " + ex.getMessage()); ex.printStackTrace(); return false; } return result; }
3
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){ try { Object o1 = session.getAttribute("UserID"); Object o2 = session.getAttribute("UserRights"); boolean bRedirect = false; if ( o1 == null || o2 == null ) { bRedirect = true; } if ( ! bRedirect ) { if ( (o1.toString()).equals("")) { bRedirect = true; } else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; } } if ( bRedirect ) { response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI())); return "sendRedirect"; } } catch(Exception e){}; return ""; }
7
@EventHandler(ignoreCancelled = true) public void rarpBlockFromTo(BlockFromToEvent event) { if (event.isCancelled()) { return; } Block blockFrom = event.getBlock(); boolean isWater = blockFrom.getTypeId() == 8 || blockFrom.getTypeId() == 9; boolean isLava = blockFrom.getTypeId() == 10 || blockFrom.getTypeId() == 11; boolean isAir = blockFrom.getTypeId() == 0; if (isAir || isLava || isWater) { Block blockTo = event.getToBlock(); if (isRailAndEnabled(blockTo)) { event.setCancelled(true); return; } if (isRedStoneAndEnabled(blockTo)) { event.setCancelled(true); } } }
8
public final WaiprParser.triggers_return triggers() throws RecognitionException { WaiprParser.triggers_return retval = new WaiprParser.triggers_return(); retval.start = input.LT(1); CommonTree root_0 = null; Token char_literal40=null; Token char_literal42=null; ParserRuleReturnScope trigger39 =null; ParserRuleReturnScope trigger41 =null; CommonTree char_literal40_tree=null; CommonTree char_literal42_tree=null; RewriteRuleTokenStream stream_17=new RewriteRuleTokenStream(adaptor,"token 17"); RewriteRuleTokenStream stream_IE=new RewriteRuleTokenStream(adaptor,"token IE"); RewriteRuleSubtreeStream stream_trigger=new RewriteRuleSubtreeStream(adaptor,"rule trigger"); try { // Waipr.g:38:9: ( trigger ( ',' trigger )* ';' -> ( trigger )* ) // Waipr.g:38:11: trigger ( ',' trigger )* ';' { pushFollow(FOLLOW_trigger_in_triggers274); trigger39=trigger(); state._fsp--; stream_trigger.add(trigger39.getTree()); // Waipr.g:38:19: ( ',' trigger )* loop11: while (true) { int alt11=2; int LA11_0 = input.LA(1); if ( (LA11_0==17) ) { alt11=1; } switch (alt11) { case 1 : // Waipr.g:38:20: ',' trigger { char_literal40=(Token)match(input,17,FOLLOW_17_in_triggers277); stream_17.add(char_literal40); pushFollow(FOLLOW_trigger_in_triggers279); trigger41=trigger(); state._fsp--; stream_trigger.add(trigger41.getTree()); } break; default : break loop11; } } char_literal42=(Token)match(input,IE,FOLLOW_IE_in_triggers283); stream_IE.add(char_literal42); // AST REWRITE // elements: trigger // token labels: // rule labels: retval // token list labels: // rule list labels: // wildcard labels: retval.tree = root_0; RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null); root_0 = (CommonTree)adaptor.nil(); // 38:38: -> ( trigger )* { // Waipr.g:38:41: ( trigger )* while ( stream_trigger.hasNext() ) { adaptor.addChild(root_0, stream_trigger.nextTree()); } stream_trigger.reset(); } retval.tree = root_0; } retval.stop = input.LT(-1); retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { // do for sure before leaving } return retval; }
6
@Override public boolean Input(double _deltaTime, MouseCursor mouse, Keyboard _keyboard) { //TODO: Check your input devices for changes. //If the game is active check for input. if(application.isFocused()) { } return true; }
1
public static String Reconstruct(int[] m) { String q = ""; char[] w = new char[m.length]; for (int x = 0; x < m.length; x++) { w[x] = (char) m[x]; q = q + w[x]; } return q; }
1
private void markExploredCell(String descriptor) throws ArenaTemplateException { String binStr = null; try{ binStr = hexToBinaryStr(descriptor); }catch(NumberFormatException e){ throw new ArenaTemplateException(2, "The descriptor contains some non-hex digit"); } if(binStr.length() != this.rowCount * this.columnCount + 4){ throw new ArenaTemplateException(3, "Invalid Map Descriptor"); } if(!(binStr.charAt(0) == '1' && binStr.charAt(0) == '1' && binStr.charAt(302) == '1' && binStr.charAt(303) == '1')){ throw new ArenaTemplateException(3, "Invalid Map Descriptor"); } // System.out.println("Original in Hex: " + descriptor); // System.out.println("Original in Binary: " + binStr); // System.out.println("No header & trailer: " + binStr); //Cut the header and trailer 11 binStr = binStr.substring(2, 302); for(int rowIndex = this.rowCount - 1; rowIndex >= 0;rowIndex--){ for(int colIndex = 0;colIndex < this.columnCount;colIndex++){ int strIndex = this.columnCount * (this.rowCount - 1 - rowIndex) + colIndex; if(binStr.charAt(strIndex) == '1'){ this.arena[rowIndex][colIndex] = CellState.EMPTY; }else{ this.arena[rowIndex][colIndex] = CellState.UNEXPLORED; } } } }
9
@Override public TextModifier getTextModifier() { TextModifier modifier = new TextModifier(); if(textColor != null) { modifier.addModifier(TextModValue.COLOR, textColor); } return modifier; }
1
public void visitNewExpr(final NewExpr expr) { // Keep track of the value number of expression that create new // objects. if (expr.valueNumber() != -1) { if (ValueFolding.DEBUG) { System.out.println("New " + expr); } news.set(expr.valueNumber()); } }
2
static double[][] transpose(double[][] A){ double[][] B = new double[A[0].length][A.length]; for(int i = 0; i < A.length; i++){ for(int j = 0; j < A[i].length; j++){ B[j][i] = A[i][j]; } } return B; }
2
public static int flip_bit_at(final int val, final int at_index) { assert(at_index >= 24); // we're only flipping bits in least sig byte of val final char[] chars = getZeroPaddedBinaryString(val).toCharArray(); chars[at_index] = chars[at_index] == '1' ? '0' : '1'; final int i = Integer.parseInt(new String(chars), 2); return i; }
1
public JSONArray getJSONArray(int index) throws JSONException { Object object = get(index); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); }
1
public static byte pedir_q_cuenta(){ byte aux=0; do{ try{ System.out.println("1. Ingreso en Cuenta Corriente"); System.out.println("2. Ingreso en Cuenta Ahorro"); System.out.print("OP => "); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); aux=Byte.parseByte(stdin.readLine()); }catch(NumberFormatException e){ System.out.println(e+"Valores numericos enteros"); } catch (IOException e) { e.printStackTrace(); } }while(aux!=1 && aux!=2); return aux; }
4
public void deleteByUserName(String userName) { EntityManager em = PersistenceManager.createEntityManager(); try { em.getTransaction().begin(); List<Openchatroomsmessage> ochrms = em.createNamedQuery("Openchatroomsmessage.GetByUser", Openchatroomsmessage.class) .setParameter("u", userName) .getResultList(); for (Openchatroomsmessage openchatroomsmessage : ochrms) { em.remove(openchatroomsmessage); } em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) em.getTransaction().rollback(); em.close(); } }
2
private int getAbsoluteInsertionIndex(Row parent, int childInsertIndex) { int insertAt; int count; if (parent == null) { count = mModel.getRowCount(); insertAt = childInsertIndex; while (insertAt < count && mModel.getRowAtIndex(insertAt).getParent() != null) { insertAt++; } } else { int i = parent.getChildCount(); if (i == 0 || !parent.isOpen()) { insertAt = mModel.getIndexOfRow(parent) + 1; } else if (childInsertIndex < i) { insertAt = mModel.getIndexOfRow(parent.getChild(childInsertIndex)); } else { Row row = parent.getChild(i - 1); count = mModel.getRowCount(); insertAt = mModel.getIndexOfRow(row) + 1; while (insertAt < count && mModel.getRowAtIndex(insertAt).isDescendantOf(row)) { insertAt++; } } } return insertAt; }
8
static BigDecimal processUserSelection(VendingMachine vendingMachine, Scanner scanner, BigDecimal balance) { // user inputs coins to the vending machine - require a balance to store the current value of the balance // validate user inputs, i.e. have they entered a valid coin value? while(balance.compareTo(MIN_BALANCE) == -1) { System.out.println("Please enter a coin..."); Coin inserted_coin = new Coin(scanner.nextBigDecimal()); System.out.println("Current balance: " + balance); // method to determine users product choice (value) against the current balance of the vending machine. // if balance is equal to or exceeds product value, dispense product and return change (if any). if(vendingMachine.getValidCoins().contains(inserted_coin)) { // increase vending machine coin values balance = processCoinEntry(coin_totals, balance, inserted_coin); } else { System.out.println("Invalid selection, please enter a valid coin value."); } } return balance; }
2
public boolean isNewCharacterOpen() { HUD hud = null; for (int i = (huds.size() - 1); i >= 0; i--) { hud = huds.get(i); if (hud.getName().equals("ScreenNewCharacter")) { return hud.getShouldRender(); } } return false; }
2
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!DOCTYPE html>\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"); out.write(" <title>User Page</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write(" <h1>Register</h1>\n"); out.write(" "); if (_jspx_meth_c_import_0(_jspx_page_context)) return; out.write("\n"); out.write(" <form action=\"UserRegister.do\" method=\"post\" onsubmit=\"return checkNaN(this.price)\">\n"); out.write(" <ul>\n"); out.write(" <li>ID :<input name=\"id\" value=\"\"/></li>\n"); out.write(" <li>password :<input name=\"password\" value=\"\"/></li>\n"); out.write(" <li><input type=\"submit\" value=\"register\"/><input type=\"reset\" value=\"Abort\"/></li>\n"); out.write(" </ul>\n"); out.write(" </form>\n"); out.write(" </body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } }
6
public static String entreeNonVide(String inviteDeChamp){ String retour = ""; Scanner sc = new Scanner(System.in); while(retour.isEmpty()){ System.out.print(inviteDeChamp); retour = sc.nextLine(); if(retour.isEmpty()) System.out.println("Le champ ne peut être vide, recommencez."); } return retour.trim(); }
2