method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
5eb09eb9-ef22-4cf3-bffa-a8ad67c95875 | 4 | @Override
public Iterator<NPuzzleMove> getMoves()
{
List<NPuzzleMove> moves = new ArrayList<NPuzzleMove>();
if (exists( openX + 1, openY ))
{
moves.add( new NPuzzleMove( openX + 1, openY ) );
}
if (exists( openX - 1, openY ))
{
moves.add( new NPuzzleMove( openX - 1, openY ) );
}
if (exists( openX, openY + 1 ))
{
moves.add( new NPuzzleMove( openX, openY + 1 ) );
}
if (exists( openX, openY - 1 ))
{
moves.add( new NPuzzleMove( openX, openY - 1 ) );
}
return moves.iterator();
} |
bc42b673-7a0f-4ed3-9df3-a673ca467f10 | 4 | public static void main(String[] args) throws Exception {
String fileName = "vectors.txt";
// Global.initializeDataBaseSimulator(fileName);
ArrayList<DataPoint> points = new ArrayList<DataPoint>();
ArrayList<Association> left = new ArrayList<Association>();
ArrayList<Association> associations = new ArrayList<Association>();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
int i = 1;
Global.DBSIMULATOR = new HashMap<String, DataPoint>();
while ((line = reader.readLine()) != null) {
System.out.println(i++);
DataPoint point = new DataPoint(line);
Cluster seed = new Cluster(point);
Core.clusterMap.put(seed.getID(),seed);
Global.DBSIMULATOR.put(point.getID(), point);
associations = Core.getIncrementalFRange(point, points);
ArrayList<Association> fClusterAssociations = Core
.getFRangeClusterAssociation(associations, point);
points.add(point);
TreeSet<Association> result = Core.mergeArrays(associations,
fClusterAssociations, left);
left = Core.incremantalMergeCluster(result);
left = Core.refineStepOne(left);
Core.refineClusters();
}
int counter=0;
for (String clusterId : clusterMap.keySet()) {
Cluster current = Core.clusterMap.get(clusterId);
System.out.println(current.getDataPointSet().size());
if(current.getDataPointSet().size()>1)
counter+=current.getDataPointSet().size();
for (String s : current.getDataPointSet()) {
// DataPoint sPoint = Global.DBSIMULATOR.get(s);
// System.out.println(sPoint.getID()+" || "+sPoint.getMin());
// for(String t : current.getDataPointSet())
// {
// if(!s.equals(t))
// {
// DataPoint tPoint = Global.DBSIMULATOR.get(t);
// System.out.println(sPoint.getID()+" || "+tPoint.getID()+" || "+sPoint.calculateDistance(tPoint));
// }
// }
System.out.println(Global.DBSIMULATOR.get(s).getUrl());
}
System.out.println("------------------------");
}
System.out.println(counter);
//
// ArrayList<Cluster> clusters = new ArrayList<Cluster>();
// for (String clusterId : clusterMap.keySet()){
// clusters.add(Core.clusterMap.get(clusterId));
// }
// Collections.sort(clusters,new Comparator<Cluster>() {
//
// @Override
// public int compare(Cluster o1, Cluster o2) {
// // TODO Auto-generated method stub
// return (o1.getSize()-o2.getSize());
// }
// });
// ArrayList<String> temp = new ArrayList<String>();
//
// for(Cluster c : clusters)
// temp.add(c.getID()+" || "+c.getSize());
// Collections.sort(temp);
// for(String s : temp)
// System.out.println(s);
// HashMap<Integer, String> patternsMap =
// Core.loadDataFromFile(fileName);
//
// Display display = new Display();
// JFreeChart chart1 = SWTBarChartDemo.createChart(clusters,
// patternsMap,
// 8000);
// Shell shell1 = new Shell(display);
// shell1.setSize(1000, 800);
// shell1.setLayout(new FillLayout());
// shell1.setText("Draw Mitosis Clusters");
// ChartComposite frame1 = new ChartComposite(shell1, SWT.NONE, chart1,
// true);
//
// frame1.pack();
// shell1.open();
// while (!shell1.isDisposed()) {
// if (!display.readAndDispatch())
// display.sleep();
// }
} |
b7dd9080-740c-470c-8bba-f50975779395 | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
b2db4e21-6f23-4aef-bd13-f49b1c05ac5d | 4 | public Ui(){
bg = new GreenfootImage (1000, 230);
cache = new GreenfootImage [6];
cache[0] = new GreenfootImage ("UI/general.png");
cache[1] = new GreenfootImage ("UI/buildTower.png");
cache[2] = new GreenfootImage ("UI/sendMobs.png");
cache[3] = new GreenfootImage ("UI/selectTower.png");
cache[4] = new GreenfootImage ("UI/selectTower.png");
cache[5] = new GreenfootImage ("UI/selectMob.png");
elements = new GreenfootImage [4];
elements[0] = new GreenfootImage ("UI/fire2.png");
elements[1] = new GreenfootImage ("UI/water2.png");
elements[2] = new GreenfootImage ("UI/air2.png");
elements[3] = new GreenfootImage ("UI/earth2.png");
generalFont = new Font ("Times New Roman", 1, 20);
name = new Font ("Vrinda" , 1, 35);
descFont = new Font ("Vrinda" , 0, 20);
statFont = new Font ("Vrinda" , 1, 25);
lifeColor = new Color (225, 0 , 0);
goldColor = new Color (225, 175, 55);
nameColor = new Color (20 , 210, 245);
descColor = new Color (255, 255, 255);
statColor = new Color (45 , 200, 45 );
debuffColor = new Color (255, 50, 0);
sellButton = new SellButton();
upgradeButton = new UpgradeButton();
buttons = new Button[2][12];
for (int i = 0; i < 12; i++){
buttons[0][i] = new SendCreeps(i+1);
}
for (int i = 0; i < 12; i++){
buttons[1][i] = new BuildTowers(i+1);
}
debuffs = new DebuffButton [5];
for (int i = 0; i < 5; i++){
debuffs[i] = new DebuffButton(i);
}
dumbDebuff = new DummyDebuff[5];
for (int i = 0; i < 5; i++){
dumbDebuff[i] = new DummyDebuff(i);
}
reload = new Reload();
waveElement = new Element[3];
waveElement[0] = new Element(); //current wave
waveElement[1] = new Element(); //next wave
waveElement[2] = new Element(); //mob element
id = 0;
lives = 20;
gold = 100;
level = 1;
wave = "Air";
next = "Water";
refresh();
} |
870533ec-18df-4f46-812e-ccafb135a09e | 2 | public static boolean CheckPlayers(int noplayers) {
if ((noplayers >= 2) && (noplayers <= 8))
return true;
else
return false;
} |
e12d3fb0-769e-48c0-98b1-f36cc0ead3f7 | 3 | public void render(Graphics2D g){
Graphics2D g2d = (Graphics2D)finalBoard.getGraphics();
g2d.drawImage(gameBoard, 0, 0, null);
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
Tile current = board[row][col];
if(current == null) continue;
current.render(g2d);
}
}
g.drawImage(finalBoard, x, y, null);
g2d.dispose();
g.setColor(Color.LIGHT_GRAY);
g.setFont(scoreFont);
g.drawString("" + score, 30, 40);
g.setColor(Color.red);
g.drawString("Best " + highScore, Game.WIDTH - DrawUtils.getMessageWidth("Best: " + highScore, scoreFont, g)-20, 40);
g.setColor(Color.black);
g.drawString("Time: "+ formattedTime, 30, 90);
g.setColor(Color.red);
g.drawString("Fastest: " + formatTime(fastestMS),
Game.WIDTH - DrawUtils.getMessageWidth("Fastest: " + formatTime(fastestMS), scoreFont, g)- 20, 90);
} |
953f7f9b-f42a-47f5-86ed-a7347ede2bb2 | 5 | public Msg recvpipe(Pipe[] pipe_) {
// Deallocate old content of the message.
Msg msg_;
// Round-robin over the pipes to get the next message.
while (active > 0) {
// Try to fetch new message. If we've already read part of the message
// subsequent part should be immediately available.
msg_ = pipes.get(current).read ();
boolean fetched = msg_ != null;
// Note that when message is not fetched, current pipe is deactivated
// and replaced by another active pipe. Thus we don't have to increase
// the 'current' pointer.
if (fetched) {
if (pipe_ != null)
pipe_[0] = pipes.get(current);
more = msg_.has_more();
if (!more)
current = (current + 1) % active;
return msg_;
}
// Check the atomicity of the message.
// If we've already received the first part of the message
// we should get the remaining parts without blocking.
assert (!more);
active--;
Utils.swap (pipes, current, active);
if (current == active)
current = 0;
}
// No message is available. Initialise the output parameter
// to be a 0-byte message.
ZError.errno(ZError.EAGAIN);
return null;
} |
fc6decb7-6da2-433f-aa35-baf3e3a0bee7 | 2 | public static Value changePlayer(Value player) {
Value state = empty;
switch(player) {
case x: {state = o; break;}
case o: {state = x; break;}
}
return state;
} |
2a32406d-b40d-4d72-b9f2-f018c80a4129 | 8 | public void eventPosted(TimeflecksEvent t)
{
if (t.equals(TimeflecksEvent.GENERAL_REFRESH))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to general refresh event.");
this.refresh();
}
else if (t.equals(TimeflecksEvent.EVERYTHING_NEEDS_REFRESH))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to everything needs refresh event.");
this.revalidate();
this.repaint();
this.refresh();
}
else if (t.equals(TimeflecksEvent.DAY_WEEK_VIEW_SWITCHED))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to day week view switched event.");
this.refreshPanels();
}
else if (t.equals(TimeflecksEvent.DATE_LEFT_ONE_BUTTON))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to date left button event.");
this.bumpDateLeft(1);
}
else if (t.equals(TimeflecksEvent.DATE_TODAY_BUTTON))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to date today button event.");
this.bumpDateToday();
}
else if (t.equals(TimeflecksEvent.DATE_RIGHT_ONE_BUTTON))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to date right button event.");
this.bumpDateRight(1);
}
else if (t.equals(TimeflecksEvent.DATE_LEFT_SEVEN_BUTTON))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to date week left button event.");
this.bumpDateLeft(7);
}
else if (t.equals(TimeflecksEvent.DATE_RIGHT_SEVEN_BUTTON))
{
GlobalLogger.getLogger().logp(Level.INFO, "MainWindow",
"eventPosted",
"MainWindow responding to date week right button event.");
this.bumpDateRight(7);
}
else
{
// We want to silently ignore all events that we aren't prepared to
// handle.
// GlobalLogger
// .getLogger()
// .logp(Level.WARNING, "MainWindow", "eventPosted",
// "MainWindow responding to unknown event. No action will be taken");
}
} |
60d99c2a-871f-421b-9236-2385bd48e6dd | 2 | private double getFreeSpaceInOutsideVehicleAcceptor(VehicleAcceptor va) {
try {
//if va is null, return 0
if (va == null) {
return 0;
}
List<Vehicle> cars = va.getCars();
//the va has cars, return the last backPos
return cars.get(cars.size()).getBackPosition();
} catch(IndexOutOfBoundsException e) {
//no cars were found, recursively call the function with the next road segment
return va.getLength() + getFreeSpaceInOutsideVehicleAcceptor(va.getNextSeg(this));
}
} |
3ec24ed3-76f6-4afc-81b8-7ebe54e0f927 | 9 | public static void step(Page page, int step) {
StyledDocument doc = page.getStyledDocument();
AbstractDocument.BranchElement section = (AbstractDocument.BranchElement) doc.getDefaultRootElement();
if (step < 0 && isSmallest(section))
return;
Enumeration enum1 = section.children();
AbstractDocument.BranchElement paragraph = null;
AbstractDocument.LeafElement content = null;
Enumeration enum2 = null, enum3 = null;
Object name = null, attr = null;
int fontSize = 0;
boolean fontSizeSet = false;
MutableAttributeSet mas = null;
while (enum1.hasMoreElements()) {
paragraph = (AbstractDocument.BranchElement) enum1.nextElement();
enum2 = paragraph.children();
while (enum2.hasMoreElements()) {
content = (AbstractDocument.LeafElement) enum2.nextElement();
enum3 = content.getAttributeNames();
mas = new SimpleAttributeSet(content.getAttributes());
fontSizeSet = false;
while (enum3.hasMoreElements()) {
name = enum3.nextElement();
attr = content.getAttribute(name);
if (name.toString().equals(StyleConstants.FontSize.toString())) {
fontSize = ((Integer) attr).intValue() + step;
if (fontSize < 8)
fontSize = 8;
StyleConstants.setFontSize(mas, fontSize);
doc.setCharacterAttributes(content.getStartOffset(), content.getEndOffset()
- content.getStartOffset(), mas, false);
fontSizeSet = true;
}
}
/* if font size of this content element is not set, it takes the default value 12. */
if (!fontSizeSet) {
fontSize = 12 + step;
if (fontSize < 8)
fontSize = 8;
StyleConstants.setFontSize(mas, fontSize);
doc.setCharacterAttributes(content.getStartOffset(), content.getEndOffset()
- content.getStartOffset(), mas, false);
}
}
}
page.setFontIncrement(page.getFontIncrement() + step);
} |
200e7b76-80bd-4a58-86e8-43695c4ede94 | 6 | public void enableBillTypes()
{
if (isFirstBill){
isFirstBill=false;
reset();
ack();
d.readToPort();
try {Thread.sleep(900L);} catch (InterruptedException e) {e.printStackTrace();}
d.writeToPort("02030C34FFFFFF000000B5C1");
try {
TimeUnit.MILLISECONDS.sleep(30);
}
catch (Exception e){
}
d.readToPort();
d.readToPort();
poll(true);
d.readToPort();
ack();
d.readToPort();
}
for (int i=1;i<30000;i++)
{
try {Thread.sleep(100L);} catch (InterruptedException e) {e.printStackTrace();}
d.writeToPort("02030600C282");
d.writeToPort("02030633DA81");
d.readToPort();
if (!isBillGetMoney)
{
i=30000;
}
}
} |
6afe1f7a-deea-4f6e-bed3-8d10730e4e71 | 1 | public float getU() {
if(animation != null) {
return animation.getU();
}
return tex.getU();
} |
65e117dc-39f4-45f0-84dc-aeb287e342b6 | 7 | private void moveNewZipFiles(String zipPath) {
File[] list = listFilesOrError(new File(zipPath));
for (final File dFile : list) {
if (dFile.isDirectory() && this.pluginExists(dFile.getName())) {
// Current dir
final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName());
// List of existing files in the new dir
final File[] dList = listFilesOrError(dFile);
// List of existing files in the current dir
final File[] oList = listFilesOrError(oFile);
for (File cFile : dList) {
// Loop through all the files in the new dir
boolean found = false;
for (final File xFile : oList) {
// Loop through all the contents in the current dir to see if it exists
if (xFile.getName().equals(cFile.getName())) {
found = true;
break;
}
}
if (!found) {
// Move the new file into the current dir
File output = new File(oFile, cFile.getName());
this.fileIOOrError(output, cFile.renameTo(output), true);
} else {
// This file already exists, so we don't need it anymore.
this.fileIOOrError(cFile, cFile.delete(), false);
}
}
}
this.fileIOOrError(dFile, dFile.delete(), false);
}
File zip = new File(zipPath);
this.fileIOOrError(zip, zip.delete(), false);
} |
f38847c8-7cd0-492e-a23e-dc0860761311 | 2 | public void setDAO(String daoLine) {
if (daoLine.equals("Mock")) {
dao = new MockDAO();
}
else if (daoLine.equals("MySQL")) {
dao = new MySQLDAO();
}
} |
12619145-b9e7-4dee-8844-b73d8c0fc900 | 4 | public int get(final int index) {
final int i0 = index >>> 22;
int[][] map1;
if (i0 != 0) {
if (map == null)
return NOT_FOUND;
map1 = map[i0];
if (map1 == null)
return NOT_FOUND;
} else
map1 = map10;
int[] map2 = map1[(index >>> 11) & 0x7ff];
if (map2 == null)
return NOT_FOUND;
return map2[index & 0x7ff];
} |
1a570b8b-d27e-49a1-80b3-fc7a2b72b118 | 1 | public void stop() {
if (!stop) {
stop = true;
}
} |
8696f1d5-2f8c-4cee-bae4-e8561d643802 | 8 | public void transferKE(float amount) {
if (iAtom <= 0)
return;
float k0 = getKin();
if (k0 < ZERO)
return;
synchronized (forceCalculator) {
for (int i = 0; i < iAtom; i++) {
if (!atom[i].isMovable())
continue;
k0 = EV_CONVERTER * atom[i].mass * (atom[i].vx * atom[i].vx + atom[i].vy * atom[i].vy + atom[i].vz * atom[i].vz);
if (k0 <= ZERO)
k0 = ZERO;
k0 = (k0 + amount) / k0;
if (k0 <= ZERO)
k0 = ZERO;
k0 = (float) Math.sqrt(k0);
if (Float.isNaN(k0) || Float.isInfinite(k0))
continue; // any abnormal number must be skipped
atom[i].vx *= k0;
atom[i].vy *= k0;
atom[i].vz *= k0;
}
}
} |
b11b5eb1-b8ee-4a78-99f4-9408e1ac1433 | 3 | public static long transfer( InputStream in,
OutputStream out,
long maxReadLength,
int bufferSize )
throws IllegalArgumentException,
IOException {
byte[] buffer = new byte[ bufferSize ];
int len;
long totalLength = 0;
long bytesLeft = maxReadLength; // Math.max( maxReadLength, bufferSize );
while( (maxReadLength == -1 || totalLength < maxReadLength)
//&& (len = in.read(buffer,0,(int)bytesLeft)) > 0 ) {
&& (len = in.read(buffer,0,(int)Math.max( maxReadLength, bufferSize ))) != -1 ) {
//for( int i = 0; i < len; i++ )
// System.out.print( "X" + (char)buffer[i] );
out.write( buffer, 0, len );
out.flush();
totalLength += len;
bytesLeft -= len;
}
return totalLength;
} |
8d8dea99-8be4-4bcb-be64-9ca37715efb6 | 7 | public void paintComponent(Graphics g){
super.paintComponent(g);
BoardObject[][] tiles = board.getBoardTiles();
if (tiles == null) return; // before board is made ...
// draws stuff
//Draw each tile on the board.
for(int y=0; y<Board.SIZE; y++){
for(int x=0; x<Board.SIZE; x++){
if(tiles[y][x] != null){
g.setColor(tiles[y][x].getColour());//Each object knows its own colour
if(tiles[y][x] instanceof Player){//Players are circles
g.fillOval(x*Board.SQUARE_SIZE, y*Board.SQUARE_SIZE, Board.SQUARE_SIZE, Board.SQUARE_SIZE);
}else{//Everything else is a square
g.fillRect(x*Board.SQUARE_SIZE, y*Board.SQUARE_SIZE, Board.SQUARE_SIZE, Board.SQUARE_SIZE);
}
}
//Draw the black outline for each square.
g.setColor(Color.BLACK);
g.drawRect(x*Board.SQUARE_SIZE, y*Board.SQUARE_SIZE, Board.SQUARE_SIZE, Board.SQUARE_SIZE);
}
}
//If we are dragging a player token, draw the current dragging position.
if(bml.dragging != null){
Point p = bml.dragging.getDraggingPosition();
g.setColor(bml.dragging.getColour());
g.fillOval(p.getX()-(Board.SQUARE_SIZE/2), p.getY()-(Board.SQUARE_SIZE/2),
Board.SQUARE_SIZE, Board.SQUARE_SIZE);
}
//Now we draw the labels on each room.
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(new Color(7,18,58));
for(Room r: board.rooms){
//Get each room's central point.
int x = (int)(r.getCentralPoint()[0] * Board.SQUARE_SIZE), y=(int)(r.getCentralPoint()[1] * Board.SQUARE_SIZE);
String label = r.getName().name();
//Offset based on the string's width and height.
x -= g.getFontMetrics().stringWidth(label)/2;
y += Board.SQUARE_SIZE/4;
g.drawString(label, x, y);//Draw it.
}
} |
489aca43-ad91-48bc-9126-bf1ae8d2d264 | 2 | protected void attemptToGrowFruit()
{
System.out.println(getName() + " is attempting to grow some fruit.");
// for each unit of growth that does not contain a fruit
for(int i = getFruits().size(); i < getSize(); i++)
{
if(Math.random() < 0.01)
{
getFruits().add(getFruit());
System.out.println(getName() + " has grown a fruit.");
}
}
System.out.println("Finished growing fruit.\n");
} |
ab61e115-ca09-4074-834c-f626fa37d783 | 6 | private static String encrypt(final int key, final String text) {
String encryptedText = "";
logger.log(Level.INFO, "Plain text: {0}", text);
for (int level = 0; level < key; level++) {
for (int n = 0; n < text.length() / (2 * key - 2) + 1; n++) {
if (level != 0 && level != key - 1 && 2 * n * (key - 1) - level > -1) {
encryptedText += text.charAt(2 * n * (key - 1) - level);
}
if (2 * n * (key - 1) + level < text.length()) {
encryptedText += text.charAt(2 * n * (key - 1) + level);
}
}
}
logger.log(Level.INFO, "Encrypted text: {0}", encryptedText);
return encryptedText;
} |
11861163-0392-468b-a86c-1bfec81051a3 | 6 | @Override
public void mousePressed(MouseEvent e) {
if (calculated) {
return;
}
Tile targetTile = getTileAt(e.getX(), e.getY());
int button = e.getButton();
if (targetTile != null) {
targetTile.handleClick(button);
if (targetTile.getState().equals(State.START)) {
if (start != null) {
start.reset();
}
start = targetTile;
}
if (targetTile.getState().equals(State.END)) {
if (end != null) {
end.reset();
}
end = targetTile;
}
}
} |
ec8d4b4e-6ad7-46a4-b74b-d4a1317f319a | 6 | public final void levelDone() {
if (!inGameState("InGame") || inGameState("LevelDone")
|| inGameState("LifeLost") || inGameState("GameOver") ) return;
// System.err.println(
// "Warning: levelDone() called from other state than InGame." );
//}
clearKey(key_continuegame);
removeGameState("StartLevel");
removeGameState("StartGame");
seqtimer=0;
if (leveldone_ticks > 0) {
if (leveldone_ingame) addGameState("LevelDone");
else setGameState("LevelDone");
new JGTimer(leveldone_ticks,true,"LevelDone") {public void alarm() {
levelDoneToStartLevel();
} };
} else {
levelDoneToStartLevel();
}
} |
e1f2e3cf-806b-4883-8ab3-938a2808d854 | 5 | public void initializeBoard() {
gameArray = new PlayableSquare[60];
for (int i = 0; i < 60; i++) { gameArray[i] = new PlayableSquare(Integer.toString(i)); }
redHomeArray = new PlayableSquare[6];
greenHomeArray = new PlayableSquare[6];
blueHomeArray = new PlayableSquare[6];
yellowHomeArray = new PlayableSquare[6];
greenStart = new PlayableSquare("gstart");
redStart = new PlayableSquare("rstart");
blueStart = new PlayableSquare("bstart");
yellowStart = new PlayableSquare("ystart");
startArrays = new PlayableSquare[]{greenStart, redStart, blueStart, yellowStart};
greenStart.setToStart("green");
redStart.setToStart("red");
blueStart.setToStart("blue");
yellowStart.setToStart("yellow");
greenStartPosition = 4;
redStartPosition = 19;
blueStartPosition = 34;
yellowStartPosition = 49;
greenHomePosition = 2;
redHomePosition = 17;
blueHomePosition = 32;
yellowHomePosition = 47;
greenSafetyIndex = 60;
redSafetyIndex = 66;
blueSafetyIndex = 72;
yellowSafetyIndex = 78;
for (int i = 0; i < 6; i++) {
greenHomeArray[i] = new PlayableSquare(Integer.toString(i + greenSafetyIndex));
greenHomeArray[i].setToSafetyZone("green");
redHomeArray[i] = new PlayableSquare(Integer.toString(i + redSafetyIndex));
redHomeArray[i].setToSafetyZone("red");
blueHomeArray[i] = new PlayableSquare(Integer.toString(i + blueSafetyIndex));
blueHomeArray[i].setToSafetyZone("blue");
yellowHomeArray[i] = new PlayableSquare(Integer.toString(i + yellowSafetyIndex));
yellowHomeArray[i].setToSafetyZone("yellow");
}
greenHomeArray[5].setToHome("green");
redHomeArray[5].setToHome("red");
blueHomeArray[5].setToHome("blue");
yellowHomeArray[5].setToHome("yellow");
setToSlider(gameArray, "green", 4, 1);
setToSlider(gameArray, "green", 5, 9);
setToSlider(gameArray, "red", 4, 16);
setToSlider(gameArray, "red", 5, 24);
setToSlider(gameArray, "blue", 4, 31);
setToSlider(gameArray, "blue", 5, 39);
setToSlider(gameArray, "yellow", 4, 46);
setToSlider(gameArray, "yellow", 5, 54);
greenPawn = new Pawn[4];
redPawn = new Pawn[4];
bluePawn = new Pawn[4];
yellowPawn = new Pawn[4];
for (int i = 0; i < 4; i++) {
greenPawn[i] = new Pawn("green", "gstart", i, -1, startArrays[0], startArrays, greenHomeArray);
redPawn[i] = new Pawn("red", "rstart", i, -1, startArrays[1], startArrays, redHomeArray);
bluePawn[i] = new Pawn("blue", "bstart", i, -1, startArrays[2], startArrays, blueHomeArray);
yellowPawn[i] = new Pawn("yellow", "ystart", i, -1, startArrays[3], startArrays, yellowHomeArray);
}
for (PlayableSquare square : startArrays) {
square.setNumOccupants(4);
square.setOccupied(true);
}
for (int i = 0; i < 4; i++) {
greenStart.putPiece(greenPawn[i]);
redStart.putPiece(redPawn[i]);
blueStart.putPiece(bluePawn[i]);
yellowStart.putPiece(yellowPawn[i]);
}
} |
b17c0f7d-9da4-4f72-b6c3-c5b2411c036f | 0 | public SetUndoAmountAction () {
super("Set Undo Amount", null);
//this.environment = environment;
} |
e8dd209d-6ee1-4416-af6f-df7b561cfef4 | 9 | private List<Mapper> estimateMappers() {
List<Mapper> newMapperList = new ArrayList<Mapper>();
if(isSplitSizeChanged || isMapperConfChanged) {
MapperEstimator mapperEstimator = new MapperEstimator(finishedConf, newConf);
//split size is changed
if(isSplitSizeChanged) {
//List<Long> splitsSizeList = InputSplitCalculator.getSplitsLength(newConf);
List<Long> splitsSizeList = splitMap.get((int)(newConf.getSplitSize() / 1024 /1024));
Map<Integer, Mapper> cacheNewMapper = new HashMap<Integer, Mapper>();
for(int i = 0; i < splitsSizeList.size(); i++) {
Long cSplitSize = splitsSizeList.get(i);
int cSplitMB = (int) (cSplitSize / (1024 * 1024)) ; //HDFS_BYTES_READ
if(!cacheNewMapper.containsKey(cSplitMB)) {
Mapper newMapper = mapperEstimator.estimateNewMapper(job.getMapperList(), cSplitSize);
newMapperList.add(newMapper);
cacheNewMapper.put(cSplitMB, newMapper);
}
else
newMapperList.add(cacheNewMapper.get(cSplitMB)); //Note: multiple references of newMapper
}
}
//do not need to consider split size
else if(isMapperConfChanged) {
for(int i = 0; i < job.getMapperList().size(); i++) {
Mapper newMapper = mapperEstimator.estimateNewMapper(job.getMapperList().get(i));
newMapperList.add(newMapper);
}
}
//none mapper configuration changed
else
for(Mapper mapper : job.getMapperList())
newMapperList.add(mapper);
}
//none mapper configuration changed
else {
for(Mapper mapper : job.getMapperList())
newMapperList.add(mapper);
}
return newMapperList;
} |
91fe4007-957d-401a-b761-35db250800b8 | 0 | @Override
public void onReceived(long delta, long bytes) {
} |
57db888b-e2d8-4151-9d44-fe0d401d54d5 | 4 | public static String doRecognition(int[] positions){
String bestMatchString = null;
float bestMatchPercentage = 0;
for(Gesture item : gestureList){
float variance = 0;
for(int i=0; i<4; i++){
variance += (float) Math.abs( item.getPosition(i) - positions[i]/(SignalProcessor.getMaxSignalValue()*0.01) );
System.out.print(Math.abs( item.getPosition(i) - positions[i]/(SignalProcessor.getMaxSignalValue()*0.01) )+" - ");
}
float matchPercent = 100 - variance*0.25f;
System.out.println(item.getName()+": "+matchPercent);
if(matchPercent > bestMatchPercentage && matchPercent > minimumMatchPercentage){
bestMatchPercentage = matchPercent;
bestMatchString = item.getName();
}
}
return bestMatchString;
} |
56493e03-8268-4cbf-a9f4-6496ea6db24c | 0 | public BlockListener(LogOre plugin) {
this.plugin = plugin;
} |
023feadc-e3b9-439a-8d21-f8d59733d667 | 9 | @Override
public void run() {
// TODO Auto-generated method stub
Random rand = new Random(50);
Random ano_rand = new Random(20);
int rand_num;
int wiget_send = 0;
int money_send = 0;
while (true) {
// get a random number between 0-2
rand_num = rand.nextInt(proc_num);
// for send the marker
// process 1 init marker at a random time
if ((id == 1) && (Main.snapshot_num > 0)
&& (ano_rand.nextInt(100) < 10)
&& (Main.snapshot_on == false)) {
Main.snapshot_on = true;
Marker m = new Marker(Main.sequence_num, 1, 1);
try {
os.writeObject((Message) m);
System.out.println(String.format(
"P%d is sending marker to P%d", 1, 1));
os.flush();
} catch (IOException e) {
System.out.println(e);
}
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
}
}
// send the regular message
if ((rand_num + 1) != id) {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
// Handle exception
}
wiget_send = 10 / (id + 1);
money_send = 5 / (id + 1);
synchronized (this) {
Main.p[id].widget -= wiget_send;
Main.p[id].money -= money_send;
sendMessage(wiget_send, money_send, id, rand_num + 1);
}
}
}
} |
3e726240-c7df-466e-92bf-7b30ee74e2d7 | 8 | @EventHandler
public void onWeatherChange(WeatherChangeEvent event) {
notifyAboutUpdate();
Random r = new Random();
Boolean voteInProgress = false;
//Check if the world is enabled
if (getFileConfig().getStringList("Worlds").contains(event.getWorld().getName())) {
//Check if it's going to rain
if (event.toWeatherState()) {
if (getFileConfig().getInt("RainTime.longest") == 0) {
event.setCancelled(true);
LogDebug("Rain event cancelled.");
return;
}
//Check if there is a vote in progress in that world. Abort if so.
for (VoteManager vote : voteManagers) {
if (vote.getVoteWorld().getName().equals(event.getWorld().getName())) {
voteInProgress = true;
continue;
}
}
LogDebug("Is vote in progress: " + voteInProgress + " " + event.getWorld().getName());
if (voteInProgress) {
return;
}
if (r.nextInt(100) >= getFileConfig().getInt("FailChance")) {
VoteManager vm = new VoteManager(this, event.getWorld(), new WeatherInformation(event.getWorld(), event.toWeatherState(), event.toWeatherState(), event.getWorld().isThundering(), event.getWorld().getWeatherDuration(), event.getWorld().getThunderDuration()));
vm.startVote(getFileConfig().getInt("TimeToVote"));
voteManagers.add(vm);
event.setCancelled(true);
} else {
messageAllPlayers(locale.getMessage("storm_too_strong"), event.getWorld());
}
} else {
if (getFileConfig().getInt("SunTime.longest") == 0) {
event.setCancelled(true);
LogDebug("Sun event cancelled.");
return;
}
Integer duration;
duration = r.nextInt((getFileConfig().getInt("SunTime.longest") - getFileConfig().getInt("SunTime.shortest")) + 1) + getFileConfig().getInt("SunTime.shortest");
event.getWorld().setWeatherDuration(duration * 20);
LogDebug("The sun will shine in " + event.getWorld().getName() + " for " + duration + " seconds.");
}
}
} |
2093390b-6d1b-4d6e-ad0c-89b8a0731892 | 9 | void applyForce()
{
//PhBody.applyForceToCenter(new Vec2(0,-3));
setForcesFromBodiesAffect();
if (BackJoint == null) return;
//parent.text(f.length(),100,100);
float CurrentJointLength = BackJoint.getLength();
LWormPart wp = (LWormPart) BackJoint.getBodyB().getUserData();
Vec2 f = new Vec2();
BackJoint.getReactionForce(Luc.GTimeStep, f);
if (f.length()>2.f) {
Luc.box2d.world.destroyJoint(BackJoint);
DistanceJoint current = BackJoint;
LWormPart wpNext = wp;
while(current != null){
wpNext = (LWormPart) current.getBodyB().getUserData();
current = wpNext.BackJoint;
}
Head = wpNext.Head;
wpNext.Head = wp;
return;}
if(stable && !wp.stable){
if(Luc.box2d.scalarWorldToPixels(CurrentJointLength) >= getSize().x * 2.3)
BackJoint.setLength(CurrentJointLength - 0.1f);
else {
wp.setStable();
}
}
if(!stable && wp.stable){
if(Luc.box2d.scalarWorldToPixels(CurrentJointLength) <= getSize().x * 2.9)
BackJoint.setLength(CurrentJointLength + 0.1f);
else {
setStable();
wp.setUnStable();
}
}
} |
2526dc5b-f757-4beb-b12d-03fcdc56f06e | 2 | public int sizeEffective() {
int count = 0;
for (String gene : this)
if (geneSets.hasValue(gene)) count++;
return count;
} |
9622b480-a58c-4364-bc26-5a6f6dbe46f2 | 7 | boolean validateMove(movePair movepr, Pair pr) {
Point src = movepr.src;
Point target = movepr.target;
boolean rightposition = false;
if (Math.abs(target.x-src.x)==Math.abs(pr.p) && Math.abs(target.y-src.y)==Math.abs(pr.q)) {
rightposition = true;
}
if (Math.abs(target.x-src.x)==Math.abs(pr.p) && Math.abs(target.y-src.y)==Math.abs(pr.q)) {
rightposition = true;
}
if (rightposition && src.value == target.value && src.value >0) {
return true;
}
else {
return false;
}
} |
30e93598-6c7b-427e-a199-c1e1a2ee6b5c | 9 | public boolean combineLocal() {
StructuredBlock firstInstr = (catchBlock instanceof SequentialBlock) ? catchBlock
.getSubBlocks()[0] : catchBlock;
if (firstInstr instanceof SpecialBlock
&& ((SpecialBlock) firstInstr).type == SpecialBlock.POP
&& ((SpecialBlock) firstInstr).count == 1) {
/* The exception is ignored. Create a dummy local for it */
exceptionLocal = new LocalInfo();
exceptionLocal.setType(exceptionType);
firstInstr.removeBlock();
return true;
} else if (firstInstr instanceof InstructionBlock) {
Expression instr = ((InstructionBlock) firstInstr).getInstruction();
if (instr instanceof StoreInstruction) {
StoreInstruction store = (StoreInstruction) instr;
if (store.getOperatorIndex() == store.OPASSIGN_OP
&& store.getSubExpressions()[1] instanceof NopOperator
&& store.getLValue() instanceof LocalStoreOperator) {
/* The exception is stored in a local variable */
exceptionLocal = ((LocalStoreOperator) store.getLValue())
.getLocalInfo();
exceptionLocal.setType(exceptionType);
firstInstr.removeBlock();
return true;
}
}
}
return false;
} |
caa1ffb6-a8a7-4c4f-833a-2b85c7a90280 | 1 | public void draw1(Graphics g, ImageObserver observer) {
if (image1 != null)
g.drawImage(image1, x, y, width, heigth, observer);
} |
336901d4-0b7f-46ea-8f81-2a6adc7f5e94 | 7 | public void writePairedNodeInformation( String filepath ) throws Exception
{
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filepath)));
writer.write("nodeA\tnodeB\tparentA\tparentB\tnodeLevel\tsameParents\tleastCommonDistnace\talignmentDistance\talignmentDistanceMinusPredictedDistance\tnumSequencesA\tnumSequencesB\tmaxTreeSeqsA\tmaxTreeSeqsB\ttotalSeqs\n");
List<ENode> list = getAllNodes();
for( int x=0; x < list.size()-1; x++)
{
System.out.println("Writing outer node " + x + " Of " + list.size());
ENode aNode = list.get(x);
if( aNode.getParent() != null && ! aNode.getParent().getNodeName().equals(ROOT_NAME))
for( int y=x+1; y <list.size(); y++)
{
ENode bNode = list.get(y);
if( bNode.getParent() != null && ! bNode.getParent().getNodeName().equals(ROOT_NAME) &&
aNode.getLevel() == bNode.getLevel())
{
writer.write( aNode.getNodeName() + "\t" );
writer.write( bNode.getNodeName() + "\t" );
writer.write( aNode.getParent().getNodeName() + "\t");
writer.write( bNode.getParent().getNodeName() + "\t");
writer.write( aNode.getLevel()+ "\t");
writer.write(aNode.getParent().getNodeName().equals(bNode.getParent().getNodeName()) + "\t");
writer.write( getLeastCommonDistance(aNode, bNode) + "\t");
ProbSequence probSeq = ProbNW.align(aNode.getProbSequence(), bNode.getProbSequence());
writer.write(probSeq.getAverageDistance() + "\t");
writer.write((probSeq.getAverageDistance() - aNode.getLevel()) + "\t" );
writer.write( aNode.getProbSequence().getNumRepresentedSequences() + "\t");
writer.write( bNode.getProbSequence().getNumRepresentedSequences() + "\t");
writer.write( aNode.getMaxNumberOfSeqsInBranch() + "\t");
writer.write( bNode.getMaxNumberOfSeqsInBranch()+ "\t");
int totalNum = aNode.getProbSequence().getNumRepresentedSequences() +
bNode.getProbSequence().getNumRepresentedSequences();
writer.write(totalNum + "\n");
}
}
writer.flush();
}
writer.flush(); writer.close();
} |
1af7f4fe-b35d-4cea-9706-0b41996639e9 | 7 | private Element parseBranch() throws ParserException, XMLStreamException {
String condition = getAttribute("condition");
startElement("branch");
Labelled left = null, right = null;
while (look().isStartElement()) {
String name = getNameOfStartElement();
if (name.equals("left")) {
if (left != null) {
throw new ParserException("Duplicate left branch.");
}
left = parseLabelled("left");
} else if (name.equals("right")) {
if (right != null) {
throw new ParserException("Duplicate right branch.");
}
right = parseLabelled("right");
} else {
throw new ParserException("Unkown branch child: " + name);
}
}
endElement("branch");
return new Branch(condition, left == null ? new Labelled() : left, right == null ? new Labelled()
: right);
} |
3088ef43-e171-418d-807d-fd3fd7d6a847 | 3 | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String id=request.getParameter("documento");
String consulta="";
String imagen="";//Captura la foto de la persona
String radio=request.getParameter("opciones"); //Captura la opcion para saber si es estudiante o profesor
consulta="select Foto from tbl_estudiante where Identificacion = '"+id+"'";
if(radio.equals("Estudiante"))
{
consulta="select Foto from tbl_estudiante where Identificacion = '"+id+"'";;
}else if(radio.equals("Profesores"))
{
consulta="select Foto from tbl_empleado where Identificacion = '"+id+"'";
}
ConexionBD cnx=new ConexionBD();
cnx.conectarse();
cnx.consulta = cnx.conector.createStatement();
cnx.resultado= cnx.consulta.executeQuery( consulta);
if( cnx.resultado.next())
{
imagen= cnx.resultado.getString("Foto");
}
out.print(" <input type=\"Hidden\" name=\"documento\" value='"+id+"'/> ");
out.print("<Center> <img src='"+imagen+"' width='250' height='250' </Center> ");
}
} |
cac03689-0c1c-4efb-83de-82c8df42be42 | 1 | public void doDelimitedMultiLine() {
try {
final String data = ConsoleMenu.getString("Data ", DelimitedMultiLine.getDefaultDataFile());
DelimitedMultiLine.call(data);
} catch (final Exception e) {
e.printStackTrace();
}
} |
2136d770-cd97-4c7e-8a39-1d088bc652e7 | 7 | public boolean isAABBInMaterial(AxisAlignedBB var1, Material var2) {
int var3 = MathHelper.floor_double(var1.minX);
int var4 = MathHelper.floor_double(var1.maxX + 1.0D);
int var5 = MathHelper.floor_double(var1.minY);
int var6 = MathHelper.floor_double(var1.maxY + 1.0D);
int var7 = MathHelper.floor_double(var1.minZ);
int var8 = MathHelper.floor_double(var1.maxZ + 1.0D);
for (int var9 = var3; var9 < var4; ++var9) {
for (int var10 = var5; var10 < var6; ++var10) {
for (int var11 = var7; var11 < var8; ++var11) {
Block var12 = Block.blocksList[this.getBlockId(var9, var10, var11)];
if (var12 != null && var12.blockMaterial == var2) {
int var13 = this.getBlockMetadata(var9, var10, var11);
double var14 = (double) (var10 + 1);
if (var13 < 8) {
var14 = (double) (var10 + 1) - (double) var13 / 8.0D;
}
if (var14 >= var1.minY) {
return true;
}
}
}
}
}
return false;
} |
f07d3edd-27b2-4a86-93f0-0713914330c8 | 5 | public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
int testCases = 0;
while (T > 0) {
T--;
int N = sc.nextInt();
testCases++;
int lowJumps = 0;
int highJumps = 0;
int currentHeight = 0;
for (int i = 0; i < N; i++) {
int temp = sc.nextInt();
if (i != 0) {
if (currentHeight < temp) {
highJumps++;
} else if (currentHeight > temp) {
lowJumps++;
}
}
currentHeight = temp;
}
System.out.println("Case "+testCases+": "+highJumps+" "+lowJumps);
}
} |
c2b5b295-1b54-4a4b-8e45-88b169774d20 | 6 | @Override
public void removeEdgesBetween(N from, N to) {
if(containsNode(from) && containsNode(to)) {
for(Edge<N> edge : edgesFrom(from)) {
if(edge.to.equals(to)) {
nodes.get(from).remove(edge);
}
}
for(Edge<N> edge : edgesFrom(to)) {
if(edge.to.equals(from)) {
nodes.get(to).remove(edge);
}
}
}
} |
2a70df44-5c85-4be2-a125-149f06593336 | 4 | public void updateGroup(Group group, List<Group_schedule> list)
{
try
{
PreparedStatement ps;
if(group.getId()>0)
{
ps = con.prepareStatement( "UPDATE groups SET name=?, level=?, capacity=?," +
" stud_age=?, teacher=? WHERE id=?" );
ps.setInt( 6, group.getId() );
}else{
ps = con.prepareStatement( "INSERT INTO groups (name, level, capacity," +
" stud_age, teacher) VALUES (?,?,?,?,?)" );
}
ps.setString( 1, group.getName());
ps.setInt( 2, group.getLevel().getId() );
ps.setInt( 3, group.getCapacity() );
ps.setInt( 4, group.getStudentAge() );
ps.setString( 5, group.getTeacher() );
//ps.setInt( 6, group.getSchedule() );
ps.executeUpdate();
ps.close();
Group_scheduleDAO group_scheduleDAO = new Group_scheduleDAO(con);
for(Group_schedule item : list)
{
if(item.getStatus() == Schedule.STATUS_NEW)
{
group_scheduleDAO.updateGroup_schedule(item);
}
else
{
group_scheduleDAO.deleteGroup_schedule(item.getId());
}
}
// for(Group_schedule item : list)
// {
// if(item.getStatus() == Schedule.STATUS_NEW)
// {
// ps = con.prepareStatement( "INSERT INTO group_schedule" +
// " (group_id, schedule_id) VALUES (?,?)" );
// ps.setInt( 1, group.getId());
// ps.setInt( 2, item.getId() );
// ps.executeUpdate();
//
// }else{
//
// ps = con.prepareStatement( "DELETE FROM group_schedule WHERE" +
// " group_id=? AND schedule_id=?" );
// ps.setInt( 1, group.getId());
// ps.setInt( 2, item.getId() );
// ps.executeUpdate();
// }
//
// }
}
catch( SQLException e )
{
e.printStackTrace();
}
} |
e55fb53b-9bdc-4552-8a22-fa8bbba799ae | 2 | public String createListInfo(String exceptName) {
String temp = "<SESSION_ACCEPT>";
for (ClientInfo node : client_list) {
if (node.name.equals(exceptName))
continue;
temp += "<PEER>";
temp += "<PEER_NAME>" + node.name + "</PEER_NAME>";
temp += "<IP>" + node.ip + "</IP>";
temp += "<PORT>" + node.portId + "</PORT>";
temp += "</PEER>";
}
temp += "</SESSION_ACCEPT>";
return temp;
} |
6fe45ea5-5d6d-45f2-bc4b-0ac03cd102d3 | 5 | public synchronized void downloadLatestVersion ()
{
FileOutputStream fos = null;
try
{
if (remoteVersion == null)
{
this.updateCheck();
}
plugin.getLogger().info("Downloading latest version...");
ReadableByteChannel rbc =
Channels.newChannel(new URL(downloadUrl.replace("{version}",
remoteVersion)).openStream());
fos =
new FileOutputStream("plugins" + File.separator + pluginName
+ ".jar");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
plugin.getLogger().info(
"Latest version has finished downloading");
plugin.getLogger().info(
"Changes will take effect on restart");
}
catch (IOException e)
{
e.printStackTrace();
}
}
downloaded.set(true);
}
} |
aeaafdf6-8448-4d29-a0a1-2a6daf41b6b2 | 0 | public static void DamonMarksReport()
{
System.out.println("Damon's final exam mark is: " + DamonStats.Final);
System.out.println("Damon's midterm exam mark is: " + DamonStats.Midterm);
System.out.println("Damon's final mark for the term is: " + (DamonStats.Final* 0.75 + DamonStats.Midterm * 0.25));
} |
42ea83ca-5048-4087-809a-c5f57c9da4b1 | 4 | private static List<Shape> buscarSubparce(List<Shape> shapes, String subparce){
List<Shape> shapeList = new ArrayList<Shape>();
for(Shape shape : shapes)
if (shape != null && shape instanceof ShapeSubparce)
if (((ShapeSubparce) shape).getSubparce().equals(subparce))
shapeList.add(shape);
return shapeList;
} |
ca725df5-af5e-42a6-b8ba-b00f0921a91e | 1 | @Override
public ArrayList<String> load() throws IOException {
ArrayList<String> words = new ArrayList<String>();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (line != null) {
words.add(line);
line = reader.readLine();
}
return words;
} |
68b9d060-0995-4b00-bb42-085cdd46c876 | 2 | @Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fieldNames.length; i++)
sb.append(fieldNames[i] + "\t" + types[i] + (multipleValues[i] ? "\tmultiple" : "") + "\n");
return sb.toString();
} |
a59be1e8-8985-4059-98a1-f11a48256ed0 | 1 | public boolean isAncestorToDescendent(final GraphNode v, final GraphNode w) {
return (preOrderIndex(v) <= preOrderIndex(w))
&& (postOrderIndex(w) <= postOrderIndex(v));
} |
2feaf90a-4a27-494e-b4c2-d61596d49819 | 5 | public static void testFileIO(){
// File I/O contained in java.io package (imported)
FileInputStream infile=null;
FileOutputStream outfile=null;
File inf=new File("input.txt");
File outf = new File("output.txt");
try{
infile = new FileInputStream(inf);
outfile = new FileOutputStream(outf);
int c;
while((c=infile.read())!=-1){
outfile.write(c);
}
if(infile!=null){ infile.close(); }
if(outfile!=null){ outfile.close(); }
}
catch(IOException ioe){
println("IOException in copy");
println(ioe.getMessage());
println(ioe.getCause());
}
// Creating directories
String dirname="E:/Documents/Projects/Java/HelloWorld/Files/";
File d = new File(dirname);
d.mkdirs();
//List directories
String dirname2="E:/Documents/Projects/Java";
String[] paths;
File pathd=new File(dirname2);
paths=pathd.list();
for(String path:paths){
println(path);
}
} |
7d277391-b23c-48df-83f6-c1b3b852d0a2 | 3 | public ArrayList<String> getFailure(){
ArrayList<String> fail = new ArrayList<String>();
if(failures.contains(Signal)){
fail.add(Signal);
}
if(failures.contains(Break)){
fail.add(Break);
}
if(failures.contains(Engine)){
fail.add(Engine);
}
return fail;
} |
d8fe6c32-ba5e-49af-a574-03b7cca4d7f3 | 9 | public boolean canPlaceRoom(int roomX, int roomY, int roomWidth, int roomHeight) {
if (roomX < 1 || roomY < 1 || roomX + roomWidth > sizeX - 2 || roomY + roomHeight > sizeY - 2) {
return false;
}
for (int x = roomX; x < roomX + roomWidth; x++) {
for (int y = roomY; y < roomY + roomHeight; y++) {
if (getTile(x, y) != TILE_EMPTY && getTile(x, y) != TILE_WALL && getTile(x, y) != TILE_WALL_CORNER) {
return false;
}
}
}
return true;
} |
d41c21d1-b715-46d9-ad18-b31825f5b9fa | 0 | @Test public void itShouldSerialize() throws Exception
{
MultiLineString multiLineString = new MultiLineString();
multiLineString.add(Arrays.asList(new LngLatAlt(100, 0), new LngLatAlt(101, 1)));
multiLineString.add(Arrays.asList(new LngLatAlt(102, 2), new LngLatAlt(103, 3)));
Assert.assertEquals("{\"coordinates\":" + "[[[100.0,0.0],[101.0,1.0]],[[102.0,2.0],[103.0,3.0]]],\"type\":\"MultiLineString\"}", mapper.toJson(multiLineString));
} |
188b4634-7eb5-43c3-9797-e6c632918719 | 5 | private void writeSheet(XSSFSheet sheet, List list) throws IOException {
int size = list.size();
int colno = 6;
if (size < 2) {
return;
}
//
for (int i = 0; i < size; i++) {
for (int j = 0; j < 4; j++) {
sheet.createRow(i * 4 + j);
}
}
ExcelUtils.copyEdge(wb, sheet, size);
for (int i = 0; i < size; i++) {
Map player = (Map) list.get(i);
String name = (String) player.get("name");
String kana = (String) player.get("kana");
String dojo = (String) player.get("dojo");
BigDecimal seq = (BigDecimal) player.get("seq");
String str1;
String str2;
if (seq == null) {
str1 = "";
str2 = "";
} else {
str1 = String.format("%s %s (%s)", seq, name, dojo);
str2 = String.format(" %s", kana);
}
XSSFRow row0 = getRow(sheet, i * 4);
row0.setHeightInPoints((float) 4);
XSSFRow row1 = getRow(sheet, i * 4 + 1);
XSSFCell cell1 = getCell(colno, row1);
cell1.setCellValue(str1);
XSSFRow row2 = getRow(sheet, i * 4 + 2);
XSSFCell cell2 = getCell(colno, row2);
cell2.setCellValue(str2);
XSSFRow row3 = getRow(sheet, i * 4 + 3);
row3.setHeightInPoints((float) 4);
}
ExcelUtils.copyEdge(wb, sheet, size);
// for (int i = 0; i < 32; i++) {
// int[] indexes = {i * 4, i * 4 + 3};
// for (int rowIndex: indexes) {
// XSSFRow row = sheet.getRow(i);
// if (row == null) {
// continue;
// }
// row.setHeight((short) 2);
// }
// }
} |
3c37f1e7-e268-4120-9e56-42e94c5d0524 | 9 | @Override
public void run()
{
if (Main.DEBUG)
{
System.out.println("SpeakThread Started");
}
Audio audio = Audio.getInstance();
while (isRunning)
{
try
{
Main.putIntoSpeakLatch.await();//wait for items to be put into speak thread
}
catch (InterruptedException ex)
{
Logger.getLogger(ReadThread.class.getName()).log(Level.SEVERE, null, ex);
}
if (isRunning)//still running.
{
if (!Main.speakFIFO.isEmpty())
{
String message = Main.speakFIFO.get(0);
Main.speakFIFO.remove(0);
InputStream sound = null;
try
{
sound = audio.getAudio(message, Language.ENGLISH);
audio.play(sound);
}
catch (IOException ex)
{
Logger.getLogger(SpeakThread.class.getName()).log(Level.SEVERE, null, ex);
}
catch (JavaLayerException ex)
{
Logger.getLogger(SpeakThread.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
try
{
sound.close();
audio = Audio.getInstance();
}
catch (IOException ex)
{
Logger.getLogger(SpeakThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
else
{
Main.putIntoSpeakLatch = new CountDownLatch(1);//after empty FIFO, relock
if(Main.DEBUG)System.out.println("putIntoSpeakLatch locked");
}
}
}
} |
31b45c5a-1329-4677-ab9c-0aa69296e979 | 3 | private void loadConfig(){
File liftFolder = new File(getDataFolder().getPath() + "/elevators/");
File signFile = new File(getDataFolder().getPath() + "/signs.yml");
if(!liftFolder.exists() || !signFile.exists()){
try{
liftFolder.mkdirs();
signFile.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
}
this.getConfig().addDefault("config.general.enable", true);
this.getConfig().addDefault("config.lift.material.ground", Material.GLASS.name());
this.getConfig().addDefault("config.lift.material.door", Material.FENCE.name());
this.getConfig().options().copyDefaults(true);
this.saveConfig();
enable = this.getConfig().getBoolean("config.general.enable");
tool = new ItemStack(Material.STICK);
ItemMeta toolMeta = tool.getItemMeta();
toolMeta.setDisplayName(messagePrefix + "Tool");
toolMeta.addEnchant(Enchantment.DURABILITY, 5, true);
tool.setItemMeta(toolMeta);
} |
2effa604-f5ed-4931-bd69-6f4c34f2d2fe | 4 | public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
} |
7e9377b8-cdc3-42fe-a4cd-8e6ab26a6b7e | 8 | private Predicate[] getSearchPredicates(Root<Passenger> root)
{
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
List<Predicate> predicatesList = new ArrayList<Predicate>();
String name = this.example.getName();
if (name != null && !"".equals(name))
{
predicatesList.add(builder.like(root.<String> get("name"), '%' + name + '%'));
}
String mobileNumber = this.example.getMobileNumber();
if (mobileNumber != null && !"".equals(mobileNumber))
{
predicatesList.add(builder.like(root.<String> get("mobileNumber"), '%' + mobileNumber + '%'));
}
String email = this.example.getEmail();
if (email != null && !"".equals(email))
{
predicatesList.add(builder.like(root.<String> get("email"), '%' + email + '%'));
}
String password = this.example.getPassword();
if (password != null && !"".equals(password))
{
predicatesList.add(builder.like(root.<String> get("password"), '%' + password + '%'));
}
return predicatesList.toArray(new Predicate[predicatesList.size()]);
} |
ba77025e-6592-426f-b12a-bbc3eeef452d | 7 | private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitHelper(false);
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitHelper(false);
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(), nextColumn);
}
}
}
});
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//This focus listener fires at the end of cell editing when focus is lost
//and when enter is pressed (because that causes the text field to lose focus).
//The problem is that if enter is pressed then cancelEdit is called before this
//listener runs and therefore the text field has been cleaned up. If the
//text field is null we don't commit the edit. This has the useful side effect
//of stopping the double commit.
if (!newValue && textField != null) {
commitHelper(true);
}
}
});
} |
4c53a161-5717-4604-a878-6e5d3c221dff | 3 | @Override
public void keyTyped(KeyEvent e) {
int s = e.getKeyChar()-48;
if(s<=0 || s>9) {
System.out.println("input is not 1-9");
} else {
Button b = (Button) e.getComponent();
String right = b.getLabel().trim();
int right2 = Integer.parseInt(right);
if(right2 == s) {
b.setLabel(String.valueOf(s));
b.setForeground(null);
b.setBackground(Color.LIGHT_GRAY);
b.removeKeyListener(this);
} else {
System.out.println("your input is error");
}
}
} |
31d183da-987e-4be3-8e05-5ac2c35eb165 | 2 | public static void createConfig() {
File dir = new File(System.getProperty("user.dir") + "/config");
// Create save directory
if(dir.mkdir()) {
try {
saveConfig();
} catch(Exception e) {
System.err.println("Config file failed to be created");
e.fillInStackTrace();
}
System.out.println("Config file created");
} else {
// Save directory failed to be created
System.err.println("Config file was not created");
}
} |
f1669b8b-35cc-4486-9db2-47b8dd777758 | 1 | public static void clearCache(){
for(String id : cacheClips.keySet()){
stop(id);
cacheClips.get(id).close();
}
cacheClips.clear();
System.out.println("[SoundManger] Clearing cache.");
} |
71f3f2d1-d993-4786-aa6b-2444477cae33 | 9 | public String minWindow(String s, String t) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (char c : s.toCharArray()) {
map.put(c, 0);
}
for (char c : t.toCharArray()) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
return "";
}
}
int start = 0, end = 0, minStart = 0, minLen = Integer.MAX_VALUE, counter = t.length();
while (end < s.length()) {
char c1 = s.charAt(end);
if (map.get(c1) > 0) {
counter--;
}
map.put(c1, map.get(c1) - 1);
end++;
while (counter == 0) {
if (minLen > end - start) {
minLen = end - start;
minStart = start;
}
char c2 = s.charAt(start);
map.put(c2, map.get(c2) + 1);
if (map.get(c2) > 0) {
counter++;
}
start++;
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
} |
1d7e8ca1-2481-4a9a-8360-7ec23769da3a | 8 | private void lstCommandeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstCommandeMouseClicked
// TODO add your handling code here:
article.removeAllElements();
articleLoiseau.removeAllElements();
int indice = 0;
for (Commande c : lesCommandes) {
if (lstCommande.getSelectedValue().toString().compareTo(c.getRef_dossier()) == 0) {
indice = lesCommandes.indexOf(c);
}
}
for (Client c : lesClient) {
if (c.getId_client() == lesCommandes.get(indice).getId_client()) {
lstClient.setSelectedIndex(lesClient.indexOf(c));
}
}
completerClient(lstClient.getSelectedIndex());
for (Article_fabrication a : lesArticle) {
if (a.getCommande() == lesCommandes.get(indice).getId_commande()) {
article.add(a);
}
}
for (Article_fabrication a : lesArticleLoiseau) {
if (a.getCommande() == lesCommandes.get(indice).getId_commande()) {
articleLoiseau.add(a);
}
}
completerCommande(indice);
afficherArticle();
calculTva();
}//GEN-LAST:event_lstCommandeMouseClicked |
ab736658-1826-4fdf-b37c-9d96fad4e222 | 9 | public void doPost (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
// --------
// Handle email sending
// -------
// If a valid email address is provided
if (req.getParameter("email") != null && req.getParameter("sptoken") == null) {
try {
//Store the account in the HTTP session
this.resetHelper.getApplication().sendPasswordResetEmail(req.getParameter("email"));
//Redirect to reset page and note success
String site = "/reset.jsp?email=true";
res.setStatus(res.SC_ACCEPTED);
res.sendRedirect(site);
} catch (Exception e) {
//Redirect back to reset page and note the error
String site = "/reset.jsp?email=error";
res.setStatus(res.SC_UNAUTHORIZED);
res.sendRedirect(site);
}
} else if (req.getParameter("email") == null && req.getParameter("sptoken") == null) {
//Redirect back to email reset page
String site = "/reset.jsp?email=false";
res.setStatus(res.SC_UNAUTHORIZED);
res.sendRedirect(site);
}
// --------
// Handle password setting
// -------
// If a new password is provided
if (req.getParameter("password") != null) {
if (req.getParameter("password").equals(req.getParameter("password_confirm")) && !req.getParameter("password").equals("")) {
try {
//Store the account in the HTTP session
Account account = this.resetHelper.getApplication().verifyPasswordResetToken(req.getParameter("sptoken"));
account.setPassword(req.getParameter("password"));
account.save();
//Redirect to reset page and note success
String site = "/set.jsp?password=true";
res.setStatus(res.SC_ACCEPTED);
res.sendRedirect(site);
} catch (ResourceException name) {
//Redirect back to reset page and note the error
String site = "/set.jsp?sptoken=" + req.getParameter("sptoken") + "&error=" + name.getMessage();
res.setStatus(res.SC_UNAUTHORIZED);
res.sendRedirect(site);
}
} else {
//Redirect back to email reset page
String site = "/set.jsp?sptoken=" + req.getParameter("sptoken") + "&password=false";
res.setStatus(res.SC_UNAUTHORIZED);
res.sendRedirect(site);
}
}
} |
9f2c563c-a02a-4c6b-acec-6f5fa98ba3e1 | 0 | public void setConcurrent(){
this.concurrent = true;
} |
b068dad7-b6f4-4147-a4a8-791ca08bcb94 | 4 | @Override
public void actionPerformed(ActionEvent e) {
boolean global = tb.getSelected();
boolean state = this.selected;
boolean result = false;
if (!global)
{
tb.setSelected();
this.setSelected(true);
result = true;
}
else
{
if (state)
{
this.setSelected(false);
tb.setSelected();
result = false;
}
else
{
ToolBarComponent[] temp = tb.getTbc();
for (int i = 0; i < temp.length; i++)
{
temp[i].setSelected(false);
temp[i].selected = false;
}
this.setSelected(true);
result = true;
}
}
sfap.hand = result ? this.getId() : 0;
sfap.objSize = new Dimension(1, 1);
this.selected = result;
} |
d04e4db5-f39c-4162-9c2b-dc0c338c5a41 | 4 | @Override
public float millisecondsPlayed()
{
switch( channelType )
{
case SoundSystemConfig.TYPE_NORMAL:
if( clip == null )
return -1;
return clip.getMicrosecondPosition() / 1000f;
case SoundSystemConfig.TYPE_STREAMING:
if( sourceDataLine == null )
return -1;
return sourceDataLine.getMicrosecondPosition() / 1000f;
default:
return -1;
}
} |
ef4c80b6-50ad-4c08-b175-a2fb09a255ba | 8 | @Override
public Void visitIndent(IndentToken token) {
assertExpected(token);
// If we're dealing with a comment, just smile and wave
if (tokens.peek().getType() == TokenType.COMMENT) {
setExpected(TokenType.COMMENT);
return null;
}
// If we're dealing with list items, don't do peep!
if (tokens.peek().getType() == TokenType.LISTITEM) {
setExpected(TokenType.LISTITEM);
return null;
}
// Get the indent amount of the token
int newIndent = token.value().length();
// And the current indent amount
int currentIndent = indents.get(level);
// Higher value -> deeper indent level
if (newIndent > currentIndent) {
if (node == null || node.get() != null) {
error("Indent mismatch 1! Expected " + currentIndent + " spaces, but found " + newIndent, token);
}
level++;
indents.put(level, newIndent);
parent = node;
} else if (newIndent < currentIndent) {
int originalIndent = currentIndent;
while (newIndent < currentIndent) {
parent = parent.getParent();
level--;
currentIndent = indents.get(level);
}
if (newIndent != currentIndent) {
error("Indent mismatch 2! Expected " + originalIndent + " spaces, but found only " + newIndent, token);
}
}
setExpected(TokenType.KEY, TokenType.COMMENT, TokenType.LISTITEM);
return null;
} |
8fad66c4-8c6b-46c8-9747-08241d5a95e9 | 7 | @Override
public void solve() {
double A = 0, B = 0, C = 0, D = 0;
updateRightWeights();
updateLeftWeights();
for (Term t : leftTerms) {
if (t instanceof XTerm) {
A += ((XTerm) t).coefficient;
} else if (t instanceof Constant) {
C += t.weight;
}
}
for (Term t : rightTerms) {
if (t instanceof XTerm) {
B += ((XTerm) t).coefficient;
} else if (t instanceof Constant) {
D += t.weight;
}
}
try {
double x = (D - C) / (A - B);
xVal.setText(x + "");
} catch (ArithmeticException ae) {
JOptionPane.showMessageDialog(this, "Sorry! I can't solve that!");
xVal.setText("0");
}
update();
} |
0f34d6ab-5c5a-456b-bfc9-e1b0fb8ed2e7 | 7 | public void setEditValue(int n, EditInfo ei) {
if (n == 0) {
inductance = ei.value;
}
if (n == 1) {
ratio = ei.value;
}
if (n == 2 && ei.value > 0 && ei.value < 1) {
couplingCoef = ei.value;
}
if (n == 3) {
if (ei.checkbox.getState()) {
flags &= ~Inductor.FLAG_BACK_EULER;
} else {
flags |= Inductor.FLAG_BACK_EULER;
}
}
} |
3dac74b2-36e7-406c-92c3-1cba7fc93dde | 5 | public void dmgUpdate(int i, int j, int k, int l) {
Obstacle[][] obs = level.getObstacles();
int dmg = 0;
if ((y+height)/Obstacle.getHeight()>=0){ // Could be out of the map
while (l<height){
int tmpK = k;
int tmpJ = j;
while(tmpK<width && i>=0){
dmg += obs[i][tmpJ].getDmg();
// if (obs[i][tmpJ].getDmg()!= 0) // to print when dmg
// System.out.println("I:"+i+" J:"+j+" Dmg :"+dmg+" Health:"+health);
tmpK += Obstacle.getWidth();
++ tmpJ;
}
l += Obstacle.getHeight();
++i;
}
}
health -= dmg;
if (health < 0)
dead = true;
} |
914c68a1-1d97-4c1d-8166-0537e4b01f87 | 5 | public boolean checkMethodInvocation( Method method ) {
if( method == null )
return false; // result not specified
// Method must be public
if( ! Modifier.isPublic(method.getModifiers()) )
return false;
return
method.getName().equals("doAnything") ||
method.getName().equals("doSomething") ||
method.getName().equals("printJSONArray") ||
method.getName().equals("printJSONObject");
} |
241b56ad-b5a2-49d2-bb73-862eaf0814e6 | 6 | public Matrix subtract(Matrix a) {
if (a == null) {
return null;
}
if ((!this.isJagged && !a.isJagged) && this.sameOrder(a)) {
double[][] new_elements = new double[this.rowCount][this.columnCount];
for (int row = 0; row < this.rowCount; row++) {
for (int column = 0; column < this.columnCount; column++) {
new_elements[row][column] = this.elements[row][column] - a.elements[row][column];
}
}
return new Matrix(new_elements);
}
return null;
} |
7b0db98a-41c5-40d0-892c-038210112f94 | 7 | public Path obtainRevisionContent(long timestamp)
{
// Check first if the specific revision is a binary revision. If it is, we're done.
Path specificRevision = getRevisionInfo(timestamp);
if(!FileOp.isPlainText(specificRevision))
{
logger.debug("Revision for file " + file.toString() + " (" + timestamp + ") is binary");
return specificRevision;
}
logger.debug("Revision for file " + file.toString() + " (" + timestamp + ") is plain text");
// Retrieve data from database
DbConnection db = DbConnection.getInstance();
List<RevisionInfo> fileRevisionList = db.getFileRevisions(file);
LinkedList<RevisionInfo> patchList = new LinkedList<>();
// Add the records we needed to a linked list
for(RevisionInfo revisionInfo : fileRevisionList)
{
if(revisionInfo.time > timestamp && revisionInfo.diff != null)
{
patchList.add(revisionInfo);
}
}
// Sort the linked list in reverse order
Collections.sort(patchList);
Collections.reverse(patchList);
// Apply diff to the file. return null if error occurs
Path newestFile = file;
Path tempPatchFile = null;
try
{
// Get the extension for the file (ensures the correct program is used to display the
// file)
String[] fileNameSplit = file.getFileName().toString().split("\\.");
String extension = fileNameSplit[fileNameSplit.length - 1];
if(fileNameSplit.length > 1)
{
extension = "." + extension;
}
tempPatchFile = Files.createTempFile("FBMS", extension);
for(RevisionInfo revisionInfo : patchList)
{
FileOp.stringToFile(revisionInfo.diff, tempPatchFile);
newestFile = FileOp.applyPatch(newestFile, tempPatchFile);
}
return newestFile;
}
catch(IOException e)
{
Errors.nonfatalError("Error occurs while applying patches.", e);
return null;
}
} |
0b9a397a-0f0f-4e7b-9b31-dcf6786306e9 | 7 | public void playerLeaveWorld(World world, Player player){
List<Player> playersInWorld = world.getPlayers();
if (playersInWorld.size() < 1 && !plugin.doNotUnload.contains(world.getName())){
Bukkit.getServer().unloadWorld(world, true);
String worldName = world.getName();
for (String worldN : plugin.mainWorlds){
if (worldName.startsWith(worldN + "_")){
adventourmovefolder.main(worldName, "inactive/" + worldName);
}
}
AdvenTourStatus adventourstatus = new AdvenTourStatus(plugin);
adventourstatus.changeStatus();
}else{
if (player.isOnline()){
if (!plugin.resettingWorld.containsKey(player)){
for (Player playeren : world.getPlayers()){
playeren.sendMessage(ChatColor.BLUE + plugin.playerLeave.replaceAll("\\$player", player.getName()));
}
}
}
}
} |
3546ea94-e1d1-4fbe-a822-269cfce4fa2b | 1 | protected void updateBall() {
ball.move();
ball.bounceOffWalls(isEndless);
ball.bounceOffPaddle(paddle1, player1);
ball.scorePoint(player1, player2, isEndless);
if (!isEndless) {
ball.bounceOffPaddle(paddle2, player2);
}
ball.teleport(isTeleport, teleport);
} |
718d9910-a4cc-4f15-ae09-9c4bd8425c61 | 2 | private void zoomtoRouteArea()
{
final double fromNodeX = fromNode.getxCoord();
final double fromNodeY = fromNode.getyCoord();
final double toNodeX = toNode.getxCoord();
final double toNodeY = toNode.getyCoord();
final double xDistance = Math.max(fromNodeX, toNodeX) - Math.min(fromNodeX, toNodeX);
final double yDistance = Math.max(fromNodeY, toNodeY) - Math.min(fromNodeY, toNodeY);
final double zoomconstant;
if (xDistance > yDistance)
{
zoomconstant = (xDistance) / xlength;
} else
{
zoomconstant = (yDistance+yDistance) / xlength;
}
final double newXLength = zoomconstant*xlength*2;
final double newYLength = zoomconstant*ylength*2;
visibleArea.setCoord(Math.min(fromNodeX, toNodeX)+xDistance/2-xlength/2, Math.min(fromNodeY, toNodeY)+yDistance/2-ylength/2, xlength, ylength);
searchXCoord = getWidth() / 2;
searchYCoord = getHeight() / 2;
timer.purge();
timer.cancel();
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run()
{
if (xlength <= newXLength)
{
visibleArea.setCoord(Math.min(fromNodeX, toNodeX)+xDistance/2-newXLength/2, Math.min(fromNodeY, toNodeY)+yDistance/2-newYLength/2, newXLength, newYLength);
timer.cancel();
timer.purge();
searchYCoord = 0;
searchXCoord = 0;
zoomInConstant = 0.98;
repaint();
}
else
{
zoomInConstant = 0.99 - Math.log(xlength)*0.0014;
zoomIn(searchXCoord, searchYCoord);
repaint();
}
}
};
timer.scheduleAtFixedRate(task, 10, 10);
} |
c630edf6-6978-4396-92d5-0cd880938cd3 | 6 | private Map<SecondLevelId, Object> getValue() {
while(true) {
if (firstVal == null && !firstCursor.hasNext()) {
return null;
}
if (firstVal == null) {
firstVal = firstCursor.next();
secondCursor = iterable.iterator();
}
while (secondCursor.hasNext()) {
Map<SecondLevelId, Object> val = Utils.join(firstVal, secondCursor.next());
if (eqAttrs.execute(val)) {
return val;
}
}
firstVal = null;
}
} |
6f9c4587-8f86-4a8d-bc8d-2d10876fd397 | 8 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
if((msg.amISource(mob))
&&(msg.tool()!=this)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_CHANNEL))
&&((CMath.bset(msg.sourceMajor(),CMMsg.MASK_MOVE))
||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_HANDS))
||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_MAGIC))
||(CMath.bset(msg.sourceMajor(),CMMsg.MASK_EYES))))
unInvoke();
return;
} |
6fc02202-fb89-4a13-b14a-a79144fdf78b | 4 | public static <T extends Comparable<? super T>> int bestPivotStrategy(ArrayList<T> list, int start, int end){
int middle = (end + start)/2;
if(list.get(middle).compareTo(list.get(start)) < 0){
normalSwap(list, start, middle);
}
if(list.get(end).compareTo(list.get(start)) < 0){
normalSwap(list, start, end);
}
if(list.get(end).compareTo(list.get(middle)) < 0){
normalSwap(list, middle, end);
}
return middle;
} |
7f79edc3-8466-44ee-8e6d-e9db6b70fdb5 | 6 | public static String downloadToString(String url) {
URL website = null;
try {
website = new URL(url);
} catch (MalformedURLException e) {
System.out.println("Couldn't connect to "+url);
return null;
}
URLConnection connection = null;
try {
connection = website.openConnection();
} catch (IOException e) {
System.out.println("Couldn't connect to " + url);
return null;
}
connection.setRequestProperty("User-Agent", "FTBPermissionsChecker");
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
System.out.println("Couldn't read " + url);
return null;
}
StringBuilder response = new StringBuilder();
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
} catch (IOException e) {
System.out.println("Trouble reading " + url);
return null;
}
try {
in.close();
} catch (IOException e) {
System.out.println("Couldn't close connection to " + url);
}
return response.toString();
} |
ccb29beb-37c2-475d-9b66-18e1813d6000 | 6 | public boolean isIdentity(){
boolean test = true;
if(this.numberOfRows==this.numberOfColumns){
for(int i=0; i<this.numberOfRows; i++){
if(this.matrix[i][i]!=1.0D)test = false;
for(int j=i+1; j<this.numberOfColumns; j++){
if(this.matrix[i][j]!=0.0D)test = false;
if(this.matrix[j][i]!=0.0D)test = false;
}
}
}
else{
test = false;
}
return test;
} |
75707500-805e-49ff-b4ff-b66632c5afc3 | 7 | private void barInput(int time){
//draw a moving bar watch out for out of boundary
int length=8;
for(int bar=0; bar<time/20; bar++){
int intercept=20*bar;
for(int i=intercept;i<time;i++){
for(int j=0;j<length;j++){
if(i+j-intercept<column && i+j-intercept>=0){
output.get(i).add(new int[]{j,i+j-intercept});
}
}
}
}
//add anomaly
for(int i=0;i<30;i++){
for(int j=0;j<length;j++){
//output.get(460+i).add(new int[]{j,i-j+length});
}
}
} |
2b3e9d9f-3988-4988-92b8-584f99a28a81 | 9 | public static Row copyRow(Sheet sheet, Row sourceRow, int destination) {
Row newRow = sheet.createRow(destination);
// get the last row from the headings
int lastCol = sheet.getRow(0).getLastCellNum();
for (int currentCol = 0; currentCol <= lastCol; currentCol++) {
Cell newCell = newRow.createCell(currentCol);
// if there is a cell in the template, copy its content and style
Cell currentCell = sourceRow.getCell(currentCol);
if (currentCell != null) {
newCell.setCellStyle(currentCell.getCellStyle());
newCell.setCellComment(currentCell.getCellComment());
switch (currentCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
newCell.setCellValue(currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
newCell.setCellValue(currentCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
String dummy = currentCell.getCellFormula();
dummy = dummy.replace("Row",
String.valueOf(destination + 1));
newCell.setCellFormula(dummy);
newCell.setCellFormula(currentCell
.getCellFormula()
.replace("Row", String.valueOf(destination + 1)));
break;
case Cell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(currentCell.getBooleanCellValue());
break;
default:
}
}
}
// if the row contains merged regions, copy them to the new row
int numberMergedRegions = sheet.getNumMergedRegions();
for (int i = 0; i < numberMergedRegions; i++) {
CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
if (mergedRegion.getFirstRow() == sourceRow.getRowNum()
&& mergedRegion.getLastRow() == sourceRow.getRowNum()) {
// this region is within the row - so copy it
sheet.addMergedRegion(new CellRangeAddress(destination,
destination, mergedRegion.getFirstColumn(), mergedRegion
.getLastColumn()));
}
}
return newRow;
} |
476685ef-2daa-4543-a93c-fc1562a0b10c | 9 | @SuppressWarnings("unused")
@Test
public void testGlyphIterator() {
//Create a few regions with text lines, words and glyphs
Page page = new Page();
PageLayout pageLayout = page.getLayout();
TextRegion r1 = (TextRegion)pageLayout.createRegion(RegionType.TextRegion);
TextLine t11 = r1.createTextLine();
Word w111 = t11.createWord();
Glyph g1111 = w111.createGlyph();
Region r2 = pageLayout.createRegion(RegionType.ChartRegion);
TextRegion r3 = (TextRegion)pageLayout.createRegion(RegionType.TextRegion);
TextRegion r4 = (TextRegion)pageLayout.createRegion(RegionType.TextRegion);
TextLine t41 = r4.createTextLine();
Word w411 = t41.createWord();
Glyph g4111 = w411.createGlyph();
Glyph g4112 = w411.createGlyph();
Word w412 = t41.createWord();
TextLine t42 = r4.createTextLine();
TextRegion r5 = (TextRegion)pageLayout.createRegion(RegionType.TextRegion);
TextRegion r6 = (TextRegion)pageLayout.createRegion(RegionType.TextRegion);
TextLine t61 = r6.createTextLine();
Word w611 = t61.createWord();
Glyph g6111 = w611.createGlyph();
//Use iterator factory
ContentIterator it = pageLayout.iterator(LowLevelTextType.Glyph);
assertTrue("Iterator created", it != null && it instanceof LowLevelTextObjectIterator);
assertTrue("Glyph 1111", it.hasNext() && it.next() == g1111);
assertTrue("Glyph 4111", it.hasNext() && it.next() == g4111);
assertTrue("Glyph 4112", it.hasNext() && it.next() == g4112);
assertTrue("Glyph 6111", it.hasNext() && it.next() == g6111);
assertFalse("End", it.hasNext());
//Layer
pageLayout.createLayers();
Layer layer = pageLayout.getLayers().createLayer();
layer.addRegionRef(r2.getId().toString());
layer.addRegionRef(r4.getId().toString());
layer.addRegionRef(r5.getId().toString());
it = new LowLevelTextObjectIterator(pageLayout, LowLevelTextType.Glyph, layer);
assertTrue("Glyph iterator with layer filter created", it != null && it instanceof LowLevelTextObjectIterator);
assertTrue("Glyph 4111 (in layer)", it.hasNext() && it.next() == g4111);
assertTrue("Glyph 4112 (in layer)", it.hasNext() && it.next() == g4112);
assertFalse("End it with layer filter", it.hasNext());
//Layer (no matching region)
layer.removeRegionRef(r4.getId().toString());
it = new LowLevelTextObjectIterator(pageLayout, LowLevelTextType.Glyph, layer);
assertTrue("Glyph iterator with layer filter created (no match)", it != null && it instanceof LowLevelTextObjectIterator);
assertFalse("End it with layer filter (no match)", it.hasNext());
} |
0137e048-d105-4789-bafe-53e824354106 | 9 | 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 " + _bot.getServer() +".");
_isConnected = false;
_bot.onDisconnect();
}
} |
4731f152-ba98-4fc9-b2d8-0525da36f695 | 8 | public static boolean isLeftButton(MouseEvent e, Boolean ctrlDown, Boolean shiftDown, Boolean altDown)
{
return (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0 &&
(e.getModifiersEx() & MouseEvent.BUTTON2_DOWN_MASK) == 0 &&
(e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) == 0 &&
(ctrlDown == null || e.isControlDown() == ctrlDown) &&
(shiftDown == null || e.isShiftDown() == shiftDown) &&
(altDown == null || e.isAltDown() == altDown);
} |
cf5a0aee-f76c-42ce-8352-bdc0dbf81e5b | 1 | private void initContent()
{
setBounds(100, 100, 400, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new BorderLayout(0, 0));
tabbedPane = new JTabbedPane(JTabbedPane.LEFT);
contentPanel.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setBorder(UIManager.getBorder("MenuBar.border"));
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
getContentPane().add(panel, BorderLayout.NORTH);
JLabel lblSchedule = new JLabel("Schedule");
lblSchedule.setHorizontalAlignment(SwingConstants.LEFT);
lblSchedule.setIcon(StaticRes.SCHEDULE48_ICON);
lblSchedule.setFont(new Font("Tahoma", Font.PLAIN, 18));
panel.add(lblSchedule);
JPanel panel_1 = new JPanel();
panel.add(panel_1);
panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JLabel lblTeacher = new JLabel("Teacher:");
lblTeacher.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblTeacher.setBorder(new EmptyBorder(0, 40, 0, 0));
panel_1.add(lblTeacher);
cbTeacher = new JComboBox();
cbTeacher.setPreferredSize(new Dimension(150, 20));
cbTeacher.setMinimumSize(new Dimension(100, 20));
TeacherDAO teacherDAO = new TeacherDAO(db.connection);
List<Teacher> teachersList = teacherDAO.getTeachersList();
cbTeacher.setModel(teacherModel(teachersList.toArray()));
cbTeacher.setRenderer(teacherRenderer());
cbTeacher.setSelectedIndex(0);
panel_1.add(cbTeacher);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setIcon(StaticRes.OK_ICON);
okButton.setActionCommand("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("OK Clicked!");
JScrollPane js = (JScrollPane)tabbedPane.getSelectedComponent();
JTable t = (JTable)js.getViewport().getComponent(0);
Schedule schedule = null;
if(t.getSelectedRow() >= 0){
schedule = (Schedule)t.getValueAt(t.getSelectedRow(), -1);
}
Teacher teacher = (Teacher)cbTeacher.getSelectedItem();
submit(schedule, teacher);
//fillGroup();
//if(saveGroup())
//{
// dispose();
//}else{
//
//}
}
});
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
cancelButton.setIcon(StaticRes.CANCEL_ICON);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Cancel Clicked!");
dispose();
}
});
buttonPane.add(cancelButton);
}
}
} |
efa83fa6-ba58-47bd-97b8-5fa25e60972f | 9 | public void GoRight(WumpusPolje[][] wumpusWorld) {
WumpusPolje oce = tmpPolje;
tmpPolje = wumpusWorld[tmpPolje.m_x][tmpPolje.m_y + 1];
obiskanaPolja.add(tmpPolje);
tmpPolje.m_oce = oce;
this.m_points += WumpusRating.action;
WumpusHelper.Print(WumpusSteps.PremikNaPolje(tmpPolje.m_x, tmpPolje.m_y));
//Varno
if(tmpPolje.IsSafe()){
this.action = WumpusActions.down;
tmpPolje.m_lastAction = action;
}
//Vetric
if(tmpPolje.m_vetrovno){
WumpusHelper.Print(WumpusSteps.zaznalVetric);
this.action = GetLogicActionVetric(wumpusWorld);
tmpPolje.m_lastAction = action;
}
//Smrad
if(tmpPolje.m_smrad){
WumpusHelper.Print(WumpusSteps.zaznalSmrad);
this.action = GetLogicActionSmrad(wumpusWorld);
tmpPolje.m_lastAction = action;
}
//Zlato
if(tmpPolje.m_zlato && (!tmpPolje.m_wumpus || !tmpPolje.m_brezno)){
WumpusHelper.Print(WumpusSteps.NaselZlato(tmpPolje.m_x, tmpPolje.m_y));
this.m_points += WumpusRating.findGold;
}
//Jama
if(tmpPolje.m_brezno){
WumpusHelper.Print(WumpusSteps.KonecBrezno(tmpPolje.m_x, tmpPolje.m_y));
this.m_points = WumpusRating.fallingIntoAPit;
this.m_endOfGame = true;
WumpusHelper.Print(WumpusSteps.GetPoints(this.m_points));
}
//Wumpus
if(tmpPolje.m_wumpus){
WumpusHelper.Print(WumpusSteps.KonecWumpus(tmpPolje.m_x, tmpPolje.m_y));
this.m_points = WumpusRating.eatenByWumpus;
this.m_endOfGame = true;
WumpusHelper.Print(WumpusSteps.GetPoints(this.m_points));
}
//Izhod
if(tmpPolje.m_izhod){
WumpusHelper.Print(WumpusSteps.KonecZmaga(tmpPolje.m_x, tmpPolje.m_y));
this.m_points = WumpusRating.climbOutOfCave;
this.m_endOfGame = true;
WumpusHelper.Print(WumpusSteps.GetPoints(this.m_points));
}
} |
ec11e122-913c-4053-bdf2-cc633662ec56 | 5 | static final char method462(byte i, int i_20_) {
anInt5216++;
int i_21_ = 0xff & i;
if ((i_21_ ^ 0xffffffff) == -1)
throw new IllegalArgumentException("Non cp1252 character 0x"
+ Integer.toString(i_21_, 16)
+ " provided");
if ((i_21_ ^ 0xffffffff) <= -129 && i_21_ < 160) {
int i_22_ = Class44.aCharArray625[i_21_ + -128];
if ((i_22_ ^ 0xffffffff) == -1)
i_22_ = 63;
i_21_ = i_22_;
}
if (i_20_ != -128)
method463(null, false);
return (char) i_21_;
} |
f2133e05-4288-4e23-995d-fa42e6a2dd26 | 1 | protected static int toUShort(final byte b1, final byte b2) {
int x = (short) (Instruction.toUByte(b1) << 8)
| Instruction.toUByte(b2);
if (x < 0) {
x += 0x10000;
}
return x;
} |
d21e04d0-f6a5-41ca-8d0b-281f79e1a3df | 6 | public int trap(int[] A) {
// Start typing your Java solution below
// DO NOT write main() function
int max = 0;
int n = A.length;
for (int i = 0; i < n; i++) {
if (A[i] > A[max])
max = i;
}
int tmpH = 0;
int res = 0;
for (int i = 0; i < max; i++) {
if (tmpH > A[i])
res += (tmpH - A[i]);
else
tmpH = A[i];
}
tmpH = 0;
for (int i = n - 1; i > max; i--) {
if (tmpH > A[i])
res += (tmpH - A[i]);
else
tmpH = A[i];
}
return res;
} |
587e41f2-de03-41b5-9abf-4fd972ed58a8 | 3 | public static void main(String args[]) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
System.out.println(">Enter your new file name:");
String fileName = in.nextLine() + ".txt";
boolean exist = false;
String[] files = FileLister.getFilesArrayString();
for (int i = 0; i < files.length; i++) {
if (files[i].equals(fileName)) {
exist = true;
}
}
if (!exist) {
String output = "C:\\Files\\"+fileName;
PrintWriter out = new PrintWriter(output);
out.print("");
out.close();
} else {
System.out.println(">File already exists");
}
} |
80c4dc98-d3d0-4ed4-9ff5-28ed7cc8c156 | 5 | double getKth(int[] a, int[] b, int k) {
int m = a.length;
int n = b.length;
if (n == 0)
return a[k - 1];
if (m == 0)
return b[k - 1];
if (k == 1)
return Math.min(a[0], b[0]);
// divide k into two parts
int p1 = Math.min(k / 2, m);
int p2 = Math.min(k - p1, n);
if (a[p1 - 1] < b[p2 - 1])
return getKth(Arrays.copyOfRange(a, p1, m), b, k - p1);
else if (a[p1 - 1] > b[p2 - 1])
return getKth(a, Arrays.copyOfRange(b, p2, n), k - p2);
else
return a[p1 - 1];
} |
7edb61e2-ed60-4f87-9d03-90717413bfd5 | 6 | @Override
public void keyTyped(KeyEvent e) {
JTextField f = (JTextField) e.getSource();
// Only accept numbers and decimals in the average mark JTextField
if ( (!Character.isDigit( e.getKeyChar() )) && (e.getKeyChar() != '.') ) {
e.consume();
// Set and display a helpful tooltip
f.setToolTipText("Only numbers and decimals allowed");
try {
e.getComponent().dispatchEvent(new KeyEvent(e.getComponent(), KeyEvent.KEY_PRESSED,
System.currentTimeMillis(), InputEvent.CTRL_MASK,
KeyEvent.VK_F1, KeyEvent.CHAR_UNDEFINED));
} catch (Exception ex) {/* No need to do anything on Exception */}
}
// Only one period allowed in a decimal number
if (e.getKeyChar() == '.') {
String text = f.getText();
if ( ( text.indexOf('.') != -1 ) && ( text.indexOf('.') != text.length() ) ) {
e.consume();
}
}
} |
f26519d7-59c1-425e-98a3-e633fa4221e0 | 7 | public int trap(int[] height) {
int water = 0;
if (height.length < 3) {
return water;
}
// find max height and its position
int maxHeight = 0;
int maxHeightPos = 0;
for (int i = 0; i < height.length; i++) {
if (height[i] > maxHeight) {
maxHeight = height[i];
maxHeightPos = i;
}
}
// calculate water before max height
int preHeight = height[0];
for (int i = 1; i < maxHeightPos; i++) {
if (height[i] < preHeight) {
water += preHeight - height[i];
} else {
preHeight = height[i];
}
}
// calculate water after max height
preHeight = height[height.length - 1];
for (int i = height.length - 1; i > maxHeightPos; i--) {
if (height[i] < preHeight) {
water += preHeight - height[i];
} else {
preHeight = height[i];
}
}
return water;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.