text
stringlengths
14
410k
label
int32
0
9
public static int getRandomNumber(int min, int max) { int num = random.nextInt(max); int mod = num % (max - min); return mod + min; }
0
public final void actualiser() { try { remplissageComboBox(lesPraticiens); indicePraticienCourant = 0; System.out.println(indicePraticienCourant); praticienCourant = lesPraticiens.get(indicePraticienCourant); afficherPraticien(praticienCourant); } catch (Exception ex) { JOptionPane.showMessageDialog(getVue(), "CtrlPresence - actualiser - " + ex.getMessage(), "Saisie des présences", JOptionPane.ERROR_MESSAGE); } }
1
protected static Ptg calcCoupNum( Ptg[] operands ) { if( operands.length < 2 ) { return new PtgErr( PtgErr.ERROR_NULL ); } debugOperands( operands, "COUPNUM" ); try { GregorianCalendar sDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[0].getValue() ); GregorianCalendar mDate = (GregorianCalendar) DateConverter.getCalendarFromNumber( operands[1].getValue() ); long settlementDate = (new Double( DateConverter.getXLSDateVal( sDate ) )).longValue(); long maturityDate = (new Double( DateConverter.getXLSDateVal( mDate ) )).longValue(); int frequency = operands[2].getIntVal(); int basis = 0; if( operands.length > 3 ) { basis = operands[3].getIntVal(); } // TODO: if dates are not valid, return #VALUE! error if( (basis < 0) || (basis > 4) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( !((frequency == 1) || (frequency == 2) || (frequency == 4)) ) { return new PtgErr( PtgErr.ERROR_NUM ); } if( settlementDate > maturityDate ) { return new PtgErr( PtgErr.ERROR_NUM ); } /* double result = getDaysFromBasis(basis, settlementDate, maturityDate) / (getDaysInYearFromBasis(basis, settlementDate, maturityDate) / frequency); result = Math.ceil(result); double delta= maturityDate-settlementDate; double result= delta/calcCoupDays(operands)); */ double result = Math.ceil( yearFrac( basis, settlementDate, maturityDate ) * frequency ); log.debug( "Result from calcCoupNUM= " + result ); PtgNumber pnum = new PtgNumber( result ); return pnum; } catch( Exception e ) { } return new PtgErr( PtgErr.ERROR_VALUE ); }
9
public void initializeTime(HardwareSet hardwareSet) { for(HardwareSetAlternative hardwareSetAlternative : hardwareSystem.getHardwareSetAlternatives()) if(hardwareSetAlternative.getHardwareSet().equals(hardwareSet)){ hardwareSetAlternative.initializeTime(); } }
2
public static int findDepth( String s ) { int countLeft = 0; int countLeftTotal = 0; int countZero = 0; int depth = -1; // countLeft - 1 for( int i = 0; i < s.length(); i++) { char a = s.charAt( i ); switch( a ){ case '0': countZero++; break; case '(': { countLeft++; countLeftTotal++; }; break; case ')': { if( depth < countLeft - 1 ) depth = countLeft - 1; countLeft = 1; };break; default: return -1; } /* if( a == '(' ) countLeft++; else if( a == ')' && depth < ( countLeft - 1 ) ) { depth = countLeft - 1; countLeft = 1; } else if( a != '0' ) return -1;*/ } if( countZero == countLeftTotal + 1 ) return depth; else return -1; }
6
public static int countCells(Board board, int x, int y, int radius) { int result = 0; for (int px = x-radius; px <= x+radius; px++) if (px >= 0 && px < board.w) for (int py = y-radius; py <= y+radius; py++) if (py >= 0 && py < board.h) if (board.cells[px][py]) result++; return result; }
7
@Override public <S> Result<S> find(Class<S> serviceClass) throws ServiceInstantiationException { Result<S> result=null; // S provider=null; // Scope scope=null; // If it still doesn't exist, get the provider class, see what scope // it prefers, and create it in that scope. Syncyhronization should // only be necessary later in the code path when access to the shared // caches is necessary (most should be cached in thread-local caches // under steady state. final ServiceProviderInfo<S> info=findProviderInfo(serviceClass); if (info!=null) { // // Request scope takes precedence when present // if (info.isScopeAllowed(Scope.REQUEST)) { // scope=Scope.REQUEST; // provider=instantiateNonApplicationService(info,scope); // } // else // if (info.isScopeAllowed(Scope.APPLICATION)) { // scope=Scope.APPLICATION; // provider=instantiateApplicationService(info); // } // else // if (info.isScopeAllowed(Scope.CLIENT_MANAGED)) { // scope=Scope.CLIENT_MANAGED; // provider=instantiateNonApplicationService(info,scope); // } // else { // // Bug in my code: unaccounted for scope type // assert false: "Cannot create service in unknown scope"; // throw new IllegalArgumentException( // "Cannot create service in unknown scope"); // } Scope scope=null; // Request scope takes precedence when present if (info.isScopeAllowed(Scope.REQUEST)) { scope=Scope.REQUEST; } else if (info.isScopeAllowed(Scope.APPLICATION)) { scope=Scope.APPLICATION; } else if (info.isScopeAllowed(Scope.CLIENT_MANAGED)) { scope=Scope.CLIENT_MANAGED; } else { // Bug in my code: unaccounted for scope type throw new IllegalArgumentException( "Cannot determine scope of service in unknown scope"); } final Scope _scope=scope; ServiceProviderFactory<S> factory= new ServiceProviderFactory<S>() { @Override public S createInstance() { S provider=null; // Request scope takes precedence when present if (_scope==Scope.REQUEST) { provider= instantiateNonApplicationService(info,_scope); } else if (_scope==Scope.APPLICATION) { provider=instantiateApplicationService(info); } else if (_scope==Scope.CLIENT_MANAGED) { provider= instantiateNonApplicationService(info,_scope); } else { // Bug in my code: unaccounted for scope type throw new IllegalArgumentException( "Cannot create service in unknown scope: "+ _scope); } return provider; } }; result=new Result<S>(serviceClass,factory,scope); } return result; }
7
@Override public String getColumnName(int columnIndex) { switch (columnIndex) { case VENDOR: return "Производитель"; case NUMBER: return "№"; case MODEL: return "Модель"; case NOTE: return "Примечание"; case RECEIPT_DATE: return "Добавлено"; default: logger.warn("Попытка получить значение для несуществующего стообца. " + "Столбец: " + columnIndex); return "Столбец №" + columnIndex; } }
5
public static boolean equal(boolean[][] a, boolean[][] b) { if(a != null && b != null) { if(a.length == b.length) { for(int i = 0; i < a.length; i++) { if(a[i].length == b[i].length) { for(int j = 0; j < a[i].length; j++) { if(a[i][j] != b[i][j]) { return false; } } } else { return false; } } return true; } else { return false; } } else if(a == null && b == null) { return true; } else { return false; } }
9
private static JCheckBox[] getAssetCheckBoxes(AIProject project) { List<AIAsset> tempAssetsList = project.getAssetsList(); JCheckBox[] assetCheckBoxLabels = new JCheckBox[tempAssetsList.size()]; for (int i = 0; i < tempAssetsList.size(); i++) { assetCheckBoxLabels[i] = new JCheckBox(tempAssetsList.get(i).getName()); } return assetCheckBoxLabels; }
1
public void read(String txt) { if (txt.length() > MAX_TXT_LENGTH) { Iterator<String> i = splitToChunks(txt).iterator(); while (i.hasNext()) { playText(i.next()); } } else { playText(txt); } }
2
public void terminated(Pipe pipe_) { // Remove the pipe from the list; adjust number of matching, active and/or // eligible pipes accordingly. if (pipes.indexOf (pipe_) < matching) matching--; if (pipes.indexOf (pipe_) < active) active--; if (pipes.indexOf (pipe_) < eligible) eligible--; pipes.remove(pipe_); }
3
public static void printGrade(double score) { if(score < 0 || score > 100) { System.out.println("Invalid Score"); return; } if (score >= 90.0) { System.out.println('A'); } else if(score >= 80.0) { System.out.println('B'); } else if(score >= 70.0) { System.out.println('C'); } else if(score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } }
6
public Object [][] getDatos(){ Object[][] data = new String[getCantidad_Cuentas ()][colum_names.length]; //realizamos la consulta sql y llenamos los datos en "Object" try{ if (colum_names.length>=0){ r_con.Connection(); String campos = colum_names[0]; for (int i = 1; i < colum_names.length; i++) { campos+=","; campos+=colum_names[i]; } String consulta = null; if (combo_filtro.getSelectedIndex()==0){ consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+"))"); ocultar_Msj(); } else{ if (combo_filtro.getSelectedIndex()==1){ String campobuscado = colum_names[relacion_indices_conTabla[numero_ordenamiento_elegido]]; consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+")) "+ "WHERE ("+campobuscado+" >= '"+rango_1.getText()+"' AND "+campobuscado+" <= '"+rango_2.getText()+"')"); String buscado = colum_names_tabla[relacion_indices_conTabla[numero_ordenamiento_elegido]]; mostrar_Msj_Exito("FILTRO: "+buscado+" entre: "+rango_1.getText()+" y "+rango_2.getText()); } else{ String campobuscado = colum_names[relacion_indices_conTabla[numero_ordenamiento_elegido]]; consulta = ("SELECT "+campos+" "+ "FROM "+name_tabla+" WITH (INDEX("+indices_tabla[numero_ordenamiento_elegido]+")) "+ "WHERE ("+campobuscado+" = '"+rango_1.getText()+"')"); String buscado = colum_names_tabla[relacion_indices_conTabla[numero_ordenamiento_elegido]]; mostrar_Msj_Exito("FILTRO: "+buscado+" = "+rango_1.getText()); } } if (consulta!=null){ PreparedStatement pstm = r_con.getConn().prepareStatement(consulta); ResultSet res = pstm.executeQuery(); int i = 0; while(res.next()){ for (int j = 0; j < colum_names.length; j++) { data[i][j] = res.getString(j+1); } i++; } res.close(); } } } catch(SQLException e){ System.out.println(e); } finally { r_con.cierraConexion(); } return data; }
8
public void addLast(E e) { if (e == null) throw new NullPointerException(); elements[tail] = e; if ( (tail = (tail + 1) & (elements.length - 1)) == head) doubleCapacity(); }
2
public void add(int x, int y) { int[] tmp = new int[2]; for(int i = 0; i < index; i++) if(x < line[i][0] || y < line[index][1]) { tmp[0] = line[i][0]; tmp[1] = line[i][1]; line[i][0] = x; line[i][1] = y; x = tmp[0]; y = tmp[1]; } line[index][0] = x; line[index][1] = y; index++; count++; }
3
@Override public void runStartupChecks() throws EngineException { Engine eng = FreeForAll.getInstance().getEngineManger().getEngine("Storage"); if (eng != null) { if (eng instanceof StorageEngine) { this.SE = (StorageEngine) eng; } } if (SE == null) { throw new EngineException("Missing Storage -Dependency."); } if (DB == null) { throw new EngineException("Missing database communication link."); } }
4
@Override public PilotAction findNextAction(double s_elapsed) { if (target_unit == null || !target_unit.isInMap() || !target_unit.isHomable() || !target_unit.getRoom().equals(target_unit_room)) { updateTarget(); return PilotAction.MOVE_FORWARD; } double angle_to_target = MapUtils.angleTo(bound_object, target_unit); if (Math.abs(angle_to_target) > max_angle_to_target || (!target_unit_room.equals(current_room) && !MapUtils.canSeeObjectInNeighborRoom(bound_object, target_unit, target_unit_room_info.getKey()))) { updateTarget(); return PilotAction.MOVE_FORWARD; } TurnDirection turn = angleToTurnDirection(angle_to_target); return new PilotAction(MoveDirection.FORWARD, turn); }
7
private int BFS(Graph graph, String start, String end) { int length = 1; if (start.equals(end)) return 0; HashSet<String> visited = new HashSet<String>(); HashSet<String> outGoing = new HashSet<String>(); HashSet<String> reaching = new HashSet<String>(); reaching.add(start); visited.add(start); while (!visited.contains(end) && reaching.size() > 0) { length++; HashSet<String> temp = outGoing; outGoing = reaching; reaching = temp; reaching.clear(); for (String word : outGoing) { for (String toWord : graph.connectTo(word)) { if (!visited.contains(toWord)) { reaching.add(toWord); visited.add(toWord); } } } } return reaching.size() > 0 ? length : 0; }
7
public List<Component> loadDatabase(){ List<Component> database = new ArrayList<Component>(); try { File fXmlFile = new File("database.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); Node root = (Node) doc.getDocumentElement(); System.out.println("Root element :" + root.getNodeName()); System.out.println("-----------------------"); NodeList nList = root.getChildNodes(); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; if(eElement.getNodeName().equals("job")){ Job job = createJob(eElement); database.add(job); } else if(eElement.getNodeName().equals("task")){ Task task = new Task(eElement.getAttribute("name"), eElement.getAttribute("description"), eElement.getAttribute("state")); NodeList intervals = eElement.getChildNodes(); for(int i = 0; i < intervals.getLength(); i++){ Node interval = intervals.item(i); if (interval.getNodeType() == Node.ELEMENT_NODE){ Element intvl = (Element) interval; Interval newInterval = new Interval(intvl.getAttribute("start"),intvl.getAttribute("end")); task.getIntervals().add(newInterval); } } database.add(task); } else if(eElement.getNodeName().equals("action")){ Action action = new Action(eElement.getAttribute("name"), eElement.getAttribute("description"), eElement.getAttribute("state")); database.add(action); } } } } catch (Exception e) { e.printStackTrace(); } return database; }
8
public int getCount() { return count; }
0
@Override public Object getValueAt(int indiceLinha, int indiceColuna) { //Verifica o índice da linha e obtém o valor através da posição na lista RegistroNaoConformidadeApontado registroNaoConformidadeApontado = linhas.get(indiceLinha); //Verifica o índice da coluna e obtém o valor switch (indiceColuna) { case 0: return registroNaoConformidadeApontado.isStatus(); case 1: return registroNaoConformidadeApontado.getFornecedor(); case 2: return registroNaoConformidadeApontado.getJob().trim().length() == 11 ? registroNaoConformidadeApontado.getJob().substring(0,6) + "." + registroNaoConformidadeApontado.getJob().substring(6,8) + "." + registroNaoConformidadeApontado.getJob().substring(8,11): registroNaoConformidadeApontado.getJob(); // return registroNaoConformidadeApontado.getJob(); case 3: return registroNaoConformidadeApontado.getSetorOrigem(); case 4: return registroNaoConformidadeApontado.getComponente(); case 5: return registroNaoConformidadeApontado.getQuantidadeRejeitado(); case 6: return registroNaoConformidadeApontado.getDescricaoDefeito(); case 7: return registroNaoConformidadeApontado.getRejeicao(); default: //Se a coluna especificada não existir é lançada uma exceção throw new IndexOutOfBoundsException("A coluna com o índice:"+indiceColuna+" não existe!"); } }
9
public void func_73188_b(int par1, int par2, byte par3ArrayOfByte[], BiomeGenBase par4ArrayOfBiomeGenBase[]) { for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { int k = 1; int l = -1; byte byte0 = (byte)Block.whiteStone.blockID; byte byte1 = (byte)Block.whiteStone.blockID; for (int i1 = 127; i1 >= 0; i1--) { int j1 = (j * 16 + i) * 128 + i1; byte byte2 = par3ArrayOfByte[j1]; if (byte2 == 0) { l = -1; continue; } if (byte2 != Block.stone.blockID) { continue; } if (l == -1) { if (k <= 0) { byte0 = 0; byte1 = (byte)Block.whiteStone.blockID; } l = k; if (i1 >= 0) { par3ArrayOfByte[j1] = byte0; } else { par3ArrayOfByte[j1] = byte1; } continue; } if (l > 0) { l--; par3ArrayOfByte[j1] = byte1; } } } } }
9
private void trickleUp(int index) { int parent = (index - 1) / 2; BTPosition<T> bottom = heap.get(index); while (index > 0 && comp.compare(heap.get(parent).element(), bottom.element()) < 0) { heap.set(index, heap.get(parent)); index = parent; parent = (parent - 1) / 2; } heap.set(index, bottom); }
2
public static void main (String args[]){ Scanner s = new Scanner(System.in); System.out.println("Enter with a value!"); while(s.hasNext()){ if(s.hasNextInt()){ System.out.println("Int.:"+s.nextInt()); }else { System.out.println("String.:"+s.next()); } } System.out.println("End"); }
2
private void genererEntete(File fichier) { String type =""; //PROTOCOLE + message réussite AFFICHÉ PLUS HAUT Date dateM = new Date(fichier.lastModified()); if(fichier.isFile()) { String extension = (fichier.getName().split("\\."))[1]; type = getType(extension); } Date dateJ = new Date(); writer.println("Server: " + NOMSERVEUR); writer.println("Date: "+ getDateRfc822(dateJ)); //Si le type n'est pas géré, la ligne sera omise... if (type.equals("")) { //il s'agit d'un dossier writer.println("Content-Type: " + "text/HTML"); } else { writer.println("Content-Type: " + type); } writer.println("Last-Modified: " + getDateRfc822(dateM)); if(fichier.length() != 0 ) { writer.println("Content-Length: " + fichier.length()); } writer.println(); }
3
public void rankSelection() { // calculate fitness, filter invalid elements List<Individual> okList = new ArrayList<Individual>(); for (Individual ind : individuals) { if (ind.fitness(MIN_G)) okList.add(ind); } // sort in preparation to calculate rank Collections.sort(okList, new Comparator<Individual>() { @Override public int compare(Individual o1, Individual o2) { /* * We want to assign the highest rank the lowest fitness value * because we want to minimize f(). * This sorts the biggest element first. */ return (int) Double.compare(o2.fitness, o1.fitness); } }); // set rank based on position in sorted list int ranks = 0; for (int i = 0; i < okList.size(); i++) { okList.get(i).rank = i + 1; ranks += i + 1; } // calculate a start value between 0.0 and 1.0 based on rank double start = 0; for (Individual ind : okList) { ind.start = start; start += 1D / (double) ranks * (double) ind.rank; } // randomly select individuals List<Individual> selectedInd = new ArrayList<Individual>(); for (int i = 0; i < individuals.size(); i++) { double r = rand.nextDouble(); for (int j = okList.size() - 1; j >= 0; j--) { Individual ind = okList.get(j); if (ind.start <= r) { Individual tmp = ind.duplicate(); tmp.index = i; selectedInd.add(tmp); break; } } } individuals = selectedInd; }
7
public void disable() { if(RealWeather.isDebug()) RealWeather.log("Disabling features."); for (Feature feature : features.values()) { try { if(RealWeather.isDebug()) RealWeather.log("DIS: " + feature.getName()); try { configs.get(feature.getName()).save(); } catch (IOException ex) { if(RealWeather.isDebug()) RealWeather.log("ERROR while saving config."); Logger.getLogger(FeatureManager.class.getName()).log(Level.SEVERE, null, ex); } feature.onDisable(); plugin.getThreadManager().stopAllThreadsForFeature(feature); } catch (Exception ex) { if(RealWeather.isDebug()) RealWeather.log("Error occured while disabling module."); Logger.getLogger(FeatureManager.class.getName()).log(Level.SEVERE, null, ex); } } if(RealWeather.isDebug()) RealWeather.log("All features disabled."); }
8
private double find(int A[], int B[], int l, int r) { int m = A.length, n = B.length; if (l > r) { return find(B, A, Math.max(0, (n - m) / 2), Math.min(B.length - 1, (m + n) / 2)); } int i = (l + r) / 2; int j = (m + n) / 2 - i - 1; int Bj = j < 0 ? Integer.MIN_VALUE : B[j]; int Bj1 = j >= n - 1 ? Integer.MAX_VALUE : B[j + 1]; if (A[i] < Bj) { return find(A, B, i + 1, r); } if (A[i] > Bj1) { return find(A, B, l, i - 1); } if ((m + n) % 2 == 1) { return A[i]; } int second = (i > 0 && j >= 0) ? Math.max(A[i - 1], Bj) : i > 0 ? A[i - 1] : Bj; return (A[i] + second) / 2.0; }
9
public Tile getCurrentDestination() { final Tile start = Players.getLocal().getLocation(); int minDist = Integer.MAX_VALUE; for (Tile t : destinations) { minDist = Math.min(minDist, MapUtil.dist(start, t)); } if (minDist > 100) return null; int pangle = -1; for (int i = destinations.length - 1; i >= 0; i--) { Tile cur = destinations[i]; int cangle = MapUtil.getOrientation(start, cur); if (cur.isOnMap()) { if (pangle == -1 || Math.abs(cangle - pangle) % 180 < 90) return cur; else return destinations[i + 1]; } if (MapUtil.dist(cur, start) == minDist) return cur; } return null; }
7
private void initGui() { getContentPane().setBackground(backgroundColor); setTitle("BATTLEBOTS ARENA"); ArrayList<Image> icons = new ArrayList<Image>(); icons.add(new ImageIcon(getClass().getResource("icon16.png")).getImage()); icons.add(new ImageIcon(getClass().getResource("icon32.png")).getImage()); icons.add(new ImageIcon(getClass().getResource("icon64.png")).getImage()); setIconImages(icons); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); JLabel title = new JLabel("BATTLEBOTS ARENA - ARENA SIZE " + xDim + "x" + yDim); title.setForeground(borderColor); score = new JLabel("BEGIN SIMULATION"); score.setOpaque(true); score.setForeground(backgroundColor); score.setBackground(borderColor); score.addMouseListener(this); labelPencil = new JLabel("PENCIL"); labelPencil.setOpaque(true); labelPencil.setForeground(backgroundColor); labelPencil.setBackground(borderColorInverted); labelPencil.addMouseListener(this); labelLine = new JLabel("LINE"); labelLine.setOpaque(true); labelLine.setForeground(backgroundColor); labelLine.setBackground(borderColor); labelLine.addMouseListener(this); labelSquare = new JLabel("SQUARE"); labelSquare.setOpaque(true); labelSquare.setForeground(backgroundColor); labelSquare.setBackground(borderColor); labelSquare.addMouseListener(this); saveButton = new JLabel("SAVE"); saveButton.setOpaque(true); saveButton.setForeground(backgroundColor); saveButton.setBackground(borderColor); saveButton.addMouseListener(this); loadButton = new JLabel("LOAD"); loadButton.setOpaque(true); loadButton.setForeground(backgroundColor); loadButton.setBackground(borderColor); loadButton.addMouseListener(this); lifeBot1 = new JLabel("Player 1 Health: 5/5"); lifeBot1.setForeground(borderColor); lifeBot1.setVisible(false); lifeBot2 = new JLabel("Player 2 Health: 5/5"); lifeBot2.setForeground(borderColor); lifeBot2.setVisible(false); JPanel containerPanel = new JPanel(); containerPanel.setBackground(backgroundColor); containerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(borderColor, borderWidth+2)); innerBoxes = new GridSquare[xDim][yDim]; for (int x = 0; x < yDim; x++) { for (int y = 0; y < xDim; y++) { GridSquare box = new GridSquare(x,y); box.setName(x + " " + y); box.addMouseListener(this); box.setBorder(javax.swing.BorderFactory.createLineBorder(borderColor, borderWidth)); box.setBackground(backgroundColor); javax.swing.GroupLayout innerBoxLayout = new javax.swing.GroupLayout(box); box.setLayout(innerBoxLayout); innerBoxLayout.setHorizontalGroup( innerBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, boxDimensions, Short.MAX_VALUE) ); innerBoxLayout.setVerticalGroup( innerBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, boxDimensions, Short.MAX_VALUE) ); innerBoxes[y][x] = box; } } obstacles = new boolean[xDim][yDim]; transObstacles = new int[xDim][yDim]; javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(containerPanel); containerPanel.setLayout(jPanel1Layout); ParallelGroup horizontalGroup = jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING); for (int x = 0; x < yDim; x++) { SequentialGroup sequentialGroup = jPanel1Layout.createSequentialGroup(); for (int y = 0; y < xDim; y++) { JPanel box = innerBoxes[y][x]; sequentialGroup.addComponent(box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE); if (y != xDim) { sequentialGroup.addContainerGap(gap, Short.MAX_VALUE); } } horizontalGroup.addGroup(sequentialGroup); } jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(horizontalGroup) .addContainerGap())); SequentialGroup verticalGroup = jPanel1Layout.createSequentialGroup().addContainerGap(); for (int x = 0; x < yDim; x++) { ParallelGroup sequentialGroup = jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING); for (int y = 0; y < xDim; y++) { JPanel box = innerBoxes[y][x]; sequentialGroup.addComponent(box, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE); } verticalGroup.addGroup(sequentialGroup); if (x == yDim) { verticalGroup.addContainerGap(10, Short.MAX_VALUE); } else { verticalGroup.addContainerGap(gap, Short.MAX_VALUE); } } jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(verticalGroup)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(score) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(lifeBot1) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(lifeBot2) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(labelPencil) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(labelLine) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(labelSquare) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(saveButton) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(10) .addComponent(loadButton) .addGap(20) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(title)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(title) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(containerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGap(40) .addComponent(score) .addGap(20) .addComponent(lifeBot1) .addComponent(lifeBot2)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGap(40) .addComponent(score) .addGap(20) .addComponent(labelPencil) .addGap(5) .addComponent(labelLine) .addGap(5) .addComponent(labelSquare) .addGap(20) .addComponent(saveButton) .addGap(5) .addComponent(loadButton)) ); pack(); }
8
private HttpURLConnection getFetchConnection(WebThumbFetchRequest webThumbFetchRequest) throws WebThumbException { Validate.notNull(webThumbFetchRequest, "webThumbFetchRequest is null!"); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Attempting to send webThumbFetchRequest: " + webThumbFetchRequest); } WebThumb webThumb = new WebThumb(apikey, webThumbFetchRequest); try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("webThumbFetchRequest sent. Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Content type: " + contentType); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException("Server side error: " + IOUtils.toString(connection.getInputStream())); } return connection; } else if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { WebThumbResponse webThumbResponse = SimpleXmlSerializer.parseResponse(connection.getErrorStream(), WebThumbResponse.class); throw new WebThumbException("Server side error: " + webThumbResponse.getError().getValue()); } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }
7
@Override public void startTransfer() throws TransferException { Runnable readRunner = new Runnable() { public void run() { try { logger.debug("Socket ready for read.. " + socket); logger.debug("Local port:" + socket.getLocalSocketAddress().toString()); // 初始化缓冲区和一些变量 byte[] buff = new byte[1024]; int len = 0; // 循环读取数据,直到遇到流的末尾,或者用户主动关闭连接 // 注意这里不能在stopTransfer里只改变关闭标志而不关闭流,否则会在reader.read()方法阻塞掉,即是中断线程也没用 // 线程在阻塞读取数据时是不能中断的,只能强制关闭流,阻塞的reader.read()方法就会立即抛出IO异常,就可以结束读线程 while (true) { len = reader.read(buff, 0, buff.length); // 这里还需要判断是否读取到流的末尾,否则会进入死循环,通常返回-1表示流的结尾 // 如果读取到结尾,表明是服务器主动关闭了连接,抛出这个异常,通知上层做资源清理工作 if (len == -1) { logger.debug("Connection closed by server.." + socket); raiseException(new TransferException( "Connection closed by server. " + socket)); break; } else { bytesRecived(buff, 0, len); } } } catch (IOException e) { // 当发生IO异常时可能是网络出现问题,也可能是用户关闭了连接,这里需要判断下 if (!userCloseFlag) { logger.warn("Connection error.. " + socket); raiseException(new TransferException(e)); } else { logger.debug("Connection closed by user.." + socket); } } // 程序执行到这里,表明流已经读取完毕,可能是服务器主动关闭了连接,或者用户关闭了连接 // 如果是服务器关闭了连接,这里就需要关闭流,如果是用户关闭了流,就什么也不做,因为在stopTranfer方法中就已经关闭了 if (!userCloseFlag) { userCloseFlag = true; try { writer.close(); reader.close(); } catch (IOException e) { logger.warn("Close socket stream failed.. " + socket, e); } } } }; readThread = new Thread(readRunner); readThread.setName(getTransferName()); readThread.start(); }
6
public EncryptCezar(String text, int k) { this.k = k; String input = text; StringBuilder output = new StringBuilder(); for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); if (isEnglish(c)) { int y = (findInEnglish(c) + k) % nEng; if (Character.isUpperCase(c)) { output.append(engslish[y]); } else { output.append(Character.toLowerCase(engslish[y])); } continue; } if (isRussian(c)) { int y = (findInRussian(c) + k) % nRus; if (Character.isUpperCase(c)) { output.append(russian[y]); } else { output.append(Character.toLowerCase(russian[y])); } continue; } if (!isEnglish(c) && !isRussian(c)) { output.append(c); } } this.output = output.toString(); }
7
@Test public void testConstructor_IllegalArgumentException() { boolean exceptionThrown = false; try { new PaymentResponse(null, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 256, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, null, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.FAILURE, null, "buyer", "seller", Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "", "seller", Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", null, Currency.BTC, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", null, 12, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 0, System.currentTimeMillis()); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; try { new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, "buyer", "seller", Currency.BTC, 12, 0); } catch (IllegalArgumentException e) { exceptionThrown = true; } assertTrue(exceptionThrown); exceptionThrown = false; }
9
public int size( ) { return manyItems; }
0
public static void main(String[] args) { try { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File(ClassLoader.getSystemResource(runXMLAUTHORITY).getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); for (String warning : warnings) { System.out.println("Warning:" + warning); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6
public static CardCombination getSameCardsOrHighestCard( ArrayList<Card> tempHandCards) { CardCombinationEnum cardCombinationEnum = null; // Sort the given hand cards just to be sure that the order is correct sortHand(tempHandCards); // Make a copy of the list, so that the given list can be manipulated ArrayList<Card> clonedHandCards = (ArrayList<Card>) tempHandCards .clone(); ArrayList<Card> sameCards = new ArrayList<Card>(); // Avoid null pointers if (clonedHandCards != null && clonedHandCards.size() >= 1) { Card currentCard = clonedHandCards.get(0); sameCards.add(currentCard); // Remove the element from the original list, because it is handled // now tempHandCards.remove(currentCard); // Compare the values of the next cards until they differ for (int j = 1; j < clonedHandCards.size(); j++) { Card nextCard = clonedHandCards.get(j); if (nextCard.getCardValue() == currentCard.getCardValue()) { // Add the card to the same card pool sameCards.add(clonedHandCards.get(j)); // Remove the just analyzed and handled card from the // original list tempHandCards.remove(nextCard); } } } switch (sameCards.size()) { case 1: cardCombinationEnum = CardCombinationEnum.HIGHEST_CARD; break; case 2: cardCombinationEnum = CardCombinationEnum.ONE_PAIR; break; case 3: cardCombinationEnum = CardCombinationEnum.THREE_OF_A_KIND; break; case 4: cardCombinationEnum = CardCombinationEnum.FOUR_OF_A_KIND; break; } return new CardCombination(cardCombinationEnum, sameCards); }
8
public static void main(String[] args) { int max = (int)(6*Math.pow(9, P)); ArrayList<Integer> ans = new ArrayList<Integer>(); for(int i = 2; i < max; i++) { int x = i; ArrayList<Integer> digits = getDigits(i); while( digits.size() > 0 && x >= 0 ) x -= Math.pow(digits.remove(digits.size()-1), P); if(x == 0 && digits.size() == 0) ans.add(i); } int sum = 0; for(Integer num : ans) sum += num; System.out.println(sum); }
6
public void borrarRegistrosIndice(String nombreTabla,String indice, int id) { try { this.bd.open(); this.table = this.bd.getTable(nombreTabla); this.bd.beginTransaction(SqlJetTransactionMode.WRITE); // Esta función busca por calve primaria aquel id que concuerde con el pasado por el usuario this.cursor = table.lookup(indice,id); // Mientras no sea fin del cursor while (!this.cursor.eof()) { // Elimina la clave buscada y sus datos asociados this.cursor.delete(); } this.cursor.close(); this.bd.commit(); this.bd.close(); } catch (SqlJetException ex) { Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex); } }
2
public BaseMethodPanel(JFrame frame, QueryDefinition query, T instance) throws MalformedURLException { super(false); this.frame = frame; this.query = query; this.query.setRequest(instance); try { this.setName(query.getName()); this.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); this.id = new JTextField(); this.id.setText(query.getId()); this.id.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent arg0) { try { String id = BaseMethodPanel.this.id.getText(); BaseMethodPanel.this.query.setId(id.trim()); stateChanged(null); } catch (Exception e1) { logger.error("Error updating query id.", e1); } } @Override public void insertUpdate(DocumentEvent arg0) { changedUpdate(arg0); } @Override public void removeUpdate(DocumentEvent arg0) { changedUpdate(arg0); } }); panel.add(new JLabel("Query Id:"), BorderLayout.WEST); panel.add(this.id, BorderLayout.CENTER); add(panel, BorderLayout.NORTH); this.views = new JTabbedPane(); this.views.setTabPlacement(JTabbedPane.LEFT); this.requestView = new XmlViewer(false, query.getDocument(), getRequestValidator()); this.responseView = new XmlViewer(true, null, getResponseValidator(), query); this.views.addTab("Request", this.requestView); this.views.addTab("Response", this.responseView); this.views.addChangeListener(this); add(this.views, BorderLayout.CENTER); panel = new JPanel(); panel.setLayout(new BorderLayout()); this.executeBtn = new JButton("Execute"); panel.add(this.executeBtn, BorderLayout.WEST); this.executeBtn.addActionListener(this); add(panel, BorderLayout.SOUTH); } catch (Exception e) { System.err.println(Utilities.getStackTrace(e)); JOptionPane.showMessageDialog(this, Utilities.getStackTrace(e), e.getMessage(), JOptionPane.ERROR_MESSAGE); } }
2
public static void main(String[] args) throws URISyntaxException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); TestAlgorithm test = new TestAlgorithm(); try { System.out.println("Please enter algorithm name, file name and minimal support level, separate by space."); String input = br.readLine(); if (input != null){ String[] cmd = input.split(" "); if(cmd !=null && cmd.length == 3 && Integer.valueOf(cmd[2]) != null){ String method = cmd[0]; test.setAlgorithm(method); List<List<String>> dataList = test.fetchDataList(cmd[1]); test.setUp(dataList, Integer.valueOf(cmd[2])); test.run(); test.finish(); System.out.println("The frequency sets are following(size "+test.getFrequencySets().size()+"):"); for (TreeSet<String> set : test.getFrequencySets()){ System.out.println("Set:"); for(String s : set){ System.out.print(s+" "); } System.out.println(); } } } } catch (IOException e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
8
public String[][] execSelectQuery(String pSQL){ String SQL = pSQL; try{ Statement stmt = this.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery(SQL); rs.last(); int columns = rs.getMetaData().getColumnCount(); int rows = rs.getRow(); //System.out.println(rows + " " + columns); rs.beforeFirst(); if(columns > 1 && rows > 0){ this.results = new String[rows][columns]; while(rs.next()){ for(int i = 1; i <= columns; i++){ results[rs.getRow()-1][i-1] = rs.getString(i); //System.out.println(rs.getString(i)); } } }else if(columns == 1 && rows > 0){ this.results = new String[rows][1]; while(rs.next()){ results[rs.getRow()-1][0] = rs.getString(1); //System.out.println(rs.getString(1)); } } }catch(SQLException e){ System.out.println(e.getMessage()); } return this.results; }
8
private Set<Card> sixFlushWithStraight() { return convertToCardSet("JS,4S,8S,3S,9S,TS,7H"); }
0
public void askClientConnectionToServer(String clientId) { try { getLogger().info("Demande d'information client : " + clientId); // On recherche si on a déjà démarré un dialogue avec le client. boolean alreadyDone = false; for (ClientDialog dialog : this.dialogs) { if (dialog.getClients().size() == 1 && dialog.getClients().get(0).getId().equals(clientId)) { alreadyDone = true; // Si la conversation existe et que on souhaite en démarrer // une c'est quelle est simplement cachée // alors on la remet en fonction dialog.setInUse(true); } } // Si aucun dialog n'a été demarrer if (!alreadyDone) { this.launchThread(); Thread.sleep(500); // On demande les informations du client this.threadComunicationClient.getClientConnection(clientId); int cpt = 0; int sizeClients = this.getClients().size(); // On attend de les recevoir while (cpt < 500 && this.getClients().size() == sizeClients) { Thread.sleep(200); cpt++; } // Si on les a bien reçu on démarre une conversation if (this.getClients().size() != sizeClients) { this.startDialogToClient(this.getClients().get(this.getClients().size() - 1)); } } } catch (InterruptedException e) { getLogger().severe("Erreur de demande d'information client du client au serveur, message : " + e.getMessage()); } }
8
public void setPcaGenerico(Integer pcaGenerico) { this.pcaGenerico = pcaGenerico; }
0
public BlockMap(String ref)throws SlickException{ entities = new ArrayList<Object>(); tmap = new TiledMap(ref, "res"); mapWidth = tmap.getWidth() * tmap.getTileWidth(); mapHeight = tmap.getHeight() * tmap.getTileHeight(); for(int x = 0; x < tmap.getWidth(); ++x) { for(int y = 0; y < tmap.getHeight(); ++y) { int tileID = tmap.getTileId(x, y, 0); if(tileID == 1) { entities.add(new Block(x * 16, y * 16, square, "square")); } } } }
3
public void create_idx( String idxFileName, String indexOnKeyString ) { if(isReadOnly()) return; if(canIfNoCdx()) { order = "[idx]"; Idx = new idx(); try { Idx.fidx = new RandomAccessFile( new File( g_idxname(idxFileName) ), fmode()); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { Idx.fidx.setLength(0); } catch (IOException e) { e.printStackTrace(); } Idx.keyString = indexOnKeyString.toUpperCase().trim(); Idx.forString = ""; // to obtain key length // be careful if self written PREPARE_KEY_FROM_DATA( Idx ); int keyLen = Idx.searchKey.length; Idx.writeHeaderToEmptyFile( keyLen ); try { Idx.fidx.close(); } catch (IOException e) { e.printStackTrace(); } set_order_to_idx( idxFileName ); } }
5
public static HashMap<Integer, Double> getFinalScores(List<TestResult> results){ HashMap<Integer, PriorityQueue<Integer> > id_scores = new HashMap<Integer, PriorityQueue<Integer> >(); for(TestResult res : results) { PriorityQueue<Integer> queue = null; if(id_scores.containsKey( res.studentId ) ) { queue = id_scores.get(res.studentId); } else { queue = new PriorityQueue<Integer>(5); } if (queue.size() < res.score) queue.add(res.score); else { if (res.score > queue.peek()) { queue.poll(); queue.add(res.score); } } id_scores.put(res.studentId, queue); } HashMap<Integer, Double> averages = new HashMap<Integer,Double>(); for(int key : id_scores.keySet()) { PriorityQueue<Integer> queue = id_scores.get(key); double avg = 0; if (queue.size() >= 5) { for(int i=0; i<5 ; i++) avg += queue.poll(); avg /= 5; averages.put(key, avg); } else { int j = queue.size(); for(int i=0; i<j ; i++) avg += queue.poll(); avg /= j; averages.put(key, avg); } } return averages; }
8
public static void print(Vector<MP3> sublist) { for (Iterator<MP3> it = sublist.iterator(); it.hasNext();) { MP3 s = it.next(); System.out.println(s.getPath()); } }
1
private String decode999( int num ) { String s = ""; // work out hundreds : numbers 100-900 int n = num % 1000; // extract the first 3 digits from num if ( n >=100 ) s += units[ n / 100 ] + " hundred"; if ( n>=100 && n % 100 != 0 ) s+= " and "; // numbers 1-99 n = num % 100; // extract the first 2 digits from num if ( n < 10 ) s+= units[ n % 10 ]; // special case numbers 11-19 if ( n >= 11 && n <=19 ) s+= teens[ n % 10 ]; // everything else if ( n==10 || n>=20 ) { s += tens[ (n/10) % 10 ]; if ( n % 10 != 0 ) s += " " + units[ n % 10 ]; } return s; }
9
public boolean update(Prestamos p){ PreparedStatement ps; try { ps = mycon.prepareStatement( "UPDATE Prestamos "+ "SET fecha=?, estado=?, id_libro=?, id_usuario=? "+ "WHERE id=?" ); ps.setDate(1, p.getFecha()); ps.setString(2, p.getEstado()); ps.setString(3, p.getIdLibro()); ps.setString(4, p.getIdUsuario()); ps.setInt(5, p.getId()); return (ps.executeUpdate()>0); } catch (SQLException ex) { Logger.getLogger(PrestamosCRUD.class.getName()).log(Level.SEVERE, null, ex); } return false; }
1
private void createTreeView(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; gridLayout.marginHeight = gridLayout.marginWidth = 2; gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0; composite.setLayout(gridLayout); treeScopeLabel = new Label(composite, SWT.BORDER); treeScopeLabel.setText(FileViewer.getResourceString("details.AllFolders.text")); treeScopeLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL)); tree = new Tree(composite, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE); tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL)); tree.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { final TreeItem[] selection = tree.getSelection(); if (selection != null && selection.length != 0) { TreeItem item = selection[0]; File file = (File) item.getData(TREEITEMDATA_FILE); notifySelectedDirectory(file); } } public void widgetDefaultSelected(SelectionEvent event) { final TreeItem[] selection = tree.getSelection(); if (selection != null && selection.length != 0) { TreeItem item = selection[0]; item.setExpanded(true); treeExpandItem(item); } } }); tree.addTreeListener(new TreeAdapter() { public void treeExpanded(TreeEvent event) { final TreeItem item = (TreeItem) event.item; final Image image = (Image) item.getData(TREEITEMDATA_IMAGEEXPANDED); if (image != null) item.setImage(image); treeExpandItem(item); } public void treeCollapsed(TreeEvent event) { final TreeItem item = (TreeItem) event.item; final Image image = (Image) item.getData(TREEITEMDATA_IMAGECOLLAPSED); if (image != null) item.setImage(image); } }); createTreeDragSource(tree); createTreeDropTarget(tree); }
6
@Override public void setAttenuation( int model ) { super.setAttenuation( model ); // make sure we are assigned to a channel: if( channel != null && channel.attachedSource == this && channelOpenAL != null && channelOpenAL.ALSource != null ) { // attenuation changed, so update the rolloff factor accordingly if( model == SoundSystemConfig.ATTENUATION_ROLLOFF ) AL10.alSourcef( channelOpenAL.ALSource.get( 0 ), AL10.AL_ROLLOFF_FACTOR, distOrRoll ); else AL10.alSourcef( channelOpenAL.ALSource.get( 0 ), AL10.AL_ROLLOFF_FACTOR, 0.0f ); checkALError(); } }
5
@Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String texto = getText(0, getLength()); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!Character.isDigit(c)) { return; } } if (texto.length() < MascaraCurrency.NUMERO_DIGITOS_MAXIMO) { super.remove(0, getLength()); texto = texto.replaceAll("\\.", "").replaceAll(",", ""); StringBuilder s = new StringBuilder(texto + str); if (s.length() > 0) { // Deletar possiveis zeros a esquerda while (s.length() > 0 && s.charAt(0) == '0') { s.deleteCharAt(0); } } // Colocar zeros das casas decimais pelo menos tres caso o campo seja vazio while (s.length() < 3) { s.insert(0, "0"); } s.insert(s.length() - 2, ","); if (s.length() > 6) { s.insert(s.length() - 6, "."); } if (s.length() > 10) { s.insert(s.length() - 10, "."); } super.insertString(0, s.toString(), a); } }
9
public void body() { int resourceID[] = new int[this.totalResource_]; String resourceName[] = new String[this.totalResource_]; LinkedList resList; ResourceCharacteristics resChar; // waiting to get list of resources. Since GridSim package uses // multi-threaded environment, your request might arrive earlier // before one or more grid resource entities manage to register // themselves to GridInformationService (GIS) entity. // Therefore, it's better to wait in the first place while (true) { // need to pause for a while to wait GridResources finish // registering to GIS super.gridSimHold(1.0); // hold by 1 second resList = getGridResourceList(); if (resList.size() == this.totalResource_) break; else { System.out.println(this.name_ + ":Waiting to get list of resources ..."); } } int SIZE = 12; // size of Integer object is roughly 12 bytes int i = 0; // a loop to get all the resources available. // Once the resources are known, then send HELLO and TEST tag to each // of them. for (i = 0; i < this.totalResource_; i++) { // Resource list contains list of resource IDs not grid resource // objects. resourceID[i] = ( (Integer) resList.get(i) ).intValue(); // Requests to resource entity to send its characteristics // NOTE: sending directly without using I/O port super.send(resourceID[i], GridSimTags.SCHEDULE_NOW, GridSimTags.RESOURCE_CHARACTERISTICS, this.ID_); // waiting to get a resource characteristics resChar = (ResourceCharacteristics) receiveEventObject(); resourceName[i] = resChar.getResourceName(); // print that this entity receives a particular resource // characteristics System.out.println(this.name_ + ":Received ResourceCharacteristics from " + resourceName[i] + ", with id = " + resourceID[i]); // send TEST tag to a resource using I/O port. // It will consider transfer time over a network. System.out.println(this.name_ + ": Sending TEST tag to " + resourceName[i] + " at time " + GridSim.clock()); super.send( super.output, GridSimTags.SCHEDULE_NOW, TEST, new IO_data(this.ID_, SIZE, resourceID[i]) ); // send HELLO tag to a resource using I/O port System.out.println(this.name_ + ": Sending HELLO tag to " + resourceName[i] + " at time " + GridSim.clock()); super.send( super.output, GridSimTags.SCHEDULE_NOW, HELLO, new IO_data(this.ID_, SIZE, resourceID[i]) ); } // need to wait for 10 seconds to allow a resource to process // receiving events. super.sim_pause(10); // shut down all the entities, including GridStatistics entity since // we used it to record certain events. shutdownGridStatisticsEntity(); shutdownUserEntity(); terminateIOEntities(); System.out.println(this.name_ + ":%%%% Exiting body()"); }
3
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Record other = (Record) obj; if (this.recordId != other.recordId) { return false; } if (this.imageId != other.imageId) { return false; } if (this.fieldId != other.fieldId) { return false; } if (this.rowNumber != other.rowNumber) { return false; } if (!Objects.equals(this.value, other.value)) { return false; } return true; }
7
public void setId(long Id) { this.Id = Id; }
0
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: String d = jTextField2.getText(); String id = jTextField1.getText(); String tgl1 = String.valueOf(jTable1.getValueAt(0, 4)); int no = 1; int pers = 0; try { for(int i=0;i<dtm.getRowCount();i++) { try { k.st = k.con.createStatement(); //String tampil = "SELECT * FROM datapengembalian WHERE id_smartcard = '" +id+ "';"; String tampil = "SELECT * FROM datapengembalian;"; k.rs = k.st.executeQuery(tampil); while(k.rs.next()) { no = Integer.parseInt(k.rs.getString("no_trans")); no++; } } catch(Exception e) { JOptionPane.showMessageDialog(rootPane, "Error: " + e); } k.st = k.con.createStatement(); String tambah = "INSERT INTO datapengembalian VALUES('" +no+ "','" +id+ "','" +tgl1+ "','" +tanggal1+ "','" +d+ "');"; k.st.executeUpdate(tambah); JOptionPane.showMessageDialog(rootPane, "Data Berhasil Ditambahkan"); } try { k.st = k.con.createStatement(); String u = "UPDATE peminjaman SET status = 'Kembali' WHERE id_smartcard = '" +id+ "';"; k.st.executeUpdate(u); JOptionPane.showMessageDialog(rootPane, "Data Berhasil Diupdate"); } catch(Exception e) { JOptionPane.showMessageDialog(rootPane, "Error: " +e); } for(int l=0;l<dtm.getRowCount();l++) { try { k.st = k.con.createStatement(); String t = "SELECT * FROM databuku WHERE id_buku = '" +String.valueOf(jTable1.getValueAt(l, 0)) + "';"; k.rs = k.st.executeQuery(t); if(k.rs.next()) { pers = Integer.parseInt(k.rs.getString("persediaan")); } } catch(Exception e) { JOptionPane.showMessageDialog(rootPane, "Error: " +e); } pers++; try { k.st = k.con.createStatement(); String u1 = "UPDATE databuku SET persediaan = '" +pers+ "' WHERE id_buku = '" +String.valueOf(jTable1.getValueAt(l, 0))+ "';"; k.st.executeUpdate(u1); JOptionPane.showMessageDialog(rootPane, "Data Berhasil Diupdate"); } catch(Exception e) { JOptionPane.showMessageDialog(rootPane, "Error: " +e); } } jTextField1.setText(""); jButton2.setEnabled(false); jDateChooser1.setDate(null); jTextField2.setText(""); jButton1.setEnabled(true); jButton3.setEnabled(false); HapusTabel(); } catch(Exception e) { JOptionPane.showMessageDialog(rootPane, "Error: " +e); } }//GEN-LAST:event_jButton3ActionPerformed
9
private boolean inBounds(int y, int x) { return x >= 0 && y >= 0 && x < BOARD_LENGTH && y < BOARD_LENGTH; }
3
@Override public void play(int objectId) { AudioChannel channel = getAudioChannel(objectId); AudioObject object = objects.get(objectId); int source = channel.source; alSourcei(source, AL_BUFFER, object.dataId); alSourcef(source, AL_PITCH, (float) object.pitch); alSourcef(source, AL_GAIN, (float) object.volume); alSourcei(source, AL_LOOPING, object.loop ? AL_TRUE : AL_FALSE); alSourcePlay(source); }
1
int insertKeyRehash(long val, int index, int hash, byte state) { // compute the double hash final int length = _set.length; int probe = 1 + (hash % (length - 2)); final int loopIndex = index; int firstRemoved = -1; /** * Look until FREE slot or we start to loop */ do { // Identify first removed slot if (state == REMOVED && firstRemoved == -1) firstRemoved = index; index -= probe; if (index < 0) { index += length; } state = _states[index]; // A FREE slot stops the search if (state == FREE) { if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } else { consumeFreeSlot = true; insertKeyAt(index, val); return index; } } if (state == FULL && _set[index] == val) { return -index - 1; } // Detect loop } while (index != loopIndex); // We inspected all reachable slots and did not find a FREE one // If we found a REMOVED slot we return the first one found if (firstRemoved != -1) { insertKeyAt(firstRemoved, val); return firstRemoved; } // Can a resizing strategy be found that resizes the set? throw new IllegalStateException("No free or removed slots available. Key set full?!!"); }
9
private int findBaseHeightForLogo(int target, int associationNameLength) { int base = 1; double height = getLogoHeight(associationNameLength, base); while (height < target) { base *= 2; height = getLogoHeight(associationNameLength, base); LOG.debug(String.format("%d --> %f", base, height)); } int delta = base / 4; while (delta >= 1) { if (height > target) { base -= delta; } else if (height < target) { base += delta; } else { break; } delta /= 2; height = getLogoHeight(associationNameLength, base); LOG.debug(String.format("%d --> %f", base, height)); } if (height > target) { double alternate = getLogoHeight(associationNameLength, base - 1); if (Math.abs(alternate - target) < Math.abs(height - target)) base--; } if (height < target) { double alternate = getLogoHeight(associationNameLength, base + 1); if (Math.abs(alternate - target) < Math.abs(height - target)) base++; } LOG.info("Best size: " + base); return base; }
8
protected String getGlobalArchiverFlags() { final StringBuilder builder = new StringBuilder(); if (globalOverrideArchiverFlags == null || globalOverrideArchiverFlags.isEmpty()) { if (parent != null) builder.append(parent.getGlobalArchiverFlags()); else builder.append(config.aflags()); } else { builder.append(globalOverrideArchiverFlags); } if (globalArchiverFlags != null && !globalArchiverFlags.isEmpty()) { if (builder.length() > 0) builder.append(' '); builder.append(globalArchiverFlags); } String dyn = getDynArchiverFlags(); if (!dyn.isEmpty()) { if (builder.length() > 0) builder.append(' '); builder.append(dyn); } return builder.toString(); }
8
public String selectionSortStable(String s) { char[] a = s.toCharArray(); for (int i = 0; i < a.length - 1; i++) { insert(a, i, getMinIndex(a, i)); } return new String(a); }
1
public static EXIT_COMMAND getCommand(String str) { for(EXIT_COMMAND exit: EXIT_COMMAND.values()) { if(exit.cmd.equalsIgnoreCase(str)) { return exit; } } return CONTINUE; }
2
private final String inlineCommentFilter( String line ) { //assert !inJavadocComment; //assert !inMultiLineComment; if ( line == null || line.equals( "" ) ) { return ""; } int index; if ( ( index = line.indexOf( "//" ) ) >= 0 && !isInsideString( line, index ) ) { return new StringBuffer( beginMultiLineCommentFilter( line.substring( 0, index ) ) ) .append( COMMENT_START ) .append( line.substring( index ) ) .append( COMMENT_END ) .toString(); } return beginMultiLineCommentFilter( line ); }
4
public boolean move(Direction direction) throws InvalidMoveException { // Max gameboard positions int left = 0; int top = 0; int bottom = board.length - 1; int right = board[0].length - 1; Tokens temp; switch(direction) { // Move up case UP: if(emptyRow == top) throw new InvalidMoveException("can't move up when at top of board"); temp = board[emptyRow - 1][emptyCol]; board[emptyRow - 1][emptyCol] = Tokens.EMPTY; board[emptyRow][emptyCol] = temp; emptyRow -= 1; moveHistory += "u"; break; // Move down case DOWN: if(emptyRow == bottom) throw new InvalidMoveException("can't move down when at bottom of board"); temp = board[emptyRow + 1][emptyCol]; board[emptyRow + 1][emptyCol] = Tokens.EMPTY; board[emptyRow][emptyCol] = temp; emptyRow += 1; moveHistory += "d"; break; // Move left case LEFT: if(emptyCol == left) throw new InvalidMoveException("can't move left when at left side of board"); temp = board[emptyRow][emptyCol - 1]; board[emptyRow][emptyCol - 1] = Tokens.EMPTY; board[emptyRow][emptyCol] = temp; emptyCol -= 1; moveHistory += "l"; break; // Move right case RIGHT: if(emptyCol == right) throw new InvalidMoveException("can't move right when at right side of board"); temp = board[emptyRow][emptyCol + 1]; board[emptyRow][emptyCol + 1] = Tokens.EMPTY; board[emptyRow][emptyCol] = temp; emptyCol += 1; moveHistory += "r"; break; } // Add the position to the history history += getPosition(); return true; }
8
public long getAverage() { long sum = 0; for (int i = 0; i < duur.size(); i++) { sum += duur.get(i).longValue(); } return sum / duur.size(); }
1
protected HsqlDaoBase(HsqlUnitOfWork uow) { super(uow); try { Connection connection = uow.getConnection(); ResultSet rs = connection.getMetaData().getTables(null, null, null, null); boolean exist = false; stmt =connection.createStatement(); while(rs.next()) { if(rs.getString("TABLE_NAME").equalsIgnoreCase(getTableName())) { exist = true; break; } } if(!exist) { stmt.executeUpdate(getCreateQuery()); } insert = connection.prepareStatement(getInsertQuery()); update = connection.prepareStatement(getUpdateQuery()); delete = connection.prepareStatement("" + "delete from "+getTableName()+" where id=?"); selectId = connection.prepareStatement("" + "select * from "+getTableName()+" where id=?"); select = connection.prepareStatement("" + "select * from "+getTableName()); } catch (SQLException e) { e.printStackTrace(); } }
4
public int getMaxFPS() { return this.maxFPS; }
0
public SquareType getSquareType(Coord c) { int squareValue = mat.getSquareValue(c); if (squareValue == -1) { return SquareType.OUTSIDE; } else if (squareValue == 0) { return SquareType.OBSTACLE; } else if (squareValue == 1) { return SquareType.FREESQUARE; } else if (squareValue >= 10 && squareValue < 30) { return SquareType.DOOR; } else if (squareValue >= 30 && squareValue < 40) { return SquareType.CHEST; } else { assert false : "Square type unknown : " + squareValue; return null; } }
7
@Override public void startSetup(Attributes atts) { JTextArea list = new JTextArea(); list.setRows(4); list.setColumns(15); list.setLineWrap(false); JScrollPane component = new JScrollPane(list); setComponent(component); super.startSetup(atts); list.addFocusListener(new TextAreaListener(list, getPreference())); }
0
private void run() { // repita ate que a lista de algum homem esteja vazia ou todos estejam casados while(!someManListEmpty() && !everyoneEngaged()) { boolean existFreeMan = true; // enquanto existir homem solteiro while(existFreeMan) { Person currentMan = existFreeMan(); if(currentMan != null && currentMan.getPreferences().size() > 0) { List<Person> head = currentMan.getPreferences().get(0); if(head.size() > 0) { for(Person topWoman : head) { if(containsManInPreferences(currentMan, topWoman)) { addMarriage(currentMan, topWoman); checkSuccesorMen(currentMan, topWoman); } } } } else { existFreeMan = false; } } checkMultiplyEngagedMen(); } if(everyoneEngaged()) { System.out.println("solution:"); printResults(); } else { System.out.println("n/a"); } }
9
public void keyPressed(KeyEvent e) { /* Pressing a key in the title screen starts a game */ if (board.titleScreenB) { board.titleScreenB = false; return; } /* Pressing a key in the win screen or game over screen goes to the title screen */ else if (board.winScreenB || board.overScreenB) { board.titleScreenB = true; board.winScreenB = false; board.overScreenB = false; return; } /* Pressing a key during a demo kills the demo mode and starts a new game */ else if (board.demo) { board.demo = false; board.newGame(); return; } /* Otherwise, key presses control the player! */ switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: board.player.desiredDirection = 'L'; break; case KeyEvent.VK_RIGHT: board.player.desiredDirection = 'R'; break; case KeyEvent.VK_UP: board.player.desiredDirection = 'U'; break; case KeyEvent.VK_DOWN: board.player.desiredDirection = 'D'; break; } repaint(); }
8
public BufferedImage greenRGBFilter() { this.greenImage = originalImage; Color actualPixel; int actualRedValue; int actualGreenValue; int actualBlueValue; float numberOfGreenPixels = 0f; for (int i = 0; i < originalImage.getWidth(); i++) { for (int j = 0; j < originalImage.getHeight(); j++) { actualPixel = new Color(originalImage.getRGB(i, j)); actualRedValue = actualPixel.getRed(); actualGreenValue = actualPixel.getGreen(); actualBlueValue = actualPixel.getBlue(); if(actualRedValue < 20 || actualRedValue > 185 || actualGreenValue < 80 || actualGreenValue > 225 || actualBlueValue < 0 || actualBlueValue > 95){ //System.out.println("entro"); greenImage.setRGB(i, j, 0); }else{ numberOfGreenPixels++; } } } float numberOfPixels = originalImage.getTileHeight() * originalImage.getTileWidth(); if ((numberOfGreenPixels / numberOfPixels) > GREEN_MINIMUN) { hasKiwi = true; }else{ hasKiwi = false; } return greenImage; }
9
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Delta other = (Delta) obj; if (original == null) { if (other.original != null) return false; } else if (!original.equals(other.original)) return false; if (revised == null) { if (other.revised != null) return false; } else if (!revised.equals(other.revised)) return false; return true; }
9
private Object fireReceiveQueryEvent(ReceiveQueryEvent evt) throws Exception { try { if (invokeHandler == null) { throw new Exception("InvokeHandler not assigned on server side."); } localConnectionInfo.remove(); localConnectionInfo.set(evt.getConnectionInfo()); return new Reflexia().invoke(invokeHandler, evt.getExecCommand(), evt.getParams()); } catch (Exception exc) { throw new Exception(getName() + ".fireReceiveQueryEvent: " + exc.getMessage()); } }
2
private static void begin() { Scanner sc = new Scanner(System.in); int nTestCases = Integer.parseInt(sc.nextLine()); sc.nextLine(); // process empty line. /* @formatter:off * Decides how to search the word in the matrix. * 0,1 -> horizontally to the right * 1,0 -> vertically to the bottom * 1,1 -> diagonally to the right and bottom * 1,1 -> diagonally to the left and bottom */ // @formatter:on int[][] dirs = {{0, 1}, {1, 0}, {1, 1}, {1, -1}}; for (int t = 0; t < nTestCases; ++t) { int m = sc.nextInt(); int n = sc.nextInt(); sc.nextLine(); // Read in the characters. char[][] matrix = new char[m + 1][n + 1]; for (int r = 1; r <= m; ++r) { String line = sc.nextLine().toLowerCase(); for (int c = 1; c <= n; ++c) { matrix[r][c] = line.charAt(c - 1); } } int nWords = Integer.parseInt(sc.nextLine()); StringBuilder testCaseOutput = new StringBuilder(); // Read in the words and find its best position. while (--nWords >= 0) { String word = sc.nextLine().toLowerCase(); List<Pos> positions = new LinkedList<Pos>(); for (int dir[] : dirs) { Pos pos = searchWord(matrix, word, dir[0], dir[1]); if (pos != null) { positions.add(pos); } } // Store the best position of the word. if (positions.size() > 0) { Collections.sort(positions); testCaseOutput.append(positions.get(0)).append("\n"); } } // Output the best positions of the words. if (testCaseOutput.length() > 0) { System.out.print(testCaseOutput); } if (t < nTestCases - 1) { System.out.println(); sc.nextLine(); // process the empty line } } }
9
@Override public boolean equals(Object o) { if(o == null) return false; if(o == this) return true; if(!(o instanceof Angebot)) return false; Angebot a = (Angebot)o; if(a.getKundeNr()!= kundeNr || a.getNr() != nr || a.getPreis() != preis || a.getBauteilNr() != bauteilNr) return false; if(!a.getGueltigAb().equals(getGueltigAb())) return false; if(!a.getGueltigBis().equals((getGueltigBis()))) return false; return true; }
9
@Override public int compareTo(Node o) { if (this.evaluation > o.evaluation) { return 1; } else if (this.evaluation < o.evaluation) { return -1; } else { return 0; } }
2
private void generateWorld() { int initSize = 10; for(int j = initSize/(-2); j < initSize/2.0; j++) { for (int k = initSize/(-2); k < initSize/2.0; ++k) { chunkLoader.queueLoad(new Point(k, j)); } } }
2
public boolean inCheck(Player player) { // Is player's king in check? return this.fieldInCheck(this.getKingField(player), player); }
0
protected ArrayList<Coordinate> takeMove(Coordinate xy) { boolean test = false; if (test || m_test) { System.out.println("Othello :: takeMove() BEGIN"); } /* if (!isValidMove(xy)) { throw new IllegalStateException( "Given move is invalid but should be valid"); } */ // In each direction, capture the opposing player's pieces if it is // bound by two of this player's pieces. // A list of changed/captured pieces to return ArrayList<Coordinate> capture = new ArrayList<Coordinate>(); // "Capture" the current piece capture.add(xy); // Capture pieces in each direction capture.addAll(take(xy, -1, 0)); // left capture.addAll(take(xy, +1, 0)); // right capture.addAll(take(xy, 0, -1)); // up capture.addAll(take(xy, 0, +1)); // down capture.addAll(take(xy, -1, -1)); // top-left capture.addAll(take(xy, +1, -1)); // top-right capture.addAll(take(xy, -1, +1)); // bottom-left capture.addAll(take(xy, +1, +1)); // bottom-right if (test || m_test) { System.out.println("Othello :: takeMove() END"); } return capture; }
4
protected void loadFields(com.sforce.ws.parser.XmlInputStream __in, com.sforce.ws.bind.TypeMapper __typeMapper) throws java.io.IOException, com.sforce.ws.ConnectionException { super.loadFields(__in, __typeMapper); __in.peekTag(); if (__typeMapper.isElement(__in, Contract__typeInfo)) { setContract((com.sforce.soap.enterprise.sobject.Contract)__typeMapper.readObject(__in, Contract__typeInfo, com.sforce.soap.enterprise.sobject.Contract.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, ContractId__typeInfo)) { setContractId(__typeMapper.readString(__in, ContractId__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedBy__typeInfo)) { setCreatedBy((com.sforce.soap.enterprise.sobject.Name)__typeMapper.readObject(__in, CreatedBy__typeInfo, com.sforce.soap.enterprise.sobject.Name.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedById__typeInfo)) { setCreatedById(__typeMapper.readString(__in, CreatedById__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, CreatedDate__typeInfo)) { setCreatedDate((java.util.Calendar)__typeMapper.readObject(__in, CreatedDate__typeInfo, java.util.Calendar.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, Field__typeInfo)) { setField(__typeMapper.readString(__in, Field__typeInfo, java.lang.String.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, IsDeleted__typeInfo)) { setIsDeleted((java.lang.Boolean)__typeMapper.readObject(__in, IsDeleted__typeInfo, java.lang.Boolean.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, NewValue__typeInfo)) { setNewValue((java.lang.Object)__typeMapper.readObject(__in, NewValue__typeInfo, java.lang.Object.class)); } __in.peekTag(); if (__typeMapper.isElement(__in, OldValue__typeInfo)) { setOldValue((java.lang.Object)__typeMapper.readObject(__in, OldValue__typeInfo, java.lang.Object.class)); } }
9
public void mouseClicked(MouseEvent e) { if (e.getSource() == cur) { int s = 20; int f1 = 8; int f2 = f1 + (int) (s * 0.6); Rectangle lRect = new Rectangle(f1, f1, s, s); Rectangle rRect = new Rectangle(f2, f2, s, s); if (lRect.contains(e.getPoint())) { Color c = JColorChooser.showDialog(null,Resources.getString("Palette.LEFT_COLOR"),left); if (c != null) setLeft(c); } else if (rRect.contains(e.getPoint())) { Color c = JColorChooser.showDialog(null,Resources.getString("Palette.RIGHT_COLOR"),right); if (c != null) setRight(c); } } }
5
public HelloWorldOGL() throws Exception { world = new World(); world.setAmbientLight(0, 255, 0); TextureManager.getInstance().addTexture("box", new Texture("box.jpg")); box = Primitives.getBox(13f, 2f); box.setTexture("box"); box.setEnvmapped(Object3D.ENVMAP_ENABLED); box.build(); world.addObject(box); world.getCamera().setPosition(50, -50, -5); world.getCamera().lookAt(box.getTransformedCenter()); }
0
public void ordena() { for (int i=0; i<cads.length - 1; i++) { for (int j=0; j<cads.length-1-i; j++) { if (cads[j].compareTo(cads[j+1]) > 0) { String aux = cads[j]; cads [j] = cads [j+1]; cads [j+1] = aux; } } } }
3
public void addAll(IntTreeBag addend){ IntBTNode addroot; if(addend == null){ throw new IllegalArgumentException(" bag is empty"); } if(root == addend.root){ addroot = IntBTNode.treeCopy(addend.root); addTree(addroot); }else{ addTree(addend.root); } }
2
public Set getClassNames() { HashSet result = new HashSet(); LongVector v = items; int size = numOfItems; for (int i = 1; i < size; ++i) { String className = ((ConstInfo) v.elementAt(i)).getClassName(this); if (className != null) result.add(className); } return result; }
2
private synchronized void defaultSend(Sim_event ev, int gisID, int statID, int shutdownID) { IO_data io = (IO_data) ev.get_data(); int destId = io.getDestID(); /***** // DEBUG info System.out.println(super.get_name() + ".defaultSend(): Send to " + GridSim.getEntityName(destId) + " tag = " + ev.get_tag() ); *****/ // if this entity uses a network extension if (link_ != null && destId != gisID && destId != statID && destId != shutdownID) { submitToLink(ev); return; } // Identify ID of an entity which acts as Input/Buffer // entity of destination entity int id = GridSim.getEntityId( "Input_" + Sim_system.get_entity(destId).get_name() ); // Send first and then hold super.sim_schedule(id, GridSimTags.SCHEDULE_NOW, ev.get_tag(), io); double receiverBaudRate = ( (Input) Sim_system.get_entity(id) ).getBaudRate(); // NOTE: io is in byte and baud rate is in bits. 1 byte = 8 bits // So, convert io into bits double minBaudRate = Math.min(baudRate_, receiverBaudRate); double communicationDelay = GridSimRandom.realIO( (io.getByteSize() * NetIO.BITS) / minBaudRate); // NOTE: Below is a deprecated method for SimJava 2 //super.sim_hold(communicationDelay); super.sim_process(communicationDelay); }
4
private void processFile() { if(settings.cur_processor != null) { processFileExternal(); } }
1
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ if(cmd.getName().equalsIgnoreCase("uhc")) { if (args.length == 0) { if (!sender.isOp()) { sender.sendMessage(ChatColor.BOLD + "" + ChatColor.RED + "UltraHardcore: " + ChatColor.RESET + "Custom coded for ThePark"); return true; } else { sender.sendMessage("UHC Admin Command Help"); sender.sendMessage("/uhc startgame - Starts the game currently running on the server."); return true; } } else if (args.length == 1) { if (args[0].equalsIgnoreCase("startgame")) { if(!sender.isOp()) { return false; } else if(UHC.getState() == GameState.IN_PROGRESS) { sender.sendMessage(ChatColor.GOLD + "The game is already in progress!"); } else { UHC.startGame(); return true; } } } } return false; }
7
private JsonParser moveToPath(String json, String path) { try { JsonFactory f = new MappingJsonFactory(createMapper()); JsonParser jp = f.createJsonParser(json); jp.nextToken(); //go to start_object if (path == null) return jp; String pathParts[]; if (path.contains(".")) { pathParts = path.split("\\."); } else { pathParts = new String[]{path}; } for (String pathPart : pathParts) { boolean foundPart = findField(jp, pathPart); if (!foundPart) throw new DeserializationException("Cannot find path " + path); } jp.nextToken(); //move into object or array return jp; } catch (Exception e) { throw new DeserializationException(e); } }
5
protected void controlMovement() { // Reset movement speed speedModifier = 1f; // Basic "run" actions // Modify the entity's movement speed by 150% if(Keybind.RUN.held()) { speedModifier = 1.5f; } // Fire a movement event on the player if any movement key presses have occured if(Keybind.movement()) { entity.fireEvent(new MoveEvent((Vector3f) new Vector3f(Keybind.RIGHT.press() ? 1f : Keybind.LEFT.press() ? -1f : 0f, Keybind.UP.press() ? -1f : Keybind.DOWN.press() ? 1f : 0f, 0f).scale(speed * speedModifier))); } }
6
public void start() { // A new thread pool is created... ThreadPoolExecutor executor = testThreadPoolExecutorService .createNewThreadPool(); executor.allowCoreThreadTimeOut(true); // Created executor is set to ThreadPoolMonitorService... threadPoolMonitorService.setExecutor(executor); // ThreadPoolMonitorService is started... Thread monitor = new Thread(threadPoolMonitorService); monitor.start(); // New tasks are executed... for (int i = 1; i < 10; i++) { executor.execute(new TestTask("Task" + i)); } try { Thread.sleep(40000); } catch (Exception e) { log.error(e.getMessage()); } for (int i = 10; i < 19; i++) { executor.execute(new TestTask("Task" + i)); } // executor is shutdown... executor.shutdown(); }
3
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(VueMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VueMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VueMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VueMenu.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 VueMenu().setVisible(true); } }); }
6
public Set<OneMutation> loadMutationList(String fName, int numMutable, boolean PEMcomp) { BufferedReader bufread = null; try { File file = new File(fName); FileReader fr = new FileReader(file); bufread = new BufferedReader(fr); } catch (FileNotFoundException e) { System.out.println(" ... no mutation list file found. Computing one."); return(null); } boolean done = false; String str = null; int resultNum = 0; Set<OneMutation> mutList = new TreeSet<OneMutation>(); while (!done) { try { str = bufread.readLine(); } catch ( Exception e ){ System.out.println("ERROR: An error occurred while reading input"); System.exit(0); } if (str == null) // stop if we've reached EOF done = true; else { if (PEMcomp) {//PEM computation OneMutation tmp = new OneMutation(); //mutList[resultNum] = new OneMutation(); //mutList[resultNum].resMut = new int[numMutable]; tmp.resMut = new int[numMutable]; for(int q=0;q<numMutable;q++) tmp.resMut[q] = new Integer(getToken(str,1+q)).intValue(); tmp.flagMutType = getToken(str,1+numMutable); mutList.add(tmp); } else {//mutation search OneMutation tmp = new OneMutation(); //mutList[resultNum] = new OneMutation(); tmp.score = new BigDecimal(getToken(str,1)); tmp.vol = new Double(getToken(str,2)).doubleValue(); tmp.resTypes = new String[numMutable]; for(int q=0;q<numMutable;q++) { tmp.resTypes[q] = getToken(str,3+q); } mutList.add(tmp); } resultNum++; /*if (resultNum >= mutList.length){ OneMutation newArray[] = new OneMutation[mutList.length+1000]; System.arraycopy(mutList,0,newArray,0,resultNum); mutList = newArray; }*/ } } // We're done reading them in try { bufread.close(); } catch(Exception e) {} // Resize completed mutation array /*OneMutation temp[] = new OneMutation[resultNum]; System.arraycopy(mutList,0,temp,0,resultNum); mutList = temp;*/ System.out.println(" ... read "+mutList.size()+" mutations from mutation list "+fName); return(mutList); }
8
public void run() { try { long outSize = 0; if (LzmaOutputStream.LZMA_HEADER) { final int n = in.read(props, 0, propSize); if (n != propSize) { throw new IOException("input .lzma file is too short"); } dec.SetDecoderProperties(props); for (int i = 0; i < 8; i++) { final int v = in.read(); if (v < 0) { throw new IOException("Can't read stream size"); } outSize |= (long) v << 8 * i; } } else { outSize = -1; dec.SetDecoderProperties(props); } if (DEBUG) { dbg.printf("%s begins%n", this); } dec.Code(in, out, outSize); if (DEBUG) { dbg.printf("%s ends%n", this); } in.close(); // ? } catch (final IOException _exn) { exn = _exn; if (DEBUG) { dbg.printf("%s exception: %s%n", this, exn.getMessage()); } } // close either way, so listener can unblock try { out.close(); } catch (final IOException _exn) { } }
9
public boolean equals(Object o) { if (o instanceof Key) { Key k = (Key) o; return tag == k.tag && intData == k.intData && objData.equals(k.objData); } return false; }
3