text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
private void ShowQuizChoice()
{
JPanel qcPanel = new JPanel();
qcPanel.setSize(600, 600);
qcPanel.setLayout(null);
TimeLbl.setVisible(false);
qnumLbl.setVisible(false);
NextBtn.setVisible(false);
PrevBtn.setVisible(false);
Quiz[] availableQuizzes = getQuizzes();
if (availableQuizzes.length > 0)
{
int l = 100;
JLabel availableLabel = new JLabel("The following quizzes are available to take:");
availableLabel.setLocation(100, 70);
availableLabel.setSize(availableLabel.getPreferredSize());
qcPanel.add(availableLabel);
for (Quiz q : availableQuizzes)
{
l += 50;
JLabel qnLabel = new JLabel();
qnLabel.setText(q.quizTitle);
JButton qButton = new JButton("Take Quiz");
qButton.setActionCommand(Integer.toString(q.quizDBId));
qButton.addActionListener(quizChoiceListener);
qnLabel.setSize(qnLabel.getPreferredSize());
qnLabel.setLocation(100, l);
qButton.setLocation(110 + qnLabel.getWidth(), l);
qButton.setSize(qButton.getPreferredSize());
qcPanel.add(qButton);
qcPanel.add(qnLabel);
}
}
else
{
JLabel noQLabel = new JLabel("No Quizzes Available");
noQLabel.setSize(noQLabel.getPreferredSize());
noQLabel.setLocation(100, 70);
qcPanel.add(noQLabel);
}
QuestionPanel.add(qcPanel);
QuestionPanel.setVisible(true);
QuestionPanel.repaint();
} | 2 |
public SubmitJob(String[] args) throws ParseException {
CommandLineParser parser = new PosixParser();
CommandLine commandLine = parser.parse(getOptions(), args);
if(commandLine.hasOption("loop")) {
numIterations_ = Integer.parseInt(commandLine.getOptionValue("loop"));
} else {
numIterations_ = 1;
}
String key = commandLine.getOptionValue("key");
String secret = commandLine.getOptionValue("secret");
String host = commandLine.getOptionValue("host");
String jobTypeString = commandLine.getOptionValue("job-type");
/*
* Turn the job type String into something that the JobType cand
* understand.
*/
String sanitizedJobTypeString = jobTypeString.toUpperCase().replace('-', '_');
jobType_ = JobType.valueOf(sanitizedJobTypeString);
if(commandLine.hasOption("image-file")) {
String imageFileName = commandLine.getOptionValue("image-file");
imageUrls_ = new ArrayList<String>();
try {
BufferedReader imageFileReader = new BufferedReader(new FileReader(imageFileName));
String line;
while((line = imageFileReader.readLine()) != null) {
imageUrls_.add(line.trim());
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
if(commandLine.hasOption("song")) {
songUrl_ = commandLine.getOptionValue("song");
}
client_ = new ApiClient(key, secret, host);
if(jobType_ == JobType.DIRECT_AND_RENDER) {
if(songUrl_ == null) {
throw new MissingArgumentException("must specify a song for " + jobTypeString + " jobs");
}
if(imageUrls_ == null) {
throw new MissingArgumentException("must specify images for " + jobTypeString + " jobs");
}
} else {
throw new UnrecognizedOptionException("code needs to be added for job type " + jobTypeString);
}
} | 8 |
public void setWorkSpace(WorkSpace workSpace)
{
if (workSpace == null
|| ! (workSpace instanceof CommandPanelWorkSpace) ||
( (CommandPanelWorkSpace) workSpace).getLoginTable() == null ||
( (CommandPanelWorkSpace) workSpace).getLoginTable().size() ==
0)
{
loginTable = LoginWindow.getDefaultLogins();
updateComboBox(cboLogins, loginTable.keySet().toArray());
return;
}
CommandPanelWorkSpace ws = (CommandPanelWorkSpace)
workSpace;
//<cvs/>added clone() - bug in calling the equals() method if same obj
loginTable = (Hashtable)ws.getLoginTable().clone();
updateComboBox(cboLogins, loginTable.keySet().toArray());
ckAutoCommit.setSelected(ws.isAutoCommit());
} | 4 |
public void warAddtoPlayer1(int s, ArrayList p1, ArrayList p2)
{
//Adds card to the player 1 pile
for(int i=0; i<s; i++)
{
if(i<p1.size())
{
Object obj1 = p1.get(0);
Card c1 = (Card)obj1;
player1.addCard(0,c1);
}
if(i<p2.size())
{
Object obj2 = p2.get(0);
Card c2 = (Card)obj2;
player1.addCard(0,c2);
}
}
} | 3 |
public boolean getRedoEnabled() {
return this instanceof UndoInterface && redoEnabled;
} | 1 |
private void listagemProf() {
final Main m = new Main();
JLabel NomeCom = new JLabel("Professores:", JLabel.CENTER);
String[] v5 = new String[m.professores.size() + 1];
v5[0] = " ";
for (int i = 1; i < m.professores.size() + 1; i++) {
v5[i] = m.professores.get(i - 1).toString();
}
final JComboBox com = new JComboBox(v5);
com.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
HorarioVazio();
ArrayList<Horario> horario = new ArrayList<>();
if (com.getSelectedIndex() > 0) {
horario = m.professores.get(com.getSelectedIndex() - 1).listarHorarioProfessor(m.professores, m.horarios);
for (int i = 0; i < horario.size(); i++) {
int dia_semana = horario.get(i).getDia_semana();
switch (dia_semana) {
case 2:
horarioSegunda(horario, dia_semana, i);
break;
case 3:
horarioTerca(horario, dia_semana,i);
break;
case 4:
horarioQuarta(horario,dia_semana, i);
break;
case 5:
horarioQuinta(horario, dia_semana, i);
break;
case 6:
horarioSexta(horario, dia_semana, i);
break;
default:
dispose();
};
}
}
else
{
HorarioVazio();
}
}
});
NomeCom.setFont(new Font("Arial", Font.BOLD, 12));
NomeCom.setForeground(Color.white);
panelbtn.add(NomeCom, BorderLayout.NORTH);
panelbtn.add(com);
} | 8 |
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key >= 48 && key <= 57) newMass = (key - 48)*100;
else if(key == KeyEvent.VK_Z)
{
game.GUI.offsetX += game.getWidth()*.05 + game.GUI.offsetX*.1;
game.GUI.offsetY += game.getHeight()*.05 + game.GUI.offsetY*.1;
game.GUI.scale *= 1.1;
}
else if(key == KeyEvent.VK_X)
{
game.GUI.offsetX -= game.getWidth()*.05 + game.GUI.offsetX*.1;
game.GUI.offsetY -= game.getHeight()*.05 + game.GUI.offsetY*.1;
game.GUI.scale *= .9;
}
else if(key == KeyEvent.VK_W) game.GUI.offsetY -= 25/game.GUI.scale;
else if(key == KeyEvent.VK_A) game.GUI.offsetX -= 25/game.GUI.scale;
else if(key == KeyEvent.VK_S) game.GUI.offsetY += 25/game.GUI.scale;
else if(key == KeyEvent.VK_D) game.GUI.offsetX += 25/game.GUI.scale;
else if(key == 192) System.exit(0); //Tilde
} | 9 |
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 'w')
{
keyPressedW = true;
move = true;
}
if (e.getKeyChar() == 's')
{
keyPressedS = true;
move = true;
}
if (e.getKeyChar() == 'a')
{
keyPressedA = true;
move = true;
}
if (e.getKeyChar() == 'd')
{
keyPressedD = true;
move = true;
}
if (e.getKeyChar() == 'p')
{
cheatKeyPressed = true;
}
/* if (e.getKeyChar() == ' '){
shootAngle+=30;
if (shootAngle == 360){
shootAngle = 0;
}
}*/
} | 5 |
public boolean update(double[] data, boolean classifier) {
double sum = 0;
//create a new data vector to encompass all data points plus classifier
double[] vector = new double[data.length+1];
double norm = 1;
for (int i = 0; i < data.length; i++) {
vector[i] = data[i];
norm += data[i]*data[i];
}
//x_n+1 = -1
vector[vector.length-1] = -1;
norm = Math.sqrt(norm);
//If the classifier is false, map x to -x.
if (!classifier) {
norm*=-1;
}
//normalize data vector
for (int i = 0; i < vector.length; i++) {
vector[i] = vector[i]/norm;
}
if (vector.length != weights.length) {
System.err.println("Error: Perceptron must be the same lenghts as features + classifier");
return false;
}
for (int i = 0; i < weights.length; i++) {
sum += weights[i]*vector[i];
}
//System.out.println("Sum: "+sum);
if (sum > 0) {
return true;
}
//update weights
for (int i = 0; i < weights.length; i++) {
weights[i]+=vector[i];
}
return false;
} | 7 |
public void drawMe(Graphics2D g) {
if (!general)
drawPercentComparisonLines(g);
int J = 0;
for (Rectangle2D.Float bar : bars) {
if (general) {
if (minMaxHisto.x == J || minMaxHisto.y == J)
g.setColor(COLOR_HISTOGRAM_BAR_THIS);
else
g.setColor(COLOR_HISTOGRAM_BAR);
} else {
g.setColor(COLOR_HISTOGRAM_BAR_VOL);
}
g.draw(bar);
g.fill(bar);
J++;
}
g.setColor(new Color(20, 20, 10 + 10 * 19));
g.draw(border);
if (!general) {
g.setColor(new Color(100, 100, 200, 200));
g.setFont(new Font("Sans-Serif", Font.ITALIC, 17));
int top = 25;
int left = 22;
int inc = 25;
g.drawString("total variability: ", left, top);
float marketPercentChange = (int) (100 * (minMaxMarket.y - minMaxMarket.x) / minMaxMarket.x);
g.drawString("market: " + marketPercentChange, left, top + inc);
float individualPercentChange = (int) (100 * (minMaxLine.y - minMaxLine.x) / minMaxLine.x);
g.drawString(ticker + ": " + individualPercentChange, left, top
+ inc * 2);
g.drawString("overall change: ", left, top + inc * 4);
float market = (int) (100 * (startFinishMarket.y - startFinishMarket.x) / startFinishMarket.x);
g.drawString("market: " + market, left, top + inc * 5);
float individual = (int) (100 * (startFinishTicker.y - startFinishTicker.x) / startFinishTicker.x);
g.drawString(ticker + ": " + individual, left, top + inc * 6);
}
if (general) {
g.setColor(Color.blue);
g.draw(timePath);
g.setColor(Color.white);
g.drawString(category, left + PIXELS_BORDER, top + 15);
g.drawString("" + minMaxLine.x, eWidth - 100, top + PIXELS_HEIGHT
- PIXELS_BORDER);
g.drawString("" + minMaxLine.y, eWidth - 100, top + 13);
} else {
Stroke s = g.getStroke();
g.setStroke(STROKE);
g.setColor(Color.magenta);
g.draw(timePath);
g.setColor(MARKET_VALUE);
g.draw(marketTimePath);
g.setStroke(s);
drawPriceRangeWindows(g);
}
} | 7 |
public void removeLocallyDeclareable(Set set) {
if (type == FOR && initInstr instanceof StoreInstruction) {
StoreInstruction storeOp = (StoreInstruction) initInstr;
if (storeOp.getLValue() instanceof LocalStoreOperator) {
LocalInfo local = ((LocalStoreOperator) storeOp.getLValue())
.getLocalInfo();
set.remove(local);
}
}
} | 3 |
public short tileToShort(Tile t)
{
short res = 0;
if (t.tileNum != -1)
res |= (short) ((t.tileNum + tileOffset) & 0x3FF);
res |= (short) ((t.hflip ? 1 : 0) << 10);
res |= (short) ((t.vflip ? 1 : 0) << 11);
res |= (short) (((t.palNum + paletteOffset) & 0x00F) << 12);
return res;
} | 3 |
private MessageBox getMessageBox() {
return (MessageBox) root.getScene().getWindow();
} | 0 |
private boolean combinedStringArrays(TupleDesc td1, TupleDesc td2, TupleDesc combined) {
for (int i = 0; i < td1.numFields(); i++) {
if (!(((td1.getFieldName(i) == null) && (combined.getFieldName(i) == null)) ||
td1.getFieldName(i).equals(combined.getFieldName(i)))) {
return false;
}
}
for (int i = td1.numFields(); i < td1.numFields() + td2.numFields(); i++) {
if (!(((td2.getFieldName(i-td1.numFields()) == null) && (combined.getFieldName(i) == null)) ||
td2.getFieldName(i-td1.numFields()).equals(combined.getFieldName(i)))) {
return false;
}
}
return true;
} | 8 |
protected void checkTypeOfOperands (List<Expression> operands)
{
List<Class<?>> expectedOperandTypes = getOperandTypes();
if (expectedOperandTypes == null) return;
boolean statusCheck = true;
for (int i = 0; i < operands.size(); i++)
{
statusCheck =
statusCheck && isCorrectInstance(operands.get(i), expectedOperandTypes.get(i));
if (statusCheck == false)
throw new ParserException("Incorrect type of operand(s). Should be " +
expectedOperandTypes.toString());
}
} | 5 |
private boolean verifyChapPassword(String plaintext)
throws RadiusException {
if (plaintext == null || plaintext.length() == 0)
throw new IllegalArgumentException("plaintext must not be empty");
if (chapChallenge == null || chapChallenge.length != 16)
throw new RadiusException("CHAP challenge must be 16 bytes");
if (chapPassword == null || chapPassword.length != 17)
throw new RadiusException("CHAP password must be 17 bytes");
byte chapIdentifier = chapPassword[0];
MessageDigest md5 = getMd5Digest();
md5.reset();
md5.update(chapIdentifier);
md5.update(RadiusUtil.getUtf8Bytes(plaintext));
byte[] chapHash = md5.digest(chapChallenge);
// compare
for (int i = 0; i < 16; i++)
if (chapHash[i] != chapPassword[i + 1])
return false;
return true;
} | 8 |
public LinkedList<Vertex> createPlan(int start, int stop, int color, boolean intekrock) {
LinkedList<Vertex> path;
Graph graph = new Graph(nodes, edges);
DijkstraAlgorithm dijkstra = new DijkstraAlgorithm(graph, ds);
// Compute shortest path
dijkstra.execute(nodes.get(start - 1));
path = dijkstra.getPath(nodes.get(stop - 1));
//System.out.println("nodes.get(start) " + nodes.get(start-1));
//System.out.println("nodes.get(stop) " + nodes.get(stop-1));
Arrays.fill(ds.notoknumber, 0);
// Get shortest path
if (intekrock) {
System.out.println("path.size() " + path.size());
for (int i = 1; i < path.size() - 1; i++) {
ds.notoknumber[i] = Integer.parseInt(path.get(i).getId());
System.out.println("ds.notoknumber[i] " + ds.notoknumber[i]);
}
}
// Arcs in the shortest path
for (int i = 0; i < path.size() - 1; i++) {
for (int j = 0; j < ds.arcs; j++) {
if (ds.arcStart[j] == Integer.parseInt(path.get(i).getId())
&& ds.arcEnd[j]
== Integer.parseInt(path.get(i + 1).getId())) {
//System.out.println("Arc: " + j);
ds.arcColor[j] = color;
}
}
}
return path;
} | 6 |
@Override
public boolean register(Game g, Rack r) {
super.register(g, r);
if (g.rack_size != 5)
return false;
for (Model m: ensemble){
if (!m.register(g, r))
return false;
}
return true;
} | 3 |
public JTextField getjTextFieldNumRapport() {
return jTextFieldNumRapport;
} | 0 |
public void delReservation(int resid){
Connection con = null;
Statement stmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
stmt = con.createStatement();
stmt.execute("Delete From reservation Where res_id = " + resid);
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
} | 4 |
public static Float getMasterOutputVolume() {
Line line = getMasterOutputLine();
if (line == null) return null;
boolean opened = open(line);
try {
FloatControl control = getVolumeControl(line);
if (control == null) return null;
return control.getValue();
} finally {
if (opened) line.close();
}
} | 3 |
public Configuration[] getInitialConfigurations(String input) {
State init = myAutomaton.getInitialState();
State[] closure = ClosureTaker.getClosure(init, myAutomaton);
Configuration[] configs = new Configuration[closure.length];
for (int k = 0; k < closure.length; k++) {
configs[k] = new FSAConfiguration(closure[k], null, input, input);
}
return configs;
} | 1 |
public Cartoon() {
System.out.println("Cartoon constructor");
} | 0 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Clientes)) {
return false;
}
Clientes other = (Clientes) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
@Override
public void getInput() {
int selection = -1;
boolean isValid = false;
do {
this.displayMenu();
Scanner input = SnakeWithPartner.getInFile();
do {
try {
selection = input.nextInt();
isValid = true;
} catch (NumberFormatException numx) {
System.out.println("Invalid Input. Please input a valid number.");
isValid = false;
}
} while (!isValid);
switch (selection) {
case 1:
this.mainMenuControl.launchPlayMenu();
break;
case 2:
this.mainMenuControl.displayHighScores();
break;
case 3:
this.mainMenuControl.launchSettingsMenu();
break;
case 4:
this.mainMenuControl.launchHelpMenu();
break;
case 0:
break;
default:
System.out.println("Please enter a valid menu item:");
continue;
}
} while (selection != 0);
} | 8 |
public int getCalled0Raised1OrFolded(MOB player)
{
if(!pot.contains(player))
return -1;
final Double inPot=(Double)pot.elementAt(pot.indexOf(player),2);
int numHigherThanPlayer=0;
int numEqualToPlayer=0;
for(int p=0;p<pot.size();p++)
if(pot.elementAt(p,1)!=player)
{
final Double potAmount=(Double)pot.elementAt(p,2);
if(potAmount.doubleValue()==inPot.doubleValue())
numEqualToPlayer++;
else
if(potAmount.doubleValue()>inPot.doubleValue())
numHigherThanPlayer++;
}
if(numHigherThanPlayer>0)
return -1;
if(numEqualToPlayer>0)
return 0;
return 1;
} | 7 |
public static String[][] run(String train, String test) {
int k = 3;
// read the train file
//String inputtrainf="IrisTrain.csv";
//String inputtestf="IrisTest.csv";
String inputtrainf=train;
String inputtestf=test;
ArrayList<String> trainList = getFile(inputtrainf);
int trainSize = trainList.size() - 6;
String trainData[][] = new String[trainSize][6];
String trainDatares[][] = new String[trainSize][6];
// trainData[i][j] is the whole array to store the file
for (int i = 0; i < trainSize; i++) {
trainData[i] = trainList.get(i + 6).split(",");
}
// read the test file
ArrayList<String> testList = getFile(inputtestf);
int testSize = testList.size() - 6;
String testData[][] = new String[testSize][4];
for (int i = 0; i < testSize; i++) {
testData[i] = testList.get(i + 6).split(",");
}
// transfer String to double and put to array myIris[][]
double myIris[][] = new double[testData.length][4];
for (int i = 0; i < testData.length; i++) {
for (int j = 0; j < 4; j++) {
myIris[i][j] = Double.parseDouble(testData[i][j]);
}
}
// put the classification result into array result
String result[] = new String[testData.length];
for (int i = 0; i < testData.length; i++) {
// sum[] is the sqrt list of each Iris' distance
double sum[] = getDistance(myIris[i], trainData,trainDatares);
int[] theFirstK = getFirstK(sum, k);
// vote record the number of votes
int[] vote = new int[k];
vote = vote(trainData, theFirstK, k, vote);
String winner = max(vote[0], vote[1], vote[2]);
result[i] = winner;
}
try {
writeToFile(testData, result);
} catch (IOException e) {
System.out.println("File write error");
e.printStackTrace();
}
return trainDatares;
} | 6 |
private static void insertRecordIntoDbUserTable(ArrayList<String> xmlList) throws SQLException {
// generates rows in table, each with file name and one keyword
Connection dbConnection = null;
PreparedStatement statement = null;
try {
dbConnection = getDBConnection();
statement = dbConnection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS);
int batchSize = 0;
for (int a = 0; a < xmlList.size(); a++) { // for each xml file
ArrayList<String> keywords = new ArrayList<String>(generateKeywords(xmlList.get(a))); //gets the file's keywords
ArrayList<String> xmlKeywords = new ArrayList<String>(curate(keywords)); //filter keywords
//start appending keywords of that xml file to database
if (xmlKeywords.size() == 1) { //if xml file has no keywords and thus list only consists of the file name
statement.setString(1, xmlKeywords.get(0));
statement.setString(2, "");
statement.addBatch();
batchSize++;
}
for (int i = 1; i < xmlKeywords.size(); i++) { //for each keyword following the file name
statement.setString(1, xmlKeywords.get(0)); //set file name
statement.setString(2, xmlKeywords.get(i)); //set keyword
statement.addBatch();
batchSize++;
if ((i) % 1000 == 0) {
statement.executeBatch(); // Execute every 1000 items.
}
}
if (batchSize >= 1000) {
statement.executeBatch();
batchSize = 0;
}
//end appending keywords for each xml file loop
} //end loop of generating table for all xml files and keywords
statement.executeBatch();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
} | 8 |
private static URL __getWsdlLocation() {
if (BOOKSERVICESOAPSERVICEIMPLSERVICE_EXCEPTION!= null) {
throw BOOKSERVICESOAPSERVICEIMPLSERVICE_EXCEPTION;
}
return BOOKSERVICESOAPSERVICEIMPLSERVICE_WSDL_LOCATION;
} | 1 |
@Override
public void takeTurn(GameBoard currentBoard) {
boolean inputInvalid = true;
Scanner sc = Main.Scan;
String invalidRowInputMessage = this.Name
+ ", that input is invalid.\n Please select a row by entering its number.";
String rowPrompt = currentBoard.toString() + "\n\n" + Name
+ ", select a row: ";
while (inputInvalid) {
int input = this.getIntInput(rowPrompt, invalidRowInputMessage);
boolean userInputFits = input > 0
&& input <= currentBoard.getCurrentState()
.getNumberOfRows();
if (userInputFits) {
int rowTokens = currentBoard.getCurrentState().checkRow(input);
if (rowTokens > 0) {
// row tokens is the number of tokens in the selected row
// in the row selected
boolean inputInvalidToken = true;
while (inputInvalidToken) {
String tokenPrompt = "There are " + rowTokens
+ " tokens in row " + input
+ ".\n How many tokens will you remove?";
String invalidTokenInputMessage = "That is not a valid number of tokens.\nPlease select a value greater than 0 and NOT greater than "
+ rowTokens;
int tokensToRemove = getIntInput(tokenPrompt,
invalidTokenInputMessage);
TurnAction action = new TurnAction();
action.setTargetRow(input);
action.setTokenAmount(tokensToRemove);
boolean successful = currentBoard.getCurrentState()
.tryTurn(action);
if (successful) {
inputInvalidToken = !successful;
inputInvalid = !successful;
} else {
System.out.println(invalidTokenInputMessage);
}
}
} else {
System.out
.println("There are not any tokens in that row. Please choose a different row.");
}
} else {
System.out
.println("That is not a valid row. Please select the number of one of the rows displayed.");
}
}
} | 6 |
public static void find(HousePetList hpArray)
{
HousePet housepet = new HousePet();
int aChipID = 0;
@SuppressWarnings("resource")
Scanner console = new Scanner(System.in);
String consoleOutMsg = "";
boolean containsHousePet = true;
System.out.println("Please enter the chipID of the HousePet you're looking for.");
try
{
aChipID = console.nextInt();
housepet.setChipId(aChipID);
}
catch(InputMismatchException e)
{
System.out.println("Error: a non-int was entered " + e);
}
catch(NoSuchElementException e)
{
System.out.println("Error: chipID not found " + e);
}
catch(IllegalStateException e)
{
System.out.println("Error: Scanner is closed " + e);
}
/* if an invalid int were to be sent to the setter, chipId would be set to 0 */
if(aChipID != 0)
{
containsHousePet = hpArray.contains(housepet);
if(containsHousePet == false)
{
consoleOutMsg = "not ";
}//end IF(containsHousePet == false)
}//end IF(aChipID != 0)
System.out.println("A HousePet with chipID " + aChipID + " was " + consoleOutMsg +
"found in the current list");
return;
}//end find() | 5 |
public void onQuery(Player player, ReplicatedPermissionsContainer query)
{
if (query != null)
{
if (!this.playerModInfo.containsKey(player.getName()))
{
this.plugin.getLogger().warning("Received query from unregistered player " + player.getName());
this.playerModInfo.put(player.getName(), new Hashtable<String, ReplicatedPermissionsContainer>());
}
// Log the query, it can be used to get information about a players mods later on, as well
// as being used in case the "refresh" command is given as a kind of query cache.
this.playerModInfo.get(player.getName()).put(query.modName, query);
if (query.permissions.size() > 0)
{
ConfigurationSection versionSection = getModVersionSection(query.modName, query.modVersion);
if (versionSection != null)
{
versionSection.set("permissions", new ArrayList<String>(query.permissions));
try
{
this.data.save(this.dataFile);
}
catch (IOException ex) {}
}
}
}
} | 5 |
public int executeCommits(ArrayList<String> c){
Statement s;
for (int i = 0; i < c.size(); i++) {
try {
s = StatusController.connection.createStatement();
s.executeUpdate(c.get(i));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return -1;
}
}
return 1;
} | 2 |
public static String join(String[] lines, String glue) {
if (lines.length == 1) {
return lines[0];
}
StringBuilder out = new StringBuilder();
for (int i = 0; i < lines.length - 1; i++) {
out.append(lines[i]).append(glue);
}
out.append(lines[lines.length - 1]);
return out.toString();
} | 2 |
private double calculateClosestBruteForce(Point[] sortedByX) {
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < sortedByX.length; i++) {
for (int j = 1; j < sortedByX.length; j++) {
//we don't want to calculate distance between the same point
if (i != j) {
double distance = getDistance(sortedByX[i], sortedByX[j]);
if (distance < minDistance) {
minDistance = distance;
closest = sortedByX[i] + " - " + sortedByX[j];
}
}
}
}
return minDistance;
} | 4 |
public void onMessage(JSONObject msg, Callback cb) {
// TODO call the callback obj in case of callback. If not send call the
// method!
String methodName = msg.optString("method", null);
JSONObject data = msg.optJSONObject("data");
if (methodName == null) {
System.err.println("No method in reqest");
}
java.lang.reflect.Method method = null;
try {
method = this.getClass().getMethod(methodName, JSONObject.class, Callback.class);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
System.err.println("Invalid method : " + methodName);
e.printStackTrace();
}
if (method != null) {
try {
method.invoke(this, data, cb);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} | 7 |
private boolean BookFieldCheck(String booklistString){
boolean isbn = false;
boolean bookdate = false;
Scanner analysisbooklist = new Scanner(booklistString);
while (analysisbooklist.hasNext()){
String getstring = analysisbooklist.next();
if(this.BooklistISBNCheck(getstring)){
isbn = true;
}
else if(this.BooklistDateCheck(getstring)){
bookdate = true;
}
}
analysisbooklist.close();
if(isbn && bookdate){
return true;
}
else{
return false;
}
} | 5 |
private int evaluateValueofBoardForBlack(Board board) {
int bValue = 0;
if (board.isBlackWinner()) {
bValue -= POINT_WON;
return bValue;
} else {
bValue = WhiteBlackPiecesDifferencePoints(board);
// bValue += BoardPositionPoints(board);
bValue /= board.whitePieces;
}
return bValue;
} | 1 |
public static void main(String[] arg) {
String input = arg[0];
String output = (arg.length > 1 ? arg[1] : null);
InputStream in = null;
try {
in = new FileInputStream(input);
} catch (Exception e) {
System.out.println(e);
}
State foo = new State();
JOrbisComment jorbiscomment = new JOrbisComment(foo);
jorbiscomment.read(in);
System.out.println(foo.vc);
if (output == null) {
return;
}
Properties props = System.getProperties();
int i = 0;
while (true) {
try {
String comment = (String) props.get("JOrbis.comment." + i);
foo.vc.add(comment);
i++;
} catch (Exception e) {
break;
}
}
// foo.vc.add("TEST=TESTTEST");
// foo.vc.add_tag("TITLE", "demodemo");
System.out.println(foo.vc);
//System.out.println(foo.vc.query("TEST"));
//System.out.println(foo.vc.query("TITLE"));
//System.out.println(foo.vc.query("ARTIST"));
try (OutputStream out = new FileOutputStream(output)) {
jorbiscomment.write(out);
} catch (Exception e) {
LOG.log(Level.FINE, e.getMessage());
}
} | 6 |
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] cardCounts = new int[N];
for (int i = 0; i < N; i++)
cardCounts[i] = in.nextInt();
long straights = 0L;
LinkedList<ArrayList<Integer>> bounds = new LinkedList<ArrayList<Integer>>();
bounds.add(new ArrayList<Integer>());
bounds.get(0).add(0);
bounds.get(0).add(N);
while (bounds.size() > 0)
{
ArrayList<Integer> currentBounds = bounds.removeFirst();
int left = currentBounds.get(0);
int right = currentBounds.get(1);
int min = cardCounts[left];
for (int i = left; i < right; i++)
if (cardCounts[i] < min)
min = cardCounts[i];
straights += min;
for (int i = left; i < right; i++)
cardCounts[i] -= min;
int a = left;
int b = left;
while (b < right)
{
if (cardCounts[b] == 0)
{
if (a < b)
{
ArrayList<Integer> newBounds = new ArrayList<Integer>();
newBounds.add(a);
newBounds.add(b);
bounds.addLast(newBounds);
}
a = b+1;
}
b++;
}
if (a < b)
{
ArrayList<Integer> newBounds = new ArrayList<Integer>();
newBounds.add(a);
newBounds.add(b);
bounds.addLast(newBounds);
}
}
System.out.println(straights);
} | 9 |
public static void Build(int n, String filename) throws FileNotFoundException{
// generate Board
int [][] Board = new int[n][n];
boolean[] numberUsed = new boolean[n*n]; // each index needs to appear on board. the value at that array position is true if on board, false if not
for (int i=0; i<n*n; i++){
numberUsed[i] = false;
}
for(int r=0; r<n; r++){
for(int c=0; c<n; c++){
int randomNumber = -1;
while(randomNumber==-1){
randomNumber = (int)Math.floor(Math.random()*n*n);
if(numberUsed[randomNumber]){
randomNumber = -1;
}
}
numberUsed[randomNumber] = true;
Board[r][c] = randomNumber;
}
}
// write to text file
PrintWriter writer = new PrintWriter(filename);
writer.print(n);
for(int r=0; r<n; r++){
for(int c=0; c<n; c++){
if(c==0){
writer.println("");
}
writer.print(Board[r][c] + " ");
}
}
writer.close();
} | 8 |
private boolean outputResults(String zOutputFile, Vector vResults)
{
try
{
// create the output stream
BufferedWriter outWriter = new BufferedWriter(new FileWriter(zOutputFile));
// go through each point in the grid and diagram the path
// Use X for obstacle squares o for clear squares that aren't in the path
// and v for squares in the path
for (int y = 0; y < m_nHeight; y++)
{
for (int x = 0; x < m_nWidth; x++)
{
// start and goal squares
if ((x == m_nStartPointX) && (y == m_nStartPointY))
{
outWriter.write("S");
}
else if ((x == m_nGoalPointX) && (y == m_nGoalPointY))
{
outWriter.write("G");
}
// obstacle squares
else if (m_nMapData[x][y] == 0)
{
outWriter.write("X");
}
else
{
if (isInList(vResults, m_nNodeIDs[x][y]))
{
// this is in the list so output a v
outWriter.write("v");
}
else
{
// not in the results list
outWriter.write("o");
}
}
// output a space
outWriter.write(" ");
}
// place a return in the file
outWriter.newLine();
}
// flush the stream
outWriter.flush();
// close the stream
outWriter.close();
}
catch (IOException e)
{
System.err.println("Cannot output to file...");
return false;
}
return true;
} | 9 |
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (super.equals(o)) {
return true;
}
orgataxe.entity.Model model = (orgataxe.entity.Model) o;
if (weight != model.weight) {
return false;
}
if (designation != null ? !designation.equals(model.designation) : model.designation != null) {
return false;
}
return true;
} | 7 |
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(args.length == 0) {
Messenger.sendMessage("NicksRequest written by codermason v1.0", sender);
Messenger.sendMessage("Use /nicks help for help!", sender);
}else{
if(args[0].equalsIgnoreCase("help")) {
new HelpCommand(this.plugin).execute(sender, command, args);
return true;
}
if(args[0].equalsIgnoreCase("list")) {
new ListCommand(this.plugin).execute(sender, command, args);
return true;
}
if(args[0].equalsIgnoreCase("mine")) {
new MineCommand(this.plugin).execute(sender, command, args);
return true;
}
if(args[0].equalsIgnoreCase("send")) {
new SendCommand(this.plugin).execute(sender, command, args);
return true;
}
if(args[0].equalsIgnoreCase("accept")) {
new AcceptCommand(this.plugin).execute(sender, command, args);
return true;
}
if(args[0].equalsIgnoreCase("deny")) {
new DenyCommand(this.plugin).execute(sender, command, args);
return true;
}
Messenger.sendMessage("Unknown command!", sender);
}
return false;
} | 7 |
public String getOutputKeyword() {
Dialog currentDialog = DialogManager.giveDialogManager().getCurrentDialog();
switch ((Start)getCurrentState()) {
case S_ENTRY:
setQuestion(false);
return "<" + currentDialog.getCurrentSession().getCurrentRobot().getRobotData().getRobotName() + ">";
case S_EXIT:
setQuestion(false);
return null;
case S_USER_DOESNT_WANT_TO_BE_SAVED:
setQuestion(false);
return null;
case S_USER_FOUND:
setQuestion(true);
return "<" + currentDialog.getCurrentSession().getCurrentUser().getUserData().getUserName() + ">";
case S_USER_NOT_FOUND:
setQuestion(true);
return null;
case S_USER_SAVED:
setQuestion(true);
return "<" + currentDialog.getCurrentSession().getCurrentUser().getUserData().getUserName() + ">";
case S_USER_WANTS_TO_BE_SAVED:
setQuestion(true);
return "<" + currentDialog.getCurrentSession().getCurrentUser().getUserData().getUserName() + ">";
case S_WAITING_FOR_EMPLOYEE_STATUS:
setQuestion(false);
return null;
case S_WAITING_FOR_USERNAME:
setQuestion(true);
return null;
default:
return null;
}
} | 9 |
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Usuario usuario;
try {
usuario = em.getReference(Usuario.class, id);
usuario.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The usuario with id " + id + " no longer exists.", enfe);
}
em.remove(usuario);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
} | 2 |
public static void setup(ExtendedEntityType mob, ValueChance<Ability> abilityChances, List<Object> optList)
{
Iterator<Object> it = optList.iterator();
while (it.hasNext())
{
Map<String, Object> optMap = MiscUtil.getConfigMap(it.next());
if (optMap == null)
continue;
int chance = MiscUtil.getInteger(optMap.get("CHANCE"));
if (chance <= 0)
continue;
String setName = MiscUtil.getMapValue(optMap, "SETNAME", mob.toString(), String.class);
if (setName == null)
continue;
AbilitySet set = getAbilitySet(setName);
if (set == null)
{
MMComponent.getAbilities().warning("Missing SetName " + setName + " for " + mob);
continue;
}
abilityChances.addChance(chance, set);
}
} | 5 |
@Override
public String toString() {
return type;
} | 0 |
private boolean isValidInput(final String s) {
return s.matches("[0-9]{1,}");
} | 0 |
public double getMaxTime (){
double maxTime = 0;
for(int i = 0; i<time.length; i++){
if(time[i]>maxTime)
maxTime = time[i];
}
return maxTime;
} | 2 |
public int getPrevIncompleteIndex(int row, int col)
{
boolean notFound = true ;
int len = translations.size() ;
int t = row ;
int back = -1 ;
while ( (t >= 0) && notFound)
{
TMultiLanguageEntry dummy = (TMultiLanguageEntry) translations.get(t) ;
String str = dummy.getTranslationOnly(col) ;
if (str == null)
{
notFound = false ;
back = t ;
}
else if (str.length() < 1)
{
notFound = false ;
back = t ;
}
else
{
t-- ;
}
}
return back ;
} | 4 |
public boolean logUser(User usertemp){
if(userList.indexOf(usertemp) == -1)
return false;
else{
user = usertemp;
return true;
}
} | 1 |
public static void led_branch(String num, String filepath, String sn, Scanner scanner){
String line="", result = "";
int item=0;
System.out.println("Please choose the LED light you want to test: 1=white led, 2=rgb led, 0=return:");
line=scanner.nextLine();
while (!(line.equals("0"))){
while ((!(line.equals("1")))&&(!(line.equals("2")))&&(!(line.equals("0")))){
System.out.println("Error input! ");
System.out.println("Please choose the LED light you want to test: 1=white led, 2=rgb led, 0=return:");
line=scanner.nextLine();
}
if (line.equals("0")){
break;
}
item = Integer.parseInt(line);
switch(item){
case 1:
result = LED_White.serialcomm(num,scanner);
LED_White.ledprocess(filepath, result, sn);
break;
case 2:
result = LED_RGB.serialcomm(num,scanner);
LED_RGB.ledprocess(filepath, result, sn);
break;
}
System.out.println("Please choose the LED light you want to test: 1=white led, 2=rgb led, 0=return:");
line=scanner.nextLine();
}
} | 7 |
@Override
public String toString() {
Field[] fields = this.getClass().getDeclaredFields();
StringBuilder sb = new StringBuilder();
sb.append('[');
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers())
|| Modifier.isFinal(f.getModifiers()))
continue;
Object value = null;
try {
f.setAccessible(true);
value = f.get(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (value != null)
sb.append(f.getName()).append('=').append(value).append(',');
}
sb.append(']');
return sb.toString();
} | 6 |
@Override
public void run() {
while (alive){
//We keep consuming jobs while they are available
IJob job = null;
synchronized (jobQueue){
if (jobs.size() > 0)
job = jobs.remove(0);
else
alive = false;
}
//Make sure not to hog the synchronization of the queue when we don't need it
if (job != null)
executeJob(job);
}
//When our job queue is empty we can either shut down or wait for more jobs to come
//Our consumer Thread will stop either way
if (callExit){
try {
updateable.send(new StatusUpdate("VM " + id + " Shutting down on soft exit request.", id, VMState.SHUTDOWN));
} catch (IOException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
}
System.exit(0);
} else {
try {
updateable.send(new StatusUpdate("VM " + id + " Done processing all jobs.", id, VMState.DONE, JobType.WAITING));
} catch (IOException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
}
}
} | 8 |
private void addAttack(int x, int y, int minRange, int maxRange)
{
int nX, nY;
for(int i = -maxRange; i <= maxRange; i++) {
for(int j = Math.abs(i) - maxRange; j <= maxRange - Math.abs(i); j++) {
nX = x + i;
nY = y + j;
if(nX >= 0 && nX < Game.map.width && nY >= 0 && nY < Game.map.height) {
if(Math.abs(i) + Math.abs(j) >= minRange) {
if(movement[nX][nY] == 0) {
attList.add(new int[]{nX, nY});
movement[nX][nY] = 99;
}
}
}
}
}
} | 8 |
public MapPanel(Map map, Game game) {
this.game = game;
// Scrolling movement timer
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (mapImage_Scaled != null && viewPort != null
&& mouseInsidePanel) {
moveIfInBounds(checkIfInBounds(mousePoint));
}
}
}, 1000, 25);
// Adds mouse listeners to panel
listener = new MapPanel_MouseListener(this);
addMouseListener(listener);
addMouseMotionListener(listener);
// adds keylisteners to panel
new MapPanel_KeyPress(this);
// Creates the map
this.map = map;
// Read map image from file
try {
mapImage_Original = ImageIO.read(getClass().getResource(
"/imgs/maps/" + map.getMapName() + ".jpg"));
} catch (IOException e1) {
System.out.println("Error getting map image!");
}
setScaledCellDimensionsPx(map.getCellDimensionsPx());
scaleMap();
animationTimer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeCharacter();
redrawMap();
repaint();
}
});
animationTimer.start();
} | 4 |
private void quickSort(int left, int right) {
int l = left; // index of left-to-right scan
int r = right; // index of right-to-left scan
if (right - left >= 1)
{
int pivot = table[left];
while (r > l)
{
while (table[l] <= pivot && l <= right && r > l)
l++; // element greater than the pivot
while (table[r] > pivot && r >= left && r >= l)
r--; // element not greater than the pivot
if (r > l)
swap(l, r);
}
swap(left, r);
quickSort(left, r - 1); // quicksort the left partition
quickSort(r + 1, right); // quicksort the right partition
} else
{
return;
}
} | 9 |
@Test
public void WhenUpdatingUnknownHost_ExpectNothing()
throws UnknownHostException {
int level = localhost_.getHostPath().length();
RoutingTable table = new RoutingTable();
table.setLocalhost(localhost_);
Assert.assertTrue(table.uniqueHostsNumber() == 0);
Host host = new PGridHost("127.0.0.1", 3333);
table.addReference(0, host);
Assert.assertTrue(table.uniqueHostsNumber() == 1);
Host hostToUpdate = new PGridHost("127.0.0.1", 1111);
table.updateReference(hostToUpdate);
Assert.assertTrue(table.levelNumber() == level);
Assert.assertTrue(table.contains(host) && !table.contains(hostToUpdate));
Assert.assertTrue(table.uniqueHostsNumber() == 1);
} | 1 |
public String logUpload(String appKey, String userKey, String testId, String fileName, String dataType) {
try {
appKey = URLEncoder.encode(appKey, "UTF-8");
userKey = URLEncoder.encode(userKey, "UTF-8");
testId = URLEncoder.encode(testId, "UTF-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
BmLog.error(e);
}
return String.format("%s/api/rest/blazemeter/testDataUpload/?app_key=%s&user_key=%s&test_id=%s&file_name=%s&data_type=%s", SERVER_URL, appKey, userKey, testId, fileName, dataType);
} | 1 |
private void checkArithmeticExpression() throws Exception {
List<Token> expression = new ArrayList<Token>();
while(iterator < tokenList.size() && isValidArithmeticElement(tokenList.get(iterator))) {
expression.add(tokenList.get(iterator));
iterator++;
}
ShuntingYard shuntingYard = new ShuntingYard(expression);
expression = shuntingYard.run();
} | 2 |
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
if (command == null) { // This is a "CANTHAPPEN" since the TLD defines it as required
throw new JspException("CommandOutputTag: command attribute is required");
}
Process p = Runtime.getRuntime().exec(command);
InputStream streamFromProcess = null;
if (output) {
// getInputStream gives an Input stream connected to
// the process p's standard output. Just use it to make
// a BufferedReader to readLine() what the program writes out,
// and copy each line to the JSP output.
streamFromProcess = p.getInputStream();
} else if (error) {
streamFromProcess = p.getErrorStream();
}
if (streamFromProcess == null) {
throw new JspException("One of output='true' or error='true' is required");
}
BufferedReader is = new BufferedReader(new InputStreamReader(streamFromProcess));
String line;
while ((line = is.readLine()) != null) {
out.println(line);
}
is.close();
} catch (IOException ex) {
throw new JspException("TextImageServleg.doEndTag: IO Error", ex);
}
return EVAL_BODY_INCLUDE;
} | 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(InscriptionMembre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InscriptionMembre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InscriptionMembre.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InscriptionMembre.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 InscriptionMembre().setVisible(true);
}
});
} | 6 |
private boolean isInSomeUSet(Integer s) {
for (AcceptingPair pair : acceptanceCondition) {
if (pair.U.contains(s)) {
return true;
}
}
return false;
} | 2 |
public static Animation bulletAnimationRight(){
Animation anim = new Animation();
anim.addFrame(getMirrorImage(loadImage("bullet1.png")), 50);
anim.addFrame(getMirrorImage(loadImage("bullet2.png")), 50);
anim.addFrame(getMirrorImage(loadImage("bullet3.png")), 50);
return anim;
} | 0 |
public void visitIfZeroStmt(final IfZeroStmt stmt) {
if (CodeGenerator.DEBUG) {
System.out.println("code for " + stmt);
}
final Block t = stmt.trueTarget();
final Block f = stmt.falseTarget();
if (f == next) {
// Fall through to the false branch.
genIfZeroStmt(stmt);
} else if (t == next) {
// Fall through to the true branch.
stmt.negate();
genIfZeroStmt(stmt);
} else {
// Generate a goto to the false branch after the if statement.
genIfZeroStmt(stmt);
method.addLabel(method.newLabelTrue()); // Tom added "True"
method.addInstruction(Opcode.opcx_goto, f.label());
}
} | 3 |
public static void main(String[] args){
Set<Integer> tri = new HashSet<Integer>();
for(int i=1;i<1000;i++){
tri.add(i*(i+1)/2);
}
Scanner in = new Scanner(System.in);
int count=0;
while(in.hasNext()){
String s = in.next();
String[] prewords = s.split(",");
for(String w : prewords){
if(isTri(w.substring(1, w.length()-1), tri)) count++;
}
}
System.out.println(count);
} | 4 |
public void deleteVertex(String id) {
increaseAccess();
Node node = nodeMap.get(id);
if (node != null) {
for(Map.Entry<String, Edge> entrySet : this.edgeMap.entrySet()) {
Edge edge = entrySet.getValue();
/**
*/
if ((edge.getNode1().equals(node))
|| (edge.getNode2().equals(node))) {
//Kante löschen
edgeMap.remove(edge.getId());
}
}//zu guter letzt den Node löschen
nodeMap.remove(node.getId());
}
} | 4 |
private int buildJump(int xo, int maxLength)
{
int js = random.nextInt(4) + 2;
int jl = random.nextInt(2) + 2;
int length = js * 2 + jl;
boolean hasStairs = random.nextInt(3) == 0;
int floor = height - 1 - random.nextInt(4);
for (int x = xo; x < xo + length; x++)
{
if (x < xo + js || x > xo + length - js - 1)
{
for (int y = 0; y < height; y++)
{
if (y >= floor)
{
level.setBlock(x, y, (byte) (1 + 9 * 16));
}
else if (hasStairs)
{
if (x < xo + js)
{
if (y >= floor - (x - xo) + 1)
{
level.setBlock(x, y, (byte) (9 + 0 * 16));
}
}
else
{
if (y >= floor - ((xo + length) - x) + 2)
{
level.setBlock(x, y, (byte) (9 + 0 * 16));
}
}
}
}
}
}
return length;
} | 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Main other = (Main) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (!Arrays.equals(inhabitants, other.inhabitants))
return false;
return true;
} | 7 |
public boolean isLegalMoveTwo(int pieceNumber){
if (board[pieceNumber].getPieceType()==1 || board[pieceNumber].getPieceType()==2){
if (board[pieceNumber].getX()==(BOARDSIZE-board[pieceNumber].getLength()+1))
return false;
}
else{
if (board[pieceNumber].getY()==(BOARDSIZE-board[pieceNumber].getLength()+1))
return false;
}
int position = board[pieceNumber].getPositions()[board[pieceNumber].getPositions().length-1];
if (board[pieceNumber].getPieceType()==1 || board[pieceNumber].getPieceType()==2){
if (positions.contains(position+1))
return false;
}
else{
if (positions.contains(position+BOARDSIZE))
return false;
}
return true;
} | 8 |
public static boolean moveOneBoxToClosestGoalGreedyBFS(Vector<State> inOutStatesVector, int pBoxIndex){
//Set the comparator for this serach:
oneBoxMoveComp.setBoxToClosestGoal(pBoxIndex);
//Create a search queue;
PriorityQueue<State> open = new PriorityQueue<State>(100, oneBoxMoveComp);
//"Local" HashSet: Only the one box's position is relevant!
HashSet<State> visitedPositions = new HashSet<State>(); //MUST BE CHANGED TO FASTER ALGORITHM
//Add inputStates to search Queue:
for(State state : inOutStatesVector){
open.add(state);
//check that none of the initial state
if( 0 == Board.getGoalGradMerged( state.getBox(pBoxIndex).getRow(),
state.getBox(pBoxIndex).getCol()) ){
//return only the correct state.
inOutStatesVector.clear();
inOutStatesVector.add(state);
return true;
}
}
//Start search:
Vector<State> tempChildStates = new Vector<State>();
int iterations = 0;
while(open.size() > 0 && iterations < 100){
State curState = open.poll();
Visualizer.printStateDelux(curState, "/Solver: moveOneBoxToClosestGoalGreedyBFS");
System.out.println("open.size: " + open.size() + " iteration: " + iterations);
tempChildStates.clear();
curState.selectiveSuccessors(tempChildStates, pBoxIndex);
for (State child : tempChildStates){
if(0 == Board.getGoalGradMerged( child.getBox(pBoxIndex).getRow(),
child.getBox(pBoxIndex).getCol()) ){
//On TargetGoal!
inOutStatesVector.clear();
inOutStatesVector.add(child);
return true;
}
else{
if(visitedPositions.contains(child)){
//nothing...
}
else{
open.add(child);
visitedPositions.add(child);
}
}
}
iterations++;
}
if(Sokoban.debugMode){
System.out.println("/Solver/MoveOne...ClosestGreedyBFS: NO path was find for moving box: "
+ pBoxIndex + "to closest goal");
System.out.println("...queue size: " + open.size() + ", iterations: " + iterations);
}
//Same States are left in inOutVector... could also add intermediate states from the search!
return false;
} | 8 |
public static boolean setFechaDeLlegada(Paquete paquete)
{
Document doc;
Long identificadorPaquete;
Element root,child;
List <Element> rootChildrens;
boolean found = false;
int pos = 0;
SAXBuilder builder = new SAXBuilder();
try
{
doc = builder.build(Util.PAQUETE_XML_PATH);
root = doc.getRootElement();
rootChildrens = root.getChildren();
while (!found && pos < rootChildrens.size())
{
child = rootChildrens.get(pos);
identificadorPaquete = Long.parseLong(child.getAttributeValue(Util.PAQUETE_IDENTIFICADOR_TAG));
if(identificadorPaquete == paquete.getIdentificador()) {
rootChildrens.get(pos).setAttribute(Util.PAQUETE_FECHA_LLEGADA_TAG, Util.dateFormat.format(paquete.getFechaLlegada()));
rootChildrens.get(pos).setAttribute(Util.PAQUETE_STATUS_TAG, Util.STATUS_SATISFACTORIO_VALOR);
found = true;
}
pos++;
}
if(found) {
try
{
Format format = Format.getPrettyFormat();
XMLOutputter out = new XMLOutputter(format);
FileOutputStream file = new FileOutputStream(Util.PAQUETE_XML_PATH);
out.output(doc,file);
file.flush();
file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return found;
} | 6 |
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} | 4 |
private void unflashol() {
for (int i = 0; i < visol.length; i++) {
if ((olflash & (1 << i)) != 0)
visol[i]--;
}
olflash = 0;
olftimer = 0;
} | 2 |
@Override
public Administratie load() throws IOException {
if (!isCorrectlyConfigured()) {
throw new RuntimeException("Serialization mediator isn't initialized correctly.");
}
ObjectInputStream in = null;
FileInputStream stream = null;
Administratie adminObject = null;
// todo opgave 2
try{
stream = new FileInputStream("stamboomadministratie.txt");
in = new ObjectInputStream(stream);
adminObject = (Administratie) in.readObject();
}
catch(IOException exc){
exc.printStackTrace();
}
catch(ClassNotFoundException exc)
{
exc.printStackTrace();
}
finally{
if(in != null)
in.close();
if(stream != null)
stream.close();
}
return adminObject;
} | 5 |
public static void computeBoundingRect(ArrayList<Point> points) {
double minX = points.get(0).getX();
double maxX = minX;
double minY = points.get(0).getY();
double maxY = minY;
for (Point p:points) {
if (p.getX() < minX) minX = p.getX();
else if (p.getX() > maxX) maxX = p.getX();
if (p.getY() < minY) minY = p.getY();
else if (p.getY() > maxY) maxY = p.getY();
}
MIN_X = minX; MAX_X = maxX;
MIN_Y = minY; MAX_Y = maxY;
double a, bx, by; // coords = a*pixels + b
if ( MAX_X - MIN_X >= MAX_Y - MIN_Y ) {
DISP_RATIO = GRID_W / ( MAX_X - MIN_X );
a = 1/DISP_RATIO;
bx = MIN_X - a*WIN_MARGIN;
ORIG_X = (int) (-bx/a);
int bottomY = WIN_MARGIN + (int) (GRID_H/2 + DISP_RATIO*(MAX_Y-MIN_Y)/2);
by = MIN_Y + a*bottomY;
ORIG_Y = (int) (by/a);
} else {
DISP_RATIO = GRID_H / ( MAX_Y - MIN_Y );
System.out.println(DISP_RATIO);
a = -1/DISP_RATIO;
by = MAX_Y - a*WIN_MARGIN;
ORIG_Y = (int) (-by/a);
int rightX = WIN_MARGIN + (int) (GRID_W/2 + DISP_RATIO*(MAX_X-MIN_X)/2);
bx = MAX_X + a*rightX;
ORIG_X = (int) (bx/a);
}
} | 6 |
public ArrayList<HashMap<String, String>> read(File file) {
ArrayList<HashMap<String, String>> addressList = new ArrayList<>();
ICsvMapReader mapReader = null;
try {
mapReader = new CsvMapReader(new FileReader(file), CsvPreference.TAB_PREFERENCE);
// the header columns are used as the keys to the Map
final String[] header = mapReader.getHeader(true);
final CellProcessor[] processors = new CellProcessor[header.length];
for (int i = 0; i < header.length; i++) {
if (header[i] != null) {
processors[i] = new Optional();
}
}
Map<String, Object> address;
while ((address = mapReader.read(header, processors)) != null) {
addressList.add((HashMap) address);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (mapReader != null) {
try {
mapReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return addressList;
} | 7 |
public String tryJoinClub(int cid, int uid) {
// if that guy already existed in the club's member list
for (int existedMember : this.userDao.clubMembersUid(cid)) {
if (uid == existedMember)
return "member";
}
// if that guy already sent out an join_club_apply
for (Object obj : this.userDao.clubJoinApplyList(cid)) {
Map<?, ?> map = (Map<?, ?>) obj;
if (uid == Integer.parseInt(map.get("applicant_uid").toString()))
return "applying";
}
return "харашо"; // good to go
} | 8 |
public void newGame() {
money = 1000;
name = JOptionPane.showInputDialog(this, "Please enter your name:");
if (name == null) {
return;
}
File savegame = new File(PATH + name + ".csg");
if (savegame.exists()) {
Object[] options = { "Yes", "No" };
int option = JOptionPane.showOptionDialog(this,
"Save game already exists. Overwrite?", "Save game exists",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[1]);
if (option == 1) {
return;
}
}
try {
savegame.createNewFile();
saveGame();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
info.updateMoney(money);
info.updateName(name);
craps.setEnabled(true);
blackjack.setEnabled(true);
slots.setEnabled(true);
saveGame.setEnabled(true);
} | 4 |
public String getToolTip() {
return "Deleter";
} | 0 |
public void requireSanity(State s) {
boolean sane = true;
if (s.players().length != players.length) {
System.err.println("inconsistent belief: number of players changed");
sane = false;
}
if (!s.deck.containsAll(known_deck_cards)) {
CardBag surplus = known_deck_cards.clone();
surplus.removeAll(s.deck);
System.err.println("inconsistent belief: known_deck_cards "+known_deck_cards+" contains cards "+surplus+" that are not in the deck "+s.deck);
sane = false;
}
for (int i = 0; i < players.length; i++) {
if (!s.playerState(i).hand.containsAll(players[i].known_cards)) {
System.err.println("inconsistent belief: for player "+s.playerState(i).name+", known_cards "+players[i].known_cards+" contains cards that are not in the hand "+s.playerState(i).hand);
sane = false;
}
}
int total_card_count = 0;
total_card_count = cards_of_unknown_location.size();
total_card_count += known_deck_cards.size();
total_card_count += s.open_deck.size();
total_card_count += s.discarded.size();
for (int i = 0; i < players.length; i++)
total_card_count += players[i].known_cards.size();
if (total_card_count != State.INITIAL_DECK.size()) {
System.err.println("inconsistent belief: "+total_card_count+" cards in the game, should be "+State.INITIAL_DECK.size());
sane = false;
}
if (!sane) {
System.err.println("events that led to this belief (most recent event last):");
for (Event e: events)
System.err.println(" "+e);
throw new RuntimeException("inconsistent belief");
}
} | 8 |
public static String readTextFromJar(String s) {
InputStream is = null;
BufferedReader br = null;
String line;
String list="";
try {
is = misc.class.getResourceAsStream(s);
br = new BufferedReader(new InputStreamReader(is));
while (null != (line = br.readLine())) {
list+=line+"\n";
}
}
catch (Exception e) {
System.err.println("Error");
}
finally {
try {
if (br != null) br.close();
if (is != null) is.close();
}
catch (IOException e) {
System.err.println("Error");
}
}
return list;
} | 5 |
public static void startupJavaTranslate() {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.$STELLA_MODULE$);
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
_StartupJavaTranslate.helpStartupJavaTranslate1();
_StartupJavaTranslate.helpStartupJavaTranslate2();
}
if (Stella.currentStartupTimePhaseP(4)) {
_StartupJavaTranslate.helpStartupJavaTranslate3();
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
_StartupJavaTranslate.helpStartupJavaTranslate4();
_StartupJavaTranslate.helpStartupJavaTranslate5();
Stella.defineFunctionObject("JAVA-CREATE-OVERLOADED-FUNCTION-NAME", "(DEFUN (JAVA-CREATE-OVERLOADED-FUNCTION-NAME SYMBOL) ((FUNCTIONNAME SYMBOL) (CLASSTYPE TYPE)))", Native.find_java_method("edu.isi.stella.Symbol", "javaCreateOverloadedFunctionName", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate")}), null);
Stella.defineMethodObject("(DEFMETHOD (JAVA-TRANSLATE-METHOD-NAME STRING-WRAPPER) ((METHOD METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.MethodSlot", "javaTranslateMethodName", new java.lang.Class [] {}), ((java.lang.reflect.Method)(null)));
Stella.defineFunctionObject("JAVA-DELETE-QUOTED-NULL-STATEMENTS", "(DEFUN (JAVA-DELETE-QUOTED-NULL-STATEMENTS CONS) ((TREES CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaDeleteQuotedNullStatements", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-WRAP-METHOD-BODY-WITH-VARARG-DECLARATIONS", "(DEFUN (JAVA-WRAP-METHOD-BODY-WITH-VARARG-DECLARATIONS CONS) ((METHODBODY CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaWrapMethodBodyWithVarargDeclarations", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-WRAP-METHOD-BODY-WITH-VARARG-VALUE-SETUP", "(DEFUN (JAVA-WRAP-METHOD-BODY-WITH-VARARG-VALUE-SETUP CONS) ((METHODBODY CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaWrapMethodBodyWithVarargValueSetup", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-VARIABLE-LENGTH-ARG-NAME", "(DEFUN (JAVA-TRANSLATE-VARIABLE-LENGTH-ARG-NAME STRING-WRAPPER) ((NAMESYMBOL SYMBOL) (PARAMETERNUMBER INTEGER)))", Native.find_java_method("edu.isi.stella.Symbol", "javaTranslateVariableLengthArgName", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-VARIABLE-LENGTH-ACTUALS", "(DEFUN (JAVA-TRANSLATE-VARIABLE-LENGTH-ACTUALS CONS) ((ACTUALS CONS) (UNUSED-METHOD METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateVariableLengthActuals", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.MethodSlot")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-ACTUAL-PARAMETERS", "(DEFUN (JAVA-TRANSLATE-ACTUAL-PARAMETERS CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateActualParameters", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-YIELD-CLASS-NAME-FOR-FUNCTION", "(DEFUN (JAVA-YIELD-CLASS-NAME-FOR-FUNCTION STRING) ((FUNCTION METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.MethodSlot", "javaYieldClassNameForFunction", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.MethodSlot")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-FUNCTION-CALL", "(DEFUN (JAVA-TRANSLATE-FUNCTION-CALL CONS) ((TREE CONS) (METHOD METHOD-SLOT)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateFunctionCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.MethodSlot")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-DEFINED-OR-NULL", "(DEFUN (JAVA-TRANSLATE-DEFINED-OR-NULL CONS) ((CLASSTYPE TYPE) (OBJECT OBJECT) (NULL? BOOLEAN)))", Native.find_java_method("edu.isi.stella.Surrogate", "javaTranslateDefinedOrNull", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-METHOD-CALL", "(DEFUN (JAVA-TRANSLATE-METHOD-CALL CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-NORMAL-METHOD-CALL", "(DEFUN (JAVA-TRANSLATE-NORMAL-METHOD-CALL CONS) ((METHODNAME SYMBOL) (CLASSTYPE TYPE) (ALLARGS CONS)))", Native.find_java_method("edu.isi.stella.Symbol", "javaTranslateNormalMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-OPERATOR-TREE", "(DEFUN (JAVA-TRANSLATE-OPERATOR-TREE CONS) ((TREE CONS)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateOperatorTree", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-OPERATOR-CALL", "(DEFUN (JAVA-TRANSLATE-OPERATOR-CALL CONS) ((OPERATORNAMES CONS) (ARGUMENTS CONS) (ARITY INTEGER)))", Native.find_java_method("edu.isi.stella.Cons", "javaTranslateOperatorCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Cons"), Native.find_java_class("edu.isi.stella.Cons"), java.lang.Integer.TYPE}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-AREF-METHOD-CALL", "(DEFUN (JAVA-TRANSLATE-AREF-METHOD-CALL CONS) ((OPERATOR SYMBOL) (OWNER TYPE) (ARGUMENTS CONS)))", Native.find_java_method("edu.isi.stella.Symbol", "javaTranslateArefMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("JAVA-TRANSLATE-NTH-METHOD-CALL", "(DEFUN (JAVA-TRANSLATE-NTH-METHOD-CALL CONS) ((OPERATOR SYMBOL) (OWNER TYPE) (ARGUMENTS CONS)))", Native.find_java_method("edu.isi.stella.Symbol", "javaTranslateNthMethodCall", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Surrogate"), Native.find_java_class("edu.isi.stella.Cons")}), null);
Stella.defineFunctionObject("STARTUP-JAVA-TRANSLATE", "(DEFUN STARTUP-JAVA-TRANSLATE () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.stella._StartupJavaTranslate", "startupJavaTranslate", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(Stella.SYM_STELLA_STARTUP_JAVA_TRANSLATE);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupJavaTranslate"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("/STELLA")))));
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-TRUE-STRING-WRAPPER* STRING-WRAPPER (WRAP-LITERAL \"true\") :PUBLIC? FALSE :DOCUMENTATION \"Wrapped true string, used to reduce consing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-FALSE-STRING-WRAPPER* STRING-WRAPPER (WRAP-LITERAL \"false\") :PUBLIC? FALSE :DOCUMENTATION \"Wrapped false string, used to reduce consing.\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *VARARGSTATEMENTS* (CONS OF CONS) NIL :DOCUMENTATION \"A list of new vectors generated for variable-length argument \n lists\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *VARARGDECLS* (CONS OF CONS) NIL :DOCUMENTATION \"A list of vector-pushes generated for variable-length argument \n lists\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *CURRENTVARARGINDEX* INTEGER 1 :DOCUMENTATION \"The current index of the variable length arguments\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-OPERATOR-TABLE* KEY-VALUE-LIST (DICTIONARY @KEY-VALUE-LIST (QUOTE ++) (CONS (WRAP-LITERAL \"++\") NIL) (QUOTE --) (CONS (WRAP-LITERAL \"--\") NIL) (QUOTE +) (CONS (WRAP-LITERAL \"+\") NIL) (QUOTE -) (CONS (WRAP-LITERAL \"-\") NIL) (QUOTE *) (CONS (WRAP-LITERAL \"*\") NIL) (QUOTE /) (CONS (WRAP-LITERAL \"/\") NIL) (QUOTE EQ?) (CONS (WRAP-LITERAL \"==\") NIL) (QUOTE >) (CONS (WRAP-LITERAL \">\") NIL) (QUOTE >=) (CONS (WRAP-LITERAL \">=\") NIL) (QUOTE =>) (CONS (WRAP-LITERAL \">=\") NIL) (QUOTE <) (CONS (WRAP-LITERAL \"<\") NIL) (QUOTE =<) (CONS (WRAP-LITERAL \"<=\") NIL) (QUOTE <=) (CONS (WRAP-LITERAL \"<=\") NIL) (QUOTE AND) (CONS (WRAP-LITERAL \"&&\") NIL) (QUOTE OR) (CONS (WRAP-LITERAL \"||\") NIL) (QUOTE NOT) (CONS (WRAP-LITERAL \"!\") NIL) (QUOTE CHOOSE) (CONS (WRAP-LITERAL \"?\") (CONS (WRAP-LITERAL \":\") NIL))) :DOCUMENTATION \"Mapping from STELLA operators to Java operators\")");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-CHARACTER-SUBSTITUTION-TABLE* STRING (JAVA-CREATE-CHARACTER-SUBSTITUTION-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-RESERVED-WORD-TABLE* (STRING-HASH-TABLE OF STRING STRING-WRAPPER) (JAVA-CREATE-RESERVED-WORD-TABLE))");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *JAVA-LOOP-NAME* SYMBOL NULL)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFSPECIAL *JAVA-LOOP-NAME-USED?* BOOLEAN FALSE)");
Stella.defineStellaGlobalVariableFromStringifiedSource("(DEFGLOBAL *JAVA-PRIMITIVE-ARRAY-TYPE-NAMES* KEY-VALUE-LIST (DICTIONARY @KEY-VALUE-LIST \"byte\" \"B\" \"char\" \"C\" \"double\" \"D\" \"float\" \"F\" \"int\" \"I\" \"long\" \"J\" \"short\" \"S\" \"boolean\" \"Z\"))");
}
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
} | 6 |
@Override
public String toString() {
return rank + " of " + suit;
} | 0 |
public static List<String> getStrings(Language path, Object... args) {
// Gets the messages for the path submitted
List list = language.getList(path.getPath());
List<String> message = new ArrayList<String>();
if (list == null) {
Logging.warning("Missing language for: " + path.getPath());
return message;
}
// Parse each item in list
for (int i = 0; i < list.size(); i++) {
String temp = formatString(list.get(i).toString(), args);
// Pass the line into the line breaker
List<String> lines = Font.splitString(temp);
// Add the broken up lines into the final message list to return
for (int j = 0; j < lines.size(); j++) {
message.add(lines.get(j));
}
}
return message;
} | 3 |
public static void updateDescriptors(ArrayList<PathDescriptor> currentDescriptors, ArrayList<PathDescriptor> newDescriptors) {
System.out.println("Before Update");
System.out.println(currentDescriptors.toString());
int currentSize = currentDescriptors.size();
for (int i = 0; i < currentSize; ++i) {
PathDescriptor current = currentDescriptors.get(i);
PathDescriptor newDescriptor = PathDescriptor.FindIfEqualRelativePath(newDescriptors, current);
if (newDescriptor == null) {
switch(current.status) {
case Deleted:
break;
case Modified:
current.status = PathDescriptor.Status.Deleted;
current.statusTimePoint = new Date();
break;
}
} else {
switch(current.status) {
case Deleted:
current.lastCreationTime = new Date();
case Modified:
current.status = PathDescriptor.Status.Modified;
current.statusTimePoint = newDescriptor.statusTimePoint;
current.lastModified = newDescriptor.lastModified;
break;
}
}
}
int newSize = newDescriptors.size();
for (int i = 0; i < newSize; ++i) {
PathDescriptor newDescriptor = newDescriptors.get(i);
PathDescriptor current = PathDescriptor.FindIfEqualRelativePath(currentDescriptors, newDescriptor);
if (current == null) {
newDescriptor.statusTimePoint = new Date();
currentDescriptors.add(newDescriptor);
}
}
System.out.println("After Update");
System.out.println(currentDescriptors.toString());
} | 8 |
private static byte lengthOfMonth(byte month, int year) {
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
if (month == 2)
if (year%4 == 0 && (year%100 != 0 || year%400 == 0))
return 29;
else return 28;
return 31;
} | 8 |
public String question(String request) {
// TODO priority vs timer (all async)
for (Brain brain : brains) {
String response = brain.question(request);
if (null != response)
return response;
}
return null;
} | 2 |
public String getAuthor(SQLconnection connection,int id)
{
String query="select author from dblpauthor where paperid="+id;
ResultSet authorSet=connection.Query(query);
String author="";
try {
while(authorSet.next())
{
author+=authorSet.getString("author")+",";
}
authorSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
return author;
} | 2 |
public void input() {
float moveAmt = (float) (10 * Time.getDelta());
float rotAmt = (float) (100 * Time.getDelta());
if (Input.getKey(Input.KEY_W))
move(getForward(), moveAmt);
if (Input.getKey(Input.KEY_S))
move(getForward(), -moveAmt);
if (Input.getKey(Input.KEY_A))
move(getLeft(), moveAmt);
if (Input.getKey(Input.KEY_D))
move(getRight(), moveAmt);
if (Input.getKey(Input.KEY_UP))
rotateX(-rotAmt);
if (Input.getKey(Input.KEY_DOWN))
rotateX(rotAmt);
if (Input.getKey(Input.KEY_LEFT))
rotateY(-rotAmt);
if (Input.getKey(Input.KEY_RIGHT))
rotateY(rotAmt);
} | 8 |
@Override
public String toString() {
return "[filePath=" + filePath + ", fieldLineIndex=" + fieldLineIndex
+ ", skipLines=" + skipLines + ", dataTypeLineIndex="
+ dataTypeLineIndex + ", ignoreColumnIndex="
+ Arrays.toString(ignoreColumnIndex) + "]";
} | 0 |
void checkin() {
if (!Modeler.directMW)
return;
StringBuffer sb = new StringBuffer();
String os = System.getProperty("os.name") + " " + System.getProperty("os.version");
String user = ModelerUtilities.getUnicode(System.getProperty("user.name"));
try {
sb.append("os=" + URLEncoder.encode(os, "UTF-8"));
sb.append("&username=" + URLEncoder.encode(processSQLEscapeCharacters(user), "UTF-8"));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
sb.append("&javaversion=" + System.getProperty("java.version"));
sb.append("&mwversion=" + Modeler.VERSION);
boolean launcher = "yes".equals(System.getProperty("mw.launcher"));
String jws = Modeler.launchedByJWS ? "yes" : (Modeler.directMW ? (launcher ? "via" : "no") : "emb");
sb.append("&jws=" + jws);
URL url = null;
try {
url = new URL(Modeler.getContextRoot() + "reception?" + sb);
}
catch (MalformedURLException e) {
e.printStackTrace();
return;
}
URLConnection con = ConnectionManager.getConnection(url);
if (!(con instanceof HttpURLConnection))
return;
try {
((HttpURLConnection) con).setRequestMethod("POST");
}
catch (ProtocolException e) {
e.printStackTrace();
return;
}
con.setDoOutput(true);
try {
responseCode = ((HttpURLConnection) con).getResponseCode();
}
catch (IOException e) {
e.printStackTrace();
}
} | 9 |
public boolean not_left_value(String val,int size){
if(in_function == 1)
{
if(func_array_var.containsKey(val)){
array_info temp = func_array_var.get(val);
if(temp.dim != size-1)
return true;
}
}
else {
if(array_var.containsKey(val)){
array_info temp = array_var.get(val);
if(temp.dim != size-1)
return true;
}
}
return false;
} | 5 |
public static void toggleEditableForSingleNode(Node node, CompoundUndoable undoable) {
int oldValue = node.getEditableState();
int newValue = Node.EDITABLE_INHERITED;
boolean isEditable = node.isEditable();
if (oldValue == Node.EDITABLE_FALSE) {
node.setEditableState(Node.EDITABLE_TRUE);
newValue = Node.EDITABLE_TRUE;
} else if (oldValue == Node.EDITABLE_TRUE) {
node.setEditableState(Node.EDITABLE_FALSE);
newValue = Node.EDITABLE_FALSE;
} else {
if (isEditable) {
node.setEditableState(Node.EDITABLE_FALSE);
newValue = Node.EDITABLE_FALSE;
} else {
node.setEditableState(Node.EDITABLE_TRUE);
newValue = Node.EDITABLE_TRUE;
}
}
undoable.addPrimitive(new PrimitiveUndoableEditableChange(node, oldValue, newValue));
} | 3 |
static final public void facteur() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case VRAI:
case FAUX:
case entier:
case ident:
case 54:
primaire();
break;
case NON:
case SUBNEG:
opNeg();
primaire();
expression.testNeg();
expression.executerOpNeg();
break;
default:
jj_la1[20] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
} | 8 |
private void rmBus (Object busname)
{
USB bus = (USB) busses.get (busname);
if (trace)
System.err.println ("rmBus " + bus);
for (int i = 0; i < listeners.size (); i++) {
USBListener listener;
listener = (USBListener) listeners.elementAt (i);
try { listener.busRemoved (bus); }
catch (Exception e) {
e.printStackTrace ();
}
}
busses.remove (busname);
bus.kill ();
} | 3 |
public void thinkAndPlay() throws BadBoardException, BadMoveException, BadPartialMoveException {
System.out.println("computer is thinking...");
if (myGame.getCurrentPlayer( ) != myColor) {
throw new BadBoardException("AI can't move now, it's not AI's turn!");
}
if ( ! myGame.myBoard.myDice.getRolled( ) ) {
myGame.getMyBoard().myDice.roll( ); // if onBar then calls handleBar, if can'tMove then calls forfeit
}
Move aiMove = myStrategy.pickBestMove(myGame.getMyBoard( ), myColor);
/* might be null, might not have any moves, might be blocked! */
if ((aiMove == null) || (aiMove.getMyPartials( ).size( ) < 1) || (! aiMove.isPossible())) {
myStrategy = switchStrategy( );
aiMove = myStrategy.pickBestMove(myGame.getMyBoard( ), myColor);
/* what if this is null?? */
if ((aiMove == null) || (! aiMove.isPossible())) {
throw new NullPointerException("Darn, I don't know where to move.");
}
}
//System.out.println(myMoves);
System.out.println("AI will move to '" + aiMove + "'");
aiMove.doMove( );
} // thinkAndPlay() | 7 |
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (this.isOptOut()) {
return false;
}
// Is metrics already running?
if (taskId >= 0) {
return true;
}
// Begin hitting the server with glorious data
taskId = plugin.getServer().getScheduler()
.scheduleAsyncRepeatingTask(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide
// with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server owner decided to opt-out
if (Metrics.this.isOptOut() && taskId > 0) {
plugin.getServer().getScheduler()
.cancelTask(taskId);
taskId = -1;
}
}
// We use the inverse of firstPost because if it
// is the first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e PING!
Metrics.this.postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (final IOException e) {
Bukkit.getLogger().log(Level.INFO,
"[Metrics] " + e.getMessage());
}
}
}, 0, Metrics.PING_INTERVAL * 1200);
return true;
}
} | 5 |
public Personnage selectionPersonnage()
{
JFileChooser fc = new JFileChooser("./src/jars/sauvegarde");
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if(file.getName().contains(".data"))
{
System.out.println(file.getName() + "\n" + file.getPath());
ClassLoader cl = Main.class.getClassLoader();
String nom = "/src/jars/classespersonnages/" + file.getClass().getSimpleName() + ".jar";
System.out.println("test = " + nom);
try
{
cl.loadClass(nom);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
Personnage p = Personnage.loadPerso(file.getName());
System.out.println(p.afficheStatPersonnage());
return p;
}else
{
System.out.println("Fichier incorrecte");
}
}
return null;
} | 3 |
Subsets and Splits