text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void run() {
try {
take = player.pass(bowl,bowlid,round,canPick,mustTake);
} catch (Exception e) {
e.printStackTrace();
exception = e;
}
} | 1 |
public void cargar()
{
try
{
String workingDir = System.getProperty("user.dir");
File dex = new File(workingDir+"/pokeDexNac.txt");
BufferedReader pokeDex = new BufferedReader(new FileReader(dex));
File stats = new File(workingDir+"/pokeStats.txt");
BufferedReader pokeStats = new BufferedReader(new FileReader(stats));
File pokAbc = new File(workingDir+"/pokeDexAbc.txt");
BufferedReader pokeAbc = new BufferedReader(new FileReader(pokAbc));
pokeDex.readLine();
pokeStats.readLine();
pokeAbc.readLine();
while(pokeDex.ready() && pokeStats.ready())
{
String statString[], abc[];
abc = pokeDex.readLine().split("\t");
statString = pokeStats.readLine().split("\t");
String numeroString, nombre, tipo1, tipo2, desc;
numeroString = abc[2].trim();
nombre = abc[3].trim();
tipo1 = abc[4].trim();
try
{
tipo2 = abc[5];
}catch(ArrayIndexOutOfBoundsException e)
{
tipo2 = "";
}
int numero = Integer.parseInt(numeroString);
int hp = Integer.parseInt(statString[2].trim());
int atk = Integer.parseInt(statString[3].trim());
int def = Integer.parseInt(statString[4].trim());
int spAtk = Integer.parseInt(statString[5].trim());
int spDef = Integer.parseInt(statString[6].trim());
int speed = Integer.parseInt(statString[7].trim());
String average = statString[8].trim().replace(",", ".");
double avg = Double.parseDouble(average);
desc = "";
pokeId[numero-1] = new Pokemon(numero, nombre, hp, atk, def, spAtk, spDef, speed, avg, desc, tipo1, tipo2);
}
String[] temp = pokeAbc.readLine().split("\t");
for(int i = 0; pokeAbc.ready(); i++)
{
temp = pokeAbc.readLine().split("\t");
int numero = Integer.parseInt(temp[1].trim());
pokeAlf[i] = pokeId[numero-1];
}
}
catch(IOException e)
{
System.out.println(e.getLocalizedMessage());
}
} | 5 |
public Object getValueAt(int row, int column) {
if (row >= listData.size())
throw new IndexOutOfBoundsException("Table row "+row+" is not valid");
AccountTransaction r = listData.get(row);
Object value;
double amount;
switch (column) {
case 0: // Date
value = r.transaction.getDate();
break;
case 1: // Description
value = r.transaction.getName();
break;
case 2: // Memo
value = r.transaction.getMemo();
break;
case 3: // Decrease
amount = r.transaction.getAmount();
if (amount < 0.0)
value = new Double(-amount);
else
value = null;
break;
case 4: // Increase
amount = r.transaction.getAmount();
if (amount >= 0.0)
value = new Double(amount);
else
value = null;
break;
case 5: // Balance
value = new Double(r.balance);
break;
default:
throw new IndexOutOfBoundsException("Table column "+column+" is not valid");
}
return value;
} | 9 |
private void handleUpdate() {
if (pref instanceof PreferenceBoolean) {
PreferenceBoolean prefBoolean = (PreferenceBoolean) pref;
prefBoolean.setTmp(checkbox.isSelected());
checkbox.setSelected(prefBoolean.tmp);
}
} | 1 |
public boolean isInitialized() {
return this.initialized;
} | 0 |
void run(){
Scanner sc = new Scanner(System.in);
int[] d = {0, 20, 19, 20, 19, 20, 19, 20, 19, 20, 19};
int T = sc.nextInt();
while(T--!=0){
int Y = sc.nextInt(), M = sc.nextInt(), D = sc.nextInt();
int res = 0;
while(!(Y==1000&&M==1&&D==1)){
if(Y%3==0&&D==20 || Y%3!=0&&D==d[M]){
M++; D=1;
}
else D++;
if(M==11){
Y++; M=1;
}
res++;
}
System.out.println(res);
}
} | 9 |
private BufferedReader createCatReader(File archivoCat) throws IOException {
InputStream inputStream = new FileInputStream(archivoCat);
if (archivoCat.getName().toLowerCase().endsWith(".gz")){
inputStream = new GZIPInputStream(inputStream);
}
return new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-15"));
} | 1 |
private void processMoveResult(String result, CardMove move) {
if (result.isEmpty()) {
game.getHistory().push(move);
} else if (!result.equals("ONTO_SELF")) {
storeMessage(new RenderMessage(result, true));
}
} | 2 |
Info(BEDictionary dict) throws MetaInfoException, InvalidBEncodingException, UnsupportedEncodingException, NullHashException {
mDictionary = dict;
// ----- Required Keys -----------------------------------------------
if (mDictionary.contains(KEY_PIECE_LENGTH))
mPieceLength = mDictionary.getInt(KEY_PIECE_LENGTH);
else
throw new MetaInfoRequiredKeyException(KEY_PIECE_LENGTH);
if (mDictionary.contains(KEY_PIECES))
parsePieces();
else
throw new MetaInfoRequiredKeyException(KEY_PIECES);
if (mDictionary.contains(KEY_NAME))
mName = mDictionary.getString(KEY_NAME);
else
throw new MetaInfoRequiredKeyException(KEY_NAME);
// -------------------------------------------------------------------
// Optional Key
if (mDictionary.contains(KEY_PRIVATE))
mPrivate = mDictionary.getInt(KEY_PRIVATE) == 1; // if (private == 1) => It is a Private Torrent.
// With one or several files, we stock them in an ArrayList.
mFiles = new ArrayList<TorrentFile>();
// the Key Files is there only for multi-files mode.
if (mDictionary.contains(KEY_FILES))
parseMultFile();
else
parseSingleFile();
mLength = 0;
for (TorrentFile file: mFiles) {
mLength += file.length();
}
} | 6 |
public boolean isUnderstood(Event event)
{
int commandType = event.getCommandType();
int minExpectedArgCount = minExpectedArgByteCount(commandType);
int maxExpectedArgCount = maxExpectedArgByteCount(commandType);
if (minExpectedArgCount == maxExpectedArgCount)
{
if (-1 != minExpectedArgCount)
{
if (minExpectedArgCount != (event.getRawData().length - EVENT_COMMAND_ARGS_OFFSET))
return false;
}
}
else
{
if (-1 != minExpectedArgCount)
{
int actualArgs = event.getRawData().length - EVENT_COMMAND_ARGS_OFFSET;
if ((actualArgs < minExpectedArgCount) || (actualArgs > maxExpectedArgCount))
return false;
}
}
int argumentTypeArray[] = getArgumentTypeArrayForCommandType(commandType);
if (ARGUMENT_TYPE__UNKNOWN == argumentTypeArray[0])
{
return false;
}
else
{
return true;
}
} | 7 |
public byte getCloneLimit() {
if (isHokage() && clonelimit < 69) {
this.clonelimit = (byte) 69;
} else if (isJounin() && clonelimit < 25) {
this.clonelimit = (byte) 25;
} else if (isGenin() && clonelimit < 15) {
this.clonelimit = (byte) 15;
}
return clonelimit;
} | 6 |
private void handleSetupDevice(SetupDeviceMessage originalMessage,
AcknowledgmentMessage message) {
switch (originalMessage.getSetupDeviceMessageType()) {
case CONNECT_DEVICE:
handleConnectDevice(originalMessage, message);
break;
case SET_IMAGE_QUALITY:
case SET_POLLING_RATE:
// do nothing?
break;
default:
break;
}
} | 3 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return super.okMessage(myHost,msg);
final MOB mob=(MOB)affected;
if((msg.amITarget(mob))
&&(CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS))
&&(msg.targetMinor()==CMMsg.TYP_CAST_SPELL)
&&(msg.tool() instanceof Ability)
&&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
&&(invoker!=null)
&&(!mob.amDead())
&&(CMLib.dice().rollPercentage()<(35+super.getXLEVELLevel(invoker())+adjustedLevel(invoker(),0)-((Ability)msg.tool()).adjustedLevel(msg.source(), 0))))
{
mob.location().show(mob,null,null,CMMsg.MSG_OK_VISUAL,L("The shield around <S-NAME> blocks off @x1!",msg.tool().name()));
return false;
}
return super.okMessage(myHost,msg);
} | 9 |
private void netTest() throws InterruptedException{
URL netTest = null;
try{
netTest = new URL("http://themoneyconverter.com");
} catch(MalformedURLException e){
System.out.println(e+"test");}
try {
InputStream xml = netTest.openStream();
} catch (IOException ex) {
Logger.getLogger(XmlParser.class.getName()).log(Level.SEVERE, null, ex);
stop();
}
} | 2 |
protected int deltaDBtoDeltaInfIndex(int curDB, int dDB) {
int dII;
if (curDB <= 0) {
if (dDB <= 0) {
// NEG NEG
// no penalty
dII = 0;
}
else {
// NEG POS
// penalty if dDB is big enough
dII = (dDB + curDB > 0)? (dDB + curDB) : 0;
}
}
else {
if (dDB >= 0) {
// POS POS
// full penalty
dII = dDB;
}
else {
// POS NEG
// full or partial gain
dII = (dDB + curDB <= 0)? -curDB : dDB;
}
}
return dII;
} | 5 |
private void parseArgs(ParseToken token, String[] args)
throws CouldNotParseException {
if (args.length > 2) {
throw new CouldNotParseException();
} else if (args.length == 1) {
String arg = args[0].trim();
if (Character.isLowerCase(arg.charAt(0))
&& !this.parentIds.contains(arg)) {
token.setId(arg);
this.parentIds.add(arg);
}
else {
throw new CouldNotParseException();
}
}
else if (args.length == 2) {
String arg1 = args[0].trim();
String arg2 = args[1].trim();
// Must have a parent in this case, the first argument is the ID of
// the parent
if (Character.isLowerCase(arg1.charAt(0))
&& this.parentIds.contains(arg1.trim())) {
token.setParent(arg1);
// If it is a parent itself, the second argument will be a lower
// case
if (Character.isLowerCase(arg2.charAt(0))) {
// Can't have duplicates with the same ID
if (this.parentIds.contains(arg2)) {
throw new CouldNotParseException();
}
else {
token.setId(arg2);
this.parentIds.add(arg2);
}
}
else {
token.setValue(arg2.replace("\"", "").replace("'", "")
.trim());
}
}
else {
throw new CouldNotParseException();
}
}
else {
throw new CouldNotParseException();
}
} | 9 |
public FixtureDef[] build() {
FixtureDef[] fixtures = new FixtureDef[shapes.size()];
Vector c1 = new Vector(allVertices.get(0));
Vector c2 = new Vector(c1);
for (Vector v : allVertices) {
c1.x = Math.min(v.x, c1.x);
c1.y = Math.min(v.y, c1.y);
c2.x = Math.max(v.x, c2.x);
c2.y = Math.max(v.y, c2.y);
}
Vector dimension = c2.minus(c1);
float xScale = size.x / dimension.x;
float yScale = size.y / dimension.y;
Vector center = c2.plus(c1).scale(.5f);
for (int i = 0; i < shapes.size(); i++){
Vector[] vertList = shapes.get(i);
Vec2[] finalVerts = new Vec2[vertList.length];
for (int j = 0; j < vertList.length; j++){
Vec2 v = new Vec2(vertList[j].x, vertList[j].y);
v = v.sub(new Vec2(center.x, center.y)).add(new Vec2(center.x, center.y));
finalVerts[j] = new Vec2(v.x * xScale, v.y * yScale);
}
PolygonShape shape = new PolygonShapeBuilder().v(finalVerts).build();
FixtureDef fixture = new FixtureDefBuilder().shape(shape).build();
if (friction != 0)
fixture.friction = friction;
if (density != 0)
fixture.density = density;
if (restitution != 0)
fixture.restitution = restitution;
fixtures[i] = fixture;
}
return fixtures;
} | 6 |
public long getLong(String key) throws JSONException {
Object object = this.get(key);
try {
return object instanceof Number ? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a long.");
}
} | 2 |
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ListIterator<Forme> it = model.getAllFormes().listIterator();
// Parcours de la liste pour redessiner toutes les formes
while (it.hasNext()) {
Forme forme = it.next();
g2d.setStroke(forme.getStroke());
forme.draw(g2d);
if (forme.isSelected()) {
forme.selectionner(g2d);
}
}
// Si courante a été initialisée
if (courante != null) {
g2d.setStroke(courante.getStroke());
courante.draw(g2d);
}
// Gestion du curseur de redimensionnement
if (this.model.getRedimensionnement() == model.NORTH_WEST_CURSOR) {
this.setCursor(new Cursor(Cursor.NW_RESIZE_CURSOR));
} else if (this.model.getRedimensionnement() == model.NORTH_EAST_CURSOR ) {
this.setCursor(new Cursor(Cursor.NE_RESIZE_CURSOR));
} else if (this.model.getCreation()) {
this.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
} else {
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
if (this.rectangleSelection != null) {
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
rectangleSelection.draw(g2d);
g2d.setComposite(AlphaComposite.SrcOver.derive(1.0f));
}
} | 7 |
@Override
public void perform(CommandSender sender, String[] args) {
List<String> GymTypes = instance.getConfig().getStringList("GymTypes");
ChatColor statusColour;
if (args.length == 1)
{
for (String i : GymTypes)
{
if (args[0].equalsIgnoreCase(i))
{
boolean gymStatus = instance.getConfig().getBoolean("Gyms." + i + ".Status");
ChatColor gymColor = ChatColor.valueOf(instance.getConfig().getString("Gyms." + i + ".Color"));
String status = gymStatus ? "Open" : "Closed";
statusColour = gymStatus ? ChatColor.GREEN : ChatColor.RED;
inform(sender, gymColor + i + informColor + " gym is : " + statusColour + status);
}
}
}
} | 5 |
@Override
public int move() {
int rockMoves = 0,rockWins = 0;
int paperMoves = 0, paperWins = 0;
int scissorMoves = 0, scissorWins = 0;
for(int i = 0;i<moves.size();i++){
if(moves.get(i)==RPSPlayer.ROCK){
rockMoves++;
if(results.get(i)){
rockWins++;
}
}else if(moves.get(i)==RPSPlayer.PAPER){
paperMoves++;
if(results.get(i)){
paperWins++;
}
}else{
scissorMoves++;
if(results.get(i)){
scissorWins++;
}
}
}
return bestMove(rockMoves,rockWins,paperMoves,paperWins,scissorMoves,scissorWins);
} | 6 |
private static List<AttackTransferMove> getNecessarySupportMoves(BotState state, Region neededHelpRegion,
int missingArmies, int minimumUsefulArmies) {
List<AttackTransferMove> out = new ArrayList<>();
List<Region> ownedNeighbors = new ArrayList<>();
ownedNeighbors.addAll(neededHelpRegion.getOwnedNeighbors(state));
ownedNeighbors = RegionValueCalculator.sortRegionsByDefenceRegionValue(state, ownedNeighbors);
int stillMissingArmies = missingArmies;
for (int i = ownedNeighbors.size() - 1; i >= 0; i--) {
Region ownedNeighbor = ownedNeighbors.get(i);
int neededDefenceArmies;
if (ownedNeighbor.getDefenceRegionValue() < RegionValueCalculator.LOWEST_MEDIUM_PRIORITY_VALUE
|| (neededHelpRegion.getDefenceRegionValue() >= RegionValueCalculator.LOWEST_HIGH_PRIORITY_VALUE && ownedNeighbor
.getDefenceRegionValue() < RegionValueCalculator.LOWEST_HIGH_PRIORITY_VALUE)) {
neededDefenceArmies = 0;
} else {
neededDefenceArmies = NeededArmiesCalculator.getNeededDefenseArmies(ownedNeighbor).defendingArmiesFullDeployment;
}
int possibleSpareArmies = Math.min(ownedNeighbor.getIdleArmies(), ownedNeighbor.getArmiesAfterDeployment()
- neededDefenceArmies);
int transferingArmies = Math.min(stillMissingArmies, possibleSpareArmies);
if (transferingArmies > 0) {
AttackTransferMove atm = new AttackTransferMove(state.getMyPlayerName(), ownedNeighbor,
neededHelpRegion, transferingArmies);
out.add(atm);
}
stillMissingArmies -= transferingArmies;
minimumUsefulArmies -= transferingArmies;
}
// if (stillMissingArmies == 0) {
if (minimumUsefulArmies <= 0) {
return out;
} else {
return new ArrayList<AttackTransferMove>();
}
} | 6 |
private void removeMarkedAlignements(boolean[][] marked) {
for (int i = 0; i < marked.length; i++) {
for (int j = 0; j < marked[i].length; j++) {
if (marked[i][j]) {
game.flush(i, j);
marked[i][j] = false;
}
}
}
} | 3 |
private boolean setIsOK(byte[] set)
{
// byte starting[] = new byte[row.length];
// System.out.println("Looking at set " + java.util.Arrays.toString(set));
for (int i=0; i < set.length - 1; i++)
{
for (int j=i + 1; j < set.length; j++)
{
// System.out.println("Comparing set[" + i + "](" + set[i] + ") and set[" + j + "](" + set[j] + ")");
if (set[i] == set[j] && set[i] != NULL_VAL && set[j] != NULL_VAL)
{
// System.out.println("Set is not OK.");
return false;
}
}
}
// System.out.println("Set is OK");
return true;
} | 5 |
public static void main(String[] args) {
/*
* Enter your code here. Read input from STDIN. Print output to STDOUT.
* Your class should be named Solution.
*/
Scanner in = new Scanner(System.in);
int res;
String n = in.nextLine();
String[] n_split = n.split(" ");
int _a_size = Integer.parseInt(n_split[0]);
int _k = Integer.parseInt(n_split[1]);
int[] _a = new int[_a_size];
int _a_item;
String next = in.nextLine();
String[] next_split = next.split(" ");
for (int _a_i = 0; _a_i < _a_size; _a_i++) {
_a_item = Integer.parseInt(next_split[_a_i]);
_a[_a_i] = _a_item;
}
res = pairs(_a, _k);
System.out.println(res);
in.close();
} | 1 |
public static void main(String[] args) {
setLookAndFeel();
boolean firstLaunch = ConfigManager.getInstance().getProperties().getProperty("virgin").equals("true");
boolean isLauncherUpdateRequired = launcherUpdateRequired();
System.out.println("First launch: " + firstLaunch + " | launcher update required: " + isLauncherUpdateRequired);
if (!firstLaunch && !isLauncherUpdateRequired) {
MainFrame mf = new MainFrame();
mf.setVisible(true);
} else {
// Prepare to loose our virginity
FirstLaunch fl = new FirstLaunch();
fl.setVisible(true);
}
} | 2 |
public boolean execute()
{
updateGraph();
if (!trace)
rp.reset(g.size());
else
nextnode = 0;
final int nn = (n < 0 ? Network.size() : n);
if (method.equals("stats")) {
IncrementalStats stats = new IncrementalStats();
for (int i = 0; i < nn; ++i)
stats.add(nextDegree());
System.out.println(name + ": " + stats);
} else if (method.equals("freq")) {
IncrementalFreq stats = new IncrementalFreq();
for (int i = 0; i < nn; ++i)
stats.add(nextDegree());
stats.print(System.out);
System.out.println("\n\n");
} else if (method.equals("list")) {
System.out.print(name + ": ");
for (int i = 0; i < nn; ++i)
System.out.print(nextDegree() + " ");
System.out.println();
}
return false;
} | 8 |
public static void display(tile[][] input) {
System.out.println(" 1 2 3 4 5 6 7 8 9 10");
for (int y = 0; y < 10; y++) {
System.out.print(y + 1 + " " + ((y != 9) ? " " : ""));
for (int x = 0; x < 10; x++) {
if (board[x][y].getFlag()) {
System.out.print("F ");
} else if (board[x][y].getCovered()) {
System.out.print(value(board[x][y]) + " ");
} else {
System.out.print("? ");
}
}
System.out.print("\n");
}
} | 5 |
@Override
protected void onPart(String channel, String sender, String login, String hostname)
{
super.onPart(channel, sender, login, hostname);
int targettab = 0;
int i = 0;
while(true)
{
try
{
if(Main.gui.tabs.get(i).title.equalsIgnoreCase(channel) || Main.gui.tabs.get(i).title.substring(1).equalsIgnoreCase(channel))
{
targettab = i;
break;
}
else
{
i++;
}
}
catch(Exception e)
{
break;
}
}
if(!sender.equals(Main.user))
{
Main.gui.tabs.get(targettab).addMessage(sender + " leaves " + channel);
}
Main.gui.tabs.get(targettab).onUpdate();
} | 5 |
public void vote(Client client, String answer) {
synchronized (votes) {
if (!votes.containsKey(client.getName())
&& answers.contains(answer)) {
if (closed) {
String popup = Popup
.create("Umfrage",
String.format("Umfrage #%s - Problem", id),
"Du hast dir f�r die Beantwortung der Umfrage zu lange Zeit gelassen.",
400, 300);
client.send(popup);
} else {
votes.put(client.getName(), answer);
}
}
}
} | 3 |
@Override
public String toScript() {
if (script != null) return script;
StringBuilder sb = new StringBuilder(1000);
// Build all hyperplanes x*(p-q) >= 0
sb.append("my $hyper = new Matrix<Rational>([");
boolean first = true;
for (Point point : this.points) {
// Corrects some problems for bad voronoi cells
if (!this.orientationCheck(point)) continue;
if (!first) {
sb.append(",");
}
else {
first = false;
}
sb.append("[0.0");
for (int i = 0; i < dim; i++) {
sb.append(", " +
(this.center.getComponents()[i] - point.getComponents()[i]));
}
sb.append("]");
}
sb.append("]);");
// Build the affine hyperplane (x-p)*p = 0
sb.append("my $aff = new Matrix<Rational>([");
double val = 0;
for (double c : this.center.getComponents())
val -= c * c;
sb.append("[" + val);
for (int i = 0; i < this.center.getComponents().length; i++) {
sb.append(" , " + this.center.getComponents()[i]);
}
sb.append("]]);");
sb.append("my $poly = new Polytope(INEQUALITIES=>$hyper, EQUATIONS=>$aff);");
sb.append("print $poly->BOUNDED;print \"\\n\";");
sb.append("print $poly->VERTICES;");
sb.append("print \"-----\\n\";");
sb.append("print $poly->GRAPH->EDGES;");
sb.append("print \"-----\\n\";");
sb.append("print $poly->FACETS;");
this.script = sb.toString();
return this.script;
} | 7 |
private void check(Object probe, Object current) {
List<Object> nl = graph.get(current);
if (nl == null) {
return;
}
for (Object o : nl) {
if (o == probe) {
throw new ComponentException("Circular reference to: "
+ probe);
} else {
check(probe, o);
}
}
} | 3 |
private void button_clean_red_listMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button_clean_red_listMousePressed
if(frame_index_selected!=-1)
{
if(current_frame==null)
{
Element new_frame = hitboxes_doc.createElement("Frame");
new_frame.setAttribute("number", ""+(frame_index_selected+1));
if(current_move==null)
{
Element new_move = hitboxes_doc.createElement("Move");
new_move.setAttribute("name", ""+list_moves.getSelectedValue());
hitboxes_doc.getFirstChild().appendChild(new_move);
current_move=new_move;
}
current_move.appendChild(new_frame);
current_frame=new_frame;
}
int i=0;
boolean hitboxes_exist=false;
for(Node hitboxes_node=current_frame.getFirstChild();hitboxes_node!=null;hitboxes_node=hitboxes_node.getNextSibling())//Hitbox loop
{
if(hitboxes_node.getNodeName().equals("Hitboxes"))
{
if(((Element)hitboxes_node).getAttribute("variable").equals("red"))
{
hitboxes_exist=true;
while(hitboxes_node.hasChildNodes())
hitboxes_node.removeChild(hitboxes_node.getFirstChild());
}
}
}
if(!hitboxes_exist)
{
Element new_hitboxes=hitboxes_doc.createElement("Hitboxes");
new_hitboxes.setAttribute("to_opponent", "no");
new_hitboxes.setAttribute("variable", "red");
current_frame.appendChild(new_hitboxes);
}
updateHitboxes(current_frame);
}
else
{
JOptionPane.showMessageDialog(null, "Select a frame first.", "Be careful", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_button_clean_red_listMousePressed | 8 |
public void update(){
if(core.SubTerra.getLevel()==null) return;
l = core.SubTerra.getLevel();
setReletiveTo(l.p);
for(Entity e: l.ents){
e.update();
}
for(int xx=0;xx<Level.SIZE;xx++){
for(int yy=0;yy<Level.SIZE;yy++){
if(l.worldDamage[xx][yy]<0){
l.world[xx][yy]=TileType.AIR;
}
}
}
repaint();
} | 5 |
@Test
public void preAuthCompletionGreaterAmount() throws BeanstreamApiException {
CardPaymentRequest paymentRequest = getCreditCardPaymentRequest(
getRandomOrderId("GAS"), "120.00");
PaymentResponse response = beanstream.payments()
.preAuth(paymentRequest);
try {
if (response.isApproved()) {
PaymentResponse authResp = beanstream.payments()
.preAuthCompletion(response.id, 200);
if (authResp.isApproved()) {
Assert.fail("This auth completion should be not be approved because a lower amount has been pre authorized");
}
}
} catch (BeanstreamApiException ex) {
Assert.assertEquals("Http status code did not match expected.", 400, ex.getHttpStatusCode());
Assert.assertEquals("Error category did not match expected", 2, ex.getCategory());
Assert.assertEquals("Error code did not match expected", 208, ex.getCode());
}
} | 3 |
@Override
public void endElement(String s, String s1, String element) throws SAXException {
// if end of book element add to list
if (element.equals("book")) {
bookL.add(bookTmp);
}
if (element.equalsIgnoreCase("isbn")) {
bookTmp.setIsbn(tmpValue);
}
if (element.equalsIgnoreCase("title")) {
bookTmp.setTitle(tmpValue);
}
if (element.equalsIgnoreCase("author")) {
bookTmp.getAuthors().add(tmpValue);
}
if (element.equalsIgnoreCase("price")) {
bookTmp.setPrice(Integer.parseInt(tmpValue));
}
if (element.equalsIgnoreCase("regDate")) {
try {
bookTmp.setRegDate(sdf.parse(tmpValue));
} catch (ParseException e) {
System.out.println("date parsing error");
}
}
} | 7 |
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String urlPath = request.getParameter("action");
String reqHelperClassName = (String) props.get(urlPath);
if (reqHelperClassName != null) {
try {
ActionInterface helper = (ActionInterface) Class.forName(reqHelperClassName).newInstance();
String nextView = helper.execute(request);
if (!nextView.contains("controller")) {
nextView = "/WEB-INF/Page/" + nextView;
}
rds = request.getRequestDispatcher(nextView);
rds.forward(request, response);
} catch (Exception ex) {
}
}
} | 3 |
protected synchronized int getRarestPiece(Peer peer)
{
int[] availability = new int[this.client_info.getNumber_of_pieces()];
//compute availability
for (Peer aPeer:connectedPeers)
{
availability = RUBTToolKit.recomputeAvailability(availability, aPeer.getBitfield());
}
ArrayList<Integer> rarestPieces = new ArrayList<Integer>();
for (int pieceIndex = 0; pieceIndex < this.client_info.getNumber_of_pieces(); pieceIndex++)
{
if (!this.client_info.getClient_bitfield()[pieceIndex] && peer.getBitfield()[pieceIndex] && !this.pieces_downloading.contains(Integer.valueOf(pieceIndex)))
{
if (rarestPieces.isEmpty())
{
//found the first piece in the list the peer has and it has not been downloaded yet
rarestPieces.add(Integer.valueOf(pieceIndex));
}
else if (availability[pieceIndex] < availability[rarestPieces.get(0)])
{
//found a piece more rare
rarestPieces.removeAll(rarestPieces);
rarestPieces.add(Integer.valueOf(pieceIndex));
}
}
}
Random r = new Random(System.currentTimeMillis());
if (rarestPieces.isEmpty())
{
return -1;
}
else
{
//choose a random piece from rarestPieces
return rarestPieces.get(r.nextInt(rarestPieces.size()));
}
} | 8 |
private classifiedData classify(String imageFilePath){
classifiedData DataIn = new classifiedData();
try {
// System.out.println("the file output: " + imageFilePath);
//load the image as a buffered image (works multiple features from a single image)
BufferedImage img = ImageIO.read(new FileInputStream(imageFilePath));
//This is for readng out the file name and the classification from the image file name
//Assuming only need last 10 chars
//Input name of file unique , removes the path and the .jpg from the file
String fileName = imageFilePath.substring((imageFilePath.length() - 8), imageFilePath.length() - 4);
//Fill the data object
DataIn.putImgName(fileName);
DataIn.putClassification(getClassification(fileName));
DataIn.putCEDDData(GetCedd(img));
DataIn.putFCTHData(getFCTH(img));
} catch (Exception e) {
System.err.println("Error indexing images.");
}
if(DataIn.isComplete()){
return DataIn;
}
return null;
} | 2 |
public void run() {
Selector selector = DatagramAcceptorDelegate.this.selector;
for (;;) {
try {
int nKeys = selector.select();
registerNew();
if (nKeys > 0) {
processReadySessions(selector.selectedKeys());
}
flushSessions();
cancelKeys();
if (selector.keys().isEmpty()) {
synchronized (lock) {
if (selector.keys().isEmpty()
&& registerQueue.isEmpty()
&& cancelQueue.isEmpty()) {
worker = null;
try {
selector.close();
} catch (IOException e) {
ExceptionMonitor.getInstance()
.exceptionCaught(e);
} finally {
DatagramAcceptorDelegate.this.selector = null;
}
break;
}
}
}
} catch (IOException e) {
ExceptionMonitor.getInstance().exceptionCaught(e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
ExceptionMonitor.getInstance().exceptionCaught(e1);
}
}
}
} | 9 |
private void ajouterSeance() {
System.out.println("Liste de vos modules :");
Professeur professeur = (Professeur) this.modeleApplication.getCurrent();
ArrayList<Module> modules = this.universite.getModulesParProfesseur(professeur);
if (modules.isEmpty()) {
System.out.println("Vous n'avez aucun module");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(BatchProfesseur.class.getName()).log(Level.SEVERE, null, ex);
}
this.afficherMenuPersonnel();
}
for (int i = 0; i< modules.size(); i++) {
System.out.println(i+1+"- "+modules.get(i).getCode());
}
System.out.println("Pour quel module souhaitez vous ajouter une séance ?");
int indice = scan.nextInt();
if (indice < 1 || indice > modules.size()+1) {
System.out.println("Cet indice n'est pas bon. Retour au choix de module.");
}
// Type
System.out.println("Type de la séance (CM, TD ou TP)");
String typeCours = this.calculerTypeCours();
// Date
System.out.println("Date de la séance");
Date dateCours = this.calculerDate();
// Heure
System.out.println("Heure de la séance");
int heureCours = this.calculerHeureCours();
//Duree
System.out.println("Durée de la séance");
int dureeCours = calculerDureeCours();
Seance s = new Seance(typeCours, modules.get(indice-1).getCode(), dateCours, heureCours, dureeCours, null);
universite.addSeance(s);
// Salle
Salle salleCours = calculerSalleCours(s, (Formation)modules.get(indice - 1).getSuccessor());
} | 5 |
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception
{
HashMap<String, HashMap<String, Integer>> map =
new HashMap<String, HashMap<String,Integer>>();
BufferedReader reader = filePath.toLowerCase().endsWith("gz") ?
new BufferedReader(new InputStreamReader(
new GZIPInputStream( new FileInputStream( filePath)))) :
new BufferedReader(new FileReader(new File(filePath
)));
String nextLine = reader.readLine();
int numDone =0;
while(nextLine != null)
{
StringTokenizer sToken = new StringTokenizer(nextLine, "\t");
String sample = sToken.nextToken();
String taxa= sToken.nextToken();
int count = Integer.parseInt(sToken.nextToken());
if( sToken.hasMoreTokens())
throw new Exception("No");
HashMap<String, Integer> innerMap = map.get(sample);
if( innerMap == null)
{
innerMap = new HashMap<String, Integer>();
map.put(sample, innerMap);
}
if( innerMap.containsKey(taxa))
throw new Exception("parsing error " + taxa);
innerMap.put(taxa, count);
nextLine = reader.readLine();
numDone++;
if( numDone % 1000000 == 0 )
System.out.println(numDone);
}
return map;
} | 6 |
public SyncDownloadView(final JPanel panel) {
// Build the left side table
final SyncDownloadTableModel model = new SyncDownloadTableModel();
final JTable table = new JTable(model);
final JScrollPane left = new JScrollPane(table);
// Build the right side info
final JPanel right = new JPanel();
right.setBorder(BorderFactory.createEtchedBorder());
right.setLayout(new GridLayout(2, 2));
final JLabel syncCountLabel = new JLabel("Sync Count:");
right.add(syncCountLabel);
final JLabel countLabel = new JLabel("");
right.add(countLabel);
final JButton totalToSyncButton = new JButton("Count Total To Sync");
totalToSyncButton.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
int total = 0;
for (int i = 0; i < model.getRowCount(); i++) {
if (model.shouldSync(i)) {
total++;
}
}
countLabel.setText(String.valueOf(total));
}
});
right.add(totalToSyncButton);
// Add split so user can move the parts
final JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
pane.setOneTouchExpandable(true);
pane.setDividerLocation(150);
final Dimension minSize = new Dimension(100, 50);
left.setMinimumSize(minSize);
right.setMinimumSize(minSize);
panel.add(pane, BorderLayout.CENTER);
} | 2 |
public static void main(String[] args) {
//Creates the return value for the highest domino in the series.
String highestDomino = null;
//Creates the placeholder for the weight of the highest domino.
int highestValue = 0;
//Creates the return value for the lowest domino in the series.
String lowestDomino = null;
//Creates the placeholder for the weight of the lowest domino.
int lowestValue = 13;
//Counter for the number of blanks.
int blanksCount = 0;
//Counter for the number of doubles.
int doublesCount = 0;
//Generates the dominos.
System.out.println("20 Randomly generated dominos:");
for (int count = 0; count < 20; count++) {
Domino domino = new Domino();
//Checks to see if the new domino is higher, and if so
//sets it as the new highest.
if (domino.getWeight() > highestValue) {
highestValue = domino.getWeight();
highestDomino = domino.toString();
}
//Checks to see if the new domino is lower, and if so
//sets it as the new lowest.
if (domino.getWeight() < lowestValue) {
lowestValue = domino.getWeight();
lowestDomino = domino.toString();
}
//Prints the domino.
System.out.println(domino.toString());
//Counts if the domino is blank.
if (domino.isBlank()) {
blanksCount++;
}
//Counts of the domino is a double.
if (domino.isDouble()) {
doublesCount++;
}
}
//Returns the asked for information.
System.out.println("Heaviest domino with higher rank: " + highestDomino);
System.out.println("Lightest domino with lowest rank: " + lowestDomino);
System.out.println("Number of doubles: " + doublesCount);
System.out.println("Number of blanks: " + blanksCount);
} | 5 |
public boolean isBlack(BufferedImage image, int posX, int posY) {
if(erase) {
if(flat) {
if(image.getRGB(posX, posY) == Color.RED.getRGB())
return true;
} else {
if(image.getRGB(posX, posY) == Color.WHITE.getRGB())
return true;
}
} else {
if(image.getRGB(posX, posY) == Color.BLACK.getRGB())
return true;
}
return false;
} | 5 |
public static InputStream inputStreamFrom(final Object object) throws IOException {
if (object instanceof InputStream) return (InputStream)object;
if (object instanceof File) return IO._inputStreamFrom_((File)object);
if (object instanceof ByteArraySection) return IO._inputStreamFrom_((ByteArraySection)object);
if (object instanceof ByteArray) return IO._inputStreamFrom_((ByteArray)object);
if (object instanceof byte[]) return IO._inputStreamFrom_((byte[])object);
throw new IOException();
} | 5 |
private String scanYamlDirectiveValue () {
while (peek() == ' ')
forward();
String major = scanYamlDirectiveNumber();
if (peek() != '.')
throw new TokenizerException("While scanning for a directive value, expected a digit or '.' but found: " + ch(peek()));
forward();
String minor = scanYamlDirectiveNumber();
if (NULL_BL_LINEBR.indexOf(peek()) == -1)
throw new TokenizerException("While scanning for a directive value, expected a digit or '.' but found: " + ch(peek()));
return major + "." + minor;
} | 3 |
public static Database getAccessionType(String accession){
if(accession.contains("UNIMOD")){
return Database.UNIMOD;
} else if(!accession.contains("UNIMOD") && accession.contains("MOD")){
return Database.PSIMOD;
} else if(!accession.contains("MOD") && NumberUtils.isNumber(accession)){
return Database.UNIMOD;
} else{
return Database.NONE;
}
} | 5 |
@Override
public void start(Stage primaryStage) throws MalformedURLException {
File f = new File("img/1.png");
System.out.println(f.getAbsolutePath());
Image image = new Image(f.toURI().toURL().toString());
// // simple displays ImageView the image as is
BackgroundRemoval br = new BackgroundRemovalImpl();
BufferedImage bf = null;
try {
bf = ImageIO.read(new File("img/gg.png"));
br.setBufferedImage(bf);
br.remove();
bf = br.getBufferedImage();
} catch (IOException ex) {
System.out.println("Image failed to load.");
}
WritableImage wr = null;
if (bf != null) {
wr = new WritableImage(bf.getWidth(), bf.getHeight());
PixelWriter pw = wr.getPixelWriter();
for (int x = 0; x < bf.getWidth(); x++) {
for (int y = 0; y < bf.getHeight(); y++) {
pw.setArgb(x, y, bf.getRGB(x, y));
}
}
}
ImageView iv1 = new ImageView();
iv1.setImage(wr);
StackPane root = new StackPane();
root.getChildren().add(iv1);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
} | 4 |
public static DPCSchema loadSchemaResource(String aResourcePath) throws IOException {
ArrayList<DPCColumnSchema> tResultColumnSchemaList = new ArrayList<DPCColumnSchema>();
InputStream tResourceInputStream = null;
BufferedReader tResourceBufferedReader = null;
tResourceInputStream = mInstance.getClass().getClassLoader().getResourceAsStream(aResourcePath);
if (tResourceInputStream == null)
throw new FileNotFoundException(aResourcePath);
try {
tResourceBufferedReader = new BufferedReader(new InputStreamReader(tResourceInputStream, StringFormatConstants.TEXT_FORMAT_UTF8));
while (true) {
String tLine = tResourceBufferedReader.readLine();
if (tLine == null) {
break;
}
String tTrimedLine = tLine.trim();
if (tTrimedLine.length() == 0
|| tTrimedLine.startsWith(Ini.COMMENT_LINE_START_SEMICOLON)
|| tTrimedLine.startsWith(Ini.COMMENT_LINE_START_SHARP)) {
continue;
}
try {
String[] tSchemaTypeName = tTrimedLine.split(DefinitionConstants.DEFINITION_SCHEMA_ALIAS_TYPE_SEPARATOR);
tResultColumnSchemaList.add(new DPCColumnSchema(tSchemaTypeName[0].trim(), tSchemaTypeName[1].trim()));
} catch (Exception e) {
throw new RuntimeException(aResourcePath + " にスキーマの設定不備が有ります。該当行 : " + tTrimedLine, e);
}
}
} finally {
if (tResourceBufferedReader != null)
tResourceBufferedReader.close();
}
return new DPCSchema(tResultColumnSchemaList);
} | 8 |
public String setName(final String name) {
if (name == null)
throw new IllegalArgumentException("name must not be null");
if (name.length() == 0)
throw new IllegalArgumentException("name must not be an empty string");
this.name = name;
return name;
} | 2 |
public String loadMedico() {
Map parametros = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String idMed = parametros.get("idMedico").toString();
Integer id = Integer.parseInt(idMed);
int i;
for (i = 0; i < medicosBean.size(); i++) {
if (medicosBean.get(i).getIdMedico().equals(id)) {
break;
}
}
this.idMedico = id;
this.nome = medicosBean.get(i).getNome();
this.crm = medicosBean.get(i).getCrm();
return "carrega";
} | 2 |
public void visit_fcmpl(final Instruction inst) {
stackHeight -= 2;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
boolean ifBlockCombination(ArrayList<String> blockSet){
boolean ifNoCombine = false;
//這邊檢查同block name的結合
String name = new String(blockSet.get(0));
for(String a : blockSet){
if(name.equals(a) == false){
ifNoCombine = true;
break;
}
}
if(ifNoCombine == false)
return true;
//這邊檢查不同block name的結合
for(String bn : blockCombination){
ifNoCombine = false;
for(String a : blockSet){
if(bn.contains(a) == false)
ifNoCombine = true;
}
if(ifNoCombine == false)
return true;
}
return false;
} | 7 |
public void setCtrMoaTipo(String ctrMoaTipo) {
this.ctrMoaTipo = ctrMoaTipo;
} | 0 |
public static String toString(JSONObject o) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(o.getString("name")));
sb.append("=");
sb.append(escape(o.getString("value")));
if (o.has("expires")) {
sb.append(";expires=");
sb.append(o.getString("expires"));
}
if (o.has("domain")) {
sb.append(";domain=");
sb.append(escape(o.getString("domain")));
}
if (o.has("path")) {
sb.append(";path=");
sb.append(escape(o.getString("path")));
}
if (o.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
} | 4 |
private Message decideErr(Message oMsg){
Message sMsg = new Message();
sMsg.setRecipient(oMsg.getSender());
sMsg.setSender(oMsg.getSender());
for(int i = 0; i < oMsg.getHeader().size(); i++)
sMsg.addHeader(oMsg.getHeader().get(i));
if (error == null) {
} else switch (error) {
case "syntax":
sMsg = this.syntaxErrorMail(sMsg);
break;
case "noneprop":
sMsg = this.nonePropError(sMsg);
break;
case "nonerecipient":
sMsg = this.noneRecipientError(sMsg);
break;
case "semantic":
sMsg = this.semanticErrorMail(sMsg);
break;
}
return sMsg;
} | 6 |
public void run() {
if (arena.isClosed()) {
sender.sendMessage(OITG.prefix + ChatColor.RED + "That arena is closed.");
return;
}
if (arena.isIngame()) {
sender.sendMessage(OITG.prefix + ChatColor.RED + "A round is already in progress in that arena.");
return;
}
if (arena.getPlayerCount() < 2) {
sender.sendMessage(OITG.prefix + ChatColor.RED + "There aren't enough players in that arena to start the round.");
return;
}
if (args.length == 1) {
arena.setTimer(0);
sender.sendMessage(OITG.prefix + ChatColor.GREEN + "Forced the round in arena " + arena.toString() + " to start immediately.");
arena.broadcast(ChatColor.GREEN + "The round was started by an administrator.");
return;
}
int delay = -1;
try {
delay = Integer.parseInt(args[1]);
} catch (NumberFormatException e) { }
if (delay < 0) {
sender.sendMessage(OITG.prefix + ChatColor.RED + "The delay must be a number no less than zero.");
return;
}
arena.setStage(1);
arena.setTimer(delay);
sender.sendMessage(OITG.prefix + ChatColor.GREEN + "Forced the round in arena " + arena.toString() +
" to start in " + delay + " seconds.");
} | 6 |
public void setFind(int i, String s) {
this.finds.set(i, s);
} | 0 |
private void threadRunner()
{
try
{
while(true)
{
Runnable runnable = _queue.take();
//System.err.println(Thread.currentThread().getName()
//+ ": Executing event.");
try
{
runnable.run();
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
} | 3 |
@Test
public void testConnected() {
// initial : 0 1 2 3 4
// union(0, 1) : 1 1 2 3 4
// union(2, 3) : 1 1 3 3 4
// union(3, 1) : 1 1 3 1 4
// 1 4
// 0 3
// 2
QuickUnion spy = Mockito.spy(new QuickUnion(5));
when(spy.getRoot(1)).thenReturn(1);
when(spy.getRoot(0)).thenReturn(1);
when(spy.getRoot(3)).thenReturn(1);
when(spy.getRoot(2)).thenReturn(1);
when(spy.getRoot(4)).thenReturn(4);
assertThat(spy.connected(0, 4), is(not(true)));
assertThat(spy.connected(1, 4), is(not(true)));
assertThat(spy.connected(2, 4), is(not(true)));
assertThat(spy.connected(3, 4), is(not(true)));
assertThat(spy.connected(0, 1), is(true));
assertThat(spy.connected(0, 2), is(true));
assertThat(spy.connected(0, 3), is(true));
assertThat(spy.connected(1, 2), is(true));
assertThat(spy.connected(1, 3), is(true));
assertThat(spy.connected(2, 3), is(true));
} | 0 |
private RoomState readRoom( InputStream in, int squaresH, int squaresV ) throws IOException {
RoomState room = new RoomState();
room.setOxygen( readInt(in) );
for (int h=0; h < squaresH; h++) {
for (int v=0; v < squaresV; v++) {
// Dunno what the third int is. The others are for fire.
// Values in the wild: 0-100 / 0-100 / -1.
// It is not related to hull breaches.
room.addSquare( readInt(in), readInt(in), readInt(in) );
}
}
return room;
} | 2 |
Stats(Collection<VoieEnum> voies) {
voituresEnAttentes = new HashMap<VoieEnum, AtomicInteger>();
attenteParVoie = new HashMap<VoieEnum, AtomicLong>();
voituresEngageesParVoies = new HashMap<VoieEnum, AtomicInteger>();
voituresEntrees = new HashMap<VoieEnum, AtomicInteger>();
voituresSorties = new HashMap<VoieEnum, AtomicInteger>();
voituresEngagees = new AtomicInteger(0);
for (VoieEnum voie : voies) {
voituresEnAttentes.put(voie, new AtomicInteger(0));
attenteParVoie.put(voie, new AtomicLong(0));
voituresEngageesParVoies.put(voie, new AtomicInteger(0));
voituresEntrees.put(voie, new AtomicInteger(0));
voituresSorties.put(voie, new AtomicInteger(0));
}
} | 1 |
@Override
public void unInvoke()
{
Item I=null;
if(affected instanceof Item)
I=(Item)affected;
super.unInvoke();
if((canBeUninvoked())&&(I!=null)&&(I.owner() instanceof MOB)
&&(!I.amWearingAt(Wearable.IN_INVENTORY)))
{
final MOB mob=(MOB)I.owner();
if((!mob.amDead())
&&(CMLib.flags().isInTheGame(mob,false)))
{
mob.tell(L("@x1 loosens its grip on your neck and falls off.",I.name(mob)));
I.setRawWornCode(0);
mob.location().moveItemTo(I,ItemPossessor.Expire.Player_Drop);
}
}
} | 7 |
public DefaultLinkFinder(final String content) {
if (content == null || "".equals(content.trim())) {
throw new IllegalArgumentException("content cannot be null");
}
this.content = content;
} | 2 |
private void firePeerDisconnected() {
for (PeerActivityListener listener : this.listeners) {
listener.handlePeerDisconnected(this);
}
} | 1 |
@After
public void teardown()
{
try{
if(connection!=null && !connection.isClosed())
{
drop.executeUpdate("Drop table Client");
connection.close();
connection = null;
}}
catch(Exception ex)
{
ex.printStackTrace();
}
} | 3 |
public RichGameMap(){
startPoint=new StartPoint();
landList.add(startPoint);
bareLands=new BareLand[58];
mines=new Mine[6];
int k=0;
for(int i=1;i<64;i++) {
if(i==14) {
hospital=new Hospital(i);
landList.add(hospital);
}else if(i==28){
toolHouse=new ToolHouse(i);
landList.add(toolHouse);
} else if(i==35){
giftHouse=new GiftHouse(i);
landList.add(giftHouse);
}else if(i==49){
prison=new Prison(i);
landList.add(prison);
} else if(i==63){
magicHouse=new MagicHouse(i);
landList.add(magicHouse);
} else {
bareLands[k]=new BareLand(i);
landList.add(bareLands[k]);
k++;
}
}
for(int i=0;i<6;i++){
mines[i]=new Mine(64+i);
landList.add(mines[i]);
}
} | 7 |
public void printMarket(){
if (deck == null){
return;
}
if (deck.getAskDeck() != null){
System.out.println("ASK:");
for(int i = 0; i < deck.getAskDeck().size(); i++){
System.out.print(deck.getAskDeck().get(i).getPrice());
System.out.print(deck.getAskDeck().get(i).isBid());
System.out.print(deck.getAskDeck().get(i).getTrader());
System.out.print(deck.getAskDeck().get(i).getSize());
System.out.print(deck.getAskDeck().get(i).getTime());
System.out.println();
}
}
if (deck.getBidDeck() != null){
System.out.println("BID:");
for(int i = 0; i < deck.getBidDeck().size(); i++){
System.out.print(deck.getBidDeck().get(i).getPrice());
System.out.print(deck.getBidDeck().get(i).isBid());
System.out.print(deck.getBidDeck().get(i).getTrader());
System.out.print(deck.getBidDeck().get(i).getSize());
System.out.print(deck.getBidDeck().get(i).getTime());
System.out.println();
}
}
if (deck.getTrades() != null){
System.out.println("TRADES:");
for(int i = 0; i < deck.getTrades().size(); i++){
System.out.print(deck.getTrades().get(i).getPrice());
System.out.print(deck.getTrades().get(i).isBid());
System.out.print(deck.getTrades().get(i).getTrader());
System.out.print(deck.getTrades().get(i).getSize());
System.out.print(deck.getTrades().get(i).getTime());
System.out.println();
}
}
} | 7 |
public static void main(String[] args) throws ParseException {
// Parse available options
Options opts = createOptions();
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(opts, args);
// if help needed
if (cmd.hasOption("h") || args.length==0) {
HelpFormatter help = new HelpFormatter();
help.setWidth(90);
// 2. from file (gridLabel and centroid) + (raw data all/testing) --> symbol in file, i.e., fileTesting.out
// parameter: fileModel fileTesting fileSymbols
String helpString = "java -jar SpComputeSymbols.jar [OPTIONS] FILEMODEL FILETESTING FILESYMBOLS\n" +
"Example: java -jar SpComputeSymbols.jar model.sp testing-raw.txt sym.txt\n" +
"FILEMODEL is the cluster configuration file, can be obtained using spComputeModel.jar\n" +
"FILETESTING is a timeseries file, comma-separated values of (timestampStart,timestampEnd,value1,value2,...)\n" +
"FILESYMBOLS is the result file, comma-separated values of (timestampStart, timestampEnd, symbol).\n" +
"=======================\n" +
"SpComputeSymbols converts the values (value1,value2, ...) into a symbol, based" +
" on the cluster configuration in the FILEMODEL. " +
"\n OPTIONS: \n";
help.printHelp(helpString, opts);
return;
}
int VERBOSE = 0;
if (cmd.hasOption("v")){
VERBOSE=0b01;
}
String fileModel = args[args.length-3];
String fileTesting = args[args.length-2];
String fileSymbols = args[args.length-1];
Spclust Wave2 = Util.loadSpclustFromFile(fileModel);
if (VERBOSE > 0) System.err.println(Wave2);
Wave2.applyCluster(fileTesting, fileSymbols );
} | 4 |
public static void main(String[] args) throws Throwable{
Escaner sc = new Escaner();
StringBuilder sb = new StringBuilder();
for (int c = 0, C = sc.nextInt(); c < C; c++) {
int D = sc.nextInt();
int[][] shuffle = new int[D][52];
for (int i = 0; i < shuffle.length; i++)
for (int j = 0; j < shuffle[i].length; j++)
shuffle[i][j] = sc.nextInt() - 1;
int[] inicial = new int[52];
for (int i = 0; i < inicial.length; i++)
inicial[i] = i;
for (String ln; (ln = sc.in.readLine()) != null && !ln.equals(""); ) {
int s = Integer.parseInt(ln.trim()) - 1;
int sol[] = new int[52];
for (int i = 0; i < shuffle[s].length; i++)
sol[i] = inicial[shuffle[s][i]];
inicial = sol;
}
for (int i = 0; i < inicial.length; i++)
sb.append(getCarta(inicial[i]) + "\n");
if(c < C-1)sb.append("\n");
}
System.out.print(new String(sb));
} | 9 |
@Override
public void updatePlayers(List<Player> players) {
allPlayers.removeAllElements();
for (Player player : players) {
allPlayers.addElement(player.getName());
}
checkMinimumPlayers();
} | 1 |
@Override
public void paint(Graphics2D g, JXMapViewer map, int w, int h) {
g = (Graphics2D) g.create();
// convert from viewport to world bitmap
Rectangle rect = map.getViewportBounds();
g.translate(-rect.x, -rect.y);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Collection<Car> carsCopy = new ArrayList<>(allCars.values());
for (Car car : carsCopy) {
Vector2d lastPosition = car.getLastPosition();
if (lastPosition == null) {
return;
}
GeoPosition geoPosition = new GeoPosition(lastPosition.getY(),
lastPosition.getX());
Point2D pt = map.getTileFactory().geoToPixel(geoPosition,
map.getZoom());
if (car.isSignificant()) {
g.drawImage(myCarIcon, (int) (pt.getX() - 20),
(int) (pt.getY() - 20), null);
} else {
g.drawImage(otherCarIcon, (int) (pt.getX() - 20),
(int) (pt.getY() - 20), null);
}
if (MapsRacer.DEBUG && car.getFrom() != null && car.getTo() != null) {
geoPosition = new GeoPosition(car.getFrom().getyLat(), car
.getFrom().getxLon());
pt = map.getTileFactory()
.geoToPixel(geoPosition, map.getZoom());
g.setColor(Color.GREEN);
g.fillOval((int) (pt.getX() - 10), (int) (pt.getY() - 10), 20,
20);
geoPosition = new GeoPosition(car.getTo().getyLat(), car
.getTo().getxLon());
pt = map.getTileFactory()
.geoToPixel(geoPosition, map.getZoom());
g.setColor(Color.BLUE);
g.fillOval((int) (pt.getX() - 10), (int) (pt.getY() - 10), 20,
20);
}
}
g.dispose();
} | 6 |
@Override
public double timeToReach(Node startNode, Node endNode, Message msg) {
// TODO Auto-generated method stub
double dist = startNode.getPosition().distanceTo(endNode.getPosition());
/* Link rate | time arrive mSec | dist
* ----------------------------------------------------
* 11 | 2542 | 399
* 5.5 | 3673 | 531
* 2 | 7634 | 669
* 1 | 13858 | 796
* */
//System.out.println("MTM distancia: "+Math.sqrt(dist));
System.out.println("MTM Sem sqrt distancia: "+dist);
if(dist < 399) return 0.002542;
if(dist >= 399 && dist < 531) return 0.003673;
if(dist >= 531 && dist < 669) return 0.007634;
if(dist >= 669 && dist <= 796) return 0.013858;
return 1;
} | 7 |
private static List<String> getEtapeIntermediare(char[] source, char[] target, int[][] positionMinimum) {
List<Operation> operations = getOperations(source, target, positionMinimum);
List<String> etapes = new ArrayList<>();
char[] temp = new char[Math.max(source.length, target.length)];
System.arraycopy(target, 0, temp, 0, target.length);
int decalage = 0;
Operation op;
for (int k = 0; k < operations.size(); k++) {
op = operations.get(k);
switch (op.operateur) {
case INSERT:
for (int i = temp.length - 1; i > decalage; i--) {
temp[i] = temp[i - 1];
}
temp[decalage] = op.operandeG;
etapes.add((new String(temp)).toLowerCase());
decalage++;
break;
case DELETE:
for (int i = decalage; i < temp.length - 1; i++) {
temp[i] = temp[i + 1];
}
temp[temp.length - 1] = '\u0000';
etapes.add((new String(temp)).toLowerCase());
break;
case SUBSTITUTION:
if (!op.operandeD.equals(op.operandeG)) {
temp[decalage] = op.operandeG;
etapes.add((new String(temp)).toLowerCase());
} else {
}
decalage++;
break;
default:
//exception
break;
}
}
if (etapes.size() > 0) {
etapes.remove(etapes.size() - 1);
}
return etapes;
} | 8 |
@EventHandler
public void IronGolemWaterBreathing(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getIronGolemConfig().getDouble("IronGolem.WaterBreathing.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getIronGolemConfig().getBoolean("IronGolem.WaterBreathing.Enabled", true) && damager instanceof IronGolem && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, plugin.getIronGolemConfig().getInt("IronGolem.WaterBreathing.Time"), plugin.getIronGolemConfig().getInt("IronGolem.WaterBreathing.Power")));
}
} | 6 |
public PhylogenyData copy() {
final NodeData new_pnd = new NodeData();
if ( isHasSequence() ) {
new_pnd.setSequence( ( Sequence ) getSequence().copy() );
}
if ( isHasEvent() ) {
new_pnd.setEvent( ( Event ) getEvent().copy() );
}
if ( isHasNodeIdentifier() ) {
new_pnd.setNodeIdentifier( ( Identifier ) getNodeIdentifier().copy() );
}
if ( isHasTaxonomy() ) {
new_pnd.setTaxonomy( ( Taxonomy ) getTaxonomy().copy() );
}
if ( isHasBinaryCharacters() ) {
new_pnd.setBinaryCharacters( ( BinaryCharacters ) getBinaryCharacters().copy() );
}
if ( isHasReference() ) {
new_pnd.setReference( ( Reference ) getReference().copy() );
}
if ( isHasDistribution() ) {
new_pnd.setDistribution( ( Distribution ) getDistribution().copy() );
}
if ( isHasDate() ) {
new_pnd.setDate( ( Date ) getDate().copy() );
}
if ( isHasProperties() ) {
new_pnd.setProperties( ( PropertiesMap ) getProperties().copy() );
}
return new_pnd;
} | 9 |
private static String getCause(int statusCode){
String cause = null;
switch(statusCode){
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
} | 9 |
public static Result preemptiveHighestPriorityFirst(FutureStack future, int duration)
{
//Implemented with RR
String result = "";
int time;
ArrayList<Process> active;
ArrayList<Process> completed = new ArrayList<Process>();
//Set up priority queues
ArrayList<ArrayList<Process>> priorityQueues = new ArrayList<ArrayList<Process>>();
priorityQueues.add(new ArrayList<Process>());
priorityQueues.add(new ArrayList<Process>());
priorityQueues.add(new ArrayList<Process>());
priorityQueues.add(new ArrayList<Process>());
for(time = 0; time <= duration; time++)
{
Process process;
char proc;
//Process is arriving, add it into the proper queue
while(future.hasActiveProcess(time))
{
process = future.pop();
priorityQueues.get(process.getPriority() - 1).add(process);
}
//Active will be set to the highest priority queue with a Process
active = null;
for (int i = 0; i < priorityQueues.size(); i++) {
if (!priorityQueues.get(i).isEmpty()) {
active = priorityQueues.get(i);
break;
}
}
//Start preemptive HPF starts here
if(active != null)
{
proc = active.get(0).getName();
if (active.get(0).process(time))
completed.add(active.remove(0).setCompletion(time + 1));
else
//removes the process that just ran, and puts it in the back
active.add(active.remove(0));
}
else
{
proc = '-';
}
result += proc;
//End Preemptive HPF
}
for (ArrayList<Process> list : priorityQueues)
for (Process p : list)
if (p.getFirstProcessTime() != -1)
completed.add(p);
return analyzeCompletion(result, completed, duration);
} | 9 |
void imeOn() {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_HIRAGANA);
robot.keyPress(KeyEvent.VK_HIRAGANA);
} catch (AWTException e) {
/* ignore exception */
}
} | 1 |
protected void listAllVoices() {
System.out.println("--------------------------------------------------");
System.out.println("All voices available:");
VoiceManager voiceManager = VoiceManager.getInstance();
Voice[] voices = voiceManager.getVoices();
for (Voice voice : voices) {
System.out.printf(" - [%s] %s\n", voice.getDomain(), voice.getName());
System.out.printf(" Description : %s\n", voice.getDescription());
System.out.printf(" Age : %s\n", voice.getAge());
System.out.printf(" Gender : %s\n", voice.getGender());
System.out.printf(" Locale : %s\n", voice.getLocale());
}
System.out.println("--------------------------------------------------");
System.out.println();
} | 1 |
public void saveProgram() {
LogoDocument program = getProgram();
File file = program.getFile();
if (file == null){
file = askForFileName();
program.setFile(file);
}
if (file != null){
try {
program.save();
} catch (IOException e) {
e.printStackTrace();
}
}
} | 3 |
@Test ( timeout = 2000 )
public void serverWriteToSocketClosedByClient () throws Exception {
Socket[] sockets = connectToServer();
try ( Socket serverSocket = sockets[ 0 ];
Socket clientSocket = sockets[ 1 ] ) {
clientSocket.close();
// wait for close to propagate
Thread.sleep(100);
IOException exception = null;
try {
/*
* http://www.unixguide.net/network/socketfaq/2.1.shtml
* http://www.faqs.org/rfcs/rfc793.html
*
* The TCP RFC allows the open side to continue sending data. In
* most (all?) implementations, the closed side will respond with a
* RST. For this reason, it takes two writes to cause an IOException
* with TCP sockets. (or more, if there is latency)
*
* However, it is expected that the write give an IOException as
* soon as possible - which means it is OK for our socket
* implementation to give an IOException on the first write.
*/
serverSocket.getOutputStream().write(new byte[] {
'1'
});
Thread.sleep(100);
serverSocket.getOutputStream().write(new byte[] {
'2'
});
}
catch ( IOException e ) {
exception = e;
}
assertNotNull("Server should see an IOException when writing to a socket that the client closed.", exception);
}
} | 1 |
private int readFully(byte[] b, int offs, int len)
throws BitstreamException
{
int nRead = 0;
try
{
while (len > 0)
{
int bytesread = source.read(b, offs, len);
if (bytesread == -1)
{
while (len-->0)
{
b[offs++] = 0;
}
break;
//throw newBitstreamException(UNEXPECTED_EOF, new EOFException());
}
nRead = nRead + bytesread;
offs += bytesread;
len -= bytesread;
}
}
catch (IOException ex)
{
throw newBitstreamException(STREAM_ERROR, ex);
}
return nRead;
} | 4 |
private void gerarTabela(List<Profile> lista, String tituloTabela, int linhaInicial) throws IOException, WriteException {
WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
NumberFormat dp3 = new NumberFormat("####.###");
WritableCellFormat casasDecimais = new WritableCellFormat(dp3);
cf.setWrap(true);
// estranhamente as células são na ordem "coluna, linha"
int coluna = 0;
int linha = linhaInicial;
Label l = new Label(coluna, linha, tituloTabela, cf);
s.addCell(l);
s.mergeCells(coluna, linha, coluna + 18, linha);
linha++;
l = new Label(coluna, linha, "Iteração", cf);
s.addCell(l);
coluna++;
l = new Label(coluna, linha, "Tempo em (s) - TXT", cf);
s.addCell(l);
s.mergeCells(coluna, linha, coluna + 8, linha);
coluna += 9;
l = new Label(coluna, linha, "Tempo em (s) - BIN", cf);
s.addCell(l);
s.mergeCells(coluna, linha, coluna + 8, linha);
linha++;
coluna = 1;
for (Profile p : lista) {
if (p.getIteracao() > 1) {
break;
}
l = new Label(coluna, linha, p.getNome(), cf);
s.addCell(l);
s.mergeCells(coluna, linha, coluna + 2, linha);
linha++;
l = new Label(coluna, linha, "10", cf);
s.addCell(l);
coluna++;
l = new Label(coluna, linha, "50", cf);
s.addCell(l);
coluna++;
l = new Label(coluna, linha, "100", cf);
s.addCell(l);
coluna++;
linha--;
}
coluna = 0;
linha += 2;
for (int i = 0; i < Trabalho.ITERACOES; i++) {
l = new Label(coluna, linha, (i + 1) + "", cf);
s.addCell(l);
linha++;
}
int itr = 1;
coluna = 1;
linha = linhaInicial+4;
for (Profile p : lista) {
if (itr != p.getIteracao()) {
coluna = 1;
linha++;
itr = p.getIteracao();
}
if(media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_10) == null){
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_10, p.getTempo10());
}else{
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_10
, media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_10)+p.getTempo10());
}
l = new Label(coluna, linha, p.getTempo10() + "", casasDecimais);
s.addCell(l);
coluna++;
if(media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_50) == null){
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_50, p.getTempo50());
}else{
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_50
, media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_50)+p.getTempo50());
}
l = new Label(coluna, linha, p.getTempo50() + "", casasDecimais);
s.addCell(l);
coluna++;
if(media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_100) == null){
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_100, p.getTempo100());
}else{
media.put(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_100
, media.get(p.getTamanho()+p.getTipoAqruivo()+Trabalho.QT_100)+p.getTempo100());
}
l = new Label(coluna, linha, p.getTempo100() + "", casasDecimais);
s.addCell(l);
coluna++;
}
linha++;
coluna = 0;
l = new Label(coluna, linha, "Media", cf);
s.addCell(l);
coluna++;
for (Entry<String, Double> e : media.entrySet()) {
double md = (e.getValue().doubleValue() / (Trabalho.ITERACOES + 0.0) );
l = new Label(coluna, linha, String.valueOf(md), casasDecimais);
s.addCell(l);
coluna++;
}
} | 9 |
public void exit() {
_scanner.close();
try {
UnicastRemoteObject.unexportObject(_instance, true);
_remoteObj.logout(_username, ServerInterface.CLIENT);
} catch(Exception ex) {
if(connect()) {
exit();
return;
}
System.out.println("Error on exit");
System.out.println(ex.getMessage());
}
} | 2 |
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
if (key == null) {
key = new LongWritable();
}
key.set(pos);
if (value == null) {
value = new Text();
}
value.clear();
final Text endline = new Text("\n");
int newSize = 0;
for(int i=0;i<NLINESTOPROCESS;i++){
Text v = new Text();
while (pos < end) {
newSize = in.readLine(v, maxLineLength,Math.max((int)Math.min(Integer.MAX_VALUE, end-pos),maxLineLength));
value.append(v.getBytes(),0, v.getLength());
value.append(endline.getBytes(),0, endline.getLength());
if (newSize == 0) {
break;
}
pos += newSize;
if (newSize < maxLineLength) {
break;
}
}
}
if (newSize == 0) {
key = null;
value = null;
return false;
} else {
return true;
}
} | 7 |
public boolean flowMayBeChanged() {
return jump != null || jumpMayBeChanged();
} | 1 |
public String generatePath() {
// Our input for solving
StartFinish startFinish = new StartFinish();
KeyTable<Vertex, String> table = new KeyTable<Vertex, String>();
prepareForSolving(table, startFinish);
Vertex start = startFinish.getStart();
Vertex finish = startFinish.getFinish();
// for (int r = 0; r < table.size(); r++) {
// System.out.println("TEST: table: " + table.getValueForKey(table.getKey(r).getA(), table.getKey(r).getB()));
// }
// Working space for solving
List<Vertex> layer;
List<Vertex> nextLayer = new ArrayList<Vertex>();
// Starting preparations
table.addKey(finish, finish, "");
table.addKey(start, start, "");
nextLayer.add(finish);
while (nextLayer.size() > 0) {
layer = nextLayer;
nextLayer = new ArrayList<Vertex>();
for (int i = 0; i < layer.size(); i++) {
// take its children, process them
for (int j = 0; j < layer.get(i).getChildrenAmount(); j++) {
Vertex thisVertex = layer.get(i).getChild(j);
Vertex parentVertex = layer.get(i);
// check table for that key
// String calculatedPath = table.getValueForKey(thisVertex, parentVertex)
// + table.getValueForKey(parentVertex, finish);
String calculatedPath = getValueForThisOrOppositeKey(table, thisVertex, parentVertex) +
getValueForThisOrOppositeKey(table, parentVertex, finish);
// I check also for parent==finish because otherwise everything(given only one child for
// finish) would terminate
if (table.keyExists(thisVertex, finish) || table.keyExists(finish, thisVertex)) {
if (getValueForThisOrOppositeKey(table, thisVertex, finish).length() > calculatedPath.length()) {
setNewValueForKeyOrOpposite(table, thisVertex, finish, calculatedPath);
}
if (parentVertex.equals(finish)) {
// CONTINUE
nextLayer.add(thisVertex);
}
// TERMINATE
} else {
table.addKey(thisVertex, finish, calculatedPath);
// table.addKey(finish, thisVertex, invert(calculatedPath));
if (!thisVertex.equals(start)) {
// CONTINUE
nextLayer.add(thisVertex);
}
// If this is Start then TERMINATE
}
}
}
}
// System.out.println("Table size:" + table.size());
// String p = table.getValueForKey(start, finish);
String p = getValueForThisOrOppositeKey(table, start, finish);
if (p == null) {
System.out.println("Start -> Finish == null");
}
return p;
} | 9 |
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
} | 0 |
public int w() {
return _map == null || _map.length < 1?0:_map[0].length;
} | 2 |
public void log(Object message, int level) {
Date date = new Date();
if (level <= this.level) {
System.out.println(ConfigurationManager.portlet + ", " + date.toString() + " MSG: " + message);
}
} | 1 |
public String getName() {
return this.name == null ? "" : this.name;
} | 1 |
@Override
public DataStructures getStructure() {
return data;
} | 0 |
public static String rowToString(JSONArray ja) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ja.length(); i += 1) {
if (i > 0) {
sb.append(',');
}
Object o = ja.opt(i);
if (o != null) {
String s = o.toString();
if (s.indexOf(',') >= 0) {
if (s.indexOf('"') >= 0) {
sb.append('\'');
sb.append(s);
sb.append('\'');
} else {
sb.append('"');
sb.append(s);
sb.append('"');
}
} else {
sb.append(s);
}
}
}
sb.append('\n');
return sb.toString();
} | 5 |
public void AlteracaoDadosPessoais(Usuario user) throws SQLException {
Connection conexao = null;
PreparedStatement comando = null;
try {
conexao = BancoDadosUtil.getConnection();
comando = conexao.prepareStatement(SQL_ALTERACAO_DADOS_PESSOAIS);
comando.setString(1, user.getNome());
comando.setString(2, user.getEmail());
comando.setString(3, user.getSenha());
comando.setInt(4, user.getIdUsuario());
comando.executeUpdate();
conexao.commit();
} catch (Exception e) {
if (conexao != null) {
conexao.rollback();
}
// throw new RuntimeException(e);
} finally {
if (comando != null && !comando.isClosed()) {
comando.close();
}
if (conexao != null && !conexao.isClosed()) {
conexao.close();
}
}
} | 6 |
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner cin = new Scanner(System.in);
String input = cin.nextLine();
String[] al = input.split(" ");
int i = 0;
for(i = 0; i < al.length-1; i++,i++){
int first = Integer.parseInt(al[i]);
int last = Integer.parseInt(al[i+1]);
if(first*100/65 != (first*100+last-1)/65){
System.out.println("NO");
break;
}
}
if(i == al.length){
System.out.println("YES");
}
} | 3 |
public void initialize() throws Exception {
if (m_baseExperiment == null) {
throw new Exception("No base experiment specified!");
}
m_experimentAborted = false;
m_finishedCount = 0;
m_failedCount = 0;
m_RunNumber = getRunLower();
m_DatasetNumber = 0;
m_PropertyNumber = 0;
m_CurrentProperty = -1;
m_CurrentInstances = null;
m_Finished = false;
if (m_remoteHosts.size() == 0) {
throw new Exception("No hosts specified!");
}
// initialize all remote hosts to available
m_remoteHostsStatus = new int [m_remoteHosts.size()];
m_remoteHostFailureCounts = new int [m_remoteHosts.size()];
m_remoteHostsQueue = new Queue();
// prime the hosts queue
for (int i=0;i<m_remoteHosts.size();i++) {
m_remoteHostsQueue.push(new Integer(i));
}
// set up sub experiments
m_subExpQueue = new Queue();
int numExps;
if (getSplitByDataSet()) {
numExps = m_baseExperiment.getDatasets().size();
} else {
numExps = getRunUpper() - getRunLower() + 1;
}
m_subExperiments = new Experiment[numExps];
m_subExpComplete = new int[numExps];
// create copy of base experiment
SerializedObject so = new SerializedObject(m_baseExperiment);
if (getSplitByDataSet()) {
for (int i = 0; i < m_baseExperiment.getDatasets().size(); i++) {
m_subExperiments[i] = (Experiment)so.getObject();
// one for each data set
DefaultListModel temp = new DefaultListModel();
temp.addElement(m_baseExperiment.getDatasets().elementAt(i));
m_subExperiments[i].setDatasets(temp);
m_subExpQueue.push(new Integer(i));
}
} else {
for (int i = getRunLower(); i <= getRunUpper(); i++) {
m_subExperiments[i-getRunLower()] = (Experiment)so.getObject();
// one run for each sub experiment
m_subExperiments[i-getRunLower()].setRunLower(i);
m_subExperiments[i-getRunLower()].setRunUpper(i);
m_subExpQueue.push(new Integer(i-getRunLower()));
}
}
} | 7 |
public void cargarXml(){
//Se crea un SAXBuilder para poder parsear el archivo
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File( "config.xml" );
try
{
Document document = (Document)builder.build( xmlFile );
Element rootNode = document.getRootElement();
List list = rootNode.getChildren();
for ( int i = 0; i < list.size(); i++ )
{
Element tabla = (Element) list.get(i);
switch(tabla.getName()){
case "servidor":
this.setServidor(tabla.getValue());
break;
case "basededatos":
this.setBaseDeDatos(tabla.getValue());
break;
case "puerto":
this.setPuerto(tabla.getValue());
break;
case "usuario":
this.setUsuario(tabla.getValue());
break;
case "contrasena":
this.setContrasena(tabla.getValue());
break;
}
}
}catch ( IOException | JDOMException io ) {
System.out.println( io.getMessage() );
}
} | 7 |
private int calculateInternalHashCode(Cell[] currentBoard){
int maxLength = (currentBoard.length <= CELL_NUMBER_TO_CALCULATE_HASHCODE)
? currentBoard.length
: CELL_NUMBER_TO_CALCULATE_HASHCODE;
Cell[] limitedCurrentBoard = Arrays.copyOfRange(currentBoard, 0, maxLength);
BigInteger biHashcode = ChessTools.calculateRepresentationNumber(limitedCurrentBoard);
int out = biHashcode.intValue();
return out;
} | 1 |
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.