method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
2c3494f9-818c-4cf4-895b-5e20076e9465
1
protected void processInput() { /*================================================================== * PROCESS INPUT HERE *===================================================================*/ if(board.keyDownOnce(KeyEvent.VK_ESCAPE)) { System.exit(0); } //================================================================== }
809e1ae2-e08d-4afd-bc2e-e0642f3d9e90
5
void mergeSuccessors(FlowBlock succ) { /* * Merge the successors from the successing flow block */ Iterator iter = succ.successors.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); FlowBlock dest = (FlowBlock) entry.getKey(); SuccessorInfo hisInfo = (SuccessorInfo) entry.getValue(); SuccessorInfo myInfo = (SuccessorInfo) successors.get(dest); if (dest != END_OF_METHOD) dest.predecessors.remove(succ); if (myInfo == null) { if (dest != END_OF_METHOD) dest.predecessors.add(this); successors.put(dest, hisInfo); } else { myInfo.gen.addAll(hisInfo.gen); myInfo.kill.retainAll(hisInfo.kill); Jump myJumps = myInfo.jumps; while (myJumps.next != null) myJumps = myJumps.next; myJumps.next = hisInfo.jumps; } } }
9a7dd1b0-347f-4e00-bb12-c624d1a75cc3
5
void getPersonList(ArrayList<Person> sendingList) { Date today = new Date(); String name, zodiac; int age; // DefaultTableModel dtModel = new DefaultTableModel(); // Object[] convertedObjects = new Object[4]; // Object[] columnNames = new Object[4]; Object[] convertedObjects = new Object[3]; Object[] columnNames = new Object[3]; columnNames[0] = "Name"; columnNames[1] = "Age"; columnNames[2] = "Zodiac Sign"; dtModel.setColumnIdentifiers(columnNames); //Define objects by Malinda ZodiacOperation zodi =new ZodiacOperation(); ArrayList<Player> playerList=new ArrayList<>(); for(Person p : sendingList) { name = p.getName(); //Get the DOB and calculate the age Date bdate = p.getDOB(); int bd = bdate.getYear(); int now = today.getYear(); age = now - bd; if (bdate.getMonth() > today.getMonth()) { age = age - 1; } if (bdate.getMonth() == today.getMonth()) { if (bdate.getDate() > today.getDate()) { age = age - 1; } } //Add Zodiac and Horosscope details of the Person. int bd_month = bdate.getMonth() + 1; int bd_date = bdate.getDate(); //Operations by Malinda Player player=new Player(); player.setName(name); player.setAge(age); player.setMonth(bd_month); player.setDay(bd_date); playerList.add(player); } //Connecting to prolog logic by Malinda ArrayList<Player> resultPlayer=zodi.getZodiacResult(playerList); for (Player player : resultPlayer) { //Display Person in the Table convertedObjects[0] = player.getName(); convertedObjects[1] = player.getAge(); convertedObjects[2] = player.getZodiacSign(); dtModel.addRow(convertedObjects); } this.tbl_Display.setModel(dtModel); }
f9eac2ed-8ccb-4167-8765-e3483538c851
4
public String generate() { String error = "No errors."; if (details) System.out.println("Biomes flags: PRODUCE="+ioflags.PRODUCE+", SAVE="+ioflags.SAVE+", LOAD="+ioflags.LOAD); if (Utils.flagsCheck(ioflags) != 0) { System.out.println("ERROR: IOFlags object is corrupted, error: "+Utils.flagsCheck(ioflags)); return "BiomesGenerator critical error - read above."; } if (ioflags.PRODUCE) error = produceBiomes(); if (ioflags.LOAD) error = loadBiomes(); return error; }
c19d6352-c430-48fe-8719-4bccaf85a06a
8
public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); boolean[] self = new boolean[1000001]; for (int i = 1; i <= 1000000; i++) { int tot = 0, x = i; while (x / 10 > 0) { tot += x % 10; x /= 10; } String ret = ""; if (tot == 0 && x == i) { ret = i + ""; for (int j = 0; j < ret.length(); j++) { tot += ret.charAt(j) - '0'; } } else { tot += x; } tot += i; if (tot <= 1000000) { self[tot] = true; } } for (int i = 1; i <= 1000000; i++) { if (!self[i]) { System.out.println(i); } } }
2586cc69-96b5-4389-ada6-5fbcd0b203f3
4
public void Unload() { currentlyReading = true; if(hashTable) hashtable.clear(); else if(hashList) hashlist.clear(); else if(binaryTree) binarytree.clear(); else if(naryTree) narytree.clear(); System.gc(); currentlyReading = false; }
78f0166c-6cb2-4f37-b3c0-ddacf5628f39
2
public MenuThing(){ super(); if (System.getProperty("os.name").contains("Mac")) { System.out.println("The game knows that it is running on Mac OS."); System.setProperty("apple.laf.useScreenMenuBar", "true"); //make JMenuBars appear at the top in Mac OS X } else if (System.getProperty("os.name").contains("Windows")){ System.out.println("The game knows that it is running on Windows."); } else { System.out.println("The game does not know what system it is running on. Unless you are running Linux or something obscure (in which case this is fine), this is a minor problem."); } JMenuBar menus = new JMenuBar(); JMenu sound = new JMenu("Sound"); JMenuItem toggleMusic = new JMenuItem("Toggle music"); JMenuItem toggleSound = new JMenuItem("Toggle sound effects"); JMenuItem changeMusic = new JMenuItem("Change music..."); sound.add(toggleMusic); sound.add(toggleSound); sound.add(changeMusic); menus.add(sound); menus.validate(); this.setJMenuBar(menus); this.validate(); this.setVisible(true); }
adfa7701-9eba-4e9a-aab0-c989fdcacf60
3
public static Integer[] graySuccessor(Integer[] e) { Integer[] copy = Arrays.copyOf(e, e.length); if (hammingDist(copy) % 2 == 0) { copy[0] = 1 - copy[0]; return copy; } else { for (int i = 0; i <= e.length - 2; i++) { if (copy[i] != 0) { copy[i + 1] = 1 - copy[i + 1]; return copy; } } } return null; }
15fa902a-79ee-4a09-91e6-beec54ae4d50
1
private List<T> getResults(ResultSet rs) throws SQLException { List<T> results = new ArrayList<T>(); while (rs.next()) { T t = fillFrom(rs); //a.setId(rs.getInt("id")); //a.setDescr(rs.getString("descr")); //a.setCh(rs.getInt("ch")); results.add(t); } return results; }
d69df00d-383a-4278-a719-4237f87483d2
6
private Rule renameVariables(Rule rule) { int uniqueVariableId = variableIdGenerator.incrementAndGet(); Set<Variable> variables = new HashSet<Variable>(); // At first I'll get a list of all variables that appear in the head of the rule. for (Term term : rule.getHead().getArgs()) { if (term instanceof Variable) { variables.add((Variable) term); } } List<Predicate> newConditions = new ArrayList<Predicate>(rule.getConditions().size()); // The next step is to go through all conditions and see whether they use variables // that don't appear in the head of the rule. If that's the case, rename those // variables to ensure that they won't be captured later on. for (Predicate condition : rule.getConditions()) { for (Term term : condition.getArgs()) { if (term instanceof Variable && !variables.contains(term)) { // If this is true, then we'll better rename this variable to some unique thing. // In this case, I'll just prepend the prefix "__$$__" and a unique ID in front // of the variable name. Variable variable = (Variable) term; condition = (Predicate) condition.substitute( variable, new Variable("__$$__" + uniqueVariableId + "_" + variable.getName())); } } newConditions.add(condition); } return new Rule(rule.getHead(), newConditions); }
7f7e639c-da22-4467-bc19-6825f45fc8c9
8
public String extend(String s, int l, int r){ if(l == r){ for(;l-1 >= 0 && r+1 < s.length(); --l, ++r){ if(s.charAt(l-1) != s.charAt(r+1)) break; } return s.substring(l, r+1); }else{ for(; l >= 0 && r < s.length(); --l, ++r){ if(s.charAt(l) != s.charAt(r)) break; } return r-1 < l+1 ? "" : s.substring(l+1, r-1+1); } }
217ad895-70ff-4aec-88f4-7c096172f2e3
9
private void decodeHeader(BufferedReader in, Map<String, String> pre, Map<String, String> parms, Map<String, String> headers) throws ResponseException { try { // Read the request line String inLine = in.readLine(); if (inLine == null) { return; } StringTokenizer st = new StringTokenizer(inLine); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html"); } pre.put("method", st.nextToken()); if (!st.hasMoreTokens()) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html"); } String uri = st.nextToken(); // Decode parameters from the URI int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } else { uri = decodePercent(uri); } // If there's another token, it's protocol version, // followed by HTTP headers. Ignore version but parse headers. // NOTE: this now forces header names lowercase since they are // case insensitive and vary by client. if (st.hasMoreTokens()) { String line = in.readLine(); while (line != null && line.trim().length() > 0) { int p = line.indexOf(':'); if (p >= 0) headers.put(line.substring(0, p).trim().toLowerCase(Locale.US), line.substring(p + 1).trim()); line = in.readLine(); } } pre.put("uri", uri); } catch (IOException ioe) { throw new ResponseException(Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage(), ioe); } }
46cc2cb6-78f1-49d5-8299-dbe5b7dd0545
6
public void menuPanelUpdate() { playerHealth.setText("Health: " + theGame.getPlayer(0).getHealth()); money.setText("Moneys: $" + theGame.getPlayer(0).getMoney()); time.setText("Time: " + theGame.getTime() + "\n Round: " + theGame.getCurrentMap().getCurrentLevel()); if (theGame.getCurrentTowerInfo() != null) { info.setText(" " + theGame.getCurrentTowerInfo().getName() + " " + "\n" + "Attacks: " + theGame.getCurrentTowerInfo().getAttacks().get(0) .getName()); if (theGame.getCurrentTowerInfo().getUpgraded() != null) { infoPanel.add(evolveButton); } else infoPanel.remove(evolveButton); } else if (theGame.getCurrentMobsInfo() != null) { for (Mob mob : theGame.getCurrentMobsInfo()) { if (mob.getHealth() > 0) info.setText(mob.getName() + ": " + mob.getHealth() + "\n"); } } else { info.setText(""); infoPanel.remove(evolveButton); } if (theGame.betweenRounds()) { switchButtons(pauseButton.getText()); } }
7d25ec4a-8337-4cef-bb3f-1d2fcf91fc9a
0
@Override public String getName() { return NAME; }
5c35bd20-b37c-48a2-abdf-3a4cc4b011e2
0
private Object readBigInteger() { byte[] longintBytes = new byte[8]; longintBytes[0] = bytes[streamPosition++]; longintBytes[1] = bytes[streamPosition++]; longintBytes[2] = bytes[streamPosition++]; longintBytes[3] = bytes[streamPosition++]; longintBytes[4] = bytes[streamPosition++]; longintBytes[5] = bytes[streamPosition++]; longintBytes[6] = bytes[streamPosition++]; longintBytes[7] = bytes[streamPosition++]; return new BigInteger(longintBytes); }
b725b7b7-14b8-4204-a15f-fed643defd0b
9
public void wakeUpPlayer(boolean par1, boolean par2, boolean par3) { this.setSize(0.6F, 1.8F); this.resetHeight(); ChunkCoordinates var4 = this.playerLocation; ChunkCoordinates var5 = this.playerLocation; Block block = (var4 == null ? null : Block.blocksList[worldObj.getBlockId(var4.posX, var4.posY, var4.posZ)]); if (var4 != null && block != null && block.isBed(worldObj, var4.posX, var4.posY, var4.posZ, this)) { block.setBedOccupied(this.worldObj, var4.posX, var4.posY, var4.posZ, this, false); var5 = block.getBedSpawnPosition(worldObj, var4.posX, var4.posY, var4.posZ, this); if (var5 == null) { var5 = new ChunkCoordinates(var4.posX, var4.posY + 1, var4.posZ); } this.setPosition((double)((float)var5.posX + 0.5F), (double)((float)var5.posY + this.yOffset + 0.1F), (double)((float)var5.posZ + 0.5F)); } this.sleeping = false; if (!this.worldObj.isRemote && par2) { this.worldObj.updateAllPlayersSleepingFlag(); } if (par1) { this.sleepTimer = 0; } else { this.sleepTimer = 100; } if (par3) { this.setSpawnChunk(this.playerLocation); } }
7a0aff83-b087-4a15-aeba-984563a09e62
8
public Set<Map.Entry<Byte,Long>> entrySet() { return new AbstractSet<Map.Entry<Byte,Long>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TByteLongMapDecorator.this.isEmpty(); } public boolean contains( Object o ) { if (o instanceof Map.Entry) { Object k = ( ( Map.Entry ) o ).getKey(); Object v = ( ( Map.Entry ) o ).getValue(); return TByteLongMapDecorator.this.containsKey(k) && TByteLongMapDecorator.this.get(k).equals(v); } else { return false; } } public Iterator<Map.Entry<Byte,Long>> iterator() { return new Iterator<Map.Entry<Byte,Long>>() { private final TByteLongIterator it = _map.iterator(); public Map.Entry<Byte,Long> next() { it.advance(); byte ik = it.key(); final Byte key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik ); long iv = it.value(); final Long v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv ); return new Map.Entry<Byte,Long>() { private Long val = v; public boolean equals( Object o ) { return o instanceof Map.Entry && ( ( Map.Entry ) o ).getKey().equals(key) && ( ( Map.Entry ) o ).getValue().equals(val); } public Byte getKey() { return key; } public Long getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public Long setValue( Long value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Byte,Long> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Byte key = ( ( Map.Entry<Byte,Long> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Byte, Long>> c ) { throw new UnsupportedOperationException(); } public void clear() { TByteLongMapDecorator.this.clear(); } }; }
bbae716e-42c9-4bdd-9b1e-084faaf137d6
0
public Equivalence deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return this.getEquivalence(json.getAsJsonArray().get(0)); }
163cf911-160b-40d7-9c4c-32f392b66bd8
1
@Override public Container getCurrentContainer() { if (containerStack.size() > 0) { return (Container) containerStack.get(containerStack.size() - 1); } else { return this; } }
ca0aba4c-c808-486d-9adc-a00b5b614aff
0
public CheckResultMessage check10(int day) { return checkReport.check10(day); }
8fd9186d-dd64-4d77-a924-04cb7aa21d40
6
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FileRights other = (FileRights) obj; if (!Arrays.equals(groupRights, other.groupRights)) { return false; } if (!Arrays.equals(othersRights, other.othersRights)) { return false; } if (!Arrays.equals(ownerRights, other.ownerRights)) { return false; } return true; }
3c4433f3-682f-48f9-8e16-958061e75011
4
private Enemy createRandomEnemy() { int random = new Random().nextInt(4); switch (random) { case 0: return new Dwarf(this); case 1: return new Elf(this); case 2: return new Hobbit(this); case 3: return new Human(this); } return null; }
1ec93074-59d3-49da-83ed-2d7e787d44d1
2
@RequestMapping(value = {"/SucursalBancaria/{idSucursalBancaria}"}, method = RequestMethod.DELETE) public void delete(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idSucursalBancaria") int idSucursalBancaria) { try { sucursalBancariaDAO.delete(idSucursalBancaria); noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } catch (Exception ex) { noCache(httpServletResponse); httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); httpServletResponse.setContentType("text/plain; charset=UTF-8"); try { noCache(httpServletResponse); ex.printStackTrace(httpServletResponse.getWriter()); } catch (Exception ex1) { noCache(httpServletResponse); } } }
a2828474-82b4-4dda-832a-671efd5446a7
8
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof OFPortMod)) { return false; } OFPortMod other = (OFPortMod) obj; if (advertise != other.advertise) { return false; } if (config != other.config) { return false; } if (!Arrays.equals(hardwareAddress, other.hardwareAddress)) { return false; } if (mask != other.mask) { return false; } if (portNumber != other.portNumber) { return false; } return true; }
f27aa4d5-e2a8-49a3-897b-3b61b66a3b5c
0
public EmptyStringCharacterAction() { //super("Test Turing Machines", null); super("Set the Empty String Character", null); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_P, MAIN_MENU_MASK)); this.fileChooser = Universe.CHOOSER; }
a30955f5-73e3-4937-aa2c-1668db50f8d0
8
public boolean isPalindrome(String s) { if (s.length() == 0) { return true; } s = s.toLowerCase(); int start = 0; int end = s.length() - 1; while (start <= end) { while (start < s.length() && !isCharNum(s.charAt(start))) { start++; } while (end >= 0 && !isCharNum(s.charAt(end))) { end--; } if (start <= end) { if (s.charAt(start) == s.charAt(end)) { start++; end--; } else { return false; } } else { return true; } } return true; }
65afd9a4-3927-401f-8d86-2d31fce5887c
6
public static void main(String[] args) { // test divide by zero - should print an error and exit new Fraction(1, 0); // test multiply Fraction f = new Fraction(3,10); Fraction g = new Fraction(1,2); Fraction h = new Fraction(3,5); if (!f.equals(g.multiply(h))) System.out.println("Multiply failed"); // test equals test(new Fraction(1, 2),new Fraction(1, 2),"error test 1"); test(new Fraction(1, 2),new Fraction(3, 6),"error test 2"); test(new Fraction(-1, 2),new Fraction(1, -2),"error test 3"); test(new Fraction(-1, -2),new Fraction(1, 2),"error test 4"); test(new Fraction(4, -8),new Fraction(1, 2),"error test 5"); // extend with extra tests // test add Fraction i = new Fraction(19,15); Fraction j = new Fraction(3,5); Fraction k = new Fraction(2,3); if(!i.equals(j.add(k))) System.out.println("Add failed"); // test subtract Fraction l = new Fraction(1,6); Fraction m = new Fraction(2,3); Fraction n = new Fraction(1,2); if(!l.equals(m.subtract(n))) System.out.println("Sub failed"); // test divide Fraction o = new Fraction(6,2); Fraction p = new Fraction(1,2); Fraction q = new Fraction(1,6); if(!o.equals(p.divide(q))) System.out.println("Divide failed"); // test absolute Fraction r = new Fraction(-3,7); Fraction s = new Fraction(3,7); if(!s.equals(r.absolute())) System.out.println("Absolute failed"); // test negative Fraction t = new Fraction(-3,7); if(!t.equals(r.negative())) System.out.println("Negative failed"); Fraction u = r.negative(); System.out.println(u.getNumerator() + "," + u.getDenominator()); // test toString Fraction v = new Fraction(3, 1); System.out.println(v.toString()); System.out.println(u.toString()); }
35a6e030-615d-4604-9d30-bdf8d575eee2
2
protected void doTestCycAccess10(CycAccess cycAccess) { long startMilliseconds = System.currentTimeMillis(); try { // demonstrate quoted strings //cycAccess.traceOn(); StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("a"); stringBuffer.append('"'); stringBuffer.append("b"); stringBuffer.append('"'); stringBuffer.append("c"); String expectedString = stringBuffer.toString(); CycList command = new CycList(); command.add(makeCycSymbol("identity")); command.add(expectedString); String resultString = cycAccess.converseString(command); assertEquals(expectedString, resultString); CycList cycList53 = cycAccess.makeCycList("(\"abc\")"); assertEquals(1, cycAccess.converseInt("(length '" + cycList53.cycListApiValue() + ")")); assertEquals(3, cycAccess.converseInt("(length (first '" + cycList53.cycListApiValue() + "))")); String string = "abc"; CycList cycList54 = new CycList(); cycList54.add(makeCycSymbol("length")); cycList54.add(string); assertEquals(3, cycAccess.converseInt(cycList54)); String quotedString = "\"abc\" def"; CycList cycList55 = new CycList(); cycList55.add(makeCycSymbol("length")); cycList55.add(quotedString); // Note that in binary mode, that Cyc's cfasl input will insert the required escape // chars for embedded quotes. // And in ascii mode note that CycConnection will insert the required escape // chars for embedded quotes. While in binary mode, CfaslOutputStream will insert // the required escapes. // // Cyc should see (length "\"abc\" def") and return 9 assertEquals(9, cycAccess.converseInt(cycList55)); // demonstrate quoted strings with the CycListParser CycList cycList56 = cycAccess.makeCycList("(\"" + string + "\")"); assertEquals(1, cycAccess.converseInt("(length " + cycList56.stringApiValue() + ")")); assertEquals(3, cycAccess.converseInt("(length (first " + cycList56.stringApiValue() + "))")); String embeddedQuotesString = "(" + "\"\\\"abc\\\" def\"" + ")"; CycList cycList57 = cycAccess.makeCycList(embeddedQuotesString); String script = "(length " + cycList57.stringApiValue() + ")"; int actualLen = cycAccess.converseInt(script); assertEquals(1, actualLen); assertEquals(9, cycAccess.converseInt("(length (first " + cycList57.stringApiValue() + "))")); script = "(identity (quote (#$givenNames #$Guest \"\\\"The\\\" Guest\")))"; String script1 = "(IDENTITY (QUOTE (#$givenNames #$Guest \"\"The\" Guest\")))"; //CycListParser.verbosity = 3; CycList scriptCycList = cycAccess.makeCycList(script); // Java strings do not escape embedded quote chars assertEquals(script1, scriptCycList.cyclify()); CycList answer = cycAccess.converseList(script); Object third = answer.third(); assertTrue(third instanceof String); assertEquals(11, ((String) third).length()); answer = cycAccess.converseList(scriptCycList); third = answer.third(); assertTrue(third instanceof String); assertEquals(11, ((String) third).length()); // isFormulaWellFormed if (!cycAccess.isOpenCyc()) { CycFormulaSentence formula1 = cycAccess.makeCycSentence("(#$isa #$Brazil #$IndependentCountry)"); CycConstant mt = cycAccess.getKnownConstantByName("WorldPoliticalGeographyDataVocabularyMt"); assertTrue(cycAccess.isFormulaWellFormed(formula1, mt)); CycFormulaSentence formula2 = cycAccess.makeCycSentence("(#$genls #$Brazil #$Collection)"); assertTrue(!cycAccess.isFormulaWellFormed(formula2, mt)); } // isCycLNonAtomicReifableTerm CycNaut formula3 = cycAccess.makeCycNaut("(#$TheCovering #$Watercraft-Surface #$Watercraft-Subsurface)"); assertTrue(cycAccess.isCycLNonAtomicReifableTerm(formula3)); CycFormulaSentence formula4 = cycAccess.makeCycSentence("(#$isa #$Plant #$Animal)"); assertTrue(!cycAccess.isCycLNonAtomicReifableTerm(formula4)); CycNaut formula5 = cycAccess.makeCycNaut("(#$PlusFn 1)"); assertTrue(!cycAccess.isCycLNonAtomicReifableTerm(formula5)); // isCycLNonAtomicUnreifableTerm CycNaut formula6 = cycAccess.makeCycNaut("(#$TheCovering #$Watercraft-Surface #$Watercraft-Subsurface)"); assertTrue(!cycAccess.isCycLNonAtomicUnreifableTerm(formula6)); CycFormulaSentence formula7 = cycAccess.makeCycSentence("(#$isa #$Plant #$Animal)"); assertTrue(!cycAccess.isCycLNonAtomicUnreifableTerm(formula7)); CycNaut formula8 = cycAccess.makeCycNaut("(#$PlusFn 1)"); assertTrue(cycAccess.isCycLNonAtomicUnreifableTerm(formula8)); } catch (Throwable e) { e.printStackTrace(); fail(e.toString()); } long endMilliseconds = System.currentTimeMillis(); System.out.println(" " + (endMilliseconds - startMilliseconds) + " milliseconds"); }
189ed6f1-6189-424d-884c-5544dcd7ff00
4
public Rating addRatings(HashMap<String, Object> rat) { @SuppressWarnings("unchecked") HashMap<String, String> holder = (HashMap<String, String>)rat.get("rating"); if(holder.containsKey("authorsId")) this.authorsId = holder.get("authorsId"); if(holder.containsKey("comment")) this.comment = holder.get("comment"); if(holder.containsKey("date")) this.date = Date.valueOf(holder.get("date")); if(holder.containsKey("stars")) this.stars = Integer.parseInt(holder.get("stars")); return this; }
e703a7a5-a0a1-491c-ad5d-f3f09774d623
1
public static User findOneAdmin() { try { return User.findOne("isAdmin", "1"); } catch (SQLException e) { e.printStackTrace(); return null; } }
b815c995-7a9b-4c88-a753-ac0af5b02912
0
public HospitalFacade() { super(Hospital.class); }
e99500c7-8c68-4225-8b31-0bc472848951
8
public IndexedModel toIndexedModel() { IndexedModel result = new IndexedModel(); IndexedModel normalModel = new IndexedModel(); HashMap<OBJIndex, Integer> resultIndexMap = new HashMap<OBJIndex, Integer>(); HashMap<Integer, Integer> normalIndexMap = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> indexMap = new HashMap<Integer, Integer>(); for(int i=0; i < indices.size(); i++) { OBJIndex currentIndex = indices.get(i); Vector3f currentPos = positions.get(currentIndex.vertexIndex); Vector2f currentTexCoord; Vector3f currentNormal; if(hasTexCoords) currentTexCoord = texCoords.get(currentIndex.texCoordIndex); else currentTexCoord = new Vector2f(0,0); if(hasNormals) currentNormal = normals.get(currentIndex.normalIndex); else currentNormal = new Vector3f(0, 0, 0); Integer modelVertexIndex = resultIndexMap.get(currentIndex); if(modelVertexIndex == null) { modelVertexIndex = result.getPositions().size(); resultIndexMap.put(currentIndex, result.getPositions().size()); result.getPositions().add(currentPos); result.getTexCoords().add(currentTexCoord); if(hasNormals) result.getNormals().add(currentNormal); } Integer normalModelIndex = normalIndexMap.get(currentIndex.vertexIndex); if(normalModelIndex == null) { normalModelIndex = normalModel.getPositions().size(); normalIndexMap.put(currentIndex.vertexIndex, normalModel.getPositions().size()); normalModel.getPositions().add(currentPos); normalModel.getTexCoords().add(currentTexCoord); normalModel.getNormals().add(currentNormal); } result.getIndices().add(modelVertexIndex); normalModel.getIndices().add(normalModelIndex); indexMap.put(modelVertexIndex, normalModelIndex); } if(!hasNormals) { normalModel.calcNormals(); for(int i=0; i<result.getPositions().size(); i++) result.getNormals().add(normalModel.getNormals().get(indexMap.get(i))); } return result; }
82961bc9-6dd9-470c-815f-5f36c9bf37f0
4
private void logout() { try { sendToServer(Packet.getLogoutPacket()); PacketManager.readPacketFromStream(in); } catch(Exception e) {} try { out.close(); } catch(Exception e) {} try { in.close(); } catch(Exception e) {} try { socket.close(); } catch(Exception e) {} dispose(); }
a7916d9e-d2ca-4547-ade3-0fd91fa00975
8
public static Description coerceToDescription(Stella_Object self, Stella_Object original) { if (original == null) { original = self; } if (self == null) { System.out.println("Can't find a description for the object `" + original + "'."); return (null); } { Surrogate testValue000 = Stella_Object.safePrimaryType(self); if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_DESCRIPTION)) { { Description self000 = ((Description)(self)); return (self000); } } else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_RELATION)) { { Relation self000 = ((Relation)(self)); return (Logic.getDescription(self000)); } } else if (Surrogate.subtypeOfSurrogateP(testValue000)) { { Surrogate self000 = ((Surrogate)(self)); return (Logic.coerceToDescription(self000.surrogateValue, original)); } } else if (Surrogate.subtypeOfSymbolP(testValue000)) { { Symbol self000 = ((Symbol)(self)); return (Logic.coerceToDescription(Surrogate.lookupSurrogateInModule(self000.symbolName, ((Module)(self000.homeContext)), false), original)); } } else if (Surrogate.subtypeOfKeywordP(testValue000)) { { Keyword self000 = ((Keyword)(self)); return (Logic.coerceToDescription(Surrogate.lookupSurrogate(self000.symbolName), original)); } } else if (Surrogate.subtypeOfStringP(testValue000)) { { StringWrapper self000 = ((StringWrapper)(self)); return (Logic.coerceToDescription(Surrogate.lookupSurrogate(self000.wrapperValue), original)); } } else { return (Logic.coerceToDescription(null, original)); } } }
90446eb2-1fe7-4223-b108-f1ea62a0aae0
5
private static boolean isNoneHexChar(char c) { // make sure the char is the following return !(((c >= 48) && (c <= 57)) || // 0-9 ((c >= 65) && (c <= 70)) || // A-F ((c >= 97) && (c <= 102))); // a-f }
9681dd4d-b6a0-45af-9046-d5a2cb7698f9
6
public SelectTaskXmlDriver(String xmlStr) throws DocumentException, XmlTypeErrorException { super(); if (!isSelectTaskXml(xmlStr)) { throw new XmlTypeErrorException("not a valid selectTask Xml"); } document = DocumentHelper.parseText(xmlStr); timestamp = document.selectSingleNode("//properties/timestamp") .getText(); aggregation = document.selectSingleNode( "//properties/operation/aggregation").getText(); fromCubeIdentifier = document.selectSingleNode( "//properties/operation/from").getText(); Element root = this.document.getRootElement(); List<?> list = root .selectNodes("//properties/operation/conditions/condition"); String dimensionName; String levelName; String start; String end; ConditionBean conditionBean; Node tmpNode; for (Iterator<?> iter = list.iterator(); iter.hasNext(); ) { Node node = (Node) iter.next(); dimensionName = node.selectSingleNode("dimensionName").getText(); levelName = node.selectSingleNode("levelName").getText(); if (null == (tmpNode = node.selectSingleNode("start"))) { start = ""; } else { start = tmpNode.getText(); } if (null == (tmpNode = node.selectSingleNode("end"))) { end = ""; } else { end = tmpNode.getText(); } conditionBean = new ConditionBean(dimensionName, levelName, start, end); conditionBeans.add(conditionBean); } }
bf6b3026-c42d-45d9-aeae-28283b311cda
5
private void compareFrames() { int r, g, b, refDataInt, inDataInt, ip = 0, op = 0, x = 0, y = 0; byte result; while (ip < refData.length) { refDataInt = (int) refData[ip] & 255; inDataInt = (int) this.inData[ip++] & 255; r = refDataInt - inDataInt; refDataInt = (int) refData[ip] & 255; inDataInt = (int) this.inData[ip++] & 255; g = refDataInt - inDataInt; refDataInt = (int) refData[ip] & 255; inDataInt = (int) this.inData[ip++] & 255; b = refDataInt - inDataInt; result = (byte) (Math.sqrt((double) ((r * r) + (g * g) + (b * b)) / 3.0)); //black/white image now. if (result > (byte) this.threshold) { if (validateActionSection(x, y)) { detectionScreen[op++] = (byte) 255; detectionScreen[op++] = (byte) 0; detectionScreen[op++] = (byte) 0; } else { detectionScreen[op++] = (byte) 0; detectionScreen[op++] = (byte) 255; detectionScreen[op++] = (byte) 0; } } else { detectionScreen[op++] = (byte) result; detectionScreen[op++] = (byte) result; detectionScreen[op++] = (byte) result; } y = x == this.sizeIn.width ? y + 1 : y; x = x == this.sizeIn.width ? 0 : x + 1; } }
aac28bc7-e196-4ad0-a062-ec04407159ff
1
private ClusterList beginBottomUp() { Cluster newCluster; ClusterList firstClusterList = new ClusterList(); for (int i = 0; i < this.instances.numInstances(); i++) { newCluster = new Cluster(this.instances.instance(i)); firstClusterList.add(newCluster); } return firstClusterList; }
dfa423e8-532f-4bdc-847d-ad202635b1de
3
public void pad(int width) throws IOException { int gap = (int) this.nrBits % width; if (gap < 0) { gap += width; } if (gap != 0) { int padding = width - gap; while (padding > 0) { this.zero(); padding -= 1; } } this.out.flush(); }
48587e0b-db27-4e02-b622-f73328645abf
1
public List<String> getLinks() { Pattern pattern = Pattern.compile("(?i)(?s)<\\s*?iframe.*?href=\"(.*?)\".*?>"); Matcher matcher = pattern.matcher(content); List<String> list = new ArrayList<String>(); while (matcher.find()) { list.add(matcher.group(1)); } return list; }
f951900e-cc05-4146-ad40-a41ff1eb30d0
8
public String isInteresting(String x){ int n = x.length(); boolean[] visited = new boolean[n]; for(int i=0; i<n-1; i++){ if(!visited[i]){ visited[i]=true; boolean found=false; for(int j=i+1; j<n; j++){ if(!visited[j] && x.charAt(i)==x.charAt(j) && j-i-1==Integer.parseInt(x.charAt(i)+"")){ found=true; visited[j]=true; } } if(!found) return "Not interesting"; } } return visited[n-1] ? "Interesting" : "Not interesting"; }
841ce4ab-2ff7-406d-8ae6-04b4096e8634
1
public boolean[] getMarkers(boolean colour) { if (colour) { return markersBlack; } else { return markersRed; } }
b23b1acf-528d-4f25-b0fd-2f3287cfe21a
7
@Override public String niceCommaList(List<?> V, boolean andTOrF) { String id=""; for(int v=0;v<V.size();v++) { String s=null; if(V.get(v) instanceof Environmental) s=((Environmental)V.get(v)).name(); else if(V.get(v) instanceof String) s=(String)V.get(v); else continue; if(V.size()==1) id+=s; else if(v==(V.size()-1)) id+=((andTOrF)?"and ":"or ")+s; else id+=s+", "; } return id; }
963d79f9-ee13-4124-9b0a-c753fec27a49
3
@Override public ExecutionContext run(ExecutionContext context) throws InterpretationException { int x = DrawingZone.turtle.getPosX(); int y = DrawingZone.turtle.getPosY(); Value value = ((AbsValueNode) this.getChildAt(0)).evaluate(context); if (value.getType() == VariableType.NUMBER) { Number num = (Number) value.getValue(); int _X = (int) (num.intValue() * Math.cos((double) Math.toRadians(DrawingZone.turtle.getHeading()))); int _Y = -(int) (num.intValue() * Math.sin((double) Math.toRadians(DrawingZone.turtle.getHeading()))); DrawingZone.turtle.setPos(x + _X, y + _Y); Color color; if(DrawingZone.turtle.getErase()) color = UserInterface.dw.getBackground(); else color = UserInterface.dw.getCurrentColor(); if (DrawingZone.turtle.getPen()) UserInterface.dw.toDraw.add(new Shape(new Line2D.Float(x, y, x + _X, y + _Y), color)); UserInterface.dw.revalidate(); } else throw new InterpretationException(InterpretationErrorType.INVALID_ARGUMENT, line, null); return context; }
85632511-908e-499f-9f3e-be8ced9a31c3
0
@Test public void testLoadFile() { // String ergebnisstring1 = ""; // String ergebnisstring2 = "Hallo, ich bin ein\nZeilenumbruch "; // String ergebnisstring3 = "Gesperrtes File"; // // // String ergebnisstring4 = // // // "D�ner mit So�e & einer b�rigen t�rkischen Bananen & Co KG"; // // // assertEquals(ergebnisstring1, // SourceLoader.loadFile("/var/www/testfiles/testfile1.txt")); //// assertEquals(ergebnisstring2, //// SourceLoader.loadFile("/var/www/testfiles/testfile2.txt")); // assertEquals(ergebnisstring3, // SourceLoader.loadFile("/var/www/testfiles/testfile3.txt")); // // assertTrue(SourceLoader.loadFile("/var/www/testfiles/fehlendesfile.txt").contains("FAIL FileNotFoundException")); }
1a04fd77-5625-49a2-9ff9-ca83c81c068f
1
public void setFrontLeftThrottle(int frontLeftThrottle) { this.frontLeftThrottle = frontLeftThrottle; if ( ccDialog != null ) { ccDialog.getThrottle1().setText(Integer.toString(frontLeftThrottle) ); } }
81d13c9d-b83b-4e33-accc-454eddac405f
7
@Override public void run() { ClientHandler c; stop = false; if (!isConnected()) throw new IllegalStateException("Service not connected!"); pool = Executors.newCachedThreadPool(new ClientThreadFactory( getUncaughtExceptionHandler())); try { try { while (!stop) { c = new ClientHandler(ns.accept(), as, this.keyDirectory, this.privateKeyServer); clientHandlerList.add(c); pool.execute(c); } } finally { if (pool != null) shutdownAndAwaitTermination(pool); if (ns != null) ns.close(); } } catch (IOException e) { // The if-clause down here is because of what is described in // http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html // under "What if a thread doesn't respond to Thread.interrupt?" // So the socket is closed when the ClientNetworkService is // closed and in that special case no error should be // propagated. if (!stop) { UncaughtExceptionHandler eh = this .getUncaughtExceptionHandler(); if (eh != null) eh.uncaughtException(this, e); } } }
0812396f-f1db-487f-b58b-8c787aa1e4e2
7
private void move() { xa = 0; ya = 0; List<Player> players = level.getPlayers(this, 50); if (players.size() > -0) { Player player = players.get(0); if (x < player.getX()) xa += speed; if (x > player.getX()) xa -= speed; if (y < player.getY()) ya += speed; if (y > player.getY()) ya -= speed; } if (xa != 0 || ya != 0) { move(xa, ya); walking = true; } else { walking = false; } }
bc8027d4-a229-4466-9466-40914590f40a
2
public boolean subst(ASTree newObj, ASTree oldObj) { for (ASTList list = this; list != null; list = list.right) if (list.left == oldObj) { list.left = newObj; return true; } return false; }
f828dfbe-9630-43eb-ae0a-28b86c12a04d
6
@EventHandler public void MagmaCubeRegeneration(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.Regeneration.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Regeneration.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getMagmaCubeConfig().getInt("MagmaCube.Regeneration.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Regeneration.Power"))); } }
89c286f7-29d6-4cd0-91a3-42cba593068a
5
public HandlerQueue buildHandlerQueue (Class<? extends IEvent> event) { // create handler queue HandlerQueue queue = new HandlerQueue (); // append queues if (this.handlerMap.containsKey (event)) queue.addAll (this.handlerMap.get (event)); // search for child if (event.getSuperclass () != null) { Class<?> superEvent = event.getSuperclass (); // cast try { queue.addAll (this.buildHandlerQueue (superEvent.asSubclass (IEvent.class))); } catch (ClassCastException ex) { } } // return finished queue return queue; }
56401375-6e76-439f-8e55-0c5fd4488b52
1
public static void ShowEnumSet(EnumSet<FontConstant> enumset) { for(Iterator<FontConstant> iter = enumset.iterator();iter.hasNext();) { System.out.println(iter.next()); } }
237fd7c3-3caa-4e2e-b314-4c4730fac32d
6
public void train(StringWrapperIterator i0) { SourcedStringWrapperIterator i = (SourcedStringWrapperIterator)i0; Set seenTokens = new HashSet(); while (i.hasNext()) { BagOfSourcedTokens bag = asBagOfSourcedTokens(i.nextSourcedStringWrapper()); seenTokens.clear(); for (Iterator j=bag.tokenIterator(); j.hasNext(); ) { totalTokenCount++; Token tokj = (Token)j.next(); if (!seenTokens.contains(tokj)) { seenTokens.add(tokj); // increment documentFrequency counts Integer df = (Integer)documentFrequency.get(tokj); if (df==null) documentFrequency.put(tokj,ONE); else if (df==ONE) documentFrequency.put(tokj,TWO); else if (df==TWO) documentFrequency.put(tokj,THREE); else documentFrequency.put(tokj, new Integer(df.intValue()+1)); } } collectionSize++; } }
fbac97c5-9fb7-4afd-bc3a-87c997d8ce05
8
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; if (!creationdate.equals(user.creationdate)) return false; if (!email.equals(user.email)) return false; if (!id.equals(user.id)) return false; if (!lastupdate.equals(user.lastupdate)) return false; if (!password.equals(user.password)) return false; if (!username.equals(user.username)) return false; return true; }
484be49a-c8f6-4dee-9f74-16bb30547c95
7
public void terminate() { // If we have any branches which should not be taken, // we need to create a failure handler for if they were taken. if (generateGlobalNotTaken) { // XXX: In the future, if we want to set specific flags here, // can add more instructions after the label and add an // unconditional branch above it to avoid executing the block at // the end of the program. instructions.add(new Instruction(new Label("nottaken"))); instructions.get(instructions.size() - 1).appendComment("failure " + "case for wrongly taken branches"); } instructions.add(new Instruction(new HLT())); String finalState = "\n"; // Summarize registers for (int i = 0; i < registerFile.length; i++) { finalState += "\n# R" + i + " = " + (isRegisterValid (registerFromNumber(i)) ? registerFile[i] : "xxxx"); } // Summarize flags finalState += "\n\n# Z = " + (isFlag_z() ? "1" : "0") + " N = " + (isFlag_n() ? "1" : "0") + " V = " + (isFlag_v() ? "1" : "0"); // Summarize memory: finalState += "\n\n# Valid memory addresses:"; for (int i : validMemory) { finalState += "\n# mem[" + i + "] = " + memory[i]; } instructions.get(instructions.size() - 1).appendComment(finalState); }
af9563d0-7f7a-45b7-bcee-e250df9f0df0
0
public Address getIndirizzo() { return indirizzo; }
6ae22a40-4768-42df-a9e6-9a2fd5db0961
4
public void getBusiness() throws IOException{ while (true) { String line = reader1.readLine(); if (line==null) break; try{ JSONObject business = new JSONObject(line); String b_id = business.getString("business_id"); List<String> categories = new ArrayList<String>(); JSONArray rawcategories = business.getJSONArray("categories"); for(int i=0; i<rawcategories.length();i++){ categories.add(rawcategories.getString(i)); } int review_count = business.getInt("review_count"); double stars = business.getDouble("stars"); Business b = new Business(b_id, categories, review_count, stars); businessMap.put(b_id, b); }catch(JSONException e) { e.printStackTrace(); System.out.print(line + System.getProperty("line.separator")); } } }
dd9c01c3-094f-4e94-804b-f78bb7593ff5
3
public static void copyFile(File inF, File outF) throws IOException { // TODO Auto-generated method stub //System.out.println("Copying"); @SuppressWarnings("resource") FileChannel inChannel = new FileInputStream(inF).getChannel(); @SuppressWarnings("resource") FileChannel outChannel = new FileOutputStream(outF).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { Misc.ErrorMessage(); throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
5336d533-5cf0-4aa6-b82c-e4593aa68b35
9
public int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid == null || obstacleGrid.length == 0) return 0; int row = obstacleGrid.length, col = obstacleGrid[0].length; int hash[][] = new int[row][col]; for (int i = 0; i < col; i++) { if (obstacleGrid[0][i] == 1) { break; } hash[0][i] = 1; } for (int i = 0; i < row; i++) { if (obstacleGrid[i][0] == 1) { break; } hash[i][0] = 1; } for (int x = 1; x < row; x++) { for (int y = 1; y < col; y++) { if (obstacleGrid[x][y] == 0) { hash[x][y] = hash[x - 1][y] + hash[x][y - 1]; } else { hash[x][y] = 0; } } } return hash[row - 1][col - 1]; }
68510a18-9809-45bd-8bfa-906dfc1fd98d
4
public static Hand getBestHand(Card[] hole, Card[] communalCards) { assert hole.length == 2; assert communalCards.length == 5; Hand[] allHands = new Hand[21]; Card[] available = new Card[]{hole[0],hole[1],communalCards[0], communalCards[1],communalCards[2],communalCards[3],communalCards[4]}; int counter = 0; for (int i = 0; i < 7; i++) { for (int j = i+1; j < 7; j++) { Hand hand = generateHand(available,i, j); if(hand != null){ allHands[counter++] = hand; } } } if(counter > 0){ List<Hand> temp = Arrays.asList(allHands).subList(0, counter); Collections.sort(temp); return temp.get(temp.size()-1); }else{ return null; } }
5ed5cf77-8d18-4ca7-9d2a-0082771b0a68
3
public static Boolean readFile(ByteBuffer buffer, FileTransfer fileReceiver){ ByteBuffer readBuffer = buffer.asReadOnlyBuffer(); buffer.limit(50);// 读取50个字节,解析获取内容的长度,内容长度最大为4个FFFF(4个字节),再加上2个字节\r\n String msg = CoderUtils.decode(buffer); if(!MyStringUtil.isBlank(msg)){// 上传文件的请求头 if(fileReceiver.isReadHead()){ fileReceiver.writeBody(readBuffer, 0, fileReceiver.getSizeWithHead());// 读取文件内容 fileReceiver.setReadHead(false); fileReceiver.setSizeWithHead(0); }else{ String packageHead = msg.split((HttpConstants.RetentionWord.CRLF_STR))[0]; try{ Integer length = Integer.parseInt(packageHead, 16); Integer btyeLength = packageHead.getBytes().length + 2;// 加上2个回车换行符 fileReceiver.writeBody(readBuffer, btyeLength, length);// 读取文件内容 }catch(NumberFormatException nfe){// 读取不带包头信息的文件 fileReceiver.writeBody(readBuffer, 0);// 读取文件内容 } } } return null; }
d65ffa95-f5c9-4817-8e25-f15fc9849c29
2
public void tagVirts() { for (Clazz clazz : classes.values()) { clazz.tagVirts(this); } for (DirManager dir : subDirs) { dir.tagVirts(); } }
cd45a245-7796-493f-98da-b768bb96bd99
0
public void setCoef(String coef) { this.coef = coef; }
e3a25d5c-cd8a-4595-a0d3-f689e4d4aea1
0
@Override public String toString() { return this.nodeString(0); }
a3e434fa-4c52-488b-8a71-813926cdb053
3
public void alertNext() { scenesCounter++; if(scenesCounter<scenePics.size()){ scene=scenePics.get(scenesCounter); }else{ if(nextLevel.startsWith("b")){ getKarpfenGame().setLvl(new BossLevel(nextLevel, getKarpfenGame())); }else if(nextLevel.startsWith("s")){ getKarpfenGame().setStory(new Storyline(nextLevel, getKarpfenGame())); }else{ getKarpfenGame().setLvl(new Level(nextLevel, karpfenGame)); } scenePics.clear(); karpfenGame.setStory(null); } }
550a3264-282e-4fc3-b67b-b2b447e00810
7
public void showValues() { String attribute; ArffSortedTableModel model; ArffTable table; HashSet values; Vector items; Iterator iter; ListSelectorDialog dialog; int i; int col; // choose attribute to retrieve values for attribute = showAttributes(); if (attribute == null) return; table = (ArffTable) getCurrentPanel().getTable(); model = (ArffSortedTableModel) table.getModel(); // get column index col = -1; for (i = 0; i < table.getColumnCount(); i++) { if (table.getPlainColumnName(i).equals(attribute)) { col = i; break; } } // not found? if (col == -1) return; // get values values = new HashSet(); items = new Vector(); for (i = 0; i < model.getRowCount(); i++) values.add(model.getValueAt(i, col).toString()); if (values.isEmpty()) return; iter = values.iterator(); while (iter.hasNext()) items.add(iter.next()); Collections.sort(items); dialog = new ListSelectorDialog(getParentFrame(), new JList(items)); dialog.showDialog(); }
d2825779-6727-453e-8f12-1c21dc070d19
4
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FilterSet)) return false; FilterSet filterSet = (FilterSet) o; if (filters != null ? !filters.equals(filterSet.filters) : filterSet.filters != null) return false; return true; }
34b5ced8-2ad0-45d9-aa31-d7677bf05989
2
public boolean instanceOf(Object obj, String className) throws InterpreterException { Class clazz; try { clazz = Class.forName(className); } catch (ClassNotFoundException ex) { throw new InterpreterException("Class " + ex.getMessage() + " not found"); } return obj != null && clazz.isInstance(obj); }
ec2e4230-0d5b-4478-99c3-05b986e5352f
9
private void addListener() { final MainViewController mainViewController = this; mainView.setAboutMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new AboutPanel(); } }); mainView.setServerConfigMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Show settings window settingsViewController = new SettingsViewController(mainView); } }); mainView.setOpenPadMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String padId = JOptionPane.showInputDialog("Pad ID"); if (padId == null) { return; } try { openPad(padId); } catch (EPLiteException e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage() + ". Are you sure you entered the correct padId?", "Error loading pad", JOptionPane.ERROR_MESSAGE); } } }); mainView.setCreatePadMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String padId = JOptionPane.showInputDialog("Pad ID"); if (padId == null) { return; } try { if (isGroupPad()) { int reply = JOptionPane.showConfirmDialog(null, "Create pad for this group?", "", JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { createGroupPad(padId); } else { createPublicPad(padId); } } else { createPublicPad(padId); } } catch (EPLiteException e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage(), "Error creating pad", JOptionPane.ERROR_MESSAGE); } } }); mainView.setManagePadsMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new ManagePadsController(epLite.getAllGroups(), mainViewController); } }); mainView.setOpenGroupMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String groupId = JOptionPane.showInputDialog("Group ID"); if (groupId == null) { return; } try { openGroup(groupId); } catch (EPLiteException e) { e.printStackTrace(); JOptionPane.showMessageDialog(mainView, "Error: " + e.getMessage(), "Error opening group", JOptionPane.ERROR_MESSAGE); } } }); mainView.setCreateGroupMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { openGroup(epLite.createGroup()); } }); /* * mainView.setDeleteGroupMenuListener(new ActionListener() { * * @Override public void actionPerformed(ActionEvent arg0) { * epLite.deleteGroup(actualGroupId); } }); */ mainView.setListAllGroupsMenuListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { new GroupListController(epLite.getAllGroups(), mainViewController); } catch (EPLiteException epEx) { epEx.printStackTrace(); JOptionPane.showMessageDialog(mainView, "Error: " + epEx.getMessage(), "Error listing groups", JOptionPane.ERROR_MESSAGE); } } }); }
ff7e4dc1-0605-456b-b62b-54ca0d40be2b
5
@Override public void executeCurrentTasks() { System.out.println("Thread: " + threadId + " is executing a task"); setThreadState(THREAD_STATE.RUNNING); // System.out.println("Task list size: " + taskList.size()); for (int i = 0; i < taskList.size(); i++) { Task task = taskList.remove(i); // System.out.println("Executing task " + task.getTaskId() // + " on thread " + getThreadId()); taskCallback = task.getTaskCallback(); if (taskCallback != null) { taskCallback.onTaskStart(task); } task.beginTask(this); task.stopTask(); do { if (getThreadState() == THREAD_STATE.FINISHED) { stopThread(); } } while (getThreadState() != THREAD_STATE.READY_FOR_NEXT_TASK || getThreadState() != THREAD_STATE.FINISHED); } }
f942ab2b-de93-4647-a246-d669dd5dffa2
2
static void maybeDebugWarn(final String message, final boolean force) { if (DEBUG_ALL || force) { System.err.println(getTimestamp() + " " + message); } }
52485aab-a12a-4965-b594-b05f536cdfed
2
public void closePanel(String chan) { int index = indexOfTab(chan); if (index != -1) { tabs.removeTabAt(index); if (index <= lastChanIndex) lastChanIndex--; } setSelectedTab(); tabs.revalidate(); }
c7e34b68-dde0-4a9a-9f1e-d946f215228f
3
@Before public void setUp() throws Exception { words = Lists.newArrayList(); for (int i = 0; i < 10; i++) { words.add("Eric"); } for (int i = 0; i < 30; i++) { words.add(String.valueOf(i)); } for (int i = 0; i < 50; i++) { words.add("Gonzalez"); } }
2942471e-a475-4016-ac10-ff203cfc72f9
0
public void setPersonId(int personId) { this.personId = personId; }
5c3b0f7f-d6e2-4b76-8d02-0c8a3a600343
4
private void initGui(Stage primaryStage) { this.stage = primaryStage; // splitPaneHoriz = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, splitPaneVerti); // splitPaneHoriz.setResizeWeight(0); // splitPaneHoriz.setDividerLocation(250); // splitPaneHoriz.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { // @Override // public void propertyChange(PropertyChangeEvent evt) { // if (!leftPanelVisible && (int) evt.getNewValue() > (int) evt.getOldValue()) { // hideLeftPanel.setText(" < "); // leftPanelVisible = true; // } // } // }); // BUILD VERTICAL SPLIT PANE ========================================= verticalSplitPane = new SplitPane(); verticalSplitPane.setOrientation(Orientation.VERTICAL); verticalSplitPane.getItems().addAll( RegionBuilder.create().build(), RegionBuilder.create().build()); verticalSplitPane.setDividerPositions(0.2); // BUILD LEFT AREA =================================================== TreeItem<ImgEvent> eventRootNode = new TreeItem<ImgEvent>(new ImgEvent("", 0, 0)); TreeView<ImgEvent> eventTree = new TreeView<ImgEvent>(); eventTree.setShowRoot(false); eventTree.setRoot(eventRootNode); for (int i=0; i<40; i++) { TreeItem<ImgEvent> item = new TreeItem<ImgEvent>(new ImgEvent("Element " + i, 0, 0)); eventRootNode.getChildren().add(item); TreeItem<ImgEvent> child = new TreeItem<ImgEvent>(new ImgEvent("Child " + i, 0, 0)); item.getChildren().add(child); } Tab eventTab = new Tab("Events"); eventTab.setContent(eventTree); TreeItem<String> dateRootNode = new TreeItem<String>("Dates"); TreeView<String> dateTree = new TreeView<String>(); dateTree.setShowRoot(false); dateTree.setRoot(dateRootNode); for (int i=0; i<40; i++) { TreeItem<String> item = new TreeItem<String>("Element " + i); dateRootNode.getChildren().add(item); TreeItem<String> child = new TreeItem<String>("Child " + i); item.getChildren().add(child); } Tab dateTab = new Tab("Dates"); dateTab.setContent(dateTree); TabPane leftTabPane = new TabPane(); leftTabPane.setSide(Side.TOP); leftTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE); leftTabPane.getTabs().addAll(dateTab, eventTab); // leftTabbedPane.addChangeListener(new ChangeListener() { // @Override // public void stateChanged(ChangeEvent e) { // if (leftTabbedPane.getSelectedComponent().equals(eventScrollPane)) { // dateTree.setSelectionInterval(-10, -1); // imageBrowser.clearDates(); // } // else if (leftTabbedPane.getSelectedComponent().equals(dateScrollPane)) { // eventTree.setSelectionInterval(-10, -1); // imageBrowser.clearEvent(); // } // loadImages(); // } // }); BorderPane leftPane = new BorderPane(); leftPane.setCenter(leftTabPane); hideLeftPane = new Label(" < "); BorderPane.setAlignment(hideLeftPane, Pos.CENTER); hideLeftPane.setOnMouseClicked(new EventHandler<Event>() { @Override public void handle(Event event) { if (leftPaneVisible) { horizontalSplitPaneDivPos = horizontalSplitPane.getDividerPositions()[0]; // ; horizontalSplitPane.setDividerPosition(0, (hideLeftPane.getWidth() +6) / stage.getWidth()); // horizontalSplitPane.set hideLeftPane.setText(" > "); leftPaneVisible = false; } else { horizontalSplitPane.setDividerPosition(0, horizontalSplitPaneDivPos); hideLeftPane.setText(" < "); leftPaneVisible = true; } } }); leftPane.setRight(hideLeftPane); // BUILD HORIZONTAL SPLIT PANE ======================================= horizontalSplitPane = new SplitPane(); horizontalSplitPane.setOrientation(Orientation.HORIZONTAL); horizontalSplitPane.getItems().addAll( leftPane, verticalSplitPane); horizontalSplitPane.setDividerPositions(0.2); SplitPane.setResizableWithParent(verticalSplitPane, false); // BUILD THE FRAME =================================================== stage.setScene(new Scene(horizontalSplitPane)); Point defaultSize = new Point(750, 600); Point size = guiProperties.getPropPoint("gui_frame_size", defaultSize); Point defaultPos = new Point(-10000, -10000); Point pos = guiProperties.getPropPoint("gui_frame_position", defaultPos); if (isWindowInScreenBounds(pos, size)) { stage.setWidth(size.x); stage.setHeight(size.y); stage.setX(pos.x); stage.setY(pos.y); } else { stage.setWidth(defaultSize.x); stage.setHeight(defaultSize.y); } stage.setMinWidth(500); stage.setMinHeight(500); stage.setTitle("Image Browser"); stage.show(); }
cb81f730-089a-462c-8ff8-9a37b73bbfaf
6
private void humanMove(int playerNumber){ boolean setCell = false; while (true){ int x = 0,y = 0; while (!setCell) { x = GetData.GetXCoordinateOfCell(field); y = GetData.GetYCoordinateOfCell(field); if (playerNumber == FIRST_PLAYER_NUMBER){ setCell = field.setCellFirstPlayer(x,y); }else if (playerNumber == SECOND_PLAYER_NUMBER){ setCell = field.setCellSecondPlayer(x,y); } } System.out.println("Do you want to change your choose?"); if(GetData.getYesOrNoAnswer()){ field.setDefaultCellValue(x,y); setCell = false; } else { if(gameRegime == TWO_PLAYERS_ONLINE_GAME_REGIME){ gameInternet.sentMove(x,y); } return; } } }
5050c551-5c26-4556-8747-551c6b5f1c3a
9
public String [] getOptions() { String [] options = new String [16]; int current = 0; if (m_noCleanup) { options[current++] = "-L"; } if (!m_collapseTree) { options[current++] = "-O"; } if (m_unpruned) { options[current++] = "-U"; } else { if (!m_subtreeRaising) { options[current++] = "-S"; } if (m_reducedErrorPruning) { options[current++] = "-R"; options[current++] = "-N"; options[current++] = "" + m_numFolds; options[current++] = "-Q"; options[current++] = "" + m_Seed; } else { options[current++] = "-C"; options[current++] = "" + m_CF; } } if (m_binarySplits) { options[current++] = "-B"; } options[current++] = "-M"; options[current++] = "" + m_minNumObj; if (m_useLaplace) { options[current++] = "-A"; } if (!m_useMDLcorrection) { options[current++] = "-J"; } while (current < options.length) { options[current++] = ""; } return options; }
cac5202f-5416-4e7e-92cf-8c555a45ef9f
4
private void logErrorsFile(byte[] data) throws IOException { if (ProduceCSV.produceLog) { if (errorsFile.size() == 0) { return; } if (fileErrorLog == null) { openErrorLogFile(); } fileErrorLog.println("------"); fileErrorLog.println(parameterData.jobName); for (String error : errorsFile) { fileErrorLog.println(error); } fileErrorLog.println(new String(data)); fileErrorLog.flush(); } }
8efa2cf2-a382-4284-a8a3-37d5af831373
6
private Boolean potEqual(Table table) { boolean allEqual = true; int max = 0; for (Player player : table.getPlayers()) { if (player == null) { continue; } System.out.println("player : " + player.getName() + " : status : " + player.getStatus() + " : " + player.getBet() + " max: " + max); if (player.getStatus().equals(Player.ACTIVE) || player.getStatus().equals(Player.INACTIVE)) { if (max == 0) { max = player.getBet(); } else if (player.getBet() != max) { return false; } } } return allEqual; }
94e69fbe-aafe-4eb8-a58b-5f047b06b23b
9
public void buttonListener(int cell){ switch (cell){ case 1: _x = 1; _y = 1; break; case 2: _x = 2; _y = 1; break; case 3: _x = 3; _y = 1; break; case 4: _x = 1; _y = 2; break; case 5: _x = 2; _y = 2; break; case 6: _x = 3; _y = 2; break; case 7: _x = 1; _y = 3; break; case 8: _x = 2; _y = 3; break; case 9: _x = 3; _y = 3; break; } doInput = true; }
0ac5e684-0b45-4e28-9b12-2ccdbcf4861e
1
public byte[] toByteArray() { return cw == null ? null : cw.toByteArray(); }
3cbb5dd3-3287-4dda-9e3b-5f093263ca34
6
public static void main(String[] args) { logger.setLevel(Level.SEVERE); ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.SEVERE); logger.addHandler(handler); if (args.length == 0) { logger.warning("Invalid arguments count."); return; } try { String key = args[0]; String alphabet = args[1]; String file = args[2]; String dir=args[3]; BufferedReader in = new BufferedReader(new FileReader(file)); while (in.ready()) { if (dir.equals("0")) { String ret = encrypt(key, in.readLine(), alphabet); System.out.println(ret); } else if (dir.equals("1")){ String ret = decrypt(key, in.readLine(), alphabet); System.out.println(ret); }else{ String ret = encrypt(key, in.readLine(), alphabet); System.out.println(ret); ret = decrypt(key, ret, alphabet); System.out.println(ret); } } } catch (NumberFormatException | FileNotFoundException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } }
5ee828c3-34fe-43ca-a4ad-0dc4a56bc568
8
public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); }
c190945c-7306-42ed-962c-ee0ef7d055e1
2
public static void omniData(Object m){ rover = head; while(rover != null){ if(rover.status == 1){ rover.sendObject(m); } rover = rover.next; } }
8a131d97-87bf-4134-88fb-fb58ffb1821a
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); session.removeAttribute("error"); session.removeAttribute("sucesso"); String valor = request.getParameter("oferta"); try { Leitor leitor = (Leitor) session.getAttribute("user"); if(leitor == null){ session.setAttribute("error", "Leitor nao está logado."); response.sendRedirect(request.getContextPath() + "/index.jsp"); }else if(valor == null || valor.trim().equals("")){ session.setAttribute("error", "Preencha todos os campos."); response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp"); }else{ ClassificadoDAO dao = new ClassificadoDAO(); double oferta = Double.parseDouble(valor); Classificado classificado = (Classificado)session.getAttribute("classificado"); if(oferta > classificado.getPreco() && oferta > classificado.getMelhorOferta()){ classificado.setUsuario(leitor); classificado.setDataOferta(new Date()); classificado.setMelhorOferta(oferta); dao.atualizar(classificado); session.setAttribute("classificado", classificado); response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp"); } else { session.setAttribute("error", "Oferta menor que ultimo lance dado."); response.sendRedirect(request.getContextPath() + "/mostrarClassificado.jsp"); } } } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } }
1a1fc045-5d76-4b8f-9367-980c5aa984dc
7
long largestPrimeFactor(long number){ ArrayList<Integer> list=new ArrayList<Integer>(); for(int i=2;i<number;i++){ boolean isPrime=false; for(Integer prime:list){ if(i%prime==0){ isPrime=true; break; } } if(isPrime) continue; list.add(i); if(number%i==0){ while(number%i==0){ number=number/i; } if(number==i) return number; } } return number; }
419ca885-ecac-4be1-865c-a65e0c53df85
2
public void openRd(String filename) { try { this.close(); this.filename = filename; inf = true; file = new File(this.filename); sc = new Scanner(file); } catch (FileNotFoundException e) { ExceptionLog.println("Ошибка открытия файла " + this.filename + " для чтения"); } catch(Exception e) { ExceptionLog.println("Ошибка в блоке открытия файла " + this.filename + " для чтения"); ExceptionLog.println(e); } }
ab00e93e-78fa-4c58-85bb-5b799498e4ca
2
private void connect() throws Exception { // // 创建SSLContext对象,并使用我们指定的信任管理器初始化 // TrustManager[] tm = { new MyX509TrustManager() }; // SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); // sslContext.init(null, tm, new java.security.SecureRandom()); // // 从上述SSLContext对象中得到SSLSocketFactory对象 // SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url2 = new URL("https://kyfw.12306.cn/otn/queryOrder/queryMyOrderNoComplete"); HttpsURLConnection con2 = (HttpsURLConnection) url2.openConnection(); con2.setSSLSocketFactory(Utils.getSsf()); InputStream is2 = con2.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.indexOf("用户未登录") != -1) System.out.println(line); } reader.close(); login("289048093@qq.com", "lichao258", "test"); }
64b09af0-1c20-4590-a396-742bc447f2f6
6
public 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; }
90ae3be9-0685-4df6-b58b-3f9d81182558
4
private boolean isLocationInPicture(final int x, final int y) { boolean result = false; // the default is false if ((x >= 0) && (x < this.picture.getWidth()) && (y >= 0) && (y < this.picture.getHeight())) { result = true; } return result; }
9cdec8cc-64d9-4f26-952d-2aa8eaab0944
7
@EventHandler public void WitherMiningFatigue(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Wither.MiningFatigue.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof WitherSkull) { WitherSkull a = (WitherSkull) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getWitherConfig().getBoolean("Wither.MiningFatigue.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_DIGGING, plugin.getWitherConfig().getInt("Wither.MiningFatigue.Time"), plugin.getWitherConfig().getInt("Wither.MiningFatigue.Power"))); } } }
41e00e17-7b1d-47cc-bb77-77f5a96e23f9
5
public void configQuickstart(Object args[]) { // // final TerrainGen TG = new TerrainGen( 64, 0.0f, Habitat.ESTUARY, 0.15f, Habitat.MEADOW , 0.35f, Habitat.BARRENS, 0.35f, Habitat.DUNE , 0.15f ) ; final World world = new World(TG.generateTerrain()) ; TG.setupMinerals(world, 0, 0, 0) ; TG.setupOutcrops(world) ; final Base base = Base.createFor(world, false) ; // // final Human ruler = new Human(new Career( Rand.yes(), Background.KNIGHTED, Background.HIGH_BIRTH, (Background) Rand.pickFrom(Background.ALL_PLANETS) ), base) ; final Human consort = new Human(new Career( ruler.traits.female(), Background.FIRST_CONSORT, Background.HIGH_BIRTH, ruler.career().homeworld() ), base) ; final List <Human> advisors = new List <Human> () ; advisors.add(ruler) ; advisors.add(consort) ; final List <Human> colonists = new List <Human> () ; for (int n = 2 ; n-- > 0 ;) { colonists.add(new Human(Background.VOLUNTEER , base)) ; colonists.add(new Human(Background.SUPPLY_CORPS, base)) ; colonists.add(new Human(Background.TECHNICIAN , base)) ; } for (int n = 3 ; n-- > 0 ;) { final Background b = (Background) Rand.pickFrom(COLONIST_BACKGROUNDS) ; colonists.add(new Human(b, base)) ; } for (Human c : colonists) { for (Skill s : house.skills()) if (c.traits.traitLevel(s) > 0) { c.traits.incLevel(s, 5) ; } } base.incCredits(10000) ; base.commerce.assignHomeworld((System) house) ; base.setInterestPaid(2) ; base.commerce.assignHomeworld((System) ruler.career().homeworld()) ; final Bastion bastion = establishBastion( world, base, ruler, advisors, colonists ) ; beginGame(world, base, bastion) ; }
f75b4a75-fb31-41dc-869b-864e88f8d504
4
public boolean sabotiere( int auswahl ) { boolean erfolgreich = false; switch ( auswahl ) { case 1: erfolgreich = goldStehlen(); break; case 2: erfolgreich = gebaeudeZerstoeren(); break; case 3: erfolgreich = kornVergiften(); break; case 4: erfolgreich = zufriedenheitVerringern(); break; } return erfolgreich; }
adb2847c-ac80-4db6-9540-68c59e170180
9
public String prepareURL(String method, HashMap<String, String> params) throws IllegalArgumentException { String ret = Connection.baseURL + method + "?"; boolean first = true; boolean illegalMethod = true; // Validate given method is a supported method for (final String s : Connection.methods) { if (s.equals(method)) { illegalMethod = false; break; } } if (illegalMethod) { throw new IllegalArgumentException( String.format("Invalid method |%s|", method)); } for (final Map.Entry<String, String> entry : params.entrySet()) { try { // Skip null if ((entry.getValue() == null) || (entry.getKey() == null)) { continue; } if (entry.getValue().length() == 0) { continue; } if (first) { first = false; } else { ret += "&"; } ret += String.format( "%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8") ); } catch (final UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } return ret; }
7d132ad9-824c-4eca-9f9e-1cc782070a4e
4
public static void continueDealing(long currentTime) { if (!isDealing) { return; } if (numCardsDealt >= Game.NUM_INITIAL_CARDS) { Game.linkedGet().flipCard(); isDealing = false; return; } if (currentTime - initialTime >= DEAL_DELAY) { Game.linkedGet().drawCard(Game.linkedGet().getPlayers().get(currentPlayerIndex)); initialTime = currentTime; currentPlayerIndex++; if (currentPlayerIndex >= Game.linkedGet().getNumPlayers()) { currentPlayerIndex = 0; numCardsDealt++; } } }
4ad5c5a8-8983-48ff-8d5a-a7b4ece578bb
5
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; // Draw the ghost Tetromino g2d.setColor(Color.LIGHT_GRAY); for (Point p : myWorld.generateGhostBlockCoordinates()) { g2d.drawRect(p.x * blockSize + 3, p.y * blockSize + 3, blockSize - 6, blockSize - 6); } // Draw each Block IIterator iter = (myWorld.getBlockCollection()).getIterator(); while (iter.hasNext()) { (iter.getNext()).draw(g2d); } Color lastColor = g2d.getColor(); // Draw the board g2d.setColor(Color.DARK_GRAY); for (int i = 0; i <= boardSizeY; i++) { g2d.drawLine(0, i * blockSize, boardSizeX * blockSize, i * blockSize); } for (int i = 0; i <= boardSizeX; i++) { g2d.drawLine(i * blockSize, 0, i * blockSize, boardSizeY * blockSize); } // Tint the board if paused if (!myWorld.getPlayStatus()) { g2d.setColor(new Color(lastColor.getRed(), lastColor.getGreen(), lastColor.getBlue(), 50)); g2d.fillRect(1, 1, boardSizeX * blockSize - 1, boardSizeY * blockSize - 1); g2d.setColor(Color.WHITE); g2d.drawString("Paused", boardSizeX * blockSize - 55, 20); } }
94d70868-b527-4db2-bf5f-791aa7dca975
7
private void startup() { HSSettings settings = HSSettings.getInstance(); // The channel store loads its current set of channels. If no channel // list is found then a default set of channels will be loaded into the // list. channelStore.setItemHistory(itemHistory); channelStore.load(settings.getChannelStoreFile()); itemStore.load(settings.getItemStoreFile()); itemHistory.load(settings.getItemHistoryFile()); // Set up the listeners. itemStore.addItemStoreListener(itemStoreListener); channelStore.addChannelStoreListener(channelStoreListener); try { bsfManager.declareBean("channelStore", channelStore, ChannelStore.class); bsfManager.declareBean("itemStore", itemStore, ItemStore.class); } catch (BSFException bsfe) { cat.error("Unable to declare beans for scripting due to " + bsfe); } // Normally Java Web Start handles a proxy for us, even if it is a proxy // that requires authentication. However, if HotSheet is run from the // command line the proxy has to be set manually so we have properties // to set us up for proxy operation (though it is not good enough for // an authenticated proxy. // // Note that the default value of this is false so unless the user sets // something it will not be used. boolean useProxy = new Boolean( settings.getProperties().getProperty("http.proxySet", "false")).booleanValue(); if (useProxy) { System.setProperty("http.proxySet", "true"); System.setProperty("http.proxyHost", settings.getProperties().getProperty("http.proxyHost")); System.setProperty("http.proxyPort", settings.getProperties().getProperty("http.proxyPort")); // See if we have an authentication name for authenticating proxies. boolean useAuth = new Boolean( settings.getProperties().getProperty("http.authSet", "false")).booleanValue(); if (useAuth) { final String authenticationName = settings.getProperties().getProperty("http.authName"); final String authenticationPassword = settings.getProperties().getProperty("http.authPass"); try { //registering with the system. Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( authenticationName, authenticationPassword.toCharArray()); } }); } catch (SecurityException se) { cat.error("Security exception while registering Authenticator with system: ", se); } } } // If the user wants to have refresh occur automatically then the number // of seconds to wait between refreshes will be set in the properties // file. int refreshInterval = (new Integer( settings.getProperties().getProperty("refresh.interval", "0"))).intValue(); if (refreshInterval > 0) { timer.scheduleAtFixedRate(new TimerTask() { public void run() { channelStore.retrieve(true); } }, refreshInterval * 1000, refreshInterval * 1000); } // If the item store is empty query the user about going ahead and doing // a refresh now. if (itemStore.size() == 0) { int answer = JOptionPane.showConfirmDialog(this, "Would you like to refresh all channels? (New HotSheet users should always say yes)", "Refresh Now?", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { refreshAllChannels(); } } else { updateItemList(); } }
11a670ba-6471-4b5e-ab5d-d44454e9ac02
7
private static void removeEmptyComments(File directory) throws IOException { for (File file : directory.listFiles()) { if (file.isDirectory()) { removeEmptyComments(file); } else { for (String currentEnding : CONFIG.getFileEndingsToCheck()) { if (file.getAbsolutePath().endsWith(currentEnding) && !ignoreFile(file)) { FileInputStream fis = new FileInputStream(file); byte[] data = new byte[(int) file.length()]; fis.read(data); fis.close(); String fileContent = new String(data, "UTF-8"); boolean foundInFile = false; String emptyComment = "/**" + (char) 10 + " */"; while (fileContent.contains(emptyComment)) { foundInFile = true; fileContent = fileContent.replace(emptyComment, ""); } if (foundInFile) { PrintWriter out = new PrintWriter(file); out.print(fileContent); out.close(); System.out.println("file: " + file.getAbsolutePath() + " modified by removing double empty comment"); COUNTER++; } } } } } }
e5329b78-c296-4fc4-a363-94e32375da3a
1
public String mapMethodName(String owner, String name, String desc) { String s = map(owner + '.' + name + desc); return s == null ? name : s; }
6f1c6969-5d5c-4878-a7aa-348e00a0c23d
2
public Key delMin() { if (isEmpty()) throw new java.util.NoSuchElementException(); Key min = pq[1]; exch(1, N--); sink(1); pq[N + 1] = null; if (N == pq.length / 4) resize(pq.length / 2); return min; }