text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void ensureXrefEntriesCapacity(int size) {
if (xrefEntries == null || xrefEntries.length < size) {
final PDFXrefEntry[] newXrefEntries = new PDFXrefEntry[size];
if (xrefEntries != null) {
System.arraycopy(xrefEntries, 0, newXrefEntries, 0, xrefEntries.length);
}
xrefEntries = newXrefEntries;
}
} | 3 |
public static BigInteger combination(BigInteger poolI,
BigInteger chooseI) {
if(poolI.compareTo(BigInteger.ZERO)<0||chooseI.compareTo(BigInteger.ZERO)<0){
throw new ArithmeticException("Cannot take combinations of negative numbers");
}
if(poolI.compareTo(chooseI)<0){
return BigInteger.ZERO;
}
if(chooseI.compareTo(BigInteger.ZERO)==0){
return BigInteger.ONE;
}
final BigRational pool = new BigRational(poolI,BigInteger.ONE);
final BigRational choose= new BigRational(chooseI,BigInteger.ONE);
final BigRational one = new BigRational(1);
final BigRational two = new BigRational(2);
BigRational i = pool.minus(choose).plus(one);
BigRational j = choose;
BigRational total = one;
while (i.compareTo(pool) <= 0
&& j.compareTo(two) >= 0) {
total = total.times(i);
total = total.dividedBy(j);
i = i.plus(one);
j = j.minus(one);
}
while (i.compareTo(pool) <= 0) {
total = total.times(i);
i = i.plus(one);
}
while (j.compareTo(two) >= 0) {
total = total.dividedBy(j);
j = j.minus(one);
}
return total.bigIntegerValue();
} | 8 |
public void share (CompNumb p); // Деление | 2 |
public Transition(String transition, State next, int pointer){
String params[] = transition.split("->");
this.right = params[1].split(" ");
this.next = null;
if(this.right.length > pointer){
this.next = next;
this.reduction = -1;
}
else{
this.reduction = getReductionId();
}
} | 1 |
@Override
protected void readAll(List<Address> members, String clustername, Responses responses) {
try {
List<String> objects = swiftClient.listObjects(container);
for(String object: objects) {
List<PingData> list=null;
byte[] bytes = swiftClient.readObject(container, object);
if((list=read(new ByteArrayInputStream(bytes))) == null) {
log.warn("failed reading " + object);
continue;
}
for(PingData data: list) {
if(members == null || members.contains(data.getAddress()))
responses.addResponse(data, data.isCoord());
if(local_addr != null && !local_addr.equals(data.getAddress()))
addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr());
}
}
} catch (Exception e) {
log.error(Util.getMessage("ErrorUnmarshallingObject"), e);
}
} | 8 |
public int getResult(){
int returnValue = 7, c = this._qtdConsumo;
int aux =0;
if(c>11){
aux = (c<30)?c:30;
returnValue += ((aux-11)+1)*1;
}//END IF
if(c>31){
aux = (c<100)?c:100;
returnValue += ((aux-31)+1)*2;
}//END IF
if(c>101){
returnValue += ((c-101)+1)*5;
}//END IF
return returnValue;
}//END FUNCTION | 5 |
public ComboBoxListener(JComboBox box, Preference pref) {
setComboBox(box);
setPreference(pref);
} | 0 |
private String sqlTypeToJavaType(int columnType) {
if (columnType == java.sql.Types.INTEGER) {
return "int";
} else if (columnType == java.sql.Types.VARCHAR || columnType == java.sql.Types.CHAR) {
return "String";
} else if (columnType == java.sql.Types.TIMESTAMP) {
return "Timestamp";
} else if (columnType == java.sql.Types.DATE) {
return "Date";
} else if (columnType == java.sql.Types.DOUBLE || columnType == java.sql.Types.NUMERIC) {
return "BigDecimal";
} else if (columnType == java.sql.Types.BOOLEAN) {
return "boolean";
}
return "nao_identificado";
} | 8 |
public static void retofinv_draw_foreground(osd_bitmap bitmap) {
int x, y, offs;
int sx, sy, tile, palette, flipx, flipy;
for (x = 0; x < 32; x++) {
for (y = 30; y <= 31; y++) {
offs = y * 32 + x;
sx = ((62 - y) + 3) << 3;
sy = (31 - x) << 3;
flipx = flipy = 0;
if (flipscreen != 0) {
sx = 280 - sx;
sy = 248 - sy;
flipx = flipy = 1;
}
tile = retofinv_fg_videoram.read(offs) + (retofinv_fg_char_bank.read(0) * 256);
palette = retofinv_fg_colorram.read(offs);
drawgfx(bitmap, Machine.gfx[0],
tile,
palette,
flipx, flipy,
sx, sy,
Machine.drv.visible_area, TRANSPARENCY_NONE, 0);
}
}
for (x = 29; x >= 2; x--) {
for (y = 31; y >= 0; y--) {
offs = x * 32 + y;
sy = ((31 - x) << 3);
sx = ((33 - y)) << 3;
flipx = flipy = 0;
if (flipscreen != 0) {
sx = 280 - sx;
sy = 248 - sy;
flipx = flipy = 1;
}
tile = retofinv_fg_videoram.read(offs) + (retofinv_fg_char_bank.read(0) * 256);
palette = retofinv_fg_colorram.read(offs);
drawgfx(bitmap, Machine.gfx[0],
tile,
palette,
flipx, flipy,
sx, sy,
Machine.drv.visible_area, TRANSPARENCY_PEN, 0);
}
}
for (x = 0; x < 32; x++) {
for (y = 1; y >= 0; y--) {
offs = y * 32 + x;
sx = (1 - y) << 3;
sy = (31 - x) << 3;
flipx = flipy = 0;
if (flipscreen != 0) {
sx = 280 - sx;
sy = 248 - sy;
flipx = flipy = 1;
}
tile = retofinv_fg_videoram.read(offs) + (retofinv_fg_char_bank.read(0) * 256);
palette = retofinv_fg_colorram.read(offs);
drawgfx(bitmap, Machine.gfx[0],
tile,
palette,
flipx, flipy,
sx, sy,
Machine.drv.visible_area, TRANSPARENCY_NONE, 0);
}
}
} | 9 |
public int generateX(int i, int j) {
double mu = 0.0;
mu += _parameters.visibleBias(j);
for (int jj = 0; jj < _parameters.numHiddenNodes(); jj++) {
mu += _parameters.weight(j, jj) * generatedHiddens[i][jj];
}
mu = MathUtilities.sigmoid(mu);
if (random.nextDouble() >= 1 - mu) {
return 1;
}
else {
return 0;
}
}; | 2 |
public static void paint(Ocean sea) {
if (sea != null) {
int width = sea.width();
int height = sea.height();
/* Draw the ocean. */
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
for (int y = 0; y < height; y++) {
System.out.print("|");
for (int x = 0; x < width; x++) {
int contents = sea.cellContents(x, y);
if (contents == Ocean.SHARK) {
System.out.print('S');
} else if (contents == Ocean.FISH) {
System.out.print('F');
} else {
System.out.print('~');
}
}
System.out.println("|");
}
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
}
} | 7 |
private String getTabReplacement(int x) {
int align = 0;
switch(this) {
case CONVERT_TO_ONE_SPACE:
return " ";
case CONVERT_TO_FOUR_SPACES:
return " ";
case CONVERT_TO_EIGHT_SPACES:
return " ";
case ALIGN_TO_COLUMN_4:
align = 4 - (x % 4);
break;
case ALIGN_TO_COLUMN_8:
align = 8 - (x % 8);
break;
}
StringBuilder replace = new StringBuilder();
for(int i = 0; i < align; i++)
replace.append(" ");
return replace.toString();
} | 6 |
public void run(){
while(true){
synchronized(this.doc){
//For each game under the games_available node, check to see if all the player ready states are true.
//If they are all true, move the game to the games_active node.
if(((Element)this.doc.getElementsByTagName("games_available").item(0)).getChildNodes() == null){
continue;
}
NodeList gamesAvailable = ((Element)this.doc.getElementsByTagName("games_available").item(0)).getElementsByTagName("game");
for(int i=0; i<gamesAvailable.getLength(); i++){
NodeList players = ((Element)(gamesAvailable.item(i))).getElementsByTagName("player");
for(int j=0; j<players.getLength(); j++){
Node ReadyNode = (Node)((Element)players.item(j)).getElementsByTagName("ready").item(0);
if(!ReadyNode.getTextContent().equals("true")){
break;
}
if(j == players.getLength() - 1){
activateGame(gamesAvailable.item(i)); //all the players must have ready states of "true" to get here
}
}
}
//Write all the changes to the XML file and update the display:
Server.writeToXML();
}
}
} | 6 |
public void update()
{
speed = potentialSpeed;
setWanDirCommand(commandLeft, commandRight, commandUp, commandDown);
if(commandC4)
placeC4();
if(cacheraufond) canard.play();
//if(cacheraufond) bouftou.play(3, 1);
if(commandTrap)
placeTrap();
if(commandBomb)
placeBomb();
if(!underTrap)
{
speed=potentialSpeed;
moveGrid();
}
else
{
timerTrap--;
if(timerTrap<=0)
{
underTrap=false;
}
}
if(hp<=0 )
{
if(TimeToChuckNorris>0){
timerDeath=90;
mort.play();
}
numberBomberman--;
destroy();
}
} | 8 |
protected String getClasspath()
throws MojoExecutionException {
try {
final List classpath = new ArrayList();
// Loading self dependencies
final List scopesToUse = new ArrayList();
scopesToUse.add(Artifact.SCOPE_COMPILE);
scopesToUse.add(Artifact.SCOPE_RUNTIME);
Iterator it = pluginArtifactMap.keySet().iterator();
while (it.hasNext()) {
Artifact artifact = (Artifact) pluginArtifactMap.get((String) it.next());
if (scopesToUse.contains(artifact.getScope())) {
artifactResolver.resolve(artifact, remoteRepositories, localRepository);
classpath.add(artifact.getFile().getAbsolutePath());
}
}
// Loading self
final Artifact self = artifactFactory.createArtifact("org.n0pe.mojo",
"ruby-maven-plugin",
"0.1-SNAPSHOT",
Artifact.SCOPE_RUNTIME,
"maven-plugin");
artifactResolver.resolve(self, remoteRepositories, localRepository);
classpath.add(self.getFile().getAbsolutePath());
// Building the classpath string
it = classpath.iterator();
final StringWriter sw = new StringWriter();
while (it.hasNext()) {
sw.append((String) it.next());
if (it.hasNext()) {
sw.append(File.pathSeparator);
}
}
return sw.toString();
} catch (ArtifactResolutionException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
} catch (ArtifactNotFoundException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
} | 6 |
protected boolean readBool(InputStream in) throws IOException {
int i = readInt(in);
if( !(i==1 || i==0) )
throw new RuntimeException("Not a bool: " + i);
return i == 1;
} | 2 |
public static final void helloWorldExample() {
try {
CycConstant planetInSolarSystem = (CycConstant) DefaultCycObject.fromCompactExternalId("Mx4rWIie-jN6EduAAADggVbxzQ", access);
CycList planets = access.getAllInstances(planetInSolarSystem);
for (Object planet : planets) {
System.out.println("Hello '"
+ access.getGeneratedPhrase((CycObject) planet) + "'.");
}
} catch (Exception e) {
e.printStackTrace();
}
} | 2 |
private String readUrl(final String url) {
try {
String inputLine, output = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
while ((inputLine = reader.readLine()) != null) {
output += inputLine;
}
reader.close();
return output;
}
catch (IOException ex) {
return null;
}
} | 2 |
private int neighborHasBomb(int neighbor_x, int neighbor_y) {
// checks a neighboring square for a bomb. If it doesn't have a bomb or
// doesn't exist
// it returns 0. Otherwise it returns 1
if (neighbor_x < 0 || neighbor_x > 9 || neighbor_y < 0
|| neighbor_y > 9)
return 0;
if (field[neighbor_x][neighbor_y].checkForBomb())
return 1;
return 0;
} | 5 |
public void MenuRun() throws Address_Table.TableException, Orders_Table.TableException, Items_Table.TableException
{
data_load = new DataLoad();
data_load.load_data();
repeat_choice = false;
while(repeat_choice == false)
{
print_menu();
try {
BufferedReader brin = new BufferedReader(new InputStreamReader(System.in));
input_line = brin.readLine();
choice_symbol = input_line.charAt(0);
switch(choice_symbol)
{
case '1': // Search by Product ID
// System.out.println("Enter Product ID : ");
// DB_Connection.Product_Queries.searchbyProductID(input_line);
repeat_choice = false;
break;
case '2': // Select ALL from Product Table
// DB_Connection.Product_Queries.searchALLProducts();
repeat_choice = false;
break;
case '3':
repeat_choice = false;
break;
case '4':
repeat_choice = false;
break;
case '5':
repeat_choice = false;
break;
case '6':
repeat_choice = false;
break;
case '7':
repeat_choice = true;
System.out.println("Good Bye...\n");
break;
default:
System.out.println("This choice is not supported\n");
repeat_choice = false;
break;
}
} //end try
catch (Exception e)
{
System.out.println("Error occurred: " + e);
}
}
} | 9 |
private String changeCharacterAtPosition(int pos, String str, String rep) {
String alteredString = str.substring(0, pos) + rep
+ str.substring(pos + 1, str.length());
return alteredString;
} | 0 |
private static void printUsage(Command command) {
if (command == Command.UNKNOWN) {
StringBuilder sb = new StringBuilder();
sb.append("Usage: StaffUtill <command> <arguments> ")
.append("\n")
.append("command: arguments :")
.append("\n")
.append("ADDEMPL filename")
.append("\n")
.append("ADDDESCR \"description\"")
.append("\n")
.append("DELEMPL employee id")
.append("\n")
.append("CHANGETYPE employee id, type(other, manager, worker)")
.append("\n")
.append("ADDTOMANAGER employee id, manager id")
.append("\n")
.append("SORTBYSURNAME")
.append("\n")
.append("SORTBYHIRINGDATE")
.append("\n")
.append("IMPORT");
System.out.println(sb);
} else if (command == Command.ADDEMPL) {
System.out.println("Usage: StaffUtill ADDEMPL filename");
} else if (command == Command.ADDDESCR) {
System.out.println("Usage: StaffUtill ADDDESCR \"description\"");
} else if (command == Command.DELEMPL) {
System.out.println("Usage: StaffUtill DELEMPL employee id");
} else if (command == Command.CHANGETYPE) {
System.out.println("Usage: StaffUtill CHANGETYPE employee id, type(other, manager, worker)");
} else if (command == Command.ADDTOMANAGER) {
System.out.println("Usage: StaffUtill ADDTOMANAGER employee id, manager id");
}
} | 6 |
private void generateCharDimensions() {
Graphics2D g2 = (new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB)).createGraphics();
g2.setFont(font);
for (int i = 0; i < characterDimensions.length; i++) {
characterDimensions[i] = font.layoutGlyphVector(g2.getFontRenderContext(), STANDARD_CHARS.toCharArray(), i, i+1, Font.LAYOUT_LEFT_TO_RIGHT).getPixelBounds(null, 0, 0);
characterDimensions[i].y += size;
}
if (characterDimensions[' ' - FIRST_STANDARD_CHAR].width <= 0) {
characterDimensions[' ' - FIRST_STANDARD_CHAR].width = (int)Math.round(size * DEFAULT_SPACE_RATIO);
}
descent = g2.getFontMetrics().getDescent();
baseline = size - descent;
g2.dispose();
} | 2 |
@RequestMapping(value="/{tripID}/deleteTravelTrip", method=RequestMethod.GET)
public String deleteTravelTrip(@PathVariable("tripID") String tripID, Model model){
travelTripService.delete(Integer.parseInt(tripID));
model.addAttribute("travelTripList", travelTripService.findAll());
return "redirect:/";
} | 0 |
public static void setPlayersNickname( String p, String nick ) throws SQLException {
if ( isPlayerOnline( p ) ) {
getPlayer( p ).setNickname( nick );
getPlayer( p ).updateDisplayName();
getPlayer( p ).updatePlayer();
}
if ( nick == null ) {
SQLManager.standardQuery( "UPDATE BungeePlayers SET nickname =NULL WHERE playername ='" + p + "'" );
} else {
SQLManager.standardQuery( "UPDATE BungeePlayers SET nickname ='" + nick + "' WHERE playername ='" + p + "'" );
}
} | 2 |
public Tile getTileByIntExp(int t_i) {
if (t_i < 0) return null;
else if (t_i < 4) return _t.get(new BoardCoordinate(3 + t_i, t_i, -3));
else if (t_i < 9) return _t.get(new BoardCoordinate(t_i - 2, t_i - 4, -2));
else if (t_i < 15) return _t.get(new BoardCoordinate(t_i - 8, t_i - 9, -1));
else if (t_i < 22) return _t.get(new BoardCoordinate(t_i - 15, t_i - 15, 0));
else if (t_i < 28) return _t.get(new BoardCoordinate(t_i - 22, t_i - 21, 1));
else if (t_i < 33) return _t.get(new BoardCoordinate(t_i - 28, t_i - 26, 2));
else if (t_i < 37) return _t.get(new BoardCoordinate(t_i - 33, t_i - 30, 3));
else return null;
} | 8 |
protected void execute() {} | 0 |
@Override
public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<Car> data = new ArrayList<Car>();
//filter
for(Car car : datasource) {
boolean match = true;
for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
String filterValue = filters.get(filterProperty);
String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
if(filterValue == null || fieldValue.startsWith(filterValue)) {
match = true;
}
else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
if(match) {
data.add(car);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new LazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
}
else {
return data;
}
} | 9 |
public static void main( String[] args ) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint( true );
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint( true );
canvas.setSize( 640, 480 );
// Add canvas to game window...
app.add( canvas );
app.pack();
app.setVisible( true );
// Create BackBuffer...
canvas.createBufferStrategy( 2 );
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage( 640, 480 );
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
Random rand = new Random();
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
while( true ) {
try {
// count Frames per second...
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
if( totalTime > 1000 ) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
// clear back buffer...
g2d = bi.createGraphics();
g2d.setColor( background );
g2d.fillRect( 0, 0, 639, 479 );
// draw some rectangles...
for( int i = 0; i < 20; ++i ) {
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
g2d.setColor( new Color(r,g,b) );
int x = rand.nextInt( 640/2 );
int y = rand.nextInt( 480/2 );
int w = rand.nextInt( 640/2 );
int h = rand.nextInt( 480/2 );
g2d.fillRect( x, y, w, h );
}
// display frames per second...
g2d.setFont( new Font( "Courier New", Font.PLAIN, 12 ) );
g2d.setColor( Color.GREEN );
g2d.drawString( String.format( "FPS: %s", fps ), 20, 20 );
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage( bi, 0, 0, null );
if( !buffer.contentsLost() )
buffer.show();
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if( graphics != null )
graphics.dispose();
if( g2d != null )
g2d.dispose();
}
}
} | 6 |
public boolean wordContainsLettersInOrder(final LetterGen letGen, final String word) {
final char[] a = word.toCharArray();
final char[] test = new char[a.length];
for(int i=0; i < a.length; i++){
test[i] = Character.toLowerCase(a[i]);
}
int i = 0;
char temp = Character.toLowerCase(letGen.getLetter1());
while(i < test.length){
if(temp==test[i]){
i++;
break;
}
i++;
}
temp = Character.toLowerCase(letGen.getLetter2());
while(i < test.length){
if(temp==test[i]){
i++;
break;
}
i++;
}
temp= Character.toLowerCase(letGen.getLetter3());
while(i < test.length){
if(temp==test[i]){
i++;
return true;
}
i++;
}
return false;
} | 7 |
private void resize() {
width = getSkinnable().getWidth();
height = getSkinnable().getHeight();
if (width > 0 && height > 0) {
if (aspectRatio * width > height) {
width = 1 / (aspectRatio / height);
} else if (1 / (aspectRatio / height) > width) {
height = aspectRatio * width;
}
font = Font.font("Open Sans", FontWeight.EXTRA_BOLD, FontPosture.REGULAR, 0.5 * height);
background.setPrefSize(width, height);
selectedText.setFont(font);
selectedText.setTextOrigin(VPos.CENTER);
selectedText.relocate(height * 0.3125, (height - selectedText.getLayoutBounds().getHeight()) * 0.5);
deselectedText.setFont(font);
deselectedText.setTextOrigin(VPos.CENTER);
deselectedText.relocate(width - height * 0.3125 - deselectedText.getLayoutBounds().getWidth(), (height - deselectedText.getLayoutBounds().getHeight()) * 0.5);
thumb.setPrefSize((height * 0.75), (height * 0.75));
thumb.setTranslateX(getSkinnable().isSelected() ? height * 1.125 : height * 0.125);
thumb.setTranslateY(height * 0.125);
moveToDeselected.setFromX(height * 1.125);
moveToDeselected.setToX(height * 0.125);
moveToSelected.setFromX(height * 0.125);
moveToSelected.setToX(height * 1.125);
}
} | 5 |
@Override
public void draw(Graphics g, Display d, int bottomPixelX, int bottomPixelY,
boolean drawHealth){
double percentMoved = count * 0.25;
// Tile coordinates of The Dude (x,y)
double x, y;
if(attacking == null) {
x = this.oldX + (this.x - this.oldX) * percentMoved;
y = this.oldY + (this.y - this.oldY) * percentMoved;
} else {
double dist = (count % 2 == 1) ? 0.2 : 0.1;
x = this.x + (facing == LEFT ? -1 : facing == RIGHT ? 1 : 0) * dist;
y = this.y + (facing == UP ? -1 : facing == DOWN ? 1 : 0) * dist;
}
// Pixel coordinates (on screen) of the Dude (i,j)
Point pt = d.tileToDisplayCoordinates(x, y);
int height = world.getTile(this.x, this.y).getHeight();
int oldHeight = world.getTile(oldX, oldY).getHeight();
pt.y -= TILE_HEIGHT * (oldHeight + (height - oldHeight) * percentMoved);
//pt.y -= TILE_HEIGHT / 2;
Image i = img[(facing + d.getRotation()) % 4];
// Draw image at (i,j)
int posX = pt.x - i.getWidth(null) / 2;
int posY = pt.y - i.getHeight(null);
g.drawImage(i, posX, posY, null);
if (drawHealth) {
int tall = 10;
int hHeight = 4;
int hWidth = 16;
g.setColor(Color.red);
g.fillRect(posX, posY - tall, hWidth, hHeight);
g.setColor(Color.green);
g.fillRect(posX, posY - tall, (int)(hWidth * currentHealth / (float)maxHealth), hHeight);
}
} | 7 |
private static String ConvierteTodo(String s, Tipo t) {
StringBuilder resultado = new StringBuilder();
int cuenta = s.length();
int cuentamillones = 0;
while (cuenta > 0) {
int inicio = (cuenta - 6 >= 0) ? (cuenta - 6) : 0;
int longitud = (6 > cuenta) ? cuenta : 6;
String stemp = s.substring(inicio, inicio + longitud);
int i6 = Integer.parseInt(stemp);
if (cuentamillones > 0 && i6 > 0) {
if (resultado.length() > 0) {
resultado.insert(0, " ");
}
if (i6 > 1) {
resultado.insert(0, nombreMillonesPlural[cuentamillones]);
} else {
resultado.insert(0, nombreMillonesSingular[cuentamillones]);
}
resultado.insert(0, " ");
}
resultado.insert(0, Convierte6(i6, t));
if (cuentamillones == 0) {
t = Tipo.DetMasculino;
}
cuentamillones++;
cuenta -= 6;
}
return resultado.toString();
} | 8 |
@Override
public int commit() {
int allNew = 0;
writeLock.lock();
try {
for (int i = 0; i < 256; ++i) {
allNew += files[i].getNewKeys();
files[i].commit();
}
} finally {
writeLock.unlock();
}
return allNew;
} | 1 |
public final boolean wasStarted() {
return myServerSocket != null && myThread != null;
} | 1 |
private static <T> T getSingleDefault(T[] params, T default_value) {
//assert params.length == 1;
T value = default_value;
if (params != null && params.length > 0)
value = params[0];
return value;
} | 2 |
public void Asearch(Point startPoint, Point goalPoint){
String start = startPoint.x + " " + startPoint.y + " " +
"0";
String goal = goalPoint.x + " " + goalPoint.y;
target = goal;
openset.add(start);
openset2.add(process(start));
parent.add(process(start));
while(!openset.isEmpty() && !closedset.contains(goal)){
current = retMin(openset);
openset.remove(current);
openset2.remove(process(current));
closedset.add(process(current));
neighbours = getNeighbours(current, goal);
for(int i = 0 ; i<neighbours.size();i++){
String s = process(neighbours.get(i));
if(!closedset.contains(s)){
if(!openset2.contains(s)){
openset.add(neighbours.get(i));
openset2.add(s);
parent.add(process(current)+ " " + s);
}
else{
int index= 0;
for(int j = 0;j<openset.size();j++){
if(openset.get(j).startsWith(s))
index = j;
}
if(Integer.parseInt(openset.get(index).split(" ")[2]) > Integer.parseInt(neighbours.get(i).split(" ")[2])){
openset.remove(index);
openset.add(neighbours.get(i));
parent.add(process(current)+ " " + s);
}
}
}
}
}
} | 8 |
public Link(long from_id, long to_id, int length, int lsiclass, int maxspeed) {
this.from_id = from_id;
this.to_id = to_id;
this.length = length;
int lsiSpeed = 0;
try {
lsiSpeed = LSISpeed.getSpeedById(lsiclass);
} catch (Exception e) {
System.out.println("LSIClass not in List: " + lsiclass);
System.exit(1);
}
if (maxspeed != 0 && maxspeed < lsiSpeed) {
this.speed = maxspeed;
} else {
this.speed = lsiSpeed;
}
this.time = (double) this.length / (double) (this.speed * 1000 / 60 / 60);
} | 3 |
protected static Ptg calcTrend( Ptg[] operands ) throws CalculationException
{
if( operands.length < 1 )
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
// KSC: THIS FUNCTION DOES NOT WORK AS EXPECTED: TODO: FIX!
if( true )
{
return new PtgErr( PtgErr.ERROR_VALUE );
}
// Ptg[] forecast = new Ptg[3];
Ptg[] forecast = new Ptg[2];
forecast[0] = operands[0];
if( operands.length > 1 )
{
forecast[1] = operands[1];
}
// TODO:
// else // If known_x's is omitted, it is assumed to be the array {1,2,3,...} that is the same size as known_y's.
Ptg[] newXs;
if( operands.length > 2 )
{
newXs = PtgCalculator.getAllComponents( operands[2] );
}
else
{
newXs = PtgCalculator.getAllComponents( operands[1] );
}
String retval = "";
for( Ptg newX : newXs )
{
//forecast[0] = newXs[i];
PtgNumber p = (PtgNumber) calcForecast( forecast );
double forcst = p.getVal();
retval += "{" + String.valueOf( forcst ) + "},";
}
// get rid of trailing comma
retval = retval.substring( 0, retval.length() - 1 );
PtgArray pa = new PtgArray();
pa.setVal( retval );
return pa;
} | 5 |
public void update()
{
renders.clear();
stringRenders.clear();
String playerId = session.getCurrentPlayerId();
if (startTimer > 0)
{
startTimer--;
if (startTimer > 60)
{
StringRender string = new StringRender("3", 315, 150, Color.BLACK);
stringRenders.add(string);
}
else if (startTimer > 30)
{
StringRender string = new StringRender("2", 315, 150, Color.BLACK);
stringRenders.add(string);
}
else
{
StringRender string = new StringRender("1", 315, 150, Color.BLACK);
stringRenders.add(string);
}
}
else
{
session.updatePlayer(playerId);
handleKeyInput();
session.decrementTimer();
}
currentScreen.setPlayerId(playerId);
currentScreen.update();
if (currentScreen.shouldSwitch())
{
switchScreen();
}
if (session.getTimer() <= 0)
{
Follower follower = session.getPlayerFollower(playerId);
if (follower != null && follower instanceof Mule)
{
session.setPlayerFollower(playerId, null);
}
startTimer = 90;
currentScreen = townScreen;
session.setTimer(timers[playerIds.indexOf(session.getCurrentPlayerId())]);
boolean newRound = session.advancePlayer();
if (newRound)
{
done = true;
}
}
renders.addAll(currentScreen.getRenders());
stringRenders.addAll(currentScreen.getStringRenders());
renders.add(session.getPlayerRender(playerId));
if (session.getPlayerFollowerRender(playerId) != null)
{
renders.add(session.getPlayerFollowerRender(playerId));
}
String id = session.getCurrentPlayerId();
//prompt.text = session.getPlayerName(id) + " please select a plot";
//stringRenders.add(prompt);
StringRender name = new StringRender(session.getPlayerName(id), 20, 380, Color.WHITE);
stringRenders.add(name);
StringRender money = new StringRender("$" + session.getPlayerMoney(id), 20, 400, Color.WHITE);
stringRenders.add(money);
StringRender ore = new StringRender("" + session.getPlayerOre(id), 140, 382, Color.WHITE);
stringRenders.add(ore);
StringRender food = new StringRender("" + session.getPlayerFood(id), 140, 402, Color.WHITE);
stringRenders.add(food);
StringRender crystite = new StringRender("" + session.getPlayerCrystite(id), 180, 382, Color.WHITE);
stringRenders.add(crystite);
StringRender energy = new StringRender("" + session.getPlayerEnergy(id), 180, 402, Color.WHITE);
stringRenders.add(energy);
StringRender timer = new StringRender("" + session.getTimer() / 100, 390, 390, Color.WHITE);
stringRenders.add(timer);
renders.add(infoBar);
} | 9 |
public ListNode detectCycle(ListNode head){
ListNode fast = head;
ListNode slow = head;
if(head == null || (head != null && head.next == null)){
return null;
}
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
break;
}
}
if(fast == null || fast.next == null){
return null;
}
fast = head;
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow;
/*
test color
*/
} | 9 |
@Override
public void awardPoints(int amount) {
points += amount;
} | 0 |
public void deleteRoad(Point p1,Point p2){
Circle tmp1 = new Circle(p1);
Circle tmp2 = new Circle(p2);
int r1=-2,r2=-2;
for (int i=0;i<pnts.length;i++)
if (tmp1.equals(pnts[i]))
r1 = i;
for (int i=0;i<pnts.length;i++)
if (tmp2.equals(pnts[i]))
r2 = i;
if (r1!=-2 && r2!=-2)
removeRoad(r1,r2);
for (Circle pnt1 : pnts) {
if (pnt1 != null) {
pnt1.print(g);
pnt1.print(g1);
}
}
} | 8 |
public void moveVolatile() {
int count = volatileFlowGrid.getCount();
double waterDensityFloor = waterDensityGrid.getWaterDensityFloor();
double carbondioxideDensityFloor = carbondioxideDensityGrid.getCarbondioxideDensityFloor();
double sodiumDensityFloor = sodiumDensityGrid.getSodiumrDensityFloor();
double potassiumDensityFloor = potassiumDensityGrid.getPotassiumDensityFloor();
for (int i = 0; i < count - 1; ++i) {
double mdot1 = volatileFlowGrid.getValue(i);
double mdot2 = volatileFlowGrid.getValue(i + 1);
double value1 = mdot1 * timeStep;
double value2 = mdot2 * timeStep;
double difference = value2 - value1;
double density = waterDensityGrid.getValue(i);
density += difference / waterDensityGrid.getArea(i);
if (density < waterDensityFloor) density = waterDensityFloor;
waterDensityGrid.setValue(i, density);
}
for (int i = 0; i < count - 1; ++i) {
double mdot1 = volatileFlowGrid.getValue(i);
double mdot2 = volatileFlowGrid.getValue(i + 1);
double value1 = mdot1 * timeStep;
double value2 = mdot2 * timeStep;
double difference = value2 - value1;
double density = carbondioxideDensityGrid.getValue(i);
density += difference / carbondioxideDensityGrid.getArea(i);
if (density < carbondioxideDensityFloor) density = carbondioxideDensityFloor;
carbondioxideDensityGrid.setValue(i, density);
}
for (int i = 0; i < count - 1; ++i) {
double mdot1 = volatileFlowGrid.getValue(i);
double mdot2 = volatileFlowGrid.getValue(i + 1);
double value1 = mdot1 * timeStep;
double value2 = mdot2 * timeStep;
double difference = value2 - value1;
double density = sodiumDensityGrid.getValue(i);
density += difference / sodiumDensityGrid.getArea(i);
if (density < sodiumDensityFloor) density = sodiumDensityFloor;
sodiumDensityGrid.setValue(i, density);
}
for (int i = 0; i < count - 1; ++i) {
double mdot1 = volatileFlowGrid.getValue(i);
double mdot2 = volatileFlowGrid.getValue(i + 1);
double value1 = mdot1 * timeStep;
double value2 = mdot2 * timeStep;
double difference = value2 - value1;
double density = potassiumDensityGrid.getValue(i);
density += difference / potassiumDensityGrid.getArea(i);
if (density < potassiumDensityFloor) density = potassiumDensityFloor;
potassiumDensityGrid.setValue(i, density);
}
} | 8 |
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
}
ListNode root = new ListNode(0);
ListNode cur = root;
while (l1 != null && l2 != null) {
if (l1.val > l2.val) {
cur.next = l2;
l2 = l2.next;
cur = cur.next;
} else {
cur.next = l1;
l1 = l1.next;
cur = cur.next;
}
}
if (l2 != null) {
cur.next = l2;
} else {
cur.next = l1;
}
return root.next;
} | 6 |
public static List<Pair<Task,Recurrence>> getAllTasksForUser(int userId,int categoryId,
CompletionType completionType,long startDateMilliseconds) {
String queryString = "SELECT * from public.\"Task\" INNER JOIN public.\"Recurrence\" ON public.\"Task\".\"ID\" = public.\"Recurrence\".\"TaskID\" WHERE \"UserID\" = ?";
if (completionType == CompletionType.COMPLETED) {
queryString += " AND ( \"CompletionGrade\"="+Task.COMPLETED_VALUE + " OR \"ID\" in (SELECT \"ParentID\" from public.\"Task\" WHERE \"CompletionGrade\"=" + Task.COMPLETED_VALUE + ") )";
} else if (completionType == CompletionType.UNFINISHED) {
queryString += " AND \"CompletionGrade\"<"+Task.COMPLETED_VALUE;
}
if(categoryId>0){
queryString += " AND \"CategoryID\"= ? ";
}
if(startDateMilliseconds > 0){
queryString += " AND \"StartDate\" <= ?";
}
try {
Connection connection = getConnection();
PreparedStatement prepStatement = connection
.prepareStatement(queryString);
int index = 1;
prepStatement.setInt(index++, userId);
if(categoryId>0){
prepStatement.setInt(index++, categoryId);
}
if(startDateMilliseconds > 0){
prepStatement.setDate(index++, new Date(startDateMilliseconds));
}
return executeTaskSelectQuery(prepStatement);
} catch (SQLException e) {
e.printStackTrace();
}
return new ArrayList<Pair<Task,Recurrence>>();
} | 7 |
public static String join(String separator, List<String> strings) {
StringBuilder appendable = new StringBuilder();
if (strings != null && strings.size() > 0) {
appendable.append(strings.get(0));
for (int i = 1; i < strings.size(); i++) {
appendable.append(separator).append(strings.get(i));
}
}
return appendable.toString();
} | 3 |
private String filter(String str)
{
StringBuffer sb = new StringBuffer();
int i=0;
while (str.charAt(i) == ' ') i++;
if (isTag(str.charAt(i))){
sb.append(str.charAt(i));
i++;
} else sb.append('+');
boolean zero = true;
while (i < str.length())
{
if (isDegit(str.charAt(i)))
{
if (!zero || str.charAt(i) != '0')
{
sb.append(str.charAt(i));
zero = false;
}
}
else
{
break;
}
i++;
}
return sb.toString();
} | 6 |
@Override
public void windowIconified(WindowEvent arg0)
{
} | 0 |
public void reparseChunkPrimitives(RandomAccessFile raff) throws IOException {
if ((this.primitives == null) || (this.primitives.size() == 0)) {
//nothing to do!
return;
}
Primitive p = primitives.get(0).getPrimitive();
long oldsize = this.getDataEndPosition() - this.getDataStartPosition();
long pos = 0;
try {
long newsize = p.writeValueToString().getBytes(textEncoding).length;
boolean needsPad = false;
if (this.getParentChunk() != null) {
if (this.getParentChunk().usesPadByte()) {
newsize = KlangUtil.adjustForPadByte(newsize);
needsPad = true;
}
}
long totnewsize = newsize + (this.getEndPosition() - this.getStartPosition()) - (this.getDataEndPosition() - this.getDataStartPosition());
if (newsize < oldsize) {
this.chunkIsAboutToChangeSize(totnewsize, raff);
KlangUtil.deleteFromFile(this.getParentFile().getFile(), this.getDataStartPosition(), this.getDataStartPosition() + (oldsize - newsize));
} else if (newsize > oldsize) {
this.chunkIsAboutToChangeSize(totnewsize, raff);
int amt = (int)(newsize - oldsize);
byte[] newbyte = new byte[amt];
KlangUtil.insertIntoFile(newbyte, this.getParentFile().getFile(), this.getDataStartPosition());
}
//write null to pad byte
if (needsPad) {
raff.seek(this.getDataStartPosition() + newsize - 1);
raff.write(0);
}
raff.seek(this.getDataStartPosition());
pos = raff.getFilePointer();
//write value back to the file
p.writeValueToFile(raff);
} catch (BadValueException err) {
err.printStackTrace();
throw new IOException(KlangConstants.ERROR_BAD_VALUE_EXCEPTION_WEIRDVALUE);
} catch (CharacterCodingException er) {
er.printStackTrace();
throw new IOException(KlangConstants.ERROR_BAD_VALUE_EXCEPTION_WEIRDVALUE);
}
//reparse the file
((EditableFileBase)this.getParentFile()).reparseFile(raff);
Chunk c = KlangFile.findDeepestChunkFor(this.getParentFile().getChunks(), pos);
c.chunkJustChanged(raff);
} | 9 |
public static String selectOne(final String title, final String[] optionNames, final String[] optionValues, final int defaultOption) {
if (optionNames.length != optionValues.length) {
throw new IllegalArgumentException("option names and values must have same length");
}
ConsoleMenu.println("Please chose " + title + " (default:" + defaultOption + ")");
for (int i = 0; i < optionNames.length; i++) {
ConsoleMenu.println(i + 1 + ") " + optionNames[i]);
}
int choice = 0;
do {
choice = ConsoleMenu.getInt("Your Choice 1-" + optionNames.length + ": ", defaultOption);
} while (choice <= 0 || choice > optionNames.length);
return optionValues[choice - 1];
} | 4 |
@Override
public void execute(VGDLSprite sprite1, VGDLSprite sprite2, Game game)
{
ArrayList<Integer> subtypes = game.getSubTypes(itype);
for (Integer i: subtypes) {
Iterator<VGDLSprite> spriteIt = game.getSpriteGroup(i);
if (spriteIt != null) while (spriteIt.hasNext()) {
try {
VGDLSprite s = spriteIt.next();
s.speed += value;
} catch (ClassCastException e) {
e.printStackTrace();
}
}
}
} | 4 |
public static int getJstatItem(List<JstatItem> jstatItemList, long timeStampMS) {
if (jstatItemList == null)
return -1;
int beforeIndex = 0;
int afterIndex = jstatItemList.size() - 1;
for (int i = 0; i < jstatItemList.size(); i++) {
JstatItem item = jstatItemList.get(i);
if (item.getTimeStampMS() == timeStampMS) {
return i;
} else if (timeStampMS > item.getTimeStampMS()) {
beforeIndex = i;
} else {
afterIndex = i;
}
}
return afterIndex;
} | 4 |
public HashMap<String, Boolean> convertStringToHash2(String args) {
HashMap<String, Boolean> pl = new HashMap<String, Boolean>();
if (args.equals(null) || args.length() < 1) return pl;
String[] sp = args.split(",");
try {
for (int i = 0; i < sp.length; i++) {
String a = String.valueOf(sp[i].split(":")[0]);
Boolean b = Boolean.valueOf(sp[i].split(":")[1]);
pl.put(a, b);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return pl;
} | 4 |
public int getTwoDegrees(String performer1, String performer2) throws SQLException {
LinkedList<String> select = new LinkedList<String>();
select.add("Performers");
LinkedList<String> from = new LinkedList<String>();
from.add("Videos");
LinkedList<Pair<String, String>> whereClauses = new LinkedList<Pair<String, String>>();
whereClauses.add(new Pair<String, String>("Performers LIKE ?", '%' + performer1 + '%'));
LinkedList<String> whereConjunctions = new LinkedList<String>();
ResultSet resultSet = executeDynamicQuery(select, from, whereClauses, whereConjunctions, null, null, 0);
HashSet<String> performersLeft = new HashSet<String>();
HashSet<String> seen = new HashSet<String>();
while (resultSet.next()) {
for (String performer : resultSet.getString(1).split(",")) {
if (performer.equals(performer2)) {
return 1;
}
if (performer.equals(performer1)) {
seen.add(performer);
}
performersLeft.add(performer);
}
}
HashSet<String> performersRight = new HashSet<String>();
whereClauses.set(0, new Pair<String, String>("Performers LIKE ?", '%' + performer2 + '%'));
resultSet = executeDynamicQuery(select, from, whereClauses, whereConjunctions, null, null, 0);
while (resultSet.next()) {
for (String performer : resultSet.getString(1).split(",")) {
if (performersLeft.contains(performer)) {
return 2;
}
if (performer.equals(performer2)) {
seen.add(performer);
}
performersRight.add(performer);
}
}
return 0;
} | 8 |
private Gridspot findAdj(Gridspot a, Gridspot from)
{
if ( getG(a.getXIndex()-1,a.getYIndex()).getColor() == a.getColor() && getG(a.getXIndex()-1,a.getYIndex()) != from )
{
return getG(a.getXIndex()-1,a.getYIndex());
}
else if ( getG(a.getXIndex()+1,a.getYIndex()).getColor() == a.getColor() && getG(a.getXIndex()+1,a.getYIndex()) != from )
{
return getG(a.getXIndex()+1,a.getYIndex());
}
else if ( getG(a.getXIndex(),a.getYIndex()-1).getColor() == a.getColor() && getG(a.getXIndex(),a.getYIndex()-1) != from )
{
return getG(a.getXIndex(),a.getYIndex()-1);
}
else if ( getG(a.getXIndex(),a.getYIndex()+1).getColor() == a.getColor() && getG(a.getXIndex(),a.getYIndex()+1) != from )
{
return getG(a.getXIndex(),a.getYIndex()+1);
}
return null;
} | 8 |
public void run() {
try {
boolean running = true;
while (running) {
try {
String line = null;
while ((line = _breader.readLine()) != null) {
try {
_bot.handleLine(line);
}
catch (Throwable t) {
// Stick the whole stack trace into a String so we can output it nicely.
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
StringTokenizer tokenizer = new StringTokenizer(sw.toString(), "\r\n");
synchronized (_bot) {
_bot.log("### Your implementation of PircBot is faulty and you have");
_bot.log("### allowed an uncaught Exception or Error to propagate in your");
_bot.log("### code. It may be possible for PircBot to continue operating");
_bot.log("### normally. Here is the stack trace that was produced: -");
_bot.log("### ");
while (tokenizer.hasMoreTokens()) {
_bot.log("### " + tokenizer.nextToken());
}
}
}
}
if (line == null) {
// The server must have disconnected us.
running = false;
}
}
catch (InterruptedIOException iioe) {
// This will happen if we haven't received anything from the server for a while.
// So we shall send it a ping to check that we are still connected.
this.sendRawLine("PING " + (System.currentTimeMillis() / 1000));
// Now we go back to listening for stuff from the server...
}
}
}
catch (Exception e) {
// Do nothing.
}
// If we reach this point, then we must have disconnected.
try {
_socket.close();
}
catch (Exception e) {
// Just assume the socket was already closed.
}
if (!_disposed) {
_bot.log("*** Disconnected.");
_isConnected = false;
_bot.onDisconnect();
}
} | 9 |
private static void traverseDOT(Node n, BufferedWriter out)
throws IOException {
if (n.parent != null) {
out.write(Integer.toString(n.nodeNum));
out.write(" -> ");
out.write(Integer.toString(n.parent.nodeNum) + ";");
}
for (Node child : n.children) {
traverseDOT(child, out);
}
} | 2 |
public ScoreDialog() {
this.setTitle("Score - Jeu du Taquin");
this.setSize(500,350);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setAlwaysOnTop(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setIconImage(new ImageIcon("essources/Icons/icon.png").getImage());
//la table
model=new ScoreModel();
table=new JTable(model);
pane.setViewportView(table);
//le bouton initialiser
if(model.getList().size()==0)
initialiser.setEnabled(false);
initialiser.addActionListener(new ActionsController(this));
//le bouton fermer
fermer.addActionListener(new ActionsController(this));
getRootPane().setDefaultButton(fermer);
//le boutonPane
boutonPane.setLayout(new FlowLayout(FlowLayout.RIGHT,10,5));
boutonPane.add(initialiser);
boutonPane.add(fermer);
//la paneau par d�faut
panel.setLayout(new BorderLayout());
panel.add(pane,BorderLayout.CENTER);
panel.add(boutonPane,BorderLayout.SOUTH);
this.getContentPane().add(panel);
centrerTable(table);
this.setVisible(true);
}//fin constructeur | 1 |
public void testToStandardSeconds_months() {
Period test = Period.months(1);
try {
test.toStandardSeconds();
fail();
} catch (UnsupportedOperationException ex) {}
test = Period.months(-1);
try {
test.toStandardSeconds();
fail();
} catch (UnsupportedOperationException ex) {}
test = Period.months(0);
assertEquals(0, test.toStandardSeconds().getSeconds());
} | 2 |
private void parseRangeNodes(Collection<ParameterNode> nodes) throws Exception {
param_ranges = new HashMap<>();
for (ParameterNode p : nodes) {
if (!p.isGroup()) {
continue;
}
ParameterGroup g = (ParameterGroup) p;
String value_name = g.getChild("valuename").getValueAsString();
float min = Float.parseFloat(g.getChild("min").getValueAsString());
float max = Float.parseFloat(g.getChild("max").getValueAsString());
int[] min_max = { (int) min, (int) max };
if (min_max[0] < 0) {
min_max[0] = 0;
}
if ((min_max[1] < 0) || (min_max[1] > 255)) {
min_max[1] = 255;
}
if (min_max[0] > min_max[1]) {
int temp = min_max[1];
min_max[1] = min_max[0];
min_max[0] = temp;
}
param_ranges.put(value_name, min_max);
}
} | 6 |
public ResourceManager(GraphicsConfiguration gc) {
this.gc = gc;
loadTileImages();
loadCreatureSprites();
loadPowerUpSprites();
} | 0 |
public Messenger connect(String host, int port) {
if (mMessenger == null) {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(host, port));
mMessenger = new Messenger(socket, mNotifyDisconnection);
mMessenger.start();
} catch (IOException e) {
try {
socket.close();
} catch (IOException exception) {
}
}
}
return mMessenger;
} | 3 |
public char readChar()
throws IOException {
mark(DEFAULT_READ_LIMIT);
int cfaslOpcode = read();
if (cfaslOpcode == CFASL_CHARACTER) {
return (char) read();
}
reset();
throw new RuntimeException("Expected a char but received opCode=" + cfaslOpcode);
} | 1 |
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvent e) {
e.getCause().printStackTrace();
e.getChannel().close();
} | 0 |
private void btnSaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnSaveKeyPressed
if (evt.getKeyCode() == 39) {
btnClear.grabFocus();
} else if (evt.getKeyCode() == 38) {
jPasswordField1.grabFocus();
}
if (evt.getKeyChar() == evt.VK_ENTER) {
btnSave.doClick();
}
}//GEN-LAST:event_btnSaveKeyPressed | 3 |
public void grabVideos(Collection<Integer, String> currentCollection) {
videos.clear();
playingVideoKeys.clear();
//Iterator through the HashMap
Iterator it = currentCollection.getMedia().entrySet().iterator();
while (it.hasNext()) {
//Contains the key and the filePath to the video
Map.Entry pairs = (Map.Entry)it.next();
//filePath
String fileName = (String)(pairs.getValue());
//Assures this file is a video
if(fileIsVideo(fileName)){
int temp = 0;
if(pairs.getKey() instanceof String){
System.out.println("astring");
temp = Integer.parseInt((String) pairs.getKey());
}else{
temp = (Integer)pairs.getKey();
System.out.println(pairs.getKey());
}
System.out.println("We have infact found a movie");
//pushes another video into the videos HashMap
videos.put(temp, new Movie(parent, fileName));
playingVideoKeys.add(temp);
stoppedVideoKeys.add(temp);
}
// avoids a ConcurrentModificationException
// also destroys our hashmap and causes everything to be null
// therefore fuck that shit. Spent too long trying to debug that bitch.
//
// ---> it.remove(); <---
}
} | 3 |
public void TouchedByItem(Item item) {
Item newItem = null;
if (item.editable) {
if (item.getClass().toString().endsWith("Sensor")) {
Item newTarget = (Item) target.clone();
if (item.getClass().toString().endsWith("ContactSensor")) {
newItem = new ContactSensor(0, 0, null, newTarget);
}
else if (item.getClass().toString().endsWith("RoomSensor")) {
newItem = new RoomSensor(0, 0, null, newTarget);
}
else if (item.getClass().toString().endsWith("DirectionalSensor")) {
newItem = new DirectionalSensor(0, 0, null, newTarget);
}
}
else {
newItem = (Item) target.clone();
}
Item carrier = item.carriedBy;
carrier.Drops();
int itemX = item.x;
int itemY = item.y;
level.items.removeElement(item);
newItem.x = itemX;
newItem.y = itemY;
newItem.room = carrier.room;
level.items.addElement(newItem);
carrier.PicksUp(newItem);
}
} | 5 |
public static LinkedList<BasicBlock> enumerateLeafFirst(Function F){
Hashtable<BasicBlock, HashSet<BasicBlock>> targets = enumerateTargets(F);
Hashtable<BasicBlock, HashSet<BasicBlock>> sources = enumerateSources(F);
LinkedList<BasicBlock> ordering = new LinkedList<BasicBlock>();
LinkedList<BasicBlock> queue = new LinkedList<BasicBlock>();
// This is supposed to enumerate basic blocks in F in leaf-first order
// This means that blocks with no targets are to be placed first, followed by their prececessors, etc.
// The entry block is to be placed last.
// Approach:
// Enumerate the targets
// Add all bbs with no targets to the end of the queue.
// While the queue is not empty:
// pop a BB off the queue
// add BB to the ordering
// put all of BB's sources at the end of the queue
// Invariant: all of BB's targets have been visited!
// IMPLEMENTATION:
// Add all bbs with no targets to the end of the queue.
for (BasicBlock bb : F.getBasicBlocks()){
if (targets.get(bb).isEmpty()){
queue.addLast(bb);
}
}
while (!queue.isEmpty()){
BasicBlock bb = queue.removeFirst();
// add BB to the ordering
ordering.addLast(bb);
// put all of BB's sources at the end of the queue
for (BasicBlock sbb : sources.get(bb)){
if ((!ordering.contains(sbb)) && (!queue.contains(sbb))){
queue.addLast(sbb);
}
}
// Invariant: all of BB's targets have been visited!
// The only exception is if the BB targets itself
for (BasicBlock tbb : targets.get(bb)){
if (tbb != bb){
// This is not possible for loops:
//assert ordering.contains(tbb);
}
}
}
// Make sure everything's been scheduled
assert ordering.size() == F.getBasicBlocks().size();
return ordering;
} | 8 |
static public void main(String[] args) {
if(args.length == 0) {
showHelp();
return;
}
boolean result = false;
try {
if(args[0].compareToIgnoreCase("-version") == 0)
result = showVersion();
else if(args.length == 2 && args[0].compareToIgnoreCase("-createSchema") == 0)
result = exportSchema(args);
else if(args.length == 2 && args[0].compareToIgnoreCase("-export") == 0)
result = exportData(args);
} catch (Exception e) {
result = false;
System.err.println(e.getMessage());
}
if(!result)
showHelp();
} | 8 |
public DIR turn(int d){
switch (this){
case N:
if(d==0)return DIR.O;
else return DIR.L;
case S:
if(d==0)return DIR.L;
else return DIR.O;
case L:
if(d==0)return DIR.N;
else return DIR.S;
case O:
if(d==0)return DIR.S;
else return DIR.N;
}
return null;
} | 8 |
public synchronized void run(){
try {
InputStream inputStream = cashSocket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
OutputStream outputStream = cashSocket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
String order = (String) objectInputStream.readObject();
switch (order) {
case "GET_DATE":
objectOutputStream.writeObject(new Date());
break;
default:
break;
}
cashSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 2 |
public void decryptFile(File read, File write) {
InputStream filein = null;
InputStream in = null;
OutputStream fileOut = null;
try {
cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(encryptKey));
filein = new FileInputStream(read);
fileOut = new FileOutputStream(write);
in = new CipherInputStream(filein, cipher);
int redbytes = 0;
byte[] buffer = new byte[1024];
while ((redbytes = in.read(buffer)) != -1) {
// System.out.println("bytes read after decryption :" + redbytes);
fileOut.write(buffer, 0, redbytes);
}
fileOut.flush();
// read.delete();
write.renameTo(read);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InvalidKeyException ik) {
ik.printStackTrace();
} finally {
try {
in.close();
filein.close();
fileOut.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/*try{
cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(encryptKey));
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer("");
byte[] utf8 = cipher.doFinal(dec);
new String(utf8, "UTF8");
}catch(InvalidKeyException ik){
ik.printStackTrace();
}catch(IllegalBlockSizeException ib){
ib.printStackTrace();
}catch(BadPaddingException bp){
bp.printStackTrace();
}catch(IOException io){
io.printStackTrace();
}*/
} | 5 |
@Override
public void setEmail(String email) {
super.setEmail(email);
} | 0 |
public void setMinute(int m){
//checks to see if the integer we passed through
//for minute is greater than or equal to zero but less
//than 60 and if the requirements are met the value stays the same
//but if they aren't, the value is set to zero.
minute = ((m >= 0 && m<60) ? m : 0);
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PresentationItem other = (PresentationItem) obj;
if (this.position != other.position) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (this.active != other.active) {
return false;
}
if (this.duration != other.duration) {
return false;
}
return true;
} | 6 |
private void insertionSort(double[] input, int lo, int hi) {
// Insertion sort
for (int i = lo + 1; i < hi; i++) {
for (int j = i; j > lo && Helper.less(input, j, j-1); j--) {
Helper.exch(input, j, j-1);
}
}
} | 3 |
public boolean verifyInventory(int productId, int inventoryChange) {
try {
Connection conn = openConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select inventory from "
+ DB_PRODUCT_TABLE + " where rowid = " + productId + ";");
inventoryChange += rs.getInt("inventory");
if(inventoryChange < 0)
{
rs.close();
conn.close();
return false;
}
rs.close();
conn.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} | 2 |
private void setTextQuest(TextQuest quest, ArrayList answerList) {
quest.setQuestAnswer(answerList);
} | 0 |
public static void Gaussian(DMatrix points , Matrix mu, Matrix sig, Matrix max){
Matrix temp;
temp = new Matrix(points.dimension(), 1);
for(int i = 0; i < points.samplenum(); i++){
boolean checker = true;
while(checker){
for(int j = 0; j < points.dimension();j++){
temp.set(j, 0, Math.random());
}
checker = Gauss(temp, mu, sig) < Math.random();
}
temp.timesEquals(500);
points.setMatrix(temp, i);
}
} | 3 |
public Year getYearStored()
{
return yearStored;
} | 0 |
protected TableModel createModel(Transition transition) {
final FSATransition t = (FSATransition) transition;
return new AbstractTableModel() {
public Object getValueAt(int row, int column) {
return s;
}
public void setValueAt(Object o, int r, int c) {
s = (String) o;
}
public boolean isCellEditable(int r, int c) {
return true;
}
public int getRowCount() {
return 1;
}
public int getColumnCount() {
return 1;
}
public String getColumnName(int c) {
return "Label";
}
String s = t.getLabel();
};
} | 0 |
public void Analyze( double[] data )
{
int length = data.length;
n_max = 0;
double[] cumSum = getCumulative_Sum(data);
//Seems OK
// for( int i = 0; i < cumSum.length; i++ )
// {
// System.out.println( cumSum[i]);
// }
//System.out.println("ind = " + ind + "\n");
x_density[0] = 0;
delta = 0;
for( int i = 1; i < n_density; i++ )
{
double yy = (double)i*1./((double)n_density); // a point in the Y axis
int ind = find_Index(cumSum, yy);
// Seems ok
//System.out.println( "yy = " + yy + " ind = " + ind + "\n" );
x_density[i] = find_interpol_x(cumSum, ind, yy);
//System.out.println( "x_density[" + i + "] = " + x_density[i] + " ind = " + ind + "\n" );
delta = delta + x_density[i] - x_density[i - 1]; // It should be always positive, therefore I didn't take the absalute value
//System.out.println("Delta i = " + (x_density[i] - x_density[i - 1]) );
}
delta = delta/(double)n_density;
//============ Clustering should start from here =============
clust_list = new ArrayList<ArrayList<Double>>();
ArrayList<Double> cur_clust = new ArrayList<>();
boolean keep_cluster = true;
for( int i = 1; i < n_density; i++ )
{
//System.out.println("i = " + i + " x_density = " + x_density[i]);
if( keep_cluster == false )
{
cur_clust.clear();
}
//System.out.println("delta = " + delta + "\n");
if( (x_density[i] - x_density[i-1]) < 0.2*delta )
{
cur_clust.add((Double) x_density[i]);
keep_cluster = true;
}
else
{
//System.out.println( "x[i] = " + x_density[i] + " x[i-1] = " + x_density[i-1] );
keep_cluster = false; // This means that this point is already far from the previous, and should be put in another cluster
//System.out.println("Size = " + cur_clust.size());
if( cur_clust.size() > 0 )
{
ArrayList<Double> tmp = new ArrayList<Double>(cur_clust);
//tmp = cur_clust;
System.out.println("adding to cluster cur_clust_size() = " + cur_clust.size());
clust_list.add( (ArrayList<Double>) tmp );
}
}
}
System.out.println("clust_lsut.size = " + clust_list.size() + "\n");
if( clust_list.size() > 0 )
{
for( int i = 0; i < clust_list.size(); i++ )
{
ArrayList<Double> new_clust = clust_list.get(i);
System.out.println("clust size = " + new_clust.size());
double summ = 0;
for( int j = 0; j < new_clust.size(); j++ )
{
//System.out.println("cur_clust.get = " + new_clust.get(j) );
summ = summ + new_clust.get(j);
}
summ = summ/((double)new_clust.size());
System.out.println( "Center of " + i + "-th peak is " + summ);
}
}
//int n_clusters =
} | 8 |
@Override
public void mark(int boardPosition, Cell[] cellBoard, int rows, int columns) throws IllegalMark {
//Find the row.
int boardPositionRow = boardPosition / columns;
//Find the column.
int boardPositionColumn = boardPosition % columns;
//Position to mark.
int positionToMark = boardPosition;
if (boardPositionColumn +2 < columns){
//Up side.
if(boardPositionRow -1 >= 0){
positionToMark = (boardPositionRow -1) * columns + boardPositionColumn +2;
mark(boardPosition,positionToMark, cellBoard);
}
if(boardPositionRow +1 < rows){
positionToMark = (boardPositionRow +1) * columns + boardPositionColumn +2;
mark(boardPosition,positionToMark, cellBoard);
}
}
} | 3 |
public double[][] getMatrix() {
return matrix;
} | 0 |
public void mutate(){
nets=SpeciationNeuralNetwork.sort(nets);
while(nets.size()<maxAllowed) // add individuals if there are too few
nets.add(nets.get(0).copyAndMutate());
while(nets.size()>maxAllowed&&nets.size()>0) // remove individuals if there are too many
nets.remove(nets.size()-1);
// mutate every one
Random random=new Random();
for(int i=1;i<nets.size();i++){
ArrayList<OutputNeuron> outputs=nets.get(i).findOutputs();
for(int f=0;f<outputs.size();f++){
try{
outputs.get(f).findDepth();
}
catch(Exception e){
new CMDTester(nets.get(i));
System.out.println("Encountered a stack overflow due to find depth. Setting this network's fitness low.");
nets.get(i).setFitness(Double.MIN_VALUE);
}
}
double mORc=random.nextDouble();
if(mORc>.8) // possibly make this global
crossover(nets.get(i),random);
else
nets.set(i,nets.get(i).copyAndMutate());
}
} | 7 |
@Override
public void pause() throws Exception {
try {
endpoint.pause();
} catch (Exception ex) {
log.error(sm.getString("http11protocol.endpoint.pauseerror"), ex);
throw ex;
}
canDestroy = false;
// Wait for a while until all the processors are idle
RequestInfo[] states = cHandler.global.getRequestProcessors();
int retry = 0;
boolean done = false;
while (!done && retry < org.apache.coyote.Constants.MAX_PAUSE_WAIT) {
retry++;
done = true;
for (int i = 0; i < states.length; i++) {
if (states[i].getStage() == org.apache.coyote.Constants.STAGE_SERVICE) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// NOTHING TO DO
}
done = false;
break;
}
}
if (done) {
canDestroy = true;
}
}
log.info(sm.getString("http11protocol.pause", getName()));
} | 7 |
* The statement before which to add stmt.
*/
public void addStmtBefore(final Stmt stmt, final Stmt before) {
if (Tree.DEBUG) {
System.out.println("insert: " + stmt + " before " + before);
}
final ListIterator iter = stmts.listIterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
if (s == before) {
iter.previous();
iter.add(stmt);
stmt.setParent(this);
return;
}
}
throw new RuntimeException(before + " not found");
} | 3 |
public void run() {
try {
this.ds = createDatagramSocket();
this.shutdown = false;
} catch (final SocketException se) {
return;
} catch (final UnknownHostException uhe) {
return;
}
final byte[] receiveData = new byte[SyslogConstants.SYSLOG_BUFFER_SIZE];
while(!this.shutdown) {
try {
final DatagramPacket dp = new DatagramPacket(receiveData,receiveData.length);
this.ds.receive(dp);
final SyslogServerEventIF event = createEvent(this.getConfig(),receiveData,dp.getLength(),dp.getAddress());
final List<SyslogServerEventHandlerIF> list = this.syslogServerConfig.getEventHandlers();
for(int i=0; i<list.size(); i++) {
final SyslogServerEventHandlerIF eventHandler = list.get(i);
eventHandler.event(this,event);
}
} catch (final IOException ioe) {
//
}
}
} | 5 |
public static String nullToString(Object inString) {
return (inString == null || "null".equalsIgnoreCase(inString.toString().trim())) ? "" : inString.toString();
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ValueObject other = (ValueObject) obj;
if (firstName == null) {
if (other.firstName != null) {
return false;
}
} else if (!firstName.equals(other.firstName)) {
return false;
}
if (lastName == null) {
if (other.lastName != null) {
return false;
}
} else if (!lastName.equals(other.lastName)) {
return false;
}
return true;
} | 9 |
public void setPizzaBuilder(PizzaBuilder pb) { pizzaBuilder = pb; } | 0 |
public Matrix transpose() {
Matrix mat = new Matrix(getHeight(), getWidth());
for (int x = 0; x < getWidth(); x++) {
for (int y = 0; y < getHeight(); y++) {
mat.data[y][x] = data[x][y];
}
}
return mat;
} | 2 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(About.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new About().setVisible(true);
}
});
} | 6 |
public Key delMax()
{
if (N == 0)
throw new RuntimeException("Priority Queue Underflow");
Key max = pq[1];
// exch(pq, 1, N);
pq[1] = pq[N]; // half exchange
pq[N--] = null;
sink(1);
// resize
if (N == pq.length / 4)
pq = resize(pq, pq.length / 2);
// keep track of min
if (N == 0)
minIndex = -1;
return max;
} | 3 |
public static boolean visibleArgumentP(Stella_Object self) {
if (self == null) {
return (true);
}
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(self), Logic.SGT_LOGIC_PROPOSITION)) {
{ Proposition self000 = ((Proposition)(self));
if ((self000.kind == Logic.KWD_ISA) &&
BooleanWrapper.coerceWrappedBooleanToBoolean(self000.variableTypeP())) {
if (((Justification)(Logic.$CURRENTJUSTIFICATION$.get())) != null) {
return (true);
}
if ((((Keyword)(Logic.$PRINTMODE$.get())) == Logic.KWD_REALISTIC) ||
(((Keyword)(Logic.$PRINTMODE$.get())) == Logic.KWD_ORIGINAL)) {
return (false);
}
else {
}
}
}
}
else {
}
return (true);
} | 7 |
public void paint(Graphics g){
g.drawImage(this.upgrade.getIcon(), 0, 0, null);
if(upgrade.isUsed()){
g.setColor(Color.red);
}else{
g.setColor(Color.black);
}
g.drawString(this.upgrade.getName(), 8, 18);
} | 1 |
public String getBallColor() {
return this.ballColor;
} | 0 |
private Object getLastElement(final Collection c) {
final Iterator itr = c.iterator();
Object lastElement = itr.next();
while (itr.hasNext()) {
lastElement = itr.next();
}
return lastElement;
} | 1 |
public void setTabu(S source, T target, int expireAfter) {
/* Pre-checks */
if (expireAfter < 0) {
return;
}
if (expireAfter > maxExpTime) {
throw new IllegalArgumentException("expiration time not in [0.." + maxExpTime + "]");
}
if ( source == null
|| target == null ) {
throw new IllegalArgumentException("cannot set null values as tabu");
}
/* Mark tabu */
HashSet<S> sources = tabu.get(target);
if (sources == null) {
// 'target' doesn't have a tabu set: make it
sources = new HashSet<S>();
tabu.put(target, sources);
}
else {
if (sources.contains(source)) {
// 'source' is already tabu for 'target': return
return;
}
}
// add 'source' as tabu for 'target'
sources.add(source);
/* Schedule expiration */
Integer expTime = (now + expireAfter + 1) % (maxExpTime + 1);
HashMap<T, HashSet<S>> expMap = expirations.get(expTime);
HashSet<S> expSet = expMap.get(target);
if (expSet == null) {
expSet = new HashSet<S>();
expMap.put(target, expSet);
}
expSet.add(source);
/* Add backpointer */
HashSet<Integer> expTimes = backptrs.get(target);
if (expTimes == null) {
expTimes = new HashSet<Integer>();
backptrs.put(target, expTimes);
}
expTimes.add(expTime);
} | 8 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.