text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void testCode(String code, int... expectedOutput) {
runner.run(code);
final String output = baos.toString();
assertEquals(expectedOutput.length, output.length());
for (int i = 0; i < output.length(); i++) {
assertEquals(expectedOutput[i], output.charAt(i));
}
} | 1 |
public static String stringPattern(String value){
String pattern = "";
for (int i = 1; i < Math.sqrt(value.length());i++){
StringBuilder strFirst = new StringBuilder("");
StringBuilder strSecond = new StringBuilder("");
StringBuilder strThird = new StringBuilder("");
for (int j = 1; j < 1*i+1; j++){
strFirst.append(value.charAt(j));
}
for (int j = 1*i+1; j < 2*i+1; j++){
strSecond.append(value.charAt(j));
}
for (int j = 2*i+1; j < 3*i+1; j++){
strThird.append(value.charAt(j));
}
if (strFirst.toString().equals(strSecond.toString())&& strFirst.toString().equals(strThird.toString())){
return strFirst.toString();
}
}
return "0";
} | 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(FormCadastrarExercicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormCadastrarExercicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormCadastrarExercicios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormCadastrarExercicios.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 FormCadastrarExercicios().setVisible(true);
}
});
} | 6 |
public Object getRemoteInterface(String nomEJB) throws ServicesLocatorException
{
// Le nom JNDI pour la récupération du service distant (stub du
// composant EJB) est de la forme :
// java:global/<nom projet EAR>/<nom sous-projet EJB>/<nom bean session EJB>!<nom complet avec package de l'interface remote du bean>
// Exemple :
// java:global/CabinetRecrutement_EAR/CabinetRecrutement_EJB/ServiceEntreprise!eu.telecom_bretagne.cabinet_recrutement.service.IServiceEntreprise
String nomJNDI = null;
if(nomEJB.equals("ServiceAsk"))
nomJNDI = "java:global/EAR/EJB/ServiceAsk!service.IEmployee";
else if(nomEJB.equals("ServiceValidate"))
nomJNDI = "java:global/EAR/EJB/ServiceValidate!service.IValidator";
// ATTENTION !!! La récupération d'un DAO n'existe ici que
// pour les contrôles (utilisés dans la servlet ControleDAOServlet) :
// ils ne sont normalement pas appelés par la couche IHM.
else if(nomEJB.equals("CommentDAO"))
nomJNDI = "java:global/EAR/EJB/CommentDAO!data.dao.CommentDAO";
else if(nomEJB.equals("EmployeeDAO"))
nomJNDI = "java:global/EAR/EJB/EmployeeDAO!data.dao.EmployeeDAO";
else if(nomEJB.equals("ServiceDAO"))
nomJNDI = "java:global/EAR/EJB/ServiceDAO!data.dao.ServiceDAO";
else if(nomEJB.equals("EmployeeDAO"))
nomJNDI = "java:global/EAR/EJB/ServiceDAO!data.dao.ServiceDAO";
else
throw new ServicesLocatorException("Il n'y a pas d'EJB avec ce nom... " + nomEJB);
// La méthode recherche d'abord le stub dans le cache, s'il est absent,
// il est récupéré via JNDI.
Object remoteInterface = cache.get(nomJNDI);
if (remoteInterface == null)
{
try
{
remoteInterface = initialContext.lookup(nomJNDI);
cache.put(nomJNDI, remoteInterface);
}
catch (Exception e)
{
throw new ServicesLocatorException(e);
}
}
return remoteInterface;
} | 8 |
@FXML public void action(ActionEvent event) {
if(event.getSource().equals(buttonOk)) {
String hpass = Hash.md5(editPass.getText());
if(editLogin.getText().equals("Компьютер"))
Model.getIntance().getFirstUser().empty();
else
Model.getIntance().getFirstUser().set(editLogin.getText(), hpass);
}
if(event.getSource().equals(buttonCancel))
Core.getIntance().close();
} | 3 |
public RandomListNode copyRandomList(RandomListNode head) {
if (head ==null){
return null;
}
RandomListNode temp = head;
while (temp!=null){
RandomListNode copy = new RandomListNode(temp.label);
RandomListNode nextNode = temp.next;
temp.next = copy;
copy.next = nextNode;
temp = nextNode;
}
temp = head;
RandomListNode ret = head.next;
while (temp !=null){
if(temp.random != null)
temp.next.random = temp.random.next;
temp = temp.next.next;
}
temp = head;
while (temp !=null){
RandomListNode nextNode = temp.next.next;
if (nextNode != null)
temp.next.next = nextNode.next;
temp.next = nextNode;
temp = nextNode;
}
return ret;
} | 6 |
public void wechsleSpieler(Spieler s) {
System.out.println("spieler wechseln");
if(s.fraktion.equals(spieler1.fraktion))
aktuellerSpieler = spieler2;
else if (s.fraktion.equals(spieler2.fraktion))
aktuellerSpieler = spieler1;
frame.getBeendenButton().doClick();
} | 2 |
public void setRoomId(String roomId) {
this.roomId.add(roomId);
} | 0 |
private void handleNetworkCommand(String[] args) throws IOException {
if (pfactory.hasGameNetwork()) {
if (args[0].equalsIgnoreCase("start")) {
pfactory.sendStartGamePacket(Strategy.Standard, 1);
} else if (args[0].equalsIgnoreCase("play")) {
handlePlayCommand(args);
} else if (args[0].equalsIgnoreCase("bet")) {
handleBetCommand(args);
}
} else {
LOG.warn("No connection available! Use \"/join\" or \"/joinip\" first");
}
} | 4 |
public List<Utr> findUtrs(Marker marker) {
List<Utr> utrs = new LinkedList<Utr>();
// Is it in UTR instead of CDS?
for (Utr utr : utrs)
if (utr.intersects(marker)) utrs.add(utr);
return utrs.isEmpty() ? null : utrs;
} | 3 |
public Capabilities getCapabilities() {
Capabilities result;
Capabilities classes;
Iterator iter;
Capability capab;
if (getFilter() == null)
result = super.getCapabilities();
else
result = getFilter().getCapabilities();
// only nominal and numeric classes allowed
classes = result.getClassCapabilities();
iter = classes.capabilities();
while (iter.hasNext()) {
capab = (Capability) iter.next();
if ( (capab != Capability.BINARY_CLASS)
&& (capab != Capability.NOMINAL_CLASS)
&& (capab != Capability.NUMERIC_CLASS)
&& (capab != Capability.DATE_CLASS) )
result.disable(capab);
}
// set dependencies
for (Capability cap: Capability.values())
result.enableDependency(cap);
if (result.getMinimumNumberInstances() < 1)
result.setMinimumNumberInstances(1);
result.setOwner(this);
return result;
} | 8 |
public int addTile(Tile t) {
if (t.getId() < 0)
t.setId(tiles.size());
if (tileDimensions.width < t.getWidth())
tileDimensions.width = t.getWidth();
if (tileDimensions.height < t.getHeight())
tileDimensions.height = t.getHeight();
tiles.add(t);
t.setTileSet(this);
return t.getId();
} | 3 |
public Reply sendCommand(Command cmd) throws IOException {
if (getConnectionStatusLock() == CSL_DIRECT_CALL)
setConnectionStatus(BUSY);
controlBuffer.clear();
//for the command PASS hide the password in created logfile
if (cmd.getCommand().equals(Command.PASS)){
String value = Command.PASS;
for(int i = 0; i < cmd.getParameter().length; i++)
//replace the characters of the password with Xs
value += " " + ((cmd.getParameter()[i]==null)?cmd.getParameter():cmd.getParameter()[i].replaceAll(".", "X"));
log.debug("Sending command: "+value.trim());
}else
log.debug("Sending command: "
+ cmd.toString().substring(0, cmd.toString().length() - 2));
controlBuffer.put(cmd.toString());
controlBuffer.flip();
socketProvider.write(encoder.encode(controlBuffer));
controlBuffer.clear();
Reply reply = null;
try {
reply = ReplyWorker.readReply(socketProvider);
}catch(IOException ioe) {
setConnectionStatus(ERROR);
disconnect();
throw ioe;
}
if (getConnectionStatusLock() == CSL_DIRECT_CALL)
setConnectionStatus(IDLE);
if (reply != null)
fireReplyMessageArrived(new FTPEvent(this, getConnectionStatus(), reply));
return reply;
} | 7 |
public static void question9a() {
/*
QUESTION PANEL SETUP
*/
questionLabel.setText("Which of these below do you like the most?");
questionNumberLabel.setText("9a");
/*
ANSWERS PANEL SETUP
*/
//resetting
radioButton1.setSelected(false);
radioButton2.setSelected(false);
radioButton3.setSelected(false);
radioButton4.setSelected(false);
radioButton5.setSelected(false);
radioButton6.setSelected(false);
radioButton7.setSelected(false);
radioButton8.setSelected(false);
radioButton9.setSelected(false);
radioButton10.setSelected(false);
radioButton11.setSelected(false);
radioButton12.setSelected(false);;
radioButton13.setSelected(false);
radioButton14.setSelected(false);
//enability
radioButton1.setEnabled(true);
radioButton2.setEnabled(true);
radioButton3.setEnabled(true);
radioButton4.setEnabled(true);
radioButton5.setEnabled(true);
radioButton6.setEnabled(true);
radioButton7.setEnabled(true);
radioButton8.setEnabled(true);
radioButton9.setEnabled(true);
radioButton10.setEnabled(true);
radioButton11.setEnabled(true);
radioButton12.setEnabled(true);
radioButton13.setEnabled(true);
radioButton14.setEnabled(true);
//setting the text
radioButton1.setText("Dating.");
radioButton2.setText("Shooting pool.");
radioButton3.setText("Playing video games.");
radioButton4.setText("Eating!");
radioButton5.setText("Going on a play");
radioButton6.setText("Just plain entertainment");
radioButton7.setText("Shopping.");
radioButton8.setText("Watching basketball.");
radioButton9.setText("Waching soccer.");
radioButton10.setText("Watching football.");
radioButton11.setText("Gamble.");
radioButton12.setText("I like smoking shisha.");
radioButton13.setText("Watching speedway.");
radioButton14.setText("Don't really care.");
// Calculating the best guesses and showing them.
Knowledge.calculateAndColorTheEvents();
} | 0 |
public void pota() {
if (padre != null) padre.rimuoviFiglio(posFiglio);
} | 1 |
private void addVertices(ArrayList<Vertex> vertices, int i, int j, float offset, boolean y, boolean z, boolean x,
float[] texCoords) {
if(x && z) {
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, offset * SPOT_HEIGHT, j * SPOT_LENGTH),
new Vector2f(texCoords[1], texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, offset * SPOT_HEIGHT, j * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, offset * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[2])));
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, offset * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH),
new Vector2f( texCoords[1], texCoords[2])));
}else if(x && y) {
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, j * SPOT_HEIGHT, offset * SPOT_LENGTH),
new Vector2f(texCoords[1], texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1)* SPOT_WIDTH, j * SPOT_HEIGHT, offset * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[3])));
vertices.add(new Vertex(new Vector3f((i + 1) * SPOT_WIDTH, (j + 1) * SPOT_HEIGHT, offset * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[2])));
vertices.add(new Vertex(new Vector3f(i * SPOT_WIDTH, (j + 1) * SPOT_HEIGHT, offset * SPOT_LENGTH),
new Vector2f( texCoords[1], texCoords[2])));
}else if(y && z) {
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, i * SPOT_HEIGHT, j * SPOT_LENGTH),
new Vector2f(texCoords[1], texCoords[3])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, i * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[3])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, (i + 1) * SPOT_HEIGHT, (j + 1) * SPOT_LENGTH),
new Vector2f(texCoords[0], texCoords[2])));
vertices.add(new Vertex(new Vector3f(offset * SPOT_WIDTH, (i + 1) * SPOT_HEIGHT, j * SPOT_LENGTH),
new Vector2f( texCoords[1], texCoords[2])));
}else{
System.err.println("Invalid plane used in level generator. Level#addVertices");
new Exception().printStackTrace();
System.exit(1);
}
} | 6 |
private void parseValue(String line, int lineNum) {
// skip a comment line
if (line.startsWith(COMMENT)) {
return;
}
String[] sp = line.split("\\s+"); // split the fields based on a space
int len = 0; // length of a string
int index = 0; // the index of an array
// check for each field in the array
for(String elem : sp) {
len = elem.length(); // get the length of a string
// if it is empty then ignore
if (len == 0) {
continue;
}
// if not, then put into the array
else {
fieldArray[index] = elem;
index++;
}
}
if (index == PLATFORM_MAX_FIELD) {
platform_extractField(fieldArray, lineNum);
}
if (index == NODE_MAX_FIELD) {
node_extractField(fieldArray, lineNum);
}
} | 5 |
private void close() throws BITalinoException {
try {
socket.close();
} catch (Exception e) {
throw new BITalinoException(BITalinoErrorTypes.BT_DEVICE_NOT_CONNECTED);
} finally {
socket = null;
}
} | 1 |
private void removeFullLines()
{
int numFullLines = 0;
for (int i = BoardHeight - 1; i >= 0; --i) {
boolean lineIsFull = true;
for (int j = 0; j < BoardWidth; ++j) {
if (shapeAt(j, i) == Tetrominoes.NoShape) {
lineIsFull = false;
break;
}
}
if (lineIsFull) {
++numFullLines;
for (int k = i; k < BoardHeight - 1; ++k) {
for (int j = 0; j < BoardWidth; ++j)
board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
}
}
}
if (numFullLines > 0) {
numLinesRemoved += numFullLines;
statusbar.setText(String.valueOf(numLinesRemoved));
isFallingFinished = true;
curPiece.setShape(Tetrominoes.NoShape);
repaint();
}
} | 7 |
@Override
public void handleGameEvent(GameEvent e) {
switch(e.type){
case COLLISION:
break;
case PLAYER_JUMP:
System.out.println("Player jump");
break;
case PLAYER_MOVE_DOWN:
System.out.println("Player down");
break;
case PLAYER_MOVE_LEFT:
System.out.println("Player left");
break;
case PLAYER_MOVE_RIGHT:
System.out.println("Player right");
break;
case PLAYER_MOVE_UP:
System.out.println("Player up");
break;
case PLAYER_SPECIAL1:
System.out.println("Player special1");
break;
case PLAYER_SPECIAL2:
System.out.println("Player special2");
break;
case PLAYER_SPECIAL3:
System.out.println("Player special3");
break;
}
} | 9 |
public void updateUI(World w, Gameplay g) {
hexgrid.updateGrid(w, g);
} | 0 |
public double weightedStandardDeviation_as_double() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
boolean holdW = Stat.weightingOptionS;
if (weightingReset) {
if (weightingOptionI) {
Stat.weightingOptionS = true;
} else {
Stat.weightingOptionS = false;
}
}
double varr = 0.0;
if (!weightsSupplied) {
System.out.println("weightedStandardDeviation_as_double: no weights supplied - unweighted value returned");
varr = this.standardDeviation_as_double();
} else {
double variance = 0.0D;
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
double[] ww = amWeights.getArray_as_double();
variance = Stat.variance(dd, ww);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
BigDecimal[] wd = amWeights.getArray_as_BigDecimal();
variance = (Stat.variance(bd, wd)).doubleValue();
bd = null;
wd = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to double");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
varr = Math.sqrt(variance);
}
Stat.nFactorOptionS = hold;
Stat.weightingOptionS = holdW;
return varr;
} | 8 |
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(MostrarCentro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MostrarCentro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MostrarCentro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MostrarCentro.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 MostrarCentro().setVisible(true);
}
});
} | 6 |
public int linearRegAngleLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 14;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return optInTimePeriod-1;
} | 3 |
public static void decodeFileToFile(String infile, String outfile)
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream(outfile));
out.write(decoded);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try {
out.close();
} catch (Exception ex) {
}
} // end finally
} // end decodeFileToFile | 2 |
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(AddAssetToElement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddAssetToElement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddAssetToElement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddAssetToElement.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 AddAssetToElement().setVisible(true);
}
});
} | 6 |
public String readChunk() throws IOException {
StringWriter writer = new StringWriter();
int ich;
int lastich = -1;
for (ich = this.nextChar(); ich != -1; ich = this.nextChar()) {
char ch = (char)ich;
if (ch == ChunkDelimeter && lastich != -1) {
ich = this.nextChar();
if (ich == -1 || (char) ich != ChunkDelimeter) {
this.pushChar(ich);
break;
}
}
if (lastich == -1 && (ch == '\r' || ch == '\n'))
continue;
writer.write(ich);
lastich = ich;
}
writer.close();
String result = writer.toString();
if (result.equals(""))
return null;
return result;
} | 9 |
public static void main(String[] args) {
int max = 0;
//all vertical
for (int x = 0; x <= 16; x++) {
for (int y = 0; y <= 19; y++) {
int[][] coords = {{x,y},{x+1,y},{x+2,y},{x+3,y}};
max = Math.max(max, product(coords));
}
}
//all horizontal
for (int x = 0; x <= 19; x++) {
for (int y = 0; y <= 16; y++) {
int[][] coords = {{x,y},{x,y+1},{x,y+2},{x,y+3}};
max = Math.max(max, product(coords));
}
}
//all diagonal down
for (int x = 0; x <= 16; x++) {
for (int y = 0; y <= 16; y++) {
int[][] coords = {{x,y},{x+1,y+1},{x+2,y+2},{x+3,y+3}};
max = Math.max(max, product(coords));
}
}
//all diagonal up, reversing x iteration
for (int x = 19; x >= 3; x--) {
for (int y = 0; y <= 16; y++) {
int[][] coords = {{x,y},{x-1,y+1},{x-2,y+2},{x-3,y+3}};
max = Math.max(max, product(coords));
}
}
System.out.println(max);
} | 8 |
@Override
public void paint(Graphics g) {
if (state == GameState.Running) {
g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
paintTiles(g);
ArrayList projectiles = robot.getProjectiles();
for (int i = 0; i < projectiles.size(); i++) {
Projectile p = (Projectile) projectiles.get(i);
g.setColor(Color.YELLOW);
g.fillRect(p.getX(), p.getY(), 10, 5);
}
g.drawImage(currentSprite, robot.getCenterX() - 61,
robot.getCenterY() - 63, this);
for(int i = 0; i< hb.size();++i){
g.drawImage(hanim.getImage(), hb.get(i).getCenterX() - 48,
hb.get(i).getCenterY() - 48, this);
}
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(Integer.toString(score), 740, 30);
} else if (state == GameState.Dead) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, 800, 480);
g.setColor(Color.WHITE);
g.drawString("Dead", 360, 240);
}
} | 4 |
public synchronized void poll() {
// If relative, return only the delta movements,
// otherwise return the current position...
if (isRelative()) {
mousePos = new Point(dx, dy);
} else {
mousePos = new Point(currentPos);
}
// Since we have polled, need to reset the delta
// so the values do not accumulate
dx = dy = 0;
// Check each mouse button
for (int i = 0; i < BUTTON_COUNT; ++i) {
// If the button is down for the first
// time, it is ONCE, otherwise it is
// PRESSED.
if (state[i]) {
if (poll[i] == MouseState.RELEASED)
poll[i] = MouseState.ONCE;
else
poll[i] = MouseState.PRESSED;
} else {
// Button is not down
poll[i] = MouseState.RELEASED;
}
}
} | 4 |
private File writeDotSourceToFile(String str) throws java.io.IOException
{
File temp;
try {
temp = File.createTempFile("graph_", ".dot.tmp", new File(GraphViz.TEMP_DIR));
FileWriter fout = new FileWriter(temp);
fout.write(str);
fout.close();
}
catch (Exception e) {
System.err.println("Error: I/O error while writing the dot source to temp file!");
return null;
}
return temp;
} | 1 |
private MBox createBox(int posX, int posY, char c) throws MazeException {
MBox retour = new EBox(posX, posY);
if (c == 'W')
retour = new WBox(posX, posY);
else if (c == 'E') { //variable deja initialise
} else if (c == 'A') {
if (grid.indexOf(new ABox(0, 0)) != -1)
throw new MazeException("Deja une case d'arrivee!");
else
retour = new ABox(posX, posY);
} else if (c == 'D') {
if (grid.indexOf(new DBox(0, 0)) != -1)
throw new MazeException("Deja une case de depart!");
else
retour = new DBox(posX, posY);
} else
throw new MazeException(" Caractere non recevable: " + c);
return retour;
} | 6 |
public void pickUp(String object, ArrayList<String> inv) {
if (object.equalsIgnoreCase("floor")) {
System.out.println("You can't pick up the floor...\n");
} else if (object.equalsIgnoreCase("wall") || object.equalsIgnoreCase("walls")) {
System.out.println("You can't pick up the walls...\n");
} else if (object.equalsIgnoreCase("door")) {
System.out.println("You can't pick up the door...\n");
} else if (object.equalsIgnoreCase("telephone") || object.equalsIgnoreCase("phone")) {
System.out.println("You pick up the telephone and hold it against your ear. You think you can hear a soft humming noise coming \n" +
"from the other end, but you are not sure. What do you say?\n");
phone();
} else if (object.equalsIgnoreCase("cord")) {
System.out.println("You pull at the cord, but it won't give.\n");
} else {
System.out.println("You want to pick up what?\n");
}
} | 7 |
public String getTelefon2() {
return telefon2;
} | 0 |
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
if (id != null) {
return id.equals(((Player) that).id);
}
return super.equals(that);
} | 4 |
private int jjMoveStringLiteralDfa14_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 13);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 13);
}
switch(curChar)
{
case 49:
return jjMoveStringLiteralDfa15_0(active0, 0xfffe00000000000L);
default :
break;
}
return jjMoveNfa_0(0, 14);
} | 3 |
public Behaviour getNextStep() {
if (! configured()) return null ;
if (stage == STAGE_GET_SEED) {
final Action collects = new Action(
actor, nursery,
this, "actionCollectSeed",
Action.LOOK, "Collecting seed"
) ;
return collects ;
}
if (stage == STAGE_PLANTING) {
final Action plants = new Action(
actor, toPlant,
this, "actionPlant",
Action.BUILD, "Planting"
) ;
final Tile to = Spacing.pickFreeTileAround(toPlant, actor) ;
plants.setMoveTarget(to) ;
return plants ;
}
if (stage == STAGE_SAMPLING) {
final Action cuts = new Action(
actor, toCut,
this, "actionCutting",
Action.BUILD, "Cutting"
) ;
cuts.setMoveTarget(Spacing.nearestOpenTile(toCut.origin(), actor)) ;
return cuts ;
}
if (stage == STAGE_RETURN) {
final Action returns = new Action(
actor, nursery,
this, "actionReturnHarvest",
Action.REACH_DOWN, "Returning Harvest"
) ;
return returns ;
}
return null ;
} | 5 |
public static HashMap<String, Object> parseMap(StringBuffer buf, int[] idx) {
idx[0]++;
HashMap<String, Object> into = new HashMap<String, Object>();
while (true) {
skipSpace(buf, idx);
if (idx[0] >= buf.length()) {
System.err.println("Unexpected end");
return into;
}
if (buf.charAt(idx[0]) == '}') {
idx[0]++;
return into; // Done
}
if (buf.charAt(idx[0]) == ',') {
idx[0]++;
continue; // skip commas, don't check for errors
}
// Should have a string key
String key = (String) parseObject(buf, idx);
// Should have colon
skipSpace(buf, idx);
assert (buf.charAt(idx[0]) == ':');
idx[0]++;
skipSpace(buf, idx);
into.put(key, parseObject(buf, idx));
}
} | 4 |
private boolean placeFire(int x, int y, position pos) {
boolean firePlaced = true;
ItemList items = field.getItems(x, y);
ItemList itCopy = new ItemList();
itCopy.addAll(items);
for (Item i : itCopy) {
if (i instanceof Player) {
Player p = (Player) i;
p.die();
firePlaced = true;
} else if (i instanceof Bomb) {
explode((Bomb) i);
firePlaced = true;
} else if (i instanceof Fire) {
firePlaced = true;
} else if (i instanceof BlockDestroyable) {
BlockDestroyable b = (BlockDestroyable) i;
b.startDestroy();
newActiveItems.add(b);
firePlaced = false;
} else if (i instanceof Powerup) {
Powerup p = (Powerup) i;
p.startDestroy();
newActiveItems.add(p);
firePlaced = false;
} else if (i instanceof BlockWall) {
firePlaced = false;
} else {
System.out.println("Ups, wer ist das? "
+ i.getClass().getName());
}
}
if (firePlaced) {
Fire fire = new Fire(x, y, pos);
field.addItem(fire);
newActiveItems.add(fire);
}
return firePlaced;
} | 8 |
public void draw(GOut og) {
GOut g = og.reclip(tlo, wsz);
Coord bgc = new Coord();
for (bgc.y = 3; bgc.y < wsz.y - 6; bgc.y += bg.sz().y) {
for (bgc.x = 3; bgc.x < wsz.x - 6; bgc.x += bg.sz().x)
g.image(bg, bgc, new Coord(3, 3), wsz.add(new Coord(-6, -6)));
}
cdraw(og.reclip(xlate(Coord.z, true), sz));
wbox.draw(g, Coord.z, wsz);
if (cap != null && draw_cap) {
GOut cg = og.reclip(new Coord(0, -7), sz.add(0, 7));
int w = cap.tex().sz().x;
int x0 = (folded) ? (mrgn.x + (w / 2)) : (sz.x / 2) - (w / 2);
cg.image(cl, new Coord(x0 - cl.sz().x, 0));
cg.image(cm, new Coord(x0, 0), new Coord(w, cm.sz().y));
cg.image(cr, new Coord(x0 + w, 0));
cg.image(cap.tex(), new Coord(x0, 0));
}
super.draw(og);
} | 5 |
public final void parse(String options){
this.reset();
selectorFormat = options.replaceAll("\\s+", "");
String trimmed;
if(selectorFormat.charAt(1)==this.bracketsOpen&&
selectorFormat.charAt(selectorFormat.length()-1)==this.bracketsClose){
if(selectorFormat.charAt(0)=='-'){
this.particleSign = -1;
} else {this.particleSign = 1;}
trimmed = selectorFormat.substring(2, selectorFormat.length()-1);
} else if(selectorFormat.charAt(0)==this.bracketsOpen&&
selectorFormat.charAt(selectorFormat.length()-1)==this.bracketsClose){
trimmed = selectorFormat.substring(1, selectorFormat.length()-1);
this.particleSign = 1;
} else {
System.err.println("[ParticleSelector] ---> Syntax error. in string ("
+this.selectorFormat + ").");
return;
}
//trimmed = selectorFormat.substring(2, selectorFormat.length()-1);
//System.err.println("[DEBUG]--> trimmed string = (" + trimmed + ")");
String[] tokens = trimmed.split(",");
if(tokens.length>0){
this.parseParticleID(tokens[0]);
this.overrideParticleID = this.particleID;
}
if(tokens.length>1){
particleSkip = Integer.parseInt(tokens[1]);
} else {
particleSkip = 0;
}
if(tokens.length>2){
overrideParticleID = Integer.parseInt(tokens[2]);
this.overridePid = true;
}
} | 8 |
@Override
public boolean test(String value) {
// TODO Auto-generated method stub
if(value == null || value.length() == 0) return false;
try {
int sal = Integer.parseInt(value);
if ((sal >= 500 && sal <= 20500)||sal==0){
return true;
}
} catch (Exception e) {
// TODO: handle exception
return false;
}
return false;
} | 6 |
public void startLocalMultiplayerGame() {
if (this.isActive) {
if (JOptionPane.showConfirmDialog(null, "Are you sure?", "Restart game", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
this.endGame();
this.startGame();
}
} else {
this.startGame();
}
} | 2 |
@Override
public int compareTo(SingleCounter that) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
// TODO Auto-generated method stub
if (this == that) return EQUAL;
if (this.value < that.value) return AFTER;
if (this.value > that.value) return BEFORE;
return EQUAL;
} | 3 |
@Test(expected=BusinessException.class)
public void partidoSinIniciarNoPuedeGenerarEquipos() {
for (int i = 0; i < 3; i++) {
inscribir(partidoPocosJugadores, new Jugador());
}
partidoPocosJugadores.generarEquipos();
} | 1 |
private static void addFocusArrowListener(JComponent jc) {
/**
* Check to see if someone already added this kind of listener:
*/
KeyListener[] listeners = jc.getKeyListeners();
for (KeyListener listener : listeners) {
if (listener instanceof FocusArrowListener) {
return;
}
}
// Add our own:
jc.addKeyListener(new FocusArrowListener());
} | 2 |
@Override
public StateModule getState() {
return state;
} | 0 |
public DbConfig(String dbName) throws IOException {
dbProperties = new Properties();
String userHomeProperties = System.getProperty("user.home")+"/."+DB_PROPERTIES;
try {
if (new File(userHomeProperties).exists()) {
dbProperties.load(new FileInputStream(userHomeProperties));
} else {
dbProperties.load(getClass().getClassLoader().getResourceAsStream(DB_PROPERTIES));
}
} catch (Exception e) {
throw new RuntimeException("Reading property file '" + userHomeProperties +
"' or property file '" + DB_PROPERTIES + "' not found in the classpath!");
}
dbPrefix = isEmpty(dbName) ? "" : dbName + ".";
if (isEmpty(getProperty(DB_DRIVER))) {
throw new RuntimeException("JDBC Driver property '" + dbPrefix + DB_DRIVER + "' not found");
}
if (isEmpty(getProperty(DB_URL))) {
throw new RuntimeException("DB URL property '" + dbPrefix + DB_URL + "' not found!");
}
if (isEmpty(getProperty(DB_USER))) {
dbProperties.put(dbPrefix + DB_USER, CommandReader.readPassword("username: "));
}
if (isEmpty(getProperty(DB_PASS))) {
dbProperties.put(dbPrefix + DB_PASS, CommandReader.readPassword("password: "));
}
if (isEmpty(getProperty(DB_AUTO_COMMIT))) {
dbProperties.put(dbPrefix + DB_AUTO_COMMIT, "true");
}
if (isEmpty(getProperty(DB_READ_ONLY))) {
dbProperties.put(dbPrefix + DB_READ_ONLY, "false");
}
} | 9 |
private synchronized void sendScreenSegment(int x, int y, int w, int h) {
if(maxSend != -1) {
if(w * h > maxSend) {
int totalSent = 0;
while(totalSent < h) {
int h1 = maxSend / w;
if(h1 == 0)
h1 = 1;
if(h1 > h - totalSent)
h1 = h - totalSent;
sendScreenSegment(x, y + totalSent, w, h1);
totalSent += h1;
}
return;
}
}
stripsSent++;
try {
adjustmentArrayOutputStream.writeInt(x);
adjustmentArrayOutputStream.writeInt(y);
adjustmentArrayOutputStream.writeInt(w);
adjustmentArrayOutputStream.writeInt(h);
writeInts(pixels[newScreen], width, height, x, y, w, h);
adjustmentArrayOutputStream.flush();
if(maxScreenUpdateChunk != -1 && adjustmentArrayOutputStream.size() > maxScreenUpdateChunk) {
endSend(RoboProtocol.SCREEN_RESPONSE_PART);
resetSendParams();
}
} catch (Exception e) {
}
} | 8 |
public static boolean inBank() {
int x = Players.getLocal().getLocation().getX();
int y = Players.getLocal().getLocation().getY();
return x >= 3250 && y >= 3419 && x <= 3257 && y <= 3423;
} | 3 |
public int checkBoundary(Vector3f playerPos)
{
int max = -1;
if(playerPos.x > maxX)
{
if(Math.abs(maxX - playerPos.x) > max)
{
max = 90;
}
}
if(playerPos.x <= minX)
{
if(Math.abs(minX - playerPos.x) > max)
{
max = 270;
}
}
if(playerPos.z > maxZ)
{
if(Math.abs(maxZ - playerPos.z) > max)
{
max = 180;
}
}
if(playerPos.z <= minZ)
{
if(Math.abs(minZ - playerPos.z) > max)
{
max = 0;
}
}
return max;
} | 8 |
public void processQueries(String strInputFilePath, String strOutputFilePath)
throws IOException {
oBufferedReader = new BufferedReader(new FileReader(strInputFilePath));
oBufferedWriter = new BufferedWriter(new FileWriter(strOutputFilePath));
calcuateTFIDF(oBufferedReader);
oBufferedReader.close();
oBufferedReader = new BufferedReader(new FileReader(strInputFilePath));
String strLine = null;
String strNumber = null;
Hashtable<String, Double> oTempTermVsTFIDF = new Hashtable<String, Double>();
while ((strLine = oBufferedReader.readLine()) != null) {
if (strLine.trim().length() == 0)
continue;
// if (strLine.trim().equalsIgnoreCase("</top>")) {
// writeTermsToFile(strNumber, oTempTermVsTFIDF);
// } else
if (strLine.trim().startsWith("<num>")) {
strNumber = strLine.substring(strLine.indexOf(":") + 1).trim();
} else if (strLine.trim().startsWith("<desc>")
|| !strLine.trim().startsWith("<")) {
if (strLine.startsWith("<desc>"))
strLine = strLine.substring(8).trim().toLowerCase();
// ----
for (String strTerm : strLine.split(" ")) {
// ----
if (oTermVsTFIDF.containsKey(strTerm))
oTempTermVsTFIDF
.put(strTerm, oTermVsTFIDF.get(strTerm));
}
}
}
// for (Entry<String, Double> entry : oTempTermVsTFIDF.entrySet()) {
// System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue() + ", Terms = " + entry);
// }
System.out.println(oTempTermVsTFIDF);
oBufferedReader.close();
oBufferedWriter.close();
} | 8 |
private JTreeNode<T> getCurrentNode(JTreeNode<T> root, T insertValue) {
if (root.getLeftNode() == null && root.getRightNode() == null)
return root;
if (root.getValue().compareTo(insertValue) > 0
&& root.getLeftNode() != null)
return getCurrentNode(root.getLeftNode(), insertValue);
if ((root.getValue().compareTo(insertValue) < 0)
&& (root.getRightNode() != null))
return getCurrentNode(root.getRightNode(), insertValue);
return root;
} | 6 |
@Override
public void display() {
System.out.print("Forecast: ");
if (currentPressure > lastPressure) {
System.out.println("Improving weather on the way!");
} else if (currentPressure == lastPressure) {
System.out.println("More of the same");
} else if (currentPressure < lastPressure) {
System.out.println("Watch out for cooler, rainy weather");
}
} | 3 |
public static int getDeltaY(int dir)
{
if(dir == UP || dir == UP_LEFT || dir == UP_RIGHT)
return -1;
if(dir == DOWN || dir == DOWN_LEFT || dir == DOWN_RIGHT)
return 1;
return 0;
} | 6 |
@SuppressWarnings("serial")
private void initGUI()
{
try {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(1003, 532);
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
{
jMenuBar1 = new JMenuBar();
setJMenuBar(jMenuBar1);
{
menuFile = new JMenu();
jMenuBar1.add(menuFile);
menuFile.setText("Datei");
{
menuItemOpen = new JMenuItem();
menuFile.add(menuItemOpen);
menuItemOpen.setText("Oeffnen");
menuItemOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemOpenActionPerformed(evt);
}
});
}
{
menuItemSave = new JMenuItem();
menuFile.add(menuItemSave);
menuItemSave.setText("Speichern");
menuItemSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemSaveActionPerformed(evt);
}
});
}
{
menuItemSaveAs = new JMenuItem();
menuFile.add(menuItemSaveAs);
menuItemSaveAs.setText("Speichern unter...");
menuItemSaveAs.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemSaveAsActionPerformed(evt);
}
});
}
{
menuExport = new JMenu();
menuFile.add(menuExport);
menuExport.setText("Exportieren...");
{
menuItemExportCurrent = new JMenuItem();
menuExport.add(menuItemExportCurrent);
menuItemExportCurrent.setText("Aktuellen Schaltplan");
menuItemExportCurrent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
menuItemExportCurrentActionPerformed(evt);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
{
menuItemExportBoth = new JMenuItem();
menuExport.add(menuItemExportBoth);
menuItemExportBoth.setText("Alle Schaltplaene");
menuItemExportBoth.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
menuItemExportBothActionPerformed(evt);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
{
menuTools = new JMenu();
jMenuBar1.add(menuTools);
menuTools.setText("Tools");
{
menuItemExtendWorkBench = new JMenuItem();
menuTools.add(menuItemExtendWorkBench);
menuItemExtendWorkBench.setText("Arbeitsflaeche vergroeßern");
menuItemExtendWorkBench.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemExtendWorkBenchActionPerformed(evt);
}
});
}
{
menuItemReduceWorkBench = new JMenuItem();
menuTools.add(menuItemReduceWorkBench);
menuItemReduceWorkBench.setText("Arbeitsflaeche verkleiner");
menuItemReduceWorkBench.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemReduceWorkBenchActionPerformed(evt);
}
});
}
}
{
menuEditor = new JMenu();
jMenuBar1.add(menuEditor);
menuEditor.setText("Editor");
{
menuItemNewSymbol = new JMenuItem();
menuEditor.add(menuItemNewSymbol);
menuItemNewSymbol.setText("Neues Schaltzeichen");
menuItemNewSymbol.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemNewSymbolActionPerformed(evt);
}
});
}
}
{
menuExtras = new JMenu();
jMenuBar1.add(menuExtras);
menuExtras.setText("Extras");
{
menuItemPreferences = new JMenuItem();
menuExtras.add(menuItemPreferences);
menuItemPreferences.setText("Benutzervorgaben");
menuItemPreferences.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
menuItemPreferencesActionPerformed(evt);
}
});
}
}
}
{
jSplitPane1 = new JSplitPane();
getContentPane().add(jSplitPane1, BorderLayout.CENTER);
//Left side of the SplitPane
{
BorderLayout jPanel1Layout = new BorderLayout();
jPanel1.setLayout(jPanel1Layout);
jPanel1.add(jScrollPane1);
jScrollPane1.setViewportView(jList1);
jSplitPane1.add(jPanel1, JSplitPane.LEFT);
jPanel1.setMinimumSize(new Dimension(300, 50));
jSplitPane1.setDividerLocation(300);
jSplitPane1.setEnabled(false);
}
//Right side of the SplitPane
{
jScrollPane2.setViewportView(drawComponent1);
jScrollPane2.getViewport().setBackground(Color.white);
jScrollPane3.setViewportView(drawComponent2);
jScrollPane3.getViewport().setBackground(Color.white);
jTabbedPane2.addTab("Wirkschaltplan", jScrollPane2);
jTabbedPane2.addTab("Stromlaufplan", jScrollPane3);
jSplitPane1.add(jTabbedPane2, JSplitPane.RIGHT);
//MOUSELISTENER
//create mouselisteners
MouseMotionAdapter mma = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent evt) {
svgCanvasMouseDragged(evt);
}
};
MouseAdapter ma = new MouseAdapter() {
public void mouseReleased(MouseEvent evt) {
svgCanvasMouseReleased(evt);
}
public void mousePressed(MouseEvent evt) {
svgCanvasMousePressed(evt);
}
};
//add mouselisteners to components
drawComponent1.addMouseMotionListener(mma);
drawComponent2.addMouseMotionListener(mma);
drawComponent1.addMouseListener(ma);
drawComponent2.addMouseListener(ma);
//KEYBINDINGS
//create keybindings
AbstractAction delete = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
svgCanvasKeyDELETEPressed();
}
};
AbstractAction plus = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
svgCanvasKeyPLUSPressed();
}
};
AbstractAction minus = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
svgCanvasKeyMINUSPressed();
}
};
//add keybindings
//Del
drawComponent1.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "deleteAction");
drawComponent1.getActionMap().put("deleteAction", delete);
//+
drawComponent1.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "plusAction");
drawComponent1.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0), "plusAction");
drawComponent1.getActionMap().put("plusAction", plus);
//-
drawComponent1.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0), "minusAction");
drawComponent1.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, 0), "minusAction");
drawComponent1.getActionMap().put("minusAction", minus);
//Del
drawComponent2.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "deleteAction");
drawComponent2.getActionMap().put("deleteAction", delete);
//+
drawComponent2.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "plusAction");
drawComponent2.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, 0), "plusAction");
drawComponent2.getActionMap().put("plusAction", plus);
//-
drawComponent2.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0), "minusAction");
drawComponent2.getInputMap(JSVGComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, 0), "minusAction");
drawComponent2.getActionMap().put("minusAction", minus);
}
}
//FileChooser Filters
{
jfc.setAcceptAllFileFilterUsed(false);
jfc.addChoosableFileFilter(new FileFilter()
{
public boolean accept( File f )
{
return f.isDirectory() || f.getName().toLowerCase().endsWith(".svg");
}
public String getDescription()
{
return "SVG-Dateien";
}
});
jfc.addChoosableFileFilter(new FileFilter()
{
public boolean accept( File f )
{
return f.isDirectory() || f.getName().toLowerCase().endsWith(".jpg");
}
public String getDescription()
{
return "JPG-Dateien";
}
});
}
pack();
} catch (Exception e) {
e.printStackTrace();
}
} | 5 |
public void initializeAnnotationComponents(ArrayList<Annotation> annotations){
if (this.annotations == null && annotations != null){
this.annotations = new ArrayList<AnnotationComponent>(annotations.size());
AnnotationComponentImpl comp;
for (Annotation annotation : annotations) {
if (!(annotation.getFlagInvisible() ||
annotation.getFlagHidden())) {
comp = new AnnotationComponentImpl(annotation,
documentViewController,
pageViewComponent, documentViewModel);
// add them to the container, using absolute positioning.
pageViewComponent.add(comp);
// add the comp reference locally so we have easier access
this.annotations.add(comp);
}
}
}
} | 5 |
@Override
public List<? extends DefaultModel> getObj(final String campo) {
return null;
} | 1 |
public void useThreadSleep() {
System.out.println("-------------Use Thread.sleep()------------");
System.out.println("Sleep for 5 seconds.");
try {
Thread.sleep(5000);
System.out.println("woke up.");
} catch (InterruptedException e) {
e.printStackTrace();
}
} | 1 |
@Override
public void run() {
CountDownLatch latch = new CountDownLatch(1);
while(autoLog) {
try {
latch.await(logInterval, TimeUnit.SECONDS);
saveLogs();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} | 2 |
public Document createDocument(final List<Student> students) {
Document doc = null;
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
final Element root = doc.createElement(Model.FIELD_STUDENTS);
for (final Student student : students) {
final Element studentElement = doc.createElement(Model.FIELD_STUDENT);
root.appendChild(studentElement);
newElement(doc, Model.FIELD_NAME, studentElement, student.getName());
newElement(doc, Model.FIELD_GROUP, studentElement, student.getGroup()
.toString());
final List<Exam> exams = student.getExams();
final Element examsElement = doc.createElement(Model.FIELD_EXAMS);
studentElement.appendChild(examsElement);
for (final Exam exam : exams) {
if (!exam.isEmpty()) {
final Element examElement = doc.createElement(Model.FIELD_EXAM);
examsElement.appendChild(examElement);
newElement(doc, Model.FIELD_NAME, examElement,
exam.getName() != null ? exam.getName() : " ");
newElement(doc, Model.FIELD_MARK, examElement,
exam.getMark() != null ? exam.getMark().toString() : " ");
}
}
}
doc.appendChild(root);
} catch (final Exception e) {
XMLWriter.LOG.log(Level.SEVERE,
Model.PROBLEM_PARSING_THE_FILE + e.getMessage(), e);
}
return doc;
} | 6 |
private void saveAdditionalSeats(JButton[] button, int flightID, int numberOfSeats, int methodChecker, int customerID) {
int seats = 0;
String nameOfSeats = new String();
for(int i = 0; i<button.length; i++) {
//Checks if the button is clicked and also if it wasnt booked to this order already.
if(button[i].getBackground() == Color.BLUE && button[i].isEnabled() == true) {
nameOfSeats = nameOfSeats+((button[i]).getText() + " ");
seats++;
}
}
//If you havent chosen any seats, you're asked to go back, otherwise it will end the process.
if(seats == 0) {
JOptionPane errorDialog = new JOptionPane();
int errorResult = errorDialog.showConfirmDialog(gui.returnFrame(),"You did not choose any seats,"
+ " do you wish to go back and select seats again?",
"No seats selected", errorDialog.OK_CANCEL_OPTION);
if(errorResult == errorDialog.YES_OPTION) {
flightseat.chooseSeats(flightID, numberOfSeats, flight, methodChecker, customerID);
}
}
//If you have chosen seats, you will be shown how many and which, whereafter it will continue to adding addtional travellers.
else if(seats > 0) {
JOptionPane succesDialog = new JOptionPane();
int succesResult = succesDialog.showConfirmDialog(gui.returnFrame(),"You have chosen: " + seats + " seat(s). Name of chosen seat(s): "+ nameOfSeats,
"Confirm your choice", succesDialog.OK_CANCEL_OPTION);
if(succesResult == succesDialog.YES_OPTION) {
addAdditionalTravellers(seats, nameOfSeats, customerID);
}
//If you're not happy with your choice or try to close the window, you're sent back to choosing seats.
else {
flightseat.chooseSeats(flightID, numberOfSeats, flight, methodChecker, customerID);
}
}
} | 7 |
private static Patient getPatient(Patient bean, PreparedStatement stmt, ResultSet rs, int numOfObject) throws SQLException{
if(bean.getPid()!=0)
stmt.setInt(1, bean.getPid());
else if(bean.getPhone()!=null){
stmt.setString(1, bean.getFirstName());
stmt.setString(2, bean.getLastName());
stmt.setString(3, bean.getPhone());
}
else{
stmt.setString(1, bean.getFirstName());
stmt.setString(2, bean.getLastName());
}
rs = stmt.executeQuery();
if (rs.next()) {
Patient newBean = new Patient();
newBean.setPid(rs.getInt("pid"));
newBean.setFirstName(rs.getString("firstname"));
newBean.setLastName(rs.getString("lastname"));
newBean.setDob(rs.getDate("dob"));
newBean.setPrimaryDoc(rs.getString("primarydoc"));
newBean.setPhone(rs.getString("phone"));
newBean.setAddress(rs.getString("address"));
newBean.setCity(rs.getString("city"));
newBean.setState(rs.getString("state"));
newBean.setZip(rs.getString("zip"));
numOfObject++;
return newBean;
} else {
System.out.println("unable to retrieve patient info");
return null;
}
} | 3 |
public static boolean isPrime(long x){
long max = (long)Math.sqrt(x);
if( x == 2){
return true;
}
if (x % 2 == 0) {
return false;
}
if (x <= 1) {
return false;
}
for( long i = 3L; i <= max; i+=2 ) {
if( x % i ==0) {
return false;
}
}
return true;
} | 5 |
void delete(){
thread=null;
try{
if(ss!=null)ss.close();
ss=null;
}
catch(Exception e){
}
} | 2 |
public int getTag(int i) throws ClassFormatException {
if (i == 0)
throw new ClassFormatException("null tag");
return tags[i];
} | 1 |
public void deleteUnselected() {
for (Integer opp : list.keySet()) {
if (!list.get(opp).selected()) {
list.remove(opp);
}
}
} | 2 |
@EventHandler
public void WolfNausea(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getWolfConfig().getDouble("Wolf.Nausea.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getWolfConfig().getBoolean("Wolf.Nausea.Enabled", true) && damager instanceof Wolf && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getWolfConfig().getInt("Wolf.Nausea.Time"), plugin.getWolfConfig().getInt("Wolf.Nausea.Power")));
}
} | 6 |
public void bufferSave(GraphNode child){
int i=0;
while(!buffer.get(i).equals(child)){
i++;
}
int k=0;
int[] temp = new int[buffer.size() - i];
while(i<buffer.size()){
temp[k] = buffer.get(i).getNodeIndex();
k++;
i++;
}
cycles.add(temp);
} | 2 |
private int getMin(int a, int b) {
return b < a? b: a;
} | 1 |
public String toString() {
try {
return this.toJSON().toString(4);
} catch (JSONException e) {
return "Error";
}
} | 1 |
private String getPath(String text, int id) {
if (text.equals(IN) || text.equals(OUT))
if (id == 0)
return LOW_PATH;
else
return HIGH_PATH;
for (int i = 0; i < COMPONENTS.getLength(); i++) {
if (COMPONENTS.get(i).equals(text))
if (id == 0)
return COMPONENTS_PATH.get(i);
else
return COMPONENTS2_PATH.get(i);
}
return "";
} | 6 |
private void readBlocks(RandomAccessFile data) throws IOException {
boolean readNext = true;
while (readNext) {
int mapX = data.readUnsignedShort();
int mapY = data.readUnsignedShort();
short musicIndex = data.readShort();
short ambienceIndex = data.readShort();
short mapIconIndex = data.readShort();
short doorBytes = data.readShort();
byte scrollByte = data.readByte();
// read map color
int mapColorRed = data.readUnsignedByte();
int mapColorGreen = data.readUnsignedByte();
int mapColorBlue = data.readUnsignedByte();
Color mapColor = new Color(mapColorRed, mapColorGreen, mapColorBlue, MAP_COLOR_ALPHA);
short mapMarkingBytes = data.readShort();
Block newBlock = new Block(this.blockSizeX, this.blockSizeY, musicIndex,
ambienceIndex, mapIconIndex, doorBytes, scrollByte, mapColor,
mapMarkingBytes);
this.addBlock(newBlock, mapX, mapY);
boolean readLayers = true;
while (readLayers) {
// read layer data
byte layerID = data.readByte();
switch (LayerID.getLayerID(layerID & 0xFF)) {
case TILE_COLLISION:
data.readByte(); // advance past fake index FF present for alignment
newBlock.setCollisionLayer(new CollisionLayer(newBlock, data, this));
break;
case COLOR_DECORATION:
newBlock.addLayer(new ColorLayer(newBlock, data));
break;
case TILE_DECORATION:
case IMAGE_DECORATION:
case ENTITY_DATA:
ZettaUtil.error("Layer type %s not implemented yet",
LayerID.getLayerID(layerID).name());
break;
case END_OF_FILE:
data.readByte();
return;
case END_BLOCK:
readLayers = false;
data.readByte(); // advance
break;
default: ZettaUtil.error("Unknown layer ID %d", layerID); break;
}
}
}
} | 9 |
public void append_blank()
{
if(isReadOnly()) return;
addreccount();
try { fdbf.seek( recordpos() ); } catch (IOException e) {}
writeChars(0,1," "); // not deleted
for(int i=0;i<fcount;i++)
{
field y = Field[i];
if(y.ftype=='0') writeNumber(0,y.fsize, 0 ); //write binary 0
if(y.ftype=='I') writeNumber(0,4, 0 ); //write binary 0
if(("BTY").indexOf(y.ftype)>=0) writeNumber(0,8, 0 ); //write binary 0
if(y.ftype=='M' || y.ftype=='G')
{
if(DOS_FOX) writeChars(0,10,"");
else writeNumber(0,4, 0 ); //write binary, not string value
}
else writeChars(0,y.fsize, ""); //string of char
}
getfieldsValues();
} | 9 |
public synchronized void processOutput(ByteBuffer buffer) throws SSLException {
if (buffer.hasRemaining()) {
do {
SSLEngineResult result = mEngine.wrap(buffer, mOutboundData);
switch (result.getHandshakeStatus()) {
case NEED_TASK:
runSSLTasks();
break;
case NEED_UNWRAP:
// Should not be possible
throw new SSLException("Need unwrap during output");
case NEED_WRAP:
// Should not be possible
throw new SSLException("Need wrap during output");
default:
break;
}
switch (result.getStatus()) {
case BUFFER_OVERFLOW:
sendOutboundData();
break;
case BUFFER_UNDERFLOW:
// Should not be possible
throw new SSLException("Buffer underflow during output");
case CLOSED:
mOutboundData.clear();
return;
default:
break;
}
} while (buffer.hasRemaining());
sendOutboundData();
}
} | 8 |
private Item get(final Item key) {
Item i = items[key.hashCode % items.length];
while (i != null && (i.type != key.type || !key.isEqualTo(i))) {
i = i.next;
}
return i;
} | 3 |
public static void openStaticSWTDemo(IDemo demo) throws Exception{
Settings.getInstance().setHardwareAccelerated(true);
Chart chart = demo.getChart();
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Bridge.adapt(shell, (Component) chart.getCanvas());
shell.setText(demo.getName());
shell.setSize(800, 600);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
} | 2 |
public static void main(String[] args) {
try {
AppGameContainer app = new AppGameContainer(new Application("The Saga of the Owl King v" + VERSION));
app.setDisplayMode(WIDTH, HEIGHT, false);
app.setTargetFrameRate(FPS);
app.setShowFPS(true);
app.start();
} catch(SlickException e) {
e.printStackTrace();
}
} | 1 |
public TuringMachine getInnerTM(){
return myInnerTuringMachine;
} | 0 |
public static void test(PersistedQueueManager queueManager) throws Exception {
processed.set(0);
// create an ArmyAudit that just show to standard output
ArmyAudit armyAudit = new SystemOutAudit();
//ArmyAudit armyAudit = new NegligentAuditor();
// create an Army to make machine guns
final Army army = new Army(armyAudit, queueManager);
// here is the dirty task producer
// ProcessIntegerSlowly simulates a "dirty work" and just sleep randomly
Factory<DirtyWork<Integer>> dirtyWorkFactory = new Factory<DirtyWork<Integer>>() {
@Override
public DirtyWork<Integer> buildANewInstance() throws BuildingException {
return new DirtyWork<Integer>() {
@Override
public void workOnIt(long jobId, String consumerName, ArmyAudit audit, Integer dataToBeProcessed) {
Integer time = random.nextInt(2);
System.out.println("*** Will process " + dataToBeProcessed
+ " for " + time + " millis...");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
decrease(dataToBeProcessed);
audit.aConsumerHasBeenFinishedHisJob(jobId, consumerName, true, null, "OK!");
}
};
}
};
// This capsule uses the Java default serialization implementation
Capsule<Integer> capsule = new GenericCapsuleForLazyPeople<Integer>();
// start the mission called "default mission" working on "default queue"
army.startANewMission("default mission", "default queue",
dirtyWorkFactory, capsule, 100000, 4, 12);
Thread[] threads = new Thread[THREADS];
// get a machine gun to strafe
final MachineGun<Integer> machineGun
= army.getANewMachineGun("default mission");
for (int i = 0; i < threads.length; i++) {
final int y = i;
threads[i] = new Thread("Producer " + i + " of " + threads.length) {
public void run() {
for (int j = 0; j < TESTS; j++) {
if (j % 100000 == 0) {
System.out.print("" + y);
}
try {
final int n = sequential.incrementAndGet();
System.out.println(Thread
.currentThread().getName()
+ " will produce " + n);
increase(n);
// strafe
machineGun.fire(n);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
};
// start the producer
threads[i].start();
}
// wait the producers die
for (Thread thread : threads) {
thread.join();
}
// wait the queue is empty
while (!queueManager.isEmpty("default queue")) {
System.out.print("?");
Thread.sleep(1000);
}
// make all consumers die
army.stopTheMission("default mission");
// everything was well processed?
if (processed.get() != 0) {
System.err.println("ERROR size != 0: " + processed);
}
assert processed.get() == 0;
} | 8 |
public void deleteAllItemToArticle(List<Integer> idAllItemsInArticle) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction().begin();
for(Integer id:idAllItemsInArticle){
Article itemDelete = (Article) session.get(Article.class, id);
session.delete(itemDelete);
}
session.getTransaction().commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
} | 3 |
private void setPath(Point start) {
int counter = 0;
path.add(start);
Point goal = mainPath.get(counter);
counter++;
int currentXPos = start.getX();
int currentYPos = start.getY();
while(true) {
while (goal.getX() != currentXPos || goal.getY() != currentYPos) {
int deltaX = goal.getX() - currentXPos;
int deltaY = goal.getY()-currentYPos;
if (deltaX != 0) {
int changeInX = deltaX/abs(deltaX); // +/- 1
currentXPos += changeInX; // update current XPos
} else if (deltaY != 0) {
int changeInY = deltaY/abs(deltaY); // +/- 1
currentYPos += changeInY; // update current YPos
}
Point pathPoint = new Point(currentXPos, currentYPos);
path.add(pathPoint);
}
assert (goal.isEmpty());
if (counter >= mainPath.size()) break;
goal = mainPath.get(counter);
counter++;
}
} | 6 |
static int [] shift(int arr[]){
int lastElement=arr[(arr.length-1)];
for (int count=(arr.length-1);count>0;count--){
arr[count]=arr[count-1];
}
if(arr.length>=1)
arr[0]=lastElement;
return arr;
} | 2 |
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == browseButton) {
if (browseFile() && recording)
startRecording();
} else if (evt.getSource() == recordButton) {
if (!recording) {
startRecording();
} else {
stopRecording();
fnameField.setText(nextNewFilename(fnameField.getText()));
}
} else if (evt.getSource() == nextButton) {
fnameField.setText(nextNewFilename(fnameField.getText()));
if (recording)
startRecording();
} else if (evt.getSource() == closeButton) {
setVisible(false);
}
} | 8 |
public boolean hasAttribute(String name) {
for (int i = 0; i < attributes.length; i++)
if (name.equals(attributes[i].name))
return true;
return false;
} | 2 |
public static void main(String[] args)
{
jlap test = new jlap();
if (args.length != 1)
{
test.showUsage();
System.exit(0);
}
else
{
try
{
test.play(args[0]);
}
catch (Exception ex)
{
System.err.println(ex.getMessage());
System.exit(0);
}
}
} | 2 |
public NonRuleBasedDamagerRepairer(TextAttribute defaultTextAttribute) {
fDefaultTextAttribute = defaultTextAttribute;
} | 0 |
@Override
public boolean registerUser(String username, String password, String email,
String firstName, String lastName) {
// Declare a local boolean to be returned by this method, where false
// means that registration has been unsuccessful
// (i.e. given username already exists) and true that an user has been
// registered
boolean registered = false;
// Find an user record in the entity bean User, passing a primary key of
// username.
User user = emgr.find(entity.User.class, username);
// Determine whether the user exists
if (user == null) { // If the user doesn't exists
// Register the new user
User newUser = new User();
newUser.setUserName(username);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
emgr.persist(newUser);
// Obtain the email creditentials to the admin email from the database
EmailCredential emailCred = emgr.find(EmailCredential.class, "qif");
Runnable r = new EmailSender(emailCred.getEmailLogin(), emailCred.getEmailPassword(), "MiniEbay - Hello !", "You have been successfully registered with us, " + username + ". \n We send u a warm welcome and hope u have a great time with us!",
emailCred.getEmailLogin(), email);
new Thread(r).start();
registered = true;
} // End of registerUser method
return registered;
} | 1 |
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Date date = (Date) o;
return day == date.day && inaccurateTime.equals(date.inaccurateTime);
} | 4 |
@Override
public void run() {
ArrayList<Navire> naviresArrives;
int compteur = 0;
int sleep = 200;
while(Partie._tempsCourant <= Partie._tempsFin) {
if(compteur%Partie._tempsTour == 0) {
incrementerTemps(compteur);
naviresArrives = _instance.getNavires(Partie._tempsCourant);
majNaviresArrives(naviresArrives);
afficherArrivesDansLog(naviresArrives);
majNaviresArrivant(naviresArrives);
majNbRetards();
actualiserPanels();
}
compteur += pausethread(sleep);
if(Partie._abandon) {
break;
}
}
if(!Partie._abandon) {
GestionScores gScores = new GestionScores();
Score score = gScores.sauvegarderScore();
new FenetreScores(score);
}
} | 4 |
public static boolean HasPermission(Player p, String permission)
{
if(p == null) return true;
if(p.hasPermission(permission)) return true;
if(PermissionsEx.getPermissionManager().has(p, permission)) return true;
return false;
} | 3 |
private void buildTree(FAT32Directory rootElement) {
DefaultMutableTreeNode top = createNodes(rootElement);
jTree = new JTree(top);
ImageIcon leafIcon = new ImageIcon(this.getClass().getResource(leafIconPath));
ImageIcon openIcon = new ImageIcon(this.getClass().getResource(openIconPath));
ImageIcon closeIcon = new ImageIcon(this.getClass().getResource(closeIconPath));
if (leafIcon != null && openIcon != null && closeIcon != null) {
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
renderer.setLeafIcon(leafIcon);
renderer.setOpenIcon(openIcon);
renderer.setClosedIcon(closeIcon);
jTree.setCellRenderer(renderer);
}
jTree.getSelectionModel().addTreeSelectionListener(new Selector());
jScrollPane1.setViewportView(jTree);
} | 3 |
public void setSaleId(int saleId) {
this.saleId = saleId;
} | 0 |
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case WHAT:
if (value == null) {
unsetWhat();
} else {
setWhat((Integer)value);
}
break;
case WHY:
if (value == null) {
unsetWhy();
} else {
setWhy((String)value);
}
break;
}
} | 4 |
public static Geometry newObj(String data) {
n_v = n_f = 0;
StringTokenizer st = new StringTokenizer(data, "\n");
while (st.hasMoreTokens()) {
String s = st.nextToken();
if (s.length() > 1)
if (s.charAt(0) == 'v' && s.charAt(1) == ' ')
n_v++;
else if (s.charAt(0) == 'f' && s.charAt(1) == ' ')
n_f++;
}
v = new double[n_v][6];
f = new int[n_f][];
i_v = i_f = 0;
st = new StringTokenizer(data, "\n");
int line = 0;
while (st.hasMoreTokens())
parseLine(st.nextToken());
Geometry g = new Geometry();
g.vertices = v;
g.faces = f;
g.computePolyhedronNormals();
for (int n = 0 ; n < n_v ; n++)
for (int j = 0 ; j < 3 ; j++)
g.vertices[n][3+j] *= -1;
return g;
} | 9 |
public static void encounter(ArrayList<Person> Group1,ArrayList<Person> Group2 )
{
///////////////////This is for zombie vs person//////////////////////
if(isZombieGroup(Group1) && !isZombieGroup(Group2))
{
zombieVsPerson(Group1,Group2);
}
///////////////////This is for person vs person//////////////////////
else if(!isZombieGroup(Group1) && !isZombieGroup(Group2))
{
}
///////////////////This is for zombie vs zombie//////////////////////
else if(isZombieGroup(Group1) && isZombieGroup(Group2))
{
}
///////////////////This is for person vs zombie//////////////////////
else if(!isZombieGroup(Group1) && isZombieGroup(Group2))
{
zombieVsPerson(Group2,Group1);
}
else{
zombieVsPerson(Group2,Group1);
}
} | 8 |
public static void main(String[] args) {
// TODO code application logic here
MySQLCli mysqlCli = new MySQLCli("//localhost/smsapp", "root", "");
if (mysqlCli.connect())
{
System.out.println("Connected to database smsapp");
Refresh R=new Refresh(mysqlCli);
try {
int NumberAdd=R.CheckAdd();
if(NumberAdd!=0)
{
R.treatment();
}
} catch (SQLException ex) { Logger.getLogger(Repertoire_telephonique.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 3 |
public FileInputAsChar(String pathName){
this.pathName = pathName;
int posSlash = pathName.indexOf("//");
int posBackSlash = pathName.indexOf("\\");
if(posSlash!=-1 || posBackSlash!=-1){
File file = new File(this.pathName);
this.fileName = file.getName();
this.dirPath = (file.getParentFile()).toString();
}
int posDot = this.fileName.indexOf('.');
if(posDot==-1){
this.stemName = this.fileName;
}
else{
this.stemName = this.fileName.substring(0, posDot);
}
try{
this.input = new BufferedReader(new FileReader(this.pathName));
}catch(java.io.FileNotFoundException e){
System.out.println(e);
fileFound=false;
}
} | 4 |
public void setConstant (double constant) {
this.constant = constant;
} | 0 |
@Override
public void addPosition(Position position) throws SQLException {
Connection dbConnection = null;
java.sql.Statement statement = null;
try {
dbConnection = PSQL.getConnection();
statement = dbConnection.createStatement();
String addPosition = "insert into position(id_position, name, sallary) values ('"
+ position.getId()
+ "' , '"
+ position.getName()
+ "' , '"
+ position.getSallary() + "')";
statement.executeUpdate(addPosition);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.