text
stringlengths
14
410k
label
int32
0
9
@Override public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D) g; drawBackground(g2); for(Sprite sprite : sprites) if(sprite.isLayered()) sprite.draw(g2); for(Sprite sprite : sprites) if(!sprite.isLayered())sprite.draw(g2); for(Sprite sprite : sprites) if(sprite.isLayered()) sprite.drawTopLayer(g2); if(gameEnding != Status.PLAYING) drawEnding(g2); }
7
public void visitIfCmpStmt(final IfCmpStmt stmt) { print("if ("); stmt.left().visit(this); print(" "); switch (stmt.comparison()) { case IfStmt.EQ: print("=="); break; case IfStmt.NE: print("!="); break; case IfStmt.GT: print(">"); break; case IfStmt.GE: print(">="); break; case IfStmt.LT: print("<"); break; case IfStmt.LE: print("<="); break; } print(" "); if (stmt.right() != null) { stmt.right().visit(this); } print(") then " + stmt.trueTarget() + " else " + stmt.falseTarget()); println(" caught by " + stmt.catchTargets()); }
7
public static BoardLoader getInstance() { if (instance == null) { instance = new BoardLoader(); } return instance; }
1
public void isPossible(final int[] code) { // Creates a new thread thread = new Thread(new Runnable() { @Override public void run() { // Checks if there are no Inputs. if (mastermind.getRowSize() == 0) { // Accepts the Input code[] as possible mastermind.finishCheck(code, true); return; } try { // Calculates the Secret-Code set. calculatePossibilities(); } catch (InterruptKIException e) { return; } // Checks if code[] is within the Secret-Code set int i; for (Integer[] arrayListElement : arrayList) { if (thread.isInterrupted()) return; for (i = 0; i < codeLength; i++) { if (!SetCode.contains(arrayListElement[i], code[i])) { break; } } if (i == codeLength) { // code[] is within the Secret-Code set // Accepts the Input code[] as possible mastermind.finishCheck(code, true); return; } } // code[] is not within the Secret-Code set // Accepts the Input code[] as not possible mastermind.finishCheck(code, false); } }); thread.start(); }
7
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (! request.getParameterMap().isEmpty()) { List<String> fouten = new ArrayList<>(); BigDecimal van = null; try { van = new BigDecimal(request.getParameter("van")); } catch (NumberFormatException ex) { fouten.add("Van moet een getal zijn"); } BigDecimal tot = null; try { tot = new BigDecimal(request.getParameter("tot")); } catch (NumberFormatException ex) { fouten.add("Tot moet een getal zijn"); } if (fouten.isEmpty()) { int vanafRij = request.getParameter("vanafRij") == null ? 0 : Integer.parseInt(request.getParameter("vanafRij")); request.setAttribute("vanafRij", vanafRij); request.setAttribute("aantalRijen", AANTAL_RIJEN); Iterable<Docent> docenten = docentService.findByWedde(van, tot, vanafRij, AANTAL_RIJEN + 1); if (! docenten.iterator().hasNext()) { fouten.add("Geen docenten gevonden"); } else { List<Docent> docentenList = (List<Docent>) docenten; if (docentenList.size() <= AANTAL_RIJEN) { request.setAttribute("laatstePagina", true); } else { docentenList.remove(AANTAL_RIJEN); } request.setAttribute("docenten", docentenList); } } if (! fouten.isEmpty()) { request.setAttribute("fouten", fouten); } } request.getRequestDispatcher(VIEW).forward(request, response); }
8
public static NamesManager getInstance() { return instance; }
0
private void setCurrentElement(PhysicsElement e) { if (currentElement != null) { currentElement.setReleased(); currentElement = null; } if (e != null) { currentElement = e; currentElement.setSelected(); if (currentElement instanceof Ball) { System.out.println("BallSelected"); } else if (currentElement instanceof FixedHook){ System.out.println("FixedHook Selected"); } else if (currentElement instanceof Spring){ System.out.println("Spring Selected"); } } }
5
public void play() { try { if (clip != null) { new Thread() { public void run() { synchronized (clip) { clip.stop(); clip.setFramePosition(0); clip.start(); } } }.start(); } } catch (Exception e) { System.out.println(e); } }
2
private static String trimSpacesAndNulls(String value) { int len = value.length(); int st = 0; while ((st < len) && (value.charAt(st) == ' ' || value.charAt(st) == 0 )) { st++; } while ((st < len) && (value.charAt(len - 1) == ' ' || value.charAt(len - 1) == 0)) { len--; } return ((st > 0) || (len < value.length())) ? value.substring(st, len) : value; }
8
@Override public void updateInputMap() { System.out.println("Uppdaterar Inputs"); final Action menuUp = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (currentOption > 0) currentOption--; } }; final Action menuDown = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (currentOption < MENU_ITEMS - 1) currentOption++; } }; final Action menuPress = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (currentOption == 0) getListener().stateChanged("GameState"); else if (currentOption == 1) getListener().stateChanged("HelpState"); else if (currentOption == 2) System.exit(0); } }; super.getInputMap().put(KeyStroke.getKeyStroke("UP"), "menuUp"); super.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "menuDown"); super.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "menuPress"); super.getActionMap().put("menuUp", menuUp); super.getActionMap().put("menuDown", menuDown); super.getActionMap().put("menuPress", menuPress); }
5
public final void setOnline(final int cid, final boolean online, final int channel) { boolean bBroadcast = true; for (final MapleGuildCharacter mgc : members) { if (mgc.getId() == cid) { if (mgc.isOnline() && online) { bBroadcast = false; } mgc.setOnline(online); mgc.setChannel((byte) channel); break; } } if (bBroadcast) { broadcast(GuildPacket.guildMemberOnline(id, cid, online), cid); } bDirty = true; // member formation has changed, update notifications }
5
private int hasInfo() { if (strings == null) { return 1; //return this.size(); } int infos = 0; for (String value : strings) { if (value != null && !value.matches(spaceRegex)) infos++; } return infos; }
4
private void dhcpResponse(){ int responseTime = -1; // create request packet LOG.info("create request packet"); byte[] requestMessage = createRequestMessage(); DatagramPacket requestPacket = null; try { requestPacket = new DatagramPacket(requestMessage, requestMessage.length, InetAddress.getByName(BroadcastIp), DHCPServerPort); } catch (UnknownHostException e) { } // send request packet LOG.info("begin to send request message"); long startTime = System.currentTimeMillis(); try { socket.send(requestPacket); socket.setSoTimeout(ResponseTimeOut); } catch (IOException e) { LOG.error("failed to send request message", e); result.setResponseTime(responseTime); result.setError(DetectResult.DHCP_SEND_REQUEST_FAILED, "Failed to send request message"); return; } // wait offer response message LOG.info("wait for DHCP ack message"); boolean gotMessage = false; byte[] ackMessage = new byte[512]; DatagramPacket ackDatagramPacket = new DatagramPacket(ackMessage, ackMessage.length); try { while (!gotMessage){ socket.receive(ackDatagramPacket); // parse received message LOG.info("received a message and parse it"); // charge transition id byte[] byteOfXID = new byte[]{ackMessage[4],ackMessage[5], ackMessage[6],ackMessage[7] }; int offerXid = Util.bytes2Int(byteOfXID); LOG.info("offerXid of the received message is " + offerXid + ", and transactionID is " + transactionID); if (offerXid == transactionID){ DHCPPacket ackDHCPPacket = DHCPPacket.getPacket(ackDatagramPacket); short ackMessageType = ackDHCPPacket.getOption(DHCPConstants.DHO_DHCP_MESSAGE_TYPE).getValue()[0]; if (ackMessageType == DHCPConstants.DHCPACK){ // for ack message result.setError(DetectResult.DETECT_SUCCESS, ""); gotMessage = true; } else if (ackMessageType == DHCPConstants.DHCPNAK){ // for nack message String errorMessage = ackDHCPPacket.getOptionAsString(DHCPConstants.DHO_DHCP_MESSAGE); LOG.error("Receive dhcp nak message, "+errorMessage); result.setError(DetectResult.DHCP_RECV_NACK_RESPONCE, "Receive dhcp nak message, "+errorMessage); gotMessage = true; } else { LOG.error("the received message is not ack or nack message, the message type is "+ackMessageType); } } } responseTime = (int)(System.currentTimeMillis() - startTime); } catch(SocketTimeoutException e){ LOG.error("Time out exception happened while wait for DHCP Ack message", e); result.setError(DetectResult.DHCP_RECV_ACK_TIMEOUT, "Wait for DHCP ACK message timeout"); } catch (IOException e) { LOG.error("IO exception happened while wait for DHCP ACK message", e); result.setError(DetectResult.DHCP_RECV_ACK_FAILED, "Failed to receive DHCP ACK message"); } result.setResponseTime(responseTime); }
8
public static void expandEverything(JoeTree tree) { tree.getRootNode().ExpandAllSubheads(); tree.getDocument().panel.layout.redraw(); return; }
0
public void setActivePanel(final PanelType type) { if (this.frame != null) { this.frame.dispose(); } switch (type) { case START: this.frame = new PlainPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case CLUBS: this.frame = new ClubPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case GYM: this.frame = new GymPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case SPIELTAG: this.frame = new GamePanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case SPIELTAG_DIR: this.frame = new AllGamesPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case TEAMS: this.frame = new TeamPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; case RANKING: this.frame = new RankingPanel(this.sfb, SWT.FILL, CompositeBrick.DEFAULT); break; } this.sfb.setWeights(new int[] {30, 70}); }
8
private final void setLeaves() { if (daughterNodes.size() > 0) for (Node n : daughterNodes) n.setLeaves(); else { isLeaf = true; for (Point p : leafLocations) if (p.x == (int) x && p.y == (int) y) isLeaf = false; if (isLeaf) leafLocations.add(new Point((int) x, (int) y)); } }
6
public MethodHelper(Class<?> clazz) { Method[] methods = clazz.getMethods(); for(Method method : methods) { if(method.getParameterTypes().length != 0) continue; if(method.getReturnType().equals(Void.TYPE)) continue; if(method.getDeclaringClass().equals(Object.class)) continue; String property = keyForMethod0(method); if(property == null) continue; if(_methodToKey.put(method, property) != null){ throw new IllegalArgumentException("Eigenschaft mehrfach definiert: " + property); } if(_keyToMethod.put(property, method) != null){ throw new IllegalArgumentException("Eigenschaft mehrfach definiert: " + property); } try { _methodToDefault.put(method, getDefault0(method)); } catch(IOException e) { throw new IllegalArgumentException("Default-Wert fehlerhaft: " + property, e); } } }
9
private void discoverAndIntimateForClassAnnotations (ClassFile classFile, boolean visible, boolean invisible) { Set<Annotation> annotations = new HashSet<Annotation>(); if (visible) { AnnotationsAttribute visibleA = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag); if (visibleA != null) annotations.addAll(Arrays.asList(visibleA.getAnnotations())); } if (invisible) { AnnotationsAttribute invisibleA = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleA != null) annotations.addAll(Arrays.asList(invisibleA.getAnnotations())); } // now tell listeners for (Annotation annotation : annotations) { // String versions of listeners Set<ClassAnnotationDiscoveryListener> listeners = classAnnotationListeners.get(annotation.getTypeName()); if (null != listeners) { for (ClassAnnotationDiscoveryListener listener : listeners) { listener.discovered(classFile.getName(), annotation.getTypeName()); } } // Object versions of listeners Set<ClassAnnotationObjectDiscoveryListener> olisteners = classAnnotationObjectListeners.get(annotation.getTypeName()); if (null != olisteners) { for (ClassAnnotationObjectDiscoveryListener listener : olisteners) { listener.discovered(classFile, annotation); } } } }
9
private final void copy() { final int length = length(); if (this.tail < this.head) { System.arraycopy(this.content[this.cIdx], this.head, this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE, length - this.tail); System.arraycopy(this.content[this.cIdx], 0, this.content[this.cIdxNext], (length - this.tail) + StringBuilder.PATTERN_SIZE, this.tail); } else if ((this.head > StringBuilder.PATTERN_SIZE) || (this.head < (StringBuilder.PATTERN_SIZE >> 2))) { System.arraycopy(this.content[this.cIdx], this.head, this.content[this.cIdxNext], StringBuilder.PATTERN_SIZE, length); } else { return; } this.head = StringBuilder.PATTERN_SIZE; this.tail = this.head + length; switchBuffer(); }
3
public boolean isOrInheritsFrom(String parent_id) { if(id.equals(parent_id)) return true; else if(parents.size() != 0) { for(int i = 0; i < parents.size(); ++i) { if(parents.get(i).isOrInheritsFrom(parent_id)) return true; } return false; } else return false; }
4
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Answer)) { return false; } Answer other = (Answer) object; if ((this.idAnswer == null && other.idAnswer != null) || (this.idAnswer != null && !this.idAnswer.equals(other.idAnswer))) { return false; } return true; }
5
public void stop() { // Pass on to upstream beans if (m_trainingProvider != null && m_trainingProvider instanceof BeanCommon) { ((BeanCommon)m_trainingProvider).stop(); } if (m_testProvider != null && m_testProvider instanceof BeanCommon) { ((BeanCommon)m_testProvider).stop(); } if (m_dataProvider != null && m_dataProvider instanceof BeanCommon) { ((BeanCommon)m_dataProvider).stop(); } if (m_instanceProvider != null && m_instanceProvider instanceof BeanCommon) { ((BeanCommon)m_instanceProvider).stop(); } }
8
public Set<Vehicule> getVehiculesDisponibles(){ System.out.println("ModeleLocations::getVehiculesDisponibles()") ; Set<Vehicule> vehiculesDisponibles = new HashSet<Vehicule>() ; for(Vehicule vehicule : this.vehicules){ if(vehicule.estDisponible()){ vehiculesDisponibles.add(vehicule) ; } } return vehiculesDisponibles ; }
2
public static void main(String[] args) { int n = scn.nextInt(); int tc = 0; while (n != 0) { // Create the nodes and put them in the map Point[] points = new Point[n + 1]; for (int i = 1; i <= n; i++) { points[i] = new Point(i); } // The starting point int s = scn.nextInt(); // The edges int p = scn.nextInt(); int q = scn.nextInt(); while (p != 0) { points[p].adjacent.add(points[q]); p = scn.nextInt(); q = scn.nextInt(); } // The BFS: List<Point> queue = new LinkedList<Point>(); queue.add(points[s]); while (!queue.isEmpty()) { Point top = queue.remove(0); for (Point next : top.adjacent) { if (next.distance < top.distance + 1) { next.distance = top.distance + 1; queue.add(next); } } } // Gets the maximum level Point finalPoint = points[s]; for (int i = 1; i <= n; i++) { if (points[i].distance > finalPoint.distance) { finalPoint = points[i]; } } System.out .printf( "Case %d: The longest path from %d has length %d, finishing at %d.\n", ++tc, s, finalPoint.distance, finalPoint.id); n = scn.nextInt(); } }
8
public void testToStandardMinutes() { Weeks test = Weeks.weeks(2); Minutes expected = Minutes.minutes(2 * 7 * 24 * 60); assertEquals(expected, test.toStandardMinutes()); try { Weeks.MAX_VALUE.toStandardMinutes(); fail(); } catch (ArithmeticException ex) { // expected } }
1
public static void main(String[] args) { float float_pi = 3.145926535897896F; double double_pi = 3.145926535897896D; System.out.println(float_pi); // 3.1459265 System.out.println(double_pi); // 3.145926535897896 }
0
private void showTrigDialog(Account acc) { Account selectedAccount = acc; TriggerDialog diag = new TriggerDialog(shell, shell.getStyle(), acc, mySelf); shell.setEnabled(false); diag.open(); // Check if the account still exists Boolean deleted = true; for (Account a : FkManager.getInstance().getList()) { if (a.equals(selectedAccount)) { deleted = false; break; } } if (deleted) { btnOpenAccount.setEnabled(false); } txtFilter.setFocus(); shell.setEnabled(true); }
3
@Override public void update(Observable o, Object arg) { String sender = o.getClass().getName(); System.out.println("Board received ["+ arg +"] from ["+ sender +"]"); if (sender.equals("Core.List")) { String message = (String) arg; // On transmet la notification pour les plugins // Seulement si le message ne contient pas (by eventlog) if (message.startsWith("Item added: ") || message.startsWith("Item deleted: ")) { setChanged(); notifyObservers(arg); clearChanged(); } if (message.startsWith("List deleted")) { if (message.contains("(by eventlog)") == false) { setChanged(); notifyObservers(arg); clearChanged(); } lists.remove(o); } } }
5
public static void close(Connection conn,Statement statement,ResultSet reSet){ if(reSet!=null){ try { reSet.close(); } catch (Exception e) { e.printStackTrace(); }finally{ /* 手动将其引用指向null,java的内存清理机制最终会对其清除 */ reSet = null; } } if(statement!=null){ try { statement.close(); } catch (Exception e) { e.printStackTrace(); }finally{ /* 手动将其引用指向null,java的内存清理机制最终会对其清除 */ statement = null; } } if(conn!=null){ try { conn.close(); } catch (Exception e) { e.printStackTrace(); }finally{ /* 手动将其引用指向null,java的内存清理机制最终会对其清除 */ conn = null; } } }
6
synchronized public static void write() { FileOutputStream fosTmp = null; Properties props = new Properties(); try { for(Field fld: EzimConf.class.getFields()) { EzimSetting setting = fld.getAnnotation(EzimSetting.class); if (null == setting) continue; props.setProperty(setting.name(), fld.get(null).toString()); } // output configuration to file fosTmp = new FileOutputStream(EzimConf.getConfFilename()); props.store(fosTmp, "--- ezim Configuration File ---"); } catch(Exception e) { EzimLogger.getInstance().severe(e.getMessage(), e); } finally { try { if (fosTmp != null) { fosTmp.flush(); fosTmp.close(); } } catch(Exception e) { EzimLogger.getInstance().severe(e.getMessage(), e); } } }
5
private boolean isHexDigit() { return current >= '0' && current <= '9' || current >= 'a' && current <= 'f' || current >= 'A' && current <= 'F'; }
5
public Tower getTower(){ int ID = (id-1) / 3; int level = (id-1) % 3 + 1; Tower t; if (ID == 0){ //air t = new AirTower(); }else if (ID == 1){ //water t = new WaterTower(); }else if (ID == 2){ //fire t = new FireTower(); }else{ //earth t = new EarthTower(); } for (int i = 1; i < level; i++){ t.upgrade (true); } return t; }
4
public TileMap createExampleMap() { int size = Configuration.getInstance().getValueAsInt("mapSize"); TileMap tileMap = new TileMap(size, size); FloorCellFactory floorCellFactory = GameFactories.getInstance().getFloorCellFactory(); FloorCell earth = floorCellFactory.getFloorCell("earth"); FloorCell grass = floorCellFactory.getFloorCell("grass"); FloorCell water = floorCellFactory.getFloorCell("water"); // add floor for (Position position : tileMap.area()) { tileMap.setFloor(position, earth); } Area area = new Area(Position.newPosition(12, 17), Position.newPosition(27, 24)); for (Position position : area) { tileMap.setFloor(position, water); } area = new Area(Position.newPosition(40, 35), Position.newPosition(44, 39)); for (Position position : area) { tileMap.setFloor(position, water); } area = new Area(Position.newPosition(10, 11), Position.newPosition(19, 37)); for (Position position : area) { tileMap.setFloor(position, grass); } StaticElementFactory staticElementFactory = GameFactories.getInstance().getStaticElementFactory(); // add group of rocks area = new Area(Position.newPosition(43, 45), Position.newPosition(48, 46)); for (Position position : area) { try { staticElementFactory.newStaticElement("rock", tileMap, position); } catch (PositionException e) { throw new GameError("Positions should be both occupable and valid"); } } // add little forest! area = new Area(Position.newPosition(33, 43), Position.newPosition(41, 45)); for (Position position : area) { try { staticElementFactory.newStaticElement("tree", tileMap, position); } catch (PositionException e) { throw new GameError("Positions should be both occupable and valid"); } } // add that single rock try { Position position = Position.newPosition(1, 2); staticElementFactory.newStaticElement("rock", tileMap, position); } catch (PositionException e) { throw new GameError("Positions should be both occupable and valid"); } return tileMap; }
9
private boolean hasLocalArrayListFlavor(DataFlavor[] arrDfIn) { if (this.dfLocal == null) return false; for(int iCnt = 0; iCnt < arrDfIn.length; iCnt ++) { if (arrDfIn[iCnt].equals(this.dfLocal)) return true; } return false; }
3
public int newLocal(final Type type) { Object t; switch (type.getSort()) { case Type.BOOLEAN: case Type.CHAR: case Type.BYTE: case Type.SHORT: case Type.INT: t = Opcodes.INTEGER; break; case Type.FLOAT: t = Opcodes.FLOAT; break; case Type.LONG: t = Opcodes.LONG; break; case Type.DOUBLE: t = Opcodes.DOUBLE; break; case Type.ARRAY: t = type.getDescriptor(); break; // case Type.OBJECT: default: t = type.getInternalName(); break; } int local = newLocalMapping(type); setLocalType(local, type); setFrameLocal(local, t); changed = true; return local; }
9
public static void main(String[] args) { server1.start(); server2.start(); HB.start(); try {filerdr();} catch (IOException e) {e.printStackTrace();} }
1
private boolean rotation(int rotation) { boolean colision = false; Vecteur<Integer> temp = new Vecteur(); if (rotation != 0) { if (rotation == -1) { courante.rotCW(); } else if (rotation == 1) { courante.rotACW(); } for (Vecteur<Integer> point : courante.getForme().getPoints()) { temp.setValue(point.get(0).intValue() + position.get(0), point.get(1).intValue() + position.get(1)); if (!isEmpty(temp)) { colision = true; break; } } if (colision) { if (rotation == -1) { courante.rotACW(); } else if (rotation == 1) { courante.rotCW(); } } } return colision; }
8
public static void writeMap(Map paramMap, OutputStream paramOutputStream) throws IOException { Dimension localDimension = paramMap.getSize(); ObjectOutputStream localObjectOutputStream; if ((paramOutputStream instanceof ObjectOutput)) localObjectOutputStream = (ObjectOutputStream)paramOutputStream; else localObjectOutputStream = new ObjectOutputStream(paramOutputStream); localObjectOutputStream.writeDouble(0.2D); localObjectOutputStream.writeObject(localDimension); Vector localVector1 = new Vector(); Vector localVector2 = new Vector(); for (int i = 0; i < localDimension.width; i++) for (int j = 0; j < localDimension.height; j++) { MapCell localMapCell1 = paramMap.getCell(i, j); if (!localVector1.contains(localMapCell1.getFilename())) localVector1.addElement(localMapCell1.getFilename()); if (!localVector2.contains(localMapCell1.getCategory())) localVector2.addElement(localMapCell1.getCategory()); } localObjectOutputStream.writeObject(localVector1); localObjectOutputStream.writeObject(localVector2); for (int j = 0; j < localDimension.width; j++) for (int k = 0; k < localDimension.height; k++) { MapCell localMapCell2 = paramMap.getCell(j, k); localObjectOutputStream.writeInt(localVector1.indexOf(localMapCell2.getFilename())); localObjectOutputStream.writeInt(localMapCell2.getImpassibility()); localObjectOutputStream.writeBoolean(localMapCell2.getStorm()); localObjectOutputStream.writeInt(localVector2.indexOf(localMapCell2.getCategory())); } localObjectOutputStream.writeObject("EOF"); }
7
public boolean charsAtEqual(ArrayList<String> file, int index, int num, String[] chars) { for (int j=0; j<chars.length; ++j){ if(charAtEquals(file, index, num, chars[j])) { return true; } // end if } // end for return false; }
2
@Override public boolean click(int mx, int my, boolean click) { if (mouseIn(mx, my)) { if(click) { if(preClick) { if (!clicked) { clicked = true; return true; } clicked = true; return false; } return false; } preClick = true; mouseOver = true; } else { mouseOver = false; preClick = false; } clicked = false; return false; }
4
private void distribute(Msg msg_, int flags_) { // If there are no matching pipes available, simply drop the message. if (matching == 0) { return; } for (int i = 0; i < matching; ++i) if(!write (pipes.get(i), msg_)) --i; // Retry last write because index will have been swapped return; }
3
private int writeBankJumpPointer(BufferedWriter bw, int curAddress, int end) throws Throwable { for(;rom.type[curAddress] == ROM.DATA_BANKJUMPPOINTER && curAddress < end;curAddress+=3) { addLabel(bw, curAddress); String bankString = "$"+Integer.toHexString(rom.data[curAddress] & 0xFF); String dataString = "$"+Integer.toHexString(((rom.data[curAddress+1]&0xFF) | ((rom.data[curAddress+2]&0xFF) << 8)) & 0xFFFF); if(rom.payloadAsBank[curAddress] >= 0) bankString = "BANK("+rom.getLabel(rom.payloadAsBank[curAddress])+")"; if(rom.payloadAsAddress[curAddress+1] >= 0) dataString = rom.getLabel(rom.payloadAsAddress[curAddress+1]); if(rom.comment[curAddress] != null && !rom.comment[curAddress].isEmpty()) dataString += " ; "+rom.comment[curAddress]; bw.write("\tdbw "+bankString+", "+dataString+"\n"); } if (rom.type[curAddress] != ROM.DATA_BYTEARRAY) bw.write("\n"); return curAddress; }
7
public static double calculateCosineSimilarity(Double[] ratingsOne, Double[] ratingsTwo) { double enumerator = 0, denominatorOne = 0, denominatorTwo = 0; for (int i = 0; i < ratingsOne.length; i++) { enumerator += ratingsOne[i] * ratingsTwo[i]; denominatorOne += Math.pow(ratingsOne[i], 2); denominatorTwo += Math.pow(ratingsTwo[i], 2); } if (enumerator == 0 || denominatorOne == 0 || denominatorTwo == 0) { return 0; } else { return (double) enumerator / (Math.sqrt(denominatorOne) * Math.sqrt(denominatorTwo)); } }
4
public void renderSprite(double x, double y, double z, double yOff, int[] pix) { int spriteSize = h / 2; double upco = -0.125; double rightco = 0.125; double forwardco = 0.125; double walkco = 0.0625; double xc = ((x / 2) - (right * rightco)) * 2 + 0.5; double yc = ((y / 2) - (up * upco)) + (walking * walkco) * 2 + yOff; double zc = ((z / 2) - (forward * forwardco)) * 2; double rotX = xc * cosine - zc * sine; double rotY = yc; double rotZ = zc * cosine + xc * sine; double xcenter = 400.0; double ycenter = 300.0; double xpixel = (rotX / rotZ * h + xcenter); double ypixel = (rotY / rotZ * h + ycenter); double xpixelL = xpixel - spriteSize / rotZ; double xpixelR = xpixel + spriteSize / rotZ; double ypixelL = ypixel - spriteSize / rotZ; double ypixelR = ypixel + spriteSize / rotZ; int xpl = (int) xpixelL; int xpr = (int) xpixelR; int ypl = (int) ypixelL; int ypr = (int) ypixelR; if (xpl < 0) { xpl = 0; } if (xpr > w) { xpr = w; } if (ypl < 0) { ypl = 0; } if (ypr > h) { ypr = h; } rotZ *= 8; for (int yp = ypl; yp < ypr; yp++) { double pixelrotY = (yp - ypixelR) / (ypixelL - ypixelR); int ytexture = (int) (8 * pixelrotY); for (int xp = xpl; xp < xpr; xp++) { double pixelrotX = (xp - xpixelR) / (xpixelL - xpixelR); int xtexture = (int) (8 * pixelrotX); if (zbuffer[xp + yp * w] > rotZ) { int col = pix[(xtexture & 7) + (ytexture & 7) * 8]; if (col != 0xffff0000) { pixels[xp + yp * w] = col; zbuffer[xp + yp * w] = rotZ; } } } } }
8
public void updateStatus() { try { if (_leftFrontMotor != null) { SmartDashboard.putNumber("Left Front Jaguar", _leftFrontMotor.getOutputVoltage()); SmartDashboard.putNumber("Left Front Current", _leftFrontMotor.getOutputCurrent()); } SmartDashboard.putNumber("Left Rear Jaguar", _leftRearMotor.getOutputVoltage()); SmartDashboard.putNumber("Left Rear Current", _leftRearMotor.getOutputCurrent()); if (_rightFrontMotor != null) { SmartDashboard.putNumber("Right Front Jaguar", _rightFrontMotor.getOutputVoltage()); SmartDashboard.putNumber("Right Front Current", _rightFrontMotor.getOutputCurrent()); } SmartDashboard.putNumber("Right Rear Jaguar", _rightRearMotor.getOutputVoltage()); SmartDashboard.putNumber("Right Rear Current", _rightRearMotor.getOutputCurrent()); } catch (Exception ex) { System.out.println("DriveTrain::updateStatus - " + ex.getMessage()); } SmartDashboard.putNumber("Ultrasonic", getDistance()); SmartDashboard.putNumber("Gyro", this.gyro.getAngle()); if (SmartDashboard.getBoolean("PrintDebug")) { //Put temporary print statements here, they can be turned off by //the PrintDebug checkbox on SmartDashboard System.out.println("Gyro = " + this.gyro.getAngle()); } }
4
private void encrypt(String pass) { try { byte[] utf8 = pass.getBytes("UTF8"); byte[] enc = this.encrypter.doFinal(utf8); this.setEncryptedPass(Base64.encode(enc)); } catch (javax.crypto.BadPaddingException e) { } catch (IllegalBlockSizeException e) { } catch (UnsupportedEncodingException e) { } }
3
private boolean checkCreditsInputs() { //first check if the user has entered text to be overlaid if (creditText.getText().equals("")) { JOptionPane.showMessageDialog(null, "Please enter text to overlay on video", "Missing Input", JOptionPane.WARNING_MESSAGE); //otherwise if text has been entered, continue with function } else { //check if the text entered has not exceeded the word limit of 30 words String[] words = titleText.getText().split(" "); if (words.length <= 30) { //check if the duration entered by user is in format required String timeFormat = "^\\d{2}:\\d{2}:\\d{2}$"; boolean startMatched = false; //boolean to show if both times entered by user are valid (within length of video) boolean bothValid = true; //first check the start time and if it matches check the finish time Matcher matcher = Pattern.compile(timeFormat).matcher(startCredits.getText()); if (matcher.find()) { startMatched = true; } if (startMatched) { matcher = Pattern.compile(timeFormat).matcher(endCredits.getText()); //if the finish time also matches now go on to check if the times entered are //less than or equal to the length of the video if (matcher.find()) { String[] startTimeSplit = startCredits.getText().split(":"); String[] endTimeSplit = endCredits.getText().split(":"); //calculate the length of the start and end times and make sure they are //less than length of the video and end time is greater than start time long startLength = Long.parseLong(startTimeSplit[0])*3600000 + Long.parseLong(startTimeSplit[1])*60000 + Long.parseLong(startTimeSplit[2])*1000; long endLength = Long.parseLong(endTimeSplit[0])*3600000 + Long.parseLong(endTimeSplit[1])*60000 + Long.parseLong(endTimeSplit[2])*1000; long videoLength = vamix.userInterface.Main.vid.getLength(); if ((startLength > videoLength) || (endLength > videoLength) || (endLength < startLength)) { bothValid = false; } //if both times are valid continue with drawing text on video if (bothValid) { return true; //otherwise display an error message to the user telling them times entered are invalid } else { JOptionPane.showMessageDialog(null, "Please enter a valid start time and end time for displaying the credits text", "Invalid time entered", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Please enter the end time in the format hh:mm:ss", "Invalid time format", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(null, "Please enter the start time in the format hh:mm:ss", "Invalid time format", JOptionPane.ERROR_MESSAGE); } } else { //The word limit of 30 was used because when using the max allowed font size (24), if more than 30 words were entered then the text //on the screen starts to wrap if it is too close to the edge of the video frame. Since this started to get quite messy, a word //limit of 30 words was used. JOptionPane.showMessageDialog(null, "The number of words to print on credits screen is too large, you cannot have more than 30.", "Exceeded word limit", JOptionPane.ERROR_MESSAGE); } } return false; }
9
@Override protected Class<?> loadClass(String name, boolean resolve) { try { if ("fruit.sim.Player".equals(name)) return parent.loadClass(name); else return super.loadClass(name, resolve); } catch (ClassNotFoundException e) { return null; } }
3
public void crearBD(String nombreBD) { try { // Abre la base de datos para realizar operaciones en ella this.bd = SqlJetDb.open(new File(nombreBD), true); this.bd.getOptions().setAutovacuum(true); // Esta función hace que las operaciones a realizar sean de escritura this.bd.beginTransaction(SqlJetTransactionMode.WRITE); this.bd.getOptions().setUserVersion(1); } catch (SqlJetException ex) {Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);} finally { try { // finaliza la transacción y cierra la base de datos this.bd.commit(); this.bd.close(); } catch (SqlJetException ex) {Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);} } }
2
public CGIExecute(String binPath) { cgiApp = new ProcessBuilder(binPath); }
0
private static boolean[] primeBoolArray(int limit) { boolean[] nums = new boolean[limit]; for (int i = 2; i < nums.length; i++) nums[i] = true; int nextPrime = 2; while (nextPrime < nums.length / 2) { int i = nextPrime; for (; i < nums.length; i += nextPrime) nums[i] = false; nums[nextPrime] = true; for (int j = nextPrime + 1; j < nums.length; j++) { if (nums[j] == true) { nextPrime = j; break; } } } return nums; }
5
@Override public void paintRow(Graphics2D g2d, int row, int firstCol, int lastCol, int x, int y, int cellWidth, int rowHeight) { Sequence seq = currentSG.get(row); setCellSize(cellWidth, rowHeight); g2d.setFont(font); List<SequenceAnnotation> orfs = seq.getAnnotationsByType(SimpleORFAnnotator.annotationType); for(SequenceAnnotation orf : orfs) { List<SingleRange> ranges = orf.getRanges(); if (orf.overlaps(firstCol, lastCol )) { for(SingleRange range : ranges) { if (orf.getDirection()==Direction.Forward) { g2d.setColor(forwardColor); g2d.fillRect( (int)(range.min*cellWidth), y+2, (int)(range.max-range.min-1)*cellWidth, rowHeight-2); int x0 = (int)Math.round((range.max-1)*cellWidth); xPoints[0] = x0; xPoints[1] = x0+2*cellWidth; xPoints[2] = x0; yPoints[0] = y+2; yPoints[1] = y+(int)Math.round((double)rowHeight/2.0+1); yPoints[2] = y+rowHeight; g2d.fillPolygon(xPoints, yPoints, 3); for(int i=2; i<(double)rowHeight/2.0; i++) { g2d.setColor(new Color(1.0f, 1.0f, 1.0f, (float)(0.5f*(1.0-2.0f*(float)i/(float)rowHeight)))); g2d.drawLine((int)(range.min*cellWidth), y+i, (int)(range.max*cellWidth+i-4), i+y); } } else { g2d.setColor(backwardColor); g2d.fillRect( (int)((range.min+2)*cellWidth), y+2, (int)(range.max-range.min-2)*cellWidth, rowHeight-2); int[] xPoints = new int[3]; int x0 = (int)Math.round(range.min*cellWidth); xPoints[0] = x0+2*cellWidth; xPoints[1] = x0; xPoints[2] = x0+2*cellWidth; int[] yPoints = new int[3]; yPoints[0] = y+2; yPoints[1] = y+(int)Math.round((double)rowHeight/2.0); yPoints[2] = y+rowHeight; g2d.fillPolygon(xPoints, yPoints, 3); for(int i=2; i<(double)rowHeight/2.0; i++) { g2d.setColor(new Color(1.0f, 1.0f, 1.0f, (float)(0.5f*(1.0-2.0f*(float)i/(float)rowHeight)))); g2d.drawLine((int)(range.min*cellWidth-cellWidth-2*i), y+i, (int)(range.max*cellWidth), i+y); } } } } //If the ORF was visible int firstDrawCol = firstCol - firstCol%hashBlockSize; for(int blockStart=firstDrawCol; blockStart<Math.min(lastCol, seq.length()); blockStart+=hashBlockSize) { drawBaseGroup(g2d, blockStart*cellWidth, y, cellWidth, rowHeight, row, blockStart, seq); } } }
7
private String getText(BufferedReader reader) { String finishedText = ""; String s = ""; StringBuilder sb = new StringBuilder(); while (s != null && !s.contains("<div class=\"csc-textpic-text\">")) { //go to the text passage in the html-code try { s = reader.readLine(); } catch (Exception e) { return null; } } try { while ((s = reader.readLine()) != null && !s.contains("</div>")) { //read all until the end of the text passage if (s.contains("www") | s.contains("<a>") | s.contains("<i>") | s.contains("<td ")) { continue; } s = s.replaceAll("\t", ""); //delete all tabulators s = s.replaceAll("<(\"[^\"]*\"|'[^']*'|[^'\">])*>", ""); //delete all html-tags s = s.replaceAll("&nbsp;", ""); //delete "&nbsp;" s = s.replaceAll(".+[^(. )]$", ""); //delete every codeline that does not conclude with a full stop s = s.replaceAll("„", ""); //delete lower " s = s.replaceAll("“", ""); //delete upper " s = s.replaceAll("&amp;", "&"); //replace amp with & s = s.replaceAll("&quot;", ""); //delete &quot; s = replaceSpecPattern(s, "\\d+\\.", "\\.", "#"); //replace all . in dates s = replaceSpecPattern(s, " [a-zA-Z]{1,3}\\.", "\\.", "#"); //replace all . in abreviations s = replaceSpecPattern(s, "#[a-zA-Z]{1,3}\\.", "\\.", "#"); //replace all . in janky abbreviations s = replaceSpecPattern(s, "Prof\\.", "\\.", "#"); //mark some abbreviations longer than 3 letters s = replaceSpecPattern(s, "Dipl\\.", "\\.", "#"); s = replaceSpecPattern(s, "Angl\\.", "\\.", "#"); s = replaceSpecPattern(s, "bspw\\.", "\\.", "#"); s = replaceSpecPattern(s, "evtl\\.", "\\.", "#"); s = s.trim(); sb.append(s); //append to the stringbuilder } } catch (Exception e) { return null; } finishedText = sb.toString(); //make a string out of the stringbuilder try { reader.close(); } catch (IOException ex) { } return finishedText; }
8
private static void debugInfo() { String cv = "kFold: " + cf.getInt("num.kfold") + (cf.isOn("is.parallel.folds") ? " [Parallel]" : " [Singleton]"); float ratio = (float) cf.getDouble("val.ratio"); int givenN = cf.getInt("num.given.n"); float givenRatio = cf.getFloat("val.given.ratio"); String cvInfo = cf.isOn("is.cross.validation") ? cv : (ratio > 0 ? "ratio: " + ratio : "given: " + (givenN > 0 ? givenN : givenRatio)); String testPath = cf.getPath("dataset.testing"); boolean isTestingFlie = !testPath.equals("-1"); String mode = isTestingFlie ? String.format("Testing:: %s.", Strings.last(testPath, 38)) : cvInfo; if (!Recommender.isRankingPred) { String view = cf.getString("rating.pred.view"); switch (view.toLowerCase()) { case "cold-start": mode += ", " + view; break; case "trust-degree": mode += String.format(", %s [%d, %d]", new Object[] { view, cf.getInt("min.trust.degree"), cf.getInt("max.trust.degree") }); break; case "all": default: break; } } String debugInfo = String.format("Training: %s, %s", Strings.last(cf.getPath("dataset.training"), 38), mode); Logs.info(debugInfo); }
9
public static Matrice createSubMatrix(Matrice matrix, int excluding_row, int excluding_col) { Matrice mat; if(excluding_row==-1) mat = new Matrice(matrix.getNbLines(), matrix.getNbColumns()-1); else if(excluding_col==-1) mat = new Matrice(matrix.getNbLines()-1, matrix.getNbColumns()); else{ mat = new Matrice(matrix.getNbLines()-1, matrix.getNbColumns()-1); } int r = -1; for (int i=0;i<matrix.getNbLines();i++) { if (i==excluding_row) continue; r++; int c = -1; for (int j=0;j<matrix.getNbColumns();j++) { if (j==excluding_col) continue; mat.setValueAt(r, ++c, matrix.getValueAt(i, j)); } } return mat; }
6
public void setPreference(Preference pref) { this.pref = pref; }
0
public void printOverzicht(){ int i = 1; for (Huisdier dier : lijst){ System.out.println("Naam dier" + i + ": " + dier.getNaam()); i ++; } }
1
public static void test3(){ try { InputStream returnStream = null; HttpsURLConnection conn = null; int connectTimeout=15000; int readTimeout=30000; String requestMethod="GET"; String charEncode="utf-8"; String url="https://localhost:8443/ssl/index.jsp?username=10"; System.setProperty("javax.net.debug","ssl"); System.setProperty("javax.net.ssl.keyStore", "G:/temp/cert/20140727/client/client.p12"); System.setProperty("javax.net.ssl.keyStorePassword","123456"); System.setProperty("javax.net.ssl.keyStoreType", "PKCS12"); System.setProperty("javax.net.ssl.trustStore", "G:/temp/cert/20140727/truststore.jks"); System.setProperty("javax.net.ssl.trustStorePassword", "222222"); System.setProperty("javax.net.ssl.truststoreType", "JKS"); URL serverUrl = new URL(null, url, new sun.net.www.protocol.https.Handler()); conn = (HttpsURLConnection) serverUrl.openConnection(); if (connectTimeout != -1) { conn.setConnectTimeout(connectTimeout); } if (readTimeout != -1) { conn.setReadTimeout(readTimeout); } conn.setRequestMethod(requestMethod); conn.setDoOutput(true); conn.connect(); conn.getOutputStream().write("jxgacsr".getBytes(charEncode)); if (conn.getResponseCode() != 200) { returnStream = conn.getErrorStream(); } else { returnStream = conn.getInputStream(); } String returnString = ""; if (returnStream != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(returnStream, "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while((line = br.readLine()) != null) { buffer.append(line); } returnString = buffer.toString(); System.out.println("返回:==》"+returnString); } catch(IOException e) { e.printStackTrace(); } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } }
9
@RequestMapping(value = {"/SucursalesBancarias"}, method = RequestMethod.GET) public void readAll(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse) { try { ObjectMapper jackson = new ObjectMapper(); String json = jackson.writeValueAsString(sucursalBancariaDAO.findAll()); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setContentType("application/json; charset=UTF-8"); noCache(httpServletResponse); httpServletResponse.getWriter().println(json); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
2
@Test public void testProfileCrudUsingCard() throws BeanstreamApiException { String profileId = null; try { Address billing = getTestCardValidAddress(); Card card = getTestCard(); // test create profile ProfileResponse createdProfile = beanstream.profiles() .createProfile(card, billing); profileId = createdProfile.getId(); Assert.assertNotNull( "Test failed because it should create the profile and return a valid id", profileId); // test get profile by id PaymentProfile paymentProfile = beanstream.profiles() .getProfileById(profileId); Assert.assertEquals( "billing address assinged does not matches with the one sent at creation time", paymentProfile.getBilling(), billing); Assert.assertNotNull("Credit card was not in the response", paymentProfile.getCard()); Assert.assertTrue("The default lenguage should be english","en".equals(paymentProfile.getLanguage())); // update the profile to francais paymentProfile.setLanguage("fr"); paymentProfile.setComments("test updating profile sending billing info only"); // update profile beanstream.profiles().updateProfile(paymentProfile); // refresh the updated profile paymentProfile = beanstream.profiles().getProfileById(profileId); Assert.assertEquals("Language was updated to Francais", paymentProfile.getLanguage(), "fr"); // delete the payment profile beanstream.profiles().deleteProfileById(profileId); try { beanstream.profiles().getProfileById(profileId); Assert.fail("This profile was deleted, therefore should throw an exception"); } catch (BeanstreamApiException e) { profileId = null; } } catch (BeanstreamApiException ex) { Assert.fail("Test can not continue, "+ex.getMessage()); } catch (Exception ex) { Assert.fail("unexpected exception occur, test can not continue"); } finally { if (profileId != null) { ProfileResponse response = beanstream.profiles() .deleteProfileById(profileId); } } }
4
private boolean check(FlowNetwork G, int s, int t) { // check that flow is feasible if (!isFeasible(G, s, t)) { System.err.println("Flow is infeasible"); return false; } // check that s is on the source side of min cut and that t is not on // source side if (!inCut(s)) { System.err.println("source " + s + " is not on source side of min cut"); return false; } if (inCut(t)) { System.err.println("sink " + t + " is on source side of min cut"); return false; } // check that value of min cut = value of max flow double mincutValue = 0.0; for (int v = 0; v < G.V(); v++) { for (FlowEdge e : G.adj(v)) { if ((v == e.from()) && inCut(e.from()) && !inCut(e.to())) mincutValue += e.capacity(); } } double EPSILON = 1E-11; if (Math.abs(mincutValue - value) > EPSILON) { System.err.println("Max flow value = " + value + ", min cut value = " + mincutValue); return false; } return true; }
9
public Integer getInf( int field, Boolean net ) { try { switch ( field) { case ALLOCATED: if ( net ) { return (int) (mInflation * mNetAllocated); } else { return (int) (mInflation * mGrossAllocated); } case REVISED: if ( net ) { return (int) (mInflation * mNetRevised); } else { return (int) (mInflation * mGrossRevised); } case USED: if ( net ) { return (int) (mInflation * mNetUsed); } else { return (int) (mInflation * mGrossUsed); } } } catch (Exception e) { return null; } return null; }
7
public int GetSequenceNumber() { return sequence; }
0
@Test public void testBuyDevCard() { //me BuyDevCardRequest request=new BuyDevCardRequest(0); ServerModel aGame=gamesList.get(2); cookie=new CookieParams("Bobby", "bobby", 0, 2); int playerNewCards=aGame.getPlayers().get(0).getNewDevCards().getTotalDevCardCount(); int playerOldCards=aGame.getPlayers().get(0).getOldDevCards().getTotalDevCardCount(); int devCards=aGame.getDeck().getTotalDevCardCount(); try { moves.buyDevCard(request, cookie); if(aGame.getPlayers().get(0).getNewDevCards().getTotalDevCardCount()!=playerNewCards){ assertEquals("Bobby should have a new development card.",playerNewCards+1,aGame.getPlayers().get(0).getNewDevCards().getTotalDevCardCount()); } else{ assertEquals("Bobby should have a new development card.",playerOldCards+1,aGame.getPlayers().get(0).getOldDevCards().getTotalDevCardCount()); } assertEquals("The deck should have one less card.",devCards-1,aGame.getDeck().getTotalDevCardCount()); } catch (InvalidMovesRequest e) { System.out.println(e.getMessage()); } }
2
private void deletePlaylist() { try { int id; System.out.println("Enter id: "); showPlaylists(); id = Keyboard.readInt(); BEPlaylist aPlaylist = new BEPlaylist(id); BLLPlaylist ds = new BLLPlaylist(); ds.deletePlaylist(aPlaylist); } catch (Exception ex) { System.out.println("Could not delete playlist - " + ex.getMessage()); } }
1
public Problem getProblem() { return problem; }
0
public List<Token> postProcess(List<Token> tokens) { if (tokens.size() == 0) { return tokens; } List<Token> newTokens = new ArrayList<Token>(); Token prevToken = null; Rule currentRule = null; outer_loop: for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); if (currentRule != null) { if ((prevToken.end() != token.getStart()) || (!currentRule.contains(token.getMorpheme().getPartOfSpeech()))) { currentRule = null; newTokens.add(prevToken); prevToken = null; } else { merge(prevToken, token, currentRule.getPartOfSpeech()); if (i == tokens.size() - 1) { newTokens.add(prevToken); prevToken = null; } continue; } } for (int j = 0; j < this.rules.size(); j++) { Rule rule = this.rules.get(j); if (rule.contains(token.getMorpheme().getPartOfSpeech())) { currentRule = rule; prevToken = token; continue outer_loop; } } currentRule = null; newTokens.add(token); } if (prevToken != null) { newTokens.add(prevToken); } return newTokens; }
9
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { config = plugin.getConfig(); if (args.length == 1 ){ if (sender instanceof Player) { if (sender.hasPermission("darkcommand.kiss")){ if (commandLabel.equalsIgnoreCase("kiss")){ Player player = (Player) sender; Player target = (Bukkit.getServer().getPlayer(args[0])); if (target != null){ Bukkit.getServer().broadcastMessage(ChatColor.DARK_RED + player.getName() + " has given " + args[0] + " a kiss!"); if(!(config.getBoolean("logcommands") == false)){ int current = config.getInt("Times.Done.Kiss"); int newint = current + 1; config.set("Times.Done.Kiss", newint); plugin.saveConfig(); } }else{ sender.sendMessage("This player either doesn't exist or isn't online!"); } } }else{ sender.sendMessage("You don't have permission for this command!"); } }else{ sender.sendMessage("You must be a player to use this command!"); } }else{ sender.sendMessage("Usage: /kiss <Player_Name>"); } return true; }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractComponent other = (AbstractComponent) obj; if (type != other.type) return false; return true; }
4
@Override public Bean parse(String filename) { Bean newBean = new Bean(); String[] splited; // lecture du fichier texte try { InputStream ips = new FileInputStream(filename); InputStreamReader ipsr = new InputStreamReader(ips); BufferedReader br = new BufferedReader(ipsr); String ligne; int i = 0; while ((ligne = br.readLine()) != null) { if (i == 0) { // On place le premier cract�re du fichier dans la variable // voulu de notre objet newBean.setNbsommet(Integer.parseInt(ligne)); System.out.println("Nombre de sommets : "+ ligne); } if (i == 1) { newBean.setValeurInfini(Integer.parseInt(ligne)); System.out.println("Valeur infini : "+ligne); } if (i == 2) { newBean.setSommetDepart(Integer.parseInt(ligne)); System.out.println("Sommet de départ : "+ligne); } else if (i > 2) { // On d�coupe la ligne par espace pour garder que nos deux // premiers caract�res splited = ligne.split("\\s+"); if (splited[0].equals("$")) { System.out.println("Fin du fichier"); break; } else { System.out.println(splited[0] + " : " + splited[1]); //On ajoute nos sommets dans le bean newBean.addSommetEntree(Integer.parseInt(splited[0])); newBean.addSommetSortie(Integer.parseInt(splited[1])); } } //System.out.println(ligne); i++; } br.close(); } catch (Exception e) { System.out.println(e.toString()); } return newBean; }
7
public static boolean updateList() { // Download mod list if (modList.exists()) { System.out.print("Backing up mod List\n"); try { if (oldList.exists()) { FileManager.deleteFile(FileManager.updaterDir, "/ModList.list.backup", false); } Boolean cc = FileManager.copyFile(modList, new File(modList + ".backup")); if (cc) { System.out.print("Downloading mod List \n"); File NmodList = Download.downloadFromUrl(updateURl, FileManager.updaterDir, "/ModList.list"); if (NmodList != null && NmodList.exists()) { modList = NmodList; System.out.print("Downloaded new list \n"); return true; } else { System.out.print("Failed to get list \n"); System.out.print("restoring old list \n"); oldList.renameTo(new File(FileManager.updaterDir + "/ModList.list")); } } } catch (IOException e) { e.printStackTrace(); } } else { System.out.print("No Mod List"); File NmodList = Download.downloadFromUrl(updateURl, FileManager.updaterDir, "/ModList.list"); if (NmodList != null && NmodList.exists()) { System.out.print("Downloaded Mod list \n"); return true; } } return false; }
8
@Override public void update() { super.update(); if (jumpCounter > 0) { dy = -3; --jumpCounter; } }
1
public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ManagerReport frame = new ManagerReport(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
1
@Override public IEmailKontakt first() throws NoEmailKontaktFoundException { System.out.println("Display first contact..."); Connection con = null; try { con = initDBConnection(); } catch (SQLException e) { e.printStackTrace(); } ResultSet rs = null; Statement stmt = null; EmailKontakt ek = new EmailKontakt(); try { stmt = con.createStatement(); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Kontakt (KontaktId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Vorname VARCHAR(32) NOT NULL, Nachname VARCHAR(32) NOT NULL, Email VARCHAR(64) NOT NULL)"); rs = stmt .executeQuery("SELECT * FROM Kontakt ORDER BY KontaktId ASC LIMIT 1"); if (rs.next()) { ek.setId(rs.getInt("KontaktId")); ek.setVorname(rs.getString("Vorname")); ek.setNachname(rs.getString("Nachname")); ek.setEmail(rs.getString("Email")); } else { throw new NoEmailKontaktFoundException("Kein Kontakt gefunden!"); } } catch (SQLException e) { e.printStackTrace(); } finally { try { stmt.close(); rs.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } return ek; }
4
public ControleurDeuxJoueurs(ModeleDeuxJoueurs _plateaux) { super(_plateaux.getPlateau1()); plateau2 = _plateaux.getPlateau2(); }
0
private void init() { input.clear(); cache.clear(); ; }
0
public IOClient(Socket client, PacketManager pm) { if (client == null) return; this.client = client; this.pm = pm; try { writer = new PrintStream(client.getOutputStream()); //writer.flush(); reader = new DataInputStream(client.getInputStream()); } catch (IOException e) { pm.server.Log("Error"); e.printStackTrace(); } }
2
public void advancePlayer(){ this.currentPlayer.setSelected(false); //if the list is at the end, reset if(list.lastIndexOf(currentPlayer) == list.size() - 1){ this.currentPlayer = list.get(0); //otherwise, go forward } else { this.currentPlayer = list.get(list.lastIndexOf(currentPlayer) + 1); } this.currentPlayer.setSelected(true); }
1
public static String rot13(String input) { StringBuilder output = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c >= 'a' && c <= 'm') { c += 13; } else if (c >= 'A' && c <= 'M') { c += 13; } else if (c >= 'n' && c <= 'z') { c -= 13; } else if (c >= 'N' && c <= 'Z') { c -= 13; } output.append(c); } return output.toString(); }
9
@Test public void testInvokeZeroArgMethod() { Bean bean = new Bean(); Assert.assertNull(ReflectUtils.invokeZeroArgMethod(bean, "voidMethod")); Assert.assertEquals( "public", ReflectUtils.invokeZeroArgMethod(bean, "publicMethod") ); Assert.assertEquals( "protected", ReflectUtils.invokeZeroArgMethod(bean, "protectedMethod") ); Assert.assertEquals( "private", ReflectUtils.invokeZeroArgMethod(bean, "privateMethod") ); Assert.assertEquals( "default", ReflectUtils.invokeZeroArgMethod(bean, "defaultMethod") ); }
0
@Test public void testNextGreaterPowerOf2() { logger.info("nextGreaterPowerOf2"); int[] number = {0, 1,2, 3,4, 5,6,7,8, 9,10,11,12,13,14,15,16,17,18,19,20}; int[] expResult = {1, 1,2, 4,4, 8,8,8,8, 16,16,16,16,16,16,16,16,32,32,32,32}; for (int i = 0; i < number.length; i++) { logger.info("Trying "+i); int result = PowersHelper.nextGreaterPowerOf2(number[i]); assertEquals(expResult[i], result); } }
1
public void getData( Config config ) { try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); saveData.dataInfo.encode = "UTF-8"; saveData.dataInfo.language = "中文"; saveData.dataInfo.crawlDate = dateFormat.format(new Date()); for (ReadConfig.newspaperClass newsInfo : config.newspaperList) { try { saveData.dataInfo.newspaper = newsInfo.newspaper; String trueLink = getTrueLink(newsInfo.startUrl, newsInfo.encode); if (trueLink.contains("58.42.249.98")) //可否写到配置文件,对于特别的起始页 trueLink = trueLink.substring(0, trueLink.lastIndexOf('/') + 1) + "PageArticleIndexGB.htm"; if ( newsInfo.getHomePage != null ) { Document doc = getDocument(trueLink, newsInfo.encode); trueLink = doc.select(newsInfo.getHomePage).select("a[href]").first().attr("abs:href"); } NewsEyeSpider.logger.info("trueLink = " + trueLink); System.out.println("trueLink = " + trueLink); getPageInfo(trueLink, config, newsInfo.encode); }catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); NewsEyeSpider.logger.debug(baos.toString()); } NewsEyeSpider.saveBloomFilter(); } }catch (Exception e) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); NewsEyeSpider.logger.debug(baos.toString()); } }
5
public CoffeescriptPartitionScanner() { IToken commentToken = new Token(COMMENT); IToken stringToken = new Token(STRING); List<IPredicateRule> rules = new ArrayList<IPredicateRule>(); rules.add( new MultiLineRule("###", "###", commentToken) ); rules.add( new EndOfLineRule("#" , commentToken) ); rules.add( new MultiLineRule("\"", "\"" , stringToken, '\\') ); rules.add( new MultiLineRule("\"\"\"", "\"\"\"" , stringToken, '\\') ); IPredicateRule[] result= new IPredicateRule[rules.size()]; rules.toArray( result ); setPredicateRules( result ); }
0
@Test /** * D'après les resultats obtenus, on peut affirmer que l'alea mis en place est correct. */ public void testDistribution() { double[] matrix; int size = 100000; int taille = 8; double[] somme = new double[taille]; for (int i = 0; i < taille; i++) { somme[i] = 0; } for (int i = 0; i < size; i++) { matrix = Alea.createRandomProbabilistDistribution(taille, 1000); for (int j = 0; j < taille; j++) { somme[j] = somme[j] + matrix[j]; } } for (int i = 0; i < taille; i++) { double moyenne = somme[i] / size; System.out.println("En moyenne, " + i + " : " + moyenne); Assert.assertEquals(1./taille, moyenne, 0.02); } }
4
public static void loadUnitPropetries(JsonReader reader, Unit unit) throws IOException { while (reader.peek() == JsonToken.NAME) { String name = reader.nextName(); if ("i".equals(name)) unit.i = reader.nextInt(); else if ("j".equals(name)) unit.j = reader.nextInt(); else if ("health".equals(name)) unit.health = reader.nextInt(); else if ("level".equals(name)) unit.level = reader.nextInt(); else if ("experience".equals(name)) unit.experience = reader.nextInt(); else if ("isMove".equals(name)) unit.isMove = reader.nextBoolean(); else if ("isTurn".equals(name)) unit.isTurn = reader.nextBoolean(); } }
8
public boolean userExists(String userName) { // inserted this pseudo-condition for testing purposes. if(true) return false; checkUserExistsSql = String.format(checkUserExistsSql, userName); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DbConnectionFactory.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(checkUserExistsSql); return rs.next(); } catch (Exception e) { e.printStackTrace(); return false; } finally { if(conn != null) { try { conn.close(); } catch (SQLException e) { //ignore } } if(stmt != null) { try { stmt.close(); } catch (SQLException e) { //ignore } } if(rs != null) { try { rs.close(); } catch (SQLException e) { //ignore } } } }
8
public void play_opponents() { Suit round = null; Submission temp; for ( Player player : players_ ) { if ( !player.is_human() ) { // Player will draw a card from the draw pile if (game_.turn_.draw()) { player.take_card(deck_.draw()); } // Player will pick a card to play if (game_.turn_.play()) { temp = player.pick_card(game_.trump(), round); if (round == null) { round = temp.card.suit(); } game_.take_card(temp); } // Player will discard a card if (game_.turn_.discard()) { // Discard a card } } } }
6
private double innerProduct(Instance instance) { double sum = 0; for (int index : linearParam.getVector().keySet()) { if (instance.getFeatureVector().getVector().containsKey(index)) { sum += instance.getFeatureVector().get(index) * linearParam.get(index); } } return sum; }
2
public Hero getHero(Player p) { return getheroesplugin().getCharacterManager().getHero(p); }
0
public HostMenuPanel(final MainFrame frame) { final JLabel error = new JLabel();; this.addLabel(frame, "PortLabel"); final JTextArea port = new JTextArea(1, 30); this.addComponent(port); ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int portNumber = 0; try { portNumber = Integer.parseInt(port.getText()); } catch (NumberFormatException e2) { showError("Please enter a valid port number") ; return; } int minPort = 1024; int maxPort = (int)Math.pow(2, 16) - 1; if (portNumber <= minPort){ showError("Port number must excede " + minPort) ; return; } if (portNumber > maxPort) { showError("Port number must precede " + maxPort); return; } final Network n; try { n = new Network(null , portNumber ); } catch (ServerNotFoundException e1) { showError("Server not found"); return; } catch (SocketBusyException e1) { showError("Port is being used by another program"); return; } catch (IOException e1) { showError("Connection failed, please try again"); return; } showError("game joined"); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { try { n.close(); } catch (IOException e) { showError("Connection failed, please try again"); return; } } }); JoinGame jg; try { jg = new JoinGame(n, true, frame); } catch (IOException e1) { showError("Connection failed, please try again"); return; } catch (ClassNotFoundException e1) { showError("Connection failed, please try again"); return; } frame.addMenu(jg.getWindow()); } private void showError(String string) { error.setText(string); } }; this.addButton(frame, listener, "CreateButton"); listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.back() ; } }; this.addButton(frame, listener, "BackButton"); this.add(error); }
9
public String getCourseName(int courseId) throws SQLException { NoteDatabaseManager dm = new NoteDatabaseManager(); String s_courseId = Integer.toString(courseId); String sql = "select course_name from course where course_id = " + s_courseId + ";"; ResultSet rs = dm.sqlQuery(sql); String courseName = null; while (rs.next()) { courseName = rs.getString("course_name"); } return courseName; }
1
public static void main(String[] args) throws Exception { new ParallaxMapping().loop(); }
0
public static Double idealGasLaw(Double p, Double v, Double n, Double t) { boolean[] nulls = new boolean[4]; nulls[0] = (p == null); nulls[1] = (v == null); nulls[2] = (n == null); nulls[3] = (t == null); int nullCount = 0; for(int k = 0; k < nulls.length; k++) { if(nulls[k]) nullCount++; } if(nullCount != 1) return null; double result = 0; if(nulls[0]) { // p is unknown result = n*Rlatm*t/v; } else if(nulls[1]) { // v is unknown result = n*Rlatm*t/p; } else if(nulls[2]) { // n is unknown result = p*v/(Rlatm*t); } else if(nulls[3]) { // t is unknown result = p*v/(Rlatm*n); } return result; }
7
public boolean connect(String remoteHost) { try { // Connect to the server m_skServer = new Socket(remoteHost, Utils.PORT_NUM); // Get the output stream object m_stOutput = new ObjectOutputStream(m_skServer.getOutputStream()); m_stInput = new ObjectInputStream(m_skServer.getInputStream()); // BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); MCPMsgDeviceOpcode msg = (MCPMsgDeviceOpcode) m_stInput.readObject(); this.m_deviceOpcode = msg.getDeviceOpcode(); if (m_deviceOpcode == DeviceOpcode.Unkown || ((m_deviceOpcode != DeviceOpcode.CameraArm) && (m_deviceOpcode != DeviceOpcode.RoboticArm))) { LOG.severe("connect() - Can't tell wich device we're currently operating "); } } catch (Exception e) { e.printStackTrace(); LOG.severe("connect() " + e.toString()); return (false); } return (true); }
4
public Main() { }
0
private void jTxtFldFindClienteKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtFldFindClienteKeyTyped // TODO add your handling code here: try { clearClientes(); String sql = "SELECT * FROM clientes WHERE email LIKE ? "; Connection conn = Conexion.GetConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareCall(sql); ps.setString(1, "%" + this.jTxtFldFindCliente.getText() + "%"); cli = ps.executeQuery(); while (cli.next()) { String[] row = {cli.getString(1), cli.getString(2), cli.getString(3), cli.getString(4), cli.getString(5), cli.getString(6)}; tmcli.addRow(row); } jTableClientes.setModel(tmcli); } catch (SQLException e) { JOptionPane.showMessageDialog(this, e.getErrorCode() + ": " + e.getMessage()); } }//GEN-LAST:event_jTxtFldFindClienteKeyTyped
2
public List<String> getMostFrequentWords(List<List<Object>> sequenceList, int highestCount) { List<String> frequentWordList = new ArrayList(); for (int i = 0; i < sequenceList.size(); i++) { List<Object> countAndSequenceList = sequenceList.get(i); //only get the most frequent words from the list if ((Integer) countAndSequenceList.get(0) == highestCount) { String sequence = (String) countAndSequenceList.get(1); //check if sequence is already in list if (!alreadyExistsInList(frequentWordList, sequence)) { frequentWordList.add(sequence); } } } return frequentWordList; }
3
@XmlAttribute public void setId(int id) { this.id = id; }
0
@Override public void warning(SAXParseException e) { System.out.println("SAXParserException Warning: " + e.getMessage()); this.errorOccurred = true; }
0
public final void redirect(String target, String... patterns) { for (String path : patterns) { pages.redirect(target, path); } }
1