text
stringlengths
14
410k
label
int32
0
9
public static void main(String[] args) { System.out.println("Loading configuration file"); loadComputeNodeConfig(); System.out.println("Connecting to master"); try { cServer = new CommunicationServer(Integer.parseInt(node_config.get("port"))); cServerThread = new Thread(cServer); cServerThread.start(); } catch (NumberFormatException e) { System.out.println("Invalid port number in config file"); System.exit(1); } catch (IOException e) { System.out.println("Socket connection exception"); System.exit(1); } try { master = new Connection(node_config.get("master_ip"), Integer.parseInt(node_config.get("master_port"))); cServer.addConnection(master); } catch (NumberFormatException e) { System.out.println("Bad port in config file"); System.exit(1); } catch (UnknownHostException e) { System.out.println("Could not find master"); System.exit(1); } catch (IOException e) { System.out.println("Socket exception connecting to master"); System.exit(1); } startShell(); }
5
private double[] test(List<List<String>> tokenizedTestTweets) { int[] classCounts = { 0, 0, 0, 0 }; double fullCount = 0.0; double[] decision = new double[4]; int idx = 0; for (List<String> tweet : tokenizedTestTweets) { /** tweetenként nézzük **/ for (int i = 0; i < 4; i++) { decision[i] = Math.log((double) classProbabilities[i] / 595.0); } for (String word : tweet) { for (int i = 0; i < 4; i++) { decision[i] += Math.log(getMagic(word, i)); } } double m = Math.max(Math.max(decision[0], decision[1]), Math.max(decision[2], decision[3])); for (int i = 0; i < decision.length; i++) { if (Double.compare(decision[i], m) == 0) { // System.err.println(MessageFormat.format("{0}: {1}->{2} ({3})", // ++idx, idx / 25, i, tweet.toString())); System.err.println(MessageFormat.format("{0}", i)); classCounts[i]++; } } fullCount += 1.0; } double[] toReturn = new double[4]; try { for (int i = 0; i < 4; i++) { toReturn[i] = classCounts[i] / fullCount; } } catch (Exception e) { return null; } return toReturn; }
8
public void redo(){ if (this.canRedo()){ current++; this.commands.get(current).execute(); } }
1
public String getLabel(TreeNode node) { return (String) labels.get(node); }
0
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { MOB target=mob; if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB)) target=(MOB)givenTarget; if(target.fetchEffect(this.ID())!=null) { mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already observing.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); final CMMsg msg=CMClass.getMsg(mob,target,this,auto?CMMsg.MSG_OK_ACTION:(CMMsg.MSG_DELICATE_HANDS_ACT|CMMsg.MASK_EYES),auto?L("<T-NAME> become(s) observant."):L("<S-NAME> open(s) <S-HIS-HER> eyes and observe(s) <S-HIS-HER> surroundings carefully.")); if(!success) return beneficialVisualFizzle(mob,null,L("<S-NAME> look(s) around carefully, but become(s) distracted.")); else if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,target,asLevel,0); } return success; }
9
public static Animation loadAnimationFile(String animationFilename) { try { Scanner reader = new Scanner(new FileReader("Resources/Animations/" + animationFilename)); String spritesPath = reader.next().substring(1); int width = reader.nextInt(); int height = reader.nextInt(); int nbOfSupportedStates = reader.nextInt(); TreeMap<State, Tuple<BufferedImage[], Integer>> spriteMap = new TreeMap<State, Tuple<BufferedImage[], Integer>>(); for(int i = 0; i < nbOfSupportedStates; i++) { String stateStr = reader.next(); int nbOfSprites = reader.nextInt(); int animationSpeed = reader.nextInt(); BufferedImage[] sprites = new BufferedImage[nbOfSprites]; for(int j = 0; j < nbOfSprites; j++) { sprites[j] = ImageIO.read(new File("Resources/Sprites/" + spritesPath + reader.next())); } spriteMap.put(State.getFromStr(stateStr), new Tuple<BufferedImage[], Integer>(sprites, animationSpeed)); } Tuple<BufferedImage[], Integer> tuple = new Tuple<BufferedImage[], Integer>(new BufferedImage[] {loadSprite("empty.png")}, 1); spriteMap.put(State.DEAD, tuple); return new Animation(width, height, spriteMap); } catch (FileNotFoundException e) { System.out.println("SpriteAnimationLoader: file <" + animationFilename + "> was not found in the folder <Animations>"); } catch (IOException e) { System.out.println("SpriteAnimationLoader: file not found"); } return null; }
4
@Override public void finishPopulate() { }
0
public int[][] getStatesOfTrans(String transcription) { String phonems = FilesLoader.getPhonemsOfTrans(transcription); int states[][]; int indexFirst = 0; System.out.println("Phonem sequence : "+phonems); String phonemsArray[]= phonems.split(" "); int noOfTriPhones = phonemsArray.length - 2; System.out.println("No of tri Phones : "+noOfTriPhones); int noOfPhones = noOfTriPhones + 2; System.out.println("No of phones in Trans : " + noOfPhones); System.out.println(); states = new int[3][3*noOfTriPhones]; triPhones = new String[noOfTriPhones]; int statesTemp[] = new int[5]; for(indexFirst = 1; indexFirst <= noOfTriPhones; indexFirst+=1) { if(indexFirst == 1){ System.out.print("Tri Phone : "+phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\tb"); triPhones[indexFirst-1] = phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\tb"; statesTemp = getStates(phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\tb"); System.out.println("\tStates : "+statesTemp[0]+" "+statesTemp[1]+" "+statesTemp[2]+" "+statesTemp[3]+" "+statesTemp[4]); } else if((indexFirst < noOfTriPhones) && (indexFirst > 1 )){ System.out.print("Tri Phone : "+phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\ti"); triPhones[indexFirst-1] = phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\ti"; statesTemp = getStates(phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\ti"); System.out.println("\tStates : "+statesTemp[0]+" "+statesTemp[1]+" "+statesTemp[2]+" "+statesTemp[3]+" "+statesTemp[4]); } else if(indexFirst == noOfTriPhones){ System.out.print("Tri Phone : "+phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\te"); triPhones[indexFirst-1] = phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\te"; statesTemp = getStates(phonemsArray[indexFirst]+"\t"+phonemsArray[indexFirst - 1]+"\t"+phonemsArray[indexFirst+1]+"\te"); System.out.println("\tStates : "+statesTemp[0]+" "+statesTemp[1]+" "+statesTemp[2]+" "+statesTemp[3]+" "+statesTemp[4]); } states[0][((indexFirst -1)*3)] = statesTemp[2]; states[0][((indexFirst -1)*3)+1] = statesTemp[3]; states[0][((indexFirst -1)*3)+2] = statesTemp[4]; states[1][((indexFirst -1)*3)] = statesTemp[1]; states[1][((indexFirst -1)*3)+1] = statesTemp[1]; states[1][((indexFirst -1)*3)+2] = statesTemp[1]; states[2][((indexFirst -1)*3)] = statesTemp[0]; states[2][((indexFirst -1)*3)+1] = statesTemp[0]; states[2][((indexFirst -1)*3)+2] = statesTemp[0]; } return states; }
5
public static void main(String[] args) { Map<String, Pet> petMap = new HashMap<String, Pet>(); petMap.put("My Cat", new Cat("Molly")); petMap.put("My Dog", new Dog("Ginger")); petMap.put("My Hamster", new Hamster("Bosco")); System.out.println(petMap); Pet dog = petMap.get("My Dog"); System.out.println(dog); System.out.println(petMap.containsKey("My Dog")); System.out.println(petMap.containsValue(dog)); }
0
@Test public void multiThreadedTest() throws InterruptedException { final AtomicBoolean failed = new AtomicBoolean(false); final LastAccessTimeCounter c = new LastAccessTimeCounter(); final AtomicLong index = new AtomicLong(0); ArrayList<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { public void run() { try { long currentIndex = index.incrementAndGet(); while (currentIndex < 2000000) { c.updateLastAccess(); if (currentIndex % 10000 == 0) c.getValue(); currentIndex = index.incrementAndGet(); } } catch (Exception e) { failed.set(true); } } }); threads.add(t); t.setDaemon(true); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } if (failed.get()) Assert.fail(); }
7
private double checkDistribution_nextBoolean(RandomGenerator randGen) { int[] count = new int[2] ; int total = FAST_TEST ? 1000000 : 10000000 ; double totalD = total ; for (int i = 0; i < total; i++) { int n = randGen.nextBoolean() ? 0 : 1 ; count[n]++ ; } double distribution = totalD / count.length ; double tolerance = 0.05 ; double minDist = distribution * (1-tolerance) ; double maxDist = distribution * (1+tolerance) ; double errTotal = 0 ; double errMax = Double.NEGATIVE_INFINITY ; for (int i = 0; i < count.length; i++) { int c = count[i] ; assertTrue( c >= minDist && c <= maxDist ) ; double err = 1 - (c / distribution) ; if (err < 0) err = -err ; errTotal += err ; if (err > errMax) errMax = err ; } double errMean = errTotal / count.length ; return errMean ; }
7
protected Class getClass(final Type t) { try { if (t.getSort() == Type.ARRAY) { return Class.forName(t.getDescriptor().replace('/', '.'), false, loader); } return Class.forName(t.getClassName(), false, loader); } catch (ClassNotFoundException e) { throw new RuntimeException(e.toString()); } }
2
public BookTicketsServlet() { super(); // TODO Auto-generated constructor stub }
0
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Group other = (Group) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
6
protected void updateRange(double delta, AABB range) { Set<Entity> entities = structure.queryRange(new HashSet<Entity>(), range); Iterator<Entity> it = entities.iterator(); while (it.hasNext()) { Entity current = (Entity) it.next(); current.update(delta); } }
1
public void binaryFilter(float cutOff, float value) { for(int i=0; i < data.length; i++) { float[] block = data[i]; for(int j=0; j < block.length; j++) { block[j] = (block[j] >= cutOff ? 1.0f : 0.0f) * value; } } }
3
private static int calcMinValueNeeded(int curActiveFrame,int minAValueNeeded,int minBValueNeeded, Map<PII, Integer> imActiveFrame, boolean optimizeA) { int minValueNeeded = (optimizeA ? minAValueNeeded : minBValueNeeded); for(Entry<PII, Integer> e : imActiveFrame.entrySet()) if(curActiveFrame > e.getValue() && (optimizeA ? e.getKey().b >= minBValueNeeded : e.getKey().a >= minAValueNeeded)) minValueNeeded = Math.max(minValueNeeded, (optimizeA ? e.getKey().a : e.getKey().b) + 1); return minValueNeeded; }
6
private void drawCurve(double[] intervalT) { if ( intervalT == null) return; double s = ( maxY + minY)/ canvasHeight; double m = Math.max( Math.max( Math.abs(derivativeY(intervalT[0])), Math.abs(derivativeY(intervalT[1]))), Math.max( Math.abs(derivativeX(intervalT[0])), Math.abs(derivativeX(intervalT[1]))) ); double dt = s / m; for (double t = intervalT[1]; t < intervalT[0]; t += dt){ double x = (t * t) / (t * t - 1); double y = (t * t + 1)/(t + 2); int coordinateX = (int) Math.round((x) * length + centerAxisX); int coordinateY = (int) Math.round((-y) * length + centerAxisY); if ((coordinateX > 0 && coordinateX < canvasWidth) && (coordinateY > 0 && coordinateY < canvasHeight)) bufferedImage.setRGB(coordinateX, coordinateY, 0); } }
6
@XmlElementDecl(namespace = "http://www.w3.org/2001/04/xmlenc#", name = "CipherReference") public JAXBElement<CipherReferenceType> createCipherReference(CipherReferenceType value) { return new JAXBElement<CipherReferenceType>(_CipherReference_QNAME, CipherReferenceType.class, null, value); }
0
public void schemeEditorAddContact() { if(ce_circuit2.getSelectionIndex() == -1 || ce_drain.getSelectionIndex() == -1) return; String circuitName = ce_circuit2.getText(); String contactName = ce_drain.getText(); scheme.getCircuits().get(circuitName).getContacts().add(new Contact(contactName)); schemeEditorSchemeChanged(); }
2
public WheresMyBusServer( int numThreads, int queueSize, String query ) { bq = new ArrayBlockingQueue<>( queueSize ); twitter = TwitterFactory.getSingleton(); tweetProcWorkers = new ArrayList<>( numThreads ); for ( int i = 0; i < numThreads; i++ ) { tweetProcWorkers.add( new TweetProcWorker( bq, twitter,"ProcWorker #" + i )); } twitterSearchWorker = new TwitterSearchWorker( bq, twitter,"SearchWorker #1", query); Logger.log( TAG, "server created." ); }
1
private void close() { try { if (statement != null) { statement.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { throw new RuntimeException("Erro ao fechar conexão!"); } }
3
public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // This thread simulate the network. It allows the program to send or // receive messages from another site. System.out.println("-- Starting Network's thread --- \n "); System.out.println(" Other sites simulation"); System.out .println(" What do you want to simulate ? ? (<Number of the site>,<Message>,<timer>) \n " + "ex:1,a,4"); while (true) { // The user says that another site sent a message to this one. String ligne_lue = null; InputStreamReader lecteur = new InputStreamReader(System.in); BufferedReader entree = new BufferedReader(lecteur); try { ligne_lue = entree.readLine(); // If the user type "view" , The program display the view that // represent the queue of a site if (ligne_lue.equals("view")) { System.out.println(mutex.getView().toString()); } else if (!ligne_lue.equals("")) { String str[] = ligne_lue.split(","); int SiteLue = Integer.parseInt(str[0]); char MessageLue = str[1].charAt(0); int HorlogeLue = Integer.parseInt(str[2]); // The network calls the method of mX depends on what the // user simulated. switch(MessageLue){ case Constantes.RECEIVE: mutex.rReceive(SiteLue, HorlogeLue); break; case Constantes.FREE: mutex.lReceive(SiteLue, HorlogeLue); break; case Constantes.ACKNOWLEDGEMENT: mutex.aReceive(SiteLue, HorlogeLue); break; } } } catch (IOException e) { System.err.println("Incorrect format"); } } }
8
private boolean readZipFile(String flName) throws IOException { boolean success = false; ZipFile zipFile = null; try { BufferedReader reader = null; // ZipFile offers an Enumeration of all the files in the file zipFile = new ZipFile(flName); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { success = false; // reset the value again ZipEntry zipEntry = e.nextElement(); reader = new BufferedReader( new InputStreamReader(zipFile.getInputStream(zipEntry))); // read one line at the time int line = 1; while (reader.ready()) { parseValue(reader.readLine(), line); line++; } reader.close(); success = true; } } finally { if (zipFile != null) { zipFile.close(); } } return success; }
4
@Override public Weapon calculateWeapon() { Weapon calculatedWeapon; weapons = CPUThrower.getWeapons(); if (round <= 4) { calculatedWeapon = NCalculateWeapon(2); } else if (round <= 6) { calculatedWeapon = NCalculateWeapon(3); } else if (round <= 8) { calculatedWeapon = NCalculateWeapon(4); } else{ calculatedWeapon = NCalculateWeapon(5); } return calculatedWeapon; }
3
public void zero_old(int[][] matrix) { if(matrix == null) return; int m = matrix.length; if(m == 0) return; int n = matrix[0].length; boolean[] row_zero = new boolean[m]; boolean[] col_zero = new boolean[n]; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(matrix[i][j] == 0) { row_zero[i] = true; col_zero[j] = true; } } for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) { if(row_zero[i] || col_zero[j]) matrix[i][j] = 0; } }
9
public boolean checkOptimization(int[] rightCuts, int index){ final int opt=index+1; if(opt==1){//no opt return true; } else if(opt==2){//2-opt check //d(t 1 ,t 2 ) > d(t 2 ,t 3 ) int t1=rightCuts[0]; int t2=Help.circleIncrement(rightCuts[0], tour.length()); // int t3=rightCuts[1]; int t3=Help.circleIncrement(rightCuts[1], tour.length()); int oldDist=tour.indexDistance(t1, t2); int newDist=tour.indexDistance(t2, t3); return newDist<oldDist; } else if(opt==3){//3-opt check //d(t 1 ,t 2 ) + d(t 3 ,t 4 ) > d(t 2 ,t 3 ) + d(t 4 ,t 5 ). int t1=rightCuts[0]; int t2=Help.circleIncrement(rightCuts[0], tour.length()); int t4=rightCuts[1]; int t3=Help.circleIncrement(rightCuts[1], tour.length()); int t5=rightCuts[2]; int oldDist=tour.indexDistance(t1, t2)+tour.indexDistance(t3, t4); int newDist=tour.indexDistance(t2, t3)+tour.indexDistance(t4, t5); return newDist<oldDist; } //add more opts here return true; }
3
public void addPatient(Patient newPatient) { if (nextPatient == null) { nextPatient = newPatient; nextPatient.previousPatient = this; } else { nextPatient.addPatient(newPatient); } }
1
private void selectImage(){ // Identify computer String computerName = null; try{ InetAddress localaddress = InetAddress.getLocalHost(); computerName = localaddress.getHostName(); } catch(UnknownHostException e){ System.err.println("Cannot detect local host : " + e); } // Set path to file selection window // Replace "name" by your "computer's name" and C:\\DigiGraphDirectory by the path to the directory containing the image to be digitized // Default path is to the C:\ directory or system default directory if no C drive present if(computerName.equals("name"))this.path = "C:\\DigiGraphDirectory"; // select image file FileChooser fc = new FileChooser(this.path); this.imageName = fc.selectFile(); if(!fc.fileFound()){ System.out.println("Class DigiGraph: No successful selection of an image file occurred"); System.exit(0); } this.imagePath = fc.getPathName(); int lastDot = this.imagePath.lastIndexOf('.'); this.extension = this.imagePath.substring(lastDot+1); if(this.extension.equalsIgnoreCase("gif"))imageFormat=1; if(this.extension.equalsIgnoreCase("jpg"))imageFormat=2; if(this.extension.equalsIgnoreCase("jpeg"))imageFormat=2; if(this.extension.equalsIgnoreCase("jpe"))imageFormat=2; if(this.extension.equalsIgnoreCase("jfif"))imageFormat=2; if(this.extension.equalsIgnoreCase("png"))imageFormat=3; }
9
public static void assertElementWithTextPosition(MyElement myElement, String elementText, int expectedPosition, WebDriver driver) { log.info("enter to function assertElementWithTextPosition with element '" + myElement.getName() + "'"); options.setDriver(driver); options.setMyElement(myElement); options.setText(elementText); int position = WebElementsServices.getElementWithTextPosition(options); if (position == -1) { log.error("Element '" + myElement.getName() + "' has not right type " ); MultiServices.errorShutdown(options); } else { if (position == 0) { log.error("Noone element with expected text " ); MultiServices.errorShutdown(options); } else { if (position == -2) { log.error("More than one element with expected text " ); MultiServices.errorShutdown(options); } else { if (position != expectedPosition) { log.error("Item with text " + elementText + " position is " + position + " but expected " + expectedPosition); MultiServices.errorShutdown(options); } else { log.info("Item with text " + elementText + " position is " + position + " is equal to expected " + expectedPosition); } } } } }
4
public void saveBoard(Board b){ FileWriter fichero = null; PrintWriter pw = null; try{ fichero = new FileWriter("savedBoard.txt"); pw = new PrintWriter(fichero); for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ pw.print(b.get(i, j)+" "); } pw.println(""); } }catch (Exception e) { e.printStackTrace(); } finally{ try{ if (null != fichero) // I make sure to close the file fichero.close(); }catch (Exception e2) { e2.printStackTrace(); } } } // end saveBoard
5
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) { this.plugin = plugin; this.type = type; this.announce = announce; this.file = file; this.id = id; this.updateFolder = plugin.getServer().getUpdateFolder(); final File pluginFile = plugin.getDataFolder().getParentFile(); final File updaterFile = new File(pluginFile, "Updater"); final File updaterConfigFile = new File(updaterFile, "config.yml"); if (!updaterFile.exists()) { updaterFile.mkdir(); } if (!updaterConfigFile.exists()) { try { updaterConfigFile.createNewFile(); } catch (final IOException e) { plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } this.config = YamlConfiguration.loadConfiguration(updaterConfigFile); this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n' + "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n' + "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration."); this.config.addDefault("api-key", "PUT_API_KEY_HERE"); this.config.addDefault("disable", false); if (this.config.get("api-key", null) == null) { this.config.options().copyDefaults(true); try { this.config.save(updaterConfigFile); } catch (final IOException e) { plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath()); e.printStackTrace(); } } if (this.config.getBoolean("disable")) { this.result = UpdateResult.DISABLED; return; } String key = this.config.getString("api-key"); if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) { key = null; } this.apiKey = key; try { this.url = new URL(Updater.HOST + Updater.QUERY + id); } catch (final MalformedURLException e) { plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid."); this.result = UpdateResult.FAIL_BADID; e.printStackTrace(); } this.thread = new Thread(new UpdateRunnable()); this.thread.start(); }
9
@Override public void loadConsole() throws DataLoadFailedException { ConfigurationSection sec = getData(specialYamlConfiguration, "console"); YamlPermissionBase permBase = new YamlPermissionConsole(sec); load(PermissionType.CONSOLE, permBase); }
0
@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 Atividade)) { return false; } Atividade other = (Atividade) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
5
private String eFormatString(double x,char eChar) { boolean noDigits=false; char[] ca4,ca5; if (Double.isInfinite(x)) { if (x==Double.POSITIVE_INFINITY) { if (leadingSign) ca4 = "+Inf".toCharArray(); else if (leadingSpace) ca4 = " Inf".toCharArray(); else ca4 = "Inf".toCharArray(); } else ca4 = "-Inf".toCharArray(); noDigits = true; } else if (Double.isNaN(x)) { if (leadingSign) ca4 = "+NaN".toCharArray(); else if (leadingSpace) ca4 = " NaN".toCharArray(); else ca4 = "NaN".toCharArray(); noDigits = true; } else ca4 = eFormatDigits(x,eChar); ca5 = applyFloatPadding(ca4,false); return new String(ca5); }
7
private static Double[][] initializeWeight(mxAnalysisGraph aGraph, Object[] nodes, Object[] edges, Map<Object, Integer> indexMap) { Double[][] weight = new Double[nodes.length][nodes.length]; for (int i = 0; i < nodes.length; i++) { Arrays.fill(weight[i], Double.MAX_VALUE); } boolean isDirected = mxGraphProperties.isDirected(aGraph.getProperties(), mxGraphProperties.DEFAULT_DIRECTED); mxCostFunction costFunction = aGraph.getGenerator().getCostFunction(); mxGraphView view = aGraph.getGraph().getView(); for (Object currEdge : edges) { Object source = aGraph.getTerminal(currEdge, true); Object target = aGraph.getTerminal(currEdge, false); weight[indexMap.get(source)][indexMap.get(target)] = costFunction.getCost(view.getState(currEdge)); if (!isDirected) { weight[indexMap.get(target)][indexMap.get(source)] = costFunction.getCost(view.getState(currEdge)); } } for (int i = 0; i < nodes.length; i++) { weight[i][i] = 0.0; } return weight; };
4
private DefaultTableModel resultSetToTableModel(DefaultTableModel model, CachedRowSetImpl rowSet) throws SQLException { ResultSetMetaData rsMetaData = rowSet.getMetaData(); if(model == null){ model = new DefaultTableModel(); } String columnLabels[] = new String[rsMetaData.getColumnCount() + 1]; columnLabels[0] = "Rank"; for(int i = 1;i < columnLabels.length; i++) { columnLabels[i] = rsMetaData.getColumnLabel(i); } model.setColumnIdentifiers(columnLabels); model.setRowCount(0); int rank = 1; while(rowSet.next()) { Object data[] = new Object[columnLabels.length + 1]; data[0] = rank; rank++; for(int i = 1; i < data.length - 1; i++) { data[i] = rowSet.getObject(i); } model.addRow(data); } return model; }
4
public static final int gcd(int x1,int x2) { if(x1<0 || x2<0) { throw new IllegalArgumentException("Cannot compute the GCD "+ "if one integer is negative."); } int a,b,g,z; if(x1>x2) { a = x1; b = x2; } else { a = x2; b = x1; } if(b==0) return 0; g = b; while (g!=0) { z= a%g; a = g; g = z; } return a; }
5
public int getPixel(int x, int y) { if (x < 0 || x >= width || y < 0 || y >= height) return -1; return pixels[x + y * width]; }
4
@Test public void minDoesNotRemoveValuesWhenCalled() { h.insert(v); h.min(); assertFalse(h.isEmpty()); }
0
private static void editarCliente() { boolean salir; String nombre, dni; Integer idCliente; Cliente cliente; do { try { System.out.print( "Introduce el Id del Cliente: "); idCliente = Integer.parseInt( scanner.nextLine()); if ((cliente = Cliente.buscar( idCliente)) == null) { System.out.println( "El cliente con no existe"); salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?"); } else { System.out.println( "Nombre actual del cliente: " + cliente.getNombre()); System.out.print( "Introduce el nuevo nombre (vaco no modifica): "); nombre = scanner.nextLine(); if (!nombre.isEmpty()) cliente.setNombre( nombre); System.out.println( "DNI actual del cliente: " + cliente.getDni()); System.out.print( "Introduce el nuevo DNI (vaco no modifica): "); dni = scanner.nextLine(); if (!dni.isEmpty()) cliente.setDni( dni); System.out.println( "- Cliente editado -"); salir = true; } } catch (Exception e) { System.out.println( e.getMessage()); salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?"); } } while (!salir); }
5
private String getEdges(Vertex<Text, Text, NullWritable> vertex) { StringBuilder sb = new StringBuilder(); for (Edge<Text, NullWritable> edge : vertex.getEdges()) { sb.append(sb.length() > 0 ? ", " : ""); sb.append(edge.getTargetVertexId()); } return sb.toString(); }
2
public boolean func_73085_a(EntityPlayer par1EntityPlayer, World par2World, ItemStack par3ItemStack) { int i = par3ItemStack.stackSize; int j = par3ItemStack.getItemDamage(); ItemStack itemstack = par3ItemStack.useItemRightClick(par2World, par1EntityPlayer); if (itemstack != par3ItemStack || itemstack != null && itemstack.stackSize != i || itemstack != null && itemstack.getMaxItemUseDuration() > 0) { par1EntityPlayer.inventory.mainInventory[par1EntityPlayer.inventory.currentItem] = itemstack; if (func_73083_d()) { itemstack.stackSize = i; itemstack.setItemDamage(j); } if (itemstack.stackSize == 0) { par1EntityPlayer.inventory.mainInventory[par1EntityPlayer.inventory.currentItem] = null; } return true; } else { return false; } }
7
private int getChunkSize() throws IOException { if (_chunkSize<0) return -1; _trailer=null; _chunkSize=-1; // Get next non blank line org.openqa.jetty.util.LineInput.LineBuffer line_buffer =_in.readLineBuffer(); while(line_buffer!=null && line_buffer.size==0) line_buffer=_in.readLineBuffer(); // Handle early EOF or error in format if (line_buffer==null) throw new IOException("Unexpected EOF"); String line= new String(line_buffer.buffer,0,line_buffer.size); // Get chunksize int i=line.indexOf(';'); if (i>0) line=line.substring(0,i).trim(); try { _chunkSize = Integer.parseInt(line,16); } catch (NumberFormatException e) { _chunkSize=-1; log.warn("Bad Chunk:"+line); log.debug(LogSupport.EXCEPTION,e); throw new IOException("Bad chunk size"); } // check for EOF if (_chunkSize==0) { _chunkSize=-1; // Look for trailers _trailer = new HttpFields(); _trailer.read(_in); } return _chunkSize; }
7
public Iterator<T> iterator() { return new Iterator<T>() { private int pos, knownMod = modCount; { iteratorCount++; } public boolean hasNext() { boolean hn = false; for(int a = pos; a < size(); a++) { if(get(a) != null) { hn = true; break; } } if(!hn) { iteratorCount--; if(iteratorCount == 0) clean(); } return hn; } private T nextItem() { checkForCoMod(); if(!hasNext()) throw new NoSuchElementException("reached the end"); T t = null; while((t = get(pos++)) == null); return t; } public T next() { T t = nextItem(); if(t == null) System.out.println("IT'S NULL!!!"); return t; } public void remove() { checkForCoMod(); Bag.this.remove(--pos); knownMod = modCount; } private void checkForCoMod() { if(knownMod != modCount) throw new ConcurrentModificationException(); } }; }
8
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(CadUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CadUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CadUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CadUsuario.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 CadUsuario().setVisible(true); } }); }
6
public static String replace(String inString, String oldPattern, String newPattern) { if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { return inString; } StringBuilder sb = new StringBuilder(); int pos = 0; // our position in the old string int index = inString.indexOf(oldPattern); // the index of an occurrence we've found, or -1 int patLen = oldPattern.length(); while (index >= 0) { sb.append(inString.substring(pos, index)); sb.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); } sb.append(inString.substring(pos)); // remember to append any characters to the right of a match return sb.toString(); }
4
public static void main(String[] args) { PairManager pman1 = new PairManager1(), pman2 = new PairManager2(); testApproaches(pman1, pman2); }
0
public TreeRow getFirstSelectedRow() { if (!mSelectedRows.isEmpty()) { for (TreeRow row : new TreeRowViewIterator(this, mRoot.getChildren())) { if (mSelectedRows.contains(row)) { return row; } } } return null; }
3
private double getCost(int nextLevelCalls, int[][] newBoard) { double cost = Double.NEGATIVE_INFINITY; if (nextLevelCalls == 0) { cost = evaluator.evaluate(newBoard); } else { for (int i = 0; i < newBoard.length; i++) { for (int j = 0; j < newBoard[i].length; j++) { if (newBoard[i][j] == 0) { newBoard[i][j] = 2; cost = Math.max(cost, findBestMoveInternal(newBoard, nextLevelCalls).cost); newBoard[i][j] = 4; cost = Math.max(cost, findBestMoveInternal(newBoard, nextLevelCalls).cost); newBoard[i][j] = 0; } } } } return cost; }
4
public void handlePut(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws ServletException, IOException { boolean exists = resource != null && resource.exists(); if (exists && !passConditionalHeaders(request, response, resource)) return; if (pathInContext.endsWith("/")) { if (!exists) { if (!resource.getFile().mkdirs()) response.sendError(HttpResponse.__403_Forbidden, "Directories could not be created"); else { response.setStatus(HttpResponse.__201_Created); response.flushBuffer(); } } else { response.setStatus(HttpResponse.__200_OK); response.flushBuffer(); } } else { try { int toRead = request.getContentLength(); InputStream in = request.getInputStream(); OutputStream out = resource.getOutputStream(); if (toRead >= 0) IO.copy(in, out, toRead); else IO.copy(in, out); out.close(); response.setStatus(exists ? HttpResponse.__200_OK : HttpResponse.__201_Created); response.flushBuffer(); } catch (Exception ex) { log.warn(LogSupport.EXCEPTION, ex); response.sendError(HttpResponse.__403_Forbidden, ex.getMessage()); } } }
9
void checkClose () { if ( this.closedInputStream && this.closedOutputStream ) { // close(); } }
2
public void renderSheet(int xp, int yp, SpriteSheet sheet, boolean fixed) { if (fixed) { xp -= xOffset; yp -= yOffset; } for (int y = 0; y < sheet.HEIGHT; y++) { int ya = y + yp; for (int x = 0; x < sheet.WIDTH; x++) { int xa = x + xp; if (xa < 0 || xa >= width || ya < 0 || ya >= height) continue; pixels[xa + ya * width] = sheet.pixels[x + y * sheet.WIDTH]; } } }
7
public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; }
6
@Override public void render(float interpolation) { if(!isEnabled) return; int xPos = x+width/2-titledim[0]/2; int yPos = y+height/2-titledim[1]/2; if(isSelected) Renderer.drawRect(new Vector2(x,y), new Vector2(width,height), 1, 0.6f, 0.6f, 1); Fonts.get("Arial").drawString(title, xPos, yPos, 20, 0xffffff); if(!isSelected) return; int currentY = height; for(int i=0;i<values.length;i++) { boolean isBoxHovered = hoveredBox == i; Renderer.drawRect(new Vector2(x,currentY), new Vector2(subWidth, height), 1, isBoxHovered?0.6f:0.2f, isBoxHovered?0.6f:0.2f, 1); Renderer.drawLineRect(new Vector2(x,currentY), new Vector2(subWidth, height), 0, 0, 0, 1); Fonts.get("Arial").drawString(values[i],x+10,currentY, 20, 0xffffff); if(keyCombos[i] != null) { int keyWidth = Fonts.get("Arial").getStringDim(keyCombos[i].toString(), 20)[0]; Fonts.get("Arial").drawString(keyCombos[i].toString(), x+subWidth-10-keyWidth, currentY, 20, 0xffffff); } currentY += subheight; } }
7
public boolean checksums() { if (h_protection_bit == 0) return true; else return false; }
1
public AntiAliasingLine(Excel ex1, Excel ex2) { begin = ex1; end = ex2; setColoredExes(); }
0
private <T extends GMResponseBase> T _GET(URL url, GMRequestBase request, Class<T> responseType) throws GongmingConnectionException { RestTemplate restTemplate = new RestTemplate(); ResponseEntity<T> responseEntity; T response = null; try { responseEntity = restTemplate.getForEntity( url.toString() + "?" + request.toQuery(url.getPath(), merchantSecret), responseType); response = responseEntity.getBody(); } catch (HttpStatusCodeException e) { // This exception has status code, e.g. 404 Not Found throw new GongmingConnectionException(e.getStatusCode(), e); } catch (InvalidKeyException e) { throw new GongmingConnectionException("商户密钥不合法", e); } return response; }
2
@Override public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (x >= this.x && y >= this.y && x <= this.x + this.width && y <= this.y + this.height) setState(ButtonState.ACTIVE); }
4
public void loadFromFile(String file) throws IOException{ File f= new File(file); FileReader fr= new FileReader(f); BufferedReader bf= new BufferedReader(fr); String line= bf.readLine(); double K=0; int vars=Integer.parseInt(line); line= bf.readLine(); double[] W= new double[vars]; double[] P=new double[vars]; int k=0; while(line!=null){ if(k==0){ K=Double.parseDouble(line); } else if(k==1){ String[] data=line.split("\t"); W= new double[data.length]; for (int i = 0; i < data.length; i++) { W[i]=Double.parseDouble(data[i]); } } else{ String[] data=line.split("\t"); P= new double[data.length]; for (int j = 0; j < data.length; j++) { P[j]=Double.parseDouble(data[j]); } } k++; line=bf.readLine(); } //Creates the model Model m = new Model(); QBnBVariable[] x= new QBnBVariable[W.length]; for (int i = 0; i < x.length; i++) { x[i]= new QBnBVariable(0, 1, 1, "x"+(i+1)); m.addVar(x[i]); } //Main Restricion QBnBLinExp le = new QBnBLinExp(); for (int i = 0; i < x.length; i++) { le.addTerm(W[i], x[i]); } QBnBconstr c = new QBnBconstr(le, 1, K, "K", m); m.addConst(c); //Objective function QBnBLinExp z = new QBnBLinExp(); for (int i = 0; i < x.length; i++) { z.addTerm(P[i], x[i]); } m.addObj(z); m.update(); QBnBEnv env= new QBnBEnv(m); env.print(true); env.maximize(); //Prints System.out.println("Value: "+env.getBestSolution()); for (int i = 0; i < x.length; i++) { System.out.println(x[i].getName()+": "+Math.round(x[i].getValue())); } }
9
public void setPriorMap(HashMap<String, Double> priorMap) throws LangDetectException { this.priorMap = new double[langlist.size()]; double sump = 0; for (int i=0;i<this.priorMap.length;++i) { String lang = langlist.get(i); if (priorMap.containsKey(lang)) { double p = priorMap.get(lang); if (p<0) throw new LangDetectException(ErrorCode.InitParamError, "Prior probability must be non-negative."); this.priorMap[i] = p; sump += p; } } if (sump<=0) throw new LangDetectException(ErrorCode.InitParamError, "More one of prior probability must be non-zero."); for (int i=0;i<this.priorMap.length;++i) this.priorMap[i] /= sump; }
5
public void moveRow(int start, int end, int to) { if (start < 0) { String message = "Start index must be positive: " + start; throw new IllegalArgumentException( message ); } if (end > getRowCount() - 1) { String message = "End index must be less than total rows: " + end; throw new IllegalArgumentException( message ); } if (start > end) { String message = "Start index cannot be greater than end index"; throw new IllegalArgumentException( message ); } int rowsMoved = end - start + 1; if (to < 0 || to > getRowCount() - rowsMoved) { String message = "New destination row (" + to + ") is invalid"; throw new IllegalArgumentException( message ); } // Save references to the rows that are about to be moved ArrayList<T> temp = new ArrayList<T>(rowsMoved); for (int i = start; i < end + 1; i++) { temp.add(modelData.get(i)); } // Remove the rows from the current location and add them back // at the specified new location modelData.subList(start, end + 1).clear(); modelData.addAll(to, temp); // Determine the rows that need to be repainted to reflect the move int first; int last; if (to < start) { first = to; last = end; } else { first = start; last = to + end - start; } fireTableRowsUpdated(first, last); }
7
private static String encode_base64(byte d[], int len) throws IllegalArgumentException { int off = 0; StringBuffer rs = new StringBuffer(); int c1, c2; if (len <= 0 || len > d.length) throw new IllegalArgumentException ("Invalid len"); while (off < len) { c1 = d[off++] & 0xff; rs.append(base64_code[(c1 >> 2) & 0x3f]); c1 = (c1 & 0x03) << 4; if (off >= len) { rs.append(base64_code[c1 & 0x3f]); break; } c2 = d[off++] & 0xff; c1 |= (c2 >> 4) & 0x0f; rs.append(base64_code[c1 & 0x3f]); c1 = (c2 & 0x0f) << 2; if (off >= len) { rs.append(base64_code[c1 & 0x3f]); break; } c2 = d[off++] & 0xff; c1 |= (c2 >> 6) & 0x03; rs.append(base64_code[c1 & 0x3f]); rs.append(base64_code[c2 & 0x3f]); } return rs.toString(); }
5
private static boolean checkIsPrime(long n) { if (n == 1) { return false; } else if (n < 1) { return false; } else if (n < 4) { return true; } else if (n % 2 == 0) { return false; } else if (n < 9) { return true; } else if (n % 3 == 0) { return false; } long maxLoop = (long) (Math.sqrt(n) + 1); for (long i = 5; i < maxLoop; i += 6) { if (n % i == 0) { return false; } if (n % (i + 2) == 0) { return false; } } return true; }
9
public Object readForthNode( File f, LoadContext<?> parentContext ) throws ScriptError, IOException { final HashMapLoadContext<Object> ctx = new HashMapLoadContext<Object>(parentContext); Interpreter interp = new Interpreter(); SafeProcedures.register(interp.wordDefinitions); interp.wordDefinitions.put("include", new StandardWordDefinition() { @Override public void run(Interpreter interp, SourceLocation sLoc) throws ScriptError { String filename = interp.stackPop(String.class, sLoc); File f = findOnIncludePath(filename); if( f == null ) { throw new ScriptError("Couldn't find '"+filename+"' on include path", sLoc); } try { runScript(interp, f); } catch( IOException e ) { throw new RuntimeException(e); } } }); interp.wordDefinitions.put("ctx-get", new StandardWordDefinition() { // name -> value @Override public void run( Interpreter interp, SourceLocation sLoc ) throws ScriptError { String name = interp.stackPop(String.class, sLoc); try { Object o = get( name, ctx ); if( o == null ) { throw new ScriptError("Couldn't resolve '"+name+"' from load context", sLoc); } interp.stackPush( o ); } catch(IOException e) { throw new RuntimeException(e); } } }); interp.wordDefinitions.put("ctx-put", new StandardWordDefinition() { // value, name -> () @Override public void run( Interpreter interp, SourceLocation sLoc ) throws ScriptError { String name = interp.stackPop(String.class, sLoc); Object value = interp.stackPop(Object.class, sLoc); ctx.put( name, value ); } }); try { runScript(interp, f); } catch( ScriptError e ) { throw e; } catch( IOException e ) { throw e; } return interp.stackPop( Object.class, new BaseSourceLocation(f.getPath(), 0, 0) ); }
7
public boolean stem() { int v_1; int v_2; int v_3; int v_4; // (, line 157 // do, line 159 v_1 = cursor; lab0: do { // call prelude, line 159 if (!r_prelude()) { break lab0; } } while (false); cursor = v_1; // do, line 160 v_2 = cursor; lab1: do { // call mark_regions, line 160 if (!r_mark_regions()) { break lab1; } } while (false); cursor = v_2; // backwards, line 161 limit_backward = cursor; cursor = limit; // do, line 162 v_3 = limit - cursor; lab2: do { // call standard_suffix, line 162 if (!r_standard_suffix()) { break lab2; } } while (false); cursor = limit - v_3; cursor = limit_backward; // do, line 163 v_4 = cursor; lab3: do { // call postlude, line 163 if (!r_postlude()) { break lab3; } } while (false); cursor = v_4; return true; }
8
protected static HostConfiguration getHostConfiguration(URL serviceURL) { HostConfiguration hostConfig = new HostConfiguration(); // apply proxy settings: String host = System.getProperty("http.proxyHost"); String port = System.getProperty("http.proxyPort"); String nonProxyHosts = System.getProperty("http.nonProxyHosts"); // check if service url is among the non-proxy-hosts: boolean serviceIsNonProxyHost = false; if (nonProxyHosts != null && nonProxyHosts.length() > 0) { String[] nonProxyHostsArray = nonProxyHosts.split("\\|"); String serviceHost = serviceURL.getHost(); for (String nonProxyHost : nonProxyHostsArray) { if ( nonProxyHost.equals(serviceHost)) { serviceIsNonProxyHost = true; break; } } } // set proxy: if ( serviceIsNonProxyHost == false && host != null && host.length() > 0 && port != null && port.length() > 0) { int portNumber = Integer.parseInt(port); hostConfig.setProxy(host, portNumber); LOGGER.info("Using proxy: " + host + " on port: " + portNumber); } return hostConfig; }
9
static String describeWar(int warLength) { switch (warLength) { case 0: return "warless battles"; case 1: return "wars"; case 2: return "double wars"; case 3: return "triple wars"; case 4: return "quadruple wars"; case 5: return "quintuple wars"; case 6: return "sextuple wars"; case 7: return "septuple wars"; case 8: return "octuple wars"; default: return "x" + warLength + " wars"; } }
9
public void handleRequest(Session Session, EventRequest Message) throws Exception { if (Message.GetHeader() == 4000) { String SWFBUILD = Message.GetBodyString().replace("{0}", ""); if (!SWFBUILD.contains(Grizzly.HabboBuild) && !SWFBUILD.contains("Cracked")) { Grizzly.WriteOut("Build Mismatch; May hit some un-runnable actions!"); Grizzly.WriteOut("Grizzly's SWF Build: " + Grizzly.HabboBuild); Grizzly.WriteOut("Your SWF Build: " + SWFBUILD); } } /*if (!MessageLibrary.containsKey(Message.GetHeader())) { Grizzly.WriteOut("Unhandle'd Incoming ID: " + Message.GetHeader()); return; }*/ if (Grizzly.GrabConfig().GrabValue("net.grizzly.packetlog").equals("1")) { Grizzly.WriteOut("[" + Message.GetHeader() + "] " + Message.GetBodyString() + " sent to " + Session.GrabIP()); } /* * A quick fix until I get the correct header. * 1014 - When a menu button is clicked (those buttons on the left) * It then checks if the button is the catalog one, if so.. it runs the catalog init! */ if (Message.GetHeader() == 1014 && Message.GetBodyString().contains("CATALOGUE")) { (new InitializeCatalogEvent()).Parse(Session, Message); return; } if (this.MessageLibrary.containsKey(Message.GetHeader())) { this.MessageLibrary.get(Message.GetHeader()).Parse(Session, Message); } }
7
@Override public ByteBuffer encode(Message message) { switch (getSession().getState()) { case CONNECTED: case LOGGING_IN: return loginEncoder.encode(message); case UPDATING: // TODO: Update encoder. break; case LOGGED_IN: // TODO: Game stream encoding. break; } return null; }
4
private static void writePrimitiveSetBestIdentifierValueForSelect(final CodeVisitor mw, final Class returnType, final int psIdx, final int valueArrayIdx, final int colPos) { mw.visitVarInsn(ALOAD, psIdx); mw.visitIntInsn(SIPUSH, colPos + 1); mw.visitVarInsn(ALOAD, valueArrayIdx); mw.visitIntInsn(SIPUSH, colPos); mw.visitInsn(AALOAD); if (returnType == boolean.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Boolean.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Boolean.class), "booleanValue", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, new Type[]{}) ); } else if (returnType == char.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Character.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Character.class), "charValue", Type.getMethodDescriptor(Type.CHAR_TYPE, new Type[]{}) ); } else if (returnType == byte.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Byte.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Byte.class), "byteValue", Type.getMethodDescriptor(Type.BYTE_TYPE, new Type[]{}) ); } else if (returnType == short.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Short.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Short.class), "shortValue", Type.getMethodDescriptor(Type.SHORT_TYPE, new Type[]{}) ); } else if (returnType == int.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Integer.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE, new Type[]{})); } else if (returnType == long.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Long.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Long.class), "longValue", Type.getMethodDescriptor(Type.LONG_TYPE, new Type[]{}) ); } else if (returnType == float.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Float.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Float.class), "floatValue", Type.getMethodDescriptor(Type.FLOAT_TYPE, new Type[]{}) ); } else if (returnType == double.class) { mw.visitTypeInsn(CHECKCAST, Type.getInternalName(Double.class)); mw.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(Double.class), "doubleValue", Type.getMethodDescriptor(Type.DOUBLE_TYPE, new Type[]{}) ); } final Method targetSetter = MethodsForPreparedStatement.findSetter( returnType); mw.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(java.sql.PreparedStatement.class), targetSetter.getName(), Type.getMethodDescriptor(targetSetter)); }
8
void txtTable() { System.out.println(String.format("%-60s\t%-60s\t%-10s\t%s", "Genome", "Organism", "Status", "Database download link")); System.out.println(String.format("%-60s\t%-60s\t%-10s\t%s", "------", "--------", "------", "----------------------")); for (String genomeVer : genVerSorted) { String name = nameByGenomeVer.get(genomeVer); // Download link String url = config.downloadUrl(genomeVer).toString(); // "http://sourceforge.net/projects/snpeff/files/databases/v" + SnpEff.VERSION_MAJOR + "/snpEff_v" + SnpEff.VERSION_MAJOR + "_" + name + ".zip"; String database = config.getDirData() + "/" + genomeVer + "/snpEffectPredictor.bin"; String status = ""; if (Gpr.canRead(database)) status = "OK"; // Show System.out.println(String.format("%-60s\t%-60s\t%-10s\t%s", genomeVer, name, status, url)); } }
2
public void getExits() { if (getNExit() == null && getSExit() == null && getEExit() == null && getWExit() == null) { System.out.println("There are no exits!"); } else { String sExits = "";//the string of exits if (oneExit() == true) { System.out.print("There is one exit to the "); } else { System.out.print("There are exits to the "); } if (getNExit() != null) { sExits += "north, "; } if (getSExit() != null) { sExits += "south, "; } if (getEExit() != null) { sExits += "east, "; } if (getWExit() != null) { sExits += "west, "; } sExits = sExits.substring(0, sExits.length() - 2); System.out.print(sExits); System.out.println("."); } }
9
@Override @SuppressWarnings("unchecked") public MaterialPattern read(Object value) { if (value == null) { logger.warning("Unknown material (null value)"); return null; } else if (value instanceof Map) { Map<Object, Object> structure = (Map<Object, Object>) value; if (structure.size() != 1) { logger.warning("Material in format (mat:data) must have only one entry"); return null; } Object material = structure.keySet().iterator().next(); if (material == null) { logger.warning("Invalid material in material:data format (null provided for material)"); return null; } MaterialPattern pattern = fromMaterial(material); if (pattern == null) { return null; // Already handled an error } if (pattern.hasDataFilter()) { logger.warning("Material '" + material + "' already has data attached in the material database; can't add more"); return pattern; } Object data = structure.get(material); if (data == null) { return pattern; } else if (data instanceof List) { for (Object dataEntry : (List<Object>) data) { appendData(pattern, dataEntry); } } else { appendData(pattern, data); } return pattern; } else { return fromMaterial(value); } }
9
public ArrayList<String> getSoundPaths() { return SoundPaths; }
0
public void showFirmwareReadme() { try { // seems odd that there isn't a cross platform way to do this! if (os == OS.WINDOWS) Runtime.getRuntime().exec("cmd.exe /c start firmware/readme.txt"); if (os == OS.MAC) Runtime.getRuntime().exec("open firmware/readme.txt"); // this seems cheezy, but I don't know a better way to do it. if (os == OS.LINUX) Controller.log("Not yet working on Linux yet! Please look in the firmware directory.", "error"); //Runtime.getRuntime().exec("vi " + System.getProperty("user.dir") + "/lib/firmware/readme.txt"); } catch (IOException e) { Controller.log("Unable to open firmware readme file.", "error"); e.printStackTrace(); } }
4
private void initializeProfile() { System.out.println("Initializing the file"); File file = new File("../src/saveData/saveFile.json"); try { writer = new PrintWriter(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } writer.flush(); writer.close(); }
1
private static void createDisplay() { try { Display.setDisplayModeAndFullscreen(new DisplayMode(1600, 900)); Display.setFullscreen(false); Display.setVSyncEnabled(true); Display.setResizable(false); Game.WIDTH = Display.getDisplayMode().getWidth(); Game.HEIGHT = Display.getDisplayMode().getHeight(); Logger.log("Display created with display mode:" + Display.getDisplayMode()); } catch (LWJGLException e) { e.printStackTrace(); } ; try { Display.create(); } catch (LWJGLException e) { e.printStackTrace(); } }
2
private int getAmicableNumberSumUnder(int limit) { Map<Integer, Integer> map = new LinkedHashMap<>(limit - 1); for (int i = 1; i < limit; i++) { map.put(i, getSumOfFactors(i)); } int total = 0; for (Map.Entry<Integer, Integer> entry : map.entrySet()) { int sum = entry.getValue(); if (sum > entry.getKey() && sum < limit && map.get(sum).equals(entry.getKey())) { total += entry.getKey() + entry.getValue(); } } return total; }
5
public void iterativeInOrder(TreeNode root) { if (root == null) { return; } Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode currentNode = root; while (currentNode != null) { if (currentNode.getLeft() != null) { stack.push(currentNode); currentNode = currentNode.getLeft(); } else { System.out.println(currentNode.getData()); if (!stack.isEmpty() && currentNode.getRight()==null) { currentNode = stack.pop(); System.out.println(currentNode.getData()); } currentNode = currentNode.getRight(); } } }
5
public void start(MapleCharacter c, int npc) { if ((autoStart || checkNPCOnMap(c, npc)) && canStart(c, npc)) { for (MapleQuestAction a : startActs) { a.runStart(c, null); } if (!customend) { final MapleQuestStatus oldStatus = c.getQuest(this); final MapleQuestStatus newStatus = new MapleQuestStatus(this, (byte) 1, npc); newStatus.setCompletionTime(oldStatus.getCompletionTime()); newStatus.setForfeited(oldStatus.getForfeited()); c.updateQuest(newStatus); } else { NPCScriptManager.getInstance().endQuest(c.getClient(), npc, getId(), true); } } }
5
synchronized public static org.omg.CORBA.TypeCode type () { if (__typeCode == null) { __typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (BankHelper.id (), "Bank"); } return __typeCode; }
1
public static void main(String[] args) throws UnspecifiedErrorException, IOException, InvalidHeaderException { // Attach the shutdown hook to do any necessary cleanup Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { in.close(); } }); // Setup the logger ClientLogger.setLevel(Level.FINEST); ClientLogger.addLogStream("C:\\logs\\clientlog%g.log", null, new MessageOnlyFormatter()); client = new Client(getUsernameFromConsole()); client.setSuppressingErrors(args.length > 0 ? Boolean.parseBoolean(args[0]) : true); while (true) { switch (getMainMenuSelection()) { case CONNECT: connectOption(); break; case DISCONNECT: disconnectOption(); break; case EXIT: exitOption(); break; case MESSAGES: MessagesOptionShell.RunMessagesOption(client, in); break; case QUEUES: QueuesOptionShell.RunQueuesOption(client, in); break; } } }
7
@Override public void setName(String name) { super.setName(name); }
0
Module removeSubModule(Module module) { if (null == this.subModules || null == module) { return this; } if (this.subModules.remove(module) && this.subModules.isEmpty()) { this.subModules = null; } return this; }
4
@Test public void testForAssignments() { for(int i = 6; i <= 10; i++) { for(int j = 1; j <= 7; j++ ) { try { assertNotNull("Assesment Getter returns assignment: " + i + " " + j, AssesmentGetter.getAssignment(i, j)); } catch (ClassNotFoundException e) { fail("Assignment " + i + " " + j + " does not exist formally"); } } } }
3
private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed if (estaModoEdicao() && exclusaoConfirmada()) { try { excluir(); } catch (ValidacaoException ex) { _unitOfWork.rollback(); JOptionPane.showMessageDialog(this, ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_btnExcluirActionPerformed
3
public static ServiceTime getServiceTime(Address srcAddr, Address dstAddr) { ServiceTime serviceTime = new ServiceTime(); serviceTime.setSrcAddr(srcAddr); serviceTime.setDstAddr(dstAddr); String url = "http://www.sf-express.com/dwr/call/plaincall/ServiceTimeManager.getServiceTime_omp.dwr"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Params.CALLCOUNT, "1")); params.add(new BasicNameValuePair(Params.PAGE, "/cn/sc/delivery_step/enquiry/serviceTime.html")); params.add(new BasicNameValuePair(Params.HTTPSESSIONID, "AA221E633D34390E22017CDF44103228")); params.add(new BasicNameValuePair(Params.SCRIPTSESSIONID, "ABCFB15977C207121D3B56939B23DAE5952")); params.add(new BasicNameValuePair(Params.C0SCRIPTNAME, "ServiceTimeManager")); params.add(new BasicNameValuePair(Params.C0METHODNAME, "getServiceTime_omp")); params.add(new BasicNameValuePair(Params.C0ID, "0")); params.add(new BasicNameValuePair(Params.C0PARAM0, "string:" + srcAddr.getProvince())); params.add(new BasicNameValuePair(Params.C0PARAM1, "string:" + srcAddr.getCity())); params.add(new BasicNameValuePair(Params.C0PARAM2, "string:" + srcAddr.getArea())); params.add(new BasicNameValuePair(Params.C0PARAM3, "string:" + srcAddr.getCountry())); params.add(new BasicNameValuePair(Params.C0PARAM4, "string:" + dstAddr.getProvince())); params.add(new BasicNameValuePair(Params.C0PARAM5, "string:" + dstAddr.getCity())); params.add(new BasicNameValuePair(Params.C0PARAM6, "string:" + dstAddr.getArea())); params.add(new BasicNameValuePair(Params.C0PARAM7, "string:" + dstAddr.getCountry())); params.add(new BasicNameValuePair(Params.C0PARAM8, "string:" + SendTime.day)); params.add(new BasicNameValuePair(Params.C0PARAM9, "string:" + SendTime.hour)); params.add(new BasicNameValuePair(Params.C0PARAM10, "string:" + SendTime.minute)); params.add(new BasicNameValuePair(Params.C0PARAM11, "string:CN")); params.add(new BasicNameValuePair(Params.C0PARAM12, "string:SC")); params.add(new BasicNameValuePair(Params.BATCHID, "24")); HttpClientUtils.doPost(url, params); String rtn = HttpClientUtils.getResponseAsString(); // System.out.println(rtn); // map<快递编号, 时间差(day)> Map<String, Double> serviceTmMap = new HashMap<String, Double>(); List<String> blearDeliverTmList = StringParserUtils.parseString(rtn, "(?:s\\d{1,}.blearDeliverTm=\")(.*?)(?:\";)"); List<String> productTypeList = StringParserUtils.parseString(rtn, "(?:s\\d{1,}.productTypeCode=\")(.*?)(?:\";)"); // log.info(srcAddr.toString() + " >> " + dstAddr.toString()); for (int i = 0; i < blearDeliverTmList.size(); ++i) { serviceTmMap.put(productTypeList.get(i), calHours(blearDeliverTmList.get(i) + ":00")); // serviceTmList.add(new ServiceTime(srcAddr, dstAddr, // blearDeliverTmList.get(i), productTypeList.get(i))); // log.info(productTypeList.get(i) + " - " + // blearDeliverTmList.get(i)); } Set<String> keys = serviceTmMap.keySet(); for (Iterator<String> it = keys.iterator(); it.hasNext();) { String key = (String) it.next(); // System.out.println(key); // System.out.println(serviceTmMap.get(key)); if ("T1".equals(key)) { serviceTime.setT1_time(serviceTmMap.get("T1")); } if ("T4".equals(key)) { serviceTime.setT4_time(serviceTmMap.get("T4")); } if ("SP4".equals(key)) { serviceTime.setSp4_time(serviceTmMap.get("SP4")); } if ("SP5".equals(key)) { serviceTime.setSp5_time(serviceTmMap.get("SP5")); } if ("T6".equals(key)) { serviceTime.setT6_time(serviceTmMap.get("T6")); } if ("T801".equals(key)) { serviceTime.setT801_time(serviceTmMap.get("T801")); } } // 加时信息 AddTimeInfo addTimeInfo = AddTimeAddrUtils.getAddTimeAddr(dstAddr); serviceTime.setAddTimeInfo(addTimeInfo); return serviceTime; }
8
public double getAttackMultiplier() { if (onPrayersCount == 0) return 1.0; double value = 1.0; // normal if (usingPrayer(0, 2)) value += 0.05; else if (usingPrayer(0, 7)) value += 0.10; else if (usingPrayer(0, 15)) value += 0.15; else if (usingPrayer(0, 25)) value += 0.15; else if (usingPrayer(0, 27)) value += 0.20; else if (usingPrayer(1, 1)) { double d = (leechBonuses[0]); value += d / 100; } else if (usingPrayer(1, 10)) { double d = (5 + leechBonuses[3]); value += d / 100; } else if (usingPrayer(1, 19)) { double d = (15 + leechBonuses[8]); value += d / 100; } return value; }
9
public int access_x_coordinate(int x) { if (x < 0) { return 0; } else if (x >= height) { return height - 1; } else { return x; } }
2
public JLabel getPlayer2Piece() { boolean test = false; if (test || m_test) { System.out.println("Drawing :: getPlayer2Piece() BEGIN"); } if (test || m_test) System.out.println("Drawing:: getPlayer2Piece() - END"); return m_player2Piece; }
4
public void draw(Graphics2D g) { g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); bg.draw(g); g.drawImage(title, 105, 25, null); g.drawImage(up, 290, 188, null); g.drawImage(down, 310, 188, null); g.drawImage(enter, 80, 188, null); if (currentChoice == 0) { g.drawImage(head, 163, 126, null); } if (currentChoice == 1) { g.drawImage(head, 163, 142, null); } g.setColor(versionColor); g.setFont(fontInfo); g.drawString("Open Beta " + Game.version, 162, 75); g.drawString("Choose", 83, 210); g.drawString("Select", 291, 210); g.setFont(font); for (int i = 0; i < options.length; i++) { if (i == currentChoice) { g.setColor(Color.BLACK); } else { g.setColor(Color.RED); } g.drawString(options[i], 190, 140 + i * 15); } }
4
private static void addQueryResults(List<ConstraintViolation> results, QueryOrTemplateCall qot, Resource resource, boolean matchValue, List<SPINStatistics> stats, SPINModuleRegistry registry) { QuerySolutionMap arqBindings = new QuerySolutionMap(); String queryString = ARQFactory.get().createCommandString(qot.getQuery(), registry); if(resource == null && SPINUtil.containsThis(qot.getQuery(), registry)) { queryString = SPINUtil.addThisTypeClause(queryString); } else { arqBindings.add(SPIN.THIS_VAR_NAME, resource); } Query arq = ARQFactory.get().createQuery(queryString); Model model = resource.getModel(); QueryExecution qexec = ARQFactory.get().createQueryExecution(arq, model); qexec.setInitialBinding(arqBindings); long startTime = System.currentTimeMillis(); if(arq.isAskType()) { if(qexec.execAsk() != matchValue) { String message; String comment = qot.getQuery().getComment(); if(comment == null) { message = SPINLabels.get().getLabel(qot.getQuery()); } else { message = comment; } message += "\n(SPIN constraint at " + SPINLabels.get().getLabel(qot.getCls()) + ")"; List<SimplePropertyPath> paths = getPropertyPaths(resource, qot.getQuery().getWhere(), null, registry); Resource source = getSource(qot); results.add(createConstraintViolation(paths, NO_FIXES, resource, message, source)); } } else if(arq.isConstructType()) { Model cm = qexec.execConstruct(); qexec.close(); addConstructedProblemReports(cm, results, model, qot.getCls(), resource, qot.getQuery().getComment(), getSource(qot), registry); } long endTime = System.currentTimeMillis(); if(stats != null) { long duration = startTime - endTime; String label = qot.toString(); String queryText; if(qot.getTemplateCall() != null) { queryText = SPINLabels.get().getLabel(qot.getTemplateCall().getTemplate(registry).getBody()); } else { queryText = SPINLabels.get().getLabel(qot.getQuery()); } Node cls = qot.getCls() != null ? qot.getCls().asNode() : null; stats.add(new SPINStatistics(label, queryText, duration, startTime, cls)); } }
9
public FineGUI(){ screenSize = Toolkit.getDefaultToolkit().getScreenSize(); screenMax = Toolkit.getDefaultToolkit().getScreenInsets(fineDialog.getGraphicsConfiguration()); taskbarSize = screenMax.bottom; screenWidth = (int)screenSize.getWidth(); screenHeight = (int)screenSize.getHeight() - taskbarSize; //Fill container contentPane.setLayout(fineLayout); contentPane.add(backButton); contentPane.add(detailButton); contentPane.add(payButton); contentPane.add(listScrollPane); contentPane.add(updateButton); //Prepare frame components listField.setEditable(false); listField.setSelectionColor(Color.LIGHT_GRAY); //Placement of components on screen fineLayout.putConstraint(SpringLayout.WEST, backButton, (int)(screenWidth * 0.01), SpringLayout.WEST, contentPane); fineLayout.putConstraint(SpringLayout.NORTH, backButton, (int)(screenHeight * 0.01), SpringLayout.NORTH, contentPane); fineLayout.putConstraint(SpringLayout.WEST, listScrollPane, (int)(screenWidth * 0.4166), SpringLayout.WEST, contentPane); fineLayout.putConstraint(SpringLayout.NORTH, listScrollPane, (int)(screenHeight * 0.3703), SpringLayout.NORTH, contentPane); fineLayout.putConstraint(SpringLayout.WEST, payButton, (int)(screenWidth * 0.9), SpringLayout.WEST, contentPane); fineLayout.putConstraint(SpringLayout.NORTH, payButton, (int)(screenHeight * 0.3703), SpringLayout.NORTH, contentPane); fineLayout.putConstraint(SpringLayout.WEST, detailButton, (int)(screenWidth * 0.9), SpringLayout.WEST, contentPane); fineLayout.putConstraint(SpringLayout.NORTH, detailButton, (int)(screenHeight * 0.43), SpringLayout.NORTH, contentPane); fineLayout.putConstraint(SpringLayout.WEST, updateButton, (int)(screenWidth * 0.50), SpringLayout.WEST, contentPane); fineLayout.putConstraint(SpringLayout.NORTH, updateButton, (int)(screenHeight * 0.85), SpringLayout.NORTH, contentPane); listField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { int offset = listField.viewToModel(e.getPoint()); int rowStart = Utilities.getRowStart(listField, offset); int rowEnd = Utilities.getRowEnd(listField, offset); listField.setSelectionStart(rowStart); listField.setSelectionEnd(rowEnd); selectedLine = listField.getText().substring(rowStart, rowEnd); int end = selectedLine.indexOf("|", 5); selectedLine = selectedLine.substring(5, end - 1); } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ MainGUI.switchToMenu(); } }); detailButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ int books = 0; int media = 0; for(Fine f : fineList){ if(f.getFineId() == Integer.valueOf(selectedLine)){ fine = f; } } if(activeUser == activeLibrarian){ rentTrans = activeLibrarian.getRentTransaction(fine.getTransactionId()); }else{ rentTrans = activeAdmin.getRentTransaction(fine.getTransactionId()); } if(rentTrans.getBookList() != null){ books = rentTrans.getBookList().size(); System.out.println(books); } if(rentTrans.getMediaList() != null){ media = rentTrans.getMediaList().size(); System.out.println(media); } JOptionPane.showMessageDialog(contentPane, "Transaction ID: " + rentTrans.getRentTransId() + "\nBooks: " + books + "\nMedia: " + media); } }); payButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ if(activeUser == activeLibrarian){ activeLibrarian.payFine(Integer.valueOf(selectedLine)); }else{ activeAdmin.payFine(Integer.valueOf(selectedLine)); } reset(); update(); } }); updateButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ reset(); update(); } }); }
7
@Override public void startSetup(Attributes atts) { super.startSetup(atts); addActionListener(this); }
0
static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } }
7
public static void printArgumentConstraint(OutputStream sql, Stella_Object argument, RelationColumnInfo column) { { NamedDescription columntype = column.columnType; Surrogate argname = Logic.objectSurrogate(argument); Module argmodule = ((argname != null) ? ((Module)(argname.homeContext)) : ((Module)(null))); RelationColumnInfo modulerefcolumn = column.moduleReferenceColumn; boolean casesensitiveP = ((argmodule != null) && argmodule.caseSensitiveP) || Stella_Object.isaP(argument, RDBMS.SGT_STELLA_STRING_WRAPPER); if (RDBMS.collectionValuedConstraintP(argument)) { sql.nativeStream.print("("); { Stella_Object subarg = null; Cons iter000 = RDBMS.collectionValuedConstraintElements(argument); int si = Stella.NULL_INTEGER; int iter001 = 1; for (;!(iter000 == Stella.NIL); iter000 = iter000.rest, iter001 = iter001 + 1) { subarg = iter000.value; si = iter001; if (si > 1) { sql.nativeStream.print(" OR "); } RDBMS.printColumnConstraint(sql, column, RDBMS.coercePowerloomObjectToString(subarg, columntype), casesensitiveP); } } sql.nativeStream.print(")"); } else { RDBMS.printColumnConstraint(sql, column, RDBMS.coercePowerloomObjectToString(argument, columntype), casesensitiveP); } if ((modulerefcolumn != null) && (argmodule != null)) { sql.nativeStream.print(" AND "); RDBMS.printColumnConstraint(sql, modulerefcolumn, argmodule.moduleName, false); } } }
8
private double calculateScore(ArrayList<seed> seedlist) { double total = 0.0; for (int i = 0; i < seedlist.size(); i++) { double score = 0.0; double chance = 0.0; double totaldis = 0.0; double difdis = 0.0; for (int j = 0; j < seedlist.size(); j++) { if (j != i) { totaldis = totaldis + Math.pow( distance(seedlist.get(i), seedlist.get(j)), -2); } } for (int j = 0; j < seedlist.size(); j++) { if (j != i && ((seedlist.get(i).tetraploid && !seedlist.get(j).tetraploid) || (!seedlist .get(i).tetraploid && seedlist.get(j).tetraploid))) { difdis = difdis + Math.pow( distance(seedlist.get(i), seedlist.get(j)), -2); } } chance = difdis / totaldis; score = chance + (1 - chance) * s; total = total + score; } return total; }
9
public String toString() { if (x!=0 && y>0) { return x+" + "+y+"i"; } if (x!=0 && y<0) { return x+" - "+(-y)+"i"; } if (y==0) { return String.valueOf(x); } if (x==0) { return y+"i"; } // shouldn't get here (unless Inf or NaN) return x+" + i*"+y; }
6
@Override public boolean activate() { return Game.isLoggedIn() && Players.getLocal() != null && Players.getLocal().isOnScreen() && !Widgets.get(1252, 1).visible() && !Widgets.get(1234, 10).visible(); }
4