text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args){ int i; Scanner keyboard = new Scanner(System.in); while (true) { System.out.println("Please input an odd number:"); i = keyboard.nextInt(); if (i % 2 == 0) { System.out.println("It's an even number! Try again."); } else { //calcute how many lines need to be filled for (int line = 0; line <= (i / 2); line++) { //calcute how many spaces and blocks are needed for (int row = 0; row < ((i / 2) - line); row++) System.out.print(" "); for (int pyramid = 0; pyramid < (line * 2 + 1); pyramid++) System.out.print("*"); System.out.println(); } } } }
5
public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
void setExampleWidgetAlignment () { int alignment = 0; if (leftButton.getSelection ()) alignment = SWT.LEFT; if (centerButton.getSelection ()) alignment = SWT.CENTER; if (rightButton.getSelection ()) alignment = SWT.RIGHT; label1.setAlignment (alignment); label2.setAlignment (alignment); label3.setAlignment (alignment); }
3
public boolean isDirectlyAccessible(Coordinate coord) { int x = coord.getCoordX(); int y = coord.getCoordY(); Coordinate coordTemp; if (y > 0) { coordTemp = coord.copy(); coordTemp.moveNorth(); if (!isObstacle(coordTemp)) { return true; } } if (x < dimension - 1) { coordTemp = coord.copy(); coordTemp.moveEast(dimension); if (!isObstacle(coordTemp)) { return true; } } if (y < dimension - 1) { coordTemp = coord.copy(); coordTemp.moveSouth(dimension); if (!isObstacle(coordTemp)) { return true; } } if (x > 0) { coordTemp = coord.copy(); coordTemp.moveWest(); if (!isObstacle(coordTemp)) { return true; } } return false; }
8
public Connection getConnectionWith(Neuron other){ for(int i=0;i<outputs.size();i++) if(outputs.get(i).getGiveNeuron()==other||outputs.get(i).getRecieveNeuron()==other) return outputs.get(i); for(int i=0;i<inputs.size();i++) if(inputs.get(i).getGiveNeuron()==other||inputs.get(i).getRecieveNeuron()==other) return inputs.get(i); return null; }
6
public LinkedList<Review> getOtherReviews(String reviewer, String isbn) throws SQLException { LinkedList<String> select = new LinkedList<String>(); select.add("*"); LinkedList<String> from = new LinkedList<String>(); from.add("Reviews"); LinkedList<Pair<String, String>> whereClauses = new LinkedList<Pair<String, String>>(); whereClauses.add(new Pair<String, String>("Reviewer<>?", username)); if (!reviewer.isEmpty()) { whereClauses.add(new Pair<String, String>("Reviewer=?", reviewer)); } if (!isbn.isEmpty()) { whereClauses.add(new Pair<String, String>("ISBN=?", isbn)); } LinkedList<String> whereConjunctions = new LinkedList<String>(); if (whereClauses.size() == 2) { whereConjunctions.add("AND"); } Pair<String, LinkedList<String>> orderBy = new Pair<String, LinkedList<String>>("(SELECT AVG(SCORE) " + "FROM Usefulness WHERE Usefulness.Reviewer = Reviews.Reviewer AND Usefulness.ISBN = Reviews.ISBN)", new LinkedList<String>()); String orderDirection = "DESC"; ResultSet resultSet = executeDynamicQuery(select, from, whereClauses, whereConjunctions, orderBy, orderDirection, 0); LinkedList<Review> result = new LinkedList<Review>(); while (resultSet.next()) { result.add(new Review(resultSet.getString(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4), resultSet.getString(5))); } return result; }
4
int bonuses(Token token) { int r = 0; if(right!=null) { r += Item.get(right,token); if(right==Item.Axe && left==null) r++; } if(left!=null) r += Item.get(left,token); for(Item e : items) r += Item.get(e, token); for(Token e : skills) { if(e==token) r++; } return r; }
7
public Activity find(long id) throws InstanceNotFoundException { Activity a = null; try { a = activities.get((int) id); } catch (ArrayIndexOutOfBoundsException e) { throw new InstanceNotFoundException(id, "Activity"); } return a; }
1
public void testWithField2() { Period test = new Period(1, 2, 3, 4, 5, 6, 7, 8); try { test.withField(null, 6); fail(); } catch (IllegalArgumentException ex) {} }
1
public void testSoundThread() throws Exception { System.out.println("playSoundThread"); MusicController mc = new MusicController(); Thread instance=new Thread (mc); // instance.start(); for(int i=0;i<150;i++){ System.out.println(i+" Seconds passed "); Thread.sleep(1000); } }
1
* @param elements Elemente der Menge der Objekt-Typen * * @throws ConfigurationChangeException Falls die Menge nicht am Objekt gespeichert werden konnte. */ private void setObjectSetTypeObjectTypes(ConfigurationArea configurationArea, ObjectSetType objectSetType, String[] elements) throws ConfigurationChangeException { NonMutableSet nonMutableSet = objectSetType.getNonMutableSet("ObjektTypen"); if(nonMutableSet == null) { // Menge neu erstellen final ConfigurationObjectType type = (ConfigurationObjectType)_dataModel.getType(Pid.SetType.OBJECT_TYPES); nonMutableSet = (NonMutableSet)configurationArea.createConfigurationObject(type, "", "ObjektTypen", null); objectSetType.addSet(nonMutableSet); _debug.finer("Menge der ObjektTypen für den Mengen-Typ mit der Pid '" + objectSetType.getPid() + "' wurde erstellt."); } else { setSystemObjectKeeping(nonMutableSet); } // Elemente der Menge ermitteln final Set<SystemObjectType> objectTypes = new LinkedHashSet<SystemObjectType>(); for(String element : elements) { // Element ist entweder im Datenmodell oder wurde just importiert final SystemObject object = getObject(element); if(object == null) throwNoObjectException(element); objectTypes.add((SystemObjectType)object); } // Menge überprüfen final List<SystemObject> elementsInVersion = nonMutableSet.getElementsInVersion(objectSetType.getConfigurationArea().getModifiableVersion()); // Erst alle überflüssigen entfernen. for(SystemObject systemObject : elementsInVersion) { SystemObjectType systemObjectType = (SystemObjectType)systemObject; if(!objectTypes.contains(systemObjectType)) { nonMutableSet.remove(systemObjectType); } } // Jetzt neue hinzufügen for(SystemObjectType objectType : objectTypes) { if(!elementsInVersion.contains(objectType)) { nonMutableSet.add(objectType); } } }
7
public CheckResultMessage checkE05(int day) { return checkReport.checkE05(day); }
0
public void uninstallUI(JComponent c) { super.uninstallUI(c); c.remove(rendererPane); rendererPane = null; }
0
public static Point getLayout(int numWindows, int maxX, int maxY) { // Look for rectangular layout Set<Integer> divisors = findDivisors(numWindows); for (int x : divisors) { int y = numWindows / x; if (x <= maxX && y <= maxY) { return new Point(x, y); } } // No rectangular layout found. Use a jagged one, possibly overflowing the screen. int x = (int)Math.ceil((double)numWindows / maxY); int y = maxY; return new Point(x, y); }
3
private int[] orderMerging(int[] a) { if(a.length == 1) return a; int leftLen = a.length / 2; int rightLen = a.length - leftLen; int[] left = new int[leftLen]; int[] right = new int[rightLen]; System.arraycopy(a, 0, left, 0, leftLen); System.arraycopy(a, leftLen, right, 0, rightLen); return merge(orderMerging(left), orderMerging(right)); }
1
public ListNode deleteDuplicates(ListNode head) { if (head == null) return null; ListNode p = head; ListNode t = head; p = p.next; while (p != null) { if (t.val == p.val) { p = p.next; } else { t.next = p; t = p; p = p.next; } } t.next = null; return head; }
3
private int getBonusMultiplier(Location loc){ Location toRemove = null; for(Location bonus : bonusSquares.keySet()){ if(loc.sameCoord(bonus)){ toRemove = bonus; break; } } if(toRemove != null){ int multiplier = bonusSquares.get(toRemove); bonusSquares.remove(toRemove); return multiplier; } return -1; }
3
@Override public PokerAction makeDecision(Card[] table, int small, int big, int amount, int potSize, int chipCount, int numPlayers, boolean allowedBet) { double random = Math.random()/(this.aggressiveness); if(table == null){ double winOdds = stats.getStat(numPlayers, currentHand); if(winOdds > 0.5 && allowedBet){ return new PokerAction(Action.BET, calculateBet(amount, chipCount, big, winOdds, potSize, numPlayers)); }else if(winOdds > 0.3){ return new PokerAction(Action.CALL, amount); }else{ return new PokerAction(Action.FOLD); } }else{ double hs = HandStrength.calculateHandStrength(currentHand, table, numPlayers-1); // System.out.println("numplayers = " + numPlayers); // System.out.println(this + " : " + hs); boolean shouldFold = (hs*(potSize) - amount) <= 0; if(hs + random > 0.7 && allowedBet && !shouldFold){ return new PokerAction(Action.BET, calculateBet(amount, chipCount, big, hs, potSize, numPlayers)); }else if(hs + random > 0.3 && !shouldFold){ return new PokerAction(Action.CALL, amount); }else{ return new PokerAction(Action.FOLD); } } }
9
public void areStreamsUp() { if (!streamList.isEmpty()) { for (;threadCount < streamList.size(); threadCount++) { new StreamIsUp(streamList.get(threadCount), threadCount, streamName.get(threadCount)).start(); } } }
2
public void showPersonMenu() { //Menüoptionen final int NEW_PERSON = 0; final int EDIT_PERSON = 1; final int DELETE_PERSON = 2; final int BACK = 3; //Personenverwaltungsmenü Menu maklerMenu = new Menu("Personen-Verwaltung"); maklerMenu.addEntry("Neue Person", NEW_PERSON); maklerMenu.addEntry("Person bearbeiten", EDIT_PERSON); maklerMenu.addEntry("Person löschen", DELETE_PERSON); maklerMenu.addEntry("Zurück zum Hauptmenü", BACK); //Verarbeite Eingabe while(true) { int response = maklerMenu.show(); switch(response) { case NEW_PERSON: newPerson(); break; case EDIT_PERSON: editPerson(); break; case DELETE_PERSON: deletePerson(); break; case BACK: return; } } }
5
public boolean shouldStore(final LocalExpr expr) { // We should store if there are more than 2 type 1 uses or // any uses of type greater than one-- which will be indicated // by type1s being greater than 2 // the parameter expr might be null, e.g., if this method is // called from "dups" in "!shouldStore((LocalExpr) expr.def())", // because if the expression is a use of a parameter in a method, // its definition is null. Return true in that case because it // will be saved to a local anyway if (expr == null) { return true; } final DefInformation DI = (DefInformation) defInfoMap.get(expr); if (DI == null) { if (StackOptimizer.DEBUG) { System.err .println("Error in StackOptimizer.shouldStore: parameter not found in defInfoMap:"); System.err.println(expr.toString()); } return true; } if ((DI.type1s > 2) || (DI.usesFound < DI.uses)) { return true; } else { return false; } }
5
public static JSONObject showUnauthorized() { JSONObject jo = new JSONObject(); try { jo.put("rtnCode", "401 unauthorized"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jo; }
1
public List<Integer> findMinHeightTrees(int n, int[][] edges) { if (n == 1) { return Collections.singletonList(0); } List<Set<Integer>> adj = new ArrayList<>(n); for (int i = 0; i < n; ++i) adj.add(new HashSet<>()); for (int[] edge : edges) { adj.get(edge[0]).add(edge[1]); adj.get(edge[1]).add(edge[0]); } List<Integer> leaves = new ArrayList<>(); for (int i = 0; i < adj.size(); i++) { if (adj.get(i).size() == 1) { leaves.add(i); } } while (n > 2) { n -= leaves.size(); List<Integer> newLeaves = new ArrayList<>(); for (int i : leaves) { int j = adj.get(i).iterator().next(); adj.get(j).remove(i); if (adj.get(j).size() == 1) { newLeaves.add(j); } } leaves = newLeaves; } return leaves; }
8
private String getPersistencyMethode() { File file = new File("init.dat"); String juist = null; if (file.exists()) { try { Scanner scanner = new Scanner(file); int tel = 0; while (scanner.hasNextLine()) { tel++; String fout = scanner.nextLine(); if (tel == 2) { juist = scanner.nextLine(); } } juist = juist.substring(20); if (scanner != null) { scanner.close(); } } catch (Exception e) { System.out.println(e.getMessage()); } } return juist; }
5
public void setOptions(String[] options) throws Exception { setDebug(Utils.getFlag('D', options)); String classIndex = Utils.getOption('c', options); if (classIndex.length() != 0) { if (classIndex.toLowerCase().equals("last")) { setClassIndex(0); } else if (classIndex.toLowerCase().equals("first")) { setClassIndex(1); } else { setClassIndex(Integer.parseInt(classIndex)); } } else { setClassIndex(0); } String trainIterations = Utils.getOption('x', options); if (trainIterations.length() != 0) { setTrainIterations(Integer.parseInt(trainIterations)); } else { setTrainIterations(50); } String trainPoolSize = Utils.getOption('T', options); if (trainPoolSize.length() != 0) { setTrainPoolSize(Integer.parseInt(trainPoolSize)); } else { setTrainPoolSize(100); } String seedString = Utils.getOption('s', options); if (seedString.length() != 0) { setSeed(Integer.parseInt(seedString)); } else { setSeed(1); } String dataFile = Utils.getOption('t', options); if (dataFile.length() == 0) { throw new Exception("An arff file must be specified" + " with the -t option."); } setDataFileName(dataFile); String classifierName = Utils.getOption('W', options); if (classifierName.length() == 0) { throw new Exception("A learner must be specified with the -W option."); } setClassifier(AbstractClassifier.forName(classifierName, Utils.partitionOptions(options))); }
8
@Override public ArrayList<Integer> findByType(String type) { ArrayList list = new ArrayList(); try { connection = getConnection(); ptmt = connection.prepareStatement("SELECT id FROM Task WHERE type=?;"); ptmt.setString(1, type); resultSet = ptmt.executeQuery(); while (resultSet.next()) { list.add(resultSet.getInt("id")); } } catch (SQLException ex) { Logger.getLogger(UserTypesDAO.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ptmt != null) { ptmt.close(); } if (connection != null) { connection.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { Logger.getLogger(UserTypesDAO.class.getName()).log(Level.SEVERE, null, ex); } } return list; }
6
public DataPair split(int feat){ HashSet<Integer> index = new HashSet<Integer>(); int[] examples = data.get(new Integer(feat)); if (examples == null) return null; for (int i=0; i < examples.length; i++){ index.add( examples[i] ); } TreeMap<Integer, Integer> leftLabels = new TreeMap<Integer,Integer>(); TreeMap<Integer, Integer> rightLabels = new TreeMap<Integer,Integer>(); for (Map.Entry<Integer,Integer> entry : labels.entrySet()){ if (index.contains( entry.getKey() )){ leftLabels.put( entry.getKey(), entry.getValue()); }else{ rightLabels.put( entry.getKey(), entry.getValue()); } } TreeMap<Integer, int[]> leftMap = new TreeMap<Integer, int[]>(); TreeMap<Integer, int[]> rightMap = new TreeMap<Integer, int[]>(); for (Map.Entry<Integer, int[]> entry : data.entrySet()){ ArrayList<Integer> leftList = new ArrayList<Integer>(); ArrayList<Integer> rightList = new ArrayList<Integer>(); examples = entry.getValue(); for (int j=0; j < examples.length; j++){ if (index.contains(examples[j])){ leftList.add(examples[j]); }else{ rightList.add(examples[j]); } } if (leftList.size() > 0) leftMap.put(entry.getKey(), toIntArray(leftList)); if (rightList.size() > 0) rightMap.put(entry.getKey(), toIntArray(rightList)); } Data leftData = new Data(leftLabels, leftMap); Data rightData = new Data(rightLabels, rightMap); // System.out.printf("split = %d(%d) | %d(%d)\n" , leftData.getNumExamples(), leftData.getMajority(), rightData.getNumExamples(), rightData.getMajority()); return new DataPair(leftData, rightData); }
9
public void write(ByteBuffer block, int offset) throws IOException { this.channel.write(block, offset); }
0
public static String transformLabel(Tree<String> tree) { String transformedLabel = tree.getLabel(); int cutIndex = transformedLabel.indexOf('-'); int cutIndex2 = transformedLabel.indexOf('='); int cutIndex3 = transformedLabel.indexOf('^'); if (cutIndex2 > 0 && (cutIndex2 < cutIndex || cutIndex == -1)) cutIndex = cutIndex2; if (cutIndex3 > 0 && (cutIndex3 < cutIndex || cutIndex == -1 )) { cutIndex = cutIndex3; } if (cutIndex > 0 && ! tree.isLeaf()) { transformedLabel = new String(transformedLabel.substring(0,cutIndex)); } return transformedLabel; }
8
private static int[] EachPlayerIO(){ // This will take inputs of visions for each player in turn, and give them their // visions immediately. int[] randOrder = getRandomOrdering(NumPlayers); // randOrder now contains a randomised ordering of indices. boolean[] CanSee = RunningGame.CheckLiveSeers(); boolean[] CanWolf = RunningGame.CheckLiveWolves(); int[] Attacks = new int[NumPlayers]; for(int i = 0; i < NumPlayers; i++){ int n = randOrder[i]; if(CanSee[n]){ int Target = ui.inputSeerTarget(n+1); byte Vision = RunningGame.HaveSingleVision(n+1,Target); ui.displaySingleVision(n+1,Target,Vision); RunningGame.SingleVisionAllStates(n+1, Target, Vision); History.SaveVision(RunningGame.getRoundNum(), n+1, Target, Vision); RunningGame.UpdateProbabilities(); CanSee = RunningGame.CheckLiveSeers(); CanWolf = RunningGame.CheckLiveWolves(); } if(CanWolf[n]){ int Target = ui.InputSingleWolfTarget(n+1); Attacks[n] = Target; History.SaveAttack(RunningGame.getRoundNum(), (n+1), Target); } else { Attacks[n] = 0; } } return Attacks; }
3
private static <E> CycList<CycList<E>> combinationsOfInternal(final CycList<E> selectedItems, final CycList<E> availableItems) { final CycList<CycList<E>> result = CycList.list(selectedItems); if (availableItems.size() == 0) { return result; } CycList<E> combination = null; for (int i = 0; i < (selectedItems.size() - 1); i++) { for (int j = 0; j < availableItems.size(); j++) { final E availableItem = availableItems.get(j); // Remove it (making copy), shift left, append replacement. combination = (CycList) selectedItems.clone(); combination.remove(i + 1); combination.add(availableItem); result.add(combination); } } final CycList newSelectedItems = (CycList) selectedItems.rest(); newSelectedItems.add(availableItems.first()); final CycList newAvailableItems = (CycList) availableItems.rest(); result.addAll(combinationsOfInternal(newSelectedItems, newAvailableItems)); return result; }
3
public static String[] readLgooFile(String path) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader( path)); } catch (FileNotFoundException e1) { e1.printStackTrace(); System.out.println("file not found"); } String line = null; String[] tempArray = new String[getOlympianNumber(path)]; int i = 0; try { line = reader.readLine(); if (line.equals("LGOO")) { while ((line = reader.readLine()) != null) { tempArray[i] = line; i++; } } else { System.out.println("Can not read file, it is not of type LGOO"); } } catch (IOException e) { System.out.println("File can not be read"); } try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tempArray; }
5
public static String parseErrorMessage(String errorMessage) { StringBuilder response = new StringBuilder(); Pattern pattern = Pattern.compile(".*?/series/(\\d*?)/default/(\\d*?)/(\\d*?)/.*?"); Matcher matcher = pattern.matcher(errorMessage); // See if the error message matches the pattern and therefore we can decode it if (matcher.find() && matcher.groupCount() == ERROR_MSG_GROUP_COUNT) { int seriesId = Integer.parseInt(matcher.group(ERROR_MSG_SERIES)); int seasonId = Integer.parseInt(matcher.group(ERROR_MSG_SEASON)); int episodeId = Integer.parseInt(matcher.group(ERROR_MSG_EPISODE)); response.append("Series Id: ").append(seriesId); response.append(", Season: ").append(seasonId); response.append(", Episode: ").append(episodeId); response.append(": "); if (episodeId == 0) { // We should probably try an scrape season 0/episode 1 response.append("Episode seems to be a misnamed pilot episode."); } else if (episodeId > MAX_EPISODE) { response.append("Episode number seems to be too large."); } else if (seasonId == 0 && episodeId > 1) { response.append("This special episode does not exist."); } else if (errorMessage.toLowerCase().contains(ERROR_NOT_ALLOWED_IN_PROLOG)) { response.append(ERROR_RETRIEVE_EPISODE_INFO); } else { response.append("Unknown episode error: ").append(errorMessage); } } else // Don't recognise the error format, so just return it { if (errorMessage.toLowerCase().contains(ERROR_NOT_ALLOWED_IN_PROLOG)) { response.append(ERROR_RETRIEVE_EPISODE_INFO); } else { response.append("Episode error: ").append(errorMessage); } } return response.toString(); }
8
public void Update(GameTime gameTime) { mMenu.Update(); if (!mMenu.IsMenuItemSelected()) { mMenu.SelectMenuItem(new Vector2(mInput.GetMouseX(), GameProperties.WindowHeight() - mInput.GetMouseY())); if (mInput.IsMouseHit(0)) { switch(mMenu.GetSelected()) { case 0: { gameTime.UnPause(); UnLoad(); } break; case 1: { mNextState = new GameState_GraphicsMenu(mGame); } break; case 2: { gameTime.UnPause(); mGame.UnLoad(); UnLoad(); } break; } } } }
5
protected JPanel buildSortPanel() { JPanel ans = new JPanel(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); ans.setLayout(layout); // c.fill = GridBagConstraints.HORIZONTAL; nameSort = new JRadioButton(""); JRadioButton noSort = new JRadioButton("ѧ", true); dec = new JCheckBox(""); ButtonGroup group = new ButtonGroup(); group.add(nameSort); group.add(noSort); // ¼ nameSort.setActionCommand("resort"); noSort.setActionCommand("resort"); dec.setActionCommand("resort"); nameSort.addActionListener(this); noSort.addActionListener(this); dec.addActionListener(this); // c.gridheight = GridBagConstraints.REMAINDER; layout.setConstraints(nameSort, c); ans.add(nameSort); c.gridx = GridBagConstraints.RELATIVE; layout.setConstraints(noSort, c); ans.add(noSort); c.gridwidth = GridBagConstraints.REMAINDER; layout.setConstraints(dec, c); ans.add(dec); return ans; }
0
public static <T> boolean equals(T[][] matrix, T[][] withMatrix) throws NullPointerException { if (matrix == withMatrix) return true; if (matrix == null && withMatrix == null) return true; if (matrix == null || withMatrix == null) return false; int width = getWidth(matrix); int height = getHeight(matrix); if (width != getWidth(withMatrix) && height != getHeight(withMatrix)) return false; for (int i = 0; i < width; i++) { if (!Arrays.equals(matrix[i], withMatrix[i])) return false; } return true; }
9
public float priorityFor(Actor actor) { if (storeShortage() <= 0) { if (sumHarvest() > 0) return Plan.ROUTINE ; else done = true ; } final float hunger = actor.health.hungerLevel() ; if (store == null && hunger <= 0) done = true ; if (done) return 0 ; float impetus = 0 ; impetus += hunger * Plan.PARAMOUNT ; impetus *= actor.traits.chance(CULTIVATION, MODERATE_DC) ; impetus *= actor.traits.chance(HARD_LABOUR, ROUTINE_DC) ; if (hunger > 0.5f) { final float scale = (hunger - 0.5f) * 2 ; impetus = (impetus * (1 - scale)) + (PARAMOUNT * scale) ; } if (source == null || source.destroyed()) { source = Forestry.findCutting(actor) ; if (source == null) return 0 ; } impetus -= Plan.rangePenalty(actor, source) ; impetus -= Plan.dangerPenalty(source, actor) ; impetus += priorityMod ; return impetus ; }
9
public EntityPlayer updateInput() { if (Keyboard.isKeyDown(Keyboard.KEY_W)) { position.y -= speed; currentY -= speed; } if (Keyboard.isKeyDown(Keyboard.KEY_A)) { position.x -= speed; currentX -= speed; } if (Keyboard.isKeyDown(Keyboard.KEY_S)) { position.y += speed; currentY += speed; } if (Keyboard.isKeyDown(Keyboard.KEY_D)) { position.x += speed; currentX += speed; } return this; }
4
public void testProperty() { LocalDate test = new LocalDate(2005, 6, 9, GJ_UTC); assertEquals(test.year(), test.property(DateTimeFieldType.year())); assertEquals(test.monthOfYear(), test.property(DateTimeFieldType.monthOfYear())); assertEquals(test.dayOfMonth(), test.property(DateTimeFieldType.dayOfMonth())); assertEquals(test.dayOfWeek(), test.property(DateTimeFieldType.dayOfWeek())); assertEquals(test.dayOfYear(), test.property(DateTimeFieldType.dayOfYear())); assertEquals(test.weekOfWeekyear(), test.property(DateTimeFieldType.weekOfWeekyear())); assertEquals(test.weekyear(), test.property(DateTimeFieldType.weekyear())); assertEquals(test.yearOfCentury(), test.property(DateTimeFieldType.yearOfCentury())); assertEquals(test.yearOfEra(), test.property(DateTimeFieldType.yearOfEra())); assertEquals(test.centuryOfEra(), test.property(DateTimeFieldType.centuryOfEra())); assertEquals(test.era(), test.property(DateTimeFieldType.era())); try { test.property(DateTimeFieldType.millisOfDay()); fail(); } catch (IllegalArgumentException ex) {} try { test.property(null); fail(); } catch (IllegalArgumentException ex) {} }
2
public void setPrice(float price) { this.price = price; }
0
protected SchlangenGlied(Rectangle masse, IntHolder unit, Color color) { super(masse, unit); this.color = color; }
0
public void deleteMessage(String sender, String receiver, String message, int sentBy) { db.deleteMessage(sender, receiver, message); if((sentBy == ServerInterface.CLIENT) && (backupServer != null)) { try { backupServer.ping(); backupServer.deleteMessage(sender, receiver, message, ServerInterface.SERVER); } catch(Exception ex) { System.out.println("backup Server not responding"); resetBackupServer(); } } }
3
public void accept(Visitor visitor) { if (visitor.visit(this)) { if (sour != null) { sour.accept(visitor); } if (date != null) { date.accept(visitor); } if (subm != null) { subm.accept(visitor); } if (subn != null) { subn.accept(visitor); } if (gedc != null) { gedc.accept(visitor); } if (charset != null) { charset.accept(visitor); } super.visitContainedObjects(visitor); visitor.endVisit(this); } }
7
public void draw(Graphics g) { Image I; boolean noBonus = false; I = map.game.getImages().getBonusBomb(); switch(type) { case 1: I = map.game.getImages().getBonusBomb(); break; case 2: I = map.game.getImages().getBonusStrike(); break; case 3: I = map.game.getImages().getBonusSpeed(); break; default: noBonus = true; } if (!noBonus) { g.drawImage(I, x*10, y*10, null); } }
4
boolean treeContains(CoreInterface ci){ if(ci.getClass() == Dvd.class){ if(dvdTree.contains(ci)){ return true; } return false; }else if(ci.getClass() == Location.class){ if(locationTree.contains(ci)){ return true; } return false; }else if(ci.getClass() == Genre.class){ if(genreTree.contains(ci)){ return true; } return false; } return false; }
6
public String updateDailyScheduleRequest(Sport sport, int year, String month, String day) { String request = null; switch(sport) { case NBA: case NHL: request = "http://api.sportsdatallc.org/" + sport.getName() + "-" + access_level + sport.getVersion() + "/games/" + year + "/" + month + "/" + day + "/schedule.xml?api_key=" + sport.getKey(); Element element = send(request); try { String scheduleID = null, scheduleStatus = null;; Node node = null; NodeList gameNodes = element.getElementsByTagName("game"); for (int i=0;i<gameNodes.getLength();i++) { NamedNodeMap nodeMapGameAttributes = gameNodes.item(i).getAttributes(); node = nodeMapGameAttributes.getNamedItem("id"); scheduleID = node.getNodeValue(); // status : closed, inprogress, scheduled, postponed node = nodeMapGameAttributes.getNamedItem("status"); scheduleStatus = node.getNodeValue(); ResultScoreModel resultScoreModel = DataStore.getScoreResultsBySchedule(scheduleID); if ( scheduleStatus.equals("closed") && resultScoreModel==null) { return scheduleID; } } } catch (Exception e) { System.out.println("@ erreur lors du parcours du fichier xml dans getScheduleRequest()"); return null; } break; default: break; } return null; }
6
public HiloBean load(HiloBean oHilo) throws NumberFormatException, ParseException { try { if ((request.getParameter("nombre") != null)) { oHilo.setNombre(request.getParameter("nombre")); } if ((request.getParameter("fecha") != null)) { oHilo.setFecha(new SimpleDateFormat("dd-MM-yyyy").parse(request.getParameter("fecha"))); } } catch (NumberFormatException e) { throw new NumberFormatException("Controller: Error: Load: Formato de datos en parámetros incorrecto " + e.getMessage()); } return oHilo; }
3
@Override public void paintComponents(Graphics g) { if (this.skin.getLocaleButtonVisible()) { Graphics g2 = g.create(); int x, y; int w, h; if (this.skin.isChanged() || (this.ground == null)) { try { String p = this.skin.getImgPath_StandardBtn(Imagetype.DEFAULT).toString() .replaceFirst(Constants.DEFAULT_SKINIMAGE_TYPE, Constants.DEFAULT_INPUTIMAGE_TYPE); this.ground = ImageIO.read(new File(p)); } catch (IOException e) { ; } } w = 32; h = 28; x = 10; y = 10; g2.drawImage(this.ground, x, y, w, h, null); g2.setColor(Color.WHITE); g2.setFont(this.font); g2.drawString("EN", x + 7, y + 18); } }
4
public byte[] getG() { return g; }
0
@Override public void actionPerformed(ActionEvent e) { repaint(); }
0
public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException { SimpleInterface simpleInterface = new SimpleClass(); simpleInterface.method(3, new SimpleClass()); simpleInterface.method(3); simpleInterface.someOtherMethod(); }
0
public void extractConfig(final String resource, final boolean replace) { final File config = new File(this.getDataFolder(), resource); if (config.exists() && !replace) return; this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() }); config.getParentFile().mkdirs(); final char[] cbuf = new char[1024]; int read; try { final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE)); final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET)); while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read); out.close(); in.close(); } catch (final Exception e) { throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e); } }
4
public static void main(String[] args) { int myPoint = 0; Status gameStatus; int sumOfDice = rollDice(); switch ( sumOfDice ) { case SEVEN: case YO_LEVEN: gameStatus = Status.WON; break; case SNAKE_EYES: case TREY: case BOX_CARS: gameStatus = Status.LOST; break; default: gameStatus = Status.CONINUE; myPoint = sumOfDice; System.out.printf("Point is %d\n", myPoint); break; } while (gameStatus == Status.CONINUE) { sumOfDice = rollDice(); if( sumOfDice == myPoint ) gameStatus = Status.WON; else if( sumOfDice == SEVEN ) gameStatus = Status.LOST; } if( gameStatus == Status.WON ) { System.out.println("Paleyer Wins"); } else System.out.println("Player Loses"); }
9
private Map<String, List> addStormsFromYear(DefaultMutableTreeNode root, String year) { DefaultMutableTreeNode yearRoot; try{ StormSet stormSet = new StormSet(new File("noaaStormCoords" + year + ".gpx")); yearRoot = new DefaultMutableTreeNode(year); root.add(yearRoot); Map<String, List> storms = stormSet.getStorms(); Iterator stormIterator = storms.keySet().iterator(); while(stormIterator.hasNext()){ String stormName = (String)stormIterator.next(); DefaultMutableTreeNode stormNode = new DefaultMutableTreeNode(stormName); yearRoot.add(stormNode); List<RoutePoint> routePoints = storms.get(stormName); Iterator pointIterator = routePoints.iterator(); while(pointIterator.hasNext()){ RoutePoint point = (RoutePoint)pointIterator.next(); stormNode.add(new DefaultMutableTreeNode(point.getTime() + " (" + point.getLatitude() + ", " + point.getLongitude() + ")")); } } return storms; }catch(Exception e){ yearRoot = new DefaultMutableTreeNode("Failed to load year " + year); root.add(yearRoot); return null; } }
3
public int getVertical(int i, int j, int r) { int sum = 0; int imax = this.length; int jmax = this.width; for (int n = 0; n <= 2 * r; n++) { int ii = topo.idI(i - r + n, j, imax, jmax); int jj = topo.idJ(i, j, imax, jmax); if ( (!(ii < 0) && !(ii >= imax)) && (!(jj < 0) && !(jj >= jmax)) && (ii != i || jj != j ) ) { sum += this.getCell(ii, jj).toBit(); } } return sum; }
7
public void cancelTimer(The5zigModTimer timer) { timer.cancel(getPlayer()); }
0
public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_LEFT); velx = -5; if(e.getKeyCode() == KeyEvent.VK_D || e.getKeyCode() == KeyEvent.VK_RIGHT); velx = 5; }
4
private void addParserNoticeHighlights(ParseResult res) { // Parsers are supposed to return at least empty ParseResults, but // we'll be defensive here. if (res==null) { return; } if (DEBUG_PARSING) { System.out.println("[DEBUG]: Adding parser notices from " + res.getParser()); } if (noticeHighlightPairs==null) { noticeHighlightPairs = new ArrayList(); } removeParserNotices(res); List notices = res.getNotices(); if (notices.size()>0) { // Guaranteed non-null RSyntaxTextAreaHighlighter h = (RSyntaxTextAreaHighlighter) textArea.getHighlighter(); for (Iterator i=notices.iterator(); i.hasNext(); ) { ParserNotice notice = (ParserNotice)i.next(); if (DEBUG_PARSING) { System.out.println("[DEBUG]: ... adding: " + notice); } try { Object highlight = null; if (notice.getShowInEditor()) { highlight = h.addParserHighlight(notice, parserErrorHighlightPainter); } noticeHighlightPairs.add(new NoticeHighlightPair(notice, highlight)); } catch (BadLocationException ble) { // Never happens ble.printStackTrace(); } } } if (DEBUG_PARSING) { System.out.println("[DEBUG]: Done adding parser notices from " + res.getParser()); } }
9
public int typeCode() { if (desc.length() == 1) { switch (desc.charAt(0)) { case BOOLEAN_CHAR: return Type.BOOLEAN_CODE; case CHARACTER_CHAR: return Type.CHARACTER_CODE; case FLOAT_CHAR: return Type.FLOAT_CODE; case DOUBLE_CHAR: return Type.DOUBLE_CODE; case BYTE_CHAR: return Type.BYTE_CODE; case SHORT_CHAR: return Type.SHORT_CODE; case INTEGER_CHAR: return Type.INTEGER_CODE; case LONG_CHAR: return Type.LONG_CODE; } } throw new IllegalArgumentException("Invalid type descriptor: " + desc); }
9
public Collection<? extends Object> search(Object obj, Connection conn) { if(obj instanceof Aluno){ return this.listAll(this.createSelectAlunoHistoricoCmd((Aluno)obj), conn); } else if(obj instanceof Turma){ return this.listAll(this.createSelectAlunosTurmaCmd((Turma)obj), conn); } return new ArrayList<Object>(); }
3
public static void main(String[] args) throws IOException { // file names : dealreport.txt and Serialized_Deals.dat String fileNames[] = {"dealreport.txt", "Serialized_Deals.dat"}; try { ZipOutputStream out_zip = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream("out_zip.zip"))); for(String fileName : fileNames ){ BufferedInputStream bf_str = new BufferedInputStream(new FileInputStream(fileName)); out_zip.putNextEntry(new ZipEntry(fileName)); int in_int = 0; while( (in_int = bf_str.read()) != -1 ){ out_zip.write(in_int); } bf_str.close(); } out_zip.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3
public double nextValue(int generatorID) { long k,s; double u=0.0; if( generatorID>Maxgen) System.out.println( "ERROR: Genval with g > Maxgen\n"); s=Cg[0][generatorID]; k=s/46693; s=45991*(s-k*46693)-k*25884; if( s<0) s+=2147483647; Cg[0][generatorID]=s; u+=(4.65661287524579692e-10*s); s=Cg[1][generatorID]; k=s/10339; s=207707*(s-k*10339)-k*870; if( s<0) s+=2147483543; Cg[1][generatorID]=s; u-=(4.65661310075985993e-10*s); if( u<0) u+=1.0; s=Cg[2][generatorID]; k=s/15499; s=138556*(s-k*15499)-k*3979; if( s<0.0) s+=2147483423; Cg[2][generatorID]=s; u+=(4.65661336096842131e-10*s); if( u>=1.0) u-=1.0; s=Cg[3][generatorID]; k=s/43218; s=49689*(s-k*43218)-k*24121; if( s<0) s+=2147483323; Cg[3][generatorID]=s; u-=(4.65661357780891134e-10*s); if( u<0) u+=1.0; return (u); }
8
public static ArrayList<String> searchTicketProduct(Integer ID) { Database db = dbconnect(); ArrayList<String> Array = new ArrayList<String>(); try { String query = ("SELECT name FROM ticket_products WHERE TID = ?"); db.prepare(query); db.bind_param(1, ID.toString()); ResultSet rs = db.executeQuery(); while(rs.next()) { Array.add(rs.getString(rs.getMetaData().getColumnName(1))); } db.close(); } catch (SQLException e) { Error_Frame.Error(e.toString()); } return Array; }
2
public void startServer(int port) throws CouldNotStartServerException { logger.fine("Starting server on port " + port + "..."); synchronized(CONNECTION_LOCK) { if(isRunning) { logger.fine("Server is already started!"); throw new ServerAlreadyStartedException(); } try { socket = new DatagramSocket(port); receivePacketThread = new ReceivePacketThread(this, socket); receivePacketThread.start(); timeoutThread = new ServerTimeoutThread(this, Server.CLIENT_TIMEOUT); timeoutThread.start(); isRunning = true; logger.fine("Server is open and receiving connections!"); } catch (SocketException e) { closeConnection(); logger.fine("Could not start server due to SocketException: " + e.getMessage()); throw new CouldNotOpenServerSocketException(e, port); } } }
2
private SlotState checkVerticalLines() { if(!((GridSlot)board[0][0]).isEmpty() && ((GridSlot)board[0][0]).getState().equals(((GridSlot)board[1][0]).getState()) && ((GridSlot)board[1][0]).getState().equals(((GridSlot)board[2][0]).getState())) { return ((GridSlot)board[0][0]).getState(); } else if(!((GridSlot)board[0][1]).isEmpty() && ((GridSlot)board[0][1]).getState().equals(((GridSlot)board[1][1]).getState()) && ((GridSlot)board[1][1]).getState().equals(((GridSlot)board[2][1]).getState())) { return ((GridSlot)board[0][1]).getState(); } else if(!((GridSlot)board[0][2]).isEmpty() && ((GridSlot)board[0][2]).getState().equals(((GridSlot)board[1][2]).getState()) && ((GridSlot)board[1][2]).getState().equals(((GridSlot)board[2][2]).getState())) { return ((GridSlot)board[0][2]).getState(); } return null; }
9
private JPanel getPanelOfComponents() { JPanel panel = new JPanel(); toStringT = new JTextField(30); toStringT.setFont(new Font("COURIER", Font.BOLD, 20)); panel.add(toStringT); return panel; }
0
public static void main(String[] args) { //standard input Scanner in = new Scanner(System.in); int n = in.nextInt(); //if no temperatures provided if(n <= 0) { System.out.println(0); in.close(); return; } //find the closest number to the zero Integer closest = null; for(int i = 0; i < n; i++) { int current = in.nextInt(); if(closest == null || Math.abs(closest) > Math.abs(current) || Math.abs(closest) == Math.abs(current) && closest < current) closest = current; } System.out.println(closest); in.close(); }
6
@Override public Action postAction(Action a) throws JSONException, BadResponseException { Representation r = new JsonRepresentation(a.toJSON()); r = serv.postResource("intervention/" + interId + "/action", a.getUniqueID(), r); Action action = null; try { action = new Action(new JsonRepresentation(r).getJsonObject()); } catch (InvalidJSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return action; }
2
@Override public boolean equals(Object o) { if (o.getClass() != Tree.class) return false; Tree t = (Tree)o; LinkedList list = toLinkedList(); while (list.hasNext()) if (!t.contains(list.getNext())) return false; return size == t.size(); }
3
private void sendEventsToThem(Set<SimpleEntity> loadedEntities, int createdIfIdGreaterThan) { for (SimpleEntity entity : loadedEntities) { Map<Class<? extends Component>, Component> components = new HashMap<>(); for (Map.Entry<Class<? extends Component>, Component> originalComponents : entity.entityValues.entrySet()) { components.put(originalComponents.getKey(), internalComponentManager.copyComponentUnmodifiable(originalComponents.getValue(), false)); } SimpleEntityRef entityRef = createSimpleEntityRef(entity, false); if (entity.getEntityId() <= createdIfIdGreaterThan) { entityRef.send(new AfterEntityLoaded(components)); } else { entityRef.send(new AfterComponentAdded(components)); } } }
5
public static boolean login(String userName, String password) { try { String parameters = "user=" + URLEncoder.encode(userName, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&version=" + URLEncoder.encode(GlobalVar.Version, "UTF-8"); String result = Utils.excutePost(GlobalVar.AuthURL, parameters); if (!result.contains(":")) { if (result.trim().equals("Bad login")) { JOptionPane.showMessageDialog( null, "Неправильный логин или пароль!", "Ошибка", JOptionPane.WARNING_MESSAGE); return false; } else if (result.trim().equals("Old version")) { JOptionPane.showMessageDialog( null, "Нужно обновить лаунчер!", "Ошибка", JOptionPane.WARNING_MESSAGE); openLink(new URI(GlobalVar.DownloadNewLauncherURL)); //System.exit(0); //Close launcher and open download launcher link return false; } else { JOptionPane.showMessageDialog( null, result, "Неизвестная ошибка", JOptionPane.ERROR_MESSAGE); return false; } } String[] values = result.split(":"); GlobalVar.userName = values[2].trim(); GlobalVar.latestVersion = values[0].trim(); GlobalVar.downloadTicket = values[1].trim(); GlobalVar.sessionId = values[3].trim(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
4
public Node getHeadNode(int linkedListLength){ if(linkedListLength==0){ return null; } Node node = new Node(); node.setData(count); count++; node.setNextNode(getHeadNode(linkedListLength-1)); return node; }
1
public static String combineStringArray(String[] words, String separator) { String string = ""; for (String word : words) { if (!string.isEmpty()) string += separator; string += word; } return string; }
2
public void addIntersectionAtCanvasLocation(int canvasX, int canvasY) { // FIRST MAKE SURE THE ENTIRE INTERSECTION IS INSIDE THE LEVEL if ((canvasX - INTERSECTION_RADIUS) < 0) return; if ((canvasY - INTERSECTION_RADIUS) < 0) return; if ((canvasX + INTERSECTION_RADIUS) > viewport.levelWidth) return; if ((canvasY + INTERSECTION_RADIUS) > viewport.levelHeight) return; // AND ONLY ADD THE INTERSECTION IF IT DOESN'T OVERLAP WITH // AN EXISTING INTERSECTION for(Intersection i : level.intersections) { double distance = calculateDistanceBetweenPoints(i.x-viewport.x, i.y-viewport.y, canvasX, canvasY); if (distance < INTERSECTION_RADIUS) return; } // LET'S ADD A NEW INTERSECTION int intX = canvasX + viewport.x; int intY = canvasY + viewport.y; Intersection newInt = new Intersection(intX, intY); level.intersections.add(newInt); view.getCanvas().repaint(); }
6
public List<List<SetCard>> findMatches() { //don't even bother if there aren't enough cards if (cards.size() < 3) { return null; } /* * iterate through all of the cards, getting all possible permutations * of SetCards... */ for (int i = 0; i < cards.size(); i++) { SetCard card1 = cards.get(i); for (int j = 1; j < cards.size(); j++) { SetCard card2 = cards.get(j); for (int k = 2; k < cards.size(); k++) { SetCard card3 = cards.get(k); //...and adding them to a temporary HashSet. LinkedHashSet<SetCard> tempCardSet = new LinkedHashSet<SetCard>(); tempCardSet.add(card1); tempCardSet.add(card2); tempCardSet.add(card3); //check that there aren't any duplicates if (tempCardSet.size() == 3) { //convert back to List if check passes List<SetCard> tempList = new LinkedList<SetCard>(tempCardSet); /* * if the cards are a set, add them to results * and remove them from the master list of cards, * so that they're not used again */ if (isSet(tempList)) { matches.add(tempList); cards.removeAll(tempList); } } } } } return matches; }
6
public void calcEffectiveRefractiveIndices(){ if(this.setMeasurementsTEgrating)this.calcTEmodeEffectiveRefractiveIndices(); if(this.setMeasurementsTMgrating)this.calcTMmodeEffectiveRefractiveIndices(); }
2
public Map getRecordByID(String table, String primaryKeyField, Object keyValue, boolean closeConnection) throws SQLException, Exception { Statement stmt = null; ResultSet rs = null; ResultSetMetaData metaData = null; final Map record = new HashMap(); // do this in an excpetion handler so that we can depend on the // finally clause to close the connection try { stmt = conn.createStatement(); String sql2; if (keyValue instanceof String) { sql2 = "= '" + keyValue + "'"; } else { sql2 = "=" + keyValue; } final String sql = "SELECT * FROM " + table + " WHERE " + primaryKeyField + sql2; rs = stmt.executeQuery(sql); metaData = rs.getMetaData(); metaData.getColumnCount(); final int fields = metaData.getColumnCount(); // Retrieve the raw data from the ResultSet and copy the values into a Map // with the keys being the column names of the table. if (rs.next()) { for (int i = 1; i <= fields; i++) { record.put(metaData.getColumnName(i), rs.getObject(i)); } } } catch (SQLException sqle) { throw sqle; } catch (Exception e) { throw e; } finally { try { stmt.close(); if (closeConnection) { conn.close(); } } catch (SQLException e) { throw e; } // end try } // end finally return record; }
7
@Override public void mouseWheelMoved(MouseWheelEvent e) { float notches = e.getWheelRotation(); final double BY = 0.05; if (notches > 0) { vscale *= (1 + BY); } else { vscale *= (1 - BY); } setScale(vscale); repaint(); }
1
public Map<String, String> getStyles() { if (styles == null) { styles = new HashMap<String, String>(); } return styles; }
1
@EventHandler(priority = EventPriority.MONITOR) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); World world = player.getWorld(); String worldname = world.getName(); String playername = player.getName(); Boolean staff = false; double x = (int) Math.floor(player.getLocation().getX()); double y = (int) Math.floor(player.getLocation().getY()); double z = (int) Math.floor(player.getLocation().getZ()); if (getConfig.PlayerQuit()) { if (player.hasPermission("PlayerLogger.staff")) { staff = true; } if (getConfig.logFilesEnabled()) { filehandler.logQuit(playername, worldname, x, y, z, staff); } if (getConfig.MySQLEnabled()) { addData.add(playername,"quit", "", x, y, z, worldname, staff); }}}
4
public int saveContact(enmSavingMode aSavingMode, clsContactsDetails aContactDetails) throws SQLException { //The creation id in the database. int mIDContacts = 0; //Create the entry in the Contacts table. String mFormattedBirthdayDate = ""; if (aContactDetails.getBirthday() != null) { SimpleDateFormat mSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mFormattedBirthdayDate = mSDF.format(aContactDetails.getBirthday()); } else { mFormattedBirthdayDate = "0000-00-00 00:00:00"; } switch (aSavingMode) { case New: //Build SQL. clsSQL mSQLCreateModifiedEntry = new clsSQL(clsSQL.enmSQLType.Insert); mSQLCreateModifiedEntry.addField(new clsSQLField("Modifications", "CreationDate", "NOW()")); mSQLCreateModifiedEntry.addField(new clsSQLField("Modifications", "ModificationDate", "NOW()")); //Create the entry in the Modifications table. //String mSQLCreateModifiedEntry = "INSERT INTO Modifications (CreationDate, ModificationDate) VALUES (NOW(), NOW());"; ResultSet mCreatedIDsInModified = this.pProgram.getDatabase().QueryExecuteCreatedID(mSQLCreateModifiedEntry); //Get the newly inserted IDs. int mIDModifications = 0; while (mCreatedIDsInModified.next()) { mIDModifications = mCreatedIDsInModified.getInt(1); break; } //Build SQL. clsSQL mSQLContactNew = new clsSQL(clsSQL.enmSQLType.Insert); mSQLContactNew.addField(new clsSQLField("Contacts", "ID_Modifications", "" + mIDModifications + "")); mSQLContactNew.addField(new clsSQLField("Contacts", "FirstName", "'" + aContactDetails.getFirstName() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "MiddleName", "'" + aContactDetails.getMiddleName() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "LastName", "'" + aContactDetails.getLastName() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Birthday", "'" + mFormattedBirthdayDate + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Gender", "'" + aContactDetails.getGender() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Street", "'" + aContactDetails.getStreet() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Postcode", "'" + aContactDetails.getPostcode() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "City", "'" + aContactDetails.getCity() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Country", "'" + aContactDetails.getCountry() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Comment", "'" + aContactDetails.getComment() + "'")); mSQLContactNew.addField(new clsSQLField("Contacts", "Availability", "'" + aContactDetails.getAvailability() + "'")); //mSQLContact = "INSERT INTO Contacts (ID_Modifications, FirstName, MiddleName, LastName, Birthday, Gender, Street, Postcode, City, Country, Comment, Availability) VALUES (" + mIDModifications + ", '" + aContactDetails.getFirstName() + "', '" + aContactDetails.getMiddleName() + "', '" + aContactDetails.getLastName() + "', '" + mFormattedBirthdayDate + "', '" + aContactDetails.getGender() + "', '" + aContactDetails.getStreet() + "', '" + aContactDetails.getPostcode() + "', '" + aContactDetails.getCity() + "', '" + aContactDetails.getCountry() + "', '" + aContactDetails.getComment() + "', '" + aContactDetails.getAvailability() + "');"; //Insert the contact. ResultSet mRSCreatedIDs = this.pProgram.getDatabase().QueryExecuteCreatedID(mSQLContactNew); mRSCreatedIDs.first(); while (mRSCreatedIDs.isAfterLast() == false) { mIDContacts = mRSCreatedIDs.getInt(1); break; } break; case Modify: //Build SQL. clsSQL mSQLContactModify = new clsSQL(clsSQL.enmSQLType.Update); mSQLContactModify.addField(new clsSQLField("Contacts", "FirstName", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "MiddleName", aContactDetails.getMiddleName())); mSQLContactModify.addField(new clsSQLField("Contacts", "LastName", aContactDetails.getLastName())); mSQLContactModify.addField(new clsSQLField("Contacts", "Birthday", mFormattedBirthdayDate)); mSQLContactModify.addField(new clsSQLField("Contacts", "Gender", aContactDetails.getGender())); mSQLContactModify.addField(new clsSQLField("Contacts", "Street", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "Postcode", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "City", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "Country", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "Comment", aContactDetails.getFirstName())); mSQLContactModify.addField(new clsSQLField("Contacts", "Availability", aContactDetails.getFirstName())); mSQLContactModify.addRelation(new clsSQLRelation(clsSQLRelation.enmRelationType.Where, new clsSQLField("Contacts", "ID"), "" + aContactDetails.getID() + "")); //mSQLContact = "UPDATE Contacts SET FirstName = '" + aContactDetails.getFirstName() + "', MiddleName = '" + aContactDetails.getMiddleName() + "', LastName = '" + aContactDetails.getLastName() + "', Birthday = '" + mFormattedBirthdayDate + "', Gender = '" + aContactDetails.getGender() + "', Street = '" + aContactDetails.getStreet() + "', Postcode = '" + aContactDetails.getPostcode() + "', City = '" + aContactDetails.getCity() + "', Country = '" + aContactDetails.getCountry() + "', Comment = '" + aContactDetails.getComment() + "', Availability = '" + aContactDetails.getAvailability() + "' WHERE ID = " + aContactDetails.getID() + ";"; //Update the contact. this.pProgram.getDatabase().QueryExecuteAffectedRows(mSQLContactModify); //Build SQL. clsSQL mSQLModification = new clsSQL(clsSQL.enmSQLType.Update); mSQLModification.addField(new clsSQLField("Modifications", "ModificationDate", "NOW()")); mSQLModification.addRelation(new clsSQLRelation(clsSQLRelation.enmRelationType.Where, new clsSQLField("Modifications", "ID"), "" + aContactDetails.getIDModifications() + "")); //mSQLModification = "UPDATE Modifications SET ModificationDate = NOW() WHERE ID = '" + aContactDetails.getIDModifications() + "';"; //Update the modification date. this.pProgram.getDatabase().QueryExecuteAffectedRows(mSQLModification); mIDContacts = aContactDetails.getID(); break; } return mIDContacts; }
5
public static void showGUI(TableModel tbl) { final TableModel t = tbl; /* 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(SearchResultsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SearchResultsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SearchResultsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SearchResultsGUI.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 SearchResultsGUI(t).setVisible(true); } }); }
6
public boolean hasPathSum(TreeNode root, int sum) { boolean result1 = false; boolean result2 = false; if (root == null) { return false; } if (root.val == sum && root.left == null && root.right == null) { return true; } if (root.left != null) { result1 = hasPathSum(root.left, sum - root.val); } if (root.right != null) { result2 = hasPathSum(root.right, sum - root.val); } return result1 || result2; }
7
@Override public void mousePressed(MouseEvent e) {}
0
public final boolean deleteAll() { if(!exists()) return false; if(!canWrite()) return false; if(CMath.bset(vfsBits, CMFile.VFS_MASK_NODELETEANY)) return false; if(!mayDeleteIfDirectory()) return false; if(demandVFS) return deleteVFS(); if(demandLocal) return deleteLocal(); final boolean delVfs=deleteVFS(); final boolean delLoc=deleteLocal(); return delVfs || delLoc; }
7
public void GUI() { setUndecorated(true); setSize(breite, hoehe); setTitle(Read.getTextwith("installer", "name")); setLocationRelativeTo(null); setIconImage(new ImageIcon(this.getClass().getResource("src/icon.png")).getImage()); final Point point = new Point(0,0); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if(!e.isMetaDown()) { point.x = e.getX(); point.y = e.getY(); setCursor(new Cursor(Cursor.MOVE_CURSOR)); } } public void mouseReleased(MouseEvent e) { setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if(!e.isMetaDown()) { Point p = getLocation(); setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y); } } }); cp = new GraphicsPanel(false); cp.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); cp.setLayout(null); add(cp); int rand = 20; int picturex = 400; int picturey = 225; int uber = (int)(hoehe*0.09); int listeya = rand+uber; int listenb = (int)(breite/2-picturex+4*rand); int listenh = hoehe-listeya-rand; int mittexa= rand+listenb+20; int modtexty = rand+uber; int infol = modtexty+2*rand; int pictureya = infol+(int)(2.5*rand); int textya = picturey+pictureya+20; int texth = listeya+listenh-textya; int liste2h= (int)(listenh*0.54); headerLabel.setBounds(0, 0, (int)(breite), (int)(hoehe*0.1)); headerLabel.setText(Read.getTextwith("installer", "name")); headerLabel.setHorizontalAlignment(SwingConstants.CENTER); headerLabel.setVerticalAlignment(SwingConstants.CENTER); headerLabel.setFont(headerLabel.getFont().deriveFont(Font.BOLD,45)); cp.add(headerLabel); mcVersLabel.setBounds((int)(rand), (int)(hoehe*0.05), listenb, 40); //Select Minecraft version mcVersLabel.setText("Minecraft ["+Start.mcVersion+"]"); mcVersLabel.setHorizontalAlignment(SwingConstants.CENTER); mcVersLabel.addMouseListener(this); mcVersLabel.setCursor(c); mcVersLabel.setFont(mcVersLabel.getFont().deriveFont(Font.BOLD,14)); cp.add(mcVersLabel); leftListMModel.addElement(Read.getTextwith("MenuGUI", "t2")); //List Modloader leftListM.setModel(leftListMModel); leftListM.setCellRenderer(new CellRenderer()); leftListM.addMouseListener(this); leftListM.addKeyListener(this); leftListFModel.addElement(Read.getTextwith("MenuGUI", "t2")); //List Forge leftListF.setModel(leftListFModel); leftListF.setCellRenderer(new CellRenderer()); leftListF.addMouseListener(this); leftListF.addKeyListener(this); leftListMSP.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); leftListFSP.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); tabbedPane.addTab("Modloader", leftListMSP); tabbedPane.addTab("Forge", leftListFSP); tabbedPane.setEnabled(false); tabbedPane.addChangeListener(this); tabbedPane.setBounds(rand, listeya, listenb, listenh-30); cp.add(tabbedPane); searchInput.setBounds(rand, listeya+listenh-25, listenb, 25); //Search field searchInput.addKeyListener(this); searchInput.addMouseListener(this); searchInput.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); searchInput.setBorder(BorderFactory.createCompoundBorder(searchInput.getBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3))); cp.add(searchInput); modNameLabel.setBounds(mittexa, modtexty, picturex, 30); //Mod name modNameLabel.setText(Read.getTextwith("MenuGUI", "t3")); modNameLabel.setHorizontalAlignment(SwingConstants.CENTER); modNameLabel.setFont(new Font("Dialog", Font.BOLD, 25)); cp.add(modNameLabel); modVersionL.setBounds(mittexa+10, infol+5, 160, 40); //Import mods modVersionL.setFont(new Font("Dialog", Font.PLAIN, 18)); modVersionL.setVisible(false); cp.add(modVersionL); for (int i=0; i<5; i++) //Stars for mod rating { ratIcons[i] = new JLabel(); ratIcons[i].setBounds(mittexa+10+i*25, infol, 40, 40); ratIcons[i].setCursor(c); ratIcons[i].setIcon(new ImageIcon(this.getClass().getResource("src/star0.png"))); ratIcons[i].addMouseListener(this); cp.add(ratIcons[i]); } topIcon.setBounds(mittexa+picturex-250, infol-1, 50, 50); // TOP or NEW picture topIcon.setIcon(new ImageIcon(this.getClass().getResource("src/top.png"))); topIcon.setVisible(false); cp.add(topIcon); sizeLabel.setBounds(mittexa+picturex-160-50-13, infol+5, 40+50, 40); // Download size sizeLabel.setHorizontalAlignment(SwingConstants.RIGHT); sizeLabel.setHorizontalTextPosition(SwingConstants.RIGHT); sizeLabel.setFont(new Font("Dialog", Font.PLAIN, 18)); cp.add(sizeLabel); videoButton.setBounds(mittexa+picturex-118, infol+5, 40, 40); // Link to mod video videoButton.setIcon(new ImageIcon(this.getClass().getResource("src/video.png"))); videoButton.addMouseListener(this); videoButton.setToolTipText(Read.getTextwith("MenuGUI", "t4")); videoButton.setCursor(c); videoButton.setVisible(false); cp.add(videoButton); modinstWebLnk.setBounds(mittexa+picturex-78, infol+5, 40, 40); // Link to Modinstaller website modinstWebLnk.setIcon(new ImageIcon(this.getClass().getResource("src/infokl.png"))); modinstWebLnk.addMouseListener(this); modinstWebLnk.setToolTipText(Read.getTextwith("MenuGUI", "t5")); modinstWebLnk.setCursor(c); cp.add(modinstWebLnk); devWebLnk.setBounds(mittexa+picturex-38, infol+5, 40, 40); // Link to mod developer devWebLnk.setIcon(new ImageIcon(this.getClass().getResource("src/devLnk.png"))); devWebLnk.addMouseListener(this); devWebLnk.setToolTipText(Read.getTextwith("MenuGUI", "t6")); devWebLnk.setCursor(c); cp.add(devWebLnk); picture.setBounds(mittexa, pictureya, picturex, picturey); //Mod picture picture.setHorizontalAlignment(SwingConstants.CENTER); picture.setVerticalAlignment(SwingConstants.CENTER); picture.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); picture.addMouseListener(this); picture.setCursor(c); picture.setIcon(new ImageIcon(this.getClass().getResource("src/wait.gif"))); picture.setToolTipText(Read.getTextwith("MenuGUI", "t7")); cp.add(picture); new DropTarget(picture, myDragDropListener); HTMLEditorKit kit = new HTMLEditorKit(); modDescPane = new JEditorPane(); //Mod description pane modDescPane.setEditable(false); modDescPane.setContentType("text/html"); Document doc = kit.createDefaultDocument(); modDescPane.setDocument(doc); modDescPane.setText(Read.getTextwith("MenuGUI", "t2")); StyleSheet ss = kit.getStyleSheet(); try { ss.importStyleSheet(new URL("http://www.minecraft-installer.de/sub/installerstyle.css")); } catch (MalformedURLException e1) { } kit.setStyleSheet(ss); scroller = new JScrollPane(modDescPane); scroller.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); scroller.setBounds(mittexa, textya, picturex, texth); cp.add(scroller); new DropTarget(modDescPane, myDragDropListener); selectArrow.setBounds(mittexa+picturex+2*rand, 250, 100, 83); // Arrow right: add mod selectArrow.setIcon(new ImageIcon(this.getClass().getResource("src/arrowSe.png"))); selectArrow.setToolTipText(Read.getTextwith("MenuGUI", "t8")); selectArrow.addMouseListener(this); selectArrow.setCursor(c); cp.add(selectArrow); removeArrow.setBounds(mittexa+picturex+rand, 360, 100, 83); // Arrow left: remove mod removeArrow.setIcon(new ImageIcon(this.getClass().getResource("src/arrowRe.png"))); removeArrow.setToolTipText(Read.getTextwith("MenuGUI", "t9")); removeArrow.addMouseListener(this); removeArrow.setCursor(c); cp.add(removeArrow); restoreButton.setBounds(breite-rand-listenb+10, (int)(hoehe*0.1), 180, 40); // Restore Minecraft restoreButton.setText(Read.getTextwith("MenuGUI", "t10")); restoreButton.setFont(restoreButton.getFont().deriveFont(Font.BOLD)); restoreButton.setIcon(new ImageIcon(this.getClass().getResource("src/restore.png"))); restoreButton.addMouseListener(this); restoreButton.setCursor(c); File backupfile = new File(Start.sport, "Backup"); if (!backupfile.exists()) // Check, if restore possible { restoreButton.setEnabled(false); } cp.add(restoreButton); importButton.setText(Read.getTextwith("MenuGUI", "t11")); //Mod import button importButton.setFont(importButton.getFont().deriveFont(Font.BOLD)); importButton.setIcon(new ImageIcon(this.getClass().getResource("src/importkl.png"))); importButton.addMouseListener(this); importButton.setCursor(c); importButton.setIcon(new ImageIcon(this.getClass().getResource("src/importkl.png"))); importButton.setBounds(breite-rand-listenb+10, (int)(hoehe*0.2), listenb+20, 50); cp.add(BorderLayout.CENTER, importButton); new DropTarget(importButton, myDragDropListener); rightListHeadl.setBounds(breite-rand-listenb, (int)(hoehe*0.315), listenb, 20); //List right headline rightListHeadl.setHorizontalAlignment(SwingConstants.CENTER); rightListHeadl.setText(Read.getTextwith("MenuGUI", "t12")); cp.add(rightListHeadl); rightListModel.addElement(""); // right list model rightList.setModel(rightListModel); rightList.setCellRenderer(new CellRenderer()); rightList.addKeyListener(this); rightList.addMouseListener(this); rightListSP.setBounds(breite-rand-listenb, (int)(hoehe*0.35), listenb, liste2h); rightListSP.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); cp.add(rightListSP); ratingBar.setBounds(breite-rand-listenb, (int)(hoehe*0.35)+liste2h-1, listenb, 15); ratingBar.setOpaque(false); ratingBar.setBorder(BorderFactory.createLineBorder(Color.decode("#9C2717"))); ratingBar.setUI(new GradientPalletProgressBarUI()); cp.add(ratingBar); new DropTarget(rightList, myDragDropListener); helpButton.setBounds(2, 5, 50, 50); // FAQ anzeigen helpButton.setIcon(new ImageIcon(this.getClass().getResource("src/help.png"))); helpButton.setToolTipText(Read.getTextwith("MenuGUI", "t13")); helpButton.addMouseListener(this); cp.add(helpButton); minButton.setBounds(breite-(35+35+3+3)-3, 3, 35, 27); //Minimieren minButton.setIcon(new ImageIcon(this.getClass().getResource("src/mini.png"))); minButton.addMouseListener(this); cp.add(minButton); maxButton.setBounds(breite-(35+35+3)-3, 3, 35, 27); //Maximieren maxButton.setIcon(new ImageIcon(this.getClass().getResource("src/maxi.png"))); maxButton.addMouseListener(this); maxButton.setEnabled(false); //cp.add(maxButton); exitButton.setBounds(breite-35-3, 3, 35, 27); //Beenden exitButton.setIcon(new ImageIcon(this.getClass().getResource("src/closeme.png"))); exitButton.addMouseListener(this); cp.add(exitButton); nextButton.setBounds((int)(breite-250-rand), hoehe-70-rand, 250, 70); // Installieren nextButton.setText(Read.getTextwith("MenuGUI", "t14")); nextButton.setFont(nextButton.getFont().deriveFont((float) 15)); nextButton.addMouseListener(this); nextButton.setCursor(c); nextButton.setHorizontalTextPosition(SwingConstants.LEFT); nextButton.setFont(nextButton.getFont().deriveFont(Font.BOLD, 20)); nextButton.setHorizontalAlignment(SwingConstants.RIGHT); nextButton.setVerticalAlignment(SwingConstants.CENTER); nextButton.setIcon(new ImageIcon(this.getClass().getResource("src/install.png"))); nextButton.setEnabled(false); cp.add(nextButton); setVisible(true); }
5
public BSTNode(Term term){ this.term = term; }
0
public double[] distributionForInstance(Instance instance) throws Exception { String stringInstance = instance.toString(); double cachedPreds[][] = null; if (m_cachedPredictions != null) { // If we have any cached predictions (i.e., if cachePredictions was // called), look for a cached set of predictions for this instance. if (m_cachedPredictions.containsKey(stringInstance)) { cachedPreds = (double[][]) m_cachedPredictions.get(stringInstance); } } double[] prediction = new double[instance.numClasses()]; for (int i = 0; i < prediction.length; ++i) { prediction[i] = 0.0; } // Now do a weighted average of the predictions of each of our models. for (int i = 0; i < m_chosen_models.length; ++i) { double[] predictionForThisModel = null; if (cachedPreds == null) { // If there are no predictions cached, we'll load the model's // classifier(s) in to memory and get the predictions. m_chosen_models[i].rehydrateModel(m_workingDirectory.getAbsolutePath()); predictionForThisModel = m_chosen_models[i].getAveragePrediction(instance); // We could release the model here to save memory, but we assume // that there is enough available since we're not using the // prediction caching functionality. If we load and release a // model // every time we need to get a prediction for an instance, it // can be // prohibitively slow. } else { // If it's cached, just get it from the array of cached preds // for this instance. predictionForThisModel = cachedPreds[i]; } // We have encountered a bug where MultilayerPerceptron returns a // null // prediction array. If that happens, we just don't count that model // in // our ensemble prediction. if (predictionForThisModel != null) { // Okay, the model returned a valid prediction array, so we'll // add the appropriate fraction of this model's prediction. for (int j = 0; j < prediction.length; ++j) { prediction[j] += m_chosen_model_weights[i] * predictionForThisModel[j] / m_total_weight; } } } // normalize to add up to 1. if (instance.classAttribute().isNominal()) { if (Utils.sum(prediction) > 0) Utils.normalize(prediction); } return prediction; }
9
private void resolveValueGrid(Node parentNode) { validateTagsOnlyOnce(parentNode, new String[]{"show_grid", "grid_step", "label_factor"}); boolean showGrid = true; double gridStep = Double.NaN; int NOT_SET = Integer.MIN_VALUE, labelFactor = NOT_SET; Node[] childNodes = getChildNodes(parentNode); for (Node childNode : childNodes) { String nodeName = childNode.getNodeName(); if (nodeName.equals("show_grid")) { showGrid = getValueAsBoolean(childNode); } else if (nodeName.equals("grid_step")) { gridStep = getValueAsDouble(childNode); } else if (nodeName.equals("label_factor")) { labelFactor = getValueAsInt(childNode); } } rrdGraphDef.setDrawYGrid(showGrid); if (!Double.isNaN(gridStep) && labelFactor != NOT_SET) { rrdGraphDef.setValueAxis(gridStep, labelFactor); } else if (!Double.isNaN(gridStep) || labelFactor != NOT_SET) { throw new IllegalArgumentException("Incomplete value axis settings"); } }
8
public boolean canMoveRight(){ int [][] temp = BlockInControl.getBlock(); int tempPosX = BlockPosX; int tempPosY = BlockPosY; for(int r = 0; r <4; r++){ for(int c = 0; c < 4;c++){ if(temp[r][c] == 1){ if(c ==3){ if(tempPosX+1 > MAX_COL-1) return false; if(board[tempPosY][tempPosX+1]==1) return false; } else{ if(tempPosX+1 > MAX_COL-1) return false; if(temp[r][c+1] == 0){ if(board[tempPosY][tempPosX+1]==1) return false; } } } tempPosX++; } tempPosX = BlockPosX; tempPosY++; } return true; }
9
static void print(Poker[][] pers){ int len1 = pers.length; for (int i = 0; i < len1 && i < 4; i++){ System.out.print(colors[i]+":"); int len2 = pers[i].length; for (int j = 0; j < len2; j++){ if (pers[i][j] != null){ System.out.print(pers[i][j].getNumber()+" "); } } System.out.println(); } }
4
public User getUser() { return user; }
0
private static Product getProduct(Serializable productID) { final Serializable productIDCopy = productID; Product result; synchronized (AutoAppro.products) { if ((result = AutoAppro.products.get(productID)) == null) { /* Try to find another that has a similar name */ for (Product p : AutoAppro.products.values()) { if (SimilarityChecker.isSimilarDel(productID.toString(), p.toString(), SIMILARITY_CHECK_ERROR)) { msgStr = lang("sim_content1") + " " + productID.toString() + "\n" + lang("sim_content2") + " " + p.toString(); while ((msgStr != null) && (!msgStr.equals("yes"))) { try { SwingUtilities.invokeAndWait(askSimilar); } catch (Exception e) {} } if (msgStr != null) { Product newProduct = new Product(); newProduct.supplierID = productID; newProduct.type = p.type; newProduct.barID = p.barID; newProduct.mult = p.mult; AutoAppro.products.put(productID, newProduct); AutoAppro.productsModified = true; try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { updateProducts(); } }); } catch (Exception e) { e.printStackTrace(); } return newProduct; } } } /* Else, ask */ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editProduct(productIDCopy, null); } }); productEditLock.lock(); productEditCondition.awaitUninterruptibly(); productEditLock.unlock(); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { updateProducts(); } }); } catch (Exception e) { e.printStackTrace(); } result = AutoAppro.products.get(productID); } } return result; }
9
public static void main (String[] args) { // The pattern for generating a range of ranom numbers looks like so. // (Math.random() * (Min - Max + 1)) + Min // Here's what a basic ranom number looks like. for (int i = 0; i < 100; i++) { System.out.println( Math.random() ); } // AS you can see they're all fractions or could be used like a percentaged. // This means that when you multiply this number by your maxium you can // get upto 99 percent of the maximum but never the max. // Here get numbers upto 10. for (int i = 0; i < 100; i++) { System.out.println( Math.random() * 10 ); } // What if we want to include the maxium? // For that we must add 1 to the number. for (int i = 0; i < 100; i++) { System.out.println( Math.random() * 10 + 1 ); } // But now we created a new problem because we'll go over our maximum. // We can either round down the decimal using Math.floor() if we need // to retain a double for some reason. for (int i = 0; i < 100; i++) { System.out.println( Math.floor(Math.random() * 10 + 1) ); } // Or we can simply cast the double to an integer. for (int i = 0; i < 100; i++) { System.out.println( (int) (Math.random() * 10 + 1) ); } // At this point we have a random between 1 - 10 including 10. We // also know how to remove the decimal in a double using Math.floor // or to change the random double into an integer. // Now what if we have a minimum. Like if we want a random between // 5 and 10. // You first might try to simply add the minimum to all the numbers. for (int i = 0; i < 100; i++) { System.out.println( (Math.random() * 10 + 1) + 5 ); } // But, now you're going over the maximum. // The remedy is to subtract the minimum from the maximum. This way // you only generate numbers that can have the minimum added to them // without going over the maximum. for (int i = 0; i < 100; i++) { System.out.println( (Math.random() * (10 - 5 + 1)) + 5 ); } // Putting it altogether: final int MAX = 10; final int MIN = 5; for (int i = 0; i < 100; i++) { System.out.println( (int) (Math.random() * (MAX - MIN + 1)) + MIN ); } }
8
public static boolean canMove(){ IsoEntity other; for (Iterator<IsoEntity> iie = PistolCaveGame.stop.iterator(); iie.hasNext(); ) { other = iie.next(); if(secondPlayer){ if (PistolCaveGame.player2.collides(other) != null) return false; } else{ if (PistolCaveGame.player.collides(other) != null) return false; } } return true; }
4
public Object instantiate(String name) throws ClassNotFoundException { String implementation = getProperty("me4se.implementation"); if(implementation != null) { implementation += ";"; } else { implementation = ""; } implementation += "org.me4se.psi.java1"; int pos = 0; do{ int cut = implementation.indexOf(';', pos); if(cut == -1) cut = implementation.length(); String qName = implementation.substring(pos, cut)+"."+name; try{ Class clazz = Class.forName(qName); return clazz.newInstance(); } catch(Exception e){ } pos = cut+1; } while(pos < implementation.length()); throw new ClassNotFoundException("No implementation class found for suffix "+name); }
4
@Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender.hasPermission("bossbar.config")) { if (args.length == 0 || args[0].equalsIgnoreCase("help")) { getExecutor("help").onCommand(sender, cmd, label, args); return true; } else if (commandExists(args[0])) { getExecutor(args[0]).onCommand(sender, cmd, label, args); return true; } else { sender.sendMessage(ChatColor.RED + "[BossBar] " + ChatColor.GOLD + "Invalid command. Try " + ChatColor.GREEN + "/bossbar help" + ChatColor.GOLD + "to see a list of valid commands!"); } return false; } else { sender.sendMessage(ChatColor.RED + "[BossBar] " + ChatColor.GOLD + "You don't have permission to configure BossBarHealth!"); return true; } }
4
private boolean checkTouchObject(int pos){ ArrayList<Line2D.Double> linies = this.getBoundLines(); boolean toca = false; for (int i = 0; i < linies.size(); i++) { for (int j = 0; j < Board.getObstacles().size(); j++) { Rectangle r = new Rectangle((int)Board.getObstacles().get(j).getX(),(int)Board.getObstacles().get(j).getY(),Board.getObstacles().get(j).getWidth(),Board.getObstacles().get(j).getHeight()); if(linies.get(pos).getBounds().intersects(r)){ toca = true; } } } return toca; }
3
public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } }
7
public final void setOptions(Map<String, ?> options) { /* Is verification of YubiKey owners enabled? */ this.verify_yubikey_owner = true; if (options.get(OPTION_YUBICO_VERIFY_YK_OWNER) != null) { if ("false".equals(options.get(OPTION_YUBICO_VERIFY_YK_OWNER).toString())) { this.verify_yubikey_owner = false; } } if (options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE) != null) { this.publicid_attribute = options.get(OPTION_YUBICO_LDAP_PUBLICID_ATTRIBUTE).toString(); } if (options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE) != null) { this.username_attribute = options.get(OPTION_YUBICO_LDAP_USERNAME_ATTRIBUTE).toString(); } if (options.get(OPTION_LDAP_URL) != null) { this.ldap_url = options.get(OPTION_LDAP_URL).toString(); } if (options.get(OPTION_LDAP_BASE_DN) != null) { this.ldap_base_dn = options.get(OPTION_LDAP_BASE_DN).toString(); } if (options.get(OPTION_LDAP_BIND_DN) != null) { this.ldap_bind_dn = options.get(OPTION_LDAP_BIND_DN).toString(); } if (options.get(OPTION_LDAP_BIND_CREDENTIAL) != null) { this.ldap_bind_credential = options.get(OPTION_LDAP_BIND_CREDENTIAL).toString(); } LdapConfig config = new LdapConfig(this.ldap_url, this.ldap_base_dn); config.setBindDn(this.ldap_bind_dn); config.setBindCredential(this.ldap_bind_credential); this.ldap = new Ldap(config); }
9