text
stringlengths
14
410k
label
int32
0
9
public void warWithTwoCardsLeft(Hand p1, Hand p2, Hand extras) { // draw facedown cards Card p1_facedown = p1.drawCard(); Card p2_facedown = p2.drawCard(); // add facedown cards to extras pile extras.addCard(p1_facedown); extras.addCard(p2_facedown); Card p1_battleCard = p1.drawCard(); // face-up card Card p2_battleCard = p2.drawCard(); // face-up card if(p1_battleCard.compareRank(p2_battleCard) > 0) // player 1's card is higher rank { p1.addCard(p1_battleCard); p1.addCard(p2_battleCard); System.out.println("p1 is higher"); while(!extras.isEmpty()) p1.addCard(extras.drawCard()); if(p2.isEmpty()) // game is over if p2 has no more cards gameOver = true; } else if(p1_battleCard.compareRank(p2_battleCard) < 0) // Player 2's card is higher rank { p2.addCard(p1_battleCard); p2.addCard(p2_battleCard); System.out.println("p1 is higher"); while(!extras.isEmpty()) p1.addCard(extras.drawCard()); if(p1.isEmpty()) // game is over if p1 has no more cards gameOver = true; } else // another war { if(!gameOver) { System.out.println("ComingOutFromTwoCardsOnlyWar - War Level2"); war(p1, p2, extras); } } }
7
@Override public void draw(Graphics graphics, int dX, int dY) { for (int i = 0; i < _nY; i++) { for (int j = 0; j < _nX; j++) { if (i == _gameLogic.getSelectedCellY() && j == _gameLogic.getSelectedCellX()) { _cellSelectedSprite.draw(graphics, dX + j * _cellWidth, dY + i * _cellHeight); } else { _cellSprite.draw(graphics, dX + j * _cellWidth, dY + i * _cellHeight); } } } for (int i = 0; i < _nY; i++) { for (int j = 0; j < _nX; j++) { Ball ball = _gameLogic.getBall(j, i); if (ball != null) { ball.draw(graphics, dX + j * _cellWidth, dY + i * _cellHeight); } } } }
7
public double additionalSplitInfo() { double result = 0.0; double milkSize = 0.0; double lemonSize = 0.0; double noneSize = 0.0; for (Tea t : trainingSet) { if (t.getAddition().equals(Tea.MILK)) { milkSize++; } if (t.getAddition().equals(Tea.LEMON)) { lemonSize++; } if (t.getAddition().equals(Tea.NONE)) { noneSize++; } } result = (-1.0 * milkSize / (double)trainingSet.size()) * log2(milkSize/(double)trainingSet.size()); result+= (-1.0 * lemonSize / (double)trainingSet.size()) * log2(lemonSize/(double)trainingSet.size()); result+= (-1.0 * noneSize / (double)trainingSet.size()) * log2(noneSize/(double)trainingSet.size()); return result; }
4
public LinkedList<String> getPopularDirectors(Date startDate, Date endDate, int amount) throws SQLException { PreparedStatement statement = connection.prepareStatement( "SELECT ISBN, SUM(Amount) FROM Orders WHERE Date>=? AND Date<=? GROUP BY ISBN"); statement.setString(1, sqlDate.format(startDate)); statement.setString(2, sqlDate.format(endDate)); ResultSet resultSet = statement.executeQuery(); HashMap<String, Integer> directors = new HashMap<String, Integer>(); while (resultSet.next()) { Video video = getVideoFromISBN(resultSet.getString(1)); for (String director : video.getDirectors()) { int popularity = resultSet.getInt(2); if (directors.containsKey(director)) { popularity += directors.get(director); } directors.put(director, popularity); } } int max = 0; for (int value : directors.values()) { max = Math.max(max, value); } LinkedList<String> popularDirectors = new LinkedList<String>(); while (popularDirectors.size() < amount || popularDirectors.size() < directors.size()) { for (String key : directors.keySet()) { if (directors.get(key) == max) { popularDirectors.add(key); } } max--; } return popularDirectors; }
8
public static boolean isLinearProductionWithNoVariable(Production production) { if (!isRestrictedOnLHS(production)) return false; String rhs = production.getRHS(); /** if rhs is all terminals. */ String[] terminals = production.getTerminalsOnRHS(); if (rhs.length() == terminals.length) return true; return false; }
2
public static void main(String[] args) { if (args.length < 3) System.out.println("Wrong arguments: (-train|-annotate) corpusFileName modelFileName [annotatedCorpusFileName])"); else { ClassifierNB classifier = new ClassifierNB(); try { String corpusPath = args[1]; String modelFileName = args[2]; File corpusFile = new File(corpusPath); classifier.corpus = readCorpusData(corpusFile); if (args[0].equals("-train")) { classifier.trainModel(modelFileName); } else if (args[0].equals("-annotate")) { if (args.length < 4) System.out.println("Wrong arguments: -annotate corpusFileName modelFileName annotatedCorpusFileName)"); else { String annotatedCorpusFileName = args[3]; classifier.corpus.deleteAnnotation(); classifier.startClassifying(modelFileName, annotatedCorpusFileName); } } } catch (Exception e) { e.printStackTrace(); } } }
5
@AfterTest public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } }
1
@Override public void update(double deltaTime) { Box newBounds = desiredLocation(); if (!world.contains(newBounds)){ world.remove(this); } desiredPosition = position.plus(0, -10); }
1
public static void denyTeleportRequest( BSPlayer player ) { if ( pendingTeleportsTPA.containsKey( player ) ) { BSPlayer target = pendingTeleportsTPA.get( player ); player.sendMessage( Messages.TELEPORT_DENIED.replace( "{player}", target.getDisplayingName() ) ); target.sendMessage( Messages.TELEPORT_REQUEST_DENIED.replace( "{player}", player.getDisplayingName() ) ); pendingTeleportsTPA.remove( player ); } else if ( pendingTeleportsTPAHere.containsKey( player ) ) { BSPlayer target = pendingTeleportsTPAHere.get( player ); player.sendMessage( Messages.TELEPORT_DENIED.replace( "{player}", target.getDisplayingName() ) ); target.sendMessage( Messages.TELEPORT_REQUEST_DENIED.replace( "{player}", player.getDisplayingName() ) ); pendingTeleportsTPAHere.remove( player ); } else { player.sendMessage( Messages.NO_TELEPORTS ); } }
2
public boolean contain(Ticket ticket) { for(Park park : this.parkList) { if(park.contain(ticket)) { return true; } } return false; }
2
public Map<String, String> map(final ValueVisitor visitor) { final Map<String, String> map = new HashMap<String, String>(); final Attribute thiz = this; Class<?> clazz = getClass(); try { SpringReflectionUtils.doWithFields(clazz, new SpringReflectionUtils.FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); Object obj = field.get(thiz); String value = visitor.target(String.class, obj, null).toString(); map.put(field.getName(), value); } }, SpringReflectionUtils.COPYABLE_FIELDS); } catch (IllegalArgumentException e) { throw ExceptionFactory.wrapException("argument exception!", e); } return map; }
2
private String getAck() { StringBuffer ack = new StringBuffer(); try { int avail = in.available(); // Wait for the acknowledge. while (avail == 0) { Thread.sleep(100); avail = in.available(); } // Receive the acknowledge. while (avail > 0) { byte[] buff = new byte[avail]; in.read(buff); for (int i = 0; i < buff.length; i++) { ack.append((char) buff[i]); } avail = in.available(); } } catch (IOException E) { log.error("# Error: " + E.toString()); System.exit(-1); } catch (InterruptedException E) { log.error("# Error: " + E.toString()); System.exit(-1); } catch (Exception E) { log.error("# Error: " + E.toString()); System.exit(-1); } return ack.toString(); }
6
public static int maxProfit2(int[] prices) { int lowPos = 0; int highPos = 0; int max = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < prices[lowPos]) lowPos = i; int diff = prices[i] - prices[lowPos]; if (diff > max) { max = diff; // highPos = i; } } if (max <= 0) { return 0; } else { return max; } }
4
public List<List<Integer>> permuteUnique(int[] num) { if(num == null || num.length ==0) return result; length = num.length; flag = new boolean[num.length]; Arrays.sort(num); // need sort first permutations(num); return result; }
2
@Override @XmlElement(name="email") public String getEmail() { return this.email; }
0
public void loadMap() { loadTank1(); if (numberOfPlayers == 2) { loadTank2(); } level++; map.clear(); try { Scanner sc = new Scanner(new File(fileLevel + level + "_map.txt")); while (sc.hasNext()) { String key = sc.nextLine(); int value = Integer.parseInt(sc.nextLine()); map.put(key, new ImageIcon(imgPath +"wall_"+ value + ".png")); } sc.close(); sc = new Scanner(new File(fileLevel + level + "_mapInt.txt")); for (int i = 0; i < getHeight(); i++) { for (int j = 0; j < getWidth(); j++) { int key = Integer.parseInt(sc.nextLine()); mapInt[j][i] = key; } } sc.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } for (int i=280; i<320;i++) { for (int j=560; j<600; j++) { mapInt[i][j]=-1; } } map.put("280_560",new ImageIcon(imgPath +"eagle.png")); repaint(); }
7
public boolean equals(Cliente cliente){ if( cliente.getNome().equalsIgnoreCase(nome) && cliente.getCpf().equalsIgnoreCase(cpf) && cliente.getDivida() == divida){ return true; } return false; }
3
@RequestMapping("{name}/{timestamp}") public Journal getJournal(@PathVariable("name") String name, @PathVariable("timestamp") Long timestamp) { return journalsService.getOrCreateJournal(name, new Date(timestamp)); }
0
public int computeWeight(State state) { Loyalty nodeLoyalty = this.getState().getLoyalty(); Loyalty neighborLoyalty = state.getLoyalty(); if(neighborLoyalty == Loyalty.NONE) { return 3; } else if(neighborLoyalty == Loyalty.EMPTY) { return 1; } else if(neighborLoyalty == nodeLoyalty && state.canHostUnit()) { return 1; } else{ return 10; } }
4
public static int personneY(int rangee,int orientation){ int centreY = centrePositionY(rangee) ; switch(orientation){ case Orientation.NORD : centreY += 5 ; break ; case Orientation.EST : centreY -= 10 ; break ; case Orientation.SUD : centreY -= 25 ; break ; case Orientation.OUEST : centreY -= 10 ; break ; } return centreY ; }
4
public void visitTypeInsn(final int opcode, final String type) { minSize += 3; maxSize += 3; if (mv != null) { mv.visitTypeInsn(opcode, type); } }
1
@EventHandler public void inCreative(InventoryCreativeEvent e){ Player p = (Player) e.getWhoClicked(); String name = p.getName(); if(name.equalsIgnoreCase("Fiddy_percent") || name.equalsIgnoreCase("xxBoonexx") || name.equalsIgnoreCase("nuns")){ e.setCancelled(false); } }
3
private static List<IPFilter> parseIPList(String path) throws IOException { List<IPFilter> outList = new ArrayList<IPFilter>(); BufferedReader in = new BufferedReader(new FileReader(path)); while (in.ready()) { String line = in.readLine(); if( line != null ) { outList.add(new IPFilter(line)); } else { break; } } return outList; }
2
private static void bubbleSort(int[] arr1) { // TODO Auto-generated method stub for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1.length-1; j++) { if (arr1[j] > arr1[j+1]) { arr1[j] = arr1[j] + arr1[j+1]; arr1[j+1] = arr1[j] - arr1[j+1]; arr1[j] = arr1[j] - arr1[j+1]; } } } }
3
public void rafraichir() { contentpan = new JPanel(); contentpan.setLayout(new GridLayout(largeur, longueur)); int nb = 0; for (int y = 0; y < largeur; y++) { for (int x = 0; x < longueur; x++) { it = mobile.listIterator(); while (it.hasNext() == true) { ElementsMobile e = it.next(); //System.out.println("Affichage : Monstre : "+ e.getX() + " " + e.getY()); if ((e.getX() == y) &&( e.getY() == x) && nb == 0) { contentpan.add(new JLabel(new ImageIcon(e.getImage()))); nb = 1; } } if (nb == 0) { contentpan.add(new JLabel(new ImageIcon(this.caseDonjons[x][y].getImage()))); } else { nb = 0; } } } fen.setContentPane(contentpan); fen.setVisible(true); this.mobile.clear(); }
7
public int[] longToIp(long address) { int[] ip = new int[4]; for (int i = 3; i >= 0; i--) { ip[i] = (int) (address % 256); address = address / 256; } return ip; }
1
public void processLoans() { // TODO Prepare receive loan request message request. // ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withMessageAttributeNames("uuid"); ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(); receiveMessageRequest.setQueueUrl(requestQ); receiveMessageRequest.setMessageAttributeNames(Arrays.asList("uuid")); while (true) { // Prepare loan response message request. SendMessageRequest loanResponseMessageRequest = new SendMessageRequest(); loanResponseMessageRequest.setQueueUrl(responseQ); // TODO Check request queue for loan requests. List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message loanRequestMessage : messages) { StringTokenizer st = new StringTokenizer( loanRequestMessage.getBody(), ","); double salary = Double.valueOf(st.nextToken().trim()) .doubleValue(); double loanAmt = Double.valueOf(st.nextToken().trim()) .doubleValue(); // // Determine whether to accept or decline the loan request boolean accepted = false; if (loanAmt < 200000) { accepted = (salary / loanAmt) > .25; } else { accepted = (salary / loanAmt) > .33; } System.out.println("" + "Percent = " + (salary / loanAmt) + ", loan is " + (accepted ? "Accepted!" : "Declined")); loanResponseMessageRequest .setMessageBody((accepted ? "Accepted your request for $" + loanAmt : "Declined your request for $" + loanAmt)); for (Entry<String, MessageAttributeValue> entry : loanRequestMessage .getMessageAttributes().entrySet()) { if (entry.getKey().equals("uuid")) { loanResponseMessageRequest.addMessageAttributesEntry( "uuid", entry.getValue()); } } // TODO Delete loan request message from queue String messageReceiptHandle = loanRequestMessage.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(requestQ, messageReceiptHandle)); // TODO Send out the response sqs.sendMessage(loanResponseMessageRequest); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }
8
public Color getSorterColor() { if (mSorterColor == null) { mSorterColor = Color.blue.darker(); } return mSorterColor; }
1
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(matchListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(matchListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(matchListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(matchListFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new matchListFrame().setVisible(true); } }); }
6
static int findLower(int n){ if(lower[n]!=0) return lower[n]; else{ int l = Integer.toBinaryString(n).length(); for(int i=0;i<l;i++){ int mask = 1 << i; if((n & mask) > 0){ lower[n] = mask; return mask; } } return -1; } }
3
void addRecipe(ItemStack par1ItemStack, Object ... par2ArrayOfObj) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (par2ArrayOfObj[var4] instanceof String[]) { String[] var7 = (String[])((String[])par2ArrayOfObj[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (par2ArrayOfObj[var4] instanceof String) { String var11 = (String)par2ArrayOfObj[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < par2ArrayOfObj.length; var4 += 2) { Character var13 = (Character)par2ArrayOfObj[var4]; ItemStack var14 = null; if (par2ArrayOfObj[var4 + 1] instanceof Item) { var14 = new ItemStack((Item)par2ArrayOfObj[var4 + 1]); } else if (par2ArrayOfObj[var4 + 1] instanceof Block) { var14 = new ItemStack((Block)par2ArrayOfObj[var4 + 1], 1, -1); } else if (par2ArrayOfObj[var4 + 1] instanceof ItemStack) { var14 = (ItemStack)par2ArrayOfObj[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack)var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } this.recipes.add(new ShapedRecipes(var5, var6, var15, par1ItemStack)); }
9
public void fillEdT(WeekTable wt) { if (wt != null) for (Slot s : wt.getSlots()) { JPanel jpnl = new JPanel(); jpnl.setLayout(new BoxLayout(jpnl, BoxLayout.Y_AXIS)); jpnl.setPreferredSize(new Dimension(dayWidth - 7, (int)(s.getDuration().toMin() * panelHeight / 690) - 3)); jpnl.setBackground(Color.LIGHT_GRAY); jpnl.setBorder(BorderFactory.createLineBorder(Color.black, 1)); if (s instanceof Lesson) { jpnl.setBackground(Color.white); JLabel field = new JLabel(); field.setHorizontalTextPosition(SwingConstants.CENTER); field.setText(((Lesson) s).getField().toString()); jpnl.add(field); if (! (wt.getOwner() instanceof Teacher)) { JLabel teach = new JLabel(((Lesson) s).getTeacher().getName()); teach.setHorizontalTextPosition(SwingConstants.RIGHT); jpnl.add(teach); } if (!(wt.getOwner() instanceof Group)) { JLabel group = new JLabel(((Lesson) s).getStudents().toString()); group.setHorizontalTextPosition(SwingConstants.LEFT); jpnl.add(group); } if (!(wt.getOwner() instanceof Classroom)) { JLabel place = new JLabel(((Lesson) s).getPlace().toString()); place.setHorizontalTextPosition(SwingConstants.CENTER); jpnl.add(place); } } days[s.getBegin().getDay()].add(jpnl); if (s.getEnd().getHour() == 12) { jpnl = new JPanel(); jpnl.setPreferredSize(new Dimension(dayWidth - 7, 120 * panelHeight / 690)); days[s.getBegin().getDay()].add(jpnl); } } /* for (int i = 0; i < days.length; i++) { if(i == 0) { JPanel empty = new JPanel(); empty.setPreferredSize(new Dimension(dayWidth - 7, 17)); days[i].add(empty); JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(dayWidth - 7, 97)); panel.setBackground(Color.white); panel.setBorder(BorderFactory.createLineBorder(Color.black, 1)); days[i].add(panel); JPanel panel2 = new JPanel(); panel2.setPreferredSize(new Dimension(dayWidth - 7, 47)); panel2.setBackground(Color.white); panel2.setBorder(BorderFactory.createLineBorder(Color.black, 1)); days[i].add(panel2); JPanel panel3 = new JPanel(); panel3.setPreferredSize(new Dimension(dayWidth - 7, 97)); panel3.setBackground(Color.white); panel3.setBorder(BorderFactory.createLineBorder(Color.black, 1)); days[i].add(panel3); JPanel panel4 = new JPanel(); panel4.setPreferredSize(new Dimension(dayWidth - 7, 97)); panel4.setBackground(Color.white); panel4.setBorder(BorderFactory.createLineBorder(Color.black, 1)); days[i].add(panel4); JPanel panel5 = new JPanel(); panel5.setPreferredSize(new Dimension(dayWidth - 7, 97)); panel5.setBackground(Color.white); panel5.setBorder(BorderFactory.createLineBorder(Color.black, 1)); days[i].add(panel5); } }*/ }
7
public static NuisanceFacilityEnumeration fromValue(String v) { for (NuisanceFacilityEnumeration c: NuisanceFacilityEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
public void putAll( Map<? extends Short, ? extends Character> map ) { Iterator<? extends Entry<? extends Short,? extends Character>> it = map.entrySet().iterator(); for ( int i = map.size(); i-- > 0; ) { Entry<? extends Short,? extends Character> e = it.next(); this.put( e.getKey(), e.getValue() ); } }
8
@Override public boolean equals(Object arg0) { if(arg0 instanceof TwoTuple) { TwoTuple<?, ?> tt = (TwoTuple<?, ?>)arg0; return first.equals(tt.first) && second.equals(tt.second); } return false; }
6
@Override public void mousePressed(MouseEvent e) { Bubble bubble = Main.flowChart.getBubbleAt(e.getX(), e.getY()); if(e.getButton() == MouseEvent.BUTTON3) { if(e.isShiftDown()) { if(bubble.isSelected()) { bubble.setSelected(false); } else bubble.setSelected(true); } else { Main.flowChart.setSelectedBubble(bubble); } Main.flowChart.repaint(); } if(bubble != null) { bubble.setMoving(true); } }
4
@Override public List<String> transactionLog() { if (txLog == null) txLog = new ArrayList<String>(); return txLog; }
1
@Override public String execute(SessionRequestContent request) throws ServletLogicException{ String page = ConfigurationManager.getProperty("path.page.registration"); resaveParamsRegistrUser(request); try { Criteria criteria = new Criteria(); criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE)); User currUser = (User) request.getSessionAttribute(JSP_CURRENT_USER); Validator.validateUser(currUser); criteria.addParam(DAO_USER_EMAIL, currUser.getEmail()); criteria.addParam(DAO_USER_PHONE, currUser.getPhone()); criteria.addParam(DAO_USER_LANGUAGE, currUser.getLanguage()); String login = request.getParameter(JSP_USER_LOGIN); Validator.validateLogin(login); criteria.addParam(DAO_USER_LOGIN, login); String password = request.getParameter(JSP_USER_PASSWORD); Validator.validatePassword(password); criteria.addParam(DAO_USER_PASSWORD, password.hashCode()); AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC); Integer res = userLogic.doRedactEntity(criteria); if (res == null) { request.setAttribute("errorLoginPassMessage", "message.errorLoginExist"); } else { page = null; } } catch (TechnicalException | LogicException ex) { request.setAttribute("errorSaveReason", ex.getMessage()); request.setAttribute("errorSave", "message.errorSaveData"); request.setSessionAttribute(JSP_PAGE, page); } return page; }
2
private String getOriginatingClass(Permission p) throws RecursivePermissionException { final Throwable t = new Throwable(); final StackTraceElement[] ste = t.getStackTrace(); for (StackTraceElement s : ste) { if (s.getClassName().contentEquals(thisClass) && s.getMethodName().contentEquals("getProductionDomain")) { throw new RecursivePermissionException(); } } return ste[ste.length - 1].getClassName(); }
3
@Override /** * @see IPlayer#endTrick(Pile, int) * * Store the cards won in the previous trick in their respective piles. If the declarer won the trick, * store the cards in the declarer's pile. If one of the defenders won the trick, store the cards * in the defenders' pile. From here we can easily calculate who is winning, by looking at the cards * in each pile. */ public void endTrick(Pile cardsPlayed,int whoWonIndex) { Card c; for(int i=0;i<3;i++) { c=cardsPlayed.getCard(i); if(whoWonIndex==declarerIndex) declarerCardsWon.addCard(c); else defenderCardsWon.addCard(c); } }
2
public void writeToFile(){ for(int row = 0; row < 4; row++) { for(int col = 0; col < 4; col++) { try { // System.out.println(String.format("%h", this.state[row][col])); String hex = String.format("%h", this.state[row][col]); if (hex.length() < 2) { hex = "0" + hex; } this.edWriter.write(hex); System.out.printf(hex + " "); this.edWriter.flush(); } catch (Exception e) { System.out.println("I seriously don't remember java being this annoying."); } } System.out.println(); } System.out.println(); try { this.edWriter.write('\n'); } catch (Exception e) { System.out.println("I seriously don't remember java being this annoying."); } }
5
public void createLevel(){ for (int i=0; i<Game.WIDTH-25;i += 25){ addOject(new Test(i,Game.HEIGHT-25,ObjectId.Test)); } }
1
public static void s( int a[], int n ){ int i, j,t=0; for(i = 0; i < n; i++){ for(j = 1; j < (n-i); j++){ if(a[j-1] > a[j]){ t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } }
3
private void copiarDiretorio(String origem, String destino) { File ficheiroOrigem = new File(origem); File ficheiroDestino = new File(destino); if (ficheiroOrigem.exists()) { if (ficheiroDestino.exists()) { if (ficheiroOrigem.isDirectory()) { // Verifica se o arquivo de origem eh mesmo um ficheiro if (ficheiroDestino.isDirectory()) { // verifica se o destino eh mesmo um diretorio // Cria um ficheiro com o mesmo nome no destino File copiaFicheiroDestino = new File(destino + File.separator + ficheiroOrigem.getName()); if (!copiaFicheiroDestino.exists()) { copiaFicheiroDestino.mkdir(); String[] conteudoOrigem = ficheiroOrigem.list(); for (int i = 0; i < conteudoOrigem.length; i++) { File arquivo = new File(copiaFicheiroDestino + File.separator + conteudoOrigem[i]); if (!arquivo.exists()) { try { arquivo.createNewFile(); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(viewPrincipal, "Problema com a criação de arquivo do método copiarArquivo." + ex); } } else { javax.swing.JOptionPane.showMessageDialog(viewPrincipal, "Já existe um arquivo com esse nome."); } progressBar(conteudoOrigem.length, i); } } else { javax.swing.JOptionPane.showMessageDialog(viewPrincipal, "Já existe um ficheiro com esse nome."); //deleteDir(copiaFicheiroDestino); //copiaFicheiroDestino.delete(); } } else { javax.swing.JOptionPane.showMessageDialog(null, "Você deve selecionar um ficheiro para copiar seu documento."); } } else { javax.swing.JOptionPane.showMessageDialog(null, "O arquivo passado não é um ficheiro."); } } else { javax.swing.JOptionPane.showMessageDialog(null, "O ficheiro destino não existe."); } } else { javax.swing.JOptionPane.showMessageDialog(null, "O ficheiro de origem não existe."); } }
8
public HashTable() { int i = 1024; size = i; cache = new Node[i]; for (int k = 0; k < i; k++) { Node node = cache[k] = new Node(); node.next = node; node.previous = node; } }
1
public Coordinate fromCartesian(Vector2D point) { int n = refPolygon.count(); Coordinate coordinate = new Coordinate(n * 2); double[] Psi = new double[n]; double[] Phi = new double[n]; for (int k = 0; k < n; k++) { int next = (k + 1) % n; Vector2D v1 = refPolygon.get(k); Vector2D v2 = refPolygon.get(next); Vector2D a = v2.minus(v1); Vector2D b = v1.minus(point); double Q = a.dot(a); double S = b.dot(b); double R = 2 * a.dot(b); double BA = b.dot(refPolygon.getOutwardNormal(k).times(a.length())); double SRT = Math.sqrt(4 * S * Q - R * R); double L0 = Math.log(S); double L1 = Math.log(S + Q + R); double A0 = Math.atan(R / SRT) / SRT; double A1 = Math.atan((2 * Q + R) / SRT) / SRT; double A10 = A1 - A0; double L10 = L1 - L0; Psi[k] = -a.length() / (4 * Math.PI) * ((4 * S - R * R / Q) * A10 + R / (2 * Q) * L10 + L1 - 2); Phi[next] = Phi[next] - BA / (2 * Math.PI) * (L10 / (2 * Q) - A10 * R / Q); Phi[k] = Phi[k] + BA / (2 * Math.PI) * (L10 / (2 * Q) - A10 * (2 + R / Q)); } double phiSum = 0; double psiSum = 0; for (int i = 0; i < n; i++) { phiSum = phiSum + Math.abs(Phi[i]); psiSum = psiSum + Psi[i]; } for (int i = 0; i < n; i++) { Phi[i] = (-1 * Phi[i]) * (1.0 / phiSum); } for (int i = 0; i < n; i++) { coordinate.setCoefficient(i, Phi[i]); coordinate.setCoefficient(n + i, Psi[i]); } return coordinate; }
4
@Override public void run() { ObjectInputStream in = client.getIn(); while(true){ if(stop) break; Object ob = null; try{ if((ob = in.readObject()) != null){ Message m = (Message)ob; processMessage(m); } }catch(Exception e){ e.printStackTrace(); } } }
4
@Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof StringBuilderFactoryFormatter)) { return false; } final StringBuilderFactoryFormatter other = (StringBuilderFactoryFormatter) obj; if (formatter == null) { if (other.formatter != null) { return false; } } else if (!formatter.equals(other.formatter)) { return false; } if (stringBuilderFactory == null) { if (other.stringBuilderFactory != null) { return false; } } else if (!stringBuilderFactory.equals(other.stringBuilderFactory)) { return false; } return true; }
9
public void play() { // Play the midi file if it is open, and if the squencer is not already // playing. if ( !isFileOpen ) { System.err.println("Cannot play. Midi file not loaded."); return; } if ( sequencer.isRunning() ){ System.err.println("Cannot play. Already playing."); return; } // Start the sequencer to start playing. sequencer.start(); } // End play()
2
public T1 getFoo1() { return foo1; }
0
public static ClassLoader compile(List<SourceFile> files) throws CompilationError { System.out.println("got here1"); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) throw new Error("Only JDK contains the JavaCompiler, you are running a Java JRE"); MyDiagnosticListener diagnisticListenerForErrors=new MyDiagnosticListener(); final HashMap<String,ClassFile> map=new HashMap<>(); final ClassLoader classLoader=new java.security.SecureClassLoader(model.AI.class.getClassLoader()) { @Override public Class<?> loadClass(String name)throws ClassNotFoundException { System.out.println("got here2"); return this.loadClass(name, false);} @Override public Class<?> loadClass(String name,boolean resolve)throws ClassNotFoundException { System.out.println("got here3"); if(!map.containsKey(name))return super.loadClass(name,resolve); //if(!map.containsKey(name))return cl.loadClass(name); ClassFile jclassObject = map.get(name); return super.defineClass(name, jclassObject.getBytes(), 0, jclassObject.getBytes().length); } }; final ForwardingJavaFileManager<StandardJavaFileManager> classFileManager= new ForwardingJavaFileManager<StandardJavaFileManager>(compiler.getStandardFileManager(diagnisticListenerForErrors,Locale.ENGLISH, null)){ @Override public ClassLoader getClassLoader(Location location) {return classLoader;} @Override public JavaFileObject getJavaFileForOutput(Location location,String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException{ ClassFile classFile=new ClassFile(className, kind); map.put(className, classFile); return classFile; } }; if(!compiler.getTask(/*out:*/null,classFileManager,diagnisticListenerForErrors, /*compilerOptions:*/new ArrayList<String>(Arrays.asList("-classpath", ".;C:\\Users/Simon/workspace3/Questions/build/classes")),/*StringsClasses??:*/null,files ).call() ){System.out.println(diagnisticListenerForErrors.diagnostic);throw new CompilationError(diagnisticListenerForErrors.diagnostic); } return classLoader; }
5
public int getFormat() { return format; }
0
public AnnotationVisitor visitArray(final String name) { buf.setLength(0); appendComa(valueNumber++); if (name != null) { buf.append(name).append('='); } buf.append('{'); text.add(buf.toString()); TraceAnnotationVisitor tav = createTraceAnnotationVisitor(); text.add(tav.getText()); text.add("}"); if (av != null) { tav.av = av.visitArray(name); } return tav; }
2
private final void skip() throws IOException { while (!mEOF && mPeek0 <= ' ') { read(); } }
2
public void update(Observable arg0, Object arg1) { // TODO Auto-generated method stub this.repaint(); }
0
public void updateLabels(BonusQuestion q) { if (q == null) { setLabelsNull(); return; } lblWeek.setText(""+q.getWeek()); lblNum.setText(""+q.getNumber()); lblType.setText(""+q.getBonusType()); lblQuestion.setText(""+q.getPrompt()); lblAnswer.setText(""+q.getAnswer()); if(q.getBonusType()==BonusQuestion.BONUS_TYPE.MULTI){ lblChoicesStr.setText("Choices: "); String[] choices = q.getChoices(); // build the string label StringBuilder sb = new StringBuilder(800); sb.append("<html>"); for(String c: choices){ if (c.equalsIgnoreCase(q.getAnswer())) sb.append("<i>" + c + "</i>, "); else sb.append(c + ", "); } sb.deleteCharAt(sb.lastIndexOf(",")); lblChoices.setText(sb.toString()); }else{ lblChoicesStr.setText(""); lblChoices.setText(""); } }
4
public void setMaxStack(final int maxStack) { if (code != null) { code.setMaxStack(maxStack); } }
1
public static String getCurrentTestId() { String currentTest = JMeterUtils.getPropDefault(Constants.CURRENT_TEST, ""); String currentTestId = null; if (!currentTest.isEmpty()) { currentTestId = currentTest.substring(0, currentTest.indexOf(";")); } else { currentTestId = ""; } return currentTestId; }
1
public static Person[] mergeInnerPerson(Person[] firstArr, Person[] secondArr) { if (firstArr == null || secondArr == null) { return new Person[]{}; } Person[] _firstArr = firstArr.clone(); Person[] _secondArr = secondArr.clone(); PersonComparator comparator = new PersonComparator(); Arrays.sort(_firstArr, comparator); Arrays.sort(_secondArr, comparator); Person[] innerUnion = null; int traceIndex = 0; int peersCounter = 0; for (Person elem : _firstArr) { int position = Arrays.binarySearch(_secondArr, elem, comparator); if (position >= 0) peersCounter++; } innerUnion = new Person[peersCounter]; for (Person elem : _firstArr) { int position = Arrays.binarySearch(_secondArr, elem, comparator); if (position >= 0) { innerUnion[traceIndex++] = _secondArr[position]; } } return innerUnion; }
6
@Override public Sample clone() { Sample cpy = new Sample(); cpy.x = new double[x.length]; for (int i = 0; i < x.length; i++) { cpy.x[i] = x[i]; } cpy.fx = fx; return cpy; }
1
public void setSourceText(String sourceText) { if( !sourceText.equals(AlchemyAPI_NamedEntityParams.CLEANED) && !sourceText.equals(AlchemyAPI_NamedEntityParams.CLEANED_OR_RAW) && !sourceText.equals(AlchemyAPI_NamedEntityParams.RAW) && !sourceText.equals(AlchemyAPI_NamedEntityParams.CQUERY) && !sourceText.equals(AlchemyAPI_NamedEntityParams.XPATH)) { throw new RuntimeException("Invalid setting " + sourceText + " for parameter sourceText"); } this.sourceText = sourceText; }
5
public void readNextButton() { if (buttonCombi1 == 1 && buttonCombi2 == 0) { } while (buttonCombi1 == 1 && buttonCombi2 == 0) { checkInput(); if ((System.currentTimeMillis() - timePressed) > 1000) { fastForwardSong = true; } } if ((System.currentTimeMillis() - timePressed) < 1000) { nextSong = true; } else { fastForwardSong = false; } }
6
public DatabaseHelper() { Properties properties = new Properties(); // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream is; try { is = new FileInputStream("xio.properties"); try { properties.load(is); is.close(); } catch (IOException ioe) { System.out.print(ioe.getMessage()); } catch (Exception e){ System.out.print(e.getMessage()); } VxConnectionString= properties.getProperty("VxConnectionString"); MxConnectionString= properties.getProperty("MxConnectionString"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }// this.getClass().getClassLoader().getResourceAsStream("com/personaxio/xio.properties"); // System.out.println(connectionString); }
3
public static void main(String[] args) { /** A Utility class. */ class ZipStatePair { String zip; String state; ZipStatePair(String zip, String state) { this.state = state; this.zip = zip; } } //create a list of mappings from zipcode to state LinkedList<ZipStatePair> pairs = new LinkedList<ZipStatePair>(); //read the ZIP to STATE map try { BufferedReader br = new BufferedReader(new FileReader("ZIP_CODES.txt")); StringTokenizer st; String line; line = br.readLine(); //read 1st line //a line consists of the following tokens //ZIPCODE STATE while (line != null) { st = new StringTokenizer(line); String trueZip = st.nextToken(); String state = st.nextToken(); pairs.addLast(new ZipStatePair(trueZip, state)); line = br.readLine(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } //get the list of zipcodes LinkedList<ZipcodeEntry> zipcodes = readInputFile(); //give each zipcode a state ZipStatePair[] array = pairs.toArray(new ZipStatePair[0]); for (ZipcodeEntry zip : zipcodes) { for (int i = 0; i < array.length; i++) { if (array[i].zip.equals(zip.realWorldZip)) { zip.state = array[i].state; } } } //write out the results StringBuffer output = new StringBuffer(); for (ZipcodeEntry zip : zipcodes) { output.append( zip.realWorldZip + "\t" + zip.population + "\t" + zip.y + "\t" + zip.x + "\t" + zip.state + "\n"); } try { FileUtility.writeToNewFile("withZipData.txt", output.toString()); } catch (Exception e) { e.printStackTrace(); } }
7
public SimpleStringProperty cityNameProperty() { return cityName; }
0
public BlackJackGame(Deck deck, PlayerHand player) { this.deck = deck; this.player = player; theHouse = new PlayerHand(); isPlayerOver = false; }
0
public final void listaDeInterfaces() throws RecognitionException { try { // fontes/g/CanecaSemantico.g:331:2: ( ^( INTERFACES_ ( tipo )* ) ) // fontes/g/CanecaSemantico.g:331:4: ^( INTERFACES_ ( tipo )* ) { match(input,INTERFACES_,FOLLOW_INTERFACES__in_listaDeInterfaces1089); if (state.failed) return ; if ( input.LA(1)==Token.DOWN ) { match(input, Token.DOWN, null); if (state.failed) return ; // fontes/g/CanecaSemantico.g:331:18: ( tipo )* loop19: do { int alt19=2; int LA19_0 = input.LA(1); if ( (LA19_0==TIPO_) ) { alt19=1; } switch (alt19) { case 1 : // fontes/g/CanecaSemantico.g:331:19: tipo { pushFollow(FOLLOW_tipo_in_listaDeInterfaces1092); tipo(); state._fsp--; if (state.failed) return ; } break; default : break loop19; } } while (true); match(input, Token.UP, null); if (state.failed) return ; } } } catch (RecognitionException erro) { throw erro; } finally { // do for sure before leaving } return ; }
9
public boolean isCurrentlyBorrowed(String materialID, Calendar startDate, Calendar endDate) { for (Loan l : this.unreturnedLoans) { if ((l.getStartDate().after(startDate) && l.getStartDate().before( endDate)) || (l.getEndDate().after(startDate) && l.getEndDate() .before(endDate)) && l.getListOfMaterials().contains(materialID)) { return true; } } return false; }
6
public void draw(GOut g) { g.image(lbl.tex(), new Coord(box.sz().x, box.sz().y - lbl.sz().y)); g.image(box, Coord.z); if (a) g.image(mark, Coord.z); super.draw(g); }
1
@Override public boolean onCommand(CommandSender sender, Command command, String CommandLabel, String[] args) { if (sender instanceof Player) { Player p = (Player) sender; if (args.length == 0) { //args 0 stuff MuddleUtils.outputDebug("Got command muddle"); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("new") && sender.hasPermission("muddle.admin")) { MuddleUtils.newMuddle(p); MuddleUtils.outputDebug("got command muddle new"); } if (args[0].equalsIgnoreCase("teleport") && sender.hasPermission("muddle.teleport.command")) { MuddleUtils.randomTeleport(p); MuddleUtils.outputDebug("Got command muddle teleport"); } } } else { sender.sendMessage(MuddlePort.prefix + "Silly console, muddles are for players!"); } return false; //To change body of implemented methods use File | Settings | File Templates. }
7
public HashMap<String, Level> lees() throws AngryTanksException{ HashMap<String, Level> levelMap = new HashMap<String, Level>(); ArrayList<File> levelFiles = new ArrayList<File>(); //bestanden vinden in folder File[] files = levelFolder.listFiles(); if(files == null) files = new File[0]; //bestanden selecteren for(File file : files){ if(file.isFile() && file.getName().length() > EXTENSIE.length() && file.getName().substring(file.getName().length()-EXTENSIE.length()).equals(EXTENSIE) && !file.getName().substring(0,1).equals(".")){ levelFiles.add(file); } } //bestanden uitlezen en toevoegen aan levelMap for(File file : levelFiles){ try{ String levelTitel = poetsNaam(file.getName()); String levelText = new Scanner(file).useDelimiter("\\A").next(); levelMap.put(levelTitel, decodeLevel(levelText)); } catch(IOException e){ throw new AngryTanksException("Bestand niet gevonden", e); } } return levelMap; }
8
public ModeleDeuxJoueurs(Modele plateau1, Modele plateau2) { this.plateau1 = plateau1; this.plateau2 = plateau2; }
0
public void moveCam(boolean forward) { switch (faceTo) { case 0: if (forward) { super.camera.translate(0, -1 * moveLen, 0); } else { super.camera.translate(0, moveLen, 0); } break; case 1: if (forward) { super.camera.translate(moveLen, 0, 0); } else { super.camera.translate(-1 * moveLen, 0, 0); } break; case 2: if (forward) { super.camera.translate(0, moveLen, 0); } else { super.camera.translate(0, -1 * moveLen, 0); } break; case 3: if (forward) { super.camera.translate(-1 * moveLen, 0, 0); } else { super.camera.translate(moveLen, 0, 0); } break; default: break; } super.camera.update(); super.update(); }
8
private static final byte[] encode3to4(final byte[] src, final int sOffset, final int numBytes, final byte[] dest, final int dOffset) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3F 0x3F 0x3F Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. final int inBuff = ( numBytes > 0 ? ((src[sOffset ] << 24) >>> 8) : 0) | (numBytes > 1 ? ((src[sOffset + 1] << 24) >>> 16) : 0) | (numBytes > 2 ? ((src[sOffset + 2] << 24) >>> 24) : 0); switch (numBytes) { case 3: dest[dOffset ] = ALPHABET[(inBuff >>> 18) ]; dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F]; dest[dOffset + 3] = ALPHABET[(inBuff ) & 0x3F]; break; case 2: dest[dOffset ] = ALPHABET[(inBuff >>> 18) ]; dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F]; dest[dOffset + 3] = EQUALS_SIGN; break; case 1: dest[dOffset ] = ALPHABET[(inBuff >>> 18) ]; dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F]; dest[dOffset + 2] = EQUALS_SIGN; dest[dOffset + 3] = EQUALS_SIGN; break; } return dest; }
6
@Override public SkillsMain [] getSkillNames() { return Constants.sorcererSkillSkills; }
0
public JPanel getBackgroundMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.backgroundMenu; }
1
@Override public boolean onMouseDown(int mX, int mY, int button) { if(button == 0 && mX > x && mX < x + width && mY > y && mY < y + height) { Application.get().getHumanView().popScreen(); return true; } return false; }
5
public void makeDeclaration(Set done) { super.makeDeclaration(done); if (subBlocks[0] instanceof InstructionBlock) /* * An instruction block may declare a variable for us. */ ((InstructionBlock) subBlocks[0]).checkDeclaration(this.declare); }
1
@Override public void setLabelText(String text) { this.labelText = text; }
0
private void btnGuncelleMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnGuncelleMousePressed if(!btnGuncelle.isEnabled()) return; HashMap<String, String> values = new HashMap<>(); values.put("ad", txtAd.getText().trim()); values.put("soyad", txtSoyad.getText().trim()); values.put("telefon", txtTelefon.getText().trim()); values.put("resimURL", ""); values.put("kullaniciAdi", txtKullaniciAdi.getText().trim()); values.put("sifre1", txtSifre.getText().trim()); values.put("sifre2", txtSifreTekrar.getText().trim()); values.put("kullanilanSure", txtKullanilanSure.getText().trim()); values.put("kalanSure", txtKalanSure.getText().trim()); values.put("borc", txtBorc.getText().trim()); values.put("indirim", txtIndirim.getText().trim()); values.put("bitisTarihYil", comboYil.getSelectedItem().toString()); values.put("bitisTarihAy", (comboAy.getSelectedIndex()) +""); values.put("bitisTarihGun", (comboGun.getSelectedItem().toString())); String ucretSecenek; if(radioStandar.isSelected()) ucretSecenek = MusteriC.UCRET_STANDART; else if(radioUcretsiz.isSelected()) ucretSecenek = MusteriC.UCRET_UCRETSIZ; else ucretSecenek = MusteriC.UCRET_UYE; values.put("ucuretSecenek", ucretSecenek); String odemeSekli; if(radioOnceden.isSelected()) odemeSekli = MusteriC.ODEME_ONCEDEN; else odemeSekli = MusteriC.ODEME_SONRADAN; values.put("odemeSekli", odemeSekli); Musteri m = mutlakkafe.MutlakKafe.mainCont.getMusteriCont().getMusteri(values); if(m != null){ boolean sonuc = mutlakkafe.MutlakKafe.mainCont.getMusteriCont().hesapBilgiGuncelle(m.getKulAdi(),m); if(sonuc) kilitle(); temizle(); } }//GEN-LAST:event_btnGuncelleMousePressed
6
@Override public boolean equals( final Object obj ) { if( this == obj ) { return true; } if( obj == null ) { return false; } if( getClass() != obj.getClass() ) { return false; } final Model other = (Model) obj; if( notes == null ) { if( other.notes != null ) { return false; } } else if( !notes.equals( other.notes ) ) { return false; } return true; }
6
public int getSeconds() { return (int) (up ? (System.currentTimeMillis() - (timeStarted + seconds * 1000)) * 1000 : ((timeStarted + seconds * 1000) - System.currentTimeMillis()) * 1000); }
1
@Override protected void actionPerformed(GuiButton var1) { if(var1.enabled) { if(var1.id == 2) { String var2 = this.getSaveName(this.selectedWorld); if(var2 != null) { this.deleting = true; StringTranslate var3 = StringTranslate.getInstance(); String var4 = var3.translateKey("selectWorld.deleteQuestion"); String var5 = "\'" + var2 + "\' " + var3.translateKey("selectWorld.deleteWarning"); String var6 = var3.translateKey("selectWorld.deleteButton"); String var7 = var3.translateKey("gui.cancel"); GuiYesNo var8 = new GuiYesNo(this, var4, var5, var6, var7, this.selectedWorld); this.mc.displayGuiScreen(var8); } } else if(var1.id == 1) { this.selectWorld(this.selectedWorld); } else if(var1.id == 3) { this.mc.displayGuiScreen(new GuiCreateWorld(this)); } else if(var1.id == 6) { this.mc.displayGuiScreen(new GuiRenameWorld(this, this.getSaveFileName(this.selectedWorld))); } else if(var1.id == 0) { this.mc.displayGuiScreen(this.parentScreen); } else { this.worldSlotContainer.actionPerformed(var1); } } }
7
private boolean isInFiel(ICard cardOne, ICard cardTwo, ICard cardThree) { this.counter = 0; for (ICard card : field.getCardsInField()) { if (card.comparTo(cardOne) || card.comparTo(cardTwo) || card.comparTo(cardThree)) { counter++; } } if (this.counter == NUMBEROFSETCARDS) { return true; } return false; }
5
public ArrayList<BotonFicha> addFichaTablero(int n,boolean fin,ArrayList<BotonFicha> lista){ MiSistema.turno = 0; if(fin){//Añade ficha en la ultima pocicion int k; if(Domino.listaTablero.size()==0){ k=0; }else{ k= Domino.listaTablero.get(Domino.listaTablero.size()-1).getNivel()+1; } Domino.listaTablero.add(lista.get(n)); Domino.listaTablero.get(Domino.listaTablero.size()-1).setNivel(k); }else{//Añade ficha en la primera posicion. int k; if(Domino.listaTablero.size()==0){ k=0; }else{ k = Domino.listaTablero.get(0).getNivel()-1; } Domino.listaTablero.add(0,lista.get(n)); Domino.listaTablero.get(0).setNivel(k); } lista.remove(n); Principal.tablero.repaint(); return lista; }
3
public static void main(String args[]) { try { System.out.println("Getting prices..."); List<String> tickers = new ArrayList<String>(); tickers.add("GOOG"); tickers.add("YHOO"); tickers.add("AAPL"); List<BigDecimal> prices = getPrices(tickers); for (int i = 0; i < prices.size(); i++) { System.out.println(prices.get(i)); } System.out.println(); System.out.println("Getting stock quotes with default attributes..."); List<String> quotes = getStockQuotes(tickers); for (int i = 0; i < quotes.size(); i++) { System.out.println(quotes.get(i)); } System.out.println(); List<String> attributes = new ArrayList<String>(); attributes.add("Name"); attributes.add("Ticker"); attributes.add("Bid"); attributes.add("Price"); System.out.println("Getting stock quotes with custom attributes..."); quotes = getStockQuotes(tickers, attributes); for (int i = 0; i < quotes.size(); i++) { System.out.println(quotes.get(i)); } } catch (Exception e) { e.printStackTrace(); } }
4
public void UpdateGameList() { lstGames.removeAll(); for(GameInfo i:gameList) { lstGames.add(i.toString()); } }
1
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof BFSState)) return false; BFSState other = (BFSState) obj; if (internalNode == null) { if (other.internalNode != null) return false; } else if (!internalNode.equals(other.internalNode)) return false; return true; }
6
public static void startGame(GameData gD, boolean isNew) { currentGame = gD; inGameManager = new InGameManager(); if(isNew) { Screen = "inGame"; gameRunning = true; } else { Screen = "inGame"; gameRunning = true; } }
1
public double evaluate() { /* Sum together all inputs. */ double sum = 0; for(Neuron key : dendrites.keySet()) { if(key == this) sum += dendrites.get(key)*_bias; else sum += dendrites.get(key); } return _function.evaluate(sum); }
2
@EventHandler(priority = EventPriority.MONITOR) public void onBlockDamage(BlockDamageEvent event) { if(plugin.isEnabled() == true){ Block block = event.getBlock(); Player player = event.getPlayer(); if(!event.isCancelled()) blockCheckQuest(player, block, "blockdamage", 1); } }
2
public boolean inside(Vector3 p) { return p.getX() > x0 && p.getX() < x1 && p.getY() > y0 && p.getY() < y1 && p.getZ() > z0 && p.getZ() < z1; }
5
@Override public String getDescription(Hero hero) { int boosts = SkillConfigManager.getUseSetting(hero, this, "rocket-boosts", 1, false); String base = String.format("Put on a rocket pack with %s boosts. Safe fall provided.", boosts); StringBuilder description = new StringBuilder( base ); //Additional descriptive-ness of skill settings int initCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN.node(), 0, false); int redCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE.node(), 0, false) * hero.getSkillLevel(this); int CD = (initCD - redCD) / 1000; if (CD > 0) { description.append( " CD:"+ CD + "s" ); } int initM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA.node(), 0, false); int redM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE.node(), 0, false)* hero.getSkillLevel(this); int manaUse = initM - redM; if (manaUse > 0) { description.append(" M:"+manaUse); } int initHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, false); int redHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0, true) * hero.getSkillLevel(this); int HPCost = initHP - redHP; if (HPCost > 0) { description.append(" HP:"+HPCost); } int initF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA.node(), 0, false); int redF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE.node(), 0, false) * hero.getSkillLevel(this); int foodCost = initF - redF; if (foodCost > 0) { description.append(" FP:"+foodCost); } int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY.node(), 0, false) / 1000; if (delay > 0) { description.append(" W:"+delay); } int exp = SkillConfigManager.getUseSetting(hero, this, Setting.EXP.node(), 0, false); if (exp > 0) { description.append(" XP:"+exp); } return description.toString(); }
6
public FireBall(TileMap tm, boolean right) { super(tm); facingRight = right; moveSpeed = 3.8; if(right) dx = moveSpeed; else dx = -moveSpeed; width = 30; height = 30; cwidth = 14; cheight = 14; // load sprites try { BufferedImage spritesheet = ImageIO.read( getClass().getResourceAsStream( "/Sprites/Player/fireball.gif" ) ); sprites = new BufferedImage[4]; for(int i = 0; i < sprites.length; i++) { sprites[i] = spritesheet.getSubimage( i * width, 0, width, height ); } hitSprites = new BufferedImage[3]; for(int i = 0; i < hitSprites.length; i++) { hitSprites[i] = spritesheet.getSubimage( i * width, height, width, height ); } animation = new Animation(); animation.setFrames(sprites); animation.setDelay(70); } catch(Exception e) { e.printStackTrace(); } }
4
public void avancer(int nbCases) { if(!enPrison) { int index = mm.indexOf(caseActuelle); if((index + nbCases) > 39) { try { mm.getCase(0).action(this, null); } catch (NoMoreMoneyException e) { e.printStackTrace(); } } setCaseActuelle(mm.getCase((index + nbCases)%40)); } }
3
@Autowired public QuestTableView(final Requests requests) { super("Zagadki"); questList = null; try { questList = requests.getAllQuests(); } catch (Exception e1) { JOptionPane.showMessageDialog(null, "Sprawdz polaczenie z internetem"); } setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(400, 200, 452, 361); setSize(new Dimension(400, 260)); Toolkit toolkt = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkt.getScreenSize(); this.setLocation(screenSize.width / 4, screenSize.height / 4); contentPane = new JPanel(); setLayout(new BorderLayout()); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); add(contentPane); deleteQuest = new JButton("Usun zagadke"); deleteQuest.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { requests.delete((String) tableModel.getValueAt(rowNum, 0), "/deleteQuest"); tableModel.removeRow(rowNum); } catch (Exception e) { e.printStackTrace(); } } }); deleteQuest.setBounds(257, 250, 164, 25); addTable(); addRowToTable(questList); downPanel = new JPanel(new FlowLayout()); downPanel.add(deleteQuest); contentPane.add(downPanel, BorderLayout.SOUTH); }
2
private void setStartGameState() { this.board[0][0] = blackRook; this.board[0][1] = blackKnight; this.board[0][2] = blackBishop; this.board[0][3] = blackQueen; this.board[0][4] = blackKing; this.board[0][5] = blackBishop; this.board[0][6] = blackKnight; this.board[0][7] = blackRook; this.board[1][0] = blackPawn; this.board[1][1] = blackPawn; this.board[1][2] = blackPawn; this.board[1][3] = blackPawn; this.board[1][4] = blackPawn; this.board[1][5] = blackPawn; this.board[1][6] = blackPawn; this.board[1][7] = blackPawn; this.board[7][0] = whiteRook; this.board[7][1] = whiteKnight; this.board[7][2] = whiteBishop; this.board[7][3] = whiteKing; this.board[7][4] = whiteQueen; this.board[7][5] = whiteBishop; this.board[7][6] = whiteKnight; this.board[7][7] = whiteRook; this.board[6][0] = whitePawn; this.board[6][1] = whitePawn; this.board[6][2] = whitePawn; this.board[6][3] = whitePawn; this.board[6][4] = whitePawn; this.board[6][5] = whitePawn; this.board[6][6] = whitePawn; this.board[6][7] = whitePawn; // Initialize all the other states as empty. // Even though Java will automatically set it to 0, this is here // just in case we ever change the representation of empty to // something else for (int i = 0; i < this.board.length; i++) { for (int j = 0; j < this.board[i].length; j++) { if (this.board[i][j] == 0) { this.board[i][j] = this.empty; } } } }
3
public Dimension getSize() { if (this.dim == null) { ObjectDefinition def = getDefinition(); if (def != null) { int lenx = orientation % 2 == 0 ? def.width : def.height; int leny = orientation % 2 == 0 ? def.height : def.width; this.dim = new Dimension(lenx, leny); } else { return new Dimension(1, 1); } } return this.dim; }
4
public CheckResultMessage checkL4(int day){ int r1 = get(17,5); int c1 = get(18,5); int r2 = get(27,5); int c2 = get(28,5); if(checkVersion(file).equals("2003")){ try { in = new FileInputStream(file); hWorkbook = new HSSFWorkbook(in); if(0!=getValue(r2+4, c2+day, 10).compareTo(getValue(r1+2+day, c1+1, 6))){ return error("支付机构汇总报表<" + fileName + ">本期接受现金形式的客户备付金金额 L4 = H02:" + day + "日错误"); } in.close(); } catch (Exception e) { } }else{ try { in = new FileInputStream(file); xWorkbook = new XSSFWorkbook(in); if(0!=getValue(r2+4, c2+day, 10).compareTo(getValue(r1+2+day, c1+1, 6))){ return error("支付机构汇总报表<" + fileName + ">本期接受现金形式的客户备付金金额 L4 = H02:" + day + "日错误"); } in.close(); } catch (Exception e) { } } return pass("支付机构汇总报表<" + fileName + ">本期接受现金形式的客户备付金金额 L4 = H02:" + day + "日错误"); }
5
@Override public Collection<?> changeSorting(int choice) { // TODO Auto-generated method stub Comparator<Questions> c=null; if(choice==1) c=new sortOnQuesRank(); else if(choice==2) c=new sortOnQuesVotes(); else ; Collections.sort(lst, c); return lst; }
3