text stringlengths 14 410k | label int32 0 9 |
|---|---|
private int defaultResultType(char convertCode) {
switch (convertCode) {
case 'i':
case 'o':
case 'd':
case 'x': {
return Record.LONG;
}
case 'c': {
return Record.CHAR;
}
case 'v':
case 'b': {
return Record.BOOLEAN;
}
case 'f': {
return Record.DOUBLE;
}
case 's': {
return Record.STRING;
}
}
return Record.NOTYPE;
} | 9 |
public int getMaxProfit(ArrayList<Transaction> transByDate) {
int maxProfit = 0;
for (int i = 0; i < transByDate.size(); i++) {
if (transByDate.get(i).profit > maxProfit)
maxProfit = transByDate.get(i).profit;
}
return maxProfit;
} | 2 |
@RequestMapping(value = "/room-event-slides-list/{roomEventId}", method = RequestMethod.GET)
@ResponseBody
public CreativeMaterialListResponse roomEventSlidesList(
@PathVariable(value = "roomEventId") final String roomEventIdStr
) {
return typedCreativeMaterialList(roomEventIdStr, CreativeMaterialType.SLIDES_TYPE_NAME);
} | 0 |
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == inicialView.getjButtonSair()) {
int fecha = JOptionPane.showConfirmDialog(null, "Deseja fechar o sistema?", null, JOptionPane.YES_NO_OPTION);
if(fecha == JOptionPane.YES_OPTION) {
System.exit(0);
}
} else if(e.getSource() == inicialView.getjButtonGestaoDestinos()) {
gestaoDestinoController = new GestaoDestinoController();
this.inicialView.dispose();
} else if(e.getSource() == inicialView.getjButtonBuscaDestino()) {
selecionaDestinoController = new SelecionaDestinoController();
this.inicialView.dispose();
}
} | 4 |
static public final String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String s = Double.toString(d);
if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
} | 7 |
public void setStatustextFontsize(int fontsize) {
if (fontsize <= 0) {
this.statustextFontSize = UIFontInits.STATUS.getSize();
} else {
this.statustextFontSize = fontsize;
}
somethingChanged();
} | 1 |
public void createMonster(){
Random numGenerator = new Random();
int i = 0;
while(i < maxNumOfMonsters){
int xPos = numGenerator.nextInt(79);
int yPos = numGenerator.nextInt(23);
int n = (int)(Math.random()*monsterPieces.length);
if(floor[xPos][yPos]==null){
switch(n){
case 0 : floor[xPos][yPos] = new Monster(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Monster) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 1 : floor[xPos][yPos] = new Troll(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Troll) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 2 : floor[xPos][yPos] = new Golem(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Golem) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 3 : floor[xPos][yPos] = new Bat(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Bat) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 4 : floor[xPos][yPos] = new Snake(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Snake) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 5 : floor[xPos][yPos] = new Zombie(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Zombie) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
case 6 : floor[xPos][yPos] = new Pirate(numGenerator.nextInt(2)+1);
listOfMonsters[xPos][yPos] = (Pirate) floor[xPos][yPos];
listOfMonsters[xPos][yPos].setLevelBonus(level);
listOfMonsters[xPos][yPos].setMonsterPosition(xPos,yPos);
break;
//Add new monsters here. Copy the case and change just the class names
default : floor[xPos][yPos] = null;
i--;
break;
}//switch
i++;
}//if(floor[xPos][yPos]==null)
}//while
//DOES NOT WORK : plan to systemize creation of monsters instead of manually adding cases
/*
for(int i = 0; i < maxNumOfMonsters; i++){
int xPos = numGenerator.nextInt(79);
int yPos = numGenerator.nextInt(23);
//randomly generates a number which determines what type monster will be created
int n = (int)(Math.random()*monsterPieces.length);
if(floor[xPos][yPos]==null){
String className = monsterPieces[n];
Class c1 = Class.forName(className);
Constructor con = c1.getConstructor(int.class);
floor[xPos][yPos] =
(GamePiece)con.newInstance(numGenerator.nextInt(2)+1);
}//if
}//for
*/
} | 9 |
public List<Position> getAlleEreichbarenNachbarn(Position position) {
List<Position> erreichbarePositionen = new ArrayList<Position>();
int[][] erreichbar = new int[7][7];
erreichbar[position.getRow()][position.getCol()] = 1;
erreichbar = getAlleErreichbarenNachbarnMatrix(position, erreichbar);
for (int i = 0; i < erreichbar.length; i++) {
for (int j = 0; j < erreichbar[0].length; j++) {
if (erreichbar[i][j] == 1) {
erreichbarePositionen.add(new Position(i, j));
}
}
}
return erreichbarePositionen;
} | 3 |
public void initialize() {
Debug.println("Cannon initialize()");
if (GameApplet.thisApplet != null)
{
Enumeration localEnumeration = getEnvironment().getObjects().elements();
while (localEnumeration.hasMoreElements())
{
PhysicalObject localPhysicalObject = (PhysicalObject)localEnumeration.nextElement();
if (!(localPhysicalObject instanceof CannonTrigger))
continue;
Debug.println("Cannon connecting to " + localPhysicalObject);
((CannonTrigger)localPhysicalObject).setCannon(this);
}
this.cannon = new AnimationComponent();
this.orientation = 210;
this.destOrientation = 210;
updateAppearance(new Integer(this.orientation));
}
} | 3 |
@Override
public boolean equals(Object obj)
{
boolean res = false;
if (obj instanceof ProtectionEntry)
{
ProtectionEntry other = (ProtectionEntry) obj;
if ((this.propertyTableNameId == null && other.propertyTableNameId == null)
|| (this.propertyTableNameId != null
&& (this.propertyTableNameId.equals(other.propertyTableNameId)
&& this.propertyId.equals(other.getPropertyId()))))
{
res = true;
}
}
return res;
} | 6 |
@Id
@Column(name = "name")
public String getName() {
return name;
} | 0 |
public static boolean nullWrapperP(Stella_Object self) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_THING)) {
{ Thing self000 = ((Thing)(self));
return (self000 == null);
}
}
else if (Surrogate.subtypeOfIntegerP(testValue000)) {
{ IntegerWrapper self000 = ((IntegerWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_INTEGER_WRAPPER));
}
}
else if (Surrogate.subtypeOfStringP(testValue000)) {
{ StringWrapper self000 = ((StringWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_STRING_WRAPPER));
}
}
else if (Surrogate.subtypeOfFloatP(testValue000)) {
{ FloatWrapper self000 = ((FloatWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_FLOAT_WRAPPER));
}
}
else if (Surrogate.subtypeOfCharacterP(testValue000)) {
{ CharacterWrapper self000 = ((CharacterWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_CHARACTER_WRAPPER));
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_FUNCTION_CODE_WRAPPER)) {
{ FunctionCodeWrapper self000 = ((FunctionCodeWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_FUNCTION_CODE_WRAPPER));
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_STELLA_METHOD_CODE_WRAPPER)) {
{ MethodCodeWrapper self000 = ((MethodCodeWrapper)(self));
return (Stella_Object.eqlP(self000, Stella.NULL_METHOD_CODE_WRAPPER));
}
}
else {
System.out.println("Not prepared to handle native slots with type " + self.primaryType());
}
}
return (false);
} | 7 |
private Type type() {
Type t = null;
if(currentToken.type() == Token.Type.Int)
t = Type.INT;
else if(currentToken.type() == Token.Type.Bool)
t = Type.BOOL;
else if(currentToken.type() == Token.Type.Float)
t = Type.FLOAT;
else if(currentToken.type() == Token.Type.Char)
t = Type.CHAR;
else if(currentToken.type() == Token.Type.Void)
t = Type.VOID;
else
error("Current token not type (current token: " + currentToken + ")");
match(currentToken.type());
return t;
} | 5 |
@Override
public Vehicule getVehicule(String vId) throws BadResponseException {
Vehicule v = null;
JsonRepresentation representation = null;
Representation repr = serv.getResource("intervention/" + interId
+ "/vehicule", vId);
try {
representation = new JsonRepresentation(repr);
} catch (IOException e) {
e.printStackTrace();
}
try {
v = new Vehicule(representation.getJsonObject());
} catch (InvalidJSONException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return v;
} | 3 |
public void libreta(int cc,Date min) throws IOException{
rLog.seek(0);
double tDeposito = 0,tRetiro=0,tInt=0,tAct=0;
boolean tiene1 = false;
while(rLog.getFilePointer() < rLog.length() ){
int cod = rLog.readInt();
double m = rLog.readDouble();
String t = rLog.readUTF();
long fecha = rLog.readLong();
if( cod == cc && fecha >= min.getTime() ){
System.out.println(t + " Lps " + m + " " +
new Date(fecha) );
tiene1 = true;
switch( Transaccion.valueOf(t) ){
case DEPOSITO:
tDeposito += m;
break;
case RETIRO:
tRetiro += m;
break;
case INTERESES:
tInt += m;
break;
default:
tAct += m;
break;
}
}
}
if( tiene1 ){
System.out.println("Total Depositado: " + tDeposito);
System.out.println("Total Retiado: " + tRetiro);
System.out.println("Total Intereses: " + tInt);
System.out.println("Total Activaciones: " + tAct );
}
else
System.out.println("CLIENTE NO TIENE TRANSACCIONES");
} | 7 |
@Override
public void keyPressed(KeyEvent e) {
// On fais tourner le bateau selectionner si c'est possible
if(e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_LEFT) {
this._partie.rotationBateau();
}
} // keyPressed(KeyEvent e) | 2 |
private void loadMouse()
{
mouseList.clear();
for (Class<?> clz : MouseLoader.load())
{
try
{
Constructor<?> struc = clz.getConstructor((Class<?>[])null);
Mouse mouse = (Mouse)struc.newInstance();
MouseController controller = new MouseController(mouse);
controller.setNumberOfBombs((int)(this.numberOfCheese * GameConfig.RATIO_BOMBS_TO_CHEESE));
mouseList.add(controller);
}
catch (Exception ex)
{
Debug.out().println(clz.getName() + " failed to load.");
ex.printStackTrace();
}
}
} | 5 |
public double evaluateState(StateObservation stateObs) {
boolean gameOver = stateObs.isGameOver();
Types.WINNER win = stateObs.getGameWinner();
double rawScore = stateObs.getGameScore();
if(gameOver && win == Types.WINNER.PLAYER_LOSES)
return HUGE_NEGATIVE;
if(gameOver && win == Types.WINNER.PLAYER_WINS)
return HUGE_POSITIVE;
return rawScore;
} | 4 |
private static float[][] generateSmoothNoise( float[][] baseNoise, int octave )
{
int width = baseNoise.length;
int height = baseNoise[0].length;
float[][] smoothNoise = new float[width][height];
int samplePeriod = 1 << octave; // calculates 2 ^ k
float sampleFrequency = 1.0f / samplePeriod;
for ( int i = 0; i < width; i++ )
{
//calculate the horizontal sampling indices
int sample_i0 = ( i / samplePeriod ) * samplePeriod;
int sample_i1 = ( sample_i0 + samplePeriod ) % width; //wrap around
float horizontal_blend = ( i - sample_i0 ) * sampleFrequency;
for ( int j = 0; j < height; j++ )
{
//calculate the vertical sampling indices
int sample_j0 = ( j / samplePeriod ) * samplePeriod;
int sample_j1 = ( sample_j0 + samplePeriod ) % height; //wrap around
float vertical_blend = ( j - sample_j0 ) * sampleFrequency;
//blend the top two corners
float top = interpolate( baseNoise[sample_i0][sample_j0], baseNoise[sample_i1][sample_j0], horizontal_blend );
//blend the bottom two corners
float bottom = interpolate( baseNoise[sample_i0][sample_j1], baseNoise[sample_i1][sample_j1], horizontal_blend );
//final blend
smoothNoise[i][j] = interpolate( top, bottom, vertical_blend );
}
}
return smoothNoise;
} | 2 |
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton5ActionPerformed
{//GEN-HEADEREND:event_jButton5ActionPerformed
world.choiceMade("left");
}//GEN-LAST:event_jButton5ActionPerformed | 0 |
public static void cleanUp () {
ModPack pack = ModPack.getSelectedPack();
File tempFolder = new File(OSUtils.getCacheStorageLocation(), "ModPacks" + sep + pack.getDir() + sep);
for (String file : tempFolder.list()) {
if (!file.equals(pack.getLogoName()) && !file.equals(pack.getImageName()) && !file.equals("version") && !file.equals(pack.getAnimation())) {
try {
if (file.endsWith(".zip")) {
Logger.logDebug("retaining modpack file: " + tempFolder + File.separator + file);
} else {
FTBFileUtils.delete(new File(tempFolder, file));
}
} catch (IOException e) {
Logger.logError(e.getMessage(), e);
}
}
}
} | 7 |
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Edge)
{
Edge e=(Edge)obj;
if(e.u==u&&e.v==v&&e.weight==weight)
return true;
}
return false;
} | 4 |
public void test(){
assert state == State.OK;
// get the internal thread number
int i = getInternalThreadId();
// activate
setState(i, State.GUARD);
try{Thread.sleep(1+i);}catch(Throwable ignore){};
// guard
if( getState(i+1) != State.IDLE ){ setState(i, State.WAIT); }
else{ setState(i, State.ACTIVE); }
System.out.println("THREAD-" + i + ":\tstate " + getState(i) );
try{Thread.sleep(1+i);}catch(Throwable ignore){};
// assert: one thread must not be ACTIVE
if( state0 == State.ACTIVE && state1 == State.ACTIVE ){
state = State.ERROR;
}
assert state0 != State.ACTIVE || state1 != State.ACTIVE;
// deactivate
setState(i, State.IDLE);
try{Thread.sleep(1+i);}catch(Throwable ignore){};
} | 7 |
private int randomSwitchDirection() {
int i;
i = (int) Math.floor(Math.random() * 10 + 1);
if (i > 5) {
return -1;
} else {
return 1;
}
} | 1 |
public Drawable findNearestClass(int x, int y) {
//Set the local variables required for the comparison
Drawable d = null;
double minDist = Double.MAX_VALUE;
int minDistIndex = -1;
//Loop through the vector
for(int i=0; i < getDrawable().size(); i++) {
//Set 'd' as the next 'Drawable' object
d = (Drawable)(getDrawable().get(i));
//Compare the distance between the object's X/Y and mouse X/Y
//against the current minDist
if(d.distanceTo(x,y) < minDist) {
//If it's less, set the minDist to that value
minDist = d.distanceTo(x,y);
//Set the index of the item with the smallest distance to 'i'
minDistIndex = i;
}
}
d = getDrawable().get(minDistIndex);
if(d instanceof ClassDiag) {
ClassDiag cd = (ClassDiag) d;
//Set the distance away from the mouse click before a class is registered
if(cd.getX() < x && cd.getX() + cd.getWidth() > x && cd.getY() < y && cd.getY() + cd.getWidth() > y) {
//If the mouse position is with the threshold, return the 'Drawable' object with the smallest distance
return cd;
}
}
//Otherwise return nothing..
return null;
} | 7 |
public WellArchetype getWellManager(World world, Random random, int chunkX, int chunkZ) {
// get the list of wells
if (wells == null)
wells = new Hashtable<Long, WellArchetype>();
// find the origin for the well
int wellX = calcOrigin(chunkX);
int wellZ = calcOrigin(chunkZ);
// hex offset... finally!
if (hexishWells && (Math.abs(wellX) / WellWorld.wellWidthInChunks) % 2 != 0)
if (wellZ + wellWidthInChunksHalf > chunkZ)
wellZ -= wellWidthInChunksHalf;
else
wellZ += wellWidthInChunksHalf;
// calculate the plat's key
long wellpos = (long) wellX * (long) Integer.MAX_VALUE + (long) wellZ;
Long wellkey = Long.valueOf(wellpos);
// see if the well is already out there
WellArchetype wellmanager = wells.get(wellkey);
// doesn't exist? then make it!
if (wellmanager == null) {
// calculate the well's random seed
long wellseed = wellpos ^ world.getSeed();
// make sure the initial spawn location is "safe-ish"
if (wellX == 0 && wellZ == 0)
wellmanager = new KnollsWell(world, wellseed, wellX, wellZ);
else {
// noise please
if (generator == null)
generator = new SimplexNoiseGenerator(world.getSeed());
// Random wellrand = new Random(wellseed);
// double noise = (generator.noise(wellrand.nextDouble() * wellX,
// wellrand.nextDouble() * wellZ,
// wellrand.nextDouble() * 23.0,
// wellrand.nextGaussian() * 71.0) + 1) / 2;
// double noise = (generator.noise(wellX / ByteChunk.Width, wellZ / ByteChunk.Width) + 1) / 2;
// double noise = ((generator.noise(wellX, wellZ) + 1) / 2 +
// getWellFactor(wellX) +
// getWellFactor(wellZ) +
// new Random(wellseed).nextDouble()) / 4;
// double noise = new Random(wellseed).nextDouble();
// double doubleNoise = wellrand.nextDouble();
// double gaussianNoise = wellrand.nextGaussian();
// double noise = (doubleNoise + gaussianNoise) / 2.0;
// double noise = (wellrand.nextGaussian() + 1.0) / 2.0;
double noise = new HighQualityRandom(wellseed).nextDouble();
// WellWorld.log.info("Well: " + wellX + ", " + wellZ + " Noise = " + noise);
// pick one from the list
wellmanager = chooseWellManager(noise, world, wellseed, wellX, wellZ);
}
// remember it for the next time
wells.put(wellkey, wellmanager);
}
// return it
return wellmanager;
} | 8 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Task)) {
return false;
}
if(object == this) {
return false;
}
Task other = (Task) object;
if ((this.idtask == null && other.idtask != null) || (this.idtask != null && !this.idtask.equals(other.idtask))) {
return false;
}
return true;
} | 6 |
public void doNextRound() {
sayRoundStatus();
if (!isStunned(player)) {
if (!multiRoundActionOnQueue(player)) {
if (playerHasAnotherAction()) {
choosePlayerAction();
} else {
System.out.println("You have no actions left!");
}
}
} else {
System.out.println("You are stunned and cannot act!");
}
if (!isStunned(creature)) {
if (!multiRoundActionOnQueue(creature)) {
if (creatureHasAnotherAction()) {
chooseCreatureAction();
} else {
System.out.println("The " + creature.getName() + " has no actions left!");
}
}
} else {
System.out.println("The " + creature.getName() + " is stunned and cannot act!");
}
// get the next actions from the queue
Action playerAction = null;
if (!isStunned(player)) {
playerAction = player.getNextCombatAction(round);
}
Action creatureAction = null;
if (!isStunned(creature)) {
creatureAction = creature.getNextCombatAction(round);
}
resolve(playerAction, creatureAction);
// resolve burn damage from previous rounds
doPlayerBurnAttacks(creatureAction, player);
doCreatureBurnAttacks(playerAction, creature);
round++;
} | 8 |
public void next()
{
// check for concurrent modification
if(expectedModCount != modCount)
throw new ConcurrentModificationException();
// go to next entry in chain, if it exists
current = current.nextEntry;
if (current == null)
{
// at end of chain; go to next cell containing an entry
while (++currentIndex < table.length && table[currentIndex] == null)
;
if (currentIndex >= table.length)
{
// past end of table
current = null;
}
else
{
// set next entry
current = table[currentIndex];
}
}
} | 5 |
private void parseArguments(String url,Processor processor) throws IllegalArgumentException{
//can be convert from string?
Class<?>[] parameterTypes = processor.getMethod().getParameterTypes();
for(Class<?> parameterType : parameterTypes){
if(!ConverterFactory.canConvert(parameterType)){
throw new IllegalArgumentException("action method's parameter type " + parameterType + " can not be converted!");
}
}
String actionUrl = processor.getMethod().getAnnotation(Action.class).value();
int argumentsCount = 0;
for(int i=0; i < actionUrl.length(); i++){
if(actionUrl.charAt(i) == '$')
argumentsCount++;
}
Object[] args = new Object[argumentsCount];
String[] urlSegments = url.split("\\/");
for(int j=0, i = urlSegments.length - argumentsCount; i < urlSegments.length; i++,j++){
args[j] = ConverterFactory.getConverter(parameterTypes[j]).convert(urlSegments[i]);
}
processor.setArguments(args);
} | 7 |
public void readFrom(org.jdom.Element element) {
Element mainConfigElement = element.getChild(PREF_CHILD_ELEMENT);
if( mainConfigElement == null )
{
postUrl = "http://localhost/" ;
return ;
}
defaultChannel = mainConfigElement.getChildText(PREF_KEY_SLACK_DEF_CHANNEL);
postUrl = mainConfigElement.getChildText(PREF_KEY_SLACK_POSTURL);
logoUrl = mainConfigElement.getChildText(PREF_KEY_SLACK_LOGOURL);
Attribute postSuccessfulAttr = mainConfigElement.getAttribute(ATTR_NAME_POST_SUCCESSFUL);
Attribute postStartedAttr = mainConfigElement.getAttribute(ATTR_NAME_POST_STARTED);
Attribute postFailedAttr = mainConfigElement.getAttribute(ATTR_NAME_POST_FAILED);
if( postSuccessfulAttr != null )
{
try {
postSuccessful = postSuccessfulAttr.getBooleanValue();
}
catch( DataConversionException ex )
{
postSuccessful = true ;
}
}
if( postStartedAttr != null )
{
try {
postStarted = postStartedAttr.getBooleanValue();
}
catch( DataConversionException ex )
{
postStarted = false ;
}
}
if( postFailedAttr != null )
{
try {
postFailed = postFailedAttr.getBooleanValue();
}
catch( DataConversionException ex )
{
postFailed = false ;
}
}
} | 7 |
public void qckSort(Card [] cardArray, int left, int right){
Card pivot = cardArray[left + (right - left) / 2];
int leftable = left;
int rightable = right;
while (leftable <= rightable){
while(cardArray[leftable].compareTo(pivot) < 0 ){
leftable++;
}
while(cardArray[rightable].compareTo(pivot) > 0){
rightable--;
}
if(leftable <= rightable){
swap(leftable,rightable);
leftable++;
rightable--;
}
}
if(left < rightable)
qckSort(cardArray, left, rightable);
if(leftable < right)
qckSort(cardArray, leftable, right);
} | 6 |
public CafeRoot(String title) throws IOException {
// Frame-Initialisierung
super(title);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Properties spielstand = Spielstart.loadProperties("spielstand.txt");
int frameWidth = 600;//506
int frameHeight = 600;//434
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setResizable(false);
Container cp = getContentPane();
setTitle(spielname);
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setLocationRelativeTo(null);
cp.setLayout(null);
// Anfang Komponenten
Komponenten.komponenten(cp);
//=============================
String string_spielangefangen = spielstand.getProperty("spielangefangen", "0");
int spielangefangen = Integer.parseInt(string_spielangefangen);
if (Spielstart.isWindows()) {
JOptionPane.showMessageDialog(null, "Dein System ist hoffnungslos veraltet!\nWindoof ist nicht kompatibel mit diesem Spiel.\nSollte es zu Problemen bei der Ausführung kommen,\ndann öffne das Spiel bitte auf einem PC\nmit Mac OS oder Linux!", "System veraltet", JOptionPane.WARNING_MESSAGE);
System.out.println("("+ausgabenummer+") "+"Ein veraltetes System \"Windows\" wurde entdeckt"); ausgabenummer += 1;
}
if(spielangefangen == 0) {
do{
Spielstart.namensfrage();
}while(spielernamenkorrekt == false);
System.out.println("("+ausgabenummer+") "+"Spieler 1 heißt: "+spielername1); ausgabenummer += 1;
System.out.println("("+ausgabenummer+") "+"Spieler 2 heißt: "+spielername2); ausgabenummer += 1;
Spielstart.neuesspiel();
Spielstart.gastkartenmischen();
Spielstart.laenderkartenmischen();
Spielstart.spielfeldgenerieren();
}
else{
Spielstart.spielstand();
}
// Ende Komponenten
setVisible(true);
addWindowListener(new MyWindowListener(this, spielstand));
//=============================
/*Random wuerfel1 = new Random(); //Würfeltest
int wuerfel = wuerfel1.nextInt(49)+1; //Würfeltest
System.out.println(wuerfel);*/
} | 3 |
final public IndexList IndexList() throws ParseException {
NodeList list = new NodeList();
Token implied_t;
Identifier identifier;
Token comma_t;
boolean implied;
implied = false;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IMPLIED_T:
implied_t = jj_consume_token(IMPLIED_T);
break;
default:
jj_la1[58] = jj_gen;
;
}
identifier = ValueIdentifier();
list.addNode(new Index(identifier, implied));
label_12:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COMMA_T:
;
break;
default:
jj_la1[59] = jj_gen;
break label_12;
}
comma_t = jj_consume_token(COMMA_T);
implied = false;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IMPLIED_T:
implied_t = jj_consume_token(IMPLIED_T);
implied = true;
break;
default:
jj_la1[60] = jj_gen;
;
}
identifier = ValueIdentifier();
list.addNode(new Index(identifier, implied));
}
list.nodes.trimToSize();
{if (true) return new IndexList(list);}
throw new Error("Missing return statement in function");
} | 8 |
public Events getNotes(Events events) {
try {
crs = qb.selectFrom("notes").all().executeQuery();
String eventID = null;
String note = null;
boolean active = false;
while(crs.next()) {
eventID = crs.getString("eventID");
if(eventID == null) {
eventID = crs.getString("cbsEventID");
}
active = crs.getBoolean("active");
note = crs.getString("text");
if(active && eventID != null) {
for(int i = 0; i < events.events.size(); i++){
if(events.events.get(i).getEventid().equals(eventID)) {
events.events.get(i).setNote(note);
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
crs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return events;
} | 8 |
public void visitLdcInsn(final Object cst) {
mv.visitLdcInsn(cst);
if (constructor) {
pushValue(OTHER);
if (cst instanceof Double || cst instanceof Long) {
pushValue(OTHER);
}
}
} | 3 |
private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
IP = ipField.getText();
nickname = "[" + nickNameField.getText() + "] ";
if ("".equals(IP) || "".equals(nickname)) {
displayMessage("You must enter a valid IP and nickname.", ERRORMESSAGE);
} else {
client = new Client(IP, 23666, nickNameField.getText(), this);
client.start();
}
}//GEN-LAST:event_connectButtonActionPerformed | 2 |
public Expr EqExpr() throws ParseException {
Token tok;
Expr e, er;
e = RelExpr();
label_8:
while (true) {
switch (jj_ntk == -1 ? jj_ntk() : jj_ntk) {
case 169:
case 170:
break;
default:
jj_la1[26] = jj_gen;
break label_8;
}
switch (jj_ntk == -1 ? jj_ntk() : jj_ntk) {
case 169:
tok = jj_consume_token(169);
break;
case 170:
tok = jj_consume_token(170);
break;
default:
jj_la1[27] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
er = RelExpr();
e = new Expr.BinOp(tok, e, er);
}
return e;
} | 7 |
public List<String> readStringSubKeys(String key) {
try {
List<String> results = new ArrayList<>();
OpenResult openResult = openKey(key, READ_ACCESS);
if (openResult.mSuccess) {
QueryResult queryResult = queryInfoKey(openResult.mHandle);
for (int i = 0; i < queryResult.mCount; i++) {
if (METHOD_ENUM_KEY_EX == null) {
METHOD_ENUM_KEY_EX = getMethod(mRoot.getClass(), "WindowsRegEnumKeyEx", int.class, int.class, int.class);
}
byte[] name = (byte[]) METHOD_ENUM_KEY_EX.invoke(mRoot, new Object[] { openResult.mHandle, Integer.valueOf(i), Integer.valueOf(queryResult.mMaxValueLength + 1) });
results.add(new String(name));
}
closeKey(openResult.mHandle);
}
return results;
} catch (Exception exception) {
Log.error(exception);
}
return null;
} | 4 |
static String getPlatformFontFace(int index) {
if(SWT.getPlatform() == "win32") {
return new String [] {"Arial", "Impact", "Times", "Verdana"} [index];
} else if (SWT.getPlatform() == "motif") {
return new String [] {"URW Chancery L", "URW Gothic L", "Times", "qub"} [index];
} else if (SWT.getPlatform() == "gtk") {
return new String [] {"URW Chancery L", "Baekmuk Batang", "Baekmuk Headline", "KacsTitleL"} [index];
} else if (SWT.getPlatform() == "carbon") {
return new String [] {"Arial", "Impact", "Times", "Verdana"} [index];
} else { // photon, etc ...
return new String [] {"Arial", "Impact", "Times", "Verdana"} [index];
}
} | 4 |
@Override
public String makeMobName(char gender, int age)
{
switch(age)
{
case Race.AGE_INFANT:
case Race.AGE_TODDLER:
return name().toLowerCase()+" pup";
case Race.AGE_CHILD:
switch(gender)
{
case 'M':
case 'm':
return "boy " + name().toLowerCase() + " pup";
case 'F':
case 'f':
return "girl " + name().toLowerCase() + " pup";
default:
return "young " + name().toLowerCase();
}
default:
return super.makeMobName(gender, age);
}
} | 7 |
@Override
public void run() {
if (!Config.toxicEnabled) return;
World w = plugin.getServer().getWorld(Config.worldToUse);
if (w == null) return;
for (Player p : w.getPlayers()) {
PConfManager pcm = PConfManager.getPConfManager(p);
if (!pcm.getBoolean("toxicspray_on", false)) continue;
if (pcm.getLong("toxicspray_expire", 0L) <= System.currentTimeMillis()) {
pcm.set("toxicspray_on", false);
pcm.set("toxicspray_expire", null);
p.sendMessage(ChatColor.BLUE + "The toxic fumes wear off.");
continue;
}
List<Entity> ents = p.getNearbyEntities(Config.toxicRadius, Config.toxicRadius, Config.toxicRadius);
for (Entity e : ents) {
if (e.getType() != EntityType.ZOMBIE) continue;
Zombie z = (Zombie) e;
z.damage(z.getMaxHealth() / 2);
}
}
} | 7 |
private void moveColumn(Board b, int caller) {
int posNr = 0;
Position tmp = null;
int i, j;
int foundPos = -1;
i = j = 1;
while (i <= b.getWidth()) {
j = 1;
while (j + 1 <= b.getHeight()) {
if (b.isFree(i, j) && b.isFree(i, j + 1)) {
b.set(i, j);
b.set(i, j + 1);
foundPos = pos.search(b.flatten());
tmp = new Position(b);
if (isSymmetrien() && foundPos == -1) {
foundPos = findSymmetricPosition(b);
}
if (foundPos == -1) {
if (!pos.get(caller).hasChildren(tmp)) {
posNr = pos.add(tmp);
pos.get(caller).addChild(pos.get(posNr));
move(b, posNr);
}
} else {
if (!pos.get(caller).hasChildren(pos.get(foundPos)))
pos.get(caller).addChild(pos.get(foundPos));
}
b.clear(i, j);
b.clear(i, j + 1);
}
j++;
}
i++;
}
} | 9 |
public void addFeatureVector(FeatureVector featureVector) throws Exceptions.FeatureTypeNotFoundException {
for (Entry<String, String> pair : featureVector.getFilteredPowerSet(FeatureTypes.getUsedFeatures()).entrySet()) {
incCount(pair.getKey(), pair.getValue());
totalCount++;
}
} | 1 |
public void setPWfieldMargin(int[] margin) {
if ((margin == null) || (margin.length != 4)) {
this.pwfield_Margin = UIMarginInits.PWFIELD.getMargin();
} else {
this.pwfield_Margin = margin;
}
somethingChanged();
} | 2 |
public void setItemCostPrice(BigDecimal itemCostPrice) {
this.itemCostPrice = itemCostPrice;
} | 0 |
public void getTest() {
try {
URL url = new URL(this.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(45000);
conn.setReadTimeout(45000);
Date d = new Date();
conn.connect();
getStatus = conn.getResponseCode();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
content = sb.toString();
getTime = new Date().getTime() - d.getTime();
} catch (IOException e) {}
} | 2 |
public void paint(GC gc, int width, int height) {
if (!example.checkAdvancedGraphics()) return;
Device device = gc.getDevice();
if (alphaImg1 == null) {
alphaImg1 = GraphicsExample.loadImage(device, GraphicsExample.class, "alpha_img1.png");
alphaImg2 = GraphicsExample.loadImage(device, GraphicsExample.class, "alpha_img2.png");
}
Rectangle rect = alphaImg1.getBounds();
gc.setAlpha(alphaValue);
gc.drawImage(alphaImg1, rect.x, rect.y, rect.width, rect.height,
width/2, height/2, width/4, height/4);
gc.drawImage(alphaImg1, rect.x, rect.y, rect.width, rect.height,
0, 0, width/4, height/4);
gc.setAlpha(255-alphaValue);
gc.drawImage(alphaImg2, rect.x, rect.y, rect.width, rect.height,
width/2, 0, width/4, height/4);
gc.drawImage(alphaImg2, rect.x, rect.y, rect.width, rect.height,
0, 3*height/4, width/4, height/4);
// pentagon
gc.setBackground(device.getSystemColor(SWT.COLOR_DARK_MAGENTA));
gc.fillPolygon(new int [] {width/10, height/2, 3*width/10, height/2-width/6, 5*width/10, height/2,
4*width/10, height/2+width/6, 2*width/10, height/2+width/6});
gc.setBackground(device.getSystemColor(SWT.COLOR_RED));
// square
gc.setAlpha(alphaValue);
gc.fillRectangle(width/2, height-75, 75, 75);
// triangle
gc.setAlpha(alphaValue + 15);
gc.fillPolygon(new int[]{width/2+75, height-(2*75), width/2+75, height-75, width/2+(2*75), height-75});
// triangle
gc.setAlpha(alphaValue + 30);
gc.fillPolygon(new int[]{width/2+80, height-(2*75), width/2+(2*75), height-(2*75), width/2+(2*75), height-80});
// triangle
gc.setAlpha(alphaValue + 45);
gc.fillPolygon(new int[]{width/2+(2*75), height-(2*75), width/2+(3*75), height-(2*75), width/2+(3*75), height-(3*75)});
// triangle
gc.setAlpha(alphaValue + 60);
gc.fillPolygon(new int[]{width/2+(2*75), height-((2*75)+5), width/2+(2*75), height-(3*75), width/2+((3*75)-5), height-(3*75)});
// square
gc.setAlpha(alphaValue + 75);
gc.fillRectangle(width/2+(3*75), height-(4*75), 75, 75);
gc.setBackground(device.getSystemColor(SWT.COLOR_GREEN));
// circle in top right corner
gc.setAlpha(alphaValue2);
gc.fillOval(width-100, 0, 100, 100);
// triangle
gc.setAlpha(alphaValue + 90);
gc.fillPolygon(new int[]{width-300, 10, width-100, 10, width-275, 50});
// triangle
gc.setAlpha(alphaValue + 105);
gc.fillPolygon(new int[]{width-10, 100, width-10, 300, width-50, 275});
// quadrilateral shape
gc.setAlpha(alphaValue + 120);
gc.fillPolygon(new int[]{width-100, 100, width-200, 150, width-200, 200, width-150, 200});
// blue circles
gc.setBackground(device.getSystemColor(SWT.COLOR_BLUE));
int size = 50;
int alpha = 20;
for (int i = 0; i < 10; i++) {
gc.setAlpha(alphaValue + alpha);
if (i % 2 > 0) {
gc.fillOval(width-((i+1)*size), height-size, size, size);
} else {
gc.fillOval(width-((i+1)*size), height-(3*size/2), size, size);
}
alpha = alpha + 20;
}
// SWT string appearing randomly
gc.setAlpha(alphaValue2);
String text = GraphicsExample.getResourceString("SWT");
Font font = createFont(device, 100, SWT.NONE);
gc.setFont(font);
Point textSize = gc.stringExtent(text);
int textWidth = textSize.x;
int textHeight = textSize.y;
if (alphaValue2 == 0){
randX = (int)(width*Math.random());
randY = (int)(height*Math.random());
randX = (randX > textWidth) ? randX - textWidth : randX;
randY = (randY > textHeight) ? randY - textHeight : randY;
}
gc.drawString(text, randX, randY, true);
font.dispose();
// gray donut
gc.setAlpha(100);
Path path = new Path(device);
path.addArc((width-diameter)/2, (height-diameter)/2, diameter, diameter, 0, 360);
path.close();
path.addArc((width-diameter+25)/2, (height-diameter+25)/2, diameter-25, diameter-25, 0, 360);
path.close();
gc.setBackground(device.getSystemColor(SWT.COLOR_GRAY));
gc.fillPath(path);
gc.drawPath(path);
path.dispose();
} | 7 |
@Override
public void render(GameContainer container, StateBasedGame sbg, Graphics g) throws SlickException {
background.draw(0,0,Button.GAME_WIDTH,Button.GAME_HEIGHT);
ttf.drawString(600, 10, "SCORE : "+score);
ttf.drawString(300, 10, "TIME : "+(int) time);
if(count > 0 && time%10 >= 7){
bonusButton.draw(g);
}
for(Entity entity : entities){
entity.draw(g);
}
} | 3 |
public void drawCenteredStringMoveY(String string, int x, int y, int color, int waveAmount) {
if (string == null) {
return;
}
x -= getTextWidth(string) / 2;
y -= baseHeight;
for (int index = 0; index < string.length(); index++) {
char c = string.charAt(index);
if (c != ' ') {
drawCharacter(characterPixels[c], x + characterOffsetX[c], y + characterOffsetY[c] + (int) (Math.sin((double) index / 2D + (double) waveAmount / 5D) * 5D), characterWidth[c], characterHeight[c], color);
}
x += characterScreenWidth[c];
}
} | 3 |
private void refreshDurationField() {
final Color defaultColor = Color.BLACK;
final Color errorColor = Color.RED;
if (startTimeDateChooser.getCalendar() == null) {
startTimeDateChooser.setCalendar(Calendar.getInstance());
}
if (endTimeDateChooser.getCalendar() == null) {
endTimeDateChooser.setCalendar(Calendar.getInstance());
}
long duration = Controller.calculateDuration(getStartTimeFromFields(), getEndTimeFromFields());
txtDuration.setForeground((duration >= 0) ? defaultColor : errorColor);
String durationString = Controller.getDurationString(duration);
txtDuration.setText(durationString);
} | 3 |
public void paint(Graphics g) {
Dimension d = getSize();
g.drawImage(icons, border, border, iconW + border, iconH + border, 0, iconIndex * iconH, iconW, (iconIndex + 1)
* iconH, null);
if (mouseOver && !mousePressed) {
g.setColor(Color.orange);
} else if (selected || mousePressed) {
g.setColor(Color.red);
} else {
g.setColor(Color.black);
}
g.drawRect(0, 0, d.width - 1, d.height - 1);
} | 4 |
public void setPassword(String password)
{
password = password.trim();
if ( password.isEmpty() ) {
throw new RuntimeException( "'password' should not be empty" );
}
if ( password.length() < 6 ) {
throw new RuntimeException( "'password' cannot be of less than 6 characters" );
}
this.password = password;
} | 2 |
public void setZoom(int zoom)
{
if (zoom == this.zoomLevel)
{
return;
}
TileFactoryInfo info = getTileFactory().getInfo();
// don't repaint if we are out of the valid zoom levels
if (info != null && (zoom < info.getMinimumZoomLevel() || zoom > info.getMaximumZoomLevel()))
{
return;
}
// if(zoom >= 0 && zoom <= 15 && zoom != this.zoom) {
int oldzoom = this.zoomLevel;
Point2D oldCenter = getCenter();
Dimension oldMapSize = getTileFactory().getMapSize(oldzoom);
this.zoomLevel = zoom;
this.firePropertyChange("zoom", oldzoom, zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
setCenter(new Point2D.Double(oldCenter.getX() * (mapSize.getWidth() / oldMapSize.getWidth()), oldCenter.getY()
* (mapSize.getHeight() / oldMapSize.getHeight())));
repaint();
} | 4 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Prioridade)) {
return false;
}
Prioridade other = (Prioridade) object;
if ((this.codprioridade == null && other.codprioridade != null) || (this.codprioridade != null && !this.codprioridade.equals(other.codprioridade))) {
return false;
}
return true;
} | 5 |
@SuppressWarnings("deprecation")
@EventHandler
public void onHit(EntityDamageByEntityEvent e)
{
if (((e.getEntity() instanceof Player)) && ((e.getDamager() instanceof Arrow)))
{
Arrow arrow = (Arrow)e.getDamager();
if ((arrow.getShooter() instanceof Player))
{
Player attacker = (Player)arrow.getShooter();
Player player = (Player)e.getEntity();
if ((Arenas.isInArena(player)) && (Arenas.isInArena(attacker)))
{
Arena arena = Arenas.getArena(player);
if (arena.isOn()) {
if (!player.getName().equalsIgnoreCase(attacker.getName())) {
e.setDamage(100.0D);
} else {
e.setCancelled(true);
}
}
}
}
}
} | 7 |
public City(Civilization owner,Point start,int population,int id,int maxSize) {
LAND=new ArrayList<Point>();
LAND.add(start);
CENTER=start;
//growthRate=owner.growthRate;
//growth=owner.getPreference(start)*growthRate/100;
this.population=population;
this.owner=owner;
this.id=id;
startYear=owner.WORLD.year;
start.owner=this;
this.maxSize=maxSize;
populationDensity=owner.populationDensity;
maxPopulation=maxSize*owner.populationDensity;
sea=false;
river=false;
for (Point p:start.adjacent)
if (p.biome==Biome.SEA)
sea=true;
else if (p.biome==Biome.RIVER)
river=true;
} | 3 |
public void next(int width, int height) {
if (nextIndex+2 < nextCoord.size()) {
nextIndex = (nextIndex+2)%nextCoord.size();
xcoord = ((Integer)nextCoord.get(nextIndex)).intValue();
ycoord = ((Integer)nextCoord.get(nextIndex+1)).intValue();
} else {
// stop animation
setAnimation(false);
isDone = true;
}
if (nextIndex2+2 < nextCoord2.size()) {
nextIndex2 = (nextIndex2+2)%nextCoord2.size();
xcoord2 = ((Integer)nextCoord2.get(nextIndex2)).intValue();
ycoord2 = ((Integer)nextCoord2.get(nextIndex2+1)).intValue();
} else {
isDone2 = true;
}
if (nextIndex3+2 < nextCoord3.size()) {
nextIndex3 = (nextIndex3+2)%nextCoord3.size();
xcoord3 = ((Integer)nextCoord3.get(nextIndex3)).intValue();
ycoord3 = ((Integer)nextCoord3.get(nextIndex3+1)).intValue();
} else {
isDone3 = true;
}
} | 3 |
public ReplaceVisitor(final Node from, final Node to) {
this.from = from;
this.to = to;
if (Tree.DEBUG) {
System.out.println("replace " + from + " VN=" + from.valueNumber()
+ " in " + from.parent + " with " + to);
}
} | 1 |
private void addOwnerIfConfirm() {
if (isUserConfirm(getConfirm())) {
try {
new OwnerServiceImpl().add(model);
logger.info("New owner ({}) successfully inserted to table {}.owners", model,
JdbcInfo.getInstance().getDbName());
} catch (DaoException e) {
view.printException(e);
logger.warn(e.getMessage(), e);
}
}
// TODO придумать что делать после добаления нового пользователя и при отмене добавления
} | 2 |
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
} | 0 |
@Override
public String toString(){
ArrayList<String> dep = new ArrayList<String>();
if(dependances != null){
for(Tache t : dependances){
dep.add(label);
}
}
if(datePlusTard == -1|| datePlusTot == -1){
return label+dep+"[ durée: "+duree+" ]";
}
else{
return label+dep+"[ durée: "+duree+", date au plus tot: "+datePlusTot+", date au plus tard: "+datePlusTard+" ]";
}
} | 4 |
public void testConstructor_int_int_int_Chronology() throws Throwable {
YearMonthDay test = new YearMonthDay(1970, 6, 9, GREGORIAN_PARIS);
assertEquals(GREGORIAN_UTC, test.getChronology());
assertEquals(1970, test.getYear());
assertEquals(6, test.getMonthOfYear());
assertEquals(9, test.getDayOfMonth());
try {
new YearMonthDay(Integer.MIN_VALUE, 6, 9, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonthDay(Integer.MAX_VALUE, 6, 9, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonthDay(1970, 0, 9, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonthDay(1970, 13, 9, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonthDay(1970, 6, 0, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
try {
new YearMonthDay(1970, 6, 31, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
new YearMonthDay(1970, 7, 31, GREGORIAN_PARIS);
try {
new YearMonthDay(1970, 7, 32, GREGORIAN_PARIS);
fail();
} catch (IllegalArgumentException ex) {}
} | 7 |
@Override
public void actionPerformed(JTable table)
{
final MediaElement[] selected = getSelected(table);
if (table != null || selected.length > 1)
new FilePlayer(selected).execute();
else
new FilePlayer(media).execute();
} | 2 |
public void body()
{
// a loop that is looking for internal events only
Sim_event ev = new Sim_event();
while ( Sim_system.running() )
{
super.sim_get_next(ev);
// if the simulation finishes then exit the loop
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION ||
super.isEndSimulation() == true)
{
break;
}
}
// CHECK for ANY INTERNAL EVENTS WAITING TO BE PROCESSED
while (super.sim_waiting() > 0)
{
// wait for event and ignore since it is likely to be related to
// internal event scheduled to update Gridlets processing
super.sim_get_next(ev);
System.out.println(super.resName_ +
".NewPolicy.body(): ignore internal events");
}
} | 4 |
void skipComment(final Input in) {
try {
final String rest = in.restOfLine();
if (rest.startsWith(lineCommentStart)) {
next(in, lineCommentStart.length());
while (in.unlessEof()) {
final char c0 = in.current();
if (c0 == CR) {
final char c1 = in.next();
if (c1 == LF) {
in.next();
}
break;
}
in.next();
if (in.reachedEof()) {
break;
}
}
} else if (rest.startsWith(blockCommentStart)) {
next(in, blockCommentStart.length());
while (in.unlessEof()) {
if (in.restStartsWith(blockCommentEnd)) {
next(in, blockCommentEnd.length());
break;
}
in.next();
}
}
return;
} catch (InputExeption e) {
throw new ParseException(e, in);
}
} | 9 |
public boolean validMove(int targetX, int targetY, boolean color) {
if (Board.onBoard(targetX, targetY)
&& ((curX == targetX)
&& ((targetY == curY + 1) || (targetY == curY - 1)) || ((curY == targetY) && ((targetX == curX + 1) || (targetX == curX - 1))))) {
return true;
}
return false;
} | 7 |
public static void compareFiles(String filePath1, String filePath2, List<String> messageDeliverOrder) {
System.out.println("Comparing " + filePath1 + " and " + filePath2 + " by thread " + Thread.currentThread().getName());
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath1));
String message;
while ((message = bufferedReader.readLine()) != null) {
messageDeliverOrder.add(message);
}
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader(filePath2));
int msgExpectedIdx = 0;
while ((message = bufferedReader.readLine()) != null) {
if (msgExpectedIdx >= messageDeliverOrder.size()) {
messageDeliverOrder.add(message);
++msgExpectedIdx;
continue;
}
String otherMessage = messageDeliverOrder.get(msgExpectedIdx);
if (otherMessage.equals(message)) {
msgExpectedIdx++;
continue;
}
int realMsgIdx = messageDeliverOrder.indexOf(message);
if (realMsgIdx == -1) {
continue;
} else if (realMsgIdx < msgExpectedIdx) {
System.err.println("[" + Thread.currentThread().getName() + "] Message deliver out of order: " + message);
}
msgExpectedIdx = realMsgIdx + 1;
}
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace(); // TODO: Customise this generated block
} catch (IOException e) {
e.printStackTrace(); // TODO: Customise this generated block
} finally {
System.out.println("Finished comparing this files");
}
} | 8 |
private void inviteToChannel(ChatChannel channel, ProxiedPlayer player, CommandSender sender) {
if (player != null) {
if (channel.containsMember(player.getName())) {
String msg = plugin.CHANNEL_IS_MEMBER;
msg = msg.replace("%player", player.getName());
msg = msg.replace("%channel", channel.getName());
sender.sendMessage(msg);
return;
}
channel.invitePlayer(player.getName());
String pmsg = plugin.PLAYER_INVITE;
pmsg = pmsg.replace("%channel", channel.getName());
pmsg = pmsg.replace("%sender", sender.getName());
player.sendMessage(pmsg);
String imsg = plugin.PLAYER_INVITED;
imsg = imsg.replace("%player", player.getName());
imsg = imsg.replace("%channel", channel.getName());
sender.sendMessage(imsg);
} else
sender.sendMessage(plugin.PLAYER_NOT_ONLINE);
} | 2 |
private boolean is_assigned(CPA cpa) throws Exception {
boolean assignmets_constraied = false;
int k = -1;
for (int i = 0; i < Domain.length; i++) {
k++;
k = find_next_possible_assignment(k);
if (k == -1) {
return false;
}
Assignment assignment = new Assignment(this._id, k);
for (int j = 0; j < cpa.length() && !assignmets_constraied; j++) {
if (constrained(assignment, cpa.getAssignment(j))) {
assignmets_constraied = true;
}
}
if (!assignmets_constraied) {
Domain[k] = 0;
cpa.add_assignment(assignment);
return true;
}
assignmets_constraied = false;
}
return false;
} | 6 |
@Override
public boolean equals(Object obj) {
return obj != null
&& obj instanceof ShopItem
&& ((ShopItem) obj).getSlot() == getSlot();
} | 2 |
public void compile(ClassFile cf) {
if ((code==17) || (code==18)) {
chi[0].compile(cf);
cf.code(code-(17 - 0xF4)); // logical_param AND/OR
chi[1].compile(cf);
cf.code(code-(17 - 0xF6)); // logical_end AND/OR
} else {
chi[0].compile(cf);
cf.code(0xFA); // ensure value;
chi[1].compile(cf);
cf.code(0xFA); // ensure value;
cf.code(ops[code][opsIDX] & 0xFFFFFFFFL);
// & is needed to prevent sign extension when converting "int" ops
// element into "long" argument of code.
cf.noteStk(chi[0].resID,-1);
cf.noteStk(chi[1].resID,-1);
if (cf.currJump==0) // jumps do not load anything to the stack
cf.noteStk(-1,resID);
};
}; | 3 |
public String[] generateDeck(String args){
Random r = new Random();
int size = r.nextInt(31) + 60;
String[] deck = new String[size];
if(args.compareToIgnoreCase("random") == 0){
for(int i = 0; i < size; i++){
int num = r.nextInt(13);
if(num % 3 == 0){
switch(num){
case 0:
deck[i] = "Swamp";
break;
case 3:
deck[i] = "Island";
break;
case 6:
deck[i] = "Mountain";
break;
case 9:
deck[i] = "Forest";
break;
case 12:
deck[i] = "Plains";
break;
default:
deck[i] = String.valueOf(num);
}
} else{
deck[i] = this.cardList.get(r.nextInt(this.cardList.size()));
}
}
}
return deck;
} | 8 |
private static Object[] parseTask(StringTokenizer str) {
String taskName = str.nextToken();
Object[] task = null;
if (taskName.equals("get")) {
task = new Object[2];
task[0] = new Integer(0);
task[1] = str.nextToken();
} else if (taskName.equals("replicate")) {
task = new Object[3];
task[0] = new Integer(1);
task[1] = str.nextToken();
task[2] = str.nextToken();
} else if (taskName.equals("attribute")) {
task = new Object[2];
task[0] = new Integer(3);
task[1] = str.nextToken();
} else if (taskName.equals("delete")) {
task = new Object[3];
task[0] = new Integer(2);
task[1] = str.nextToken();
task[2] = str.nextToken();
}
return task;
} | 4 |
public void run() {
while (true) {
try {
logger.debug("Waiting for new message");
permits.acquire();
Message msg = queue.poll();
if (msg == null) {
logger.error("Received null message from the queue, programming error??? Ignoring the message");
break;
}
if (msg == poison) {
logger.info("Received close signal, closing queue:"
+ name);
break;
}
// Bottleneck prone - Intro multiple thread per set of subscribers
for (AsyncMessageConsumer subscriber : subscribers) {
subscriber.onMessage(msg.clone());
logger.debug("Message sent to a client");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
} | 5 |
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int k = Reader.nextInt();
int[] a = new int[n+1];
int[] pos = new int[n+1];
for (int i = 0; i < n; i++) {
int x = Reader.nextInt();
a[i+1] = x;
pos[x] = i + 1;
}
int[] remain = new int[k];
for (int i = 0; i < k; i++) {
remain[i] = Reader.nextInt();
}
HashSet<Integer> togo = new HashSet<Integer>();
int cur = 1;
for (int i = 0; i < k; i++) {
while (a[cur] != remain[i]) {
togo.add(a[cur]);
cur++;
}
cur++;
}
for (; cur < n+1; cur++) {
togo.add(a[cur]);
}
BIT bit = new BIT(n);
TreeSet<Integer> occu = new TreeSet<Integer>();
long result = 0;
for (int i = 1; i < n+1; i++) {
int x = pos[i];
if (togo.contains(i)) {
int right = (occu.ceiling(x+1) == null ? n : occu.ceiling(x+1)-1);
int left = (occu.floor(x-1) == null ? 1 : occu.floor(x-1)+1);
int discarded = getDiscarded(bit, left, right);
result += right - left + 1 - discarded;
bit.set(x, 1);
} else {
occu.add(x);
}
}
System.out.println(result);
} | 9 |
public void setMusicType(MusicTypes musicType) {
this.musicType = musicType;
} | 0 |
private void drawBar() {
GL11.glColor3f(color2[0], color2[1], color2[2]);
GL11.glBegin(GL11.GL_QUADS);
if (isDouble != 1) {
switch (orientation) {
case Tile.UP:
GL11.glVertex2f(x,y);
GL11.glVertex2f(x + width,y);
GL11.glVertex2f(x + width,y + length - barLength);
GL11.glVertex2f(x,y + length - barLength);
break;
case Tile.DOWN:
GL11.glVertex2f(x,y + length);
GL11.glVertex2f(x,y + barLength);
GL11.glVertex2f(x + width,y + barLength);
GL11.glVertex2f(x + width,y + length);
break;
case Tile.LEFT:
GL11.glVertex2f(x,y);
GL11.glVertex2f(x + length - barLength,y);
GL11.glVertex2f(x + length - barLength,y + width);
GL11.glVertex2f(x,y + width);
break;
case Tile.RIGHT:
GL11.glVertex2f(x + length,y);
GL11.glVertex2f(x + length,y + width);
GL11.glVertex2f(x + barLength,y + width);
GL11.glVertex2f(x + barLength,y);
break;
}
}
GL11.glEnd();
} | 5 |
private void refreshDialog() {
String nr = currentAccountNumber();
accountcombo.removeAllItems();
if (bank != null) {
try{
Set<String> s = bank.getAccountNumbers();
ArrayList<String> accnumbers = new ArrayList<String>(s);
Collections.sort(accnumbers);
ignoreItemChanges=true;
for(String item : accnumbers){
accountcombo.addItem(item);
if(item.equals(nr)) accountcombo.setSelectedItem(item);
}
ignoreItemChanges=false;
// clean up local accounts map
for(String key : s){
if(!accounts.containsKey(key)){
accounts.put(key, bank.getAccount(key));
}
}
Iterator<String> it = accounts.keySet().iterator();
while(it.hasNext()){
if(!s.contains(it.next())) it.remove();
}
int size = s.size();
btn_deposit.setEnabled(size > 0);
btn_withdraw.setEnabled(size > 0);
btn_transfer.setEnabled(size > 1);
item_close.setEnabled(size > 0);
for (BankTest t : tests) {
JMenuItem m = testMenuItems.get(t);
m.setEnabled(t.isEnabled(size));
}
updateCustomerInfo();
}
catch(Exception e){
error(e);
}
}
} | 9 |
public List<T> getAllItems()
{
List<T> list = new ArrayList<>();
for(IAliasedItem<T> item : backingMap.values())
{
list.add(item.getItem());
}
return list;
} | 1 |
public static void toggleMoveable(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
JoeNodeList nodeList = tree.getSelectedNodes();
for (int i = 0, limit = nodeList.size(); i < limit; i++) {
toggleMoveableForSingleNode(nodeList.get(i), undoable);
}
if (!undoable.isEmpty()) {
if (undoable.getPrimitiveCount() == 1) {
undoable.setName("Toggle Moveability for Node");
} else {
undoable.setName(new StringBuffer().append("Toggle Moveability for ").append(undoable.getPrimitiveCount()).append(" Nodes").toString());
}
tree.getDocument().getUndoQueue().add(undoable);
}
layout.draw(currentNode, OutlineLayoutManager.ICON);
} | 3 |
private void fineUser(Criteria criteria, AbstractDao dao) throws DaoException {
Criteria bean = new Criteria();
bean.addParam(DAO_ID_USER, criteria.getParam(DAO_ID_USER));
bean.addParam(DAO_USER_SELECT_FOR_UPDATE, true);
List<User> users = dao.findUsers(bean);
if (users.isEmpty()) {
throw new DaoException("User not found.");
}
User user = users.get(0);
Integer userDiscount = user.getDiscount();
Integer discountForDeleteOrder = PriceDiscountManager.getDiscountForDeleteOrder(userDiscount);
Criteria crit = new Criteria();
crit.addParam(DAO_USER_DISCOUNT, discountForDeleteOrder);
dao.updateUser(bean, crit);
} | 1 |
private void setAdjacentNumbers()
{
//top two for loops iterate through the board and pass each cell into the second two for loops, which check each cell adjacent to the cell for a mine
for (int x = 0; x<boardSize; x++) { //this is to iterate through each cell
for (int y = 0; y<boardSize; y++) {
for (int t = x-1;t<x+2;t++) { //3x3 grid of original cell, checks for mines in this grid and if so increments counter for original cell
for (int b = y-1; b<y+2; b++) {
if (t<0 || b < 0 || t>boardSize-1 || b>boardSize-1 ) { //so that out of bounds cannot occur
continue;
}
if (cells[t][b].getMined()) { //if there is a mine in one of the adjacent cells
cells[x][y].incrementAdjacentMines(); //then increment the number of adjacent mines
}
}
}
}
}
} | 9 |
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
// nanoPosts.clear();
tabs.setSelectedIndex(1);
DefaultTableModel model = (DefaultTableModel) tableSync.getModel();
int rows = model.getRowCount();
for (int i = rows - 1; i >= 0; i--) {
model.removeRow(i);
}
WorkerLocalSync wls = new WorkerLocalSync(this, edBoardCode.getText());
wls.execute();
for (Rule r : RulesManager.getInstance().getRulesList()) {
if (r.isIsEnabled()) {
WorkerExecuteRule wer = new WorkerExecuteRule(this, r);
wer.execute();
}
}
}//GEN-LAST:event_btnStartActionPerformed | 3 |
public void clearConversations() {
for(String user : mMessageWindows.keySet()) {
mMessageWindows.get(user).setVisible(false);
}
mMessageWindows.clear();
} | 1 |
@Override
public void paint(Graphics windowGraphics) {
if (windowGraphics == null)
return;
windowWidth = getWidth();
windowHeight = getHeight();
if (frontImageBuffer == null) {
// no image to display
windowGraphics.clearRect(0, 0, windowWidth, windowHeight);
return;
}
synchronized (Zen.class) {
Image image = paintImmediately ? backImageBuffer : frontImageBuffer;
if (stretchToFit) {
paintAtX = paintAtY = 0;
windowGraphics.drawImage(image, 0, 0, windowWidth,
windowHeight, this);
} else { // Blacken unused sides
int x = windowWidth - bufferSize.width;
int y = windowHeight - bufferSize.height;
paintAtX = x / 2;
paintAtY = y / 2;
windowGraphics.setColor(Color.BLACK);
// Notes: Some of the +1's may be unnecessary.
// Notes: Actually there's some overlap in the 4 corners that
// could
// be removed
if (y > 0) {
windowGraphics.fillRect(0, 0, windowWidth + 1, paintAtY);
windowGraphics.fillRect(0, windowHeight - paintAtY - 1,
windowWidth + 1, paintAtY + 1);
}
if (x > 0) {
windowGraphics.fillRect(0, 0, paintAtX + 1,
windowHeight + 1);
windowGraphics.fillRect(windowWidth - paintAtX - 1, 0,
paintAtX + 1, windowHeight + 1);
}
windowGraphics.drawImage(image, paintAtX, paintAtY, this);
}
}
} // paint | 6 |
public static int firstEmptyPosition(Board board, int col) {
int row = Board.MINHEIGHT;
//Error-checking
if (!Util.isColumnValid(board, col)) {
//Column is out of bounds
row = Util.ERRORTHRESHOLD;
}
else {
while ((row <= board.getHeight()) &&
(board.getPosition(col, row) == Counter.EMPTY)) {
row++;
}
if (!Util.isRowValid(board, row)) {
row = Util.ERRORTHRESHOLD;
}
}
return row - 1;
} | 4 |
@Override
public void updateBounty(Bounty bounty) throws DataStorageException {
try {
PreparedStatement ps = getFreshPreparedStatementColdFromTheRefrigerator("UPDATE bounties SET issuer = ?, hunted = ?, reward = ?, created = ?, hunter = ?, turnedin = ?, redeemed = ? WHERE id = ?");
ps.setString(1, bounty.getIssuer());
ps.setString(2, bounty.getHunted());
ps.setDouble(3, bounty.getReward());
ps.setTimestamp(4, new Timestamp(bounty.getCreated().getTime()));
if (bounty.getHunter() == null)
ps.setNull(5, Types.VARCHAR);
else
ps.setString(5, bounty.getHunter());
if (bounty.getTurnedIn() == null)
ps.setNull(6, Types.TIMESTAMP);
else
ps.setTimestamp(6, new Timestamp(bounty.getTurnedIn().getTime()));
if (bounty.getRedeemed() == null)
ps.setNull(7, Types.TIMESTAMP);
else
ps.setTimestamp(7, new Timestamp(bounty.getRedeemed().getTime()));
ps.setInt(8, bounty.getID());
ps.execute();
} catch (SQLException e) {
throw new DataStorageException(e);
}
} | 4 |
@Test(expected = InstanceNotFoundException.class)
public void removeInexistentActivityTest() throws InstanceNotFoundException {
Activity activity = null;
try {
activity = activityService.find(0);
} catch (InstanceNotFoundException e1) {
fail("Activity not exist");
}
activityService.remove(activity);
activityService.remove(activity);
} | 1 |
public boolean deleteDirOrFile(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDirOrFile(new File(dir, children[i]));
if (!success)
return false;
}
}
boolean estSupprime = dir.delete();
System.out.println(dir.toString() + " est supprimé !");
// The directory is now empty so delete it
return estSupprime;
} | 3 |
void computeCubicCoefficients(int n, double[][] C) {
double[][] H = Geometry.Hermite;
for (int j = 0 ; j < dd[n].length ; j++)
vec[j] = dd[n+1][j] - dd[n][j];
double cordLength = norm(vec, dd[n].length);
double scale = 1.0;
if (isFunction())
scale = Math.max(0.25, Math.min(1.0, vec[0] / (Math.abs(vec[1]) + 0.01)));
for (int j = 0 ; j < dd[n].length ; j++) {
double scaleTangent = cordLength * 1.15;
switch (nRows) {
case 3: scaleTangent *= 1.20; break;
case 4: scaleTangent *= 1.15; break;
case 6: scaleTangent *= 0.95; break;
}
if (isFunction())
scaleTangent *= scale;
double p0 = dd[n][j];
double p1 = dd[n+1][j];
double r0 = scaleTangent * ddd[n][j];
double r1 = scaleTangent * ddd[n+1][j];
for (int i = 0 ; i < 4 ; i++)
C[j][i] = H[i][0] * p0 + H[i][1] * p1 + H[i][2] * r0 + H[i][3] * r1;
}
} | 8 |
private void tick() {
if (network.hasUnreadDTOs())
synchronizeEntities(network.getUnreadDTOs());
if (network.hasClientDisconnected())
removeDisconnectedClientEntities(network.getClientDisconnectedId());
List<Long> deletedEntities = new ArrayList<>();
for (Entity e : entityMap.values()) {
e.tick(this);
if (e.isDeleted())
deletedEntities.add(e.getEntityID());
}
entityMap.keySet().removeAll(deletedEntities);
entityFactory.putAllNewEntities(entityMap);
// add new asteroid from time to time
if (timerAddAsteroids.isTimeleft()) {
AsteroidEntity entity = entityFactory.createAsteroid(
new Vector2d(Constants.WIDTH / 2, Constants.HEIGHT / 2), new Vector2d(), AsteroidEntity.INIT_SIZE,
Constants.SERVER_ID);
addEntity(entity);
}
logger.debug("Entitycount: " + entityMap.size());
if (timerSend.isTimeleft()) {
network.sendDTO(new ServerInfoDTO(StringFormatter.format(cpuWorkload)));
for (Entry<Long, Entity> e : entityMap.entrySet()) {
network.sendDTO(e.getValue().toDTO());
}
network.sendNow();
}
} | 7 |
public int run(String[] arg) throws IOException, ClassNotFoundException, InterruptedException {
// //First Job, here the algorithm is ran
Configuration prefixconf = new Configuration();
String support = arg[1];
prefixconf.set("Support", support);
Job PrefixSpan = new Job(prefixconf);
PrefixSpan.setJarByClass(PrefixSpanHadoop.class);
FileSystem fs = FileSystem.get(new Configuration());
Path temp_output = new Path("temp_output");
if (fs.exists(temp_output)) {
fs.delete(temp_output, true); //Delete existing Directory
}
PrefixSpan.setJobName("Mining the Data");
//Setting configuration object with the Data Type of output Key and Value
PrefixSpan.setOutputKeyClass(Text.class);
PrefixSpan.setOutputValueClass(Text.class);
//Providing the mapper and reducer class names
PrefixSpan.setMapperClass(PrefixSpanMapper.class);
PrefixSpan.setNumReduceTasks(0);
//the hdfs input and output directory to be fetched from the command line
FileInputFormat.addInputPath(PrefixSpan, new Path(arg[0]));
PrefixSpan.setInputFormatClass(TextInputFormat.class);
FileOutputFormat.setOutputPath(PrefixSpan, temp_output);
// Execute job
PrefixSpan.waitForCompletion(true);
//Second job, iterating mapper tasks until we get a list of sequences and the count of each
long thistask = 0;
long lastask;
while (true) {
lastask =thistask;
Configuration NoSequencesConf = new Configuration();
Job NoSequences = new Job(NoSequencesConf);
NoSequences.setJarByClass(PrefixSpanHadoop.class);
Path Sequences = new Path("Sequences");
if (fs.exists(Sequences)) {
fs.delete(Sequences, true); //Delete existing Directory
}
NoSequences.setJobName("Counting number of sequences");
//Setting configuration object with the Data Type of output Key and Value
NoSequences.setOutputKeyClass(Text.class);
NoSequences.setOutputValueClass(Text.class);
//Providing the mapper and reducer class names
NoSequences.setMapperClass(Mapper_no_sequences.class);
NoSequences.setNumReduceTasks(0);
//the hdfs input and output directory to be fetched from the command line
FileInputFormat.addInputPath(NoSequences, temp_output);
NoSequences.setInputFormatClass(NLinesInputFormat.class);
FileOutputFormat.setOutputPath(NoSequences, Sequences);
NoSequences.waitForCompletion(true);
fs.delete(temp_output, true);
fs.rename(Sequences, temp_output);
//check if it has converged
Counters counters = NoSequences.getCounters();
thistask = counters.findCounter("org.apache.hadoop.mapred.Task$Counter", "MAP_INPUT_RECORDS").getValue();
if (thistask == lastask) {
break;
}
}
//Thirth job getting the total number of sequences found
Configuration getnumOfSeqsconf = new Configuration();
Job getnumOfSeqs = new Job(getnumOfSeqsconf);
getnumOfSeqs.setJobName("get total number of sequences");
getnumOfSeqs.setJarByClass(PrefixSpanHadoop.class);
//Providing the mapper and reducer class names
getnumOfSeqs.setMapperClass(Mapper_getnumOfSeqs.class);
getnumOfSeqs.setReducerClass(Reducer_getnumOfSeqs.class);
Path numOfSeqs = new Path("numOfSeqs");
if (fs.exists(numOfSeqs)) {
fs.delete(numOfSeqs, true); //Delete existing Directory
}
FileOutputFormat.setOutputPath(getnumOfSeqs, numOfSeqs);
FileInputFormat.addInputPath(getnumOfSeqs, temp_output);
//Setting configuration object with the Data Type of output Key and Value
getnumOfSeqs.setOutputKeyClass(Text.class);
getnumOfSeqs.setOutputValueClass(Text.class);
getnumOfSeqs.setInputFormatClass(NLinesInputFormat.class);
getnumOfSeqs.waitForCompletion(true);
//Last job wrapping up everything
Configuration finalCalcConf = new Configuration();
//get the number of sequences from the previous job scanning the output folder
String numofSeqs = "0";
FileStatus[] fss = fs.listStatus(numOfSeqs);
for (FileStatus status : fss) {
Path path = status.getPath();
BufferedReader bfr=new BufferedReader(new InputStreamReader(fs.open(path)));
if (bfr.ready()){
String[] line = bfr.readLine().split("\t");
if (line[0].contains("size")) {
numofSeqs = line[1];
}
}
}
finalCalcConf.set("numofSeqs", numofSeqs);
finalCalcConf.set("Support", support);
Job finalCalc = new Job(finalCalcConf);
finalCalc.setJobName("gathering all sequences and filtering by support");
finalCalc.setJarByClass(PrefixSpanHadoop.class);
//Providing the mapper and reducer class names
finalCalc.setMapperClass(Mapper_finalCalc.class);
finalCalc.setReducerClass(Reducer_finalCalc.class);
Path output = new Path("output");
if (fs.exists(output)) {
fs.delete(output, true); //Delete existing Directory
}
FileOutputFormat.setOutputPath(finalCalc, output);
FileInputFormat.addInputPath(finalCalc, temp_output);
//Setting configuration object with the Data Type of output Key and Value
finalCalc.setOutputKeyClass(Text.class);
finalCalc.setOutputValueClass(Text.class);
finalCalc.setInputFormatClass(NLinesInputFormat.class);
finalCalc.waitForCompletion(true);
return 0;
} | 9 |
@Override
public boolean activate() {
return (Bank.isOpen()
&& !Widgets.get(13, 0).isOnScreen()
&& Settings.usingFlask
);
} | 2 |
private void statement(Symbol function) throws ParserException {
enterRule(NonTerminal.STATEMENT);
if (have(NonTerminal.ASSIGNMENT)) assignment();
else if (have(NonTerminal.INPUT)) input();
else if (have(NonTerminal.OUTPUT)) output();
else if (have(NonTerminal.IF_STATEMENT)) ifStatement();
else if (have(NonTerminal.WHILE_STATEMENT)) whileStatement();
else if (have(NonTerminal.RETURN_STATEMENT)) returnStatement(function);
else if (have(NonTerminal.PROCEDURE_STATEMENT)) procedureStatement();
else expect(NonTerminal.STATEMENT);
exitRule(NonTerminal.STATEMENT);
} | 7 |
public Set<String> getBranches() {
return branches;
} | 0 |
public boolean getLeftKeyPressed() {
return leftKeyPressed;
} | 0 |
public void updateRecord(Record in) throws SQLException
{
// First get the format number
int formatNumber = in.getFormat().save();
// Get the new category number
int catNum = in.getCategory().save();
// Add the record itself
updateRecord.setString(1, in.getTitle());
updateRecord.setDate(2, new java.sql.Date(in.getDate().getTime().getTime()));
updateRecord.setInt(3, formatNumber);
updateRecord.setString(4, in.getNotes());
updateRecord.setInt(5, in.getReleaseYear());
updateRecord.setInt(6, catNum);
updateRecord.setString(7, in.getAuthor());
updateRecord.setInt(8, in.getReleaseMonth());
updateRecord.setInt(9, in.getReleaseType());
updateRecord.setInt(10, in.getOwner());
updateRecord.setDouble(11, in.getPrice());
updateRecord.setInt(12, in.getShelfPos());
updateRecord.setString(13, in.getRiploc());
updateRecord.setInt(14, in.getDiscogsNum());
updateRecord.setInt(15, in.getParent());
updateRecord.setInt(17, in.getNumber());
updateRecord.setDouble(16, in.getSoldPrice());
updateRecord.execute();
int recordNumber = in.getNumber();
// Delete the label numbers
PreparedStatement ps = Connect.getConnection().getPreparedStatement(
"DELETE FROM LabelSet WHERE RecordNumber = ?");
ps.setInt(1, recordNumber);
ps.execute();
// Get the label numbers
int[] labNums = new int[in.getLabels().size()];
int labPointer = 0;
for (Label lab : in.getLabels())
labNums[labPointer++] = lab.save();
for (int labNum : labNums)
{
// Add the numbers to the label set
PreparedStatement lps = Connect.getConnection().getPreparedStatement(
"INSERT INTO LabelSet (RecordNumber,LabelNumber) VALUES (?,?)");
lps.setInt(1, recordNumber);
lps.setInt(2, labNum);
lps.execute();
}
// Delete the catalogue numbers
PreparedStatement lps = Connect.getConnection().getPreparedStatement(
"DELETE FROM CatNoSet WHERE RecordNumber = ?");
lps.setInt(1, recordNumber);
lps.execute();
// Add the catalogue numbers
Iterator<String> cIt = in.getCatNos().iterator();
while (cIt.hasNext())
{
String catNo = cIt.next();
PreparedStatement llps = Connect.getConnection().getPreparedStatement(
"INSERT INTO CatNoSet (RecordNumber,CatNo) VALUES (?,?)");
llps.setInt(1, recordNumber);
llps.setString(2, catNo);
llps.execute();
}
// Deal with the tracks
for (Track t : in.getTracks())
t.save(in.getNumber());
// Delete any miscreant tracks
PreparedStatement dps = Connect.getConnection().getPreparedStatement(
"DELETE FROM Track WHERE recordnumber = ? AND tracknumber > ?");
dps.setInt(1, in.getNumber());
dps.setInt(2, in.getTracks().size());
dps.execute();
} | 4 |
public Integer[] nextIntArray() throws Exception {
String[] line = reader.readLine().trim().split(" ");
Integer[] out = new Integer[line.length];
for (int i = 0; i < line.length; i++) {
out[i] = Integer.valueOf(line[i]);
}
return out;
} | 1 |
public void paintComponent(Graphics g){
super.paintComponent(g);
// if(this.isFocusOwner()){
for( int i = 0; i < attachRods.size(); i++){
attachRods.get(i).paintComponent(g);
}
for( int i = 0; i < attachPoints.size(); i++){
attachPoints.get(i).paintComponent(g);
}
if(!placeRod){
Point mouseLoc = getMouseLocationOnComp();
g.drawLine((int)tempPointHead.position[0], (int)tempPointHead.position[1],
mouseLoc.x, mouseLoc.y);
g.drawOval(mouseLoc.x - 5, mouseLoc.y - 5, 10, 10);
}
// }
} | 3 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.