text
stringlengths
14
410k
label
int32
0
9
static String getDataSource() { Properties props = new Properties(); try { props.load(new InputStreamReader(new FileInputStream("pos.properties"), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (FileNotFoundException e) { throw new RuntimeException("jarファイルと同じディレクトリに pos.properties を配置してください。"); } catch (IOException e) { throw new RuntimeException(e); } return props.getProperty("datasource"); }
3
public ArrayList<T> levelOrdertoArray(LBT<T> t) { ArrayList<T> list; list = new ArrayList<>(); int height=t.height(); for(int i=0;i<Math.pow(2, height)-2;i++){ list.add(null); } int i = 0; ArrayQueue<BinaryTreeNode<T>> q = new ArrayQueue<>(); BinaryTreeNode<T> tt = t.root; list.add(0,t.root.element); while (tt != null) { if(list.get(i)!=null){ // put t's children on queue if (tt.leftChild != null) { q.put(tt.leftChild); list.set(2 * i + 1, tt.leftChild.element); } if (tt.rightChild != null) { q.put(tt.rightChild); list.set(2 * i + 2, tt.rightChild.element); } // get next node to visit tt = (BinaryTreeNode<T>) q.remove(); } i++; } return list; }
5
public static boolean combineObject(SynchronizedBlock synBlock, StructuredBlock last) { /* Is there another expression? */ if (!(last.outer instanceof SequentialBlock)) return false; SequentialBlock sequBlock = (SequentialBlock) last.outer; if (!(sequBlock.subBlocks[0] instanceof InstructionBlock)) return false; InstructionBlock ib = (InstructionBlock) sequBlock.subBlocks[0]; if (!(ib.getInstruction() instanceof StoreInstruction)) return false; StoreInstruction assign = (StoreInstruction) ib.getInstruction(); if (!(assign.getLValue() instanceof LocalStoreOperator)) return false; LocalStoreOperator lvalue = (LocalStoreOperator) assign.getLValue(); if (lvalue.getLocalInfo() != synBlock.local.getLocalInfo() || assign.getSubExpressions()[1] == null) return false; synBlock.object = assign.getSubExpressions()[1]; synBlock.moveDefinitions(last.outer, last); last.replace(last.outer); return true; }
6
private String calc(String input) { //Person 2 put your implementation here Random r = new Random(); char[] str = input.toCharArray(); char temp; int rIndex; for(int i = 0; i < input.length(); i++){ temp = str[i]; rIndex = r.nextInt(input.length()); str[i] = str[rIndex]; str[rIndex] = temp; } String resString = ""; for(char c: str){ resString = resString + c; } return resString; //TODO }
2
public void setInstances(Instances inst) { m_Instances = inst; String [] attribNames = new String [m_Instances.numAttributes()]; for (int i = 0; i < attribNames.length; i++) { String type = ""; switch (m_Instances.attribute(i).type()) { case Attribute.NOMINAL: type = "(Nom) "; break; case Attribute.NUMERIC: type = "(Num) "; break; case Attribute.STRING: type = "(Str) "; break; case Attribute.DATE: type = "(Dat) "; break; case Attribute.RELATIONAL: type = "(Rel) "; break; default: type = "(???) "; } attribNames[i] = type + m_Instances.attribute(i).name(); } m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames)); if (attribNames.length > 0) { if (inst.classIndex() == -1) m_ClassCombo.setSelectedIndex(attribNames.length - 1); else m_ClassCombo.setSelectedIndex(inst.classIndex()); m_ClassCombo.setEnabled(true); m_StartBut.setEnabled(m_RunThread == null); m_StopBut.setEnabled(m_RunThread != null); } else { m_StartBut.setEnabled(false); m_StopBut.setEnabled(false); } }
8
@Override public void update(long delta) { double timeFactor = (delta) / Main.targetFrameDuration; System.out.println(timeFactor); // SPACE DOWN if (Input.keyDown(32)) { spaceDown = true; progressSpeed += 0.05 * timeFactor; } else { if (spaceDown && releaseListener != null) { releaseListener.jump(progress); } spaceDown = false; progressSpeed = 1; progress *= Math.pow(0.8, timeFactor); } progress += progressSpeed * timeFactor; if (progress < 0) progress = 0; if (progress > width) progress = width; }
5
public static void main(String[] args) throws IOException { Thread threads[] = new Thread[10]; Thread.State status[] = new Thread.State[10]; for(int i = 0; i <10; i++){ threads[i] = new Thread(new Calculator(i)); if(i%2 == 0){ threads[i].setPriority(Thread.MAX_PRIORITY); }else{ threads[i].setPriority(Thread.MIN_PRIORITY); } threads[i].setName("Thread " + i); } try( FileWriter file = new FileWriter(".\\log.txt"); PrintWriter pw = new PrintWriter(file); ){ for(int i = 0; i < 10; i++){ pw.println("Main : Status of Thread " + i + " : " + threads[i].getState()); status[i] = threads[i].getState(); } for(int i = 0; i < 10; i++){ threads[i].start(); } boolean finish = false; while(!finish){ for(int i =0; i < 10; i++){ if(threads[i].getState() != status[i]){ writeThreadInfo(pw, threads[i], status[i]); status[i] = threads[i].getState(); } } finish = true; for(int i = 0; i < 10; i++){ finish = finish && (threads[i].getState() == State.TERMINATED); } } } }
9
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Triple)) return false; Triple triple = (Triple) o; if (first != null ? !first.equals(triple.first) : triple.first != null) return false; return !(second != null ? !second.equals(triple.second) : triple.second != null) && !(third != null ? !third.equals(triple.third) : triple.third != null); }
7
private void etsiSiirrot() { paivitaTiedot(); for (int i = 0; i < 10; i++) { //etsii lailliset x-sijainnit Muodostelma muod = putoava.kloonaa(); if (muod.getMuoto() == Muoto.nelio) { // nelio-muoto aina samanlainen, ts. sillä ei ole kiertoja siirraMuodostelma(muod, i); laskeSiirto(muod, 0); } else if (muod.getMuoto() == Muoto.S || muod.getMuoto() == Muoto.peiliS) { // näillä muodoilla vain kaksi eri orientaatiota siirraMuodostelma(muod, i); laskeSiirto(muod, 0); muod.putoa(); muod.kierra(); siirraMuodostelma(muod, i); laskeSiirto(muod, 1); } else if (muod.getMuoto() == Muoto.I) { // I-muodolla myös vain kaksi orientaatiota siirraMuodostelma(muod, i); laskeSiirto(muod, 0); muod.putoa(); muod.putoa(); muod.kierra(); siirraMuodostelma(muod, i); laskeSiirto(muod, 1); } else { // lopuilla muodoilla kaikki neljä orientaatiota siirraMuodostelma(muod, i); laskeSiirto(muod, 0); muod.putoa(); for (int j = 1; j < 4; j++) { if (i == 9) { siirraMuodostelma(muod, i - 1); } if (i == 0) { siirraMuodostelma(muod, i + 1); } muod.kierra(); siirraMuodostelma(muod, i); laskeSiirto(muod, j); } } } }
8
private void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); loadLevel.render(render); player.render(render); for (int i = 0; i < pixels.length; i++) { pixels[i] = render.pixels[i]; } Menu.score = score; Menu.renderMap(g, image, time, currentLevel); if (gameStatus.equals("menu")) { Menu.renderMenu(g, player.hasMoved(), WIDTH); } else if(gameStatus.equals("ingame")) { if (Player.won == 1) { Menu.renderIngameLost(g, WIDTH); } if (Player.won == 2) { Menu.renderIngameWin(g, WIDTH, currentLevel); } } else if(gameStatus.equals("credits")) { Menu.renderCredits(g, WIDTH, HEIGHT); } g.dispose(); bs.show(); }
7
@SuppressWarnings("static-access") @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerInteract (PlayerInteractEntityEvent event) { Entity interactedEntity = event.getRightClicked(); if (interactedEntity instanceof Wolf) { Wolf hound = (Wolf) interactedEntity; if (MMHellhound.isHellhound(hound)) { event.setCancelled(true); } } }
2
public void checkOval(){ if (ovalHeight <= HEIGHT && ovalWidth <= getWidth()){ resetOval(); } }
2
private void initWinchPositionsList() { try{ RecentLaunchSelections recent = RecentLaunchSelections.getRecentLaunchSelections(); winchPositions = DatabaseUtilities.DatabaseDataObjectUtilities.getWinchPositions(); List<WinchPosition> recentWinchPositions = recent.getRecentWinchPosition(); for (int i = 0; i < recentWinchPositions.size(); i++){ winchPositions.add(0, recentWinchPositions.get(i)); } }catch(SQLException e) { } catch (ClassNotFoundException ex) { Logger.getLogger(AirfieldPanel.class.getName()).log(Level.SEVERE, null, ex); } }
3
public void actionPerformed(ActionEvent e){ if(e.getSource() == brushPicker){ for(int ind = 0; ind < brushes.length; ind++){ //Set Editing Brush type if(brushPicker.getSelectedItem() == brushes[ind]){command = 401; bruush = ind+1; setGonzo(bruush); toggleControls(); break;} } fireucEvent(); command = 404; fireucEvent(); } for(int indy = 0; indy< orients.length; indy++){ //Set Brush Orientation if(e.getSource() == orients[indy]){ brushdir = indy; command = 402;fireucEvent(); break; } } }
5
public void addData(TagAndURISubModel dictionary) throws Exception { boolean alreadyExists = false; for (int i = 0; i < datas.size() && !alreadyExists; i++) { TagAndURISubModel item = datas.get(i); if (item.getTag().equals(dictionary.getTag()) && item.getURI().equals(dictionary.getURI())) { alreadyExists = true; } } if (alreadyExists) { throw new Exception("Le fichier " + dictionary.getTag() + " est déjà dans la base."); } else { datas.add(dictionary); support.firePropertyChange(propertyName, null, datas.toArray(new TagAndURISubModel[0])); } }
5
public boolean insert(String s, State data) { TrieNode current = root; if (s.length() == 0) //For an empty character { if (!current.isMarker()) { current.setMarker(true); } else { return false; } } for (int i = 0; i < s.length(); i++) { TrieNode child = current.subNode(s.charAt(i)); if (child != null) { current = child; } else { current.getChild().add(new TrieNode(s.charAt(i))); current = current.subNode(s.charAt(i)); } // Set marker to indicate end of the word if (i == s.length() - 1) { if (!current.isMarker()) { current.setMarker(true); current.setData(data); current.setName(s); current.setIDnode(count); //data.setID(count); count++; return true; } else { return false; } } } return false; }
6
private boolean checkForStraight(List<Card> hand) { List<Card> newHand = new ArrayList<Card>(); int s = hand.size()-1; int initValue = 0; boolean flag = true; do { flag = true; initValue = hand.get(s).getValue(); for (int i = 0 ; i < 5 ; i++) { if (hand.get(s-(i+1)).getValue() == initValue) { i--; continue;//if the previous card is the same value, skip } else if (hand.get(s-(i+1)).getValue() != initValue-1) { flag = false;//not a straight if previous card is not value - 1 break; } newHand.add(hand.get(s-(i+1))); Collections.sort(newHand, new Card.CardComparator());//making sure it's sorted initValue--; } s--;//start at each position in the hand that gives 5 cards in the check } while(!flag && s < 4); hand = newHand; return flag; }
5
public void emitEvent(EventObject event) { int eventType = ((Integer) event.getSource()).intValue(); if (eventType == DataPortListener.DATA_PORT_FINISH_READING) { System.out.println("Data port read event...\nData port read:"); ByteBuffer bb = dataPort.getReadBuffer(); // debugging BufferUtil.debug(bb); dataPort.readyReadReadBufufer(); byte[] barr = null; if (bb.hasArray() && bb.hasRemaining()) { barr = bb.array(); bb.clear(); dataPort.setReadBufferExpectWrite(true); } if (null != barr) { List<XmlTag> tags = parser.parser(barr); for (XmlTag tag : tags) { Package pkg = new Package(this); pkg.setXmlTag(tag); try { PackageQueue.getPackageQ().put(pkg); } catch (Exception e) { System.out.println(e); } } } } else if (eventType == DataPortListener.DATA_PORT_FINISH_WRITING) { } else if (eventType == DataPortListener.DATA_PORT_OPENED) { } else if (eventType == DataPortListener.DATA_PORT_CLOSED) { } }
9
private boolean touchHorizontally(Line first, Line second) { Point fEnd = first.getEnd(); Point sEnd = second.getEnd(); if (fEnd.getY() != sEnd.getY()) { return false; } Point fStart = first.getStart(); Point sStart = second.getStart(); if ((fStart.getX() <= sStart.getX() && fEnd.getX() >= sStart.getX() && fEnd.distanceTo(sStart) != 0) || fStart.getX() >= sStart.getX() && fEnd.getX() <= sEnd.getX() && sEnd.distanceTo(fStart) != 0) { return true; } return false; }
7
private String getDescription() { String desc = "@Update(" + this.getParsedSql().getOriginalExpression() + ")"; if(this.isReturnId()) { desc = desc + ",@ReturnId()"; } return desc; }
1
@Override public ArrayList<Suunta> suunnat() { ArrayList<Suunta> suunnat = new ArrayList<Suunta>(); if(palikat[0].sijainti().y() != vertailupiste.y()) suunnat.add(palikat[0].sijainti().y() > vertailupiste.y() ? Suunta.ALAS : Suunta.YLOS); if(palikat[0].sijainti().x() != vertailupiste.x()) suunnat.add(palikat[0].sijainti().x() < vertailupiste.x() ? Suunta.VASEN : Suunta.OIKEA); return suunnat; }
4
protected void cellDrawn(mxICanvas canvas, mxCellState state) { if (isFoldingEnabled() && canvas instanceof mxGraphics2DCanvas) { mxIGraphModel model = graph.getModel(); mxGraphics2DCanvas g2c = (mxGraphics2DCanvas) canvas; Graphics2D g2 = g2c.getGraphics(); // Draws the collapse/expand icons boolean isEdge = model.isEdge(state.getCell()); if (state.getCell() != graph.getCurrentRoot() && (model.isVertex(state.getCell()) || isEdge)) { ImageIcon icon = getFoldingIcon(state); if (icon != null) { Rectangle bounds = getFoldingIconBounds(state, icon); g2.drawImage(icon.getImage(), bounds.x, bounds.y, bounds.width, bounds.height, this); } } } }
6
protected void receiveQueryData(IRemoteCallObjectMetaData meta, IRemoteCallObjectData data, final long callObjectId) throws Exception { ExceptionList excl = new ExceptionList(); try { //..execute handler Object result = null; if (!meta.getExecCommand().equalsIgnoreCase(ISession.KEEPALIVE_MESSAGE)) { setLastAccessTime(new Date().getTime()); ConnectionInfo info = new ConnectionInfo( this.idConnection, this.getCreationTime(), this.getIdleTimeout(), this.getLastAccessTime(), this.getLastReceiptTime(), this.getRemoteIP(), this.getRemotePort()); result = fireReceiveQueryEvent( new ReceiveQueryEvent(this, info, meta.getExecCommand(), data.getData())); } //..header for response to the server meta = new RemoteCallObjectMetaData(null, RemoteCallObjectType.Respond); //..put result data.setData(result); } catch (Exception exc) { excl.add(exc); //..header for exception to the server meta = new RemoteCallObjectMetaData(null, RemoteCallObjectType.RespondError); //..put exception data.setData(exc); } //..send data, but if catch exception, try send this exception try { send(SerializeUtils.serializeToBytes(new RemoteCallObject(callObjectId, meta, data))); } catch (Exception e){ excl.add(e); byte responseData[]; meta = new RemoteCallObjectMetaData(null, RemoteCallObjectType.RespondError); //..put exception data.setData(excl); //..create and serialize object response responseData = SerializeUtils.serializeToBytes(new RemoteCallObject(callObjectId, meta, data)); //..send exception data send(responseData); } //..rethrow first exception in the list if (excl.size() > 0) throw new Exception(excl.get(0)); }
4
public Map<String, String> returnMap() throws Exception { Map<String, String> map = new HashMap<String,String>(); BufferedReader reader = new BufferedReader(new FileReader(this.fileName)); String line; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } if (line.charAt(0) == '#') { continue; } int delimPosition = line.indexOf('='); String key = line.substring(0, delimPosition).trim(); String value = line.substring(delimPosition + 1).trim(); map.put(key, value); } reader.close(); return map; }
3
static private boolean jj_3R_12() { if (jj_scan_token(SEND)) return true; if (jj_3R_18()) return true; if (jj_scan_token(TO)) return true; Token xsp; xsp = jj_scanpos; if (jj_3_17()) { jj_scanpos = xsp; if (jj_3_18()) return true; } return false; }
5
public static String query(int table_id, String str, int start_index, int max_fetch) throws Exception { JSONObject result = new JSONObject(); JSONArray entry_list = new JSONArray(); Map temp = new LinkedHashMap(); int max_count,count; int maxCount[] = new int[6]; Connection Con = global.getConnection(); switch (table_id) { case 0:{ entry_list.clear(); start_index/=6; max_fetch/=6; /* Course */ maxCount[0] = Course.getResultCount(Con, str); /* Student */ maxCount[1] = Student.getResultCount(Con, str); /* Instructor */ maxCount[2] = Instructor.getResultCount(Con, str); /* Work */ maxCount[3] = Work.getResultCount(Con, str); /* Project */ maxCount[4] = Project.getResultCount(Con, str); /* Post */ maxCount[5] = Post.getResultCount(Con, str); /* entry_list = Course.Query(Con,str,start_index,max_fetch); entry_list.addAll(Student.Query(Con,str,start_index,max_fetch)); entry_list.addAll(Instructor.Query(Con,str,start_index,max_fetch)); entry_list.addAll(Work.Query(Con,str,start_index,max_fetch)); entry_list.addAll(Project.Query(Con,str,start_index,max_fetch)); entry_list.addAll(Post.Query(Con,str,start_index,max_fetch)); */ max_count = 0; SortedSet<Pair> set = new TreeSet<Pair>(); for(int ii=0; ii<6; ii++) { set.add(new Pair(ii, maxCount[ii])); max_count += maxCount[ii]; } addResults(entry_list, set, Con, str, start_index, max_fetch); break; } case 1: { entry_list = Course.Query(Con,str,start_index,max_fetch); max_count = Course.getResultCount(Con, str); break; } case 2: { entry_list = Student.Query(Con,str,start_index,max_fetch); max_count = Student.getResultCount(Con, str); break; } case 3: { entry_list = Instructor.Query(Con,str,start_index,max_fetch); max_count = Instructor.getResultCount(Con, str); break; } case 4: { entry_list = Project.Query(Con,str,start_index,max_fetch); max_count = Project.getResultCount(Con, str); break; } case 5: { entry_list = Work.Query(Con,str,start_index,max_fetch); max_count = Work.getResultCount(Con, str); break; } case 6: { entry_list = Post.Query(Con,str,start_index,max_fetch); max_count = Post.getResultCount(Con, str); break; } default: { max_count =0; break; } } count = entry_list.size(); temp.put("max_count", max_count); temp.put("count",count); temp.put("entries", entry_list); result.put("results", temp); Con.close(); return result.toJSONString(); }
8
public MultiPolygon add(Polygon polygon) { coordinates.add(polygon.getCoordinates()); return this; }
0
public static void main(String[] args) { //TODO find out what the hell this thing was supposed to do /* String path = jPapaya.class.getProtectionDomain().getCodeSource().getLocation().getPath(); try { String decodedPath = URLDecoder.decode(path, "UTF-8"); System.out.println(path); System.out.println(decodedPath); System.exit(-1); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } */ System.out.println("Start"); int botCount = Integer.parseInt(Config.getInstance().get("BotCount")); int loopSleepTime = Integer.parseInt(Config.getInstance().get( "LoopSleep")); ArrayList<Bot> threadList = new ArrayList<Bot>(); try { for (int i = 0; i < botCount; i++) { threadList.add(new Bot(Datamodel.getInstance(), UrlGetter .getInstance().get())); } while (true) { for (Bot bot : threadList) { if (bot.isAlive() == false) { bot.restart(UrlGetter.getInstance().get()); } } /* * Pazuza przed kolejn rundą */ try { Thread.sleep(loopSleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); } }
6
final private boolean jj_3R_121() { if (jj_scan_token(FOR)) return true; if (jj_scan_token(LPAREN)) return true; Token xsp; xsp = jj_scanpos; if (jj_3R_192()) jj_scanpos = xsp; if (jj_scan_token(SEMICOLON)) return true; xsp = jj_scanpos; if (jj_3R_193()) jj_scanpos = xsp; if (jj_scan_token(SEMICOLON)) return true; xsp = jj_scanpos; if (jj_3R_194()) jj_scanpos = xsp; if (jj_scan_token(RPAREN)) return true; if (jj_3R_47()) return true; return false; }
9
public static int fromDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else throw new IllegalArgumentException("Invalid hexadecimal digit: " + c); }
6
public boolean insert(DatabaseTableData data, Class<?> layout, boolean instant) { Field[] publicFields = layout.getFields(); String fields = "("; String values = "VALUES ("; for (Field field : publicFields) { fields += field.getName() + ","; try { if (field.getType().isEnum()) { values += "\"" + ((Enum<?>)field.get(data)).ordinal() + "\","; } values += "\"" + field.get(data).toString() + "\","; } catch (Exception e) { e.printStackTrace(); } } fields = fields.substring(0, fields.length() - 1) + ") "; values = values.substring(0, values.length() - 1) + ");"; String insertQuery = "INSERT INTO `" + m_name + "` " + fields + values; m_database.query(insertQuery, instant); return true; }
5
public void menuPrincipal() { mostrar("Bienvenido al sistema de administracion remota de Bases de datos"); linea(); mostrar("Por favor, ingrese el nombre de la base de datos a consultar"); String db = entrada.nextLine(); while (db == null) { mostrar("No se ha ingresado el nombre de la base de datos, intentelo nuevamente"); db = entrada.nextLine(); } mostrar("Por favor, ingrese la consulta a realizar a la base de datos"); String query = entrada.nextLine(); while (!chequearQuery(query)) { mostrar("Consulta invalida, por favor intentelo de nuevo"); query = entrada.nextLine(); } mostrar("Datos obtenidos con exito, espere por favor..."); controlador.enviarDatos(db, query); }
2
@Override public boolean equals(Object o) { if (o instanceof Vector2D) { Vector2D p = (Vector2D) o; double xD = p.x - x, yD = p.y - y; return xD == 0 && yD == 0; } return false; }
2
@Override public void ParseIn(Connection Main, Server Environment) { int X = Main.DecodeInt(); int Y = Main.DecodeInt(); Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom); if (Room == null) { return; } Main.Data.RoomUser.IdleTime = 0; if (X != Main.Data.RoomUser.X && Y != Main.Data.RoomUser.Y) { Main.Data.RoomUser.SetRot(Rotation.Calculate(Main.Data.RoomUser.X, Main.Data.RoomUser.Y, X, Y)); } }
3
public static Picture readPictureFromTriangles(String path) throws Exception { List<Triangle> triangles = new ArrayList<Triangle>(); File file = new File(path); System.out.println(file.getAbsolutePath()); // File file = new File("/home/arto/Popup-course/triangulation/testi.tr"); Scanner reader = new Scanner(file); String size = reader.nextLine(); String[] dimension = size.split("\\s+"); int width = Integer.parseInt(dimension[0]); int height = Integer.parseInt(dimension[1]); int numOfTriangles = Integer.parseInt(reader.nextLine()); while (reader.hasNextLine()) { String line = reader.nextLine().trim(); if (line.isEmpty()) { continue; } String[] parts = line.split("\\s+"); int[] rgba = new int[]{Integer.parseInt(parts[6]), Integer.parseInt(parts[7]), Integer.parseInt(parts[8]), Integer.parseInt(parts[9])}; Triangle t = new Triangle(rgba, new Point(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])), new Point(Integer.parseInt(parts[2]), Integer.parseInt(parts[3])), new Point(Integer.parseInt(parts[4]), Integer.parseInt(parts[5]))); triangles.add(t); } assert triangles.size() == numOfTriangles; Picture p = new Picture(width, height); for (Triangle t : triangles) { p.addTriangle(t); } return p; }
3
private void generatePositions() { // rozměry int X = lab.length + 1; int Y = lab[0].length() + 1; int tryNr = 0; int x, y; // pozice hráče a nepřátel pos = new Coord[enemies + 1]; // nejprve pozice hráče na volném políčku int x0 = 0, y0 = 0; while (pos[0] == null) { x0 = (int)(Math.random() * (X - 2)) + 1; y0 = (int)(Math.random() * (Y - 2)) + 1; if (lab[x0].charAt(y0) == '.') pos[0] = new Coord(x0 * 10, y0 * 10); } // pozice nepřátel a cíle na volných políčcích dostatečně daleko // od hráče for (int i = 1; i < enemies + 1; i++) { tryNr = 0; while (pos[i] == null) { x = (int)(Math.random() * (X - 2)) + 1; y = (int)(Math.random() * (Y - 2)) + 1; if (lab[x].charAt(y) == '.' && (Math.pow(x - x0, 2) + Math.pow(y - y0, 2) > 80 || tryNr > 10)) // nebudeme zkoušet věčně { pos[i] = new Coord(x * 10, y * 10); lab[x].setCharAt(y, 'o'); } tryNr++; } } // zkopírování pozic do záloh oldPos = new Coord[enemies + 1]; for (int i = 0; i <= enemies; i++) oldPos[i] = new Coord(pos[i].row, pos[i].col); }
8
public static boolean isSkeletonWarriorGold ( SkeletonWarriorGold MMSkeletonWarriorGold) { if (MMSkeletonWarriorGold instanceof Skeleton) { Skeleton SkeletonWarriorGold = (Skeleton) MMSkeletonWarriorGold; if (SkeletonWarriorGold.getEquipment().getChestplate() .equals(new ItemStack(315))) { return true; } } return false; }
2
public void updateLists() { // Listen clearen boxitems.clear(); lastname.clear(); prename.clear(); table.clear(); // L�schdaten einlesen zeile = 0; BufferedReader br = null; String line; try { System.out.println("*** Auschecken-Tabllen-Daten werden geladen ***"); br = new BufferedReader(new FileReader("tableData.txt")); while ((line = br.readLine()) != null && !line.isEmpty()) { System.out.println(line); // String aufsplitten String[] arr = line.split(";"); // Tabelleninhalt wird in Liste gespeichert table.add(line); // Als n�chste die Index der Gastnummer bekommen, aus der // Table-liste l�schen und Datei neu abspeichern! boxitems.add(arr[0]); if (arr[4] != null && arr[5] != null) { lastname.add(arr[4]); prename.add(arr[5]); } zeile++; } } catch (IOException e) { e.printStackTrace(); } // Statistiken laden BufferedReader stats_br = null; String stats; try { System.out.println("*** Auschecken-Statistiken werden geladen ***"); stats_br = new BufferedReader(new FileReader("statistics.txt")); while ((stats = stats_br.readLine()) != null) { System.out.println(stats); String[] arr = stats.split(";"); came = Integer.parseInt(arr[0]); there = Integer.parseInt(arr[1]); away = Integer.parseInt(arr[2]); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } comboBoxGuestnumber.setModel(new DefaultComboBoxModel<>(new String[] {"Bitte ausw\u00E4hlen"})); for (String item : boxitems) { comboBoxGuestnumber.addItem(item); } }
8
public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; }
4
private void parentRank() { // TODO Auto-generated method stub long totalFitness = 0; for(Chromasome chro : population){ totalFitness += chro.getFitness(); int index = 0; while(true){ if(index + 1 > parents.size()){ rouletteTable.add(chro); break; } else if(chro.getFitness() < parents.get(index).getFitness()){ rouletteTable.add(index, chro); break; } index++; } } mu = totalFitness / populationSize; long varHold = 0; //long selection = (long)(rand.nextDouble() * totalFitness); for(Chromasome chro : population){ //int numSlots = (int)((double)(chro.fitness)/(double)(totalFitness) * 100); double num = (chro.getFitness() - mu); varHold += (num * num); /*for(int i = 0; i < numSlots; i++){ rouletteTable.add(chro); }*/ } int toAdd = 2; long selectionRange = 1; while(toAdd <= populationSize){ selectionRange += toAdd; toAdd ++; } Variance = varHold / populationSize; stdDeviation = Math.sqrt(Variance); while(parents.size() < populationSize){ long selection = (long)(rand.nextDouble() * selectionRange); int index = 0; while(selection > 0){ Chromasome selected = rouletteTable.get(index); selection -= index + 1; if(selection<=0){ parents.add(selected); } index++; } //parents.add(rouletteTable.get(rand.nextInt(rouletteTable.size()))); } }
9
public void changeDirection() { int x= 0, y= 0, d= 0, posX, posY; boolean wall = true; //Get current position on the board posX = this.getHLocation(); posY = this.getVLocation(); while(wall) //Are you going to hit a wall? { d = randDirection(); if(d == 0) //North { x = 0; y = -1; } if(d == 1) //East { x = 1; y = 0; } if(d == 2) //South { x = 0; y = 1; } if(d == 3) //West { x = -1; y = 0; } wall = Collision.hitWall(posX+x, posY+y); } if(Collision.hitHero(posX+x, posY+y)) //Are you going to hit the hero? Window.gameLost(); //If the position BadGuy is on has energy, then set the number to 1 if(Window.getEnergy(posX, posY) == 1) Window.setMapPosition(posX, posY, 2); else Window.setMapPosition(posX, posY, 3); Window.setMapPosition((posX+x), (posY+y), 4); this.setLocation((posX+x), (posY+y)); }
7
public boolean isEmptySpace() { for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { if(entries[i][j].getText().equals("")) { System.out.println("isEmptySpace() returned false at i: " + i + " j: " + j); return false; } } } return true; }
3
private void pivot(int p, int q) { // everything but row p and column q for (int i = 0; i <= M; i++) for (int j = 0; j <= M + N; j++) if (i != p && j != q) a[i][j] -= a[p][j] * a[i][q] / a[p][q]; // zero out column q for (int i = 0; i <= M; i++) if (i != p) a[i][q] = 0.0; // scale row p for (int j = 0; j <= M + N; j++) if (j != q) a[p][j] /= a[p][q]; a[p][q] = 1.0; }
8
private void checkCollisionBar(OperateShape ball, OperateShape bar) { boolean isBallXBarRange = ball.getX() >= bar.getX() - bar.getWidthFromCenter() && ball.getX() <= bar.getX() + bar.getWidthFromCenter(); boolean isBallYBarRange = ball.getY() >= bar.getY() - bar.getHeightFromCenter() && ball.getY() <= bar.getY() + bar.getHeightFromCenter(); boolean isBallBarRangeLeft = ball.getX() < (((bar.getWidthFromCenter() * 2) / 3) + (bar.getX() - bar.getWidthFromCenter())); boolean isBallBarRangeCenter = ball.getX() >= (((bar.getWidthFromCenter() * 2) / 3) + (bar.getX() - bar.getWidthFromCenter())); boolean isBallBarRangeRight = ball.getX() >= ((((bar.getWidthFromCenter() * 2) / 3) * 2) + (bar.getX() - bar.getWidthFromCenter())); if (isBallXBarRange && isBallYBarRange) { if (isBallBarRangeLeft) { EdgeType edgeType = EdgeType.LEFTSIDEOFTHEBAR; event.setEdgeType(edgeType); isCollision = true; } else if (isBallBarRangeCenter && !isBallBarRangeRight) { EdgeType edgeType = EdgeType.MIDDLEOFTHEBAR; event.setEdgeType(edgeType); isCollision = true; } else if (isBallBarRangeRight) { EdgeType edgeType = EdgeType.RIGHTSIDEOFTHEBAR; event.setEdgeType(edgeType); isCollision = true; } } }
8
public static void main(String[] args) { /* * if the user has not specified just a URL then * we don't even want to try to handle the request */ if (args.length != 1) usage(); /* * We setup a URL object to parse the hostname and */ URL url = new URL(args[0]); /* * we setup a socket so we can communicate with a server, and * an http client that will handle the connections */ Socket socket; HttpClient httpClient = null; /* * now we construct an http client so we can talk to the server */ try { socket = new Socket(url.getHostname(), url.getPortNumber()); httpClient = new HttpClient(socket); } catch (IOException ex) { System.err.println(ex.getMessage()); usage(); } /* * first we have to get the original url */ String response = null; try { assert httpClient != null; response = httpClient.send(new HttpRequest(new URL(url.getFullPath()))); } catch (IOException ex) { System.err.println(ex.getMessage()); usage(); } /* * now we construct an htmlBody object so we can * manipulate the links */ HtmlBody htmlBody = new HtmlBody(response); /* * now we specify a URL prefix to make printing easier */ String urlPrefix = "http://" + url.getHostname() + url.getPath() + "/"; /* * while we still have more links we want to print the * status of the links */ for (HtmlLink htmlLink : htmlBody) { HttpResponse httpResponse = null; URL currentURL = htmlLink.getURL(); if (currentURL.getHostname().equals("")) { /* * we create an http client so we can request the next url * and we formulate the http client response after sending a * request for the httpClient */ try { httpClient = new HttpClient(new Socket(url.getHostname(), url.getPortNumber())); httpResponse = new HttpResponse(httpClient.send(new HttpRequest(new URL(url.getPath() + "/" + currentURL.getFullPath())))); } catch (IOException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedHttpException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } assert httpResponse != null; if (httpResponse.getStatusCode().equals(HttpStatusCodes.HTTPSTATUSOK)) System.out.println(urlPrefix + currentURL.getFullPath() + " ACTIVE " + httpResponse.getLastModified()); else if (httpResponse.getStatusCode().equals(HttpStatusCodes.HTTPSTATUSNOTFOUND)) System.out.println(urlPrefix + currentURL.getFullPath() + " INACTIVE "); } } }
9
public void setCost(int cost) { this.cost = cost; }
0
private void checkCollision(double x, double y) { int leftTile = (int) getBounds(x, y).getMinX() >> 4; int rightTile = (int) (getBounds(x, y).getMaxX() - 1) >> 4; int topTile = (int) getBounds(x, y).getMinY() >> 4; int bottomTile = (int) (getBounds(x, y).getMaxY() - 1) >> 4; topLeft = level.getTile(leftTile, topTile).isSolid(); topRight = level.getTile(rightTile, topTile).isSolid(); bottomLeft = level.getTile(leftTile, bottomTile).isSolid(); bottomRight = level.getTile(rightTile, bottomTile).isSolid(); }
0
private void displayHelp(String helpType) { String helpText = null; switch (helpType) { case HelpMenuView.OBJECTIVE: helpText = "\t The objective of this game is to try and find \n\n" + "\tthe match for each cards by memorizing them"; break; case HelpMenuView.PLAYER_ONE: helpText = "\t You have 115 points.\n\n" +"\tYour points is substructed when you make a move\n\n" +"\tTry to finish the game with just few moves"; break; case HelpMenuView.PLAYER_TWO: helpText = "\t You compete against the computer. The one that\n\n" +"\thas the most matches at the nd of the game wins!\n\n"; break; } StringBuilder dividerLine = new StringBuilder(80); for (int i = 0; i < 80; i++) { dividerLine.insert(i, '~'); } System.out.println("\t" + dividerLine.toString()); System.out.println(helpText); System.out.println("\t" + dividerLine.toString()); }
4
public void bind(SocketAddress address, IoHandler handler, IoServiceConfig config) throws IOException { if (handler == null) throw new NullPointerException("handler"); if (config == null) { config = getDefaultConfig(); } if (address != null && !(address instanceof InetSocketAddress)) throw new IllegalArgumentException("Unexpected address type: " + address.getClass()); RegistrationRequest request = new RegistrationRequest(address, handler, config); synchronized (lock) { startupWorker(); registerQueue.add(request); selector.wakeup(); } synchronized (request) { while (!request.done) { try { request.wait(); } catch (InterruptedException e) { throw new RuntimeIOException(e); } } } if (request.exception != null) { throw (IOException) new IOException("Failed to bind") .initCause(request.exception); } }
7
protected Transition initTransition(State from, State to) { return new MooreTransition(from, to, ""); }
0
@Override public Object clone() throws CloneNotSupportedException { Student1 student1 = (Student1)super.clone(); student1.setT1((teacher)student1.getT1().clone()); return student1; }
0
private void planForAgent(Agent agent) { TaskDispenser td = agent.td; Node node = agent.node; // Remove completed task from queue if (agent.request != null) { if (agent.request.requestBox.atField == agent.request.requestGoal) { agent.request = null; // System.err.println("Completed request"); } } if (agent.taskQueue != null && agent.taskQueue.size() > 0 && (agent.taskQueue.peek().commandQueue == null || agent.taskQueue.peek().commandQueue.size() == 0)) { if (agent.taskQueue.peek() instanceof DockTask) { DockTask t = (DockTask) agent.taskQueue.peek(); t.box.reserved = false; t.moveBoxTo.reserved = false; } agent.taskQueue.poll(); } // If agent has no tasks, try to find a task if (agent.taskQueue.size() == 0 ) { // System.err.println("agentId " + agent.getId()); agent.taskQueue.clear(); if(agent.td.agents.size() == 1){ agent.taskQueue.addAll(td.newDispenseTaskForAgent(agent)); } else{ agent.taskQueue.addAll(td.simpleDispenseTaskForAgent(agent)); } } }
9
private boolean jj_2_8(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_8(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(7, xla); } }
1
public static ArrayList LexBFS(Graph G, Partition P){ ArrayList sigma = new ArrayList(); System.out.println(); System.out.println("STEP A: Let L be the one element ordered list (V)"); System.out.println("L => (" + P.toString() + ")\n"); System.out.println("STEP B: i 1 to " + G.cardV() + "\n"); int i = 1; System.out.println("P => "+P.toString() + "and |P| = " +P.size() +"\n"); while(i<=G.cardV() || P.size() < G.cardV()){ System.out.println("STEP C"+i+": while there exists a non-singleton class in L = X1 ,...Xn do"); System.out.println("P => "+P.toString() + "and |P| = " +P.size()); System.out.println("------STEP D"+i+": let Xa be the last class made of non-visited vertices"); Classe c1 = P.getClasse(i); Vertex pivot = c1.getVertex(1); pivot.visit(); if (i==G.cardV()) { sigma.add(pivot); break; } System.out.print("------STEP E"+i+": remove vertex "+pivot+" from Xa, with Xa = " + pivot.getClasse()); if(c1.size()>1) { c1.removeVertex(1); Classe c2 = new Classe(); System.out.println(" and add "+pivot+"to just before X'a = "+ pivot.getClasse()); c2.addVertex(pivot); try { P.add(c2,P.indexOf(c1)); System.out.println("------------> X'a = {"+c2.toString()+"} added to the Partition"); } catch (Exception e) { System.out.println("getmessage"); System.out.println(e.getMessage()); System.out.println(" "); System.out.println("toString"); System.out.println(e.toString()); System.out.println(" "); System.out.println("printStackTrace"); e.printStackTrace();; } } if(c1.size()==1) { System.out.println("|Xa| = 1 : DO NOTHING "); } System.out.print("------STEP F"+i+": (x) i, "); sigma.add(pivot); System.out.println("(x) = " + sigma.toString()); System.out.println("------STEP G"+i+": i = i+1"); i++; // Refine Partition System.out.println("STEP H"+i+": REFINE PARTITION"); ArrayList<Vertex> S = G.atIndex(i).getNeighbors(); try { P.pivots(S); } catch (InvalidIndexException e) { System.err.println("P.pivots(S) initialisation error"); e.printStackTrace(); break; } try { P.refine(); } catch (InvalidIndexException e) { System.err.println("P.refine() execution error"); e.printStackTrace(); break; } System.out.println("P =>" + P.toString()); System.out.println(); } System.out.println("15: end while"); System.out.println("P => "+P.toString() + "and |P| = " +P.size()); System.out.println("(x) = " + sigma.toString()); return sigma; }
8
public boolean isSetMethodPresentFor(Field field) { FieldStoreItem item = store.get(FieldStoreItem.createKey(field)); if(item != null) { return item.getSetMethod() != null ? true : false; } return false; }
2
public static String caesarianShift(String code, int shift) { char[] codeline = code.toCharArray(); String result = ""; for(int i = 0; i < codeline.length; i++) { if(codeline[i] >= 'a' && codeline[i] <= 'z') { if(codeline[i] + shift > 'z') codeline[i] = (char) (('a' - 1) + ((codeline[i] + shift) - 'z')); else codeline[i] = (char) (codeline[i] + shift); } else if(codeline[i] >= 'A' && codeline[i] <= 'Z') { if(codeline[i] + shift > 'Z') codeline[i] = (char) (('A' - 1) + ((codeline[i] + shift) - 'Z')); else codeline[i] = (char) (codeline[i] + shift); } } for(char element : codeline) { result += element; } return result.trim(); }
8
public final void addSlider(BufferedImage i) { TButton slider; if (i != null) slider = new TButton(0, 0, i); else slider = new TButton(0, 0, 1, 1, ""); sliders.add(slider); if (i == null) setSliderImage(sliders.size() - 1, i); int sWidth = slider.getWidthI(); int sHeight = slider.getHeightI(); double sliderX = isVertical ? getXD() - (sWidth / 2) : getXD() + (getWidthD() / 2) - (sWidth / 2); double sliderY = isVertical ? getYD() + (getHeightD() / 2) - (sHeight / 2) : getYD() - (sHeight / 2); slider.setLocation(sliderX, sliderY); setDimensions(slider.getWidthD(), slider.getHeightD()); int intWidth = (int) slider.tLabel.font.getStringBounds("0", ((Graphics2D) (new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getGraphics())).getFontRenderContext()).getWidth(); int labelWidth = Math.max(String.valueOf(sliderMin).length() * intWidth, String.valueOf(sliderMax).length() * intWidth); slider.tLabel.setBackgroundColour(Color.WHITE); slider.tLabel.setDimensions(labelWidth, 15); slider.tLabel.fixedSize = true; if (parentComponent != null) slider.setParentComponent(parentComponent); }
5
static long solve(int l, int prev, int acum) { if (l == k) return 1L; if ((s - acum) > (k - l) * n) return 0L; if (dp[l][prev][acum] != -1L) return dp[l][prev][acum]; long ans = 0; int min = Math.min(n, s - acum - (k - l - 1) * n); min = Math.max(min, prev + 1); int max = Math.max(0, (s - acum) - (k - l - 1)); max = Math.min(max, n); for (int i = min; i <= max; i++) ans += solve(l + 1, i, acum + i); return dp[l][prev][acum] = ans; }
4
@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (!(obj instanceof ElectricLocomotive)) return false; ElectricLocomotive other = (ElectricLocomotive) obj; if (batteryVolume != other.batteryVolume) return false; return true; }
4
public void move() { animation = (animation + 1) % 50; x -= left? speed:0; x += right? speed:0; y -= up? speed:0; y += down? speed:0; if ( x < 0 ) x = 0; if ( x + width > 800 ) x = 800 - width; if ( y + height > 600 ) y = 600 - height; if ( y < 400 ) y = 400; if ( isShooting ) shootGuns(); }
9
protected void createTradingInventories() { int rows = 4; int rowsP1 = getAllowedGuiRows(p1); int rowsP2 = getAllowedGuiRows(p2); if (rowsP2 > rowsP1) { if (plugin.yamlHandler.configYaml.getBoolean("use_biggest", true)) rows = rowsP2; else { rows = rowsP1; } } else if (plugin.yamlHandler.configYaml.getBoolean("use_biggest", true)) rows = rowsP1; else { rows = rowsP2; } ItemStack small = new ItemStack(plugin.yamlHandler.configYaml.getInt("economy.items.small.type", 371), plugin.yamlHandler.configYaml.getInt("economy.items.small.amount", 1)); ItemStack medium = new ItemStack(plugin.yamlHandler.configYaml.getInt("economy.items.medium.type", 371), plugin.yamlHandler.configYaml.getInt("economy.items.medium.amount", 1)); ItemStack large = new ItemStack(plugin.yamlHandler.configYaml.getInt("economy.items.large.type", 371), plugin.yamlHandler.configYaml.getInt("economy.items.large.amount", 1)); p1inv = new CurrencyTradeInventory(plugin, p2.getName(), rows, small, medium, large, plugin.yamlHandler.configYaml.getInt("economy.values.small", 1), plugin.yamlHandler.configYaml.getInt("economy.values.medium", 10), plugin.yamlHandler.configYaml.getInt("economy.values.large", 50)); p2inv = new CurrencyTradeInventory(plugin, p1.getName(), rows, small, medium, large, plugin.yamlHandler.configYaml.getInt("economy.values.small", 1), plugin.yamlHandler.configYaml.getInt("economy.values.medium", 10), plugin.yamlHandler.configYaml.getInt("economy.values.large", 50)); }
3
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
0
public void refreshNickname() { AbstractTab tab = InputHandler.getActiveTab(); if (tab != null) { String nick = tab.getServerTab().getConnection().getNick(); setText(nick); } }
1
public void register(Object value) { if (JSONzip.probe) { int integer = find(value); if (integer >= 0) { JSONzip.log("\nDuplicate key " + value); } } if (this.length >= this.capacity) { compact(); } this.list[this.length] = value; this.map.put(value, this.length); this.ticks[this.length] = 1; if (JSONzip.probe) { JSONzip.log("<" + this.length + " " + value + "> "); } this.length += 1; }
4
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddGeocache.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddGeocache.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddGeocache.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddGeocache.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AddGeocache().setVisible(true); } }); }
6
@Override public void actionPerformed(ActionEvent e) { if ( e.getSource() == certifications ) { switchContentPanel(new EditCertificationsPanel()); } else if ( e.getSource() == users ) { switchContentPanel(new EditUsersPanel()); } else if ( e.getSource() == tools ) { switchContentPanel(new EditToolsPanel()); } else if ( e.getSource() == machines ) { switchContentPanel(new EditMachinesPanel()); } else if ( e.getSource() == privileges ) { switchContentPanel(new EditPrivilegesPanel()); } else if ( e.getSource() == generateReport ) { switchContentPanel(new GenerateReportPanel()); } else if ( e.getSource() == viewActiveUsers ) { switchContentPanel(new ViewActiveUsersPanel() ); } else if ( e.getSource() == viewToolsAndMachines ) { switchContentPanel(new ViewToolsAndMachinesPanel()); } else if ( e.getSource() == logInUser ) { switchContentPanel(new LogInAnotherUserPanel()); } JButton current = (JButton) e.getSource(); current.setBackground(orange); }
9
@Override Object writeObject(Map<String, Object> functions, Map<String, Object> model, TemplateMessages messages) throws TemplateException { String o = (String) functionIdentifier.writeObject(functions, model, messages); Object fp = functions.get(o); if (fp == null && functionIdentifier.isRequired()) { throw new TemplateException("No transform function named '%s' is associated with the template for rendering '\u2026:%s' at position '%s'.", o, functionIdentifier.getIdentifier(), functionIdentifier.cursor.getPosition()); } else if (fp == null && functionIdentifier.getIdentifier().endsWith("?")) { throw new TemplateIgnoreRenderingException("Ignore rendering because key '%s' is not present or has null value in the model map at position '%s'.", o, functionIdentifier.cursor.getPosition()); } Object arg = ((input instanceof Element) ? ((Element) input).writeObject(functions, model, messages) : input); if (arg == null) { return null; } List<Object> initParametersProcessed = super.create_parameters_after_process(initParameters, functions, model, messages); if (initParametersProcessed == null) { return null; } if (fp instanceof Transform) { Method method = getApplyMethod((Transform) fp); List<Object> wrap = new ArrayList<Object>(); wrap.add(asArray(initParametersProcessed, null)); Object zz = callMethod(method, o, fp, wrap); method = getApplyMethod((Transform) zz); return super.callMethod(method, o, zz, arg); } else if (fp instanceof Method) { Method method = ((Method) fp); return callMethod(method, o, arg, initParametersProcessed); } else { throw new TemplateException("Invalid transform function type '%s'.", fp.getClass().getCanonicalName()); } }
9
public static void unZiphasDir(String zipFileName, String targetDir) throws Exception { ZipFile zipFile = new ZipFile(zipFileName, "GBK"); Enumeration emu = zipFile.getEntries(); while (emu.hasMoreElements()) { ZipEntry entry = (ZipEntry) emu.nextElement(); if (entry.isDirectory()) { File dir = new File(targetDir + entry.getName()); if (!dir.exists()) { dir.mkdirs(); } continue; } BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); File file = new File(targetDir + entry.getName()); File parent = file.getParentFile(); if (parent != null && (!parent.exists())) { parent.mkdirs(); } FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); byte[] buf = new byte[BUFFER]; int len = 0; while ((len = bis.read(buf, 0, BUFFER)) != -1) { fos.write(buf, 0, len); } bos.flush(); bos.close(); bis.close(); } zipFile.close(); }
6
@Override public void paste(int x, int y, BaseImage img) { if(img.getMode() != mode) { img = img.changeMode(mode); } if (img.getHeight()+y < 0 || y >= this.height) { return; } if (img.getWidth()+x < 0 || x >= this.width) { return; } int imgXOff = 0; int imgYOff = 0; if(x < 0) { imgXOff = Math.abs(x); x=0; } if(y < 0) { imgYOff = Math.abs(y); y=0; } int thisLineWidth = width * getColors(); int imgLineWidth = img.getWidth() * img.getColors(); int imgXOffBytes = imgXOff * img.getColors(); int XBytes = x * getColors(); for(int h=y; h < height; h++) { int imgYPos = h-y+imgYOff; if( imgYPos >= img.getHeight()) { break; } int thisStart = thisLineWidth*h; int imgStart = imgLineWidth*(imgYPos); System.arraycopy(img.getArray(), imgStart+(imgXOffBytes), this.MAP, thisStart+(XBytes), Math.min(imgLineWidth-(imgXOffBytes), thisLineWidth-(XBytes))); } }
9
public void update() { if(autoUpdate == true) { try { Updater updater = new Updater(this, "magic-explosion", this.getFile(), Updater.UpdateType.DEFAULT, false); Updater.UpdateResult result = updater.getResult(); switch(result) { case SUCCESS: System.out.println("[Magic Explosion] " + enableMessage); break; case NO_UPDATE: System.out.println("[Magic Explosion] " + noUpdate); break; case FAIL_DOWNLOAD: System.out.println("[Magic Explosion] " + failDownload); break; case FAIL_DBO: System.out.println("[Magic Explosion] " + failDBO); break; case FAIL_NOVERSION: System.out.println("[Magic Explosion] " + failNoVersion); break; case FAIL_BADSLUG: System.out.println("[Magic Explosion] " + failBadSlug); break; case UPDATE_AVAILABLE: System.out.println("[Magic Explosion] " + UpdateAvailable); break; } } catch (Exception ex) { getLogger().log(Level.SEVERE, "[Magic Explosion] " + ex); } } else { doNothing(); } }
9
private void placePlayers(){ for (Player p : players) { grid.addElement(p); } }
1
private static void inputLoop(GUIConsoleInterface console, String prompt) { Reader input; input = ((JConsole)console).getIn(); BufferedReader bufInput = new BufferedReader(input); String newline = System.getProperty("line.separator"); console.print(prompt, Color.BLUE); String line; try { while ((line = bufInput.readLine()) != null) { console.print("You typed: " + line + newline, Color.ORANGE); // try to sync up the console //System.out.flush(); //System.err.flush(); //Thread.yield(); // this helps a little if (line.equals("quit")) break; console.print(prompt, Color.BLUE); } bufInput.close(); } catch (IOException e) { e.printStackTrace(); } }
3
public static List<String> asArray(final String jsonString) { if (!jsonString.startsWith("[")) { throw new IllegalArgumentException(jsonString + " does not appear to be an array"); } final List<String> elements = new ArrayList<String>(); final StringBuilder sb = new StringBuilder(); int depth = 0; for (int i = 1; i < jsonString.length() - 1; i++) { final char charAt = jsonString.charAt(i); if (openValue(charAt)) { depth++; } else if (closeValue(charAt)) { depth--; } if (depth == 0 && charAt == ',') { // end of element elements.add(sb.toString()); sb.delete(0, sb.length()); } else { sb.append(charAt); } } elements.add(sb.toString()); return elements; }
6
public QryResult evaluateBoolean (RetrievalModel r) throws IOException { // Initialization allocDaaTPtrs (r); QryResult result = new QryResult (); // Sort the arguments so that the shortest lists are first. This // improves the efficiency of exact-match AND without changing // the result. for (int i=0; i<(this.daatPtrs.size()-1); i++) { for (int j=i+1; j<this.daatPtrs.size(); j++) { if (this.daatPtrs.get(i).scoreList.scores.size() > this.daatPtrs.get(j).scoreList.scores.size()) { ScoreList tmpScoreList = this.daatPtrs.get(i).scoreList; this.daatPtrs.get(i).scoreList = this.daatPtrs.get(j).scoreList; this.daatPtrs.get(j).scoreList = tmpScoreList; } } } // Exact-match AND requires that ALL scoreLists contain a // document id. Use the first (shortest) list to control the // search for matches. // Named loops are a little ugly. However, they make it easy // to terminate an outer loop from within an inner loop. // Otherwise it is necessary to use flags, which is also ugly. DaaTPtr ptr0 = this.daatPtrs.get(0); EVALUATEDOCUMENTS: for ( ; ptr0.nextDoc < ptr0.scoreList.scores.size(); ptr0.nextDoc ++) { int ptr0Docid = ptr0.scoreList.getDocid (ptr0.nextDoc); double docScore = 1.0; // Do the other query arguments have the ptr0Docid? for (int j=1; j<this.daatPtrs.size(); j++) { DaaTPtr ptrj = this.daatPtrs.get(j); while (true) { if (ptrj.nextDoc >= ptrj.scoreList.scores.size()) break EVALUATEDOCUMENTS; // No more docs can match else if (ptrj.scoreList.getDocid (ptrj.nextDoc) > ptr0Docid) continue EVALUATEDOCUMENTS; // The ptr0docid can't match. else if (ptrj.scoreList.getDocid (ptrj.nextDoc) < ptr0Docid) ptrj.nextDoc ++; // Not yet at the right doc. else break; // ptrj matches ptr0Docid } } // The ptr0Docid matched all query arguments, so save it. result.docScores.add (ptr0Docid, docScore); } freeDaaTPtrs (); return result; }
9
static private int jjMoveStringLiteralDfa3_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(2, active0); return 3; } switch(curChar) { case 68: return jjMoveStringLiteralDfa4_0(active0, 0x4L); case 69: return jjMoveStringLiteralDfa4_0(active0, 0xf3c0L); case 72: return jjMoveStringLiteralDfa4_0(active0, 0x30L); case 73: return jjMoveStringLiteralDfa4_0(active0, 0xc00L); case 83: return jjMoveStringLiteralDfa4_0(active0, 0x8L); case 101: if ((active0 & 0x2L) != 0L) return jjStartNfaWithStates_0(3, 1, 3); break; default : break; } return jjStartNfa_0(2, active0); }
9
public MazeCell anyIntactNeighbor(MazeCell[] Array){ //Will try to find and choose randomly an intact neighbour with his walls up //Used when creating a labyrinth MazeCell randcell = null; int count = 0; if(Array.length == 0) System.out.println("No neighbours"); for(int i = 0; i < Array.length; i++){ if(Array[i].get_visited() == false) { //if(Array[i] == n) System.out.println("North is here!"); //if(Array[i] == s) System.out.println("South is here!"); //if(Array[i] == w) System.out.println("West is here!"); //if(Array[i] == e) System.out.println("East is here!"); count++; //System.out.println("WHAT IS LOVE\n"); } } if(count == 0){ System.out.println("No intact neighbouring cell to explore :("); return null; } else{ do{ randcell = Array[generator.nextInt(Array.length)]; }while(randcell.get_visited() == true); if(randcell == null) System.out.println("BINGO"); if(randcell == n){ System.out.println("I have chosen the north neighbor!"); System.out.println("I am knocking down my northern wall and his southern wall!"); setWalls(false,east(),west(),south()); randcell.setWalls(randcell.north(),randcell.east(),randcell.west(),false); } else if(randcell == s){ System.out.println("I have chosen my south neighbor!"); System.out.println("I am knocking down my southern wall and his northern wall!"); setWalls(north(),east(),west(),false); randcell.setWalls(false,randcell.east(),randcell.west(),randcell.south()); } else if(randcell == w){ System.out.println("I have chosen my west neighbor!"); System.out.println("I am knocking down my western wall and his eastern wall!"); setWalls(north(),east(),false,south()); randcell.setWalls(randcell.north(),false,randcell.west(),randcell.south()); } else{ System.out.println("I have chosen my east neighbor!"); System.out.println("I am knocking down my eastern wall and his western wall!"); setWalls(north(),false,west(),south()); randcell.setWalls(randcell.north(),randcell.east(),false,randcell.south()); } return randcell; } }
9
private static void testStructures() { out.println("Reading test_structures.sdl"); Tag root = null; try { root=new Tag("root").read(new InputStreamReader( Test.class.getResourceAsStream("test_structures.sdl"), "UTF8")); } catch(IOException ioe) { reportException("Problem reading test_structures.sdl", ioe); } catch(SDLParseException spe) { reportException("Problem parsing test_structures.sdl", spe); } out.println("Successfully read and parsed test_structures.sdl"); try { testTagWriteParse("test_structures.sdl", root); } catch(Throwable e) { reportException(TAG_WRITE_PARSE, e); } try { testEmptyTag(root); } catch(Throwable e) { reportException(EMPTY_TAG, e); } try { testValues(root); } catch(Throwable e) { reportException(VALUES, e); } try { testAttributes(root); } catch(Throwable e) { reportException(ATTRIBUTES, e); } try { testValuesAndAttributes(root); } catch(Throwable e) { reportException(VALUES_AND_ATTRIBUTES, e); } try { testChildren(root); } catch(Throwable e) { reportException(CHILDREN, e); } try { testNamespaces(root); } catch(Throwable e) { reportException(NAMESPACES, e); } }
9
private MyConnection() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (ClassNotFoundException ex) { Logger.getLogger(MyConnection.class.getName()). log(Level.SEVERE, null, ex); } catch (InstantiationException ex) { Logger.getLogger(MyConnection.class.getName()). log(Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { Logger.getLogger(MyConnection.class.getName()). log(Level.SEVERE, null, ex); } try { this.con = DriverManager.getConnection( "jdbc:mysql://192.168.56.21:3306/Biblioteca", "testing", "021$" ); } catch (SQLException ex) { Logger.getLogger(MyConnection.class.getName()). log(Level.SEVERE, null, ex); } }
4
@Override public String toString() { String sz = "Z["; String sy = "Y["; for (E e : controleZ) sz += e.toString() + ", "; for (E e : controleY) sy += e.toString() + ", "; if (sz.length() > 2) sz = sz.substring(0, sz.length() - 2); if (sy.length() > 2) sy = sy.substring(0, sy.length() - 2); return sz + "]\n" + sy + "]"; }
4
public Location(double latitude , double longitude) { this.latitude = String.valueOf(latitude); this.longitude = String.valueOf(longitude); }
0
public int [][] multiResultsetWins(int comparisonColumn, int [][] nonSigWin) throws Exception { int numResultsets = getNumResultsets(); int [][] win = new int [numResultsets][numResultsets]; // int [][] nonSigWin = new int [numResultsets][numResultsets]; for (int i = 0; i < numResultsets; i++) { for (int j = i + 1; j < numResultsets; j++) { System.err.print("Comparing (" + (i + 1) + ") with (" + (j + 1) + ")\r"); System.err.flush(); for (int k = 0; k < getNumDatasets(); k++) { try { PairedStats pairedStats = calculateStatistics(m_DatasetSpecifiers.specifier(k), i, j, comparisonColumn); if (pairedStats.differencesSignificance < 0) { win[i][j]++; } else if (pairedStats.differencesSignificance > 0) { win[j][i]++; } if (pairedStats.differencesStats.mean < 0) { nonSigWin[i][j]++; } else if (pairedStats.differencesStats.mean > 0) { nonSigWin[j][i]++; } } catch (Exception ex) { //ex.printStackTrace(); System.err.println(ex.getMessage()); } } } } return win; }
8
public void setVSBBottomCorner(Component component) { if (mVSBBottomCorner != component) { if (mVSBBottomCorner != null) { remove(mVSBBottomCorner); } mVSBBottomCorner = component; if (mVSBBottomCorner != null) { add(mVSBBottomCorner); } } }
3
protected void setColoredExes() { ArrayList<Excel> temp = PyramidGenerator.generatePyramid4(side, base); coloredEx.clear(); for(Excel ex: temp) { ex.setX(ex.getX() + Dx); ex.setY(ex.getY() + Dy); coloredEx.add(ex); } }
1
public void tick() { if (displayedMessage > -1) { if (!fading) { displayTicks++; if (displayTicks == TICKS_PER_MESSAGE) { displayTicks = 0; fading = true; } } else { fadingTicks++; if (fadingTicks == FADE_TICKS) { fadingTicks = 0; fading = false; displayedMessage--; } } } }
4
public static void h() throws Exception { try { f(); } catch (Exception e) { System.out.println("Inside h(),e.printStackTrace()"); e.printStackTrace(System.out); throw (Exception) e.fillInStackTrace(); } }
1
public boolean canHaveAsBalance(BigInteger balance) { return (balance != null) && (balance.compareTo(this.getCreditLimit()) >= 0); }
1
public boolean equals(Object object) { return object == null || object == this; }
1
public static void main(String[] args) throws Exception { Command command = processArgs(args, "OpusComment"); OpusFile op = new OpusFile(new File(command.inFile)); if (command.command == Commands.List) { listTags(op.getTags()); } else { // Have the new tags added addTags(op.getTags(), command); // Write out List<OpusAudioData> audio = new ArrayList<OpusAudioData>(); OpusAudioData ad; while( (ad = op.getNextAudioPacket()) != null ) { audio.add(ad); } // Now write out op.close(); OpusFile out = new OpusFile( new FileOutputStream(command.outFile), op.getSid(), op.getInfo(), op.getTags() ); for(OpusAudioData oad : audio) { out.writeAudioData(oad); } out.close(); } }
3
public static int min(int depth, int hardMin){ if (depth == MAX_DEPTH) return evaluate(); int bestScore = Integer.MAX_VALUE; long[] tempData = data; String moves = MoveGenerator.getMoves(data); for (int i = 0; i < moves.length(); i += 4){ data = MoveGenerator.makeMove(moves.substring(i, i + 4), tempData); if (data != null){ int tempScore = max(depth + 1, bestScore); if (tempScore <= hardMin) return tempScore; else if (tempScore < bestScore) bestScore = tempScore; } if (!run) break; } if (bestScore == Integer.MAX_VALUE) if (MoveGenerator.underCheck(tempData)) return 200000 - depth; else return 0; return bestScore; }
8
@Override public void onTakeStep() { // _players[0].setBehaviour(_behaviours[1]); Queue<Message> messagelist = getTrainerMessages(); while (!messagelist.isEmpty()){ Message message = messagelist.poll(); if (message instanceof MessageEvent) { MessageEvent messageEvent = (MessageEvent) message; if (messageEvent.getEventText().equals("Portero bloqueado") && _players[4].getBehaviour() != _behaviours[0]) { _players[4].setBehaviour(_behaviours[0]); Goalkeeper secondGoalkeeper = (Goalkeeper) _players[4].getBehaviour(); secondGoalkeeper.setSecondGoalkeeper(true); } else if (messageEvent.getEventText().equals("Portero libre") && _players[4].getBehaviour() != _behaviours[2]) { _players[4].setBehaviour(_behaviours[2]); } else if (messageEvent.getEventText().equals("Delantero bloqueado")) { _players[2].setBehaviour(_behaviours[2]); } } } }
7
private void colorMidTemp(int i, int j, long temp) { for (int k = 0; k < tempRangesMid.length; k++) { if (temp < tempRangesMid[k]) { drawing.setRGB(i, j, colorRangesMid[k]); break; } } }
2
public void startMaze() { for (int i = 0; i < newRun.BOARD_MAX; i++) { for (int j = 0; j < newRun.BOARD_MAX; j++) { board[i][j].setBorder(null); } } }
2
public static Keyword uBaseMeasuresSpecialist(ControlFrame frame, Keyword lastmove) { { Proposition proposition = frame.proposition; Stella_Object mainarg = (proposition.arguments.theArray)[0]; Stella_Object mainargvalue = Logic.argumentBoundTo(mainarg); int value = Stella.NULL_INTEGER; if (mainargvalue == null) { return (Units.KWD_FAILURE); } else { { Surrogate testValue000 = Stella_Object.safePrimaryType(mainargvalue); if (Surrogate.subtypeOfP(testValue000, Units.SGT_UNIT_SUPPORT_DIM_NUMBER_LOGIC_WRAPPER)) { { DimNumberLogicWrapper mainargvalue000 = ((DimNumberLogicWrapper)(mainargvalue)); { GeneralizedSymbol testValue001 = proposition.operator; if (testValue001 == Units.SGT_UNIT_KB_NUMERATOR_MEASURES) { value = ((DimNumber)(mainargvalue000.wrapperValue)).pid.numerator; } else if (testValue001 == Units.SGT_UNIT_KB_DENOMINATOR_MEASURES) { value = ((DimNumber)(mainargvalue000.wrapperValue)).pid.denominator; } else { { OutputStringStream stream000 = OutputStringStream.newOutputStringStream(); stream000.nativeStream.print("`" + testValue001 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace())); } } } return (Units.integerToMeasuresHelper(frame, lastmove, value)); } } else if (Surrogate.subtypeOfP(testValue000, Units.SGT_LOGIC_LOGIC_OBJECT)) { { LogicObject mainargvalue000 = ((LogicObject)(mainargvalue)); { Measure measure = ((Measure)(Units.$INSTANCE_MEASURE_TABLE$.lookup(mainargvalue000))); if (measure != null) { { GeneralizedSymbol testValue002 = proposition.operator; if (testValue002 == Units.SGT_UNIT_KB_NUMERATOR_MEASURES) { value = measure.primeId.numerator; } else if (testValue002 == Units.SGT_UNIT_KB_DENOMINATOR_MEASURES) { value = measure.primeId.denominator; } else { { OutputStringStream stream001 = OutputStringStream.newOutputStringStream(); stream001.nativeStream.print("`" + testValue002 + "' is not a valid case option"); throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace())); } } } return (Units.integerToMeasuresHelper(frame, lastmove, value)); } } return (Units.KWD_FAILURE); } } else { return (Units.KWD_FAILURE); } } } } }
8
public static void main(String args[]){ MyDataImpl obj = new MyDataImpl(); obj.print(""); obj.isNull("abc"); }
0
public void searchFor(String key) throws SQLException { if (dic != null) { this.key = key; if (key.isEmpty()) { ids = dic.getAllIDs(); } else { ids = dic.searchID(key); } for (TableModelListener l : listeners) { l.tableChanged(new TableModelEvent(this)); } } }
3
public void addComment(String path, String... commentLines) { StringBuilder commentstring = new StringBuilder(); String leadingSpaces = ""; for(int n = 0; n < path.length(); n++) { if(path.charAt(n) == '.') { leadingSpaces += " "; } } for(String line : commentLines) { if(!line.isEmpty()) { line = leadingSpaces + "# " + line; } else { line = " "; } if(commentstring.length() > 0) { commentstring.append("\r\n"); } commentstring.append(line); } comments.put(path, commentstring.toString()); }
5
public static void saveProperties(Properties props, File propertyFile, String headerText) { OutputStream out = null; try { out = new FileOutputStream(propertyFile); if (StringUtils.isNotBlank(headerText)) { props.store(out, headerText); } } catch (FileNotFoundException ex) { LOG.warn("Failed to find properties file", ex); } catch (IOException ex) { LOG.warn("Failed to read properties file", ex); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException ex) { LOG.warn("Failed to close properties file", ex); } } } }
5
public ArrayList<ArrayList<String>> partition(String s) { isPal = new boolean[s.length()][s.length()]; this.s = s; isPal[0][0] = true; for (int i = 1; i < s.length(); i++) { isPal[i][i] = true; isPal[i - 1][i] = s.charAt(i - 1) == s.charAt(i); } for (int l = 2; l < s.length(); l++) { for (int i = 0; i + l < s.length(); i++) { isPal[i][i + l] = (s.charAt(i) == s.charAt(i + l)) && isPal[i + 1][i + l - 1]; } } return partitionHelper(s.length()); }
4
public void saveUndefinedStrings(String path){ if(save){ String stringsToSave = getUndefinedStringsForSave(); if(!stringsToSave.equals("")){ Path p = Paths.get(path); Path parent = p.getParent(); boolean exists = Files.exists(p); if(!Files.exists(parent)){ try { Files.createDirectories(parent); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { if(exists) Files.write(p,stringsToSave.getBytes(),StandardOpenOption.APPEND); else Files.write(p,stringsToSave.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
6
@Override protected byte[] load_from_current_position(String frameId, int dataLength, RandomAccessFile openFile) throws IOException { byte[] frameData=super.load_from_current_position(frameId, dataLength, openFile); if(frameData==null) { this.setValue(null); } else if(frameData.length==0) { this.setValue(null); } else { this.rawFrameContents=new ResizingByteBuffer(frameData); } return frameData; }
2