text
stringlengths
14
410k
label
int32
0
9
public BackGround(final JFrame frame, final String imageName ){ Container panel = frame.getContentPane(); try { imageOrg = ImageIO.read(this.getClass().getResource("/Image/" + imageName)); image = imageOrg.getScaledInstance(panel.getWidth(), panel.getHeight(), Image.SCALE_SMOOTH); } catch (IOException ex) { ex.printStackTrace(); } /** * Using anonymous method to add a listener to the frame * which will be used to adjust the dimensions of the image * based on changes of the same to the frame. */ frame.addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { final int width = frame.getWidth(); final int height = frame.getHeight(); image = width > 0 && height > 0 ? imageOrg.getScaledInstance(width, height, Image.SCALE_SMOOTH) : imageOrg; frame.repaint(); } }); }//end ctor
3
static void llenar(LinkedList<int[]> r, Pieza p, int vAbajo){ int v=vAbajo,x=vAbajo; for(Pieza m=p;m!=null;m=m.piezas[(x+1)%4]){ r.add(new int[]{m.valor,v}); int i=0; if(m.piezas[(v+1)%4]!=null)for(;i<4;i++)if(m.piezas[(v+1)%4].piezas[i]==m)break; x=v; v=(i+1)%4; } v=vAbajo;x=vAbajo; for(Pieza m=p;m!=null;m=m.piezas[(x+3)%4]){ if(m!=p)r.addFirst(new int[]{m.valor,v}); int i=0; if(m.piezas[(v+3)%4]!=null)for(;i<4;i++)if(m.piezas[(v+3)%4].piezas[i]==m)break; x=v; v=(i+3)%4; } }
9
private void runStateMachine() { while(!tokenFoundFlag){ if(exitSMFlag) break; switch(nextState){ case 1: // letter letter(); break; case 2: symbol(); break; case 3: number(); break; case 4: otherChar(); break; } } }// end of "runStateMachine"
6
private static void validate(String input) throws Exception { if (input.length() > MAX_LENGTH) throw new Exception("word can be no longer than 30 characters"); Set<Character> set = new HashSet<Character>(); for (int i = 0; i < input.length(); i++) { set.add(input.charAt(i)); if (!Character.isLetter(input.charAt(i))) throw new Exception("Word can only has letters"); } if (set.size() > MAX_UNIQUE_CHARS) throw new Exception(String.format("word can not have more than %d unique characters", MAX_UNIQUE_CHARS)); }
4
public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; }
0
public static boolean isInRange(float num, float max, float min, boolean showError) { final boolean bool = false; if (num > max || num < min) if (showError) { final IllegalArgumentException as = new IllegalArgumentException("The Number Has to be more than " + max + " and less than " + min + "!"); as.printStackTrace(); exit(); } return bool; }
3
public void shootAt(Robot paramRobot, Point paramPoint) { Debug.println("shootAt(" + paramPoint + ")"); this.RobotsWereShootingAt.addElement(paramRobot); paramRobot.playSound("Robot-Angry"); if (!this.active) { Point localPoint1 = getPosition().getMapPoint(); localPoint1.translate(1, 1); getEnvironment().getShroud().setVisible(localPoint1, 1, true, true); Point localPoint2 = new Point(paramPoint.x - getPosition().x + 1, paramPoint.y - getPosition().y + 1); Debug.println(localPoint2); int i = (int)Math.rint(Math.atan2(-localPoint2.y, localPoint2.x) * 57.295779513082323D); if (i < 0) { i = 360 + i; } Debug.println("angle: " + i + ", distance: " + this.distance); i %= 180; this.distance = (1 + this.distance / 3); i = ANGLE_LOOKUP[i]; this.destOrientation = i; Debug.println("angle: " + i + ", distance: " + this.distance); if (this.missImages == null) { this.missImages = new Image[9]; for (int j = 0; j < 9; j++) this.missImages[j] = GameApplet.thisApplet.getImage( "com/templar/games/stormrunner/media/images/objects/cannon_miss/g_miss_0" + (j + 1) + ".gif"); } AnimationComponent localAnimationComponent = new AnimationComponent(); AnimationComponent[] arrayOfAnimationComponent = new AnimationComponent[1]; localAnimationComponent.setCells(this.missImages); localAnimationComponent.setSequence(missSequence, null, false); boolean[][] arrayOfBoolean = new boolean[3][3]; Mask localMask = new Mask(getEnvironment(), new Position(paramPoint.x - 1, paramPoint.y - 1, 0, 0), null, arrayOfBoolean, true); localMask.setLayer("miss anim"); localMask.setLayer("Robot Effects"); arrayOfAnimationComponent[0] = localAnimationComponent; localMask.setImages(arrayOfAnimationComponent); localMask.setVisible(false); getEnvironment().addObject(localMask); Debug.println("misses.put(" + paramPoint + "," + localMask + ")"); this.misses.put(paramPoint, localMask); this.active = true; this.shootPos = paramPoint; } }
4
private static void launchLoginPage() { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop() .browse(new URI( "https://www.freesound.org/apiv2/oauth2/logout_and_authorize/?client_id=608002b12fb0074895d5&response_type=code&state=xyz")); } catch (IOException e) { e.printStackTrace(); flagLogIn = true; } catch (URISyntaxException e) { e.printStackTrace(); flagLogIn = true; } } }
3
public static void drawPixels(int i, int j, int k, int l, int i1) { if(k < topX) { i1 -= topX - k; k = topX; } if(j < topY) { i -= topY - j; j = topY; } if(k + i1 > bottomX) i1 = bottomX - k; if(j + i > bottomY) i = bottomY - j; int k1 = width - i1; int l1 = k + j * width; for(int i2 = -i; i2 < 0; i2++) { for(int j2 = -i1; j2 < 0; j2++) pixels[l1++] = l; l1 += k1; } }
6
public void setId(int id) throws ErroValidacaoException { if(id >0) { this.id = id; } else { throw new ErroValidacaoException("O id não pode ser menor que 0 !"); } }
1
public static void validateMove() { if (!validMove) { System.out.println("Invalid Move! Try Again"); System.out.println(); } else { moves = moves + 1; points = points + 5; AchievementRatio = points / moves; } }
1
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof BoundaryBoxFilter)) return false; BoundaryBoxFilter other = (BoundaryBoxFilter) o; if (!this.fieldName.equals(other.fieldName) || this.includeLower != other.includeLower || this.includeUpper != other.includeUpper ) { return false; } if (this.lowerTerm != null ? !this.lowerTerm.equals(other.lowerTerm) : other.lowerTerm != null) return false; if (this.upperTerm != null ? !this.upperTerm.equals(other.upperTerm) : other.upperTerm != null) return false; return true; }
9
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(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CompareFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CompareFrame.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 CompareFrame().setVisible(true); } }); }
6
public int checkMouseCollision(Point clickedPoint) { double d0 = points.get(0).getDistanceTo(clickedPoint); if (d0 <= Constants.POINT_RADIUS) { return 0; } double d1 = points.get(1).getDistanceTo(clickedPoint); if (d1 <= Constants.POINT_RADIUS) { return 1; } double d2 = points.get(2).getDistanceTo(clickedPoint); if (d2 <= Constants.POINT_RADIUS) { return 2; } double d3 = points.get(3).getDistanceTo(clickedPoint); if (d3 <= Constants.POINT_RADIUS) { return 3; } return -1; }
4
public void update(double elapsed) { this.elapsed += elapsed; while (this.elapsed > MOVE_TIME_MILLS) { this.elapsed -= MOVE_TIME_MILLS; for (GameElement element : gameElements) { element.colides(schlange); } schlange.move(); } //check if there are catchable diamonds boolean catchableDias = false; for (Diamant dia : diamanten) { if (!dia.isCatched()) { catchableDias = true; } } if (!catchableDias) { for (GameListener listener : listeners) { listener.win(new GameEvent(schlange.getLength())); } } //check if game is lost if (!schlange.isAlive()) { for (GameListener listener : listeners) { listener.loose(new GameEvent(schlange.getLength())); } } //update fps fps = (int) (1000 / elapsed); }
8
public void validateEventStructure(String eventName, List<MMTFieldValueHeader> fieldValueElements) throws MMTInitializationException { if (this.getProtoConfig() == null) { throw new MMTInitializationException("Initialization Exception: getProtoConfig() returns null. A valid MMTRemoteProtocolConfig must be set."); } else { MMTEventConfig event = this.getProtoConfig().getEventByName(eventName); if (event == null) { throw new MMTInitializationException("Initialization Exception: Event name \"" + eventName + "\" is not registered. Each Event MUST be registered in order to be used."); } else { for (MMTFieldValueHeader fvh : fieldValueElements) { if (!event.isHeaderField(fvh.getHeaderField())) { throw new MMTInitializationException("Initialization Exception: Unkown header field \"" + fvh.getHeaderField() + "\" in event \"" + eventName + "\". All header fields MUST be configured."); } } List<String> requiredHeaderFields = event.getRequiredHeaderFields(); for (String requiredField : requiredHeaderFields) { boolean fieldExists = false; for (MMTFieldValueHeader fvh : fieldValueElements) { if (requiredField.equals(fvh.getHeaderField())) { fieldExists = true; break; } } if (!fieldExists) { throw new MMTInitializationException("Initialization Exception: required header field \"" + requiredField + "\" is missing in event \"" + eventName + "\". All required headers MUST be present."); } } } } }
8
public int[] rangeOfBST(TreeNode root) { int []result = {root.val,root.val}; if(root.left !=null){ int []range = rangeOfBST(root.left); if(range[0]<=range[1]&&range[1]<root.val){ result[0]=range[0]; } else { result[0] = 1;result[1] = -1; return result; } } if(root.right !=null){ int []range = rangeOfBST(root.right); if(range[0]<=range[1]&&range[0]>root.val){ result[1]=range[1]; } else { result[0] = 1;result[1] = -1; return result; } } return result; }
6
@Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (!(value instanceof TreeItem)) { setText(value.toString()); setBackground(isSelected ? _enabledSelectedBackground : _defaultBackground); setForeground(isSelected ? _enabledSelectedForeground : _defaultForeground); } else { TreeItem item = (TreeItem) value; sb.setLength(0); sb.append(item._treeName); sb.append(" ("); sb.append(item._volumeName); sb.append(")"); setText(sb.toString()); boolean enabled = item._selected ^ _supplySide; Color background = isSelected ? (enabled ? _enabledSelectedBackground : _disabledSelectedBackground) : (enabled ? _defaultBackground : _disabledBackground); Color foreground = isSelected ? (enabled ? _enabledSelectedForeground : _disabledSelectedForeground) : (enabled ? _defaultForeground : _disabledForeground); setBackground(background); setForeground(foreground); } return this; }
9
public void createGlobalItem(GroundItem i) { for (Player p : Server.playerHandler.players){ if(p != null) { Client person = (Client)p; if(person != null){ if(person.playerId != i.getItemController()) { if (!person.getItems().tradeable(i.getItemId()) && person.playerId != i.getItemController()) continue; if (person.distanceToPoint(i.getItemX(), i.getItemY()) <= 60) { person.getItems().createGroundItem(i.getItemId(), i.getItemX(), i.getItemY(), i.getItemAmount()); } } } } } }
7
public boolean tienePrevio(){ boolean resp = false; if(previo != null) resp = true; return resp; }
1
@Override public void moveCursor(int x, int y) { if(x < 0) x = 0; if(x >= size().getColumns()) x = size().getColumns() - 1; if(y < 0) y = 0; if(y >= size().getRows()) y = size().getRows() - 1; textPosition.setColumn(x); textPosition.setRow(y); refreshScreen(); }
4
private static int index(char c) { switch (c) { case '*': return 0; case 'S': return 1; case 'I': return 2; case 'V': return 3; case 'X': return 4; case 'L': return 5; case 'C': return 6; case 'D': return 7; case 'M': return 8; //case 'E': // return 7; } return -1; }
9
public void paintComponent(Graphics g){ super.paintComponent(g); g.clearRect(0, 0, getWidth(), getWidth()); int height = engine.area.length; /* if(height * cellSize >= this.getHeight()){ height = (int) Math.floor(this.getHeight()/cellSize); }*/ int width = engine.area[0].length; /* if(width * cellSize >= this.getWidth()){ width = (int)Math.floor( this.getWidth()/cellSize); }*/ if (cellSize>5){ for (int i=0;i<=width-x;i++){ g.drawLine(i*cellSize, 0, i*cellSize, (height-y)*cellSize); } for (int i=0;i<=height-y;i++){ g.drawLine(0, i*cellSize, (width-x)*cellSize, i*cellSize); } } for (int i=y;i<height;i++){ for (int j=x;j<width;j++){ if (engine.getArea()[i][j]){ painLiveCell(i-y, j-x, g); } } } }
6
public int getColumnCount() { return 3; }
0
public static void main(String[] args) { Scanner myScan = new Scanner(System.in); System.out.print("Veuillez entrez vos symptomes: "); String descripMaladie = myScan.nextLine().toUpperCase(); String msgDocteur; if (descripMaladie.contains("TOUSSE") && descripMaladie.contains("SANG")) { msgDocteur = "Tuberculose"; } else if (descripMaladie.contains("TOUSSE") && descripMaladie.contains("GORGE")) { msgDocteur = "Angine aigue"; } else if (descripMaladie.contains("GORGE")) { msgDocteur = "Angine"; } else if (descripMaladie.contains("TETE")) { msgDocteur = "Migraine"; } else if (descripMaladie.contains("FATIGUE")) { msgDocteur = "Besoin d'exercices"; } else if (descripMaladie.contains("TOUSSE")) { msgDocteur = "Toux sèche"; } else { msgDocteur = "Maladie inconnue"; } System.out.printf("Votre maladie: %s\n", msgDocteur); }
8
public boolean hasFlag (Integer id, Variables flag) { if (npcData.containsKey(id + ":flag")) { String[] flags = npcData.get(id + ":flag").split(","); for (Integer i = 0; flags.length > i; i++) { if (flags[i].equals(flag.toString())) return true; } } return false; }
3
public String toString() { if (nome != null) return nome.toString(); return id + ""; }
1
public void tick() { try { player.tick(); } catch (InterruptedException e) { e.printStackTrace(); } sun.tick(); wife.idle(); par.tick(); sad.tick(); /*The Bottom Bounding boxes */ //stop1 = new Rectangle(122, 725, 256, 40); stop2 = new Rectangle(350, 440, 256, 10); stop3 = new Rectangle(122, 718, 256, 10); stop4 = new Rectangle(122, 718, 256, 10); stop5 = new Rectangle(122, 718, 256, 10); stop6 = new Rectangle(122, 718, 256, 10); for (int i = 0; i < flyers.size(); i++) { Flying fly = (Flying)flyers.get(i); fly.tick(); } for (int i = 0; i < items.size(); i++) { Item it = (Item)items.get(i); it.tick(); } if(tickCount2 == DELAY){ tickCount2 = 0; } if(timeLeft <= 0){ timeLeft = 0; } if(tickCount3 >= 100 && timerStarted){ tickCount3 = 0; timeLeft--; } if(tickCount == 1000){ tickCount = 0; tickChunk += 1; System.out.println(tickChunk); } tickCount3++; tickCount2++; tickCount++; }
8
private void animate() { if (startGameImage.contains(currentMouseX, currentMouseY)) { animationIsRunning = true; if (levelSelectAnimation != null) { remove(levelSelectAnimation); } if (levelEditorAnimation != null) { remove(levelEditorAnimation); } startGameAnimation = new RingAnimation(startGameImage.getHeight(), startGameImage.getHeight()); add(startGameAnimation, startGameImage.getX() - (startGameImage.getHeight() / 2.0), startGameImage.getY() + (startGameImage.getHeight() / 2.0)); } else if (levelSelectImage.contains(currentMouseX, currentMouseY)) { animationIsRunning = true; if (startGameAnimation != null) { remove(startGameAnimation); } if (levelEditorAnimation != null) { remove(levelEditorAnimation); } levelSelectAnimation = new RingAnimation( levelSelectImage.getHeight(), levelSelectImage.getHeight()); add(levelSelectAnimation, levelSelectImage.getX() - (levelSelectImage.getHeight() / 2.0), levelSelectImage.getY() + (levelSelectImage.getHeight() / 2.0)); } else if (levelEditorImage.contains(currentMouseX, currentMouseY)) { animationIsRunning = true; if (startGameAnimation != null) { remove(startGameAnimation); } if (levelSelectAnimation != null) { remove(levelSelectAnimation); } levelEditorAnimation = new RingAnimation( levelEditorImage.getHeight(), levelEditorImage.getHeight()); add(levelEditorAnimation, levelEditorImage.getX() - (levelEditorImage.getHeight() / 2.0), levelEditorImage.getY() + (levelEditorImage.getHeight() / 2.0)); } }
9
public boolean addFrame(BufferedImage im) { if ((im == null) || !started) { return false; } boolean ok = true; try { if (!sizeSet) { // use first frame's size setSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptior writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; } catch (IOException e) { ok = false; } return ok; }
7
public int buildAndStartNewPipelineFromGson(GsonNewPipelineRequest request) { LatLong boundingBoxNW = new LatLong(request.NWlat, request.NWlong); LatLong boundingBoxSE = new LatLong(request.SElat, request.SElong); GeoParams geoParams = new GeoParams(request.resolutionX, request.resolutionY, boundingBoxNW, boundingBoxSE); AuthFields authFields = new AuthFields( request.oauthAccessToken, request.oauthAccessTokenSecret, request.oauthConsumerKey, request.oauthConsumerKeySecret); WrapperParams wrapperParams = new WrapperParams(request.source, request.theme); WrapperFactory.WrapperType type = WrapperFactory.WrapperType.valueOf(request.wrapperType); AbstractDataWrapper tw = WrapperFactory.getWrapperInstance(type, wrapperParams, authFields, geoParams); PointStream ps = new PointStream(tw, request.pointPollingTimeMS); EmageBuilder eb = new EmageBuilder(ps, EmageBuilder.Operator.valueOf(request.operatorType)); EmageStream es = new EmageStream(eb, request.emageCreationRateMS, request.emageWindowLength); //Add the pipeline to our collection by it's index so we can reaccess it final DataPipeline p = new DataPipeline(ps, es); this.dataPipelines.put(p.pipelineID, p); //Create the threads and Start the streams Thread pointThread = new Thread(new Runnable(){ @Override public void run() { while (true) { p.pointStream.getNextPoint(); } } }); Thread emageThread = new Thread(new Runnable(){ @Override public void run() { while (true) { Emage emage = p.emageStream.getNextEmage(); try { Logger.log(emage.toString()); } catch (IOException e) { } System.out.println(emage); } } }); pointThread.start(); emageThread.start(); return p.pipelineID; }
3
public void pickupItems(int numberOfItems, float maxDistance) throws IOException { int itemsPicked = 0; long startDeadlockCheck = System.currentTimeMillis(); do { float[] itemAgentIdAndDistance = this.getNearestItemToAgentEx(-2); long currentlyElapsedTime = System.currentTimeMillis() - startDeadlockCheck; if (itemAgentIdAndDistance[0] == 0 || itemAgentIdAndDistance[1] > maxDistance || currentlyElapsedTime > 30000) { break; } boolean itemStillExists = true; do { //FIXME: why pickup item twice?? this.pickupItem((int) itemAgentIdAndDistance[0]); try { //FIXMR: why is there a sleep needed? Thread.sleep(500); } catch (InterruptedException ex) { // ignore } itemStillExists = this.getAgentExists((int) itemAgentIdAndDistance[0]); long startDeadlockCheck2 = System.currentTimeMillis(); long currentlyElapsedTime2 = System.currentTimeMillis() - startDeadlockCheck2; if (currentlyElapsedTime2 > 5000) { // try the next item break; } } while (itemStillExists); itemsPicked++; } while (itemsPicked != numberOfItems); }
7
public boolean equals(Spire s) { if ((s.getX() == this.x) && (s.getY() == this.y) && (s.getZ() == this.z) && (s.getXs() == this.xs) && (s.getYs() == this.y) && (s.getZs() == this.zs)) { return true; } return false; }
6
public boolean isAnimating() { return animating; }
0
public static List<Word> parseWords(String sentence) { List<Word> words = new ArrayList<>(); String[] strings = sentence.split("\\s+"); for (String string : strings) { words.add(new Word(string)); } return words; }
1
protected void search(String fileName){ startOutput(fileName); while(!cobweb.getUnsearchQueue().isEmpty()){ final WebPage wp = cobweb.peekUnsearchQueue();// 查找列隊 if (!cobweb.isSearched(wp.getUrl())) { try { leavesContentFileWriter.write(CrawlResultFormat.webPageHead(wp)); leavesContentFileWriter.write(WebPageParser.toPureHtml(wp)); leavesContentFileWriter.write(CrawlResultFormat.webPageTail()); } catch (Exception e) { e.printStackTrace(); } } } closeOutput(); }
3
private void locateNext() { hasNext = true; pos += value.length(); int i = -1; int iOr = lowered.indexOf("or", pos); int iAnd = lowered.indexOf("and", pos); if (iOr != -1 && iAnd != -1) i = iOr < iAnd ? iOr : iAnd; else if (iOr != -1) i = iOr; else if (iAnd != -1) i = iAnd; if (i == -1) { hasNext = pos < where.length(); value = where.substring(pos); return; } else if (i == pos) { value = i == iOr ? "or" : "and"; hasNext = true; return; } value = where.substring(pos, i); if (value.trim().length() == 0) { locateNext(); } }
9
public static TriCubicSpline[] oneDarray(int nP, int mP, int lP, int kP){ if(mP<3 || lP<3 || kP<3)throw new IllegalArgumentException("A minimum of three x three x three data points is needed"); TriCubicSpline[] a = new TriCubicSpline[nP]; for(int i=0; i<nP; i++){ a[i]=TriCubicSpline.zero(mP, lP, kP); } return a; }
4
public static double NeedlemanWunsch(String mSeqA, String mSeqB) { final int L1 = mSeqA.length(); final int L2 = mSeqB.length(); int[][] matrix = new int[L1 + 1][L2 + 1]; for (int i = 0; i < L1 + 1; i++) matrix[i][0] = -1 * i; for (int j = 0; j < L2 + 1; j++) matrix[0][j] = -1 * j; for (int i = 1; i < L1 + 1; i++) { for (int j = 1; j < L2 + 1; j++) { int penalty = matrix[i - 1][j - 1] + ((mSeqA.charAt(i - 1) == mSeqB.charAt(j - 1)) ? 1 : -1); matrix[i][j] = Math.max(Math.max(penalty, matrix[i][j - 1] - 1), matrix[i - 1][j] - 1); } } return ((double) (matrix[L1][L2] / Math.max(mSeqA.length(), mSeqB.length()))); }
5
@Before public void setUp() { }
0
public static void printToConsole(String text) { for (String line : text.split("\n")) { log.info(line); } }
1
public void followingItem(Item I) { if(I.container()!=null) I.setContainer(null); final Room R=CMLib.map().roomLocation(I); if(R==null) return; if(R!=lastOwner.location()) lastOwner.location().moveItemTo(I,ItemPossessor.Expire.Never,ItemPossessor.Move.Followers); if((inventory)&&(R.isInhabitant(lastOwner))) { CMLib.commands().postGet(lastOwner,null,I,true); if(!lastOwner.isMine(I)) { lastOwner.moveItemTo(I); if(lastOwner.location()!=null) lastOwner.location().recoverRoomStats(); } } }
7
private void AddbtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddbtnActionPerformed int Fi = Table.getSelectedRow(); if (Fi < 0) { String Mensaje = "Elija Un Producto Antes de Continuar," + "o elija menos de dos productos"; JOptionPane.showMessageDialog(null, Mensaje, "", JOptionPane.ERROR_MESSAGE); } else { String id = String.valueOf(Table.getValueAt(Fi, 0)); String nam = String.valueOf(Table.getValueAt(Fi, 1)); String descri = String.valueOf(Table.getValueAt(Fi, 2)); String preci = String.valueOf(Table.getValueAt(Fi, 3)); String cost = String.valueOf(Table.getValueAt(Fi, 4)); String cantidad = String.valueOf(Table.getValueAt(Fi, 5)); int n = Integer.parseInt(id); try { it = dao.findByID(n); } catch (IOException ex) { Logger.getLogger(RemoveTableFrame.class.getName()).log(Level.SEVERE, null, ex); } int i = it.getId(); String name = it.getName(); String desc = it.getDescripcion(); String costo = it.getCosto(); String precio = it.getPrecio(); String cant = it.getCantidad(); String Mensaje = " Producto Seleccionado\n" + "Id: " + id + "\n" + "Nombre: " + nam + "\n" + "Descripcion: " + descri + "\n" + "Costo: " + cost + "\n" + "Precio :" + preci + "\n" + "Cantidad :" + cantidad; String valor = JOptionPane.showInputDialog(null, Mensaje, "Inventario", JOptionPane.INFORMATION_MESSAGE); if (!(valor == null || valor == "")) { int x = Integer.parseInt(cant); int y = Integer.parseInt(valor); if (y > x) { JOptionPane.showMessageDialog(this, "El valor de unidades es menor al " + "disponible", "Inventario", JOptionPane.WARNING_MESSAGE); } else { int can = x - y; String nc = String.valueOf(can); it.setId(i); it.setName(name); it.setDescripcion(desc); it.setCosto(costo); it.setPrecio(precio); it.setCantidad(nc); try { dao.update(it); } catch (IOException ex) { } Mensaje = "Se han eliminado las unidades del Producto Seleccionado"; JOptionPane.showMessageDialog(null, Mensaje, "Invetario", JOptionPane.INFORMATION_MESSAGE); try { setClosed(true); } catch (PropertyVetoException ex) { Logger.getLogger(RemoveTableFrame.class.getName()).log(Level.SEVERE, null, ex); } } } else { JOptionPane.showMessageDialog(null, "Debe agregar una cantidad", "Inventario", JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_AddbtnActionPerformed
7
private void checkShowWelcomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkShowWelcomeActionPerformed File config = DFAMainWin.getConfigFile(); if(checkShowWelcome.isSelected()) { if(config.exists()) { //delete if(!config.delete()) { System.err.println("Could not delete config file properly."); } else { dFAMainWin.setShowWelcomeWindow(true); } } } else { if(!config.exists()) { try { config.createNewFile(); dFAMainWin.setShowWelcomeWindow(false); } catch (IOException ex) { ex.printStackTrace(); } } } }//GEN-LAST:event_checkShowWelcomeActionPerformed
5
public String worstQuestion() { if(questionStats.size() > 0) { QuestionStatistic min = Collections.min(questionStats); return min.questionText + ", " + min.correctAnswers + " times."; } return "no statistics found!"; }
1
public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (c == 0) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } }
6
public final void write(DataOutputStream out) throws IOException { _debug.fine("Anmeldelistentelegramm versenden: ", this); out.writeShort(length); out.writeBoolean(delta); out.writeLong(transmitterId); if(objectsToAdd == null) { out.writeShort(0); } else { out.writeShort(objectsToAdd.length); for(int i = 0; i < objectsToAdd.length; ++i) { out.writeLong(objectsToAdd[i]); } } if(objectsToRemove == null) { out.writeShort(0); } else { out.writeShort(objectsToRemove.length); for(int i = 0; i < objectsToRemove.length; ++i) { out.writeLong(objectsToRemove[i]); } } if(attributeGroupAspectsToAdd == null) { out.writeShort(0); } else { out.writeShort(attributeGroupAspectsToAdd.length); for(int i = 0; i < attributeGroupAspectsToAdd.length; ++i) { attributeGroupAspectsToAdd[i].write(out); } } if(attributeGroupAspectsToRemove == null) { out.writeShort(0); } else { out.writeShort(attributeGroupAspectsToRemove.length); for(int i = 0; i < attributeGroupAspectsToRemove.length; ++i) { attributeGroupAspectsToRemove[i].write(out); } } }
8
public static void cleanDirectory(final File directory) throws IOException { if (!directory.exists()) { final String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { final String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } final File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list content of " + directory); } IOException exception = null; for (final File file : files) { try { forceDelete(file); } catch (final IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } }
6
public Sequence getSubsequence(Nucleotide aStartNucleotide, Nucleotide anEndNucleotide) throws NonConsecutiveNucleotideException { if (!this.containsNucleotide(aStartNucleotide) || !this.containsNucleotide(anEndNucleotide)) { return null; } if(aStartNucleotide.compareTo(anEndNucleotide) == -1 ){ return null; } boolean addToSubSequence = false; Set<Nucleotide> returnMe = new LinkedHashSet<Nucleotide>(); for (Nucleotide nucleotide : this.getNucleotides()) { if (addToSubSequence && nucleotide.equals(anEndNucleotide)) { returnMe.add(nucleotide); addToSubSequence = false; break; } else if (addToSubSequence) { returnMe.add(nucleotide); } else if (nucleotide.equals(aStartNucleotide)) { returnMe.add(nucleotide); addToSubSequence = true; } } if (addToSubSequence) { return null; } return new Sequence(returnMe); }
9
public void init(int nplayers, int[] pref) { this.preferences = pref.clone(); this.id = this.getIndex(); this.players = nplayers; this.maxBowls[0] = this.players - this.id; this.maxBowls[1] = this.id + 1; //System.out.println("Player ID: " + this.id); //System.out.println("Max bowls can be seen: Round 0: " + this.maxBowls[0]); //System.out.println("Max bowls can be seen: Round 1: " + this.maxBowls[1]); this.start[0] = 0; this.start[1] = maxBowls[0] - 1; this.len[0] = 0; this.len[1] = 1; //strategy 2: optimal stopping, 0: build distribution 1: optimal round 0 int y=10; x=4; if(maxBowls[0]>y) strategy = 0; else if((maxBowls[1]+maxBowls[0]<y) && maxBowls[0] < x) strategy = 2; else strategy = 1; }
3
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
@Override public void Insertar(Object value) { Session session = null; try { Ejecutivo ejecutivo = (Ejecutivo) value; session = NewHibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(ejecutivo); } catch (HibernateException e) { System.out.println(e.getMessage()); session.getTransaction().rollback(); } finally { if (session != null) { // session.close(); } } }
2
public boolean addSkillXP(int amount, int skill){ if (c.expLock) { return false; } if (amount+c.playerXP[skill] < 0 || c.playerXP[skill] > 200000000) { if(c.playerXP[skill] > 200000000) { c.playerXP[skill] = 200000000; } return false; } amount *= Config.SERVER_EXP_BONUS; int oldLevel = getLevelForXP(c.playerXP[skill]); c.playerXP[skill] += amount; if (oldLevel < getLevelForXP(c.playerXP[skill])) { if (c.playerLevel[skill] < c.getLevelForXP(c.playerXP[skill]) && skill != 3 && skill != 5) c.playerLevel[skill] = c.getLevelForXP(c.playerXP[skill]); levelUp(skill); handleLevelUpGfx(); requestUpdates(); } setSkillLevel(skill, c.playerLevel[skill], c.playerXP[skill]); refreshSkill(skill); return true; }
8
public static boolean pointIsWithinSectorAngleBoundries(Point2D.Double p, Point2D.Double origo, double angle1, double angle2) { // System.out.println("Point: "+p.getX()+"-"+p.getY()); // System.out.println("Heuristic origo: "+origo.getX()+"-"+origo.getY()); // System.out.println("Vector: "+angle1+ "===== sector: "+angle2); Line2D.Double vectorToP = new Line2D.Double(origo, p); double vectorToPAngle = Math.toDegrees(angle(vectorToP)); if(angle2 > 360 && vectorToPAngle >= 0.0 && vectorToPAngle <= (angle2-360)) { vectorToPAngle += 360; } if(vectorToPAngle >= angle1 && vectorToPAngle <= angle2) { return true; } else { return false; } }
5
@Test public void EnsureLeadingAndTrailingSlashIsRemoved() { String path = "/x/y/"; String newpath = Path.trimSlashes(path); assertEquals("x/y", newpath); }
0
public int getCoordonneeY() { return y; }
0
public void write(Writer out) throws IOException { out.write(HEADER); Object[] sumval = {result, totalTime, numTestTotal, numTestPasses, numTestFailures, numCommandPasses, numCommandFailures, numCommandErrors, seleniumVersion, seleniumRevision, userAgent, suite.getUpdatedSuite()}; out.write(MessageFormat.format(SUMMARY_HTML, sumval)); // Display storedVars in a table if (giVersion != null) { out.write("<table id=\"gitak_vars\"><tr><td>GI Version:</td><td>" + giVersion + "</td></tr>"); } else { out.write("<table>"); } if (storedVars != null) { String[] vars = storedVars.split(","); if (vars.length > 0) for (String var : vars) { String[] nv = var.split("::"); if (nv.length > 1) { String value = escapeXML(nv[1]) + " "; out.write("<tr><td>" + nv[0] + "</td><td>" + value + "</td></tr>"); } } } out.write("</table>"); // End storedvars table for (int i = 0; i < testTables.size(); i++) { String table = testTables.get(i).replace("\u00a0", "&nbsp;"); Object[] val= {suite.getSuiteTitle()+"-"+suite.getCaseName(i), suite.getHref(i), table}; out.write(MessageFormat.format(SUITE_HTML, val)); } out.write("</table><pre>\n"); if (log != null) { out.write(quoteCharacters(log)); } out.write("</pre></body></html>"); out.flush(); }
7
public java.io.Serializable readAutomaton(Node parent, Document document) { Set locatedStates = new java.util.HashSet(); Automaton root = createEmptyAutomaton(document); if(parent == null) return root; readBlocks(parent, root, locatedStates, document); // Read the states and transitions. readTransitions(parent, root, readStates(parent, root, locatedStates, document)); //read the notes readnotes(parent, root, document); // Do the layout if necessary. performLayout(root, locatedStates); automatonMap.put(parent.getNodeName(), root); return root; }
1
private static void input(String[] args) throws Exception { // argument checking if (args.length > 0) { if (args[0].equals("-h")) { System.out.println("**HELP MENU**"); System.out.println("tf2mapgen <filename>"); System.out.println("output is saved as tf2mapgenfile.vmf"); System.out.println("For use, see README"); throw new Exception("Help menu exit"); } else if (args.length > 2 && args[1].equals("-o")) { loadPath = args[0]; generatedFilename = args[2]; } else { loadPath = args[0]; generatedFilename = loadPath.substring(loadPath.lastIndexOf("\\") + 1, loadPath.lastIndexOf(".")); } } else { System.out.println("No build-file given, -h for help."); throw new Exception("No build-file given."); } //Let'initKill take a look at that file then try { reader = new Scanner(new File(loadPath)); } catch (FileNotFoundException e) { throw new FileNotFoundException("\nNo file found at " + loadPath + "\n" + e); } }
5
public boolean hasCoupPossible() { for (Case caseDame : tablier.getAllCase()) { if((!tablier.isDameDansCaseBarre(joueurEnCour) && caseDame.getCouleurDame() == joueurEnCour) || caseDame.isCaseBarre()) for (DeSixFaces de : deSixFaces) { if(!de.isUtilise()) if(isCoupPossible(caseDame,tablier.getCaseADistance(caseDame, de))) return true; } } return false; }
7
@Override public synchronized void writeCreditTransactionToFile(Transaction transaction) { if (creditCounter % BATCH_SIZE == 0 && creditCounter > 0) { String newCreditFileName = this.reportDao.getCurrentFileName(TransactionType.CREDIT.toString(), creditFileName); if (!newCreditFileName.equalsIgnoreCase(creditFileName)) { try { flushAndCloseFile(creditFileOut); } catch (IOException e) { e.printStackTrace(); } creditFileOut = createOutFile(newCreditFileName); } } try { this.writeToFile(transaction, this.creditFileOut); creditCounter++; } catch (IOException e) { logger.warn("Could not write credit transaction : " + e.getMessage()); this.writeDeadLetterTransactionToFile(transaction); } }
5
public static void call(final String data) throws Exception { // delimited by a comma // text qualified by double quotes // ignore first record final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new File(data), ',', '\"'); final DataSet ds = pzparser.parse(); final String[] colNames = ds.getColumns(); while (ds.next()) { for (final String colName : colNames) { System.out.println("COLUMN NAME: " + colName + " VALUE: " + ds.getString(colName)); } System.out.println("==========================================================================="); } if (ds.getErrors() != null && !ds.getErrors().isEmpty()) { System.out.println("FOUND ERRORS IN FILE"); } }
4
@Override public void run(String arg) { int numImages = WindowManager.getImageCount(); if( numImages == 0 ) { IJ.error( "Geodesic reconstruction 3D", "At least one image needs to be open to run Geodesic reconstruction in 3D" ); return; } String[] names = new String[ numImages ]; for (int i = 0; i < numImages; i++) names[ i ] = WindowManager.getImage(i + 1).getShortTitle(); GenericDialog gd = new GenericDialog("Geodesic reconstruction 3D"); if( maskIndex >= numImages) maskIndex = 0; if( markerIndex >= numImages) markerIndex = 0; gd.addChoice( "Marker", names, names[ markerIndex ] ); gd.addChoice( "Mask", names, names[ maskIndex ] ); String[] operations = new String[]{ "reconstruction by dilation" }; gd.addChoice( "Geodesic operation", operations, operations[ operationIndex ] ); gd.showDialog(); if ( gd.wasOKed() ) { markerIndex = gd.getNextChoiceIndex(); maskIndex = gd.getNextChoiceIndex(); operationIndex = gd.getNextChoiceIndex(); final ImagePlus marker = WindowManager.getImage( markerIndex + 1 ); final ImagePlus mask = WindowManager.getImage( maskIndex + 1 ); if( null == marker || null == mask ) { IJ.error( "Geodesic reconstruction 3D", "Error when opening input images" ); return; } GeodesicReconstruction gr = new GeodesicReconstruction( marker, mask ); ImagePlus output = null; final long start = System.currentTimeMillis(); switch( operationIndex ) { case 0: output = gr.reconstructionByDilationHybrid(); break; default: } if ( null != output ) output.show(); final long end = System.currentTimeMillis(); IJ.log("Geodesic operation took " + (end-start) + " ms."); } }
9
public static void castVote(VoteCast vote){ if(vote == VoteCast.A) A+=1; else if(vote == VoteCast.B) B+=1; else if(vote == VoteCast.R) R+=1; updatePlayerReadout(); }
3
private void btnExcelExportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcelExportActionPerformed String input = Utils.showFileChooser("Opslaan", "Rooster"); if (!input.isEmpty()) { boolean inverted = Utils.promptQuestion("Wilt u de tabel omgedraaid of precies zoals hierboven?", false, "Zoals hierboven", "Omgedraaid"); ExcelExporter.Export(tblSchedule, new File(input.contains(".xls") ? input : input + ".xls"), inverted); } }//GEN-LAST:event_btnExcelExportActionPerformed
2
public void personDetailsForm() { super.personDetailsForm(); vatNumber = null; contactName = null; // Contact name if (!contactNameField.getText().equals("")) { contactName = contactNameField.getText(); contactNameLabel.setForeground(Color.black); } else { errorMessage = errorMessage + "Contact name field cannot be empty!\n"; contactNameLabel.setForeground(Color.red); } // Vat number if (!vatNumberField.getText().equals("")) { vatNumber = vatNumberField.getText(); vatNumberLabel.setForeground(Color.black); } else { errorMessage = errorMessage + "VAT number field cannot be empty!\n"; vatNumberLabel.setForeground(Color.red); } // Execute if anything has been entered into any field if (name != null && address != null && email != null && contactNumber != null && vatNumber != null && contactName != null) { // Specific handler for edit mode if (editMode) { driver.getPersonDB().changePersonDetails(person, name, email, contactNumber, address, 0, null, vatNumber, contactName); setTextField(getIndex(driver.getPersonDB().getSupplierList()), driver.getPersonDB() .getSupplierList()); valid = true; } // Handler for new supplier mode else { valid = true; driver.getPersonDB().createNewPerson(person, name, email, contactNumber, address, 0, null, contactName, vatNumber); setTextField(driver.getPersonDB().getSupplierList().size() - 1, driver .getPersonDB().getSupplierList()); } // Enable buttons deletePersonButton.setEnabled(true); editPersonButton.setEnabled(true); newPersonButton.setEnabled(true); // Set the visibility of buttons newPersonButton.setVisible(true); editPersonButton.setVisible(true); submitButton.setVisible(false); cancelEditButton.setVisible(false); } // Print an error message if errors exist else { JOptionPane.showMessageDialog(null, "" + errorMessage); } revalidate(); repaint(); }
9
public void removeTask(int taskEntID) { Task toRemove = null; synchronized (tasks) { for (Task t : tasks) { if (t.getEntityID() == taskEntID) { System.out.println("TASK TO REMOVE FOUND"); toRemove = t; } } if (toRemove != null) { tasks.remove(toRemove); } } }
3
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, o, null); } return o; }
2
public Hashtable<String, K> getCodes() { return codes; }
0
@Override public void render() { double[] pos; float[] color; double size; double angle; int numVerts_ = 8; GL11.glBegin(GL11.GL_TRIANGLES); for(int i = 0; i < MAX_PARTICLES; i++) { color = getCRule(cID_[i]).getColor(r_[i], g_[i], b_[i], a_[i], age_[i], props_[i]); size = getSRule(sID_[i]).getSize(size_[i], age_[i], props_[i]); pos = getPRule(pID_[i]).getPos(xCoord_[i], yCoord_[i], angle_[i], age_[i], props_[i]); if(size != 0 && color[3] > 0) { for(int j = 0; j < numVerts_; j++) { GL11.glColor4f(color[0], color[1], color[2], color[3]); angle = j * 2 * Math.PI / numVerts_; GL11.glVertex2d(pos[0] + (Math.cos(angle) * size), pos[1] + (Math.sin(angle) * size)); angle = (j + 1) * 2 * Math.PI / numVerts_; GL11.glVertex2d(pos[0] + (Math.cos(angle) * size), pos[1] + (Math.sin(angle) * size)); GL11.glVertex2d(pos[0], pos[1]); } } } GL11.glEnd(); }
4
private void sendPackage(String type, String... item) { if ( (manager.getCurrentStage() != null && !manager.isStageItemsEmpty()) || type.equals(OVERLAY) ){ //printStage(); IsaacGamePackage isaacPackage = manager.createGamePackage(type, item); try { if (isGameActive()) { queue.put(isaacPackage); // blocks if queue is full } else { notifyIsaacLogStatus(false); } } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
6
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result) { if (a == null || a.length == 0) return; Manager min = a[0]; Manager max = a[0]; for (int i = 1; i < a.length; i++) { if (min.getBonus() > a[i].getBonus()) min = a[i]; if (max.getBonus() < a[i].getBonus()) max = a[i]; } result.setFirst(min); result.setSecond(max); }
6
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; NucleotideInteraction other = (NucleotideInteraction) obj; if (firstNucleotide == null) { if (other.firstNucleotide != null) return false; } else if (!firstNucleotide.equals(other.firstNucleotide)) return false; if (secondNucleotide == null) { if (other.secondNucleotide != null) return false; } else if (!secondNucleotide.equals(other.secondNucleotide)) return false; return true; }
9
@Override public boolean evaluate(RuleContext ruleContext) { BigDecimal lhs = new BigDecimal(mValues.get(0).asString(ruleContext)); BigDecimal lower = new BigDecimal(mValues.get(1).asString(ruleContext)); BigDecimal upper = new BigDecimal(mValues.get(2).asString(ruleContext)); boolean result = false; switch (upper.compareTo(lower)) { case -1: // a_upper < lower if (ruleContext.getEvents().isDebugEnabled()) { ruleContext.getEvents().debug(TYPE + ": upper < lhs < lower: " + upper + " < " + lhs + " < " + lower); } result = ((lhs.compareTo(lower) < 0) && (lhs.compareTo(upper) > 0)); break; case 0: // a_upper == lower if (ruleContext.getEvents().isDebugEnabled()) { ruleContext.getEvents().debug(TYPE + ": upper == lower, always false."); } result = false; break; case 1: // a_upper > lower if (ruleContext.getEvents().isDebugEnabled()) { ruleContext.getEvents().debug(TYPE + ": lower < lhs < upper: " + lower + " < " + lhs + " < " + upper); } result = ((lhs.compareTo(lower) > 0) && (lhs.compareTo(upper) < 0)); break; default: throw new RuntimeException(TYPE + ": Unexpected comparisson result of lower='" + lower + "' and upper='" + upper + "'"); } return result ^ mNot; }
8
protected void renameProfile() { boolean doit = true; for(int i=profiles.size()-1; i>=0; i--) { Profile p = profiles.get(i); if(p.name.equals(txtProfile.getText())){ doit = false; //if we find a duplicate name, don't do it! } } if(doit){ selProfile.name = txtProfile.getText(); profileListMdl.removeAllElements(); for(int i=0; i<=profiles.size()-1; i++) { Profile p = profiles.get(i); profileListMdl.addElement(p.name); if(p.name.equals(txtProfile.getText())){ profileList.setSelectedValue(profileListMdl.lastElement(), true); selectedProfile(); con.log("Log","Renamed profile"); writeData(); } } } }
5
@RequestMapping("/listarStock") public ModelAndView listarStock() { Stock stock = Stock.getInstance(); Map<String, Integer> mapStock = stock.obtenerStock(); Set<String> setStock = mapStock.keySet(); List<Producto> productList = new ArrayList<Producto>(); for (Iterator<String> iterator = setStock.iterator(); iterator.hasNext();) { String nombre = iterator.next(); Integer cantidad = mapStock.get(nombre); Producto otroProducto = new Producto(nombre, cantidad); productList.add(otroProducto); } ModelMap model = new ModelMap(); model.put("nombre", "stockList"); model.put("productos", productList); return new ModelAndView("listarStock", model); }
1
private JSONWriter append(String s) throws JSONException { if (s == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(s); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); }
7
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if (num == null) return res; if (num.length == 0) { res.add(new ArrayList<Integer>()); return res; } Arrays.sort(num); for (int i = 0; i < (int)Math.pow(2, num.length); i++) { ArrayList<Integer> set = new ArrayList<Integer>(); int temp = i; int lastUnselected = -1; boolean add = true; for (int j = 0; j < num.length; j++) { if ((temp & 1) != 0) { if (lastUnselected >= 0 && lastUnselected + 1 == j && num[lastUnselected] == num[j]) { add = false; break; } set.add(num[j]); } else { lastUnselected = j; } temp >>= 1; } if (add) res.add(set); } return res; }
9
private BigInteger[] getPrimesParallel(int keyBitSize) { GenPrimeThread[] primeThreads = new GenPrimeThread[cores]; BigInteger[] primes = new BigInteger[cores]; BigInteger[] retPrime = new BigInteger[2]; for (int i = 0; i < cores; i++) { primeThreads[i] = new GenPrimeThread(core, keyBitSize); } // Start Threads for (int i = 0; i < cores; i++) { primeThreads[i].start(); } for (int i = 0; i < cores; i++) { try { primeThreads[i].join(); } catch (InterruptedException ex) { Logger.getLogger(KeyGenRSA.class .getName()).log(Level.SEVERE, null, ex); } } for (int i = 0; i < cores; i++) { primes[i] = primeThreads[i].getPrime(); } for (int i = 0; i < cores; i++) { for (int j = cores - 1; j >= 0; j--) { log2ofPQ = Math.abs(CryptobyHelper.logBigInteger(primes[i]) - CryptobyHelper.logBigInteger(primes[j])); if (log2ofPQ >= 0.1 || log2ofPQ <= 30) { retPrime[0] = primes[i]; retPrime[1] = primes[j]; return retPrime; } } } retPrime[0] = BigInteger.ZERO; retPrime[1] = BigInteger.ZERO; return retPrime; }
9
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed if (!txtCaminhoBanco.getText().isEmpty() && (txtCaminhoBanco.getText().contains(":/") || txtCaminhoBanco.getText().contains(":\\"))) { JTextField pwd = new JPasswordField(10); JLabel label = new JLabel("Digite a senha:"); int x = JOptionPane.showConfirmDialog(null, new Object[]{label, pwd}, "Senha", JOptionPane.OK_CANCEL_OPTION); pwd.requestFocus(); if (x == 0) { if (pwd.getText().equals(new Validacoes().geraPassword())) { criaXML(txtIPServidor.getText(), txtCaminhoBanco.getText()); this.dispose(); new Login().setVisible(true); } else { JOptionPane.showMessageDialog(null, "Senha incorreta", "Erro", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_btnOkActionPerformed
5
private double classificationConverter(String classification) { double convertedClassification; if (classification.equals("Definitive")) convertedClassification = 1.0; else if (classification.equals("Dependent")) convertedClassification = 2.0/3.0; else if (classification.equals("Dangerous")) convertedClassification = 2.0/3.0; else if (classification.equals("Dominant")) convertedClassification = 2.0/3.0; else if (classification.equals("Demanding")) convertedClassification = 1.0/3.0; else if (classification.equals("Dormant")) convertedClassification = 1.0/3.0; else if (classification.equals("Discretionary")) convertedClassification = 1.0/3; else convertedClassification = 0; return convertedClassification; }
7
public static int GetCurrentSecondHighActivatedNodeAL(){ //功能: //得到当前激活强度次高的节点的激活强度 int low=0; int GraphSize=CognitiveGraph.size(); Vector<Integer> useforsort = new Vector<Integer>(); for(int i=0;i<GraphSize;i++){ int ListSize=CognitiveGraph.get(i).ObjOrAttri.size(); for(int ii=0;ii<ListSize;ii++){ useforsort.add(CognitiveGraph.get(i).ObjOrAttri.get(ii).ActivatedLevel); } } int length=useforsort.size(); for(int i=1;i<length;i++){ for(int j=length-1;j>=i;j--){ if(useforsort.get(j-1)<useforsort.get(j)){ int temp=useforsort.get(j-1); useforsort.set(j-1, useforsort.get(j)); useforsort.set(j, temp); } } } int max=useforsort.get(0); for(int i=0;i<length;i++) { if(useforsort.get(i)<max){ low=useforsort.get(i); break; } } return low; }
7
public static ScoringStyle parseStyle(String styleString) { if (styleString.contains("PERCENT_SCORE")) { return PERCENT_SCORE; } else if (styleString.contains("BULLET_DAMAGE")) { return BULLET_DAMAGE; } else if (styleString.contains("SURVIVAL_FIRSTS")) { return SURVIVAL_FIRSTS; } else if (styleString.contains("SURVIVAL_SCORE")) { return SURVIVAL_SCORE; } else if (styleString.contains("MOVEMENT_CHALLENGE") || styleString.contains("ENERGY_CONSERVED")) { return MOVEMENT_CHALLENGE; } else { throw new IllegalArgumentException( "Unrecognized scoring style: " + styleString); } }
6
private StringBuilder hexToString(StringBuilder hh) { // make sure we have a valid hex value to convert to string. // can't decrypt an empty string. if (hh != null && hh.length() == 0){ return new StringBuilder(); } StringBuilder sb; // special case, test for not a 4 byte character code format if (!((hh.charAt(0) == 'F' | hh.charAt(0) == 'f') && (hh.charAt(1) == 'E' | hh.charAt(1) == 'e') && (hh.charAt(2) == 'F' | hh.charAt(2) == 'f') && (hh.charAt(3) == 'F') | hh.charAt(3) == 'f')) { int length = hh.length(); sb = new StringBuilder(length / 2); String subStr; for (int i = 0; i < length; i = i + 2) { subStr = hh.substring(i, i + 2); sb.append((char) Integer.parseInt(subStr, 16)); } return sb; } // otherwise, assume 4 byte character codes else { int length = hh.length(); sb = new StringBuilder(length / 4); String subStr; for (int i = 0; i < length; i = i + 4) { subStr = hh.substring(i, i + 4); sb.append((char) Integer.parseInt(subStr, 16)); } return sb; } }
8
public ReaderConfig(ResourceBundle resourceBundle) { Enumeration<String> fileContext = resourceBundle.getKeys(); while (fileContext.hasMoreElements()) { String element = (String) fileContext.nextElement(); if ("storiesNumber".equals(element)) { storiesNumber = Integer.valueOf(resourceBundle .getString(element)); } else if ("elevatorCapacity".equals(element)) { elevatorCapacity = Integer.valueOf(resourceBundle .getString(element)); } else if ("passengersNumber".equals(element)) { passengersNumber = Integer.valueOf(resourceBundle .getString(element)); } else if ("animationBoost".equals(element)) { animationBoost = Integer.valueOf(resourceBundle .getString(element)); } else { System.err.println("Problem with resource file"); } } try{ checkRightMinNumbers( storiesNumber, elevatorCapacity,passengersNumber); checkRightMaxNumbers(storiesNumber, elevatorCapacity, passengersNumber, animationBoost); }catch(ExceptionInInitializerError e){ System.err.println("Error: "+e); System.exit(1); } }
6
public void moveleft(){ switch (polygonPaint) { case 0: line.moveLeft(); repaint(); break; case 1: curv.moveLeft(); repaint(); break; case 2: triangle.moveLeft(); repaint(); break; case 3: rectangle.moveLeft(); repaint(); break; case 4: cu.moveLeft(); repaint(); break; case 5: elipse.moveLeft(); repaint(); break; case 6: arc.moveLeft(); repaint(); break; } repaint(); }
7
@Override public T askChoice(boolean cancel) { String playerName = control.getPlayer().getName(); System.out.println(playerName + ", " + promptMessage); int choice = -1; int cancelChoiceNb = control.getChoices().size() + 1; int maxSize; if (cancel) { maxSize = cancelChoiceNb; } else { maxSize = control.getChoices().size(); } while (choice < 1 || choice > maxSize) { Iterator<T> it = control.getChoices().iterator(); int i = 1; while (it.hasNext()) { T t = it.next(); System.out.println(i + " : " + t); i++; } if (cancel) { System.out.println(cancel + " : Cancel"); } choice = TextIHM.scanner.nextInt(); if (Game.IS_TEST) { System.out.println(choice); } System.out.println(); } T result; if (cancel && choice == cancelChoiceNb) { result = null; } else { result = control.getChoices().get(choice - 1); } return result; }
8
public void processEvent(Event event) { if (event.getType() == Event.COMPLETION_EVENT) { System.out.println(_className + ": Receive a COMPLETION_EVENT, " + event.getHandle()); return; } System.out.println(_className + ".processEvent: Received Login Response... "); if (event.getType() != Event.OMM_ITEM_EVENT) { System.out.println("ERROR: " + _className + " Received an unsupported Event type."); _mainApp.cleanup(-1); return; } OMMItemEvent ie = (OMMItemEvent)event; OMMMsg respMsg = ie.getMsg(); if (respMsg.getMsgModelType() != RDMMsgTypes.LOGIN) { System.out.println("ERROR: " + _className + " Received a non-LOGIN model type."); _mainApp.cleanup(-1); return; } if (respMsg.isFinal()) { System.out.println(_className + ": Login Response message is final."); GenericOMMParser.parse(respMsg); _mainApp.processLogin(false); return; } if ((respMsg.getMsgType() == OMMMsg.MsgType.STATUS_RESP) && (respMsg.has(OMMMsg.HAS_STATE)) && (respMsg.getState().getStreamState() == OMMState.Stream.OPEN) && (respMsg.getState().getDataState() == OMMState.Data.OK)) { System.out.println(_className + ": Received Login STATUS OK Response"); GenericOMMParser.parse(respMsg); _mainApp.processLogin(true); } else { System.out.println(_className + ": Received Login Response - " + OMMMsg.MsgType.toString(respMsg.getMsgType())); GenericOMMParser.parse(respMsg); } }
8
@Test void testA() { if (true) throw new RuntimeException("This test always failed"); }
1
public void generateNodes(int number) { for(int i=0;i<number;i++) { Node n = new Node(i); this.nodes.add(n); } }
1
public int [][] loadTrainData (String fileName) { System.out.println ("Load Train Data Start!"); wordMapping = new HashMap <String,Integer> (); BufferedReader reader = null; int trainData [][] = null; try { File file = new File (fileName); reader = new BufferedReader (new FileReader (file)); String line = null; String word = null; int count = 0; int M = 0; // Doc count int m = 0; // a doc id int N = 0; // Doc size int wordId = 0; // First line is the total count of the Doc line = reader.readLine (); M = Integer.valueOf (line); System.out.println ("Doc cnt is " + M); trainData = new int [M][]; while ((line = reader.readLine ())!= null) { String [] words = line.split (" "); N = words.length; trainData [m] = new int [N]; for (int n=0;n<N;++n) { word = words [n]; Integer wordId_ = null; if ((wordId_ = wordMapping.get (word)) == null) { trainData [m][n] = wordId; wordId_ = new Integer (wordId); wordMapping.put (word, wordId_); ++ wordId; } else { trainData [m][n] = wordId_.intValue (); } } ++ m; } reader.close (); } catch (IOException e) { e.printStackTrace (); } finally { if (reader != null) { try { reader.close (); } catch (IOException e) { e.printStackTrace (); } } } if (0 != wordMapping.size ()) { String folderPath = MyUtil.getFolderPath (fileName); saveWordMapping (folderPath + "/wordMapping.txt", wordMapping); } System.out.println ("Word Dict size is " + wordMapping.size ()); System.out.println ("Doc cout " + trainData.length); return trainData; }
7
public static void main (String [] args) { double salarioatual,salarionovo; char salario ; Scanner teclado = new Scanner(System.in); System.out.print("Informe o seu salario para saber qual foi o aumento:"); salarioatual = teclado.nextInt(); if (salarioatual >0 && salarioatual <=1499){ salarionovo = ((salarioatual*15)/100)+salarioatual; System.out.println("Voce teve um aumento salarial de 15%"); System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo); } if (salarioatual >1499 && salarioatual <=1750){ salarionovo = ((salarioatual*12)/100)+salarioatual; System.out.println("Voce teve um aumento salarial de 12%"); System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo); } if (salarioatual >1750 && salarioatual <=2000){ salarionovo = ((salarioatual*10)/100)+salarioatual; System.out.println("Voce teve um aumento salarial de 10%"); System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo); } if (salarioatual >2000 && salarioatual <=3000){ salarionovo = ((salarioatual*7)/100)+salarioatual; System.out.println("Voce teve um aumento salarial de 7"); System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo); } if (salarioatual >3000){ salarionovo = ((salarioatual*5)/100)+salarioatual; System.out.println("Voce teve um aumento salarial de 5%"); System.out.println("Seu salario era de:"+salarioatual+"Agora e de:"+salarionovo); } }
9
public MenuItem getDisplayMenu() { if (displayMenu == null) { displayMenu = new Menu("Display"); // Create listener for Display menu items. ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { MenuItem item = (MenuItem) e.getSource(); if ("Error".equals(item.getLabel())) { trayIcon.displayMessage(MESSAGE_HEADER, "This is an " + item.getLabel() + " message", TrayIcon.MessageType.ERROR); } else if ("Warning".equals(item.getLabel())) { trayIcon.displayMessage(MESSAGE_HEADER, "This is a " + item.getLabel() + " message", TrayIcon.MessageType.WARNING); } else if ("Info".equals(item.getLabel())) { trayIcon.displayMessage(MESSAGE_HEADER, "This is an " + item.getLabel() + " message", TrayIcon.MessageType.INFO); } else if ("None".equals(item.getLabel())) { trayIcon.displayMessage(MESSAGE_HEADER, "This is an " + item.getLabel() + " message", TrayIcon.MessageType.NONE); } } }; errorItem = new MenuItem("Error"); warningItem = new MenuItem("Warning"); infoItem = new MenuItem("Info"); noneItem = new MenuItem("None"); // Add listeners to Display menu items. errorItem.addActionListener(listener); warningItem.addActionListener(listener); infoItem.addActionListener(listener); noneItem.addActionListener(listener); displayMenu.add(errorItem); displayMenu.add(warningItem); displayMenu.add(infoItem); displayMenu.add(noneItem); } return displayMenu; }
5
@Override public int hashCode() { int hash = 0; hash += (idPeriferico != null ? idPeriferico.hashCode() : 0); return hash; }
1
private void unpackBigPacket(DemultiplexerStreaminformations stream) throws InterruptedException { // Nutzdatenpakete (das können mehrere sein) und der Paketindex(des großen Pakets) stehen nun zur Verfügung. // Genau an dieser Stelle greift der Thread auf eine Queue zu, die ihn schlafen legt, wenn KEIN Paket vorhanden ist. // Um aber auf diese Schlange ein Paket zu legen, muss man sich auf die <code>DemultiplexerStreaminformations</code> // aber synchronisieren. Hat aber der wartende Thread den Monitor noch, dann gibt es einen Deadlock. // Aus diesem Grund wird dieser Zugriff aus jeden <code>synchronized(stream)</code> rausgehalten. final ReferenceDataPacket referenceDataPacket = stream.getReferenceDataPacket(); // Der neue maximale Paketindex, dieser wird hier deklariert, weil er außerhalb des synch. Blocks benötigt wird. // Er wird aber innerhalb des synch. Blocks gesetzt, dies stellt aber kein Problem dar (siehe Kommentar zum versenden des Tickets). int newMaxStreamPacketIndex = 0; // Wenn im synch. Block ein neuer max Index Wert berechnet wird, dann muß ein Ticket versandt werden (aber nur dann). // Ist diese Variable auf true, dann muß ein Ticket versandt werden. boolean sendNewTicket = false; final int indexOfStream; // War das null-Paket in dem großen Paket boolean nullPacket = false; synchronized (stream) { // Nutzdaten und der Paketindex stehen nun zur Verfügung // Index des Stream indexOfStream = stream.getIndexOfStream(); // Falls der Paketindex mit dem Index an dem eine neue Sendebestätigung gesendet werden muß überein stimmt, dann wird ein Ticket verschickt if (stream.getPacketIndexToSendNextMaxTicketIndex() == referenceDataPacket.getStreamPacketIndex()) { // Dieses Packet muß den Sender benachrichtigen, dass er neue Pakete verschicken muß. // Es werden _blockingFactor viele Pakete angefordert. // Den neuen Index berechnen, bis zu dem der Sender Pakete schicken darf newMaxStreamPacketIndex = stream.getPacketIndexToSendNextMaxTicketIndex() + _blockingFactor; // Den neuen Index berechnen, an dem eine neue Sendeerlaubnis an den Sender verschickt werden darf. Dies entspricht // _blockingFactor/2 oder aber der Variablen _ticketBlockingFactor. Diese wird bei einem // _blockingFactor von 1 automatisch auf 1 gesetzt. final int newPacketIndexToSendNextMaxTicketIndex = stream.getPacketIndexToSendNextMaxTicketIndex() + _ticketBlockingFactor; stream.setMaxStreamPacketIndex(newMaxStreamPacketIndex); stream.setPacketIndexToSendNextMaxTicketIndex(newPacketIndexToSendNextMaxTicketIndex); sendNewTicket = true; } // Hier steht nun das große Paket zur Verfügung, alle Berechnungen ob ein Ticket verschickt werden muss // (wenn ja, was für eins) wurden beendet. Nun können die Nutzdatenpakete (die kleinen Pakete) erzeugt werden. // Dabei kann gleich geprüft werden, ob ein null-Paket dabei war, falls ja, muß das Ticket (wenn denn eins verschickt // werden muss) gar nicht mehr versandt werden. // Das ganze findet auf einem synchronisierten Stream statt, da auf die Queue für die Nutzdaten zugegriffen werden // muss. Ist dieser nicht synchronisiert, kann die Reihenfolge der Nutzdaten durcheinander kommen. // Wurden alle Pakete aus dem großen Paket ausgepackt boolean unpackedAllPackets = false; // Hier sind alle kleinen Nutzdatenpakete(die für die Empfängerapplikation bestimmt sind) verpackt final byte[] bigDataPacket = referenceDataPacket.getData(); final InputStream in = new ByteArrayInputStream(bigDataPacket); //deserialisieren final Deserializer deserializer = SerializingFactory.createDeserializer(in); while (unpackedAllPackets == false) { try { // Größe des Nutzdatenpakets int sizeOfData = deserializer.readInt(); byte[] data; if (sizeOfData >= 0) { // Es sind Nutzdaten vorhanden, das null-Paket hat einen negativen Index data = deserializer.readBytes(sizeOfData); // Das gerade ausgepackte Nutzdatenpaket kann nun im Stream gespeichert werden. // _debug.fine("Ein normales Nutzdatenpaket wird in die kleine Queue gespeichert"); stream.putDataSmallDataPacketQueue(data); } else { // Die Größe des Nutzdatenpakets ist negativ, somit wurde entweder ein null-Paket empfangen oder // das große Paket hat keine kleinen Nutzdatenpakete mehr. if (sizeOfData == -1) { // Das bedeutet, dass die Senderapplikation keine Nutzdaten mehr für die // Empfängerapplikation hat. Der Stream wurde auf der Senderseite bereits als // "beendet" markiert. // Es wird nicht weiter geguckt ob die -2 auch noch versandt wurde (was der Fall ist), weil // die -1 bereits eindeutig ist. data = null; nullPacket = true; unpackedAllPackets = true; // Das gerade ausgepackte Nutzdatenpaket kann nun im Stream gespeichert werden. stream.putDataSmallDataPacketQueue(data); _debug.fine("Beim auspacken eines großen Pakets, Stream(" + indexOfStream + ") wurde ein null-Paket mit Index(Index des großen Pakets) " + referenceDataPacket.getStreamPacketIndex() + " gefunden"); } else { // Es wurden alle bytes des byte-Arrays ausgelesen, also ist das große Paket "leer" unpackedAllPackets = true; _debug.finer("Ein großes Paket wurde ausgepackt, es enthielt nur Nutzdaten. Stream:" + indexOfStream + " Index des großen Pakets: " + referenceDataPacket.getStreamPacketIndex()); } } } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } // synchronized(stream) // Das versenden darf außerhalb des synch. Blocks stehen, da auf der Gegenseite (Sender) geprüft wird, ob // der neue maximale Index größer ist als der der gerade empfangen wird. // Es ist also nicht schlimm, wenn der Empfänger einen "alten" Index an den Sender schickt. if ((sendNewTicket == true) && (nullPacket == false)) { // Ein neues Ticket muß an den Sender verschickt werden. Dies muß aber nur geschehen, wenn der Sender noch Nutzdaten // für den Empfänger hat. Dies erkennt man daran, dass die Nutzdaten ungleich null sind. Sind sie null, dann hat // der Sender keine Nutzdaten mehr und hat seinerseits den Stream schon beendet (falls noch Tickets für // den Stream unterwegs sind, wird der Sender diese ignorieren) try { sendNewTicketIndexToSender(indexOfStream, newMaxStreamPacketIndex); } catch (IOException e) { e.printStackTrace(); _debug.error("Ein Fehler beim serialisieren/deserialisieren: " + e); } } // Debug _numberOfTakes[indexOfStream] = _numberOfTakes[indexOfStream] + 1; _debug.finer("Take Stream(" + indexOfStream + ") liefert: Paket mit Index " + referenceDataPacket.getStreamPacketIndex() + " Insgesamt wurden " + _numberOfTakes[indexOfStream] + " takes auf diesem Stream ausgeführt"); }
8
public static String right(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(str.length() - len); }
3
private static void setIsPrime() { for(int i = 2; i < isPrime.length; i++) isPrime[i] = true; for(int i = 2; i < isPrime.length; i++) if( isPrime[i] ) for(int j = 2; j*i < isPrime.length; j++) isPrime[i*j] = false; }
4
public void render(){ //BS bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } //END BS Graphics g = bs.getDrawGraphics(); if(gameState == GameState.MENU) g.drawImage(menuImage, 0, 0, getWidth(), getHeight(), null); else g.drawImage(level.getDojoImage(), 0, 0, getWidth(), getHeight(), null); if(gameState == GameState.MENU){ if(input.menuUp || input.menuDown) Sound.WUSH.play(false); menu.render(g); }else if(gameState == GameState.SINGLE){ level.render(g); }else if(gameState == GameState.MULTI){ level.render(g); } g.dispose(); bs.show(); }
7
private void process(Transferable t) { final DataFlavor df = DataFlavor.stringFlavor; if (t.isDataFlavorSupported(df)) { try { BufferedReader r = new BufferedReader(df.getReaderForText(t)); String line; while ((line = r.readLine()) != null) { if (Site.resolve(line) != Site.UNKNOWN) { LOG.trace(format("Из буфера обмена прочитан URL %s", line)); loader.load(ArticleFactory.getArticle(new UrlWrapper(line))); } else { LOG.trace(format("Строка не является URL: %s", line)); } } r.close(); } catch (UnsupportedFlavorException | IOException e) { LOG.error(e.getMessage(), e); } } else { LOG.trace("Содержимое буфера обмена проигнорировано."); } }
4
public static void main(String[] args) { TestAtom A = new TestAtom(); Movable player = new Movable(); ArrayList<VerbSignature> signatures = A.getVerbs(player).verbs; for(VerbSignature v : signatures) { System.out.println("Verb: "+v.verbName); for(VerbParameter p : v.parameters) { System.out.println("Param Type: "+p.type.toString()); } } /** Object[] met_args = {"Head", "Beep"}; Object[] con_args = {"Hey Head!"}; if(A.callVerb("printTest", met_args)) // This should work. System.out.println("Called PrintTest(String,String) fine"); else System.out.println("Called PrintTest(String,String) badly"); if(A.callVerb("printTest", con_args))// This should fail because printTest(String A) does not have a @Verb System.out.println("Called PrintTest(String) perfectly fine, wait what?"); else System.out.println("Called PrintTest(String) failed as expected."); HashMap<String,Object> class_variables = new HashMap<String,Object>(); class_variables.put("UID", 55); Object B = Utils.createClass("complexion.server.Atom",con_args,class_variables); Atom C = (Atom)B; System.out.print(C.getUID()); **/ }
2