method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
04a36339-6145-4b0b-b264-0e74459c9346 | 5 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
RaavareLagerKompDTOView raavareLagerKomp = raavareLagerKompList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = raavareLagerKomp.getRaavareId();
break;
case 1:
value = raavareLagerKomp.getRaavareNavn();
break;
case 2:
value = raavareLagerKomp.getKostprisPrStk();
break;
case 3:
value = raavareLagerKomp.getTotalAntal();
break;
case 4:
value = raavareLagerKomp.getKostprisIalt();
break;
}
return value;
} |
9dc7d623-f5d4-4804-ab24-09d40d0c5b40 | 1 | public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
return new SAXAnnotationAdapter(getContentHandler(), "annotation",
visible ? 1 : -1, null, desc);
} |
929933d9-d0ba-4fca-bcb2-2838cc436727 | 8 | public void removePlayer(Player player) {
this.logger.info("Jugador " + player.getUser().getUsername()
+ " solicita salir de sala " + this.roomName );
// se elimina del equipo correspondiente
if( player.getTeam().getType() != Team.NONE ){
if( player.getTeam().getType() == Team.RED ){
this.teamRed.removePlayer(player);
// Para debug
this.logger.debug("Lista de usuarios en equipo rojo: ");
for( Player p : this.teamRed.getPlayers() ){
this.logger.debug( p.getUser().getUsername() );
}
this.logger.debug("Fin lista");
}else if( player.getTeam().getType() == Team.BLACK ){
this.teamBlack.removePlayer(player);
// Para debug
this.logger.debug("Lista de usuarios en equipo negro: ");
for( Player p : this.teamBlack.getPlayers() ){
this.logger.debug( p.getUser().getUsername() );
}
this.logger.debug("Fin lista");
}
this.currNumPlayers--;
this.toRedTeam = !this.toRedTeam;
}
if( player.equals( this.gameMaster ) ){
// si es el gameMaster
if( this.playerList.size() >= 2 ){
// si hay mas jugadores se cambia de gameMaster
this.gameMaster = this.playerList.get(1);
//TODO revisar
// this.toRedTeam = !this.toRedTeam;
}else{
// sino se cierra
this.close();
}
}
// se elimina de la sala
this.playerList.remove(player);
player.setRoom(null);
// se les avisa a todos los demas
RequestRoomUpdate rru = new RequestRoomUpdate();
rru.roomInfo = getTeamList();
for( Player p : playerList ){
p.getConnection().sendTCP(rru);
}
} |
a179e603-f2f2-4c07-802e-b9d5f596bcec | 0 | protected boolean isFinished() {
return false;
} |
17054dc9-ae1e-4f58-b919-0895fb7bc890 | 6 | public ShowEmployeePanel() {
super(null); // Declares as a null layout
model = new EmployeeTableModel();
sorter = new TableRowSorter<EmployeeTableModel>(model);
employeeTable = new JTable(model);
employeeTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
employeeTable.setFillsViewportHeight(true);
employeeTable.setRowSorter(sorter);
employeeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
employeeTable.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e) {
int tableRow = employeeTable.rowAtPoint(e.getPoint());
Employee[] employeeData = ReadFromFile.findAllEmployeeData();
try
{
String indexValue =(String)employeeTable.getValueAt(tableRow, 0);
for(int i = 0; i < employeeData.length; i++) {
if(indexValue.equals(employeeData[i].getEmployeeID())) {
JOptionPane.showMessageDialog(null,
employeeDataInfo(Integer.parseInt(indexValue)-1, employeeData), "Employee Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
catch(IndexOutOfBoundsException f){}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
try {
logo = ImageIO.read(new File("MMT_Logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
try{
background = ImageIO.read(new File("DAPP_Background2.jpg"));
}catch(IOException e) {
e.printStackTrace();
}
chooseFilter = new JComboBox(filterLabels);
filterText = new JTextField();
//Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newEmployeeFilter();
}
public void insertUpdate(DocumentEvent e) {
newEmployeeFilter();
}
public void removeUpdate(DocumentEvent e) {
newEmployeeFilter();
}
});
// Labels declared and initialized
firstnameLabel = new JLabel("First Name : ");
firstnameLabel.setForeground(allColor);
firstnameLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
lastnameLabel = new JLabel("Last Name : ");
lastnameLabel.setForeground(allColor);
lastnameLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
emailLabel = new JLabel("Email : ");
emailLabel.setForeground(allColor);
emailLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
cellphoneLabel = new JLabel("Cell Phone :");
cellphoneLabel.setForeground(allColor);
cellphoneLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
homephoneLabel = new JLabel("Home Phone: ");
homephoneLabel.setForeground(allColor);
homephoneLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
addressLabel = new JLabel("Address : ");
addressLabel.setForeground(allColor);
addressLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
cityLabel = new JLabel("City : ");
cityLabel.setForeground(allColor);
cityLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
stateLabel = new JLabel("State : ");
stateLabel.setForeground(allColor);
stateLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
zipLabel = new JLabel("Zip Code : ");
zipLabel.setForeground(allColor);
zipLabel.setFont(new Font("Sans Serif",Font.BOLD, fontSize));
// JTextFields declared with their lengths declared as well
firstnameField = new JTextField();
lastnameField = new JTextField();
emailField = new JTextField();
cellphoneField = new JTextField();
homephoneField = new JTextField();
addressField = new JTextField();
cityField = new JTextField();
stateField = new JTextField();
zipField = new JTextField();
// Button which cancels the registration, going back to the Main Frame
cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
clearTextFields();
}
});
// Button that enters all the data to an Employee file and also prints to txt file
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if(checkTextFields()) {
getText();
clearTextFields();
enterToFile();
model.changeData();
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, "Your information on this employee has been submitted");
}
}
});
// Adds JPanels showing the label and the fields together as well as the buttons at the end
employeetxt = "employee.txt";
employeeTextData = new String[10];
this.setBorder(BorderFactory.createEmptyBorder(50, 200, 50, 190));
currentY = registerY;
this.add(firstnameLabel);
firstnameLabel.setBounds(registerX, currentY, 150, 20);
this.add(firstnameField);
firstnameField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(lastnameLabel);
lastnameLabel.setBounds(registerX, currentY, 150, 20);
this.add(lastnameField);
lastnameField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(emailLabel);
emailLabel.setBounds(registerX, currentY, 150, 20);
this.add(emailField);
emailField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(cellphoneLabel);
cellphoneLabel.setBounds(registerX, currentY, 150, 20);
this.add(cellphoneField);
cellphoneField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(homephoneLabel);
homephoneLabel.setBounds(registerX, currentY, 150, 20);
this.add(homephoneField);
homephoneField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(addressLabel);
addressLabel.setBounds(registerX, currentY, 150, 20);
this.add(addressField);
addressField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(cityLabel);
cityLabel.setBounds(registerX, currentY, 150, 20);
this.add(cityField);
cityField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(stateLabel);
stateLabel.setBounds(registerX, currentY, 150, 20);
this.add(stateField);
stateField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(zipLabel);
zipLabel.setBounds(registerX, currentY, 150, 20);
this.add(zipField);
zipField.setBounds(registerX + 170, currentY, 250, 20);
currentY+= addition;
this.add(cancel);
cancel.setBounds(registerX, currentY, 70, 20);
this.add(submit);
submit.setBounds(registerX + 90, currentY, 70, 20);
this.add(chooseFilter);
chooseFilter.setBounds(tableX, 590, 150, 20);
this.add(filterText);
filterText.setBounds(tableX + 170, 590, 300, 20);
tablePane = new JScrollPane(employeeTable);
this.add(tablePane);
tablePane.setBounds(tableX, tableY, 500, 500);
} |
3a9d64f8-192e-44f6-9746-ce1585bc103d | 7 | @Override
public ContainerRequest filter(ContainerRequest request) {
final String accessToken = request.getHeaderValue("Authorization");
Session session = null;
TokenWrapper response = null;
if (accessToken != null && accessToken.length() > 0) {
try {
PhiAuthClient.setHostname("http://evergreenalumniclub.com:7080/PhiAuth/rest");
response = PhiAuthClient.validateToken(accessToken);
} catch (URISyntaxException e) {
throw new UnableToValidateException(String.valueOf(Math.random()),"Could not validate token due to URI exception." + e.getMessage());
} catch (HttpException e) {
throw new UnableToValidateException(String.valueOf(Math.random()),"Could not validate token due to http exception." + e.getMessage());
} catch (IOException e) {
throw new UnableToValidateException(String.valueOf(Math.random()),"Could not validate token due to IO exception.");
} catch (DependentServiceException e){
throw e;
} catch (UnableToValidateException e){
throw new WebApplicationException();
}
}else{
throw new InvalidTokenException(String.valueOf(Math.random()),"No token provided");
}
// Set security context
request.setSecurityContext(new PhiAuthSecurityContext(session, response));
return request;
} |
b9e5077d-1c79-4ef4-a976-13e2c5748915 | 6 | 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(Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Search.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 Search().setVisible(true);
}
});
} |
53e36e56-cd12-47a3-9edb-a3bff8fd6294 | 5 | public void print() {
String nullString = "null";
if (root != null) {
int treeDepth = root.height();
List[] levels = new List[treeDepth];
for(int i = 0; i < levels.length; i++){
levels[i] = new ArrayList<Node>();
}
levels = getLevelsList(levels);
//Actually print everything.
for(int i = 0; i < levels.length; i++){
System.out.print("Lv" + i + ": ");
for(int j = 0; j < levels[i].size(); j++)
{
Node node = (Node)levels[i].get(j);
System.out.print(node.data + "["+node.weight+"]|P=" + (node.parent == null ? "NULL" : node.parent.data +"["+node.parent.weight+"]") + " ");
}
System.out.println();
}
} else {
System.out.println("There is no data in this tree. Root is null.");
}
} |
901a0e95-f2f7-4a6d-bb6f-5eb57d3a3bdf | 8 | public void update(ChiVertex<Integer, Integer> vertex, GraphChiContext context) {
final int iteration = context.getIteration();
final int numEdges = vertex.numEdges();
/* On first iteration, each vertex chooses a label equalling its id */
if (iteration == 0) {
vertex.setValue(vertex.getId());
/* Schedule the vertex itself for execution on next iteration */
context.getScheduler().addTask(vertex.getId());
}
/* Choose the smallest id of neighbor vertices. Each vertex
writes its label to its edges, so it can be accessed by neighbors.
*/
int curMin = vertex.getValue();
for(int i=0; i < numEdges; i++) {
int nbLabel = vertex.edge(i).getValue();
if (iteration == 0) nbLabel = vertex.edge(i).getVertexId(); // Note!
if (nbLabel < curMin) {
curMin = nbLabel;
}
}
/**
* Set my new label
*/
vertex.setValue(curMin);
int label = curMin;
/**
* Broadcast my value to neighbors by writing the value to my edges.
*/
if (iteration > 0) {
for(int i=0; i < numEdges; i++) {
if (vertex.edge(i).getValue() > label) {
vertex.edge(i).setValue(label);
context.getScheduler().addTask(vertex.edge(i).getVertexId());
}
}
} else {
// Special case for first iteration to avoid overwriting
for(int i=0; i < vertex.numOutEdges(); i++) {
vertex.outEdge(i).setValue(label);
}
}
} |
39711c49-c513-4902-b59e-92d1cb394017 | 7 | public static void startupOptimize() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/LOGIC", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupOptimize.helpStartupOptimize1();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupOptimize.helpStartupOptimize2();
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("GOAL-RECORD", "(DEFCLASS GOAL-RECORD (STANDARD-OBJECT) :SLOTS ((GENERATOR-GOALS :TYPE (LIST OF PROPOSITION) :ALLOCATION :EMBEDDED) (OTHER-GOALS :TYPE (LIST OF PROPOSITION) :ALLOCATION :EMBEDDED)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.powerloom.logic.GoalRecord", "newGoalRecord", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.powerloom.logic.GoalRecord", "accessGoalRecordSlotValue", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.GoalRecord"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupOptimize.helpStartupOptimize3();
_StartupOptimize.helpStartupOptimize4();
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("LOGIC")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *DISTRIBUTEDOPENGOAL?* BOOLEAN FALSE :DOCUMENTATION \"Used by 'distribute-open-goal' to signal that\na goal was distributed by 'help-distribute-goal'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-0-0 BOOLEAN-VECTOR (ZERO-ONE-LIST-TO-BOOLEAN-VECTOR (LIST 0 0)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-1-0 BOOLEAN-VECTOR (ZERO-ONE-LIST-TO-BOOLEAN-VECTOR (LIST 1 0)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-0-1 BOOLEAN-VECTOR (ZERO-ONE-LIST-TO-BOOLEAN-VECTOR (LIST 0 1)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-1-1 BOOLEAN-VECTOR (ZERO-ONE-LIST-TO-BOOLEAN-VECTOR (LIST 1 1)))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-1-0-AND-V-0-1 (LIST OF BOOLEAN-VECTOR) (LIST V-1-0 V-0-1))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-1-0-SINGLETON (LIST OF BOOLEAN-VECTOR) (LIST V-1-0))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT V-0-1-SINGLETON (LIST OF BOOLEAN-VECTOR) (LIST V-0-1))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-SLOT-VALUE-COLLECTION-SIZE COST-ESTIMATE 4.0 :DOCUMENTATION \"Estimate of the average size of a collection\nrepresenting the fillers of a slot.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-NUMBER-OF-PREDICATE-BINDINGS COST-ESTIMATE 6.0 :DOCUMENTATION \"Very crude estimate of the number of stored propositions\nthat will match a predicate at least one of whose arguments are bound.\nChosen to be larger than ESTIMATED-SLOT-VALUE-COLLECTION-SIZE.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-SIZE-OF-CLASS-EXTENSION COST-ESTIMATE 11.0 :DOCUMENTATION \"Must be greater than ESTIMATED-NUMBER-OF-PREDICATE-BINDINGS\nto force the optimizer to prefer predicates containing at least\none bound variable. Also greater than ESTIMATED-SIZE-OF-PREDICATE-EXTENSION,\nfor no particularly valid reason.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-CARDINALITY-OF-DESCRIPTION COST-ESTIMATE 20.0 :DOCUMENTATION \"Indefensible estimate of the number instances\ngenerable by an arbitrary unnamed description.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-CARDINALITY-OF-MEMBER-OF COST-ESTIMATE 30.0 :DOCUMENTATION \"Even more indefensible estimate of the number instances\ngenerable by a 'member-of' predicate. CAUTION: Must be set\nless than 'ESTIMATED-CARDINALITY-OF-SUBSET-OF'.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT ESTIMATED-CARDINALITY-OF-SUBSET-OF COST-ESTIMATE 40.0 :DOCUMENTATION \"Egregiously indefensible estimate of the number instances\ngenerable by a 'subset-of' predicate. Set high because 'subset-of'\ncan't generate all defined supersets or subsets, causing potential\nincompleteness.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT INFERABLE-PENALTY-COST COST-ESTIMATE 7.0 :DOCUMENTATION \"Amount of penalty for using inferable relations as goals.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFCONSTANT SUBSET-OF-PENALTY-COST COST-ESTIMATE 20.0 :DOCUMENTATION \"Amount of penalty for using 'subset-of' as a goal.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *OPTIMALGOALORDERINGRECURSIONS* INTEGER NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *OPTIMAL-GOAL-ORDERING-CUTOFF* INTEGER 100)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *QUERYOPTIMIZERCONTROLFRAME* CONTROL-FRAME :DOCUMENTATION \"Keeps track of last control frame allocated by\nthe query optimizer. Used by recursive invocations of the optimizer.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *BOUNDTOOFFSETCOUNTER* INTEGER NULL :DOCUMENTATION \"Enables 'select-optimal-query-pattern' to tell\n'copy-variables-vector' that it should initialize the 'bound-to-offset'\nslot of each variable in the copy operation.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *QUERY-OPTIMIZATION-STRATEGY* KEYWORD :DYNAMIC :DOCUMENTATION \"Keyword indicating what clause reordering strategy should\nbe used for conjunctive queries. Legal values are :STATIC which performs\noptimization once for each conjunctive pattern by simulating a query,\n:STATIC-WITH-CLUSTERING which additionally tries to cluster conjunction into\nindependent clusters, :DYNAMIC which performs simple greedy optimization\ndynamically during a query, :DYNAMIC-WITH-CLUSTERING which also looks\nfor clusters (not yet implemented), and :NONE to indicate no optimization\nshould be performed.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *POSTOPTIMIZATION?* BOOLEAN FALSE :DOCUMENTATION \"Used by 'simplify-description' to permit application\nof order-dependent optimizations.\")");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} |
c2e7c627-fedf-413a-8958-e620330a499e | 2 | public void doubleAster(String single) throws IOException {
int i = 0;
for (String double_block : single.split("<br />:?\\*\\* ")) {
double_block = double_block.replaceAll("<br />", "");
status[5] = double_block;
if (i > 0)
status[4] = "laka前に倣うslk";
addToArray(status);
i++;
}
} |
5b9699f6-9407-494d-8bda-e68799e1ab7f | 0 | @Override
public void setAddress(Address address) {
super.setAddress(address);
} |
38572e13-cf9a-47af-9280-8eca3c3d3b41 | 9 | public static void main(String[] args) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 0; i < isPrime.length; i++)
if (isPrime[i])
primes.add(i);
int[] primeSumTerms = new int[1000000];
for (int i = 0; i < primes.size(); i++) {
int terms = 1;
int sum = primes.get(i);
for (int j = i + 1; j < primes.size() && sum < 1000000; j++) {
sum += primes.get(j);
terms++;
if (sum < 1000000 && isPrime[sum])
primeSumTerms[sum] = Math.max(terms, primeSumTerms[sum]);
}
}
int maxTerms = 0;
int maxNum = 0;
for (int prime : primes) {
if (primeSumTerms[prime] > maxTerms){
maxTerms = primeSumTerms[prime];
maxNum = prime;
}
}
System.out.println(maxNum);
// Solution: 997651
} |
e24248c0-2f8a-41ab-944d-23e355144cf9 | 5 | @Override
public void doAction(String value) {
char choice = value.toUpperCase().charAt(0);
do {
switch (choice) {
case 'R': //return to game
return; //displays main menu
case 'S': //save the game by storing data away, and quit by cancelling game
MenuControl.saveGame();
MenuControl.quitGame();
break;
case 'Q': //cancels game
MenuControl.quitGame();
break;
case 'C': // display credits
displayCredits();
printQuitMenu();
break;
default:
System.out.println("\n*** Invalid selection *** Try again");
break;
}
choice = getInput().toUpperCase().charAt(0);
} while (true);
} |
70fb7a11-2674-42ee-a1d5-64a936a26c5f | 3 | public TraverseMode getNonTransitMode() {
if (contains(TraverseMode.CAR)) {
return TraverseMode.CAR;
}
if (contains(TraverseMode.BICYCLE)) {
return TraverseMode.BICYCLE;
}
if (contains(TraverseMode.WALK)) {
return TraverseMode.WALK;
}
return null;
} |
c14dbdd2-b9b9-4779-8886-ef3c92dcade5 | 2 | public ImageIcon getImage() {
System.out.println("Getting image");
if (image == null) {
if (imagePath != null) {
System.out.println(imagePath);
image = new ImageIcon(getClass().getResource("images/" + imagePath));
} else {
image = new ImageIcon();
}
}
return image;
} |
554acfd1-3ca6-4c39-a011-7da9d0c7fb00 | 6 | public static void main(String args[]) {
try {
System.out.println("RS2 user client - release #" + 317);
if (args.length != 5) {
System.out
.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
localWorldId = Integer.parseInt(args[0]);
portOffset = Integer.parseInt(args[1]);
if (args[2].equals("lowmem"))
setLowMemory();
else if (args[2].equals("highmem")) {
setHighMem();
} else {
System.out
.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
if (args[3].equals("free"))
membersWorld = false;
else if (args[3].equals("members")) {
membersWorld = true;
} else {
System.out
.println("Usage: node-id, port-offset, [lowmem/highmem], [free/members], storeid");
return;
}
signlink.storeid = Integer.parseInt(args[4]);
signlink.startpriv(InetAddress.getLocalHost());
Client client1 = new Client();
client1.createClientFrame(765, 503);
} catch (Exception exception) {
}
} |
4be341aa-b440-4615-b5c8-1ad2610a4797 | 6 | public int sarLookback( double optInAcceleration,
double optInMaximum )
{
if( optInAcceleration == (-4e+37) )
optInAcceleration = 2.000000e-2;
else if( (optInAcceleration < 0.000000e+0) || (optInAcceleration > 3.000000e+37) )
return -1;
if( optInMaximum == (-4e+37) )
optInMaximum = 2.000000e-1;
else if( (optInMaximum < 0.000000e+0) || (optInMaximum > 3.000000e+37) )
return -1;
return 1;
} |
5a147e6b-d0a9-47ec-8b7b-394eacc752d8 | 7 | */
public static void help(Cons commands) {
{ Cons thecommands = commands;
if (thecommands == Stella.NIL) {
{
System.out.println("The following commands are available (type `(help <command>+)'");
System.out.println("to get command-specific documentation):");
System.out.println();
}
;
{ List allcommands = Logic.listLogicCommands();
{ MethodSlot command = null;
Cons iter000 = allcommands.theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
command = ((MethodSlot)(iter000.value));
if (((StringWrapper)(KeyValueList.dynamicSlotValue(command.dynamicSlots, Logic.SYM_STELLA_DOCUMENTATION, Stella.NULL_STRING_WRAPPER))).wrapperValue != null) {
command.printDocumentation(Stella.STANDARD_OUTPUT, true);
}
}
}
{
System.out.println();
System.out.println("Undocumented Commands:");
System.out.println();
}
;
{ MethodSlot command = null;
Cons iter001 = allcommands.theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
command = ((MethodSlot)(iter001.value));
if (!(((StringWrapper)(KeyValueList.dynamicSlotValue(command.dynamicSlots, Logic.SYM_STELLA_DOCUMENTATION, Stella.NULL_STRING_WRAPPER))).wrapperValue != null)) {
System.out.println(command.slotName + ":");
}
}
}
}
}
else {
{ Symbol commandname = null;
Cons iter002 = thecommands;
for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) {
commandname = ((Symbol)(iter002.value));
{ MethodSlot command = Symbol.lookupCommand(commandname);
if (command != null) {
command.printDocumentation(Stella.STANDARD_OUTPUT, false);
}
else {
System.out.println("Undefined command: `" + commandname + "'");
}
}
}
}
}
}
} |
de384596-1d25-4cea-91f0-e4ebfa39284a | 5 | @Override
public void run() {
while(true){
try {
Thread.sleep(Delta);
} catch (InterruptedException e) {
e.printStackTrace();
}
// go through the list of timeStamps
Double[] ts = timestamps.toArray(new Double[timestamps.size()]);
for(int i = 0; i< ts.length; i++){
// if last timestamp exceeds given delta/ delay add to suspected list
if(System.currentTimeMillis()- ts[i] > delayForProcess.get(i) && !isSuspect(i)){
// add to suspect list
isSuspected(i);
calculateLeader();
}
}
}
} |
7b89a57a-8529-49d2-a093-44d66bfe8368 | 6 | public void eatFood() {
if (isCheap() && getHousingRole().getHouse() != null){
//DAVID I'm trying this out to see what happens...
print("Going to market to buy food to eat at home");
goToMarket();
print("Going to eat at home");
getHousingRole().msgEatAtHome();
mCommuterRole.mActive = true;
mCommuterRole.setLocation(getHousingRole().getLocation());
mCommutingTo = EnumCommuteTo.HOUSE;
mCommuterRole.mState = PersonState.walking;
}else{
print("Going to restaurant");
//set random restaurant
int restaurantChoice;
Random rand = new Random();
if (SimCityGui.TESTING) {
restaurantChoice = SimCityGui.TESTNUM; //override if testing
} else if(firstRun) {
restaurantChoice = mSSN % 8;
firstRun = false;
} else {
restaurantChoice = rand.nextInt(8);
}
RestaurantCustomerRole restCustRole = null;
for (Role iRole : mRoles.keySet()){
if (iRole instanceof RestaurantCustomerRole){
restCustRole = (RestaurantCustomerRole)iRole;
}
}
restCustRole.setRestaurant(restaurantChoice);
mRoles.put(restCustRole, true);
mCommuterRole.mActive = true;
mCommuterRole.setLocation(ContactList.cRESTAURANT_LOCATIONS.get(restaurantChoice));
mCommutingTo = EnumCommuteTo.RESTAURANT;
mCommuterRole.mState = PersonState.walking;
stateChanged();
}
} |
ec3e9d86-cb79-4b1b-8846-410f0a7a6c11 | 3 | @Override
public void run() {
while(true){
try {
ArrayList<ChatMessage> messageCopy = new ArrayList<>(writtenMessages);
writtenMessages.clear();
for (ChatMessage chatMessage : messageCopy) {
dbCon.addMessage(chatMessage);
}
writtenMessages.clear();
loadMessages();
loadUsers();
sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
} |
5287962c-f3b5-488b-8416-0f35c02177c1 | 1 | public MainMenu() {
Random rand = new Random();
menu = new OptionsMenu();
config.loadConfig("settings", ".xml");
sound = Config.songs.get(rand.nextInt(Config.songs.size()));
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setPreferredSize(new Dimension(800, 400));
frame.setUndecorated(true);
frame.setResizable(false);
frame.setTitle("MainMenu");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//setContentPane(contentPane);
contentPane.setLayout(null);
drawButtons();
InputHandler input = new InputHandler();
addMouseListener(input);
addMouseMotionListener(input);
addKeyListener(input);
addFocusListener(input);
frame.repaint();
} |
ec1eb1bd-3874-4c74-b95c-34cb17bcdb02 | 2 | public void persistTransactionSet(TransactionSet transactionSet) {
String sqlStatement;
dao.connect();
sqlStatement = generateInsertStmt(transactionSet);
if(dao.getErrorLogs().getErrorMsgs().size() == 0){
dao.executeUpdate(sqlStatement);
}
if(dao.getErrorLogs().getErrorMsgs().size() == 0){
dao.disconnect();
}
} |
f1443e42-5e8c-43fa-8eb3-933958553ee7 | 8 | public Matrix solve (Matrix B) {
if (B.getRowDimension() != n) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!isspd) {
throw new RuntimeException("Matrix is not symmetric positive definite.");
}
// Copy right hand side.
double[][] X = B.getArrayCopy();
int nx = B.getColumnDimension();
// Solve L*Y = B;
for (int k = 0; k < n; k++) {
for (int j = 0; j < nx; j++) {
for (int i = 0; i < k ; i++) {
X[k][j] -= X[i][j]*L[k][i];
}
X[k][j] /= L[k][k];
}
}
// Solve L'*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
for (int i = k+1; i < n ; i++) {
X[k][j] -= X[i][j]*L[i][k];
}
X[k][j] /= L[k][k];
}
}
return new Matrix(X,n,nx);
} |
531963ae-6926-4d88-b337-2058872abac5 | 6 | private void saveFile() {
byte[] data = new byte[this.torrentInfo.file_length];
System.out.println("building file...");
for(int i : this.pieces.keySet()){
Piece p = pieces.get(i);
int pind = p.getIndex();
byte[] pdata = p.getData();
int dataOffset = pind * this.torrentInfo.piece_length;
if(pind < 0)
continue;
for(int j = 0; j < pdata.length && dataOffset + j < data.length; j++){
data[dataOffset + j] = pdata[j];
}
}
BufferedOutputStream bos;
try {
System.out.println("saving file...");
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(data);
bos.flush();
bos.close();
System.out.println("File Saved.");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
1bda4133-828d-4d2d-9490-b42b5db0a1ad | 4 | public static Object[] getSinkVertices(mxAnalysisGraph aGraph) throws StructuralException
{
if (!mxGraphProperties.isDirected(aGraph.getProperties(), mxGraphProperties.DEFAULT_DIRECTED))
{
throw new StructuralException("The graph is undirected, so it can't have sink vertices.");
}
ArrayList<Object> sourceList = new ArrayList<Object>();
Object[] vertices = aGraph.getChildVertices(aGraph.getGraph().getDefaultParent());
for (int i = 0; i < vertices.length; i++)
{
Object currVertex = vertices[i];
Object[] outEdges = aGraph.getEdges(vertices[i], null, false, true, true, true);
Object[] inEdges = aGraph.getEdges(vertices[i], null, true, false, true, true);
if (inEdges.length > 0 && outEdges.length == 0)
{
sourceList.add(currVertex);
}
}
return sourceList.toArray();
}; |
7c096898-27ef-451b-934f-99372601ab38 | 2 | @Override
public boolean equals(Object obj) {
if (obj instanceof Piece) {
Piece otherPiece = (Piece)obj;
return this.name.equals(otherPiece.name) &&
this.color == otherPiece.color;
}
return false;
} |
84449caa-855e-4cf3-b584-083db4c41e28 | 2 | public void begin(){
while(true){
partida.mover();
repaint();
try{
Thread.sleep(18);
}catch(InterruptedException e){}
}
} |
378387e5-ab49-4121-a021-aeb16327861b | 2 | public void run()
{
try
{
PrintWriter out =
new PrintWriter(socket.getOutputStream(),true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String userInput;
while ((userInput = in.readLine()) != null)
{
out.println("Echo " +userInput);
}
}
catch (Exception E)
{
System.out.println("something went wrong");
}
} |
50e198f5-312e-41e7-98f0-f03ff01f5bac | 8 | public double[][] createLattice(int rows, int cols, double rate,
double up, double down, double q)
{
double[][] lattice = new double[rows][cols];
for(int row = 0; row < rows; ++row)
{
for(int col = 0; col < cols; ++col)
{
/*
* Generate the first column and first row with the value
* of the 'rate' constant
*/
if(row == 0 && col == 0)
{
lattice[0][0] = rate;
}
/*
* Generate data for all columns > 0 in row 0
*/
else if(row == 0 && col != 0)
{
lattice[row][col] = down * lattice[row][col - 1];
}
/*
* Where the row number is equal to the column number, multiply
* 'up' constant times the value in lattice[row-1][column-1].
* All other values in this row will be dealt with in the next
* conditional.
*/
else if(row == col)
{
lattice[row][col] = up * lattice[row - 1][col - 1];
}
/*
* Generate data for all columns greater than the row number.
* This will only work where the values have already been
* generated where row number equal column number as set forth
* in the preceding conditional.
*/
else if(row < col)
{
lattice[row][col] = up * lattice[row - 1][col - 1];
}
}
}
return lattice;
} |
0966e4a1-5500-4cc2-a757-46cd6be475e3 | 5 | public void compareSignaturesFromFile(String inputfile, String outputfile)
{
try {
BufferedReader br = new BufferedReader(new FileReader(inputfile));
File output = new File(outputfile);
FileWriter writer = new FileWriter(output);
String line;
while ((line = br.readLine()) != null) {
String[] tokens = line.split(" ");
if (tokens.length != 2) {
System.err.println("Malformed input file.");
return;
}
// Create signatures
Signature s1 = new Signature(tokens[0]);
Signature s2 = new Signature(tokens[1]);
// Preprocess signatures
Preprocessor.normalizeAndReduce(s1);
Preprocessor.normalizeAndReduce(s2);
// Compare signatures
CompareResult res = Comparator.compareSignatures(s1, s2, this.threshold);
// Write result
writer.write(line + " " + res.distance + " " + res.getDecision() + System.getProperty("line.separator"));
}
br.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
}
} |
cc55e81e-3898-4c6e-b101-5618e04d4259 | 0 | public void setSeatType(long value) {
this._seatType = value;
} |
f9562c64-d7b3-4e75-9d69-faecd61fc995 | 3 | public static Object getDirectedLeaf(mxAnalysisGraph aGraph, Object parent)
{
Object[] vertices = aGraph.getChildVertices(parent);
int vertexNum = vertices.length;
Object currVertex;
for (int i = 0; i < vertexNum; i++)
{
currVertex = vertices[i];
int inEdgeCount = aGraph.getEdges(currVertex, parent, true, false, false, true).length;
int outEdgeCount = aGraph.getEdges(currVertex, parent, false, true, false, true).length;
if (outEdgeCount == 0 || inEdgeCount == 0)
{
return currVertex;
}
}
return null;
}; |
21e40681-0db9-4a8a-b139-03755e4d9b14 | 4 | public static boolean line_line(double x0, double y0, double x1, double y1, double x2, double y2, double x3, double y3){
double f1 = (x1 - x0);
double g1 = (y1 - y0);
double f2 = (x3 - x2);
double g2 = (y3 - y2);
double f1g2 = f1 * g2;
double f2g1 = f2 * g1;
double det = f2g1 - f1g2;
if(Math.abs(det) > ACCY){
double s = (f2*(y2 - y0) - g2*(x2 - x0))/ det;
double t = (f1*(y2 - y0) - g1*(x2 - x0))/ det;
return (s >= 0 && s <= 1 && t >= 0 && t <= 1);
}
return false;
} |
405da865-46a9-4da3-ace3-24ba761b74dd | 0 | public String getName ()
{
return name;
} |
196e3ca4-20a9-42a4-9139-6bdb1df48d92 | 6 | public void updateCondition(
float newCondition, boolean normalState, boolean burning
) {
//
// Firstly, make any necessary state transitions-
final float oldCondition = condition ;
condition = newCondition ;
if (scaffolding == null && ! normalState) {
clearAllAttachments() ;
scaffolding = scaffoldFor(size, high, condition) ;
attach(scaffolding, 0, 0, 0) ;
}
if (scaffolding != null && normalState) {
clearAllAttachments() ;
scaffolding = null ;
attach(baseSprite, 0, 0, 0) ;
}
//
// Then, update appearance based on current condition-
if (scaffolding != null) {
final int oldStage = scaffoldStage(size, high, oldCondition) ;
final int newStage = scaffoldStage(size, high, newCondition) ;
if (oldStage == newStage) return ;
clearAllAttachments() ;
scaffolding = scaffoldFor(size, high, newCondition) ;
attach(scaffolding, 0, 0, 0) ;
}
else {
final float c = (1 - condition) ;
this.fog *= (4 - (c * c)) / 4f ;
}
} |
465b2fd9-b95c-45fe-b434-66405dfb1f3e | 7 | @Override
protected void process() {
super.process();
Monster actor = (Monster) ai.getActor();
Player player = getPlayerToAttack(actor);
if (actor == null || player == null) {
terminate();
return;
}
if (actor.isFeared() && actor.getFearedSource() != null) {
actor.moveAwayFromPoint(actor.getFearedSource());
} else {
actor.moveTowardsPoint(player.getCenterPoint());
}
if (player != null) {
if (player.getPerimeter().intersects(actor.getPerimeter())) {
actor.attack();
} else {
if (actor.isAttacking()) {
actor.stopAttack();
}
}
}
} |
0dee82e4-6a10-4a3f-bc87-89bf475c5798 | 3 | public List<POWMessage> getObjects(List<InventoryVectorMessage> inventoryVectors) {
List<POWMessage> objects = new ArrayList<>(inventoryVectors.size());
for (InventoryVectorMessage m : inventoryVectors) {
POWMessage p = objectCache.get(m);
if (p != null) {
objects.add(p);
} else {
p = database.getObject(m);
if (p != null) {
objects.add(p);
}
}
}
return objects;
} |
06a88a90-5d6a-4f8f-9664-e8884c2fbb34 | 9 | public static void main(String[] args) throws Exception {
bytes = new byte[800000000];
urlmap = new HashMap<String, ArrayList<Integer>>(4500000);
HashMap<Long, Integer> map = readHashMap("UsersMapping");
File dir = new File(inDirectory);
int cnt = 0;
long t1 = System.currentTimeMillis();
int totalUsers = 0;
File[] lista = dir.listFiles();
// sorting in time so that the data is sorted in time
Arrays.sort(lista, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
System.out.println("Number of files : " + lista.length);
for (File f : lista) {
if (f.getName().endsWith(".txt")) {
cnt++;
System.out.println(cnt + " Read File : " + f.getName());
FileInputStream fis;
DataInputStream dis = new DataInputStream(
fis = new FileInputStream(f));
int size = dis.available();
dis.read(bytes);
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(bytes));
try {
w: while (true) {
Status status = (Status) ois.readObject();
URLEntity[] urlEntity = status.getURLEntities();
for (int i = 0; i < urlEntity.length; i++) {
String url = urlEntity[i].getExpandedURL();
if (!urlmap.containsKey(url))
urlmap.put(url, new ArrayList<Integer>());
ArrayList<Integer> list = urlmap.get(url);
if (!map.containsKey(status.getUser().getId()))
continue w;
int id = map.get(status.getUser().getId());
if (list.size() < MAX_SIZE) {
list.add(id);
totalUsers++;
}
}
}
} catch (Exception e) {
}
fis.close();
dis.close();
}
System.out.println(totalUsers);
if (totalUsers > MAX_NUM_USERS)
break;
}
System.out.println("Finish Files");
writeHashMap(URLS_MAP_FILE, urlmap);
System.out.println("== FINISHED Successfully ==");
System.out
.println("Finished in : " + (System.currentTimeMillis() - t1));
} |
162b0d31-d831-446d-8aec-c0b3ba1ccc90 | 3 | private void editParamCell() {
int row = table.getSelectedRow();
if (row >= 0) {
ParameterEditor pe = new ParameterEditor(model.getParameter(row));
if (pe.isOk()) {
try {
model.update(row, pe.getFormula());
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
}
} |
269d3685-c39f-4c9f-b838-a8c0b45d61c5 | 4 | public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
} |
b32ebd78-179a-4a71-992a-bb0ba86f1b51 | 3 | * @return boolean whether the two decks contain the same order of cards
*/
public boolean equalsInOrder(Deck d) {
if (this.cardArray.length != d.cardArray.length)
return false;
for (int i = 0; i < cardArray.length; i++) {
if (cardArray[i].compareTo(d.cardArray[i]) != 0) {
return false;
}
}
return true;
} |
0d24eb32-f443-4a81-acb9-c22e46e3ef57 | 7 | protected void genDoorsNLocks(MOB mob, CloseableLockable E, String doorName, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
boolean HasDoor=E.hasADoor();
boolean Open=E.isOpen();
boolean DefaultsClosed=E.defaultsClosed();
boolean HasLock=E.hasALock();
boolean Locked=E.isLocked();
boolean DefaultsLocked=E.defaultsLocked();
if((showFlag!=showNumber)&&(showFlag>-999))
{
mob.tell(L("@x1. Has a @x5: @x2\n\r Has a lock : @x3\n\r Open ticks: @x4",""+showNumber,""+E.hasADoor(),""+E.hasALock(),""+E.openDelayTicks(),doorName));
return;
}
if(genGenericPrompt(mob,"Has a "+doorName,E.hasADoor()))
{
HasDoor=true;
DefaultsClosed=genGenericPrompt(mob,"Defaults closed",E.defaultsClosed());
Open=!DefaultsClosed;
if(genGenericPrompt(mob,"Has a lock",E.hasALock()))
{
HasLock=true;
DefaultsLocked=genGenericPrompt(mob,"Defaults locked",E.defaultsLocked());
Locked=DefaultsLocked;
}
else
{
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
mob.tell(L("\n\rReset Delay (# ticks): '@x1'.",""+E.openDelayTicks()));
final int newLevel=CMath.s_int(mob.session().prompt(L("Enter a new delay\n\r:"),""));
if(newLevel>0)
E.setOpenDelayTicks(newLevel);
else
mob.tell(L("(no change)"));
}
else
{
HasDoor=false;
Open=true;
DefaultsClosed=false;
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
E.setDoorsNLocks(HasDoor,Open,DefaultsClosed,HasLock,Locked,DefaultsLocked);
} |
f2b44562-04d1-4468-89d3-6a376632b4bc | 0 | public void pulse() {
DCPackage pulsePackage = new DCPackage(currentRound, new byte[DCPackage.PAYLOAD_SIZE]);
currentRound = (currentRound+1) % pulsePackage.getNumberRange();
resetRound();
broadcast(pulsePackage);
} |
26edc6e1-c5fb-4075-b90e-9a9e351f4a88 | 2 | public void bornAgain()
{
if (getParent() != null)
{
if (getParent().getParent() != null)
{
getParent().getParent().repaint();
}
}
} |
367d8f0c-2e65-4136-9eb9-fdc7657dcfc5 | 6 | public void update(Observable o, Object arg) {
String name, str, text, textFinal, requete;
List<String> keywords = sqlCommand.getKeywords();
List<String> types = sqlCommand.getTypes();
//textFinal = "<html><body style=\"font-family:Geneva,Arial,Helvetica,sans-serif;font-size:11px;\">";
textFinal = "<html><body><PRE>";
text = sqlCommand.getRequests() ;
for (StringTokenizer st = new StringTokenizer(text, " (),<>;", true); st
.hasMoreElements();) {
str = st.nextToken() ;
str = str.replace(",", ",<br>") ;
if (keywords.contains(str))
textFinal += "<b style=\"color: blue;\">" + str + "</b>";
else if (types.contains(str))
textFinal += "<b style=\"color: red;\">" + str + "</b>";
else if (str.equals("(") || str.equals(")"))
textFinal += "<b>" + str + "</b>";
else if (str.equals(";"))
textFinal += ";<br><br>";
else
textFinal += str;
}
textFinal += "</PRE></body></html>";
textFinal = textFinal.replace("<br><br><b style=\"color: blue;\">CREATE", "<br><b style=\"color: blue;\">CREATE") ;
textFinal = textFinal.replace("<b>)</b>;<br><br>", "<b>)</b>;<br>" ) ;
editor.setText(textFinal);
state.setText(sqlCommand.getLabelState());
} |
eb49a55e-0362-4cc0-885d-1d86d97e5cd0 | 4 | public static byte[] dumpElement(TypeModel tm) {
ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
String name = tm.bcType();
cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, name + "Element", "L" + collections + "impl/AbstractHugeElement<L" + name + "Allocation;>;L" + name + ";Ljava/io/Externalizable;", collections + "impl/AbstractHugeElement", new String[]{name, "java/io/Externalizable"});
cw.visitSource(tm.type().getSimpleName() + "Element.java", null);
{
fv = cw.visitField(0, "allocation", "L" + name + "Allocation;", null, null);
fv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "(L" + collections + "impl/AbstractHugeArrayList;J)V", "(L" + collections + "impl/AbstractHugeArrayList<L" + name + ";L" + name + "Allocation;L" + name + "Element;>;J)V", null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(34, l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(LLOAD, 2);
mv.visitMethodInsn(INVOKESPECIAL, collections + "impl/AbstractHugeElement", "<init>", "(L" + collections + "impl/AbstractHugeContainer;J)V");
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLineNumber(35, l1);
mv.visitInsn(RETURN);
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this", "L" + name + "Element;", null, l0, l2, 0);
mv.visitLocalVariable("list", "L" + collections + "impl/AbstractHugeArrayList;", "L" + collections + "impl/AbstractHugeArrayList<L" + name + ";L" + name + "Allocation;L" + name + "Element;>;", l0, l2, 1);
mv.visitLocalVariable("n", "J", null, l0, l2, 2);
mv.visitMaxs(4, 4);
mv.visitEnd();
}
for (FieldModel fm : tm.fields()) {
///////// SETTER //////////
int maxLocals = 2 + fm.bcFieldSize();
mv = cw.visitMethod(ACC_PUBLIC, "set" + fm.titleFieldName(), "(" + fm.bcLFieldType() + ")V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(39, l0);
int invoke = INVOKESTATIC;
if (fm.virtualGetSet()) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "container", "L" + collections + "impl/AbstractHugeContainer;");
mv.visitTypeInsn(CHECKCAST, name + "ArrayList");
mv.visitFieldInsn(GETFIELD, name + "ArrayList", fm.fieldName() + "FieldModel", fm.bcLModelType());
invoke = INVOKEVIRTUAL;
maxLocals++;
}
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "allocation", "L" + name + "Allocation;");
mv.visitFieldInsn(GETFIELD, name + "Allocation", "m_" + fm.fieldName(), fm.bcLStoreType());
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "offset", "I");
mv.visitVarInsn(loadFor(fm.bcType()), 1);
mv.visitMethodInsn(invoke, fm.bcModelType(), "set", "(" + fm.bcLStoreType() + "I" + fm.bcLSetType() + ")V");
mv.visitInsn(RETURN);
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this", "L" + name + "Element;", null, l0, l2, 0);
mv.visitLocalVariable("elementType", "Ljava/lang/annotation/ElementType;", null, l0, l2, 1);
mv.visitMaxs(maxLocals, 1 + fm.bcFieldSize());
mv.visitEnd();
///////// GETTER //////////
mv = cw.visitMethod(ACC_PUBLIC, "get" + fm.titleFieldName(), "()" + fm.bcLFieldType(), null, null);
mv.visitCode();
Label l3 = new Label();
mv.visitLabel(l3);
mv.visitLineNumber(144, l3);
BCType bcType = fm.bcType();
if (fm.virtualGetSet()) {
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "container", "L" + collections + "impl/AbstractHugeContainer;");
mv.visitTypeInsn(CHECKCAST, name + "ArrayList");
mv.visitFieldInsn(GETFIELD, name + "ArrayList", fm.fieldName() + "FieldModel", fm.bcLModelType());
bcType = BCType.Reference;
}
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "allocation", "L" + name + "Allocation;");
mv.visitFieldInsn(GETFIELD, name + "Allocation", "m_" + fm.fieldName(), fm.bcLStoreType());
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "offset", "I");
mv.visitMethodInsn(invoke, fm.bcModelType(), "get", "(" + fm.bcLStoreType() + "I)" + fm.bcLSetType());
if (!fm.bcLSetType().equals(fm.bcLFieldType()))
mv.visitTypeInsn(CHECKCAST, fm.bcFieldType());
mv.visitInsn(returnFor(bcType));
Label l4 = new Label();
mv.visitLabel(l4);
mv.visitLocalVariable("this", "L" + name + "Element;", null, l3, l4, 0);
mv.visitMaxs(4, 2);
mv.visitEnd();
}
{
mv = cw.visitMethod(ACC_PROTECTED, "updateAllocation0", "(I)V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(170, l0);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "container", "L" + collections + "impl/AbstractHugeContainer;");
mv.visitVarInsn(ALOAD, 0);
mv.visitFieldInsn(GETFIELD, name + "Element", "index", "J");
mv.visitMethodInsn(INVOKEVIRTUAL, collections + "impl/AbstractHugeContainer", "getAllocation", "(J)L" + collections + "api/HugeAllocation;");
mv.visitTypeInsn(CHECKCAST, name + "Allocation");
mv.visitFieldInsn(PUTFIELD, name + "Element", "allocation", "L" + name + "Allocation;");
Label l1 = new Label();
mv.visitLabel(l1);
mv.visitLineNumber(171, l1);
mv.visitInsn(RETURN);
Label l2 = new Label();
mv.visitLabel(l2);
mv.visitLocalVariable("this", "L" + name + "Element;", null, l0, l2, 0);
mv.visitLocalVariable("allocationSize", "I", null, l0, l2, 1);
mv.visitMaxs(4, 2);
mv.visitEnd();
}
appendToStringHashCodeEqualsCopyOf(tm, cw, name + "Element", true);
cw.visitEnd();
final byte[] bytes = cw.toByteArray();
// ClassReader cr = new ClassReader(bytes);
// cr.accept(new ASMifierClassVisitor(new PrintWriter(System.out)), 0);
return bytes;
} |
7ab4658f-e8dc-487e-871c-03c076968e97 | 8 | public long FindSumOfPandigitalNumbersWithAscendingPrimeSubStringDivisibilityProperty() {
Permutizer permutizer = new Permutizer();
long toReturn = 0;
String currentPandigitalNumber = "0123456789";
do{
int twothreefour = Integer.parseInt(
currentPandigitalNumber.substring(1, 2)
+ currentPandigitalNumber.substring(2, 3)
+ currentPandigitalNumber.substring(3, 4) );
int threefourfive = Integer.parseInt(
currentPandigitalNumber.substring(2, 3)
+ currentPandigitalNumber.substring(3, 4)
+ currentPandigitalNumber.substring(4, 5) );
int fourfivesix = Integer.parseInt(
currentPandigitalNumber.substring(3, 4)
+ currentPandigitalNumber.substring(4, 5)
+ currentPandigitalNumber.substring(5, 6) );
int fivesixseven = Integer.parseInt(
currentPandigitalNumber.substring(4, 5)
+ currentPandigitalNumber.substring(5, 6)
+ currentPandigitalNumber.substring(6, 7));
int sixseveneight = Integer.parseInt(
currentPandigitalNumber.substring(5, 6)
+ currentPandigitalNumber.substring(6, 7)
+ currentPandigitalNumber.substring(7, 8));
int seveneightnine = Integer.parseInt(
currentPandigitalNumber.substring(6, 7)
+ currentPandigitalNumber.substring(7, 8)
+ currentPandigitalNumber.substring(8, 9));
int eightnineten = Integer.parseInt(
currentPandigitalNumber.substring(7, 8)
+ currentPandigitalNumber.substring(8, 9)
+ currentPandigitalNumber.substring(9, 10));
if(twothreefour % 2 == 0 && threefourfive % 3 ==0 && fourfivesix % 5 == 0
&& fivesixseven % 7 == 0 && sixseveneight % 11 == 0 && seveneightnine % 13== 0
&& eightnineten % 17 == 0)
{
toReturn += Long.parseLong(currentPandigitalNumber);
}
currentPandigitalNumber = permutizer.GetNextPermutation(currentPandigitalNumber);
}while (!currentPandigitalNumber.equals(""));
return toReturn;
} |
c4c3ca66-fd20-40b6-ad73-2cb5bbcb2a65 | 5 | public LedString(int x, int y, String s) {
this.x = x;
this.y = y;
stringShapes = new LedShape[s.length()];
int xOffset = x;
for(int i = 0; i < s.length(); i++) {
stringShapes[i] = charToShape(s.charAt(i));
stringShapes[i].setXY(xOffset, y);
if(stringShapes[i].width == 0)
stringShapes[i].moveX(4);
else if(i > 0){
LedShape prev = stringShapes[i-1];
while(stringShapes[i].intersects(prev))
stringShapes[i].moveX(1);
stringShapes[i].moveX(1);
}
xOffset = stringShapes[i].width != 0 ? stringShapes[i].getX() : 4;
}
} |
411a833d-7061-47c3-a1ac-f88f62403e48 | 7 | public List<Subset> filterSubset(List<Subset> subsetList, int preferredSize){
if(subsetList.size () <=preferredSize && preferredSize !=-1)return subsetList;
for (int i =0; i <subsetList.size ()-1; i ++) {
for (int j =i+1; j <subsetList.size (); j ++) {
Subset focus =subsetList.get (i);
if(focus.isEqual (subsetList.get (j))){
subsetList.remove (j);
j--;
if(subsetList.size () <=preferredSize && preferredSize !=-1)return subsetList;
}
}
}
return subsetList;
} |
b98854cf-8dc7-440e-88c4-6602fcc6faa4 | 8 | private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
Component node = (Component) jTree1.getLastSelectedPathComponent();
//System.out.println(node.getClass());
String description = null;
if (node != null) {
if (node.getClass() == Tasks.Action.class || node.getClass() == Tasks.Job.class || node.getClass() == Tasks.Task.class) {
logoLabel.setVisible(false);
taskManiaWelcome.setVisible(false);
taskName.setText(node.getName());
statusLabel.setVisible(true);
deleteButton.setVisible(true);
taskStatus.setText(node.getState());
if (node.getClass() == Tasks.Task.class) {
taskName.setText(node.getName());
taskName.setVisible(true);
descriptionLabel.setVisible(true);
taskDescription.setText(node.getDescription());
taskDescription.setCaretPosition(0);
taskDescription.setVisible(true);
actionDescription.setCaretPosition(0);
statusLabel.setVisible(true);
deleteButton.setVisible(true);
taskStatus.setText(node.getState());
jobPane.setVisible(false);
actionPane.setVisible(false);
taskPane.setVisible(true);
((ImagePanel) taskPane).task = true;
taskTimeSpent.setVisible(true);
timeSpentLabel.setVisible(true);
playLabel.setVisible(true);
stopLabel.setVisible(true);
pauseLabel.setVisible(true);
taskStatus.setVisible(true);
taskTimeSpent.setText(Time.periodToFormat(((Tasks.Task) node).getElapsedTime()));
} else {
taskPane.setVisible(false);
if (node.getClass() == Tasks.Job.class) {
((ImagePanel) jobPane).task = false;
jobPane.setVisible(true);
actionPane.setVisible(false);
taskPane.setVisible(false);
taskTimeSpent1.setText(Time.periodToFormat(((Tasks.Job) node).getElapsedTime()));
taskTimeSpent1.setVisible(true);
timeSpentLabel1.setVisible(true);
taskName1.setText(node.getName());
taskName1.setVisible(true);
jobLabel.setVisible(true);
taskStatus1.setText(node.getState());
taskStatus1.setVisible(true);
descriptionLabel1.setVisible(true);
jobDescription.setVisible(true);
jobDescription.setText(node.getDescription());
jobDescription.setCaretPosition(0);
statusLabel1.setVisible(true);
deleteButtonJob.setVisible(true);
} else if (node.getClass() == Tasks.Action.class) {
((ImagePanel) actionPane).task = false;
actionPane.setVisible(true);
jobPane.setVisible(false);
taskPane.setVisible(false);
actionName.setText(node.getName());
descriptionLabel2.setVisible(true);
actionDescription.setText(node.getDescription());
actionDescription.setCaretPosition(0);
statusLabel2.setVisible(true);
deleteButtonAction.setVisible(true);
taskStatus2.setText(node.getState());
actionLabel.setVisible(true);
actionName.setVisible(true);
actionDescription.setVisible(true);
taskStatus2.setVisible(true);
if (((Tasks.Action) node).getState().equals("To Do")) {
doneButton.setVisible(true);
}
}
}
}
}
jobPane.repaint();
actionPane.repaint();
taskPane.repaint();
}//GEN-LAST:event_jTree1MouseClicked |
8632b17c-0096-4817-afac-de5f9f87a7e9 | 3 | @SuppressWarnings("unused")
public static void main(String[] args) {
if (args.length < 1) {
System.out
.println("Argumentos insuficientes para ejecutar la aplicación.");
} else {
if (args[0].toLowerCase().equals(MODO_CLIENTE)) {
ControladorCliente c = new ControladorCliente();
} else if (args[0].toLowerCase().equals(MODO_SERVIDOR)) {
ControladorServidor s = new ControladorServidor();
s.iniciarConexion();
} else {
System.out
.println("Argumento erroneo, ingrese 'c' para cliente o 's' para servidor.");
}
}
} |
33daeb42-0de5-4a83-ae1c-e1176f2b2f49 | 0 | public String getAlertDescription() {
return alertDescription;
} |
d9d36180-c469-484f-829f-90a857b1231c | 4 | private void chooseNewPlaylist() {
if(!LockedPlaylistValueAccess.lockedPlaylist) {
newFilePath = fileChooser.getNewFilePath();
String[] options = {};
// Only change the playlist if the new path is different from the old one.
if((currentFilePath != newFilePath) && (newFilePath != null)) {
mediaPlayer.stop();
mediaListPlayer.stop();
ArrayList<String> files = getFilenames(newFilePath);
createList(files);
currentFilePath = newFilePath;
mediaList.clear();
// Add the new items to the playlist.
for(String filename : files) {
mediaList.addMedia(newFilePath + "\\" + filename, options);
}
mediaListPlayer.setMediaList(mediaList);
mediaListPlayer.setMode(MediaListPlayerMode.LOOP);
mediaListPlayer.setMediaPlayer(mediaPlayer);
mediaPlayer.release();
mainFrame.dispose();
mainFrame.setVisible(false);
mediaPlayer = openMediaPlayer();
currentPlayIndex = 0;
playContentsJList.repaint();
}
}
} |
c5065a50-284c-44bb-97dd-201cef6bc1f0 | 9 | public boolean addTile(int x, int y, Tile tile)
{
Tile old = getLowestTile(x, y);
if(old == null)
return false;
if(old.height == tile.height)
{
tile.next = old.next;
tiles.set(getPos(x, y, this.width, this.height), tile);
return true;
}
do
{
if(old.height == tile.height)
{
old.data = tile.data;
return true;
}
else if(old.next != null)
{
if(old.next.height > tile.height && old.height < tile.height)
{
tile.next = old.next;
old.next = tile;
return true;
}
}
else if(old.height < tile.height)
{
if(old.next == null)
{
old.next = tile;
return true;
}
}
old = old.next;
}
while(old != null);
/*System.out.println("added a tile");
System.out.print(x); System.out.print(" "); System.out.println(y);
System.out.println(tile.data);
System.out.println(tile.height);*/
//return false;
return false;
} |
ce7a4d3b-f30d-41e1-9ebf-805cc867e12d | 7 | public void doCommand(int command) {
switch (command) {
case P2:
case P3:
case P4:
main.newGame(selection + 2);
break;
case CONTROL_SETUP:
new BomberConfigDialog(main);
break;
case EXIT:
/** create the dialog content */
JOptionPane pane =
new JOptionPane("Are you sure you want to exit Bomberman?");
/** setup the dialog content */
pane.setOptionType(JOptionPane.YES_NO_OPTION);
pane.setMessageType(JOptionPane.WARNING_MESSAGE);
/** create the dialog */
JDialog dialog = pane.createDialog(this, "Exit Bomberman?");
dialog.setResizable(false);
/** show the dialog */
dialog.show();
Object selection = pane.getValue();
/** if user clicked on yes */
if (selection != null && selection.toString().equals("0"))
/** terminate the program */
System.exit(0);
}
} |
ffddff1c-86d2-4487-83b0-537c4bda23b8 | 6 | private String getMime(String extension) {
String mime = "";
switch (extension) {
case ".pdf":
mime = "application/pdf";
break;
case ".png":
mime = "image/png";
case ".css":
mime = "text/css";
break;
case ".js":
mime = "text/javascript";
break;
case ".html":
mime = "text/html";
break;
case ".jar":
mime = "application/java-archive";
break;
}
return mime;
} |
0a44ac0e-b2c1-43fc-ad1b-54e86c27e414 | 0 | protected Field getField()
{
return field;
} |
e4b8a9cc-adec-4efc-99f9-c76c30b49961 | 1 | protected Token jjFillToken()
{
final Token t;
final String curTokenImage;
final int beginLine;
final int endLine;
final int beginColumn;
final int endColumn;
String im = jjstrLiteralImages[jjmatchedKind];
curTokenImage = (im == null) ? input_stream.GetImage() : im;
beginLine = input_stream.getBeginLine();
beginColumn = input_stream.getBeginColumn();
endLine = input_stream.getEndLine();
endColumn = input_stream.getEndColumn();
t = Token.newToken(jjmatchedKind, curTokenImage);
t.beginLine = beginLine;
t.endLine = endLine;
t.beginColumn = beginColumn;
t.endColumn = endColumn;
return t;
} |
68f1fffc-45b6-4f44-8c16-5c75f0a9a576 | 7 | public static void main(String[] args) {
try {
Integer max = 0;
Integer min = 0;
Integer maxGoal = 0;
Integer minGoal = 0;
String maxName = "";
String minName = "";
String teamName="";
Scanner scanner = new Scanner(new File("file_Location/football.dat"));
while (scanner.hasNext()) {
String string = scanner.nextLine();
Matcher matcherName = Pattern.compile("\\s[aA-zZ]+").matcher(string);
Matcher forPattern = Pattern.compile("\\d[0-9]\\s+-").matcher(string);
Matcher againstPattern = Pattern.compile("-\\s+[0-9]+").matcher(string);
while (matcherName.find()) {
teamName = matcherName.group().trim();
}
while (forPattern.find()) {
max = new Integer(forPattern.group().replace("-", " ").trim());
}
while (againstPattern.find()) {
min = new Integer(againstPattern.group().replace("-", " ").trim());
}
if (maxGoal > (max - min)) {
} else {
maxGoal = max - min;
maxName = teamName;
}
if (minGoal < (max - min)) {
} else {
minGoal = max - min;
minName = teamName;
}
}
System.out.println("Maximum Goal scored team:");
System.out.println(maxName + ":" + maxGoal + "\n");
System.out.println("Minimum Goal scored team:");
System.out.println(minName + ":" + minGoal);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} |
657df89a-758d-4c5a-b518-c2719ccdba0d | 1 | private String _parseMessage(String ... array) {
String error = "";
for (String temp : array) {
error += temp + " ";
}
return error;
} |
18db7034-6de5-438a-a663-4c65009e3f9f | 0 | public String getEventName() {
return eventName;
} |
56432700-feee-4a72-a70a-b9a7a2ed7700 | 6 | private void bonoPuntaje(){
if(nivel.equals("Basico") && intentos == 6){
bono = 30;
puntuacion += 30;
}
if(nivel.equals("Intermedio") && intentos == 4){
bono = 50;
puntuacion += 50;
}
if(nivel.equals("Avanzado") && intentos == 2){
bono = 100;
puntuacion += 100;
}
} |
d19e999d-c1a7-4d9b-8e8e-63b7cbdefca5 | 8 | public LinkedNode removeDuplicates(LinkedNode head){
if(head==null){
return null;
}
if(head.getNext()==null){
return head;
}
Set<Integer> existingValues = new HashSet<Integer>();
List<Integer> nonDuplicateValues = new ArrayList<Integer>();
LinkedNode currentNode = head;
nonDuplicateValues.add(currentNode.value);
existingValues.add(currentNode.value);
while(currentNode.getNext()!=null){
currentNode = currentNode.getNext();
if(existingValues.contains(currentNode.getValue())){
for(int i=0; i<nonDuplicateValues.size(); i++){
if(nonDuplicateValues.get(i) == currentNode.getValue()){
nonDuplicateValues.remove(i);
i=i-1;
}
}
}
else{
//Not already added
existingValues.add(currentNode.getValue());
nonDuplicateValues.add(currentNode.getValue());
}
}
if(nonDuplicateValues.size()==0){
return null;
}
LinkedNode start = new LinkedNode(nonDuplicateValues.get(0));
LinkedNode previous;
LinkedNode current = start;
for(int i=1; i<nonDuplicateValues.size(); i++){
previous = current;
current = new LinkedNode(nonDuplicateValues.get(i));
previous.nextNode = current;
}
return start;
} |
cdaae256-d960-421e-893f-627fcbf65bfe | 2 | private void resaveParamsShowTour(SessionRequestContent request) {
Direction direction = (Direction) request.getSessionAttribute(JSP_CURRENT_DIRECTION);
if (direction != null) {
Integer idDirection = direction.getIdDirection();
if (idDirection != null) {
request.setAttribute(JSP_ID_DIRECTION, idDirection);
}
}
} |
9ae62641-9c65-414c-8930-e92e9a0c5f97 | 5 | private static DisplayMode getBestDisplayMode(GraphicsDevice device) {
for (DisplayMode bestDisplayMode : BEST_DISPLAY_MODES) {
DisplayMode[] modes = device.getDisplayModes();
for (DisplayMode mode : modes) {
if (mode.getWidth() == bestDisplayMode.getWidth()
&& mode.getHeight() == bestDisplayMode.getHeight()
&& mode.getBitDepth() == bestDisplayMode.getBitDepth()
) {
return bestDisplayMode;
}
}
}
return null;
} |
991cc82f-a6e1-4e8b-b55e-eb4478597a58 | 4 | private static int copyGapBytes(byte[] newcode, int j, byte[] code, int i, int iEnd) {
switch (iEnd - i) {
case 4:
newcode[j++] = code[i++];
case 3:
newcode[j++] = code[i++];
case 2:
newcode[j++] = code[i++];
case 1:
newcode[j++] = code[i++];
default:
}
return j;
} |
a257ef55-75a0-4102-b621-cd6fcfac071a | 6 | 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(Credits.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Credits.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Credits.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Credits.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 Credits().setVisible(true);
}
});
} |
63d0d3b0-1331-42d6-9bfa-eb3da9e09ffc | 1 | public Dimension getMinimumSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
}
return super.getMinimumSize();
} |
0cad830c-e795-400a-b74f-3410d0bd4a46 | 6 | public boolean memberP(Stella_Object value) {
{ Iterator self = this;
if ((value == null) ||
value.standardObjectP()) {
{ Stella_Object m = null;
Iterator iter000 = self;
while (iter000.nextP()) {
m = iter000.value;
if (m == value) {
return (true);
}
}
}
}
else {
{ Stella_Object m = null;
Iterator iter001 = self;
while (iter001.nextP()) {
m = iter001.value;
if (Stella_Object.eqlP(m, value)) {
return (true);
}
}
}
}
return (false);
}
} |
551b708f-0851-4479-85f8-433094648fdc | 5 | public static void newStartMenu(Game game, Screen parent) {
try {
startMenuClass.getConstructors()[0].newInstance(game, parent);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
} |
eff99548-01ca-4966-836e-c355fe4459e5 | 0 | public Company getCompany() {
return company;
} |
1604207c-82d8-4286-a480-89b8cd4693d1 | 8 | public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if(command.equals("About..."))
{
JFrame aboutFrame = new JFrame("About SChemP");
aboutFrame.setLocation(frame.getX()+250,frame.getY()+150);
aboutFrame.setSize(300,300);
aboutFrame.setVisible(true);
}
else if(command.equals("New Calculator"))
{
JFrame calcFrame = new JFrame("SChemP Calculator");
//Calculator c = new Calculator(calcFrame);
calcFrame.setLocation(frame.getX()+250,frame.getY()+150);
calcFrame.setSize(300,600);
calcFrame.setVisible(true);
}
else if(command.equals(SChemPCore.systemLAFName))
{
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception ex){}
SwingUtilities.updateComponentTreeUI(frame);
}
else if(command.equals("Java"))
{
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(Exception ex){}
SwingUtilities.updateComponentTreeUI(frame);
}
else if(command.equals("Motif"))
{
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}catch(Exception ex){}
SwingUtilities.updateComponentTreeUI(frame);
}
} |
bfb5be30-8d67-4001-be6b-2b015a007653 | 3 | private String convertAddressToString (byte[] ipAddress, int port) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (ipAddress[i] < 0) {
str.append(ipAddress[i] + 256);
}
else {
str.append(ipAddress[i]);
}
if (i < 3) {
str.append(".");
}
}
return str.append("-" + port).toString();
} |
e0f95b54-0da8-42d4-9718-06662487c115 | 1 | public void makeSelection() {
if(!list.getSelectedValue().startsWith("-1")) {
selection = list.getSelectedValue().substring(0, list.getSelectedValue().indexOf(";"));
dispose();
}
} |
77b5a865-6705-4621-bcc4-e428540454d2 | 2 | public void close() throws IOException {
if (inStream != null) inStream.close();
if (inReader != null) inReader.close();
} |
1caf12f4-7db6-4dbb-b6be-fe2acae3484d | 5 | public boolean removeWarpUser(CommandSender cs, Command cmd, String string,
String[] args) {
Player player = (Player) cs;
if (player.hasPermission("warspandports.user.remove") || player.isOp()) {
if (args.length != 4) {
player.sendMessage(ChatColor.RED + "Proper use is "
+ ChatColor.AQUA
+ "/wnp user remove <Player Name> <Warp Name>");
} else {
MainClass.loadPlayers();
Player target = player.getServer().getPlayer(args[2]);
List<String> warps = MainClass.players.getStringList(target.getUniqueId() + ".Warps");
String warp = args[3];
for(String s: warps){
if(warps.contains(s)){
warps.remove(args[3]);
MainClass.savePlayers();
player.sendMessage(ChatColor.GREEN + "The warp "
+ ChatColor.AQUA + args[3] + ChatColor.GREEN
+ " has been removed from the list of "
+ ChatColor.AQUA + args[2]);
return true;
}
player.sendMessage(ChatColor.RED + "That player does not have that warp!");
}
}
}
return false;
} |
c534d2ee-d080-449c-821d-86dc4bad5415 | 1 | final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
} |
ba980901-02e1-469e-b818-24dc62ad5d71 | 1 | private void miSelPlayer2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_miSelPlayer2MousePressed
Object[] profileNames = Manager.getInstance().getProfileNames().toArray();
String selectedProfile = (String) JOptionPane.showInputDialog(this,
"Select a player.",
"Profile Select",
JOptionPane.QUESTION_MESSAGE,
null,
profileNames,
profileNames[0]);
if (selectedProfile == null) { return; }
updateColumnTitle(3, selectedProfile);
} |
b73f1c14-eb1f-4aff-823f-95b0369b263b | 3 | public void preload(String root) {
File file = new File(root);
File[] files = file.listFiles();
for(File f : files) {
if(f.isDirectory()) {
preload(f.getPath());
}
else if(f.isFile()) {
getSound(f.getPath());
}
}
} |
71bd95c2-935b-4e6f-ab1c-4e035ef9444d | 4 | private Boolean connectToServer(String serverName) {
String rmiSerName = "rmi://localhost/" + serverName + "/";
try{
serverConnected = (ServerInterface)Naming.lookup(rmiSerName);
if(!serverConnected.connect(this,getName()))
gui.addLogArea("Impossibile connettersi\nNome già " +
"presente nella lista Client di " + serverName + "\n");
else
gui.addLogArea("Connesso a server " + serverName + "\n");
}
catch(RemoteException e){
gui.addLogArea("Problemi di connessione al server\n");
return false;
}
catch(NotBoundException e1){
gui.addLogArea("Server non connesso al sistema\n");
return false;
}
catch (MalformedURLException e2){
return false;
}
return true;
} |
ca66f730-5e74-40a8-be38-98444eafe2a3 | 0 | public void clickTutorial() {
System.out.println("You have chosen your characters so please equip him with items next.");
} |
f1e9f843-9bc6-40a4-bffd-ab69bbedaadc | 9 | public static String getColor(int i)
{
switch(i)
{
case 0:
return "black";
case 1:
return "red";
case 2:
return "blue";
case 3:
return "green";
case 4:
return "grey";
case 5:
return "purple";
case 6:
return "yellow";
case 7:
return "brown";
case 8:
return "orange";
}
return "";
} |
a1d63eb1-f2ca-4cac-bd3c-14bbef9ab53e | 9 | protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)
{
init();
this.options = options;
// an iterator for the command line tokens
Iterator iter = Arrays.asList(arguments).iterator();
// process each command line token
while (iter.hasNext())
{
// get the next command line token
String token = (String) iter.next();
// handle long option --foo or --foo=bar
if (token.startsWith("--"))
{
int pos = token.indexOf('=');
String opt = pos == -1 ? token : token.substring(0, pos); // --foo
if (!options.hasOption(opt))
{
processNonOptionToken(token, stopAtNonOption);
}
else
{
currentOption = options.getOption(opt);
tokens.add(opt);
if (pos != -1)
{
tokens.add(token.substring(pos + 1));
}
}
}
// single hyphen
else if ("-".equals(token))
{
tokens.add(token);
}
else if (token.startsWith("-"))
{
if (token.length() == 2 || options.hasOption(token))
{
processOptionToken(token, stopAtNonOption);
}
// requires bursting
else
{
burstToken(token, stopAtNonOption);
}
}
else
{
processNonOptionToken(token, stopAtNonOption);
}
gobble(iter);
}
return (String[]) tokens.toArray(new String[tokens.size()]);
} |
df683ae0-2442-4a67-85b3-6751ac777dd5 | 3 | @Override
public void caseAAvalieExpSenaoComando(AAvalieExpSenaoComando node)
{
inAAvalieExpSenaoComando(node);
{
List<PComando> copy = new ArrayList<PComando>(node.getSenao());
Collections.reverse(copy);
for(PComando e : copy)
{
e.apply(this);
}
}
{
List<PEstrCaso> copy = new ArrayList<PEstrCaso>(node.getEstrCaso());
Collections.reverse(copy);
for(PEstrCaso e : copy)
{
e.apply(this);
}
}
if(node.getAvalie() != null)
{
node.getAvalie().apply(this);
}
outAAvalieExpSenaoComando(node);
} |
ba1606da-badc-4927-b20a-efeb38a42a3e | 3 | public List getEncoders(Serializable structure) {
if (structure == null)
return Collections.unmodifiableList(encoders);
List validEncoders = new ArrayList();
Iterator it = encoders.iterator();
while (it.hasNext()) {
Codec enc = (Codec) it.next();
if (enc.canEncode(structure))
validEncoders.add(enc);
}
return Collections.unmodifiableList(validEncoders);
} |
67a67c66-0daf-43c7-b267-d1148be7e2b4 | 8 | public boolean wordPatternMatch(String pattern, String str) {
if (pattern.isEmpty()) {
return str.isEmpty();
}
if (map.containsKey(pattern.charAt(0))) {
String value = map.get(pattern.charAt(0));
if (str.length() < value.length() || !str.substring(0, value.length()).equals(value)) {
return false;
}
if (wordPatternMatch(pattern.substring(1), str.substring(value.length()))) {
return true;
}
} else {
for (int i = 1; i <= str.length(); i++) {
if (set.contains(str.substring(0, i))) {
continue;
}
map.put(pattern.charAt(0), str.substring(0, i));
set.add(str.substring(0, i));
if (wordPatternMatch(pattern.substring(1), str.substring(i))) {
return true;
}
set.remove(str.substring(0, i));
map.remove(pattern.charAt(0));
}
}
return false;
} |
888d6f06-b52d-4105-b615-2b5205cacfe3 | 6 | public boolean growNetherWart(Player player, String[] args, int radius) {
Block playerCenter = player.getLocation().getBlock(); // Get Centrepoint (Player)
int netherWarts = 0;
for (int x = -radius; x < radius; x++) {
for (int y = -radius; y < radius; y++) {
for (int z = -radius; z < radius; z++) {
Block b = playerCenter.getRelative(x,y,z);
if (playerCenter.getRelative(x,y,z).getType() == Material.NETHER_WARTS) {
int dataValue = b.getData();
if (dataValue != 3) {
b.setData((byte) 3);
netherWarts++;
} else if (dataValue == (byte) 7) {
// DO NOTHING
}
}
}
}
}
player.sendMessage(ChatColor.GREEN+"Grown "+netherWarts+" netherwarts");
return true;
} |
fbf67d75-42bd-486b-bcfe-44c92d8e7806 | 8 | @Override
public boolean setBelt(Wearable belt) throws NoSuchItemException, WrongItemTypeException {
if (belt != null) {
if (belt instanceof Belt) {
if (belt.getLevelRequirement() > level || belt.getStrengthRequirement() > stats[0]
|| belt.getDexterityRequirement() > stats[1] || belt.getMagicRequirement() > stats[2]) {
return false;
}
if (inventory.remove(belt)) {
if (onPerson[7] != null) {
removeItem(7);
}
putOnItem(belt, 7);
return true;
} else {
throw new NoSuchItemException();
}
}
throw new WrongItemTypeException();
} else {
removeItem(7);
return true;
}
} |
c451e0e4-b800-4ca6-8eee-b73969bf2edb | 9 | private void setCapacity(int capacity) {
if (capacity < _n) {
capacity = _n;
}
double factor = (_factor < 0.01) ? 0.01 : (_factor > 0.99) ? 0.99 : _factor;
int nbit, nmax;
for (nbit = 1, nmax = 2; nmax * factor < capacity && nmax < NMAX; ++nbit, nmax *= 2) {
// no-op
}
int nold = _nmax;
if (nmax == nold) {
return;
}
_nmax = nmax;
_nlo = (int)(nmax * factor);
_nhi = (int)(NMAX * factor);
_shift = 1 + NBIT - nbit;
_mask = nmax - 1;
int[] key = _key;
int[] value = _value;
boolean[] filled = _filled;
_n = 0;
_key = new int[nmax];
// semantically equivalent to _value = new V[nmax]
_value = new int[nmax];
_filled = new boolean[nmax];
if (key != null) {
for (int i = 0; i < nold; ++i) {
if (filled[i]) {
put(key[i], value[i]);
}
}
}
} |
2893f490-16e1-4376-80cc-c23a29b7d8a9 | 2 | public static void main(String[] args) throws IOException
{
decodeCustom decoder = new decodeCustom();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args[1])));
String recieved;
while((recieved = in.readLine()) != null)
{
int ascii = decoder.PNToAscii(recieved);
if(ascii < 128)
{
out.write((char)ascii);
}
}
out.close();
} |
a52eabb5-a373-4e3b-88c7-4cad1cf818b8 | 5 | public static void registerQueryRowVTIs( String className, String connectionURL )
throws Exception
{
// find public static methods which return ResultSet
Class theClass = Class.forName( className );
Method[] methods = theClass.getMethods();
int count = methods.length;
Method candidate = null;
QueryRow queryRowAnnotation = null;
for ( int i = 0; i < count; i++ )
{
candidate = methods[ i ];
int modifiers = candidate.getModifiers();
if (
Modifier.isPublic( modifiers ) &&
Modifier.isStatic( modifiers ) &&
candidate.getReturnType() == ResultSet.class
)
{
queryRowAnnotation = candidate.getAnnotation( QueryRow.class );
if ( queryRowAnnotation != null )
{
VTIHelper.unregisterVTI( candidate );
registerVTI
(
candidate,
queryRowAnnotation.jdbcDriverName(),
connectionURL,
queryRowAnnotation.query(),
new String[] {}
);
}
}
}
} |
927024f4-15f9-4dd0-8b2b-4672a3f06fe3 | 4 | public static void process(String text) throws Exception {
System.out.println(text);
String[] args = StringUtil.tokenize(text);
ModelCommand command = getCommand(args[0]);
if (command == null) {
Logger.log("\n" + "Comando '");
Logger.log(args[0]);
Logger.log(
"' nao encontrado. Digite 'help' para obter a lista de comandos validos."
+ "\n");
} else {
// Logger.log("\n>> ");
//Logger.log(args[0] + " ");
for (int i = 1; i < args.length; i++) {
// Logger.log(args[i] + " ");
}
//Logger.log("\n");
String[] params = null;
if (args.length > 1) {
params = new String[2];
} else {
params = new String[1];
}
params[0] = args[0];
if (args.length > 1) {
params[1] = StringUtil.untokenize(args, 1, args.length);
}
command.run(params);
}
} |
d09d090e-1516-4bd8-b4eb-e78d2c23449e | 2 | public void levelNode(List<List<Integer>> result,TreeNode node,int level){
if(node == null)
return ;
if(level == result.size())
result.add(new ArrayList());
result.get(level).add(node.val);
levelNode(result,node.left,level+1);
levelNode(result,node.right,level+1);
} |
8e7de6df-15b8-4d46-80a7-6e542223bc1f | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GeneratorState other = (GeneratorState) obj;
if (rootUrl == null) {
if (other.rootUrl != null)
return false;
} else if (!rootUrl.equals(other.rootUrl))
return false;
if (urlTemplate == null) {
if (other.urlTemplate != null)
return false;
} else if (!urlTemplate.equals(other.urlTemplate))
return false;
return true;
} |
e562cb21-3c37-4e24-a5d7-282b8ed38992 | 4 | @Override
public STAFResult execute(RequestInfo reqInfo) {
STAFResult result = super.execute(reqInfo);
if (result.rc == STAFResult.Ok) {
CommandAction command = null;
String parsedCommandName = (parseResult.numInstances() >= 2) ? parseResult.instanceName(2).toUpperCase() : null;
LOG.info("Looking for command action with name " + parsedCommandName);
if (parsedCommandName != null) {
command = subCommands.get(parsedCommandName);
} else {
LOG.warning("No command specified");
}
if (command != null) {
result = command.execute(parseResult);
} else {
result = new STAFResult(STAFResult.InvalidParm, "No service command found.");
}
}
return result;
} |
592c4df0-4e58-4945-98af-06c645cbf0cf | 2 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
LoginWorker loginWorker = new LoginWorker();
loginWorker.execute();
while (!loginWorker.isDone()) {
}
if (Client.getUser() != null) {
this.setVisible(false);
// this.getRootPane().setVisible(true);
MailBox.main(new String[]{});
}
}// GEN-LAST:event_jButton1ActionPerformed |
0e7b9d48-d39a-4703-bc8b-21cdd5a622f3 | 1 | public void changePassword(String username, String password) throws UserExistsException {
User user = getUserByUsername(username);
user.setPassword(password);
try {
saveUser(user);
} catch (UserExistsException e) {
throw new UserExistsException("Tne new password equals to the old one! Think up other password!");
}
} |
bc43c993-0940-4aff-87a9-0e70db36c321 | 9 | public void getMessage() {
try {
JSONObject params = new JSONObject();
JSONObject meta = new JSONObject();
meta.put("client_version", PANDA_CLIENT_VERSION);
meta.put("session_id", this.sessionId);
params.put("meta", meta);
JSONObject result = (JSONObject)jsonRPC(this.rpcUri, "get_message", params);
if (result.has("abort")) {
String abort = result.getString("abort");
if (!abort.isEmpty()) {
JOptionPane.showMessageDialog(topWindow, abort);
System.exit(0);
}
}
if (result.has("popup")) {
String popup = result.getString("popup");
if (!popup.isEmpty()) {
PopupNotify.popup(Messages.getString("Protocol.message_notify_summary"), popup, GtkStockIcon.get("gtk-dialog-info"), 0);
return;
}
}
if (result.has("dialog")) {
String dialog = result.getString("dialog");
if (!dialog.isEmpty()) {
JOptionPane.showMessageDialog(topWindow, dialog);
}
}
} catch (JSONException ex) {
ExceptionDialog.showExceptionDialog(ex);
System.exit(1);
} catch (IOException ex) {
ExceptionDialog.showExceptionDialog(ex);
System.exit(1);
} catch (HeadlessException ex) {
ExceptionDialog.showExceptionDialog(ex);
System.exit(1);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.