text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void setName(String name) {
this.name = name;
setDirty();
} | 0 |
public static void main(String[] args) throws IOException {
Library stopWordDictionary = new StopWordLibrary(new Settings().getStopWordLibrary());
File directory = new File("dataSource/samples/Teste/comp.os.ms-windows.misc");
String[] arquivos = directory.list();
if (arquivos != null) {
for (int i = 0; i < arquivos.length; i++) {
String filePath = directory.getAbsolutePath() + "/"
+ arquivos[i];
InputStream inputStream = new FileInputStream(filePath);
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (isValidLine(line)) {
StringTokenizer stringTokenizer = new StringTokenizer(line);
while (stringTokenizer.hasMoreTokens()){
String nextToken = stringTokenizer.nextToken();
nextToken = nextToken.replace(",", "");
nextToken = nextToken.replace(".", "");
//nextToken = nextToken.replace("/", "");
nextToken = nextToken.replace("-", "");
nextToken = nextToken.replace("_", "");
nextToken = nextToken.replace("^", "");
nextToken = nextToken.replace("=", "");
nextToken = nextToken.replace(":", "");
nextToken = nextToken.replace("+", "");
nextToken = nextToken.replace("{", "");
nextToken = nextToken.replace("}", "");
nextToken = nextToken.replace("[", "");
nextToken = nextToken.replace("]", "");
nextToken = nextToken.replace("~", "");
nextToken = nextToken.replace("(", "");
nextToken = nextToken.replace(")", "");
nextToken = nextToken.replace("|", "");
nextToken = nextToken.replace("?", "");
nextToken = nextToken.replace("!", "");
nextToken = nextToken.toUpperCase().trim();
if (!nextToken.equals("") && (nextToken.length() > 1)){
if (!stopWordDictionary.contains(nextToken)){
try{
Integer.parseInt(nextToken);
}catch(NumberFormatException e){
System.out.println(nextToken);
}
}
}
}
//System.out.println(line);
}
}
}
System.out.println("\n\n\n####################\n\n\n");
}
} | 9 |
private void drawLine(Graphics g, int x, int y, int xMax, int xLen, FontMetrics fm, int alignment) {
if (y > getHeight() - 3)
return;
StringBuffer s = new StringBuffer();
String str1;
int xx = x;
while (true) {
int m = random.nextInt(10) + 1;
str1 = dummy.substring(0, m) + " ";
int len = fm.stringWidth(str1);
if (xx + len >= xLen)
break;
xx += len;
s.append(str1);
}
String str = s.toString();
switch (alignment) {
case StyleConstants.ALIGN_LEFT:
g.drawString(str, x, y);
break;
case StyleConstants.ALIGN_CENTER:
xx = (xMax + x - fm.stringWidth(str)) / 2;
g.drawString(str, xx, y);
break;
case StyleConstants.ALIGN_RIGHT:
xx = xMax - fm.stringWidth(str);
g.drawString(str, xx, y);
break;
case StyleConstants.ALIGN_JUSTIFIED:
while (x + fm.stringWidth(str) < xMax)
str += "a";
g.drawString(str, x, y);
break;
}
} | 8 |
public Data serverMsg() {
Object obj;
try {
try {
obj = input.readObject();
} catch (ClassNotFoundException ex) {
setDef("No connection to the server! Don't run Server.java" + ex.getMessage(), 1);
return null;
}
} catch (IOException ex) {
setDef("No connection to the server! " + ex.getMessage(), 1);
return null;
}
if (((Data) obj).getKey().getItem().equals("@@@notserverdb@@@")) {
try {
socket.close();
} catch (IOException ex) {
setDef("No connection to the server! " + ex.getMessage(), 1);
}
}
System.out.println("Term = " + ((Data) obj).getKey().getItem());
return (Data) obj;
} | 4 |
protected void setupTempInventory(Clan doer) {
for (int i = 0; i < tmpInventory.length; i++) {tmpInventory[i] = 0;}
QStack qs = doer.MB.QuestStack;
if (qs.isEmpty()) {return;}
Quest q = qs.peek();
if (!(q instanceof LaborQuest)) {return;}
LaborQuest lq = (LaborQuest) q;
int[] wm = lq.getWM(); int[]wmx = lq.getWMX();
for (int i = 1; i < wm.length; i++) {
int g = Math.abs(wm[i]);
if(g == E) {return;}
tmpInventory[g] = wmx[i];
}
} | 5 |
public static MovieData parseMovieFileName(File fileEntry) throws Exception {
String fileName = fileEntry.getName();
System.out.println(fileName);
MovieData data = null;
if (data == null) {
// Rule1: Braveheart.1995.1080p.BrRip.x264.YIFY+HI
// ^^^^^^^^^^ ^^^^ ^^^^^ ^^^^^^^^^^^^^^^^^^
// Name Year Res Publisher
Pattern p = Pattern.compile("(.*)[ .]\\(?(\\d{4})\\)?.*[ .](\\d{3,4}p)[ .]?(.*)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(fileName);
if (m.matches()) {
data = new MovieData();
data.file = fileEntry;
data.fileMovieName = m.group(1);
data.fileMovieYear = m.group(2);
data.fileResolution = m.group(3);
data.filePublisher = m.group(4);
System.out.println("Match Rule 1: " + data.getRawDataString());
}
}
if (data == null) {
// Rule2: Der Untergang (Downfall) (2004) [1080p] x264 - Jalucian
// ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^^^^ ^^^^^^^^^^^^^^^^^^
// Name Year Res Publisher
Pattern p = Pattern.compile("(.*)[ .]\\(?(\\d{4})\\)?.*[ .]\\[(\\d{3,4}p)\\][ .]?(.*)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(fileName);
if (m.matches()) {
data = new MovieData();
data.file = fileEntry;
data.fileMovieName = m.group(1);
data.fileMovieYear = m.group(2);
data.fileResolution = m.group(3);
data.filePublisher = m.group(4);
System.out.println("Match Rule 2: " + data.getRawDataString());
}
}
if (data == null) {
// Rule3: Inglourious.Basterds.1080p.BluRay.x264.anoXmous_
// ^^^^^^^^^^^^^^^^^^^^ ^^^^^ ^^^^^^^^^^^^^^^^^^
// Name Res Publisher
Pattern p = Pattern.compile("(.*)[ .](\\d{3,4}p)[ .]?(.*)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(fileName);
if (m.matches()) {
data = new MovieData();
data.file = fileEntry;
data.fileMovieName = m.group(1);
data.fileResolution = m.group(2);
data.filePublisher = m.group(3);
System.out.println("Match Rule 3: " + data.getRawDataString());
}
}
if (data == null) {
// Rule4: Mononoke.hime.[Princess.Mononoke].1997.HDTVRip.H264.AAC.Gopo
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^
// Name Year Publisher
Pattern p = Pattern.compile("(.*)[ .]\\(?(\\d{4})\\)?[ .](.*)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(fileName);
if (m.matches()) {
data = new MovieData();
data.file = fileEntry;
data.fileMovieName = m.group(1);
data.fileMovieYear = m.group(2);
data.filePublisher = m.group(3);
System.out.println("Match Rule 4: " + data.getRawDataString());
}
}
return data;
} | 8 |
@Override
public void update() {
if (this.lastAlphaUpdate == 0) {
this.lastAlphaUpdate = Timer.getTime();
}
if (Timer.getTime() - this.lastAlphaUpdate >= 75) {
if (this.increaseAlpha) {
this.alpha += 0.04f;
if (this.alpha >= 1.0f) {
this.alpha = 1.0f;
this.increaseAlpha = false;
}
} else {
this.alpha -= 0.04f;
if (this.alpha <= 0.0f) {
this.alpha = 0.0f;
this.increaseAlpha = true;
}
}
this.lastAlphaUpdate = Timer.getTime();
}
//update Labels -> align them correct
int width = GameWindow.getInstance().getWidth();
int height = GameWindow.getInstance().getHeight();
this.firstTitleLabel.verticalAlignCenter(0, width);
this.secondTitleLabel.setY(this.firstTitleLabel.getY() + 10);
this.secondTitleLabel.verticalAlignCenter(0, width);
this.pressSpaceLabel.setY(height * 9 / 10 - this.pressSpaceLabel.getHeight() / 2);
this.pressSpaceLabel.verticalAlignCenter(0, width);
if (Keyboard.isPressed(KeyEvent.VK_SPACE)) {
Game.getInstance().loadScene(Scene.SCENE_MENU);
}
} | 6 |
FileType(String type) {
this.type = type;
} | 0 |
public static void main(String[] args) {
try {
workDir=new File(ModManager.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath().replace("McLauncher.jar", ""));
System.out.println("Running McLauncher from " + workDir);
} catch (URISyntaxException e1) {
workDir=new File("");
e1.printStackTrace();
}
// try {
// // Get a file channel for the file
// boolean FileNotLocked=false;
//
//
// try {
// FileWriter file2 = new FileWriter(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
// file2.write("McLauncher lock");
// file2.close();
// } catch (IOException e) {
// FileNotLocked=true;
// }
//
// File file = new File(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
//
// FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// if(file.renameTo(file)) FileNotLocked=true;
// if(FileNotLocked){
// JOptionPane.showMessageDialog(null, "Already running McLauncher, Only one instance allowed at a time\n"
// + "Is this wrong? Delete McLauncher.lock in your temp folder");
// System.out.println("Already running McLauncher, Only one instance allowed at a time");
// System.exit(0);
// }
// lock = channel.lock();
//
// try {
// lock = channel.tryLock();
// } catch (OverlappingFileLockException e) {
// }
// channel.close();
// } catch (Exception e) {
// }
//Not added because i do not want to lock people out from using McLauncher if somehow this fails.
// if(new File(System.getProperty("java.io.tmpdir") + "/McLauncher.lock").exists()){
// System.exit(0);//close this instance if McLauncher is already running.
// }
// try {
// FileWriter file = new FileWriter(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
// file.write("McLauncher one instance lock");
// file.close();
// } catch (IOException e) {
// System.out.println("Severe, failed to create temp lock file");
// }
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
con = new Console();
con.setVisible(false);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - con.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - con.getHeight()) / 2);
con.setLocation(x, y);
} catch (Exception e) {
e.printStackTrace();
}
}
});
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
ModManager frame = new ModManager();
frame.setResizable(false);
frame.setVisible(true);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} | 5 |
public boolean isInArea(Area checkArea) {
if (x <= checkArea.getLocation1().getX()
|| x >= checkArea.getLocation2().getX()
|| y <= checkArea.getLocation1().getY()
|| y >= checkArea.getLocation2().getY())
return false;
else
return true;
} | 4 |
@SuppressWarnings("static-access")
private void ROUND8() {
enemises.clear();
System.out.println("Round8!!!!!!");
for (int i = 0; i < level.getWidth(); i++) {
for (int j = 0; j < level.getHeight(); j++) {
if ((level.getPixel(i, j) & 0x0000FF) == 2) {
Transform monsterTransform = new Transform();
monsterTransform.setTranslation((i + 0.5f) * Game.getLevel().SPOT_WIDTH, 0.4375f, (j + 0.5f) * Game.getLevel().SPOT_LENGTH);
enemises.add(new Enemies(monsterTransform));
}
}
}
} | 3 |
private Widget creerCreateRoomPanel() {
setWidth("100%");
setHeight("100%");
addSallePan.isVisible();
addSallePan.setTitle("Ajouter une salle");
// Create a table to layout the form options
FlexTable layout = new FlexTable();
layout.setCellSpacing(6);
layout.setWidth("350px");
layout.setHeight("450px");
FlexCellFormatter cellFormatter = layout.getFlexCellFormatter();
// Add a title to the form
layout.setHTML(0, 0, "<br><i>Il ne vous suffira que de remplir ces infos pour vous créer une nouvelle salle <hr>");
cellFormatter.setColSpan(0, 0, 2);
cellFormatter.setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
final HTML error2HTML = new HTML("");
// Create TextBox
final TextBox nomSalle2Box = new TextBox();
final TextBox theme2Box = new TextBox();
final TextBox description2Box = new TextBox();
// Add a drop box with the list types
final ListBox nbPlaceBox = new ListBox(false);
for (int i = 2; i <= 23; i++) {
nbPlaceBox.addItem(""+i+" places");
}
// Add some standard form options
layout.setHTML(1, 0, "Nom:");
layout.setWidget(1, 1, nomSalle2Box);
layout.setHTML(2, 0, "Theme");
layout.setWidget(2, 1, theme2Box);
layout.setHTML(3, 0, "Description");
layout.setWidget(3, 1, description2Box);
layout.setHTML(4, 0, "Nombre de places");
layout.setWidget(4, 1, nbPlaceBox);
layout.setWidget(5, 1, new Button(
"Ajouter Salle", new ClickHandler() {
public void onClick(ClickEvent event) {
if (casesRemplies()){
int nbplace = Integer.parseInt(nbPlaceBox.getItemText(nbPlaceBox.getSelectedIndex()).substring(0,2).trim());
SalleService.Util.getInstance().creerSalle(nomSalle2Box.getText(), theme2Box.getText(),
description2Box.getText(),nbplace, new AsyncCallback<Boolean>(){
public void onFailure(Throwable caught) {
Window.alert("Erreur : "+ caught.getMessage());
}
public void onSuccess(Boolean result) {
if (result==null)
Window.alert("Erreur lors de l'ajout de la salle !");
else{
Window.alert("Votre salle à été créée");
}
}
});
}else error2HTML.setHTML("<font color=\"#FF00\"><em><small>Erreur : Vous n'avez " +
"pas rempli tous les champs !</small></em></font>");
}
private boolean casesRemplies() {
return (nomSalle2Box.getText().length()!=0 &&
theme2Box.getText().length()!=0 &&
description2Box.getText().length()!=0
);
}
}));
layout.setWidget(6, 0, error2HTML);
addSallePan.add(layout);
return addSallePan;
} | 5 |
private boolean checkForNakedQuads(LinkedList<NakedCandidates> pool, NakedCandidates comparator) {
LinkedList<String> candidates = new LinkedList<String>();
for (int index=0; index < pool.size(); index++) {
for (int i=0; i < pool.get(index).values.size(); i++) {
if (!passOver(candidates, pool.get(index).values.get(i))) {
candidates.add(pool.get(index).values.get(i));
}
}
}
for (int index=0; index < comparator.values.size(); index++) {
if (!passOver(candidates, comparator.values.get(index))) {
candidates.add(comparator.values.get(index));
}
}
return candidates.size() <= 4;
} | 5 |
@Override
public String getText() {
String res = "";
res = res + this.text + " ";
Iterator<Integer> it_operands = this.operands.iterator();
Iterator<Character> it_operators = this.operators.iterator();
Iterator<Integer> it_unknowns = this.unknowns.iterator();
res = res + it_operands.next();
while (it_operands.hasNext()) {
int u = it_unknowns.next();
if (u == 1) {
res = res + "x ";
} else if (u == 2) {
res = res + "x² ";
} else {
res = res + " ";
}
res = res + it_operators.next() + " ";
res = res + it_operands.next();
}
int u = it_unknowns.next();
if (u == 1) {
res = res + "x ";
} else if (u == 2) {
res = res + "x² ";
} else {
res = res + " ";
}
return res;
} | 5 |
@Override
public void addCandidate(Route route)
{
if (route.getNumberOfStops() == limit)
{
routes.add(route);
}
} | 1 |
public void testParseStandardFail2() {
PeriodFormatter parser = ISOPeriodFormat.standard();
try {
parser.parsePeriod("PS");
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((k == null) ? 0 : k.hashCode());
return result;
} | 1 |
private void drawGrid(){
//indicate the intervals between vertical lines
int vertDist = APPLICATION_WIDTH/NDECADES;
//window fit
int fit = 60;
//a buffer for everything
int buffer =5;
bottomLineY = APPLICATION_HEIGHT-GRAPH_MARGIN_SIZE-fit;
for(int i=0;i<NDECADES;i++){
decadeArray[i] = START_DECADE + i*10;
decadeXArray[i] = buffer + i*vertDist;
}
for(int i=0;i<NDECADES;i++){
GLine vertical = new GLine (decadeXArray[i],0,decadeXArray[i],APPLICATION_HEIGHT-fit);
add(vertical);
String decadeString = "" + decadeArray[i];
GLabel year = new GLabel(decadeString);
year.setFont("Helvetica-24");
add(year,i*vertDist+buffer*2,APPLICATION_HEIGHT-fit-buffer);
}
GLine top = new GLine(0,topLineY,APPLICATION_WIDTH,topLineY);
GLine bottom = new GLine(0, bottomLineY,APPLICATION_WIDTH,bottomLineY);
add(top);
add(bottom);
} | 2 |
protected boolean isElementoEnListas(String elemento) {
if (isElementoEnHechosInicio(elemento)) {
return true;
}
if (isElementoEnHechosInferidos(elemento)) {
return true;
}
if (isElementoEnHechosPreguntados(elemento)) {
return true;
}
return false;
} | 3 |
public void draw(Object obj, Component comp, Graphics2D g2)
{
Color color;
if (obj == null)
color = null;
else
color = (Color) getProperty(obj, "color");
String imageSuffix = (String) getProperty(obj, "imageSuffix");
if (imageSuffix == null)
imageSuffix = "";
// Compose image with color using an image filter.
Image tinted = tintedVersions.get(color + imageSuffix);
if (tinted == null) // not cached, need new filter for color
{
Image untinted = tintedVersions.get(imageSuffix);
if (untinted == null) // not cached, need to fetch
{
try
{
URL url = cl.getClassLoader().getResource(
imageFilename + imageSuffix + imageExtension);
if (url == null)
throw new FileNotFoundException(imageFilename
+ imageSuffix + imageExtension + " not found.");
untinted = ImageIO.read(url);
tintedVersions.put(imageSuffix, untinted);
}
catch (IOException ex)
{
untinted = tintedVersions.get("");
}
}
if (color == null)
tinted = untinted;
else
{
FilteredImageSource src = new FilteredImageSource(untinted
.getSource(), new TintFilter(color));
tinted = comp.createImage(src);
// Cache tinted image in map by color, we're likely to need it
// again.
tintedVersions.put(color + imageSuffix, tinted);
}
}
int width = tinted.getWidth(null);
int height = tinted.getHeight(null);
int size = Math.max(width, height);
// Scale to shrink or enlarge the image to fit the size 1x1 cell.
g2.scale(1.0 / size, 1.0 / size);
g2.clip(new Rectangle(-width / 2, -height / 2, width, height));
g2.drawImage(tinted, -width / 2, -height / 2, null);
} | 7 |
public void completeRows()
{
int count = 0;
for (int i = 0; i < NUM_ROWS; i++) // Loop through rows
{
for (int j = 1; j < NUM_COLUMNS - 1; j++) // Loop through columns
{
// Check each column in the row to see if it is occupied by an INACTIVE_BLOCK
if(gameBoard[i][j] == INACTIVE_BLOCK)
{
count++;
}
else
{
break;
}
}
// A row will be full if the count reaches 10
if (count == 10)
{
// Deletes row of INACTIVE_BLOCKS
for (int j = 1; j < NUM_COLUMNS - 1; j++) // Loop through columns
{
gameBoard[i][j] = EMPTY;
}
score++;
// Copies row above deleted row down one unit, repeats until top of gameBoard reached
for(int x = i; x > 1; x--)
{
for(int j = 1; j < NUM_COLUMNS - 1; j++)
{
gameBoard[x][j] = gameBoard[x-1][j];
}
}
// Deletes top row of any blocks
for(int j = 1; j < 11; j++)
{
gameBoard[0][j] = EMPTY;
}
}
// Resets count before moving to next row
count = 0;
}
} | 8 |
private void decodeParameters(String parameters) {
StringTokenizer tokenizer = new StringTokenizer(parameters, "&");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
int index = token.indexOf('=');
String name = decodePercent(index == -1 ? token : token.substring(0, index)).trim();
List<String> list = mParameters.get(name);
if (list == null) {
list = new ArrayList<>();
mParameters.put(name, list);
}
if (index != -1) {
if (++index < token.length()) {
list.add(decodePercent(token.substring(index)));
}
}
}
} | 5 |
public static void showFrame () {
/* 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(DescriptionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DescriptionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DescriptionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DescriptionWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new DescriptionWindow().setVisible(true);
}
});
} | 6 |
@Test(expected = ParkException.class)
public void in_a_car_when_all_park_is_full() {
for(int i = 0; i <= 15; i ++) {
parkBoy.in(new Car(String.valueOf(i)));
}
} | 1 |
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
{
JOptionPane.showMessageDialog(null, "Are you Sure you want to exit?");
System.exit(0);
}
else if(e.getActionCommand().equals("About"))
{
JOptionPane.showMessageDialog(null,
"Medical Application Integration Final Project\n" +
"Lab Information System Group\n" +
"Kov, Chris O, Nicolette"
);
System.exit(0);
}
} | 2 |
public Voiture ajouterVoiture(VoieEnum depart, VoieEnum destination) {
VoieExterne entree, sortie;
entree = voiesExternes.get(depart.ordinal());
sortie = voiesExternes.get(destination.ordinal());
Voiture voiture = new Voiture(sortie);
if (statistiques != null) {
voiture.addObserver(statistiques);
}
entree.entrer(voiture);
return voiture;
} | 1 |
public void visit_baload(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
@Override
public void removeDefi(long id) {
em.clear();
try {
Defi defiToRemove = em.find(Defi.class, id);
em.remove(defiToRemove);
} catch(Exception e) {}
} | 1 |
public static String getMIME(String str){
//This method gets the MIME according to the extension.
if(str.endsWith("/")) return "text/html";
String extension = str.substring(str.lastIndexOf(".")+1);
switch (extension){
case "html":
return "text/html";
case "htm":
return "text/html";
case "jpeg":
return "image/jpeg";
case "jpg":
return "image/jpeg";
case "gif":
return "image/gif";
case "js":
return "application/javascript";
case "css":
return "text/css";
}
return "error";
} | 8 |
public int getIndex() {
return this.index;
} | 0 |
private boolean insertStrict(T model, Long oldUpdatedAt) throws JackException, IOException {
PreparedStatement insertStmt = conn.getPreparedStatement(getInsertWithIdStatement(fieldNames));
try {
setAttrs(model, insertStmt);
insertStmt.setLong(fieldNames.size() + 1, model.getId());
insertStmt.execute();
final int updateCount = insertStmt.getUpdateCount();
insertStmt.close();
if (updateCount > 1) {
throw new TooManyRowsUpdatedException();
} else if (updateCount < 1) {
revertRailsUpdatedAt(model, oldUpdatedAt);
throw new StaleModelException();
} else {
if (useCache) {
cachedById.put(model.getId(), model);
}
clearForeignKeyCache();
model.setCreated(true);
return true;
}
} catch (SQLException e) {
revertRailsUpdatedAt(model, oldUpdatedAt);
throw new IOException(e);
}
} | 4 |
protected AutomatonPane getView() {
return view;
} | 0 |
private Animation createPlayerAnim(Image player1,
Image player2, Image player3, Image player4,
Image player5, Image player6, Image player7,
Image player8, Image player9, Image player10)
{
Animation anim = new Animation();
anim.addFrame(player1, 80);
anim.addFrame(player2, 80);
anim.addFrame(player3, 80);
anim.addFrame(player4, 80);
anim.addFrame(player5, 80);
anim.addFrame(player6, 80);
anim.addFrame(player7, 80);
anim.addFrame(player8, 80);
anim.addFrame(player9, 80);
anim.addFrame(player10, 80);
return anim;
} | 0 |
@RequestMapping(value="/edit.do", method=RequestMethod.GET)
public String editProfile(@RequestParam(value="userId", required = false) Long userId, Model model) {
if(userId == null) {
model.addAttribute("user", new User());
} else {
model.addAttribute("user", new User() ); //userService.getUser(userId));
}
return "editProfile";
} | 1 |
* @throws IOException
* if there is a low-level IO error
*/
public void updateDocValues(Term term, Field... updates) throws IOException {
ensureOpen();
DocValuesUpdate[] dvUpdates = new DocValuesUpdate[updates.length];
for (int i = 0; i < updates.length; i++) {
final Field f = updates[i];
final DocValuesType dvType = f.fieldType().docValuesType();
if (dvType == null) {
throw new NullPointerException("DocValuesType must not be null (field: \"" + f.name() + "\")");
}
if (dvType == DocValuesType.NONE) {
throw new IllegalArgumentException("can only update NUMERIC or BINARY fields! field=" + f.name());
}
if (!globalFieldNumberMap.contains(f.name(), dvType)) {
throw new IllegalArgumentException("can only update existing docvalues fields! field=" + f.name() + ", type=" + dvType);
}
switch (dvType) {
case NUMERIC:
dvUpdates[i] = new NumericDocValuesUpdate(term, f.name(), (Long) f.numericValue());
break;
case BINARY:
dvUpdates[i] = new BinaryDocValuesUpdate(term, f.name(), f.binaryValue());
break;
default:
throw new IllegalArgumentException("can only update NUMERIC or BINARY fields: field=" + f.name() + ", type=" + dvType);
}
}
try {
if (docWriter.updateDocValues(dvUpdates)) {
processEvents(true, false);
}
} catch (VirtualMachineError tragedy) {
tragicEvent(tragedy, "updateDocValues");
}
} | 8 |
public void clear() {
this.data = new int[DEFAULT_SIZE];
size = 0;
} | 0 |
private void moveNewZipFiles(String zipPath) {
File[] list = listFilesOrError(new File(zipPath));
for (final File dFile : list) {
if (dFile.isDirectory() && this.pluginExists(dFile.getName())) {
// Current dir
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName());
// List of existing files in the new dir
final File[] dList = listFilesOrError(dFile);
// List of existing files in the current dir
final File[] oList = listFilesOrError(oFile);
for (File cFile : dList) {
// Loop through all the files in the new dir
boolean found = false;
for (final File xFile : oList) {
// Loop through all the contents in the current dir to see if it exists
if (xFile.getName().equals(cFile.getName())) {
found = true;
break;
}
}
if (!found) {
// Move the new file into the current dir
File output = new File(oFile, cFile.getName());
this.fileIOOrError(output, cFile.renameTo(output), true);
} else {
// This file already exists, so we don't need it anymore.
this.fileIOOrError(cFile, cFile.delete(), false);
}
}
}
this.fileIOOrError(dFile, dFile.delete(), false);
}
File zip = new File(zipPath);
this.fileIOOrError(zip, zip.delete(), false);
} | 7 |
public void keyPressed(KeyEvent e) {
if(!credits) {
input.set(e.getKeyCode(), true);
} else if (credits) {
System.exit(0);
}
} | 2 |
public int findFirstOccurrence(int [] arrA, int x, int start, int end){
if(end>=start){
int mid = (start+end)/2;
if((mid==0||(arrA[mid-1]<x)) && arrA[mid]==x){
return mid;
}else if(arrA[mid]<x){
return findFirstOccurrence(arrA, x, mid+1, end);
}else{
return findFirstOccurrence(arrA, x, start, mid-1);
}
}else return -1;
} | 5 |
public ListNode rotateRight(ListNode head, int n)
{
if (null == head || null == head.next)
return head;
ListNode p = head;
int len = 0;
while (p != null)
{
len++;
p = p.next;
}
n %= len;
if (n == 0)
return head;
ListNode r = null, end = head;
int i = 0;
p = head;
while (p != null)
{
if (null == p.next)
end = p;
if (i < n)
{
p = p.next;
++i;
}
else if (i == n)
{
r = head;
p = p.next;
++i;
}
else
{
r = r.next;
p = p.next;
++i;
}
}
ListNode h = r.next;
end.next = head;
r.next = null;
return h;
} | 8 |
@Override
public void handlePieceAvailability(SharingPeer peer,
Piece piece) { /* Do nothing */ } | 0 |
public void splitAndInsert(String value, long split_ts) {
for (Map.Entry<String, String> entry : optimizedData.entrySet()) {
String times = entry.getValue();
String[] timespan = times.split(",");
Long firstTime = Long.parseLong(timespan[0]);
if (split_ts < firstTime)
continue;
Long secondTime = Long.parseLong(timespan[1]);
if (split_ts == firstTime) {
if(split_ts==secondTime){
entry.setValue(value);
return;
}else{
String val1=firstTime+","+firstTime;
String val2=(split_ts+1)+","+secondTime;
optimizedData.put(value,val1);
String prevKey=entry.getKey();
optimizedData.put(prevKey,val2);
return;
}
}
if(split_ts>firstTime && split_ts<=secondTime){
String val1=firstTime+","+(split_ts-1);
String val2=split_ts+","+secondTime;
String prevKey=entry.getKey();
optimizedData.put(prevKey,val1);
optimizedData.put(value,val2);
return;
}
if(split_ts<firstTime || split_ts>secondTime){
continue;
}
}
optimizedData.put(value, split_ts+","+split_ts);
} | 8 |
private static int getASMModifiers(Modifiers modifiers) {
int mods = 0;
if (modifiers == null) {
return mods;
}
if (modifiers.hasModifier("public")) {
mods += ACC_PUBLIC;
}
if (modifiers.hasModifier("protected")) {
mods += ACC_PROTECTED;
}
if (modifiers.hasModifier("static")) {
mods += ACC_STATIC;
}
if (modifiers.hasModifier("synchronized")) {
mods += ACC_SYNCHRONIZED;
}
if (modifiers.hasModifier("abstract")) {
mods += ACC_ABSTRACT;
}
return mods;
} | 6 |
public static IRCCommand getResponse(String command){
if (requiresResponse(command)){
IRCCommand cmd;
try {
cmd = IRCCommand.valueOf(command.toUpperCase()).response;
return cmd;
} catch (IllegalArgumentException e){System.out.println("Unkown command: " + command);}
}
return null;
} | 2 |
public TreeDrawer getTreeDrawer() {
return treeDrawer;
} | 0 |
public static int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] pathsum = new int[m][n];
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
if (i == m - 1 && j == n - 1) pathsum[i][j] = grid[i][j];
else if (i == m - 1) pathsum[i][j] = pathsum[i][j + 1] + grid[i][j];
else if (j == n - 1) pathsum[i][j] = pathsum[i + 1][j] + grid[i][j];
else {
int right = pathsum[i][j + 1];
int down = pathsum[i + 1][j];
pathsum[i][j] = right > down ? down + grid[i][j] : right + grid[i][j];
}
}
}
return pathsum[0][0];
} | 7 |
public boolean equals(Object object) {
return object == null || object == this;
} | 1 |
Result tryRule( TotalisticRule r, int fieldSize ){
double p = 0.5;
ArrayField field = new ArrayField();
field.setCells( Util.randomField( fieldSize, p) );
Path[] soup = field.getAliveCellsArray(); //it returns reference
sortCells( soup );
int initialPopulation = soup.length;
int limitPopulaion = initialPopulation * 10;
int limitIteration = 500;
int step = 0;
while ( soup.length > 0 && soup.length < limitPopulaion && step < limitIteration){
field.evaluate( r );
Path[] soup1 = field.getAliveCellsArray();
step += 1;
sortCells( soup1 );
if (Arrays.equals( soup1, soup )){//stabilized
return new Result( R_STATIC, step );
}
soup = soup1;
}
//now analyze the situation.
if ( soup.length == 0 ) return new Result( R_DIE_OUT, step );
if ( soup.length >= limitPopulaion ) return new Result(R_EXPONENTIAL, step);
//most interesting case.
//Trying to detect cycle
int period = detectCycle( field, r );
if (period == NO_PERIOD){
//search for the gliders
if ( hasGliders( soup, fieldSize ))
return new Result( R_CHAOTIC_GLIDERS, NO_PERIOD);
else
return new Result( R_CHAOTIC, NO_PERIOD );
}
else
return new Result( R_CYCLIC, period );
} | 8 |
public Polynomial modPow(long e, Polynomial p) throws Exception {
Polynomial x = this;
Polynomial r = one();
while (e > 0) {
if ((e & 1L) != 0) r = r.mul(x).div(p)[1]; // r *= x mod p
e >>= 1;
x = x.mul(x).div(p)[1]; // x = x^2 mod p
}
return r;
} | 2 |
@Override
public String[] getHelp() {
return new String[]{
"ttp debug <username> [on/off]",
"Toggles the debug state of a user"
};
} | 0 |
@Test
public void testSingleReaderManyWriters()
{
final int MESSAGES = 10000;
final int WRITERS = 10;
final int MESSAGES_PER_WRITER = MESSAGES / WRITERS;
final AtomicInteger nullCounter = new AtomicInteger();
final BlockableQueue<Integer> q = new BlockableQueue<Integer>();
q.setBlocking(true);
Runnable reader = new Runnable() {
public void run() {
int total = 0;
double minWait = Double.MAX_VALUE;
double maxWait = -Double.MAX_VALUE;
Stopwatch watch = new Stopwatch();
while (total < MESSAGES) {
watch.start();
Integer value = q.poll();
watch.stop();
if (value != null) {
minWait = Math.min(minWait, watch.seconds());
maxWait = Math.max(maxWait, watch.seconds());
total++;
} else {
nullCounter.incrementAndGet();
}
}
System.out.format("Wait: min[%.6fs] max[%.6fs]\n", minWait, maxWait);
}
};
Runnable writer = new Runnable() {
public void run() {
for (int i = 0; i < MESSAGES_PER_WRITER; i++) {
assertTrue( q.offer(i) );
// Causes the reader to wait some amount of time
sleep(1);
}
}
};
GroupTask.initialize(WRITERS + 1);
GroupTask.add(writer, WRITERS);
GroupTask.add(reader);
GroupTask.execute();
System.out.println("Null polls: " + nullCounter.get());
} | 3 |
public static void main (String[] args) {
int i = 1;
for (; ; i++) {
if (i % 20 == 0 && i % 19 == 0 && i % 18 == 0 && i % 17 == 0 && i % 16 == 0 && i % 14 == 0 && i % 13 == 0 &
i % 11 == 0) {
break;
}
}
System.out.println(i);
} | 8 |
private void waitTime () {
if (isFirstTimeToDisplay) {
isFirstTimeToDisplay = false;
// Wait a little time for gui initial display.
try {
Thread.sleep(INPUT_WAITING_TIME_LONG);
} catch (final InterruptedException e) {
e.printStackTrace();
}
lastRunTime = System.currentTimeMillis();
} else {
final long thisRunTime = System.currentTimeMillis();
final long duration = thisRunTime - lastRunTime;
if (duration >= 0 && duration < INPUT_WAITING_TIME_SHORT) {
// Wait a little time for preventing too soon to invoke another
// display.
try {
Thread.sleep(INPUT_WAITING_TIME_SHORT - duration);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
lastRunTime = System.currentTimeMillis();
}
} | 5 |
private void autoSelectListBox(List<String> headers) {
String loc;
if ((loc = Utils.getBestMatch(controller.getLocationKeywords(), headers)) != null) {
locationHeaderCB.setSelectedItem(loc);
}
String category;
if ((category = Utils.getBestMatch(controller.getCategoryKeywords(), headers)) != null) {
categoryHeaderCB.setSelectedItem(category);
}
String buyer;
if ((buyer = Utils.getBestMatch(controller.getBuyerKeywords(), headers)) != null) {
buyerHeaderCB.setSelectedItem(buyer);
}
String rate;
if ((rate = Utils.getBestMatch(controller.getRateKeywords(), headers)) != null) {
rateHeaderCB.setSelectedItem(rate);
}
String cost;
if ((cost = Utils.getBestMatch(controller.getCostKeywords(), headers)) != null) {
costHeaderCB.setSelectedItem(cost);
}
String price;
if ((price = Utils.getBestMatch(controller.getPriceKeywords(), headers)) != null) {
priceHeaderCB.setSelectedItem(price);
}
String profit;
if ((profit = Utils.getBestMatch(controller.getProfitKeywords(), headers)) != null) {
profitHeaderCB.setSelectedItem(profit);
}
String date;
if ((date = Utils.getBestMatch(controller.getDateKeywords(), headers)) != null) {
dateHeaderCB.setSelectedItem(date);
}
} | 8 |
public void mouseExited(MouseEvent e) {
mouseMoved(e);
} | 0 |
public void setMenuIcons(ImageIcon normal, ImageIcon selected) {
if (normal != null) {
for (AccordionRootItem menu : getMenus()) {
menu.setNormalIcon(normal);
}
}
if (selected != null) {
for (AccordionRootItem menu : getMenus()) {
menu.setSelectedIcon(selected);
}
}
updateLeafs();
} | 4 |
public static void main(String args[]) throws ClassNotFoundException {
/*
* Load core config
*/
ConfigLoaderCore cf = new ConfigLoaderCore();
cf.LoadCoreConfig(); // Load core properties
// Проверяем обновление и качаем если надо
jmc.minecraft.utils.LauncherUpdater.UpdateLauncher(); //TODO обновыление лаунчера
cf.LoadUserConfig(); // Load user config
cf.LoadClientConfig(GlobalVar.itemsServers[GlobalVar.CurrentServer]);// Load
// first
// info
// about
// client
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
Log("Проверка совместимости");
Log("Запуск под OS: "+System.getProperty("os.name")+" ("+Utils.getPlatform().toString()+")");
Log("Память всего:"+Utils.getOSTotalMemory()+" свободно:"+Utils.getOSFreeMemory());
//JavaInfo java = Settings.getSettings().getCurrentJava();
Log("Java ver: "+Utils.getCurrentJava() + " " + System.getProperty("sun.arch.data.model") +" path:"+System.getProperty("java.home"));
String[] s = Utils.getCurrentJava().split("[._-]");
int major = Integer.parseInt(s[0]);
int minor = s.length > 1 ? Integer.parseInt(s[1]) : 0;
int revision = s.length > 2 ? Integer.parseInt(s[2]) : 0;
int build = s.length > 3 ? Integer.parseInt(s[3]) : 0;
ButtonLogin.setEnabled(true);
if (GlobalVar.JavaVer17 && !((major == 1) && (minor == 7)) ) {
Log("Версия java должна быть 1.7. Переустановите Java на версию 1.7");
ButtonLogin.setEnabled(false);
}
if (GlobalVar.Java64 && System.getProperty("sun.arch.data.model").equals("32")) {
Log("Версия java 32bit. Если у Вас 32 битная система, то вы не сможете играть в эту сборку.");
ButtonLogin.setEnabled(false);
}
if (!System.getProperty("sun.arch.data.model").equals("64")) {
Log("Установленная у Вас версия java 32bit. Рекомендуем установить 64 битную версию для увеличения объема оперативной памяти для приложения.");
}
}
});
} | 9 |
@Override
public void setUp() {
mapping = new HashMap<>();
final List<ColumnMetaData> listColumns = new ArrayList<>();
for (final String column : new String[] { "Id", "Description" }) {
final ColumnMetaData columnMetadata = new ColumnMetaData();
columnMetadata.setColName(column);
listColumns.add(columnMetadata);
}
mapping.put(FPConstants.DETAIL_ID, listColumns);
} | 1 |
@Override
public void execute() {
Variables.status = "Looting nest";
if(Inventory.getItem(Variables.seedNest_ID) != null)
Inventory.getItem(Variables.seedNest_ID).getWidgetChild().interact("Search");
sleep(1000,1200);
if(Inventory.contains(Variables.seed_IDs))
System.out.println("yo");
if(Inventory.contains(Variables.dropSeed_IDs))
Inventory.getItem(Variables.dropSeed_IDs).getWidgetChild().interact("Drop");
sleep(1000,1200);
if(Inventory.getItem(Variables.nest_ID) != null)
Inventory.getItem(Variables.nest_ID).getWidgetChild().interact("Drop");
} | 4 |
public void visit_idiv(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
private void checkEvictionOrder(boolean lifo) throws Exception {
SimpleFactory factory = new SimpleFactory();
GenericKeyedObjectPool pool = new GenericKeyedObjectPool(factory);
pool.setNumTestsPerEvictionRun(2);
pool.setMinEvictableIdleTimeMillis(100);
pool.setLifo(lifo);
for (int i = 0; i < 3; i ++) {
Integer key = new Integer(i);
for (int j = 0; j < 5; j++) {
pool.addObject(key);
}
}
// Make all evictable
Thread.sleep(200);
/*
* Initial state (Key, Object) pairs in order of age:
*
* (0,0), (0,1), (0,2), (0,3), (0,4)
* (1,5), (1,6), (1,7), (1,8), (1,9)
* (2,10), (2,11), (2,12), (2,13), (2,14)
*/
pool.evict(); // Kill (0,0),(0,1)
assertEquals(3, pool.getNumIdle(zero));
Object obj = pool.borrowObject(zero);
assertTrue(lifo ? obj.equals("04") : obj.equals("02"));
assertEquals(2, pool.getNumIdle(zero));
obj = pool.borrowObject(zero);
assertTrue(obj.equals("03"));
assertEquals(1, pool.getNumIdle(zero));
pool.evict(); // Kill remaining 0 survivor and (1,5)
assertEquals(0, pool.getNumIdle(zero));
assertEquals(4, pool.getNumIdle(one));
obj = pool.borrowObject(one);
assertTrue(lifo ? obj.equals("19") : obj.equals("16"));
assertEquals(3, pool.getNumIdle(one));
obj = pool.borrowObject(one);
assertTrue(lifo ? obj.equals("18") : obj.equals("17"));
assertEquals(2, pool.getNumIdle(one));
pool.evict(); // Kill remaining 1 survivors
assertEquals(0, pool.getNumIdle(one));
pool.evict(); // Kill (2,10), (2,11)
assertEquals(3, pool.getNumIdle(two));
obj = pool.borrowObject(two);
assertTrue(lifo ? obj.equals("214") : obj.equals("212"));
assertEquals(2, pool.getNumIdle(two));
pool.evict(); // All dead now
assertEquals(0, pool.getNumIdle(two));
pool.evict(); // Should do nothing - make sure no exception
pool.evict();
// Reload
pool.setMinEvictableIdleTimeMillis(500);
factory.counter = 0; // Reset counter
for (int i = 0; i < 3; i ++) {
Integer key = new Integer(i);
for (int j = 0; j < 5; j++) {
pool.addObject(key);
}
Thread.sleep(200);
}
// 0's are evictable, others not
pool.evict(); // Kill (0,0),(0,1)
assertEquals(3, pool.getNumIdle(zero));
pool.evict(); // Kill (0,2),(0,3)
assertEquals(1, pool.getNumIdle(zero));
pool.evict(); // Kill (0,4), leave (1,5)
assertEquals(0, pool.getNumIdle(zero));
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
pool.evict(); // (1,6), (1,7)
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
pool.evict(); // (1,8), (1,9)
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
pool.evict(); // (2,10), (2,11)
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
pool.evict(); // (2,12), (2,13)
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
pool.evict(); // (2,14), (1,5)
assertEquals(5, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
Thread.sleep(200); // Ones now timed out
pool.evict(); // kill (1,6), (1,7) - (1,5) missed
assertEquals(3, pool.getNumIdle(one));
assertEquals(5, pool.getNumIdle(two));
obj = pool.borrowObject(one);
assertTrue(lifo ? obj.equals("19") : obj.equals("15"));
} | 9 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
while ((line = in.readLine()) != null && line.length() != 0) {
int nSet = Integer.parseInt(line.trim());
for (int i = 0; i < nSet; i++) {
int nWords = Integer.parseInt(in.readLine().trim());
String[] words = new String[nWords];
for (int j = 0; j < words.length; j++)
words[j] = in.readLine().trim();
int ans = 0;
for (int j = 0; j < words.length; j++)
for (int k = j + 1; k < words.length; k++)
ans = Math.max(check(words[j], words[k]), ans);
out.append(ans + "\n");
}
}
System.out.print(out);
} | 6 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} | 0 |
public static void adjustComponentBounds(Component comp, Component parentComp){
if(parentComp == null){
int x = Math.max(comp.getX(), 12);
int y = Math.max(comp.getY(), 12);
int width = Math.min(comp.getWidth(), Toolkit.getDefaultToolkit().getScreenSize().width-100);
int height = Math.min(comp.getHeight(), Toolkit.getDefaultToolkit().getScreenSize().height-100);
if(x + width > Toolkit.getDefaultToolkit().getScreenSize().width - 12){
x = Toolkit.getDefaultToolkit().getScreenSize().width - width - 12;
}
if(x < 0){
x = 12;
}
if(y + height > Toolkit.getDefaultToolkit().getScreenSize().height - 64){
y = Toolkit.getDefaultToolkit().getScreenSize().height - height - 64;
}
if(y < 0){
y = 12;
}
comp.setBounds(x, y, width, height);
}
} | 5 |
public void addTime(String playerName, int time, DB_Timers timer) {
String message, bmessage;
Integer timerID = timer.getId();
String st_time = this.plugin.util.formatTime(Integer.valueOf(time));
DB_Times data = this.plugin.database.getDatabase().find(DB_Times.class).where().ieq("Playername", playerName).where().eq("TimerID", timerID).findUnique();
if (data == null) {
data = new DB_Times();
data.setPlayername(playerName);
data.setTime(time);
data.setTimerID(timerID);
message = "Your time has been saved.";
bmessage = "It was their first time.";
this.plugin.database.getDatabase().save(data);
}
else {
Long savedTime = data.getTime();
if (time < savedTime) {
message = "New personal best. " + st_time;
bmessage = "with a new personal best of " + st_time;
data.setTime(time);
this.plugin.database.getDatabase().save(data);
}
else if (time == savedTime) {
message = "You matched your best time of " + st_time;
bmessage = "They matched their best time of " + st_time;
}
else {
Integer difference = (int) (time - savedTime);
String fasterTime = this.plugin.util.formatTime(difference);
message = "Your old time was " + fasterTime + " faster.";
bmessage = "which was " + fasterTime + " slower.";
}
}
if (this.plugin.broadcast_times) {
this.plugin.util.broadcast(bmessage);
}
else {
this.plugin.util.messagePlayer(playerName, message);
}
this.updateRanks(timer, false);
} | 4 |
public int[] getPosition() {
return this.position;
} | 0 |
public double visibleNode(int index) {
if(index < 0 || index >= m)
throw new RuntimeException("given m=" + m + ", illegal value for index: " + index);
return _visibleNodes[index];
} | 2 |
public void add(E element) {
if (root == null && element != null) {
root = new Node<E>(element);
size++;
} else if (element != null) {
root = insert(root, element);
}
} | 3 |
public boolean pass(int[] bowl, int bowlId, int round,
boolean canPick,
boolean musTake) {
counter++;
if(counter==1){
for(int i=0;i<12;i++){
bowSize+=bowl[i];
}
//update(bowSize*6);
}
update(bowl,bowlId,round);
if (musTake){
return true;
}
if(canPick==false)
return false;
//no enough information
if (info.size()<=1) {
return false;
}
if (round==0) {
futureBowls=nplayer-position-counter;
//return round0(bowl,bowlId,round,canPick,musTake);
} else {
futureBowls=nplayer-counter+1;
//return round1(bowl,bowlId,round,canPick,musTake);
}
double b=score(bowl);
double PrB=1, p=probLessThan(b);
for (int i = 0; i < futureBowls; i++) { PrB*=p; }
double PrA=1-PrB;
double ExA=exptGreaterThan(b);
double ExB=exptLessThan(b);
double Ex2=PrA*ExA+PrB*ExB;
double tStar=search();
double fTStar=f(tStar);
//double fb=f(b,futureBowls);
//double fb1=f(b+1, futureBowls);
if(fTStar>b) { //
return false;
}
else {
return true;
}
} | 8 |
public int characterAt(int at) throws JSONException {
int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
return character;
}
}
throw new JSONException("Bad character at " + at);
} | 8 |
public void save() throws IOException {
try {
// Generate XML builder
// (thanks to
// http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/)
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Required element level objects
Element e0, e1, e2, e3, e4, e5;
// <favourites>
e0 = doc.createElement("favourites");
for (Favourite f : list) {
// <favourite name="">
e1 = doc.createElement("favourite");
e1.setAttribute("name", f.getName());
// <algorithm name="">
e2 = doc.createElement("algorithm");
e2.setAttribute("name", f.getAlgorithm().getName());
// <iterations>
e3 = doc.createElement("iterations");
e3.appendChild(doc.createTextNode(f.getAlgorithm().getIterations() + ""));
e2.appendChild(e3);
// <escaperadius>
e3 = doc.createElement("escaperadius");
e3.appendChild(doc.createTextNode(f.getAlgorithm().getEscapeRadius() + ""));
e2.appendChild(e3);
// </algorithm>
e1.appendChild(e2);
// <selected>
e2 = doc.createElement("selected");
// <real>
e3 = doc.createElement("real");
e3.appendChild(doc.createTextNode(f.getSelected().real() + ""));
e2.appendChild(e3);
// <imaginary>
e3 = doc.createElement("imaginary");
e3.appendChild(doc.createTextNode(f.getSelected().imaginary() + ""));
e2.appendChild(e3);
// </selected>
// <bounds>
e2 = doc.createElement("bounds");
// <bottomleft>
e3 = doc.createElement("bottomleft");
// <real>
e4 = doc.createElement("real");
e4.appendChild(doc.createTextNode(f.getBounds()[0].real() + ""));
e3.appendChild(e4);
// <imaginary>
e4 = doc.createElement("imaginary");
e4.appendChild(doc.createTextNode(f.getBounds()[0].imaginary() + ""));
e3.appendChild(e4);
e2.appendChild(e3);
// </bottomleft>
// <topright>
e3 = doc.createElement("topright");
// <real>
e4 = doc.createElement("real");
e4.appendChild(doc.createTextNode(f.getBounds()[1].real() + ""));
e3.appendChild(e4);
// <imaginary>
e4 = doc.createElement("imaginary");
e4.appendChild(doc.createTextNode(f.getBounds()[1].imaginary() + ""));
e3.appendChild(e4);
// </topright>
e2.appendChild(e3);
// </bounds>
e1.appendChild(e2);
// <scheme>
e2 = doc.createElement("scheme");
// <gridlines>
e3 = doc.createElement("gridlines");
e3.appendChild(doc.createTextNode(serialiseColour(f.getScheme().getGridlineColour())));
e2.appendChild(e3);
// <colours>
e3 = doc.createElement("colours");
for (Map.Entry<Double, Color> entry : f.getScheme().entrySet()) {
// <colourstop>
e4 = doc.createElement("colourstop");
// <progress>
e5 = doc.createElement("progress");
e5.appendChild(doc.createTextNode(entry.getKey() + ""));
e4.appendChild(e5);
// <colour>
e5 = doc.createElement("colour");
e5.appendChild(doc.createTextNode(serialiseColour(entry.getValue())));
e4.appendChild(e5);
// </colourstop>
e3.appendChild(e4);
}
// </colours>
e2.appendChild(e3);
// </scheme>
e1.appendChild(e2);
// </favourite>
e0.appendChild(e1);
}
// </favourites>
doc.appendChild(e0);
// Request a cleanup of all those objects now
System.gc();
// Prepare Optimus Prime
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// Write output
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(filename);
transformer.transform(source, result);
} catch (Exception ex) {
// Re-throw XML generation exceptions as IOExceptions
if (ex instanceof IOException)
throw (IOException) ex;
else
throw new IOException(ex);
}
} | 4 |
public RepairGUI() {
setBounds(100, 100, 537, 393);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 535, 364);
contentPane.add(panel);
panel.setLayout(null);
JTextArea textArea = new JTextArea();
textArea.setBounds(56, 154, 1, 15);
panel.add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setBounds(56, 154, 1, 15);
panel.add(textArea_1);
JLabel label_4 = new JLabel("Repair");
label_4.setFont(new Font("Dialog", Font.BOLD, 16));
label_4.setBounds(239, 12, 70, 15);
panel.add(label_4);
JButton btn_R_first = new JButton("<<");
btn_R_first.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
result = query.query(nameTBL, 1, nameID);
insertValues(result);
currentID = 1;
}
});
btn_R_first.setBounds(12, 274, 54, 25);
panel.add(btn_R_first);
JButton btn_R_back = new JButton("<");
btn_R_back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentID > 1) {
currentID--;
result = query.query(nameTBL, currentID, nameID);
while (result[1] == null) {
currentID--;
result = query.query(nameTBL, currentID, nameID);
}
insertValues(result);
}
}
});
btn_R_back.setBounds(66, 274, 54, 25);
panel.add(btn_R_back);
JButton btn_R_forward = new JButton(">");
btn_R_forward.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
currentID++;
if (currentID > 1 && currentID <= maxID) {
result = query.query(nameTBL, currentID, nameID);
while (result[1] == null && currentID <= maxID) {
currentID++;
result = query.query(nameTBL, currentID, nameID);
}
insertValues(result);
}
}
});
btn_R_forward.setBounds(118, 274, 54, 25);
panel.add(btn_R_forward);
JButton btn_R_last = new JButton(">>");
btn_R_last.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
while (currentID<maxID) {
currentID++;
}
result = query.query(nameTBL, currentID, nameID);
insertValues(result);
}
});
btn_R_last.setBounds(173, 274, 54, 25);
panel.add(btn_R_last);
JButton btn_R_new = new JButton("New");
btn_R_new.setBounds(228, 274, 70, 25);
panel.add(btn_R_new);
JButton btn_R_save = new JButton("Save");
btn_R_save.setBounds(296, 274, 68, 25);
panel.add(btn_R_save);
JButton btn_R_del = new JButton("Del");
btn_R_del.setBounds(366, 274, 70, 25);
panel.add(btn_R_del);
JLabel lblNewLabel = new JLabel("Error Description");
lblNewLabel.setBounds(28, 52, 126, 15);
panel.add(lblNewLabel);
JLabel lblErrorType = new JLabel("Error Type:");
lblErrorType.setBounds(28, 127, 126, 15);
panel.add(lblErrorType);
int lengthErrortype = query.maxID(errorTypeTBL, "errortype_ID");
String[] cbx_R_valuesErr = new String[lengthErrortype];
cbx_R_valuesErr = query.queryColumn(errorTypeTBL, "errorname", lengthErrortype);
DefaultComboBoxModel<String> modelErr = new DefaultComboBoxModel(cbx_R_valuesErr);
cbx_R_errortype = new JComboBox(modelErr);
cbx_R_errortype.setBounds(185, 122, 251, 20);
panel.add(cbx_R_errortype);
int lengthEmployee = query.maxID(employeeTBL, "employee_ID");
String[] cbx_R_valuesEmp = new String[lengthErrortype];
cbx_R_valuesEmp = query.queryColumn(employeeTBL, "name", lengthEmployee);
DefaultComboBoxModel<String> modelEmp = new DefaultComboBoxModel(cbx_R_valuesEmp);
cbx_R_employee = new JComboBox(modelEmp);
cbx_R_employee.setBounds(185, 154, 251, 20);
panel.add(cbx_R_employee);
JLabel lblEmployee = new JLabel("Employee:");
lblEmployee.setBounds(28, 154, 126, 15);
panel.add(lblEmployee);
int lengthOrder = query.maxID(orderTBL, "orderdetails_ID");
String[] cbx_R_valuesOrd = new String[lengthErrortype];
cbx_R_valuesOrd = query.queryColumn(orderTBL, "orderdetails_ID", lengthOrder);
DefaultComboBoxModel<String> modelOrd = new DefaultComboBoxModel(cbx_R_valuesOrd);
cbx_R_order = new JComboBox(modelOrd);
cbx_R_order.setBounds(185, 181, 251, 20);
panel.add(cbx_R_order);
JLabel lblOrderDetails = new JLabel("Order Details:");
lblOrderDetails.setBounds(28, 186, 126, 15);
panel.add(lblOrderDetails);
txt_R_spec = new JTextArea();
txt_R_spec.setBounds(171, 39, 265, 68);
panel.add(txt_R_spec);
JButton btnErrorType = new JButton("Error Type");
btnErrorType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ErrorTypeGUI eGui = new ErrorTypeGUI();
eGui.openErrorTypeGUI();
}
});
btnErrorType.setBounds(37, 327, 117, 25);
panel.add(btnErrorType);
JButton btnEmployee = new JButton("Employee");
btnEmployee.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
EmployeeGUI emGui = new EmployeeGUI();
emGui.openEmployeeGUI();
}
});
btnEmployee.setBounds(185, 327, 117, 25);
panel.add(btnEmployee);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
} | 7 |
protected void end() {
Robot.tilter.stop();
} | 0 |
public static void main(String[] args) {
JSAP jsap = initParameters();
JSAPResult jsapResult = jsap.parse(args);
if(!jsapResult.success()) {
printHelp(jsap);
}
boolean withShortedPath = jsapResult.getBoolean("shortedPath");
//Boolean reduced = jsapResult.getBoolean("reduced");
File inputFile = new File(jsapResult.getString("input"));
File outputFile = new File(jsapResult.getString("output"));
if(!inputFile.canRead()) {
System.err.println("Can't read on " + inputFile.getPath());
System.exit(-1);
}
Xml xml = XmlFactory.newXml(inputFile);
Maze maze = new Maze(xml.getRectangle().getDimension());
maze.initMaze(xml.getPoints().getStart(), xml.getPoints().getEnd(),
xml.getRectangle().getObstacles().getObstacle());
Integer start = xml.getPoints().getStart().getX() +
xml.getPoints().getStart().getY() *
xml.getRectangle().getDimension().getWidth();
Integer stop = xml.getPoints().getEnd().getX() +
xml.getPoints().getEnd().getY() *
xml.getRectangle().getDimension().getWidth();
if(withShortedPath) {
NodeListGraph nodeListGraph = NodeListGraphFactory.newNodeListGraph(maze);
Dijkstra dijkstra = new Dijkstra(nodeListGraph);
maze.colorShortedPath(dijkstra.getShortedPath(start, stop));
}
try {
maze.createImage(outputFile);
} catch (IOException e) {
System.err.println("Erreur d'écriture de l'image !");
e.printStackTrace();
System.exit(-1);
}
} | 4 |
public void writeAttributeList(Writer writer, Iterable<? extends Iterable<Tuple2<?, ?>>> attributes) throws IOException {
if (attributes != null) {
for (Iterable<Tuple2<?, ?>> alist : attributes) {
writeAList(writer, alist);
}
}
} | 7 |
public static Surrogate coerceToBoundOrLocalSurrogate(GeneralizedSymbol self) {
{ Surrogate surrogate = null;
if (Logic.explicitlyQualifiedLogicObjectNameP(self, ((Module)(Stella.$MODULE$.get())))) {
{ Object old$Module$000 = Stella.$MODULE$.get();
Object old$Context$000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, ((Module)(self.homeContext)));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
return (Logic.coerceToBoundOrLocalSurrogate(self));
} finally {
Stella.$CONTEXT$.set(old$Context$000);
Stella.$MODULE$.set(old$Module$000);
}
}
}
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate self000 = ((Surrogate)(self));
surrogate = self000;
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol self000 = ((Symbol)(self));
surrogate = Surrogate.lookupSurrogateInModule(self000.symbolName, ((Module)(self000.homeContext)), false);
if ((surrogate == null) &&
(!(((Module)(self000.homeContext)) == ((Module)(Stella.$MODULE$.get()))))) {
surrogate = Surrogate.lookupSurrogateInModule(self000.symbolName, ((Module)(Stella.$MODULE$.get())), false);
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
if ((surrogate != null) &&
(surrogate.surrogateValue != null)) {
return (surrogate);
}
return (Stella.shadowSurrogate(self.symbolName));
}
} | 7 |
public PartnerRole(final String name) {
super(name);
} | 0 |
private void jbtnValiderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnValiderActionPerformed
if (modeCMS.equals("C")) {
if (JOptionPane.showConfirmDialog(this, "Etes-vous sûr de vouloir créer ce livre ?", "Confirmation", YES_NO_OPTION)==YES_OPTION){
creer();
try{
connection.close();
} catch ( SQLException ex) {
JOptionPane.showMessageDialog(this,"erreur base de données "+ ex.getErrorCode());
}
this.dispose();
}
} else if (modeCMS.equals("S")) {
if (JOptionPane.showConfirmDialog(this, "Etes-vous sûr de vouloir supprimer ce livre ?", "Confirmation", YES_NO_OPTION)==YES_OPTION){
supprimer();
try{
connection.close();
} catch ( SQLException ex) {
JOptionPane.showMessageDialog(this,"erreur base de données "+ ex.getErrorCode());
}
this.dispose();
}
} else if (modeCMS.equals("M")) {
if (JOptionPane.showConfirmDialog(this, "Etes-vous sûr de vouloir modifier ce livre ?", "Confirmation", YES_NO_OPTION)==YES_OPTION){
modifier();
try{
connection.close();
} catch ( SQLException ex) {
JOptionPane.showMessageDialog(this,"erreur base de données "+ ex.getErrorCode());
}
this.dispose();
}
}
}//GEN-LAST:event_jbtnValiderActionPerformed | 9 |
public FileStorage() {
super();
File citationsFile = new File(serializationFilename);
ObjectInputStream objectInputStream = null;
try {
if (!citationsFile.exists()) {
return;
}
FileInputStream fileInputStream = new FileInputStream(citationsFile);
objectInputStream = new ObjectInputStream(fileInputStream);
List<Citation> citations = (List<Citation>) objectInputStream.readObject();
for (Citation c : citations) {
super.addCitation(c);
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
if (ex instanceof java.io.InvalidClassException) {
citationsFile.delete();
}
System.out.println(ex);
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} finally {
closeStream(objectInputStream);
}
} | 6 |
public T getById(int id) throws SQLException {
Session session = null;
T t = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
t = (T) session.load(this.getRealClass(), id);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Data error", JOptionPane.OK_OPTION);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return t;
} | 3 |
@Override
public void setPerPage(int per_page) {
this.per_page = (per_page > 0) ? per_page : 1;
this.pages = (int) Math.ceil((double) this.rows / (double) this.per_page);
} | 1 |
public String search() {
ProductService productService = new ProductService();
try {
if (this.item.getQuantity() != 0) {
this.searchList = productService.searchProduct(
item.getCategory(), item.getTitle(),
item.getLeadSinger(), item.getQuantity(), searchList);
if (this.searchList.size() == 0)
this.errorMessage = "No items returned in Search";
else
this.errorMessage = "";
} else {
this.errorMessage = "Item Not Added. Please Specify Item Quantity More than 0";
}
} catch (ConnectException e) {
this.errorMessage = e.getMessage();
} catch (SQLException e) {
this.errorMessage = e.getMessage();
}
return "search";
} | 4 |
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
switch(key){
case KeyEvent.VK_D :
br = true;
break;
case KeyEvent.VK_A :
bl = true;
break;
case KeyEvent.VK_W :
bu = true;
break;
case KeyEvent.VK_S :
bd = true;
break;
}
locateDirection();
} | 4 |
public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
DecoderState state = (DecoderState) session.getAttribute(DECODER_STATE_KEY);
if (state == null) {
state = new DecoderState();
session.setAttribute(DECODER_STATE_KEY, state);
}
if (state.image1 == null) {
if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
state.image1 = readImage(in);
} else {
return false;
}
}
if (state.image1 != null) {
if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) {
BufferedImage image = readImage(in);
ImageResponse response = new ImageResponse(state.image1, image);
out.write(response);
state.image1 = null;
return true;
} else {
return false;
}
}
return false;
} | 5 |
private void menuItemNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemNuevoActionPerformed
int change=-1;
if (changed){
change= JOptionPane.showOptionDialog(rootPane, ((currentFile==null)? "El Archivo nuevo": (currentFile.getName() ))
+ " ha sido modificado, ¿Guardar cambios?",
"Advertencia", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
}
switch (change){
case 0:
menuItemGuardarActionPerformed(null);
try{
textPane.getStyledDocument().remove(0, textPane.getStyledDocument().getLength());
updateTitle();
currentFile=null;
status.setText("Nuevo Archivo");
}catch(BadLocationException ble){
status.setText("Operación fallida");
}
break;
case 1:
try{
textPane.getStyledDocument().remove(0, textPane.getStyledDocument().getLength());
updateTitle();
currentFile=null;
status.setText("Nuevo Archivo");
}catch(BadLocationException ble){
status.setText("Operación fallida");
}
break;
case 2:
break;
}
}//GEN-LAST:event_menuItemNuevoActionPerformed | 7 |
@Override
public boolean handleRightClick(Point clickPoint) {
if (this.isActivated()) {
Point mapPoint = new Point(
placeableManager.panelToMapX(clickPoint.x),
placeableManager.panelToMapY(clickPoint.y));
if (currentState == State.Placed) {
if (isInside(mapPoint)) {
if (registry.getPlayerManager().getCurrentPlayer().getCenterPoint().distance(getCenterPoint()) <= 40) {
placeableManager.teleportPlayer(this);
return true;
}
}
}
}
return false;
} | 4 |
public static void main(String[] args) {
System.out.println("Task 5 - Smallest Multiple.\n"
+ "\n2520 is the smallest number that can be divided by each of "
+ "the numbers from 1 to 10 without any remainder.\n"
+ "What is the smallest positive number that is evenly divisible"
+ " by all of the numbers from 1 to 20\n");
boolean divisibleByAll = false;
for (int curNum = 2520; !divisibleByAll; curNum++) {
divisibleByAll = true;
for (int i = 2; i <= 20; i++) {
if (curNum % i != 0) {
divisibleByAll = false;
break;
}
}
if (divisibleByAll) {
System.out.println("The smallest number is: " + curNum);
}
}
} | 4 |
public void updateTicket() {
Database db = dbconnect();
String noEmployee = null;
try {
String query = "UPDATE ticket SET customer_CID = ?, "
+ "employee_EID = ?, CategoryID = ?, "
+ "StatusID = ?, Topic = ?, "
+ "Problem = ?, Note = ?, "
+ "Solution = ?, created_on = ?, "
+ "last_update = ? WHERE TID = ?";
if (this.employee_EID != null) {
noEmployee = this.employee_EID.toString();
}
db.prepare(query);
db.bind_param(1, this.customer_CID.toString());
db.bind_param(2, noEmployee);
db.bind_param(3, this.CategoryID.toString());
db.bind_param(4, this.StatusID.toString());
db.bind_param(5, this.Topic);
db.bind_param(6, this.Problem);
db.bind_param(7, this.Note);
db.bind_param(8, this.Solution);
db.bind_param(9, this.created_on);
db.bind_param(10, this.last_update);
db.bind_param(11, this.TID.toString());
db.executeUpdate();
db.close();
} catch(SQLException e){
Error_Frame.Error(e.toString());
}
} | 2 |
public static String convertJavaStyletoDBConvention( String name )
{
char[] chars = name.toCharArray();
StringBuffer buf = new StringBuffer();
for( int i = 0; i < chars.length; i++ )
{
// if there is a single upper-case letter, then it's a case-word
if( Character.isUpperCase( chars[i] ) )
{
if( (i > 0) && ((i + 1) < chars.length) )
{
if( !Character.isUpperCase( chars[i + 1] ) )
{
buf.append( "_" );
}
}
buf.append( chars[i] );
}
else
{
buf.append( Character.toUpperCase( chars[i] ) );
}
}
return buf.toString();
} | 5 |
public static void main(String[] args) {
Test test=new Test();
} | 0 |
String order(double x, double y, double z ){
String classify = null;
double []store = new double[3];
store[0] = x; store[1] = y; store[2] = z;
classify = (store[0] < store[1] && store[1] < store[2] || store[2] < store[1] && store[1] < store[0]) ?
store[0] < store[1] && store[1] < store[2] ? "increasing" : "decreasing": "no order";
return classify;
} | 6 |
protected void newGame(MouseEvent e, int nx, int nw, int ny, int nh, TicTacToeBoard tb, TicTacToePlayer tp, Main m, LinkedList<Square> SquareStore) {
// new game button
if (tb.getGameOver()) {
if (e.getX() > nx && e.getX() < nx + nw) {
if (e.getY() > ny && e.getY() < ny + nh) {
for (int i = 0; i < 10; i++) {
wipeBoard(tb, tp, SquareStore);
}
}
}
}
} | 6 |
public void selectCell(int r, int c) {
if (this.stateTable && c > this.stateColumn || !this.stateTable && c >= this.inPinCount) {
if (this.cells[r][c].equals("0")) {
this.cells[r][c] = "1";
} else {
this.cells[r][c] = "0";
}
}
} | 5 |
private String prepareConfigString(String configString) {
int lastLine = 0;
int headerLine = 0;
String[] lines = configString.split("\n");
StringBuilder config = new StringBuilder("");
for(String line : lines) {
if(line.startsWith(this.getPluginName() + "_COMMENT")) {
String comment = "#" + line.trim().substring(line.indexOf(":") + 1);
if(comment.startsWith("# +-")) {
/*
* If header line = 0 then it is
* header start, if it's equal
* to 1 it's the end of header
*/
if(headerLine == 0) {
config.append(comment + "\n");
lastLine = 0;
headerLine = 1;
} else if(headerLine == 1) {
config.append(comment + "\n\n");
lastLine = 0;
headerLine = 0;
}
} else {
/*
* Last line = 0 - Comment
* Last line = 1 - Normal path
*/
String normalComment;
if(comment.startsWith("# ' ")) {
normalComment = comment.substring(0, comment.length() - 1).replaceFirst("# ' ", "# ");
} else {
normalComment = comment;
}
if(lastLine == 0) {
config.append(normalComment + "\n");
} else if(lastLine == 1) {
config.append("\n" + normalComment + "\n");
}
lastLine = 0;
}
} else {
config.append(line + "\n");
lastLine = 1;
}
}
return config.toString();
} | 8 |
public void componentResized(ComponentEvent e) {
if (adapt)
transformNeedsReform = true;
repaint();
} | 1 |
public void addUpdatedFilesData(List<String> updatedFiles) {
for (int i = 0; i < updatedFiles.size(); i++) {
try {
Map<String, Set<Flight>> flightCSVData = readCsvAddData(updatedFiles
.get(i));
/*
* Sends every set related to a particular location along with
* the Departure-Arrival key to insert it into the database
*/
for (Map.Entry<String, Set<Flight>> flight : flightCSVData
.entrySet()) {
FlightData.insertCsvFileData(flight.getKey(), flight.getValue());
}
} catch (NewCustomException exception) {
exception.printMessage();
}
}
} | 3 |
public void setDates(String start, String end) {
this.dates = start + " - " + ((end == null || end.equalsIgnoreCase("null")) ? "no end" : end);
} | 2 |
private String readFileAsString(String filename) throws Exception {
StringBuilder source = new StringBuilder();
FileInputStream in = new FileInputStream(filename);
Exception exception = null;
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Exception innerExc = null;
try {
String line;
while ((line = reader.readLine()) != null)
source.append(line).append('\n');
} catch (Exception exc) {
exception = exc;
} finally {
try {
reader.close();
} catch (Exception exc) {
if (innerExc == null)
innerExc = exc;
else
exc.printStackTrace();
}
}
if (innerExc != null)
throw innerExc;
} catch (Exception exc) {
exception = exc;
} finally {
try {
in.close();
} catch (Exception exc) {
if (exception == null)
exception = exc;
else
exc.printStackTrace();
}
if (exception != null)
throw exception;
}
return source.toString();
} | 9 |
public void run() {
while (true) {
// cambio de colision y actualiza
actualiza();
checaColision();
repaint(); // Se actualiza el <code>JFrame</code> repintando el contenido.
try {
// El thread se duerme.
Thread.sleep(80);
} catch (InterruptedException ex) {
System.out.println("Error en " + ex.toString());
}
}
} | 2 |
private String setParam(int columnType) {
if (columnType == java.sql.Types.INTEGER) {
return "Int";
} else if (columnType == java.sql.Types.VARCHAR || columnType == java.sql.Types.CHAR) {
return "String";
} else if (columnType == java.sql.Types.TIMESTAMP) {
return "Timestamp";
} else if (columnType == java.sql.Types.DATE) {
return "Date";
} else if (columnType == java.sql.Types.DOUBLE || columnType == java.sql.Types.NUMERIC) {
return "BigDecimal";
} else if (columnType == java.sql.Types.BOOLEAN) {
return "Boolean";
}
return "nao_identificado";
} | 8 |
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.