text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@BeforeClass
public static void setUpBeforeClass() {
try {
String localTestProperty = System
.getProperty(BookStoreConstants.PROPERTY_KEY_LOCAL_TEST);
localTest = (localTestProperty != null) ? Boolean
.parseBoolean(localTestProperty) : localTest;
if (localTest) {
CertainBookStore store = new CertainBookStore();
storeManager = store;
client = store;
} else {
storeManager = new ReplicationAwareStockManagerHTTPProxy();
client = new ReplicationAwareBookStoreHTTPProxy();
}
storeManager.removeAllBooks();
} catch (Exception e) {
e.printStackTrace();
}
} | 3 |
public Medicine findMedicine(int id) {
String query = "SELECT * FROM `medicine` WHERE `id` = %d LIMIT 1;";
Utils.DBA dba = Helper.getDBA();
Medicine m = new Medicine();
try {
ResultSet rs = dba.executeQuery(String.format(query, id));
rs.next();
m.setID(rs.getInt("id"));
m.setName(rs.getString("name"));
m.setCost(rs.getInt("cost"));
} catch (SQLException sqlEx) {
Helper.logException(sqlEx);
}
return m;
} | 1 |
public static long convertUnitToOrigByte(String unitByte) {
if (isEmpty(unitByte)) return 0;
unitByte = unitByte.toUpperCase();
// , 제거
unitByte = unitByte.replace(",", "");
String regx = "^\\p{Digit}+(K|KB|M|MB|G|GB)?$";
if (!unitByte.matches(regx)) return 0;
long origByte = parseLong(strainNumber(unitByte));
if (unitByte.endsWith("K") || unitByte.endsWith("KB")) {
origByte = origByte * 1024;
} else if (unitByte.endsWith("M") || unitByte.endsWith("MB")) {
origByte = origByte * 1024 * 1024;
} else if (unitByte.endsWith("G") || unitByte.endsWith("GB")) {
origByte = origByte * 1024 * 1024 * 1024;
}
return origByte;
} | 8 |
public boolean func_48647_a(PathEntity par1PathEntity)
{
if (par1PathEntity == null)
{
return false;
}
else if (par1PathEntity.points.length != this.points.length)
{
return false;
}
else
{
for (int var2 = 0; var2 < this.points.length; ++var2)
{
if (this.points[var2].xCoord != par1PathEntity.points[var2].xCoord || this.points[var2].yCoord != par1PathEntity.points[var2].yCoord || this.points[var2].zCoord != par1PathEntity.points[var2].zCoord)
{
return false;
}
}
return true;
}
} | 6 |
private void register() {
if (brokerUrl == null
|| registryId == null
|| (System.currentTimeMillis() - lastRegistered > 10 * 1000)) {
Response response = null;
if(getType().equals("producer")){
response = Announce.callAsProducer(getLocation());
} else {
response = Announce.callAsConsumer(registryId, brokerUrl, getLocation(), ((Consumer)this).interestRadius);
}
if(response != null){
JSONObject obj = (JSONObject) JSONValue.parse(response.body);
this.registryId = (String)obj.get("consumer_id");
this.brokerUrl = (String)obj.get("broker_url");
if(brokerUrl != null){
brokerUrl = brokerUrl.substring(7, brokerUrl.length()-1);
}
}
lastRegistered = System.currentTimeMillis();
}
if (getType().equals("consumer") && registryId ==null) {
System.err.println("Error getting consumerId "+getType()+" "+name+" from registery");
}
if (brokerUrl == null) {
System.err.println("Error getting brokerUrl "+getType()+" "+name+" with registery");
}
} | 9 |
@Override
public void mouseMoved(MouseEvent event) {
if (isEnabled()) {
Row rollRow = null;
try {
boolean local = event.getSource() == this;
int x = event.getX();
int y = event.getY();
Row rowHit;
Column column;
Cursor cursor = Cursor.getDefaultCursor();
if (overColumnDivider(x) != null) {
if (allowColumnResize()) {
cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
}
} else if (local) {
column = overColumn(x);
if (column != null) {
rowHit = overRow(y);
if (rowHit != null) {
if (overDisclosureControl(x, y, column, rowHit)) {
rollRow = rowHit;
} else {
Cell cell = column.getRowCell(rowHit);
cursor = cell.getCursor(event, getCellBounds(rowHit, column), rowHit, column);
}
}
}
}
setCursor(cursor);
} finally {
repaintChangedRollRow(rollRow);
}
}
} | 7 |
public void setType(Type otherType) {
Type newType = otherType.intersection(type);
if (type.equals(newType))
return;
if (newType == Type.tError && otherType != Type.tError) {
GlobalOptions.err.println("setType: Type error in " + this
+ ": merging " + type + " and " + otherType);
if (parent != null)
GlobalOptions.err.println("\tparent is " + parent);
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0)
Thread.dumpStack();
}
type = newType;
if (type != Type.tError)
updateSubTypes();
} | 6 |
public void changeCellType(int x, int y, CellType selectedMode, boolean delete) {
Cell cell = getCell(x, y);
switch (selectedMode) {
case FOOD:
if (cell.getType().equals(CellType.FOOD)) {
cell.setType(CellType.SPACE);
} else {
cell.setType(CellType.FOOD);
}
break;
case ANTHILL:
Cell antHill = getAnthillCell();
if (antHill != null) {
antHill.setType(CellType.SPACE);
}
cell.setType(CellType.ANTHILL);
break;
case BARRIER:
CellType type = cell.getType();
if (type.equals(CellType.SPACE)) {
cell.setType(CellType.BARRIER);
} else if (delete && type.equals(CellType.BARRIER)) {
cell.setType(CellType.SPACE);
}
break;
default:
}
} | 8 |
private void sendData( String message )
{
try // send object to server
{
output.writeObject( "CLIENT>>> " + message );
output.flush(); // flush data to output
System.out.println( "\nCLIENT>>> " + message );
} // end try
catch ( IOException ioException )
{
// displayArea.append( "\nError writing object" );
} // end catch
} // end method sendData | 1 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vector3f vector3f = (Vector3f) o;
if (Float.compare(vector3f.x, x) != 0) return false;
if (Float.compare(vector3f.y, y) != 0) return false;
if (Float.compare(vector3f.z, z) != 0) return false;
return true;
} | 6 |
Pakkit(Plugin plugin) {
this.plugin = plugin;
final String serverPackage = this.plugin.getServer().getClass().getPackage().getName();
final String version = serverPackage.substring(serverPackage.lastIndexOf('.') + 1);
try {
this.craftPlayer = Class.forName(serverPackage + ".entity.CraftPlayer");
this.getHandle = this.craftPlayer.getMethod("getHandle");
this.entityPlayerClass = this.getHandle.getReturnType();
this.playerConnectionField = this.entityPlayerClass.getField("playerConnection");
this.playerConnectionField.setAccessible(true);
this.playerConnectionClass = this.playerConnectionField.getType();
this.networkManagerField = this.playerConnectionClass.getField("networkManager");
this.networkManagerField.setAccessible(true);
this.networkManagerClass = this.networkManagerField.getType();
for (final Field field : this.networkManagerClass.getDeclaredFields()) {
if (field.getType().equals(Channel.class)) {
this.channelFields.add(field);
field.setAccessible(true);
}
}
if (this.channelFields.isEmpty()) {
throw new Exception("NO CHANNELS IN NETWORK MANAGER OMG");
}
} catch (final Exception e) {
plugin.getLogger().log(Level.SEVERE, "Could not start, unknown stuffs", e);
return;
}
for (final Map.Entry<String, Object> entry : plugin.getConfig().getValues(false).entrySet()) {
if (entry.getValue() instanceof ConfigurationSection) {
Class<?> clazz;
try {
clazz = Class.forName("net.minecraft.server." + version + "." + entry.getKey());
} catch (final ClassNotFoundException e) {
plugin.getLogger().info("Ignoring entry " + entry.getKey());
continue;
}
final ConfigurationSection pac = (ConfigurationSection) entry.getValue();
this.packets.put(clazz, new PakkitPacket(clazz, pac.getBoolean("enabled", false), pac.getBoolean("full", true)));
}
}
plugin.getCommand("pakkit").setExecutor(new Command(this));
plugin.getServer().getPluginManager().registerEvents(this, plugin);
for (final Player player : plugin.getServer().getOnlinePlayers()) {
this.inject(player);
}
} | 9 |
* @param output
*/
public static void translateLoomFile(String input, String output) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
Object old$PrintprettyP$000 = Stella.$PRINTPRETTYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Native.setBooleanSpecial(Stella.$PRINTPRETTYp$, true);
{ InputFileStream in = null;
try {
in = Stella.openInputFile(input, Stella.NIL);
{ OutputFileStream out = null;
try {
out = Stella.openOutputFile(output, Stella.NIL);
{ Cons translation = Stella.NIL;
SExpressionIterator iter = InputStream.sExpressions(in);
Stella_Object form = Logic.safeGetNextSExpression(iter);
boolean dialectEmittedP = false;
{
out.nativeStream.println(";; Automatic Translation for file " + input);
out.nativeStream.println();
}
;
while (form != null) {
translation = Logic.translateOneLoomForm(form);
if (translation == null) {
}
else if (translation == Stella.NIL) {
}
else if (Stella_Object.isaP(translation.value, Logic.SGT_STELLA_CONS)) {
dialectEmittedP = true;
{
out.nativeStream.println(Cons.list$(Cons.cons(Logic.SYM_LOGIC_IN_DIALECT, Cons.cons(Logic.KWD_KIF, Cons.cons(Stella.NIL, Stella.NIL)))));
out.nativeStream.println();
}
;
{ Stella_Object subform = null;
Cons iter000 = translation;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
subform = iter000.value;
{
out.nativeStream.println(subform);
out.nativeStream.println();
}
;
}
}
}
else {
if ((!dialectEmittedP) &&
(!(translation.value == Logic.SYM_STELLA_IN_MODULE))) {
dialectEmittedP = true;
{
out.nativeStream.println(Cons.list$(Cons.cons(Logic.SYM_LOGIC_IN_DIALECT, Cons.cons(Logic.KWD_KIF, Cons.cons(Stella.NIL, Stella.NIL)))));
out.nativeStream.println();
}
;
}
{
out.nativeStream.println(translation);
out.nativeStream.println();
}
;
}
form = Logic.safeGetNextSExpression(iter);
}
}
} finally {
if (out != null) {
out.free();
}
}
}
} finally {
if (in != null) {
in.free();
}
}
}
} finally {
Stella.$PRINTPRETTYp$.set(old$PrintprettyP$000);
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
} | 9 |
public void UpdateLevelConditions() {
if (TimeMet() && TimePrimary) {
if (RequiredMet()) {
gameCondition = 2;
}
gameCondition = 3;
return;
} else if (RequiredMet()) {
gameCondition = 2;
} else if (p.health < 0) {
gameCondition = 3;
} else if (AnySecondaryMet()) {
gameCondition = 2;
} else {
gameCondition = 1;
}
} | 6 |
public void loadFromFile(File f) {
try {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(f));
Osoba osoba = null;
while((osoba = (Osoba) inputStream.readObject()) != null){
data.addElement(osoba);
}
inputStream.close();
fireTableDataChanged();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} | 5 |
public static void writeAverageMetrics(String outputFile, int k, double size, boolean calcTags, boolean endLine) {
try {
FileWriter writer = new FileWriter(new File("./data/metrics/" + outputFile + "_avg.txt"), true);
BufferedWriter bw = new BufferedWriter(writer);
double recall = recallSum / size;
double precision = precisionSum / size;
bw.write(Double.toString(recall).replace('.', ',') + ";");
bw.write(Double.toString(precision).replace('.', ',') + ";");
//bw.write(Double.toString((fMeasureSum / size)).replace('.', ',') + ";");
bw.write(Double.toString(2.0 * recall * precision / (recall + precision == 0 ? 1.0 : recall + precision)).replace('.', ',') + ";");
bw.write(Double.toString((mrrSum / size)).replace('.', ',') + ";");
bw.write(Double.toString((mapSum / size)).replace('.', ',') + ";");
bw.write(Double.toString((nDCGSum / size)).replace('.', ',') + ";");
bw.write(Double.toString((userCoverageSum / size)).replace('.', ','));
if (!calcTags) {
bw.write(";");
bw.write(Double.toString((diversitySum / size)).replace('.', ',') + ";");
bw.write(Double.toString((serendipitySum / size)).replace('.', ',') + ";");
}
if (endLine)
bw.write("\n");
bw.write("\n");
bw.close();
resetMetrics();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public FillFrame(DataStore DS) {
this.ds = DS;
this.setBounds(100, 100, 450, 300);
this.pane = new JPanel();
this.setContentPane(pane);
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
JLabel lblTraitementDesErreurs = new JLabel("Traitement des erreurs :");
lblTraitementDesErreurs.setAlignmentX(Component.CENTER_ALIGNMENT);
pane.add(lblTraitementDesErreurs);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
pane.add(panel);
final JRadioButton rdbtnIgnorer = new JRadioButton("Ignorer");
final JRadioButton rdbtnArrter = new JRadioButton("Arrêter");
final JRadioButton rdbtnRsoudre = new JRadioButton("Résoudre");
this.btnGroup = new ButtonGroup();
btnGroup.add(rdbtnArrter);
btnGroup.add(rdbtnIgnorer);
btnGroup.add(rdbtnRsoudre);
btnGroup.setSelected(rdbtnRsoudre.getModel(), true);
panel.add(rdbtnIgnorer);
panel.add(rdbtnArrter);
panel.add(rdbtnRsoudre);
this.btnLancer = new JButton("Lancer");
btnLancer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int mode = rdbtnArrter.isSelected() ? Filler.ABORT : rdbtnIgnorer.isSelected() ? Filler.IGNORE : Filler.RETRY;
txtrResultats.setText("");
File log = new File("temp.log");
PrintStream ps = new PrintStream(log);
Filler fill = new Filler(new TextAreaPrintStream(txtrResultats, ps), ds);
//fill.setMode(mode);
System.out.println("FillFrame.startFilling()");
fill.fill(fill.computeConstraints(true), mode);
System.out.println("FillFrame.endFilling()");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
pane.remove(btnLancer);
pane.add(btnQuitter);
}
});
pane.add(btnLancer);
this.btnQuitter = new JButton("Quitter");
btnQuitter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
panel_1.setAlignmentX((float)0.5);
pane.add(panel_1);
panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
this.lblConsole = new JLabel(">>> Console :");
this.lblConsole.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {
toggleShowOutPut();
}
});
lblConsole.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
toggleShowOutPut();
}
});
lblConsole.setHorizontalAlignment(SwingConstants.LEFT);
panel_1.add(lblConsole);
this.txtrResultats = new JTextArea();
txtrResultats.addNotify();
txtrResultats.setText("Résultats :");
panel_1.add(txtrResultats);
rdbtnRsoudre.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
}
});
setVisible(true);
} | 3 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSoba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSoba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSoba.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSoba.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 EkranZaPracenjeRaspolozivostiSoba().setVisible(true);
}
});
} | 6 |
public RowUndoSnapshot(Row row) {
mParent = row.getParent();
mOpen = row.isOpen();
mChildren = row.canHaveChildren() ? new ArrayList<>(row.getChildren()) : null;
} | 1 |
public Boolean dropGraph(String graphURI) {
this.dropGraphs.add(graphURI);
if(this.autoCommit){
//TODO ändern!!!
this.beginTransaction();
Boolean ret = this.commit();
this.endTransaction();
if(ret){
this.dropGraphs.clear();
}
return ret;
}
return null;
} | 2 |
public static int[][] loadColors(String filename) throws FileNotFoundException{
int[][] colors = new int[COLORDEPTH][3];
if (filename.equals("")){
return null;
}
File colorFile = new File("src" + File.separator + "mnd" + File.separator + filename);
if(!colorFile.exists()){
System.out.print("Invalid filename! Mandelbrot is drawn without colors");
JOptionPane.showMessageDialog(null,"Invalid filename! Mandelbrot is drawn without colors","No such file!",JOptionPane.WARNING_MESSAGE);
return null;
}
Scanner fileScanner = new Scanner(colorFile);
//The following code assumes a properly formatted color file
for (int i=0; i<COLORDEPTH; i++){
for (int j=0; j<3; j++){
if (fileScanner.hasNextInt()){
colors[i][j]=fileScanner.nextInt();
}
}
}
fileScanner.close();
return colors;
} | 5 |
public VuePraticiens(CtrlAbstrait ctrlA) {
super(ctrlA);
initComponents();
} | 0 |
public void setB(float b) {
this.b = b;
} | 0 |
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
if(subMenu){
if(menuSelect==0)
if(newFileMenu)
if(l.mouseSelect(244, 170, 152, 28))
if(Mouse.isButtonDown(0))
sbg.enterState(1);
}
gc.setFullscreen(Main.fullScreen);
AppGameContainer appgc = (AppGameContainer) gc;
mr.function(appgc);
} | 5 |
public Object get(int index) throws JSONException {
Object object = this.opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
return object;
} | 1 |
private ExtendedModInfo examinePathForMod(IDirectory dir) {
String path = dir.getPath();
String modMainFile = findModMainClassFilePath(dir);
if(modMainFile == null) {
return null;
}
if(!dir.exists(modMainFile.replace('.', '/'))) {
log.err("Directory[" + dir.getPath() + "] does not contain the mod class \"" + modMainFile + "\"!");
return null;
}
log.info("Found modfile \"" + dir.getPath(modMainFile) + "\"");
for(ExtendedModInfo modi : modList) {
if(modi.getModPath().equals(path)) {
return modi;
}
}
log.info("Was not on the list! Gather information...");
ClassLoader loader = new TWClassLoader(dir);
Class<?> plainClass = null;
Class<? extends IMod> mainModClass = null;
try {
plainClass = loader.loadClass(modMainFile);
mainModClass = plainClass.asSubclass(IMod.class);
} catch (ClassNotFoundException e) {
log.err("Failed to load mod main class!");
log.excp(e);
return null;
} catch(ClassCastException e) {
log.crit("Was able to load mod main class, but main class does not implements the tradewar.api.IMod interface!");
log.excp(e);
return null;
}
// Constructor<? extends IMod> ctors = mainModClass.getConstructors();
return null;
} | 8 |
private Padding10() {
} | 0 |
private static JComponent[] copy(JComponent[] c) {
JComponent[] newArray = new JComponent[c.length];
for (int a = 0; a < c.length; a++) {
newArray[a] = c[a];
}
return newArray;
} | 1 |
public void run() {
setSizeField();
array = new ButtonArray(field.sizeField);
setBounds(500, 300, 500, 500);
this.setLayout(new GridLayout(field.sizeField, field.sizeField, 5, 5));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
field.initField();
Check check = new Check();
for (int i = 0; i < field.sizeField; i++) {
for (int j = 0; j < field.sizeField; j++) {
this.add(array.getButton(i, j));
array.getButton(i,j).addActionListener(new ButActListener());
}
}
setVisible(true);
} | 2 |
public boolean getBoolean(String key) throws JSONException {
Object o = get(key);
if(o==null) return false;
if (o.equals(Boolean.FALSE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("false"))) {
return false;
} else if (o.equals(Boolean.TRUE) ||
(o instanceof String &&
((String)o).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
} | 7 |
public void visitTryCatchBlock(
final Label start,
final Label end,
final Label handler,
final String type)
{
buf.setLength(0);
buf.append(tab2).append("TRYCATCHBLOCK ");
appendLabel(start);
buf.append(' ');
appendLabel(end);
buf.append(' ');
appendLabel(handler);
buf.append(' ');
appendDescriptor(INTERNAL_NAME, type);
buf.append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitTryCatchBlock(start, end, handler, type);
}
} | 1 |
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} | 7 |
public int search(char[] word) {
int i, j, k;
ST_NODE tmpnode = new ST_NODE();
ST_NODE rnode = null;
int child;
byte cs;
for (i = 0, j = 0; j < word.length && i < this.search_end; i++) {
if (word[j] == this.search_word[i])
j++;
else break;
}
this.search_end = i;
if (this.search_end == 0 ) {
cs = this.head.s_node.CS;
child = this.head.s_node.child;
} else {
child = this.search_idx[this.search_end-1];
cs = this.nf[child].node.CS;
child = this.nf[child].node.child;
}
while (j < word.length && cs != 0) {
tmpnode.K=word[j];
rnode = null;
for (k = child; k < child + cs; k++){
if (tmpnode.K == this.nf[k].node.K){
rnode = this.nf[k].node;
break;
}
}
if (rnode == null) break;
else {
this.search_word[this.search_end] = word[j];
this.search_idx[this.search_end] = k;
this.search_end++;
j++;
child = this.nf[k].node.child;
cs = this.nf[k].node.CS;
}
}
return this.search_end;
} | 9 |
public static long arrayPositiveElementsSum(long[]array){
long sum = 0L;
for(long i:array)if(i>0)sum += i;
return sum;
} | 2 |
@SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
long lall = 0, tall = 0;
int[] efforts = {1, 50, 100};
for(int effort : efforts) {
for(File f : new File("resources/testdata/").listFiles()) {
RandomAccessFile raf = new RandomAccessFile(f, "r");
byte[] data = new byte[(int) raf.length()];
raf.readFully(data);
Buffer b = new Buffer();
long l = 0, m = 0;
int iterations = 5;
long t0 = System.nanoTime();
for(int i=0; i<iterations; i++) {
m += SnappyCompressor.compress(data, 0, data.length, b, effort).getLength();
l += data.length;
}
long t1 = System.nanoTime();
lall += l;
tall += (t1-t0);
// System.out.println(f.getName() + ": " + String.format("%.2f", (l * 1000000000. / (t1-t0))/(1024*1024)));
}
System.out.println("all (" + effort + "): " + String.format("%.2f", (lall * 1000000000. / (tall))/(1024*1024)));
}
} | 3 |
public int CheckSmithing(int ItemID, int ItemSlot) {
boolean GoFalse = false;
int Type = -1;
if (IsItemInBag(2347) == false) {
sendMessage("You need a "+GetItemName(2347)+" to hammer bars.");
return -1;
}
switch (ItemID) {
case 2349: //Bronze Bar
Type = 1;
break;
case 2351: //Iron Bar
Type = 2;
break;
case 2353: //Steel Bar
Type = 3;
break;
case 2359: //Mithril Bar
Type = 4;
break;
case 2361: //Adamantite Bar
Type = 5;
break;
case 2363: //Runite Bar
Type = 6;
break;
default:
sendMessage("You cannot smith this item.");
GoFalse = true;
break;
}
if (GoFalse == true) {
return -1;
}
return Type;
} | 8 |
private void unfilterPaeth(byte[] curLine, byte[] prevLine) {
final int bpp = this.bytesPerPixel;
int i;
for(i=1 ; i<=bpp ; ++i) {
curLine[i] += prevLine[i];
}
for(int n=curLine.length ; i<n ; ++i) {
int a = curLine[i - bpp] & 255;
int b = prevLine[i] & 255;
int c = prevLine[i - bpp] & 255;
int p = a + b - c;
int pa = p - a; if(pa < 0) pa = -pa;
int pb = p - b; if(pb < 0) pb = -pb;
int pc = p - c; if(pc < 0) pc = -pc;
if(pa<=pb && pa<=pc)
c = a;
else if(pb<=pc)
c = b;
curLine[i] += (byte)c;
}
} | 8 |
private SceneObject getAt(final Tile tile) {
final SceneObject[] locations = SceneEntities.getLoaded(tile);
return locations.length > 0 ? locations[0] : null;
} | 1 |
public static void main(String[] args){
int[] dimension = {30,1,40,10,25};
// method 1
int min = CMMNo(dimension);
System.out.println(min);
// method 2
int[][] array = new int[dimension.length-1][dimension.length-1];
String[][] sequence = new String[dimension.length-1][dimension.length-1];
for(int i = 0; i < dimension.length-1; i++){
array[i][i] = 0;
sequence[i][i] = "" + i;
}
for(int i = 0; i < dimension.length-1; i++){
for(int j = i+1; j < dimension.length-1; j++){
array[i][j] = Integer.MAX_VALUE;
sequence[i][j] = "";
}
}
int min2 = CMM2(dimension, array, sequence, 0, dimension.length-1-1);
System.out.println(min2);
System.out.println(sequence[0][dimension.length-1-1]);
} | 3 |
public void update(Avatar player, Map map, long gameTime) {
if (!isOutOfScreen) {
if (!canFall) {
Rectangle2D rectplayer = new Rectangle2D.Float(player.getX(),
player.getY(), 18, 18);
Rectangle2D thisrect = new Rectangle2D.Float(x - 1, y - 1, 19,
19);
if (rectplayer.intersects(thisrect)) {
canFall = true;
time = gameTime;
}
} else if (gameTime - time > (0.3 * Framework.secInNanosec)) {
if (!isFalling) {
isFalling = true;
map.removeTile(tilePositon);
} else
fall();
}
if (y > 340)
isOutOfScreen = true;
}
} | 6 |
public static boolean withinRange(int objectType, int objectX, int objectY, int playerX, int playerY, int atHeight)
{
if(objectSizes.size() == 0)
loadObjectSizes();
int sizeX = 1;
int sizeY = 1;
if(objectSizes.get(objectType) != null)
{
sizeX = objectSizes.get(objectType)[0];
sizeY = objectSizes.get(objectType)[1];
}
int face = getOrientation(objectX, objectY, atHeight);
if(face == 1 || face == 3)
{
int tempX = sizeX;
sizeX = sizeY;
sizeY = tempX;
}
java.awt.Rectangle objectField = new java.awt.Rectangle(objectX, objectY, sizeX, sizeY);
java.awt.Rectangle playerField = new java.awt.Rectangle(objectX - 1, (objectY - 1), (sizeX + 2), (sizeY + 2));
return playerField.contains(playerX, playerY) && !objectField.contains(playerX, playerY);
} | 5 |
public void run() {
// signal that this thread has started
threadStarted();
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// if getTask() returned null or was interrupted,
// close this thread.
if (task == null) {
break;
}
// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
// signal that this thread has stopped
threadStopped();
} | 4 |
private static void modRest(int decisio){
int opcio = 0;
while( opcio != 7 ) {
opcio = 0;
if(decisio == 1)System.out.println(" Indica el tipus de restriccio a modificar ");
if(decisio == 2)System.out.println(" Indica el tipus de restriccio a esborrar ");
System.out.println(" 1 - Restringir un grup a una aula");
System.out.println(" 2 - Restringir un grup a un dia i hora");
System.out.println(" 3 - Restringir una hora en la que no es pugui impartir una asignatura+grup");
System.out.println(" 4 - Restringir un dia per a que no es pugu impartir una assig+grup");
System.out.println(" 5 - Una assig+grup no es pot impartir a la vegada que una altre temporalmente parlant");
System.out.println(" 6 - Forzar una aula a no poderse usar un dia/hora");
System.out.println(" 7 - Tornar");
while(1>opcio || opcio>7){opcio = s.nextInt();if(1>opcio || opcio>7) System.out.println("valor no valid. Torna a seleccinar");}
switch (decisio) {
case 1: modificarRest(opcio);
break;
case 2: esborrarRest(opcio);
break;
}
}
} | 9 |
public void onUserLogout(NetworkSharedUser user) {
if(thisUser == null) return;
if(privateChats.get(user.getId()) != null) {
privateChats.get(user.getId()).userDisconnected(user.getName());
}
globalChat.addText(user.getName() + " has logged out.");
model.removeElement(user.getName());
} | 2 |
private void doWalk(Ant ant) {
//set reachable and shuffle it
ACOUtil.changeReachable(reachable, 0);
ACOUtil.shuffleArray(reachable, rand);
ant.setWorkUnitIndex(0, reachable[0]);
for (int step = 1; step < indexes.length; step++) {
//1]
int previousIndex = ant.getWorkUnitIndex(step-1);
//2] compute probabilities for next step
double probabilitySum = 0.0;
for (int candidate = step%subProjectActivities;
candidate < reachable.length; candidate++) {
int workIndex = reachable[candidate];
probabilities[workIndex] =
Math.pow(trails[previousIndex][workIndex], α) *
heuristics[previousIndex][workIndex];
probabilitySum += probabilities[workIndex];
}
//3] normalize probabilities
for (int candidate = step%subProjectActivities;
candidate < reachable.length; candidate++) {
int workIndex = reachable[candidate];
probabilities[workIndex] = probabilities[workIndex] / probabilitySum;
}
//4] next step selection
double number = rand.nextDouble();
probabilitySum = 0.0;
int selectedCandidate = -1;
for (int candidate = step%subProjectActivities;
candidate < reachable.length; candidate++) {
int workIndex = reachable[candidate];
probabilitySum += probabilities[workIndex];
if (number <= probabilitySum) {
selectedCandidate = candidate;
break;
}
}
//5]
if (selectedCandidate == -1) {
selectedCandidate = reachable.length-1;
}
int tmp = reachable[step%subProjectActivities];
reachable[step%subProjectActivities] = reachable[selectedCandidate];
reachable[selectedCandidate] = tmp;
ant.setWorkUnitIndex(step, reachable[step%subProjectActivities]);
//6] goto activities of other subproject
if ((step+1) % subProjectActivities == 0) {
ACOUtil.changeReachable(reachable, step+1);
ACOUtil.shuffleArray(reachable, rand);
}
}
//evaluate ant solution
ant.evaluate();
} | 7 |
protected static boolean isWrapperClass(String name) {
return name.equals("java.lang.Integer")
|| name.equals("java.lang.Long")
|| name.equals("java.lang.Short")
|| name.equals("java.math.BigInteger")
|| name.equals("java.math.BigDecimal")
|| name.equals("java.lang.Float")
|| name.equals("java.lang.Double")
|| name.equals("java.lang.Byte")
|| name.equals("java.lang.Boolean")
|| name.equals("java.lang.Character");
} | 9 |
public void update(){
if(speedX <0){
centerX += speedX;
}
if(speedX ==0 || speedX < 0){
bg1.setSpeedX(0);
bg2.setSpeedX(0);
}
if(centerX<=200 && speedX > 0){
centerX += speedX;
}//end scrolling else
if(centerY + speedY >=GROUND){
centerY = GROUND;
}
if(jumped==true){
speedY+=1;
if(centerY+speedY >=GROUND){
centerY = GROUND;
speedY = 0;
jumped = false;
}
}
//prevents going beyond zero
if(centerX + speedX<=60){
centerX = 61;
}
}//end update | 9 |
protected void paintComponent(Graphics g) {
if (isOpaque()) {
Dimension size = getSize();
g.setColor(getBackground());
g.fillRect(0, 0, size.width, size.height);
}
int stepSize = 0;
int cDist = 0;
int rDist = 0;
for (int vectorIndex = 0; vectorIndex < resultVector.size(); vectorIndex++) {
double coreDistance = ((DataObject) resultVector.elementAt(vectorIndex)).getCoreDistance();
double reachDistance = ((DataObject) resultVector.elementAt(vectorIndex)).getReachabilityDistance();
if (coreDistance == DataObject.UNDEFINED)
cDist = getHeight();
else
cDist = (int) (coreDistance * verticalAdjustment);
if (reachDistance == DataObject.UNDEFINED)
rDist = getHeight();
else
rDist = (int) (reachDistance * verticalAdjustment);
int x = vectorIndex + stepSize;
if (isShowCoreDistances()) {
/**
* Draw coreDistance
*/
g.setColor(coreDistanceColor);
g.fillRect(x, getHeight() - cDist, widthSlider, cDist);
}
if (isShowReachabilityDistances()) {
int sizer = widthSlider;
if (!isShowCoreDistances()) sizer = 0;
/**
* Draw reachabilityDistance
*/
g.setColor(reachabilityDistanceColor);
g.fillRect(x + sizer, getHeight() - rDist, widthSlider, rDist);
}
if (isShowCoreDistances() && isShowReachabilityDistances()) {
stepSize += (widthSlider * 2);
} else
stepSize += widthSlider;
}
} | 9 |
protected int sync_header(byte [] stream){
int offset = 0;
for(; offset < stream.length; offset++)
if(stream[offset] == -1 &&
((stream[offset+1] & 0xf0) >>> 4)
== 0xf && (stream[offset+1]&0xf ) != 0xf)
break;
return offset;
} | 4 |
public static String loadFile(String filePath)
{
String result = "";
FileInputStream inputStream = null;
DataInputStream dataInputStream = null;
StringBuilder stringBuilder = new StringBuilder();
String charset = "";
try
{
inputStream = new FileInputStream(filePath);
String line = "";
byte[] array = IOUtils.toByteArray(inputStream);
charset = guessEncoding(array);
if (charset.equalsIgnoreCase("WINDOWS-1252"))
{
charset = "CP1252";
}
inputStream = new FileInputStream(filePath);
dataInputStream = new DataInputStream(inputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, charset));
while ((line = bufferedReader.readLine()) != null)
{
if (stringBuilder.length() > 0)
{
stringBuilder.append("\n");
}
stringBuilder.append(line);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
_logger.fatal(e.getMessage(), e);
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
_logger.fatal(e.getMessage(), e);
e.printStackTrace();
}
finally
{
if (dataInputStream != null)
{
try
{
dataInputStream.close();
}
catch (IOException e)
{
_logger.fatal(e.getMessage(), e);
e.printStackTrace();
}
result = stringBuilder.toString();
}
}
return result;
} | 7 |
public int findFreeNumSmallMemory(File file, final int blocksCount, final int blockSize) throws IOException {
final int vector_item_size = 32; //because we use int
int freeBlock;
if ((freeBlock = findFreeBlock(file, blocksCount, blockSize)) != -1) {
//find free num in block: read from file
int[] bitVector = new int[blockSize / vector_item_size];
try (Scanner sc = new Scanner(new FileInputStream(file));) {
int num;
while (sc.hasNextInt() && (num = sc.nextInt()) >= 0) {
if (blockIndex(num, blockSize) == freeBlock) {
num = num % blockSize;
bitVector[num / vector_item_size] |= 1 << (num % vector_item_size);
}
}
}
//find free num in bitVector
for (int i = 0; i < bitVector.length; i ++) {
if (bitVector[i] != 0xFFFFFFFF) { //has free space
for (int j = 0; j < vector_item_size; j ++) {
if ((bitVector[i] & (1 << j)) == 0) {
return freeBlock * blockSize + i * vector_item_size + j;
}
}
}
}
}
return -1; // no result
} | 8 |
public boolean removeVertex(final City city) {
int index = getIndex(city);
if (index < 0) {
return false;
} else {
cities[index] = null;
}
for (int i = 0; i < edges.length; i++) {
if (i == index) {
edges[index] = new int[edges[index].length];
} else {
for (int x = 0; x < edges[i].length; x++) {
if (x == index) {
edges[i][x] = 0;
}
}
}
}
currentSize--;
defragment();
return true;
} | 5 |
private static boolean isLocalMax(double[] frequencyData, int i) {
if (i - 1 < 0 || i + 1 >= frequencyData.length)
return false;
double left = frequencyData[i - 1];
double mid = frequencyData[i];
double right = frequencyData[i + 1];
if (right < mid && mid > left)
return true;
return false;
} | 4 |
private Color getPColor(Player p){
if(p instanceof White ){
return Color.WHITE;
}
else if(p instanceof Green){
return Color.GREEN;
}
else if(p instanceof Peacock){
return Color.BLUE;
}
else if(p instanceof Plum){
return Color.pink;
}
else if(p instanceof Scarlett){
return Color.RED;
}
return Color.yellow;
} | 5 |
private void fillHighScore(){
scores = Database.DatabaseInstance.fillTopScores(singlePlayer);
for(ScoreUser score : scores){
usernameLabel = new JLabel(score.getUserName());
usernameLabel.setForeground(Color.white);
toReturnPanel.add(usernameLabel);
scoreLabel = new JLabel("" + score.getScore());
scoreLabel.setForeground(Color.white);
toReturnPanel.add(scoreLabel);
}
if (scores.size() > 0 && scores.size() < 5) {
for (int i = 0; i < (5-scores.size()); i++) {
usernameLabel = new JLabel("-");
toReturnPanel.add(usernameLabel);
scoreLabel = new JLabel("-");
toReturnPanel.add(scoreLabel);
}
}
} | 4 |
public void setActivityType(ActivityTypes activityType) {
this.activityType = activityType;
} | 0 |
public boolean isExpired() {
return expired;
} | 0 |
private void parseRest(String measureDefinition) {
for (int i = 1; i < measureDefinition.length(); i++) {
switch(measureDefinition.charAt(i)) {
case 't':
beats.add(SongEvent.TITLE_CARD);
break;
case '.':
beats.add(SongEvent.REST);
break;
case '-':
beats.add(SongEvent.HOLD);
break;
default:
break;
}
}
} | 4 |
public void initXML() {
vermilionCascadeNotebook.initDataDir();
File dataFile = new File(VCNConstants.WORK_FILE_PATH);
boolean isExistDataFile = dataFile.isFile();
if (!isExistDataFile) {
GeneralUtils.clearTree(vermilionCascadeNotebook.getTree());
TreeItem iItem = new VCNTreeItem(vermilionCascadeNotebook.getTree(), 0);
iItem.setText(VCNConstants.ROOT);
vermilionCascadeNotebook.setModified();
saveXml();
}
} | 1 |
public void gainItem(int id, int quantity) {
if (quantity >= 0) {
MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
IItem item = ii.getEquipById(id);
MapleInventoryType type = InventoryConstants.getInventoryType(id);
if (!MapleInventoryManipulator.checkSpace(client, id, quantity, "")) {
client.getSession().write(MaplePacketCreator.serverNotice(1, "Your inventory is full."));
return;
}
if (type.equals(MapleInventoryType.EQUIP) && !InventoryConstants.isThrowingStar(item.getItemId()) && !InventoryConstants.isBullet(item.getItemId())) {
MapleInventoryManipulator.addFromDrop(client, item, true);
} else {
MapleInventoryManipulator.addById(client, id, (short) quantity, "");
}
} else {
MapleInventoryManipulator.removeById(client, InventoryConstants.getInventoryType(id), id, -quantity, true, false);
}
client.getSession().write(MaplePacketCreator.getShowItemGain(id, (short) quantity, true));
} | 5 |
public RdpPacket_Localised receive(Rdp rdpLayer) throws RdesktopException,
IOException, CryptoException, OrderException {
int sec_flags = 0;
RdpPacket_Localised buffer = null;
while (true) {
int[] channel = new int[1];
GWT.log("new receive at MCS");
buffer = McsLayer.receive(channel, rdpLayer);
GWT.log("after receive at mcs");
if (buffer == null)
return null;
buffer.setHeader(RdpPacket_Localised.SECURE_HEADER);
if (Constants.encryption || (!this.licenceIssued)) {
sec_flags = buffer.getLittleEndian32();
if ((sec_flags & SEC_LICENCE_NEG) != 0) {
licence.process(buffer, option);
continue;
}
if ((sec_flags & SEC_ENCRYPT) != 0) {
buffer.incrementPosition(8); // signature
byte[] data = new byte[buffer.size() - buffer.getPosition()];
buffer.copyToByteArray(data, 0, buffer.getPosition(),
data.length);
byte[] packet = this.decrypt(data);
buffer.copyFromByteArray(packet, 0, buffer.getPosition(),
packet.length);
// buffer.setStart(buffer.getPosition());
// return buffer;
}
}
if (channel[0] != MCS.MCS_GLOBAL_CHANNEL) {
channels.channel_process(buffer, channel[0]);
continue;
}
buffer.setStart(buffer.getPosition());
return buffer;
}
} | 7 |
public static double queryFoilGain(Cons rule, double utility, List coveredPos, List coveredNeg) {
{ int p = 0;
int n = 0;
double result = 0.0;
{ TrainingExample example = null;
Cons iter000 = coveredNeg.theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
example = ((TrainingExample)(iter000.value));
if (Logic.ruleCoversExampleP(rule, example)) {
n = n + 1;
}
}
}
{ TrainingExample example = null;
Cons iter001 = coveredPos.theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
example = ((TrainingExample)(iter001.value));
if (Logic.ruleCoversExampleP(rule, example)) {
p = p + 1;
}
}
}
if ((p == 0) &&
(n == 0)) {
return (0.0);
}
result = p * (Logic.foilUtility(p, n) - utility);
if (result < 1.0e-6) {
result = 0.0;
}
return (result);
}
} | 7 |
@EventHandler(ignoreCancelled = true)
public void handle(BlockBreakEvent event) {
Player player = event.getPlayer();
GameSession session = plugin.getGameManager().getGameSessionOfPlayer(
player);
if (session == null) {
return;
}
if (!(session.isStarted()) && !(session.isAdmin(player))) {
event.setCancelled(true);
}
if (session.isStarted() && session.getDeadPlayers().contains(player)) {
event.setCancelled(true);
}
} | 5 |
boolean doubledUp( String token, String mergedCell, FragList cell )
{
if ( token.equals(mergedCell) )
{
if ( cell.fragments.size()==1 )
{
Atom a = cell.fragments.get(0);
if ( a instanceof Fragment )
{
Fragment f = (Fragment)a;
if ( f.contents!=null&&f.contents.equals(token) )
return true;
}
}
}
return false;
} | 5 |
public void insert(A a) {
assert a != null;
Match m = findMatch(a);
if (m.matchFound) {
m.node.contents = a;
splay(m.node);
} else {
Node parent = m.node;
Node newNode = new Node(a);
if (m.smallerThanNode) {
parent.setLeft(newNode);
} else {
parent.setRight(newNode);
}
splay(newNode);
}
} | 2 |
@Override
public List<Entry<String, List<?>>> getValue() {
List<Entry<String, List<?>>> ret = new ArrayList<>();
for(ParseOption<?> p : optionList) {
ret.add(new ArgsEntry<String, List<?>>(p.getShortOption(), p.getValue()));
}
return ret;
} | 5 |
private static void PriorityQueueMenu(PriorityQueue<Integer> PriorityQueue){
System.out.println("What do you want to do ?");
System.out.println("1) Dequeue");
System.out.println("2) Enqueue");
System.out.println("3) Print");
System.out.println("Enter your option");
try{
choose = in.nextInt();
switch (choose){
case 1:
try{
System.out.println("Insert the number to enqueue: ");
size = in.nextInt();
start = System.nanoTime();
PriorityQueue.Enqueue(size);
end = System.nanoTime();
System.out.println("Enqueueing lasted: " + (end - start));
break;
}catch(Exception e){
break;
}
case 2:
try{
start = System.nanoTime();
PriorityQueue.Dequeue();
end = System.nanoTime();
System.out.println("Dequeueing lasted: " + (end - start));
break;
}catch(Exception e){
break;
}
case 3 :
System.out.println(PriorityQueue.describe());
}
System.out.println("Do you want to exit the Priority Queue Menu? (Yes / No)");
exitPriorityQueueMenu(PriorityQueue);
}catch (Exception e){
System.out.println("Do you want to exit the Priority Queue Menu? (Yes / No)");
exitPriorityQueueMenu(PriorityQueue);
}
} | 6 |
public void focusLost(FocusEvent e) {
Debug.print("Focus changed on: " + e.getSource());
if(e.getSource() == txtName) {
// this is where we have lost focus, so now we need to populate the data
// See if we can find the Fermentable
Fermentable temp = new Fermentable();
temp.setName(txtName.getText());
int result = db.find(temp);
Debug.print("Searching for " + txtName.getText() + " found: " + result);
if(result >= 0) {
// we have the index, load it into the hop
temp = db.fermDB.get(result);
// set the fields
if (Double.toString(temp.getPppg())!= null) {
txtYield.setText(Double.toString(temp.getPppg()));
}
if (Double.toString(temp.getLov()) != null) {
txtCost.setText(Double.toString(temp.getLov()));
}
if (Double.toString(temp.getCostPerU()) != null) {
txtCost.setText(Double.toString(temp.getCostPerU()));
}
if (Double.toString(temp.getStock()) != null) {
txtStock.setText(Double.toString(temp.getStock()));
}
if (temp.getUnits() != null) {
cUnits.setSelectedItem(temp.getUnits());
}
bMash.setSelected(temp.getMashed());
bSteep.setSelected(temp.getSteep());
bModified.setSelected(temp.getModified());
bFerments.setSelected(temp.ferments());
if (temp.getDescription() != null){
txtDescr.setText(temp.getDescription());
jScrollDescr.invalidate();
}
jScrollDescr.getVerticalScrollBar().setValue(0);
jScrollDescr.revalidate();
}
}
} | 8 |
private ImageIcon getTexture(int id, int x, int y) {
switch (id) {
case 1:
field = new ImageIcon("Images/textures/Gras-Erde.png");
Rectangle rec = new Rectangle(x, y, dimension, dimension);
World.fieldColList.add(rec);
break;
case 2:
field = new ImageIcon("Images/textures/Erde.png");
break;
case 3:
field = new ImageIcon("Images/textures/Stein.png");
break;
case 4:
field = new ImageIcon("Images/textures/Steinkachel.png");
break;
}
return field;
} | 4 |
void reportDetail(String date, BufferedWriter bw) {
List<Map<String, Object>> maps = getPersist().readMapList(Sql.get("report-detail.sql"), date);
for (Map<String, Object> map : maps) {
String supplierCode = map.get("suppliercode").toString();
String supplierName = map.get("name").toString();
String amount = map.get("amount").toString();
try {
bw.write(String.format("%s\t%s\t%s\t%s\r\n", date, supplierCode, supplierName, amount));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | 2 |
public boolean canSendNextPacket() {
if (timeStampNow - lastZeroWindow > getTimeOutMicros() && lastZeroWindow != 0 && maxWindow == 0) {
log.debug("setting window to one packet size. current window is:" + currentWindow);
maxWindow = MAX_PACKET_SIZE;
}
boolean windowNotFull = !isWondowFull();
boolean burstFull = false;
if (windowNotFull) {
burstFull = isBurstFull();
}
if (!burstFull && windowNotFull) {
currentBurstSend++;
}
if (burstFull) {
currentBurstSend = 0;
}
return SEND_IN_BURST ? (!burstFull && windowNotFull) : windowNotFull;
} | 9 |
public static BufferedImage[] loadMultiImage(String s, int x, int y, int subImages) {
BufferedImage[] ret;
try {
final BufferedImage spritesheet = ImageIO.read(Images.class.getResourceAsStream(s));
ret = new BufferedImage[subImages];
for (int i = 0; i < subImages; i++)
ret[i] = spritesheet.getSubimage(i * x, y, x, x);
return ret;
} catch (final Exception e) {
e.printStackTrace();
System.out.println("Error loading graphics." + " " + s + " might be an invalid directory");
System.exit(0);
}
return null;
} | 2 |
public static void main(String args[]){
//crear un arreglo con frutas que me gusten
String frutas []={"kiwi", "mango", "sandia", "caña", "platano"};
for(String x:frutas){
System.out.println(x);
}
} | 1 |
public Vector<Object> subarray_as_Vector(int start, int end){
if(end>=this.length)throw new IllegalArgumentException("end, " + end + ", is greater than the highest index, " + (this.length-1));
Vector<Object> vec = new Vector<Object>(end-start+1);
for(int i=start; i<=end; i++)vec.addElement(array.get(i));
return vec;
} | 2 |
public TransactionSet twoItemSubsets(TransactionSet candidSet, double minSupportLevel, TransactionSet transSet) {
//System.out.println("2 ItemSubsets starting");
//System.out.println("Starting ItemSet to make 2 item subsets");
TransactionSet allSubsets = new TransactionSet();/*New subset of transactions to return in a TransactionSet*/
int size = candidSet.getTransactionSet().size();
//System.out.println("SIZE: " + size);
for(int i = 0; i < size; i++){
//System.out.println("i: " + i);
Item currItem = new Item(candidSet.getTransactionSet().get(i).getTransaction().getItemSet().get(0).toString());
for(int j = i+1; j < size; j++){
//System.out.println("j: " + j);
Item nextItem = new Item(candidSet.getTransactionSet().get(j).getTransaction().getItemSet().get(0).toString());
ItemSet iSet = new ItemSet();
iSet.getItemSet().add(currItem);
iSet.getItemSet().add(nextItem);
//System.out.println("ItemSet to check:\n:" + iSet.toString());
double supportLevel = transSet.findSupport(iSet);
//iSet.setItemSetSupport(findSupport);
iSet.setItemSetSupport(supportLevel/transSet.getTransactionSet().size());
//System.out.println("findSupport: " + (findSupport/transSet.getTransactionSet().size()) + "vs. minSupport: " + minSupportLevel);
//if(iSet.getItemSet().size() >1){
if (iSet.getItemSetSupport() >= minSupportLevel) {
//System.out.println("Passed: ");
Transaction ts = new Transaction(iSet);
allSubsets.getTransactionSet().add(ts);
}
//}
}
}
return (allSubsets);/*final combination of all possible subsets based on the size of k*/
} | 3 |
public void setArenaState(ArenaState state) {
this.arenastate = state;
} | 0 |
@Override
public HandshakeBuilder postProcessHandshakeResponseAsServer(
Handshakedata request, HandshakeBuilder response) throws Exception {
response.put("Upgrade", "websocket");
response.put("Connection", request.getFieldValue("Connection")); // to
// respond
// to
// a
// Connection
// keep
// alives
response.setHttpStatusMessage("Switching Protocols");
String seckey = request.getFieldValue("Sec-WebSocket-Key");
if (seckey == null)
throw new Exception("missing Sec-WebSocket-Key");
response.put("Sec-WebSocket-Accept", generateFinalKey(seckey));
return response;
} | 1 |
@Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {} | 0 |
public String[] obtenerRespuestasCorrectas(int tamaño){
String csvFile = "dataset/diabetes_prueba_resultados.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
String respuestas [] = new String [tamaño];
int contador = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] patron = line.split(cvsSplitBy);
respuestas[contador] = patron[8];
contador++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException e) {
System.out.println("Error accediendo al csv");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return respuestas;
} | 6 |
public HashMapStats(){
stats = new HashMap<StatType, Stat>(8);
} | 0 |
private JPanel createRoadtypeBox(String roadtypeString, boolean selected) {
JPanel roadTypeBoxPanel = new JPanel(new FlowLayout(0));
JCheckBox box = new JCheckBox(roadtypeString);
box = setLabelFont(box);
box.setSelected(selected);
box.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBox box = (JCheckBox) e.getSource();
if (box.getText().equals("Highways"))
number = 1;
if (box.getText().equals("Expressways"))
number = 2;
if (box.getText().equals("Primary roads"))
number = 3;
if (box.getText().equals("Secondary roads"))
number = 4;
if (box.getText().equals("Normal roads"))
number = 5;
if (box.getText().equals("Trails & streets"))
number = 6;
if (box.getText().equals("Paths"))
number = 7;
if (e.getStateChange() == ItemEvent.SELECTED)
controller.updateMap(number, true);
else
controller.updateMap(number, false);
}
});
boxes.put(roadtypeString, box);
roadTypeBoxPanel.add(box);
return roadTypeBoxPanel;
} | 8 |
public String getConfigPath(String filename) {
if (eng.isApplet()) return null;
File jgamedir;
try {
jgamedir = new File(System.getProperty("user.home"), ".jgame");
} catch (Exception e) {
// probably AccessControlException of unsigned webstart
return null;
}
if (!jgamedir.exists()) {
// try to create ".jgame"
if (!jgamedir.mkdir()) {
// fail
return null;
}
}
if (!jgamedir.isDirectory()) return null;
File file = new File(jgamedir,filename);
// try to create file if it didn't exist
try {
file.createNewFile();
} catch (IOException e) {
return null;
}
if (!file.canRead()) return null;
if (!file.canWrite()) return null;
try {
return file.getCanonicalPath();
} catch (IOException e) {
return null;
}
} | 9 |
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
Object parameterObject = invocation.getArgs()[1];
final Configuration configuration = ms.getConfiguration();
final StatementHandler handler = configuration.newStatementHandler((Executor) invocation.getTarget(),
ms, parameterObject, RowBounds.DEFAULT, null, null);
final BoundSql boundSql = handler.getBoundSql();
final String sql = boundSql.getSql();
List<String> splitted = splitter.split(sql);
int rc = 0;
List<ParameterMapping> fullParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
for (String sqlPart: splitted) {
if (skipEmptyStatements && sqlPart.length() == 0) {
continue;
}
int numParams = 0;
for (int index = sqlPart.indexOf('?'); index >=0; index = sqlPart.indexOf('?', index + 1)) {
numParams++;
}
MappedStatement subStatement = subStatements.get(ms);
if (subStatement == null) {
subStatement = new MappedStatement.Builder(
ms.getConfiguration(), ms.getId(), new SwitchingSqlSource(configuration), ms.getSqlCommandType())
.cache(ms.getCache())
.databaseId(ms.getDatabaseId())
.fetchSize(ms.getFetchSize())
.timeout(ms.getTimeout())
.flushCacheRequired(ms.isFlushCacheRequired())
.useCache(ms.isUseCache())
.build();
subStatements.put(ms, subStatement);
}
List<ParameterMapping> subParameterMappings = fullParameterMappings.subList(0, numParams);
((SwitchingSqlSource)subStatement.getSqlSource()).switchParams(sqlPart, boundSql,
new ArrayList<ParameterMapping>(subParameterMappings));
subParameterMappings.clear();
int subRc = (Integer)invocation.getMethod().invoke(invocation.getTarget(), subStatement, parameterObject);
if (rc >= 0) {
rc = subRc < 0 ? subRc : rc + subRc;
}
}
return rc;
} | 7 |
public ConnectionLabelConfiguration( String id ) {
if( id == null ) {
throw new IllegalArgumentException( "id must not be null" );
}
this.id = id;
} | 1 |
private int[] getBaseEncoding(String encodingName) {
if (encodingName.equals("MacRomanEncoding")) {
return FontSupport.macRomanEncoding;
} else if (encodingName.equals("MacExpertEncoding")) {
return FontSupport.type1CExpertCharset;
} else if (encodingName.equals("WinAnsiEncoding")) {
return FontSupport.winAnsiEncoding;
} else {
throw new IllegalArgumentException("Unknown encoding: " + encodingName);
}
} | 3 |
private void setLookAndFeel() {
//<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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HovedGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HovedGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HovedGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HovedGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>>
} | 6 |
@Test
public void determineHighestStraight_whenHandContainsTto7FourCardStraight_returnsNull() {
assertNull(findHighestStraight(nonStraightFiveFlush()));
} | 0 |
protected Behaviour getNextStep() {
if (eventsVerbose && begun()) {
I.sayAbout(actor, "NEXT COMBAT STEP "+this.hashCode()) ;
}
//
// This might need to be tweaked in cases of self-defence, where you just
// want to see off an attacker.
if (isDowned(target)) { // TODO: This might need to be varied-
if (eventsVerbose && begun()) I.sayAbout(actor, "COMBAT COMPLETE") ;
return null ;
}
Action strike = null ;
final DeviceType DT = actor.gear.deviceType() ;
final boolean melee = actor.gear.meleeWeapon() ;
final boolean razes = target instanceof Venue ;
final float danger = Retreat.dangerAtSpot(
actor.origin(), actor, razes ? null : (Actor) target
) ;
final String strikeAnim = DT == null ? Action.STRIKE : DT.animName ;
if (razes) {
strike = new Action(
actor, target,
this, "actionSiege",
strikeAnim, "Razing"
) ;
}
else {
strike = new Action(
actor, target,
this, "actionStrike",
strikeAnim, "Striking at"
) ;
}
//
// Depending on the type of target, and how dangerous the area is, a bit
// of dancing around may be in order.
if (melee) configMeleeAction(strike, razes, danger) ;
else configRangedAction(strike, razes, danger) ;
///if (eventsVerbose) I.sayAbout(actor, "NEXT STRIKE "+strike) ;
return strike ;
} | 9 |
public void visitTypeInsn(final int opcode, final String type) {
minSize += 3;
maxSize += 3;
if (mv != null) {
mv.visitTypeInsn(opcode, type);
}
} | 1 |
public void run() {
DCPU cpu = new DCPU();
this.display = ((VirtualMonitor)new VirtualMonitor().connectTo(cpu));
this.keyboard = ((VirtualKeyboard)new VirtualKeyboard(new AWTKeyMapping()).connectTo(cpu));
new VirtualClock().connectTo(cpu);
new VirtualFloppyDrive().connectTo(cpu);
new VirtualSleepChamber().connectTo(cpu);
new VirtualVectorDisplay().connectTo(cpu);
try {
new Assembler(cpu.ram).assemble(new URL(getParameter("source")));//getParameter("source"));
// DCPU.load(cpu.ram);
} catch (Exception e1) {
e1.printStackTrace();
}
int SCALE = 3;
try
{
setFocusable(true);
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent ke) {
DCPUApplet.this.keyboard.keyPressed(ke.getKeyCode());
}
public void keyReleased(KeyEvent ke) {
DCPUApplet.this.keyboard.keyReleased(ke.getKeyCode());
}
public void keyTyped(KeyEvent ke) {
DCPUApplet.this.keyboard.keyTyped(ke.getKeyChar());
}
});
BufferedImage img2 = new BufferedImage(160, 128, 2);
BufferedImage img = new BufferedImage(128, 128, 2);
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
this.display.setPixels(pixels);
requestFocus();
int khz = 100;
long ops = 0L;
int hz = khz * 1000;
int cyclesPerFrame = hz / 60;
long nsPerFrame = 16666666L;
long nextTime = System.nanoTime();
double tick = 0.0D;
double total = 0.0D;
long time = System.currentTimeMillis();
while (!this.stop) {
long a = System.nanoTime();
while (System.nanoTime() < nextTime) {
try {
Thread.sleep(1L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long b = System.nanoTime();
while (cpu.cycles < cyclesPerFrame) {
cpu.tick();
}
cpu.tickHardware();
this.display.render();
Graphics g = img2.getGraphics();
g.setColor(new Color(pixels[12288]));
g.fillRect(0, 0, 160, 128);
g.drawImage(img, 16, 16, 128, 128, null);
g.dispose();
g = getGraphics();
if (g != null) {
g.drawImage(img2, 0, 0, 160 * SCALE, 128 * SCALE, null);
g.dispose();
}
cpu.cycles -= cyclesPerFrame;
long c = System.nanoTime();
ops += cyclesPerFrame;
nextTime += nsPerFrame;
tick += (c - b) / 1000000000.0D;
total += (c - a) / 1000000000.0D;
while (System.currentTimeMillis() > time) {
time += 1000L;
System.out.println("1 DCPU at " + ops / 1000.0D + " khz, " + tick * 100.0D / total + "% cpu use");
tick = total = ops = 0L;
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public int endElement(String name) throws MiniXMLException {
if (name == null)
throw new MiniXMLException(MiniXMLException._MXMLE_AE_UKNOWN_END_TOKEN);
if (name.compareToIgnoreCase(getName()) != 0)
throw new MiniXMLException(MiniXMLException._MXMLE_AE_UKNOWN_END_TOKEN);
int state = oState.getStateID();
oState = oState.getParent();
// if(oState.isRoot())
// return state;
// oState = oState.getParent();
if (oState == null)
throw new MiniXMLException(MiniXMLException._MXMLE_AE_UKNOWN_PARENT);
return state;
} | 3 |
public static int decodeAnimationBytes( byte prgsection[], int offset, CHREditorModel modelRef) {
int cnt = 0;
int numAnimations = prgsection[offset + cnt] & 0xFF; cnt++;
int animDuration = prgsection[offset+cnt] & 0xFF; cnt++;
int animGrid[][] = new int[numAnimations][animDuration];
for(int i=0;i<numAnimations;i++) {
for(int j=0;j<animDuration;j++){
animGrid[i][j] = prgsection[offset+cnt] & 0xFF; cnt++;
}
}
int numKfs = prgsection[offset+cnt] & 0xFF; cnt++;
AnimationKeyframeData kfs[] = new AnimationKeyframeData[numKfs];
// now extract the keyframes
for(int i=0;i<numKfs;i++){
kfs[i] = new AnimationKeyframeData();
kfs[i].yPos = prgsection[offset+cnt]; cnt++;
kfs[i].spriteIndex = prgsection[offset+cnt]; cnt++;
kfs[i].setSpriteAttributesByte(prgsection[offset+cnt]);cnt++;
kfs[i].xPos = prgsection[offset+cnt]; cnt++;
}
for(int i=0;i<animGrid.length;i++) {
modelRef.addAnimation();
for(int j=0;j<animGrid[i].length;j++){
int val = animGrid[i][j];
if(val != 0) {
AnimationKeyframeData kf = modelRef.constructKeyFrame(i,j);
kfs[val-1].copyInto(kf);
}
}
}
return cnt;
} | 6 |
protected Item getPoison(MOB mob)
{
if(mob==null)
return null;
if(mob.location()==null)
return null;
for(int i=0;i<mob.location().numItems();i++)
{
final Item I=mob.location().getItem(i);
if((I!=null)
&&(I instanceof Drink)
&&(((((Drink)I).containsDrink())
&&(((Drink)I).liquidType()==RawMaterial.RESOURCE_LAMPOIL))
||(I.material()==RawMaterial.RESOURCE_LAMPOIL)))
return I;
}
return null;
} | 8 |
public void deleteTable(byte[] table)
{
boolean isSystemTable = ForemanConstants.TableIdentifier.getIdentifierFromName(table) != null;
if (tableExists(table) && !isSystemTable)
{
instance.hdel(ForemanConstants.TableIdentifier.TABLE.getId(), table);
Set<byte[]> keys = instance.hkeys(table);
for (byte[] key : keys)
{
instance.hdel(table, key);
}
}
else if (isSystemTable)
{
log.warn("Delete table ignored. Table{} is a system table.", new String(table));
}
else
{
log.warn("Delete table ignored. Table {} does not exist", new String(table));
}
} | 4 |
public boolean append(E element) {
if (lastPos == array.length - 1 || array.length == 0) {
changeCapacityBy(1);
if (array.length == 1) {
return setElement(0, element);
}
}
if (array.length > 0 && lastPos == 0 && array[lastPos] == null) {
return setElement(lastPos, element);
}
return setElement(++lastPos, element);
} | 6 |
public void update(boolean up, boolean down, boolean left, boolean right, Dimension d) {
//check for movment
if(up){
this.setPlayerY(this.getPlayerY()-4);
}
else if(down){
this.setPlayerY(this.getPlayerY()+4);
}
if(left){
this.setPlayerX(this.getPlayerX()-7);
}
else if(right){
this.setPlayerX(this.getPlayerX()+7);
}
//create bounds the player cannot pass through
if(d.height-15<this.getPlayerY()){
this.setPlayerY(d.height-15);
}
if(10>this.getPlayerY()){
this.setPlayerY(10);
}
if(d.width-15<this.getPlayerX()){
this.setPlayerX(d.width-15);
}
if(10>this.getPlayerX()){
this.setPlayerX(10);
}
//draw location of player
playerX=this.getPlayerX();
playerY=this.getPlayerY();
} | 8 |
protected static void createDescriptor()
{
try
{
InputStream descriptorStream = RtgParseControllerGenerated.class.getResourceAsStream(DESCRIPTOR);
InputStream table = RtgParseControllerGenerated.class.getResourceAsStream(TABLE);
boolean filesystem = false;
if(descriptorStream == null && new File("./" + DESCRIPTOR).exists())
{
descriptorStream = new FileInputStream("./" + DESCRIPTOR);
filesystem = true;
}
if(table == null && new File("./" + TABLE).exists())
{
table = new FileInputStream("./" + TABLE);
filesystem = true;
}
if(descriptorStream == null)
throw new BadDescriptorException("Could not load descriptor file from " + DESCRIPTOR + " (not found in plugin: " + getPluginLocation() + ")");
if(table == null)
throw new BadDescriptorException("Could not load parse table from " + TABLE + " (not found in plugin: " + getPluginLocation() + ")");
descriptor = DescriptorFactory.load(descriptorStream, table, filesystem ? Path.fromPortableString("./") : null);
descriptor.setAttachmentProvider(RtgParseControllerGenerated.class);
}
catch(BadDescriptorException exc)
{
notLoadingCause = exc;
Environment.logException("Bad descriptor for " + LANGUAGE + " plugin", exc);
throw new RuntimeException("Bad descriptor for " + LANGUAGE + " plugin", exc);
}
catch(IOException exc)
{
notLoadingCause = exc;
Environment.logException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc);
throw new RuntimeException("I/O problem loading descriptor for " + LANGUAGE + " plugin", exc);
}
} | 9 |
@Override
public void keyPressed(int key, char character, GUIComponent component) {
switch (key) {
case (Keyboard.KEY_ESCAPE) : this.deactivate(500); break;
case (Keyboard.KEY_1) : suiteSelected(Card.CLUBS); break;
case (Keyboard.KEY_2) : suiteSelected(Card.DIAMONDS); break;
case (Keyboard.KEY_3) : suiteSelected(Card.SPADES); break;
case (Keyboard.KEY_4) : suiteSelected(Card.HEARTS); break;
}
} | 5 |
public void ENTER() {
if (atTitle) {
atTitle = !atTitle;
inTransition = !inTransition;
Pikachu = PikaDance1;
num = 0;
gameTimer.setDelay(25);
} else if (gamestarted && !inMenu && movable && !inBattle && !walking && !inDialog) {
SE.playClip("Menu");
menu.inMain = true;
inMenu = true;
}
} | 7 |
public void rowEventListener(RowEditEvent e) {
try {
PersonasDTO personasDTO = (PersonasDTO) e.getObject();
if (txtGenero == null) {
txtGenero = new InputText();
}
txtGenero.setValue(personasDTO.getGenero());
if (txtPrimerApellido == null) {
txtPrimerApellido = new InputText();
}
txtPrimerApellido.setValue(personasDTO.getPrimerApellido());
if (txtPrimerNombre == null) {
txtPrimerNombre = new InputText();
}
txtPrimerNombre.setValue(personasDTO.getPrimerNombre());
if (txtProfesion == null) {
txtProfesion = new InputText();
}
txtProfesion.setValue(personasDTO.getProfesion());
if (txtSegundoApellido == null) {
txtSegundoApellido = new InputText();
}
txtSegundoApellido.setValue(personasDTO.getSegundoApellido());
if (txtSegundoNombre == null) {
txtSegundoNombre = new InputText();
}
txtSegundoNombre.setValue(personasDTO.getSegundoNombre());
if (txtIdPersona == null) {
txtIdPersona = new InputText();
}
txtIdPersona.setValue(personasDTO.getIdPersona());
if (txtFechaNacimiento == null) {
txtFechaNacimiento = new Calendar();
}
txtFechaNacimiento.setValue(personasDTO.getFechaNacimiento());
action_modify();
} catch (Exception ex) {
}
} | 9 |
@Override
public Competicao get(Object key) {
try {
Competicao al = null;
Statement stm = conn.createStatement();
String sql = "SELECT Competicao.*,Torneio.* FROM Torneio,competicao WHERE Torneio.Cod_Torneio='" + (String) key + "'and competicao.cod_competicao=torneio.cod_torneio";
ResultSet rs = stm.executeQuery(sql);
if (rs.next()){
if(rs.getInt("tipotorneio")==0) {
al = new Eliminatorias(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
rs.close();
return al;
} else {
if(rs.getInt("tipotorneio")==1){
al = new EliminatoriaDupla(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
rs.close();
return al;
}
}
}
sql = "SELECT Competicao.*,Campeonato.* FROM Campeonato,competicao WHERE Campeonato.Cod_Campeonato='" + (String) key + "'and competicao.cod_competicao=Campeonato.cod_campeonato";
rs = stm.executeQuery(sql);
if (rs.next()) {
al = new Campeonato(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
rs.close();
}
return al;
} catch (SQLException | NumberFormatException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
return null;
}
} | 5 |
Subsets and Splits