text
stringlengths
14
410k
label
int32
0
9
public AcceptedConnectionThread(Socket clientSocket) { this.clientSocket = clientSocket; try { input = new ObjectInputStream(clientSocket.getInputStream()); // the first message sent by the client is its application // address senderAddress = (Address) input.readObject(); if (verbose) { System.out .println("Net: new unicast receiver connection to " + senderAddress); } start(); } catch (Exception e) { e.printStackTrace(); try { clientSocket.close(); } catch (IOException e1) { e1.printStackTrace(); } } }
3
public void motionDetected(double cX, double cY, double area) { if ( this.controller.getCamState().getCamSpeedX() == 0 && this.controller.getCamState().getCamSpeedY() == 0 ) { Point2D motion = this.camPosToAbsPos(new Point2D(cX, cY)); Body closest = null; this.controller.getRoomState().lock(true); for (Body candidate : this.controller.getRoomState().getBodyList()) { Point2D bodyAng = this.cartesianToAbsRad(candidate.getPos()); double bDist = candidate.getDistance(); double angDist = this.angularDistance(motion, bodyAng); // TODO proper size calculation if ( ((angDist / Math.pow(bDist, 0.45)) < 0.2) && ( closest == null || closest.getDistance() > bDist ) ) { closest = candidate; } } if (closest != null) { Point3D motionPos = this.absPosToCartesian(motion, closest.getDistance()); closest.moved(motionPos); this.controller.getGui().printConsole("Bewegung erkannt (" + df.format(motionPos.x) + ", " + df.format(motionPos.y) + ", " + df.format(motionPos.z) + ")", 6); } this.controller.getRoomState().lock(false); } }
7
private static void processClasses(CompiledClass[] entries, int n) throws Exception { Reflection implementor = new Reflection(); ClassPool pool = ClassPool.getDefault(); implementor.start(pool); for (int i = 0; i < n; ++i) { CtClass c = pool.get(entries[i].classname); if (entries[i].metaobject != null || entries[i].classobject != null) { String metaobj, classobj; if (entries[i].metaobject == null) metaobj = "javassist.tools.reflect.Metaobject"; else metaobj = entries[i].metaobject; if (entries[i].classobject == null) classobj = "javassist.tools.reflect.ClassMetaobject"; else classobj = entries[i].classobject; if (!implementor.makeReflective(c, pool.get(metaobj), pool.get(classobj))) System.err.println("Warning: " + c.getName() + " is reflective. It was not changed."); System.err.println(c.getName() + ": " + metaobj + ", " + classobj); } else System.err.println(c.getName() + ": not reflective"); } for (int i = 0; i < n; ++i) { implementor.onLoad(pool, entries[i].classname); pool.get(entries[i].classname).writeFile(); } }
7
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhpposSuppliersEntity that = (PhpposSuppliersEntity) o; if (personId != that.personId) return false; if (accountNumber != null ? !accountNumber.equals(that.accountNumber) : that.accountNumber != null) return false; return true; }
6
public boolean syncOperation(List<String> state) { System.out.println("[TEMP] Sync of " + this); Operation old = getReferenceToOperation().getReferenceToOperation(); switch (old.operation) { case 0: return true; case 1: System.out.println("here"); System.out.println(startPosition + "" + old.startPosition + "" + toEnd + "" + old.toEnd); if (startPosition != old.startPosition || toEnd != old.toEnd) { System.out.println("here again"); Operation delete = new Operation().delete(old.startPosition, old.startPosition + 1); delete.applyOperation(state); new Operation().insert(startPosition, old.data, toEnd).applyOperation(state); } return true; case 2: case 3: default: { System.out.println("syncOperation not working!"); return false; } } }
6
public void lackOfFood(){ if(Variables.foodAmount <= 0){ if(Variables.deerPopulation >= 10){ Variables.deerPopulation = Variables.deerPopulation - 10; Variables.foodAmount = Variables.foodAmount + 10; } if(Variables.deerPopulation < 10){ Variables.foodAmount = Variables.foodAmount + 10; Variables.deerPopulation = Variables.deerPopulation - 2; } if(Variables.offSpring >= 2){ Variables.offSpring = Variables.offSpring - 2; Variables.foodAmount = Variables.foodAmount + 5; } if(Variables.offSpring < 2){ Variables.offSpring = Variables.offSpring - 1; Variables.foodAmount = Variables.foodAmount + 5; } } }
5
boolean isBlockDiag(int y, int x, int yp, int xp) { int dy = yp-y; int dx = xp-x; if(Math.abs(dy)==1 && Math.abs(dx)==1) { if(this.isValidCord(y+dy, x) && this.isValidCord(y, x+dx)) { if(this.isBlocked(y+dy, x) && this.isBlocked(y, x+dx)) return true; } } return false; }
6
public double[] readData(){ if( this.cur < 8) { return null; } double [] ddata = new double[this.cur/8]; long l; int index = 0; for(int i = 0 ; i < ddata.length; i++) { l=data[index++]; l&=0xff; l|=((long)data[index++]<<8); l&=0xffff; l|=((long)data[index++]<<16); l&=0xffffff; l|=((long)data[index++]<<24); l&=0xffffffffl; l|=((long)data[index++]<<32); l&=0xffffffffffl; l|=((long)data[index++]<<40); l&=0xffffffffffffl; l|=((long)data[index++]<<48); l&=0xffffffffffffffl; l|=((long)data[index++]<<56); ddata [i] = Double.longBitsToDouble(l); } int start = this.cur - this.cur%8; for( int i = 0; i < this.cur%8; i++) { this.data[i] = this.data[start+i]; } this.cur %= 8; return ddata; }
3
public boolean save() { if (mDirty) { try { SafeFileUpdater trans = new SafeFileUpdater(); trans.begin(); try { File file = trans.getTransactionFile(mFile); try (OutputStream out = new FileOutputStream(file)) { mPrefs.storeToXML(out, BundleInfo.getDefault().getName()); } } catch (IOException ioe) { trans.abort(); throw ioe; } trans.commit(); mDirty = false; } catch (Exception exception) { return false; } } return true; }
3
public List<Integer> lexicalOrder(int n) { LinkedList<Integer> list = new LinkedList<Integer>(); LinkedList<String> string = new LinkedList<>(); for (int i = 1; i <= n; i++) { string.add(String.valueOf(n)); } string.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { for (int i = 0; i < o1.length() && i < o2.length(); i++) { if (o1.charAt(i) < o2.charAt(i)) return -1; else if (o1.charAt(i) > o2.charAt(i)) return 1; } return o1.length() < o2.length() ? -1 : o1.length() > o2.length() ? 1 : 0; } }); for(int i=0;i<string.size();i++){ list.add(Integer.parseInt(string.get(i))); } return list; }
8
@Override public void rightMultiply(IMatrix other) { for(int i=0;i<4;i++) for(int j=0;j<4;j++) copy[i][j]=0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { copy[i][j]=copy[i][j] + this.get(k, i) * other.get(j, k); } } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this.set(j, i, copy[i][j]); } } }
7
public AirNowDataPoint[][] getDataPoints(){ ArrayList<ArrayList<AirNowDataPoint>> temp = new ArrayList<ArrayList<AirNowDataPoint>>(); for (AirNowDataPoint dataPoint : dataPoints){ String variableType = dataPoint.getParameterCd(); boolean added = false; for (ArrayList<AirNowDataPoint> a : temp){ if (a.get(0).getParameterCd().equals(variableType)){ a.add(dataPoint); added = true; break; } } if (!added){ ArrayList<AirNowDataPoint> a = new ArrayList<AirNowDataPoint>(); a.add(dataPoint); temp.add(a); } } AirNowDataPoint[][] retLists = new AirNowDataPoint[temp.size()][]; for (int i = 0; i < retLists.length; i++){ retLists[i] = temp.get(i).toArray(new AirNowDataPoint[]{}); } return retLists; }
5
public void setData(FeatureCollection fc, String[] data_headers, String[][] data) { this.fc = fc; this.data_headers = data_headers; this.data = data; map_headers = fc.getHeaders(); map_data = fc.getData(map_headers); int found = -1; comboBoxMapLayer.removeAllItems(); for( int i = 0; i < map_headers.length; i++) { comboBoxMapLayer.addItem(map_headers[i]); if( found < 0 && map_headers[i].toUpperCase().trim().indexOf("GEOID") == 0) { found = i; } } found = found < 0 ? 0 : found; comboBoxMapLayer.setSelectedIndex(found); found = -1; comboBoxFileLinkColumn.removeAllItems(); for( int i = 0; i < data_headers.length; i++) { comboBoxFileLinkColumn.addItem(data_headers[i]); if( found < 0 && data_headers[i].toUpperCase().trim().indexOf("GEOID") == 0) { found = i; } } found = found < 0 ? 0 : found; comboBoxFileLinkColumn.setSelectedIndex(found); /* comboBoxFilePopulationColumn.removeAllItems(); for( int i = 0; i < data_headers.length; i++) { comboBoxFilePopulationColumn.addItem(data_headers[i]); } comboBoxFilePopulationColumn.setSelectedIndex(0); */ }
8
public void setPaddingWithZeroes(int length) { if (length < 0) { length = 0; } if (length > _DHCP_MAX_MTU) { throw new IllegalArgumentException("length is > " + _DHCP_MAX_MTU); } this.setPadding(new byte[length]); }
2
public void updateRef(String key, U obj){ if(!this.bloom.isPresent(key)){ throw new IllegalArgumentException("key is not present"); } synchronized(this.cache){ this.cache.put(key, new SoftReference<U>(obj)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream objOut; try{ objOut = new ObjectOutputStream(baos); objOut.writeObject(obj); objOut.close(); this.backing.queue.add(new KeyValAction(key, this.group, baos, KVActions.PUT, obj)); }catch(IOException e){ e.printStackTrace(); } } }
2
private StructuralToken getTokenFromOpenBracket() { String c = getCharAtCurrentLineIndex(); if (c.equals("[")) { linePtr++; if (!lineHasNext()) { //Must be just a | barline return new StructuralToken(StructType.BARLINE); } else { c = getCharAtCurrentLineIndex(); if (c.equals("|")) { linePtr++; //linePtr points to first character after [| if (lineHasNext()) { c = getCharAtCurrentLineIndex(); if (c.equals("|") || c.equals("]")) { throw new IllegalArgumentException("Cannot have three of [ or | or ] in a row"); } } return new StructuralToken(StructType.ENDOFSECTION); } else if (c.equals("1")) { linePtr++; //linePtr points to first character after [1 return new StructuralToken(StructType.FIRSTREPEAT); } else if (c.equals("2")) { linePtr++; //linePtr points to first character after [2 return new StructuralToken(StructType.SECONDREPEAT); } else { //Begin chord return new StructuralToken(StructType.BEGINCHORD); } } } else { throw new IllegalArgumentException("Expected a ["); } }
8
public void visitEnd() { text.add("}\n"); print(pw); pw.flush(); if (cv != null) { cv.visitEnd(); } }
1
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line = ""; while ((line = in.readLine()) != null && line.length() != 0) { int[] nb = readInts(line); int n = nb[0], b = nb[1]; if (n == 0 && b == 0) break; inint(n); for (int i = 0; i < b; i++) { int[] box = readInts(in.readLine()); int u = box[0] - 1, v = box[1] - 1, w = box[2]; d[u][v] = Math.min(d[u][v], -w); d[v][u] = Math.min(d[v][u], w); } floyd(n); boolean cycle = false; for (int i = 0; i < n && !cycle; i++) cycle |= d[i][i] < 0; out.append(cycle ? "Y\n" : "N\n"); } System.out.print(out); }
8
private void bookingTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bookingTableMouseClicked if (bookingTable.getSelectedRow() > -1) { int selectedRowIndex = bookingTable.getSelectedRow(); int bookingId = (Integer) bookingTableModel.getValueAt(selectedRowIndex, 0); Booking currentBooking = null; ArrayList<Booking> bookingList; bookingList = ctr.getBookings(); for (Booking booking : bookingList) { if (booking.getBookingId() == bookingId) { ctr.setCurrentBooking(booking); currentBooking = booking; } } if (currentBooking != null) { bookingDetailModel.clear(); ArrayList<Guest> roomGuestList; roomGuestList = ctr.getBookingDetailsFromDB(currentBooking); // Her henter vi rummets størrelse som bruges til at vise antallet af gæster/roomSize i GUI. ArrayList<Room> roomList; roomList = ctr.getRooms(); int roomSize = 0; for (Room room : roomList) { if (currentBooking.getRoomNo() == room.getRoomNo()) { roomSize = room.getRoomSize(); } } // for (int i = 0; i < roomGuestList.size(); i++) { bookingDetailModel.addElement(roomGuestList.get(i)); } bookingDetailsJList.setModel(bookingDetailModel); bookingIdLabel.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 0)); bookingOwnerLabel.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 1)); roomNoLabel.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 2)); agencyLabel.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 3)); checkInLabel.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 4)); checkOutLabel.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 5)); noOfGuestsInRoomLabel.setText("" + roomGuestList.size() + "/" + roomSize); bookingDetailsJList1.setModel(bookingDetailModel); bookingIdLabel3.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 0)); bookingOwnerLabel3.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 1)); roomNoLabel3.setText("" + (Integer) bookingTableModel.getValueAt(selectedRowIndex, 2)); agencyLabel3.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 3)); checkInLabel3.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 4)); checkOutLabel3.setText("" + bookingTableModel.getValueAt(selectedRowIndex, 5)); noOfGuestsInRoomLabel3.setText("" + roomGuestList.size() + "/" + roomSize); if (evt.getClickCount() == 2) { jTabbedPane.setSelectedIndex(4); } } } }//GEN-LAST:event_bookingTableMouseClicked
8
public void windowClosing(WindowEvent e) { if(Main.gameRunning) { // DataIO.save(Main.currentGame, new File(Main.currentGame.aPath)); } OptionsIO.save(); }
1
private ArrayList<String> getTransitionsInputArray(String commaSeparatedInput) { ArrayList<String> newArray = new ArrayList<String>(commaSeparatedInput.length()); for(int i=0; i<commaSeparatedInput.length(); i++) { String c = commaSeparatedInput.substring(i, i+1); if(c.equals(",")) continue; newArray.add(c); } return newArray; }
2
private void finishMethod() { if (currMethod!=null) { // finish the previous method int codeEnd=tsize; writeShort(0); // no exception table // TODO: add exceptions writeShort(0); // no attributes int currPos=tsize; // Code attribute length tsize=startCodeAttr+2; writeInt(currPos-startCodeAttr-6); tsize=startCodeAttr+6; writeShort(mW); tsize=startCode-2; writeShort(codeEnd-startCode); tsize=currPos; currMethod=null; }; };
1
public void insertUser(UserData userData) throws SQLException { if (conn != null) { User user = new User(userData.id, userData.firstName, userData.lastName, userData.gender, userData.age); user.insert(conn); Availability availability = new Availability(userData.id, userData.email, userData.address); availability.insert(conn); Interest interest = new Interest(userData.id, userData.sport); interest.insert(conn); } }
1
public static boolean isWorldScorePosted(int worldCreated) throws Exception { File f = new File(CFG.DIR, "scores"); try { if (!f.exists()) return false; BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; while ((line = br.readLine()) != null) { if (Integer.parseInt(line) == worldCreated) { br.close(); return true; } } br.close(); } catch (Exception e) { e.printStackTrace(); } return false; }
4
public void entering(final String name, final Object o, String ... args) { info(StringUtils.shortName(o.getClass()) + "-" + o.hashCode() + " entering " + name + "(" + StringUtils.join(args, ", ") + ")"); }
0
public void setBorderType(String s) { if (s == null) throw new IllegalArgumentException("border cannot be null"); type = s; if (s.equals(RAISED_BEVEL_BORDER)) { border = BorderFactory.createRaisedBevelBorder(); } else if (s.equals(LOWERED_BEVEL_BORDER)) { border = BorderFactory.createLoweredBevelBorder(); } else if (s.equals(RAISED_ETCHED_BORDER)) { border = BorderFactory.createEtchedBorder(EtchedBorder.RAISED); } else if (s.equals(LOWERED_ETCHED_BORDER)) { border = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); } else if (s.equals(LINE_BORDER)) { border = BorderFactory.createLineBorder(getForeground(), 2); } else if (s.equals(MATTE_BORDER)) { border = BorderFactory.createMatteBorder(2, 2, 2, 2, TILE_ICON); } else { border = null; } }
7
public void testConstructor_ObjectStringEx3() throws Throwable { try { new TimeOfDay("1970-04-06T10:20:30.040"); fail(); } catch (IllegalArgumentException ex) {} }
1
public void devientLeTairo(Set<Joueur> hjoueur){ int nbsceaux = 0; for(Joueur j : hjoueur){ if(j.getTitre().getNbsceaux() > nbsceaux){ nbsceaux = j.getTitre().getNbsceaux(); this.tairo = j; } } }
2
private void replaceText(Prize prize, XWPFDocument doc) { for (XWPFParagraph p : doc.getParagraphs()) { for (XWPFRun r : p.getRuns()) { String text = r.getText(0); if (text == null) { continue; } if (text.indexOf("CLASSIFICATION") >= 0) { String classification = String.format("%s %s", prize.getCategory(), prize.getClassification()); classification = StringUtils.noBlank(classification); r.setText(classification, 0); } if (text.indexOf("RANK") >= 0) { r.setText(prize.getRank(), 0); } if (text.indexOf("NAME") >= 0) { r.setText(String.format("%s 殿", prize.getName()), 0); } } } }
6
public void letsBound(){ // first: weight the graph! this.weightTheGraph(); // initialize the removed weight this.weight_removed = 0.0; // now, on the factor graph, compute the maximum spanning tree // and save the list of edges to be removed // priority queue, the first has biggest cost // -1 -> MAXIMUM spanning tree PriorityQueue<Edge> edges = this.getEdgeQueue(-1); // Disjoint sets //DisjointSetEdge.initDS(this.getFactorgraph().getEdges()); DisjointSetNode.initDS(this.getFactorgraph().getNodes()); HashSet<Edge> edges_to_keep = new HashSet<Edge>(); HashSet<Edge> edges_to_remove = new HashSet<Edge>(); Edge edge_extracted; // mst with kruskal while (!edges.isEmpty()) { edge_extracted = edges.poll(); if (!DisjointSetNode.sameDS( edge_extracted.getSource(), edge_extracted.getDest() )){ // different sets -> keep the edge edges_to_keep.add(edge_extracted); // join the sets DisjointSetNode.union( edge_extracted.getSource(), edge_extracted.getDest() ); } else { // same sets -> trash the edge if (edges_to_remove.add(edge_extracted)){ try { // the edge is added to the to-be-removed set, so: this.weight_removed += this.getFactorgraph().getWeight(edge_extracted); } catch (WeightNotSetException ex) { // do not add anything // is it possible?! } } } } // kruskal is over if (debug>=3) { String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName(); String dclass = Thread.currentThread().getStackTrace()[2].getClassName(); System.out.println("---------------------------------------"); System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "After Kruskal, these are the edges to be removed:"); for (Edge er : edges_to_remove){ System.out.println("To remove: "+er); } System.out.println("---------------------------------------"); } // do remove the edges this.getFactorgraph().removeEdge(edges_to_remove); if (debug>=3) { String dmethod = Thread.currentThread().getStackTrace()[2].getMethodName(); String dclass = Thread.currentThread().getStackTrace()[2].getClassName(); System.out.println("---------------------------------------"); System.out.println("[class: "+dclass+" method: " + dmethod+ "] " + "After the remove, the factorgraph is:\n"+this.getFactorgraph()); System.out.println("---------------------------------------"); } }
7
public Sequence getReverseComplement(int start, int end) { StringBuilder newStr = new StringBuilder(); for(int i=end-1; i>=start; i--) { char compBase = '-'; char theBase = this.at(i); switch(theBase) { case 'A' : compBase = 'T'; break; case 'G' : compBase = 'C'; break; case 'C' : compBase = 'G'; break; case 'T' : compBase = 'A'; break; case 'U' : compBase = 'A'; break; } newStr.append(compBase); } if (newStr.length() != (end-start)) { System.out.println("New seq length is not the same as the usual sequence length, it's: " + newStr.length()); } return new StringSequence(newStr.toString(), name); }
7
public void updateProfile() { tProfileSummary.setText(Manager.getInstance().getCurrentProfile().getProfileSummary()); DefaultListModel<String> dlm = new DefaultListModel<String>(); for (Disc disc : Manager.getInstance().getCurrentProfile().getDiscs().getDiscs()){ dlm.addElement(disc.getName()); } lDiscs.setModel(dlm); }
1
@Override public boolean register(Game g, Rack r){ super.register(g, r); rack_size = g.rack_size; card_count = g.card_count; //Setup reinforcement learning if (use_reinforcement){ weights = new int[rack_size+1][card_count+1]; //reset stopping criteria done_learning = false; RI_stop.reset(); } return true; }
1
public static String[] resplitArgsWithQuotes(String[] args, int begin, int end) { ArrayList<String> ret = new ArrayList<String>(args.length); StringBuilder line = new StringBuilder(); boolean inStr = false; for (int i = begin; i < end; i++) { String s = args[i]; if (inStr) { boolean isEndStr = s.endsWith("\"") ? !s.endsWith("\\\"") || s.endsWith("\\\\\"") : false; if (isEndStr) { line.append(s.substring(0, s.length() - 1)); ret.add(line.toString()); line.delete(0, line.length()); inStr = false; } else { line.append(s); line.append(' '); } } else if (s.startsWith("\"")) { inStr = true; line.append(s.substring(1)); } else if (!s.equals("")) { ret.add(s); } } return ret.toArray(new String[ret.size()]); }
7
private final boolean pushText(int delimiter) throws IOException { boolean whitespace = true; int next = mPeek0; while (!mEOF && next != delimiter) { // covers EOF, '<', '"' if (delimiter == ' ') { if (next <= ' ' || next == '>') { break; } } if (next == '&') { if (!pushEntity()) { whitespace = false; } } else { if (next > ' ') { whitespace = false; } push(read()); } next = mPeek0; } return whitespace; }
8
private boolean registered() { JLabel regNameLabel = new JLabel("Login name (4-10 chars):", JLabel.RIGHT); JTextField regNameField = new JTextField(20); JLabel regPasswordLabel = new JLabel("Password (2-10 chars):", JLabel.RIGHT); JPasswordField regPasswordField = new JPasswordField(20); JLabel regPasswordLabel2 = new JLabel("Confirm password:", JLabel.RIGHT); JPasswordField regPasswordField2 = new JPasswordField(20); JPanel fieldsPanel = new JPanel(); fieldsPanel.setLayout(new GridLayout(3, 2, 10, 10)); fieldsPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); fieldsPanel.add(regNameLabel); fieldsPanel.add(regNameField); fieldsPanel.add(regPasswordLabel); fieldsPanel.add(regPasswordField); fieldsPanel.add(regPasswordLabel2); fieldsPanel.add(regPasswordField2); final String optionNames[] = {"Register", "Cancel"}; if (JOptionPane.showOptionDialog(thisWindow, fieldsPanel, "New user registration", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionNames, optionNames[0]) != 0) return true; // User pressed "Cancel" String name = regNameField.getText().trim().toLowerCase(); String password = (new String(regPasswordField.getPassword())).trim().toLowerCase(); String password2 = (new String(regPasswordField2.getPassword())).trim().toLowerCase(); String errorMsg = ""; int result = password.compareTo(password2); if (result != 0) { errorMsg = "Passwords mismatch, re-enter"; } else { result = server.addUser(name, password); if (result < 0) { if (result == -1) errorMsg = "Login name must be 4-10 characters long"; else if (result == -2) errorMsg = "Password must be 2-10 characters long"; else if (result == -3) errorMsg = "Login name already taken, choose another one"; else errorMsg = "Unknown error code"; } } if (result != 0) { JOptionPane.showMessageDialog(thisWindow, errorMsg, "Registration failed", JOptionPane.ERROR_MESSAGE); nameField.setText(""); passwordField.setText(""); return false; } else { JOptionPane.showMessageDialog(thisWindow, "Added " + name, "Registration successful", JOptionPane.INFORMATION_MESSAGE); nameField.setText(name); passwordField.setText(password); return true; } }
7
public void loadFromSparseFile(String trainFile, String testFile, String quizFile, String featureFile, int featureCount) { System.out.print("Loading dataset... "); this.featureCount = featureCount; try { if(trainFile != null && trainFile.length() > 0); loadDataFromSparseFile(trainFile, InstanceType.Train, featureCount); if(testFile != null && testFile.length() > 0) loadDataFromSparseFile(testFile, InstanceType.Test, featureCount); if(quizFile != null && quizFile.length() > 0) loadDataFromSparseFile(quizFile, InstanceType.Quiz, featureCount); if(featureFile != null && featureFile.length() > 0) loadFeatureFromFile(featureFile); } catch (IOException e) { e.printStackTrace(); } System.out.println(this.toString()); }
9
public boolean accept(File f) { if (f.isDirectory()) { return true; } String extension = Utils.getExtension(f); if (extension != null) { if (extension.equals(Utils.tiff) || extension.equals(Utils.tif) || extension.equals(Utils.gif) || extension.equals(Utils.jpeg) || extension.equals(Utils.jpg) || extension.equals(Utils.png)) { return true; } else { return false; } } return false; }
8
private void actionDisconnectFromAll() { Component[] array = MainWindow.getInstance().getTabContainer().getComponents(); for (int i = 0; i < array.length; i++) { Component component = array[i]; if (component instanceof ServerTab) { ServerTab c = (ServerTab) component; InputHandler.handleQuit(c, null); } } }
2
public static String currentValues() { String result = ""; Iterator it = inputTable.entrySet().iterator(); while(it.hasNext()) { Map.Entry pair = (Map.Entry)it.next(); result += pair.getKey() + "=" + pair.getValue() + "\n"; } return result; }
1
public BiCubicSplineShort(double[] x1, double[] x2, double[][] y){ this.nPoints=x1.length; this.mPoints=x2.length; this.csm = new CubicSplineShort(this.nPoints); this.csn = CubicSplineShort.oneDarray(this.nPoints, this.mPoints); this.x1 = new double[this.nPoints]; this.x2 = new double[this.mPoints]; this.y = new double[this.nPoints][this.mPoints]; for(int i=0; i<this.nPoints; i++){ this.x1[i]=x1[i]; } for(int j=0; j<this.mPoints; j++){ this.x2[j]=x2[j]; } for(int i =0; i<this.nPoints; i++){ for(int j=0; j<this.mPoints; j++){ this.y[i][j]=y[i][j]; } } double[] yTempn = new double[mPoints]; for(int i=0; i<this.nPoints; i++){ for(int j=0; j<mPoints; j++)yTempn[j]=y[i][j]; this.csn[i].resetData(x2,yTempn); this.csn[i].calcDeriv(); } }
6
@Test public void testAppendRow() throws Exception { if(sampleDoc != null) { String []strings = {"33445566","KK","Test City","1","1122334455"}; Row row = new Row(sampleDoc.getRecords().size() , strings ); sampleDoc.appendRow(row); } }
1
public void playerLostAllLives(int id) { List<Controllable> players = entities.getList(Controllable.class); for (Controllable plr : players) { if (plr.playerID() == id) entities.removeEntity((Entity)plr); } if (menu != null && isGameOver()) menu.showHighScore(); }
4
private final String loadFile(final String filename) { if (filename == null) return null; final File file = new File(filename); final char[] data = new char[(int)file.length()]; try { final FileReader reader = new FileReader(file); if (reader.read(data) != data.length) System.err.println("???"); reader.close(); return String.valueOf(data); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; }
4
public static void postToSubs(String str){ if(!userObj.getUser().contentEquals("GUEST")){ subFile = new File(userObj.getUser() + "Subs.UMW"); if(subFile.exists()){ try { Scanner input = new Scanner(subFile); while(input.hasNextLine()){ String tempFileName = input.nextLine(); postFile = new File(tempFileName + ".UMW"); if(postFile.exists()){ updateFile(userObj.getUser() + ": " + str + "\n", postFile); } } input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } } }
5
public static void encodeIntoImage(File containerImg, File outputFile, byte[] srcBytes, String key) { try { BufferedImage in = ImageIO.read(containerImg); BufferedImage newImage = new BufferedImage(in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = newImage.createGraphics(); g.drawImage(in, 0, 0, null); g.dispose(); srcBytes = CompressionProvider.compressBytes(srcBytes); byte[] encryptedBytes = EncryptionProvider.encryptBytes(srcBytes, key.getBytes()); // Trick: convert from unsigned number to signed byte short[] srcS = new short[encryptedBytes.length]; for (int i = 0; i < encryptedBytes.length; i++) { srcS[i] = (short) (encryptedBytes[i] & 0xFF); } ImageEncoder.writeBytesToImage(in, encryptedBytes, outputFile.toString(), key); System.out.println("[OK] Steganographic .png \"" + outputFile.toString() + "\" generated."); } catch (DataFormatException ex) { Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ImageWriteException | IOException ex) { Logger.getLogger(ImageUtils.class.getName()).log(Level.SEVERE, null, ex); } }
3
@Override protected void process(Map<String, Object> jsonrpc2Params) throws Exception { //To change body of implemented methods use File | Settings | File Templates. if(method.equals(Constants.Method.GET_THREAD_CONTENT)){ getThreadContent(jsonrpc2Params); } else if(method.equals(Constants.Method.CREATE_THREAD)){ createThread(jsonrpc2Params); } else if(method.equals(Constants.Method.MODIFY_THREAD)){ modifyThread(jsonrpc2Params); } else if(method.equals(Constants.Method.DELETE_THREAD)){ deleteThread(jsonrpc2Params); } else if(method.equals(Constants.Method.GET_LATEST_THREADS)){ getLatestThreads(jsonrpc2Params); } else if(method.equals(Constants.Method.CREATE_LINKED_THREAD)){ createLinkedThread(jsonrpc2Params); } else if(method.equals(Constants.Method.MODIFY_LINKED_THREAD)){ modifyLinkedThread(jsonrpc2Params); } else if(method.equals(Constants.Method.DELETE_LINKED_THREAD)){ deleteLinkedThread(jsonrpc2Params); } else { throwJSONRPC2Error(JSONRPC2Error.METHOD_NOT_FOUND, Constants.Errors.METHOD_NOT_FOUND, method); } }
8
public void mouseClicked(MouseEvent e) { Point p = e.getPoint(); if (SwingUtilities.isRightMouseButton(e)) { if (isInNavigationImage(p)) { navZoomFactor = 1.0 - zoomIncrement; zoomNavigationImage(); } else if (isInImage(p)) { zoomFactor = 1.0 - zoomIncrement; zoomImage(); } } else { if (isInNavigationImage(p)) { navZoomFactor = 1.0 + zoomIncrement; zoomNavigationImage(); } else if (isInImage(p)) { zoomFactor = 1.0 + zoomIncrement; zoomImage(); } } }
5
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(DevModelStorage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(DevModelStorage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(DevModelStorage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(DevModelStorage.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 DevModelStorage().setVisible(true); } }); }
6
public Set<List<Integer>> computePartition(List<String> attributesByName){ Set<List<Integer>> partition = new HashSet<List<Integer>>(); //Make a new list of integers to store some hashed strings (could maybe use array instead) List<Integer> hashedAttributes = new ArrayList<Integer>(); //Concat (string) values of each nonDec attribute and hash it and put it in a list for(int i=0;i<relation.attributeData.get(0).instanceValues.size();i++){ String comboToHash = ""; for(int j=0;j<attributesByName.size();j++){ //Holy cow comboToHash+= relation.attributeData.get(attributeIndexMap.get(attributesByName.get(j))).instanceValues.get(i); } hashedAttributes.add(comboToHash.hashCode()); } //Need to look through each value in hashedAttributes and get the indexesss Object[] uniqueHash = new HashSet<Integer>(hashedAttributes).toArray(); for(int i=0;i<uniqueHash.length;i++){ //For each unique value List<Integer> singlePartition = new ArrayList<Integer>(); for(int j=0;j<hashedAttributes.size();j++){//Find all occurrences in hashedAttributes //If they match, do some stuff if(hashedAttributes.get(j).hashCode()==uniqueHash[i].hashCode()){ singlePartition.add(j); //Add the index number to one *list* or piece of a partition ({x1,x2}) } } partition.add(singlePartition); //Add each list ({x1,x2}) to the partition ( [{x3,x4},...,{x1,x2}] ) } return partition; }
5
private Move askPredatorForMove() { // Get the All possible edges for the predator final Set<Edge> allPossibleEdges = Ship.getAll(ship.getPredatorNode().getCoordinates(), ship, connectedShip); // Get the adjacent edges for the predator final Set<Edge> adjacentEdges = ship.getPredatorNode().getAdjacent(); // Is the predator at the control room boolean predAtControlRoom = ship.getPredatorNode().equals(controlNode); // prints to the status bar if (predAtControlRoom) { uigui.changeCRStatus(" The Predator is at the Control Room"); } // Is the predator at the scanner boolean predAtScanner = ship.getPredatorNode().equals(scannerNode); // If the predator it on the scanner, make sure he gets it for // the rest // of the game if (predAtScanner) { // prints to the status bar uigui.changeScannerStatus(" The Predator has the scanner"); predatorHasScanner = true; scannerNode = null; } // By default the predator does not get info from the // scanner Ship scannerShip = null; // If the predator has the scanner, give him a copy of // the ship if (predatorHasScanner) { // make a copy of the ship scannerShip = Engine.ship.clone(); } // By default, the Predator cannot sense the alien boolean isAlienWithinSight = false; // By default, the Predator does not know if the Edge directionOfAlien = null; // Get the shortest path between the alien and predator List<Edge> shortestPath = Engine.ship.getPath(ship.getPredatorNode(), ship.getAlienNode()); // If there is a path between the alien and the predator and the // distance within the predator's sensing distance if (shortestPath != null && shortestPath.size() <= PRED_SENSE) { // Indicate that the alien is within sight isAlienWithinSight = true; // Store the direction of the Alien directionOfAlien = shortestPath.iterator().next(); // prints to status bar uigui.changePSenseStatus(" The Predator senses the Alien"); } else { uigui.changePSenseStatus(""); } // Make an info class for the Alien Info info = new Info(ship.getPredatorNode(), allPossibleEdges, adjacentEdges, predAtControlRoom, predAtScanner, scannerShip, isAlienWithinSight, directionOfAlien, null); // Get the predator's move Move predatorMove = predator.nextMove(info); // Validate the predator's move if (validateMove(predatorMove, allPossibleEdges, false, PRINT_DIAGNOSTIC)) { // If valid, make the move return predatorMove; } else { // If invalid move then indicate a pass return new Move(adjacentEdges.iterator().next(), false, false); } }
6
@Override public void setValueAt(Object value, int row, int col) { User user = (User) globalData.get(row); switch (col) { case INDEX_ID: // this can't be changed.. break; case INDEX_FIRSTNAME: try { user.setFirstName((String) value); } catch (InvalidFieldException e1) { } break; case INDEX_LASTNAME: try { user.setLastName((String) value); } catch (InvalidFieldException e) { } break; default: // can't change here! break; } fireTableCellUpdated(row, col); }
5
public boolean isSubtree(TreeNode<Integer> root1, TreeNode<Integer> root2) { if (root2 == null) return false; if (treeMatch(root1, root2)) return true; return isSubtree(root1.left, root2) || isSubtree(root1.right, root2); }
3
public static ArrayList <RobotData> loadData() { File load = new File("resources/files/RobotData/"); Gson loader = new Gson(); ArrayList <RobotData> res = new ArrayList <RobotData>(); for (File f : load.listFiles()) { BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } RobotData read = null; try { read = loader.fromJson(br.readLine(), RobotData.class); res.add(read); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } return res; }
6
public String toString() { return this.mode == 'd' ? this.writer.toString() : null; }
1
public void setKeyProfileId(String value) { this.keyProfileId = value; }
0
public void genC(PW pw) { if (aug == Symbol.DIVASSIGN) { pw.print("/="); } if (aug == Symbol.MODASSIGN) { pw.print("%="); } if (aug == Symbol.MINUSASSIGN) { pw.print("-="); } if (aug == Symbol.ASSIGN) { pw.print("="); } if (aug == Symbol.PLUSASSIGN) { pw.print("+="); } if (aug == Symbol.MULTIASSIGN) { pw.print("*="); } if (aug == Symbol.ORASSIGN) { pw.print("|="); } if (aug == Symbol.XORASSIGN) { pw.print("^="); } if (aug == Symbol.ANDASSIGN) { pw.print("&="); } }
9
@Override public void updateIngredient(Ingredient c) throws IngredientRepositoryException { validate(c); try(Connection connection = DriverManager.getConnection(connectionString)){ PreparedStatement statement = connection.prepareStatement("update ingredient set name = ? where id = ? "); statement.setString(1, c.getName().toUpperCase(Locale.ENGLISH)); statement.setInt(2, c.getIngredientId()); statement.executeUpdate(); statement = connection.prepareStatement("delete from parent where idIngredient = ?"); statement.setInt(1, c.getIngredientId()); statement.executeUpdate(); for(int parent : c.getParentIngredients()){ statement = connection.prepareStatement("insert into parent values (?,?)"); statement.setInt(1, c.getIngredientId()); statement.setInt(2, parent); statement.executeUpdate(); } connection.close(); } catch(SQLException ex){ ex.printStackTrace(); System.exit(-1); } }
2
void getFirstMove() { int x = 1; int y = 1; int[] humanLoc = lastSpaceMoved.pos; // If center --> random corner if (humanLoc[0] == 1 && humanLoc[1] == 1) { if (Math.random() < .5) x = 0; else x = 2; if (Math.random() < .5) y = 0; else y = 2; } // If corners --> random adjacent space else if (humanLoc[0] != 1 && humanLoc[1] != 1) { x = y = 1; } // If edge middle row --> opposite side else if (humanLoc[0] == 1) { if (humanLoc[1] == 0) y = 2; else y = 0; } // If edge middle column --> opposite side else { if (humanLoc[0] == 0) x = 2; else x = 0; } placePiece(board[x][y], O); }
9
public String validarDatosAltaUsuario(String nombre, String apPaterno, String apMaterno, String usuario, String password,String permisos) { String errorLog =""; Usuario resultadoBusqueda = new Usuario(true); Object[] resultado = null; Object[][] opciones = new Object[][] {{"usuario","=",usuario}}; resultado = resultadoBusqueda.buscarBD("all", opciones); if(resultado.length>0) errorLog += "¡ El nombre de usuario ya existe, favor de utilizar otro !\n"; // return errorLog; if(nombre.trim().length()<=0) { errorLog +="¡ El campo Nombre no debe quedar vacío !\n"; } if(apPaterno.trim().length()<=0) { errorLog +="¡ El campo Apellido Paterno no debe quedar vacío !\n"; } if(apMaterno.trim().length()<=0) { errorLog +="¡ El campo Apellido Materno no debe quedar vacío !\n"; } if(usuario.trim().length()<=0) { errorLog +="¡ El campo Nombre de Usuario no debe quedar vacío !\n"; } if(password.trim().length()<=0) { errorLog +="¡ El campo Password no debe quedar vacío !\n"; } if(password.trim().length()<=5 ||password.length()>=13) { errorLog += "¡ El password debe contener entre 6 y 12 caracteres !\n"; } if(permisos.trim().length()<=0) { errorLog +="¡ El campo Permisos no debe quedar vacío !\n"; } return errorLog; }
9
@Override public void deleteResult(String key, String text) { if(results.get(key) != null){ for(int i = 0; i < results.get(key).size(); i++){ if(results.get(key).get(i).getSolution().contains(text)){ results.get(key).remove(i); } } } }
3
@Override public void dragExit(DropTargetEvent dte) { if (mDragDockable != null) { clearDragState(); } }
1
public void testConstructor_int_int_int() throws Throwable { LocalTime test = new LocalTime(10, 20, 30); assertEquals(ISO_UTC, test.getChronology()); assertEquals(10, test.getHourOfDay()); assertEquals(20, test.getMinuteOfHour()); assertEquals(30, test.getSecondOfMinute()); assertEquals(0, test.getMillisOfSecond()); try { new LocalTime(-1, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(24, 20, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, -1, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 60, 30); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, -1); fail(); } catch (IllegalArgumentException ex) {} try { new LocalTime(10, 20, 60); fail(); } catch (IllegalArgumentException ex) {} }
6
@Override public Program generateOffspring(Program firstParent, Program secondParent) throws InvalidProgramException { if (!(firstParent instanceof ProgramImpl) || !(secondParent instanceof ProgramImpl)) { throw new InvalidProgramException(); } ProgramImpl offspring = ((ProgramImpl) firstParent).clone(); ProgramImpl parent = ((ProgramImpl) secondParent); List<Reaction> offspringReactions = offspring.getReactions(); List<Reaction> parentReactions = parent.getReactions(); Random randomGenerator = new Random(); Reaction selectedReaction = null; Reaction simmilarReaction = null; int attempts = 0; do { selectedReaction = offspringReactions.get(randomGenerator.nextInt(offspringReactions.size())); simmilarReaction = getSimmilarReaction(parentReactions, selectedReaction); attempts++; } while (simmilarReaction == null && attempts < MAX_NUMBER_OF_TRIES); if (simmilarReaction != null) { selectedReaction.changePattern(simmilarReaction.getPattern()); } return offspring; }
5
public void destroyCritter(Critter item){ synchronized(lock_critter){ ListIterator<Critter> iter = play_pen.listIterator(); Critter kill = null; while(iter.hasNext()){ Critter temp = iter.next(); if(temp.equals(item)){ kill = item; break; } } if(kill != null){ play_pen.remove(kill); System.out.println(kill + " dies"); } } }
3
public static String[][] getUsernames() { List<User> list = DataProvider.getUsers(); String[][] usernames = new String[list.size()][4]; Iterator<User> it = list.iterator(); for (int x = 0; it.hasNext(); x++) { User user = it.next(); usernames[x][0] = String.valueOf(user.getId()); usernames[x][1] = user.getUsername(); usernames[x][2] = user.getName(); } return usernames; }
1
public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } }
2
public void autoPromoterCheck(Player player) { String curRank = perms().getPrimaryGroup(player); if ( config.promoterWatchingRank(curRank) ) if ( getASPlayer(player.getName()).total.getActivity() > config.promoterPoints(curRank) ) if ( perms().playerAddGroup(player, config.promoterRankTo(curRank)) ) info("AutoPromoted " + player.getName()); }
3
void popDuskObject(DuskObject objIn) { synchronized(objEntities) { if (objIn.intLocX < 0 || objIn.intLocY < 0 || objIn.intLocX >= MapColumns || objIn.intLocY >= MapRows) { return; } if (objEntities[objIn.intLocX][objIn.intLocY] == null) { return; }else { if (objEntities[objIn.intLocX][objIn.intLocY] == objIn) { objEntities[objIn.intLocX][objIn.intLocY] = objIn.objNext; objIn.objNext = null; }else { DuskObject objStore = objEntities[objIn.intLocX][objIn.intLocY]; while (objStore.objNext != null && objStore.objNext != objIn) { objStore = objStore.objNext; } if (objStore.objNext != null) { objStore.objNext = objStore.objNext.objNext; } objIn.objNext = null; } } } }
9
public static boolean parsebool(String s, boolean def) { if (s == null) return (def); else if (s.equalsIgnoreCase("1") || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("true") || s.equalsIgnoreCase("yes")) return (true); else if (s.equalsIgnoreCase("0") || s.equalsIgnoreCase("off") || s.equalsIgnoreCase("false") || s.equalsIgnoreCase("no")) return (false); return (def); }
9
@Test(dataProvider = "addressBookDataProviderAsIterator") public void addressBookDataNotEmpty(String first, String second, String third) { Assert.assertFalse(first.isEmpty()); Assert.assertFalse(second.isEmpty()); Assert.assertFalse(third.isEmpty()); }
0
@Override public void execute() { if(Global.useRejuvenate && ActionBar.getAdrenaline() == 1000 && ActionBar.getNode(0).canUse()){ ActionBar.getNode(0).use(); Task.sleep(1000); }else if(Global.eatFood && Methods.getHpPercent() <= HEAL_PERCENT - 10){ Inventory.getItem(Global.foodId).getWidgetChild().interact("Eat"); } }//End of Execute
5
private void renderItemChose() { if (validChosenItemIndex()) label.setText("Choosen index is: " + getChosenItemIndex()); }
1
public Expression simplify() { for (int i = 0; i < subExpressions.length; i++) { if (subExpressions[i] != null) subExpressions[i] = subExpressions[i].simplify(); } return this; }
2
private synchronized void calculateNextMonth() { int initialSize = this.schedule.size(); // If the schedule has already been generated if (this.schedule.size() > 0) { scheduleUpdate(); } // Used to see if month changes int currentMonth = this.cal.get(Calendar.MONTH); int daysInMonth = 0; ArrayList<Integer> numOfJobs = new ArrayList<Integer>(); // While still in the current month generate a schedule for each day while (currentMonth == this.cal.get(Calendar.MONTH)) { for (Day day : this.days) { if (this.cal.get(Calendar.DAY_OF_WEEK) == this.numForName(day .getNameOfDay())) { TreeMap<String, Worker> jobsWithWorker = new TreeMap<String, Worker>(); ArrayList<String> workersWorking = new ArrayList<String>(); ArrayList<String> jobsInOrder = day.getJobs(); daysInMonth++; numOfJobs.add(jobsInOrder.size()); for (String job : jobsInOrder) { //SWAP 1 TEAM 5 /* * QUALITY CHANGES * created jobWorkers to get the list of people who can work that certain job */ ArrayList<Worker> workersForJob = jobWorkers(job, day, workersWorking); if (workersForJob.size() > 0) { Worker workerForJob = getWorkers(job, workersForJob); jobsWithWorker.put(job, workerForJob); workersWorking.add(workerForJob.getName()); workerForJob.addWorkedJob(job); } else { jobsWithWorker.put(job, new Worker("Empty",new ArrayList<Day>())); JOptionPane.showMessageDialog(new JFrame(),"No workers are able to work as a(n) " + job + " on " + day.getNameOfDay()); this.workerForEveryJob = false; break; } } String date = this.cal.get(Calendar.YEAR) + "/" + String.format("%02d",(this.cal.get(Calendar.MONTH) + 1)) + "/" + String.format("%02d",this.cal.get(Calendar.DAY_OF_MONTH)); this.schedule.put(date, jobsWithWorker); break; // Breaks so it doesn't check the other days } } this.cal.add(Calendar.DATE, 1); } HTMLGenerator.makeTable(daysInMonth, numOfJobs); // Calls itself if there aren't many days generated // For instance if the date it was created is the last day of the // month it would only makes one day of schedule. if (this.schedule.size() - initialSize < 2 && !this.workerForEveryJob) { this.calculateNextMonth(); } Main.dumpConfigFile(); }
8
static long shift(int cnt){ if(cnt<32) return cnt>1?(1<<(cnt-1)):1; else return (long) Math.pow(2, cnt-1); }
2
public static void log(String message) { String lines[] = message.split("\n"); for (String l : lines) { String temp = ""; String date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa").format(Calendar.getInstance().getTime()); temp = date + ": " + l; System.out.println(temp); } }
1
public ControleurListe(Liste liste, VueListe vueListe) { Liste_ = liste; vueListe_ = vueListe; // vueListe.getTableListe().getModel().addTableModelListener(this); vueListe.getTableListe().addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent mE) { if (mE.getClickCount() == 2) { JTable target = (JTable) mE.getSource(); int ligSelection = target.getSelectedRow(); int colSelection = target.getSelectedColumn(); String nom = (String) target.getValueAt(ligSelection, 0); String chemin = BDApplication.getChemin(nom); if (chemin != null) { try { desk.open(new File("docs//" + chemin)); } catch (Exception e) { e.printStackTrace(); } } Liste_.testLigne(ligSelection, 0, nom); Liste_.execlisteMetaDonneesParTitre(nom); // int column = target.getSelectedColumn(); // do some action if appropriate column } } }); }
3
public boolean importData(TransferSupport supp) { /* do not continue if the drop is not of a supported flavor */ System.out.println("FileTransferHandler::importData()\n type:: "+ supp.getDataFlavors()[0]); if (!canImport(supp)) { System.out.println("Drop type ::" + supp.getDataFlavors()[0] + " not supported"); return false; } Component c = supp.getComponent(); /* get the name of the destination */ to_name = c.getName(); /* fetch the Transferable */ Transferable t = supp.getTransferable(); /* get the flavor of the drop */ DataFlavor[] d = supp.getDataFlavors(); try { /* fetch the data from the Transferable */ filenames = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor); /* if NOT an EXTERNAL Drop */ if(!external_OSX.equals(d[0].toString()) && !external_WIN.equals(d[0].toString())) { //Object obj = (Object)t.getTransferData(DataFlavor.stringFlavor); from_name = (String) t.getTransferData(DataFlavor.stringFlavor); } else from_name = "----external source-----"; //System.out.println("made it to line 122"); if(to_name.equals(from_name)) { System.err.println("ERROR::PlayList::"+to_name +":: trying to drop on PlayList::" + from_name + ":::import aborted!!!" ); //from_name = ""; return false; } else { System.out.println("Drag from Playlist::" + from_name + " to PlayList::" + to_name + " accepted!!"); } for(int i = 0; i < filenames.size(); i++) { System.out.println(filenames.get(i).getAbsolutePath()); gui.addToList(filenames.get(i).getAbsolutePath()); } } catch (UnsupportedFlavorException e) { System.out.println("FileTransferHandler::importData():: Unsupported Data Flavor!"); e.printStackTrace(); return false; } catch (IOException e) { return false; } return true; }
7
public void faireAction(Tamagoshi monTama) { Scanner entree = new Scanner(System.in); System.out.println("\n\n\n\n\n"); System.out.println("1-Manger 2-Boire 3-Se laver 4-Se faire beau 5-Dormir 6-Aller aux toilettes 7-Retour"); //Entre le choix int choix=0; try { choix = entree.nextInt(); } catch(java.util.InputMismatchException e) { faireAction(monTama); } switch (choix) { case 1: monTama.manger(); System.out.println("Miam!"); faireAction(monTama); break; case 2: monTama.boire(); System.out.println("Gloup!"); faireAction(monTama); break; case 3: monTama.seLaver(); System.out.println(monTama.getPrenom() + " est tout propre"); faireAction(monTama); break; case 4: monTama.seFaireBeau(); System.out.println(monTama.getPrenom() + " est magnifique!"); faireAction(monTama); break; case 5: monTama.seReposer(); System.out.println("Rrrrrrrrrrrrr"); faireAction(monTama); break; case 6: monTama.allerAuxToilettes(); System.out.println(monTama.getPrenom() + " est plus légé!"); faireAction(monTama); break; case 7: this.menuJeu(monTama); break; default: faireAction(monTama); } }
8
protected void countIfNecessary(Item I) { if(CMLib.flags().isInTheGame(I,false)) { int max=CMath.s_int(text()); List<Item> myInstances=null; synchronized(instances) { if(!instances.containsKey(I.Name())) { myInstances=new Vector<Item>(); instances.put(I.Name(),myInstances); myInstances.add(I); } } myInstances=instances.get(I.Name()); if(myInstances!=null) { synchronized(myInstances) { if(!myInstances.contains(I)) { if(max==0) max++; int num=0; for(int i=myInstances.size()-1;i>=0;i--) if(!myInstances.get(i).amDestroyed()) num++; else myInstances.remove(i); if(num>=max) { I.destroy(); destroy=true; } else myInstances.add(I); } } } } }
8
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { Taikhoandangnhap account = (Taikhoandangnhap) request.getSession() .getAttribute("user"); Soyeulylich soyeulylich = account.getSoyeulylich(); (new SoyeulylichHome()).attachDirty(soyeulylich); FileUpload file = (FileUpload) command; String typeaccount = request.getParameter("type"); MultipartFile multipartFile = file.getFile(); System.out.println(typeaccount); String pathFile = ""; String filename = ""; InputStream sIn = null; OutputStream sOut = null; if (multipartFile != null) { if (multipartFile.getSize() > 0) { sIn = multipartFile.getInputStream(); System.out.println("Size: " + multipartFile.getSize()); Date now = new Date(); filename = "/resources/images/avatar/" + now.getTime() + "-" + multipartFile.getOriginalFilename(); pathFile = request.getRealPath("") + filename; System.err.println(pathFile); System.err.println(multipartFile.getContentType()); String type = multipartFile.getContentType(); if (!type.startsWith("image")) { System.out.println("here"); if (typeaccount.equals("staff")){ ModelAndView modelAndView = new ModelAndView("sua_thongtincanhan"); modelAndView.addObject("error", "File ảnh không hợp lệ"); modelAndView.addObject("canbo", account.getSoyeulylich()); return modelAndView; } else if (typeaccount.equals("manager")){ ModelAndView modelAndView = new ModelAndView("QL_TTPhongban"); modelAndView.addObject("error", "File ảnh không hợp lệ"); modelAndView.addObject("phongban", soyeulylich.getPhongban()); return modelAndView; } else { ModelAndView modelAndView = new ModelAndView("quanly_TTDonVi"); modelAndView.addObject("error", "File ảnh không hợp lệ"); modelAndView.addObject("donvi", soyeulylich.getPhongban().getDonviquanly()); return modelAndView; } } sOut = new FileOutputStream(pathFile); System.out.println("fileName:" + multipartFile.getOriginalFilename()); int readBytes = 0; byte[] buffer = new byte[10000]; while ((readBytes = sIn.read(buffer, 0, 10000)) != -1) { sOut.write(buffer, 0, readBytes); } sOut.close(); sIn.close(); if (typeaccount.equalsIgnoreCase("staff")){ SoyeulylichHome soyeulylichHome = new SoyeulylichHome(); soyeulylich.setDuongdananh(filename); soyeulylichHome.attachDirty(soyeulylich); soyeulylichHome.getSessionFactory().getCurrentSession().flush(); return new ModelAndView("sua_thongtincanhan", "canbo", soyeulylich); } else if (typeaccount.equalsIgnoreCase("manager")){ PhongbanHome phongbanHome = new PhongbanHome(); Phongban phongban = account.getSoyeulylich().getPhongban(); phongbanHome.attachDirty(phongban); phongban.setHinhanh(filename); phongbanHome.attachDirty(phongban); phongbanHome.getSessionFactory().getCurrentSession().flush(); return new ModelAndView("QL_TTPhongban", "phongban", phongban); } else { System.out.println("here"); DonviquanlyHome donviquanlyHome = new DonviquanlyHome(); SoyeulylichHome soyeulylichHome = new SoyeulylichHome(); Donviquanly donviquanly = soyeulylich.getPhongban().getDonviquanly(); donviquanlyHome.attachDirty(donviquanly); donviquanly.setDuongdananh(filename); donviquanlyHome.getSessionFactory().getCurrentSession().flush(); return new ModelAndView("quanly_TTDonVi", "donvi", donviquanly); } } } return null; }
8
@SuppressWarnings("unchecked") public void initialize(String pathToYml) throws IOException { YamlReader reader = new YamlReader(new FileReader(pathToYml)); Map<String, Object> input = (Map<String, Object>) reader.read(); this.blastDbSettings = (Map<String, Map<String, String>>) input .get(BLAST_DBS_KEY); setPathToProteinsFasta((String) input.get(PROTEINS_FASTA_KEY)); setPathToInterproDatabase((String) input.get(INTERPRO_DATABASE_KEY)); setPathToInterproResults((String) input.get(INTERPRO_RESULT_KEY)); setPathToGeneOntologyResults((String) input .get(GENE_ONTOLOGY_RESULT_KEY)); setPathToOutput((String) input.get(OUTPUT_KEY)); setTokenScoreBitScoreWeight(Double.parseDouble((String) input .get(TOKEN_SCORE_BIT_SCORE_WEIGHT))); setTokenScoreDatabaseScoreWeight(Double.parseDouble((String) input .get(TOKEN_SCORE_DATABASE_SCORE_WEIGHT))); setTokenScoreOverlapScoreWeight(Double.parseDouble((String) input .get(TOKEN_SCORE_OVERLAP_SCORE_WEIGHT))); setDescriptionScorePatternFactorWeight(Double .parseDouble((String) input .get(DESCRIPTION_SCORE_RELATIVE_DESCIPTION_FREQUENCY_WEIGHT))); setWriteTokenSetToOutput(Boolean.parseBoolean((String) input .get(WRITE_TOKEN_SET_TO_OUTPUT))); setWriteBestBlastHitsToOutput(Boolean.parseBoolean((String) input .get(WRITE_BEST_BLAST_HITS_TO_OUTPUT))); setWriteScoresToOutput(Boolean.parseBoolean((String) input .get(WRITE_SCORES_TO_OUTPUT))); // Generate the Blacklists and Filters for each Blast-Database from // their appropriate files: for (String blastDatabaseName : getBlastDatabases()) { this.blastResultsBlacklists .put(blastDatabaseName, fromFile(getPathToBlastResultsBlackList(blastDatabaseName))); this.blastResultsFilter.put(blastDatabaseName, fromFile(getPathToBlastResultsFilter(blastDatabaseName))); this.tokenBlacklists.put(blastDatabaseName, fromFile(getPathToTokenBlacklist(blastDatabaseName))); // Set Database-Weights and Description-Score-Bit-Score-Weight: this.getParameters().setBlastDbWeight( blastDatabaseName, this.getBlastDbSettings(blastDatabaseName).get( Settings.BLAST_DB_WEIGHT_KEY)); this.getParameters().setDescriptionScoreBitScoreWeight( blastDatabaseName, this.getBlastDbSettings(blastDatabaseName).get( Settings.DESCRIPTION_SCORE_BIT_SCORE_WEIGHT)); } // If started to train the algorithm references are stored in this file: setPathToReferencesFasta((String) input.get(REFERENCES_FASTA_KEY)); // If started in training-mode the F-Measure's Beta-Parameter can be set // to some other value than 1.0 if (input.get(F_MEASURE_BETA_PARAM_KEY) != null) this.fMeasureBetaParameter = Double.parseDouble((String) input .get(F_MEASURE_BETA_PARAM_KEY)); // If started to compare AHRD with Blast2Go, enable reading of // B2G-Annotations: if (input.get(BLAST_2_GO_ANNOT_FILE_KEY) != null) this.pathToBlast2GoAnnotations = (String) input .get(BLAST_2_GO_ANNOT_FILE_KEY); // Simulated Annealing can be started with custom temperature and value // it is cooled-down by each step: if (input.get(TEMPERATURE_KEY) != null) setTemperature(Integer .parseInt((String) input.get(TEMPERATURE_KEY))); if (input.get(COOL_DOWN_BY_KEY) != null) this.coolDownBy = Integer.parseInt((String) input .get(COOL_DOWN_BY_KEY)); if (input.get(REMEMBER_SIMULATED_ANNEALING_PATH_KEY) != null && Boolean.parseBoolean(input.get( REMEMBER_SIMULATED_ANNEALING_PATH_KEY).toString())) this.rememberSimulatedAnnealingPath = true; // Evaluation or Optimization might be interested in the highest // possibly achievable evaluation-score: if (input.get(FIND_HIGHEST_POSSIBLE_EVALUATION_SCORE_KEY) != null && Boolean.parseBoolean(input.get( FIND_HIGHEST_POSSIBLE_EVALUATION_SCORE_KEY).toString())) this.findHighestPossibleEvaluationScore = true; }
9
public static Position bestAproxPositionOf(List<Position> pos, Position refPosition, double APROX) throws NoPositionAvailableException { Position best = null; double normBest = APROX+8; for(int i = 0; i < pos.size(); i++) { double tempNorm = new Vector(refPosition, pos.get(i)).norm(); if(tempNorm < normBest) { best = pos.get(i); normBest = tempNorm; } } if (normBest > APROX) throw new NoPositionAvailableException(); return best; }
3
public MiniXMLState getChild(int state, int token) { Integer oToken = new Integer(token); if (!children.containsKey(oToken)) { MiniXMLState child = new MiniXMLState(state, token, this); children.put(oToken, child); } return (MiniXMLState) children.get(oToken); }
1
private void treeRefresh(File[] masterFiles) { TreeItem[] items = tree.getItems(); int masterIndex = 0; int itemIndex = 0; for (int i = 0; i < items.length; ++i) { final TreeItem item = items[i]; final File itemFile = (File) item.getData(TREEITEMDATA_FILE); if ((itemFile == null) || (masterIndex == masterFiles.length)) { // remove bad item or placeholder item.dispose(); continue; } final File masterFile = masterFiles[masterIndex]; int compare = compareFiles(masterFile, itemFile); if (compare == 0) { // same file, update it treeRefreshItem(item, false); ++itemIndex; ++masterIndex; } else if (compare < 0) { // should appear before file, insert it TreeItem newItem = new TreeItem(tree, SWT.NONE, itemIndex); treeInitVolume(newItem, masterFile); new TreeItem(newItem, SWT.NONE); // placeholder child item to get "expand" button ++itemIndex; ++masterIndex; --i; } else { // should appear after file, delete stale item item.dispose(); } } for (;masterIndex < masterFiles.length; ++masterIndex) { final File masterFile = masterFiles[masterIndex]; TreeItem newItem = new TreeItem(tree, SWT.NONE); treeInitVolume(newItem, masterFile); new TreeItem(newItem, SWT.NONE); // placeholder child item to get "expand" button } }
6
public void removeChatGuiListener(ChatGuiListener listener) { chatGuiListener.remove(listener); }
0
public static void main(String[] args) { System.out.println("Hello"); IntNode head = new IntNode(111, null); IntNode node = new IntNode(555, head); IntNode node2 = new IntNode(777,node); System.out.println("good morning"); System.out.println(head.toString()); System.out.println("node"); System.out.println(node.toString()); System.out.println("node2"); System.out.println(node2.toString()); head.addNodeAfter(node.getData()); System.out.println("head"); head.toString(); IntNode position; position = IntNode.listPosition(head, 2); IntNode.insertAtPos(head, 2, 10101); System.out.println("inserted ---- head"); System.out.println(head.toString()); System.out.println("print node2"); System.out.println(node2.toString()); }
0
@RequestMapping(value = "/{worldId}/{mapId}/{eventId}") @ResponseBody public List<Event> getEventByWorldAndMapAndEvent(@PathVariable int worldId, @PathVariable int mapId, @PathVariable String eventId) { List<Event> result = new ArrayList<Event>(); List<Event> events = data.getEvents(); for(Event event : events) { if(event.getWorldId() == worldId && event.getMapId() == mapId && event.getEventId().equals(eventId)) { result.add(event); } } return result; }
4
private Point getFirstWithOtherType(int sX, int sY, int dX, int dY, int type) { int cX = sX + dX; int cY = sY + dY; while (cX >= 0 && cX < _nX && cY >= 0 && cY < _nY && _state[cY][cX] != null && _state[cY][cX].getType() == type) { cX += dX; cY += dY; } return new Point(cX, cY); }
6
void enableForGroovy() { saveButton.setEnabled(true); runButton.setEnabled(false); clearButton.setEnabled(false); editButton.setEnabled(false); graphButton.setEnabled(false); docButton.setEnabled(false); syslogCombo.setEnabled(false); logLabel.setEnabled(false); outputButton.setEnabled(false); buildButton.setEnabled(false); if (isGroovy()) { runButton.setEnabled(true); clearButton.setEnabled(true); return; } if (isSim()) { buildButton.setEnabled(true); runButton.setEnabled(true); editButton.setEnabled(true); graphButton.setEnabled(true); docButton.setEnabled(true); syslogCombo.setEnabled(true); logLabel.setEnabled(true); outputButton.setEnabled(true); clearButton.setEnabled(true); return; } }
2
private void onUnpause() { if (!downloadsTable.getSelectionModel().isSelectionEmpty()) { int id = downloadsTable.convertRowIndexToModel(downloadsTable.getSelectedRow()); Integer gid = (Integer) downloadsTable.getModel().getValueAt(id, 0); downloadManager.unpauseDownload(gid); } }
1
private static IFuzzyCommand parseOperator(String[] tokens) throws FuzzyParserException { if(!tokens[0].equals("set") || !tokens[3].equals("to")) { throw new FuzzyParserException("Illegal command format!"); } String sign = tokens[2]; String opID = tokens[4]; IOperator operator; switch(opID) { case "ZadehS": operator = new ZadehS(sign); break; case "ZadehT": operator = new ZadehT(sign); break; case "ZadehNot": operator = new ZadehNot(sign); break; case "Mamdani": operator = new MamdaniMin(sign); break; default: try { double v = Double.parseDouble(opID.substring(11, opID.length() - 1)); if(opID.startsWith("HammacherS")) { operator = new HammacherS(sign, v); break; } else if(opID.startsWith("HammacherT")) { operator = new HammacherT(sign ,v); break; } } catch(Exception ignorable) {} throw new FuzzyParserException("Unknown operator!"); } return new SetOperatorCommand(operator); }
9
@Override public void run(){ System.setProperty("http.proxyHost", addr); System.setProperty("http.proxyPort", port); URL url; InputStream in; try { url = new URL("http://www.xiami.com"); in = url.openStream(); if(in!=null){ byte[] tmp =new byte[1024]; String s; int i; while((i=in.read(tmp))!=-1){ s=new String(tmp,0,i); if(s.indexOf("xiami.net")!=-1){ Log.Print(s); System.out.println(addr+":"+port); FileWriter fw; try { fw = new FileWriter("D:\\res\\proxy-"+addr+"-"+port+".txt", true); fw.append(addr+":"+port+'\n'); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (MalformedURLException e) { // TODO Auto-generated catch block //e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block //e.printStackTrace(); }finally { mcdl.countDown(); } }
6
private static int session() { int resul[] = new int[CAN.length]; // tableau contenant les résultats de chaque personne double pourc[] = new double[CAN.length]; // tableau contenant les résultats sous un pourcentage int somme; // contient le nombre total de vote int vote; // contient le nombre de vote entré par l'utilisateur int gagnant = 0; // contient l'index du gagnant int i; // contient un compteur int j; // contient un compteur String resultat; // contient la chaîne de charactères contenant les résultats String input; // contient la valeur renvoyé par getNumber() NumberFormat percent = NumberFormat.getPercentInstance(); // pour chaque bureaux, demander le nombre de vote pour chaque personnes for(i = somme = 0; i < BUREAU; i++) for(j = 0; j < CAN.length; j++) { // demander le nombre de vote pour X bureau et Y personne // si l'utilisateur annule, le programme se termine input = getVote(i, j); if(input == ERR) return 1; vote = Integer.parseInt(input); // classer ces votes et les ajouter à la somme total de vote resul[j] += vote; somme += vote; } // création des résultats resultat = "Résultat des élections municipales.\n\n"; for(i = 0; i < CAN.length; i++) { // en même temps, déterminer la gagnant des élections if(resul[i] > resul[gagnant]) gagnant = i; // en même temps, convertir le nombre de vote en pourcentage pourc[i] = (double)resul[i]/somme; // ajouter la ligne d'un député dans le résultat resultat += (CAN[i]+": \t"+resul[i]+" "+(resul[i]>1?"votes":"vote") +" ("+percent.format(pourc[i])+")\n"); } // finaliser et afficher les résultats avec le gagnant resultat += ("\nLe gagnant des élections municipales est " +CAN[gagnant]+" avec "+resul[gagnant]+" " +(resul[gagnant]>1?"votes":"vote")+"."); JOptionPane.showMessageDialog(null, new JTextArea(resultat)); return 0; }
7
@Override public void paint(Graphics g) { super.paint(g); Iterator<Pfad> pfadIterator = laenderGraph.getPathIterator(); g.drawImage(bild, 0, 0, null); while (pfadIterator.hasNext()) { Pfad tmpPathRef = pfadIterator.next(); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(10)); g2.drawLine(tmpPathRef.getFirstLand().getXLocation(), tmpPathRef .getFirstLand().getYLocation(), tmpPathRef.getSecondLand() .getXLocation(), tmpPathRef.getSecondLand().getYLocation()); } /* JBUTTON */ for (Land c : laenderGraph) { JButton jbutton; // math int landMidX = c.getXLocation(); int landMidY = c.getYLocation(); int squareHalf = (citySquareSize / 2); int cityX = landMidX - squareHalf; int cityY = landMidY - squareHalf; Fraktion owner = c.getOwner(); // draws the text and the rect String drawString = Integer.toString(c.getID()); if (owner == Fraktion.Blau) { drawString += "[" + c.getAnzahlEinheiten() + "]"; } else if (owner == Fraktion.Rot) { drawString += "[" + c.getAnzahlEinheiten() + "]";; } g.setColor(getCityColor(owner)); g.fillRect(cityX, cityY, citySquareSize, citySquareSize); g.setColor(new Color(0, 0, 0)); g.drawString(drawString, landMidX - (3 * drawString.length()), landMidY + 5); // adds button jbutton = buttonFactory(cityX, cityY, c.getID()); buttonMap.put(c.getID(), jbutton); add(jbutton); } }
4
public static int search_var_by_name(Variable_table variable_table, String name) { int num = variable_table.variable_name.size(); for (int i = 0; i < num; i++) { if (variable_table.variable_name.get(i).toString().equals(name)) { return i; } } return -1; }
2
public void generateMoves(Piece[][] squares, ArrayList<Move> validMoves, ArrayList<Move> validCaptures) { // for each possible direction (NE, SE, SW, NW) int xPos; int yPos; for (int direction = 0; direction < xMoves.length; direction++) { xPos = xPosition + xMoves[direction]; yPos = yPosition + yMoves[direction]; while (0 <= xPos && xPos <= 7 && 0 <= yPos && yPos <= 7) { if (squares[xPos][yPos] == null) { //if the square is empty validMoves.add(new Move(xPosition, yPosition, xPos, yPos)); } else { //if the square contains a piece if (squares[xPos][yPos].colour == this.colour) { //if the square contains a friendly piece break; } else { validCaptures.add(new Move(xPosition, yPosition, xPos, yPos)); break; //if the square contains an enemy piece } } //increment the position xPos += xMoves[direction]; yPos += yMoves[direction]; } } }
7
private void acao165(Token token) throws SemanticError { if (tipoFator != Tipo.BOOLEANO) { throw new SemanticError("Operador 'não' exige operando BOOLEANO", token.getPosition()); } if(!indexandoVetorParametro) parametroAtualPodeSerReferencia = false; }
2
public int maxProfitRange(int startIndex, int endIndex, int[] prices) { int maxProfit = 0; if (endIndex == startIndex) { return maxProfit; } // only two numbers in range if (endIndex - startIndex == 1) { int curProfit = prices[endIndex] - prices[startIndex]; if (curProfit > maxProfit) maxProfit = curProfit; return maxProfit; } for (int i = startIndex; i < endIndex; i++) { for (int j = i + 1; j <= endIndex; j++) { int curProfit = prices[j] - prices[i]; if (curProfit > maxProfit) maxProfit = curProfit; } } return maxProfit; }
6