text
stringlengths
14
410k
label
int32
0
9
public boolean transitionsFromTuringFinalStateAllowed() { return transTuringFinal; }
0
public void jsFunction_waitCraft(String wnd, int timeout) { deprecated(); int cur = 0; while (true) { if(cur > timeout) break; if (UI.instance.make_window != null) if ((UI.instance.make_window.is_ready) && (UI.instance.make_window.craft_name.equals(wnd))) return; Sleep(25); cur += 25; } }
5
public static void getSubString(String input){ HashSet<String> usedset = new HashSet<String>(); HashSet<String> validSet = new HashSet<String>(); for(int i=1; i<=input.length();i++){ for(int j= 0; j+i<= input.length();j++){ String sub = input.substring(j,i+j); if(usedset.contains(sub)){ validSet.remove(sub); }else{ usedset.add(sub); validSet.add(sub); } } } ArrayList<String> arr = new ArrayList<String>(); arr.addAll(validSet); validSet.clear(); int shortest = arr.get(0).length(); for(String s : arr){ if(s.length() <shortest){ validSet.clear(); shortest = s.length(); validSet.add(s); }else if(s.length() == shortest){ validSet.add(s); } } Iterator<String> itr = validSet.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } }
7
public String getMove() { switch(move){ case 1: return "up"; case 2: return "down"; case 3: return "left"; case 4: return "right"; } return ""; }
4
public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } Stack<TreeNode> leftStack = new Stack<>(); Stack<TreeNode> rightStack = new Stack<>(); leftStack.add(root.left); rightStack.add(root.right); while (!leftStack.isEmpty() && !rightStack.isEmpty()) { TreeNode left = leftStack.pop(); TreeNode right = rightStack.pop(); if (left == null || right == null) { if (left != right) { return false; } } else { if (left.val != right.val) { return false; } leftStack.push(left.left); leftStack.push(left.right); rightStack.push(right.right); rightStack.push(right.left); } } return leftStack.size() == rightStack.size(); }
7
public static BufferedImage fsDithering(BufferedImage input, int numberOfRedHues, int numberOfGreenHues, int numberOfBlueHues) { BufferedImage result = new BufferedImage(input.getWidth(), input.getHeight(), input.getType()); for (int i = 0; i < result.getHeight(); i++) { for (int j = 0; j < result.getWidth(); j++) { Color oldColor = new Color(input.getRGB(i, j)); Color newColor = closestPaletteColor(oldColor, numberOfRedHues, numberOfGreenHues, numberOfBlueHues); result.setRGB(i, j, newColor.getRGB()); int quantError[] = new int[]{newColor.getRed() - oldColor.getRed(), newColor.getGreen() - oldColor.getGreen(), newColor.getBlue() - oldColor.getBlue()}; Color changeColor; if (i + 1 < result.getHeight()) { changeColor = new Color(input.getRGB(i + 1, j)); input.setRGB(i + 1, j, normColor( changeColor.getRed() + quantError[0] * 7 / 16, changeColor.getGreen() + quantError[1] * 7 / 16, changeColor.getBlue() + quantError[2] * 7 / 16 ).getRGB() ); if (j - 1 > 0) { changeColor = new Color(input.getRGB(i + 1, j - 1)); input.setRGB(i + 1, j - 1, normColor( changeColor.getRed() + quantError[0] * 3 / 16, changeColor.getGreen() + quantError[1] * 3 / 16, changeColor.getBlue() + quantError[2] * 3 / 16 ).getRGB() ); } } if (j + 1 < input.getWidth()) { changeColor = new Color(input.getRGB(i, j + 1)); input.setRGB(i, j + 1, normColor( changeColor.getRed() + quantError[0] * 5 / 16, changeColor.getGreen() + quantError[1] * 5 / 16, changeColor.getBlue() + quantError[2] * 5 / 16 ).getRGB() ); if (i + 1 < input.getHeight()) { changeColor = new Color(input.getRGB(i + 1, j + 1)); input.setRGB(i + 1, j + 1, normColor( changeColor.getRed() + quantError[0] / 16, changeColor.getGreen() + quantError[1] / 16, changeColor.getBlue() + quantError[2] / 16 ).getRGB() ); } } } } return result; }
6
public static Object invokeMethodWithString(Object o, String methodName, String value) { if (o == null) return null; if (Functions.isEmpty(methodName)) return null; Object retObj; try { Class<?> c = o.getClass(); if (c == null) return null; Method m = c.getMethod(methodName); Object arglist[] = new Object[1]; arglist[0] = value; retObj = m.invoke(o,arglist); } catch (Throwable e) { return null; } return retObj; }
5
private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed System.exit(0); }//GEN-LAST:event_btnSalirActionPerformed
0
public Tile getTile(int x, int y) { if(x >= width || x < 0 || y >= height || y < 0) return null; return World.tiles[map[x][y]]; }
4
public void setIdPrueba(Integer idPrueba) { this.idPrueba = idPrueba; }
0
public List<ExtensionsType> getExtensions() { if (extensions == null) { extensions = new ArrayList<ExtensionsType>(); } return this.extensions; }
1
@Override public void actionPerformed(ActionEvent event) { try { Desktop.getDesktop().open(mFile); } catch (IOException exception) { WindowUtils.showError(null, exception.getMessage()); } }
1
@Test public void testRollbackSucceededState() throws ProcessExecutionException, ProcessRollbackException { IProcessComponent<?> comp = TestUtil.executionSuccessComponent(true); // use reflection to set internal process state TestUtil.setState(comp, ProcessState.ROLLBACK_SUCCEEDED); assertTrue(comp.getState() == ProcessState.ROLLBACK_SUCCEEDED); // test valid operations TestUtil.setState(comp, ProcessState.ROLLBACK_SUCCEEDED); try { comp.execute(); } catch (InvalidProcessStateException ex) { fail("This operation should have been allowed."); } // test invalid operations TestUtil.setState(comp, ProcessState.ROLLBACK_SUCCEEDED); try { comp.rollback(); fail("InvalidProcessStateException should have been thrown."); } catch (InvalidProcessStateException ex) { // should happen } TestUtil.setState(comp, ProcessState.ROLLBACK_SUCCEEDED); try { comp.pause(); fail("InvalidProcessStateException should have been thrown."); } catch (InvalidProcessStateException ex) { // should happen } TestUtil.setState(comp, ProcessState.ROLLBACK_SUCCEEDED); try { comp.resume(); fail("InvalidProcessStateException should have been thrown."); } catch (InvalidProcessStateException ex) { // should happen } }
5
protected String[] getViewChoices() { return new String[] { "Noninverted Tree", "Derivation Table" }; }
0
public String getDirFilterExclude() { return this.dirFilterExclude; }
0
protected static void mult_BYTE_COMP_Data(WritableRaster wr) { // System.out.println("Multiply Int: " + wr); ComponentSampleModel csm; csm = (ComponentSampleModel) wr.getSampleModel(); final int width = wr.getWidth(); final int scanStride = csm.getScanlineStride(); final int pixStride = csm.getPixelStride(); final int[] bandOff = csm.getBandOffsets(); DataBufferByte db = (DataBufferByte) wr.getDataBuffer(); final int base = (db.getOffset() + csm.getOffset(wr.getMinX() - wr.getSampleModelTranslateX(), wr.getMinY() - wr.getSampleModelTranslateY())); int aOff = bandOff[bandOff.length - 1]; int bands = bandOff.length - 1; // Access the pixel data array final byte[] pixels = db.getBankData()[0]; for (int y = 0; y < wr.getHeight(); y++) { int sp = base + y * scanStride; final int end = sp + width * pixStride; while (sp < end) { int a = pixels[sp + aOff] & 0xFF; if (a != 0xFF) for (int b = 0; b < bands; b++) { int i = sp + bandOff[b]; pixels[i] = (byte) (((pixels[i] & 0xFF) * a) >> 8); } sp += pixStride; } } }
4
public void setBoxDate(Date boxDate) { this.boxDate = boxDate; }
0
@Override public void paintComponent(Graphics g) { BufferedImage bufferedImage = new BufferedImage( this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB ); Graphics tmpG = bufferedImage.createGraphics(); super.paintComponent( tmpG ); tmpG.setColor( Color.green ); tmpG.fillRect( 0, 0, this.getWidth(), this.getHeight() ); int objectSize = Math.min( this.getHeight()/level.getHeight(), this.getWidth()/level.getWidth() ); for ( int y=0; y<level.getHeight(); ++y ) { for ( int x=0; x<level.getWidth(); ++x ) { Tile field = level.getField(x, y); field.draw( new Dimension(objectSize, objectSize) ); tmpG.drawImage( drawers[x][y].getBufferedImage(), x*objectSize, y*objectSize, null ); } } for ( int i=0; i<miceDrawers.length; ++i ) { Mouse m = GameCore.getInstanceOfGameCore().getMice().get( i ); m.draw( new Dimension(objectSize, objectSize) ); tmpG.drawImage( miceDrawers[i].getBufferedImage(), m.getCoordinates().x*objectSize, m.getCoordinates().y*objectSize, null ); } { tmpG.setColor( Color.red ); //tmpG.fillRect( mousePoint.x-mousePoint.x%objectSize+objectSize/4, mousePoint.y-mousePoint.y%objectSize+objectSize/4, objectSize/2, objectSize/2 ); tmpG.drawRect( mousePoint.x-mousePoint.x%objectSize, mousePoint.y-mousePoint.y%objectSize, objectSize, objectSize ); tmpG.drawRect( mousePoint.x-mousePoint.x%objectSize+1, mousePoint.y-mousePoint.y%objectSize+1, objectSize-2, objectSize-2 ); //2pixel thickness } //now check the gameState: if ( GameCore.getInstanceOfGameCore().getGameState().ordinal() < GameState.RUNNING.ordinal() ) { //tmpG.setColor( Color.white ); int mouseID = GameCore.getInstanceOfGameCore().getPersonalMouseID(); tmpG.setColor( DrawerFactory.getColorFromColorTable(mouseID) ); tmpG.fillRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setColor( Color.black ); tmpG.drawRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setFont( tmpG.getFont().deriveFont(20.0f) ); if ( !GameCore.getInstanceOfGameCore().getReadySteadyGoMessage().isEmpty() ) { String msg = GameCore.getInstanceOfGameCore().getReadySteadyGoMessage(); tmpG.drawString( msg, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg)/2, getHeight()/2 ); } else { String msg = "Waiting for players!"; tmpG.drawString( msg, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg)/2, getHeight()/2 ); } String msgWhatMouse = "Your mouse is " + DrawerFactory.getColorNameFromColorTable( mouseID ) + "!"; tmpG.drawString( msgWhatMouse, getWidth()/2-tmpG.getFontMetrics().stringWidth(msgWhatMouse)/2, getHeight()/2+60 ); } if ( GameCore.getInstanceOfGameCore().getWinnerMouseID() != -1 ) { int myMouseID = GameCore.getInstanceOfGameCore().getPersonalMouseID(); int winnerMouseID = GameCore.getInstanceOfGameCore().getWinnerMouseID(); String msg1 = "Congratulations!"; String msg2 = "You won the game!"; if ( myMouseID != winnerMouseID ) { msg1 = "Game Over!"; msg2 = "The " + DrawerFactory.getColorNameFromColorTable(winnerMouseID) + " mouse won the game!"; tmpG.setColor( Color.red ); } else tmpG.setColor( Color.green ); tmpG.fillRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setColor( Color.black ); tmpG.drawRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setFont( tmpG.getFont().deriveFont(20.0f) ); tmpG.drawString( msg1, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg1)/2, getHeight()/2 ); tmpG.drawString( msg2, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg2)/2, getHeight()/2+60 ); } if ( GameCore.getInstanceOfGameCore().isServerLoss() ) { String msg1 = "Connection to Server has been lost!"; String msg2 = "Please Restart the game!"; tmpG.setColor( Color.red ); tmpG.fillRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setColor( Color.black ); tmpG.drawRect( getWidth()/4, getHeight()/4, getWidth()-getWidth()/2, getHeight()-getHeight()/2 ); tmpG.setFont( tmpG.getFont().deriveFont(20.0f) ); tmpG.drawString( msg1, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg1)/2, getHeight()/2 ); tmpG.drawString( msg2, getWidth()/2-tmpG.getFontMetrics().stringWidth(msg2)/2, getHeight()/2+60 ); } //redraw image g.drawImage( bufferedImage, 0, 0, null ); }
8
public List tools(AutomatonPane view, AutomatonDrawer drawer) { List list = new java.util.ArrayList(); list.add(new MooreArrowTool(view, drawer)); list.add(new MooreStateTool(view, drawer)); list.add(new TransitionTool(view, drawer)); list.add(new DeleteTool(view, drawer)); list.add(new UndoTool(view, drawer)); list.add(new RedoTool(view, drawer)); return list; }
0
private String processStringValues(String rawValue, HashSet<String> stopHash){ if(rawValue.equals("")){ return rawValue; } StringBuilder sb = new StringBuilder(); rawValue = rawValue.toLowerCase(); String[] strArray = rawValue.split(" "); Arrays.sort(strArray); for(String str : strArray){ if(stopHash.contains(str)){ continue; } sb.append(str); sb.append(" "); } return sb.toString(); }
3
@SuppressWarnings("rawtypes") @Override public boolean equals(Object o) { if (o instanceof Entry) { Entry other = (Entry) o; return (key == null ? other.getKey() == null : key.equals(other.getKey())) && (value == null ? other.getValue() == null : value.equals(other.getValue())); } return false; }
4
private void evaluateNFATransition(Transition transition, ExecutionState candidate, String candidateWord, List<ExecutionState> worklist) { // Add to the worklist any state according to the current state // and the position reached into the candidate word. switch(transition.getType()) { case Any: { if(candidate.wordPosition < candidateWord.length()) { for(State nextState : transition.getNextStates()) { worklist.add(new ExecutionState(nextState, candidate.wordPosition + 1)); } } break; } case Epsilon: { for(State nextState : transition.getNextStates()) { worklist.add(new ExecutionState(nextState, candidate.wordPosition)); } break; } case Letter: { if(candidate.wordPosition < candidateWord.length() && candidateWord.charAt(candidate.wordPosition) == transition.getLetter()) { for(State nextState : transition.getNextStates()) { worklist.add(new ExecutionState(nextState, candidate.wordPosition + 1)); } } break; } } }
9
final void send(ByteBuffer buffer) { mLastActivity = System.currentTimeMillis(); if (isSecure()) { try { mSSLSupport.processOutput(buffer); } catch (Throwable throwable) { Log.error(this, throwable); } } else { mServer.send(mChannel, buffer); } }
2
public HotKeyFlags setKey(String k) { if (k != null && !k.equals("")) low = keysr.get(k); return this; }
2
public String longestPrefixOf(String s) { if (s == null || s.length() == 0) return null; int length = 0; Node x = root; int i = 0; while (x != null && i < s.length()) { char c = s.charAt(i); if (c < x.c) x = x.left; else if (c > x.c) x = x.right; else { i++; if (x.val != null) length = i; x = x.mid; } } return s.substring(0, length); }
7
public ChatRmiClient () { client = new Client(); client.start(); // Register the classes that will be sent over the network. Network.register(client); // Get the Player on the other end of the connection. // This allows the client to call methods on the server. player = ObjectSpace.getRemoteObject(client, Network.PLAYER, IPlayer.class); client.addListener(new Listener() { public void disconnected (Connection connection) { EventQueue.invokeLater(new Runnable() { public void run () { // Closing the frame calls the close listener which will stop the client's update thread. chatFrame.dispose(); } }); } }); // Request the host from the user. String input = (String)JOptionPane.showInputDialog(null, "Host:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null, null, "localhost"); if (input == null || input.trim().length() == 0) System.exit(1); final String host = input.trim(); // Request the user's name. input = (String)JOptionPane.showInputDialog(null, "Name:", "Connect to chat server", JOptionPane.QUESTION_MESSAGE, null, null, "Test"); if (input == null || input.trim().length() == 0) System.exit(1); final String name = input.trim(); // The chat frame contains all the Swing stuff. chatFrame = new ChatFrame(host); // Register the chat frame so the server can call methods on it. new ObjectSpace(client).register(Network.CHAT_FRAME, chatFrame); // This listener is called when the send button is clicked. chatFrame.setSendListener(new Runnable() { public void run () { player.sendMessage(chatFrame.getSendText()); } }); // This listener is called when the chat window is closed. chatFrame.setCloseListener(new Runnable() { public void run () { client.stop(); } }); chatFrame.setVisible(true); // We'll do the connect on a new thread so the ChatFrame can show a progress bar. // Connecting to localhost is usually so fast you won't see the progress bar. new Thread("Connect") { public void run () { try { client.connect(5000, host, Network.port); // Server communication after connection can go here, or in Listener#connected(). player.registerName(name); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } }.start(); }
5
@Test public void findDuplicateTypeHand_whenNoPairExists_returnsHighCardHand() { Hand hand = findDuplicateTypeHand(kingQueenNineSixFourThreeTwo()); assertEquals(HandRank.HighCard, hand.handRank); assertEquals(Rank.King, hand.ranks.get(0)); assertEquals(Rank.Queen, hand.ranks.get(1)); assertEquals(Rank.Nine, hand.ranks.get(2)); assertEquals(Rank.Six, hand.ranks.get(3)); assertEquals(Rank.Four, hand.ranks.get(4)); }
0
private void registerPermissions () { this.getServer().getScheduler() .scheduleSyncDelayedTask(this, new Runnable() { public void run () { PluginManager pm = instance.getServer().getPluginManager(); Map<String, Boolean> children = new HashMap<String, Boolean>(); Map<Spell.Type, Permission> types = new HashMap<Spell.Type, Permission>(); Map<Spell.Type, Map<String, Boolean>> typeChildren = new HashMap<Spell.Type, Map<String, Boolean>>(); for (Spell spell : Spell.values()) { Map<String, Boolean> spellTypeChildren = typeChildren.get(spell.getType()); if (spellTypeChildren == null) { typeChildren.put(spell.getType(), spellTypeChildren = new HashMap<String, Boolean>()); } pm.addPermission(new Permission(spell.getPermission(), spell.getDescription())); spellTypeChildren.put(spell.getPermission(), true); } for (Spell.Type type : Spell.Type.values()) { String permName = "merlin.cast." + type.toString().toLowerCase() + ".*"; Permission perm = new Permission(permName, "Gives access to all " + type.getName() + " spells", typeChildren .get(type)); types.put(type, perm); pm.addPermission(perm); children.put(permName, true); } pm.addPermission(new Permission("merlin.cast.*", "Gives access to all spells", children)); Permission standard = null; for (Permission perm : instance.getDescription() .getPermissions()) { if (perm.getName().equals("merlin.standard")) { standard = perm; break; } } standard.getChildren().put("merlin.cast.*", true); standard.recalculatePermissibles(); pm.removePermission(standard); pm.addPermission(standard); } }); }
5
public static String readParamInXmlFile(String paramName, String fileName){ ArrayList<String> params = new ArrayList<String>(); try{ File fXmlFile = new File(fileName); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc; doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(paramName); for (int i = 0; i < nList.getLength(); i++){ params.add(nList.item(i).getTextContent()); } } catch (ParserConfigurationException e) { Logger.getLogger(ReadParametersFile.class).debug("EXCEPTION while reading parameters : "+ e.getMessage()+ " Description : "+ e.toString()); } catch (SAXException | IOException e) { Logger.getLogger(ReadParametersFile.class).debug("EXCEPTION while reading parameters : "+ e.getMessage()+ " Description : "+ e.toString()); } if(params.size()>0){ return params.get(0); } else { return null; } }
4
public static void modifierSujet(Sujet sujet, String nouveauSujet, String nouveauMessage, Utilisateur utilisateur) throws ChampInvalideException, ChampVideException { if (!sujet.peutModifier(utilisateur)) throw new InterditException("Vous n'avez pas les droits requis pour modifier cette réponse"); EntityTransaction transaction = SujetRepo.get().transaction(); String ancienSujet = sujet.getSujet(); String ancienMessage = sujet.getReponsePrincipale().getMessage(); try { transaction.begin(); sujet.setSujet(nouveauSujet); sujet.getReponsePrincipale().setMessage(nouveauMessage); validerSujet(sujet); validerReponse(sujet.getReponsePrincipale()); SujetRepo.get().mettreAJour(sujet); transaction.commit(); } catch(Exception e) { if (transaction.isActive()) transaction.rollback(); sujet.setSujet(ancienSujet); sujet.getReponsePrincipale().setMessage(ancienMessage); throw e; } }
3
public void setAllProducts(List<Product> allProducts) { this.allProducts = allProducts; }
0
public void setMemory(Integer memory) { this.memory = memory; }
0
public static DbHelper getDbHelper() { if(dbHelper == null){ dbHelper = new DbHelper(); } return dbHelper; }
1
public SimpleDateFormat getFormatter() { return formatter; }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tipo other = (Tipo) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; return true; }
9
public Class<?> getColumnClass(int col) { return getValueAt(0, col).getClass(); }
1
public static void main(String[] args) { int[] A = {3,4,5,1,4,2}; int[] B = {9,9,9}; int[] C = {1,2}; int target = 6; Solution sl = new Solution(); //int[] result = sl.twoSum(A, target); // int[] result = sl.PlusOne(A); // for(int i=0;i<result.length;i++){ // System.out.println(result[i]); // } // // String s = "the sky is blue"; // System.out.println(sl.candy(C)); ListNode n1 = new ListNode(2); ListNode n2 = new ListNode(3); ListNode n3 = new ListNode(4); ListNode n4 = new ListNode(3); ListNode n5 = new ListNode(4); ListNode n6 = new ListNode(5); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; //printList(sl.sortList(n1)); // StackTest stktest = new StackTest(); // System.out.println("peek is: " +stktest.stk.peek()); // stktest.testStackArray(); //queue test // QueueArray<String> queue= new QueueArray<String>(); // queue.enqueue("Hello").enqueue("world"); // System.out.println(queue.dequeue()+","+queue.dequeue()); //missing postive int // int[] uu = {2,1}; // System.out.println(sl.firstMissingPositive(uu)); // permutation test // System.out.println(sl.getPermutation(1, 1)); // sl.permute(C); //evalRPN test String[] token = {"2","1","+","3","*"}; // System.out.println(evalRPN.result(token)); //reserve int //System.out.println(sl.reserve(-900)); //LetterCombination List<String> list = sl.letterCombinations("2"); }
0
public Set entrySet() { accessTimes.clear(); // we're redoing everything so we might as well touch(map.keySet()); return map.entrySet(); }//entrySet
0
public static String encodeURI (String argString) { StringBuilder uri = new StringBuilder(); // Encoded URL char[] chars = argString.toCharArray(); for (char c : chars) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || mark.indexOf(c) != -1) { uri.append(c); } else { uri.append("%"); uri.append(Integer.toHexString((int) c)); } } return uri.toString(); }
8
@Override public void characters( char[] ch, int start, int length ) throws SAXException { if( length > 0 ){ String value = new String( ch, start, length ); String old = stack.getFirst().getValue(); if( old != null && old.length() > 0 ){ value = old + value; } stack.getFirst().setValue( value ); } }
3
private void setVoltageMode() { if (!m_voltageMode) { if(m_robotDrive != null) { m_robotDrive.setMaxOutput(12); } try { if (_leftFrontMotor != null) { _leftFrontMotor.changeControlMode(CANJaguar.ControlMode.kVoltage); _leftFrontMotor.configNeutralMode(CANJaguar.NeutralMode.kBrake); } _leftRearMotor.changeControlMode(CANJaguar.ControlMode.kVoltage); _leftRearMotor.configNeutralMode(CANJaguar.NeutralMode.kBrake); if (_rightFrontMotor != null) { _rightFrontMotor.changeControlMode(CANJaguar.ControlMode.kVoltage); _rightFrontMotor.configNeutralMode(CANJaguar.NeutralMode.kBrake); } _rightRearMotor.changeControlMode(CANJaguar.ControlMode.kVoltage); _rightRearMotor.configNeutralMode(CANJaguar.NeutralMode.kBrake); if (_leftFrontMotor != null) { _leftFrontMotor.enableControl(); } _leftRearMotor.enableControl(); if (_rightFrontMotor != null) { _rightFrontMotor.enableControl(); } _rightRearMotor.enableControl(); m_voltageMode = true; } catch (CANTimeoutException ex) { System.out.println("DriveTrain::setVoltageMode - " + ex.getMessage()); } } }
7
public boolean isValidField(char row, byte column) { if(row >= 97 && row <= 104 && column <= 7 && column >= 0) { return true; } return false; }
4
public void getRoutes(IntTreeNode p_root, int p_currentSum) { // TreeNode l_cloned = new TreeNode(p_root.getValue()); int l_sumForSubTree = p_currentSum - p_root.getValue(); if (l_sumForSubTree == 0 && p_root.getLeft() == null && p_root.getRight() == null) { for (int l_i = 0; l_i < m_routeStack.size(); l_i++) { System.out.print(m_routeStack.get(l_i)); System.out.print(','); } System.out.print(p_root.getValue()); System.out.println(); } else if (l_sumForSubTree > 0) { if (l_sumForSubTree > p_root.getValue()) { if (p_root.getRight() != null) { m_routeStack.push(p_root.getValue()); getRoutes((IntTreeNode)p_root.getRight(), l_sumForSubTree); m_routeStack.pop(); } } if (p_root.getLeft() != null) { m_routeStack.push(p_root.getValue()); getRoutes((IntTreeNode)p_root.getLeft(), l_sumForSubTree); m_routeStack.pop(); } } /*else if(l_sumForSubTree < 0) { l_cloned = null; }*/ }
8
@Override public void mouseDragged(MouseEvent event) { if (isEnabled()) { boolean wasPressed = mPressed; mPressed = isOver(event.getX(), event.getY()); if (mPressed != wasPressed) { repaint(); } } }
2
public String getId() { return id; }
0
public void keyPressed(int k) { if(k == KeyEvent.VK_LEFT) player.setLeft(true); if(k == KeyEvent.VK_RIGHT) player.setRight(true); if(k == KeyEvent.VK_UP) player.setUp(true); if(k == KeyEvent.VK_DOWN) player.setDown(true); if(k == KeyEvent.VK_W) player.setJumping(true); if(k == KeyEvent.VK_R) player.setScratching(); if(k == KeyEvent.VK_F) player.setFiring(); }
7
public static boolean Read(String hostname) { try { BufferedReader prefixes = new BufferedReader(new FileReader(PrefixesFile)); String line; while((line = prefixes.readLine()) != null) { System.out.println("prefixes - readline - " + line);//debug if(!line.contains(" ")){ Utils.Warning("Invalid line in prefixes.txt!"); continue; } String[] split = line.split(" "); if(split.length < 2){ Utils.Warning("Invalid line in prefixes.txt!"); continue; } final String host_trim = hostname.trim(); final String file_trim = split[0].trim(); if(file_trim.equalsIgnoreCase(host_trim)) Prefixes.add(file_trim + " " + split[1]); else//debug { System.out.println("prefixes - no match"); System.out.println(host_trim); System.out.println(file_trim); } } prefixes.close(); BufferedReader suffixes = new BufferedReader(new FileReader(SuffixesFile)); while((line = suffixes.readLine()) != null) { System.out.println("suffixes - readline - " + line);//debug if(!line.contains(" ")){ Utils.Warning("Invalid line in suffixes.txt!"); continue; } String[] split = line.split(" "); if(split.length < 2){ Utils.Warning("Invalid line in suffixes.txt!"); continue; } final String host_trim = hostname.trim(); final String file_trim = split[0].trim(); if(file_trim.equalsIgnoreCase(host_trim)) Suffixes.add(file_trim + " " + split[1]); else//debug { System.out.println("prefixes - no match"); System.out.println(file_trim); System.out.println(host_trim); } } suffixes.close(); return true; } catch(Exception e) { Utils.LogException(e, "reading prefixes/suffixes"); return false; } }
9
protected JTable createTable(Transition transition) { JTable table = super.createTable(transition); if (!blockTransition) { TableColumn directionColumn = table.getColumnModel().getColumn(2); directionColumn.setCellEditor(new DefaultCellEditor(BOX) { public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { final JComboBox c = (JComboBox) super .getTableCellEditorComponent(table, value, isSelected, row, column); InputMap imap = c.getInputMap(); ActionMap amap = c.getActionMap(); Object o = new Object(); amap.put(o, CHANGE_ACTION); for (int i = 0; i < STROKES.length; i++) imap.put(STROKES[i], o); return c; } }); } return table; }
2
@Override public void dataModificationStateChanged(Object obj, boolean modified) { if (modified) { setIcon(StdImage.MODIFIED_MARKER); setToolTipText(MODIFIED); } else { setIcon(StdImage.NOT_MODIFIED_MARKER); setToolTipText(NOT_MODIFIED); } repaint(); JRootPane rootPane = getRootPane(); if (rootPane != null) { rootPane.putClientProperty("Window.documentModified", modified ? Boolean.TRUE : Boolean.FALSE); //$NON-NLS-1$ } }
3
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); }
0
public double distance(Color color, int mode) { if (mode == RGB_DISTANCE) { int red = this.getRed()-color.getRed(); int green = this.getGreen()-color.getGreen(); int blue = this.getBlue()-color.getBlue(); return Math.sqrt(red*red + green*green + blue*blue); } else if (mode == HSV_DISTANCE) { return 1000; } else { throw new IllegalArgumentException("Unknown distance calculation mode"); } }
2
private static Object[] compare(Scanner testOutputScanner, Scanner correctFileScanner, boolean hadError) { StringBuilder correctOutputStrBldr = new StringBuilder(); StringBuilder testOutputStrBldr = new StringBuilder(); boolean correct = true; while (testOutputScanner.hasNextLine()) { String correctLine = correctFileScanner.hasNextLine() ? correctFileScanner.nextLine() : null; if (correctLine != null) { correctOutputStrBldr.append(correctLine + "\n"); String testLine = testOutputScanner.nextLine(); testOutputStrBldr.append(testLine + "\n"); // Check if this line was supposed to be an error. if (correctLine.indexOf(ERROR_PREFIX) == 0) { String expectedError = correctLine.substring(ERROR_PREFIX.length()); // Either not an error, or the wrong error if (testLine.indexOf(expectedError) != 0) { correct = false; } break; } // Incorrect output if (!correctLine.equals(testLine)) { correct = false; break; } } else { // Not enough output - incorrect correct = false; break; } } // Test output had extra stuff in it while (!hadError && testOutputScanner.hasNextLine()) { correct = false; testOutputStrBldr.append(testOutputScanner.nextLine() + "\n"); } return new Object[] {correct, testOutputStrBldr.toString().replaceAll(System.getProperty("line.separator"), "\n").trim(), correctOutputStrBldr.toString().replaceAll(System.getProperty("line.separator"), "\n").trim()}; }
8
private void relaxLength(Edge e, Node prevNode) { Node nextNode; if (prevNode.equals(e.getFromNode())) { nextNode = e.getToNode(); } else { nextNode = e.getFromNode(); } double g_Score = prevNode.getDistTo() + e.getLength(); if (g_Score < nextNode.getDistTo()) { edgeTo.put(nextNode, e); double h_Score = Math.sqrt(Math.pow((toNode.getxCoord() - nextNode.getxCoord()), 2) + Math.pow(toNode.getyCoord() - nextNode.getyCoord(), 2)) / 1000; double f_Score = h_Score + g_Score; pQueue.remove(nextNode); nextNode.setDistTo(g_Score); nextNode.setHeuristic(f_Score); pQueue.add(nextNode); } /* if(edgeTo.containsKey(nextNode)) return; if (nextNode.getDistTo() > prevNode.getDistTo() + e.getLength()) { nextNode.setDistTo(prevNode.getDistTo()+e.getLength() + Math.sqrt(Math.pow((toNode.getxCoord()-nextNode.getxCoord()), 2)+Math.pow(toNode.getyCoord()-nextNode.getyCoord(), 2))); edgeTo.put(nextNode, e); if (pQueue.contains(nextNode)){ pQueue.remove(nextNode);pQueue.add(nextNode);} else pQueue.add(nextNode); } */ }
2
static Point2D interseccionSq(Line2D l1,Line2D l2){ Point2D p=interseccionLn(l1, l2);if(p==null)return null; double p1x=l1.getX1(),p1y=l1.getY1(),p2x=l1.getX2(),p2y=l1.getY2(),q1x=l2.getX1(), q1y=l2.getY1(),q2x=l2.getX2(),q2y=l2.getY2(),px=p.getX(),py=p.getY(); if(px<=Math.max(p1x,p2x)&&px>=Math.min(p1x,p2x)&&py<=Math.max(p1y,p2y)&& py>=Math.min(p1y,p2y)&&px<=Math.max(q1x,q2x)&&px>=Math.min(q1x,q2x)&& py<=Math.max(q1y,q2y)&&py>=Math.min(q1y,q2y))return p; return null; }
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(CadastraPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadastraPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadastraPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadastraPedido.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 CadastraPedido().setVisible(true); } }); }
6
public boolean incrementIndexes() { if ( fixedRow && fixedColumn || !fixedRow && rowIndex >= maxSize - 1 || !fixedColumn && columnIndex >= maxSize - 1 ) { return false; } if ( !fixedRow ) { rowIndex++; } if ( !fixedColumn ) { columnIndex++; } return true; }
8
AddRecord (MainWindow p) { parent = p; textFields = new ArrayList<JTextField>(0); String[] months = { "January","February","March","April","May","June", "July","August","September","October","November","December" }; int currentYear = Calendar.getInstance().get(Calendar.YEAR); int currentMonth = Calendar.getInstance().get(Calendar.MONTH); int currentDay = Calendar.getInstance().get(Calendar.DATE); //set up the current month's index int monthIndex = 0; for(int i=0;i<months.length;i++) { if (i == currentMonth) { monthIndex = i; break; } } //set up the current day's index ArrayList<String> days = new ArrayList<String>(0); int dayIndex = 0; for(int i=1;i<=31;i++) { String addme = ""; if (i<=9) addme = "0" + Integer.toString(i); else addme = Integer.toString(i); days.add(addme); if(i == currentDay) dayIndex = i-1; } String [] theDays = days.toArray(new String[days.size()]); int yearIndex = 0; ArrayList<String> years = new ArrayList<String>(0); int t = 0; for(int i=currentYear-10;i<currentYear+1;i++) { years.add(Integer.toString(i)); if (i == currentYear) yearIndex = t; t++; } String [] theYears = years.toArray(new String[years.size()]); /* *create a grouplayout here */ //this is my stuff here Border paneEdge = BorderFactory.createEmptyBorder(10,10,10,10); Border gridEdge = BorderFactory.createEmptyBorder(5,5,5,5); //top,left,bottom,right Border lowered = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED); Border compound = BorderFactory.createCompoundBorder(paneEdge,lowered); JLabel acctNoLabel = new JLabel("Account No."); JLabel stickerNoLabel = new JLabel("Sticker No."); JLabel fnameLabel = new JLabel("First Name"); JLabel lnameLabel = new JLabel("Last Name"); JLabel addressLabel = new JLabel("Address"); JLabel cityLabel = new JLabel("City"); JLabel stateLabel = new JLabel("State"); JLabel zipLabel = new JLabel("Zip"); JLabel typeLabel = new JLabel("Type"); JLabel beginLabel = new JLabel("Begin Date"); JLabel endLabel = new JLabel("End Date"); JTextField acctNoField = new JTextField(); JTextField stickerNoField = new JTextField(); JTextField fnameField = new JTextField(); JTextField lnameField = new JTextField(); JTextField addressField = new JTextField(); JTextField cityField = new JTextField(); JTextField stateField = new JTextField(); JTextField zipField = new JTextField(); textFields.add(acctNoField); textFields.add(stickerNoField); textFields.add(fnameField); textFields.add(lnameField); textFields.add(addressField); textFields.add(cityField); textFields.add(stateField); textFields.add(zipField); JButton saveChanges = new JButton("Save Changes"); AddRecordAction addRecordAction = new AddRecordAction(this); saveChanges.addActionListener(addRecordAction); bgroup = new ButtonGroup(); JPanel choices = new JPanel(); choices.setLayout(new BoxLayout(choices,BoxLayout.PAGE_AXIS)); String[] buttons = {"Residential","Business"}; for(int i=0;i<buttons.length;i++) { JRadioButton b = new JRadioButton(buttons[i]); bgroup.add(b); choices.add(b); if (i==0) b.setSelected(true); } beginMonth = new JComboBox<String>(months); beginMonth.setBackground(Color.white); beginMonth.setSelectedIndex(monthIndex); beginDay = new JComboBox<String>(theDays); beginDay.setBackground(Color.white); beginDay.setSelectedIndex(dayIndex); beginYear = new JComboBox<String>(theYears); beginYear.setBackground(Color.white); beginYear.setSelectedIndex(yearIndex); JPanel beginPanel = new JPanel(new FlowLayout(FlowLayout.LEADING,5,0)); // beginPanel.setBackground(Color.yellow); beginPanel.add(beginMonth); beginPanel.add(beginDay); beginPanel.add(beginYear); JPanel panel = new JPanel(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); //automatically add gaps between components layout.setAutoCreateGaps(true); //turn on gaps for components that touch the container?? layout.setAutoCreateContainerGaps(true); //sequential group, horizontal axis GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); // The sequential group in turn contains two parallel groups. // One parallel group contains the labels, the other the text fields. // Putting the labels in a parallel group along the horizontal axis // positions them at the same x location. // // Variable indentation is used to reinforce the level of grouping. // Create a sequential group for the vertical axis. GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); // The sequential group contains two parallel groups that align // the contents along the baseline. The first parallel group contains // the first label and text field, and the second parallel group contains // the second label and text field. By using a sequential group // the labels and text fields are positioned vertically after one another. //the first horizontal group will contain a parallel group with the labels hGroup.addGroup(layout.createParallelGroup(). addComponent(acctNoLabel) .addComponent(stickerNoLabel) .addComponent(fnameLabel) .addComponent(lnameLabel) .addComponent(addressLabel) .addComponent(cityLabel) .addComponent(stateLabel) .addComponent(zipLabel) .addComponent(typeLabel) .addComponent(beginLabel) // .addComponent(endLabel) ); //the next horizontal group contains a parallel group with the textfields hGroup.addGroup(layout.createParallelGroup(). addComponent(acctNoField) .addComponent(stickerNoField) .addComponent(fnameField) .addComponent(lnameField) .addComponent(addressField) .addComponent(cityField) .addComponent(stateField) .addComponent(zipField) .addComponent(choices) .addComponent(beginPanel) // .addComponent(endPanel) ); //the first vertical group will contain one label and one text field vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(acctNoLabel) .addComponent(acctNoField) ); vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(stickerNoLabel) .addComponent(stickerNoField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(fnameLabel) .addComponent(fnameField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(lnameLabel) .addComponent(lnameField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(addressLabel) .addComponent(addressField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(cityLabel) .addComponent(cityField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(stateLabel) .addComponent(stateField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(zipLabel) .addComponent(zipField) ); //next vertical group vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(typeLabel) .addComponent(choices) ); vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). addComponent(beginLabel) .addComponent(beginPanel) ); // vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE). // addComponent(endLabel) // .addComponent(endPanel) // ); layout.setHorizontalGroup(hGroup); layout.setVerticalGroup(vGroup); //make a panel just for the save changes button JPanel buttonPanel = new JPanel(); buttonPanel.add(saveChanges); //make a panel to hold the "panel" and the buttonpanel JPanel lfbPanel = new JPanel(); lfbPanel.setLayout(new BoxLayout(lfbPanel,BoxLayout.PAGE_AXIS)); lfbPanel.setBorder(compound); lfbPanel.add(panel); lfbPanel.add(buttonPanel); JPanel slPanel = new JPanel(); slPanel.setLayout(new BoxLayout(slPanel,BoxLayout.LINE_AXIS)); slPanel.setBorder(gridEdge); statusText = new JLabel(" "); slPanel.add(Box.createHorizontalGlue()); slPanel.add(statusText); JPanel statusPanel = new JPanel(); statusPanel.setLayout(new BoxLayout(statusPanel,BoxLayout.LINE_AXIS)); statusPanel.setBorder(compound); statusPanel.add(slPanel); setLayout(new BorderLayout()); add(lfbPanel,BorderLayout.PAGE_START); add(statusPanel,BorderLayout.PAGE_END); // add(saveChanges); }//end constructor
9
private void kingTopPossibleMove(Piece piece, Position position) { int x1 = position.getPositionX(); int y1 = position.getPositionY(); if((x1 >= 0 && y1 >= 0) && (x1 < maxWidth && y1 <= 6)) { if(board.getChessBoardSquare(x1, y1+1).getPiece().getPieceType() != board.getBlankPiece().getPieceType()) { if(board.getChessBoardSquare(x1, y1+1).getPiece().getPieceColor() != piece.getPieceColor()) { // System.out.print(" " + coordinateToPosition(x1, y1+1)+"*"); Position newMove = new Position(x1, y1+1); piece.setPossibleMoves(newMove); } } else { // System.out.print(" " + coordinateToPosition(x1, y1+1)); Position newMove = new Position(x1, y1+1); piece.setPossibleMoves(newMove); } } }
6
CtNewClass(String name, ClassPool cp, boolean isInterface, CtClass superclass) { super(name, cp); wasChanged = true; String superName; if (isInterface || superclass == null) superName = null; else superName = superclass.getName(); classfile = new ClassFile(isInterface, name, superName); if (isInterface && superclass != null) classfile.setInterfaces(new String[] { superclass.getName() }); setModifiers(Modifier.setPublic(getModifiers())); hasConstructor = isInterface; }
4
private int compareFuncSanitise(int func) { switch (func) { case NEVER: return 0; case LESS: return 1; case LEQUAL: return 2; case GREATER: return 3; case GEQUAL: return 4; case EQUAL: return 5; case NOTEQUAL: return 6; case ALWAYS: return 7; default: throw nope("Invalid enum."); } }
8
@Override public void setAccounting(Accounting accounting) { setAccountTypes(accounting == null ? null : accounting.getAccountTypes()); setAccounts(accounting == null ? null : accounting.getAccounts()); // could be popup.setAccounting() with constructor call in this.constructor popup = new AccountsPopupMenu(accounts, accountTypes); setJournals(accounting == null ? null : accounting.getJournals()); }
3
public void studentCategorySubscribe(String userid, String categoryName){ int catId = CategoryDao.getCategoryIdByName(categoryName); int id = PersonDao.fetchPersonId(userid); //deleteSubscribedCategories(id); ResultSet rs=null; Connection con=null; PreparedStatement ps=null; try{ String sql="INSERT INTO STUDENT_CATEGORY_MAPPING(s_id, c_id) VALUES (?,?)"; con=ConnectionPool.getConnectionFromPool();; ps=con.prepareStatement(sql); ps.setInt(1, id); ps.setInt(2, catId); ps.execute(); } catch(Exception ex) { ex.printStackTrace(); } finally{ if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con!=null) { try { ConnectionPool.addConnectionBackToPool(con);; } catch (Exception e) { e.printStackTrace(); } } } }
7
public Entity findEntityGlobal(int ID) { for (Layer L : gameLayers) { for (Entity e : L.getEntList() ) { if (e.getID() == ID) { return e; } } } return new Entity(-1); }
3
@Override public void run() { Type type = game.getType(); Player player = game.getPlayer(); String name = type.getName(); Double cost = type.getCost(); Double won = 0.0; Stat stat; ArrayList<Reward> results = getResults(); if(!results.isEmpty()) { // Send the rewards for(Reward reward : results) { game.plugin.rewardData.send(player, reward); won += reward.getMoney(); } // Managed SlotMachine slot = game.getSlot(); if(slot.isManaged()) { slot.withdraw(won); Double max = game.plugin.typeData.getMaxPrize(type.getName()); if(slot.getFunds() < max) { slot.setEnabled(false); } game.plugin.slotData.saveSlot(slot); game.plugin.configData.saveSlots(); } } // No win else { game.plugin.sendMessage(player, type.getMessages().get("noWin")); } // Register statistics if(game.plugin.configData.trackStats) { if(game.plugin.statsData.isStat(name)) { stat = game.plugin.statsData.getStat(name); stat.add(won, cost); } else { stat = new Stat(name, 1, won, cost); } game.plugin.statsData.addStat(stat); if(!results.isEmpty()) { game.plugin.configData.saveStats(); } } // All done game.getSlot().toggleBusy(); }
7
@Override public String getCity() { return super.getCity(); }
0
public void doExplosionB(boolean par1) { this.worldObj.playSoundEffect(this.explosionX, this.explosionY, this.explosionZ, "random.explode", 4.0F, (1.0F + (this.worldObj.rand.nextFloat() - this.worldObj.rand.nextFloat()) * 0.2F) * 0.7F); this.worldObj.spawnParticle("hugeexplosion", this.explosionX, this.explosionY, this.explosionZ, 0.0D, 0.0D, 0.0D); ArrayList var2 = new ArrayList(); var2.addAll(this.destroyedBlockPositions); int var3; ChunkPosition var4; int var5; int var6; int var7; int var8; for (var3 = var2.size() - 1; var3 >= 0; --var3) { var4 = (ChunkPosition)var2.get(var3); var5 = var4.x; var6 = var4.y; var7 = var4.z; var8 = this.worldObj.getBlockId(var5, var6, var7); if (par1) { double var9 = (double)((float)var5 + this.worldObj.rand.nextFloat()); double var11 = (double)((float)var6 + this.worldObj.rand.nextFloat()); double var13 = (double)((float)var7 + this.worldObj.rand.nextFloat()); double var15 = var9 - this.explosionX; double var17 = var11 - this.explosionY; double var19 = var13 - this.explosionZ; double var21 = (double)MathHelper.sqrt_double(var15 * var15 + var17 * var17 + var19 * var19); var15 /= var21; var17 /= var21; var19 /= var21; double var23 = 0.5D / (var21 / (double)this.explosionSize + 0.1D); var23 *= (double)(this.worldObj.rand.nextFloat() * this.worldObj.rand.nextFloat() + 0.3F); var15 *= var23; var17 *= var23; var19 *= var23; this.worldObj.spawnParticle("explode", (var9 + this.explosionX * 1.0D) / 2.0D, (var11 + this.explosionY * 1.0D) / 2.0D, (var13 + this.explosionZ * 1.0D) / 2.0D, var15, var17, var19); this.worldObj.spawnParticle("smoke", var9, var11, var13, var15, var17, var19); } if (var8 > 0) { Block.blocksList[var8].dropBlockAsItemWithChance(this.worldObj, var5, var6, var7, this.worldObj.getBlockMetadata(var5, var6, var7), 0.3F, 0); this.worldObj.setBlockWithNotify(var5, var6, var7, 0); Block.blocksList[var8].onBlockDestroyedByExplosion(this.worldObj, var5, var6, var7); } } if (this.isFlaming) { for (var3 = var2.size() - 1; var3 >= 0; --var3) { var4 = (ChunkPosition)var2.get(var3); var5 = var4.x; var6 = var4.y; var7 = var4.z; var8 = this.worldObj.getBlockId(var5, var6, var7); int var25 = this.worldObj.getBlockId(var5, var6 - 1, var7); if (var8 == 0 && Block.opaqueCubeLookup[var25] && this.explosionRNG.nextInt(3) == 0) { this.worldObj.setBlockWithNotify(var5, var6, var7, Block.fire.blockID); } } } }
8
@Override public void simpleRender(RenderManager rm) { }
0
public static void UpdateGeneratorPath(String profile, String genername, String generpath) { File file = new File(profile); if (file.exists()) { try { // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); doc.normalize(); NodeList nodelist = doc.getElementsByTagName(GENERATOR); if (nodelist.getLength() != 0) { Element elem; for (int i = 0; i < nodelist.getLength(); i++) { elem = (Element)nodelist.item(i); //find the generator if (elem.getAttribute("name").equals(genername)) { //find Generator path node nodelist = elem.getElementsByTagName(GENERATORPATH); if (nodelist.getLength() == 1) { elem = (Element)nodelist.item(0); if (elem.getFirstChild() != null) elem.getFirstChild().setNodeValue(generpath); doc2XmlFile(doc, profile); } } } } } catch (Exception e) { System.out.println(e.toString()); e.getStackTrace(); } } }
7
public List<Book> getBooksByBookCategory(int branch_id, int [] bookcategory_id) { List<Book> list = new ArrayList<>(); Connection con = null; Statement stmt = null; try { DBconnection dbCon = new DBconnection(); Class.forName(dbCon.getJDBC_DRIVER()); con = DriverManager.getConnection(dbCon.getDATABASE_URL(), dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD()); stmt = con.createStatement(); String query="SELECT * FROM book Inner Join bookstatus On bookstatus_id=bks_id Where bookcategory_id IN ("; for(int bcid:bookcategory_id) { query+=bcid+","; } query=Utils.str_RemoveLastChar(query); query+=") AND branch_id= "+branch_id+" Order by bok_id"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Book book = new Book(); book.setId(rs.getLong(1)); book.setTitle(rs.getString(2)); book.setSubtitle(rs.getString(3)); book.setIsbn(rs.getString(4)); book.setPublisher(rs.getString(5)); book.setPublishDate(rs.getDate(6)); book.setPagesNb(rs.getInt(7)); book.setBookCategory_id(rs.getLong(8)); book.setLanguage_id(rs.getLong(9)); book.setAuthor_id(rs.getLong(10)); book.setItem_id(rs.getLong(11)); book.setBookStatus_id(rs.getLong(12)); list.add(book); } } catch (SQLException | ClassNotFoundException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.err.println("Caught Exception: " + ex.getMessage()); } } System.err.println(list.size()); return list; }
6
private void bellmanFord(int source, int[] dist, HashMap<Integer, HashMap<Integer, Integer>> g){ dist[source]=0; for(int i=1;i<dist.length;i++){ for(int j=1;j<dist.length;j++){ if(dist[j]<Integer.MAX_VALUE){ for(int neighbor:g.get(j).keySet()){ if(dist[neighbor] > dist[j]+g.get(j).get(neighbor)){ dist[neighbor] = dist[j]+g.get(j).get(neighbor); } } } } } }
5
@Before public void putDataCountingSort(){ a = new int[MAX]; for(int i = 0; i < MAX; ++i){ a[i] = i + 1; } shuffleIntArray(a); }
1
public void executeSetMethod(Object instance, Method method, Object value) { if(method == null) return; try { method.invoke(instance, value); } catch (IllegalArgumentException e) { System.err.println("<ClassInspect> Failed to execute SET Method <" + method.getName() + ">. Arguments passed to method is wrong."); } catch (IllegalAccessException e) { System.err.println("<ClassInspect> Failed to execute SET Method <" + method.getName() + ">. Method isn't marked as public."); } catch (InvocationTargetException e) { System.err.println("<ClassInspect> Failed to execute SET Method <" + method.getName() + ">. Exception: \n" + e.getMessage()); } }
4
private JMenuBar createMainMenu(ActionListener listener) { JMenuBar menuBar = new JMenuBar(); JMenu menu, submenu; JMenuItem menuItem; // // File Menu // menu = new JMenu(language.getString("menu_file")); menu.setMnemonic(KeyEvent.VK_F); menuBar.add(menu); if (controller.isRunningAsApplet()) { menuItem = new JMenuItem(language.getString("send_oekaki"), KeyEvent.VK_V); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("send_oekaki_hint")); menuItem.setActionCommand("CPSend"); menuItem.addActionListener(listener); menu.add(menuItem); } // // Edit Menu // menu = new JMenu(language.getString("menu_edit")); menu.setMnemonic(KeyEvent.VK_E); menuBar.add(menu); menuItem = new JMenuItem(language.getString("undo"), KeyEvent.VK_U); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("undo_hint")); menuItem.setActionCommand("CPUndo"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("redo"), KeyEvent.VK_R); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("redo_hint")); menuItem.setActionCommand("CPRedo"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("clear_memory"), KeyEvent.VK_H); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("clear_memory_hint")); menuItem.setActionCommand("CPClearHistory"); menuItem.addActionListener(listener); menu.add(menuItem); menu.add(new JSeparator()); menuItem = new JMenuItem(language.getString("cut"), KeyEvent.VK_T); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setActionCommand("CPCut"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("copy"), KeyEvent.VK_C); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setActionCommand("CPCopy"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("copy_merged"), KeyEvent.VK_Y); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setActionCommand("CPCopyMerged"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("paste"), KeyEvent.VK_P); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setActionCommand("CPPaste"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); menu.add(menuItem); menu.add(new JSeparator()); menuItem = new JMenuItem(language.getString("select_all"), KeyEvent.VK_A); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("select_all_hint")); menuItem.setActionCommand("CPSelectAll"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("deselect"), KeyEvent.VK_D); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("deselect_hint")); menuItem.setActionCommand("CPDeselectAll"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK)); menu.add(menuItem); menu = new JMenu(language.getString("menu_layers")); menu.setMnemonic(KeyEvent.VK_L); menuBar.add(menu); menuItem = new JMenuItem(language.getString("duplicate"), KeyEvent.VK_D); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("duplicate_hint")); menuItem.setActionCommand("CPLayerDuplicate"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK)); menu.add(menuItem); menu.add(new JSeparator()); menuItem = new JMenuItem(language.getString("merge_down"), KeyEvent.VK_E); menuItem.getAccessibleContext().setAccessibleDescription( language.getString("merge_down_hint")); menuItem.setActionCommand("CPLayerMergeDown"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK)); menu.add(menuItem); /* * menuItem = new JMenuItem("Merge Visible", KeyEvent.VK_V); * menuItem.getAccessibleContext().setAccessibleDescription("Merges all the visible layers"); * menuItem.setActionCommand("CPLayerMergeVisible"); menuItem.addActionListener(listener); * menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK | * ActionEvent.SHIFT_MASK)); menu.add(menuItem); */ menuItem = new JMenuItem(language.getString("merge_visible"), KeyEvent.VK_A); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("merge_visible_hint")); menuItem.setActionCommand("CPLayerMergeAll"); menuItem.addActionListener(listener); menu.add(menuItem); // // Effects Menu // menu = new JMenu(language.getString("menu_effects")); menu.setMnemonic(KeyEvent.VK_E); menuBar.add(menu); menuItem = new JMenuItem(language.getString("clear"), KeyEvent.VK_C); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("clear_hint")); menuItem.setActionCommand("CPClear"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("fill"), KeyEvent.VK_F); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("fill_hint")); menuItem.setActionCommand("CPFill"); menuItem.addActionListener(listener); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); menu.add(menuItem); menuItem = new JMenuItem(language.getString("flip_h"), KeyEvent.VK_H); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("flip_h_hint")); menuItem.setActionCommand("CPHFlip"); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem(language.getString("flip_v"), KeyEvent.VK_V); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("flip_v_hint")); menuItem.setActionCommand("CPVFlip"); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem(language.getString("invert"), KeyEvent.VK_I); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("invert_h")); menuItem.setActionCommand("CPFXInvert"); menuItem.addActionListener(listener); menu.add(menuItem); submenu = new JMenu(language.getString("blur")); submenu.setMnemonic(KeyEvent.VK_B); menuItem = new JMenuItem(language.getString("box_blur"), KeyEvent.VK_B); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("box_blur_hint")); menuItem.setActionCommand("CPFXBoxBlur"); menuItem.addActionListener(listener); submenu.add(menuItem); menu.add(submenu); submenu = new JMenu(language.getString("menu_noise")); submenu.setMnemonic(KeyEvent.VK_N); menuItem = new JMenuItem(language.getString("render_mono"), KeyEvent.VK_M); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("render_mono_hint")); menuItem.setActionCommand("CPMNoise"); menuItem.addActionListener(listener); submenu.add(menuItem); menuItem = new JMenuItem(language.getString("render_color"), KeyEvent.VK_C); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("render_color_hint")); menuItem.setActionCommand("CPCNoise"); menuItem.addActionListener(listener); submenu.add(menuItem); menu.add(submenu); // // View Menu // menu = new JMenu(language.getString("menu_view")); menu.setMnemonic(KeyEvent.VK_V); menuBar.add(menu); if (controller.isRunningAsApplet()) { menuItem = new JMenuItem(language.getString("floating_mode"), KeyEvent.VK_F); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("floating_mode_hint")); menuItem.setActionCommand("CPFloat"); menuItem.addActionListener(listener); menu.add(menuItem); menu.add(new JSeparator()); } menuItem = new JMenuItem(language.getString("zoom_in"), KeyEvent.VK_I); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("CPZoomIn"); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem(language.getString("zoom_out"), KeyEvent.VK_O); menuItem.getAccessibleContext().setAccessibleDescription(""); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("CPZoomOut"); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem(language.getString("zoom_100"), KeyEvent.VK_1); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("zoom_100_hint")); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("CPZoom100"); menuItem.addActionListener(listener); menu.add(menuItem); menu.add(new JSeparator()); menuItem = new JCheckBoxMenuItem(language.getString("linear_int"), false); menuItem.setMnemonic(KeyEvent.VK_L); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("linear_int_hint")); menuItem.setActionCommand("CPLinearInterpolation"); menuItem.addActionListener(listener); menu.add(menuItem); menu.add(new JSeparator()); menuItem = new JCheckBoxMenuItem(language.getString("show_grid"), false); menuItem.setMnemonic(KeyEvent.VK_G); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("show_grid_hint")); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK)); menuItem.setActionCommand("CPToggleGrid"); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem(language.getString("grid_opt"), KeyEvent.VK_D); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("grid_opt_hint")); menuItem.setActionCommand("CPGridOptions"); menuItem.addActionListener(listener); menu.add(menuItem); menu.add(new JSeparator()); submenu = new JMenu(language.getString("menu_palettes")); submenu.setMnemonic(KeyEvent.VK_P); menuItem = new JMenuItem(language.getString("toggle_palettes"), KeyEvent.VK_P); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("toggle_palettes_hint")); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)); menuItem.setActionCommand("CPTogglePalettes"); menuItem.addActionListener(listener); submenu.add(menuItem); submenu.add(new JSeparator()); menuItem = new JCheckBoxMenuItem(language.getString("show_brush"), true); menuItem.setMnemonic(KeyEvent.VK_B); menuItem.setActionCommand("CPPalBrush"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Brush", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_color"), true); menuItem.setMnemonic(KeyEvent.VK_C); menuItem.setActionCommand("CPPalColor"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Color", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_layers"), true); menuItem.setMnemonic(KeyEvent.VK_Y); menuItem.setActionCommand("CPPalLayers"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Layers", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_misc"), true); menuItem.setMnemonic(KeyEvent.VK_M); menuItem.setActionCommand("CPPalMisc"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Misc", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_stroke"), true); menuItem.setMnemonic(KeyEvent.VK_S); menuItem.setActionCommand("CPPalStroke"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Stroke", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_swatches"), true); menuItem.setMnemonic(KeyEvent.VK_W); menuItem.setActionCommand("CPPalSwatches"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Color Swatches", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_textures"), true); menuItem.setMnemonic(KeyEvent.VK_X); menuItem.setActionCommand("CPPalTextures"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Textures", (JCheckBoxMenuItem) menuItem); menuItem = new JCheckBoxMenuItem(language.getString("show_tools"), true); menuItem.setMnemonic(KeyEvent.VK_T); menuItem.setActionCommand("CPPalTool"); menuItem.addActionListener(listener); submenu.add(menuItem); paletteItems.put("Tools", (JCheckBoxMenuItem) menuItem); menu.add(submenu); // // Help Menu // menu = new JMenu(language.getString("menu_help")); menu.setMnemonic(KeyEvent.VK_H); menuBar.add(menu); menuItem = new JMenuItem(language.getString("about"), KeyEvent.VK_A); menuItem.getAccessibleContext().setAccessibleDescription(language.getString("about_hint")); menuItem.setActionCommand("CPAbout"); menuItem.addActionListener(listener); menu.add(menuItem); return menuBar; }
2
public void clickBlock(int par1, int par2, int par3, int par4) { if (this.creativeMode) { this.netClientHandler.addToSendQueue(new Packet14BlockDig(0, par1, par2, par3, par4)); PlayerControllerCreative.clickBlockCreative(this.mc, this, par1, par2, par3, par4); this.blockHitDelay = 5; } else if (!this.isHittingBlock || par1 != this.currentBlockX || par2 != this.currentBlockY || par3 != this.currentblockZ) { this.netClientHandler.addToSendQueue(new Packet14BlockDig(0, par1, par2, par3, par4)); int var5 = this.mc.theWorld.getBlockId(par1, par2, par3); if (var5 > 0 && this.curBlockDamageMP == 0.0F) { Block.blocksList[var5].onBlockClicked(this.mc.theWorld, par1, par2, par3, this.mc.thePlayer); } if (var5 > 0 && Block.blocksList[var5].blockStrength(mc.theWorld, mc.thePlayer, par1, par2, par3) >= 1.0F) { this.onPlayerDestroyBlock(par1, par2, par3, par4); } else { this.isHittingBlock = true; this.currentBlockX = par1; this.currentBlockY = par2; this.currentblockZ = par3; this.curBlockDamageMP = 0.0F; this.prevBlockDamageMP = 0.0F; this.stepSoundTickCounter = 0.0F; } } }
9
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Facility)) { return false; } Facility other = (Facility) object; if ((this.facilityID == null && other.facilityID != null) || (this.facilityID != null && !this.facilityID.equals(other.facilityID))) { return false; } return true; }
5
public void testSetText() { try { ISOChronology.getInstanceUTC().year().set(0, null, java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals(null, e.getIllegalStringValue()); assertEquals("null", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().year().set(0, "nineteen seventy", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.year(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("year", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("nineteen seventy", e.getIllegalStringValue()); assertEquals("nineteen seventy", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().era().set(0, "long ago", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.era(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("era", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("long ago", e.getIllegalStringValue()); assertEquals("long ago", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().monthOfYear().set(0, "spring", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.monthOfYear(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("monthOfYear", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("spring", e.getIllegalStringValue()); assertEquals("spring", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().dayOfWeek().set(0, "yesterday", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.dayOfWeek(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("dayOfWeek", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("yesterday", e.getIllegalStringValue()); assertEquals("yesterday", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } try { ISOChronology.getInstanceUTC().halfdayOfDay().set(0, "morning", java.util.Locale.US); fail(); } catch (IllegalFieldValueException e) { assertEquals(DateTimeFieldType.halfdayOfDay(), e.getDateTimeFieldType()); assertEquals(null, e.getDurationFieldType()); assertEquals("halfdayOfDay", e.getFieldName()); assertEquals(null, e.getIllegalNumberValue()); assertEquals("morning", e.getIllegalStringValue()); assertEquals("morning", e.getIllegalValueAsString()); assertEquals(null, e.getLowerBound()); assertEquals(null, e.getUpperBound()); } }
6
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { String name = method.getName(); if (name.equals("close")) { boolean previouslyClosed = closed.getAndSet(true); if (config.isEnabled(Check.RESULT_SET_DOUBLE_CLOSE) && previouslyClosed) { Utils.fail(config, exception, "ResultSet already closed"); } if (!unreadColumns.isEmpty()) { rs.close(); checkUnreadColumns(); } return null; } if (name.equals("next")) { return next(); } else if (GETTERS.contains(name)) { String columnLabel; if (args[0] instanceof Integer) { columnLabel = columnIndexToLabel((Integer) args[0]); } else { columnLabel = (String) args[0]; } unreadColumns.remove(columnLabel); } try { Object returnVal = method.invoke(rs, args); if (name.equals("getBlob")) { returnVal = BlobProxy.newInstance((Blob) returnVal, config); } return returnVal; } catch (InvocationTargetException ite) { throw ite.getTargetException(); } }
9
public void onLivingUpdate() { if (!this.worldObj.isRemote) { if (this.isWet()) { this.attackEntityFrom(DamageSource.drown, 1); } --this.heightOffsetUpdateTime; if (this.heightOffsetUpdateTime <= 0) { this.heightOffsetUpdateTime = 100; this.heightOffset = 0.5F + (float)this.rand.nextGaussian() * 3.0F; } if (this.getEntityToAttack() != null && this.getEntityToAttack().posY + (double)this.getEntityToAttack().getEyeHeight() > this.posY + (double)this.getEyeHeight() + (double)this.heightOffset) { this.motionY += (0.30000001192092896D - this.motionY) * 0.30000001192092896D; } } if (this.rand.nextInt(24) == 0) { this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.fire", 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F); } if (!this.onGround && this.motionY < 0.0D) { this.motionY *= 0.6D; } for (int var1 = 0; var1 < 2; ++var1) { this.worldObj.spawnParticle("largesmoke", this.posX + (this.rand.nextDouble() - 0.5D) * (double)this.width, this.posY + this.rand.nextDouble() * (double)this.height, this.posZ + (this.rand.nextDouble() - 0.5D) * (double)this.width, 0.0D, 0.0D, 0.0D); } super.onLivingUpdate(); }
9
public int getsockopt(int option_) { if (ctx_terminated) { ZError.errno(ZError.ETERM); return -1; } if (option_ == ZMQ.ZMQ_RCVMORE) { return rcvmore ? 1 : 0; } if (option_ == ZMQ.ZMQ_EVENTS) { boolean rc = process_commands (0, false); if (!rc && (ZError.is(ZError.EINTR) || ZError.is(ZError.ETERM))) return -1; assert (rc); int val = 0; if (has_out ()) val |= ZMQ.ZMQ_POLLOUT; if (has_in ()) val |= ZMQ.ZMQ_POLLIN; return val; } return (Integer) getsockoptx(option_); }
9
Type constantType(int id){ Object o = constants.nth(id); Class c = o.getClass(); if(Modifier.isPublic(c.getModifiers())) { //can't emit derived fn types due to visibility if(LazySeq.class.isAssignableFrom(c)) return Type.getType(ISeq.class); else if(c == Keyword.class) return Type.getType(Keyword.class); // else if(c == KeywordCallSite.class) // return Type.getType(KeywordCallSite.class); else if(RestFn.class.isAssignableFrom(c)) return Type.getType(RestFn.class); else if(AFn.class.isAssignableFrom(c)) return Type.getType(AFn.class); else if(c == Var.class) return Type.getType(Var.class); else if(c == String.class) return Type.getType(String.class); // return Type.getType(c); } return OBJECT_TYPE; } } enum PATHTYPE { PATH, BRANCH; } static class PathNode{ final PATHTYPE type; final PathNode parent; PathNode(PATHTYPE type, PathNode parent) { this.type = type; this.parent = parent; } } static PathNode clearPathRoot(){ return (PathNode) CLEAR_ROOT.get(); } enum PSTATE{ REQ, REST, DONE } public static class FnMethod extends ObjMethod{ //localbinding->localbinding PersistentVector reqParms = PersistentVector.EMPTY; LocalBinding restParm = null; Type[] argtypes; Class[] argclasses; Class retClass; String prim ; public FnMethod(ObjExpr objx, ObjMethod parent){ super(objx, parent); } static public char classChar(Object x){ Class c = null; if(x instanceof Class) c = (Class) x; else if(x instanceof Symbol) c = primClass((Symbol) x); if(c == null || !c.isPrimitive()) return 'O'; if(c == long.class) return 'L'; if(c == double.class) return 'D'; throw new IllegalArgumentException("Only long and double primitives are supported"); } static public String primInterface(IPersistentVector arglist) throws Exception{ StringBuilder sb = new StringBuilder(); for(int i=0;i<arglist.count();i++) sb.append(classChar(tagOf(arglist.nth(i)))); sb.append(classChar(tagOf(arglist))); String ret = sb.toString(); boolean prim = ret.contains("L") || ret.contains("D"); if(prim && arglist.count() > 4) throw new IllegalArgumentException("fns taking primitives support only 4 or fewer args"); if(prim) return "clojure.lang.IFn$" + ret; return null; } static FnMethod parse(ObjExpr objx, ISeq form, boolean isStatic) throws Exception{ //([args] body...) IPersistentVector parms = (IPersistentVector) RT.first(form); ISeq body = RT.next(form); try { FnMethod method = new FnMethod(objx, (ObjMethod) METHOD.deref()); method.line = (Integer) LINE.deref(); //register as the current method and set up a new env frame PathNode pnode = (PathNode) CLEAR_PATH.get(); if(pnode == null) pnode = new PathNode(PATHTYPE.PATH,null); Var.pushThreadBindings( RT.map( METHOD, method, LOCAL_ENV, LOCAL_ENV.deref(), LOOP_LOCALS, null, NEXT_LOCAL_NUM, 0 ,CLEAR_PATH, pnode ,CLEAR_ROOT, pnode ,CLEAR_SITES, PersistentHashMap.EMPTY )); method.prim = primInterface(parms); if(method.prim != null) method.prim = method.prim.replace('.', '/'); method.retClass = tagClass(tagOf(parms)); if(method.retClass.isPrimitive() && !(method.retClass == double.class || method.retClass == long.class)) throw new IllegalArgumentException("Only long and double primitives are supported"); //register 'this' as local 0 //registerLocal(THISFN, null, null); if(!isStatic) { if(objx.thisName != null) registerLocal(Symbol.intern(objx.thisName), null, null,false); else getAndIncLocalNum(); } PSTATE state = PSTATE.REQ; PersistentVector argLocals = PersistentVector.EMPTY; ArrayList<Type> argtypes = new ArrayList(); ArrayList<Class> argclasses = new ArrayList(); for(int i = 0; i < parms.count(); i++) { if(!(parms.nth(i) instanceof Symbol)) throw new IllegalArgumentException("fn params must be Symbols"); Symbol p = (Symbol) parms.nth(i); if(p.getNamespace() != null) throw new Exception("Can't use qualified name as parameter: " + p); if(p.equals(_AMP_)) { // if(isStatic) // throw new Exception("Variadic fns cannot be static"); if(state == PSTATE.REQ) state = PSTATE.REST; else throw new Exception("Invalid parameter list"); } else { Class pc = primClass(tagClass(tagOf(p))); // if(pc.isPrimitive() && !isStatic) // { // pc = Object.class; // p = (Symbol) ((IObj) p).withMeta((IPersistentMap) RT.assoc(RT.meta(p), RT.TAG_KEY, null)); // } // throw new Exception("Non-static fn can't have primitive parameter: " + p); if(pc.isPrimitive() && !(pc == double.class || pc == long.class)) throw new IllegalArgumentException("Only long and double primitives are supported: " + p); if(state == PSTATE.REST && tagOf(p) != null) throw new Exception("& arg cannot have type hint"); if(state == PSTATE.REST && method.prim != null) throw new Exception("fns taking primitives cannot be variadic"); if(state == PSTATE.REST) pc = ISeq.class; argtypes.add(Type.getType(pc)); argclasses.add(pc); LocalBinding lb = pc.isPrimitive() ? registerLocal(p, null, new MethodParamExpr(pc), true) : registerLocal(p, state == PSTATE.REST ? ISEQ : tagOf(p), null, true); argLocals = argLocals.cons(lb); switch(state) { case REQ: method.reqParms = method.reqParms.cons(lb); break; case REST: method.restParm = lb; state = PSTATE.DONE; break; default: throw new Exception("Unexpected parameter"); } } } if(method.reqParms.count() > MAX_POSITIONAL_ARITY) throw new Exception("Can't specify more than " + MAX_POSITIONAL_ARITY + " params"); LOOP_LOCALS.set(argLocals); method.argLocals = argLocals; // if(isStatic) if(method.prim != null) { method.argtypes = argtypes.toArray(new Type[argtypes.size()]); method.argclasses = argclasses.toArray(new Class[argtypes.size()]); for(int i = 0; i < method.argclasses.length; i++) { if(method.argclasses[i] == long.class || method.argclasses[i] == double.class) getAndIncLocalNum(); } } method.body = (new BodyExpr.Parser()).parse(C.RETURN, body); return method; } finally { Var.popThreadBindings(); } } public void emit(ObjExpr fn, ClassVisitor cv){ if(prim != null) doEmitPrim(fn, cv); else if(fn.isStatic) doEmitStatic(fn,cv); else doEmit(fn,cv); } public void doEmitStatic(ObjExpr fn, ClassVisitor cv){ Method ms = new Method("invokeStatic", getReturnType(), argtypes); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, ms, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); Label loopLabel = gen.mark(); gen.visitLineNumber(line, loopLabel); try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel, METHOD, this)); emitBody(objx, gen, retClass, body); Label end = gen.mark(); for(ISeq lbs = argLocals.seq(); lbs != null; lbs = lbs.next()) { LocalBinding lb = (LocalBinding) lbs.first(); gen.visitLocalVariable(lb.name, argtypes[lb.idx].getDescriptor(), null, loopLabel, end, lb.idx); } } catch(Exception e) { throw new RuntimeException(e); } finally { Var.popThreadBindings(); } gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); //generate the regular invoke, calling the static method Method m = new Method(getMethodName(), OBJECT_TYPE, getArgTypes()); gen = new GeneratorAdapter(ACC_PUBLIC, m, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); for(int i = 0; i < argtypes.length; i++) { gen.loadArg(i); HostExpr.emitUnboxArg(fn, gen, argclasses[i]); } gen.invokeStatic(objx.objtype, ms); gen.box(getReturnType()); gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); } public void doEmitPrim(ObjExpr fn, ClassVisitor cv){ Method ms = new Method("invokePrim", getReturnType(), argtypes); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC + ACC_FINAL, ms, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); Label loopLabel = gen.mark(); gen.visitLineNumber(line, loopLabel); try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel, METHOD, this)); emitBody(objx, gen, retClass, body); Label end = gen.mark(); gen.visitLocalVariable("this", "Ljava/lang/Object;", null, loopLabel, end, 0); for(ISeq lbs = argLocals.seq(); lbs != null; lbs = lbs.next()) { LocalBinding lb = (LocalBinding) lbs.first(); gen.visitLocalVariable(lb.name, argtypes[lb.idx-1].getDescriptor(), null, loopLabel, end, lb.idx); } } catch(Exception e) { throw new RuntimeException(e); } finally { Var.popThreadBindings(); } gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); //generate the regular invoke, calling the prim method Method m = new Method(getMethodName(), OBJECT_TYPE, getArgTypes()); gen = new GeneratorAdapter(ACC_PUBLIC, m, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); gen.loadThis(); for(int i = 0; i < argtypes.length; i++) { gen.loadArg(i); HostExpr.emitUnboxArg(fn, gen, argclasses[i]); } gen.invokeInterface(Type.getType("L"+prim+";"), ms); gen.box(getReturnType()); gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); } public void doEmit(ObjExpr fn, ClassVisitor cv){ Method m = new Method(getMethodName(), getReturnType(), getArgTypes()); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC, m, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); Label loopLabel = gen.mark(); gen.visitLineNumber(line, loopLabel); try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel, METHOD, this)); body.emit(C.RETURN, fn, gen); Label end = gen.mark(); gen.visitLocalVariable("this", "Ljava/lang/Object;", null, loopLabel, end, 0); for(ISeq lbs = argLocals.seq(); lbs != null; lbs = lbs.next()) { LocalBinding lb = (LocalBinding) lbs.first(); gen.visitLocalVariable(lb.name, "Ljava/lang/Object;", null, loopLabel, end, lb.idx); } } finally { Var.popThreadBindings(); } gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); } public final PersistentVector reqParms(){ return reqParms; } public final LocalBinding restParm(){ return restParm; } boolean isVariadic(){ return restParm != null; } int numParams(){ return reqParms.count() + (isVariadic() ? 1 : 0); } String getMethodName(){ return isVariadic()?"doInvoke":"invoke"; } Type getReturnType(){ if(prim != null) //objx.isStatic) return Type.getType(retClass); return OBJECT_TYPE; } Type[] getArgTypes(){ if(isVariadic() && reqParms.count() == MAX_POSITIONAL_ARITY) { Type[] ret = new Type[MAX_POSITIONAL_ARITY + 1]; for(int i = 0;i<MAX_POSITIONAL_ARITY + 1;i++) ret[i] = OBJECT_TYPE; return ret; } return ARG_TYPES[numParams()]; } void emitClearLocals(GeneratorAdapter gen){ // for(int i = 1; i < numParams() + 1; i++) // { // if(!localsUsedInCatchFinally.contains(i)) // { // gen.visitInsn(Opcodes.ACONST_NULL); // gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), i); // } // } // for(int i = numParams() + 1; i < maxLocal + 1; i++) // { // if(!localsUsedInCatchFinally.contains(i)) // { // LocalBinding b = (LocalBinding) RT.get(indexlocals, i); // if(b == null || maybePrimitiveType(b.init) == null) // { // gen.visitInsn(Opcodes.ACONST_NULL); // gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), i); // } // } // } // if(((FnExpr)objx).onceOnly) // { // objx.emitClearCloses(gen); // } } } abstract public static class ObjMethod{ //when closures are defined inside other closures, //the closed over locals need to be propagated to the enclosing objx public final ObjMethod parent; //localbinding->localbinding IPersistentMap locals = null; //num->localbinding IPersistentMap indexlocals = null; Expr body = null; ObjExpr objx; PersistentVector argLocals; int maxLocal = 0; int line; PersistentHashSet localsUsedInCatchFinally = PersistentHashSet.EMPTY; protected IPersistentMap methodMeta; public final IPersistentMap locals(){ return locals; } public final Expr body(){ return body; } public final ObjExpr objx(){ return objx; } public final PersistentVector argLocals(){ return argLocals; } public final int maxLocal(){ return maxLocal; } public final int line(){ return line; } public ObjMethod(ObjExpr objx, ObjMethod parent){ this.parent = parent; this.objx = objx; } static void emitBody(ObjExpr objx, GeneratorAdapter gen, Class retClass, Expr body) throws Exception{ MaybePrimitiveExpr be = (MaybePrimitiveExpr) body; if(Util.isPrimitive(retClass) && be.canEmitPrimitive()) { Class bc = maybePrimitiveType(be); if(bc == retClass) be.emitUnboxed(C.RETURN, objx, gen); else if(retClass == long.class && bc == int.class) { be.emitUnboxed(C.RETURN, objx, gen); gen.visitInsn(I2L); } else if(retClass == double.class && bc == float.class) { be.emitUnboxed(C.RETURN, objx, gen); gen.visitInsn(F2D); } else if(retClass == int.class && bc == long.class) { be.emitUnboxed(C.RETURN, objx, gen); gen.invokeStatic(RT_TYPE, Method.getMethod("int intCast(long)")); } else if(retClass == float.class && bc == double.class) { be.emitUnboxed(C.RETURN, objx, gen); gen.visitInsn(D2F); } else throw new IllegalArgumentException("Mismatched primitive return, expected: " + retClass + ", had: " + be.getJavaClass()); } else { body.emit(C.RETURN, objx, gen); if(retClass == void.class) { gen.pop(); } else gen.unbox(Type.getType(retClass)); } } abstract int numParams(); abstract String getMethodName(); abstract Type getReturnType(); abstract Type[] getArgTypes(); public void emit(ObjExpr fn, ClassVisitor cv){ Method m = new Method(getMethodName(), getReturnType(), getArgTypes()); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC, m, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); Label loopLabel = gen.mark(); gen.visitLineNumber(line, loopLabel); try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel, METHOD, this)); body.emit(C.RETURN, fn, gen); Label end = gen.mark(); gen.visitLocalVariable("this", "Ljava/lang/Object;", null, loopLabel, end, 0); for(ISeq lbs = argLocals.seq(); lbs != null; lbs = lbs.next()) { LocalBinding lb = (LocalBinding) lbs.first(); gen.visitLocalVariable(lb.name, "Ljava/lang/Object;", null, loopLabel, end, lb.idx); } } finally { Var.popThreadBindings(); } gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); } void emitClearLocals(GeneratorAdapter gen){ } void emitClearLocalsOld(GeneratorAdapter gen){ for(int i=0;i<argLocals.count();i++) { LocalBinding lb = (LocalBinding) argLocals.nth(i); if(!localsUsedInCatchFinally.contains(lb.idx) && lb.getPrimitiveType() == null) { gen.visitInsn(Opcodes.ACONST_NULL); gen.storeArg(lb.idx - 1); } } // for(int i = 1; i < numParams() + 1; i++) // { // if(!localsUsedInCatchFinally.contains(i)) // { // gen.visitInsn(Opcodes.ACONST_NULL); // gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), i); // } // } for(int i = numParams() + 1; i < maxLocal + 1; i++) { if(!localsUsedInCatchFinally.contains(i)) { LocalBinding b = (LocalBinding) RT.get(indexlocals, i); if(b == null || maybePrimitiveType(b.init) == null) { gen.visitInsn(Opcodes.ACONST_NULL); gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), i); } } } } } public static class LocalBinding{ public final Symbol sym; public final Symbol tag; public Expr init; public final int idx; public final String name; public final boolean isArg; public final PathNode clearPathRoot; public boolean canBeCleared = true; public boolean recurMistmatch = false; public LocalBinding(int num, Symbol sym, Symbol tag, Expr init, boolean isArg,PathNode clearPathRoot) throws Exception{ if(maybePrimitiveType(init) != null && tag != null) throw new UnsupportedOperationException("Can't type hint a local with a primitive initializer"); this.idx = num; this.sym = sym; this.tag = tag; this.init = init; this.isArg = isArg; this.clearPathRoot = clearPathRoot; name = munge(sym.name); } public boolean hasJavaClass() throws Exception{ if(init != null && init.hasJavaClass() && Util.isPrimitive(init.getJavaClass()) && !(init instanceof MaybePrimitiveExpr)) return false; return tag != null || (init != null && init.hasJavaClass()); } public Class getJavaClass() throws Exception{ return tag != null ? HostExpr.tagToClass(tag) : init.getJavaClass(); } public Class getPrimitiveType(){ return maybePrimitiveType(init); } } public static class LocalBindingExpr implements Expr, MaybePrimitiveExpr, AssignableExpr{ public final LocalBinding b; public final Symbol tag; public final PathNode clearPath; public final PathNode clearRoot; public boolean shouldClear = false; public LocalBindingExpr(LocalBinding b, Symbol tag) throws Exception{ if(b.getPrimitiveType() != null && tag != null) throw new UnsupportedOperationException("Can't type hint a primitive local"); this.b = b; this.tag = tag; this.clearPath = (PathNode)CLEAR_PATH.get(); this.clearRoot = (PathNode)CLEAR_ROOT.get(); IPersistentCollection sites = (IPersistentCollection) RT.get(CLEAR_SITES.get(),b); if(b.idx > 0) { // Object dummy; if(sites != null) { for(ISeq s = sites.seq();s!=null;s = s.next()) { LocalBindingExpr o = (LocalBindingExpr) s.first(); PathNode common = commonPath(clearPath,o.clearPath); if(common != null && common.type == PATHTYPE.PATH) o.shouldClear = false; // else // dummy = null; } } if(clearRoot == b.clearPathRoot) { this.shouldClear = true; sites = RT.conj(sites,this); CLEAR_SITES.set(RT.assoc(CLEAR_SITES.get(), b, sites)); } // else // dummy = null; } } public Object eval() throws Exception{ throw new UnsupportedOperationException("Can't eval locals"); } public boolean canEmitPrimitive(){ return b.getPrimitiveType() != null; } public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen){ objx.emitUnboxedLocal(gen, b); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ if(context != C.STATEMENT) objx.emitLocal(gen, b, shouldClear); } public Object evalAssign(Expr val) throws Exception{ throw new UnsupportedOperationException("Can't eval locals"); } public void emitAssign(C context, ObjExpr objx, GeneratorAdapter gen, Expr val){ objx.emitAssignLocal(gen, b,val); if(context != C.STATEMENT) objx.emitLocal(gen, b, false); } public boolean hasJavaClass() throws Exception{ return tag != null || b.hasJavaClass(); } public Class getJavaClass() throws Exception{ if(tag != null) return HostExpr.tagToClass(tag); return b.getJavaClass(); } } public static class BodyExpr implements Expr, MaybePrimitiveExpr{ PersistentVector exprs; public final PersistentVector exprs(){ return exprs; } public BodyExpr(PersistentVector exprs){ this.exprs = exprs; } static class Parser implements IParser{ public Expr parse(C context, Object frms) throws Exception{ ISeq forms = (ISeq) frms; if(Util.equals(RT.first(forms), DO)) forms = RT.next(forms); PersistentVector exprs = PersistentVector.EMPTY; for(; forms != null; forms = forms.next()) { Expr e = (context != C.EVAL && (context == C.STATEMENT || forms.next() != null)) ? analyze(C.STATEMENT, forms.first()) : analyze(context, forms.first()); exprs = exprs.cons(e); } if(exprs.count() == 0) exprs = exprs.cons(NIL_EXPR); return new BodyExpr(exprs); } } public Object eval() throws Exception{ Object ret = null; for(Object o : exprs) { Expr e = (Expr) o; ret = e.eval(); } return ret; } public boolean canEmitPrimitive(){ return lastExpr() instanceof MaybePrimitiveExpr && ((MaybePrimitiveExpr)lastExpr()).canEmitPrimitive(); } public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen){ for(int i = 0; i < exprs.count() - 1; i++) { Expr e = (Expr) exprs.nth(i); e.emit(C.STATEMENT, objx, gen); } MaybePrimitiveExpr last = (MaybePrimitiveExpr) exprs.nth(exprs.count() - 1); last.emitUnboxed(context, objx, gen); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ for(int i = 0; i < exprs.count() - 1; i++) { Expr e = (Expr) exprs.nth(i); e.emit(C.STATEMENT, objx, gen); } Expr last = (Expr) exprs.nth(exprs.count() - 1); last.emit(context, objx, gen); } public boolean hasJavaClass() throws Exception{ return lastExpr().hasJavaClass(); } public Class getJavaClass() throws Exception{ return lastExpr().getJavaClass(); } private Expr lastExpr(){ return (Expr) exprs.nth(exprs.count() - 1); } } public static class BindingInit{ LocalBinding binding; Expr init; public final LocalBinding binding(){ return binding; } public final Expr init(){ return init; } public BindingInit(LocalBinding binding, Expr init){ this.binding = binding; this.init = init; } } public static class LetFnExpr implements Expr{ public final PersistentVector bindingInits; public final Expr body; public LetFnExpr(PersistentVector bindingInits, Expr body){ this.bindingInits = bindingInits; this.body = body; } static class Parser implements IParser{ public Expr parse(C context, Object frm) throws Exception{ ISeq form = (ISeq) frm; //(letfns* [var (fn [args] body) ...] body...) if(!(RT.second(form) instanceof IPersistentVector)) throw new IllegalArgumentException("Bad binding form, expected vector"); IPersistentVector bindings = (IPersistentVector) RT.second(form); if((bindings.count() % 2) != 0) throw new IllegalArgumentException("Bad binding form, expected matched symbol expression pairs"); ISeq body = RT.next(RT.next(form)); if(context == C.EVAL) return analyze(context, RT.list(RT.list(FN, PersistentVector.EMPTY, form))); IPersistentMap dynamicBindings = RT.map(LOCAL_ENV, LOCAL_ENV.deref(), NEXT_LOCAL_NUM, NEXT_LOCAL_NUM.deref()); try { Var.pushThreadBindings(dynamicBindings); //pre-seed env (like Lisp labels) PersistentVector lbs = PersistentVector.EMPTY; for(int i = 0; i < bindings.count(); i += 2) { if(!(bindings.nth(i) instanceof Symbol)) throw new IllegalArgumentException( "Bad binding form, expected symbol, got: " + bindings.nth(i)); Symbol sym = (Symbol) bindings.nth(i); if(sym.getNamespace() != null) throw new Exception("Can't let qualified name: " + sym); LocalBinding lb = registerLocal(sym, tagOf(sym), null,false); lb.canBeCleared = false; lbs = lbs.cons(lb); } PersistentVector bindingInits = PersistentVector.EMPTY; for(int i = 0; i < bindings.count(); i += 2) { Symbol sym = (Symbol) bindings.nth(i); Expr init = analyze(C.EXPRESSION, bindings.nth(i + 1), sym.name); LocalBinding lb = (LocalBinding) lbs.nth(i / 2); lb.init = init; BindingInit bi = new BindingInit(lb, init); bindingInits = bindingInits.cons(bi); } return new LetFnExpr(bindingInits, (new BodyExpr.Parser()).parse(context, body)); } finally { Var.popThreadBindings(); } } } public Object eval() throws Exception{ throw new UnsupportedOperationException("Can't eval letfns"); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ for(int i = 0; i < bindingInits.count(); i++) { BindingInit bi = (BindingInit) bindingInits.nth(i); gen.visitInsn(Opcodes.ACONST_NULL); gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), bi.binding.idx); } IPersistentSet lbset = PersistentHashSet.EMPTY; for(int i = 0; i < bindingInits.count(); i++) { BindingInit bi = (BindingInit) bindingInits.nth(i); lbset = (IPersistentSet) lbset.cons(bi.binding); bi.init.emit(C.EXPRESSION, objx, gen); gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), bi.binding.idx); } for(int i = 0; i < bindingInits.count(); i++) { BindingInit bi = (BindingInit) bindingInits.nth(i); ObjExpr fe = (ObjExpr) bi.init; gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ILOAD), bi.binding.idx); fe.emitLetFnInits(gen, objx, lbset); } Label loopLabel = gen.mark(); body.emit(context, objx, gen); Label end = gen.mark(); // gen.visitLocalVariable("this", "Ljava/lang/Object;", null, loopLabel, end, 0); for(ISeq bis = bindingInits.seq(); bis != null; bis = bis.next()) { BindingInit bi = (BindingInit) bis.first(); String lname = bi.binding.name; if(lname.endsWith("__auto__")) lname += RT.nextID(); Class primc = maybePrimitiveType(bi.init); if(primc != null) gen.visitLocalVariable(lname, Type.getDescriptor(primc), null, loopLabel, end, bi.binding.idx); else gen.visitLocalVariable(lname, "Ljava/lang/Object;", null, loopLabel, end, bi.binding.idx); } } public boolean hasJavaClass() throws Exception{ return body.hasJavaClass(); } public Class getJavaClass() throws Exception{ return body.getJavaClass(); } } public static class LetExpr implements Expr, MaybePrimitiveExpr{ public final PersistentVector bindingInits; public final Expr body; public final boolean isLoop; public LetExpr(PersistentVector bindingInits, Expr body, boolean isLoop){ this.bindingInits = bindingInits; this.body = body; this.isLoop = isLoop; } static class Parser implements IParser{ public Expr parse(C context, Object frm) throws Exception{ ISeq form = (ISeq) frm; //(let [var val var2 val2 ...] body...) boolean isLoop = RT.first(form).equals(LOOP); if(!(RT.second(form) instanceof IPersistentVector)) throw new IllegalArgumentException("Bad binding form, expected vector"); IPersistentVector bindings = (IPersistentVector) RT.second(form); if((bindings.count() % 2) != 0) throw new IllegalArgumentException("Bad binding form, expected matched symbol expression pairs"); ISeq body = RT.next(RT.next(form)); if(context == C.EVAL || (context == C.EXPRESSION && isLoop)) return analyze(context, RT.list(RT.list(FN, PersistentVector.EMPTY, form))); ObjMethod method = (ObjMethod) METHOD.deref(); IPersistentMap backupMethodLocals = method.locals; IPersistentMap backupMethodIndexLocals = method.indexlocals; PersistentVector recurMismatches = null; //we might repeat once if a loop with a recurMistmatch, return breaks while(true){ IPersistentMap dynamicBindings = RT.map(LOCAL_ENV, LOCAL_ENV.deref(), NEXT_LOCAL_NUM, NEXT_LOCAL_NUM.deref()); method.locals = backupMethodLocals; method.indexlocals = backupMethodIndexLocals; if(isLoop) dynamicBindings = dynamicBindings.assoc(LOOP_LOCALS, null); try { Var.pushThreadBindings(dynamicBindings); PersistentVector bindingInits = PersistentVector.EMPTY; PersistentVector loopLocals = PersistentVector.EMPTY; for(int i = 0; i < bindings.count(); i += 2) { if(!(bindings.nth(i) instanceof Symbol)) throw new IllegalArgumentException( "Bad binding form, expected symbol, got: " + bindings.nth(i)); Symbol sym = (Symbol) bindings.nth(i); if(sym.getNamespace() != null) throw new Exception("Can't let qualified name: " + sym); Expr init = analyze(C.EXPRESSION, bindings.nth(i + 1), sym.name); if(isLoop) { if(recurMismatches != null && ((LocalBinding)recurMismatches.nth(i/2)).recurMistmatch) { init = new StaticMethodExpr("", 0, null, RT.class, "box", RT.vector(init)); if(RT.booleanCast(RT.WARN_ON_REFLECTION.deref())) RT.errPrintWriter().println("Auto-boxing loop arg: " + sym); } else if(maybePrimitiveType(init) == int.class) init = new StaticMethodExpr("", 0, null, RT.class, "longCast", RT.vector(init)); else if(maybePrimitiveType(init) == float.class) init = new StaticMethodExpr("", 0, null, RT.class, "doubleCast", RT.vector(init)); } //sequential enhancement of env (like Lisp let*) LocalBinding lb = registerLocal(sym, tagOf(sym), init,false); BindingInit bi = new BindingInit(lb, init); bindingInits = bindingInits.cons(bi); if(isLoop) loopLocals = loopLocals.cons(lb); } if(isLoop) LOOP_LOCALS.set(loopLocals); Expr bodyExpr; try { if(isLoop) { PathNode root = new PathNode(PATHTYPE.PATH, (PathNode) CLEAR_PATH.get()); Var.pushThreadBindings( RT.map(CLEAR_PATH, new PathNode(PATHTYPE.PATH,root), CLEAR_ROOT, new PathNode(PATHTYPE.PATH,root))); } bodyExpr = (new BodyExpr.Parser()).parse(isLoop ? C.RETURN : context, body); } finally{ if(isLoop) { Var.popThreadBindings(); recurMismatches = null; for(int i = 0;i< loopLocals.count();i++) { LocalBinding lb = (LocalBinding) loopLocals.nth(i); if(lb.recurMistmatch) recurMismatches = loopLocals; } } } if(recurMismatches == null) return new LetExpr(bindingInits, bodyExpr, isLoop); } finally { Var.popThreadBindings(); } } } } public Object eval() throws Exception{ throw new UnsupportedOperationException("Can't eval let/loop"); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ doEmit(context, objx, gen, false); } public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen){ doEmit(context, objx, gen, true); } public void doEmit(C context, ObjExpr objx, GeneratorAdapter gen, boolean emitUnboxed){ for(int i = 0; i < bindingInits.count(); i++) { BindingInit bi = (BindingInit) bindingInits.nth(i); Class primc = maybePrimitiveType(bi.init); if(primc != null) { ((MaybePrimitiveExpr) bi.init).emitUnboxed(C.EXPRESSION, objx, gen); gen.visitVarInsn(Type.getType(primc).getOpcode(Opcodes.ISTORE), bi.binding.idx); } else { bi.init.emit(C.EXPRESSION, objx, gen); gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), bi.binding.idx); } } Label loopLabel = gen.mark(); if(isLoop) { try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel)); if(emitUnboxed) ((MaybePrimitiveExpr)body).emitUnboxed(context, objx, gen); else body.emit(context, objx, gen); } finally { Var.popThreadBindings(); } } else { if(emitUnboxed) ((MaybePrimitiveExpr)body).emitUnboxed(context, objx, gen); else body.emit(context, objx, gen); } Label end = gen.mark(); // gen.visitLocalVariable("this", "Ljava/lang/Object;", null, loopLabel, end, 0); for(ISeq bis = bindingInits.seq(); bis != null; bis = bis.next()) { BindingInit bi = (BindingInit) bis.first(); String lname = bi.binding.name; if(lname.endsWith("__auto__")) lname += RT.nextID(); Class primc = maybePrimitiveType(bi.init); if(primc != null) gen.visitLocalVariable(lname, Type.getDescriptor(primc), null, loopLabel, end, bi.binding.idx); else gen.visitLocalVariable(lname, "Ljava/lang/Object;", null, loopLabel, end, bi.binding.idx); } } public boolean hasJavaClass() throws Exception{ return body.hasJavaClass(); } public Class getJavaClass() throws Exception{ return body.getJavaClass(); } public boolean canEmitPrimitive(){ return body instanceof MaybePrimitiveExpr && ((MaybePrimitiveExpr)body).canEmitPrimitive(); } } public static class RecurExpr implements Expr{ public final IPersistentVector args; public final IPersistentVector loopLocals; final int line; final String source; public RecurExpr(IPersistentVector loopLocals, IPersistentVector args, int line, String source){ this.loopLocals = loopLocals; this.args = args; this.line = line; this.source = source; } public Object eval() throws Exception{ throw new UnsupportedOperationException("Can't eval recur"); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ Label loopLabel = (Label) LOOP_LABEL.deref(); if(loopLabel == null) throw new IllegalStateException(); for(int i = 0; i < loopLocals.count(); i++) { LocalBinding lb = (LocalBinding) loopLocals.nth(i); Expr arg = (Expr) args.nth(i); if(lb.getPrimitiveType() != null) { Class primc = lb.getPrimitiveType(); try { final Class pc = maybePrimitiveType(arg); if(pc == primc) ((MaybePrimitiveExpr) arg).emitUnboxed(C.EXPRESSION, objx, gen); else if(primc == long.class && pc == int.class) { ((MaybePrimitiveExpr) arg).emitUnboxed(C.EXPRESSION, objx, gen); gen.visitInsn(I2L); } else if(primc == double.class && pc == float.class) { ((MaybePrimitiveExpr) arg).emitUnboxed(C.EXPRESSION, objx, gen); gen.visitInsn(F2D); } else if(primc == int.class && pc == long.class) { ((MaybePrimitiveExpr) arg).emitUnboxed(C.EXPRESSION, objx, gen); gen.invokeStatic(RT_TYPE, Method.getMethod("int intCast(long)")); } else if(primc == float.class && pc == double.class) { ((MaybePrimitiveExpr) arg).emitUnboxed(C.EXPRESSION, objx, gen); gen.visitInsn(D2F); } else { // if(true)//RT.booleanCast(RT.WARN_ON_REFLECTION.deref())) throw new IllegalArgumentException // RT.errPrintWriter().println (//source + ":" + line + " recur arg for primitive local: " + lb.name + " is not matching primitive, had: " + (arg.hasJavaClass() ? arg.getJavaClass().getName():"Object") + ", needed: " + primc.getName()); // arg.emit(C.EXPRESSION, objx, gen); // HostExpr.emitUnboxArg(objx,gen,primc); } } catch(Exception e) { throw new RuntimeException(e); } } else { arg.emit(C.EXPRESSION, objx, gen); } } for(int i = loopLocals.count() - 1; i >= 0; i--) { LocalBinding lb = (LocalBinding) loopLocals.nth(i); Class primc = lb.getPrimitiveType(); if(lb.isArg) gen.storeArg(lb.idx-(objx.isStatic?0:1)); else { if(primc != null) gen.visitVarInsn(Type.getType(primc).getOpcode(Opcodes.ISTORE), lb.idx); else gen.visitVarInsn(OBJECT_TYPE.getOpcode(Opcodes.ISTORE), lb.idx); } } gen.goTo(loopLabel); } public boolean hasJavaClass() throws Exception{ return true; } public Class getJavaClass() throws Exception{ return null; } static class Parser implements IParser{ public Expr parse(C context, Object frm) throws Exception{ int line = (Integer) LINE.deref(); String source = (String) SOURCE.deref(); ISeq form = (ISeq) frm; IPersistentVector loopLocals = (IPersistentVector) LOOP_LOCALS.deref(); if(context != C.RETURN || loopLocals == null) throw new UnsupportedOperationException("Can only recur from tail position"); if(IN_CATCH_FINALLY.deref() != null) throw new UnsupportedOperationException("Cannot recur from catch/finally"); PersistentVector args = PersistentVector.EMPTY; for(ISeq s = RT.seq(form.next()); s != null; s = s.next()) { args = args.cons(analyze(C.EXPRESSION, s.first())); } if(args.count() != loopLocals.count()) throw new IllegalArgumentException( String.format("Mismatched argument count to recur, expected: %d args, got: %d", loopLocals.count(), args.count())); for(int i = 0;i< loopLocals.count();i++) { LocalBinding lb = (LocalBinding) loopLocals.nth(i); Class primc = lb.getPrimitiveType(); if(primc != null) { boolean mismatch = false; final Class pc = maybePrimitiveType((Expr) args.nth(i)); if(primc == long.class) { if(!(pc == long.class || pc == int.class || pc == short.class || pc == char.class || pc == byte.class)) mismatch = true; } else if(primc == double.class) { if(!(pc == double.class || pc == float.class)) mismatch = true; } if(mismatch) { lb.recurMistmatch = true; if(RT.booleanCast(RT.WARN_ON_REFLECTION.deref())) RT.errPrintWriter().println (source + ":" + line + " recur arg for primitive local: " + lb.name + " is not matching primitive, had: " + (pc != null ? pc.getName():"Object") + ", needed: " + primc.getName()); } } } return new RecurExpr(loopLocals, args, line, source); } } } private static LocalBinding registerLocal(Symbol sym, Symbol tag, Expr init, boolean isArg) throws Exception{ int num = getAndIncLocalNum(); LocalBinding b = new LocalBinding(num, sym, tag, init, isArg, clearPathRoot()); IPersistentMap localsMap = (IPersistentMap) LOCAL_ENV.deref(); LOCAL_ENV.set(RT.assoc(localsMap, b.sym, b)); ObjMethod method = (ObjMethod) METHOD.deref(); method.locals = (IPersistentMap) RT.assoc(method.locals, b, b); method.indexlocals = (IPersistentMap) RT.assoc(method.indexlocals, num, b); return b; } private static int getAndIncLocalNum(){ int num = ((Number) NEXT_LOCAL_NUM.deref()).intValue(); ObjMethod m = (ObjMethod) METHOD.deref(); if(num > m.maxLocal) m.maxLocal = num; NEXT_LOCAL_NUM.set(num + 1); return num; } public static Expr analyze(C context, Object form) throws Exception{ return analyze(context, form, null); } private static Expr analyze(C context, Object form, String name) throws Exception{ //todo symbol macro expansion? try { if(form instanceof LazySeq) { form = RT.seq(form); if(form == null) form = PersistentList.EMPTY; } if(form == null) return NIL_EXPR; else if(form == Boolean.TRUE) return TRUE_EXPR; else if(form == Boolean.FALSE) return FALSE_EXPR; Class fclass = form.getClass(); if(fclass == Symbol.class) return analyzeSymbol((Symbol) form); else if(fclass == Keyword.class) return registerKeyword((Keyword) form); else if(form instanceof Number) return NumberExpr.parse((Number) form); else if(fclass == String.class) return new StringExpr(((String) form).intern()); // else if(fclass == Character.class) // return new CharExpr((Character) form); else if(form instanceof IPersistentCollection && ((IPersistentCollection) form).count() == 0) { Expr ret = new EmptyExpr(form); if(RT.meta(form) != null) ret = new MetaExpr(ret, MapExpr .parse(context == C.EVAL ? context : C.EXPRESSION, ((IObj) form).meta())); return ret; } else if(form instanceof ISeq) return analyzeSeq(context, (ISeq) form, name); else if(form instanceof IPersistentVector) return VectorExpr.parse(context, (IPersistentVector) form); else if(form instanceof IPersistentMap) return MapExpr.parse(context, (IPersistentMap) form); else if(form instanceof IPersistentSet) return SetExpr.parse(context, (IPersistentSet) form); // else //throw new UnsupportedOperationException(); return new ConstantExpr(form); } catch(Throwable e) { if(!(e instanceof CompilerException)) throw new CompilerException((String) SOURCE_PATH.deref(), (Integer) LINE.deref(), e); else throw (CompilerException) e; } } static public class CompilerException extends Exception{ final public String source; public CompilerException(String source, int line, Throwable cause){ super(errorMsg(source, line, cause.toString()), cause); this.source = source; } public String toString(){ return getMessage(); } } static public Var isMacro(Object op) throws Exception{ //no local macros for now if(op instanceof Symbol && referenceLocal((Symbol) op) != null) return null; if(op instanceof Symbol || op instanceof Var) { Var v = (op instanceof Var) ? (Var) op : lookupVar((Symbol) op, false); if(v != null && v.isMacro()) { if(v.ns != currentNS() && !v.isPublic()) throw new IllegalStateException("var: " + v + " is not public"); return v; } } return null; } static public IFn isInline(Object op, int arity) throws Exception{ //no local inlines for now if(op instanceof Symbol && referenceLocal((Symbol) op) != null) return null; if(op instanceof Symbol || op instanceof Var) { Var v = (op instanceof Var) ? (Var) op : lookupVar((Symbol) op, false); if(v != null) { if(v.ns != currentNS() && !v.isPublic()) throw new IllegalStateException("var: " + v + " is not public"); IFn ret = (IFn) RT.get(v.meta(), inlineKey); if(ret != null) { IFn arityPred = (IFn) RT.get(v.meta(), inlineAritiesKey); if(arityPred == null || RT.booleanCast(arityPred.invoke(arity))) return ret; } } } return null; } public static boolean namesStaticMember(Symbol sym){ return sym.ns != null && namespaceFor(sym) == null; } public static Object preserveTag(ISeq src, Object dst) { Symbol tag = tagOf(src); if (tag != null && dst instanceof IObj) { IPersistentMap meta = RT.meta(dst); return ((IObj) dst).withMeta((IPersistentMap) RT.assoc(meta, RT.TAG_KEY, tag)); } return dst; } public static Object macroexpand1(Object x) throws Exception{ if(x instanceof ISeq) { ISeq form = (ISeq) x; Object op = RT.first(form); if(isSpecial(op)) return x; //macro expansion Var v = isMacro(op); if(v != null) { try { return v.applyTo(RT.cons(form,RT.cons(LOCAL_ENV.get(),form.next()))); } catch(ArityException e) { // hide the 2 extra params for a macro throw new ArityException(e.actual - 2, e.name); } } else { if(op instanceof Symbol) { Symbol sym = (Symbol) op; String sname = sym.name; //(.substring s 2 5) => (. s substring 2 5) if(sym.name.charAt(0) == '.') { if(RT.length(form) < 2) throw new IllegalArgumentException( "Malformed member expression, expecting (.member target ...)"); Symbol meth = Symbol.intern(sname.substring(1)); Object target = RT.second(form); if(HostExpr.maybeClass(target, false) != null) { target = ((IObj)RT.list(IDENTITY, target)).withMeta(RT.map(RT.TAG_KEY,CLASS)); } return preserveTag(form, RT.listStar(DOT, target, meth, form.next().next())); } else if(namesStaticMember(sym)) { Symbol target = Symbol.intern(sym.ns); Class c = HostExpr.maybeClass(target, false); if(c != null) { Symbol meth = Symbol.intern(sym.name); return preserveTag(form, RT.listStar(DOT, target, meth, form.next())); } } else { //(s.substring 2 5) => (. s substring 2 5) //also (package.class.name ...) (. package.class name ...) int idx = sname.lastIndexOf('.'); // if(idx > 0 && idx < sname.length() - 1) // { // Symbol target = Symbol.intern(sname.substring(0, idx)); // Symbol meth = Symbol.intern(sname.substring(idx + 1)); // return RT.listStar(DOT, target, meth, form.rest()); // } //(StringBuilder. "foo") => (new StringBuilder "foo") //else if(idx == sname.length() - 1) return RT.listStar(NEW, Symbol.intern(sname.substring(0, idx)), form.next()); } } } } return x; } static Object macroexpand(Object form) throws Exception{ Object exf = macroexpand1(form); if(exf != form) return macroexpand(exf); return form; } private static Expr analyzeSeq(C context, ISeq form, String name) throws Exception{ Integer line = (Integer) LINE.deref(); if(RT.meta(form) != null && RT.meta(form).containsKey(RT.LINE_KEY)) line = (Integer) RT.meta(form).valAt(RT.LINE_KEY); Var.pushThreadBindings( RT.map(LINE, line)); try { Object me = macroexpand1(form); if(me != form) return analyze(context, me, name); Object op = RT.first(form); if(op == null) throw new IllegalArgumentException("Can't call nil"); IFn inline = isInline(op, RT.count(RT.next(form))); if(inline != null) return analyze(context, preserveTag(form, inline.applyTo(RT.next(form)))); IParser p; if(op.equals(FN)) return FnExpr.parse(context, form, name); else if((p = (IParser) specials.valAt(op)) != null) return p.parse(context, form); else return InvokeExpr.parse(context, form); } catch(Throwable e) { if(!(e instanceof CompilerException)) throw new CompilerException((String) SOURCE_PATH.deref(), (Integer) LINE.deref(), e); else throw (CompilerException) e; } finally { Var.popThreadBindings(); } } static String errorMsg(String source, int line, String s){ return String.format("%s, compiling:(%s:%d)", s, source, line); } public static Object eval(Object form) throws Exception{ return eval(form, true); } public static Object eval(Object form, boolean freshLoader) throws Exception{ boolean createdLoader = false; if(true)//!LOADER.isBound()) { Var.pushThreadBindings(RT.map(LOADER, RT.makeClassLoader())); createdLoader = true; } try { Integer line = (Integer) LINE.deref(); if(RT.meta(form) != null && RT.meta(form).containsKey(RT.LINE_KEY)) line = (Integer) RT.meta(form).valAt(RT.LINE_KEY); Var.pushThreadBindings(RT.map(LINE, line)); try { form = macroexpand(form); if(form instanceof IPersistentCollection && Util.equals(RT.first(form), DO)) { ISeq s = RT.next(form); for(; RT.next(s) != null; s = RT.next(s)) eval(RT.first(s), false); return eval(RT.first(s), false); } else if(form instanceof IPersistentCollection && !(RT.first(form) instanceof Symbol && ((Symbol) RT.first(form)).name.startsWith("def"))) { ObjExpr fexpr = (ObjExpr) analyze(C.EXPRESSION, RT.list(FN, PersistentVector.EMPTY, form), "eval" + RT.nextID()); IFn fn = (IFn) fexpr.eval(); return fn.invoke(); } else { Expr expr = analyze(C.EVAL, form); return expr.eval(); } } catch(Throwable e) { if(!(e instanceof Exception)) throw new RuntimeException(e); throw (Exception)e; } finally { Var.popThreadBindings(); } } finally { if(createdLoader) Var.popThreadBindings(); } } private static int registerConstant(Object o){ if(!CONSTANTS.isBound()) return -1; PersistentVector v = (PersistentVector) CONSTANTS.deref(); IdentityHashMap<Object,Integer> ids = (IdentityHashMap<Object,Integer>) CONSTANT_IDS.deref(); Integer i = ids.get(o); if(i != null) return i; CONSTANTS.set(RT.conj(v, o)); ids.put(o, v.count()); return v.count(); } private static KeywordExpr registerKeyword(Keyword keyword){ if(!KEYWORDS.isBound()) return new KeywordExpr(keyword); IPersistentMap keywordsMap = (IPersistentMap) KEYWORDS.deref(); Object id = RT.get(keywordsMap, keyword); if(id == null) { KEYWORDS.set(RT.assoc(keywordsMap, keyword, registerConstant(keyword))); } return new KeywordExpr(keyword); // KeywordExpr ke = (KeywordExpr) RT.get(keywordsMap, keyword); // if(ke == null) // KEYWORDS.set(RT.assoc(keywordsMap, keyword, ke = new KeywordExpr(keyword))); // return ke; } private static int registerKeywordCallsite(Keyword keyword){ if(!KEYWORD_CALLSITES.isBound()) throw new IllegalAccessError("KEYWORD_CALLSITES is not bound"); IPersistentVector keywordCallsites = (IPersistentVector) KEYWORD_CALLSITES.deref(); keywordCallsites = keywordCallsites.cons(keyword); KEYWORD_CALLSITES.set(keywordCallsites); return keywordCallsites.count()-1; } private static int registerProtocolCallsite(Var v){ if(!PROTOCOL_CALLSITES.isBound()) throw new IllegalAccessError("PROTOCOL_CALLSITES is not bound"); IPersistentVector protocolCallsites = (IPersistentVector) PROTOCOL_CALLSITES.deref(); protocolCallsites = protocolCallsites.cons(v); PROTOCOL_CALLSITES.set(protocolCallsites); return protocolCallsites.count()-1; } private static void registerVarCallsite(Var v){ if(!VAR_CALLSITES.isBound()) throw new IllegalAccessError("VAR_CALLSITES is not bound"); IPersistentCollection varCallsites = (IPersistentCollection) VAR_CALLSITES.deref(); varCallsites = varCallsites.cons(v); VAR_CALLSITES.set(varCallsites); // return varCallsites.count()-1; } static ISeq fwdPath(PathNode p1){ ISeq ret = null; for(;p1 != null;p1 = p1.parent) ret = RT.cons(p1,ret); return ret; } static PathNode commonPath(PathNode n1, PathNode n2){ ISeq xp = fwdPath(n1); ISeq yp = fwdPath(n2); if(RT.first(xp) != RT.first(yp)) return null; while(RT.second(xp) != null && RT.second(xp) == RT.second(yp)) { xp = xp.next(); yp = yp.next(); } return (PathNode) RT.first(xp); } static void addAnnotation(Object visitor, IPersistentMap meta){ try{ if(meta != null && ADD_ANNOTATIONS.isBound()) ADD_ANNOTATIONS.invoke(visitor, meta); } catch (Exception e) { throw new RuntimeException(e); } } static void addParameterAnnotation(Object visitor, IPersistentMap meta, int i){ try{ if(meta != null && ADD_ANNOTATIONS.isBound()) ADD_ANNOTATIONS.invoke(visitor, meta, i); } catch (Exception e) { throw new RuntimeException(e); } } private static Expr analyzeSymbol(Symbol sym) throws Exception{ Symbol tag = tagOf(sym); if(sym.ns == null) //ns-qualified syms are always Vars { LocalBinding b = referenceLocal(sym); if(b != null) { return new LocalBindingExpr(b, tag); } } else { if(namespaceFor(sym) == null) { Symbol nsSym = Symbol.intern(sym.ns); Class c = HostExpr.maybeClass(nsSym, false); if(c != null) { if(Reflector.getField(c, sym.name, true) != null) return new StaticFieldExpr((Integer) LINE.deref(), c, sym.name, tag); throw new Exception("Unable to find static field: " + sym.name + " in " + c); } } } //Var v = lookupVar(sym, false); // Var v = lookupVar(sym, false); // if(v != null) // return new VarExpr(v, tag); Object o = resolve(sym); if(o instanceof Var) { Var v = (Var) o; if(isMacro(v) != null) throw new Exception("Can't take value of a macro: " + v); registerVar(v); return new VarExpr(v, tag); } else if(o instanceof Class) return new ConstantExpr(o); else if(o instanceof Symbol) return new UnresolvedVarExpr((Symbol) o); throw new Exception("Unable to resolve symbol: " + sym + " in this context"); } static String destubClassName(String className){ //skip over prefix + '.' or '/' if(className.startsWith(COMPILE_STUB_PREFIX)) return className.substring(COMPILE_STUB_PREFIX.length()+1); return className; } static Type getType(Class c){ String descriptor = Type.getType(c).getDescriptor(); if(descriptor.startsWith("L")) descriptor = "L" + destubClassName(descriptor.substring(1)); return Type.getType(descriptor); } static Object resolve(Symbol sym, boolean allowPrivate) throws Exception{ return resolveIn(currentNS(), sym, allowPrivate); } static Object resolve(Symbol sym) throws Exception{ return resolveIn(currentNS(), sym, false); } static Namespace namespaceFor(Symbol sym){ return namespaceFor(currentNS(), sym); } static Namespace namespaceFor(Namespace inns, Symbol sym){ //note, presumes non-nil sym.ns // first check against currentNS' aliases... Symbol nsSym = Symbol.intern(sym.ns); Namespace ns = inns.lookupAlias(nsSym); if(ns == null) { // ...otherwise check the Namespaces map. ns = Namespace.find(nsSym); } return ns; } static public Object resolveIn(Namespace n, Symbol sym, boolean allowPrivate) throws Exception{ //note - ns-qualified vars must already exist if(sym.ns != null) { Namespace ns = namespaceFor(n, sym); if(ns == null) throw new Exception("No such namespace: " + sym.ns); Var v = ns.findInternedVar(Symbol.intern(sym.name)); if(v == null) throw new Exception("No such var: " + sym); else if(v.ns != currentNS() && !v.isPublic() && !allowPrivate) throw new IllegalStateException("var: " + sym + " is not public"); return v; } else if(sym.name.indexOf('.') > 0 || sym.name.charAt(0) == '[') { return RT.classForName(sym.name); } else if(sym.equals(NS)) return RT.NS_VAR; else if(sym.equals(IN_NS)) return RT.IN_NS_VAR; else { if(Util.equals(sym, COMPILE_STUB_SYM.get())) return COMPILE_STUB_CLASS.get(); Object o = n.getMapping(sym); if(o == null) { if(RT.booleanCast(RT.ALLOW_UNRESOLVED_VARS.deref())) { return sym; } else { throw new Exception("Unable to resolve symbol: " + sym + " in this context"); } } return o; } } static public Object maybeResolveIn(Namespace n, Symbol sym) throws Exception{ //note - ns-qualified vars must already exist if(sym.ns != null) { Namespace ns = namespaceFor(n, sym); if(ns == null) return null; Var v = ns.findInternedVar(Symbol.intern(sym.name)); if(v == null) return null; return v; } else if(sym.name.indexOf('.') > 0 && !sym.name.endsWith(".") || sym.name.charAt(0) == '[') { return RT.classForName(sym.name); } else if(sym.equals(NS)) return RT.NS_VAR; else if(sym.equals(IN_NS)) return RT.IN_NS_VAR; else { Object o = n.getMapping(sym); return o; } } static Var lookupVar(Symbol sym, boolean internNew) throws Exception{ Var var = null; //note - ns-qualified vars in other namespaces must already exist if(sym.ns != null) { Namespace ns = namespaceFor(sym); if(ns == null) return null; //throw new Exception("No such namespace: " + sym.ns); Symbol name = Symbol.intern(sym.name); if(internNew && ns == currentNS()) var = currentNS().intern(name); else var = ns.findInternedVar(name); } else if(sym.equals(NS)) var = RT.NS_VAR; else if(sym.equals(IN_NS)) var = RT.IN_NS_VAR; else { //is it mapped? Object o = currentNS().getMapping(sym); if(o == null) { //introduce a new var in the current ns if(internNew) var = currentNS().intern(Symbol.intern(sym.name)); } else if(o instanceof Var) { var = (Var) o; } else { throw new Exception("Expecting var, but " + sym + " is mapped to " + o); } } if(var != null) registerVar(var); return var; } private static void registerVar(Var var) throws Exception{ if(!VARS.isBound()) return; IPersistentMap varsMap = (IPersistentMap) VARS.deref(); Object id = RT.get(varsMap, var); if(id == null) { VARS.set(RT.assoc(varsMap, var, registerConstant(var))); } // if(varsMap != null && RT.get(varsMap, var) == null) // VARS.set(RT.assoc(varsMap, var, var)); } static Namespace currentNS(){ return (Namespace) RT.CURRENT_NS.deref(); } static void closeOver(LocalBinding b, ObjMethod method){ if(b != null && method != null) { if(RT.get(method.locals, b) == null) { method.objx.closes = (IPersistentMap) RT.assoc(method.objx.closes, b, b); closeOver(b, method.parent); } else if(IN_CATCH_FINALLY.deref() != null) { method.localsUsedInCatchFinally = (PersistentHashSet) method.localsUsedInCatchFinally.cons(b.idx); } } } static LocalBinding referenceLocal(Symbol sym) throws Exception{ if(!LOCAL_ENV.isBound()) return null; LocalBinding b = (LocalBinding) RT.get(LOCAL_ENV.deref(), sym); if(b != null) { ObjMethod method = (ObjMethod) METHOD.deref(); closeOver(b, method); } return b; } private static Symbol tagOf(Object o){ Object tag = RT.get(RT.meta(o), RT.TAG_KEY); if(tag instanceof Symbol) return (Symbol) tag; else if(tag instanceof String) return Symbol.intern(null, (String) tag); return null; } public static Object loadFile(String file) throws Exception{ // File fo = new File(file); // if(!fo.exists()) // return null; FileInputStream f = new FileInputStream(file); try { return load(new InputStreamReader(f, RT.UTF8), new File(file).getAbsolutePath(), (new File(file)).getName()); } finally { f.close(); } } public static Object load(Reader rdr) throws Exception{ return load(rdr, null, "NO_SOURCE_FILE"); } public static Object load(Reader rdr, String sourcePath, String sourceName) throws Exception{ Object EOF = new Object(); Object ret = null; LineNumberingPushbackReader pushbackReader = (rdr instanceof LineNumberingPushbackReader) ? (LineNumberingPushbackReader) rdr : new LineNumberingPushbackReader(rdr); Var.pushThreadBindings( RT.map(LOADER, RT.makeClassLoader(), SOURCE_PATH, sourcePath, SOURCE, sourceName, METHOD, null, LOCAL_ENV, null, LOOP_LOCALS, null, NEXT_LOCAL_NUM, 0, RT.CURRENT_NS, RT.CURRENT_NS.deref(), LINE_BEFORE, pushbackReader.getLineNumber(), LINE_AFTER, pushbackReader.getLineNumber() )); try { for(Object r = LispReader.read(pushbackReader, false, EOF, false); r != EOF; r = LispReader.read(pushbackReader, false, EOF, false)) { LINE_AFTER.set(pushbackReader.getLineNumber()); ret = eval(r,false); LINE_BEFORE.set(pushbackReader.getLineNumber()); } } catch(LispReader.ReaderException e) { throw new CompilerException(sourcePath, e.line, e.getCause()); } finally { Var.popThreadBindings(); } return ret; } static public void writeClassFile(String internalName, byte[] bytecode) throws Exception{ String genPath = (String) COMPILE_PATH.deref(); if(genPath == null) throw new Exception("*compile-path* not set"); String[] dirs = internalName.split("/"); String p = genPath; for(int i = 0; i < dirs.length - 1; i++) { p += File.separator + dirs[i]; (new File(p)).mkdir(); } String path = genPath + File.separator + internalName + ".class"; File cf = new File(path); cf.createNewFile(); FileOutputStream cfs = new FileOutputStream(cf); try { cfs.write(bytecode); cfs.flush(); cfs.getFD().sync(); } finally { cfs.close(); } } public static void pushNS(){ Var.pushThreadBindings(PersistentHashMap.create(Var.intern(Symbol.intern("clojure.core"), Symbol.intern("*ns*")).setDynamic(), null)); } public static ILookupThunk getLookupThunk(Object target, Keyword k){ return null; //To change body of created methods use File | Settings | File Templates. } static void compile1(GeneratorAdapter gen, ObjExpr objx, Object form) throws Exception{ Integer line = (Integer) LINE.deref(); if(RT.meta(form) != null && RT.meta(form).containsKey(RT.LINE_KEY)) line = (Integer) RT.meta(form).valAt(RT.LINE_KEY); Var.pushThreadBindings( RT.map(LINE, line ,LOADER, RT.makeClassLoader() )); try { form = macroexpand(form); if(form instanceof IPersistentCollection && Util.equals(RT.first(form), DO)) { for(ISeq s = RT.next(form); s != null; s = RT.next(s)) { compile1(gen, objx, RT.first(s)); } } else { Expr expr = analyze(C.EVAL, form); objx.keywords = (IPersistentMap) KEYWORDS.deref(); objx.vars = (IPersistentMap) VARS.deref(); objx.constants = (PersistentVector) CONSTANTS.deref(); expr.emit(C.EXPRESSION, objx, gen); expr.eval(); } } finally { Var.popThreadBindings(); } } public static Object compile(Reader rdr, String sourcePath, String sourceName) throws Exception{ if(COMPILE_PATH.deref() == null) throw new Exception("*compile-path* not set"); Object EOF = new Object(); Object ret = null; LineNumberingPushbackReader pushbackReader = (rdr instanceof LineNumberingPushbackReader) ? (LineNumberingPushbackReader) rdr : new LineNumberingPushbackReader(rdr); Var.pushThreadBindings( RT.map(SOURCE_PATH, sourcePath, SOURCE, sourceName, METHOD, null, LOCAL_ENV, null, LOOP_LOCALS, null, NEXT_LOCAL_NUM, 0, RT.CURRENT_NS, RT.CURRENT_NS.deref(), LINE_BEFORE, pushbackReader.getLineNumber(), LINE_AFTER, pushbackReader.getLineNumber(), CONSTANTS, PersistentVector.EMPTY, CONSTANT_IDS, new IdentityHashMap(), KEYWORDS, PersistentHashMap.EMPTY, VARS, PersistentHashMap.EMPTY // ,LOADER, RT.makeClassLoader() )); try { //generate loader class ObjExpr objx = new ObjExpr(null); objx.internalName = sourcePath.replace(File.separator, "/").substring(0, sourcePath.lastIndexOf('.')) + RT.LOADER_SUFFIX; objx.objtype = Type.getObjectType(objx.internalName); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor cv = cw; cv.visit(V1_5, ACC_PUBLIC + ACC_SUPER, objx.internalName, null, "java/lang/Object", null); //static load method GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, Method.getMethod("void load ()"), null, null, cv); gen.visitCode(); for(Object r = LispReader.read(pushbackReader, false, EOF, false); r != EOF; r = LispReader.read(pushbackReader, false, EOF, false)) { LINE_AFTER.set(pushbackReader.getLineNumber()); compile1(gen, objx, r); LINE_BEFORE.set(pushbackReader.getLineNumber()); } //end of load gen.returnValue(); gen.endMethod(); //static fields for constants for(int i = 0; i < objx.constants.count(); i++) { cv.visitField(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, objx.constantName(i), objx.constantType(i).getDescriptor(), null, null); } final int INITS_PER = 100; int numInits = objx.constants.count() / INITS_PER; if(objx.constants.count() % INITS_PER != 0) ++numInits; for(int n = 0;n<numInits;n++) { GeneratorAdapter clinitgen = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, Method.getMethod("void __init" + n + "()"), null, null, cv); clinitgen.visitCode(); try { Var.pushThreadBindings(RT.map(RT.PRINT_DUP, RT.T)); for(int i = n*INITS_PER; i < objx.constants.count() && i < (n+1)*INITS_PER; i++) { objx.emitValue(objx.constants.nth(i), clinitgen); clinitgen.checkCast(objx.constantType(i)); clinitgen.putStatic(objx.objtype, objx.constantName(i), objx.constantType(i)); } } finally { Var.popThreadBindings(); } clinitgen.returnValue(); clinitgen.endMethod(); } //static init for constants, keywords and vars GeneratorAdapter clinitgen = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, Method.getMethod("void <clinit> ()"), null, null, cv); clinitgen.visitCode(); Label startTry = clinitgen.newLabel(); Label endTry = clinitgen.newLabel(); Label end = clinitgen.newLabel(); Label finallyLabel = clinitgen.newLabel(); // if(objx.constants.count() > 0) // { // objx.emitConstants(clinitgen); // } for(int n = 0;n<numInits;n++) clinitgen.invokeStatic(objx.objtype, Method.getMethod("void __init" + n + "()")); clinitgen.invokeStatic(Type.getType(Compiler.class), Method.getMethod("void pushNS()")); clinitgen.mark(startTry); clinitgen.invokeStatic(objx.objtype, Method.getMethod("void load()")); clinitgen.mark(endTry); clinitgen.invokeStatic(VAR_TYPE, Method.getMethod("void popThreadBindings()")); clinitgen.goTo(end); clinitgen.mark(finallyLabel); //exception should be on stack clinitgen.invokeStatic(VAR_TYPE, Method.getMethod("void popThreadBindings()")); clinitgen.throwException(); clinitgen.mark(end); clinitgen.visitTryCatchBlock(startTry, endTry, finallyLabel, null); //end of static init clinitgen.returnValue(); clinitgen.endMethod(); //end of class cv.visitEnd(); writeClassFile(objx.internalName, cw.toByteArray()); } catch(LispReader.ReaderException e) { throw new CompilerException(sourcePath, e.line, e.getCause()); } finally { Var.popThreadBindings(); } return ret; } static public class NewInstanceExpr extends ObjExpr{ //IPersistentMap optionsMap = PersistentArrayMap.EMPTY; IPersistentCollection methods; Map<IPersistentVector,java.lang.reflect.Method> mmap; Map<IPersistentVector,Set<Class>> covariants; public NewInstanceExpr(Object tag){ super(tag); } static class DeftypeParser implements IParser{ public Expr parse(C context, final Object frm) throws Exception{ ISeq rform = (ISeq) frm; //(deftype* tagname classname [fields] :implements [interfaces] :tag tagname methods*) rform = RT.next(rform); String tagname = ((Symbol) rform.first()).toString(); rform = rform.next(); Symbol classname = (Symbol) rform.first(); rform = rform.next(); IPersistentVector fields = (IPersistentVector) rform.first(); rform = rform.next(); IPersistentMap opts = PersistentHashMap.EMPTY; while(rform != null && rform.first() instanceof Keyword) { opts = opts.assoc(rform.first(), RT.second(rform)); rform = rform.next().next(); } ObjExpr ret = build((IPersistentVector)RT.get(opts,implementsKey,PersistentVector.EMPTY),fields,null,tagname, classname, (Symbol) RT.get(opts,RT.TAG_KEY),rform, frm); return ret; } } static class ReifyParser implements IParser{ public Expr parse(C context, Object frm) throws Exception{ //(reify this-name? [interfaces] (method-name [args] body)*) ISeq form = (ISeq) frm; ObjMethod enclosingMethod = (ObjMethod) METHOD.deref(); String basename = enclosingMethod != null ? (trimGenID(enclosingMethod.objx.name) + "$") : (munge(currentNS().name.name) + "$"); String simpleName = "reify__" + RT.nextID(); String classname = basename + simpleName; ISeq rform = RT.next(form); IPersistentVector interfaces = ((IPersistentVector) RT.first(rform)).cons(Symbol.intern("clojure.lang.IObj")); rform = RT.next(rform); ObjExpr ret = build(interfaces, null, null, classname, Symbol.intern(classname), null, rform, frm); if(frm instanceof IObj && ((IObj) frm).meta() != null) return new MetaExpr(ret, MapExpr .parse(context == C.EVAL ? context : C.EXPRESSION, ((IObj) frm).meta())); else return ret; } } static ObjExpr build(IPersistentVector interfaceSyms, IPersistentVector fieldSyms, Symbol thisSym, String tagName, Symbol className, Symbol typeTag, ISeq methodForms, Object frm) throws Exception{ NewInstanceExpr ret = new NewInstanceExpr(null); ret.src = frm; ret.name = className.toString(); ret.classMeta = RT.meta(className); ret.internalName = ret.name.replace('.', '/'); ret.objtype = Type.getObjectType(ret.internalName); if(thisSym != null) ret.thisName = thisSym.name; if(fieldSyms != null) { IPersistentMap fmap = PersistentHashMap.EMPTY; Object[] closesvec = new Object[2 * fieldSyms.count()]; for(int i=0;i<fieldSyms.count();i++) { Symbol sym = (Symbol) fieldSyms.nth(i); LocalBinding lb = new LocalBinding(-1, sym, null, new MethodParamExpr(tagClass(tagOf(sym))),false,null); fmap = fmap.assoc(sym, lb); closesvec[i*2] = lb; closesvec[i*2 + 1] = lb; } //todo - inject __meta et al into closes - when? //use array map to preserve ctor order ret.closes = new PersistentArrayMap(closesvec); ret.fields = fmap; for(int i=fieldSyms.count()-1;i >= 0 && ((Symbol)fieldSyms.nth(i)).name.startsWith("__");--i) ret.altCtorDrops++; } //todo - set up volatiles // ret.volatiles = PersistentHashSet.create(RT.seq(RT.get(ret.optionsMap, volatileKey))); PersistentVector interfaces = PersistentVector.EMPTY; for(ISeq s = RT.seq(interfaceSyms);s!=null;s = s.next()) { Class c = (Class) resolve((Symbol) s.first()); if(!c.isInterface()) throw new IllegalArgumentException("only interfaces are supported, had: " + c.getName()); interfaces = interfaces.cons(c); } Class superClass = Object.class; Map[] mc = gatherMethods(superClass,RT.seq(interfaces)); Map overrideables = mc[0]; Map covariants = mc[1]; ret.mmap = overrideables; ret.covariants = covariants; String[] inames = interfaceNames(interfaces); Class stub = compileStub(slashname(superClass),ret, inames, frm); Symbol thistag = Symbol.intern(null,stub.getName()); try { Var.pushThreadBindings( RT.map(CONSTANTS, PersistentVector.EMPTY, CONSTANT_IDS, new IdentityHashMap(), KEYWORDS, PersistentHashMap.EMPTY, VARS, PersistentHashMap.EMPTY, KEYWORD_CALLSITES, PersistentVector.EMPTY, PROTOCOL_CALLSITES, PersistentVector.EMPTY, VAR_CALLSITES, emptyVarCallSites() )); if(ret.isDeftype()) { Var.pushThreadBindings(RT.map(METHOD, null, LOCAL_ENV, ret.fields , COMPILE_STUB_SYM, Symbol.intern(null, tagName) , COMPILE_STUB_CLASS, stub)); } //now (methodname [args] body)* ret.line = (Integer) LINE.deref(); IPersistentCollection methods = null; for(ISeq s = methodForms; s != null; s = RT.next(s)) { NewInstanceMethod m = NewInstanceMethod.parse(ret, (ISeq) RT.first(s),thistag, overrideables); methods = RT.conj(methods, m); } ret.methods = methods; ret.keywords = (IPersistentMap) KEYWORDS.deref(); ret.vars = (IPersistentMap) VARS.deref(); ret.constants = (PersistentVector) CONSTANTS.deref(); ret.constantsID = RT.nextID(); ret.keywordCallsites = (IPersistentVector) KEYWORD_CALLSITES.deref(); ret.protocolCallsites = (IPersistentVector) PROTOCOL_CALLSITES.deref(); ret.varCallsites = (IPersistentSet) VAR_CALLSITES.deref(); } finally { if(ret.isDeftype()) Var.popThreadBindings(); Var.popThreadBindings(); } ret.compile(slashname(superClass),inames,false); ret.getCompiledClass(); return ret; } /*** * Current host interop uses reflection, which requires pre-existing classes * Work around this by: * Generate a stub class that has the same interfaces and fields as the class we are generating. * Use it as a type hint for this, and bind the simple name of the class to this stub (in resolve etc) * Unmunge the name (using a magic prefix) on any code gen for classes */ static Class compileStub(String superName, NewInstanceExpr ret, String[] interfaceNames, Object frm){ ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor cv = cw; cv.visit(V1_5, ACC_PUBLIC + ACC_SUPER, COMPILE_STUB_PREFIX + "/" + ret.internalName, null,superName,interfaceNames); //instance fields for closed-overs for(ISeq s = RT.keys(ret.closes); s != null; s = s.next()) { LocalBinding lb = (LocalBinding) s.first(); int access = ACC_PUBLIC + (ret.isVolatile(lb) ? ACC_VOLATILE : ret.isMutable(lb) ? 0 : ACC_FINAL); if(lb.getPrimitiveType() != null) cv.visitField(access , lb.name, Type.getType(lb.getPrimitiveType()).getDescriptor(), null, null); else //todo - when closed-overs are fields, use more specific types here and in ctor and emitLocal? cv.visitField(access , lb.name, OBJECT_TYPE.getDescriptor(), null, null); } //ctor that takes closed-overs and does nothing Method m = new Method("<init>", Type.VOID_TYPE, ret.ctorTypes()); GeneratorAdapter ctorgen = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cv); ctorgen.visitCode(); ctorgen.loadThis(); ctorgen.invokeConstructor(Type.getObjectType(superName), voidctor); ctorgen.returnValue(); ctorgen.endMethod(); if(ret.altCtorDrops > 0) { Type[] ctorTypes = ret.ctorTypes(); Type[] altCtorTypes = new Type[ctorTypes.length-ret.altCtorDrops]; for(int i=0;i<altCtorTypes.length;i++) altCtorTypes[i] = ctorTypes[i]; Method alt = new Method("<init>", Type.VOID_TYPE, altCtorTypes); ctorgen = new GeneratorAdapter(ACC_PUBLIC, alt, null, null, cv); ctorgen.visitCode(); ctorgen.loadThis(); ctorgen.loadArgs(); for(int i=0;i<ret.altCtorDrops;i++) ctorgen.visitInsn(Opcodes.ACONST_NULL); ctorgen.invokeConstructor(Type.getObjectType(COMPILE_STUB_PREFIX + "/" + ret.internalName), new Method("<init>", Type.VOID_TYPE, ctorTypes)); ctorgen.returnValue(); ctorgen.endMethod(); } //end of class cv.visitEnd(); byte[] bytecode = cw.toByteArray(); DynamicClassLoader loader = (DynamicClassLoader) LOADER.deref(); return loader.defineClass(COMPILE_STUB_PREFIX + "." + ret.name, bytecode, frm); } static String[] interfaceNames(IPersistentVector interfaces){ int icnt = interfaces.count(); String[] inames = icnt > 0 ? new String[icnt] : null; for(int i=0;i<icnt;i++) inames[i] = slashname((Class) interfaces.nth(i)); return inames; } static String slashname(Class c){ return c.getName().replace('.', '/'); } protected void emitMethods(ClassVisitor cv){ for(ISeq s = RT.seq(methods); s != null; s = s.next()) { ObjMethod method = (ObjMethod) s.first(); method.emit(this, cv); } //emit bridge methods for(Map.Entry<IPersistentVector,Set<Class>> e : covariants.entrySet()) { java.lang.reflect.Method m = mmap.get(e.getKey()); Class[] params = m.getParameterTypes(); Type[] argTypes = new Type[params.length]; for(int i = 0; i < params.length; i++) { argTypes[i] = Type.getType(params[i]); } Method target = new Method(m.getName(), Type.getType(m.getReturnType()), argTypes); for(Class retType : e.getValue()) { Method meth = new Method(m.getName(), Type.getType(retType), argTypes); GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC + ACC_BRIDGE, meth, null, //todo don't hardwire this EXCEPTION_TYPES, cv); gen.visitCode(); gen.loadThis(); gen.loadArgs(); gen.invokeInterface(Type.getType(m.getDeclaringClass()),target); gen.returnValue(); gen.endMethod(); } } } static public IPersistentVector msig(java.lang.reflect.Method m){ return RT.vector(m.getName(), RT.seq(m.getParameterTypes()),m.getReturnType()); } static void considerMethod(java.lang.reflect.Method m, Map mm){ IPersistentVector mk = msig(m); int mods = m.getModifiers(); if(!(mm.containsKey(mk) || !(Modifier.isPublic(mods) || Modifier.isProtected(mods)) || Modifier.isStatic(mods) || Modifier.isFinal(mods))) { mm.put(mk, m); } } static void gatherMethods(Class c, Map mm){ for(; c != null; c = c.getSuperclass()) { for(java.lang.reflect.Method m : c.getDeclaredMethods()) considerMethod(m, mm); for(java.lang.reflect.Method m : c.getMethods()) considerMethod(m, mm); } } static public Map[] gatherMethods(Class sc, ISeq interfaces){ Map allm = new HashMap(); gatherMethods(sc, allm); for(; interfaces != null; interfaces = interfaces.next()) gatherMethods((Class) interfaces.first(), allm); Map<IPersistentVector,java.lang.reflect.Method> mm = new HashMap<IPersistentVector,java.lang.reflect.Method>(); Map<IPersistentVector,Set<Class>> covariants = new HashMap<IPersistentVector,Set<Class>>(); for(Object o : allm.entrySet()) { Map.Entry e = (Map.Entry) o; IPersistentVector mk = (IPersistentVector) e.getKey(); mk = (IPersistentVector) mk.pop(); java.lang.reflect.Method m = (java.lang.reflect.Method) e.getValue(); if(mm.containsKey(mk)) //covariant return { Set<Class> cvs = covariants.get(mk); if(cvs == null) { cvs = new HashSet<Class>(); covariants.put(mk,cvs); } java.lang.reflect.Method om = mm.get(mk); if(om.getReturnType().isAssignableFrom(m.getReturnType())) { cvs.add(om.getReturnType()); mm.put(mk, m); } else cvs.add(m.getReturnType()); } else mm.put(mk, m); } return new Map[]{mm,covariants}; } } public static class NewInstanceMethod extends ObjMethod{ String name; Type[] argTypes; Type retType; Class retClass; Class[] exclasses; static Symbol dummyThis = Symbol.intern(null,"dummy_this_dlskjsdfower"); private IPersistentVector parms; public NewInstanceMethod(ObjExpr objx, ObjMethod parent){ super(objx, parent); } int numParams(){ return argLocals.count(); } String getMethodName(){ return name; } Type getReturnType(){ return retType; } Type[] getArgTypes(){ return argTypes; } static public IPersistentVector msig(String name,Class[] paramTypes){ return RT.vector(name,RT.seq(paramTypes)); } static NewInstanceMethod parse(ObjExpr objx, ISeq form, Symbol thistag, Map overrideables) throws Exception{ //(methodname [this-name args*] body...) //this-name might be nil NewInstanceMethod method = new NewInstanceMethod(objx, (ObjMethod) METHOD.deref()); Symbol dotname = (Symbol)RT.first(form); Symbol name = (Symbol) Symbol.intern(null,munge(dotname.name)).withMeta(RT.meta(dotname)); IPersistentVector parms = (IPersistentVector) RT.second(form); if(parms.count() == 0) { throw new IllegalArgumentException("Must supply at least one argument for 'this' in: " + dotname); } Symbol thisName = (Symbol) parms.nth(0); parms = RT.subvec(parms,1,parms.count()); ISeq body = RT.next(RT.next(form)); try { method.line = (Integer) LINE.deref(); //register as the current method and set up a new env frame PathNode pnode = new PathNode(PATHTYPE.PATH, (PathNode) CLEAR_PATH.get()); Var.pushThreadBindings( RT.map( METHOD, method, LOCAL_ENV, LOCAL_ENV.deref(), LOOP_LOCALS, null, NEXT_LOCAL_NUM, 0 ,CLEAR_PATH, pnode ,CLEAR_ROOT, pnode ,CLEAR_SITES, PersistentHashMap.EMPTY )); //register 'this' as local 0 if(thisName != null) registerLocal((thisName == null) ? dummyThis:thisName,thistag, null,false); else getAndIncLocalNum(); PersistentVector argLocals = PersistentVector.EMPTY; method.retClass = tagClass(tagOf(name)); method.argTypes = new Type[parms.count()]; boolean hinted = tagOf(name) != null; Class[] pclasses = new Class[parms.count()]; Symbol[] psyms = new Symbol[parms.count()]; for(int i = 0; i < parms.count(); i++) { if(!(parms.nth(i) instanceof Symbol)) throw new IllegalArgumentException("params must be Symbols"); Symbol p = (Symbol) parms.nth(i); Object tag = tagOf(p); if(tag != null) hinted = true; if(p.getNamespace() != null) p = Symbol.intern(p.name); Class pclass = tagClass(tag); pclasses[i] = pclass; psyms[i] = p; } Map matches = findMethodsWithNameAndArity(name.name, parms.count(), overrideables); Object mk = msig(name.name, pclasses); java.lang.reflect.Method m = null; if(matches.size() > 0) { //multiple methods if(matches.size() > 1) { //must be hinted and match one method if(!hinted) throw new IllegalArgumentException("Must hint overloaded method: " + name.name); m = (java.lang.reflect.Method) matches.get(mk); if(m == null) throw new IllegalArgumentException("Can't find matching overloaded method: " + name.name); if(m.getReturnType() != method.retClass) throw new IllegalArgumentException("Mismatched return type: " + name.name + ", expected: " + m.getReturnType().getName() + ", had: " + method.retClass.getName()); } else //one match { //if hinted, validate match, if(hinted) { m = (java.lang.reflect.Method) matches.get(mk); if(m == null) throw new IllegalArgumentException("Can't find matching method: " + name.name + ", leave off hints for auto match."); if(m.getReturnType() != method.retClass) throw new IllegalArgumentException("Mismatched return type: " + name.name + ", expected: " + m.getReturnType().getName() + ", had: " + method.retClass.getName()); } else //adopt found method sig { m = (java.lang.reflect.Method) matches.values().iterator().next(); method.retClass = m.getReturnType(); pclasses = m.getParameterTypes(); } } } // else if(findMethodsWithName(name.name,allmethods).size()>0) // throw new IllegalArgumentException("Can't override/overload method: " + name.name); else throw new IllegalArgumentException("Can't define method not in interfaces: " + name.name); //else //validate unque name+arity among additional methods method.retType = Type.getType(method.retClass); method.exclasses = m.getExceptionTypes(); for(int i = 0; i < parms.count(); i++) { LocalBinding lb = registerLocal(psyms[i], null, new MethodParamExpr(pclasses[i]),true); argLocals = argLocals.assocN(i,lb); method.argTypes[i] = Type.getType(pclasses[i]); } for(int i = 0; i < parms.count(); i++) { if(pclasses[i] == long.class || pclasses[i] == double.class) getAndIncLocalNum(); } LOOP_LOCALS.set(argLocals); method.name = name.name; method.methodMeta = RT.meta(name); method.parms = parms; method.argLocals = argLocals; method.body = (new BodyExpr.Parser()).parse(C.RETURN, body); return method; } finally { Var.popThreadBindings(); } } private static Map findMethodsWithNameAndArity(String name, int arity, Map mm){ Map ret = new HashMap(); for(Object o : mm.entrySet()) { Map.Entry e = (Map.Entry) o; java.lang.reflect.Method m = (java.lang.reflect.Method) e.getValue(); if(name.equals(m.getName()) && m.getParameterTypes().length == arity) ret.put(e.getKey(), e.getValue()); } return ret; } private static Map findMethodsWithName(String name, Map mm){ Map ret = new HashMap(); for(Object o : mm.entrySet()) { Map.Entry e = (Map.Entry) o; java.lang.reflect.Method m = (java.lang.reflect.Method) e.getValue(); if(name.equals(m.getName())) ret.put(e.getKey(), e.getValue()); } return ret; } public void emit(ObjExpr obj, ClassVisitor cv){ Method m = new Method(getMethodName(), getReturnType(), getArgTypes()); Type[] extypes = null; if(exclasses.length > 0) { extypes = new Type[exclasses.length]; for(int i=0;i<exclasses.length;i++) extypes[i] = Type.getType(exclasses[i]); } GeneratorAdapter gen = new GeneratorAdapter(ACC_PUBLIC, m, null, extypes, cv); addAnnotation(gen,methodMeta); for(int i = 0; i < parms.count(); i++) { IPersistentMap meta = RT.meta(parms.nth(i)); addParameterAnnotation(gen, meta, i); } gen.visitCode(); Label loopLabel = gen.mark(); gen.visitLineNumber(line, loopLabel); try { Var.pushThreadBindings(RT.map(LOOP_LABEL, loopLabel, METHOD, this)); emitBody(objx, gen, retClass, body); Label end = gen.mark(); gen.visitLocalVariable("this", obj.objtype.getDescriptor(), null, loopLabel, end, 0); for(ISeq lbs = argLocals.seq(); lbs != null; lbs = lbs.next()) { LocalBinding lb = (LocalBinding) lbs.first(); gen.visitLocalVariable(lb.name, argTypes[lb.idx-1].getDescriptor(), null, loopLabel, end, lb.idx); } } catch(Exception e) { throw new RuntimeException(e); } finally { Var.popThreadBindings(); } gen.returnValue(); //gen.visitMaxs(1, 1); gen.endMethod(); } } static Class primClass(Symbol sym){ if(sym == null) return null; Class c = null; if(sym.name.equals("int")) c = int.class; else if(sym.name.equals("long")) c = long.class; else if(sym.name.equals("float")) c = float.class; else if(sym.name.equals("double")) c = double.class; else if(sym.name.equals("char")) c = char.class; else if(sym.name.equals("short")) c = short.class; else if(sym.name.equals("byte")) c = byte.class; else if(sym.name.equals("boolean")) c = boolean.class; else if(sym.name.equals("void")) c = void.class; return c; } static Class tagClass(Object tag) throws Exception{ if(tag == null) return Object.class; Class c = null; if(tag instanceof Symbol) c = primClass((Symbol) tag); if(c == null) c = HostExpr.tagToClass(tag); return c; } static Class primClass(Class c){ return c.isPrimitive()?c:Object.class; } static public class MethodParamExpr implements Expr, MaybePrimitiveExpr{ final Class c; public MethodParamExpr(Class c){ this.c = c; } public Object eval() throws Exception{ throw new Exception("Can't eval"); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ throw new RuntimeException("Can't emit"); } public boolean hasJavaClass() throws Exception{ return c != null; } public Class getJavaClass() throws Exception{ return c; } public boolean canEmitPrimitive(){ return Util.isPrimitive(c); } public void emitUnboxed(C context, ObjExpr objx, GeneratorAdapter gen){ throw new RuntimeException("Can't emit"); } } public static class CaseExpr extends UntypedExpr{ public final LocalBindingExpr expr; public final int shift, mask, low, high; public final Expr defaultExpr; public final HashMap<Integer,Expr> tests; public final HashMap<Integer,Expr> thens; public final boolean allKeywords; public final int line; final static Method hashMethod = Method.getMethod("int hash(Object)"); final static Method hashCodeMethod = Method.getMethod("int hashCode()"); final static Method equalsMethod = Method.getMethod("boolean equals(Object, Object)"); public CaseExpr(int line, LocalBindingExpr expr, int shift, int mask, int low, int high, Expr defaultExpr, HashMap<Integer,Expr> tests,HashMap<Integer,Expr> thens, boolean allKeywords){ this.expr = expr; this.shift = shift; this.mask = mask; this.low = low; this.high = high; this.defaultExpr = defaultExpr; this.tests = tests; this.thens = thens; this.line = line; this.allKeywords = allKeywords; } public Object eval() throws Exception{ throw new UnsupportedOperationException("Can't eval case"); } public void emit(C context, ObjExpr objx, GeneratorAdapter gen){ Label defaultLabel = gen.newLabel(); Label endLabel = gen.newLabel(); HashMap<Integer,Label> labels = new HashMap(); for(Integer i : tests.keySet()) { labels.put(i, gen.newLabel()); } Label[] la = new Label[(high-low)+1]; for(int i=low;i<=high;i++) { la[i-low] = labels.containsKey(i) ? labels.get(i) : defaultLabel; } gen.visitLineNumber(line, gen.mark()); expr.emit(C.EXPRESSION, objx, gen); gen.invokeStatic(UTIL_TYPE,hashMethod); gen.push(shift); gen.visitInsn(ISHR); gen.push(mask); gen.visitInsn(IAND); gen.visitTableSwitchInsn(low, high, defaultLabel, la); for(Integer i : labels.keySet()) { gen.mark(labels.get(i)); expr.emit(C.EXPRESSION, objx, gen); tests.get(i).emit(C.EXPRESSION, objx, gen); if(allKeywords) { gen.visitJumpInsn(IF_ACMPNE, defaultLabel); } else { gen.invokeStatic(UTIL_TYPE, equalsMethod); gen.ifZCmp(GeneratorAdapter.EQ, defaultLabel); } thens.get(i).emit(C.EXPRESSION,objx,gen); gen.goTo(endLabel); } gen.mark(defaultLabel); defaultExpr.emit(C.EXPRESSION, objx, gen); gen.mark(endLabel); if(context == C.STATEMENT) gen.pop(); } static class Parser implements IParser{ //(case* expr shift mask low high default map<minhash, [test then]> identity?) //prepared by case macro and presumed correct //case macro binds actual expr in let so expr is always a local, //no need to worry about multiple evaluation public Expr parse(C context, Object frm) throws Exception{ ISeq form = (ISeq) frm; if(context == C.EVAL) return analyze(context, RT.list(RT.list(FN, PersistentVector.EMPTY, form))); PersistentVector args = PersistentVector.create(form.next()); HashMap<Integer,Expr> tests = new HashMap(); HashMap<Integer,Expr> thens = new HashMap(); LocalBindingExpr testexpr = (LocalBindingExpr) analyze(C.EXPRESSION, args.nth(0)); testexpr.shouldClear = false; PathNode branch = new PathNode(PATHTYPE.BRANCH, (PathNode) CLEAR_PATH.get()); for(Object o : ((Map)args.nth(6)).entrySet()) { Map.Entry e = (Map.Entry) o; Integer minhash = ((Number)e.getKey()).intValue(); MapEntry me = (MapEntry) e.getValue(); Expr testExpr = new ConstantExpr(me.getKey()); tests.put(minhash, testExpr); Expr thenExpr; try { Var.pushThreadBindings( RT.map(CLEAR_PATH, new PathNode(PATHTYPE.PATH,branch))); thenExpr = analyze(context, me.getValue()); } finally{ Var.popThreadBindings(); } thens.put(minhash, thenExpr); } Expr defaultExpr; try { Var.pushThreadBindings( RT.map(CLEAR_PATH, new PathNode(PATHTYPE.PATH,branch))); defaultExpr = analyze(context, args.nth(5)); } finally{ Var.popThreadBindings(); } return new CaseExpr(((Number)LINE.deref()).intValue(), testexpr, ((Number)args.nth(1)).intValue(), ((Number)args.nth(2)).intValue(), ((Number)args.nth(3)).intValue(), ((Number)args.nth(4)).intValue(), defaultExpr, tests,thens,args.nth(7) != RT.F); } } }
7
public static double[] erlangCresources(double nonZeroDelayProbability, double totalTraffic) { double[] ret = new double[8]; long counter = 1; double lastProb = Double.NaN; double prob = Double.NaN; boolean test = true; while (test) { prob = Stat.erlangCprobability(totalTraffic, counter); if (prob <= nonZeroDelayProbability) { ret[0] = counter; ret[1] = prob; ret[2] = Stat.erlangCload(nonZeroDelayProbability, counter); ret[3] = (counter - 1); ret[4] = lastProb; ret[5] = Stat.erlangCload(nonZeroDelayProbability, counter - 1); ret[6] = nonZeroDelayProbability; ret[7] = totalTraffic; test = false; } else { lastProb = prob; counter++; if (counter == Integer.MAX_VALUE) { System.out.println("Method erlangCresources: no solution found below " + Long.MAX_VALUE + "resources"); for (int i = 0; i < 8; i++) ret[i] = Double.NaN; test = false; } } } return ret; }
4
public void buildClassifier(Instances insts) throws Exception { m_Filter = null; if (!isPresent()) throw new Exception("libsvm classes not in CLASSPATH!"); // remove instances with missing class insts = new Instances(insts); insts.deleteWithMissingClass(); if (!getDoNotReplaceMissingValues()) { m_ReplaceMissingValues = new ReplaceMissingValues(); m_ReplaceMissingValues.setInputFormat(insts); insts = Filter.useFilter(insts, m_ReplaceMissingValues); } // can classifier handle the data? // we check this here so that if the user turns off // replace missing values filtering, it will fail // if the data actually does have missing values getCapabilities().testWithFail(insts); if (getNormalize()) { m_Filter = new Normalize(); m_Filter.setInputFormat(insts); insts = Filter.useFilter(insts, m_Filter); } Vector vy = new Vector(); Vector vx = new Vector(); int max_index = 0; for (int d = 0; d < insts.numInstances(); d++) { Instance inst = insts.instance(d); Object x = instanceToArray(inst); int m = Array.getLength(x); if (m > 0) max_index = Math.max(max_index, ((Integer) getField(Array.get(x, m - 1), "index")).intValue()); vx.addElement(x); vy.addElement(new Double(inst.classValue())); } // calculate actual gamma if (getGamma() == 0) m_GammaActual = 1.0 / max_index; else m_GammaActual = m_Gamma; // check parameter String error_msg = (String) invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_check_parameter", new Class[]{ Class.forName(CLASS_SVMPROBLEM), Class.forName(CLASS_SVMPARAMETER)}, new Object[]{ getProblem(vx, vy), getParameters()}); if (error_msg != null) throw new Exception("Error: " + error_msg); // train model m_Model = invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_train", new Class[]{ Class.forName(CLASS_SVMPROBLEM), Class.forName(CLASS_SVMPARAMETER)}, new Object[]{ getProblem(vx, vy), getParameters()}); // save internal model? if (!m_ModelFile.isDirectory()) { invokeMethod( Class.forName(CLASS_SVM).newInstance(), "svm_save_model", new Class[]{ String.class, Class.forName(CLASS_SVMMODEL)}, new Object[]{ m_ModelFile.getAbsolutePath(), m_Model}); } }
8
private static void printFileReaders(String prefix, Map<String, FileReadingMessageSource> fileReaders) { Assert.notNull(fileReaders, "Mandatory argument missing."); for (String key : fileReaders.keySet()) { FileReadingMessageSource readTarget = fileReaders.get(key); File inDirectory = (File) new DirectFieldAccessor(readTarget).getPropertyValue("directory"); if (inDirectory != null) LOGGER.info("{} source directory configured: {}", prefix, inDirectory.getAbsolutePath()); Boolean autoCreateDirectory = (Boolean) new DirectFieldAccessor(readTarget).getPropertyValue("autoCreateDirectory"); LOGGER.info("{} Auto Creating directories is: {}", prefix, autoCreateDirectory); } }
2
private ParserResult limitConditionAmount(boolean limited, ParserResult result, SyntaxAnalyser analyser) throws GrammarCheckException { result = this.replaceNick(result, analyser); boolean conditionsIsOk = result.getConditions().size() == result .getDimensionLevelInfo().size(); if (!conditionsIsOk) { this.throwException("where", "Conditions you gave for query didn't match the select sentence", analyser); } if (limited && result.getDimensionLevelInfo().size() != 1) { this.throwException("slice", " this operation just for one dimension partition problem", analyser); } if (result.getAggregateFunctionName() != null) { this.throwException(result.getOperationName(), null, analyser); } if (result.getResultCube() == null) { this.throwException(result.getOperationName(), "Your have to name the result cube", analyser); } return result; }
5
public StageWelcome(StageManager stageManager, Map<String, String> data) { super(stageManager, data); try { welcome = ImageIO.read(getClass().getResourceAsStream("/graphics/loading/Welcome.png")); } catch (IOException e) { e.printStackTrace(); } }
1
public void startMoving(Direction dir) { move(dir); int last = queuedMoveDirectionPreferences.length - 1; int dirIndex = last; for(int i = 0; i < last && dirIndex == last; i++) if(queuedMoveDirectionPreferences[i] == dir) dirIndex = i; for(int i = dirIndex; i >= 1; i--) queuedMoveDirectionPreferences[i] = queuedMoveDirectionPreferences[i - 1]; queuedMoveDirectionPreferences[0] = dir; }
4
protected void onChannelInfo(String channel, int userCount, String topic) {}
0
public Connection getConnection(String dbname){ PropertiesReader p = PropertiesReader.getInstance(); // 驱动程序名 String driver = p.getValue("mysql.driver",R.Constants.mysql_driver); // URL指向要访问的数据库名scutcs String url = p.getValue("mysql.url"); url = url.replaceAll("\\$\\{dbname\\}",dbname); // MySQL配置时的用户名 String user = p.getValue("mysql.username"); // MySQL配置时的密码 String password = p.getValue("mysql.password"); try { // 加载驱动程序 Class.forName(driver); // 连续数据库 Connection conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) log.debug("Succeeded connecting to the Database!"); return conn; }catch (Exception e){ log.error(e); return null; } }
2
public String getLocation_id() { return location_id; }
0
public void moveCharacters() { for (Character character : characters.values()) { ArrayList<Room> neighboursList = character.getLocation().getNeighbours(); boolean found = false; // if character's hostile, stay if player's in the same room. If not, sense if player's in a nearby room and go there if found. If not, go randomly as usual. if (character.getHostile()) { if (character.getLocation() == player.getLocation()) { return; } for (Room neighbour : neighboursList) { if (player.getLocation() == neighbour) { Room nextRoom = neighbour; character.addLocationHistory(nextRoom); found = true; } } } // randomly go to a nearby room. if (!found && character.getMoveable() && random.nextInt(2) == 1) { Room nextRoom = neighboursList.get(random.nextInt(neighboursList.size())); character.addLocationHistory(nextRoom); } } }
8
public static void readStrings (String [] strings, String file) { BufferedReader bufferedReader=null; try { bufferedReader = new BufferedReader (new FileReader(file)); } catch (FileNotFoundException e) { System.out.print(e+"\n"); } try { int lines =0; while (bufferedReader!=null && bufferedReader.ready()) { if ((bufferedReader.readLine()).equals("")) { lines++; } } strings = new String[lines]; lines =0; while (bufferedReader!=null && bufferedReader.ready()) { strings[lines]=bufferedReader.readLine(); lines++; } } catch (IOException e) { System.out.print(e+"\n"); } }
7
@Override public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext mc) { if (normal == true) { for (Field f : mInfo.getAllFields()) { writer.startNode(f.getName()); if (treatAsReferences.contains(f.getType())) { try { mc.convertAnother(f.get(o), entityReferenceConvertors.get(f.getType())); } catch (Exception ex) { Logger.getLogger(XMLStoreConverter.class.getName()).log(Level.SEVERE, null, ex); } } else { try { mc.convertAnother(f.get(o)); } catch (Exception ex) { Logger.getLogger(XMLStoreConverter.class.getName()).log(Level.SEVERE, null, ex); } } writer.endNode(); } } else { Object pKeyValue = PrimaryKeyUtils.getPrimaryKeyValue(mInfo.getpKeyField(), o); //writer.startNode(mInfo.getForClass().getCanonicalName()); writer.startNode("fKey"); mc.convertAnother(pKeyValue); writer.endNode(); //writer.endNode(); } }
5
/** @return The default configuration. */ public String getDefaultConfig() { if (mDefaultConfig == null) { mDefaultConfig = getConfig(); } return mDefaultConfig; }
1
private void parseStatus(String status, Map<String, Object> pageVariables) { switch (status) { case ExceptionMessages.EMPTY_DATA: case ExceptionMessages.FAILED_AUTH: case ExceptionMessages.NO_SUCH_USER_FOUND: case ExceptionMessages.SQL_ERROR: case ExceptionMessages.USER_ALREADY_EXISTS: pageVariables.put("errorMsg", status); break; case AccountServiceMessages.WAIT_AUTH: case AccountServiceMessages.WAIT_USER_REG: case AccountServiceMessages.USER_ADDED: pageVariables.put("infoMsg", status); break; default: pageVariables.put("userStatus", status); break; } }
8
public void addIfaces(Collection result, ClassIdentifier ancestor) { ClassInfo[] ifaceInfos = ancestor.info.getInterfaces(); for (int i = 0; i < ifaceInfos.length; i++) { ClassIdentifier ifaceident = Main.getClassBundle() .getClassIdentifier(ifaceInfos[i].getName()); if (ifaceident != null && !ifaceident.isReachable()) addIfaces(result, ifaceident); else result.add(ifaceInfos[i]); } }
3
public void optimize(ArrayList<House> houses) { if (created) { int start = (int) System.currentTimeMillis(); Optimum opt = new Optimum(this, houses); this.grid = opt.getBestSolution().getGrid(); this.mapObjects = opt.getBestSolution().getMapObjects(); int area = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j].isAvailable() && grid[i][j].getObject() == null) { area++; } } } this.gridArea = area; opt = new Optimum(this, houses); this.grid = opt.getBestSolution().getGrid(); this.mapObjects = opt.getBestSolution().getMapObjects(); area = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if (grid[i][j].isAvailable() && grid[i][j].getObject() == null) { area++; } } } System.out.println(opt.getBestSolution().getValue()); int end = (int) System.currentTimeMillis(); System.out.println((end - start) / 1000); repaint(); } }
9
public static void init() { int count = 0; String s; try { BufferedReader in = new BufferedReader(new FileReader("../word-values.txt")); while ((s = in.readLine()) != null) { words[count] = s.trim(); count++; } in.close(); } catch (Exception e) { e.printStackTrace(); } int totalsIndex = 0, index = 0; System.out.print("\nReading:"); for (int i=0; i<99; i++) { String n = String.format("%02d",i); String filename = "../entropies/entropies."+n+".txt"; boolean first = true; if (i%10==0) System.out.println(); System.out.print(String.format(" %02d /", i)); try { BufferedReader reader = new BufferedReader(new FileReader(filename)); while ((s = reader.readLine()) != null) { if (first) { if (s.equals("X")) { totals[totalsIndex] = 0.0; starts[totalsIndex] = index; list[index] = 0L; } else { long x = Long.parseLong(s); totals[totalsIndex] = x / 1000000.0; starts[totalsIndex] = index; list[index] = x; } index++; first = false; } else if (s.equals("")) { first = true; totalsIndex++; } else { list[index] = Long.parseLong(s); index++; } } reader.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("\nDatabase created. Size: " + index); System.out.println("Total # of words: " + totalsIndex); }
9
public Node getNode(String expression, Object context) throws XPathExpressionException { assert(expression != null); if(context == null) { assert(document != null); context = document; } return (Node) xpath.evaluate(expression, context, XPathConstants.NODE); }
1
private void broadSearch(int maxdepth, Vector<Integer> Row) { //Warteschlange die die Knoten bereithaelt LinkedList<Vector<Integer>> Queue = new LinkedList<Vector<Integer>>(); //Startknoten beginnen Queue.add(Row); //Loop sucht nach dem Ziel while(!Queue.isEmpty()) { //Begrenzung der Suchtiefe if(Queue.getFirst().size() > maxdepth) { break; } //Position des ersten Knotens in der Warteschlange float[] nodepos = null; nodepos = getPoint(Queue.getFirst()); //Auf Ziel pruefen if(nodepos[0] == goal[0] && nodepos[1] == goal[1]) { //Gefundenen Weg speichern savePath(Queue.getFirst()); //Weitere Suche abbrechen break; } //Jede Verzweigung der Warteschlange hinzufügen int numofpos = getMember(Queue.getFirst()); for(int i=0; i<numofpos; i++) { //Neuen Weg beschreiben, Alten kopieren Vector<Integer> R = new Vector<Integer>(); for(int l=0; l<Queue.getFirst().size(); l++) { int n = (int) Queue.getFirst().elementAt(l); R.add(n); } R.add(i); Queue.add(R); } //Aktuelles Element aus der Schlange entfernen Queue.removeFirst(); } }
6
public void filterPacks() { packPanels.clear(); packs.removeAll(); currentPacks.clear(); packMapping.clear(); int counter = 0; selectedPack = 0; packInfo.setText(""); // all removed, repaint packs.repaint(); // not really needed //modPacksAdded = false; for (ModPack pack : ModPack.getPackArray()) { if (filterForTab(pack) && mcVersionCheck(pack) && avaliabilityCheck(pack) && textSearch(pack)) { currentPacks.put(counter, pack); packMapping.put(counter, pack.getIndex()); addPack(pack); counter++; } } updateDatas(); updatePacks(); }
5