text
stringlengths
14
410k
label
int32
0
9
private void BtGravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtGravarActionPerformed if (camposobrigatoriospreenchidos()) { if (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja realmente Gravar os dados deste funcionário?", "Confirmar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (TfCodigo.getText().equals("")) { enviardados(); if (funcionario.incluir()) msg.Sucesso(LbNotificacao, "Dados do Funcionário gravados com sucesso!"); funcionario.getPessoafis().getPessoa().getTelefone().setCodigopessoa(funcionario.getPessoafis().getPessoa().getCodigo()); funcionario.getPessoafis().getPessoa().getEmail().setCodigopessoa(funcionario.getPessoafis().getPessoa().getCodigo()); JOptionPane.showMessageDialog(null, "Código: " + funcionario.getCodigo() + "\n" + "Funcionário: " + funcionario.getPessoafis().getNome().toUpperCase(), "Informe o Código", JOptionPane.INFORMATION_MESSAGE); for (int i = 0; i < TbTelefone.getRowCount(); i++) { funcionario.getPessoafis().getPessoa().getTelefone().setCodigo(i + 1); funcionario.getPessoafis().getPessoa().getTelefone().setNrtelefone(TbTelefone.getValueAt(i, 1).toString()); funcionario.getPessoafis().getPessoa().getTelefone().setTipotelefone(TbTelefone.getValueAt(i, 2).toString()); funcionario.getPessoafis().getPessoa().getTelefone().incluir(); } for (int i = 0; i < TbEmail.getRowCount(); i++) { funcionario.getPessoafis().getPessoa().getEmail().setCodigo(i + 1); funcionario.getPessoafis().getPessoa().getEmail().setEmail(TbEmail.getValueAt(i, 1).toString()); funcionario.getPessoafis().getPessoa().getEmail().setTipoemail(TbEmail.getValueAt(i, 2).toString()); funcionario.getPessoafis().getPessoa().getEmail().incluir(); } limpar.Limpar(PnCadastro); limpar.Limpar(TbTelefone); limpar.Limpar(TbEmail); TfNrCPFKeyReleased(null); valida.validacamposCancelar(PnCadastro, PnBotoes); } else { funcionario.setCodigo(Integer.parseInt(TfCodigo.getText())); funcionario.getPessoafis().getPessoa().setCodigo(funcionario.retornacodigopessoafuncionario()); enviardados(); if(funcionario.alterar()) msg.Sucesso(LbNotificacao, "Dados do Funcionário alterados com sucesso!"); funcionario.getPessoafis().getPessoa().getTelefone().setCodigopessoa(funcionario.getPessoafis().getPessoa().getCodigo()); funcionario.getPessoafis().getPessoa().getEmail().setCodigopessoa(funcionario.getPessoafis().getPessoa().getCodigo()); funcionario.getPessoafis().getPessoa().getTelefone().deletartelefones(); funcionario.getPessoafis().getPessoa().getEmail().deletaremails(); for (int i = 0; i < TbTelefone.getRowCount(); i++) { funcionario.getPessoafis().getPessoa().getTelefone().setCodigo(i + 1); funcionario.getPessoafis().getPessoa().getTelefone().setNrtelefone(TbTelefone.getValueAt(i, 1).toString()); funcionario.getPessoafis().getPessoa().getTelefone().setTipotelefone(TbTelefone.getValueAt(i, 2).toString()); funcionario.getPessoafis().getPessoa().getTelefone().incluir(); } for (int i = 0; i < TbEmail.getRowCount(); i++) { funcionario.getPessoafis().getPessoa().getEmail().setCodigo(i + 1); funcionario.getPessoafis().getPessoa().getEmail().setEmail(TbEmail.getValueAt(i, 1).toString()); funcionario.getPessoafis().getPessoa().getEmail().setTipoemail(TbEmail.getValueAt(i, 2).toString()); funcionario.getPessoafis().getPessoa().getEmail().incluir(); } limpar.Limpar(PnCadastro); limpar.Limpar(TbTelefone); limpar.Limpar(TbEmail); TfNrCPFKeyReleased(null); valida.validacamposCancelar(PnCadastro, PnBotoes); } } } }//GEN-LAST:event_BtGravarActionPerformed
9
@Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { final MOB target=mob; if(mob.isInCombat()) { mob.tell(L("You can't meditate while in combat!")); return false; } if(!CMLib.flags().isSitting(mob)) { mob.tell(L("You must be in a sitting, restful position to meditate.")); return false; } if(target.fetchEffect(ID())!=null) { mob.tell(L("You are already meditating!")); return false; } // now see if it worked final boolean success=proficiencyCheck(mob,0,auto); if(success) { invoker=mob; final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_OK_VISUAL|(auto?CMMsg.MASK_ALWAYS:0),auto?"":L("<S-NAME> begin(s) to meditate...")); if(mob.location().okMessage(mob,msg)) { mob.location().send(mob,msg); beneficialAffect(mob,mob,asLevel,Ability.TICKS_FOREVER); helpProficiency(mob, 0); } } else return beneficialVisualFizzle(mob,target,L("<S-NAME> attempt(s) to meditate, but lose(s) concentration.")); // return whether it worked return success; }
7
public void setName(String name) { Name = name; }
0
private void getSaisie(boolean decrypt) { ISaisie s=new Saisie(this.menu,decrypt,this); while(s.estEnCours() && !this.stop) { try { Thread.sleep(100); } catch (InterruptedException e) { } } s.masquer(); if(!this.stop) { this.key=s.getKey(); this.m=s.getMessage(); this.typeCode=s.getTypeCode(); if(decrypt) { this.res=Interface.decrypter(this.m, this.typeCode, this.key); s.liberer(); s=null; this.enregistrer("dcrypt"); } else { this.res=Interface.crypter(this.m, this.typeCode, this.key); s.liberer(); s=null; this.enregistrer("crpyt"); } } else { this.stop=false; s.liberer(); s=null; this.action(); } }
5
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); result = prime * result + ((startDate == null) ? 0 : startDate.hashCode()); result = prime * result + ((carType == null) ? 0 : carType.hashCode()); return result; }
3
public void Show() { System.out.print("["); for (int i = 0; i < _ListaDeObjetos.size(); i++) { if(_ListaDeObjetos.get(i) != null) { System.out.print(_ListaDeObjetos.get(i).getNombre()); if(i + 1 < _ListaDeObjetos.size()) { System.out.print(", "); } } else { if(i + 1 < _ListaDeObjetos.size()) { System.out.print("Vacio, "); } else { System.out.print("Vacio"); } } } System.out.print("]"); }
4
private boolean unzip() { URL url = null; try { url = new URL(src); } catch (MalformedURLException e) { e.printStackTrace(); return false; } if (EventQueue.isDispatchThread()) page.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (Zipper.sharedInstance().getProcessMonitor() == null) { ProcessMonitor m = new ProcessMonitor(JOptionPane.getFrameForComponent(page)); m.getProgressBar().setMinimum(0); m.getProgressBar().setMaximum(100); m.getProgressBar().setPreferredSize(new Dimension(300, 20)); Zipper.sharedInstance().setProcessMonitor(m); } String s = Modeler.getInternationalText("DownloadingAndUncompressing"); Zipper.sharedInstance().getProcessMonitor().setTitle( "<html><body>" + (s != null ? s : "Downloading and uncompressing......") + "<br>" + src + "</body></html>"); Zipper.sharedInstance().getProcessMonitor().setLocationRelativeTo(JOptionPane.getFrameForComponent(page)); URLConnection conn = ConnectionManager.getConnection(url); if (conn == null) { page.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return false; } InputStream is = null; try { is = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); page.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); return false; } if (is instanceof ZipInputStream) { dirList = Zipper.sharedInstance().unzip((ZipInputStream) is, des, -1L); } else { dirList = Zipper.sharedInstance().unzip(new ZipInputStream(is), des, -1L); } return true; }
7
private void moveAllAnimals() { for (int i = 0; i < animalFactory.getQuantityOfVictims(); i++) { animalFactory.getVictim(i).move(); } for (int i = 0; i < animalFactory.getQuantityOfPredator(); i++) { animalFactory.getPredator(i).move(); } }
2
public void buildMatrix() { this.getSize().setWidth(this.RowCells * this.CellSize.getWidth()); this.getSize().setHeight(this.Rows * this.CellSize.getHeight()); this.Matrix.clear(); int row = 0; int z = 0; for(int i = 0; i < Cells; i++) { this.Matrix.add(new Rectangle(z * CellSize.getWidth(), row * CellSize.getHeight(), CellSize.getWidth(), CellSize.getHeight())); z++; if(z == RowCells) { row++; z = 0; } } }
2
public Button(String text) { this.text = text; setBounds(0, 0, text != null ? Text.getDefault().getWidth(text) : 1, text != null ? Text.getDefault().getHeight(text) : 1); addMouseListener(new DefaultButtonAdapter()); }
2
public static void collapseToParent(JoeTree tree) { TextKeyListener.collapseToParent(tree.getEditingNode()); return; }
0
private int countMatadors() { // If it's a null game, we don't have multipliers, skip this. if(this.gameType.getGameType() == GameTypeOptions.GameType.Null) return 0; // Create our trump card list. List<Card> trumpList = new ArrayList<Card>(); trumpList.add(new Card(Card.CARD_SUIT.CLUBS, Card.FACE_VALUE.JACK)); trumpList.add(new Card(Card.CARD_SUIT.SPADES, Card.FACE_VALUE.JACK)); trumpList.add(new Card(Card.CARD_SUIT.HEARTS, Card.FACE_VALUE.JACK)); trumpList.add(new Card(Card.CARD_SUIT.DIAMONDS, Card.FACE_VALUE.JACK)); // If it's a Suit game, we have more trump cards. if(this.gameType.getGameType() == GameTypeOptions.GameType.Suit) { // Get our trump suit (this enum is the same, except the None option in the beginning, so we subtract 1 to index it) Card.CARD_SUIT trumpSuit = Card.CARD_SUIT.values()[this.gameType.getTrumpSuit().ordinal() - 1]; trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.ACE)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.TEN)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.KING)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.QUEEN)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.NINE)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.EIGHT)); trumpList.add(new Card(trumpSuit, Card.FACE_VALUE.SEVEN)); } // Get our game hand and game options to determine what to check. GameTypeOptions.SkatHandType handGameType = this.gameType.getHandType(); Pile declarerHand = this.players[this.declarerIndex].getHandPile(); // Create our matador count and our boolean to check if we are counting with or without. int matadorCount = 0; boolean countingWith = true; // Loop through all the trump cards we're checking if we have or don't have. for(Card curTrumpCard : trumpList) { // Check our declarers hand. boolean foundCard = declarerHand.containsCard(curTrumpCard); // Check our skat pile if it's a skat game, and we haven't found the card if(handGameType == GameTypeOptions.SkatHandType.Skat && !foundCard) // Check our skat pile foundCard = this.skat.containsCard(curTrumpCard); // If it's the first time we're here, we should set if we're counting with or without. if(matadorCount == 0) countingWith = foundCard; // Check our with/without status if(countingWith == foundCard) matadorCount++; else break; } return matadorCount; }
7
@Override // #TODO: Bug when clicking, sometimes requires a double click? public void mouseClicked(MouseEvent e) { GridLabel g = (GridLabel) e.getSource(); if(currentlyClickedLabel != null && g == currentlyClickedLabel) // Clicked the same button, deselect { g.setBackground(Color.LIGHT_GRAY); GameWindow.resetSquares(); currentlyClickedLabel = null; destination = null; } else if(currentlyClickedLabel != null && g != currentlyClickedLabel) // Clicked a different button, deselect and reselect new { for (GridLabel i: GameWindow.potentialMoves) { if (g == i) { destination = i; } } if (destination != null) { //Inside range destination.associatePiece(currentlyClickedLabel.piece); currentlyClickedLabel.dissociatePiece(); } currentlyClickedLabel.setBackground(Color.LIGHT_GRAY); GameWindow.resetSquares(); currentlyClickedLabel = null; } else if(currentlyClickedLabel == null) // Nothing has been clicked { g.setBackground(Color.BLACK); if(g.piece != null) { g.piece.getPossibleMoves(); GameWindow.displayMoves(); } currentlyClickedLabel = g; } System.out.println("Mouse Pressed over grid point +" + g.x + ", " + g.y); //if(g.piece != null) System.out.println("Associated piece here: " + g.piece.getID()); }
9
public static void makeAMove(HanoiGame game, int pileA, int pileB) { int sizeTopPileA = game.getCurrentSituation().get(pileA).seeLast() .getSize(); int sizeTopPileB = game.getCurrentSituation().get(pileB).seeLast() .getSize(); if (sizeTopPileA != 0 && (sizeTopPileB == 0 || sizeTopPileA < sizeTopPileB)) { moveDisk(game, pileA, pileB); System.out.println("on bouge de " + pileA + " vers " + pileB); } else if (sizeTopPileB != 0) { moveDisk(game, pileB, pileA); System.out.println("on bouge de " + pileB + " vers " + pileA); } }
4
public void die() { Deer prev = null; Deer curr = null; // remove this deer from the linked list of deer if (head == this) head = head.next; else { prev = head; curr = prev.next; while (curr != null && curr != this) { prev = curr; curr = prev.next; } if (curr != null) prev.next = curr.next; } // ask the model display to remove this getModelDisplay().remove(this); }
4
public String toString() { return name; }
0
@Override public PermissionType getType() { return PermissionType.USER; }
0
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(GUI.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true); } }); }
6
public int getProbableDirectionCode(final String theDir) { if(theDir.length()==0) return -1; final String upDir=theDir.toUpperCase(); for (final Object[] element : DIRECTIONS_FULL_CHART) { if((element[0].toString().equals(upDir)) &&(((Integer)element[1]).intValue()<NUM_DIRECTIONS())) return ((Integer)element[1]).intValue(); } for(int i=0;i<NUM_DIRECTIONS();i++) { if(upDir.equals(DIRECTION_CHARS[i])) return i; } for (final Object[] element : DIRECTIONS_FULL_CHART) { if((element[0].toString().startsWith(upDir)) &&(((Integer)element[1]).intValue()<NUM_DIRECTIONS())) return ((Integer)element[1]).intValue(); } return -1; }
9
@Override public void unInvoke() { if(canBeUninvoked()) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((buildingI!=null)&&(!aborted)) { if(messedUp) { if(activity == CraftingActivity.LEARNING) commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",buildingI.name())); else commonTell(mob,L("You've ruined @x1!",buildingI.name(mob))); buildingI.destroy(); } else if(activity==CraftingActivity.LEARNING) { deconstructRecipeInto( buildingI, recipeHolder ); buildingI.destroy(); } else { dropAWinner(mob,buildingI); CMLib.achievements().possiblyBumpAchievement(mob, AchievementLibrary.Event.CRAFTING, 1, this); } } buildingI=null; } } super.unInvoke(); }
7
public T get(int i){ T dato = null; if(i >= 0){ Integer contador = 0; Nodo<T> nodoQ = this.inicio; while(nodoQ != null){ if(i == contador){ dato = nodoQ.getInfo(); break; }else{ nodoQ = nodoQ.getLiga(); contador++; } } return dato; }else{ return dato; } }
3
@Override public int getAge() { String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); /* save all arguments into an array */ Object[] args = new Object[0]; Class<?>[] argsType = new Class<?>[0]; int ret = 0; try { ret = (Integer)super.invokeMethod(methodName, args, argsType); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ret; }
5
private final void capLinePath() { g.draw(linePath); // Dump the path to the graphics... linePath.reset(); // Clear the path... linePath.moveTo((float) currentTurtle.position.getX(), (float) currentTurtle.position.getY()); // We've started anew! }
0
private void GoToRestaurant() { state = AgentState.WaitingInRestaurant; print("Doing GoToRestaurant"); switch(name) { case "0.00": money = 0.00; break; case "5.00": money = 5.00; break; case "10.00": money = 10.00; break; case "15.00": money = 15.00; break; case "20.00": money = 20.00; break; default: // Random Money amount. // $0.00 - $20.00 (approx) Random rng = new Random(); money = rng.nextDouble() + rng.nextInt(20); break; } if(owesMoney) { money = 40.00; owesMoney = false; } print("$" + formatOutput.format(money)); choice = null; customerGui.DoGoToWaitingArea(); try { atWaitingArea.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } AndreRestaurant.host.msgIWantToEat(this, customerGui.WAIT_POS); //send our instance, so he can respond to us }
7
private boolean checkHorizontal(Cell origin) { int count = 1; Cell next = null; Position pos = origin.getPosition(); // Count coins to the left if (pos.getCol() > 0) { // First cell to the left next = getCell(pos, 0, -1); // Continue left until the cell is empty or placed by another player while (next != null && next.getPlayer() == origin.getPlayer()) { count += 1; next = next.getPosition().getCol() > 0 ? getCell(next.getPosition(), 0, -1) : null; } } // Count coins to the right if (pos.getCol() < (COLS - 1)) { next = getCell(pos, 0, 1); // Continue right until the cell is empty or placed by another player while (next != null && next.getPlayer() == origin.getPlayer()) { count += 1; next = next.getPosition().getCol() < (COLS - 1) ? getCell(next.getPosition(), 0, 1) : null; } } if (count >= N) { return true; } return false; }
9
@Override public void mouseEntered(int mx, int m, GUIComponent component) { if (component instanceof CardComponent && component.belongsTo(playersComponent) && ((CardComponent) component).getAssociatedPlayer() instanceof HumanPlayer) { setHoverCardComponent((CardComponent)component); } }
3
public void renderTile(int xPos, int yPos, Tile tile) { xPos -= xOffset; yPos -= yOffset; for(int y = 0; y < tile.sprite.size; y++){ int ya = y + yPos; for(int x = 0; x < tile.sprite.size; x++) { int xa = x + xPos; if(xa < -tile.sprite.size || xa >= width || ya < 0 || ya > width) break; if(xa < 0) xa = 0; pixels[xa + ya * width] = tile.sprite.pixels[x + y * tile.sprite.size]; } } }
7
@Override public boolean onMouseDown(int mX, int mY, int button) { if(super.onMouseDown(mX, mY, button)) { return true; } for(ShopItemButton sib : itemSlots) { if(sib.onMouseDown(mX, mY, button)) { return true; } } return false; }
3
static public boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return (path.delete()); }
3
public static void main(String a[]) throws SocketException, IOException { String hostName = new String(""); int port = 6000; String team = new String("Krislet3"); String prototype = "Krislet"; try { // First look for parameters for( int c = 0 ; c < a.length ; c += 2 ) { if( a[c].compareTo("-host") == 0 ) { hostName = a[c+1]; } else if( a[c].compareTo("-port") == 0 ) { port = Integer.parseInt(a[c+1]); } else if( a[c].compareTo("-team") == 0 ) { team = a[c+1]; } else if ( a[c].compareTo("-proto") == 0 ) { prototype = a[c+1]; } else { throw new Exception(); } } } catch(Exception e) { System.err.println(""); System.err.println("USAGE: krislet [-parameter value]"); System.err.println(""); System.err.println(" Parameters value default"); System.err.println(" ------------------------------------"); System.err.println(" host host_name localhost"); System.err.println(" port port_number 6000"); System.err.println(" team team_name Kris"); System.err.println(" proto agent_proto Krislet"); System.err.println(""); System.err.println(" Example:"); System.err.println(" krislet -host www.host.com -port 6000 -team Poland -proto Krislet"); System.err.println(" or"); System.err.println(" krislet -host 193.117.005.223"); return; } Replicant player = new Replicant(InetAddress.getByName(hostName), port, team, prototype); // enter main loop player.mainLoop(); }
6
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { boolean isValueNumeric = false; try { if (value.equals("0") || !value.endsWith("0")) { Double.parseDouble(value); isValueNumeric = true; } } catch (NumberFormatException e) { isValueNumeric = false; } if (json.charAt(json.length() - 1) != '{') { json.append(','); } json.append(escapeJSON(key)); json.append(':'); if (isValueNumeric) { json.append(value); } else { json.append(escapeJSON(value)); } }
5
public int getTeamPointsObtained(PlayerModel player, PlayerModel partner) { int combinedBid = player.getNumBid() + partner.getNumBid(); int combinedTricks = player.getNumTricks() + partner.getNumTricks(); boolean BurntMellow1 = player.isBurntMellow(); boolean BurntMellow2 = partner.isBurntMellow(); int score = 0; //if double mellow: //I award you no extra points and god have mercy on your soul. //you get 10*bid + number overbid. //(It looks good when logged with pen & paper) if(combinedTricks >= combinedBid && combinedBid > 0) { score += 10*combinedBid + (combinedTricks-combinedBid); } else if(combinedTricks < combinedBid) { //Burnt: score -= 10 * combinedBid; } //check for mellow for first player if(BurntMellow1) { score -= 100; } else if(BurntMellow1 == false && player.isMellow()) { score += 100; } if(BurntMellow2) { score -= 100; } else if(BurntMellow2 && partner.isMellow()) { score += 100; } return score; }
9
private void jButtonUpdateFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateFornecedorActionPerformed // UPDATE FORNECEDOR -> DEPOIS DE EDITAR String nome = jTextFieldNomeFornecedor.getText(); String morada = jTextFieldMoradaFornecedor.getText(); String codPostal = jTextFieldCodPostalFornecedor.getText(); String localidade = jTextFieldLocalidadeFornecedor.getText(); String contacto = jTextFieldContactoFornecedor.getText(); String email = jTextFieldEmailFornecedor.getText(); String nif = jTextFieldNIFFornecedor.getText(); String tipoProduto = jTextFieldTipoProdutoFornecedor.getText(); if (nome.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Nome !"); } else if (morada.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Morada !"); } else if (codPostal.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Codigo Postal !"); } else if (localidade.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira a Localidade !"); } else if (contacto.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Contacto !"); } else if (nif.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o NIF !"); } else if (tipoProduto.equals("")) { JOptionPane.showMessageDialog(jDialogNovaMateriaPrima, "Insira o Tipo de Produto !"); } else { UpdateDadosFornecedor(); } }
7
public static ArrayList<Point> reverseArray(ArrayList<Point> array) { ArrayList<Point> newarray = new ArrayList<Point>(); for (int c = array.size() - 1; c >= 0; c--) { newarray.add(array.get(c)); } return newarray; }
1
private static final int method3963(int i, Class251 class251) { if (i != 594) return 7; if (class251 == Class135_Sub2.aClass251_4835) return 1; if (class251 != Class239_Sub18.aClass251_6030) { if (class251 != Class348_Sub40_Sub38.aClass251_9477) { if (Class57.aClass251_1051 == class251) return 4; if (class251 == Class239_Sub14.aClass251_5989) return 256; } else return 3; } else return 2; return 0; }
6
private void runHideZigZag(int array[][]) { convolution = zigZag.getHideZigZagArray(array, SIZE); for (int i = 0; i < STEP * STEP; i++) { arrayForZigZag[position++] = convolution[i]; } }
1
public final int getN() { return n; }
0
public String getSortConfig() { StringBuilder buffer = new StringBuilder(); int count = mColumns.size(); boolean hasSort = false; buffer.append('S'); buffer.append(CONFIG_VERSION); buffer.append('\t'); buffer.append(count); for (int i = 0; i < count; i++) { Column column = getColumnAtIndex(i); int sequence = column.getSortSequence(); buffer.append('\t'); buffer.append(column.getID()); buffer.append('\t'); buffer.append(sequence); buffer.append('\t'); buffer.append(column.isSortAscending()); if (sequence > -1) { hasSort = true; } } return hasSort ? buffer.toString() : null; }
3
@Override public void in() throws Exception { if (data == null) { throw new ComponentException("Not connected: " + toString()); } Object val = data.getFieldValue(); // fire only if there is a listener if (ens.shouldFire()) { DataflowEvent e = new DataflowEvent(ens.getController(), this, val); //// DataflowEvent e = new DataflowEvent(ens.getController(), this, access.toObject()); ens.fireIn(e); // // the value might be altered val = e.getValue(); } // access.pass((Access) val); fa.setFieldValue(val); }
2
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this); if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) { try { String tempString; tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor); jTextField1.setText(tempString); } catch (Exception e) { e.printStackTrace(); } } }//GEN-LAST:event_jButton3ActionPerformed
3
@Override public void windowDeiconified(WindowEvent arg0) { }
0
@Id @Column(name = "PRP_MOA_CONSEC") public Integer getPrpMoaConsec() { return prpMoaConsec; }
0
public static String getALError(int err) { switch (err) { case AL_NO_ERROR: return "AL_NO_ERROR"; case AL_INVALID_NAME: return "AL_INVALID_NAME"; case AL_INVALID_ENUM: return "AL_INVALID_ENUM"; case AL_INVALID_VALUE: return "AL_INVALID_VALUE"; case AL_INVALID_OPERATION: return "AL_INVALID_OPERATION"; case AL_OUT_OF_MEMORY: return "AL_OUT_OF_MEMORY"; default: return "UNKNOWN_ERROR"; } }
6
public void sendAssignment(File file, String assignment, String course, String vfykey) throws IOException { if (!open) { try { connect(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } DataOutputStream dos= null; BufferedInputStream br = null; try { dos = new DataOutputStream(graderSocket.getOutputStream()); dos.writeUTF(vfykey); dos.writeUTF(course); dos.writeUTF(assignment); dos.writeLong(file.length()); br = new BufferedInputStream(new FileInputStream(file)); byte[] data = new byte[GradingServerConstants.BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = br.read(data)) != -1) { //System.out.println(bytesRead); dos.write(data, 0, bytesRead); } dos.flush(); } finally { if (br != null) { br.close(); } } }
8
@Override public void analyze(){ try { for(int i=0; i<numFiles; i++){ File f = files.get(i); InputStream traingInputStrem = new BufferedInputStream(new FileInputStream(f.getPath())); trainSequencer.setSequence(traingInputStrem); Sequence trainSequence = trainSequencer.getSequence(); Track[] trainTracks = trainSequence.getTracks(); for (int j=0; j<trainTracks.length;j++){ Track singleTrainTrack = trainTracks[j]; ArrayList<Chord> noteLists = trackAnalyze(singleTrainTrack); updateHistogram(noteLists); } } //printHistogram(); } catch (ArrayIndexOutOfBoundsException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidMidiDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
6
public static void displayStudent(int mode) { if (FileReadService.sList.isEmpty()) { System.out.println("There is no Students !"); } else { System.out.println("Which student do you want to choose ?"); int i; for (i = 0; i < FileReadService.sList.size(); i++) { System.out.print(i + ":(" + FileReadService.sList.get(i).displayNames() + ") "); } System.out.println(); Scanner scIndexS = new Scanner(System.in); Student s = null; while (s == null) { int iS = scIndexS.nextInt(); s = chooseStudentList(iS); } if (mode == 0) { System.out.println(s); } else { System.out.println(s.displayAverage()); } } }
4
public static double getMetric(Evaluation eval, int metric_index) { switch (metric_index) { case METRIC_ACCURACY: return eval.pctCorrect(); case METRIC_RMSE: return 1.0 - eval.rootMeanSquaredError(); case METRIC_ROC: return eval.areaUnderROC(1); //TODO - is 1 right? case METRIC_PRECISION: return eval.precision(1); //TODO - same question case METRIC_RECALL: return eval.recall(1); //TODO - same question case METRIC_FSCORE: return eval.fMeasure(1); //TODO - same question case METRIC_ALL: double average = 0; int num_metrics = 0; average += eval.pctCorrect(); ++num_metrics; average += 1.0 - eval.rootMeanSquaredError(); ++num_metrics; average += eval.areaUnderROC(1); ++num_metrics; average += eval.precision(1); ++num_metrics; average += eval.recall(1); ++num_metrics; average += eval.fMeasure(1); ++num_metrics; return average / num_metrics; default: return 0.0; //FIXME TODO - this should probably be an exception? } }
7
public void setDocumentInfo (DocumentInfo someDocInfo) { docInfo = someDocInfo; }
0
@Override protected int processHeader (byte[] header) { // TBD //if (Outliner.DEBUG) // System.out.println ("\tStan_Debug:\tPdbSPReaderWriter:processHeader"); } return SUCCESS ; } // end protected method processRecord
0
@Override public String toString() { return (e.getAttributeValue("name") != null ? e .getAttributeValue("name") : e.getName()); }
1
public void stopAllSounds() { for (Clip sound : managingSounds) { sound.stop(); } }
1
* @return - Position on the board to drop piece */ public Point makeAIMove(ConnectFourBoard board) { Random r = new Random(); int maximum = 0; ArrayList<Point> m_MaxChoice = new ArrayList<Point>(); int arrayPosition; /** Set maximum to be the maximum chain length of piece on board */ for (int i = 0; i < WIDTH; i++) { if (MaximumChain(i,board.getLowestEmptySlot(i), board) > maximum) { maximum = MaximumChain(i,board.getLowestEmptySlot(i), board); } } /** If more maximum chain length exist store all in an array */ for (int i = 0; i < WIDTH; i++) { // checking if more than one maximum chain exist if (MaximumChain(i,board.getLowestEmptySlot(i), board) == maximum) { m_MaxChoice.add(new Point(i,HEIGHT)); } } arrayPosition= r.nextInt(m_MaxChoice.size()); return m_MaxChoice.get(arrayPosition); }
4
@Override // Buscar todos los alojamientos disponibles public int seleccionarUsuarios(JTable pTable){ Connection conn = null; PreparedStatement stmt; ResultSet rs; try{ conn = SQLServerDAOFactory.createConnection(); stmt = conn.prepareStatement("EXEC SPUSeleccionarUsuarios"); rs = stmt.executeQuery(); DefaultTableModel tabla= new DefaultTableModel(); tabla.addColumn("Id Usuario"); tabla.addColumn("Nombre"); tabla.addColumn("Apellidos"); tabla.addColumn("Tipo"); while (rs.next()){ Object dato[] = new Object[4]; for (int i=0; i<4; i++){ dato[i]=rs.getString(i+1); if(i == 3){ switch(dato[i].toString()){ case "1": dato[i] = "Administrador"; break; case "2": dato[i] = "Agente"; break; case "3": dato[i] = "Participante"; break; } } } tabla.addRow(dato); } pTable.setModel(tabla); return 1; } catch(SQLException e){ System.out.println("Message: " + e.getMessage() + "\n" + "Code: " + e.getErrorCode()); } finally{ if(conn != null){ try{ conn.close(); } catch(SQLException e){ System.out.println("Message: " + e.getMessage() + "\n" + "Code: " + e.getErrorCode()); } } } return -1; }
9
public void run() { while(isWriter) { int i; int j; synchronized(this) { if(buffIndex == writeIndex) try { wait(); } catch(InterruptedException _ex) { } if(!isWriter) return; j = writeIndex; if(buffIndex >= writeIndex) i = buffIndex - writeIndex; else i = 5000 - writeIndex; } if(i > 0) { try { outputStream.write(buffer, j, i); } catch(IOException _ex) { hasIOError = true; } writeIndex = (writeIndex + i) % 5000; try { if(buffIndex == writeIndex) outputStream.flush(); } catch(IOException _ex) { hasIOError = true; } } } }
9
private void setBoard(String board){ boolean test = false; if (test || m_test) { System.out.println("Drawing :: setBoard() BEGIN"); } gameBoardGraphics.SetBoard(board); if (test || m_test) System.out.println("Drawing::setBoard() - END"); }
4
public Token getNextToken() { if (m_characterIterator == null) { return ExceptionHandler.getInstance().throwException(Exception.NO_INPUT_STREAM, ExceptionStrength.STRONG); } else { while (m_characterIterator.hasNext()) { if (CharacterUtilities.isWhitespace(m_characterIterator.peek())) { m_characterIterator.getNext(); } else if (CharacterUtilities.isDigit(m_characterIterator.peek())) { return getIntegerToken(m_characterIterator.getNext(), m_characterIterator.getIndex()); } else if (CharacterUtilities.isLetter(m_characterIterator.peek())) { return getKeywordOrIdentifierToken(m_characterIterator.getNext(), m_characterIterator.getIndex()); } else if (startsWithReservedSymbol(m_characterIterator.peek())) { Token token = getSymbolToken(m_characterIterator.getNext(), m_characterIterator.getIndex()); if (isOpeningComment(token)) { skipCommentedCode(); return getNextToken(); } else if (isClosingComment(token)) { return ExceptionHandler.getInstance().throwException(Exception.IMPROPERLY_FORMATTED_COMMENT, ExceptionStrength.STRONG); } else { return token; } } else { return ExceptionHandler.getInstance().throwException(Exception.INVALID_CHARACTER, ExceptionStrength.STRONG, m_characterIterator.peek(), m_characterIterator.getIndex() + 1); } } return new Token<String>(m_characterIterator.getIndex(), 1, Token.Type.EOF, Token.Type.EOF.toString()); } }
8
@Override public Event next() { String input = null; try { input = br.readLine(); } catch (IOException e) { e.printStackTrace(); } //alters state if(input == null || input.equals("")){ return new DefaultState(as); } if(input.equalsIgnoreCase("add")){ return new AuctionCreateState(name, as); } else{ return new SearchResultsState(as, name, input); } }
4
public static String getIpClient() throws UnknownHostException, SocketException { String interfaceRede = "wlan0"; String meuIp = null; Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface face = interfaces.nextElement(); if (face.isLoopback() || !face.isUp()) { continue; } Enumeration<InetAddress> endereco = face.getInetAddresses(); while (endereco.hasMoreElements()) { InetAddress addr = endereco.nextElement(); if (face.getDisplayName().equals(interfaceRede) && addr.getHostAddress().indexOf(".") > -1) { meuIp = addr.getHostAddress(); } } } clientIp = meuIp; return meuIp; }
6
public Point[][] getPointArray(int x, int y){ Point[][] res = new Point[WORD_LENGTH][(int)Math.pow(8,WORD_LENGTH)]; res[0][0] = points[x][y]; for (int i = 0; i < WORD_LENGTH-1; i++){ for (int j = 0; j < (int)Math.pow(8,i); j++){ for (int l = 0; l < 8; l++){ res[i + 1][8 * j + l] = getPointsAround(res[i][j])[l] != null ? getPointsAround(res[i][j])[l] : new Point('*', -1, -1); } } } for (int i = 0;i < WORD_LENGTH; i++){ for (int j = 0; j < (int)Math.pow(8,WORD_LENGTH); j++){ if (res[i][j] == null){ res[i][j] = new Point('*',-1,-1); } } } return res; }
7
public static void createProfessor() { System.out.println("=== Creation of a professor ==="); System.out.print("Give a name: "); String name = ""; while (name.equals("")) { Scanner scName = new Scanner(System.in); name = scName.nextLine(); } System.out.print("Give a first name: "); String forename = ""; while (forename.equals("")) { Scanner scForename = new Scanner(System.in); forename = scForename.nextLine(); } Professor prof = new Professor(name, forename); // We check if the professor doesn't still exist in the Professor List. boolean exist = false; for (int i = 0; i < profList.size(); i++) { if (profList.get(i).equals(prof)) { exist = true; } } if (!exist) { profList.add(prof); System.out.println("Professor " + prof + " created."); } else { System.out.println("This professor still exist !"); } System.out.println(); }
5
@Override protected void execute(CommandSender sender, String Command, List<String> list) { this.init(sender); if (Command.equals("creategp")) { if (this.getGP(list.get(0)) != null) { this.reply("Es gibt bereits einen GlobalPrice mit der ID"); return; } if (list.get(1).matches("\\d*")) { this.addGP(list.get(0), Integer.parseInt(list.get(1))); this.reply("GlobalPrice " + list.get(0) + " wurde erstellt!"); } else { this.reply("Der Preis (" + list.get(1) + ") darf nur Zahlen enthalten..."); } } if (Command.equals("setgp")) { Globalprice gp = this.getGP(list.get(0)); if (gp == null) { this.reply("Ein GlobalPrice mit der ID " + list.get(0) + " konnte nicht gefunden werden."); return; } if (!list.get(1).matches("\\d*")) { this.reply("Der Preis (" + list.get(1) + ") darf nur Zahlen enthalten..."); return; } gp.setPrice(Integer.parseInt(list.get(1))); plugin.marketHandler.updateAll(gp); this.reply("Der Preis wurd ge�ndert"); } if (Command.equals("listgp") && player.hasPermission("XcraftRegionMarket.GP.Use")) { this.reply("Globalprices: " + this.getGP().toString()); } }
8
public void setMoodleNoteField(String nodeName,String content) { if (nodeName.equals("clientnoteid")) if (!content.isEmpty() && content!=null) setClientNoteId(content); if (nodeName.equals("noteid")) setNoteId(Integer.parseInt(content)); if (getNoteId()==-1) if (nodeName.equals("errorMessage")) setErrorMessage(content); }
6
public Set<LinkDigest> addAllLinks(final Set<LinkDigest> all) { for (Block block : mBlocks) { all.addAll(block.getDigests()); } if (all.contains(LinkDigest.NULL_DIGEST)) { throw new RuntimeException("Assertion Failure: NULL_DIGEST in blocks"); } for (RootObject obj : mRootObjects) { if (obj.mDigest.isNullDigest()) { continue; } if (!all.contains(obj.mDigest)) { throw new RuntimeException("Assertion Failure: root object not in blocks: " + obj.mDigest); } } return all; }
5
public static long readLong() { long x = 0; for (int i = 0; i < 8; i++) { char c = readChar(); x <<= 8; x |= c; } return x; }
1
public static void createFile(String content, String urlPath) { /* ָurl */ String[] elems = divUrl(urlPath); StringBuffer path = new StringBuffer(); File file = null; for (int i = 1; i < elems.length; i++) { if (i != elems.length - 1) { path.append(elems[i]); path.append(File.separator); file = new File("D:" + File.separator + path.toString()); } if (i == elems.length - 1) { Pattern pattern = Pattern.compile("\\w+\\.[a-zA-Z]+"); Matcher matcher = pattern.matcher(elems[i]); if ((matcher.matches())) { if (!file.exists()) { file.mkdirs(); } String[] fileName = elems[i].split("\\."); file = new File("D:" + File.separator + path.toString() + File.separator + fileName[0] + ".txt"); try { file.createNewFile(); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); writer.write(content); writer.flush(); writer.close(); System.out.println("ļɹ"); } catch (IOException e) { e.printStackTrace(); } } } } }
6
public void addAll(String[][] L) { data = new String[L.length][4]; for (int i = 0; i < data.length; i++) { data[i][0] = L[i][0]; data[i][1] = L[i][1]; data[i][2] = L[i][2]; data[i][3] = L[i][3]; } }
1
public void actionPerformed(ActionEvent e) { Object o = e.getSource(); // if it is the Logout button if (o == logout) { client.sendMessage(new ChatMessage(ChatMessage.LOGOUT, "")); return; } // if it the who is in button if (o == whoIsIn) { client.sendMessage(new ChatMessage(ChatMessage.WHOISIN, "")); return; } // ok it is coming from the JTextField if (connected) { // just have to send the message client.sendMessage(new ChatMessage(ChatMessage.MESSAGE, tf .getText())); tf.setText(""); return; } if (o == login) { // ok it is a connection request String username = tf.getText().trim(); // empty username ignore it if (username.length() == 0) return; // empty serverAddress ignore it String server = tfServer.getText().trim(); if (server.length() == 0) return; // empty or invalid port numer, ignore it String portNumber = tfPort.getText().trim(); if (portNumber.length() == 0) return; int port = 0; try { port = Integer.parseInt(portNumber); } catch (Exception en) { return; // nothing I can do if port number is not valid } // try creating a new Client with GUI client = new Client(server, port, username, this); // test if we can start the Client if (!client.start()) return; tf.setText(""); label.setText("Enter your message below"); connected = true; // disable login button login.setEnabled(false); // enable the 2 buttons logout.setEnabled(true); whoIsIn.setEnabled(true); // disable the Server and Port JTextField tfServer.setEditable(false); tfPort.setEditable(false); // Action listener for when the user enter a message tf.addActionListener(this); } }
9
@Override public ValidationResult validate(Game game) { int allowedQuestionsCount = getQuestionsCount(); int allowedAnswersCount = getAnswersCount(); int allowedCorrectAnswersCount = getCorrectAnswersCount(); List<Question> questions = game.getQuestions(); if (questions == null || questions.size() != allowedQuestionsCount) { return new ValidationResult("Game must contain exactly " + allowedQuestionsCount + " questions!"); } int questionNr = 1; for (Question question : questions) { List<Answer> answers = question.getAnswers(); if (answers == null || answers.size() != allowedAnswersCount) { return new ValidationResult("Question #" + questionNr + " must have exactly " + allowedAnswersCount + " answers!"); } int correctAnswers = 0; for (Answer answer : answers) { if (answer.isCorrect()) { correctAnswers++; } } if (correctAnswers != allowedCorrectAnswersCount) { return new ValidationResult("Question #" + questionNr + " must have exactly " + allowedCorrectAnswersCount + " correct answer!"); } questionNr++; } return new ValidationResult(); // all OK }
8
public void run() { Map<String, Term> solution; // Variable X = new Variable("X"); // Query q2 = new Query("child_of(joe,ralf)"); System.err.println("child_of(joe,ralf) is " + (q2.hasSolution() ? "provable" : "not provable")); new Query("sleep(?)", new Term[] { new org.jpl7.Integer(delay) }).hasSolution(); // Query q3 = new Query("descendent_of(steve,ralf)"); System.err.println("descendent_of(steve,ralf) is " + (q3.hasSolution() ? "provable" : "not provable")); delay(); // Query q4 = new Query("descendent_of(X, ralf)"); solution = q4.oneSolution(); System.err.println("first solution of descendent_of(X, ralf)"); System.err.println("X = " + solution.get("X")); delay(); // Map<String, Term>[] solutions = q4.allSolutions(); System.err.println("all solutions of descendent_of(X, ralf)"); for (int i = 0; i < solutions.length; i++) { System.err.println("X = " + solutions[i].get("X")); } delay(); // System.err.println("each solution of descendent_of(X, ralf)"); while (q4.hasMoreSolutions()) { solution = q4.nextSolution(); System.err.println("X = " + solution.get("X")); } delay(); // Query q5 = new Query("descendent_of(X, Y)"); System.err.println(id + ": each solution of descendent_of(X, Y)"); while (q5.hasMoreSolutions()) { solution = q5.nextSolution(); System.err.println(id + ": X = " + solution.get("X") + ", Y = " + solution.get("Y")); delay(); } }
5
@Override protected void mutate(Individual indiv) { Sudoku sudoku = (Sudoku)indiv; Sudoku best = null; Random r = new Random(); for(int i=0; i<numOfTries; i++){ //choose a row int row = r.nextInt(9); //choose 2 cols int c1= r.nextInt(9); int c2 = r.nextInt(9); if(c1==c2 || sudoku.rows[row][c1]<0 || sudoku.rows[row][c2]<0) continue; Sudoku newOne = (Sudoku)sudoku.clone(); //switch c1 & c2 int p = newOne.rows[row][c1]; newOne.rows[row][c1]= newOne.rows[row][c2]; newOne.rows[row][c2]= p; newOne.recalcule(); if(best==null||newOne.compareTo(best)>0)//choose the best one best= newOne; } if(best==null)return; sudoku.rows = best.rows; sudoku.lastEvaluation = best.lastEvaluation; }
7
private String scanString(String listData) { StringBuilder cadenafinal = new StringBuilder(); Scanner innerScan = new Scanner(listData); boolean firstPass = true; while (innerScan.hasNext()) { if (firstPass) { cadenafinal.append(" ").append(innerScan.nextLine()).append('\r'); firstPass = false; } else { cadenafinal.append('\n').append(" ").append(innerScan.nextLine()).append('\r'); } } return cadenafinal.toString(); }
2
public static MilkyWay getMilkyWay(List<String> filePathList) throws IOException { MilkyWay milkyWay = new MilkyWay(); int i = 0; Double ngp = Math.toRadians(27.4); for (String filePath : filePathList) { List<Coord> dataSet = new LinkedList<>(); try ( InputStream inputStream = MilkyWayLoader.class.getResourceAsStream(filePath); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "ASCII"))) { String strLine; while ((strLine = reader.readLine()) != null) { if (!strLine.isEmpty() && !strLine.startsWith("#")) { String[] values = strLine.split(" "); Double l = Math.toRadians(360.0 - 33.0 - (180.0 + Double.parseDouble(values[0]) / 100.0)); Double b = Math.toRadians(Double.parseDouble(values[1]) / 1000.0); Double Dec = Math.toDegrees(Math.asin(Math.cos(b) * Math.cos(ngp) * Math.sin(l) + Math.sin(b) * Math.sin(ngp))); Double RA = 90.0 + (282.25 + Math.toDegrees(Math.atan2(Math.cos(b) * Math.cos(l), Math.sin(b) * Math.cos(ngp) - Math.cos(b) * Math.sin(ngp) * Math.sin(l)))) / 15.0; Coord coord = new Coord(RA, Dec); dataSet.add(coord); } } } switch (i) { case 0: milkyWay.setDarkNorth(dataSet); break; case 1: milkyWay.setDarkSouth(dataSet); break; case 2: milkyWay.setBrightNorth(dataSet); break; case 3: milkyWay.setBrightSouth(dataSet); break; default: } i++; } return milkyWay; }
8
public static List<String> getStructures(CyNetwork network, CyIdentifiable id) { String pdbColumn = getPDBColumnName(network); if (pdbColumn == null || pdbColumn.length() == 0) return null; if (!network.getRow(id).isSet(pdbColumn)) return null; List<String> columnListString = null; if (network.getDefaultNodeTable().getColumn(pdbColumn).getType() == List.class) columnListString = network.getRow(id).getList(pdbColumn, String.class); else { String str = network.getRow(id).get(pdbColumn, String.class); if (str != null && str.length() > 0) { String[] splitStr = str.split(","); columnListString = Arrays.asList(splitStr); } } return columnListString; }
6
@Override public Auction[] search(String criteria) { Predicate<Auction> cp = null; ArrayList<Auction> theSearch = new ArrayList<Auction>(); Stack<Predicate<Auction>> predicateStack = new Stack<Predicate<Auction>>(); Stack<String> operatorStack = new Stack<String>(); Predicate<Auction> firstSearchString; Predicate<Auction> secondSearchString; /*if(stringSplit.equals("NOT")){ * this method should check if a name or description does not contain * the search criteria and not will have to be checked first * then and then or */ for(String stringSplit: criteria.split(" ")){ //criteria = stringSplit; if(stringSplit.equalsIgnoreCase("AND")){ operatorStack.add(stringSplit.trim()); } else if(stringSplit.equalsIgnoreCase("OR")){ // Pop off the top two from the predicate stack and the top one from the // operator stack. Take the two predicates and use them to create an // AndPredicate. Place it onto the predicate stack. // Now that AND is off, place OR on the operator stack. operatorStack.add(stringSplit.trim()); while(operatorStack.peek().equalsIgnoreCase("AND") && !operatorStack.isEmpty()){ operatorStack.pop(); firstSearchString = predicateStack.pop(); secondSearchString = predicateStack.pop(); cp = new AndPredicate<Auction>(firstSearchString, secondSearchString); predicateStack.add(cp); } } else{ predicateStack.add(cp = new ContainsPredicate(stringSplit.trim())); // operatorStack.push(stringSplit); } } while(!operatorStack.isEmpty()){ // Step Five. Pop off the top two from the predicate stack and the top // one from the operator stack. Take the two predicates and use them to // create an AndPredicate. Place it onto the predicate stack. firstSearchString = predicateStack.pop(); secondSearchString = predicateStack.pop(); if(operatorStack.pop().equalsIgnoreCase("AND")){ cp = new AndPredicate<Auction>(firstSearchString, secondSearchString); predicateStack.add(cp); } else{ cp = new OrPredicate<Auction>(firstSearchString, secondSearchString); predicateStack.add(cp); } //operatorStack.add(stringSplit.trim()); // op = new OrPredicate<Auction>(firstSearchString, secondSearchString); if(operatorStack.isEmpty()){ predicateStack.pop(); } } theSearch.addAll(CollectionUtils.filter(searches.values(), cp)); return theSearch.toArray(new Auction[theSearch.size()]); }
8
public Format getFormat() throws SQLException { if (format == null && formatNumber > 0) format = GetFormats.create().getFormat(formatNumber); return format; }
2
public static void main (String[] args) { Wordsmith wordsmith = new Wordsmith(); // Choosing the number of topics is tricky. Trial and error is not a bad way necessarily... // Too few topics and it will be more summarization, but not capture a lot of the nuances. // Too many topics, and they can become junky and repetitive, // but more nuanced topics get through. int numTopics = 6; // Alpha usually should be between 0.5 & 3. Beta should be between 0.01 & 0.2. // Hyperparameter optimization (built-in) makes the initial values not as important, given // enough iterations. wordsmith.createNewModel(numTopics, 2.5, 0.37); // Values for johnmaeda's twitter // Speed up the algorithm if you have a multicore machine by setting the number of cores // higher, but only do so for large data sets (like tens of thousands of large documents). // Otherwise it will be slower. int numCores = 1; wordsmith.useMulticore(numCores); // Not too much data so its relatively quick. Better to get higher accuracy instead. wordsmith.setNumberOfProcessIterations(1000); // Don't output so much debug data wordsmith.setIntermediateResultsFrequency(500); wordsmith.setNumberShownWordsForIntermediateResults(20); // Strip out meaningless pieces of the tweet. wordsmith.cacheTokenizationOfDocuments(true); wordsmith.removeHtmlFromDocuments(); wordsmith.removeCommonEnglishWordsFromDocuments(); wordsmith.pruneWordsOccurringLessThanThreshold(3); // Load the Tweets Pwitter twitter = new Pwitter(new PApplet()); String user = "johnmaeda"; ArrayList tweets = twitter.loadTweets("data/" + user + ".xml"); wordsmith.removeWordFromDocuments(user); for (int i = 0; i < tweets.size(); i++) { Pweet tweet = (Pweet) tweets.get(i); String tweetText = tweet.getText(); wordsmith.addDocumentInString(tweetText); } // Fire it up! wordsmith.extractTopicsFromDocuments(); // Report on what we found! for (int topic = 0; topic < numTopics; topic++) { System.out.println("\nTopic " + topic + " ------------------"); Object[] topWords = wordsmith.getTopWordsForTopic(topic); for (int i = 0; i < 10; i++) { String prefix; switch(i) { case 0: prefix = "st"; break; case 1: prefix = "nd"; break; case 2: prefix = "rd"; break; default: prefix = "th"; } System.out.println(" " + (i+1) + prefix + " most probable word: " + topWords[i]); } } // Grab a random tweet and go through its assignments. Pweet tweet = (Pweet) tweets.get(5); System.out.println("\n\n\nTopic assignments per word in tweet: " + tweet.getText()); TopicWordAssignment[] assignments = wordsmith.getTopicWordAssignmentsForDocument(5); for (int i = 0; i < assignments.length; i++) { TopicWordAssignment assignment = assignments[i]; System.out.println(assignment.getWord() + " is assigned to topic " + assignment.getTopic()); } System.out.println("\nWords not printed have been excluded from the vocabulary using the filters above."); }
7
@Override public void fixSubtree(String footpath, String subtreePrefix, RepairIssue[] issues) { Host[] failedHosts = new Host[issues.length]; for (int i = 0; i < issues.length; i++) { failedHosts[i] = Deserializer.deserializeHost(issues[i].failedPeer); } delegate_.fixSubtree(footpath, subtreePrefix, failedHosts); }
1
public void run() { if (DEBUG) log("Now running TaskEdit Command"); if (taskViewsToUpdate != null) { if (DEBUG) log("currentState completed? " + currentState.isCompleted()); if (DEBUG) log("newState completed? " + newState.isCompleted()); if (DEBUG) log("Update currentState to newState"); currentState.updateFrom(newState); if (DEBUG) log("currentState completed after update? " + currentState.isCompleted()); if (DEBUG) log("Update taskViews"); for (TaskView taskView : taskViewsToUpdate) { taskView.updateTaskInfo(); } } }
8
public void setHLevel(int hLevel) { if(hLevel > 0 && hLevel < 6) { this.hLevel = hLevel; } else { System.err.println("hLevel invalid"); this.hLevel = 5; } }
2
private URL encodeurl(URL raw) throws IOException { /* * This is "kinda" ugly. It is, actually, how the Java documentation * recommend that it be done, though... */ try { return (new URL(new URI(raw.getProtocol(), raw.getHost(), raw.getPath(), raw.getRef()).toASCIIString())); } catch (URISyntaxException e) { throw (new IOException(e)); } }
1
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!plugin.hasPerm(sender, "warp", false)) { sender.sendMessage(ChatColor.YELLOW + "You do not have permission to use /" + label); return true; } if (args.length == 0) return false; Player player = (Player) sender; String world = player.getWorld().getName(); Location loc = null; WarpTable wt = plugin.getDatabase().find(WarpTable.class).where() .ieq("name", args[0]).ieq("world", world).findUnique(); if (wt != null) { loc = this.getLocation(wt); } else { sender.sendMessage(CraftEssence.premessage + "Warp location not found."); return true; } player.teleport(loc); player.sendMessage(CraftEssence.premessage + "Warping to " + args[0] + "..."); return true; }
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(InterfacePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InterfacePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InterfacePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InterfacePrincipal.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 InterfacePrincipal().setVisible(true); } }); }
6
public boolean isMenuKey() { switch(keyCode) { case VK_SHIFT: case VK_CONTROL: case VK_ALT: return true; } return false; }
3
public void setItemNumber(String itemNumber) { this.itemNumber = itemNumber; }
0
public String performAddition(String tal1, String tal2) { StringBuilder sBuilder = new StringBuilder(); int lenght = tal1.length(); tal2 = matchLenght(lenght, tal2); int carry = 0; int i = 0; if(tal2.length() > lenght) { lenght = tal2.length(); tal1 = matchLenght(lenght, tal1); } // Reverse tal1 = new StringBuilder(tal1).reverse().toString(); tal2 = new StringBuilder(tal2).reverse().toString(); while(i < lenght || carry == 1) { int temp; if(i < lenght) { temp = (tal1.charAt(i) - 48) + (tal2.charAt(i) - 48) + carry; }else { temp = carry; } System.out.println(temp); carry = 0; if(temp > 9) { carry = 1; sBuilder.append(temp % 10); }else { sBuilder.append(temp); } i++; } return new StringBuilder(sBuilder.toString()).reverse().toString(); }
5
@Test public void getVertexSetNeigourhoodTest(){ VertexSet s = new VertexSet(); s.addVertex(city_graph.getCity(6)); VertexSet v = city_graph.getVertexSetNeighbourhood(s); assertTrue(!v.containsID(6)); }
0
public float move(float amtXIn, float amtYIn) { if (amtXIn != 0.0f && amtYIn != 0.0f) { throw new IllegalArgumentException( "Can only move in 1 dimension per call"); } structure.remove(this); double amtX = (double) amtXIn; double amtY = (double) amtYIn; CollisionComponent c = (CollisionComponent) getComponent(CollisionComponent.ID); if (c != null) { DoublePair amts = c.resolveCollisions(amtX, amtY); amtX = amts.getVal1(); amtY = amts.getVal2(); } x += amtX; y += amtY; structure.add(this); if (amtX != 0) { return (float) amtX; } else { return (float) amtY; } }
4
public Vector<Block> selectBlocks(Vector<Block> originalPopulation) { Vector<Block> fitBlocks = new Vector<Block>(); //first, calculate the sum of e^(fitness of each of the blocks) double fitnessSum = 0.0; for(Block b : originalPopulation) { fitnessSum += Math.exp(b.getFitness()); } //second figure out what the maximum double value we would get to select each block double maxSelectionValue[] = new double[originalPopulation.size()]; maxSelectionValue[0] = Math.exp(originalPopulation.get(0).getFitness()) / fitnessSum; for(int i = 1; i < originalPopulation.size(); i++) { maxSelectionValue[i] = maxSelectionValue[i-1] + (Math.exp(originalPopulation.get(i).getFitness())/fitnessSum); } //now, select sum of the blocks using Boltzman selection double randDouble; for(int i = 0; i < BLOCK_POPULATION_SIZE; i++) { //get a random double randDouble = RANDOM_NUMBER_GENERATOR.nextDouble(); //check to see if that random number is less than the first max selection value //if it is, take the block in the 0th index if(randDouble < maxSelectionValue[0]) { fitBlocks.add(new Block(originalPopulation.get(0))); continue; } //if not, go through the rest of the selection values and find //the value that is less than the current value but greater than the prev value for(int j = 1; j < maxSelectionValue.length; j++) { if(randDouble < maxSelectionValue[j] && randDouble > maxSelectionValue[j-1]) { fitBlocks.add(new Block(originalPopulation.get(j))); break; } } } return fitBlocks; }
7
public void guardarDatos(){ try { FileOutputStream fileOut = new FileOutputStream("usuario.ser",true); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this); out.close(); fileOut.close(); System.out.println("datos guardados en usuario.ser"); }catch (IOException i) { i.printStackTrace(); } }
1
public void setState(int state) { this.state=state; // Change the status label if (state==1) theApp.setStatusLabel("Start Tone Hunt"); else if (state==2) theApp.setStatusLabel("Sync Hunt"); else if (state==3) theApp.setStatusLabel("Sync Found"); else if (state==4) theApp.setStatusLabel("Decoding"); else if (state==5) theApp.setStatusLabel("Complete"); }
5
public void draw(Graphics2D g) { g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.drawImage(board, 0, 123, null); synchronized(model) { if (model.done()) { if (model.hasWon(model.CROSSES)) { drawMessage(1, g); } if (model.hasWon(model.CIRCLES)) { drawMessage(3, g); } } else { drawMessage(model.team() * 2, g); } for(int x = 0; x < 3; x++) { for(int y = 0; y < 3; y++) { Actor a = model.actorAt(new Location(model, x, y)); if (a instanceof Factional) { drawCross(x, y, ((Factional)a).team() != model.CROSSES, g); } } } } }
6
public String getURLString() { return assembleURL( this.host, this.port, this.userInfo, this.authority, this.protocol, this.path_list, this.query_list, this.fragment ); }
0
public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); } return jo; }
2
public ServerReply getReply(HttpPost post) { ServerReply reply = null; HttpClient client = this.getClient(); try { log.finest(String.format("[%s] Executing POST.", post.getURI())); HttpResponse resp = client.execute(post); try { HttpEntity entity = resp.getEntity(); if(resp.getStatusLine().getStatusCode() == 200) { InputStream in = entity.getContent(); log.finest(String.format("[%s] Received HTTP code %d: %dbytes (%s)", post.getURI(), resp.getStatusLine().getStatusCode(), entity.getContentLength(), entity.getContentType().getValue())); Document document = this.builder.parse(in); Element replyElement = (Element)document.getFirstChild(); Element contents = ElementUtils.getFirstElementByName(replyElement, "contents"); /* * Test the first element found within the element 'contents'. If the * element's name is 'token', then this is a LoginReply. However, if the * name of the element is 'reports', this will mean this is a ReportListReply. * */ Element firstElement = (Element)contents.getFirstChild(); if(firstElement == null) reply = new ErrorReply(replyElement); else if(firstElement.getTagName().equals("reports")) reply = new ReportListReply(replyElement); else reply = new LoginReply(replyElement); log.finest(String.format("[%s] Parsed XML succcessfully: %s", post.getURI(), reply.getClass().getName())); }else{ log.warning(String.format("[%s] Received HTTP code %d. Skipping parsing of content.", post.getURI(), resp.getStatusLine().getStatusCode())); EntityUtils.consume(entity); } }catch(IOException | SAXException | ElementNotFoundException e) { log.warning(String.format("Could read/parse reply from server %s: %s %s", this.url, e.getClass().getName(), e.getMessage())); } }catch(IOException e) { log.warning(String.format("Could not connect to server %s: %s", this.url, e.getMessage())); } return reply; }
5
@SuppressWarnings("resource") public void loadPak(File file, boolean spawnPlayer){ pakFile = file; String thisfile = "properties"; try { ZipFile zipFile = new ZipFile(file); ZipEntry zipEntry = zipFile.getEntry(thisfile); InputStream in = zipFile.getInputStream(zipEntry); BufferedReader input = new BufferedReader(new InputStreamReader(in)); propReader(input); } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { eio.loadPakData(file); } catch (IOException e) { e.printStackTrace(); } if(spawnPlayer){ boolean playerExists=false; for(Entity e: eio.entities){ if(e instanceof Creature){ Creature c = (Creature)e; if(c.name.equals(Molybdenum.settings.PLAYER_NAME)){ playerExists=true; } } } if(playerExists){ ((GameState)Molybdenum.getStateManager().getState(StateManager.GAMESTATE)).em.setEntities(eio.entities); Molybdenum.getStateManager().setState(StateManager.GAMESTATE); }else{ spawnPlayer(); } } }
8
@Override public Usuario salvar(Usuario entidade) throws ValidacaoException { if (entidade == null) { throw new IllegalArgumentException("'usuario' não pode ser nulo"); } for (Usuario usuario : obterTodos()) { if (usuario.getUsuarioId() == entidade.getUsuarioId()) { continue; } if (usuario.getLogin().equals(entidade.getLogin())) { throw new ValidacaoException(String.format("O Login '%s' já está em uso", usuario.getLogin())); } } return super.salvar(entidade); }
4
public static final String getHomeDir() { String homeDir = null; try { String os = System.getProperty("os.name").toLowerCase(); try { if (os.startsWith("windows")) { // JRE prior to 1.5 cannot reliably determine USERPROFILE. // Return user.home and hope it's right. if (Integer.parseInt(System.getProperty("java.version").split("\\.")[1]) < 5) { try { homeDir = System.getProperty("user.home"); } catch(java.security.AccessControlException e) { vlog.error("Cannot access user.home system property:" + e.getMessage()); } } else { homeDir = System.getenv("USERPROFILE"); } } else { try { homeDir = FileSystemView.getFileSystemView(). getDefaultDirectory().getCanonicalPath(); } catch(java.security.AccessControlException e) { vlog.error("Cannot access system property:" + e.getMessage()); } } } catch(java.lang.Exception e) { e.printStackTrace(); } } catch(java.security.AccessControlException e) { vlog.error("Cannot access os.name system property:" + e.getMessage()); } return homeDir + getFileSeparator(); }
6
public static long kthFac(int k, int n) { long res = 1; long limit = n; for (long i = 2; i <= limit; i++) { res *= i; if (i == limit && k > 0) { k--; limit = res; } } return res; }
3
public static void setTerrain(int direction) { switch(direction) { case 1: tiley--; break; case 2: tiley++; break; case 3: tilex++; break; case 4: tilex--; break; } for(int i = 0; i<80; i++) { for(int j = 0; j<60; j++) { terrain[i][j]=map[tilex+i][tiley+j]; } } }
6
public static void main(final String[] args) { //check useage if(args.length < 1) { System.out.println("UTF8 Validator version: " + VERSION); System.out.println("Useage: utf8validate [options] <file>"); System.out.println(""); System.out.println("\t-f | --fail-fast"); System.out.println("\t\tStops on the first validation error rather than reporting all errors"); System.out.println(""); System.exit(ExitCode.INVALID_ARGS.getCode()); } //parse args final boolean failFast; final File f; if(args[0].equals("-f") || args[0].equals("--fail-fast")) { failFast = true; f = new File(args[1]); } else { failFast = false; f = new File(args[0]); } if(!f.exists()) { System.out.println("File: " + f.getPath() + " does not exist!"); System.exit(ExitCode.INVALID_ARGS.getCode()); } final PrintingValidationHandler handler = new PrintingValidationHandler(failFast, System.out); ExitCode result = ExitCode.OK; final long start = System.currentTimeMillis(); System.out.println("Validating: " + f.getPath()); try { new Utf8Validator(handler).validate(f); if(!failFast && handler.isErrored()) { result = ExitCode.VALIDATION_ERROR; } else { System.out.println("Valid OK (took " + (System.currentTimeMillis() - start) + "ms)"); result = ExitCode.OK; } } catch(final ValidationException ve) { System.out.println(ve.getMessage()); result = ExitCode.VALIDATION_ERROR; } catch(final IOException ioe) { System.err.println("[ERROR]" + ioe.getMessage()); result = ExitCode.IO_ERROR; } System.exit(result.getCode()); }
8