text
stringlengths
14
410k
label
int32
0
9
private void runLive() { TalkerTextWork localTalkerTextWork = this.dd.getTalkerTextWork(); TalkerLineWork localTalkerLineWork = this.dd.getTalkerLineWork(); long l1 = System.currentTimeMillis(); long l2 = l1 + 86400000L; long l3 = l1 + 3600000L; while (this.live) try { Thread.sleep(60000L); if (!(this.live)) break; localTalkerTextWork.gc(); localTalkerLineWork.gc(); if (ThreadPool.getCountOfSleeping() >= 8) ThreadPool.poolGcAll(); if (this.debug.bool_debug) { int i = localTalkerTextWork.size(); int j = localTalkerLineWork.size(); this.debug.logSys("pchats_gc:connect t=" + i + " l=" + j); this.debug.logSys("ThreadSleep=" + ThreadPool.getCountOfSleeping() + " ThreadWork=" + ThreadPool.getCountOfWorking()); } if (localTalkerTextWork.size() == 0) { synchronized (this.tLive) { this.debug.log("pchat_gc:suspend"); ThreadPool.poolGcAll(); this.isLiveThread = false; this.tLive.wait(); this.isLiveThread = true; } this.debug.log("pchat_gc:resume"); } l1 = System.currentTimeMillis(); if (l1 >= l3) { l3 = l1 + 3600000L; this.debug.log(new Date().toString()); ThreadPool.poolGcAll(); System.gc(); System.runFinalization(); } if (l1 >= l2) { l2 += l1 + 86400000L; this.debug.newLogFile(Io.getDateString("pserv_", "log", this.config.getString("Server_Log_Server_Dir", "save_server"))); this.dd.clearKillList(); } } catch (Throwable localThrowable) { if (this.live) localThrowable.printStackTrace(); } label354: exitServer(); }
9
static double normalizeAngle(double a) { while (a < 0) a += 2*Math.PI; while (a >= 2*Math.PI) a -= 2*Math.PI; return a; }
2
public void searchAvailableCells(){ int numB1 = 1 ; int numB2 = 1 ; int numB3 = 1 ; int numB4 = 1 ; for (int i = 0; i < 28; i++) { if (i < 7) { if (this.testAvailabe(numB1 * -1, numB1, i)){ numB1++; }else{ this.FilterAvailable(i, 7); i = 7 ; continue; } } else if (i < 14) { if(this.testAvailabe(numB2 * -1, numB2 * -1, i)){ numB2++; }else{ this.FilterAvailable(i, 14); i= 14 ; continue; } } else if (i < 21) { if(this.testAvailabe(numB3, numB3 * -1, i)){ numB3++; }else{ this.FilterAvailable(i, 21); i= 21; continue; } } else if (i < 28) { if(this.testAvailabe(numB4, numB4, i)){ numB4++; }else{ this.FilterAvailable(i, 28); i= 28 ; continue; } } } }
9
public CheckResultMessage pass(String message) { return new CheckResultMessage(message); }
0
public void generateInOrderWire() { recursiveTraverse(this.root, new TraverseCallback() { private TreeNode previous; public void action(TreeNode current) { if (current.hasNoLeftSide()) { if (previous != null) { current.leftChild = previous; } current.leftIsWire = true; } if (previous != null && previous.hasNoRightSide()) { previous.rightChild = current; previous.rightIsWire = true; } previous = current; } }); }
4
private static String encrypt(final int[] key, final String text) { String encryptedText = ""; logger.log(Level.INFO, "Plain text: {0}", text); logger.log(Level.FINE, "Key: {0}", Arrays.toString(key)); char temp[][] = new char[text.length()][key.length]; int order[] = new int[key.length]; for (int i = 0; i < order.length; i++) { int j = 0; while (key[j] != i + 1) { j++; } order[i] = j; } int n = 0, maxrow = 0; for (int row = 0; n < text.length(); row++, maxrow++) { for (int column = 0; n < text.length() && column < key.length; column++) { temp[row][column] = text.charAt(n++); } // System.out.println(Arrays.toString(temp[row])); } for (int column = 0; column < key.length; column++) { for (int row = 0; row < maxrow; row++) { if (temp[row][order[column]] != '\0') { encryptedText += temp[row][order[column]]; } else { // encryptedText += ' '; } } } logger.log(Level.INFO, "Encrypted text: {0}", encryptedText); return encryptedText; }
8
private void checkCollision(){ if(r.intersects(StartingClass.hb.r)){ visible=false; if(StartingClass.hb.health > 0){ StartingClass.hb.health -= 1; } if(StartingClass.hb.health == 0){ StartingClass.hb.setCenterX(-100); StartingClass.score += 5; } } if(r.intersects(StartingClass.hb2.r)){ visible = false; StartingClass.score += 1; if(StartingClass.hb2.health > 0){ StartingClass.hb2.health -= 1; } if(StartingClass.hb2.health == 0){ StartingClass.hb2.setCenterX(-100); StartingClass.score += 5; } } }
6
public YAMLConfig(InputStream configStream, File configFile, int comments, JavaPlugin plugin) { this.comments = comments; this.manager = new YAMLConfigManager(plugin); this.file = configFile; try { this.config = YamlConfiguration.loadConfiguration(new InputStreamReader(configStream, "UTF-8")); } catch (NoSuchMethodError ignored) { } catch (UnsupportedEncodingException ignored) { } if (this.config == null) { this.config = YamlConfiguration.loadConfiguration(configStream); } this.plugin = plugin; }
3
public AutomatonChecker() { }
0
@Override public void resetSettings() { settings.setDefault(); }
0
private void batchEstimateDataAndMemory(boolean useRuntimeMaxJvmHeap, String outputDir, int reduceBase) throws IOException { //File mDataOutputFile = new File(outputDir, "eDataMappers.txt"); //File rDataOutputFile = new File(outputDir, "eDataReducers.txt"); File mJvmOutputFile = new File(outputDir, "eJvmMappers.txt"); File rJvmOutputFile = new File(outputDir, "eJvmReducers.txt"); if(!mJvmOutputFile.getParentFile().exists()) mJvmOutputFile.getParentFile().mkdirs(); //PrintWriter mDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(mDataOutputFile))); //PrintWriter rDataWriter = new PrintWriter(new BufferedWriter(new FileWriter(rDataOutputFile))); PrintWriter mJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(mJvmOutputFile))); PrintWriter rJvmWriter = new PrintWriter(new BufferedWriter(new FileWriter(rJvmOutputFile))); //displayMapDataTitle(mDataWriter); //displayReduceDataTitle(rDataWriter); displayMapJvmCostTitle(mJvmWriter); displayReduceJvmCostTitle(rJvmWriter); for(int splitMB = 64; splitMB <= 256; splitMB = splitMB * 2) { for(int xmx = 1000; xmx <= 4000; xmx = xmx + 1000) { for(int ismb = 200; ismb <= 800; ismb = ismb + 200) { for(int reducer = reduceBase; reducer <= reduceBase * 2; reducer = reducer * 2) { for(int xms = 0; xms <= 1; xms++) { //--------------------------Estimate the data flow--------------------------- //-----------------for debug------------------------------------------------- //System.out.println("[xmx = " + xmx + ", xms = " + xms + ", ismb = " + // ismb + ", RN = " + reducer + "]"); //if(xmx != 4000 || ismb != 400 || reducer != 16 || xms != 1) // continue; //if(xmx != 4000 || xms != 1 || ismb != 1000 || reducer != 9) // continue; //--------------------------------------------------------------------------- Configuration conf = new Configuration(); long newSplitSize = splitMB * 1024 * 1024l; conf.set("io.sort.mb", String.valueOf(ismb)); if(xms == 0) conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m"); else conf.set("mapred.child.java.opts", "-Xmx" + xmx + "m" + " -Xms" + xmx + "m"); conf.set("mapred.reduce.tasks", String.valueOf(reducer)); conf.set("split.size", String.valueOf(newSplitSize)); setNewConf(conf); // -------------------------Estimate the data flow------------------------- List<Mapper> eMappers = estimateMappers(); //don't filter the mappers with small split size List<Reducer> eReducers = estimateReducers(eMappers, useRuntimeMaxJvmHeap); String fileName = conf.getConf("mapred.child.java.opts").replaceAll(" ", "") + "-ismb" + ismb + "-RN" + reducer; displayMapperDataResult(eMappers, fileName , outputDir + File.separator + "eDataflow" + splitMB); displayReducerDataResult(eReducers, fileName, outputDir + File.separator + "eDataflow" + splitMB); // -------------------------Estimate the memory cost------------------------- InitialJvmCapacity gcCap = computeInitalJvmCapacity(); if(!gcCap.getError().isEmpty()) { System.err.println(gcCap.getError() + " [xmx = " + xmx + ", xms = " + xms + ", ismb = " + ismb + ", RN = " + reducer + "]"); } else { //filter the estimated mappers with low split size List<MapperEstimatedJvmCost> eMappersMemory = estimateMappersMemory(eMappers, gcCap); List<ReducerEstimatedJvmCost> eReducersMemory = estimateReducersMemory(eReducers, gcCap); displayMapperJvmCostResult(eMappersMemory, gcCap, mJvmWriter); displayReducerJvmCostResult(eReducersMemory, gcCap, rJvmWriter); } } } } } } mJvmWriter.close(); rJvmWriter.close(); }
8
public static void main(String[] args) { // TODO Auto-generated method stub int n = Integer.parseInt(args[0]); //n is between 3 and 1000; int k = Integer.parseInt(args[1]); //k is an integer between 0 and n; int v = Integer.parseInt(args[2]); //v is in {0,1,2,3}. N = n; K = k; // Copy n, k to N, K for the convenience of subsequent retrieval int [] A = new int [n+1]; // The array that holds the data long sum = 0; // The total counts of all possible permutations/combinations long startTime=0, endTime=0; // The start and end time of running the algorithm switch(v){ // Test verbose to determine the output mode /* If v = 0, the program outputs one line with 2 integers: * the number of permutations of k objects out of n distinct objects, * the time taken by the program in milliseconds. * */ case 0: { // Initialize array A with 1...n for(int i = 1; i <= n; i++){ A[i] = i; } A[0] = -1; // Introduce a sentinel A[0], which is strictly less than the largest element in A[1...n]. //visit P(n, k) and get the number of all possible permutations startTime = System.currentTimeMillis(); sum = permutation(A, n, k, v); endTime = System.currentTimeMillis(); break; } /* If v = 1, the program again outputs one line with 2 integers: * the number of permutations of k objects out of n distinct objects, * the time taken by the program in milliseconds. * */ case 1: { // Initialize array A with {0}. When an object is selected, A[i] = 1; otherwise A[i] = 0 for(int i = 1; i <= n; i++){ A[i] = 0; } // visit C(n, k) and get the number of all possible combinations startTime = System.currentTimeMillis(); sum = combination(A, n, k, v); endTime = System.currentTimeMillis(); break; } /* If v = 2, the program should output: * all the actual permutations, one line at a time, * and then the output of v=0. * */ case 2: { // Initialize array A with 1...n for(int i = 1; i <= n; i++){ A[i] = i; } A[0] = -1; // Introduce a sentinel A[0], which is strictly less than the largest element A[n]. //visit P(n, k) and get the number of all possible permutations startTime = System.currentTimeMillis(); sum = permutation(A, n, k, v); endTime = System.currentTimeMillis(); break; } /* If v = 3, the program should output: * all the actual combinations, one line at a time, * and then the output of v=1. * */ case 3: { // Initialize array A with {0}. When an object is selected, A[i] = 1; otherwise A[i] = 0 for(int i = 1; i <= n; i++){ A[i] = 0; } // visit C(n, k) and get the number of all possible combinations startTime = System.currentTimeMillis(); sum = combination(A, n, k, v); endTime = System.currentTimeMillis(); break; } default: break; } // Print the total counts of all possible permutations/combinations and the time taken by the program in milliseconds. System.out.println(sum + " " +(endTime - startTime)); }
8
public static void Command(CommandSender sender) { if(sender.hasPermission("gm.adventure.all")) { for(Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getGameMode() != GameMode.ADVENTURE) { player.setGameMode(GameMode.ADVENTURE); if(sender instanceof Player) { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, (Player) sender, player, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, (Player) sender, player, false, true, false, null); } else { me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Changed Target GameMode").toString(), sender, null, player, true, false, false, null); me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.General.Player Changed Your GameMode").toString(), sender, null, player, false, true, false, null); } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, (Player) sender, player, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.Target Already in GameMode").toString(), sender, null, player, true, false, false, null); } } } else { if(sender instanceof Player) me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, (Player) sender, null, true, false, false, null); else me.Vinceguy1.ChangeGameMode.Functions.Message.Function(me.Vinceguy1.ChangeGameMode.ConfigClass.config.get("Messages.Errors.No Permission").toString(), sender, null, null, true, false, false, null); } }
6
private void create(int[] init, Color bg, String fieldTitle) { setPreferredSize(new Dimension(GUIConstants.DEFAULT_FIELD_WIDTH, FIELDHEIGHT)); setBackground(bg); setBorder(BorderFactory.createTitledBorder(fieldTitle)); setLayout(new VerticalLayout(0, VerticalLayout.CENTER)); setToolTipText(Field.strBorderTooltip); JPanel panel = new JPanel(); panel.setBackground(bg); this.add(panel); final JTextField left = new JTextField(); left.setColumns(NUMBERLENGTH + 1); left.setToolTipText(Field.strBorderTooltip); panel.add(left); final JTextField top = new JTextField(); top.setColumns(NUMBERLENGTH + 1); top.setToolTipText(Field.strBorderTooltip); panel.add(top); final JTextField right = new JTextField(); right.setColumns(NUMBERLENGTH + 1); right.setToolTipText(Field.strBorderTooltip); panel.add(right); final JTextField bottom = new JTextField(); bottom.setColumns(NUMBERLENGTH + 1); bottom.setToolTipText(Field.strBorderTooltip); panel.add(bottom); if (init != null) { left.setText(init[0] + ""); top.setText(init[1] + ""); right.setText(init[2] + ""); bottom.setText(init[3] + ""); } left.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(left, NUMBERLENGTH, false)) { leftFieldOnKeyReleased(left.getText()); } } }); top.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(top, NUMBERLENGTH, false)) { topFieldOnKeyReleased(top.getText()); } } }); right.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(right, NUMBERLENGTH, false)) { rightFieldOnKeyReleased(right.getText()); } } }); bottom.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (controlThicknessInput(bottom, NUMBERLENGTH, false)) { bottomFieldOnKeyReleased(bottom.getText()); } } }); JButton reset = new JButton(super.strReset); reset.setBackground(bg); this.add(reset); reset.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int[] tmp = reset(); if (tmp != null) { left.setText(tmp[0] + ""); top.setText(tmp[1] + ""); right.setText(tmp[2] + ""); bottom.setText(tmp[3] + ""); } else { left.setText(""); top.setText(""); right.setText(""); bottom.setText(""); } } }); }
6
@Override protected void startServerLoop() { Runnable thread = new Runnable(){ @Override public void run() { while(running){ try { Thread.sleep(GAMEINTERVAL); updateServerGame(); } catch (InterruptedException e) { e.printStackTrace(); } } } }; (new Thread(thread)).start(); }
2
@Override MessageExoType getMessageExoType(String arrow) { if (arrow.contains("<")) { return MessageExoType.FROM_RIGHT; } if (arrow.contains(">")) { return MessageExoType.TO_RIGHT; } if (arrow.startsWith("/") || arrow.startsWith("\\")) { return MessageExoType.FROM_RIGHT; } if (arrow.endsWith("\\]") || arrow.endsWith("/]") || arrow.endsWith("\\") || arrow.endsWith("/")) { return MessageExoType.TO_RIGHT; } throw new IllegalArgumentException(arrow); }
8
private static ValuePtr readPtr(CompileInfo ci, String p) { if(p.charAt(0)!='['){ makeDiagnostic(ci, Kind.ERROR, "expect.ptr.start");//$NON-NLS-1$ }else if(p.charAt(p.length()-1)!=']'){ makeDiagnostic(ci, Kind.ERROR, "expect.ptr.end");//$NON-NLS-1$ } List<MiniScriptValue> values = new ArrayList<MiniScriptValue>(); List<Boolean> mul = new ArrayList<Boolean>(); int index = 0; int oldIndex = 1; boolean neg = false; while(true){ oldIndex = index+1; index = indexOf(p, "+*-", oldIndex);//$NON-NLS-1$ if(neg){ oldIndex--; if(index==-1){ ValueNum val = readNum(ci, p.substring(oldIndex, p.length()-1)); val.num = -val.num; values.add(val); mul.add(false); break; }else{ makeDiagnostic(ci, Kind.ERROR, "expect.number.at.end");//$NON-NLS-1$ } }else{ if(index==-1){ MiniScriptValue val = readValueOrReg(ci, p.substring(oldIndex, p.length()-1)); values.add(val); mul.add(false); break; }else{ MiniScriptValue val = readValueOrReg(ci, p.substring(oldIndex, index)); values.add(val); mul.add(p.charAt(index)=='*'); if(val instanceof ValueNum){ makeDiagnostic(ci, Kind.ERROR, "expect.number.at.end");//$NON-NLS-1$ } } } neg = false; neg = p.charAt(index)=='-'; if(neg){ index++; } } return new ValuePtr(values, mul); }
8
public JPanel getLocaleBtnMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.localeBtn; }
1
public static CardStack createFromFile(String fileName) { InputStreamReader inStream; try { inStream = new InputStreamReader(new FileInputStream(fileName), CHARSET); } catch(IOException e) { return null; } BufferedReader bufferedReader = new BufferedReader(inStream); ArrayList<Card> newStack = new ArrayList<Card>(); for(;;) { Card card = Card.createFromFile(bufferedReader); if(card == null) break; newStack.add(card); } try { bufferedReader.close(); inStream.close(); // just in case } catch(IOException e) { /* don't care */ } return new CardStack(newStack); }
4
public int longestValidParentheses_2(String s) { // Note: The Solution object is instantiated only once and is reused by // each test case. Stack<Integer> stack = new Stack<Integer>(); int max = 0; int count = 0; for(int i = 0; i < s.length(); ++i){ if(s.charAt(i) == '('){ stack.push(count); count = 0; }else if(stack.size() > 0){ count += 2 + stack.pop(); max = Math.max(max, count); }else { count = 0; } } return max; }
3
@Override public boolean evaluate(T2 obj) throws Exception { return true; }
0
private boolean xIntersects(Vec3D var1) { return var1 == null?false:var1.y >= this.y0 && var1.y <= this.y1 && var1.z >= this.z0 && var1.z <= this.z1; }
4
public void update(int delta) { if(!entityAddList.isEmpty()) { for(Entity ent : entityAddList) { entityList.add(ent); } entityAddList.clear(); } if(!entityRemoveList.isEmpty()) { for(Entity ent : entityRemoveList) { if(ent instanceof EntityPlayer) this.lose(); entityList.remove(ent); } entityRemoveList.clear(); } for(Entity ent : entityList) { ent.update(delta); } for(Decoration d : decorList) { d.update(delta); } render.updateEntityRenderList(this); }
7
@BeforeClass public static void setUpClass() { }
0
@Override public String perform(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String status = "Client not added, did you fill all required field?..."; //** 1. Retrieve the Form Input (Name-Value Pairs) from the HTTP Request *** String fName = request.getParameter("firstName"); String lName = request.getParameter("lastName"); String phone = request.getParameter("phone"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String address = (address1+ " "+address2); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String cDate = new SimpleDateFormat("MM-dd-yyyy").format(new Date()); //** 2. Instantiate a User Bean and Load the Info from the Form ****** if(fName==null || lName==null || phone==null || address==null || city==null ||state==null ||zip==null){ session.setAttribute("status", status); return "User_Add"; } else{ User client = new User(); client.setFirst_Name(fName); client.setLast_Name(lName); client.setPhone(phone); client.setAddress(address.trim()); client.setCity(city); client.setState(state); client.setZIP(zip); client.setDate(cDate); //** 3. Add the Bean to the Database **** int results = UserDB.addUser(client); if(results > 0) { status = "Successful Registration!"; session.setAttribute("status", status); User clientbybean = UserDB.getUserByBean(client); session.setAttribute("client", clientbybean); return "Credential_Add"; }} return "User_Add"; }
8
public boolean ModificarPunto(Punto p){ if (p!=null) { cx.Modificar(p); return true; }else { return false; } }
1
public DungeonFloor() { Random random = new Random(1000); int w = 6; int h = 8; double ws = 1.0 / (w); double hs = 1.0 / (h); for (int x = 0; x < w; x++) { for (int z = 0; z < w; z++) { for (int y = 0; y < h; y++) { double xx = x * ws + (random.nextFloat() - 0.5) * 0.03; double yy = y * hs + (random.nextFloat() - 0.5) * 0.03; double zz = z * ws + (random.nextFloat() - 0.5) * 0.03; sprites.add(new Sprite(xx, yy, zz, Art.brick)); if (y == 0) y = h - 2; } } } }
4
public static String getFlightModeName(eMode mode) { if (mode == eMode.NORMAL_MODE) return "NORMAL"; if (mode == eMode.MUHA_MODE) return "MUHA"; if (mode == eMode.TAG_MODE) return "TAG"; return "UNKNOWN"; }
3
public static boolean onSegment(Point2d p1, Point2d p2, Point2d Q){ if(Q.sub(p1).crossProduct(p2.sub(p1))== 0 && Math.min(p1.x, p2.x)<=Q.x && Math.max(p1.x, p2.x)>=Q.x && Math.min(p1.y, p2.y)<=Q.y && Math.max(p1.y, p2.y)>=Q.y) return true; return false; }
5
public void ShowAsBit() { System.out.print("["); for (int i = 0; i < _ListaDeObjetos.size(); i++) { if(_ListaDeObjetos.get(i) != null) { System.out.print("1"); if(i + 1 < _ListaDeObjetos.size()) { System.out.print(", "); } } else { if(i + 1 < _ListaDeObjetos.size()) { System.out.print("0, "); } else { System.out.print("0"); } } } System.out.print("]"); }
4
public static void writeToCSV(String fileName, List<HashMap> dataMaps) { try (FileWriter writer = new FileWriter(fileName)) { System.out.println("Writing to file " + fileName); writer.append("_type,_id,name,type,latitude,longitude\n"); String typeS; String id; String name; String type; String longitude; String latitude; for (HashMap map : dataMaps) { typeS = map.get("_type") != null ? (String) map.get("_type") : null; id = map.get("_id") != null ? map.get("_id").toString() : null; name = map.get("name") != null ? (String) map.get("name") : null; type = map.get("type") != null ? (String) map.get("type") : null; longitude = null; latitude = null; if (map.get("geo_position") != null) { Map geo = (HashMap<String, Object>) map.get("geo_position"); latitude = geo.get("latitude").toString(); longitude = geo.get("longitude").toString(); } writer.append(typeS).append(","); writer.append(id).append(","); writer.append(name).append(","); writer.append(type).append(","); writer.append(latitude).append(","); writer.append(longitude).append("\n"); } } catch (IOException e) { System.out.println("Exception parsing data"); e.printStackTrace(); } }
7
private int getMaxSizeY(final JComponent[] components) { int max = 0; for (final JComponent component : components) { final Dimension dimension = component.getMaximumSize(); if (dimension != null) { if ((dimension.height > max) && (dimension.height != Integer.MAX_VALUE)) { max = dimension.height; } } } return max; }
4
public boolean isSet(String path) { Configuration root = getRoot(); if (root == null) { return false; } if (root.options().copyDefaults()) { return contains(path); } return get(path, null) != null; }
2
private Boolean load_last() { // We initialize pointer to root of document try { settings = document.getRootElement(); List listsections = settings.getChildren(); if (listsections != null){ Iterator i = listsections.iterator(); while(i.hasNext()){ Element current = (Element)i.next(); String currname = current.getName(); //System.out.println("Trouvé : "+currname); if(currname.equals("last")) { last_section = current; } else if(currname.equals("readers")) { readers = current; } else if(currname.equals("users")) { users = current; } } } if(last_section != null) { //Point elements Path, etc... XML_Path = last_section.getChild("XML_Path"); GGC_Path = last_section.getChild("GGC_Path"); Start_Date = last_section.getChild("Start_Date"); End_Date = last_section.getChild("End_Date"); last_meter = last_section.getChild("Meter"); lang = last_section.getChild("lang").getValue(); } else { System.out.println("XML Document 'settings.xml' 'last' section not found"); return false; } } catch(Exception e){ System.out.println("'settings.xml' does'nt have expected structure !"); return false; } return true; }
7
public void crackShotEventListener(WeaponDamageEntityEvent e){ if (e.isCancelled() || (e.getDamage() == 0)){return;} Player dmgr = e.getPlayer(); if(e.getVictim() instanceof Player){ Player tagged = (Player) e.getVictim(); if(plugin.entityListener.disallowedWorld(tagged.getWorld().getName())){return;} //If the damaged player is an npc do nothing if ((dmgr instanceof Player) && plugin.settings.playerTag()){ Player damagerPlayer = (Player) dmgr; if(damagerPlayer != tagged && damagerPlayer != null){ plugin.entityListener.onPlayerDamageByPlayer(damagerPlayer,tagged); } } } }
8
@Override public void update(){ super.update(); if(prevX != this.getX() || prevY != this.getY() || prevZ != this.getZ() || prevAngle != this.getAngle()){ this.updateRenderPosition(); this.syncPreviousPosition(); } }
4
private void isiIC() { int count = 0; this.copyPapan[9][2]="C"; this.copyPapan[2][7]="C"; this.copyPapan[3][9]="C"; count=3; for (int i = 0; i < this.banyakIC; i++) { Random randrow = new Random(); Random randcol = new Random(); int row = randrow.nextInt(10); int col = randcol.nextInt(10); if (this.copyPapan[row][col].equals("O")) { if (row!=1 &&col!=3) { this.copyPapan[row][col] = "C"; System.out.println(row+"=R "+col+"=C"); count++; } } } this.banyakIC = count; }
4
private static int inputCustomerChoice() { String choice = null; if (scanner.hasNext()) { choice = scanner.nextLine(); } isValidChoice(choice); return Integer.parseInt(choice); }
1
public void extractFeature(List<Article> artList, boolean isTraining) { final int SENT_LEN_MAX_CUTOFF = 15; final int SENT_LEN_MIN_CUTTOFF = 3; int sentCount = 0; for (Article art : artList) { if (sentCount >= 100) { return; } if (art.getLabel().equals("1")) { continue; } for (String sent : art.getSentences()) { sent = sent.replaceAll("<[/]?s>", "").trim().toLowerCase(); Annotation document = new Annotation(sent); pipeline.annotate(document); CoreMap sentence = document.get(SentencesAnnotation.class).get( 0); if (sentence.get(TokensAnnotation.class).size() > SENT_LEN_MAX_CUTOFF || sentence.get(TokensAnnotation.class).size() < SENT_LEN_MIN_CUTTOFF) { continue; } sentCount++; for (CoreLabel token : sentence.get(TokensAnnotation.class)) { System.out .print(token.get(TextAnnotation.class) + "_" + MiscUtil.pad(token .get(PartOfSpeechAnnotation.class), 5)); } System.out.println(); } } }
7
Class323(AbstractToolkit var_ha, int i, boolean bool, Component component) { aBoolean4037 = false; aClass105Array4042 = new RasterToolkit[256]; anIntArray4039 = new int[256]; Font font = new Font("Helvetica", bool ? 1 : 0, i); FontMetrics fontmetrics = component.getFontMetrics(font); for (int i_19_ = 0; i_19_ < anInt4038; i_19_++) method2559 (var_ha, font, fontmetrics, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"\u00a3$%^&*()-_=+[{]};:'@#~,<.>/?\\| \u00c4\u00cb\u00cf\u00d6\u00dc\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00df\u00c1\u00c0\u00c9\u00c8\u00cd\u00cc\u00d3\u00d2\u00da\u00d9\u00e1\u00e0\u00e9\u00e8\u00ed\u00ec\u00f3\u00f2\u00fa\u00f9\u00c2\u00ca\u00ce\u00d4\u00db\u00e2\u00ea\u00ee\u00f4\u00fb\u00c6\u00e6\u00e3\u00c3\u00f5\u00d5\u00e7\u00c7" .charAt(i_19_), i_19_, false); if (bool && aBoolean4037) { aBoolean4037 = false; font = new Font("Helvetica", 0, i); fontmetrics = component.getFontMetrics(font); for (int i_20_ = 0; i_20_ < anInt4038; i_20_++) method2559 (var_ha, font, fontmetrics, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"\u00a3$%^&*()-_=+[{]};:'@#~,<.>/?\\| \u00c4\u00cb\u00cf\u00d6\u00dc\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00df\u00c1\u00c0\u00c9\u00c8\u00cd\u00cc\u00d3\u00d2\u00da\u00d9\u00e1\u00e0\u00e9\u00e8\u00ed\u00ec\u00f3\u00f2\u00fa\u00f9\u00c2\u00ca\u00ce\u00d4\u00db\u00e2\u00ea\u00ee\u00f4\u00fb\u00c6\u00e6\u00e3\u00c3\u00f5\u00d5\u00e7\u00c7" .charAt(i_20_), i_20_, false); if (!aBoolean4037) { aBoolean4037 = false; for (int i_21_ = 0; i_21_ < anInt4038; i_21_++) method2559 (var_ha, font, fontmetrics, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"\u00a3$%^&*()-_=+[{]};:'@#~,<.>/?\\| \u00c4\u00cb\u00cf\u00d6\u00dc\u00e4\u00eb\u00ef\u00f6\u00fc\u00ff\u00df\u00c1\u00c0\u00c9\u00c8\u00cd\u00cc\u00d3\u00d2\u00da\u00d9\u00e1\u00e0\u00e9\u00e8\u00ed\u00ec\u00f3\u00f2\u00fa\u00f9\u00c2\u00ca\u00ce\u00d4\u00db\u00e2\u00ea\u00ee\u00f4\u00fb\u00c6\u00e6\u00e3\u00c3\u00f5\u00d5\u00e7\u00c7" .charAt(i_21_), i_21_, true); } } }
7
public boolean getTalkable(Player other) { if ((other.getCurrentY()+1) == getCurrentY()) { if ((other.getCurrentX()) == getCurrentX()) { return true; } } if ((other.getCurrentY()-1) == getCurrentY()) { if ((other.getCurrentX()) == getCurrentX()) { return true; } } if ((other.getCurrentX()+1) == getCurrentX()) { if ((other.getCurrentY()) == getCurrentY()) { return true; } } if ((other.getCurrentX()-1) == getCurrentX()) { if ((other.getCurrentY()) == getCurrentY()) { return true; } } return false; }
8
public String endSection(Marker marker) { StringBuilder sb = new StringBuilder(); // Add header? if (showHeader && (sectionNum == 0)) { String header = toStringHeader(); if (!header.isEmpty()) { sb.append(header); sb.append("\n"); } } // Add current line sb.append(toString()); sectionNum++; changeEffects.clear(); return supressOutput ? null : sb.toString(); }
4
@Override public int print(Graphics pg, PageFormat pageFormat, int pageIndex) throws PrinterException { pg.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY()); int wPage = 0; int hPage = 0; if (pageFormat.getOrientation() == PageFormat.LANDSCAPE) { wPage = (int)pageFormat.getImageableWidth(); hPage = (int)pageFormat.getImageableHeight(); } else { wPage = (int)pageFormat.getImageableWidth(); wPage += wPage/2; hPage = (int)pageFormat.getImageableHeight(); pg.setClip(0,0,wPage,hPage); } int y = 20; pg.setFont(new java.awt.Font("Tahoma", Font.BOLD, 15)); pg.setColor(Color.black); FontMetrics fm = pg.getFontMetrics(); y += fm.getAscent(); Graphics2D pg2 = (Graphics2D) pg; FontRenderContext frc = pg2.getFontRenderContext(); StringBuffer sb = new StringBuffer(WindMill.propertyFile.getProperty("SHIP")); sb.append(" alarm data"); String bigTitle = sb.toString(); Rectangle2D bounds = pg2.getFont().getStringBounds(bigTitle, frc); int tWidth = (int) bounds.getWidth(); pg.drawString(bigTitle, wPage/3 -tWidth/2, y); y += 20; // space between title and table headers Font headerFont = new Font("Tahoma", Font.PLAIN, 11); pg.setFont(headerFont); fm = pg.getFontMetrics(); TableColumnModel colModel = table.getColumnModel(); int nColumns = colModel.getColumnCount(); int x[] = new int[nColumns]; x[0] = 50; int h = fm.getAscent(); y += h; // add ascent of header font because of baseline // positioning (see figure 2.10) int nRow, nCol; for (nCol=0; nCol<nColumns; nCol++) { TableColumn tk = colModel.getColumn(nCol); int width = 100;//tk.getWidth(); if (x[nCol] + width > wPage) { nColumns = nCol; break; } if (nCol+1<nColumns) x[nCol+1] = x[nCol] + width; String title = (String)tk.getIdentifier(); pg.drawString(title, x[nCol], y); } pg.setFont(new java.awt.Font("Tahoma", Font.PLAIN, 8)); fm = pg.getFontMetrics(); int header = y; h = fm.getHeight(); int rowH = Math.max((int)(h*1.5), 10); int rowPerPage = (hPage-header-3*rowH)/rowH; // 2*rowH is one blank line plus footer plus one blank int m_maxNumPage = Math.max((int)Math.ceil(table.getRowCount()/ (double)rowPerPage), 1); if (pageIndex >= m_maxNumPage) return NO_SUCH_PAGE; int iniRow = pageIndex*rowPerPage; int endRow = Math.min(table.getRowCount(), iniRow+rowPerPage); for (nRow=iniRow; nRow<endRow; nRow++) { //y += h; y+=rowH; for (nCol=0; nCol<nColumns; nCol++) { int col = table.getColumnModel().getColumn(nCol).getModelIndex(); Object obj = table.getValueAt(nRow, col); String str = obj.toString(); pg.setColor(Color.black); pg.drawString(str, x[nCol], y); } } pg.drawString("Page "+ (pageIndex+1), 300, hPage - rowH); //System.gc(); return PAGE_EXISTS; }
7
private static String generateQuery(String query, Object... parameters) { assertThatParamsCanBeBound(query, parameters); int paramIndex = 0; while (query.contains(TOKEN)) { Object parameter = parameters[paramIndex++]; query = bindParamIntoQuery(query, parameter); } return query; }
1
public void dealerWon() { if (dealerHand.getHandRanks().contains("Ace") && (dealerHand.getHandRanks().contains("Ten") || dealerHand .getHandRanks().contains("Jack")) || dealerHand.getHandRanks().contains("Queen") || dealerHand.getHandRanks().contains("King")) { System.out.println("Dealer got BlackJack!"); dealerHand.clearHand(); player.playerLost(); handEnd = true; } else { player.playerLost(); handEnd = true; } }
5
private Token buildWordToken(String word){ TokenType tt = null; switch(word.toUpperCase()) { case "IF": tt = TokenType.IF_DECL; break; case "ELSE": tt = TokenType.ELSE_DECL; break; case "WHILE": tt = TokenType.WHILE_DECL; break; case "INT": tt = TokenType.INT_TYPE; break; case "CHAR": tt = TokenType.CHAR_TYPE; break; case "BOOL": tt = TokenType.BOOL_TYPE; break; case "TRUE": tt = TokenType.BOOL; break; case "FALSE": tt = TokenType.BOOL; break; case "PRINT": tt = TokenType.PRINT; break; default: tt = TokenType.ID; word = buildIdName(word); } return(new Token(tt, word, 0, st.lineno())); }
9
private void putRequiredOption( Collection<String> precedentSynonyms, OptionSpec<?> required, Map<Collection<String>, Set<OptionSpec<?>>> target ) { for ( String each : precedentSynonyms ) { AbstractOptionSpec<?> spec = specFor( each ); if ( spec == null ) throw new UnconfiguredOptionException( precedentSynonyms ); } Set<OptionSpec<?>> associated = target.get( precedentSynonyms ); if ( associated == null ) { associated = new HashSet<OptionSpec<?>>(); target.put( precedentSynonyms, associated ); } associated.add( required ); }
8
public boolean inside(MultiColor c) { for (int i = 0; i < min.length; i++) { if (c.data[i] == -1) continue; if (c.data[i] < min[i]) return false; if (c.data[i] > max[i]) return false; } return true; }
4
public int calculateLowestCost() { locked = true; // System.out.println(name + " is locked"); int lowestCostStorePrice; int lowestFusionCost; if (storePricesList.size() > 0) { lowestCostStorePrice = getLowestStorePrice(); if (lowestCostStorePrice < lowestItemCost) { lowestItemCost = lowestCostStorePrice; bestBuyInStore = true; } } if (fusionList.size() > 0) { lowestFusionCost = getLowestFusionCost(); if (lowestFusionCost < lowestItemCost) { lowestItemCost = lowestFusionCost; bestBuyInStore = false; } } // locked = false; // System.out.println("new lowest item cost (~" + lowestItemCost + ") for " + name ); // System.out.println(name + " is unlocked"); return lowestItemCost; }
4
void draw( ChartGraphics g, int[] xValues, double[] stackValues, int lastPlotType ) throws RrdException { g.setColor( color ); g.setStroke( lineWidth != 1 ? new BasicStroke(lineWidth) : DEF_LINE_STROKE ); Graphics2D gd = g.getGraphics(); int len = values.length; double value; int ax = 0, ay = 0, nx = 0, ny = 0; for ( int i = 0; i < len; i++ ) { value = values[i]; nx = xValues[i]; if ( stacked ) value += stackValues[i]; ny = g.getY( value ); if ( visible && nx != 0 && ay != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) gd.drawLine(ax, -ay, nx, -ny); stackValues[i] = value; ax = nx; ay = ny; } g.setStroke( STROKE ); }
7
private void setBalance(BigInteger balance) throws IllegalArgumentException { if (! this.canHaveAsBalance(balance)) throw new IllegalArgumentException(); this.balance = balance; }
1
public State getStateByValue(String value){ for(State state : states){ if(state.mathByValue(value)) return state; } return null; }
2
@Override public void documentRemoved(DocumentRepositoryEvent e) {}
0
private void processScalar() throws IOException { ScalarEvent ev = (ScalarEvent) event; if (analysis == null) { analysis = analyzeScalar(ev.getValue()); } if (style == null) { style = chooseScalarStyle(); } style = options.calculateScalarStyle(analysis, ScalarStyle.createStyle(style)).getChar(); boolean split = !simpleKeyContext; if (style == null) { writePlain(analysis.scalar, split); } else { switch (style) { case '"': writeDoubleQuoted(analysis.scalar, split); break; case '\'': writeSingleQuoted(analysis.scalar, split); break; case '>': writeFolded(analysis.scalar); break; case '|': writeLiteral(analysis.scalar); break; } } analysis = null; style = null; }
7
public void stop() { if (this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } if (this.runningState == STATE_RUNNING) { this.stopTime = System.currentTimeMillis(); } this.runningState = STATE_STOPPED; }
3
public int get(byte[] data, int offset, int len) { if (len == 0) return 0; int dataLen = 0; synchronized (signal) { // see if we have enough data while (getAvailable() <= 0) { if (eof) return (-1); try { signal.wait(1000); } catch (Exception e) { System.out.println("Get.Signal.wait:" + e); } } len = Math.min(len, getAvailable()); // copy data if (getHere < putHere) { int l = Math.min(len, putHere - getHere); System.arraycopy(buffer, getHere, data, offset, l); getHere += l; if (getHere >= bufferSize) getHere = 0; dataLen = l; } else { int l = Math.min(len, bufferSize - getHere); System.arraycopy(buffer, getHere, data, offset, l); getHere += l; if (getHere >= bufferSize) getHere = 0; dataLen = l; if (len > l) dataLen += get(data, offset + l, len - l); } signal.notify(); } return dataLen; }
8
private void onClear(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onClear if (spawnMenuItem.isEnabled()) { toggler.setState(false); game.reset(); repaint(); } }//GEN-LAST:event_onClear
1
@SuppressWarnings("unchecked") @Override public void init() throws Exception { endpoint.setName(getName()); endpoint.setHandler(cHandler); // Verify the validity of the configured socket factory try { if (isSSLEnabled()) { sslImplementation = (SSLImplementation<NioChannel>) SSLImplementation .getInstance(NioJSSEImplementation.class.getName()); socketFactory = sslImplementation.getServerSocketChannelFactory(); endpoint.setServerSocketChannelFactory(socketFactory); } } catch (Exception ex) { log.error(sm.getString("http11protocol.socketfactory.initerror"), ex); throw ex; } if (socketFactory != null) { Iterator<String> attE = attributes.keySet().iterator(); while (attE.hasNext()) { String key = attE.next(); Object v = attributes.get(key); socketFactory.setAttribute(key, v); } } int maxThreads = 0; // Setting the max thread number String property = System.getProperty(Constants.MAX_THREAD_NAME); if (property != null) { try { maxThreads = Integer.valueOf(property); log.info("Configure max thread number : " + maxThreads); } catch (Exception e) { log.warn("Invalid MAX-THREAD number, using the default value " + maxThreads); } } this.endpoint.setMaxThreads(maxThreads); // Setting the max connection number int maxConnections = 2 * maxThreads; property = System.getProperty(Constants.MAX_CONNECTIONS_NAME); if (property != null) { try { maxConnections = Integer.valueOf(property); log.info("Configure max connection number : " + maxConnections); } catch (Exception e) { log.warn("Invalid MAX-CONNECTION number, using the default value " + maxConnections); } } this.endpoint.setMaxConnections(maxConnections); try { endpoint.setKeepAliveTimeout(this.timeout); endpoint.init(); } catch (Exception ex) { log.error(sm.getString("http11protocol.endpoint.initerror"), ex); throw ex; } // log.info(sm.getString("http11protocol.init", getName())); }
9
@SuppressWarnings("deprecation") @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); // Player only moved to look around but didn't walk if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockY() == event.getTo().getBlockY() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) return; if (plugin.getTeleportHandler().isReady(player.getName())) { if (player.hasPermission("scrollteleportation.walkbypass")) return; String scroll = plugin.getMainConfig().getScroll( plugin.fixName(player.getItemInHand().getItemMeta() .getDisplayName())); if (!plugin.getMainConfig().doCancelOnMove(scroll)) return; // Player has moved so teleportation is cancelled plugin.getTeleportHandler().setReady(player.getName(), false); if (plugin.getTeleportHandler().taskID.get(player.getName()) != null) { // Cancel teleport task plugin.getServer().getScheduler().cancelTask(plugin.getTeleportHandler().taskID.get(player.getName())); // Set taskID null plugin.getTeleportHandler().taskID.put(player.getName(), null); } // Inform player player.sendMessage(ChatColor.RED + "Teleportation is cancelled because you moved."); } }
7
public void toggleEditingMode() { if(!Main.editingMode) { mySea.renderEditingShip = false; theirSea.renderEditingShip = false; } else { if(myTurnEditing) mySea.renderEditingShip = true; else theirSea.renderEditingShip = true; } if(!Main.editingMode) { mySea.reset(); theirSea.reset(); } else { mySea.clearShips(); theirSea.clearShips(); } }
3
@Override public int hashCode() { int prime = 31; int prime2 = 47; int tId = this.projectId; int tFCount = this.recordCount; int tYCoord = this.firstYCoord; int tFHeight = this.fieldHeight; int tTitle; if (tId == 0) { tId = prime; } if (tFCount < 0) { tFCount = prime2; } if (tYCoord < 0) { tYCoord = prime ^ prime2; } if (tFHeight < 0) { tFHeight = prime * prime2; } if (this.title == null) { tTitle = prime; } else { tTitle = this.title.length(); } int hash = tId * prime2; hash *= tFCount ^ prime; hash += tYCoord * prime2; hash *= tFHeight ^ prime; hash += tTitle * prime2; return hash; }
5
public double[] rawPersonVariances(){ if(!this.dataPreprocessed)this.preprocessData(); if(!this.variancesCalculated)this.meansAndVariances(); return this.rawPersonVariances; }
2
public static double rayleighInverseCDF(double beta, double prob) { if (prob < 0.0 || prob > 1.0) throw new IllegalArgumentException("Entered cdf value, " + prob + ", must lie between 0 and 1 inclusive"); double icdf = 0.0D; if (prob == 0.0) { icdf = 0.0; } else { if (prob == 1.0) { icdf = Double.POSITIVE_INFINITY; } else { icdf = beta * (Math.sqrt(-Math.log(1.0 - prob))); } } return icdf; }
4
@Override public boolean isSameElementAs(Element<?> element) { ClassElement other = element.adaptTo(ClassElement.class); if (other == null) { return false; } return getClassName().equals(other.getClassName()); }
2
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String login = request.getParameter("login"); String password = request.getParameter("password"); String action = request.getParameter("action") == null ? "" : request.getParameter("action"); // On récupere la session HttpSession session = request.getSession(); if (action.equals("deco")) { session.setAttribute("isLoginOk", false); request.setAttribute("message", "vous avez bien été déconnecté."); } else if (login != null && password != null) { if (gestionnaireUtilisateurs.isLoginCorrect(login, password)) { session.setAttribute("isLoginOk", true); request.setAttribute("message", "Bienvenue chez vous " + login + " !"); } else { request.setAttribute("messageErreur", "Login ou mot de passe incorrect. Try again."); } } String forwardTo = "accueil.jsp"; RequestDispatcher dp = request.getRequestDispatcher(forwardTo); dp.forward(request, response); }
5
private void comparePDFHolder(PDFHolder pdfHolder1, PDFHolder pdfHolder2) { for (PDFPageHolder pdfPageHolder1 : pdfHolder1.getPageHolders()) { // get the same page from the other pdf document PDFPageHolder pdfPageHolder2 = pdfHolder2.getPageHolder(pdfPageHolder1.getPageNumber()); if (pdfPageHolder2 == null) { diff.log(pdfInfoHolder.getFilename()+": page " + pdfPageHolder1.getPageNumber() + " missing in other pdf"); return; } // run thru all structure elements for this page for (PDFEntryHolder pdfEntryHolder1 : pdfPageHolder1.getElements()) { // try to find the same element at the same page of the other pdf PDFEntryHolder pdfEntryHolder2 = findEntryHolder(pdfEntryHolder1, pdfPageHolder2); // no valid element found, assume difference if(pdfEntryHolder2 == null) { pdfEntryHolder1.setDifferent(true); DecimalFormat df = new DecimalFormat( "####.###" ); if(pdfEntryHolder1 instanceof PDFTextHolder) { PDFTextHolder th = (PDFTextHolder)pdfEntryHolder1; diff.log(pdfInfoHolder.getFilename()+": Could not find smiliar text \""+th.getText()+"\" on page " + (pdfPageHolder1.getPageNumber()+1) + " at position " + df.format(th.getX())+" | " + df.format(th.getY()) + " with size " + df.format(th.getWidth()) + " width and " + df.format(th.getHeight()) + " height"); } else { diff.log(pdfInfoHolder.getFilename()+": Could not find smiliar image on page " + (pdfPageHolder1.getPageNumber()+1) + " at position " + df.format(pdfEntryHolder1.getX())+" | " + df.format(pdfEntryHolder1.getY()) + " with size " + df.format(pdfEntryHolder1.getWidth()) + " width and " + df.format(pdfEntryHolder1.getHeight()) + " height"); } } } } }
5
public int raw_seek(int pos) { if (!seekable) { return (-1); // don't dump machine if we can't seek } if (pos < 0 || pos > offsets[links]) { //goto seek_error; pcm_offset = -1; decode_clear(); return -1; } // clear out decoding machine state pcm_offset = -1; decode_clear(); // seek seek_helper(pos); // we need to make sure the pcm_offset is set. We use the // _fetch_packet helper to process one packet with readp set, then // call it until it returns '0' with readp not set (the last packet // from a page has the 'granulepos' field set, and that's how the // helper updates the offset switch (process_packet(1)) { case 0: // oh, eof. There are no packets remaining. Set the pcm offset to // the end of file pcm_offset = pcm_total(-1); return (0); case -1: // error! missing data or invalid bitstream structure //goto seek_error; pcm_offset = -1; decode_clear(); return -1; default: // all OK break; } while (true) { switch (process_packet(0)) { case 0: // the offset is set. If it's a bogus bitstream with no offset // information, it's not but that's not our fault. We still run // gracefully, we're just missing the offset return (0); case -1: // error! missing data or invalid bitstream structure //goto seek_error; pcm_offset = -1; decode_clear(); return -1; default: // continue processing packets break; } } // seek_error: // dump the machine so we're in a known state //pcm_offset=-1; //decode_clear(); //return -1; }
8
private final void nullifyVideoFileTempData() { synchronized (this.videoFileTempLock) { if (this.videoFileTempGenerator != null) { this.videoFileTempGenerator.cancel(); this.videoFileTempIsGenerating = false; } if (this.videoFileTemp != null) { this.videoFileTemp.delete(); this.videoFileTemp = null; } for (int i = 0; i < this.videoPreviewTempScreenshotGenerators.length; ++i) { if (this.videoPreviewTempScreenshotGenerators[i] != null) { this.videoPreviewTempScreenshotGenerators[i].cancel(); } } for (int i = 0; i < this.videoPreviewFilesTemp.length; ++i) { if (this.videoPreviewFilesTemp[i] != null) { this.videoPreviewFilesTemp[i].delete(); this.videoPreviewFilesTemp[i] = null; } } for (int i = 0; i < this.videoPreviewTempImages.length; ++i) { this.videoPreviewTempImages[i] = null; } this.videoFileTempMightNeedReEncoding = false; } this.stopEncoding(); this.clearMuxFile(); }
7
public Behaviour jobFor(Actor actor) { final Repairs b = Repairs.getNextRepairFor(actor, Plan.CASUAL) ; if (b != null) { final float priority = b.priorityFor(actor) ; if (priority * Planet.dayValue(world) >= Plan.ROUTINE) { return b ; } } if ((! structure.intact()) || (! personnel.onShift(actor))) return null ; final Choice choice = new Choice(actor) ; if (b != null) choice.add(b) ; final Service services[] = services() ; final Delivery d = Deliveries.nextCollectionFor( actor, this, services, 10, null, world ) ; choice.add(d) ; return choice.pickMostUrgent() ; }
5
public static Stella_Object accessBinaryValue(Stella_Object self, Surrogate relation) { { MemoizationTable memoTable000 = null; Cons memoizedEntry000 = null; Stella_Object memoizedValue000 = null; if (Stella.$MEMOIZATION_ENABLEDp$) { memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ACCESS_BINARY_VALUE_MEMO_TABLE_000.surrogateValue)); if (memoTable000 == null) { Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_ACCESS_BINARY_VALUE_MEMO_TABLE_000, "(:MAX-VALUES 1000 :TIMESTAMPS (:KB-UPDATE))"); memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_ACCESS_BINARY_VALUE_MEMO_TABLE_000.surrogateValue)); } memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), self, relation, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, 6); memoizedValue000 = memoizedEntry000.value; } if (memoizedValue000 != null) { if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) { memoizedValue000 = null; } } else { memoizedValue000 = Logic.helpMemoizeAccessBinaryValue(self, relation); if (Stella.$MEMOIZATION_ENABLEDp$) { memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000); } } { Stella_Object value000 = ((Stella_Object)(memoizedValue000)); return (value000); } } }
6
public CommandNode parseScript( String script ) { File f = null; FileInputStream fis = null; InputStreamReader isr = null; BufferedReader reader = null; String line = null; int flag = 0; Stack< CommandNode > stack = new Stack< CommandNode >(); CommandNode current = null; CommandNode back = null; try { f = new File( script ); fis = new FileInputStream( f ); isr = new InputStreamReader( fis, "UTF-8" ); reader = new BufferedReader( isr ); while ( (line = reader.readLine()) != null ) { line = line.trim(); String start = line.substring( 0, line.indexOf( " " ) ); if ( start.compareToIgnoreCase( "IF" ) == 0 ) { line = line.substring( line.indexOf( " " ) + 1 ); flag = 1; back = generateNode(line); stack.push( back ); } if ( start.compareToIgnoreCase( "ELSE" ) == 0 ) { line = line.substring( line.indexOf( " " ) + 1 ); flag = 2; } if ( start.compareToIgnoreCase( "WHILE" ) == 0 ) { line = line.substring( line.indexOf( " " ) + 1 ); flag = 3; } if ( start.compareToIgnoreCase( "END" ) == 0 ) { line = line.substring( line.indexOf( " " ) + 1 ); flag = 4; } if ( current == null ) { current = generateNode( line ); } else { current.setNext( "default", generateNode( line ) ); current = current.getNext( "default" ); } } reader.close(); } catch ( FileNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch ( UnsupportedEncodingException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch ( IOException e ) { parseLog.logToConsole( "", LogCollector.ERROR ); parseLog.logToConsole( e.getMessage(), LogCollector.ERROR ); } return head; }
9
public void setjComboBoxPraticien(JComboBox jComboBoxPraticien) { this.jComboBoxPracticien = jComboBoxPraticien; }
0
public void showLoginStats(CommandSender sender, ListType type, String since, int page, int itemsPerPage) { List<LoginEntry> rawList = new ArrayList<LoginEntry>(); ListPage<LoginEntry> pList = new ListPage<LoginEntry>(); int nPages = 0; switch (type) { case NEW: rawList = plugin.sqlDb.readLogins(); pList = helper.paginate(rawList, page, itemsPerPage); nPages = helper.nPages(rawList.size(), itemsPerPage); sender.sendMessage("[Statistics] Logins " + ChatColor.YELLOW + "(Page " + pList.getPage() + "/" + nPages + ")"); break; case NEWP: rawList = plugin.sqlDb.readNewestPlayers(); pList = helper.paginate(rawList, page, itemsPerPage); nPages = helper.nPages(rawList.size(), itemsPerPage); sender.sendMessage("[Statistics] Players " + ChatColor.YELLOW + "(Page " + pList.getPage() + "/" + nPages + ")"); break; case SINCE: rawList = plugin.sqlDb.readLoginsSince(since); pList = helper.paginate(rawList, page, itemsPerPage); nPages = helper.nPages(rawList.size(), itemsPerPage); sender.sendMessage("[Statistics] Logins since " + since + ChatColor.YELLOW + " (Page " + pList.getPage() + "/" + nPages + ")"); break; } for (LoginEntry e : pList.getList()) { showLoginEntry(sender, e); } }
4
public Tank call(){ Tank tank = null; try { // tank = (Tank)ois.readObject(); String recvBuf = in.readLine(); tank = Oz.getTank(recvBuf); } catch (IOException e) { e.printStackTrace(); } return tank; }
1
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Experiment start:"); WriteFile wf = new WriteFile(new File("experimentFloydWarshall.txt")); WriteFile wf2 = new WriteFile(new File("experimentFloydWarshall2.txt")); for (int i = 10; i < 800; i++) { int N = i; System.out.print("Size: " + i); Double[][] firstD = util.Random.randCostArray(N); Double[][] D = null; Double[][] P = new Double[N][N]; StopWatch sw = new StopWatch(); StopWatch sw2 = new StopWatch(); sw.start(); D = FloydWarshall.shortestpath(firstD, P, sw2); sw.stop(); System.out.println(" time: " + sw.getTime() + " ms"); String buffer = i + " " + sw.getTime() + "\n"; String buffer2 = i + " " + sw2.getTime() + "\n"; wf.writeString(buffer); wf2.writeString(buffer2); } }
1
public static boolean analysisNSMXMJ(AnalysisOutput o, List<AnalysisOutput> candidates) throws MorphException { int idxVbSfix = VerbUtil.endsWithVerbSuffix(o.getStem()); if(idxVbSfix==-1) return false; o.setVsfx(o.getStem().substring(idxVbSfix)); o.setStem(o.getStem().substring(0,idxVbSfix)); o.setPatn(PatternConstants.PTN_NSMXMJ); o.setPos(PatternConstants.POS_NOUN); WordEntry entry = DictionaryUtil.getWordExceptVerb(o.getStem()); if(entry!=null) { if(entry.getFeature(WordEntry.IDX_NOUN)=='0') return false; else if(o.getVsfx().equals("하")&&entry.getFeature(WordEntry.IDX_DOV)!='1') return false; else if(o.getVsfx().equals("되")&&entry.getFeature(WordEntry.IDX_BEV)!='1') return false; else if(o.getVsfx().equals("내")&&entry.getFeature(WordEntry.IDX_NE)!='1') return false; o.setScore(AnalysisOutput.SCORE_CORRECT); // '입니다'인 경우 인명 등 미등록어가 많이 발생되므로 분석성공으로 가정한다. }else { o.setScore(AnalysisOutput.SCORE_ANALYSIS); // '입니다'인 경우 인명 등 미등록어가 많이 발생되므로 분석성공으로 가정한다. } candidates.add(o); return true; }
9
public int getCantPerson() { return CantPerson; }
0
private JSONArray readArray(boolean stringy) throws JSONException { JSONArray jsonarray = new JSONArray(); jsonarray.put(stringy ? read(this.stringhuff, this.stringhuffext, this.stringkeep) : readValue()); while (true) { if (probe) { log(); } if (!bit()) { if (!bit()) { return jsonarray; } jsonarray.put(stringy ? readValue() : read(this.stringhuff, this.stringhuffext, this.stringkeep)); } else { jsonarray.put(stringy ? read(this.stringhuff, this.stringhuffext, this.stringkeep) : readValue()); } } }
7
@Override @SuppressWarnings("unchecked") public void run() { DBPort connection = null; try { ServerDescription currentServerDescription = getConnectingServerDescription(null); Throwable currentException = null; while (!isClosed) { ServerDescription previousServerDescription = currentServerDescription; Throwable previousException = currentException; try { if (connection == null) { connection = new DBPort(serverAddress, null, getOptions(), 0); } try { currentServerDescription = lookupServerDescription(connection); } catch (IOException e) { // in case the connection has been reset since the last run, do one retry immediately before reporting that the // server is down count = 0; elapsedNanosSum = 0; if (connection != null) { connection.close(); connection = null; connectionProvider.invalidate(); } connection = new DBPort(serverAddress, null, getOptions(), 0); try { currentServerDescription = lookupServerDescription(connection); } catch (IOException e1) { connection.close(); connection = null; throw e1; } } } catch (Throwable t) { currentException = t; currentServerDescription = getConnectingServerDescription(t); } if (!isClosed) { try { logStateChange(previousServerDescription, previousException, currentServerDescription, currentException); sendStateChangedEvent(previousServerDescription, currentServerDescription); } catch (Throwable t) { LOGGER.log(Level.WARNING, "Exception in monitor thread during notification of server state change", t); } } waitForNext(); } } finally { if (connection != null) { connection.close(); } } }
9
private void method117(Stream stream) { stream.initBitAccess(); int j = stream.readBits(1); if(j == 0) return; int k = stream.readBits(2); if(k == 0) { anIntArray894[anInt893++] = myPlayerIndex; return; } if(k == 1) { int l = stream.readBits(3); myPlayer.moveInDir(false, l); int k1 = stream.readBits(1); if(k1 == 1) anIntArray894[anInt893++] = myPlayerIndex; return; } if(k == 2) { int i1 = stream.readBits(3); myPlayer.moveInDir(true, i1); int l1 = stream.readBits(3); myPlayer.moveInDir(true, l1); int j2 = stream.readBits(1); if(j2 == 1) anIntArray894[anInt893++] = myPlayerIndex; return; } if(k == 3) { plane = stream.readBits(2); int j1 = stream.readBits(1); int i2 = stream.readBits(1); if(i2 == 1) anIntArray894[anInt893++] = myPlayerIndex; int k2 = stream.readBits(7); int l2 = stream.readBits(7); myPlayer.setPos(l2, k2, j1 == 1); } }
8
public SensorSingleData filter(SensorSingleData sensorSingleData) { if (sensorSingleData.getAccX() < Constants.NOISE_DELTA_ERROR && sensorSingleData.getAccX() > -Constants.NOISE_DELTA_ERROR) { sensorSingleData.setAccX(0); } if (sensorSingleData.getAccY() < Constants.NOISE_DELTA_ERROR && sensorSingleData.getAccY() > -Constants.NOISE_DELTA_ERROR) { sensorSingleData.setAccY(0); } if (sensorSingleData.getAccZ() < Constants.NOISE_DELTA_ERROR && sensorSingleData.getAccZ() > -Constants.NOISE_DELTA_ERROR) { sensorSingleData.setAccZ(0); } return sensorSingleData; }
6
@Override public void actionPerformed(ActionEvent e) { LogLine selected = ((LogTableModel) mListLog.getModel()) .getItem(mListLog.getSelectedRow()); if (selected != null) { switch (e.getActionCommand()) { case Main.COMMAND_FILTER_THISTAG: setFilteredTag(selected.getTags()); break; case Main.COMMAND_FILTER_THISPROC: setFilteredPID(selected.getPID()); break; case Main.COMMAND_FILTER_WATCHPROC: mMonitoringPID = selected.getPID(); break; case Main.COMMAND_FILTER_COPY: copyToClipboard(selected.toString()); break; case Main.COMMAND_FILTER_COPYBODY: copyToClipboard(selected.getBody()); break; case Main.COMMAND_LOG_DETAILS: LogDetailDialog dialog = new LogDetailDialog(selected); JOptionPane.showMessageDialog(this, dialog, "ログの詳細", JOptionPane.PLAIN_MESSAGE); default: break; } } }
7
private ArrayList<Method> getAnnotatedMethodsRecursively(Class<?> klass) { if (klass == null || klass.equals(Class.class)) { annotatedMethodsByClass.put(klass, null); return null; } if (annotatedMethodsByClass.containsKey(klass)) { return annotatedMethodsByClass.get(klass); } ArrayList<Method> result = new ArrayList<Method>(); Method[] methods = klass.getDeclaredMethods(); if (methods == null) { annotatedMethodsByClass.put(klass, null); return null; } for (Method method : methods) { ASticky annotation = method.getAnnotation(ASticky.class); if (annotation != null) { method.setAccessible(true); result.add(method); } } ArrayList<Method> methodsFromSuperClass = getAnnotatedMethodsRecursively(klass.getSuperclass()); if (methodsFromSuperClass != null) { result.addAll(methodsFromSuperClass); } annotatedMethodsByClass.put(klass, result); return result; }
8
private void outputStats(StateMap stateMap) { System.out.println("LCDC: " + lcdc.getSize()); SpriteStateRange minBefore = null; SpriteStateRange maxInFrame = null; SpriteStateRange minAfter = null; for (SpriteStateRange sprite : sprites) { if (sprite.notBeforeOrAt >= 0 && (minBefore == null || sprite.from - sprite.notBeforeOrAt < minBefore.from - minBefore.notBeforeOrAt)) minBefore = sprite; if (maxInFrame == null || sprite.to - sprite.from > maxInFrame.to - maxInFrame.from) maxInFrame = sprite; if (minAfter == null || sprite.notAtOrAfter - sprite.to < minAfter.notAtOrAfter - minAfter.to) minAfter = sprite; } System.out.println("sprites: " + sprites.size()); System.out.println("min before: " + minBefore); System.out.println("max in frame: " + maxInFrame); System.out.println("min after: " + minAfter); System.out.println("known tiles: " + stateMap.tileRegistry.getSize()); System.out.println("known palettes: " + stateMap.objPaletteRegistry.getSize()); System.out.println(); }
8
static ClassInterfacesType create(ClassInfo clazz, ClassInfo[] ifaces) { /* Make sure that every {java.lang.Object} equals tObject */ if (ifaces.length == 0 && clazz == null) return tObject; if (ifaces.length == 0) return tClass(clazz); if (ifaces.length == 1 && clazz == null) return tClass(ifaces[0]); return new ClassInterfacesType(clazz, ifaces); }
5
private void playerMove(Player player, Location location, Reason reason) { // Check if he left the zone he currently is in List<Zone> zones = assignedZones.get(player.getName()); if(zones == null) { zones = new ArrayList<Zone>(3); assignedZones.put(player.getName(), zones); } // Remove old zones, if necessary if(zones.size() > 0) { Iterator<Zone> iter = zones.iterator(); while(iter.hasNext()) { Zone zone = iter.next(); // Player left the zone? if(!zone.contains(location)) { // make sure that custom "remove" code doesn't crash us try { zone.remove(player, reason); } catch(Exception e) { e.printStackTrace(); } iter.remove(); } } } // Apply new zones, if necessary for(Zone zone : zoneMap.getZones(player.getWorld().getName(), location.getX(), location.getY(), location.getZ())) { if(!zones.contains(zone)) { // Player entered a new zone! // Make sure that custom "add" code doesn't crash us try { zone.add(player, reason); } catch(Exception e) { e.printStackTrace(); } zones.add(zone); } } }
8
public void winner(int winner) { if (winner == myID) { winnerField.setText(myName + " wins!"); } else if (winner == theirID) { winnerField.setText(theirName + " wins!"); } else { winnerField.setText("Draw!"); } }
2
public List<Tuote> haeTuotteet() throws DAOPoikkeus { ArrayList<Tuote> tuotteet = new ArrayList<Tuote>(); // avataan yhteys Connection yhteys = avaaYhteys(); try { // Haetaan tietokannasta tuotteet String sql = "select nimi, numero, hinta, tuoteID from Tuote"; Statement haku = yhteys.createStatement(); ResultSet tulokset = haku.executeQuery(sql); while(tulokset.next()) { int numero = tulokset.getInt("numero"); String nimi = tulokset.getString("nimi"); double hinta = tulokset.getDouble("hinta"); int id = tulokset.getInt("tuoteID"); // TESTI Tuote tuote = new Tuote(numero, nimi, hinta, id); tuotteet.add(tuote); } } catch(Exception e) { // Tapahtui jokin virhe? throw new DAOPoikkeus("Tietokantahaku aiheutti virheen.", e); } finally { // Lopulta aina suljetaan yhteys! suljeYhteys(yhteys); } return tuotteet; }
2
protected static void methodChoices() { if(getJRadioButton_FCFS().isSelected()){ choice=1; getJRadioButton_SSTF().setSelected(false); getJRadioButton_SCAN().setSelected(false); getJRadioButton_CSCAN().setSelected(false); getJRadioButton_LOOK().setSelected(false); getJRadioButton_CLOOK().setSelected(false); } else if(getJRadioButton_SSTF().isSelected()){ choice=2; getJRadioButton_FCFS().setSelected(false); getJRadioButton_SCAN().setSelected(false); getJRadioButton_CSCAN().setSelected(false); getJRadioButton_LOOK().setSelected(false); getJRadioButton_CLOOK().setSelected(false); } else if(getJRadioButton_SCAN().isSelected()){ choice=3; getJRadioButton_SSTF().setSelected(false); getJRadioButton_FCFS().setSelected(false); getJRadioButton_CSCAN().setSelected(false); getJRadioButton_LOOK().setSelected(false); getJRadioButton_CLOOK().setSelected(false); } else if(getJRadioButton_CSCAN().isSelected()){ choice=4; getJRadioButton_SSTF().setSelected(false); getJRadioButton_SCAN().setSelected(false); getJRadioButton_FCFS().setSelected(false); getJRadioButton_LOOK().setSelected(false); getJRadioButton_CLOOK().setSelected(false); } else if(getJRadioButton_LOOK().isSelected()){ choice=5; getJRadioButton_SSTF().setSelected(false); getJRadioButton_SCAN().setSelected(false); getJRadioButton_CSCAN().setSelected(false); getJRadioButton_FCFS().setSelected(false); getJRadioButton_CLOOK().setSelected(false); } else if(getJRadioButton_CLOOK().isSelected()){ choice=6; getJRadioButton_SSTF().setSelected(false); getJRadioButton_SCAN().setSelected(false); getJRadioButton_CSCAN().setSelected(false); getJRadioButton_LOOK().setSelected(false); getJRadioButton_FCFS().setSelected(false); } }
6
public List<CarrierInfo> findOFDMCarriers (double spectrum[],double sampleRate,int binCount,double multiFactor) { List<CarrierInfo> cList=new ArrayList<CarrierInfo>(); int a; double dPoint=-1.0; for (a=0;a<(spectrum.length-1);a++) { if (spectrum[a]>dPoint) dPoint=spectrum[a]; } dPoint=dPoint*multiFactor; for (a=1;a<(spectrum.length-1);a++) { // Check the current spectrum value is higher than the last one and the next one // if it is then this is a peak so classify this as a carrier if ((spectrum[a]>spectrum[a-1])&&(spectrum[a]>spectrum[a+1])&&(spectrum[a]>dPoint)) { CarrierInfo cInfo=new CarrierInfo(); cInfo.setBinFFT(a); cInfo.setEnergy(spectrum[a]); // Calculate the actual frequency of the carrier double freq=(double)a*(sampleRate/(double)binCount); cInfo.setFrequencyHZ(freq); // Add this carrier object to the list cList.add(cInfo); } } return cList; }
6
public String extract(Element element) { return key != null && element.hasAttr(key) ? element.attr(key) : ""; }
2
public void loadFromFile() { if (!fileExists()) return; // Exit if file doesn't exist RmiData o = null; try { FileInputStream fileIn = new FileInputStream(FILE); ObjectInputStream in = new ObjectInputStream(fileIn); o = (RmiData) in.readObject(); in.close(); fileIn.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } this.setLoginResult(o.getLoginResult()); this.setContestants(o.getContestants()); this.setLanguages(o.getLanguages()); this.setProblems(o.getProblems()); this.setSubmissions(o.getSubmissions()); this.setTimeLeft(o.getTimeLeft()); this.setContestRunning(o.getContestRunning()); }
2
private int[] calculateExpectedAndStandardDev(int[] platter) { int[] bowl; int total_score = 0; int max_score = -1; int[] samples = new int[SAMPLE_NUM]; for (int i=0; i < SAMPLE_NUM; i++) { bowl = createBowl(platter); int bowl_score = scoreBowl(bowl); samples[i] = bowl_score; total_score += bowl_score; if (bowl_score > max_score) max_score = bowl_score; } int ev = Math.round(total_score/SAMPLE_NUM); int sum = 0; for (int i=0; i < SAMPLE_NUM; i++) { sum += Math.pow(samples[i] - ev, 2); } int stdv = (int) Math.round(Math.sqrt(sum/SAMPLE_NUM-1)); int[] return_val = {ev, stdv}; return return_val; }
3
public void update(GameContainer container, int delta) throws SlickException { if (container.getInput().isKeyDown(Input.KEY_Q)) { zoom += (delta * 0.01f); if (zoom > 10) { zoom = 10; } } if (container.getInput().isKeyDown(Input.KEY_A)) { zoom -= (delta * 0.01f); if (zoom < 0.1f) { zoom = 0.1f; } } if (container.getInput().isKeyDown(Input.KEY_RIGHT)) { x += (delta * 0.1f); } if (container.getInput().isKeyDown(Input.KEY_LEFT)) { x -= (delta * 0.1f); } if (container.getInput().isKeyDown(Input.KEY_DOWN)) { y += (delta * 0.1f); } if (container.getInput().isKeyDown(Input.KEY_UP)) { y -= (delta * 0.1f); } }
8
private void buildMetadataElements(JoeTree tree, String line_ending, StringBuffer buf) { Iterator it = tree.getAttributeKeys(); StringBuffer readOnlyAtts = new StringBuffer(); if (it != null) { while (it.hasNext()) { String key = (String) it.next(); Object value = tree.getAttribute(key); if (isReservedMetadataName(key)) { continue; } boolean isReadOnly = tree.isReadOnly(key); if (isReadOnly) { readOnlyAtts.append(key).append(" "); } appendMetadataElement(buf, key, value.toString(), line_ending); } } if (readOnlyAtts.length() > 0) { appendMetadataElement(buf, IS_READ_ONLY_ATTS_LIST, readOnlyAtts.toString().trim(), line_ending); } }
5
private void saveModified(){ if(modified){ if(JOptionPane.showConfirmDialog(null, "Scene modified, save it?", "Confirm", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){ saveScene(); } } }
2
private int gradient_optimize_with_step(double step) throws Exception { double grad[][] = { { 0D, 0D, 0D, 0D, 0D, 0D }, { 0D, 0D, 0D, 0D, 0D, 0D }, { 0D, 0D, 0D, 0D, 0D, 0D }, { 0D, 0D, 0D, 0D, 0D, 0D }, { 0D, 0D, 0D, 0D, 0D, 0D } }; int i, j, l; int result = 0; double minDist = Double.MAX_VALUE; double copiaStartVec[] = this.section.poincareStartVector.clone(); double copiaEndVec[] = this.section.poincareEndVector.clone(); double copiaDifMap[] = this.section.poincareDifMap.clone(); i = 0; l = 0; while (result == 0 && this.totalPendingIter > 0 && this.section.poincareEndVector[1] < minDist && this.section.poincareEndVector[1] > this.aproxEndBodyDistance) { // Copia vector inicial i diferencial copyVector(this.section.poincareStartVector, copiaStartVec); copyVector(this.section.poincareEndVector, copiaEndVec); copyVector(this.section.poincareDifMap, copiaDifMap); minDist = this.section.poincareEndVector[1]; l++; for (j = 0; j < 6; j++) { grad[i][j] = -this.aproxMetricPar[j] * this.section.poincareDifMap[1 + 6 * j]; } if (Funcions.normaliserd(grad[i], 6) == 0D) { result = ErrorCode.GradientUnderFlow.getErrorNumber(); break; } Funcions.adamsBashforth(this.section.poincareStartVector, 6, grad[i], grad[(i + 4) % 5], grad[(i + 3) % 5], grad[(i + 2) % 5], l >= AB_POINTS ? AB_POINTS : 1, step); result = this.section.poincareMap(); if (result != 0 || minDist < this.section.poincareEndVector[1]) { // Restaura vector inicial i diferencial copyVector(copiaStartVec, this.section.poincareStartVector); this.section.poincareEndVector = copiaEndVec.clone(); this.section.poincareDifMap = copiaDifMap.clone(); } else { i = (i + 1) % 5; this.totalPendingIter--; } } return result; }
9
private void getParameters(String inputFileName){ /* try{ TextIO.readFile(inputFileName); }catch(IllegalArgumentException ee){ }*/ //GetComments assume to know how comments are written in the file. I use the ! (bang) symbol for them //For the moment, I do not store the comments new GetComments(); //first the number of rows and columns is retrieved String rowsN=TextIO.getWord(); //System.out.println(rowsN); rows=TextIO.getlnInt(); System.out.println(rows); String colsN=TextIO.getWord(); //System.out.println(colsN); cols=TextIO.getlnInt(); //System.out.println(cols); //Here the variables names are retrieved String variablesNames=TextIO.getlnString(); //Here the units are retrieved String variablesUnits=TextIO.getlnString(); //The number of names must be equal to the number of cols + 1. The first field names followed by ':' (with no space) this.vnames=variablesNames.split(" "); for(int k=1;k<cols+1;k++){ vnames[k]=vnames[k].replaceAll("\\s", ""); //System.out.println("["+k+"] "+vnames[k]); } this.vunits=variablesUnits.split(" ",vnames.length); for(int k=1;k<cols+1;k++){ vunits[k]=vunits[k].replaceAll("\\s", ""); //System.out.println("["+k+"] "+vunits[k]); } String variables; this.vls=new double[rows][cols]; //All the values are retrieved as strings for(int i=0;i<rows;i++){ variables=TextIO.getlnString(); this.var=variables.split(" ",variables.length()); var[i]=var[i].replaceAll("\\s", ""); //All the variables retrieved are converted to double for(int k=0;k< cols;k++){ vls[i][k]=Double.parseDouble(var[k]); //System.out.println("["+i+"] "+"["+k+"] "+vls[i][k]); } } }
4
void createToolBar(final Composite parent) { final Display display = parent.getDisplay(); toolBar = new ToolBar(parent, SWT.FLAT); Listener toolBarListener = new Listener() { public void handleEvent(Event event) { switch (event.type) { case SWT.Selection: { if (event.widget == playItem) { animate = true; playItem.setEnabled(!animate); pauseItem.setEnabled(animate); } else if (event.widget == pauseItem) { animate = false; playItem.setEnabled(!animate); pauseItem.setEnabled(animate); } } break; } } }; // play tool item playItem = new ToolItem(toolBar, SWT.PUSH); playItem.setText(GraphicsExample.getResourceString("Play")); //$NON-NLS-1$ playItem.setImage(example.loadImage(display, "play.gif")); //$NON-NLS-1$ playItem.addListener(SWT.Selection, toolBarListener); // pause tool item pauseItem = new ToolItem(toolBar, SWT.PUSH); pauseItem.setText(GraphicsExample.getResourceString("Pause")); //$NON-NLS-1$ pauseItem.setImage(example.loadImage(display, "pause.gif")); //$NON-NLS-1$ pauseItem.addListener(SWT.Selection, toolBarListener); // timer spinner Composite comp = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(2, false); comp.setLayout(gridLayout); Label label = new Label(comp, SWT.CENTER); label.setText(GraphicsExample.getResourceString("Animation")); //$NON-NLS-1$ timerSpinner = new Spinner(comp, SWT.BORDER | SWT.WRAP); timerSpinner.setMaximum(1000); playItem.setEnabled(false); animate = true; timerSpinner.setSelection(getInitialAnimationTime()); }
3
public ArrayList<HashMap<String, String>> getAnafores(){ /* * epistrefei tis anafores ths vashs se mia lista opou pairnei to onoma tou column kai thn timi tou */ ArrayList<HashMap<String, String>> anafores=new ArrayList<HashMap<String, String>>(); try { pS = conn.prepareStatement("SELECT * FROM anafores INNER JOIN odigoi ON odigos_id=odigoi.id"); rs=pS.executeQuery(); while(rs.next()){ HashMap<String, String> map = new HashMap<String, String>(); map.put("id", rs.getString("id")); map.put("provlima", rs.getString("provlima")); map.put("sxolia", rs.getString("sxolia")); map.put("oxima", rs.getString("oxima")); map.put("time", rs.getString("time")); anafores.add(map); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return anafores; }
3