method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
e9bdaa4e-55eb-4190-9f85-061e99761203
| 1
|
public boolean isLiving(Player player) {
if (livingplayers.contains(player))
return true;
return false;
}
|
244c3bbf-971f-484b-9714-2486ce909f06
| 8
|
public static void getProgramStats() throws IOException{
// INIT
List <Word> anew = StatsBank.buildANEW();
List<String> dictionaryAnew = new ArrayList<String>();
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("files/result-programStats.csv",true)));
List<String> items = Arrays.asList(channels.split(","));
for (Word wi : anew) dictionaryAnew.add(anew.indexOf(wi), wi.getWord()); // create the index
for(String channel : items){
try{
ArrayList <Program> programList = new ArrayList <Program>();
// QUERY PARAMETERS FOR API
// TWO WEEKS IN FEBRUARY 2014 .
// GET THE EPG!
String url = "/epg/channels/"+channel+"/boxfish/72283b8f-cddd-40b1-b41c-c837a56df2f5/2014-02-07T00:00:00/2014-02-14T00:00:00/All?upcoming=true";
// PROCESSING JSON RESULT
JSONArray json = APICalls.doHttpRequest(url);
JsonObject jsonA = JsonObject.readFrom(json.get(0).toString());
JsonArray nestedArray = jsonA.get( "timetable" ).asArray();
// DOING ALL THE FANCY STUFF : PROGRAM MERGING AND ANEW VALUES
for(JsonValue jsonI : nestedArray){
String genre ="";
JsonObject a = (JsonObject) jsonI;
if(!a.get("genre").isNull()) genre = a.get("genre").asString();
String start = a.get("start").asString();
String stop = a.get("stop").asString();
String idText = a.get("id").asString().replaceAll("\"", "");
int id = Integer.parseInt(idText);
String text = APICalls.getFeatures(start, stop, anew,channel);
Program program = new Program(channel, genre, id, text);
// if the program was already seen add the new text
if (programList.contains(program)){
int index = programList.indexOf(program);
Program oldProgram = programList.get(index);
oldProgram.addText(text);
programList.set(index, oldProgram);
}
else programList.add(program);
}
System.out.println(programList.size()+" programs found in channel "+channel);
// PRINT THE RESULTS INTO A FILE
for (Program programI : programList){
double [] values = StatsBank.calcANEWVals(programI.getText(), anew, dictionaryAnew, StatsBank.readSentimentFiles(true), StatsBank.readSentimentFiles(false));
String valuesText ="";
System.out.println(programI.getText());
for (int w = 0 ; w < 26 ; w++){
valuesText+=values[w]+",";
}
System.out.println(channel+","+programI.getGenre()+","+programI.getId()+","+valuesText+" text");//+programI.getText());
writer.println(channel+","+programI.getGenre()+","+programI.getId()+","+valuesText+programI.getText());//+programI.getText());
writer.flush();
}
}
catch(Exception e ) {System.out.println("an exception was caught!");}
}
writer.close();
}
|
3f0b922f-5dac-47ac-84e7-40096bbb04bf
| 0
|
public long getBulletDelay(){
return this.bulletDelay;
}
|
18e10391-8cfb-4744-8377-d3957e4e9158
| 2
|
@Override
public void move(Excel start, Excel end) {
// TODO Auto-generated method stub
if (start.getX() == begin.getX() && start.getY() == begin.getY())
{
begin = end;
setColoredExes();
}
}
|
6a294dff-38ae-4a7d-9221-e372cbe08cbe
| 1
|
public void writeRevTable() {
TranslationTable revtable = new TranslationTable();
basePackage.writeTable(revtable, true);
try {
OutputStream out = new FileOutputStream(outRevTableFile);
revtable.store(out);
out.close();
} catch (java.io.IOException ex) {
GlobalOptions.err.println("Can't write rename table "
+ outRevTableFile);
ex.printStackTrace(GlobalOptions.err);
}
}
|
25015c9b-92d8-4f17-bfa1-fc0f0389ce64
| 0
|
@Override
public String getCur() {
return convertToString(cur);
}
|
9f644d93-9b0f-4ab0-9b22-e4eab299cd79
| 6
|
public void moveInDirection(double d, HashSet<Line2D> walls) {
d = d -30 + GameConfig.random.nextInt(60);
if(location.getY() - Math.sin(d*Math.PI/180) < 0 || location.getY() - Math.sin(d*Math.PI/180) > 100 || location.getX() + Math.cos(d*Math.PI/180) > 100 || location.getX() + Math.cos(d*Math.PI/180) < 0)
return;
Line2D.Double pathLine = new Line2D.Double(location.getX(),location.getY(),location.getX() + Math.cos(d*Math.PI/180), location.getY() - Math.sin(d*Math.PI/180));
for(Line2D l : walls)
{
if(l.intersectsLine(pathLine))
return;
}
location.setLocation(location.getX() + Math.cos(d*Math.PI/180), location.getY() - Math.sin(d*Math.PI/180));
}
|
b51b34c5-4152-4fe9-a5b9-8559ffa2b2fa
| 8
|
@Override
public String toString() {
String type = "UNKNOWN";
switch (bufferType) {
case POINT_BUFFER: type = "POINT_BUFFER"; break;
case LINE_BUFFER: type = "LINE_BUFFER"; break;
case TRIANGLE_BUFFER: type = "TRIANGLE_BUFFER"; break;
}
String data = "";
if ((bufferDataPresent & NORMAL_IN_BUFFER) != 0)
data = data + "NORMALS ";
if ((bufferDataPresent & COLOR_IN_BUFFER) != 0)
data = data + "COLORS ";
if ((bufferDataPresent & ALPHA_IN_BUFFER) != 0)
data = data + "ALPHA ";
String lbound = "null";
if (lowerBound != null)
lbound = lowerBound.toString();
String ubound = "null";
if (upperBound != null)
ubound = upperBound.toString();
return
"majorVersionNumber: " + majorVersionNumber + " " +
"minorVersionNumber: " + minorVersionNumber + " " +
"minorMinorVersionNumber: " + minorMinorVersionNumber + "\n" +
"bufferType: " + type + " " +
"bufferDataPresent: " + data + "\n" +
"size: " + size + " " +
"start: " + start + "\n" +
"lower bound: " + lbound + "\n" +
"upper bound: " + ubound + " ";
}
|
ad06182a-3c2e-4763-95d3-18c29e28f359
| 0
|
public void removeInstance(Instance instance) {
this.instances.remove(instance);
}
|
e4bd17d6-e10f-46be-ba6b-5eac8e0669d2
| 2
|
public void run() {
try {
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
write=new PrintWriter(socket.getOutputStream(),true);
String msg;
while((msg=reader.readLine())!=null) {
System.out.println(msg);
socketMan.writeAll(msg); //ͻϢд
}
}catch(Exception e){
e.printStackTrace();
}
}
|
013c7ffc-204f-4436-8eaa-777ffe1ec954
| 3
|
public void busAdded (Bus bus)
throws IOException
{
if (model == null)
return;
synchronized (busses) {
Bus newBusses [] = new Bus [busses.length + 1];
HubNode newHubs [] = new HubNode [newBusses.length];
// old busses first
System.arraycopy (busses, 0, newBusses, 0, busses.length);
System.arraycopy (hubs, 0, newHubs, 0, busses.length);
// new one always at the end (simpler)
newBusses [busses.length] = bus;
try {
newHubs [busses.length]
= new HubNode (bus.getRootHub (), this);
} catch (IOException e) {
// why?
e.printStackTrace ();
}
System.err.println ("new bus: " + newHubs [busses.length]);
busses = newBusses;
hubs = newHubs;
if (model != null)
model.nodesWereInserted (this,
new int [] { busses.length });
}
}
|
ea0f8fa4-1789-47cf-bee4-d6132de5f3c0
| 0
|
public void setItemName(String itemName) {
this.itemName = itemName;
}
|
dbdc0d20-a021-455e-b61a-d747880d4daa
| 7
|
private void optimizeMondayTimeTableForIAndIIGymnasium() {
List<LinkedHashMap> daysTimeTablesForItr = addDaysTimeTablesForIteration();
List<String> teachersForIteration = createTeachersListForIteration();
LinkedHashMap<String, String> teachersTimeTable;
HashMap<String, Teacher> teachersMapForDeletion = copyTeacherForDeletion();
for (int lectureNumber = 1; lectureNumber <= properties.getHoursPerDay(); lectureNumber++) {
// System.out.println("--------------Lecture-----------------");
// System.out.println("Lecture number: " + lectureNumber);
for (String teacherName : teachersForIteration) {
// System.out.println("--------------Teacher-----------------");
for (LinkedHashMap dayTimeTable : daysTimeTablesForItr) {
// System.out.println("-----------------Day-------------");
teachersTimeTable = getTeachersTimeTable(teacherName, dayTimeTable);
Teacher teacher = teachersMapForDeletion.get(teacherName);
List<Group> teachersGroups = teacher.getTeachersGroups();
int teachersGroupsTotal = teachersGroups.size();
// System.out.println("teachersGroupsTotal: " + teachersGroupsTotal);
// System.out.println("Teacher: " + teacherName);
if (teachersGroupsTotal == 0) {
teachersTimeTable.put(String.valueOf(lectureNumber), lectureNumber + ": -----");//Add group, because all the groups for teacher was added already
// System.out.println("add empty at the end");
continue;
}
Group group = getRandomGroup(teachersGroups, teachersGroupsTotal);
while (group == null) {
group = getRandomGroup(teachersGroups, teachersGroupsTotal);
}
boolean isGroupAllowedToAdd = isMandatoryConditionsMet(teacher, teachersGroups, group, lectureNumber, dayTimeTable);
// System.out.println("Grupe idejimui: " + group.getGroupName());
// System.out.println("isGroupAllowedToAdd: " + isGroupAllowedToAdd);
// System.out.println("Teachers time table: " + teachersTimeTable);
// System.out.println("lecture number: " + lectureNumber);
if (isGroupAllowedToAdd) {
// System.out.println("Mokytojas: " + teacherName);
// System.out.println("Grupe, kai galima deti ja: " + group);
addGroupToTeachersTimeTable(group, teachersTimeTable, lectureNumber, teachersGroups);
} else {
if (teacher.isTeacherInAllClasses()) {
continue;
}
teachersTimeTable.put(String.valueOf(lectureNumber), lectureNumber + ": -----");
}
}
}
}
optimizationResults.setAllDaysTeacherTimeTable(daysTimeTablesForItr);
}
|
6ab6b6a0-cdb8-42c1-ba70-fa6c159bfe28
| 5
|
@Override
public ResultMessage check(UserPO po) {
// TODO Auto-generated method stub
boolean exist=false;
for(UserPO realPO:users){
if(po.getUserName().equals(realPO.getUserName())&&po.getPassword().equals(realPO.getPassword())
&&po.getUserSort()==realPO.getUserSort()){
exist=true;
break;
}
}
if(exist)
return ResultMessage.login_success;
else
return ResultMessage.login_failure;
}
|
51219221-44d0-4183-88bb-8fee592c4e01
| 7
|
public void renderSprite(Graphics g, Sprite s)
{
// ONLY RENDER THE VISIBLE ONES
if (!s.getState().equals(pathXTileState.INVISIBLE_STATE.toString()) &&
!s.getSpriteType().getSpriteTypeID().contains(LEVEL_BUTTON_TYPE) &&
!s.getSpriteType().getSpriteTypeID().contains(MAP_TYPE) &&
!s.getState().equals(LEVEL_SELECT_SCREEN_STATE) &&
!s.getState().equals(GAME_SCREEN_STATE))
{
SpriteType bgST = s.getSpriteType();
Image img = bgST.getStateImage(s.getState());
g.drawImage(img, (int)s.getX(), (int)s.getY(), bgST.getWidth(), bgST.getHeight(), null);
} else if (s.getState().equals(LEVEL_SELECT_SCREEN_STATE) ||
s.getState().equals(GAME_SCREEN_STATE))
{
SpriteType bgST = s.getSpriteType();
Image img = bgST.getStateImage(s.getState());
g.drawImage(img, (int)s.getX(), (int)s.getY(), img.getWidth(null), img.getHeight(null), null);
}
}
|
17da11da-0596-4fb9-ab6e-d8e43ecd396d
| 5
|
public void mouseMoved(MouseEvent ev) {
//récupération de la position de la souris
final Point p = ev.getPoint();
if (m.zoneAccueil.contains(p)) {
m.afficheEffet(1);
} else if (m.zoneAllSeries.contains(p)) {
m.afficheEffet(2);
} else if (m.zoneMySeries.contains(p)) {
m.afficheEffet(3);
} else if (m.zoneCalendrier.contains(p)) {
m.afficheEffet(4);
} else if (m.zoneProfil.contains(p)) {
m.afficheEffet(5);
} else {
m.afficheEffet(0);
}
m.repaint();
}
|
8c0261d6-5923-4f7b-95ae-bfe04279c142
| 9
|
@Override
public void update(GameContainer gc, StateBasedGame game, int delta) throws SlickException {
//delta calculates frames per second (stay at same speed regardless of framerate)
super.update(gc, game, delta);
timer++;
levelTimer++;
int randomInt = r.nextInt(550);
int randomAlien = r.nextInt(550);
if(levelTimer >= 750) {
level++;
levelTimer = 0;
}
if(timer >= (lag - (level*20))) {
Asteroid a = new Asteroid(randomInt, -50);
asteroids.add(a);
a.depth += 1;
add(a);
timer = 0;
}
if(level >= 4) {
alienTimer++;
if(alienTimer >= (lag - level*30)) {
Alien alien = new Alien(randomAlien, -50);
aliens.add(alien);
add(alien);
alienTimer = 0;
}
}
for(int i = 0; i < asteroids.size(); i++) {
asteroids.get(i).setLevel(level);
if(asteroids.get(i).getY() > ME.world.getHeight()) {
asteroids.remove(i);
p.health -=1;
}
}
for(int j = 0; j < aliens.size(); j++) {
aliens.get(j).setLevel(level);
if(aliens.get(j).getY() > ME.world.getHeight()) {
aliens.remove(j);
p.health -= 1;
}
}
if(p.health == 0) {
p.destroy();
game.enterState(2, new FadeOutTransition(), new FadeInTransition());
}
}
|
60f06552-7421-43e6-8fd0-22a8e0d96071
| 1
|
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
|
a658fc10-f1c8-4be8-918c-b7da60314a0c
| 3
|
public boolean Autorizar(){
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
JPanel p = new JPanel();
p.add(pass);
try {
con.ConsultarSQL("select id,senha from tb_usuarios where funcao = 1",true);
con.rs.first();
JOptionPane.showMessageDialog(null, p, "Autorização", JOptionPane.PLAIN_MESSAGE);
pass.grabFocus();
do{
if(pass.getText().equals(con.rs.getString("senha"))){
Gerente = con.rs.getString("id");
return true;
}
}while(con.rs.next());
} catch (SQLException ex) {
Logger.getLogger(Validacao.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
|
1e1dcf21-7eb2-4656-a5f2-1024049eba4e
| 8
|
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
successLabel.setVisible(false);
if (groupNameBox.getText() == null
|| groupNameBox.getText().equals("")) {
//we don't want to do anything, no name set
JOptionPane.showMessageDialog(this,
"No group name specified. Update failed.",
"Missing name",
JOptionPane.WARNING_MESSAGE);
return;
}
transferChanges();
if ((editingFilt != null
&& !editingFilt.equals(original))) {
int n = 0;
if (original != null
&& !editingFilt.getName().equals(original.getName())
&& original.getName() != null) {
//have a name, name differs, and not changing index
Object[] options = {"Yes", "Cancel"};
n = JOptionPane.showOptionDialog(this,
"This will edit the name of the current activity.\n"
+ "Are you sure you wish to continue?",
"Activity name change",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
}
//they want to change the name
if (n == 0) {
//write local object to db & update user
manager.updateGroup(editingFilt);
original = (Group) editingFilt.clone();
//update our display
getGroups();
successLabel.setVisible(true);
}
} else {
successLabel.setVisible(true);
}
}//GEN-LAST:event_updateButtonActionPerformed
|
7197bc3b-a96e-43cc-8f25-1f87924c2ec6
| 2
|
protected HttpURLConnection createConnection(URL url, String method,
Map<String, String> options) throws Exception {
HttpURLConnection connection = null;
if(testFlag)
connection = (HttpURLConnection)url.openConnection();
else
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod(method);
for(Entry<String, String> s : options.entrySet()) {
connection.setRequestProperty(s.getKey(), s.getValue());
}
connection.setDoOutput(true);
return connection;
}
|
a8533cd1-0bcb-4070-aa00-f111ffae4b8b
| 4
|
private void init(){
//Fill dungeon with walls.
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
setTile(x, y, 2);
}
}
//Place start and end rooms.
for(int y = 0; y < 9; y++){
int ya = y + (32 / 2) - (9 / 2);
for(int x = 0; x < 9; x++){
int xa = x + (64 - 9);
setTile(x + 1, ya, 1);
setTile(xa - 1, ya, 1);
}
}
// setTile(start.getX(), start.getY(), 6);
// setTile(end.getX(), end.getY(), 6);
placeWalls();
}
|
6938be4b-f805-4808-a42d-be9f8db42a87
| 3
|
public void addProduction(Production production) {
super.addProduction(production);
// If it's both, we shouldn't change at all.
if (ProductionChecker.isRightLinear(production)
&& ProductionChecker.isLeftLinear(production))
return;
// If we get to this point it must be either left or right
// linear, and not both.
setLinearity(ProductionChecker.isRightLinear(production) ? RIGHT_LINEAR
: LEFT_LINEAR);
}
|
316a6afe-ece6-4196-9c14-7cd44ca4ab95
| 3
|
public void generate() {
System.out.println("Generating world. Please be patient, as older computers will take longer to create the chunks.");
chunks = new Chunk[WORLD_SIZE][WORLD_SIZE];
for(int x = 0; x < WORLD_SIZE; x++)
{
for(int y = 0; y < WORLD_SIZE; y++)
{
chunks[x][y]=new Chunk();
if(chunks[x][y]!=null)
{
System.out.println("Generating chunks. X: "+x+" Y: "+y);
chunks[x][y].x=x;
chunks[x][y].y=y;
chunks[x][y].seed=seed;
//chunks[x][y].octave0=this.octave0;
//chunks[x][y].octave1=this.octave1;
//chunks[x][y].octave2=this.octave2;
//chunks[x][y].octave3=this.octave3;
//chunks[x][y].octave4=this.octave4;
chunks[x][y].generate();
}
}
}
/*blocks = new Block[WORLD_SIZE][WORLD_SIZE][WORLD_SIZE];
for (int x = 0; x < WORLD_SIZE; x++) {
for (int y = 0; y < WORLD_SIZE; y++) {
for (int z = 0; z < WORLD_SIZE; z++) {
blocks[x][y][z] = Block.blockAir;
}
}
}*/
//System.out.println("World filled with air.");
/*
blocks[0][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.blockCobble;
blocks[1][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.blockGrass;
blocks[2][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.blockDirt;
blocks[3][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.blockStone;
blocks[4][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.MELCobble;
blocks[5][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.MELGrass;
blocks[6][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.MELDirt;
blocks[7][WORLD_SIZE - 1][WORLD_SIZE - 1] = Block.MELStone;
blocks[3][13][3] = Block.MELGrass;
blocks[4][13][3] = Block.MELGrass;
blocks[5][13][3] = Block.MELGrass;
blocks[3][13][4] = Block.MELGrass;
blocks[4][13][4] = Block.MELGrass;
blocks[5][13][4] = Block.MELGrass;
blocks[3][13][5] = Block.MELGrass;
blocks[4][13][5] = Block.MELGrass;
blocks[5][13][5] = Block.MELGrass;
blocks[3][12][3] = Block.MELDirt;
blocks[4][12][3] = Block.MELDirt;
blocks[5][12][3] = Block.MELDirt;
blocks[3][12][4] = Block.MELDirt;
blocks[4][12][4] = Block.MELDirt;
blocks[5][12][4] = Block.MELDirt;
blocks[3][12][5] = Block.MELDirt;
blocks[4][12][5] = Block.MELDirt;
blocks[5][12][5] = Block.MELDirt;
blocks[3][11][3] = Block.MELStone;
blocks[4][11][3] = Block.MELStone;
blocks[5][11][3] = Block.MELStone;
blocks[3][11][4] = Block.MELStone;
blocks[4][11][4] = Block.MELStone;
blocks[5][11][4] = Block.MELStone;
blocks[3][11][5] = Block.MELStone;
blocks[4][11][5] = Block.MELStone;
blocks[5][11][5] = Block.MELStone;
blocks[3][10][3] = Block.MELStone;
blocks[4][10][3] = Block.MELStone;
blocks[5][10][3] = Block.MELStone;
blocks[3][10][4] = Block.MELStone;
blocks[4][10][4] = Block.MELStone;
blocks[5][10][4] = Block.MELStone;
blocks[3][10][5] = Block.MELStone;
blocks[4][10][5] = Block.MELStone;
blocks[5][10][5] = Block.MELStone;
}*/
/*System.out.println("Building terrain...");
if(isMelonDim==false)
{
System.out.println("Isn't melondimension.");
for (int i = 0; i < this.WORLD_SIZE; i++) {
for (int j = 0; j < this.WORLD_SIZE; j++) {
for (int k = 0; k < this.WORLD_SIZE; k++) {
if(i<WORLD_SIZE && j<WORLD_SIZE && k<WORLD_SIZE)
{
if (5.0D * checkOctave(i, k, this.octave0) + 15.0D * checkOctave(i, k, this.octave1) + 7.0D * checkOctave(i, k, this.octave2) + 1.0D * checkOctave(i, k, this.octave3) + 1.0D * checkOctave(i, k, this.octave4) >= j) {
this.blocks[i][j][k] = Block.blockStone;
}
if ((checkOctave(i, k, this.octave4) > 0.9D) && (10.0D * checkOctave(i, k, this.octave4) >= j)) {
this.blocks[i][j][k] = Block.blockStone;
}
}
}
}
}
System.out.println("Terrain formed...");
System.out.println("Planting grass and dirt...");
for (int i = 0; i < this.WORLD_SIZE; i++) {
for (int j = 0; j < this.WORLD_SIZE; j++) {
for (int k = 0; k < this.WORLD_SIZE; k++) {
if(j<WORLD_SIZE-1)
{
if ((this.blocks[i][j][k] == Block.blockStone) && (this.blocks[i][(j + 1)][k] == Block.blockAir)) {
this.blocks[i][j][k] = Block.blockGrass;
if (j > 1) {
this.blocks[i][(j - 1)][k] = Block.blockDirt;
this.blocks[i][(j - 2)][k] = Block.blockDirt;
}
}
}
}
}
}
System.out.println("World fully formed!");
}
if(isMelonDim==true)
{
System.out.println("Forming melonland...");
for (int i = 0; i < this.WORLD_SIZE; i++) {
for (int j = 0; j < this.WORLD_SIZE; j++) {
for (int k = 0; k < this.WORLD_SIZE; k++) {
if(i<WORLD_SIZE && j<WORLD_SIZE && k<WORLD_SIZE)
{
if (5.0D * checkOctave(i, k, this.octave0) + 15.0D * checkOctave(i, k, this.octave1) + 7.0D * checkOctave(i, k, this.octave2) + 1.0D * checkOctave(i, k, this.octave3) + 1.0D * checkOctave(i, k, this.octave4) >= j) {
this.blocks[i][j][k] = Block.MELStone;
}
if ((checkOctave(i, k, this.octave4) > 0.9D) && (10.0D * checkOctave(i, k, this.octave4) >= j)) {
this.blocks[i][j][k] = Block.MELStone;
}
}
}
}
}
System.out.println("Melon-Terrain formed...");
System.out.println("Planting melongrass and melondirt...");
for (int i = 0; i < this.WORLD_SIZE; i++) {
for (int j = 0; j < this.WORLD_SIZE; j++) {
for (int k = 0; k < this.WORLD_SIZE; k++) {
if(j<WORLD_SIZE-1)
{
if ((this.blocks[i][j][k] == Block.MELStone) && (this.blocks[i][(j + 1)][k] == Block.blockAir)) {
this.blocks[i][j][k] = Block.MELGrass;
if (j > 1) {
this.blocks[i][(j - 1)][k] = Block.MELDirt;
this.blocks[i][(j - 2)][k] = Block.MELDirt;
}
}
}
}
}
}
System.out.println("Melonland fully formed!");
}*/
/*
* for (int x = 0; x < WORLD_SIZE; x++) { for (int y = WORLD_SIZE-1; y <
* WORLD_SIZE; y++) { for (int z = 0; z < WORLD_SIZE; z++) {
* blocks[x][y][z] = Block.blockGrass; } } }
*/
}
|
dfb71c2f-ab74-48c1-947b-53d855507a17
| 0
|
private static int getIntBigEndian(byte[] a, int offs) {
return
(a[offs] & 0xff) << 24 |
(a[offs + 1] & 0xff) << 16 |
(a[offs + 2] & 0xff) << 8 |
a[offs + 3] & 0xff;
}
|
5de9b480-8aed-4986-9752-f4135f9b7d3f
| 0
|
public static String getRequestParameter(String key) {
return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
}
|
5c51c736-9b5b-488c-884f-224860108d79
| 7
|
public static void main(String[] args) throws IOException {
if(args.length < 1) {
System.err.println("No key file specified.");
System.exit(-1);
}
ByteBuffer buffer = new ByteBuffer();
System.err.print("Loading key file");
DotThread dt = new DotThread();
dt.start();
try(FileInputStream in = new FileInputStream(new File(args[0]))) {
while(true) {
int c = in.read();
if(c < 0) break;
buffer.append(c);
}
} catch(Exception e) {
System.err.println("--- Can't read key file ---");
e.printStackTrace();
System.exit(-1);
}
System.err.print("\nComputing genesis");
byte[] hash = func.computeHash(buffer.toArray());
System.err.print("\nEncoding");
byte[] streamBuf = new byte[func.getDigestLength()];
while(true) {
int len = System.in.read(streamBuf, 0, func.getDigestLength());
if(len <= 0) break;
for(int i = 0; i < func.getDigestLength(); i++)
streamBuf[i] ^= hash[i];
System.out.write(streamBuf, 0, len);
byte[] hashNew = func.computeHash(hash);
hash = hashNew;
}
dt.interrupt();
System.err.println();
}
|
404342cd-dcdb-415f-b225-5a3eded43c1c
| 5
|
public void fixTopics() {
Map<String, String> topicMap = new HashMap();
try {
Properties prop = new Properties();
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Journal.properties");
prop.load(inputStream);
BufferedReader fin = new BufferedReader(new FileReader(prop.getProperty("Topics")));
String temp;
while (fin.ready()) {
temp = fin.readLine();
String[] tTopics = temp.split(":");
String topic = tTopics[0];
String[] terms = tTopics[1].split(",");
for (String t : terms) {
topicMap.put(t, topic);
}
}
} catch (IOException e) {
System.out.println("loadTopics broke yo");
}
Collection<String> hTopics = new HashSet<>();
ArrayList<String> newTopics = new ArrayList<>();
for (String t : this.topics) {
String temp = topicMap.get(t);
hTopics.add(temp);
}
for (String t : hTopics) {
newTopics.add(t);
}
this.topics = newTopics;
}
|
cb675e46-0bbd-4314-9224-21fa6e009bf7
| 0
|
public PelaajaTest() {
}
|
d75edb06-466c-426c-adec-094f5fbcc0ba
| 7
|
public static void preloadAll()
{
try
{
CodeSource cs = RHImageLoader.class.getProtectionDomain()
.getCodeSource();
File codeSource = new File(URLDecoder.decode(cs.getLocation()
.getFile(), "UTF-8"));
String desiredPackage = RHImageLoader.class.getPackage().getName()
.replace('.', '/');
Enumeration contents = new JarFile(codeSource).entries();
while (contents.hasMoreElements())
{
JarEntry je = (JarEntry) contents.nextElement();
String pkg = je.getName().substring(0,
je.getName().lastIndexOf("/"));
String fname = je.getName().substring(
je.getName().lastIndexOf("/") + 1);
if (je.getName().endsWith(".gif") && pkg.equals(desiredPackage))
{
RHImageLoader.getImageIcon(fname);
}
}
}
catch (Exception e)
{
try
{
// System.out.println("Mustn't have a jar.");
URL dirURL = RHImageLoader.class.getResource(".");
File[] files = new File(URLDecoder.decode(dirURL.getFile(),
"UTF-8")).listFiles();
for (int i = 0; i < files.length; i++)
{
String fname = files[i].getName();
if (fname.endsWith(".gif"))
{
RHImageLoader.getImageIcon(fname);
}
}
}
catch (Exception e2)
{
// TODO: handle exception
}
}
}
|
85422620-e47e-4294-a56f-c0ac51220321
| 1
|
public ChatGui() {
super();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
settings = Settings.getInstance();
participantList = ParticipantList.getInstance();
chatHistory = ChatHistory.getInstance();
URL iconUrl = ClassLoader.getSystemResource(Constants.ICON_FILE);
Image icon = new ImageIcon( iconUrl ).getImage();
setIconImage( icon );
createMenuBar();
createGui();
refreshTitle();
outputTextArea.setContentType("text/html");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for(int k=0; k<chatGuiListener.size(); ++k) {
chatGuiListener.get(k).sendMessage(inputTextArea.getText());
}
inputTextArea.setText("");
}
});
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Dimension windowSize = getSize();
textAreSplitPane.setDividerLocation((int) (0.5 * windowSize.height));
mainSplitPane.setDividerLocation((int) (0.7 * windowSize.width));
}
});
setSize(600, 400);
setVisible(true);
}
|
440c026e-4187-4432-8b28-95c3a407ce81
| 3
|
public static String selectListParam(Map<String, Object> paramMap) throws SQLException{
@SuppressWarnings("unchecked")
java.util.Map<String,Object> sqlWhereMap = (Map<String, Object>) (paramMap.get("sqlWhereMap")==null ? "": paramMap.get("sqlWhereMap"));
BEGIN();
SELECT(Permission.COLUMNS);
FROM(Permission.TABLE_NAME);
if (sqlWhereMap != null && !"".equals(sqlWhereMap)) {
//拼接查询条件
WHERE(BaseModel.getSqlWhereWithValues(sqlWhereMap));
}
return SQL();
}
|
b38eae6a-8d6c-4507-8fc0-9d6aae102061
| 7
|
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
thita -= (float) (Math.PI / 14);
thita %= 2*Math.PI;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN) {
thita += (float) (Math.PI / 14);
thita %= 2*Math.PI;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
phi += (float) (Math.PI / 14);
phi %= 2*Math.PI;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
phi -= (float) (Math.PI / 14);
phi %= 2*Math.PI;
}
if(e.getKeyCode() == KeyEvent.VK_I) {
radius -= (radius > 5.0f) ? 2.0f : 0.0f;
}
if(e.getKeyCode() == KeyEvent.VK_O) {
radius += 2.0f;
}
}
|
7d323b2c-68fe-4bc8-8f26-1c00afdca241
| 6
|
public boolean getBoolean(int index) throws JSONException {
Object object = 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.");
}
|
c5e827d8-fce1-4390-995e-0a7a1cc5542d
| 8
|
private static int method524(char arg0[]) {
if (arg0.length > 6) {
return 0;
}
int k = 0;
for (int l = 0; l < arg0.length; l++) {
char c = arg0[arg0.length - l - 1];
if (c >= 'a' && c <= 'z') {
k = k * 38 + c - 97 + 1;
} else if (c == '\'') {
k = k * 38 + 27;
} else if (c >= '0' && c <= '9') {
k = k * 38 + c - 48 + 28;
} else if (c != 0) {
return 0;
}
}
return k;
}
|
46e69d83-3f23-40c7-ad8b-1df8884b25ff
| 8
|
@Override
public void promptPrint(String msg)
{
print(msg);
if(promptSuffix.length>0)
{
try
{
rawBytesOut(rawout, promptSuffix);
}
catch (IOException e)
{
}
}
final MOB mob=mob();
if((!getClientTelnetMode(TELNET_SUPRESS_GO_AHEAD))
&& (!killFlag)
&& (mightSupportTelnetMode(TELNET_GA)
||(mob==null)
||(mob.isAttributeSet(MOB.Attrib.TELNET_GA))))
{
try
{
rawBytesOut(rawout, TELNETGABYTES);
}
catch (final Exception e)
{
}
}
}
|
5b14bb64-03fc-474c-8f62-b5ba948fbe9a
| 4
|
private void calculatePosition(){
nx = Math.cos(getRadians());
ny = Math.sin(getRadians());
x+=speed*nx;
y+=speed*ny;
if(x>MainWindow.WIDTH) x = -sprite.getWidth();
if(y>MainWindow.HEIGHT) y = -sprite.getHeight();
if(x+sprite.getWidth()<0) x = MainWindow.WIDTH;
if(y+sprite.getHeight()<0) y = MainWindow.HEIGHT;
}
|
55fbed6c-db64-48f9-89b6-886239dda5be
| 5
|
private void initUserlistLayoutMenu(Color bg) {
this.userlistLayoutMenu = new JPanel();
this.userlistLayoutMenu.setBackground(bg);
this.userlistLayoutMenu.setLayout(new VerticalLayout(5, VerticalLayout.LEFT));
// size
this.userlistLayoutMenu.add(new Numberfield(this.skin.getUserlistHeight(), 3, bg, strSizeFieldTitle, strNumfieldHeight,
true) {
private final long serialVersionUID = 1L;
@Override
public void onKeyReleased(String input) {
if (!UserlistChangesMenu.this.skin.setUserlistHeight(parseInt(input))) {
update(Color.RED);
}
}
@Override
public void resetOnClick() {
UserlistChangesMenu.this.skin.setUserlistHeight(-1);
update(UserlistChangesMenu.this.skin.getUserlistHeight());
}
});
// checkbox
boolean b = this.skin.getUserlistVertical();
this.userlistLayoutMenu.add(new CheckField(b, bg, strUserlistVTitle, strUserlistVBtn) {
private final long serialVersionUID = 1L;
@Override
public void btnPressed(boolean selected) {
UserlistChangesMenu.this.skin.setUserlistVertical(selected);
}
});
// position
Position pos = this.skin.getUserlistPosition();
boolean[] active = { true, true, true, true, true, true, true, true, true };
this.userlistLayoutMenu.add(new PositionField(pos, active, bg, strPosFieldTitle) {
private final long serialVersionUID = 1L;
@Override
public void toprightOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.TOPRIGHT);
}
@Override
public void topleftOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.TOPLEFT);
}
@Override
public void topOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.TOP);
}
@Override
public void centerrightOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.RIGHT);
}
@Override
public void centerleftOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.LEFT);
}
@Override
public void centerOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.CENTER);
}
@Override
public void bottomrightOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.BOTTOMRIGHT);
}
@Override
public void bottomleftOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.BOTTOMLEFT);
}
@Override
public void bottomOnPressed() {
UserlistChangesMenu.this.skin.setUserlistPosition(Position.BOTTOM);
}
});
// padding
final int[] padding = this.skin.getUserlistPadding();
this.userlistLayoutMenu.add(new PaddingField(padding, bg, strPaddingFieldTitle + "(" + strUserlistPaddingHint + ")") {
private final long serialVersionUID = 1L;
private int[] tmp = (padding == null) ? new int[] { 0, 0, 0, 0 } : padding;
@Override
public void topFieldOnKeyReleased(String input) {
controlAndSet(input, 1);
}
@Override
public void rightFieldOnKeyReleased(String input) {
controlAndSet(input, 2);
}
@Override
public void leftFieldOnKeyReleased(String input) {
controlAndSet(input, 0);
}
@Override
public void bottomFieldOnKeyReleased(String input) {
controlAndSet(input, 3);
}
private void controlAndSet(String s, int index) {
int i = FAILURE;
if (s != null) {
try {
i = Integer.parseInt(s);
} catch (NumberFormatException e) {
i = FAILURE;
}
}
if (i == FAILURE) {
UserlistChangesMenu.this.skin.setUserlistPadding(null);
} else {
this.tmp[index] = i;
UserlistChangesMenu.this.skin.setUserlistPadding(this.tmp);
}
}
@Override
public int[] reset() {
UserlistChangesMenu.this.skin.setUserlistPadding(null);
this.tmp = UserlistChangesMenu.this.skin.getUserlistPadding();
return this.tmp;
}
});
}
|
c5c9652f-9995-4053-ad1f-6ad9457eb0c3
| 9
|
public ClassDescriptorSourceScript sourceFileSearch(boolean firstTime,SourceScriptRoot scriptFile,ClassDescriptorSourceFileRegistry sourceRegistry,LinkedList<ClassDescriptorSourceUnit> updatedSourceFiles,LinkedList<ClassDescriptorSourceUnit> newSourceFiles)
{
ClassDescriptorSourceScript scriptFileDesc = (scriptFile == null) ? null : processSourceFileScript(firstTime,scriptFile,sourceRegistry,updatedSourceFiles,newSourceFiles);
FileExt[] folderSourceList = parent.getFolderSourceList().getArray();
if (folderSourceList == null) // Es el caso de shell interactivo o code snippet
return scriptFileDesc;
boolean allEmpty = true;
String scriptFileJavaCannonPath = (scriptFile != null && (scriptFile instanceof SourceScriptRootFileJavaExt)) ? ((SourceScriptRootFileJavaExt)scriptFile).getFileExt().getCanonicalPath() : null;
for(int i = 0; i < folderSourceList.length; i++)
{
FileExt rootFolderOfSources = folderSourceList[i];
String[] children = rootFolderOfSources.getFile().list();
if (children == null) continue; // El que ha configurado los rootFolders es tonto y ha puesto alguno nulo o no es válido el path
if (children.length == 0) continue; // Empty
if (allEmpty) allEmpty = false;
recursiveSourceFileJavaSearch(firstTime,scriptFileJavaCannonPath, i ,rootFolderOfSources,children,sourceRegistry,updatedSourceFiles,newSourceFiles);
}
if (allEmpty)
throw new RelProxyException("All specified input source folders are empty");
return scriptFileDesc;
}
|
55d3c196-2311-4999-aca0-29d48ba2534d
| 6
|
public CardSetStats(Collection<Card> cardCollection) {
// Find dupes
Map<Rank, Set<Card>> rankMap = new HashMap<Rank, Set<Card>>();
for (Card card : cardCollection) {
Set<Card> dupeSet = rankMap.get(card.rank);
if (dupeSet == null) {
dupeSet = new HashSet<Card>();
}
dupeSet.add(card);
rankMap.put(card.rank, dupeSet);
}
Rank qr = null;
tripsList = new ArrayList<Rank>();
pairList = new ArrayList<Rank>();
Set<Rank> rankSet = new HashSet<Rank>();
for (Rank rank : rankMap.keySet()) {
switch (rankMap.get(rank).size()) {
case 4: qr = rank; break;
case 3: tripsList.add(rank); break;
case 2: pairList.add(rank); break;
}
rankSet.add(rank);
}
quadsRank = qr;
rankList = new ArrayList<Rank>(rankSet);
Collections.sort(tripsList);
Collections.sort(pairList);
Collections.sort(rankList);
}
|
84bf9ad5-d5e4-4086-ad38-f7058375741a
| 1
|
public final EsperParser.print_return print() throws RecognitionException {
EsperParser.print_return retval = new EsperParser.print_return();
retval.start = input.LT(1);
Object root_0 = null;
Token PRINT42=null;
EsperParser.expr_return expr43 =null;
Object PRINT42_tree=null;
try {
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:57:7: ( PRINT ^ expr )
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:57:9: PRINT ^ expr
{
root_0 = (Object)adaptor.nil();
PRINT42=(Token)match(input,PRINT,FOLLOW_PRINT_in_print570);
PRINT42_tree =
(Object)adaptor.create(PRINT42)
;
root_0 = (Object)adaptor.becomeRoot(PRINT42_tree, root_0);
pushFollow(FOLLOW_expr_in_print573);
expr43=expr();
state._fsp--;
adaptor.addChild(root_0, expr43.getTree());
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
|
dc6ce724-b890-45b6-a3c7-8d24b6eb7fda
| 2
|
public void printVal() {
int i = 0;
while (true) {
System.out.println(Thread.currentThread().getName() + " " + this.getVal() + "\t" + i );
if (i == 10000) {
break;
} else {
i++;
}
}
}
|
e2207939-4880-4884-9438-4a26145ee275
| 8
|
void drawboard(Graphics g) {
g.setColor(Color.black);
g.fillRect(0,0,getWidth(), getHeight());
sqw = getWidth()/xdim;
sqh = getHeight()/ydim;
// draw background panels
if (def != null) {
for (int y=0; y<ydim; y++) {
for (int x=0; x<xdim; x++) def.drawObject(g, x, y, sqw, sqh, this);
}
}
if (USEVEC) {
// draw each element in the vector
for (Enumeration e = boardVec.elements(); e.hasMoreElements();) {
boardContainer c = (boardContainer) e.nextElement();
c.o.drawObject(g,c.d.width, c.d.height, sqw, sqh, this);
}
} else {
// draw from grid
for (int y=0; y<ydim; y++) {
for (int x=0; x<xdim; x++)
if (board[x][y] != null)
board[x][y].drawObject(g, x, y, sqw, sqh, this);
}
}
}
|
4f692a47-b6a8-4b17-86c0-88f632057d58
| 5
|
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButton8ActionPerformed
{//GEN-HEADEREND:event_jButton8ActionPerformed
if (!gameover) {
if (rule.turn()) {
if (rule.check(1, 2)) {
rule.pressed(1, 2);
if (rule.changeTurn()) {
ai.takeTurn(this, rule, new Coordinate(1, 2));
if (!rule.winner().equalsIgnoreCase(winner)) {
gameover = true;
winner = rule.winner();
jLabel1.setText(winner);
}
}
else {
gameover = true;
winner = rule.winner();
jLabel1.setText(winner);
}
}
}
}
}//GEN-LAST:event_jButton8ActionPerformed
|
6d6ffc4e-d354-4171-b888-9e8b609fcef9
| 9
|
public void getClientCommand()
throws Exception
{
int Addr_Len;
SOCKS_Version = getByte();
socksCommand = getByte();
RSV = getByte();
ATYP = getByte();
Addr_Len = ADDR_Size[ATYP];
DST_Addr[0] = getByte();
if( ATYP==0x03 ) {
Addr_Len = DST_Addr[0]+1;
}
for( int i=1; i<Addr_Len; i++ ) {
DST_Addr[i]= getByte();
}
DST_Port[0] = getByte();
DST_Port[1] = getByte();
if( SOCKS_Version != Constants.SOCKS5_Version ) {
DebugLog.getInstance().println( "SOCKS 5 - Incorrect SOCKS Version of Command: "+
SOCKS_Version );
refuseCommand( (byte)0xFF );
throw new Exception("Incorrect SOCKS Version of Command: "+
SOCKS_Version);
}
if( (socksCommand < Constants.SC_CONNECT) || (socksCommand > Constants.SC_UDP) ) {
DebugLog.getInstance().error( "SOCKS 5 - GetClientCommand() - Unsupported Command : \"" + commName( socksCommand )+"\"" );
refuseCommand( (byte)0x07 );
throw new Exception("SOCKS 5 - Unsupported Command: \"" + socksCommand +"\"" );
}
if( ATYP == 0x04 ) {
DebugLog.getInstance().error( "SOCKS 5 - GetClientCommand() - Unsupported Address Type - IP v6" );
refuseCommand( (byte)0x08 );
throw new Exception( "Unsupported Address Type - IP v6" );
}
if( (ATYP >= 0x04) || (ATYP <=0) ) {
DebugLog.getInstance().error( "SOCKS 5 - GetClientCommand() - Unsupported Address Type: " + ATYP );
refuseCommand( (byte)0x08 );
throw new Exception( "SOCKS 5 - Unsupported Address Type: " + ATYP );
}
if( !calculateAddress() ) { // Gets the IP Address
refuseCommand( (byte)0x04 );// Host Not Exists...
throw new Exception( "SOCKS 5 - Unknown Host/IP address '" + m_ServerIP.toString()+"'" );
}
DebugLog.getInstance().println( "SOCKS 5 - Accepted SOCKS5 Command: \""+commName(socksCommand)+"\"" );
}
|
0d4d3fad-1273-48ce-938f-a1e22502ea50
| 1
|
public StructuredBlock appendBlock(StructuredBlock block) {
if (outer instanceof ConditionalBlock) {
IfThenElseBlock ifBlock = new IfThenElseBlock(
((ConditionalBlock) outer).getInstruction());
ifBlock.moveDefinitions(outer, this);
ifBlock.replace(outer);
ifBlock.moveJump(outer.jump);
ifBlock.setThenBlock(this);
}
block.replace(this);
return block;
}
|
c49d740d-7ac5-4628-ab8f-d62dee92fb50
| 5
|
protected static Ptg calcIsna( Ptg[] operands )
{
if( operands.length != 1 )
{
return PtgCalculator.getError();
}
if( operands[0] instanceof PtgErr )
{
PtgErr per = (PtgErr) operands[0];
if( per.getErrorType() == PtgErr.ERROR_NA )
{
return new PtgBool( true );
}
}
else if( operands[0].getIsReference() )
{
Object o = operands[0].getValue();
if( o.toString().equalsIgnoreCase( new PtgErr( PtgErr.ERROR_NA ).toString() ) )
{
return new PtgBool( true );
}
}
return new PtgBool( false );
}
|
9503dec0-daae-4378-bfa7-cd22277d636c
| 1
|
public void showMatrixS()
{
System.out.print("Second column");
System.out.println();
for(int j=0; j<rows; j++)
{
System.out.print(matrix[1][j]);
}
}
|
839bb807-8a98-4ce9-bf52-ff9d5e8e7529
| 7
|
public void go() {
try {
PrintWriter writer = new PrintWriter(new FileOutputStream("xkcdTitles.txt"));
for(int i = 1; i <= 1330; i++) {
if(i == 100 || i == 404 || i == 1037) {
System.out.println("Skipping " + Integer.toString(i));
continue;
}
File file = new File("XKCD/" + Integer.toString(i) + ".html");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String temp = "";
while((temp = reader.readLine()) != null) {
String r = "<title>xkcd: ";
if(temp.contains(r)) {
String[] title = temp.split(r);
title = title[1].split("</title>");
writer.write(title[0] + "\n");
writer.flush();
}
}
reader.close();
}
writer.close();
} catch(Exception ex) {ex.printStackTrace();}
}
|
6d617985-1b59-4007-bef2-77598ab50b96
| 4
|
public void setLineNumbers(final LineNumberDebugInfo[] lineNumbers) {
if (lineNumbers == null) {
for (int i = 0; i < attrs.length; i++) {
if (this.lineNumbers == attrs[i]) {
final Attribute[] a = attrs;
attrs = new Attribute[a.length - 1];
System.arraycopy(a, 0, attrs, 0, i);
System.arraycopy(a, i + 1, attrs, i, attrs.length - i);
break;
}
}
this.lineNumbers = null;
} else if (this.lineNumbers != null) {
this.lineNumbers.setLineNumbers(lineNumbers);
}
}
|
427d188f-0293-4025-9000-62e7f924ba70
| 0
|
public static void main(String[] args)
{
ParentInterface<String,String> P = null;
P = new ChildClass<String,String>("aaa");
P.setFoo2("ljgla");
System.out.println(P.getFoo2());
}
|
6eb88b41-4f3f-44a2-b363-259f45e8b9bd
| 9
|
public DataSourceImpl(List<String> data) {
final Pattern p = Pattern.compile("\\{[-+#!*/]?");
for (String s : data) {
final StringTokenizer st = new StringTokenizer(s, "|}", true);
while (st.hasMoreTokens()) {
final String token = st.nextToken().trim();
if (token.equals("|")) {
continue;
}
final Terminator terminator = st.hasMoreTokens() ? Terminator.NEWCOL : Terminator.NEWLINE;
final Matcher m = p.matcher(token);
final boolean found = m.find();
if (found == false) {
addInternal(token, terminator);
continue;
}
int lastStart = 0;
int end = 0;
do {
final int start = m.start();
if (start > lastStart) {
addInternal(token.substring(lastStart, start), Terminator.NEWCOL);
}
end = m.end();
final Terminator t = end == token.length() ? terminator : Terminator.NEWCOL;
addInternal(token.substring(start, end), t);
lastStart = end;
} while (m.find());
if (end < token.length()) {
addInternal(token.substring(end), terminator);
}
}
}
}
|
09bb7901-b887-4d8c-a397-2401fd40e9a9
| 1
|
@Test
public void pieniEsteVasemmalla() {
laitetaasPariPientaEstetta();
pe.siirra(900, 0);
pe.liikuVasemmalle();
for (int i = 0; i < 100; i++) {
pe.eksistoi();
}
assertTrue("Hahmo pääsi matalasta seinästä läpi vasemmalle paahtaessaan. x = "
+ pe.getX(), pe.getX() > 600);
}
|
d2f7389d-1396-425e-9289-c6a1829c74cc
| 7
|
public void invoke(MindMapNode pNode) {
// generate string to search for
StringBuffer sb = new StringBuffer();
List selecteds = getMindMapController().getSelecteds();
for (Iterator it = selecteds.iterator(); it.hasNext(); ) {
MindMapNode node = (MindMapNode) it.next();
// Convert to plain text
final String plainText = HtmlTools.htmlToPlain(node.getText());
if (sb.length() != 0) {
sb.append(" ");
}
sb.append(plainText);
}
final String searchText = sb.toString();
// First of all: ask user:
int showResult = new OptionalDontShowMeAgainDialog(
getMindMapController().getFrame().getJFrame(),
getMindMapController().getSelectedView(),
REALLY_SEARCH_FOR_NODE_TEXT_IN_WEB,
"confirmation",
new TextTranslator() {
public String getText(String pKey) {
String text = getMindMapController()
.getText(pKey);
if (pKey.equals(REALLY_SEARCH_FOR_NODE_TEXT_IN_WEB)) {
Object[] messageArguments = {searchText};
MessageFormat formatter = new MessageFormat(text);
text = formatter.format(messageArguments);
}
return text;
}
},
new OptionalDontShowMeAgainDialog.StandardPropertyHandler(
getMindMapController().getController(),
FreeMind.RESOURCES_SEARCH_FOR_NODE_TEXT_WITHOUT_QUESTION),
OptionalDontShowMeAgainDialog.ONLY_OK_SELECTION_IS_STORED)
.show().getResult();
if (showResult != JOptionPane.OK_OPTION) {
return;
}
// is the map open? Ask base class.
Registration registration = getRegistration();
if (registration != null) {
// is the map open?
MapDialog mapDialog = registration.getMapDialog();
if (mapDialog == null) {
// if not, open it!
getMindMapController().createModeControllerHook(
MapDialog.MAP_HOOK_NAME);
}
mapDialog = registration.getMapDialog();
if (mapDialog != null) {
mapDialog.setSingleSearch();
mapDialog.search(sb.toString(), true);
} else {
logger.warning("Can't find dialog to connect to!");
}
} else {
logger.warning("Can't find registration base class!");
}
}
|
0f6a01b2-3d24-491e-a764-aa6ed7a2ea78
| 6
|
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Vista vist = new Vista();
vist.setLocationRelativeTo(null);
vist.setVisible(true);
}
});
}
|
f3f78a75-ef32-460f-b012-cc98ede37291
| 3
|
boolean boardFull(){
for(int j = 0; j < HEIGHT; j++){
for(int i = 0; i < WIDTH; i++){
if(m_Pieces[i][j].equals(m_EmptyPiece)){
return false;
}
}
}
return true;
}
|
28949bf0-e020-436d-b943-602b2eadda3e
| 2
|
public int getAdjacentBlank(State s,Hexpos hp){
// iterate over a list of all neighbours
int adjacent=0;
MyList neighbours = hp.neighbours();
Iterator it = neighbours.iterator();
while (it.hasNext()) {
Hexpos neighbour = (Hexpos) it.next();
// only 'change' ownership if the square was not empty
if (s.owner(neighbour) == null)
adjacent++;
// changeOwner(player, neighbour);
}
return adjacent;
}
|
2838c08f-f540-4ba7-9260-aa3736462d52
| 9
|
public void loadFromObject() { try {
if (cls==null) return;
for (int i=0; i<fields.size(); i++) {
String fieldname = (String)fields.get(i);
String fieldtype = (String)fieldtypes.get(fieldname);
//System.out.println("<field "+fieldname+" "+fieldvalue);
if (fieldtype.equals("key")
|| fieldtype.equals("int")
|| fieldtype.equals("double")
|| fieldtype.equals("boolean")
|| fieldtype.equals("String") ) {
Field field = cls.getField(fieldname);
// if obj==null we get a static field
fieldvalues.put(fieldname, field.get(obj));
} else {
System.out.println("not implemented!");
}
}
} catch (NoSuchFieldException e) {
throw new JGameError("Field not found.");
} catch (IllegalAccessException e) {
throw new JGameError("Field cannot be accessed.");
} }
|
b8aa4355-e091-4c06-ae3d-79a9f1825e14
| 6
|
static Object[][] add(Object[][] x, Object[][] y) {
Object[][] ret = new Object[x.length][];
for (int i = 0; i < x.length; i++) {
ret[i] = new Object[x[i].length];
for (int j = 0; j < x[i].length; j++) {
Object a = x[i][j];
Object b = y[i][j];
if (a == null || b == null) {
ret[i][j] = null;
} else if (a instanceof Integer) {
ret[i][j] = (Integer) a + (Integer) b;
} else if (a instanceof Double) {
ret[i][j] = (Double) a + (Double) b;
} else {
ret[i][j] = ((BigInteger) a).add((BigInteger) b);
}
}
}
return ret;
}
|
2a00b6f7-5267-4f9b-827d-d91700a7f689
| 2
|
private void shiftStackTwoUp(){
if(array[stack2StartIndex]==null){
stack2StartIndex++;
return;
}
else{
Object current = array[stack2StartIndex];
Object next = array[stack2StartIndex+1];
Object temp = next;
array[stack2StartIndex+1] = current;
array[stack2StartIndex] = null;
stack2StartIndex++;
while(temp!=null){
current = next;
next = array[stack2StartIndex+1];
temp = next;
array[stack2StartIndex+1] = current;
}
}
}
|
1f84e6b1-3ffb-4ed1-a9c4-17e90cf5fb69
| 2
|
public void addPhi(final Block block) {
if (phis[cfg.preOrderIndex(block)] != null) {
return;
}
final VarExpr target = (VarExpr) prototype.clone();
final PhiJoinStmt phi = new PhiJoinStmt(target, block);
phis[cfg.preOrderIndex(block)] = phi;
if (SSA.DEBUG) {
System.out.println(" place " + phi + " in " + block);
}
}
|
fcc6f1fe-6446-4eef-a706-c1bacf6c2d73
| 1
|
public boolean running() {
try {
process.exitValue();
return false;
} catch (IllegalThreadStateException e) {
return true;
}
}
|
72f2f026-ea1e-4d01-8b1d-e5c897ff388b
| 8
|
public void visit_fload(final Instruction inst) {
final int index = ((LocalVariable) inst.operand()).index();
if (index + 1 > maxLocals) {
maxLocals = index + 1;
}
if (inst.useSlow()) {
if (index < 256) {
addOpcode(Opcode.opc_fload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_fload);
addShort(index);
}
stackHeight++;
return;
}
switch (index) {
case 0:
addOpcode(Opcode.opc_fload_0);
break;
case 1:
addOpcode(Opcode.opc_fload_1);
break;
case 2:
addOpcode(Opcode.opc_fload_2);
break;
case 3:
addOpcode(Opcode.opc_fload_3);
break;
default:
if (index < 256) {
addOpcode(Opcode.opc_fload);
addByte(index);
} else {
addOpcode(Opcode.opc_wide);
addByte(Opcode.opc_fload);
addShort(index);
}
break;
}
stackHeight++;
}
|
d81bf708-f7f0-4bb9-a8a3-a3c5f874738f
| 7
|
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(postorder.length == 0 || inorder.length == 0) return null;
TreeNode mid = new TreeNode(postorder[postorder.length-1]);
if(postorder.length == 1) return mid;
int midIndex = -1;
for(int i=0; i< inorder.length; i++)
{
if(inorder[i] == mid.val)
{
midIndex = i;
break;
}
}
int[] leftInorder = {}, leftpostorder= {};
if(midIndex>0)
{
leftInorder = Arrays.copyOfRange(inorder, 0, midIndex);
leftpostorder = Arrays.copyOfRange(postorder, 0, midIndex);
}
int[] rightInorder= {}, rightpostorder= {};
if(midIndex<inorder.length-1)
{
rightInorder = Arrays.copyOfRange(inorder, midIndex+1, inorder.length-1);
rightpostorder = Arrays.copyOfRange(postorder, midIndex , postorder.length-2);
}
mid.left = buildTree(leftInorder, leftpostorder);
mid.right = buildTree(rightInorder, rightpostorder);
return mid;
}
|
646051a3-141d-407c-84ef-68cf95d13f8a
| 2
|
public void getStudents(String courseID) throws Exception {
String sql;
PreparedStatement st;
ResultSet rs;
Connection db = ConnectionUtils.getConnection();
//String student_ID = UserLogin.id;
// get the student information
sql = "select course.crs_ID, course.crs_name, student.student_ID, "
+ "student.first_name, student.last_name FROM course, student, "
+ "section, enrollment where course.crs_ID =? AND course.crs_ID "
+ "= section.crs_ID AND section.section_ID = "
+ "enrollment.section_ID AND enrollment.student_ID = "
+ "student.student_ID;";
st = db.prepareStatement(sql);
st.setString(1, courseID);
rs = st.executeQuery();
if (!rs.next()) {
throw new IllegalArgumentException("invalid course id");
}
ResultSetMetaData rsmd = rs.getMetaData();
courses = new String[rsmd.getColumnCount()][2];
setColumns(rsmd.getColumnCount());
String tempID = "";
String tempfirst = "";
String templast = "";
tempID = rs.getString(3);//student id
tempfirst = rs.getString(4);
templast = rs.getString(5);
int i = 0;
courses[i][0] = tempID;//student id
courses[i][1] = tempfirst + " " + templast;//name
i++;
while(rs.next())
{
tempID = rs.getString(3);//student id
tempfirst = rs.getString(4);
templast = rs.getString(5);
courses[i][0] = tempID;//student id
courses[i][1] = tempfirst + " " + templast;//name
i++;
//courses[i][2] = rs.getString(5);
}
rs.close();
st.close();
db.close();
}
|
2901e29e-9489-42b8-8d6f-b3eb54ccab55
| 4
|
public File askForTargetArchive(File def) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String suffix = model.getAlgorithm().getSuffix();
while (true) {
try {
sysOut.println(bundle.getString("path_correct_suffix") + " \"" + suffix + "\".");
sysOut.print(bundle.getString("enter_archive") + ": [" + def + "] ");
String input = br.readLine();
if (input.equalsIgnoreCase("")) {
return def;
}
if (input.endsWith(suffix)) {
return new File(input);
}
} catch (IOException ex) {
displayError(bundle.getString("error_console_read"),
ex.getLocalizedMessage());
}
}
}
|
4737c35d-e0db-4155-8573-025b629646bd
| 3
|
void addData(String fn, String id,String name, float price) {
File fname = new File(fn);
FileOutputStream f_out = null;
BufferedOutputStream b_out = null;
DataOutputStream d_out = null;
try {
f_out = new FileOutputStream(fname,true);
b_out = new BufferedOutputStream(f_out);
d_out = new DataOutputStream(b_out);
d_out.writeUTF(id);
d_out.writeUTF(name);
d_out.writeFloat(price);
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
if (d_out != null)
d_out.close();
}
catch (IOException e){
System.out.println(e);
}
}
}
|
7d502b19-0953-4d94-97e8-0e4287af3578
| 6
|
public char[] othelierTab()
{
char []TAB=new char[66];
if(this.tour==Pion.NOIR)
TAB[0]='X';
else
TAB[0]='O';
// TAB[1]=difficultee;
for(int i=0,k=2;i<NB_LIGNE;i++)
{
for(int j=0;j<NB_COLONNE;j++,k++)
{
Position p=new Position(i,j);
if(getCasePion(p) instanceof Pion)
{
if(((Pion)getCasePion(p)).estBlanc())
{
TAB[k]='O';
}
if(((Pion)getCasePion(p)).estNoir())
{
TAB[k]='X';
}
}
}
}
return TAB;
}
|
b6cc22ae-9555-4341-8d8d-54ef2b8e8d0a
| 0
|
public AbstractPlay getRelatedPlay(){
return this.relatedPlay;
}
|
846ad7cd-540c-4ad5-829a-6cda6ebcb0b0
| 0
|
public float getVelocityX() {
return dx;
}
|
6392725d-c3a8-4412-a105-6b43f029c541
| 8
|
public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
}
|
dddad6fc-53b6-4a8a-816d-5534814abc3b
| 9
|
private void rotate_nearest_z(final Image image, final Image rotated) {
// Initialization:
messenger.log("Nearest-neighbor sampling in x-y");
progressor.status("Rotating"+component+"...");
progressor.steps(odims.c*odims.t*odims.z*odims.y);
// Rotate using the inverse of the rotation matrix:
final Coordinates ci = new Coordinates();
final Coordinates co = new Coordinates();
final double[] row = new double[odims.x];
rotated.axes(Axes.X);
progressor.start();
for (co.c=ci.c=0; co.c<odims.c; ++co.c, ++ci.c) {
for (co.t=ci.t=0; co.t<odims.t; ++co.t, ++ci.t) {
for (co.z=ci.z=0; co.z<odims.z; ++co.z, ++ci.z) {
for (co.y=0; co.y<odims.y; ++co.y) {
final double dy = co.y*ovy - oyc;
final double xcdysinaz = ixc + dy*sinaz;
final double ycdycosaz = iyc + dy*cosaz;
for (int x=0; x<odims.x; ++x) {
final double dx = x*ovx - oxc;
ci.x = FMath.round((xcdysinaz + dx*cosaz)/ivx);
ci.y = FMath.round((ycdycosaz - dx*sinaz)/ivy);
if (ci.x < 0 || ci.x > imaxx ||
ci.y < 0 || ci.y > imaxy) {
row[x] = background;
} else {
row[x] = image.get(ci);
}
}
rotated.set(co,row);
progressor.step();
}
}
}
}
progressor.stop();
}
|
6d6387f1-982b-4e86-b9da-3b37565e74c0
| 2
|
public ICacheable remove(Object key){
if (key == null) {
throw new NullPointerException("key == null");
}
ICacheable previous = null;
synchronized (this) {
previous = mCacheMap.remove(key);
if (previous != null) {
mCurrSize -= safeSizeOf(key, previous);
}
}
return previous;
}
|
4c3a8235-f434-43e2-acfb-81058be95ac1
| 3
|
public static boolean setWindowsExplorerActive(boolean active) {
boolean ret = false;
if (active) {
try {
ret = WindowsExplorer.start();
} catch (IOException
| InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
ret = WindowsExplorer.shutdown();
} catch (IOException
| InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ret;
}
|
b5258621-7766-4b93-af47-25e9e3675daf
| 4
|
public void updateViews() {
View tab = tabWindow.getFocusedView();
if (tab == curTab)
return;
if (tab instanceof NSMBeTab) {
curTab = (NSMBeTab)tab;
for (View v : rootViews) {
if (v instanceof NSMBeView) {
((NSMBeView)v).update(curTab);
}
}
}
}
|
698f6119-e2a6-40d7-a0fd-7a59f86b7146
| 4
|
public void parseVersion(String inString){
try{
if(inString.contains(".")){
// there is more than one integer
int occurances = countOccurrencesOf(inString, '.');
for(int i = 0; i < occurances; i++){
int nextOccurance = inString.indexOf('.');
String number = inString.substring(0, nextOccurance);
versionString += inString.substring(0, nextOccurance);
intList.add(Integer.parseInt(number));
inString = inString.substring(nextOccurance +1 );
if(i < occurances-1){
versionString+=".";
}
}
intList.add(Integer.parseInt(inString));
}
else { // otherwise its just one number
intList.add(Integer.parseInt(inString));
}
}
catch(NumberFormatException e){
intList.add(0);
}
}
|
2ca4c1cc-af4b-40d3-890c-0fff08db8ded
| 5
|
private static void readMessageAux(Core output, Document xml, XmlMessage type) {
if (type == XmlMessage.DESCONECTAR) readInDesconectar(output, xml);
else if (type == XmlMessage.PESO) readInPeso(output, xml);
else {
String updateId = xml.getElementsByTagName(UPDATEID).item(HEAD).getTextContent();
switch (type) {
case CONNECTION:
readInConnection(output, xml, updateId);
break;
case GRAFO:
readInGrafo(output, xml, updateId);
break;
case MENSAJE:
readInMessage(output, xml, updateId);
break;
}
}
}
|
ad6d187d-50c4-4b58-9c70-83201f17ce59
| 0
|
public Point2D getRelativeChunkCenter()
{
return new Point2D.Double(getChunkSideLength()/2.0, getChunkSideLength()/2.0);
}
|
8bb3e8d6-40ca-4bd2-bab2-8c8af39193a4
| 3
|
private void sort(int[] A, int low, int high){
if(high - low == 1){
if(A[high] < A[low]) {
exchange(A, low, high);
}
}
if(high - low > 1) {
int mid = (int)Math.ceil(2.0 * (high - low + 1) / 3.0);
sort(A, low, low + mid - 1);
sort(A, high - mid + 1, high);
sort(A, low, low + mid - 1);
}
}
|
377bb667-415f-42bb-829f-83c9115e98e7
| 8
|
public String getRecommendListForTransition(){
String recommend = "";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/NETWORK_TEST?"
+ "user=root&password=root");
connect.setAutoCommit(false);
statement = connect.createStatement();
String sql = "UPDATE NETWORK_TEST." + this.table + "Sim"
+ " SET SIM_VALUE = '0', PATH = '0' where (START_NODE, END_NODE) "
+ "not in (select START_NODE, END_NODE from network_test." + this.table + ")";
statement.execute(sql);
for (String node : nodeList) {
String recommendSql = "select se.START_NODE, se.END_NODE, (sm.SIM_VALUE * me.SIM_VALUE) as SIM_VALUE"
+ " from network_test." + this.table + "sim"
+ " as sm, network_test." + this.table + "sim"
+ " as me, network_test." + this.table + "sim"
+ " as se where sm.START_NODE <> sm.END_NODE and me.START_NODE <> me.END_NODE and se.START_NODE <> se.END_NODE"
+ " and sm.PATH = 1 and me.PATH = 1 and se.PATH = 0"
+ " and sm.START_NODE = '" + node + "' and se.START_NODE = '" + node + "'"
+ " and sm.END_NODE = me.START_NODE and me.END_NODE = se.END_NODE"
+ " group by START_NODE, END_NODE order by SIM_VALUE desc limit 10";
resultSet = statement.executeQuery(recommendSql);
recommend += node + ":";
while (resultSet.next()) {
String recommendNode = resultSet.getString("END_NODE");
recommend += recommendNode + ",";
}
recommend += "\n";
}
connect.commit();
statement.close();
connect.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
if(statement!=null)
statement.close();
} catch(SQLException se2) {
}// nothing we can do
try{
if(connect!=null)
connect.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
return recommend;
}
|
c20b917d-8232-4b1b-82c6-5b49c28a7bde
| 3
|
public static void addToShopList(String[] newList){
String[] combineList;
int i = 0;
if (shopListArr == null){
combineList = new String[newList.length];
}else{
combineList = new String[shopListArr.length + newList.length];
for ( ;i < shopListArr.length;i++)
combineList[i] = shopListArr[i];
}
for (int j=0; j<newList.length;j++,i++)
combineList[i] = newList[j];
shopListArr = combineList;
}
|
d72dba11-fa95-4e22-a4b0-57c3251460fc
| 8
|
*/
public void rename(Nameable object) {
Player player = freeColClient.getMyPlayer();
if (!(object instanceof Ownable)
|| !player.owns((Ownable) object)) {
return;
}
String name = null;
if (object instanceof Colony) {
Colony colony = (Colony) object;
name = gui.showInputDialog(colony.getTile(),
StringTemplate.key("renameColony.text"), colony.getName(),
"renameColony.yes", "renameColony.no", true);
if (name == null) {
// User cancelled, 0-length invalid.
return;
} else if (colony.getName().equals(name)) {
// No change
return;
} else if (player.getSettlement(name) != null) {
// Colony name must be unique.
gui.showInformationMessage((Colony) object,
StringTemplate.template("nameColony.notUnique")
.addName("%name%", name));
return;
}
} else if (object instanceof Unit) {
Unit unit = (Unit) object;
name = gui.showInputDialog(unit.getTile(),
StringTemplate.key("renameUnit.text"), unit.getName(),
"renameUnit.yes", "renameUnit.no", false);
if (name == null) return; // User cancelled, 0-length clears name.
} else {
logger.warning("Tried to rename an unsupported Nameable: "
+ object.toString());
return;
}
askServer().rename((FreeColGameObject) object, name);
}
|
60561aca-a250-4579-a61c-ab7f248ca643
| 4
|
protected List<Integer> getAllPrimes() {
boolean[] sito = new boolean[N];
for (int i = 1; i < sito.length; i++) {
sito[i] = true;
}
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < sito.length; i++) {
if (sito[i]) {
int i1 = i + 1;
list.add(i1);
int x = 2;
int j = (i1 * x);
while (j <= N) {
sito[j - 1] = false;
x++;
j = (i1 * x);
}
}
}
return list;
}
|
6e721b1a-9afd-4605-b193-34da2a0306cf
| 9
|
public static char convertFromString(String s) {
// if (s.contains("E")) {
// return 'E';
//}
if (s.contains("M")) {
return 'M';
}
if (s.contains("D")) {
return 'D';
}
if (s.contains("C")) {
return 'C';
}
if (s.contains("L")) {
return 'L';
}
if (s.contains("X")) {
return 'X';
}
if (s.contains("V")) {
return 'V';
}
if (s.contains("I")) {
return 'I';
}
if (s.contains("S")) {
return 'S';
}
if (s.contains("*")) {
return '*';
}
return 'A';
}
|
1f94afa8-5f80-4d82-bd07-5894e01aed14
| 5
|
private void addShadows(Bitmap tile){
if (isShadowed_north) {
tile.blit(Art.shadow_north, 0, 0);
} else {
if (isShadowed_north_east) {
tile.blit(Art.shadow_north_east, Tile.WIDTH - Art.shadow_east.w, 0);
}
if (isShadowed_north_west) {
tile.blit(Art.shadow_north_west, 0, 0);
}
}
if (isShadowed_east) {
tile.blit(Art.shadow_east, Tile.WIDTH - Art.shadow_east.w , 0);
}
if (isShadowed_west) {
tile.blit(Art.shadow_west, 0, 0);
}
}
|
06209935-7baf-4014-a31d-a15170f69aaf
| 7
|
private String changed(String inp, int len) {
StringBuilder c = new StringBuilder();
int count = 0;
int b = 0;
boolean first = true;
for (int i = 0; i < inp.length(); i++) {
char ch = inp.charAt(i);
switch (ch) {
case ' ':
break; // TODO, repect string quotes.
case LB:
case RB:
case SEP:
first = true;
c.append(ch);
break;
default:
if (first) {
c.append(count++);
first = false;
}
}
}
if (count != len) {
throw new IllegalArgumentException(count + "!=" + len);
}
return c.toString();
}
|
adc8e0c7-c6cd-40f1-9a5a-2e3c02db280c
| 4
|
public void verifyBallCollides(Ball ball) {
//TODO: refactor this.
for (Collidable collidable : this.getCollidables()) {
GameComponent<?> component = collidable.asComponent();
if (CollisionDetector.INSTANCE.collidesCircleAgainstRect(ball.getCirc(), component.getRect())) {
// Notify collides ball with component
ball.collide(collidable);
collidable.collidedBy(ball);
}
}
if (this.getBlocks().isEmpty()) {
this.win();
}
}
|
9b0d9545-9479-4e06-a957-1fe21d4361a2
| 1
|
public void setMusicPlaying(final boolean m) {
musicPlaying = m;
if (musicPlaying) {
SoundStore.get().restartLoop();
}
else {
SoundStore.get().pauseLoop();
}
}
|
09712ca8-f97e-4566-968c-fe0b312d581b
| 0
|
protected synchronized Integer initialValue() {
return rand.nextInt(10000);
}
|
f21cbb1d-a2f1-4795-bc05-1d88c7f26d0f
| 1
|
@Override
public List<Integer> delete(Criteria criteria, GenericDeleteQuery deleteGeneric, Connection conn) throws DaoQueryException {
List paramList = new ArrayList<>();
StringBuilder sb = new StringBuilder(DELETE_QUERY);
String queryStr = new QueryMapper() {
@Override
public String mapQuery() {
Appender.append(DAO_ID_DIRECTION, DB_DIRCITY_ID_DIRECTION, criteria, paramList, sb, AND);
Appender.append(DAO_ID_CITY, DB_DIRCITY_ID_CITY, criteria, paramList, sb, AND);
return sb.toString();
}
}.mapQuery();
try {
return deleteGeneric.sendQuery(queryStr, paramList.toArray(), conn);
} catch (DaoException ex) {
throw new DaoQueryException(ERR_DIR_CITY_DELETE, ex);
}
}
|
0c520d9a-7883-4bfa-bf38-74dc9a0d7750
| 9
|
public static Object newInstance(Node xml) {
try {
Class<?> c = Class.forName(xml.getNodeName());
Constructor<?> constructor =
c.getConstructor(new Class[] { Class.forName("org.w3c.dom.Element") });
return constructor.newInstance(xml);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
|
070bdac8-9ef0-4e1d-bf4f-155da3dfaa6e
| 5
|
public void login(PlayerDetails details) throws Exception {
int response = Constants.LOGIN_RESPONSE_OK;
// Check if the player is already logged in.
for (Player player : World.getWorld().getPlayers()) {
if (player == null) {
continue;
}
if (player.getUsername().equals(details.getUsername())) {
response = Constants.LOGIN_RESPONSE_ACCOUNT_ONLINE;
}
}
// Load the player and send the login response.
int status = 1 /* load this player bitch!*/;
if (status == 2) { // Invalid username/password.
response = Constants.LOGIN_RESPONSE_INVALID_CREDENTIALS;
}
PacketBuilder resp = new PacketBuilder();
resp.put((byte) response);
resp.put((byte) /* login.getStaffRights() */0);
resp.put((byte) 0);
details.getSession().write(resp.toPacket());
if (response != 2) {
details.getSession().disconnect();
return;
}
Player login = new Player(details);
details.getSession().setAttachment(login);
World.getWorld().register(login);
login.getActionSender().sendLogin();
System.out.println(login + " has logged in.");
}
|
41d68eaa-c831-4586-ae04-39809cfef509
| 4
|
public static void main(String[] args) {
// 初始化一个Callable对象和FutureTask对象
Callable pAccount = new PrivateAccount();
FutureTask futureTask = new FutureTask(pAccount);
// 使用futureTask创建一个线程
Thread pAccountThread = new Thread(futureTask);
System.out.println("futureTask线程现在开始启动,启动时间为:" + System.nanoTime());
pAccountThread.start();
System.out.println("主线程开始执行其他任务");
// 从其他账户获取总金额
int totalMoney = new Random().nextInt(100000);
System.out.println("现在你在其他账户中的总金额为" + totalMoney);
System.out.println("等待私有账户总金额统计完毕...");
// 测试后台的计算线程是否完成,如果未完成则等待
while (!futureTask.isDone()) {
try {
Thread.sleep(500);
System.out.println("私有账户计算未完成继续等待...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("futureTask线程计算完毕,此时时间为" + System.nanoTime());
Integer privateAccountMoney = null;
try {
privateAccountMoney = (Integer) futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("您现在的总金额为:" + totalMoney + privateAccountMoney.intValue());
}
|
d423c9a0-8d8e-43ce-8af0-540319e51fae
| 0
|
public StopRangeGroup getGroup() {
return this._group;
}
|
a6d2c3f2-67c4-47fa-afbc-ff16daa63b1a
| 7
|
private TreeMap<Integer, Integer> notWantedColor(int nbCouleur, TreeMap< Integer, TreeSet<Integer>> couleurNonVoulue)
{
TreeMap<Integer, TreeSet<Integer>> couleurPossible = new TreeMap<Integer, TreeSet<Integer>>();
ArrayList<Integer> elementNonColorie = new ArrayList<Integer>();
for(Integer key : noeuds.keySet())
{
couleurPossible.put(key, new TreeSet<Integer>());
elementNonColorie.add(key);
}
for(Map.Entry<Integer, TreeSet<Integer>> entry : couleurPossible.entrySet())
{
for(int i = 0; i < nbCouleur; ++i)
{
entry.getValue().add(i);
}
}
for(Integer noeud : couleurNonVoulue.keySet())
{
if(couleurPossible.get(noeud) != null)
{
for(Integer i :couleurNonVoulue.get(noeud))
{
TreeSet<Integer> couleurPotentiel = couleurPossible.get(noeud);
couleurPotentiel.remove(i);
couleurPossible.put(noeud, couleurPotentiel);
}
}
}
TreeMap<Integer, Integer> resultat = colorieur(new TreeMap<Integer, Integer>(), couleurPossible);
if(resultat == null)
{
//TODO envoye erreur pas possible colorier avec les contraintes de couleur demande
}
else
{
// OK!
}
return resultat;
}
|
9f36576b-7327-463c-a137-4954cb9f2d5e
| 7
|
public String getBrowserEXEpath (String browserName, String browserVersion){
String browserEXEpath = "" ;
try{
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
//Getting the instance of DocumentBuilderFactory
domFactory.setNamespaceAware(true);
//true if the parser produced will provide support for XML namespaces;
DocumentBuilder builder = domFactory.newDocumentBuilder();
//Creating document builder
String xmlFilePath= this.getEnvVariablesXMLfilepath().trim(); //"D:\\workspace\\Roark_ver2\\TAF_Demo\\Configuration\\EnvironmentVariables.xml";
Document doc = builder.parse(xmlFilePath);
XPath xpath = XPathFactory.newInstance().newXPath();
//getting instance of xPath
XPathExpression expr = xpath.compile("//Browsers/browser[@name='"+browserName.toUpperCase().trim()+"']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if(nodes.getLength()!=0){
for (int i = 0; i < nodes.getLength(); i++) {
try{
int attriLen = nodes.item(i).getAttributes().getLength();
for(int j=0;j<attriLen; j++){
if(nodes.item(i).getAttributes().item(j).getNodeName().equalsIgnoreCase("exePath")==true){
browserEXEpath= nodes.item(i).getAttributes().item(j).getNodeValue();
logger.info("browserEXEpath:"+browserEXEpath);
break;
}
}
}catch(Exception e){
browserEXEpath= "NOT_FOUND";
logger.error("Exception in getBrowserEXEpath - \n stacktraceInfo::"+e.getMessage());
}
}
}else{
browserEXEpath="NOT_FOUND";
logger.error("browserEXEpath is set to NOT_FOUND ");
}
}catch(Exception e){
//e.printStackTrace();
browserEXEpath="NOT_FOUND";
logger.error("Exception in getBrowserEXEpath - \n stacktraceInfo::"+e.getMessage());
}
if(browserEXEpath.equals("")== true){
browserEXEpath="NOT_FOUND";
}
return browserEXEpath;
}
|
7b527bcb-602e-4cf9-ae52-384511ba552e
| 2
|
public int getSize() {
return type == Type.LONG_TYPE || type == Type.DOUBLE_TYPE ? 2 : 1;
}
|
20934031-782f-490f-b93a-8c15359c5351
| 9
|
@Override
public boolean remove(E value) {
Node<E> link=head;
while(link!=null&&!value.equals(link.value)) {
link=link.next;
}
if (link == null) return false;
Node<E> prev = link.prev;
Node<E> next = link.next;
if(prev!=null&&next!=null){
prev.next=next;
next.prev=prev;
}else if(prev!=null&&next==null){
prev.next=null;
tail=prev;
}else if(next!=null&&prev==null){
next.prev=null;
head=next;
}else{
head=null;
tail=null;
}
size--;
return true;
}
|
84eb218e-3b6e-42f2-b40a-0f38bdc066bc
| 0
|
@Override
public void loadConsole() throws DataLoadFailedException {
Map<String, Object> data = getData("server", "name", "console");
load(PermissionType.CONSOLE, "console", data);
}
|
15e81bd0-7355-4070-b349-d11f3327f445
| 4
|
public void setPaused(boolean paused) {
if (this.paused != paused && sequencer != null && sequencer.isOpen()) {
this.paused = paused;
if (paused) {
sequencer.stop();
}
else {
sequencer.start();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.