text
stringlengths
14
410k
label
int32
0
9
private void showTemporalProjects(String queryString) { PanelHelper.cleanPanel(spelprojectHolderPanel); ArrayList<String> tempal = new ArrayList<>(); ArrayList<Spelprojekt> al = new ArrayList<>(); Date now = new Date(); //fetch what the date is right now String nowdate = new java.text.SimpleDateFormat("dd.MM.yyyy").format(now); //format it to something we can use queryString = queryString.replaceAll("(NOWDATEHERE)", nowdate); try { String query = queryString; tempal = DB.fetchColumn(query); } catch (InfException e) { e.getMessage(); } if (tempal != null) { // if we found some, add them to the panel for (String st : tempal) { al.add(new Spelprojekt(Integer.parseInt(st))); } for (Spelprojekt sp : al) { PanelHelper.addPanelToPanel(new SpelprojektPanelViewbox("" + sp.getSid(), sp.getBeteckning(), sp.getReleasedatum(), sp.getStartdatum()), spelprojectHolderPanel, 150, 120); } } }
4
public int getRXAxisValue() { if (rxaxis == -1) { return 127; } return getAxisValue(rxaxis); }
1
public String extractLastName(String fullName) { String lastName=""; String msg=""; //String temp=""; //String pattern = "[a-zA-Z]"+ " " + "[a-zA-Z]"; boolean nameRight=false; int j=0; do{ if(fullName==null||fullName.length()==0){ nameRight=false; msg=NULL_VAL; }else{ for(int i=fullName.length()-1;i>=0;i--){ if(fullName.charAt(i)==32&&nameRight==false){ nameRight=true; msg=""; //extract last name for(j=i;j<fullName.length();j++){ lastName+=fullName.toCharArray()[j]; } } } } if(!nameRight){ fullName = JOptionPane.showInputDialog(msg+REQUEST_FULL_NAME); } }while(!nameRight); return lastName; //String[] nameParts = fullName.split(" "); //return nameParts[LAST_NAME_IDX]; //tried /* * else if(!fullName.matches(pattern)){ nameRight=false; System.out.println("not matching pattern"); */ }
8
public void run () { //Guarda tiempo actual del sistema lonTiempoActual = System.currentTimeMillis(); // se realiza el ciclo del juego en este caso nunca termina while (true) { /* mientras dure el juego, se actualizan posiciones de jugadores se checa si hubo colisiones para desaparecer jugadores o corregir movimientos y se vuelve a pintar todo */ if(!booPausa && !booAyuda){ actualiza(); checaColision(); repaint(); } try { // El thread se duerme. Thread.sleep (20); } catch (InterruptedException iexError) { System.out.println("Hubo un error en el juego " + iexError.toString()); } if(booGuardar){ booGuardar = false; booPausa = false; } } }
5
Object lock(Ref ref){ //can't upgrade readLock, so release it releaseIfEnsured(ref); boolean unlocked = true; try { tryWriteLock(ref); unlocked = false; if(ref.tvals != null && ref.tvals.point > readPoint) throw retryex; Info refinfo = ref.tinfo; //write lock conflict if(refinfo != null && refinfo != info && refinfo.running()) { if(!barge(refinfo)) { ref.lock.writeLock().unlock(); unlocked = true; return blockAndBail(refinfo); } } ref.tinfo = info; return ref.tvals == null ? null : ref.tvals.val; } finally { if(!unlocked) ref.lock.writeLock().unlock(); } }
8
public static void main(String args[]) { System.out.println("Number\tPossible Combinations"); for (int x = 1; x <= 18; x++) { int count = 0; for (int k = 1; k <= 6; k++) { for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 6; j++) { if (k + i + j == x) count++; } } } System.out.println(x + "\t\t\t" + count); } }
5
public int verifyNumberOfPlayersOnBoard(){ int players = 0; Tile currentJTile = topTile; for(int j = 0; j < dimension; j++){ Tile currentKTile = currentJTile; for(int k = 0; k < dimension; k++){ if(currentKTile.playerOnTile != null){ players++; } currentKTile = currentKTile.rightDown; } currentJTile = currentJTile.leftDown; } return players; }
3
public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb=new StringBuilder(); for (String ln;(ln=in.readLine())!=null;) { StringTokenizer st=new StringTokenizer(ln); int N=parseInt(st.nextToken()),M=parseInt(st.nextToken()); boolean[] mod=new boolean[M]; for(int s=0;;s=(s+N)%M)if(mod[s])break;else mod[s]=true; boolean ws=true; for(int i=0;i<M&&ws;i++)ws=mod[i]; for(int i=(N+"").length();i<10;i++)sb.append(" "); sb.append(N); for(int i=(M+"").length();i<10;i++)sb.append(" "); sb.append(M); sb.append(" "+(ws?"Good Choice":"Bad Choice")+"\n\n"); } System.out.print(new String(sb)); }
8
public Category getCategory(String naam){ for (Category cat : categories) { if ( cat.naam.equals(naam) ){ return cat; } } Category returnCat = new Category(naam); categories.add(returnCat); return returnCat; }
2
private Expr expr() { Expr res, nextTerm; res = term(); while (theTokenizer.ttype == '+' || theTokenizer.ttype == '-') { char op = (char) theTokenizer.ttype; theTokenizer.next(); nextTerm = term(); if (op == '+') { res = new Add(res,nextTerm); } else { res = new Sub(res,nextTerm); } } return res; }
3
private String bidForAuction() { if (user.isOnline()) { int auctionID = 0; double amount = 0.0; if (stringParts.length < 3) { return "Error: Please enter the bid- Command like this: " + "!bid <auction-id> <amount>"; } try { auctionID = Integer.parseInt(stringParts[1]); amount = Double.parseDouble(stringParts[2]); amount = (double)(Math.round(amount*100))/100; if (amount <= 0 ) { return "Error: The amount has to be > 0!"; } } catch (NumberFormatException e) { return "Error: Please enter the bid- Command like this: " + "!bid <auction-id> <amount>"; } catch (ArrayIndexOutOfBoundsException e) { return "Error: Please enter the bid- Command like this: " + "!bid <auction-id> <amount>"; } return userManagement.bidForAuction(user, auctionID, amount); } return "You have to log in first!"; }
5
public static void main(String[] args) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); sb = new StringBuilder( ); int N = Integer.parseInt(in.readLine()); in.readLine(); for (int i = 0; i < N; i++) { score = new TreeMap<Integer,int[]>(); solved = new TreeMap<Integer, boolean[]>(); penales = new TreeMap<Integer, int[]>(); for (String line; (line = in.readLine())!=null && line.length()>0;) { StringTokenizer st = new StringTokenizer(line); int team = Integer.parseInt(st.nextToken())-1; int penalPosition = Integer.parseInt(st.nextToken())-1; int valuePosition = Integer.parseInt(st.nextToken()); char judge = st.nextToken().trim().charAt(0); // if( judge == 'C' || judge == 'I' ){ int[] penalties; boolean[] solve; int[] cantPenales; if( !score.containsKey(team) ){ penalties = new int[10]; solve = new boolean[9]; cantPenales = new int[9]; } else{ penalties = score.get(team); solve = solved.get(team); cantPenales = penales.get(team); } if( judge == 'I' && !solve[penalPosition]){ cantPenales[penalPosition] += 1; }else if( judge== 'C' && !solve[penalPosition] ){ penalties[penalPosition] += valuePosition; penalties[penalties.length-1]+=valuePosition; solve[penalPosition]=true; } score.put(team, penalties); solved.put(team, solve); penales.put(team, cantPenales); } // } solve( ); if( i < N-1 ) sb.append("\n"); } System.out.print(new String(sb)); }
9
public void main(String sourceDir, String destDir) { try { String currentdir = plugin.minecraft_folder; // File (or directory) to be moved File source = new File(currentdir + "/" + sourceDir); // Destination directory File dest = new File(currentdir + "/" + destDir); if (source.exists()){ // Move file to new directory boolean success = source.renameTo(dest); if (!success) { // File was not successfully moved plugin.logMessage("File was not moved!"); } }else{ plugin.logMessage("File does not exist! '" + source.getPath() + "'"); } } catch (Exception e){ plugin.logMessage("Something went wrong!"); } }
3
public static double maxProfitJor(double[] prices) { double percentOriginal = 1; double lowestCurrent = prices[0]; double highestCurrent = prices[0]; for(int i=0; i < prices.length; i++) { if (prices[i] > highestCurrent && i < prices.length - 1) { highestCurrent = prices[i]; continue; } percentOriginal = percentOriginal * (highestCurrent / lowestCurrent); if (prices[i] < lowestCurrent) lowestCurrent = prices[i]; highestCurrent = prices[i]; } if (prices[prices.length-1] > prices[prices.length-2]) { percentOriginal = percentOriginal * ((double)prices[prices.length-1] / (double)prices[prices.length-2]); } return percentOriginal; }
5
public Population tournamentSelection(Population pop, int outSize, int tourSize){ Individual [] subset = new Individual[outSize]; int popSize = pop.size(); int [] indexes = new int[tourSize]; Set<Integer> indexesB = new HashSet<Integer>(); int outCount = 0; while (outCount<outSize){//until we have the output subset population size int tourCount=0; double bestFitness = 0; int bestIndex = -1; while (tourCount<tourSize){//until we have the specified tour size int index = rand.nextInt(popSize); if (!indexesB.contains(index)){ // If index hasn't yet been selected add it indexesB.add(index);// only need if using probability indexes[tourCount]=index; tourCount++; double fitness=Config.getInstance().calculateFitness(pop.population.get(index)); if(fitness>bestFitness){// fitness of this individual is best bestFitness=fitness; bestIndex=index; }// take best one? or take best one with probability prob (as wiki suggests) } } subset[outCount]=pop.population.get(bestIndex); outCount++; indexesB.clear(); } return new Population(subset); }
4
public synchronized TrackedTorrent announce(Torrent newTorrent) { TrackedTorrent torrent = this.torrents.get(newTorrent.getHexInfoHash()); if (torrent != null) { logger.warn("Tracker already announced torrent for '" + torrent.getName() + "' with hash " + torrent.getHexInfoHash() + "."); return torrent; } else { torrent = new TrackedTorrent(newTorrent); } this.torrents.put(torrent.getHexInfoHash(), torrent); logger.info("Registered new torrent for '" + torrent.getName() + "' " + "with hash " + torrent.getHexInfoHash()); return torrent; }
1
private boolean addModeToSet(final String modeName, Map<String, Set<String>> modeSets, String[] modeToAdd) { if (null == modeName || "".equals(modeName.trim())) return false; boolean isModified = false; String o = modeName.trim().toUpperCase(); Set<String> modeSet = modeSets.get(o); if (null == modeSet) { modeSet = new TreeSet<String>(); modeSets.put(o, modeSet); } for (String newMode : modeToAdd) { String n = newMode.trim().toUpperCase(); if ("".equals(n)) continue; if (modeSet.add(n)) isModified = true; } if (modeSet.size() == 0) modeSets.remove(o); return isModified; }
7
public static int findNumDays(String fileName) { int lineNumber = 0; String line; try { BufferedReader br = new BufferedReader( new FileReader(fileName)); while( (line = br.readLine()) != null) { lineNumber++; //counts number of entries in file } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return lineNumber; }
3
private void updateAlt() { mAltCount = mCount; mAltModifier = mModifier; if (EXTRA_DICE_FROM_MODIFIERS) { int average = (mSides + 1) / 2; if ((mSides & 1) == 1) { // Odd number of sides, so average is a whole number mAltCount += mAltModifier / average; mAltModifier %= average; } else { // Even number of sides, so average has an extra half, which means we alternate while (mAltModifier > average) { if (mAltModifier > 2 * average) { mAltModifier -= 2 * average + 1; mAltCount += 2; } else { mAltModifier -= average + 1; mAltCount++; } } } } }
4
@Override public String toString() { return "&markers=color:blue%7Clabel:"+Integer.toString(id)+"%7C"+Double.toString(latitude)+","+Double.toString(longtitude); }
0
public Color getTopDividerColor() { return mTopDividerColor == null ? mOwner.getDividerColor() : mTopDividerColor; }
1
public static void main(String[] args) { /* program to print the pattern 55555 4444 333 22 1 */ for (int i=5;i>=0;i--) { for (int j=i;j>=0;j--) System.out.print(i); System.out.println(""); }}
2
public void repaintView() { repaint(); if (mHeaderPanel != null) { mHeaderPanel.repaint(); } }
1
@Override public List<String> getGroups() { return (LinkedList<String>) groups.clone(); }
0
private void anothing() { System.out.println("功能B"); }
0
private synchronized void schedule() { if (!mPending && isDisplayable()) { mPending = true; Tasks.scheduleOnUIThread(this, 1, TimeUnit.SECONDS, this); } }
2
public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); }
6
@Override public boolean tick(Tickable ticking, int tickID) { if(!super.tick(ticking,tickID)) return false; if(affected==null) return false; if(affected instanceof Room) { final Room R=(Room)affected; if(isBlightable(R.myResource())) R.setResource(RawMaterial.RESOURCE_SAND); for(int i=0;i<R.numItems();i++) { final Item I=R.getItem(i); if((I!=null)&&(isBlightable(I.material()))) { R.showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 withers away.",I.name())); I.destroy(); break; } } } return true; }
7
public void createCoupon(String cou_name,String cou_file, int quantity){ Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql = ""; try{ conn = getConnection(); sql = "insert into coupon(cou_num,cou_name,cou_usage,cou_date.cou_file) values" + "(cou_num_seq.nextval,?,0,sysdate+180,?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, cou_name); pstmt.setString(2, cou_file); for(int i=0;i<quantity;i++){ rs =pstmt.executeQuery(); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(rs!=null)try{rs.close();}catch(SQLException ex){} if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){} if(conn!=null)try{conn.close();}catch(SQLException ex){} } }
8
private void expandArrayCapacityBy(int number) { E[] temparr = (E[]) new Object[array.length + number]; System.arraycopy(array, 0, temparr, 0, (number > 0) ? array.length : array.length + number); array = temparr; }
1
private boolean getDataBlock(int leafItemIndex) { // check for valid data block if (leafItemIndex >= leafHitList.size()) return false; // Perform a block read for indexed leaf item leafHitItem = leafHitList.get(leafItemIndex); // get the chromosome names associated with the hit region ID's int startChromID = leafHitItem.getChromosomeBounds().getStartChromID(); int endChromID = leafHitItem.getChromosomeBounds().getEndChromID(); chromosomeMap = chromIDTree.getChromosomeIDMap(startChromID, endChromID); boolean isLowToHigh = chromDataTree.isIsLowToHigh(); int uncompressBufSize = chromDataTree.getUncompressBuffSize(); // decompress leaf item data block for feature extraction wigDataBlock = new BigWigDataBlock(fis, leafHitItem, chromosomeMap, isLowToHigh, uncompressBufSize); // get section Wig item list and set next index to first item wigItemList = wigDataBlock.getWigData(selectionRegion, isContained); wigItemIndex = 0; // data block items available for iterator if (wigItemList.size() > 0) return true; else return false; }
2
public int getBumoncode() { return this.bumoncode; }
0
public void closeSocket() { try { if ( this.isaMc != null && this.ms != null && ! this.ms.isClosed() ) this.ms.leaveGroup(isaMc, EzimNetwork.localNI); } catch(Exception e) { EzimLogger.getInstance().severe(e.getMessage(), e); } try { if (this.ms != null && ! this.ms.isClosed()) this.ms.close(); } catch(Exception e) { EzimLogger.getInstance().severe(e.getMessage(), e); } }
7
@Override public void emitCode(GluonOutput code) { factor.emitCode(code); for (int i=0; i<factors.size(); i++) { code.code("PUSH EAX"); factors.get(i).emitCode(code); switch (ops.get(i)) { case MULTIPLY: code.code("POP EBX"); code.code("IMUL EAX,EBX"); break; case DIVIDE: code.code("MOV EBX, EAX"); code.code("MOV EDX, 0"); code.code("POP EAX"); code.code("IDIV EBX"); break; } } }
3
public static int Cardinality(Object obj, Collection coll){ if(coll == null){ throw new NullPointerException(); } if(obj == null){ throw new NullPointerException(); } for(Object o : coll){ if(o.equals(obj)){ total++; } } return total; }
4
public void removeCleanup(int start, int end){ // проверяет не нужно ли удалить схлопнувшиеся сегменты Set<ASection> s = aDataMap.keySet(); Iterator<ASection> it = s.iterator (); boolean foundCollapsed = false; Vector <ASection> toRemove = new Vector <ASection>(); while(it.hasNext()){ ASection sect = it.next(); if (sect.getStartOffset()> start && sect.getStartOffset()<= end && sect.getEndOffset()> start && sect.getEndOffset()<= end ){ //it.remove(); toRemove.add(sect); foundCollapsed = true;} } for (int i = 0; i<toRemove.size(); i++){ removeASection(toRemove.get(i)); } if (foundCollapsed) fireADocumentChanged(); }
7
private void ensureStructure() { try (Statement statement = openStatement()) { ResultSet rs = statement.executeQuery("SELECT time FROM scores"); } catch (SQLException e) { try { Statement s = openStatement(); s.executeUpdate("CREATE TABLE scores(" + "time INT)"); } catch (SQLException e1) { e1.printStackTrace(); } } }
2
void sendMessageToSocket (Message msg, DataOutputStream dos) throws IOException { int len = msg.data != null ? msg.data.length : 0; if (isControlOpcode (msg.opcode) && len > 125) throw new IOException ("payload for control packet too large"); if (msg.opcode <= 0 || msg.opcode > 0xf) throw new IOException ("opcode out of range 1-15 inclusive"); dos.write (0x80 | msg.opcode); if (len <= 125) { dos.write (len); } else if (len <= 0xffff) { dos.write (126); dos.writeShort (len); } else { dos.write (127); dos.writeLong (len); } if (msg.data != null) dos.write (msg.data); dos.flush (); }
8
@EventHandler public void WitchNausea(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.getWitchConfig().getDouble("Witch.Nausea.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (plugin.getWitchConfig().getBoolean("Witch.Nausea.Enabled", true) && damager instanceof Witch && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getWitchConfig().getInt("Witch.Nausea.Time"), plugin.getWitchConfig().getInt("Witch.Nausea.Power"))); } }
6
private void moveMouse(final Gamepad gamepad, final double delta) { final int MAX_SPEED = 1800; Point mouse = MouseInfo.getPointerInfo().getLocation(); float x = gamepad.getStickRight().getValueX(); float y = gamepad.getStickRight().getValueY(); if (Math.abs(x) > 0.25) { moveX += (delta * x * x * x * x * x * MAX_SPEED); } if (Math.abs(y) > 0.25) { moveY += (delta * y * y * y * y * y * MAX_SPEED); } if (Math.abs(moveX) > 1 || Math.abs(moveY) > 1) { System.out.println((int) (mouse.x + moveX) + " : " + (int) (mouse.y + moveY)); robot.mouseMove((int) (mouse.x + moveX), (int) (mouse.y + moveY)); if (Math.abs(moveX) > 1) moveX = 0; if (Math.abs(moveY) > 1) moveY = 0; } }
6
public UserOperator stop() { thisTimer.cancel(); run = false; return this; }
0
final public void Class_tail() throws ParseException { /*@bgen(jjtree) Class_tail */ SimpleNode jjtn000 = new SimpleNode(JJTCLASS_TAIL); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000); jjtn000.jjtSetFirstToken(getToken(1)); try { jj_consume_token(END); jj_consume_token(CLASS); jj_consume_token(SEMICOLON); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); jjtn000.jjtSetLastToken(getToken(0)); } } }
1
private void isEqualToBoolean(final Object param, final Object value) { if (value instanceof Boolean) { if (!((Boolean) value).equals((Boolean) param)) { throw new IllegalStateException("Booleans are not equal."); } } else { throw new IllegalArgumentException(); } }
2
public String getstatetext(){ return state; }
0
public static boolean isNullOrEmpty(String value) { return value == null || value.length() == 0; }
1
@Test public void testParseInvalidPredicateName() throws Exception { Parser parser = new Parser(); try { parser.parsePredicate("father*of(P, C)"); fail("This predicate contains invalid characters in the name."); } catch (ParseException ex) { // Expected exception } }
1
private void waitForThread() { if ((this.thread != null) && this.thread.isAlive()) { try { this.thread.join(); } catch (final InterruptedException e) { plugin.getLogger().log(Level.SEVERE, null, e); } } }
3
private void dbCheck(String dir){ //checks to see if the db has been created File isdb = new File(dir +"\\myDB"); if (isdb.exists()){ if (DBRead.DBIntegrityCheck(countries)){ JOptionPane.showMessageDialog(null,"The Database appears to be damaged, please wait create a new one.", "Warning",JOptionPane.WARNING_MESSAGE); DBRead.DBDelete(countries); new Thread(new XmlParser(countries, false, appP)).start(); } else if (!DBRead.DBIntegrityCheck(countries)){ // if db files exists check for the date tables were loaded. // if less then 24 hours old prompt to load again Boolean refresh = dbDateCheck(); int c=0; if (!refresh){ c = JOptionPane.showConfirmDialog(null, "The currecncy information is less than 24 hours old.\n" + "Do you want to update anyway?", "Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); // if user selects yes, update the tables if (c==0){ new Thread(new XmlParser(countries, false, appP)).start(); } } // if dates are older than 24 hours, update tables else if (refresh){ new Thread(new XmlParser(countries, false, appP)).start(); } } } else{// if it does not exist run the DB create class to create DB // show message box informing that a db does not exist JOptionPane.showMessageDialog(null,"A Database does not exist, please wait for the database to be created", "Warning",JOptionPane.WARNING_MESSAGE); new DBCreate(countries, dir, appP); } }
6
@Test public void deletingFromEmptyListDoesntAffectSize() { a.delete(v); assertEquals(0, a.getSize()); for (int i = 0; i < 10; i++) { a.delete(v); } assertEquals(0, a.getSize()); }
1
private static List<Appointment> findWeeklyByDay(long uid, long day) throws SQLException { List<Appointment> aAppt = new ArrayList<Appointment>(); // select * from Appointment where frequency = $WEEKLY // and startTime <= $(day + DateUtil.DAY_LENGTH) // and lastDay >= $day // and freqHelper = $freqHelper PreparedStatement statement = connect.prepareStatement("select * from (" + makeSqlSelectorForUser(uid) + ") as Temp where frequency = ? " + "and startTime <= ? " + "and lastDay >= ? " + "and freqHelper = ? "); statement.setInt(1, Frequency.WEEKLY); statement.setLong(2, day + DateUtil.DAY_LENGTH); statement.setLong(3, day); statement.setInt(4, Appointment .computeFreqHelper(Frequency.WEEKLY, day)); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { aAppt.add(Appointment.createOneFromResultSet(resultSet)); } return aAppt; }
1
public void unregisterListeners( Plugin plugin ) { for( Class< ? extends Event > eventClass : executors.keySet()) { List< EventExecutor > keep = new ArrayList< EventExecutor >(); for( EventExecutor e : executors.get( eventClass ) ) { if( e.getPlugin().getClass() == plugin.getClass() ) { continue; } keep.add( e ); } if( keep.isEmpty() ) { executors.remove( eventClass ); } else { executors.put( eventClass, keep ); } } }
5
public static boolean marshalSalesResponse(com.adammargherio.xml.schemas.salesorder.Message m, boolean save) { com.adammargherio.xml.schemas.standardresponse.Message response = new com.adammargherio.xml.schemas.standardresponse.Message(); //Fill message header contents MessageHeader responseHeader = new MessageHeader(); responseHeader.setMessageId(m.getMessageHeader().getMessageId().toString()); responseHeader.setPartnerName(m.getMessageHeader().getPartnerName()); responseHeader.setTransactionName(m.getMessageHeader().getTransactionName()); responseHeader.setResponseRequest(BigInteger.ZERO); responseHeader.setSourceUrl(m.getMessageHeader().getSourceUrl()); response.setMessageHeader(responseHeader); //Fill message status contents MessageStatus responseStatus = new MessageStatus(); if (save == true) { responseStatus.setStatusCode(BigInteger.ZERO); responseStatus.setStatusDescription("success"); } else { responseStatus.setStatusCode(BigInteger.ONE); responseStatus.setStatusDescription("false"); } //TODO: Insert MessageStatus.setComments() here if necessary responseStatus.setResponseTimestamp(OrderTransformer.generateTimestamp()); response.setMessageStatus(responseStatus); //Fill transaction info if present in incoming message TransactionInfo responseTransInfo = new TransactionInfo(); if (!(m.getTransactionInfo() == null)) { if (m.getTransactionInfo().getEventID().isEmpty() || m.getTransactionInfo().getEventID().equalsIgnoreCase("") || m.getTransactionInfo().getEventID() == null) { responseTransInfo.setEventID(""); } else { responseTransInfo.setEventID(m.getTransactionInfo().getEventID()); } } else { responseTransInfo.setEventID(""); } //TODO: Write code here that gets remote connection and outputs to the correct directory response.setTransactionInfo(responseTransInfo); try { JAXBContext jc = JAXBContext.newInstance("com.adammargherio.xml.schemas.standardresponse"); Marshaller marshaller = jc.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); marshaller.marshal(response, sw); HttpConnectionManager http = new HttpConnectionManager(); if (http.writeMessage(sw.toString())) { System.out.println("Standard Response sent across the wire to the remote server."); } else { } } catch (JAXBException jaxe) { jaxe.printStackTrace(); } return true; }
7
public ShellLink setIconLocation(String s) { if (s == null) header.getLinkFlags().clearHasIconLocation(); else { header.getLinkFlags().setHasIconLocation(); String t = resolveEnvVariables(s); if (!Paths.get(t).isAbsolute()) s = Paths.get(s).toAbsolutePath().toString(); } iconLocation = s; return this; }
2
static private float[] subArray(final float[] array, final int offs, int len) { if (offs+len > array.length) { len = array.length-offs; } if (len < 0) len = 0; float[] subarray = new float[len]; for (int i=0; i<len; i++) { subarray[i] = array[offs+i]; } return subarray; }
3
@Override public Grid generateGrid() { playerFactory.generate(); // Give the players some items to start for (Player player : grid.getAllPlayersOnGrid()) { LightGrenade item1 = new LightGrenade(player.getPosition()); this.addObservable(item1); this.addObserver(item1); player.addItemToInventory(item1); IdentityDisc item2 = new IdentityDisc(player.getPosition()); this.addObservable(item2); player.addItemToInventory(item2); IdentityDisc item3 = new IdentityDisc(player.getPosition(), true); this.addObservable(item3); player.addItemToInventory(item3); } // add some elements to the grid grid.addElement(new Wall(new Position(2, 9), 2, Direction.HORIZONTAL)); grid.addElement(new Wall(new Position(0, 1), 2, Direction.HORIZONTAL)); LightGrenade lightGrenade1 = new LightGrenade(new Position(0, 7)); grid.addElement(lightGrenade1); this.addObservable(lightGrenade1); this.addObserver(lightGrenade1); LightGrenade lightGrenade2 = new LightGrenade(new Position(1, 7)); grid.addElement(lightGrenade2); this.addObservable(lightGrenade2); this.addObserver(lightGrenade2); LightGrenade activeLightGrenade1 = new LightGrenade(new Position(2, 8)); activeLightGrenade1.setActive(true); grid.addElement(activeLightGrenade1); this.addObservable(activeLightGrenade1); this.addObserver(activeLightGrenade1); LightGrenade activeLightGrenade2 = new LightGrenade(new Position(1, 6)); activeLightGrenade2.setActive(true); grid.addElement(activeLightGrenade2); this.addObservable(activeLightGrenade2); this.addObserver(activeLightGrenade2); Teleporter teleporter = new Teleporter(new Position(0, 5)); Teleporter teleporterDestionation = new Teleporter(new Position(0, 2)); teleporter.setDestination(teleporterDestionation); grid.addElement(teleporter); this.addObserver(teleporter); // add some effects to the grid PowerFailure powerFailure1 =new PowerFailure(new Position(1, 6)); this.addObservable(powerFailure1); this.addObserver(powerFailure1); grid.addEffectToGrid(powerFailure1); PowerFailure powerFailure2 =new PowerFailure(new Position(1, 7)); this.addObservable(powerFailure2); this.addObserver(powerFailure2); grid.addEffectToGrid(powerFailure2); PowerFailure powerFailure3 =new PowerFailure(new Position(1, 8)); this.addObservable(powerFailure3); this.addObserver(powerFailure3); grid.addEffectToGrid(powerFailure3); return grid; }
1
public Gui getGui() { return new Gui() { @Override public void render(Graphics2D g2d, int width, int height) { LinearGradientPaint gradient = new LinearGradientPaint(0, 0, 0, 100, new float[]{0,1}, new Color[]{new Color(0x666666),new Color(0x444444)}); g2d.setPaint(gradient); g2d.fillRect(0, 0, width, 100); g2d.setColor(new Color(0x666666)); g2d.fillRect(0, 100, width, height - 100); g2d.setColor(Color.WHITE); g2d.setFont(Client.instance.translation.font.deriveFont(Font.BOLD, 35F)); g2d.drawString(name, 50, 50); g2d.setFont(Client.instance.translation.font.deriveFont(Font.BOLD, 18F)); g2d.setColor(Color.GRAY); g2d.drawString(ip, 50, 75); if(ping >= 0) { if(ping == 0) g2d.setColor(Color.RED.darker()); g2d.drawString(ping == 0 ? Client.instance.translation.translate("protocol.timeout") : ping + "ms", 50, 95); } } }; }
3
public void doPrint() { List<String> nodes = this.graph.getVertexes(); for (String node : nodes) { List<String> edges = this.graph.getIncident(node); for (String edge : edges) { if (this.graph.getSource(edge).equals(node)) { System.out.format("%4s (%3s,%3s) %4s", node, this.graph.getValE(edge, this.attrEdgeCapacity), this.graph.getValE(edge, this.attrEdgeFlow), this.graph.getTarget(edge)); System.out.println(); } } System.out.println("---------------"); } System.out.println("Es wurde über " + ((backtracks == 0) ? "keine": backtracks) + " Rückswärtskante" + ((backtracks == 1)?"":"n") + " gegangen."); System.out.println("#######################"); }
5
public Colony build(){ // player not set, get default if(player == null){ player = game.getPlayer(defaultPlayer); if(player == null){ throw new IllegalArgumentException("Default Player " + defaultPlayer + " not in game"); } } // settlement tile no set, get default if(colonyTile == null){ colonyTile = game.getMap().getTile(5, 8); if(colonyTile == null){ throw new IllegalArgumentException("Default tile not in game"); } } /* if(this.name != null){ for(Colony colony : player.getColonies()){ if(colony.getName().equals(this.name)){ throw new IllegalArgumentException("Another colony already has the given name"); } } } */ Colony colony = new ServerColony(game, player, name, colonyTile); player.addSettlement(colony); colony.placeSettlement(true); // Add colonists int nCol = 0; Iterator<UnitType> iter = colonists.keySet().iterator(); while (iter.hasNext()) { UnitType type = iter.next(); Integer n = colonists.get(type); for (int i = 0; i < n; i++) { Unit colonist = new ServerUnit(game, colonyTile, player, type); colonist.setLocation(colony); nCol++; } } // add rest of colonists as simple free colonists for (int i = nCol; i < initialColonists; i++) { Unit colonist = new ServerUnit(game, colonyTile, player, colonistType); colonist.setLocation(colony); } return colony; }
7
public int getBurnDurationOfFuelBlock(int blockID) { int time = 0; if(fuelBlocksGroupIDlist_Wool.contains(blockID)) { time = Arctica.burnDuration_Wool; } else if(fuelBlocksGroupIDlist_CraftedWood.contains(blockID)) { time = Arctica.burnDuration_CraftedWood; } else if(fuelBlocksGroupIDlist_Log.contains(blockID)) { time = Arctica.burnDuration_Log; } else if(fuelBlocksGroupIDlist_CoalOre.contains(blockID)) { time = Arctica.burnDuration_CoalOre; } else { // block with this ID is not a valid flammable block, so it has no Group and no burn duration } return (time); }
4
public static boolean hasStrongNode(Node node) { try { node.getNodeType(); } catch (Exception e) { return true; } if (node.getNodeType() == Node.TEXT_NODE) { return !node.getNodeValue().isEmpty(); } if (node.getNodeName().equalsIgnoreCase("img")) { return true; } Node nextSibling, child = node.getFirstChild(); while (child != null) { nextSibling = child.getNextSibling(); if (child.getNodeType() == Node.TEXT_NODE) { if (child.getNodeValue() != null && !child.getNodeValue().isEmpty()) { return true; } } else if (child.getNodeName().equalsIgnoreCase("br") && nextSibling == null) { return !BRElement.as(child).getAttribute(DIRTY_ATTRIBUTE).equals("true"); } else { return true; } child = child.getNextSibling(); } return false; }
9
public static int delete(String sql, List<Param> params)throws SQLException{ C3p0Pool pool = C3p0Pool.getInstance(); Connection conn = pool.getConnection(); PreparedStatement statement = conn.prepareStatement(sql); if(params!=null){ int i=1; for(Param p:params){ if(p.getColumnType()==ColumnType.Date){ statement.setDate(i++, (Date)p.getValue()); }else if(p.getColumnType()==ColumnType.DateTime){ statement.setDate(i++, (Date)p.getValue()); }else if(p.getColumnType()==ColumnType.Integer){ statement.setInt(i++, (Integer)p.getValue()); }else if(p.getColumnType()==ColumnType.BigInt){ statement.setLong(i++, (Long)p.getValue()); }else if(p.getColumnType()==ColumnType.String){ statement.setString(i++, (String)p.getValue()); }else if(p.getColumnType()==ColumnType.DateTime){ statement.setTimestamp(i++, (Timestamp)p.getValue()); }else if(p.getColumnType()==ColumnType.String){ statement.setString(i++, (String)p.getValue()); } } } try{ log.info(sql); return statement.executeUpdate(); }finally{ statement.close(); conn.close(); } }
9
public static double findNthSortedArrays(int A[], int B[], int nth) { int alen = A.length; int blen = B.length; int i = 0, j = 0; while (i < alen && j < blen) { if (1 == nth) { return min(A[i], B[j]); } int nth1 = nth / 2; int nth2 = nth - nth1; nth1 = min(nth1, alen - i); nth2 = min(nth2, blen - j); if (A[i + nth1 - 1] > B[j + nth2 - 1] ) { nth = nth - nth2; j = j + nth2; } else { nth = nth - nth1; i = i + nth1; } } if (i == alen) { return B[j + nth - 1]; } else { return A[i + nth - 1]; } }
5
public void addPopup(int x, int y) { JMenuItem item = new JMenuItem(); JPopupMenu menu = new JPopupMenu(); if(list.getSelectedValue() == null) { item = new JMenuItem("Add"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { NewVariableEditor varEdit = new NewVariableEditor(); if(varEdit.getVariable() != null) { listModel.add(listModel.getSize() - 1, varEdit.getVariable()); } } }); } else { item = new JMenuItem("Remove"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { listModel.remove(list.getSelectedIndex()); list.clearSelection(); } }); } menu.add(item); menu.show(list, x, y); }
2
@Override public ForeignKey parse() { if(!this.prepared) { this.prepared = true; StringBuilder sB = new StringBuilder(); sB.append("FOREIGN KEY ("); int i = 0; for(String lF : lFL) { if(i > 0) { sB.append(", "); }else{ ++i; } sB.append(lF); } sB.append(") \n"); sB.append(" REFERENCES "); sB.append(this.remoteTable.replace("#__", this.db.getPrefix())); sB.append(" ("); i = 0; for(String rF : rFL) { if(i > 0) { sB.append(", "); }else{ ++i; } sB.append(rF); } sB.append(") \n"); if(null != this.onUpdate) { sB.append(" ON UPDATE "); sB.append(this.onUpdate.getTextual()); sB.append(" \n"); } if(null != this.onDelete) { sB.append(" ON DELETE "); sB.append(this.onDelete.getTextual()); sB.append(" \n"); } this.fk = sB.toString(); } return this; }
7
public Student search(int id) throws UnknownStudent { Student s = null; boolean found = false; int i = 0; while (i < list.size() && !found) { s = list.get(i); if (s.getId() == id) found = true; i++; } if (!found) { throw new UnknownStudent("No student with an id " + id + " in the Promotion " + name + " !"); } else { return s; } }
4
@Test public void deleteOneTest() { final int n = 1_000; IntArray arr = IntArray.empty(); for(int k = 0; k < n; k++) { for(int i = 0; i < k; i++) { final IntArray arr2 = arr.remove(i); final Iterator<Integer> iter = arr2.iterator(); for(int j = 0; j < k - 1; j++) { assertTrue(iter.hasNext()); assertEquals(j < i ? j : j + 1, iter.next().intValue()); } assertFalse(iter.hasNext()); } arr = arr.snoc(k); assertEquals(k + 1, arr.size()); assertEquals(k, arr.last().intValue()); } }
4
@Override public void draw(Graphics page) { BulletImage.drawImage(page, xLocation, yLocation);//Draws the plane on the component //Draws the collision Border if(this.getBorderVisibility()) { drawCollisionBorder(page,xLocation,yLocation,BulletImage.getWidth(),BulletImage.getHeight()); } }
1
public MapObject findNextTargetObject() { for (Robot robot : current_room.getRobots()) { if (robot.isVisible() && shouldTargetObject(robot) && (!bound_pyro.isCloaked() || Math.random() < TARGET_ROBOT_WHEN_CLOAKED_PROB)) { return robot; } } for (Powerup powerup : current_room.getPowerups()) { if (shouldTargetObject(powerup) && shouldCollectPowerup(powerup)) { return powerup; } } return null; }
8
public static void main(String[] args){ try { String name = "main"; int num_rand; ArrayList<JvnObjectImpl> array = new ArrayList<JvnObjectImpl>(); //MonObjet o1 = new MonObjet("objet1"); //JvnObjectImpl shared_object_1 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnCreateObject(o1); //JvnServerImpl.jvnGetServer().jvnRegisterObject("objet1", shared_object_1); //Thread.sleep(5000); JvnObjectImpl shared_object_1 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnLookupObject("objet1"); JvnObjectImpl shared_object_2 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnLookupObject("objet2"); JvnObjectImpl shared_object_3 = (JvnObjectImpl) JvnServerImpl.jvnGetServer().jvnLookupObject("objet3"); array.add(shared_object_1); array.add(shared_object_2); array.add(shared_object_3); for(int i = 0; i < 50; i++){ for(JvnObjectImpl obj : array){ num_rand = (int) Math.round(Math.random()); switch(num_rand){ case 0 : System.out.println("Lock write on "+obj.jvnGetObjectId()+" by "+name); obj.jvnLockWrite(); System.out.println("Lock acquire"); ((MonObjet)obj.jvnGetObjectState()).setString("lock by"+name); Thread.sleep(1000*(num_rand+1)); obj.jvnUnLock(); System.out.println("Unlock done"); break; case 1 : System.out.println("Lock read on "+obj.jvnGetObjectId()+" by "+name); obj.jvnLockRead(); System.out.println("Actual value : "+((MonObjet)obj.jvnGetObjectState()).getString()); //Thread.sleep(1000*(num_rand+1)); obj.jvnUnLock(); System.out.println("Unlock done"); break; } } } JvnServerImpl.jvnGetServer().jvnTerminate(); System.out.println("YES fin du test pour "+name); System.exit(0); } catch (JvnException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6
private String[] getCombinations(String[] variables) { ArrayList list = new ArrayList(); for (int k = 0; k < ((int) Math.pow(2, variables.length)); k++) { String comb = pad(Integer.toBinaryString(k), variables.length); list.add(getRepresentation(comb, variables)); } return (String[]) list.toArray(new String[0]); }
1
@Override public void onPhase(PHASE phase, PHASE_STAGE stage) { if (phase.equals(PHASE.CONTENT_SCRAPE) && stage.equals(PHASE_STAGE.COMPLETE) && canTerminate) { logger.debug("Done scrapping. Deleting mapping"); // delete the mapping. We are done with the scrape } else if (phase.equals(PHASE.PAGE_SCRAPE) && stage.equals(PHASE_STAGE.COMPLETE)) { if (lowerYearBound > upperYearBound) { canTerminate = true; logger.info("Fetched complete year range. Can terminate"); } else { addYearRange(); String fetchUrl = buildFetchURL(); computeMaxPage(APIUtil.initTemplate(), fetchUrl); this.controlFlowManager.startPageScrape(apiKey, fetchUrl, maxPages); } } }
6
public Node getNext() { Node node = current; if (node == head) { current = null; return null; } else { current = node.next; return node; } }
1
private static boolean magicSquare(int[][] matrix) { int n = matrix.length; int nSquare = n * n; int magicSum = (n * n * (n * n + 1) / 2) / n; // Distribution of first k // = n * n natural // numbers distributed // among n rows/columns int rowSum = 0, colSum = 0, firstDiagonalSum = 0, secondDiagonalSum = 0; boolean[] flag = new boolean[n * n]; for (int row = 0; row < n; row++) { rowSum = 0; colSum = 0; for (int col = 0; col < n; col++) { if (matrix[row][col] < 1 || matrix[row][col] > nSquare) return false; if (flag[matrix[row][col] - 1] == true) return false; flag[matrix[row][col] - 1] = true; rowSum += matrix[row][col]; colSum += matrix[col][row]; } firstDiagonalSum += matrix[row][row]; secondDiagonalSum += matrix[row][n - row - 1]; if (rowSum != magicSum || colSum != magicSum) return false; } if (secondDiagonalSum != magicSum || secondDiagonalSum != magicSum) return false; return true; }
9
public CheckerBoard(int size) { boardSize = size; checkersBoard = new char[boardSize][boardSize]; typeR = 'r'; typeB = 'b'; empty = '_'; typeRList = new LinkedList<Chip>(); typeBList = new LinkedList<Chip>(); for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { if ((i + j) % 2 == 0) { checkersBoard[i][j] = empty; //EMPTY cell } } } for (int i = 0; i < (boardSize / 2) - 1; i++) { int j; if (i % 2 == 0) { j = 0; } else { j = 1; } while (j < boardSize) { checkersBoard[i][j] = typeR; //RED piece typeRList.add(new Chip(j, i)); j += 2; } } for (int i = boardSize - 1; i >= (boardSize) / 2 + 1; i--) { int j; if (i % 2 == 0) { j = 0; } else { j = 1; } while (j < boardSize) { checkersBoard[i][j] = typeB; //BLACK piece typeBList.add(new Chip(j, i)); j += 2; } } }
9
public void qSortMedianThree(int[] array, int left, int right){ if((right-left)<=0) return; if((right-left)==1){ if(array[left]>array[right]) swap(array, left, right); }else{ int median = medianOf3(array, left, right); int part = partIt(array, left, right, median); qSortMedianThree(array, left, part-1); qSortMedianThree(array, part+1, right); } }
3
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Jogador other = (Jogador) obj; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; return true; }
6
private void init(final String mapPath, final Properties props) { this.props = props; // Hajo: walls for all squares of this map if(props.get("walls") != null) { walls = getIntegers(props, "walls", '#'); } // Hajo: Floor for all squares of this map that have no other floor // Floors are randomly picked from the interval, including both borders. if(props.get("floors") != null) { standardGrounds = getIntegers(props, "floors", '.'); } // Hajo: floor tile range for corridors if(props.get("corridor_floors") != null) { corridorFloors = getIntegers(props, "corridor_floors", '.'); } // Hajo: standard floor for rooms // Hajo: floor tile range for corridors if(props.get("room_floors") != null) { roomFloors = getIntegers(props, "room_floors", '.'); } if(props.get("room_features") != null) { roomFeatures = getIntegers(props, "room_features", '.'); } roomWidthMin = getInt(props, "room_width_min", roomWidthMin); roomHeightMin = getInt(props, "room_height_min", roomHeightMin); roomWidthMax = getInt(props, "room_width_max", roomWidthMax); roomHeightMax = getInt(props, "room_height_max", roomHeightMax); roomGapHoriz = getInt(props, "room_gap_horiz", roomGapHoriz); roomGapVert = getInt(props, "room_gap_vert", roomGapVert); corridorWidth = getInt(props, "corridor_width", corridorWidth); hiddenWall = getInt(props, "hidden_wall", hiddenWall); outsideFloor = getInt(props, "outside_floor", outsideFloor); stairsUp = getInt(props, "stairs_up", stairsUp); door = getInt(props, "door", door); damagedFloorChance = getInt(props, "damaged_floor_chance", damagedFloorChance); viewRadius = getInt(props, "view_radius", viewRadius); // Hajo: at least 2 layers are needed. mapLayers = Math.max(getInt(props, "map_layers", mapLayers) , 2); }
5
private void batchEstimateDataAndMemory(boolean useRuntimeMaxJvmHeap, String outputDir, int newRNBase, boolean outputDetailedDataflow) throws IOException { File mDataOutputFile = new File(outputDir, "eDataMappers.txt"); File rDataOutputFile = new File(outputDir, "eDataReducers.txt"); // outputDir = /estimatedDM/jobId/ File mJvmOutputFile = new File(outputDir, "eJvmMappers.txt"); File rJvmOutputFile = new File(outputDir, "eJvmReducers.txt"); if(!mJvmOutputFile.getParentFile().exists()) mJvmOutputFile.getParentFile().mkdirs(); PrintWriter mDfWriter = new PrintWriter(new BufferedWriter(new FileWriter(mDataOutputFile))); PrintWriter rDfWriter = new PrintWriter(new BufferedWriter(new FileWriter(rDataOutputFile))); PrintWriter mJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(mJvmOutputFile))); PrintWriter rJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(rJvmOutputFile))); displayAllMapDataTitle(mDfWriter); displayAllReduceDataTitle(rDfWriter); displayMapJvmCostTitle(mJvmWriter); displayReduceJvmCostTitle(rJvmWriter); for(int splitMB = 64; splitMB <= 256; splitMB = splitMB * 2) { for(int xmx = 1000; xmx <= 4000; xmx = xmx + 1000) { for(int ismb = 200; ismb <= 800; ismb = ismb + 200) { for(int reducer = newRNBase; reducer <= newRNBase * 2; reducer = reducer * 2) { for(int xms = 0; xms <= 1; xms++) { //--------------------------Estimate the data flow--------------------------- //-----------------for debug------------------------------------------------- //System.out.println("[split = " + splitMB + " [xmx = " + xmx + ", xms = " + xms + ", ismb = " + // ismb + ", RN = " + reducer + "]"); //if(splitMB != 256 || xmx != 1000 || ismb != 200 || reducer != 9 || xms != 1) // continue; //if(xmx != 4000 || xms != 1 || ismb != 1000 || reducer != 9) // continue; //--------------------------------------------------------------------------- Configuration conf = new Configuration(); long newSplitSize = splitMB * 1024 * 1024l; conf.set("io.sort.mb", String.valueOf(ismb)); if(xms == 0) conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m"); else conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m" + " -Xms" + xmx + "m"); conf.set("mapred.reduce.tasks", String.valueOf(reducer)); conf.set("split.size", String.valueOf(newSplitSize)); setNewConf(conf); // -------------------------Estimate the data flow------------------------- List<Mapper> eMappers = estimateMappers(); //don't filter the mappers with small split size List<Reducer> eReducers = estimateReducers(eMappers, useRuntimeMaxJvmHeap); String fileName = conf.getConf("mapred.child.java.opts").replaceAll(" ", "") + "-ismb" + ismb + "-RN" + reducer; if(outputDetailedDataflow) { displayMapperDataResult(eMappers, fileName , outputDir + File.separator + "eDataflow" + splitMB); displayReducerDataResult(eReducers, fileName, outputDir + File.separator + "eDataflow" + splitMB); } displayMapperDataResult(eMappers, mDfWriter, splitMB, xmx, xms * xmx, ismb, reducer); displayReducerDataResult(eReducers, rDfWriter, splitMB, xmx, xms * xmx, ismb, reducer); // -------------------------Estimate the memory cost------------------------- InitialJvmCapacity gcCap = computeInitalJvmCapacity(); if(!gcCap.getError().isEmpty()) { System.err.println(gcCap.getError() + " [xmx = " + xmx + ", xms = " + xms + ", ismb = " + ismb + ", RN = " + reducer + "]"); } else { //filter the estimated mappers with low split size List<MapperEstimatedJvmCost> eMappersMemory = estimateMappersMemory(eMappers, gcCap); List<ReducerEstimatedJvmCost> eReducersMemory = estimateReducersMemory(eReducers, gcCap); displayMapperJvmCostResult(eMappersMemory, gcCap, mJvmWriter); displayReducerJvmCostResult(eReducersMemory, gcCap, rJvmWriter); } } } } } } mDfWriter.close(); rDfWriter.close(); mJvmWriter.close(); rJvmWriter.close(); }
9
private void setup() { dataFolder = main.getDataFolder(); accountFolder = new File(dataFolder.getPath() + "\\accounts"); transactionFolder = new File(dataFolder.getPath() + "\\transactions"); main.debug("Data folder: " + dataFolder.getPath()); main.debug("Account folder: " + accountFolder.getPath()); main.debug("Transaction folder: " + transactionFolder.getPath()); if (!dataFolder.exists()) { main.info("Preparing for first use..."); main.saveDefaultConfig(); dataFolder.mkdir(); } if (!accountFolder.exists()) { accountFolder.mkdir(); } if (!transactionFolder.exists()) { transactionFolder.mkdir(); } main.debug("Completed initial filecheck"); }
3
public Image(int width, int height) { this.width = width; this.height = height; this.pixels = new int[this.width*this.height]; }
0
public void setEmail(String email) { this.email = email; }
0
public void buildDetail(String id, JPanel panel) { if (getId().equals(id)) { return; } TileType tileType = getSpecification().getTileType(id); panel.setLayout(new MigLayout("wrap 4, gap 20")); String movementCost = String.valueOf(tileType.getBasicMoveCost() / 3); String defenseBonus = Messages.message("none"); Set<Modifier> defenceModifiers = tileType.getDefenceBonus(); if (!defenceModifiers.isEmpty()) { defenseBonus = getModifierAsString(defenceModifiers.iterator().next()); } JLabel nameLabel = localizedLabel(tileType.getNameKey()); nameLabel.setFont(smallHeaderFont); panel.add(nameLabel, "span, align center"); panel.add(localizedLabel("colopedia.terrain.terrainImage"), "spany 3"); Image terrainImage = getLibrary().getCompoundTerrainImage(tileType, 1); panel.add(new JLabel(new ImageIcon(terrainImage)), "spany 3"); List<ResourceType> resourceList = tileType.getResourceTypeList(); if (resourceList.size() > 0) { panel.add(localizedLabel("colopedia.terrain.resource")); if (resourceList.size() > 1) { panel.add(getResourceButton(resourceList.get(0)), "split " + resourceList.size()); for (int index = 1; index < resourceList.size(); index++) { panel.add(getResourceButton(resourceList.get(index))); } } else { panel.add(getResourceButton(resourceList.get(0))); } } else { panel.add(new JLabel(), "wrap"); } panel.add(localizedLabel("colopedia.terrain.movementCost")); panel.add(new JLabel(movementCost)); panel.add(localizedLabel("colopedia.terrain.defenseBonus")); panel.add(new JLabel(defenseBonus)); panel.add(localizedLabel("colopedia.terrain.production")); List<AbstractGoods> production = tileType.getProduction(); if (production.size() > 0) { AbstractGoods goods = production.get(0); if (production.size() > 1) { panel.add(getGoodsButton(goods.getType(), goods.getAmount()), "span, split " + production.size()); for (int index = 1; index < production.size(); index++) { goods = production.get(index); panel.add(getGoodsButton(goods.getType(), goods.getAmount())); } } else { panel.add(getGoodsButton(goods.getType(), goods.getAmount()), "span"); } } else { panel.add(new JLabel(), "wrap"); } panel.add(localizedLabel("colopedia.terrain.description")); panel.add(getDefaultTextArea(Messages.message(tileType.getDescriptionKey()), 20), "span, growx"); }
8
public ItemTablePanel(Class<T> clazz, ItemSet<T> items) throws Exception { this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); this.model = new ItemTableModel(clazz, items, this); this.table = new JTable(this.model); this.table.setFillsViewportHeight(true); int index = 0; for(Field field : clazz.getDeclaredFields()) { if(field.isAnnotationPresent(Value.class)) { Value val = field.getAnnotation(Value.class); TableColumn col = this.table.getColumnModel().getColumn(index); TableCellEditor editor = null; switch(val.type()) { case ComboBox: { @SuppressWarnings("rawtypes") Class<? extends Collection> collType = val.collection(); if(collType != null) { @SuppressWarnings("rawtypes") Collection collection = collType.newInstance(); if(collection != null) { editor = new TableCellComboBoxEditor(collection); } } break; } default: { break; } } if(editor != null) { col.setCellEditor(editor); } } } TableColumn removeCol = this.table.getColumnModel().getColumn(this.model.getColumnCount() - 1); removeCol.setMaxWidth(100); c.anchor = GridBagConstraints.PAGE_START; c.fill = GridBagConstraints.BOTH; c.gridwidth = 2; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; JScrollPane scroll = new JScrollPane(this.table); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); add(scroll, c); Dimension preferredSize = new Dimension(90, 25); this.addBtn = new JButton("Add"); this.addBtn.setPreferredSize(preferredSize); this.addBtn.addActionListener(this); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.5; c.weighty = 0; c.gridwidth = 1; c.gridx = 0; c.gridy = 1; add(this.addBtn, c); this.removeBtn = new JButton("Remove"); this.removeBtn.setPreferredSize(preferredSize); this.removeBtn.addActionListener(this); c.gridx = 1; c.gridy = 1; add(this.removeBtn, c); }
7
public int getPreferredHeight(List<Column> columns) { int preferredHeight = 0; for (Column column : columns) { int height = column.getRowCell(this).getPreferredHeight(this, column); if (height > preferredHeight) { preferredHeight = height; } } return preferredHeight; }
2
private static void colorButtonByPercentChangeAfterEarningsReport( CustomButton a, String dateInfo, String ticker) { String[] dates = dateInfo.split(" "); if (dates.length < 2) { // System.out.println("\n\nARRAY IS SHORT : " + dateInfo + " --> " // + Arrays.toString(dates)); return; } try { long earningsReportDate = EarningsTest.singleton.dateFormatForFile .parse(dates[1]).getTime() / 1000 / 3600 / 24; // int collectionDate = (int) Double.parseDouble(dates[0]); // TODO: COMPARE TO MARKET NOT ABSOLUTE int daysBefore = 10; int daysAfter = 2; float beforeReport = earningsReportDate - daysBefore; float afterReport = earningsReportDate + daysAfter; float marketFactor = Database.calculateMarketChange(beforeReport, afterReport); float change = Database.calculatePercentChange( Database.dbSet.indexOf(ticker), beforeReport, afterReport); // System.out.println("market calc: " + marketFactor); // System.out.println("change calc: " + change); change = change - marketFactor; int red = (int) (120 + change * 1); int green = (int) (140 + change * 1); int blue = (int) (140 + change * 3); if (red > 254) red = 255; if (green > 254) green = 255; if (blue > 254) blue = 255; if (red < 1) red = 1; if (green < 1) green = 1; if (blue < 1) blue = 1; a.setBackground(new Color(red, green, blue)); String rename = a.getText() + change + " % v mkt -" + daysBefore + ", +" + daysAfter + " days "; a.setText(rename); } catch (Exception e) { } }
8
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BankAccount other = (BankAccount) obj; if (listeners == null) { if (other.listeners != null) return false; } else if (!listeners.equals(other.listeners)) return false; if (money != other.money) return false; return true; }
7
@Test(expected = BadNextValueException.class) public void testInfixToPostfix8() throws BadNextValueException, DAIllegalArgumentException, DAIndexOutOfBoundsException, ShouldNotBeHereException, UnmatchingParenthesisException { try { infix.addLast("5"); QueueInterface<String> postFix = calc.infixToPostfix(infix); } catch (DAIllegalArgumentException e) { throw new DAIllegalArgumentException(); } catch (DAIndexOutOfBoundsException e) { throw new DAIndexOutOfBoundsException(); } catch (ShouldNotBeHereException e) { throw new ShouldNotBeHereException(); } catch (BadNextValueException e) { throw new BadNextValueException(); } catch (UnmatchingParenthesisException e) { throw new UnmatchingParenthesisException(); } }
5
public void buildEventTree() { eventRootNode.removeAllChildren(); List<ImgEvent> events = imageBrowser.getEvents(); if (events == null) { return; } for (ImgEvent e : events) { Calendar c = new GregorianCalendar(); c.setTimeInMillis(e.eventstart); int year = c.get(Calendar.YEAR); DefaultMutableTreeNode node = null; for (int i = 0; i < eventRootNode.getChildCount(); i++) { Object o = eventRootNode.getChildAt(i); if (o instanceof DefaultMutableTreeNode && o.toString().equals("" + year)) { node = (DefaultMutableTreeNode) o; break; } } if (node == null) { node = new DefaultMutableTreeNode("" + year); eventRootNode.add(node); } node.add(new DefaultMutableTreeNode(e, false)); } eventTreeModel.reload(); }
6
private static Key toKey(String password) throws Exception { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey; }
0
public <T extends NMEAEvent<? extends NMEASentence>>void bindEvent( Class<? extends NMEASentence> c, T event ) { events.put( c, event ); }
2
public void applyPrefixes(LinkedList<Prefix> pre){ //Scan subject, predicate and object (data indices 0 to 2) for (int i=0; i<3; i++){ String value=getByIndex(i); //Starts with '<'? (IRI) if (value.startsWith("<")){ //'a' predicate if (i==1 && value.equals("<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>")){ setPredicate("a"); }else{ //Try to find matching prefix for (Prefix p:pre){ if (value.startsWith("<"+p.getIriContent())){ //Replace IRI with prefix setByIndex(i,p.getPrefix()+value.substring(p.getIriContent().length()+1,value.length()-1)); //Only one prefix can match! Break! break; } } } } } }
6
private int aslB(int dest, int n) { clearFlags(SR_N, SR_Z, SR_V, SR_C); boolean hibitSet = msbSetB(dest); boolean hasOverflow = false; int result = dest; boolean msbSet; for (int i = 0; i < n; i++) { msbSet = msbSetB(result); if (msbSet) setFlags(SR_X, SR_C); else clearFlags(SR_X, SR_C); if (hibitSet && !msbSet) hasOverflow = true; else if (!hibitSet && msbSet) hasOverflow = true; result <<= 1; } if (n == 0) clearFlag(SR_C); if (msbSetB(result)) setFlags(SR_N); if (isZeroB(result)) setFlags(SR_Z); return result; }
9
public static <E> Node<E> bookIterative(Node<E> head, int k) { if (head == null) { return null; } Node<E> p1 = head; Node<E> p2 = head; int i = 0; for (; i < k && p1 != null; i++) { p1 = p1.next; } // This condition to check if k is greater than size of the list if (p1 == null && i < k) { return null; } while (p1 != null) { p1 = p1.next; p2 = p2.next; } return p2; }
6
public void paint(Graphics g) { // This method is called by the swing thread, so may be called // at any time during execution... // First draw the background elements /* for (Element<Light> e : _lightElements) { if (e.x.getState() == LightState.GreenNS_RedEW) { g.setColor(Color.GREEN); } else if(e.x.getState() == LightState.YellowNS_RedEW) { g.setColor(Color.YELLOW); } else { g.setColor(Color.RED); } XGraphics.fillOval(g, e.t, 0, 0, MP.baseCarLength, VP.elementWidth); } */ for (Element<Intersection> e : _intersectionElements) { if (e.x.getLightControl().getState() == LightState.GreenNS_RedEW) { g.setColor(Color.GREEN); } else if(e.x.getLightControl().getState() == LightState.YellowNS_RedEW) { g.setColor(Color.YELLOW); } else { g.setColor(Color.RED); } for (Vehicle d : e.x.getCars().toArray(new Vehicle[0])) { g.setColor(d.getColor()); XGraphics.fillOval(g, e.t, normalizeVehicleValueIntersection(d.getPosition(), e.x), 0, normalizeVehicleValueIntersection(d.getLength(), e.x), VP.elementWidth); } XGraphics.fillOval(g, e.t, 0, 0, MP.baseCarLength, VP.elementWidth); } g.setColor(Color.BLACK); for (Element<VehicleAcceptor> e : _roadElements) { XGraphics.fillRect(g, e.t, 0, 0, MP.baseRoadLength, VP.elementWidth); } // Then draw the foreground elements for (Element<VehicleAcceptor> e : _roadElements) { // iterate through a copy because e.x.getCars() may change during iteration... for (Vehicle d : e.x.getCars().toArray(new Vehicle[0])) { g.setColor(d.getColor()); XGraphics.fillOval(g, e.t, normalizeVehicleValue((d.getPosition() - d.getLength() ) , e.x), 0, normalizeVehicleValue(d.getLength(), e.x), VP.elementWidth); } } }
7
private boolean fireReceiveExceptionEvent(ExceptionEvent evt) { if (evt.getException() != null) { logger.debug(getName() + " receive exception : " + evt.getException().getMessage()); } return true; }
1
public static Professor addProfessors(Professor prof) { boolean exist = false; int pos = 0; if (prof == null) return null; for (int i = 0; i < FileReadService.profList.size(); i++) { if (FileReadService.profList.get(i).equals(prof)) { exist = true; pos = i; } } if (!exist) { FileReadService.profList.add(prof); return prof; } return FileReadService.profList.get(pos); }
4
public void onKeyReleased(KeyEvent e) { switch (e.getKeyCode()) { case VK_UP: case VK_W: directions.remove(Direction.UP); break; case VK_DOWN: case VK_S: directions.remove(Direction.DOWN); break; case VK_RIGHT: case VK_D: directions.remove(Direction.RIGHT); break; case VK_LEFT: case VK_A: directions.remove(Direction.LEFT); break; } }
8
public void printCars(ArrayList<Car> carList) { for (int i = 0; i < carList.size(); i++) System.out.println(carList.get(i).toString()); }
1
public static int getDatabaseMatchesInfo(int mode, int match, int teamID) { mode++; if (mode == 1) { return getMatchAutoPoints(match, teamID); } else if (mode == 2) { return getMatchTelePoints(match, teamID); } else if (mode == 3) { return getMatchFrisbyCollectionRating(match, teamID); } else if (mode == 4) { return getMatchAimingShootingSkillsRating(match, teamID); } else if (mode == 5) { int i = getMatchCanClimbInt(match, teamID); return i; } else if (mode == 6) { return getMatchPyramidLevel(match, teamID); } else if (mode == 7) { return getMatchFouls(match, teamID); } else if (mode == 8) { return getMatchTechFouls(match, teamID); } else if (mode == 9) { return getMatchLostConnectionInt(match, teamID); } else { return 0; } }
9
synchronized public void addElementWithReplacement (Element e) { Element root = doc.getRootElement(); Collection<Element> oldCachedElements = queryXPathList( String.format(ELEMENT_BY_URL_XPATH,e.getAttributeValue("url"))); for (Element current: oldCachedElements) current.detach(); root.addContent((Element)e.clone()); }
1