text
stringlengths
14
410k
label
int32
0
9
public void grab(Boolean hasGold) { this.performance = this.performance -1; if (hasGold) { this.performance = this.performance + 1000; this.setState(WumpusConsts.STATE_GOAL); } }
1
@Override public void addQuestAnswer(String answ) { questAnswer.add(answ); }
0
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(PridajUpravFilterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(PridajUpravFilterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(PridajUpravFilterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(PridajUpravFilterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { PridajUpravFilterForm dialog = new PridajUpravFilterForm(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
6
private JTextField getJTextField0() { if (jTextField0 == null) { jTextField0 = new JTextField(); } return jTextField0; }
1
public final byte[] readBytes(final int amount) throws FileNotOnDiskException, DiskReadException { checkExists(); byte[] buffer = new byte[FILE_READ_BUFFER_SIZE]; final List<Byte> list = new ArrayList<Byte>(); int totalRead = 0; BufferedInputStream reader = null; try { reader = new BufferedInputStream(new FileInputStream(this)); while (totalRead < amount) { final int justReadCount = reader.read(buffer); if (justReadCount < 0) break; final int toReadInCount = totalRead + justReadCount > amount ? amount - totalRead : justReadCount; for (int i = 0; i < toReadInCount; i++) list.add(buffer[i]); totalRead += toReadInCount; } } catch (final FileNotFoundException e) { handleNotExists(); return null; } catch (final IOException e) { throw new DiskReadException("Failed to read bytes from file", this.toString(), e); } finally { closeStream(reader); } final byte[] listBytes = new byte[list.size()]; for (int i = 0; i < list.size(); i++) listBytes[i] = list.get(i); return listBytes; }
7
public static void main(String[] args) throws InterruptedException { SimpleCreature adam = new SimpleCreature(100.0); List<SimpleCreature> list = new ArrayList<SimpleCreature>(); list.add(adam); List<SimpleCreature> newBorn; while (true) { newBorn = new ArrayList<SimpleCreature>(); for (SimpleCreature creature : list) { creature.eat(new SimpleCreature(10.0)); if (creature.foodLevel > 200.0) { newBorn.add(creature.bear()); } } list.addAll(newBorn); System.out.println(list.size()); Thread.sleep(100); } }
3
private void pruneBeam(ArrayList<SegResult> beam, ArrayList<SegResult> candidates) { // TODO Implement pruning properly for (SegResult candidate : candidates) { if (beam.size() < beamSize) { beam.add(candidate); } } }
2
@Override public void run() { while (true) { try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (String b : Network.res.keySet()) { if (Calendar.getInstance().getTimeInMillis()/1000 - Network.res.get(b).time > 15){ continue; } System.out.println((Network.res.get(b).ip[0] + 256) % 256 + "." + (Network.res.get(b).ip[1] + 256) % 256 + "." + (Network.res.get(b).ip[2] + 256) % 256 + "." + (Network.res.get(b).ip[3] + 256) % 256 + " " + Network.res.get(b).name + " " + Network.res.get(b).time + " " + Network.res.get(b).compname); } } }
4
@Override public boolean containsDrink() { if((!CMLib.flags().isGettable(this)) &&(owner()!=null) &&(owner() instanceof Room) &&(((Room)owner()).getArea()!=null) &&(((Room)owner()).getArea().getClimateObj().weatherType((Room)owner())==Climate.WEATHER_DROUGHT)) return false; if(liquidRemaining()<1) { final List<Item> V=getContents(); for(int v=0;v<V.size();v++) { if((V.get(v) instanceof Drink) &&((V.get(v).material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)) return true; } return false; } return true; }
9
public Set<Map.Entry<Long,V>> entrySet() { return new AbstractSet<Map.Entry<Long,V>>() { public int size() { return _map.size(); } public boolean isEmpty() { return TLongObjectMapDecorator.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 TLongObjectMapDecorator.this.containsKey( k ) && TLongObjectMapDecorator.this.get( k ).equals( v ); } else { return false; } } public Iterator<Map.Entry<Long,V>> iterator() { return new Iterator<Map.Entry<Long,V>>() { private final TLongObjectIterator<V> it = _map.iterator(); public Map.Entry<Long,V> next() { it.advance(); long k = it.key(); final Long key = (k == _map.getNoEntryKey()) ? null : wrapKey( k ); final V v = it.value(); return new Map.Entry<Long,V>() { private V 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 Long getKey() { return key; } public V getValue() { return val; } public int hashCode() { return key.hashCode() + val.hashCode(); } public V setValue( V value ) { val = value; return put( key, value ); } }; } public boolean hasNext() { return it.hasNext(); } public void remove() { it.remove(); } }; } public boolean add( Map.Entry<Long,V> o ) { throw new UnsupportedOperationException(); } public boolean remove( Object o ) { boolean modified = false; if ( contains( o ) ) { //noinspection unchecked Long key = ( ( Map.Entry<Long,V> ) o ).getKey(); _map.remove( unwrapKey( key ) ); modified = true; } return modified; } public boolean addAll( Collection<? extends Map.Entry<Long,V>> c ) { throw new UnsupportedOperationException(); } public void clear() { TLongObjectMapDecorator.this.clear(); } }; }
7
public static void keyReleased(KeyEvent keyEvent) { Iterator<PComponent> it = components.iterator(); while(it.hasNext()) { PComponent comp = it.next(); if(comp == null) continue; if (shouldHandleKeys) { if (comp.shouldHandleKeys()) comp.keyReleased(keyEvent); } else { if (comp instanceof PFrame) { for (PComponent component : ((PFrame) comp).getComponents()) if (component.forceKeys()) component.keyReleased(keyEvent); } else if (comp.forceKeys()) comp.keyReleased(keyEvent); } } }
8
private Object handleCaln(Object tos) { if ((tos instanceof RepositoryRef && ((RepositoryRef)tos).getCallNumber() == null) || (tos instanceof Source && ((Source)tos).getCallNumber() == null)) { return new FieldRef(tos, "CallNumber"); } return null; }
4
public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus ) { if ( value instanceof LeafNode ) { JPanel panel = new JPanel(); String text = ( ( (LeafNode) value ).getItem() ).toString(); panel.add( new JLabel( text ) ); panel.setBackground( new Color( 0, 0, 0, 0 ) ); panel.setEnabled( tree.isEnabled() ); return panel; } else { super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus ); // Custom folder icon if ( value instanceof FolderNode ) { if ( expanded ) { if ( ( (FolderNode) value ).isAutoDL() ) setIcon( openFolderSelIcon ); else setIcon( openFolderIcon ); } else { if ( ( (FolderNode) value ).isAutoDL() ) setIcon( closedFolderSelIcon ); else setIcon( closedFolderIcon ); } } // Root icon else if ( ( (DefaultMutableTreeNode) value ).isRoot() ) setIcon( putioIcon ); setBorder( BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) ); if ( sel ) { if ( ( (DefaultMutableTreeNode) value ).isRoot() ) { setBackgroundSelectionColor( null ); setForeground( Color.BLACK ); } else { setBackgroundSelectionColor( colorSel ); } setBorderSelectionColor( null ); } return this; } }
8
private void loadDataFromFile(String file, InstanceType type) throws IOException { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); ArrayList<Double> features = new ArrayList<Double>(); String line = null; while((line = br.readLine()) != null) { String[] tks = line.trim().split("[\t]+"); int id = Integer.parseInt(tks[0]); double target = Double.parseDouble(tks[1]); features.clear(); for(int i = 2; i < tks.length; i++) { double value = Double.parseDouble(tks[i].split(":")[1]); features.add(value); } if(features.size() > this.featureCount) featureCount = features.size(); DenseInstance inst = new DenseInstance(id, target); inst.type = type; inst.addFeature(features); this.addInstance(inst); } br.close(); fr.close(); }
3
public static StringBuffer[] createScoreTemplate() { StringBuffer[] scoreLine = new StringBuffer[2]; for (int i = 0; i < scoreLine.length; i++) { scoreLine[i] = new StringBuffer(); } scoreLine[0].append(IConstants.SCORE_TABLE_TEMPLATE); scoreLine[1].append(IConstants.SCORE_TABLE_TEMPLATE); for (int i = 0; i < IConstants.FRAME_PER_PERSON - 1; i++) { scoreLine[0].append(IConstants.SCORE_TABLE_DIVIDED_TEMPLATE); scoreLine[1].append(IConstants.SCORE_TABLE_TEMPLATE); } scoreLine[0].append(IConstants.SCORE_TABLE_FINAL_DIVIDED_TEMPLATE); scoreLine[1].append(IConstants.SCORE_TABLE_FINAL_TEMPLATE); scoreLine[0].append(IConstants.SCORE_TABLE_DIVIDED_TEMPLATE); scoreLine[1].append(IConstants.SCORE_TABLE_TEMPLATE); return scoreLine; }
2
public String toPrettyString() { PaddingStringBuilder output = new PaddingStringBuilder(); // Settings section PaddingStringBuilder.PaddingSection settingsSection = new PaddingStringBuilder.PaddingSection(true); output .append(" | ").append(settingsSection, "Score limit: ").append(scoreLimit) .append("\n | ").append(settingsSection, "Population size: ").append(populationSize) .append("\n | ").append(settingsSection, "Generation limit: ").append(generationLimit) .append("\n | ").append(settingsSection, "Execution timeout: ").append(String.format("%,d", executionTimeout)).append(" (ms)") .append("\n | ").append(settingsSection, "Status interval: ").append(String.format("%,d", statusInterval)).append(" (ms)") .append("\n | ").append(settingsSection, "Random seed: ").append(randomSeed) .append("\n | ").append(settingsSection, "Project main class: ").append(projectMain) .append("\n | ").append(settingsSection, "Project problem class: ").append(problemClassName); // Breeding operators section DecimalFormat oneDotTwoFormat = new DecimalFormat("0.00"); Double totalWeight = 0D; for (BreedingOperatorSetup opSetup : breedingOperators) { totalWeight += opSetup.weight; } output.append("\n | Breeding operators:"); PaddingStringBuilder.PaddingSection breedOpWeights = new PaddingStringBuilder.PaddingSection(false); PaddingStringBuilder.PaddingSection breedOpPercent = new PaddingStringBuilder.PaddingSection(false); for (BreedingOperatorSetup opSetup : breedingOperators) { output.append("\n | | ").append(breedOpWeights, oneDotTwoFormat.format(opSetup.weight)).append(" -> ").append(breedOpPercent, Math.round(opSetup.weight / totalWeight * 100)).append("%: ").append(opSetup.breedingOperator); } // Breeding classes output.append("\n | Approved breeding classes:"); StringBuilder classesWith = new StringBuilder(); StringBuilder classesWithout = new StringBuilder(); for (BreedingClassSetup classSetup : breedingClasses) { if (classSetup.instantiable) { classesWith.append("\n | | | ").append(classSetup.className); } else { classesWithout.append("\n | | | ").append(classSetup.className); } } if (classesWith.length() > 0) { output.append("\n | | With instantiation:").append(classesWith); } if (classesWithout.length() > 0) { output.append("\n | | Without instantiation:").append(classesWithout); } return output.toString(); }
6
public boolean isEmptySpace () { int i = 0, j = 0; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { if (entries[i][j].getText().equals("")) { System.out.println("isEmptySpace() returned false at i: " + i + " j: "+j); return false; } } } return true; }
3
String factorStr() { if (factor > 1000000000) return factor / 1000000000 + "Gb"; if (factor > 1000000) return factor / 1000000 + "Mb"; if (factor > 1000) return factor / 1000 + "Kb"; return factor + "b"; }
3
public static void main(String args[]) throws IOException, InterruptedException { /* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> int opc=0; BufferedReader leer=new BufferedReader(new InputStreamReader(System.in)); do{ Menu.Principal(); try{ opc=Integer.parseInt(leer.readLine()); }catch(NumberFormatException ex) {ex.getMessage();} switch(opc){ case 1: java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new Login().LoginDialog.setVisible(true); } }); return; case 2: Farmacia.VentaMain(); break; case 3: System.err.println("- - Saliendo del programa - -"); Sleep.s2(); System.exit(0); default: System.err.println("No ha ingresado una opcion correcta!!"); break; } }while(opc!=3); }
8
public Comparable<?> getValue(ResultSet rs) throws Exception { if("int".equals(dataType)) { return rs.getInt(columnName); } if("bigint".equals(dataType)) { return rs.getLong(columnName); } if("nchar".equals(dataType)) { return rs.getString(columnName); } if("varchar".equals(dataType)) { return rs.getString(columnName); } if("uniqueidentifier".equals(dataType)) { byte[] bytes = rs.getBytes(columnName); UUID uuid = UuidUtil.byteArrayToUuid(bytes); return uuid; } if("date".equals(dataType)) { return rs.getDate(columnName); } throw new RuntimeException("Type not recognized: " + dataType); }
7
public Move move(boolean[] foodpresent, int[] neighbors, int foodleft, int energyleft) throws Exception { Move m = null; // placeholder for return value // this player selects randomly int direction = rand.nextInt(6); switch (direction) { case 0: m = new Move(STAYPUT); break; case 1: m = new Move(WEST); break; case 2: m = new Move(EAST); break; case 3: m = new Move(NORTH); break; case 4: m = new Move(SOUTH); break; case 5: direction = rand.nextInt(4); // if this organism will reproduce: // the second argument to the constructor is the direction to which the offspring should be born // the third argument is the initial value for that organism's state variable (passed to its register function) if (direction == 0) m = new Move(REPRODUCE, WEST, state); else if (direction == 1) m = new Move(REPRODUCE, EAST, state); else if (direction == 2) m = new Move(REPRODUCE, NORTH, state); else m = new Move(REPRODUCE, SOUTH, state); } return m; }
9
protected InputStream getConnectionInputStream(final URLConnection urlconnection) throws DownloadException { final AtomicReference<InputStream> is = new AtomicReference<InputStream>(); for (int j = 0; (j < 3) && (is.get() == null); j++) { StreamThread stream = new StreamThread(urlconnection, is); stream.start(); int iterationCount = 0; while ((is.get() == null) && (iterationCount++ < 5)) { try { stream.join(1000L); } catch (InterruptedException ignore) { } } if (stream.permDenied.get()) { throw new PermissionDeniedException("Permission denied!"); } if (is.get() != null) { break; } try { stream.interrupt(); stream.join(); } catch (InterruptedException ignore) { } } if (is.get() == null) { throw new DownloadException("Unable to download file from " + urlconnection.getURL()); } return new BufferedInputStream(is.get()); }
9
@Override public void attributesVisibilityChanged(OutlinerDocumentEvent e) {}
0
@SuppressWarnings ("unchecked" ) @Override public boolean retainAll( Collection<?> collection ) { final int previousSize = trie.size(); final Trie<E, Object> newTrie = trie.newEmptyClone(); for (Object element : collection) { if (trie.containsKey( element )) { newTrie.put( (E)element, FLAG ); } } trie = newTrie; return previousSize != trie.size(); }
3
protected boolean test5 () { return true; }
0
public static void copyFile(String src, String dest, boolean keepDate) throws UtilException { try { FileUtils.copyFile(new File(src), new File(dest), keepDate); } catch (IOException e) { throw new UtilException("拷贝文件失败", e); } }
1
public static final void SpawnPet(final SeekableLittleEndianAccessor slea, final MapleClient c, final MapleCharacter chr) { slea.skip(4); final byte slot = slea.readByte(); final IItem item = chr.getInventory(MapleInventoryType.CASH).getItem(slot); switch (item.getItemId()) { case 5000047: case 5000028: { final MaplePet pet = MaplePet.createPet(item.getItemId() + 1); if (pet != null) { MapleInventoryManipulator.addById(c, item.getItemId() + 1, (short) 1, null, pet); MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.CASH, slot, (short) 1, false); } break; } default: { final MaplePet pet = item.getPet(); if (pet != null) { if (pet.getSummoned()) { // Already summoned, let's keep it chr.unequipPet(pet, true, false); } else { if (chr.getSkillLevel(SkillFactory.getSkill(8)) == 0 && chr.getPet(0) != null) { chr.unequipPet(chr.getPet(0), false, false); } if (slea.readByte() == 1) { // Follow the Lead // c.getPlayer().shiftPetsRight(); } final Point pos = chr.getPosition(); pet.setPos(pos); pet.setFh(chr.getMap().getFootholds().findBelow(pet.getPos()).getId()); pet.setStance(0); pet.setSummoned(true); chr.addPet(pet); chr.getMap().broadcastMessage(chr, PetPacket.showPet(chr, pet, false, false), true); final List<Pair<MapleStat, Integer>> stats = new ArrayList<Pair<MapleStat, Integer>>(1); stats.add(new Pair<MapleStat, Integer>(MapleStat.PET, Integer.valueOf(pet.getUniqueId()))); c.getSession().write(PetPacket.petStatUpdate(chr)); chr.startFullnessSchedule(PetDataFactory.getHunger(pet.getPetItemId()), pet, chr.getPetIndex(pet)); } } break; } } c.getSession().write(PetPacket.emptyStatUpdate()); }
8
private int find_index( int index, int target ){ // divide weight into three groups: Self, Son & Daughter, and test each // Testing self int sum = tree.elementAt(index).chance_weight; if( target < sum ) { return index; // found within self } // else outside self, must be in children // Testing son (first-born is always a son) sum += tree.elementAt( 2*index+1 ).family_weight; if( target < sum ) { return find_index( 2*index+1, target - tree.elementAt(index).chance_weight ); } // else not in son's range // Testing daughter sum += tree.elementAt( 2*(index+1) ).family_weight; if( target < sum ) { return find_index( 2*(index+1), target - tree.elementAt(index).chance_weight - tree.elementAt( 2*index+1 ).family_weight ); } // possible to reach here if a custom random number generator is used, // and it fails to deliver a number in the correct range return 0; };
3
void processUnixWay(String argChars, String[] args, boolean shouldFail) { GetOpt getopt = new GetOpt(argChars); int errs = 0; char c; while ((c = getopt.getopt(args)) != 0) { if (c == '?') { ++errs; } else { Debug.println("getopt", "Found " + c); //if (getopt.optarg() != null) // System.out.print("; Option " + getopt.optarg()); } } // Process any filename-like arguments. assertTrue(args.length >= getopt.getOptInd()); for (int i = getopt.getOptInd(); i<args.length; i++) { Debug.printf("getopt", "%d %s%n", i, args[i]); String fileName = args[i]; assertFalse(fileName.startsWith("-")); } if (errs > 0 && !shouldFail) { fail("Errors in this run"); } }
5
private void findCaptureArea(int x, int y, int owner) { if(!isOnMap(x, y)) { return; } if(map[x][y].owner == owner) { return; } boolean mask[][] = new boolean[getXSize()][getYSize()]; for(int i = 0; i < getXSize(); i++) { for(int j = 0; j < getYSize(); j++) { mask[i][j] = false; } } if(!processDot_r(x, y, owner, mask)) { return; } for(int i = 0; i < getXSize(); i++) { for(int j = 0; j < getYSize(); j++) { if(mask[i][j]) { map[i][j].invade(owner); if(map[i][j].owner == ServerGameMapCell.WITHOUT_OWNER_OPT) { freePoint--; } } } } countScores(); }
9
@Test(expected = RuntimeException.class) public void itShouldFailOnAddInteriorRingWithoutExteriorRing() throws Exception { Polygon polygon = new Polygon(); polygon.addInteriorRing(MockData.EXTERNAL); }
0
public int cdlMorningDojiStarLookback( double optInPenetration ) { if( optInPenetration == (-4e+37) ) optInPenetration = 3.000000e-1; else if( (optInPenetration < 0.000000e+0) || (optInPenetration > 3.000000e+37) ) return -1; return ((( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) > ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) ? ( ((( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) > ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ? ( (this.candleSettings[CandleSettingType.BodyDoji.ordinal()].avgPeriod) ) : ( (this.candleSettings[CandleSettingType.BodyLong.ordinal()].avgPeriod) )) ) : ( (this.candleSettings[CandleSettingType.BodyShort.ordinal()].avgPeriod) )) + 2; }
6
@Override public SQLResult executeSqlQuery(String query) throws Exception { Session session = null; Transaction trx = null; SQLResult result = new SQLResult(); try { session = sessionFactory.openSession(); trx = session.beginTransaction(); PreparedStatement statement = session.connection().prepareStatement(query); ResultSet rs = statement.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); //create header String[] header = new String[rsmd.getColumnCount()]; for(int i=1; i<=rsmd.getColumnCount(); i++) { header[i-1] = (rsmd.getColumnName(i)); } result.setHeader(header); //create body List<String[]> body = new ArrayList<String[]>(); while(rs.next()) { String[] values = new String[rsmd.getColumnCount()]; for(int i=1; i<=rsmd.getColumnCount(); i++) { values[i-1] = rs.getString(i); } body.add(values); } result.setBody(body); } catch(HibernateException e) { if(trx != null) { try {trx.rollback(); } catch(HibernateException he) {} } } finally { try { if( session != null ) session.close(); } catch( Exception exC1 ) {} } return result; }
8
private static TreeMap<String, Tuple<BufferedImage, Integer>> loadTilesetFile(String tilesetFilename) { try { Scanner reader = new Scanner(new FileReader("Resources/Tilesets/" + tilesetFilename)); TreeMap<String, Tuple<BufferedImage, Integer>> tileMap = new TreeMap<String, Tuple<BufferedImage, Integer>>(); while(reader.hasNext()) { String id = reader.next(); String tileFilename = reader.next(); int passability = reader.nextInt(); // 1 means obstacle try { tileMap.put(id, new Tuple(ImageIO.read(new File("Resources/Tiles/" + tileFilename)), passability)); } catch (IOException e) { System.out.println("MapLoader: file <" + tileFilename + "> was not found in the folder <Tiles>"); e.printStackTrace(); } } return tileMap; } catch (FileNotFoundException e) { System.out.println("MapLoader: file <" + tilesetFilename + "> was not found in the folder <Tilesets>"); } return null; }
3
static final void method2554(byte i) { if (i != -45) anInt4032 = 61; anInt4030++; if (Class312.anInt3931 == 1 || Class312.anInt3931 == 3 || (Class312.anInt3931 != Class83.anInt1447 && ((Class312.anInt3931 ^ 0xffffffff) == -1 || Class83.anInt1447 == 0))) { Class348_Sub32.anInt6930 = 0; Class150.anInt2057 = 0; Class282.aClass356_3654.removeAll(0); } Class83.anInt1447 = Class312.anInt3931; }
6
public ChannelLPC(BitInputStream is, Header header, ChannelData channelData, int bps, int wastedBits, int order) throws IOException { super(header, wastedBits); this.order = order; // read warm-up samples //System.out.println("Order="+order); for (int u = 0; u < order; u++) { warmup[u] = is.readRawInt(bps); } //for (int i = 0; i < order; i++) System.out.println("Warm "+i+" "+warmup[i]); // read qlp coeff precision int u32 = is.readRawUInt(SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN); if (u32 == (1 << SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) { throw new IOException("STREAM_DECODER_ERROR_STATUS_LOST_SYNC"); } qlpCoeffPrecision = u32 + 1; //System.out.println("qlpCoeffPrecision="+qlpCoeffPrecision); // read qlp shift quantizationLevel = is.readRawInt(SUBFRAME_LPC_QLP_SHIFT_LEN); //System.out.println("quantizationLevel="+quantizationLevel); // read quantized lp coefficiencts for (int u = 0; u < order; u++) { qlpCoeff[u] = is.readRawInt(qlpCoeffPrecision); } // read entropy coding method info int codingType = is.readRawUInt(ENTROPY_CODING_METHOD_TYPE_LEN); //System.out.println("codingType="+codingType); switch (codingType) { case ENTROPY_CODING_METHOD_PARTITIONED_RICE2 : case ENTROPY_CODING_METHOD_PARTITIONED_RICE : entropyCodingMethod = new EntropyPartitionedRice(); ((EntropyPartitionedRice) entropyCodingMethod).order = is.readRawUInt(ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN); ((EntropyPartitionedRice) entropyCodingMethod).contents = channelData.getPartitionedRiceContents(); break; default : throw new IOException("STREAM_DECODER_UNPARSEABLE_STREAM"); } // read residual if (entropyCodingMethod instanceof EntropyPartitionedRice) { ((EntropyPartitionedRice) entropyCodingMethod).readResidual(is, order, ((EntropyPartitionedRice) entropyCodingMethod).order, header, channelData.getResidual(), (codingType == ENTROPY_CODING_METHOD_PARTITIONED_RICE2)); } //System.out.println(); //for (int i = 0; i < header.blockSize; i++) {System.out.print(channelData.residual[i]+" "); //if (i%200==0)System.out.println(); //} //System.out.println(); // decode the subframe System.arraycopy(warmup, 0, channelData.getOutput(), 0, order); if (bps + qlpCoeffPrecision + BitMath.ilog2(order) <= 32) { if (bps <= 16 && qlpCoeffPrecision <= 16) LPCPredictor.restoreSignal(channelData.getResidual(), header.blockSize - order, qlpCoeff, order, quantizationLevel, channelData.getOutput(), order); else LPCPredictor.restoreSignal(channelData.getResidual(), header.blockSize - order, qlpCoeff, order, quantizationLevel, channelData.getOutput(), order); } else { LPCPredictor.restoreSignalWide(channelData.getResidual(), header.blockSize - order, qlpCoeff, order, quantizationLevel, channelData.getOutput(), order); } }
9
private int[] exploreNextMove() { for (int col = 0; col < 7; col++) { if (board.validateStep(col)) { int row = board.availableSpace(col); if (board.checkConnectFour(player1, row, col) || board.checkConnectFour(player2, row, col)) { return new int[] { row, col }; } } } return new int[] { -1, -1 }; }
4
private String getDecodedParameterKey() throws IOException { String[] splitOnMark = requestArray[1].split("\\?"); try { String parameters = splitOnMark[1]; String paramsWithSpace = parameters.replaceAll("=", " = "); String paramsWithAmpSpace = paramsWithSpace.replaceAll("&", " "); return URLDecoder.decode(paramsWithAmpSpace, "UTF-8"); } catch (ArrayIndexOutOfBoundsException e) { return "No Parameter Key Exists"; } }
1
public void insertUser() { PreparedStatement st = null; String q = "INSERT INTO users SET email= ?, password = MD5(?), first_name = ?, last_name = ?"; try { conn = dbconn.getConnection(); conn.setAutoCommit(false); st = conn.prepareStatement(q); st.setString(1, this.email); st.setString(2, this.password); st.setString(3, this.firstName); st.setString(4, this.lastName); st.executeUpdate(); insertUserRoles(this.email, this.role, conn); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException o) { o.printStackTrace(); } } finally { try { conn.close(); st.close(); } catch (SQLException e) { System.out.println("Unable to close connection"); } } }
3
@Override public void onAudioSamples(IAudioSamplesEvent event) { if (sectionIterator < randomSections.size()) { VideoSection currentSection = randomSections.get(sectionIterator); Long timeStamp = event.getTimeStamp(currentSection.getTimeUnit()); if (currentSection.getStart() < timeStamp) { if (currentSection.getEnd() < timeStamp) { sectionIterator++; } } else { adjustVolume(event); } } else { adjustVolume(event); } super.onAudioSamples(event); }
3
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) { selector.wakeup(); try { if( removeConnection( conn ) ) { onClose( conn, code, reason, remote ); } } finally { try { releaseBuffers( conn ); } catch ( InterruptedException e ) { Thread.currentThread().interrupt(); } } }
2
public void restoreItem(T item) { for (TimeOutListItem<T> listItem : this.list) { if (listItem.equals(item)) { listItem.restore(); this.list.remove(listItem); break; } } }
2
public RegisterWidget() { this.setTitle("Register a UniChat Account"); this.setWidth("50%"); this.setHeight("50%"); this.setShowMinimizeButton(false); this.setIsModal(true); this.setShowModalMask(true); this.centerInPage(); this.setAlign(Alignment.CENTER); layout = new HLayout(); layout.setShowEdges(true); layout.setMargin(10); layout.setWidth100(); layout.setHeight100(); layout.setLayoutAlign(Alignment.CENTER); // Form form = new DynamicForm(); //form.setShowEdges(true); //form.setWidth("50%"); form.setAlign(Alignment.CENTER); form.setLayoutAlign(Alignment.CENTER); form.setTitleOrientation(TitleOrientation.LEFT); form.setErrorOrientation(FormErrorOrientation.RIGHT); form.setMargin(5); // First Name input firstNameInput = new TextItem(); firstNameInput.setTitle("First Name"); firstNameInput.setRequired(true); firstNameInput.addKeyPressHandler(new KeyPressHandler(){ @Override public void onKeyPress(com.smartgwt.client.widgets.form.fields.events.KeyPressEvent event) { if(event.getKeyName().equals(KeyNames.ENTER)) doSubmit(); } }); // Last Name input lastNameInput = new TextItem(); lastNameInput.setTitle("Last Name"); lastNameInput.setRequired(true); lastNameInput.addKeyPressHandler(new KeyPressHandler(){ @Override public void onKeyPress(com.smartgwt.client.widgets.form.fields.events.KeyPressEvent event) { if(event.getKeyName().equals(KeyNames.ENTER)) doSubmit(); } }); // E-Mail input emailInput = new TextItem(); emailInput.setTitle("E-Mail"); emailInput.setRequired(true); RegExpValidator emailValidator = new RegExpValidator(); emailValidator.setErrorMessage("Invalid email address"); emailValidator.setExpression("^([a-zA-Z0-9_.\\-+])+@(([a-zA-Z0-9\\-])+\\.)+[a-zA-Z0-9]{2,4}$"); emailInput.setValidators(emailValidator); emailInput.addKeyPressHandler(new KeyPressHandler(){ @Override public void onKeyPress(com.smartgwt.client.widgets.form.fields.events.KeyPressEvent event) { if(event.getKeyName().equals(KeyNames.ENTER)) doSubmit(); } }); // Password input passwordInput = new PasswordItem(); passwordInput.setTitle("Password"); passwordInput.setName("Password"); passwordInput.setRequired(true); passwordInput.addKeyPressHandler(new KeyPressHandler(){ @Override public void onKeyPress(com.smartgwt.client.widgets.form.fields.events.KeyPressEvent event) { if(event.getKeyName().equals(KeyNames.ENTER)) doSubmit(); } }); // Password input #2 passwordVerify = new PasswordItem(); passwordVerify.setTitle("Verify Password"); passwordVerify.setRequired(true); passwordVerify.setType("password"); passwordVerify.addKeyPressHandler(new KeyPressHandler(){ @Override public void onKeyPress(com.smartgwt.client.widgets.form.fields.events.KeyPressEvent event) { if(event.getKeyName().equals(KeyNames.ENTER)) doSubmit(); } }); // Password validators // Passwords match MatchesFieldValidator matchValidator = new MatchesFieldValidator(); matchValidator.setOtherField("Password"); matchValidator.setErrorMessage("Passwords do not match"); // Passwords of minimum length LengthRangeValidator lengthValidator = new LengthRangeValidator(); lengthValidator.setMin(6); lengthValidator.setMax(20); lengthValidator.setErrorMessage("Password must be between 6 and 20 characters long"); passwordInput.setValidators(lengthValidator); passwordVerify.setValidators(matchValidator, lengthValidator); // Buttons // Register Button registerButton = new ButtonItem("Register"); //registerButton.setWidth("100%"); registerButton.setEndRow(false); registerButton.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { doSubmit(); } }); // Cancel Button cancelButton = new ButtonItem("Cancel"); //cancelButton.setWidth("100%"); final Window thisWidget = this; cancelButton.setStartRow(false); cancelButton.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { thisWidget.destroy(); } }); form.setFields(new FormItem[] {firstNameInput, lastNameInput, emailInput, passwordInput, passwordVerify, registerButton, cancelButton}); layout.addMember(form); this.addItem(layout); }
5
private void stopServer_adbMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopServer_adbMenuActionPerformed try { adbController.stopServer(); } catch (IOException ex) { logger.log(Level.ERROR, "An error occurred while stopping the ADB server!"); ex.printStackTrace(System.err); } }//GEN-LAST:event_stopServer_adbMenuActionPerformed
1
public static Ball probe(Ball ball, int boxSize, int shiftIncrement, Rectangle2D.Double acceptQuadrant){ Cardinal direction = Cardinal.NORTH; Ball probe = new Ball(new Point2D.Double(ball.getCenterPoint().getX(), ball.getCenterPoint().getY()), ball.getVelocity(), ball.getSpeed(), MyColor.BLACK); //displace the invalid ball outside the game field so the probe can find a closer valid position ball.setCenterX(-Ball.RADIUS); ball.setCenterY(-Ball.RADIUS); for(int i = 1; i <= boxSize; i++){ for(int j = 0; j < 2; j++){ for(int k = 0; k < i; k++){ switch(direction){ case WEST: probe.move(-shiftIncrement, 0); break; case NORTH: probe.move(0, -shiftIncrement); break; case EAST: probe.move(shiftIncrement, 0); break; case SOUTH: probe.move(0, shiftIncrement); break; } } boolean b1 = acceptQuadrant.contains(probe.getCenterPoint().getX(), probe.getCenterPoint().getY()); boolean b2 = probe.isPositionValid(); if(b1 && b2){ return probe; } direction = direction.nextClockwise(); } } return null; }
9
public int RowCount() { try { ResultSet Result = Statement.executeQuery(ClassQuery); return (Result.last() ? Result.getRow() : 0); } catch(SQLException E) { Grizzly.WriteOut(E.getMessage()); return 0; } }
2
public static void setGamemode(Player player, String playerName, String gamemodePlayerName, String gamemode) { ArrayList<Player> gamemodePlayers = AdminEyeUtils .requestPlayers(gamemodePlayerName); if (gamemodePlayers == null && gamemodePlayerName != null) { StefsAPI.MessageHandler.buildMessage().addSender(playerName) .setMessage("error.playerNotFound", AdminEye.messages) .changeVariable("playername", gamemodePlayerName).build(); return; } if (!AdminEyeUtils.isGamemode(gamemode)) { StefsAPI.MessageHandler.buildMessage().addSender(playerName) .setMessage("error.notAGamemode", AdminEye.messages) .changeVariable("gamemode", gamemode).build(); return; } String gamemodedPlayers = ""; for (Player gamemodePlayer : gamemodePlayers) { gamemodePlayer.setGameMode(AdminEyeUtils.getGameMode(gamemode)); if (AdminEyeUtils.getGameMode(gamemode) == GameMode.CREATIVE) { PlayerFile playerFile = new PlayerFile(gamemodePlayer.getName()); playerFile.flyFlying = false; playerFile.save(); } gamemodedPlayers += "%A" + gamemodePlayer.getName() + "%N, "; } gamemodedPlayers = (gamemodePlayerName.equals("*") ? gamemodedPlayers = AdminEye.config .getFile().getString("chat.everyone") + "%N, " : gamemodedPlayers); AdminEye.broadcastAdminEyeMessage(playerName, "setgamemode", "gamemode", "playernames", gamemodedPlayers, "gamemode", AdminEyeUtils.getGameMode(gamemode).name().toLowerCase()); }
6
public Value unaryOperation(final AbstractInsnNode insn, final Value value) { int size; switch (insn.getOpcode()) { case LNEG: case DNEG: case I2L: case I2D: case L2D: case F2L: case F2D: case D2L: size = 2; break; case GETFIELD: size = Type.getType(((FieldInsnNode) insn).desc).getSize(); break; default: size = 1; } return new SourceValue(size, insn); }
9
public OSCPortIn(int port) throws SocketException { super(new DatagramSocket(port), port); }
0
public static FastStringBuffer decimalToString(BigDecimal value, FastStringBuffer fsb) { // Can't use the plain BigDecimal#toString() under JDK 1.5 because this produces values like "1E-5". // JDK 1.5 offers BigDecimal#toPlainString() which might do the job directly int scale = value.scale(); if (scale == 0) { fsb.append(value.toString()); return fsb; } else if (scale < 0) { String s = value.abs().unscaledValue().toString(); if (s.equals("0")) { fsb.append('0'); return fsb; } //FastStringBuffer sb = new FastStringBuffer(s.length() + (-scale) + 2); if (value.signum() < 0) { fsb.append('-'); } fsb.append(s); for (int i=0; i<(-scale); i++) { fsb.append('0'); } return fsb; } else { String s = value.abs().unscaledValue().toString(); if (s.equals("0")) { fsb.append('0'); return fsb; } int len = s.length(); //FastStringBuffer sb = new FastStringBuffer(len+1); if (value.signum() < 0) { fsb.append('-'); } if (scale >= len) { fsb.append("0."); for (int i=len; i<scale; i++) { fsb.append('0'); } fsb.append(s); } else { fsb.append(s.substring(0, len-scale)); fsb.append('.'); fsb.append(s.substring(len-scale)); } return fsb; } }
9
public void initTable(ITable subtable) { _table = subtable; updateTable(); }
0
IMySQLConnection getConnection() throws SQLException { System.out.println("Connections: " + conns.size()); ++cullTicker; if(cullTicker > CULL_SCHEDULE) { cullTicker = 0; cullConnections(); } for (IMySQLConnection conn : conns) { if(conn.isAvailable()) { return conn; } } return addNewConnection(); }
3
@Override public boolean shadow_hit(Ray ray, FloatRef tmin) { float ox = ray.getOrigin().getX(); float oy = ray.getOrigin().getY(); float oz = ray.getOrigin().getZ(); float dx = ray.getDirection().getX(); float dy = ray.getDirection().getY(); float dz = ray.getDirection().getZ(); float a = dx * dx + dz * dz; float b = 2.0f * (ox * dx + oz * dz); float c = ox * ox + oz * oz - radius * radius; float disc = b * b - 4.0f * a * c; if (disc < 0.0) return false; float e = (float) sqrt(disc); float denom = 2.0f * a; float t = (-b - e) / denom; // smaller root if (t > K_EPSILON) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin.value = t; return true; } } t = (-b + e) / denom; // bigger root if (t > K_EPSILON) { double yhit = oy + t * dy; if (yhit > y0 && yhit < y1) { tmin.value = t; return true; } } return false; }
7
private Color setclr(int i){ if(i == 0){ return Color.BLUE; } else if(i == 1){ return Color.RED; } else if(i == 2){ return Color.GREEN; } else if(i == 3){ return Color.ORANGE; } else if(i == 4){ return Color.YELLOW; } else if(i == 5){ return Color.PINK; } else{ return Color.BLACK; } }
6
@EventHandler(priority = EventPriority.NORMAL) public void onBlockPlace(BlockPlaceEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); Block block = event.getBlock(); if (plugin.isLifestone(block) == true) { if (!(player.hasPermission("lifestones.breaklifestone"))) { plugin.sendMessage(player, GRAY + L("cannotModifyLifestone")); event.setCancelled(true); return; } } else if (plugin.isProtected(block) == true) { if (!(player.hasPermission("lifestones.modifyprotectedblocks"))) { plugin.sendMessage(player, GRAY + L("blockProtectedByLifestone")); event.setCancelled(true); return; } } }
5
public void run() { try { voyageHandler voyhandlr = new voyageHandler(); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); hc = (HttpConnection) Connector.open("http://localhost:8080/smartPhp/getXmlAnnonce.php?id="+selectedAnn); dis = new DataInputStream(hc.openDataInputStream()); parser.parse(dis, voyhandlr); annonces = voyhandlr.getVoyages(); if (annonces.length > 0) { for (int i = 0; i < annonces.length; i++) { annonce = annonces[i]; } } source = Image.createImage("/smartravelmobile/media/logo.jpg"); } catch (Exception ex) { ex.printStackTrace(); } disp.setCurrent(new Midletdetail.Draw()); }
3
public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); }
4
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){ try { Object o1 = session.getAttribute("UserID"); Object o2 = session.getAttribute("UserRights"); boolean bRedirect = false; if ( o1 == null || o2 == null ) { bRedirect = true; } if ( ! bRedirect ) { if ( (o1.toString()).equals("")) { bRedirect = true; } else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; } } if ( bRedirect ) { response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI())); return "sendRedirect"; } } catch(Exception e){}; return ""; }
7
private int computeHeight(TPoint[] points) { int maxY = points[0].y; int minY = points[0].y; for (int i = 1; i < points.length; i++) { TPoint currentPoint = points[i]; if (currentPoint.y > maxY) maxY = currentPoint.y; if (currentPoint.y < minY) minY = currentPoint.y; } // + 1 is to account for differences in coordinates and actual width int width = maxY - minY + 1; return width; }
3
public int getGroundDecorationUid(int z, int x, int y) { GroundTile groundTile = groundTiles[z][x][y]; if (groundTile == null || groundTile.groundDecoration == null) { return 0; } else { return groundTile.groundDecoration.uid; } }
2
public DocumentEvent(Document doc) { setDocument(doc); }
0
public Shape getShape(String shapeName) { // Java 8 can use Strings in switch. switch (shapeName) { case "CIRCLE": return new Circle(); case "RECTANGLE": return new Rectangle(); case "SQUARE": return new Square(); default: return null; } }
3
public static String GetAuthToken(String username, String password) { try { CookieManager m = new CookieManager(); CookieHandler.setDefault(m); URL u3 = new URL("http://www.havenandhearth.com/portal/login"); HttpURLConnection connection3 = (HttpURLConnection) u3 .openConnection(); connection3.setDoOutput(true); connection3.connect(); // read the result from the server BufferedReader rd3 = new BufferedReader(new InputStreamReader( connection3.getInputStream())); StringBuilder sb3 = new StringBuilder(); String line3; while ((line3 = rd3.readLine()) != null) { sb3.append(line3 + '\n'); } String data2 = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data2 += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); String data = "http://www.havenandhearth.com/portal/sec/login?r=/portal/"; URL u1 = new URL(data); HttpURLConnection connection = (HttpURLConnection) u1 .openConnection(); connection.setDoOutput(true); connection.connect(); OutputStreamWriter wr = new OutputStreamWriter( connection.getOutputStream()); wr.write(data2); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader( connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line + '\n'); } URL u2 = new URL("http://www.havenandhearth.com/portal/autohaven"); HttpURLConnection connection2 = (HttpURLConnection) u2 .openConnection(); connection2.setDoOutput(true); connection2.connect(); BufferedReader rd2 = new BufferedReader(new InputStreamReader( connection2.getInputStream())); StringBuilder sb2 = new StringBuilder(); String line2; while ((line2 = rd2.readLine()) != null) { sb2.append(line2 + '\n'); } String jnlp = sb2.toString(); Pattern p = Pattern .compile("<property name=\"haven.authck\" value=\"(.+)\" />"); Matcher ma = p.matcher(jnlp); String token = null; if (ma.find()) { token = ma.group(1); } return token; } catch (Exception e) { return null; } }
5
private static void loadRankURIs(URL[] URLs, String urlBase) { for (int i = 0; i < 13; i++) { URLs[i] = ImageManager.class.getResource(urlBase + i + ".svg"); } }
1
public static int d_mht(final int n) { return (int) Math.ceil(log(log(n,2)+1,2)); }
0
public static String getText(Categories category) { switch (category) { case SHOES: return "Ботинки"; case SHIRTS: return "Футболки"; case CAPS: return "Головные уборы"; case PANTS: return "Штаны"; } return ""; }
4
private void addNode(Position pos, GameNode node) { if(pos.x<mapSize) throw new RuntimeException("X выходит за границы игровой карты"); if(pos.y<mapSize) throw new RuntimeException("Y выходит за границы игровой карты"); node.setPosition(pos); ArrayList<GameNode> col = mainMap.get(pos.x); if(col == null) { col = new ArrayList<GameNode>(mapSize); mainMap.add(pos.x,col); } col.add(pos.y,node); }
3
private void addVessel(Map<String, EnumElement> board, EnumLine line, EnumColumn column, boolean vertical, EnumElement vessel) throws InvalidPositionException { if (this.validatePosition(line, column, vertical, vessel)) { if (this.notOverrideVessel(board, line, column, vertical, vessel)) { final int initLinePosition = line.getPosition(); final int initColumnPosition = column.getPosition(); for (int i = 1; i < (vessel.getLength() + 1); i++) { if (vertical) { board.put(this.createPosition(line, column), vessel); line = EnumLine.getEnumLine(initLinePosition + i); } else { board.put(this.createPosition(line, column), vessel); column = EnumColumn.getEnumColumn(initColumnPosition + i); } } } else { throw new InvalidPositionException(); } } else { throw new InvalidPositionException(); } }
4
private int alpha_beta(BoardNode root,int a, int b, int d) { int i,var; BoardNode tmp; if(d==0){/*if reach the max depth, return the static value */ var = this.evaluator.Evaluate(root, this.myClr); return var; } if (root.isMAX){/*for max node*/ for(i=0;i<7;i++) { if((tmp=root.NewNode(i))==null)/*if this column is full, try the next node*/ continue; var = alpha_beta(tmp,a, b, d-1); if(var>=a) { a = var; } if (a>=b) return b; } return a; }else /*for min node*/ { for(i=0;i<7;i++) { if((tmp=root.NewNode(i))==null)/*if this column is full, try the next node*/ continue; b = min(b,alpha_beta(root.NewNode(i),a, b, d-1)); if (b<=a) return a; } return b; } }
9
static void Pixel(osd_bitmap bitmap, int x, int y, int spr_number, int color) { int xr, yr, spr_y1, spr_y2; int SprOnScreen; if (x < Machine.drv.visible_area.min_x || x > Machine.drv.visible_area.max_x || y < Machine.drv.visible_area.min_y || y > Machine.drv.visible_area.max_y) { return; } if (SpritesCollisionTable[256 * y + x] == 255) { SpritesCollisionTable[256 * y + x] = (char) spr_number; plot_pixel.handler(bitmap, x, y, color); } else { SprOnScreen = SpritesCollisionTable[256 * y + x]; system1_sprites_collisionram.write(SprOnScreen + 32 * spr_number, 0xff); if (system1_pixel_mode == system1_SPRITE_PIXEL_MODE1) { spr_y1 = GetSpriteBottomY.handler(spr_number); spr_y2 = GetSpriteBottomY.handler(SprOnScreen); if (spr_y1 >= spr_y2) { plot_pixel.handler(bitmap, x, y, color); SpritesCollisionTable[256 * y + x] = (char) spr_number; } } else { plot_pixel.handler(bitmap, x, y, color); SpritesCollisionTable[256 * y + x] = (char) spr_number; } } xr = ((x - background_scrollx) & 0xff) / 8; yr = ((y - background_scrolly) & 0xff) / 8; /* TODO: bits 5 and 6 of backgroundram are also used (e.g. Pitfall2, Mr. Viking) */ /* what's the difference? Bit 7 is used in Choplifter/WBML for extra char bank */ /* selection, but it is also set in Pitfall2 */ if (system1_background_memory == system1_BACKGROUND_MEMORY_SINGLE) { if ((system1_backgroundram.read(2 * (32 * yr + xr) + 1) & 0x10) != 0) { system1_background_collisionram.write(0x20 + spr_number, 0xff); } } else { /* TODO: I should handle the paged background memory here. */ /* maybe collision detection is not used by the paged games */ /* (wbml and tokisens), though tokisens doesn't play very well */ /* (you can't seem to fit in gaps where you should fit) */ } /* TODO: collision should probably be checked with the foreground as well */ /* (TeddyBoy Blues, head of the tiger in girl bonus round) */ }
9
private String Complement(String binaryString) { StringBuilder complementBuilder = new StringBuilder(binaryString); for(int i = 0; i < binaryString.length(); ++i) { char flip = binaryString.charAt(i) == '0' ? '1' : '0'; complementBuilder.setCharAt(i, flip); } return complementBuilder.toString(); }
2
public boolean removeModerator(String subForumId, User invoker, User moderator) { if (!invoker.hasPermission(Permissions.REMOVE_MODERATOR)) return false; getSubForumById(subForumId).removeModerator(moderator); save(); return true; }
1
private void AIteleport() { if (ball.getX() < 100 && ball.getVx() > 0) { if (tempBallReturned + 1 == player1.getBallReturned() && tempBallReturned != 0) { if (player2.useTeleport()) { createTeleport(); tempBallReturned = 0; } } } else { tempBallReturned = player1.getBallReturned(); } }
5
public PersonHistory(Person P) { setIconImage(Toolkit.getDefaultToolkit().getImage(PersonHistory.class.getResource("/InterfazGrafica/Images/1418023120_Program-Group.png"))); getContentPane().setBackground(new Color(248, 248, 255)); setBounds(10, 50, 836, 739); getContentPane().setLayout(null); contentPanel.setBackground(new Color(248, 248, 255)); contentPanel.setBounds(0, 40, 820, 600); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel); contentPanel.setLayout(null); setLocationRelativeTo(null); setModal(true); setTitle("Historial del Solicitante"); table = new JTable(); table.setBorder(new LineBorder(new Color(0, 0, 0))); table.setBounds(35, 400, 400, 200); tableModel = new DefaultTableModel(); String[] columnNames = { "No.", "Empresa", "Pocision", "Area", "No. Solicitudes" }; tableModel.setColumnIdentifiers(columnNames); ArrayList<CompanyPerson> CP = new ArrayList<CompanyPerson>(); CP = Satisfied.getInstanceSatisfied().SearchPersonHistory(P); loadPerson(CP); scrollPane = new JScrollPane(); scrollPane.setBounds(0, 0, 819, 600); scrollPane.setViewportView(table); contentPanel.add(scrollPane); { JPanel buttonPane = new JPanel(); buttonPane.setBackground(new Color(248, 248, 255)); buttonPane.setBounds(0, 640, 820, 61); buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER)); getContentPane().add(buttonPane); { JButton okButton = new JButton("Aceptar"); okButton.setIcon(new ImageIcon(PersonHistory.class.getResource("/InterfazGrafica/Images/botonsi.png"))); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } JButton btnEliminar = new JButton("Eliminar"); btnEliminar.setIcon(new ImageIcon(PersonHistory.class.getResource("/InterfazGrafica/Images/eliminar32.png"))); buttonPane.add(btnEliminar); } lblPersona = new JLabel("Nombre:"); lblPersona.setFont(new Font("Tahoma", Font.BOLD, 11)); lblPersona.setBounds(10, 15, 58, 14); getContentPane().add(lblPersona); JLabel labelID = new JLabel("ID:"); labelID.setFont(new Font("Tahoma", Font.BOLD, 11)); labelID.setBounds(271, 15, 28, 14); getContentPane().add(labelID); label = new JLabel(""); label.setBounds(64, 15, 197, 14); getContentPane().add(label); label.setText(P.getName()); label_2 = new JLabel(""); label_2.setBounds(298, 15, 197, 14); getContentPane().add(label_2); label_2.setText(P.getID()); }
0
@Override public boolean add(T e) { if (e == null) throw new RuntimeException("Does not permit nulls"); int hash =e.cuckooHash(); int hash2 = e.cuckooHashTwo(); int hash3 =e.cuckooHashThree(); hash =hash & mask; hash2 =hash2 & mask; hash3 =hash3 & mask; //inlining for performance. makes add about 20% faster if (e.equals(table[hash]) || e.equals(table[hash2]) || e.equals(table[hash3])) return false; if(table[hash]==null){ table[hash]=e; }else if(table[hash2]==null){ table[hash2]=e; }else if(table[hash3]==null){ table[hash3]=e; }else{ T pushed=(T)table[hash]; table[hash]=e; //System.out.println("Pushing "+e); pushInsert(pushed); } size++; // check size... to avoid cascading rehashes. if (size > threshold) rehash(); return true; }
8
@SuppressWarnings("unused") @Deprecated private ComplexMatrix strassenMultiply(ComplexMatrix mx) { int n = getRowsNum() / 2; // 0 1 2 3 ComplexMatrix[] m1 = divideMatrixIntoFour(n, n); // a b c d ComplexMatrix[] m2 = mx.divideMatrixIntoFour(n, n); // e f g h if (m1[0].getColsNum() == 1) { Complex a = m1[0].getElem(0, 0); Complex b = m1[1].getElem(0, 0); Complex c = m1[2].getElem(0, 0); Complex d = m1[3].getElem(0, 0); Complex e = m2[0].getElem(0, 0); Complex f = m2[1].getElem(0, 0); Complex g = m2[2].getElem(0, 0); Complex h = m2[3].getElem(0, 0); Complex p1 = a.times(f.subtract(h)); Complex p2 = a.add(b).times(h); Complex p3 = c.add(d).times(e); Complex p4 = d.times(g.subtract(e)); Complex p5 = a.add(d).times(e.add(h)); Complex p6 = b.subtract(d).times(g.add(h)); Complex p7 = a.subtract(c).times(e.add(f)); // Complex p1 = m1[0].getElem(0, // 0).times(m2[1].getElem(0, // 0).subtract(m2[3].getElem(0, 0))); // Complex p2 = m1[0].getElem(0, 0).add(m1[1] // .getElem(0, 0)).times(m2[3].getElem(0, 0)); // Complex p3 = m1[2].getElem(0, 0).add(m1[3] // .getElem(0, 0)).times(m2[0].getElem(0, 0)); // Complex p4 = m1[3].getElem(0, // 0).times(m2[2].getElem(0, // 0).subtract(m2[0].getElem(0, 0))); // Complex p5 = m1[0].getElem(0, 0).add(m1[3] // .getElem(0, 0)).times(m2[0].getElem(0, // 0).add(m2[3].getElem(0, 0))); // Complex p6 = m1[1].getElem(0, // 0).subtract(m1[3].getElem(0, // 0)).times(m2[2].getElem(0, 0).add(m2[3].getElem(0, // 0))); // Complex p7 = m1[0].getElem(0, // 0).subtract(m1[2].getElem(0, // 0)).times(m2[0].getElem(0, 0).add(m2[1].getElem(0, // 0))); // System.out.println(" = = = = = = = = = = = = = = = = "); // System.out.println("p1 = " + p1); // System.out.println("p2 = " + p2); // System.out.println("p3 = " + p3); // System.out.println("p4 = " + p4); // System.out.println("p5 = " + p5); // System.out.println("p6 = " + p6); // System.out.println("p7 = " + p7); try { // return new ComplexMatrix(new Complex[][] { // { p5.add(p4).add(p6).add(p2), p1.add(p2) }, // { p3.add(p4), // p1.add(p5).subtract(p3).subtract(p7) } }); return new ComplexMatrix(new Complex[][]{{p5.add(p4).subtract(p6).subtract(p2), p1.add(p2)}, {p3.add(p4), p1.add(p5).subtract(p3).subtract(p7)}}); } catch (Exception e1) { e1.printStackTrace(); return null; } } ComplexMatrix p1, p2, p3, p4, p5, p6, p7; ComplexMatrix a, b, c, d; try { p1 = m1[0].multiply(m2[1].subtract(m2[3])); p2 = m1[0].add(m1[1]).multiply(m2[3]); p3 = m1[2].add(m1[3]).multiply(m2[0]); p4 = m1[3].multiply(m2[2].subtract(m2[0])); p5 = m1[0].add(m1[3]).multiply(m2[0].add(m2[3])); p6 = m1[1].subtract(m1[3]).multiply(m2[2].add(m2[3])); p7 = m1[0].subtract(m1[2]).multiply(m2[0].add(m2[1])); // a = p5.add(p4).subtract(p2).add(p6); // b = p1.add(p2); // b // c = p3.add(p4); // c // d = p1.add(p5).subtract(p3).subtract(p7); a = p5.add(p4).subtract(p2).subtract(p6); b = p1.add(p2); // b c = p3.add(p4); // c d = p1.add(p5).subtract(p3).subtract(p7); } catch (Exception e) { e.printStackTrace(); return null; } return joinMatrixFromFour(a, b, c, d); }
3
private void process() { boolean inEpsilonRange = false; int i = 0; double error = 0; Vector prevV = v; while (i < iterations && !inEpsilonRange) { i++; v = MatrixOps.toVector(A.multiply(v)); if (v.get(1) < 0) { v = v.multiply(-1); } double temp = v.norm(); if (Math.abs(temp - norm) < epsilon && Math.abs(temp - norm) < error) { Vector tempV = MatrixOps.toVector(MatrixOps.multiply(v, 1 / v.norm())); if (Math.abs(tempV.get(1) - prevV.get(1)) + Math.abs(tempV.get(2) - prevV.get(2)) < 0.01) { inEpsilonRange = true; } } error = Math.abs(temp - norm); norm = v.norm(); v = v.multiply(1 / norm); prevV = v; } if (i >= iterations) { v = null; iterationsNeeded = -1; //System.out.println("Failure to converge the vector in the given number of iterations."); } else { iterationsNeeded = i; //System.out.println("Approximation done in " + i + " iterations. Eigenvalue is " + norm + " and eigenvector is: " + v); } }
7
private void computeMatch() { /* Phase 1 */ for (int j = 0; j < match.length; j++) { match[j] = match.length; } //O(m) computeSuffix(); //O(m) /* Phase 2 */ //Uses an auxiliary array, backwards version of the KMP failure function. //suffix[i] = the smallest j > i s.t. p[j..m-1] is a prefix of p[i..m-1], //if there is no such j, suffix[i] = m //Compute the smallest shift s, such that 0 < s <= j and //p[j-s]!=p[j] and p[j-s+1..m-s-1] is suffix of p[j+1..m-1] or j == m-1}, // if such s exists, for (int i = 0; i < match.length - 1; i++) { int j = suffix[i + 1] - 1; // suffix[i+1] <= suffix[i] + 1 if (suffix[i] > j) { // therefore pattern[i] != pattern[j] match[j] = j - i; } else {// j == suffix[i] match[j] = Math.min(j - i + match[i], match[j]); } } //End of Phase 2 /* Phase 3 */ //Uses the suffix array to compute each shift s such that //p[0..m-s-1] is a suffix of p[j+1..m-1] with j < s < m //and stores the minimum of this shift and the previously computed one. if (suffix[0] < pattern.length()) { for (int j = suffix[0] - 1; j >= 0; j--) { if (suffix[0] < match[j]) { match[j] = suffix[0]; } } int j = suffix[0]; for (int k = suffix[j]; k < pattern.length(); k = suffix[k]) { while (j < k) { if (match[j] > k) match[j] = k; j++; } } }//endif }
9
void doHit() { if (gameInProgress == false) { message = "Click \"New Game\" to start a new game."; repaint(); return; } playerHand.addCard( deck.dealCard() ); if ( playerHand.getBlackjackValue() > 21 ) { message = "You've busted! Sorry, you lose."; gameInProgress = false; } else if (playerHand.getCardCount() == 5) { message = "You win by taking 5 cards without going over 21."; gameInProgress = false; } else { message = "You have " + playerHand.getBlackjackValue() + ". Hit or Stand?"; } repaint(); }
3
public double getRadius() { return radius; }
0
public void testPropertyCompareToHour() { LocalDateTime test1 = new LocalDateTime(TEST_TIME1); LocalDateTime test2 = new LocalDateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(test2) < 0); assertEquals(true, test2.hourOfDay().compareTo(test1) > 0); assertEquals(true, test1.hourOfDay().compareTo(test1) == 0); try { test1.hourOfDay().compareTo((ReadablePartial) null); fail(); } catch (IllegalArgumentException ex) {} DateTime dt1 = new DateTime(TEST_TIME1); DateTime dt2 = new DateTime(TEST_TIME2); assertEquals(true, test1.hourOfDay().compareTo(dt2) < 0); assertEquals(true, test2.hourOfDay().compareTo(dt1) > 0); assertEquals(true, test1.hourOfDay().compareTo(dt1) == 0); try { test1.hourOfDay().compareTo((ReadableInstant) null); fail(); } catch (IllegalArgumentException ex) {} }
2
public void setCount(int count) { this.count = count; }
0
public static byte[] constructPacket(HostRecord hostRecord, int txnId) throws Exception { // calculate packet length String host = hostRecord.getDomainName(); ArrayList<IPAddress> ipAddresses = hostRecord.getIpAddresses(); int headLen = 12; String hostParts[] = host.split("\\."); int questionLen = 5; for (String s: hostParts) { questionLen += s.length(); questionLen += 1; } int answerLen = 0; answerLen += 16 * ipAddresses.size(); // 2 bytes domain name pointer // 8 bytes type, class, ttl // 6 bytes ip address int totalLen = headLen + questionLen + answerLen; // push stuff in ByteArrayOutputStream bos = new ByteArrayOutputStream(totalLen); DataOutputStream dos = new DataOutputStream(bos); // head dos.writeShort(txnId); // transaction id short flags = (short) 0x8180; if (hostRecord.getIpAddresses().size() == 0) flags |= 0x03; // name error dos.writeShort(flags); // flags dos.writeShort(1); // number of questions dos.writeShort(ipAddresses.size()); dos.writeShort(0); // authority RRs dos.writeShort(0); // additional RRs // questions for (String s: hostParts) { dos.writeByte(s.length()); for (char c: s.toCharArray()) { dos.writeByte((byte)c); } } dos.writeByte(0); // ending 0 dos.writeShort(Utils.QUERY_TYPE_A); // query type dos.writeShort(1); // query class // answers for (IPAddress address: ipAddresses) { dos.writeByte(0xC0); // the domain name is a pointer dos.writeByte(0x0C); // the pointer location dos.writeShort(Utils.QUERY_TYPE_A); // query type dos.writeShort(1); // query class dos.writeInt(360); // TTL = 6 minutes dos.writeShort(4); // RR data length dos.write(address.getBuffer(), 0, 4); // IP address } dos.close(); return bos.toByteArray(); }
5
public Image getAvatarAsImage(int px) { switch(px) { case 16: return new ImageIcon(gravatar_16px).getImage(); case 32: return new ImageIcon(gravatar_32px).getImage(); case 64: return new ImageIcon(gravatar_64px).getImage(); case 128: return new ImageIcon(gravatar_128px).getImage(); case 256: return new ImageIcon(gravatar_256px).getImage(); default: return new ImageIcon(gravatar_256px).getImage(); } }
5
public String getAnswer(){ long answer = 0; for(int x = 0; x < 20; x++){ long currentLoop = 1; for(int i = 0; i < 37; i++){ for( int y = 0; y < 13; y++){ char theNum = NUM.charAt((50 * x) + i + y); long number = theNum; currentLoop *= number; } if (currentLoop > answer) answer = currentLoop; } } for(int x = 0; x < 50; x++){ long currentLoop = 1; for(int i = 0; i < 7; i++){ for( int y = 0; y < 13; y++){ char theNum = NUM.charAt( x + i + (y * 50)); long number = theNum; currentLoop *= number; } if (currentLoop > answer) answer = currentLoop; } } return String.valueOf(answer); }
8
private void addFeatDialog() { JLabel nameLabel = new JLabel("Feat name"); nameLabel.setAlignmentX(Component.LEFT_ALIGNMENT); JTextField nameField = new JTextField(); nameField.setAlignmentX(Component.LEFT_ALIGNMENT); JLabel descLabel = new JLabel("Feat description"); descLabel.setAlignmentX(Component.LEFT_ALIGNMENT); JTextArea descField = new JTextArea(); descField.setColumns(40); descField.setRows(30); descField.setLineWrap(true); descField.setAlignmentX(Component.LEFT_ALIGNMENT); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.add(nameLabel); panel.add(nameField); panel.add(descLabel); panel.add(descField); boolean showAgain = true; do { int option = JOptionPane.showConfirmDialog(null, panel, "New Feat", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { String newFeatName = nameField.getText(); String newFeatDesc = descField.getText(); Feat newFeat = new Feat(); newFeat.setName(newFeatName); if (newFeatDesc == null || newFeatDesc.equals("")) { newFeat.setDescription("No description provided."); } else { newFeat.setDescription(newFeatDesc); } if (newFeat.getName() == null || newFeat.getName().equals("")) { JOptionPane.showMessageDialog(this.getTopLevelAncestor(), "New feat must have a name.", "Error", JOptionPane.ERROR_MESSAGE); } else if (feats.contains(newFeat)) { JOptionPane.showMessageDialog(this.getTopLevelAncestor(), "New feat must have a unique name.", "Error", JOptionPane.ERROR_MESSAGE); } else { feats.add(newFeat); updateParent(); showAgain = false; } } else { showAgain = false; } } while (showAgain); }
7
public static void configureStandardUI() { System.setProperty("apple.laf.useScreenMenuBar", Boolean.TRUE.toString()); //$NON-NLS-1$ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(System.err); } }
1
public List<Integer> match(String pattern, String text) { List<Integer> matches = new ArrayList<Integer>(); int m = text.length(); int n = pattern.length(); Map<Character, Integer> rightMostIndexes = preprocessForBadCharacterShift(pattern); int alignedAt = 0; while (alignedAt + (n - 1) < m) { for (int indexInPattern = n - 1; indexInPattern >= 0; indexInPattern--) { int indexInText = alignedAt + indexInPattern; char x = text.charAt(indexInText); char y = pattern.charAt(indexInPattern); if (indexInText >= m) break; if (x != y) { Integer r = rightMostIndexes.get(x); if (r == null) { alignedAt = indexInText + 1; } else { int shift = indexInText - (alignedAt + r); alignedAt += shift > 0 ? shift : 1; } break; } else if (indexInPattern == 0) { matches.add(alignedAt); alignedAt++; } } } return matches; }
7
@Override public void paintComponent(Graphics g) { List<BeeHive> beeHiveList = _temporaryEnvironment.getBeeHives(); for (BeeHive f : beeHiveList) { g.setColor(new Color(255, 0, 0)); g.fillOval( (_fieldSizeX / 2) * _fieldScaleFactor + (((f.getPosition().x * _fieldScaleFactor) - 5) + 15), (_fieldSizeY / 2) * _fieldScaleFactor + (((f.getPosition().y * _fieldScaleFactor) - 5) + 15), 10, 10); } List<Flower> flowerList = _temporaryEnvironment.getFlowers(); for (Flower f : flowerList) { g.setColor(new Color(0, 255, 0)); g.drawRect( (_fieldSizeX / 2) * _fieldScaleFactor + (((f.getPosition().x * _fieldScaleFactor) - 2) + 15), (_fieldSizeY / 2) * _fieldScaleFactor + (((f.getPosition().y * _fieldScaleFactor) - 2) + 15), 5, 5); } List<Bee> beeList = _temporaryEnvironment.getBees(); for (Bee f : beeList) { g.setColor(_hiveMap.get(f.getHomeName())); if (f.isMoving()) { drawArrow(g, (_fieldSizeX / 2 * _fieldScaleFactor) + ((f.getPosition().x * _fieldScaleFactor) - 1) + 15, (_fieldSizeY / 2 * _fieldScaleFactor) + ((f.getPosition().y * _fieldScaleFactor) - 1) + 15, (_fieldSizeX / 2 * _fieldScaleFactor) + ((f.getDestination().x * _fieldScaleFactor) - 1) + 15, (_fieldSizeY / 2 * _fieldScaleFactor) + ((f.getDestination().y * _fieldScaleFactor) - 1) + 15); } else { g.fillRect((_fieldSizeX / 2) * _fieldScaleFactor + ((((f.getPosition().x) * _fieldScaleFactor) - 1) + 15), (_fieldSizeY / 2) * _fieldScaleFactor + ((((f.getPosition().y) * _fieldScaleFactor) - 1) + 15), 4, 4); } } }
4
private void checkForPeakY(double y) { if (isUpPeakY) { if (y < lastY) { peakY = lastY; isUpPeakY = false; } } else { if (y > lastY) { peakY = lastY; isUpPeakY = true; } } lastY = y; }
3
public boolean isScramble(String s1, String s2) { if (s1.equals(s2)) { return true; } char[] one = s1.toCharArray(); char[] two = s2.toCharArray(); Arrays.sort(one); Arrays.sort(two); if (!Arrays.equals(one, two)) { return false; } int len = s1.length(); for (int i = 1; i < len; i++) { String s1Left = s1.substring(0, i); String s1Right = s1.substring(i); String s2Left = s2.substring(0, i); String s2Right = s2.substring(i); if (isScramble(s1Left, s2Left) && isScramble(s1Right, s2Right)) { return true; } s2Left = s2.substring(0, len - i); s2Right = s2.substring(len - i); if (isScramble(s1Left, s2Right) && isScramble(s1Right, s2Left)) { return true; } } return false; }
7
public void addPopup(int x, int y) { JMenuItem item = new JMenuItem(); JPopupMenu menu = new JPopupMenu(); item = new JMenuItem("Rename"); if(list.getSelectedIndex() == -1) item.setEnabled(false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { @SuppressWarnings("unused") RenameFactionEditor factionEditor = new RenameFactionEditor(list.getSelectedValue()); list.setModel(buildList()); } }); menu.add(item); item = new JMenuItem("Remove"); if(list.getSelectedIndex() == -1) item.setEnabled(false); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ((DefaultListModel<String>) list.getModel()).removeElementAt(list.getSelectedIndex()); try { save(); } catch (IOException e) { e.printStackTrace(); } list.setModel(buildList()); } }); menu.add(item); menu.show(list, x, y); }
3
private String readInput() throws IOException { return this.keyboard.readLine(); }
0
@Override public boolean execute(Mob usr) { Container loc = usr.getLoc(); //Search the player's loc for the item's container, if we need to. if(getTargetContainer() != null){ Obj container = search(getTargetContainer(), loc); if (container != null && container.isContainer()){ loc = (Container) container; } } //Regardless of whether we found a new container, //search for the item, same as above. Obj obj = search(getTarget(), loc); if (obj != null && obj.isGetable() && obj.isWearable()){ if(obj.getClass() == Item.class){ Item item = (Item) obj; usr.wear(item); return true; } } return false; }
7
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BookService bookService = (BookService) getServletContext().getAttribute("bookService");//呼叫service int booksCount = bookService.getBooksCount();//取得book總數 int size = 10; int page = 1;//此變數名稱固定在getBooksPages()方法裡 if (request.getParameter("size") != null &&request.getParameter("page") != null) {//檢查目前page,size page = Integer.parseInt(request.getParameter("page")); size = Integer.parseInt(request.getParameter("size")); } else if (request.getSession().getAttribute("page") != null && request.getSession().getAttribute("size") != null) { page = (int) request.getSession().getAttribute("page");//從session找page,size size = (int) request.getSession().getAttribute("size"); } request.getSession().setAttribute("page", page); request.getSession().setAttribute("size", size); List<StringBuilder> pages = getBooksPages("ShowBookStore.view", booksCount, size);//計算需要頁面且回傳超連結 Set<Book> bookSet = bookService.getAllBook(Math.min(page, pages.size()), size);//根據page與size查找資料庫book,page不超過size // request.getSession().setAttribute("page", page); // request.getSession().setAttribute("size", size); request.setAttribute("booksPage", bookSet);//反正每次都要查新的,不用活太久 request.setAttribute("pagesCount", pages); //購物session檢查 HttpSession session = request.getSession(); if (session.getAttribute("shoppingCar") != null) {//拿session最精準,list會變 ShoppingCar shoppingcar = (ShoppingCar) session.getAttribute("shoppingCar");//呼叫購物車物件 ShoppingCarService shoppingCarService = (ShoppingCarService) getServletContext().getAttribute("shoppingCarService");// request.setAttribute("CarSize", shoppingCarService.CountTotal(shoppingcar.getShoppingCarMap()));//數量給頁面 } else { // Map<Book,Integer> shoppingCarMap=new TreeMap<>();//若無session則set session.setAttribute("shoppingCar", new ShoppingCar());//若無session則建立 } // BookService bookService=(BookService) getServletContext().getAttribute("bookService"); // // // request.setAttribute("bookSet", bookService.getAllBook());//List給頁面 request.getRequestDispatcher("BookStore.jsp").forward(request, response); }
5
protected void setOutput(String output) { /* * Too careful again. */ if(output == null) myOutput = ""; else myOutput = output; }
1
private double getCoordinate(String RationalArray) { //num + "/" + den String[] arr = RationalArray.substring(1, RationalArray.length()-1).split(","); String[] deg = arr[0].trim().split("/"); String[] min = arr[1].trim().split("/"); String[] sec = arr[2].trim().split("/"); double degNumerator = Double.parseDouble(deg[0]); double degDenominator = 1D; try{degDenominator = Double.parseDouble(deg[1]);} catch(Exception e){} double minNumerator = Double.parseDouble(min[0]); double minDenominator = 1D; try{minDenominator = Double.parseDouble(min[1]);} catch(Exception e){} double secNumerator = Double.parseDouble(sec[0]); double secDenominator = 1D; try{secDenominator = Double.parseDouble(sec[1]);} catch(Exception e){} double m = 0; if (degDenominator != 0 || degNumerator != 0){ m = (degNumerator / degDenominator); } if (minDenominator != 0 || minNumerator != 0){ m += (minNumerator / minDenominator) / 60D; } if (secDenominator != 0 || secNumerator != 0){ m += (secNumerator / secDenominator / 3600D); } return m; }
9
public int getplayernum() { return players.size(); }
0
@Override public void run() { API api = Plugin.getAPI(); for(Player p : Bukkit.getOnlinePlayers()){ api.setMoney(p, api.getMoney(p) + api.getPlayersJob(p).getSalary()); p.sendMessage("[RP] " + api.getPlayersJob(p).getSalary() + "$ has been added to your wallet!"); } }
1
public static boolean validaMesAno (String strMesAno){ if(strMesAno == null || strMesAno.trim().equals("")){ return false; } if(strMesAno.length()!=7) return false; else{ String mes = strMesAno.substring(0, 2); if(validaNumero(mes)){ if(Long.valueOf(mes).compareTo(Long.valueOf("12")) > 0 || Long.valueOf(mes).compareTo(Long.valueOf("0")) != 1) return false; }else return false; String ano = strMesAno.substring(3,7); if(!validaNumero(ano)) return false; else{ if(Long.valueOf(ano).compareTo(Long.valueOf("0")) != 1) return false; } } return true; }
8