text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) {
Dinosaur n = new Dinosaur();
n.f();
n.i = 40;
n.j++;
} | 0 |
private void saveCompletedLevel(String mapName) {
boolean createdNewFile = false;
try {
File file = new File(COMPLETED_TXT_PATH.toString());
if (!file.exists()) {
createdNewFile = file.createNewFile();
}
String mapUrl = COMPLETED_TXT_PATH.toString();
File inFile = new File(mapUrl);
// open input stream test.txt for reading purpose.
List<String> completedMaps = new ArrayList<String>();
BufferedReader bufferedReader = new BufferedReader(new FileReader(inFile));
try {
String thisLine = bufferedReader.readLine();
while (thisLine != null) {
completedMaps.add(thisLine);
thisLine = bufferedReader.readLine();
}
checkIfCompleted(completedMaps, mapName, file);
}finally {
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
if (createdNewFile){
System.out.println("Created an new completed.txt");
}
} | 4 |
public void expandPath(TreePath path) {
for(Object node : path.getPath()){
TreeItem parentItem = (TreeItem) node;
if(parentItem != path.getLastPathComponent() && !isExpanded(new TreePath(parentItem.getPath()))){
return;
}
}
super.expandPath(path);
} | 3 |
public void followWaypoint()
{
if(!close)
{
setWaypoint(targetX + (scrollX - state.get(9)), targetY + (scrollY - state.get(10))); //calculate speed and direction to waypoint (same as last turn)
double eachTurn; //turn this frame is a fraction of the total turn
if(toTurn>0)
{
eachTurn = Math.min(toTurn, maxTheta);
}
else eachTurn = Math.max(-maxTheta, toTurn); //limit by maximum theta
if(state.get(8)>=0 && eachTurn<=0 || state.get(8)<=0 && eachTurn>=0)
{
setTurn(eachTurn);
}
else setTurn(0);
}
else
{
state.set(2, 0.0);
state.set(3, 0.0);
setTurn(0);
}
} | 6 |
public String updateGradeItem() throws IOException {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(in);
DBConnector db = new DBConnector();
System.out.println("Updating an assignment");
System.out.println("Assignment ID : ");
int id = Integer.parseInt(keyboard.readLine());
System.out.println("Possible Points: ");
int possiblePoints = Integer.parseInt(keyboard.readLine());
System.out.println("Earned Points: ");
int earnedPoints = Integer.parseInt(keyboard.readLine());
try {
db.updateGradeItem(id, possiblePoints, earnedPoints);
return "Grade updated";
} catch (Exception e) {
return e.getMessage();
}
} | 1 |
public void disabledPeriodic()
{
if (System.currentTimeMillis() >= time + 20) {
time = System.currentTimeMillis();
if (oi.getGunS() > 0.5)
auton = "Left";
else if (oi.getGunS() < -0.5)
auton = "Right";
else
auton = "None";
Log.println(auton);
}
SmartDashboard.putString("Auton selector", auton);
Scheduler.getInstance().run();
} | 3 |
public void setLeft(PExp node)
{
if(this._left_ != null)
{
this._left_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._left_ = node;
} | 3 |
@Override
public boolean insert(DataRow row) {
String statement = "INSERT INTO " + row.getTableName();
String args = "";
String values = "";
boolean isFirst = true;
for(DataCell cell : row.row)
{
if(isFirst)
{
isFirst = false;
args += cell.getName();
values += "'" + cell.getValue() + "'";
} else {
args += ", " + cell.getName();
values += ", " + "'" + cell.getValue() + "'";
}
}
//System.out.println(args);
//System.out.println(values);
statement += "(" + args + ")" + " VALUES(" + values + ")";
try
{
Statement stat = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
stat.executeUpdate(statement);
return true;
} catch(Exception e) {
ErrorDialog errorDialog = new ErrorDialog(true, "Nastąpił błąd podczas wykonywania insert do bazy danych:\n" + e.getMessage(), "SqlServerLocalDatabaseConnector", "insert", "row, statement");
errorDialog.setVisible(true);
return false;
}
} | 3 |
public long getLong(int bits) throws IOException {
if (bits > 64) {
throw new IllegalArgumentException("Argument \"bits\" must be <= 64");
}
long res = 0;
if (endian == LITTLE_ENDIAN) {
for (int i = 0; i < bits; i++) {
if (getBit()) {
res |= (1L << i);
}
}
} else {
for (int i = bits - 1; i >= 0; i--) {
if (getBit()) {
res |= (1L << i);
}
}
}
return res;
} | 6 |
public Result execute(Command command) {
LabelDTO labelDTO = (LabelDTO) command.getCommandSource();
Account account;
account = accountDAO.getAccountByname(labelDTO.getAccount());
Set<Label> labels = account.getLabel();
//labels = account.getLabel();
for (Iterator<Label> it = labels.iterator(); it.hasNext();) {
Label label = it.next();
if (label.getName().equals(labelDTO.getName())) {
labelDAO.deleteLabel(label);
}
}
return result;
} | 2 |
protected String toLetter(String c) {
if(" ".equals(c)) return "space";
if("<".equals(c)) return "less then";
if(">".equals(c)) return "grater then";
if("&".equals(c)) return "ampersand";
if("\\".equals(c)) return "back slash";
if("/".equals(c)) return "slash";
if("'".equals(c)) return "quote";
if("\"".equals(c)) return "double quote";
return c;
} | 8 |
public void setId(long Id) {
this.Id = Id;
} | 0 |
final private boolean jj_3R_63() {
if (jj_scan_token(LPAREN)) return true;
if (jj_3R_29()) return true;
if (jj_scan_token(RPAREN)) return true;
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(88)) {
jj_scanpos = xsp;
if (jj_scan_token(87)) {
jj_scanpos = xsp;
if (jj_scan_token(73)) {
jj_scanpos = xsp;
if (jj_scan_token(70)) {
jj_scanpos = xsp;
if (jj_scan_token(40)) {
jj_scanpos = xsp;
if (jj_3R_108()) return true;
}
}
}
}
}
return false;
} | 9 |
private void checkWeekend() {
//Friday is 5
//Saturday is 6
//Sunday is 7
if (weekday == 5) {
infoList.add(bundle.getString("SaturdayTomorrow"));
tomorrowValid = false;
eventPresent = true;
} else if (weekday == 6) {
infoList.add(bundle.getString("SaturdayToday"));
todayValid = false;
tomorrowValid = false;
eventPresent = true;
} else if (weekday == 7) {
infoList.add(bundle.getString("SundayToday"));
todayValid = false;
eventPresent = true;
}
} | 3 |
@Override
public void handleNewConnection(Socket client) {
try {
new ChatGUI(client);
} catch (IOException e) {
System.out.println("Failed to connect!");
e.printStackTrace();
}
} | 1 |
@Test
public void nonceTest() throws IOException {
String nonce = "myUniqueNonce" + System.currentTimeMillis();
String result = null;
TeleSignRequest tr;
if(!timeouts && !isHttpsProtocolSet)
tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY);
else if(timeouts && !isHttpsProtocolSet)
tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, connectTimeout, readTimeout);
else if(!timeouts && isHttpsProtocolSet)
tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, HTTPS_PROTOCOL);
else
tr = new TeleSignRequest("https://rest.telesign.com", "/v1/phoneid/standard/" + PHONE_NUMBER, "GET", CUSTOMER_ID, SECRET_KEY, connectTimeout, readTimeout, HTTPS_PROTOCOL);
tr.setNonce(nonce);
assertNotNull(tr);
result = tr.executeRequest();
assertNotNull(result);
Gson gson = new Gson();
PhoneIdStandardResponse response = gson.fromJson(result, PhoneIdStandardResponse.class);
assertTrue(response.errors.length == 0);
result = tr.executeRequest();
assertNotNull(result);
response = gson.fromJson(result, PhoneIdStandardResponse.class);
assertTrue(response.errors[0].code == -30012);
} | 6 |
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} | 6 |
public Explosion(int x, int y , TankClient tc){
this.x = x;
this.y = y;
this.tc = tc;
} | 0 |
@Override
public void train(List<Instance> instances) {
// initialize w values
for (Instance instance : instances) {
for (Entry<Integer, Double> entry : instance.getFeatureVector().getVector().entrySet()) {
linearParam.add(entry.getKey(), 0.0);
}
}
int iter = 0;
while (iter < iters) {
iter ++;
for (Instance instance : instances) {
double y = Double.valueOf(instance.getLabel().toString()) * 2.0 - 1.0; // get label
double loss = y * MathUtilities.innerProduct(linearParam, instance);
if ( loss < 1) {
double tau = (1.0 -loss) / MathUtilities.innerProduct(instance.getFeatureVector(), instance);
for (Entry<Integer, Double> entry : instance.getFeatureVector().getVector().entrySet()) {
int key = entry.getKey();
linearParam.add(key, linearParam.get(key) + tau * y * instance.getFeatureVector().get(key));
}
}
}
}
} | 6 |
final byte getByte(int pos) {
int b0 = charAt(pos) - '0';
int b1 = charAt(pos + 1) - '0';
if (b0 > 9) {
b0 -= 7;
if (b0 > 16) {
b0 -= 32;
}
}
if (b1 > 9) {
b1 -= 7;
if (b1 > 16) {
b1 -= 32;
}
}
return (byte) ((b0 << 4) + b1);
} | 4 |
public Edge get(){
if(lastStack == null || Configuration.hasEdgeTypeChanged()){
lastStackTypeName = Configuration.getEdgeType();
lastStack = stacks.get(lastStackTypeName);
if(lastStack == null) {
lastStack = new Stack<Edge>();
stacks.put(Configuration.getEdgeType(), lastStack);
}
}
if(lastStack.empty()){
return null;
}
return lastStack.pop();
} | 4 |
@Override
public void run()
{
long time = System.nanoTime();
final double maxTick = 30.0 * gameSpeed;
double ns = 1000000000 / maxTick;
double delta = 0;
while(running)
{
long now = System.nanoTime();
delta += (now - time) / ns;
time = now;
if(delta >= 1)
{
tick();
delta--;
}
}
stop();
} | 2 |
@Override
public KThread nextThread()
{
boolean debug = false;
Lib.assertTrue(Machine.interrupt().disabled());
ThreadState winner = null;
if (queue.isEmpty())
{
return null;
}
if (debug) //ONLY FOR DEBUG! checking priority #'s correct
{
for (ThreadState t : queue)
{
if (winner == null)
{
winner = t;
}
else
{
if (t.getEffectivePriority() > winner.getEffectivePriority())
{
winner = t;
}
}
}
}
else
{
/**
* Based on the number tickets owned per thread, give each
* thread that many tickets then randomly choose a ticket
* and find the winner!
*
* Example) Threads have this many tickets: 1 1 3 4 1 1 2 1.
* Create an Array of [1 2 5 9 10 11 13] 2. Randomly choose
* winning ticket #9 -> 5th thread wins! 3. Randomly choose
* winning ticket #0 -> 1st thread wins! Note: Ticket #13
* can never be chosen!
*/
maxList.clear();
int counter = 0;
for (ThreadState t : queue)
{
counter += t.getEffectivePriority();
maxList.add(counter);
}
int winningTicket = rand.nextInt(counter);
for (int i = 0; i < maxList.size(); i++)
{
if (maxList.get(i) > winningTicket)
{
winner = queue.get(i);
break;
}
}
}
// =========================================
queue.remove(winner);
setActiveThread(winner);
winner.listOfQueues.remove(this);
return winner.getThread();
} | 8 |
public boolean getCollision(ArrayList<Tetromino> tetrominoArray)
{
// Can't use TetrisPanel's getArray()'s, because that will include
// itself.
ArrayList<Double> xArray = new ArrayList<Double>();
ArrayList<Double> yArray = new ArrayList<Double>();
for (Tetromino tetr : tetrominoArray)
if (tetr != this)
{
for (Block block : tetr.blockArray)
{
xArray.add(block.getXValue());
yArray.add(block.getYValue());
}
}
for (Block block : blockArray)
{
for (int i = 0; i < xArray.size(); i++)
{
if ((xArray.get(i) == block.getXValue())
&& (yArray.get(i) == (block.getYValue() + 40)))
{
return true;
}
}
}
for (Block block : blockArray)
if (block.getYValue() == 760)
return true;
return false;
} | 9 |
@Override
public Object getValueAt(int row, int col)
{
{
StockItem s = si.get(row);
switch (col)
{
case 0:
return s.getID();
case 1:
return s.getStockQuantity();
case 2:
return s.getLength();
case 3:
return s.getChargeNo();
case 4:
return s.getSleeveID();
case 5:
return s.getCoilTypeID();
}
return null;
}
} | 6 |
public void AddNew(ServerHandleConnect serverHandleConnect) {
this.curconnected++;
this.serverHandleConnectList.add(serverHandleConnect);
} | 0 |
public int getATK() {
return atk;
} | 0 |
public boolean vihkoTaynna(){
for(int i=0; i<pelaajat.size(); i++){
if(!pelaajat.get(i).getVihko().full()){
return false;
}
}
return true;
} | 2 |
public Menu getMenu() throws NoPagesException, InvalidMenuException{
if(style == null){
throw new InvalidMenuException("No style set");
}
if(pages.size() <= 0){
throw new NoPagesException();
}
Menu menu = new Menu();
menu.setStyle(style);
for(Page page : pages){
try{
menu.addPage(page);
}catch(PageAlreadyExistsException e){
throw new InvalidMenuException("Duplicate pages in menu");
}
}
menu.updatePages();
menu.setTitle(title);
menu.setColor(mainColor, titleColor, pageColor);
menu.setPrefix(prefix);
menu.setUsePrefix(usePrefix);
return menu;
} | 4 |
public JSONObject asJson() {
JSONObject obj = new JSONObject();
if (minValue != null) {
obj.put("min", new JSONNumber(minValue));
}
if (maxValue != null) {
obj.put("max", new JSONNumber(maxValue));
}
if (decimalPrecision != null) {
obj.put("tickDecimals", new JSONNumber(decimalPrecision));
}
if(isTimeAxis)
{
obj.put("mode", new JSONString("time"));
obj.put("timeformat", new JSONString(timeFormat));
JSONArray minTickSize = new JSONArray();
minTickSize.set(0, new JSONNumber(minTickLength));
minTickSize.set(1, new JSONString(this.minTickUnit.asString()));
obj.put("minTickSize", minTickSize);
}
else
{
obj.put("minTickSize", new JSONNumber(minTickLength));
}
if(axisMapping != null)
{
JSONArray ticks = new JSONArray();
int i = 0;
for(Integer k : axisMapping.keySet())
{
JSONArray t = new JSONArray();
t.set(0, new JSONNumber(k));
t.set(1, new JSONString(axisMapping.get(k)));
ticks.set(i++, t);
}
obj.put("ticks", ticks);
}
if (__formatter__ != null) {
JSONObject formatterFuncObj = new JSONObject(__formatter__);
obj.put("tickFormatter", formatterFuncObj);
}
if (__transform__ != null && __inverseTransform__ != null) {
JSONObject transformObj = new JSONObject(__transform__);
JSONObject inverseTransformObj = new JSONObject(__inverseTransform__);
obj.put("transform", transformObj);
obj.put("inverseTransform", inverseTransformObj);
}
return obj;
} | 9 |
static byte[] transferArray(byte[] buffer, int start, int x, byte[] hashArray, int hashStart, boolean hashToBuffer) {
if(buffer == null) {
return null;
}
int bufferPos = startPoint[x] + start;
int thisStep1 = step1[x];
int hashPos = hashStart;
for(int outer=0;outer<16;outer++) {
for(int mid=0;mid<16;mid++) {
for(int inner=0;inner<8;inner++) {
if(!hashToBuffer) {
hashArray[hashPos] = buffer[bufferPos];
} else {
buffer[bufferPos] = hashArray[hashPos];
}
hashPos++;
bufferPos++;
}
bufferPos+=thisStep1;
}
}
return buffer;
} | 5 |
private void updatePlayerList(Buffer stream, int count) {
while (stream.bitPosition + 10 < count * 8) {
int pId = stream.readBits(11);
if (pId == 2047)
break;
if (players[pId] == null) {
players[pId] = new Player();
if (playerAppearanceData[pId] != null)
players[pId]
.updatePlayerAppearance(playerAppearanceData[pId]);
}
localPlayers[localPlayerCount++] = pId;
Player player = players[pId];
player.lastUpdateTick = tick;
int observed = stream.readBits(1);
if (observed == 1)
playersObserved[playersObservedCount++] = pId;
int teleported = stream.readBits(1);
int x = stream.readBits(5);
if (x > 15)
x -= 32;
int y = stream.readBits(5);
if (y > 15)
y -= 32;
player.setPos(localPlayer.waypointX[0] + y,
localPlayer.waypointY[0] + x, teleported == 1);
}
stream.finishBitAccess();
} | 7 |
public static void main(String[] args) {
try {
CsvReader trips = new CsvReader("C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\InputFiles\\trips_updated.csv");
String allDates = "C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\TempFiles\\Temp1.csv";
String execptionCase = "C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\TempFiles\\Temp2.csv";
CsvWriter daysOutput = new CsvWriter(new FileWriter(allDates, true), ',');
CsvWriter exception = new CsvWriter(new FileWriter(execptionCase, true), ',');
//set headers to output file
daysOutput.write("TripStartDay");
daysOutput.write("TripEndDay");
daysOutput.endRecord();
exception.write("TripStartDay");
exception.write("TripEndDay");
exception.endRecord();
//read headers from input file
trips.readHeaders();
while (trips.readRecord())
{
String startTime = trips.get("starttime");
String endTime = trips.get("stoptime");
Date dt1 = new Date();
Date dt2 = new Date();
try {
dt1 = getDateFromString(startTime,"MM/dd/yyyy HH:mm");
dt2 = getDateFromString(endTime,"MM/dd/yyyy HH:mm");
daysOutput.write(Integer.toString(dt1.getDay()));
daysOutput.write(Integer.toString(dt2.getDay()));
daysOutput.endRecord();
if(dt1.getDay() != dt2.getDay()){
exception.write(Integer.toString(dt1.getDay()));
exception.write(Integer.toString(dt2.getDay()));
exception.endRecord();
}
} catch (Exception e) {
e.printStackTrace();
}
}
trips.close();
daysOutput.close();
exception.close();
//Write actual output to CSV in FinalFiles folder
String finalOutput = "C:\\Users\\ThejaSwarup\\Box Sync\\Fall 2014\\CS 424\\Project2\\FinalFiles\\BikesOutByDayOfWeek_Chicago.csv";
CsvWriter daysCount = new CsvWriter(new FileWriter(finalOutput, true), ',');
daysCount.write("Day");
daysCount.write("No_Of_Bikes");
daysCount.endRecord();
CsvReader temp1 = new CsvReader(allDates);
CsvReader temp2 = new CsvReader(execptionCase);
temp1.readHeaders();
temp2.readHeaders();
while (temp1.readRecord()){
days[Integer.parseInt(temp1.get("TripStartDay"))] += 1;
}
while (temp2.readRecord()){
days[Integer.parseInt(temp2.get("TripEndDay"))] += 1;
}
//write all counts
for(int index = 0;index< 7; index++){
daysCount.write(Integer.toString(index));
daysCount.write(Integer.toString(days[index]));
daysCount.endRecord();
}
daysCount.close();
temp1.close();
temp2.close();
System.out.println("Program Executed");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 8 |
public boolean isEatable() {
String s = GetResName();
if (s.indexOf("gfx/invobjs/bread") >= 0)
return true;
if (s.indexOf("gfx/invobjs/meat") >= 0)
return true;
if (s.indexOf("gfx/invobjs/mussel-boiled") >= 0)
return true;
return false;
} | 3 |
@Test
public void random_test() {
try{
double [][]mat= {{1.0,2.0}, {3.0,1.0}};
int m=2;
int n=2;
double[][]result = Matrix.random(m,n);
double exp[][]={{1.0,2.0},{3.0,1.0}};
Assert.assertNotSame(exp, result);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
} | 1 |
public void randomizeCurrentGeneration() {
Random random = new Random();
for (int row = 0; row < currentGeneration.getHeight(); row++) {
for (int col = 0; col < currentGeneration.getWidth(); col++) {
if (random.nextBoolean())
currentGeneration.resurrectCell(col, row);
}
}
} | 3 |
protected void processEndSimulation()
{
resList_.clear();
arList_.clear();
if (regionalList_ != null) {
regionalList_.clear();
}
if (globalResList_ != null) {
globalResList_.clear();
}
if (globalResARList_ != null) {
globalResARList_.clear();
}
if (userList_ != null) {
userList_.clear();
}
if (userARList_ != null) {
userARList_.clear();
}
} | 5 |
private final void method702(byte byte0, int i, Stream stream, int j) {
if (i != 1) {
if (i != 2) {
if (i != 3) {
if (i == 4) {
anInt1013 = -1;
}
} else {
aBoolean1020 = true;
}
} else {
anInt1016 = stream.readTriByte();
}
} else {
anInt1013 = stream.readUShort();
}
if (byte0 >= -49) {
method703(false, -36);
}
} | 5 |
public boolean equals(Token t) {
if(!(t.getType()==type)) {
return false;
}
if(!(t.getUnderlyingObject().equals(this.underlyingObject))) {
return false;
}
return true;
} | 2 |
public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sNumber1 = reader.readLine();
String sNumber2 = reader.readLine();
String sNumber3 = reader.readLine();
String sNumber4 = reader.readLine();
int n1 = Integer.parseInt(sNumber1);
int n2 = Integer.parseInt(sNumber2);
int n3 = Integer.parseInt(sNumber3);
int n4 = Integer.parseInt(sNumber4);
int m;
if (n1 < n2)
m = n2;
else m = n1;
if (m < n3)
m = n3;
if (m < n4)
m = n4;
System.out.println(m);
} | 3 |
private static void fillData(Sheet s, int rownum, ProcessedCell cell){
//Assume that a header was already generated
Row r = s.createRow(rownum);
String[] headers = ProcessedCell.getTags();
Cell c = null;
for(int i = 0; i < headers.length; i++){
c = r.createCell(i);
c.setCellValue(cell.getAttribute(headers[i]));
}
} | 1 |
public void newParamSet() {
for (OptParam op : opt_params) {
Param p = op.getParam();
double new_mean = random.nextDouble() * op.getRange() + p.getLower();
op.setMean(new_mean);
// Calculate new parameter values based on the random mean.
double[] pro_dev = op.getDev();
double[] new_val = new double[pro_dev.length];
double min = p.getLower();
double max = p.getUpper();
for (int j = 0; j < new_val.length; j++) {
new_val[j] = pro_dev[j] * new_mean;
if (new_val[j] > max) {
new_val[j] = max;
}
if (new_val[j] < min) {
new_val[j] = min;
}
}
// Update the Parameter objects with the new values
Util.setVals(new_val, p);
}
} | 4 |
private boolean crossingInternal(Point2DInt direction1, Point2DInt direction2) {
if (angles.size() < 2) {
return false;
}
final double angle1 = convertAngle(new LineSegmentInt(center, direction1).getAngle());
final double angle2 = convertAngle(new LineSegmentInt(center, direction2).getAngle());
Double last = null;
for (Double current : angles) {
if (last != null) {
assert last < current;
if (isBetween(angle1, last, current) && isBetween(angle2, last, current)) {
return false;
}
}
last = current;
}
final double first = angles.first();
if ((angle1 <= first || angle1 >= last) && (angle2 <= first || angle2 >= last)) {
return false;
}
return true;
} | 9 |
public String toString()
{
String ret = "";
try
{
ret = getLocation();
if( (ret.indexOf( "!" ) == -1) && (sheetname != null) )
{ // prepend sheetname
if( (sheetname.indexOf( ' ' ) == -1) && (sheetname.charAt( 0 ) != '\'') ) // 20081211 KSC: Sheet names with spaces must have surrounding quotes
{
ret = sheetname + "!" + ret;
}
else
{
ret = "'" + sheetname + "'!" + ret;
}
}
}
catch( Exception ex )
{
log.error( "PtgRef3d.toString() failed", ex );
}
return ret;
} | 5 |
@Override
public StringConverter<?> findConverter(Class<?> cls) {
if (cls.isArray()) {
if (cls == Long[].class) {
return LongArrayStringConverter.INSTANCE;
}
if (cls == Integer[].class) {
return IntArrayStringConverter.INSTANCE;
}
if (cls == Short[].class) {
return ShortArrayStringConverter.INSTANCE;
}
if (cls == Double[].class) {
return DoubleArrayStringConverter.INSTANCE;
}
if (cls == Float[].class) {
return FloatArrayStringConverter.INSTANCE;
}
}
return null;
} | 8 |
@Override
public List<List<String>> breakOutMudChatVs(String MUDCHAT, TriadList<String,String,Integer> behaviors)
{
final int mndex=behaviors.indexOfFirst(MUDCHAT);
String mudChatStr=(mndex<0)?"":(String)behaviors.get(mndex).second;
if(mudChatStr.startsWith("+"))
mudChatStr=mudChatStr.substring(1);
final List<String> rawMCV=CMParms.parseSemicolons(mudChatStr,true);
final List<List<String>> mudChatV=new Vector<List<String>>();
String s=null;
List<String> V=new Vector<String>();
mudChatV.add(V);
for(int r=0;r<rawMCV.size();r++)
{
s=rawMCV.get(r);
if(s.startsWith("(")&&s.endsWith(")"))
{
if(V.size()>0)
{
V=new Vector<String>();
mudChatV.add(V);
}
s=s.substring(1,s.length()-1);
}
V.add(s);
}
if(V.size()==0)
mudChatV.remove(V);
return mudChatV;
} | 7 |
public void itemExpanded(TreeItem item){
if(item == tree.getRoot()){return;}
expand(((FilePathTreeItem) item).getFilePath());
for(int i=0; i<item.getChildCount(); i++){
FilePathTreeItem childItem = (FilePathTreeItem) item.getChildAt(i);
if(childItem.isLeaf()){continue;}
try{
if(expanded.get(childItem.getFilePath())){
childItem.setExpanded(true);
}
} catch(NullPointerException e){}
}
} | 5 |
public Map<Integer, Integer> getCountReps(Map<String, Integer> map) {
List<Integer> list = new ArrayList<>(map.values());
Map<Integer, Integer> reps = new TreeMap<>();
Integer first = 1;
Integer current;
for (Integer e : list) {
if (reps.containsKey(e)) {
current = reps.get(e);
current++;
reps.put(e, current);
} else {
reps.put(e, first);
}
}
return reps;
} | 2 |
public static void main(String args[]){
int op;
do{
System.out.println("\n\n1- Agregar Servidor");
System.out.println("2- Agregar Entry");
System.out.println("3- Navegar");
System.out.println("4- Ver Detalle");
System.out.println("5- Consultar DNS");
System.out.println("6- Salir");
System.out.print("Escoja Opcion: ");
op = lea.nextInt();
try{
switch( op ){
case 1:
System.out.println("Ingrese tipo servidor HTTP o DNS: ");
agregarServidor( TipoProtocolo.valueOf(lea.next()) );
break;
case 2:
System.out.println("Ingrese el Numero IP: ");
agregarEntry( lea.next() );
break;
case 3:
System.out.print("URL: http:\\\\");
navegar( lea.next() );
break;
case 4:
System.out.println("Ingrese tipo servidor HTTP o DNS: ");
detalles( TipoProtocolo.valueOf(lea.next()) );
break;
case 5:
System.out.println("Ingrese Url o ip: ");
consultaDNS( lea.next() );
}
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
}while( op!= 6 );
} | 7 |
protected void readAllocation() throws DecoderException
{
// start to read audio data:
for (int i = 0; i < num_subbands; ++i)
subbands[i].read_allocation(stream, header, crc);
} | 1 |
public Boolean loadPlayer(String file) {
boolean test = false;
if (test || m_test) {
System.out.println("Loader :: loadPlayer() BEGIN");
}
m_valid = false;
m_playerInfo = new String[PLAYER_INFO_SIZE];
m_hashString = "";
try {
setFile(file);
m_in = new Scanner(this.getFile()); // may throw exception
m_in.useDelimiter(",");
//try reading file
try {
//read the file
for (int x = 0; x < m_playerInfo.length; ++x) {
if (m_in.hasNext()) {
m_playerInfo[x] = m_in.next();
m_hashString += m_playerInfo[x] + ",";
}
}
m_hash = m_hashString.hashCode();
m_in.reset();
if (m_in.hasNext()) {
String b = m_in.next();
int readHash = 0;
readHash = Integer.parseInt(b.substring(1));
m_valid = (m_hash == readHash);
}
}finally {
m_in.close();
}
} catch (Exception exc) {
System.err.println("Error Reading File");
}
if (test || m_test) {
System.out.println("Loader :: loadPlayer() END");
}
return m_valid;
} | 8 |
@Override
public Object drawCell(mxCellState state)
{
Map<String, Object> style = state.getStyle();
if (state.getAbsolutePointCount() > 1)
{
List<mxPoint> pts = state.getAbsolutePoints();
// Transpose all points by cloning into a new array
pts = mxUtils.translatePoints(pts, translate.x, translate.y);
drawLine(pts, style);
}
else
{
int x = (int) state.getX() + translate.x;
int y = (int) state.getY() + translate.y;
int w = (int) state.getWidth();
int h = (int) state.getHeight();
if (!mxUtils.getString(style, mxConstants.STYLE_SHAPE, "").equals(
mxConstants.SHAPE_SWIMLANE))
{
drawShape(x, y, w, h, style);
}
else
{
int start = (int) Math.round(mxUtils.getInt(style,
mxConstants.STYLE_STARTSIZE,
mxConstants.DEFAULT_STARTSIZE)
* scale);
// Removes some styles to draw the content area
Map<String, Object> cloned = new Hashtable<String, Object>(
style);
cloned.remove(mxConstants.STYLE_FILLCOLOR);
cloned.remove(mxConstants.STYLE_ROUNDED);
if (mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true))
{
drawShape(x, y, w, start, style);
drawShape(x, y + start, w, h - start, cloned);
}
else
{
drawShape(x, y, start, h, style);
drawShape(x + start, y, w - start, h, cloned);
}
}
}
return null;
} | 3 |
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
} | 3 |
public void writeCSV(Collection<?> entities, String fileName, boolean override) throws ParsingException,
ClassValidationException, ConverterException {
if (configuration == null) {
throw new NullPointerException("Initialize engine with init method first!");
}
StringBuilder filePath = new StringBuilder();
filePath.append(configuration.getCSVDirectory());
if (configuration.getCSVDirectory().charAt(configuration.getCSVDirectory().length() - 1) != '/'
&& configuration.getCSVDirectory().charAt(configuration.getCSVDirectory().length() - 1) != '\\') {
filePath.append("/");
}
filePath.append(fileName).append(".").append(configuration.getCSVExtension());
File file = new File(filePath.toString());
if (file.exists() && !override) {
throw new ParsingException("File already exist and override is set to false");
}
mappingEngine.mapEntityToCSV(entities, file);
} | 6 |
private boolean correctChar(char a)
{
if (a >= '0' && a <= '9') {
return true;
}
if (a == 'A') {
return true;
} else if (a == 'B') {
return true;
} else if (a == 'C') {
return true;
} else if (a == 'D') {
return true;
} else if (a == 'E') {
return true;
} else if (a == 'F') {
return true;
} else {
return false;
}
} | 8 |
public Account create ()
{
org.omg.CORBA.portable.InputStream $in = null;
try {
org.omg.CORBA.portable.OutputStream $out = _request ("create", true);
$in = _invoke ($out);
Account $result = AccountHelper.read ($in);
return $result;
} catch (org.omg.CORBA.portable.ApplicationException $ex) {
$in = $ex.getInputStream ();
String _id = $ex.getId ();
throw new org.omg.CORBA.MARSHAL (_id);
} catch (org.omg.CORBA.portable.RemarshalException $rm) {
return create ( );
} finally {
_releaseReply ($in);
}
} // create | 2 |
@Test
public void getSurplus() {
AmateurAthlete test = null;
AmateurAthlete test1 = null;
try {
test = new AmateurAthlete("Franz", 3);
test1 = new AmateurAthlete("Karl", 5);
} catch (Exception e) {
// expected
}
try {
AmateurAthlete test3 = new AmateurAthlete("Sepp", 12);
} catch (ValueException e) {
// excepted
} catch (Exception e) {
fail("Unexpected Exception");
}
try {
AmateurAthlete test4 = new AmateurAthlete("Tony", -5);
} catch (ValueException e) {
// excepted
} catch (Exception e) {
fail("Unexpected Exception");
}
assertEquals(210, test.getSurplus(), 0);
assertEquals(150, test1.getSurplus(), 0);
} | 5 |
public void assemble()
throws MbiException, IOException {
if(deBruijnGraph == null)
System.out.println("graph NULL");
// System.out.println("edges: " + deBruijnGraph.getEdgeCount());
// System.out.println("vertices: " + deBruijnGraph.getVertexCount());
List<String> path = deBruijnGraph.findEulerPath_FleuryAlg();
if (path != null && path.size() > 0) {
assembledSequence = pathToGenome(path);
} else {
throw new MbiException("Returned empty or null Euler path!");
}
} | 3 |
public static void main(String args[]) {
String players[] = new String[4];
for (int i = 1; i <= 4; i++) {
players[i-1] = "P" + i;
}
StringBuilder playbackString = new StringBuilder();
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String string;
try {
while((string = reader.readLine()) != null)
playbackString.append(string);
} catch (Exception e) {
System.err.println("ERROR: game player failed while reading game " +
"playback string.");
System.exit(1);
}
CLViewer c = new CLViewer(players, playbackString.toString().trim());
c.show();
} | 3 |
public void updateMemory() {
DecimalFormat format = new DecimalFormat("0.0");
Runtime rt = java.lang.Runtime.getRuntime();
float maxMemory = rt.maxMemory() / (1024f * 1024f);
float totalUsed = (rt.totalMemory() - rt.freeMemory()) / (1024f * 1024f);
float docMem = 0;
float undoMem = 0;
CPArtwork artwork = controller.getArtwork();
if (artwork != null) {
docMem = artwork.getDocMemoryUsed() / (1024f * 1024f);
undoMem = artwork.getUndoMemoryUsed() / (1024f * 1024f);
}
if ((docMem + undoMem) / maxMemory > .5) {
memory.setForeground(Color.RED);
} else {
memory.setForeground(Color.BLACK);
}
String zerofiller = "";
if (totalUsed < 10) zerofiller = "0";
memory.setText(CPMainGUI.language.getString("status_edit_mem") +
": " + zerofiller + format.format(totalUsed) + "/" + format.format(maxMemory) + ",D"
+ format.format(docMem) + " U" + format.format(undoMem));
} | 3 |
private static void missingNumber(int[] array) {
int startingTerm = array[0];
int commonDiff = array[1] - startingTerm;
int currentTerm = startingTerm;
for (int i = 0; i < array.length; i++) {
if (currentTerm != array[i]) {
//System.out.println(currentTerm);
//System.out.println(array[i]);
System.out.println(currentTerm);
break;
} else {
currentTerm += commonDiff;
}
}
} | 2 |
public String getPredictedThrow()
{
if(computerResponse == 0)
return "Scissors";
else if(computerResponse == 1)
return "Rock";
else
return "Paper";
} | 2 |
public int maxProfit(int[] stations, int demand) {
if(stations == null || stations.length == 0 || demand < 1) {
throw new IllegalArgumentException("error");
}
Comparator<Integer> comp = new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return b - a;
}
};
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(10, comp);
int total = 0;
for(int ele : stations) {
maxHeap.offer(ele);
total += ele;
}
if(total < demand) {
throw new IllegalArgumentException("error");
}
int cur = maxHeap.poll();
int max = 0;
while(demand > 0 && maxHeap.size() > 0) {
int next = maxHeap.peek();
if(next <= cur) {
max += cur;
cur--;
demand--;
}
else {
int temp = cur;
cur = maxHeap.poll();
max += cur;
cur--;
demand--;
maxHeap.offer(temp);
}
}
if(demand != 0) {
throw new IllegalArgumentException("error");
}
return max;
} | 9 |
public ExportTrackingResponse exportTrackings(ParametersTrackingExport parameters)
throws AftershipAPIException,IOException,ParseException,JSONException{
List<Tracking> trackingList = null;
String requestParams = parameters.generateQueryString();
JSONObject response = this.request("GET","/trackings/exports" + requestParams, null);
String cursor = response.getJSONObject("data").getString("cursor");
JSONArray trackingJSON = response.getJSONObject("data").getJSONArray("trackings");
if(trackingJSON.length() > 0) {
trackingList = new ArrayList<Tracking>();
for (int i = 0; i < trackingJSON.length(); i++) {
trackingList.add(new Tracking(trackingJSON.getJSONObject(i)));
}
}
return new ExportTrackingResponse(trackingList, cursor);
} | 2 |
public static Cons cppTranslateFunctionCall(Cons tree, MethodSlot method) {
{ Symbol functionname = ((Symbol)(tree.value));
Cons functionargs = Cons.copyConsList(tree.rest);
Stella_Object firstarg = functionargs.value;
MethodSlot function = ((method != null) ? method : Symbol.lookupFunction(functionname));
Cons operator = Symbol.cppLookupOperatorTable(functionname.softPermanentify());
Cons otree = null;
if ((functionname == Stella.SYM_STELLA_GET_SYM) ||
((functionname == Stella.SYM_STELLA_GET_KWD) ||
(functionname == Stella.SYM_STELLA_GET_SGT))) {
if (Surrogate.subtypeOfIntegerP(Stella_Object.safePrimaryType(firstarg))) {
{ IntegerWrapper firstarg000 = ((IntegerWrapper)(firstarg));
return (Symbol.cppTranslateHardcodedSymbolReference(functionname, firstarg000.wrapperValue));
}
}
else {
}
}
else {
}
functionargs = functionargs.concatenate(MethodSlot.cppYieldUnusedDummyArgs(function, functionargs), Stella.NIL);
if (operator != null) {
otree = Cons.cppTranslateOperatorCall(operator, functionargs, functionargs.length());
}
else {
otree = Cons.list$(Cons.cons(Stella.SYM_STELLA_CPP_FUNCTION_CALL, Cons.cons(Cons.list$(Cons.cons(Stella.SYM_STELLA_CPP_IDENT, Cons.cons(MethodSlot.cppTranslateFunctionName(function, true), Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(((((BooleanWrapper)(KeyValueList.dynamicSlotValue(function.dynamicSlots, Stella.SYM_STELLA_METHOD_VARIABLE_ARGUMENTSp, Stella.FALSE_WRAPPER))).wrapperValue &&
(!MethodSlot.passVariableArgumentsAsListP(function))) ? Cons.cppTranslateVariableLengthActuals(functionargs, function) : Cons.cppTranslateActualParameters(functionargs)), Cons.cons(Stella.NIL, Stella.NIL)))));
}
return (otree);
}
} | 8 |
public QuickFind(int n){
id = new int[n];
for(int i=0;i<n;i++)
id[i]=i;
} | 1 |
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
minSize += 3;
maxSize += 3;
if (mv != null) {
mv.visitFieldInsn(opcode, owner, name, desc);
}
} | 1 |
private int IncDigit(int number, int pos)
{
int term = 1;
int i;
for (i = 0; i < pos; i++) term *= 10;
return number + term;
} | 1 |
public void saveScore(String pseudo, int time, Calendar date, String gD) {
Score newScore = new Score(pseudo, time, date);
ObjectOutputStream os = null;
try {
this.removeLastElement();
os = new ObjectOutputStream(new FileOutputStream(gD+".ser", false));
bestScores.add(newScore);
Collections.sort(bestScores);
os.writeObject(bestScores);
} catch (IOException ioEx) {
Logger.getLogger(ScoresModel.class.getName()).log(Level.SEVERE, null, ioEx);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException ex) {
Logger.getLogger(ScoresModel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} | 3 |
protected void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 371);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
meaningsLabel = new JLabel("New label");
meaningsLabel.setFont(new Font("Verdana", Font.PLAIN, 12));
kunReadingLabel = new JLabel("New label");
onReadingLabel = new JLabel("New label");
kanjiLabel = new JLabel("New label");
kanjiLabel.setHorizontalAlignment(SwingConstants.CENTER);
kanjiLabel.setFont(new Font("Meiryo", Font.PLAIN, 70));
JButton btnPrev = new JButton("Prev");
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dict().previous();
update();
}
});
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dict().next();
update();
}
});
meaningsLabel.setHorizontalAlignment(SwingConstants.CENTER);
kunReadingLabel.setFont(new Font("Meiryo UI", Font.BOLD, 14));
kunReadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
onReadingLabel.setFont(new Font("Meiryo UI", Font.BOLD, 14));
onReadingLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel = new JLabel("Kun");
lblNewLabel_1 = new JLabel("Means");
lblNewLabel_2 = new JLabel("On");
JButton btnRandom = new JButton("Random");
btnRandom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dict().random();
update();
}
});
btnNewButton = new JButton("test");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
List<Kanji> ks = dict().queryKanjis(
new Condition(Criterias.MOST_SHARED_MEANINGS_WITH_KANJI, dict().current())
);
if(ks != null) {
Logger.log("found " + ks.size() + " kanjis which matches criterias");
dict().setIndex(dict().getIndexOf(ks.get(0)));
update();
} else {
Logger.log("No kanjis with similar meanings found (surprising huh ?)");
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnLauchTestWindow = new JButton("Lauch test window");
btnLauchTestWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new TestWindow();
}
});
btnSettings = new JButton("Settings");
btnSettings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new SettingsWindow();
}
});
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(kanjiLabel, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
.addComponent(lblNewLabel_1, GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE)
.addComponent(lblNewLabel_2, GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(onReadingLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(meaningsLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(kunReadingLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnPrev, GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnSettings, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
.addComponent(btnRandom, GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(btnLauchTestWindow, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnNext, GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE))))
.addContainerGap())
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(kanjiLabel, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(kunReadingLabel, GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
.addComponent(lblNewLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(meaningsLabel, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_1))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(onReadingLabel, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addComponent(lblNewLabel_2))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNext)
.addComponent(btnPrev)
.addComponent(btnRandom))
.addGap(8)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNewButton)
.addComponent(btnLauchTestWindow)
.addComponent(btnSettings))
.addContainerGap())
);
frame.getContentPane().setLayout(groupLayout);
} | 3 |
protected static void removeCompressTag(MediaWiki wiki, String fileFullName) throws MediaWiki.BlockException {
while (true) {
try {
MediaWiki.EditToken editToken = wiki.startEdit(fileFullName);
// Remove the {{compress}} tag from the description page.
Iterator<MediaWiki.Revision> descriptionPageRevisions = wiki.getLastRevision(true, fileFullName);
if (descriptionPageRevisions.hasNext()) {
MediaWiki.Revision descriptionPageRevision = descriptionPageRevisions.next();
if (descriptionPageRevision == null)
throw new MediaWiki.MissingPageException(fileFullName);
String oldText = descriptionPageRevision.getContent(), newText = compressTagRemover.matcher(oldText).replaceAll("");
if (!oldText.equals(newText)) {
wiki.replacePage(editToken, newText, "-Template:Compression", true /*- bot */, true /*- minor */);
log.log(Level.INFO, "Successfully edited {0}", fileFullName);
}
}
break;
} catch (final MediaWiki.ActionDelayException e) {
log.log(Level.WARNING, "Edition of " + fileFullName + " delayed", e);
shortDelay();
// retry later
} catch (final MediaWiki.ConflictException shouldNotHappen) {
log.log(Level.WARNING, "Received a conflict while editing " + fileFullName + "; retrying", shouldNotHappen);
// retry immediately
} catch (final MediaWiki.BlockException e) {
// fatal
throw e;
} catch (final IOException ioe) {
log.log(Level.WARNING, "Network error occurred while editing " + fileFullName + "; retrying shortly", ioe);
shortDelay();
// retry later
} catch (final MediaWiki.MediaWikiException mwe) {
log.log(Level.WARNING, "Edition of " + fileFullName + " failed", mwe);
break;
}
}
} | 9 |
*/
public void setSplashBackgroundColor(String s) {
String prevText = IOSImageUtil.isNullOrWhiteSpace(this.splashBackgroundColor.getText()) ? PLACEHOLDER_SPLASH_BGCOL : this.splashBackgroundColor.getText();
Color col = null;
if (!IOSImageUtil.isNullOrWhiteSpace(s)) {
while (s.length() < 6) s = "0".concat(s);
if (s.length() > 8) s = s.substring(0, 8);
if (s.length() == 7) s = "0".concat(s);
try {
col = new Color(Long.valueOf(s, 16).intValue(), true);
splashBackgroundColor.setText(s);
splashBackgroundColor.setBackground(new Color(col.getRed(), col.getGreen(), col.getBlue()));
float[] hsb = Color.RGBtoHSB(col.getRed(), col.getGreen(), col.getBlue(), null);
splashBackgroundColor.setForeground(new Color(Color.HSBtoRGB(hsb[0], 1.0f - hsb[1], 1.0f - hsb[2])));
splashImage.setBackground(splashBackgroundColor.getBackground());
splashImage.setForeground(splashBackgroundColor.getForeground());
ipadLaunchImage.setBackground(splashImage.getBackground());
} catch (Exception ex) {
ex.printStackTrace();
splashBackgroundColor.setForeground(COLOR_DARK_GRAY);
splashBackgroundColor.setBackground(Color.WHITE);
splashImage.setBackground(null);
splashImage.setForeground(COLOR_DARK_GRAY);
ipadLaunchImage.setBackground(BGCOLOR_GRAY);
}
}
if (col == null) {
splashBackgroundColor.setText(PLACEHOLDER_SPLASH_BGCOL);
splashBackgroundColor.setForeground(COLOR_DARK_GRAY);
splashBackgroundColor.setBackground(Color.WHITE);
splashImage.setBackground(null);
splashImage.setForeground(COLOR_DARK_GRAY);
ipadLaunchImage.setBackground(BGCOLOR_GRAY);
}
ipadLaunchImage.setForeground(splashImage.getForeground());
if (!prevText.equals(this.splashBackgroundColor.getText())) {
this.setStorePropertiesRequested(true);
}
} | 8 |
static boolean isStandardProperty(Class clazz) {
return clazz.isPrimitive() ||
clazz.isAssignableFrom(Byte.class) ||
clazz.isAssignableFrom(Short.class) ||
clazz.isAssignableFrom(Integer.class) ||
clazz.isAssignableFrom(Long.class) ||
clazz.isAssignableFrom(Float.class) ||
clazz.isAssignableFrom(Double.class) ||
clazz.isAssignableFrom(Character.class) ||
clazz.isAssignableFrom(String.class) ||
clazz.isAssignableFrom(Boolean.class);
} | 9 |
private static void attackColonyAnt(Ant ant) {
int XLoc = ant.getLocationX();
int YLoc = ant.getLocationY();
int randNum = RandomNumGen.randomNumber(0, 3);
// 50% Chance of killing an ant in the same node as the bala
// If the number 1 or 3 is generated, the attack is successful and an ant is killed
if (randNum == 1 || randNum == 3) {
// Iterates through the linked list of colony ants until it find the first ant
// whose location is in the same node as the attacking bala ant
for (Ant colonyAnt : AntColony.activeAnts) {
// Bala Ant kills queen and ends sim if in the same node
if (XLoc == 13 && YLoc == 13) {
AntColony.activeAnts.getFirst().setAlive(false);
AntColony.endSim = true;
return;
}
// Bala Ant kills a colony ant
else if (colonyAnt.getLocationX() == XLoc && colonyAnt.getLocationY() == YLoc) {
colonyAnt.setAlive(false);
UpdateIcons.removeAntIcon(colonyAnt);
AntColony.activeAnts.remove(colonyAnt);
return;
}
}//end for loop
}
return;
} | 7 |
private void loadPlugins() {
print("Loading modules");
File pluginsDir = new File(homeDir, "plugins");
// Create plugins folder if it doesn't exist
if (!pluginsDir.isDirectory()) {
pluginsDir.mkdir();
}
// Scan for plugins
File[] pluginFiles = pluginsDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File arg0, String arg1) {
return arg1.endsWith(".jar");
}
});
if (pluginFiles.length == 0) {
print("ERROR: No modules were loaded! LAURA will have no functionality!");
exit();
}
// Iterate through .jar files
JarFileLoader classLoader;
JarFile jarFile;
for (File plugin: pluginFiles) {
try {
classLoader = new JarFileLoader(new URL[]{plugin.toURI().toURL()});
jarFile = new JarFile(plugin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
continue;
}
// Search through the JAR for class files
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry element = entries.nextElement();
if (element.getName().endsWith(".class")) {
try {
// Instantiate a module and add it to Laura.modules
Class<?> c = Class.forName(
element.getName().replaceAll(".class", "").replaceAll("/", "."),
true, classLoader
);
Module m = (Module)c.newInstance();
m.init(this);
modules.add(m);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException | ClassCastException | IllegalAccessException e) {
// Class isn't a module. No need to panic.
}
}
}
}
print("Successfully loaded " + modules.size() + " modules");
// Add the DefaultModule last - it simply says the command was not understood.
Module defaultModule = new DefaultModule();
defaultModule.init(this);
modules.add(defaultModule);
} | 9 |
public void dfs(Graph G, int v)
{
marked[v] = true;
preAnyAdjacentVerticesVisit(G, v);
for (int w : G.adj(v))
if (!marked[w])
{
preAdjacentVertexVisit(v, w);
dfs(G, w);
postAdjacentVertexVisit(v, w);
}
} | 2 |
private static void init() {
Class<Selenium> selC = Selenium.class;
for (Method m : selC.getMethods()) {
if ("void".equals(m.getReturnType().toString())
||"boolean".equals(m.getReturnType().toString())
|| m.getReturnType().isAssignableFrom(String.class)) {
Class<?>[] types = m.getParameterTypes();
if (types.length == 0) {
methods.put(m.getName(), m);
continue;
}
for (Class<?> t : types) {
if (!t.isAssignableFrom(String.class)) {
continue;
}
}
methods.put(m.getName(), m);
}
}
} | 9 |
public boolean writeMsg (String sender,String message) {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance();
String date = " Sent on-" + dateFormat.format(cal.getTime());
String text = message;
String Msg = sender + ": " + text + date;
BufferedWriter writer = null;
boolean status = false;
try {
FileWriter fr = new FileWriter("./ChatHistory.txt",true);
writer = new BufferedWriter(fr);
writer.append(Msg);
writer.append("<br>");
writer.newLine();
status = true;
}
catch (IOException e) {
System.err.println(e);
status = false;
} finally
{
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
return status;
} | 3 |
public static ArrayList<CubeNode> getSuccessors(CubeNode node) {
ArrayList<CubeNode> successors = new ArrayList<CubeNode>();
for (Map.Entry<Character, int[]> face : Cube.FACES.entrySet()) {
// Make a clockwise turn
char[] newState = Cube.rotate(node.state, face.getKey(), 1);
// Encode the corner
int encodedCorner = Integer.parseInt(Cube.encodeCorners(newState));
// Encode the edges
String encodedEdges = Cube.encodeEdges(newState);
int encodedEdgeSetOne = Integer.parseInt(encodedEdges.substring(0, 6));
int encodedEdgeSetTwo = Integer.parseInt(encodedEdges.substring(6, 12));
// Find all of the heuristic values for the given corner,
// and two edge sets
int[] possibleHeuristics = new int[3];
possibleHeuristics[0] = IDAStar.corners[encodedCorner];
possibleHeuristics[1] = IDAStar.edgesSetOne[encodedEdgeSetOne];
possibleHeuristics[2] = IDAStar.edgesSetTwo[encodedEdgeSetTwo];
// Find the maximum of the 3 heuristics as per the details of Korf's paper
int max = possibleHeuristics[0];
for (int i = 1; i < possibleHeuristics.length; i++) {
if (possibleHeuristics[i] > max) {
max = possibleHeuristics[i];
}
}
// Add the rotated state and it's heuristic value to the successors
successors.add(new CubeNode(newState, IDAStar.corners[encodedCorner], node.path + face.getKey() + "1")) ;
}
return successors;
} | 3 |
public void populateMap() throws FroshProjectException {
// Get the list of IDs
//
String idList = FroshProjectConfig.getProperty("WorldMap.ids");
// Log a message
//
FroshProject.getLogger().log(Level.FINE,
"List of Element ids " + idList);
// Check the presence of the list
//
if (idList == null) {
throw new FroshProjectException(
FroshProjectExceptionConfig.MAP_MISSING_IDS, null);
}
// Store it as an Integer list
//
List<Integer> ids = new LinkedList<Integer>();
for (String s : idList.split(";")) {
ids.add(Integer.parseInt(s));
}
// Create all the Elements
//
Map<String, Object> configuration;
Integer elementX, elementY;
Element currentElement;
for (Integer id : ids) {
// Get the configuration for that Element
//
configuration = FroshProjectConfig.getElementConfig(id);
if (configuration == null) {
throw new FroshProjectException(
FroshProjectExceptionConfig.ELEMENT_MISSING_CONFIG,
null);
}
// Get its location
//
elementX = (Integer) configuration.get("positionX");
elementY = (Integer) configuration.get("positionY");
// Create the Element
//
Class<? extends Element> elementClass;
try {
elementClass = ElementType.valueOf(
(String) configuration.get("type"))
.getAssociatedClass();
currentElement = elementClass.getConstructor(Integer.class,
Map.class).newInstance(id, configuration);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e1) {
throw new FroshProjectException(
FroshProjectExceptionConfig.ELEMENT_INVALID_CONFIG,
null, id.toString());
}
// Put the Element in the matrix
//
try {
population[elementX][elementY] = currentElement;
} catch (Exception e) {
throw new FroshProjectException(
FroshProjectExceptionConfig.MAP_INVALID_ELEMENT_LOCATION,
e, id.toString());
}
}
} | 7 |
protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (tabSize - (column % tabSize));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
} | 6 |
public static void main(String args[]) {
Gongming gongming = new Gongming(merchantId, merchantSecret);
try {
String userIdentityNumber = "1" + String.format("%017d", new Random().nextInt(1000000000));
logger.log(Level.INFO, "创建理财账户");
CreateUserRequest createUserRequest = new CreateUserRequest(
merchantId, // 商户号
"18680008813", // 手机号
userIdentityNumber, // 身份证号
"ManagerOfMoney" // 真实姓名
);
CreateUserResponse createUserResponse = gongming.createUser(createUserRequest);
logger.log(Level.INFO, "创建理财账户成功,理财账户号" + createUserResponse.userId);
Long userId = createUserResponse.userId;
logger.log(Level.INFO, "根据身份证号查询理财账户");
QueryUserByIdentityNumberRequest queryUserByIdentityNumberRequest = new QueryUserByIdentityNumberRequest(
merchantId, // 商户号
userIdentityNumber // 身份证号
);
QueryUserByIdentityNumberResponse queryUserByIdentityNumberResponse = gongming.queryUserByIdentityNumber(
queryUserByIdentityNumberRequest);
logger.log(Level.INFO, "根据身份证号查询理财账户成功,理财账户号为" + queryUserByIdentityNumberResponse.user.id);
logger.log(Level.INFO, "查询理财计划");
QueryPlansRequest queryPlansRequest = new QueryPlansRequest(
merchantId // 商户号
);
QueryPlansResponse queryPlansResponse = gongming.queryPlans(queryPlansRequest);
logger.log(Level.INFO, "查询理财计划成功,返回理财计划" + queryPlansResponse.plans.size() + "个");
if (queryPlansResponse.plans.size() == 0) {
logger.log(Level.INFO, "当前没有可购买的理财计划,退出");
return;
}
Long planId = queryPlansResponse.plans.get(0).id;
String bidAmount = queryPlansResponse.plans.get(0).minAmount;
logger.log(Level.INFO, "理财计划申购");
OrderRequest orderRequest = new OrderRequest(
merchantId, // 商户号
userId, // 理财账户号
bidAmount, // 申购金额
"11100003431", // 商户请求ID
planId // 计划ID
);
OrderResponse orderResponse = gongming.orderWithoutPayment(orderRequest);
logger.log(Level.INFO, "理财计划申购成功,订单号" + orderResponse.orderId + "," +
"成功申购" + orderResponse.successAmount + "元");
Long orderId = orderResponse.orderId;
// 若上一个申购操作成功,查询订单状态
logger.log(Level.INFO, "查询订单");
QueryOrderRequest queryOrderRequest = new QueryOrderRequest(
merchantId, // 商户号
orderId // 订单号
);
QueryOrderResponse queryOrderResponse = gongming.queryOrder(queryOrderRequest);
logger.log(Level.INFO, "订单查询成功,状态为" + queryOrderResponse.order.status.toString() + "");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String startDate = simpleDateFormat.format(new Date());
String endDate = simpleDateFormat.format(new Date(System.currentTimeMillis() + 1 * MILLISECONDS_PER_DAY));
logger.log(Level.INFO, "按日期查询订单,查询日期区间: " + startDate + " 到 " + endDate);
QueryOrdersByDateRequest queryOrderByDateRequest = new QueryOrdersByDateRequest(
merchantId, // 商户号
startDate, // 范围开始日期
endDate // 范围结束日期
);
QueryOrdersByDateResponse queryOrdersByDateResponse = gongming.queryOrderByDate(queryOrderByDateRequest);
logger.log(Level.INFO, "按日期查询订单成功,共有" + queryOrdersByDateResponse.orders.size() + "个订单");
logger.log(Level.INFO, "确认支付结果");
ConfirmPaymentRequest confirmPaymentRequest = new ConfirmPaymentRequest(
merchantId, // 商户号
orderId, // 订单号
true // 支付是否成功
);
ConfirmPaymentResponse confirmPaymentResponse = gongming.confirmPayment(confirmPaymentRequest);
logger.log(Level.INFO, "确认支付结果成功");
logger.log(Level.INFO, "查询订单收益");
QueryOrdersByDateRequest.QueryOrderInterestRequest queryOrderInterestRequest = new QueryOrdersByDateRequest.QueryOrderInterestRequest(
merchantId, // 商户号
orderId // 订单号
);
QueryOrderInterestResponse queryOrderInterestResponse = gongming.queryOrderInterest(queryOrderInterestRequest);
logger.log(Level.INFO, "查询订单收益成功,当日收益" + queryOrderInterestResponse.dailyInterest + "元," +
"累计收益" + queryOrderInterestResponse.totalInterest + "元");
} catch (GongmingConnectionException e) {
logger.log(Level.INFO, "连接失败:" + e.toString());
} catch (GongmingApplicationException e) {
logger.log(Level.INFO, "后台处理异常:" + e.toString());
}
} | 3 |
@Override
public void run() {
if (isAlive) {
System.out.println(name + " running");
Controller.start();
hunger = new stats.Hunger();
health = new stats.Health();
social = new stats.Social();
} else {
kill();
}
} | 1 |
public void run() {
for(int i = 0; i < _rounds; i ++){
ClusterRound(_minSpanningTree);
}
} | 1 |
public List<QuadTree> getTopNeighbors()
{
QuadTree sibling = this.getTopSibling();
if ( sibling == null ) return new ArrayList<QuadTree>();
return sibling.getBottomChildren();
} | 1 |
public void repaint(Game game){
for(List<Token> row : game.getBoard().tokens()){
for(Token token : row){
fieldButtons[token.yPos()][token.xPos()].setState(token.color(),token.isMoveable());
}
}
String startText = "<html><ul style='list-style-type:disc; margin:0 0 0 15; padding:0;'>";
String endText = "</ul></html>";
aiScoreLabel.setText(startText+buildScoreList(game.getAiStones())+endText);
playerScoreLabel.setText(startText+buildScoreList(game.getPlayerStones())+endText);
f.validate();
f.repaint();
if(game.isOver()){
String msg = "";
if(game.hasAiWon()){
msg = "Game over.";
}else{
msg = "You win!";
}
doneButton.setEnabled(false);
JOptionPane.showMessageDialog(f,msg,"End of Game",JOptionPane.PLAIN_MESSAGE);
}
} | 4 |
public V put (K newKey, V newValue) {
if (root == null) {
root = new Node(newKey, newValue);
size++;
return null;
}
Node node = root;
while (true) {
if (newKey.compareTo(node.mKey) < 0) {
if (node.left == null) {
node.left = new Node(newKey, newValue);
size++;
return null;
} else
node = node.left;
} else if (newKey.compareTo(node.mKey) > 0) {
if (node.right == null) {
node.right = new Node(newKey, newValue);
size++;
return null;
} else
node = node.right;
} else { // (newKey.compareTo(node.mKey) == 0)
V oldValue = node.mValue;
node.mValue = newValue;
return oldValue;
}
}
} | 6 |
public void Tick() {
while (true) {
if (this.stage == 1) {
this.LH = new LobbyHandler(net, userName);
StageFlipper passOn = LH.init(new StageFlipper());
stop(passOn);
} else if (this.stage == 20) {
this.TH = new TiarHandler(net, userName);
StageFlipper passOn = this.TH.init(lastMsg);
stop(passOn);
} else if (this.stage == 30) {
this.SH = new SnakeHandler(net, userName);
StageFlipper passOn = this.SH.init(lastMsg);
stop(passOn);
} else {
System.out.println("Weird stage");
}
}
} | 4 |
private Tile[] getLine(int idx) {
Tile[] result = new Tile[4];
for (int i : _0123) {
result[i] = tileAt(i, idx);
}
return result;
} | 1 |
public long directorySize(boolean includeSubDirs) throws IOException {
if (!file.isDirectory()) {
throw new IOException("FileConnection.directorySize() cannot be invoked on a file: " + file);
}
else {
if (includeSubDirs) {
throw new RuntimeException("FileConnection.directorySize(includingSubDirs) not implemented yet.");
}
else {
String[] list = file.list();
if (list != null) {
long size = 0L;
for (int i = 0; i < list.length; i++) {
File f = new File(file, list[i]);
if (f.isFile())
size += f.length();
}
return size;
}
}
return 0L;
}
} | 5 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} | 3 |
protected Content getNavSummaryLinks() throws Exception {
Content li = HtmlTree.LI(summaryLabel);
li.addContent(getSpace());
Content ulNav = HtmlTree.UL(HtmlStyle.subNavList, li);
MemberSummaryBuilder memberSummaryBuilder = (MemberSummaryBuilder)
configuration.getBuilderFactory().getMemberSummaryBuilder(this);
String[] navLinkLabels = new String[] {
"doclet.navNested", "doclet.navEnum", "doclet.navField", "doclet.navConstructor",
"doclet.navMethod"
};
for (int i = 0; i < navLinkLabels.length; i++ ) {
Content liNav = new HtmlTree(HtmlTag.LI);
if (i == VisibleMemberMap.ENUM_CONSTANTS && ! classDoc.isEnum()) {
continue;
}
if (i == VisibleMemberMap.CONSTRUCTORS && classDoc.isEnum()) {
continue;
}
AbstractMemberWriter writer =
((AbstractMemberWriter) memberSummaryBuilder.
getMemberSummaryWriter(i));
if (writer == null) {
liNav.addContent(getResource(navLinkLabels[i]));
} else {
writer.addNavSummaryLink(
memberSummaryBuilder.members(i),
memberSummaryBuilder.getVisibleMemberMap(i), liNav);
}
if (i < navLinkLabels.length-1) {
addNavGap(liNav);
}
ulNav.addContent(liNav);
}
return ulNav;
} | 7 |
private void dumpBArray( BitSet[] barray )
{
for ( int i=0;i<barray.length;i++ )
{
StringBuilder sb = new StringBuilder();
for (int j = barray[i].nextSetBit(1); j>= 0;
j = barray[i].nextSetBit(j+1))
{
if ( j <= sigla.size()&&j>0 )
{
Version v = sigla.get( j-1 );
sb.append( v.shortName );
sb.append( " " );
}
}
System.out.println( sb.toString() );
}
} | 4 |
public void render(Point top_left, int width, int height) {
DungeonFloor dungeonFloor = dungeonHandler.getActiveDungeon().getActiveFloor();
float ppt = (DisplayConstant.width_no_ui / (float) width);
float scale = (float) ppt / (float) DisplayConstant.sprite_size;
for (int x = (int) top_left.x; x < top_left.x + width; x++) {
for (int y = (int) top_left.y; y < top_left.y + height; y++) {
//render tiles
Tile tile = dungeonFloor.getTile(x, y);
if (tile != null & x >= 0) {//TODO poor bounds workaround
if (tile == Tile.WALL_STONE) {
}
SpriteID spriteID = tile.getSpriteID();
Image image = environment.getSprite(spriteID);
image.draw((float) ((x - top_left.x) * ppt), (float) ((y - top_left.y) * ppt), scale);
}
//render entities
Entity entity = dungeonFloor.getEntity(x, y);
if (entity != null & x >= 0) {
SpriteID spriteID = entity.getSpriteID();
Image image = environment.getSprite(spriteID);
image.draw((float) ((x - top_left.x) * ppt), (float) ((y - top_left.y) * ppt), scale);
}
//render inactive actors
//render active actors
Actor actor = dungeonFloor.getActor(x, y);
if (actor != null & x >= 0) {
SpriteID spriteID = actor.spriteID;
Image image = actor_sprites.getSprite(spriteID);
image.draw((float) ((x - top_left.x) * ppt), (float) ((y - top_left.y) * ppt), scale);
}
}
}
//render player
Image player_image = actor_sprites.getSprite(game.player.spriteID);
int player_x = (int) game.player.dungeon_position.x;
int player_y = (int) game.player.dungeon_position.y;
player_image.draw((float) ((player_x - top_left.x) * ppt), (float) ((player_y - top_left.y) * ppt), scale);
} | 6 |
private void openMainPage() {
driver.get(baseUrl + "/addressbookv4.1.4/index.php");
} | 0 |
private void drawWorld(Graphics2D g) {
BufferedImage i = Main.getLoadedWorld().draw((int)screen.getMinX(), (int)screen.getMinY(), (int)Math.ceil(screen.getWidth()), (int)Math.ceil(screen.getHeight()));
g.drawImage(i, 0, 0, GraphicsMain.WIDTH, GraphicsMain.HEIGHT, null);
} | 0 |
private void compute_pcm_samples2(Obuffer buffer)
{
final float[] vp = actual_v;
//int inc = v_inc;
final float[] tmpOut = _tmpOut;
int dvp =0;
// fat chance of having this loop unroll
for( int i=0; i<32; i++)
{
final float[] dp = d16[i];
float pcm_sample;
pcm_sample = (float)(((vp[2 + dvp] * dp[0]) +
(vp[1 + dvp] * dp[1]) +
(vp[0 + dvp] * dp[2]) +
(vp[15 + dvp] * dp[3]) +
(vp[14 + dvp] * dp[4]) +
(vp[13 + dvp] * dp[5]) +
(vp[12 + dvp] * dp[6]) +
(vp[11 + dvp] * dp[7]) +
(vp[10 + dvp] * dp[8]) +
(vp[9 + dvp] * dp[9]) +
(vp[8 + dvp] * dp[10]) +
(vp[7 + dvp] * dp[11]) +
(vp[6 + dvp] * dp[12]) +
(vp[5 + dvp] * dp[13]) +
(vp[4 + dvp] * dp[14]) +
(vp[3 + dvp] * dp[15])
) * scalefactor);
tmpOut[i] = pcm_sample;
dvp += 16;
} // for
} | 1 |
public void generateNQueens(ArrayList<String[]> result,String[] temp,int[] position,int insertN,int n) {
for (int i=0;i<n;i++){
position[insertN-1] = i;
boolean satis = true;
for (int j=0;j<insertN-1;j++){
if(insertN-1-j==position[insertN-1]-position[j]||insertN-1-j==position[j]-position[insertN-1]||
position[insertN-1]==position[j]){
satis = false;
continue;
}
}
if(satis){
if(insertN == n){
String [] a = new String[n];
for(int k=0;k<n;k++){
a[k] = temp[position[k]];
}
result.add(a);
return;
}
else {
generateNQueens(result,temp, position,insertN+1,n);
}
}
}
} | 8 |
public boolean removeTile(int x, int y) {
for (int i = 0; i < tiles.size(); i++) {
Tile t = tiles.get(i);
if (t.getX() == x && t.getY() == y) {
tiles.remove(i);
return true;
}
}
return false;
} | 3 |
public Tiedostonlukija(String tiedostonnimi) throws Exception {
this.tiedosto = new File(tiedostonnimi);
lukija = new Scanner(tiedosto);
this.rivit = new ArrayList();
rivitTalteen();
} | 0 |
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.