method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
a9f39980-69cf-4a28-aee4-96bcce2fa410 | 5 | public void eventDispatched(AWTEvent event) {
if (MouseEvent.MOUSE_CLICKED == event.getID() && event.getSource() != button) {
Set<Component> components = getAllComponents(datePanel);
boolean clickInPopup = false;
for (Component component : components) {
if (event.getSource() == component) {
clickInPopup = true;
}
}
if (!clickInPopup) {
hidePopup();
}
}
} |
5adb0d4f-3e74-40b5-a63e-2c923b81d7f8 | 9 | private Color getColor(SquareType square) {
if (square == null) {
return Color.WHITE;
} else {
switch (square) {
//I, L , J, T, O, S, Z, EMPTY, OUTSIDE;
case I:
return Color.BLUE;
case L:
return Color.RED;
case J:
return Color.CYAN;
case T:
return Color.GREEN;
case O:
return Color.ORANGE;
case S:
return Color.GRAY;
case Z:
return Color.PINK;
//case EMPTY: return '¨';
case OUTSIDE:
return Color.BLACK;
}
}
return Color.MAGENTA;
} |
4884c44f-5637-40ed-b4ad-24c7373ad600 | 4 | public void buildcountytable(List<Tuple> tups, StateProfile result) {
Iterator<Tuple> tupiter = tups.iterator();
while (tupiter.hasNext())
{
Tuple t = tupiter.next();
outputService.getCountyProfile(result.getStateInfo().getID(), t.getId(), new AsyncCallback<CountyProfile>() {
public void onFailure(Throwable caught) {
return;
}
public void onSuccess(CountyProfile result) {
if (result.getCountyInfo().getName().equals(countylistbox.getValue(countylistbox.getSelectedIndex())))
{
int seventy = result.getCountyInfo().get1970();
int eighty = result.getCountyInfo().get1980();
int ninety = result.getCountyInfo().get1990();
int two = result.getCountyInfo().get2000();
int twoten = result.getCountyInfo().get2010();
DataTable data = DataTable.create();
data.addColumn(ColumnType.STRING, "Year");
data.addColumn(ColumnType.NUMBER, result.getCountyInfo().getName());
data.addColumn(ColumnType.NUMBER, result.getStateInfo().getName());
if (!useGrowth.isChecked())
{
data.addRows(5);
data.setValue(0, 0, "1970");
data.setValue(1, 0, "1980");
data.setValue(2, 0, "1990");
data.setValue(3, 0, "2000");
data.setValue(4, 0, "2010");
data.setValue(0, 1, seventy);
data.setValue(1, 1, eighty);
data.setValue(2, 1, ninety);
data.setValue(3, 1, two);
data.setValue(4, 1, twoten);
data.setValue(0, 2, result.getStateInfo().get1970());
data.setValue(1, 2, result.getStateInfo().get1980());
data.setValue(2, 2, result.getStateInfo().get1990());
data.setValue(3, 2, result.getStateInfo().get2000());
data.setValue(4, 2, result.getStateInfo().get2010());
updatechart(data);
}
else
{
data.addRows(4);
data.setValue(0, 0, "1970");
data.setValue(1, 0, "1980");
data.setValue(2, 0, "1990");
data.setValue(3, 0, "2000");
data.setValue(0, 1, 100*((eighty / seventy)/ eighty));
data.setValue(1, 1, 100*((ninety / eighty) / ninety));
data.setValue(2, 1, 100*((two / ninety) / two));
data.setValue(3, 1, 100*((twoten / two) / twoten));
seventy = result.getStateInfo().get1970();
eighty = result.getStateInfo().get1980();
ninety = result.getStateInfo().get1990();
two = result.getStateInfo().get2000();
twoten = result.getStateInfo().get2010();
data.setValue(0, 2, 100*((eighty / seventy)/ eighty));
data.setValue(1, 2, 100*((ninety / eighty) / ninety));
data.setValue(2, 2, 100*((two / ninety) / two));
data.setValue(3, 2, 100*((twoten / two) / twoten));
updatechart(data);
}
}
Iterator<Tuple> placeiter = result.getPlaceTuples().iterator();
placelistbox.clear();
handlePlacelist(result);
while (placeiter.hasNext()) {
placelistbox.addItem(placeiter.next().getName());
}
}
});
}
} |
e4c08969-dbc9-43ea-b065-33008d33efd8 | 2 | public static void drawHerbsMinimap(GOut g, Coord tc, Coord hsz) {
if(UI.instance.minimap == null) return;
synchronized (UI.instance.minimap.hherbs) {
for (Pair<Coord, String> arg : UI.instance.minimap.hherbs) {
Coord ptc = arg.fst.div(tileSize).add(tc.inv())
.add(hsz.div(2));
g.chcolor(Color.GRAY);
g.fellipse(ptc, new Coord(10, 10));
g.chcolor();
//drawing icon
String resn = arg.snd;
Resource res = Resource.load(resn);
res.loadwait();
g.image(res.layer(Resource.imgc).tex(), ptc.sub(new Coord(10, 10)), new Coord(20, 20));
}
}
} |
f5cb831b-f710-42ec-b8f3-42fb03f00cb1 | 1 | @Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
try
{
g.drawImage(object.getSprite(), 5, 5, null);
}
catch(NullPointerException e) {}
} |
3ea9523e-4f84-4afe-be21-61026182a985 | 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(AdresseBok.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AdresseBok.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AdresseBok.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AdresseBok.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AdresseBok().setVisible(true);
}
});
} |
b4b148d7-b322-45eb-8203-0c6be210e285 | 9 | public Map<UserType, Set<Session>> getMySessions(String email) {
Map<UserType, Set<Session>> mySessions = new HashMap<UserType, Set<Session>>();
Set<Session> adminSessions = new HashSet<Session>();
Set<Session> facilitatorSessions = new HashSet<Session>();
Set<Session> attendeeSessions = new HashSet<Session>();
for (Session thisSession : getAllSessions()) {
if (thisSession.getAdmin()!=null&&thisSession.getAdmin().getEmail().equals(email)) {
adminSessions.add(thisSession);
}
}
for (Session thisSession : getAllSessions()) {
for (User thisFacilitator : thisSession.getFacilitators()) {
if (thisFacilitator.getEmail().equals(email)) {
facilitatorSessions.add(thisSession);
}
}
}
for (Session thisSession : getAllSessions()) {
for (User thisAttendee : thisSession.getAttendees()) {
if (thisAttendee.getEmail().equals(email)) {
attendeeSessions.add(thisSession);
}
}
}
mySessions.put(UserType.ADMIN, adminSessions);
mySessions.put(UserType.FACILITATOR, facilitatorSessions);
mySessions.put(UserType.ATTENDEE, attendeeSessions);
return mySessions;
} |
7f86568e-2a4e-4209-ac75-e4b38d080b57 | 3 | public static int Dcalculation(Planet pA, Planet pB) { // Tested
// The next values are only relatives value to the global values of grothrates and number of ships
int hisLoss = 0;
int myLoss = 0;
int hisGrowth = 0;
int myGrowth = 0;
if (Helper.WillCapture(pA,pB)){
/* if A capture B */
myLoss = pB.NumShips();
myGrowth = pB.GrowthRate();
if (pB.Owner()!=0) {
/* if it is an enemy planet (not neutral)*/
hisLoss = pB.NumShips();
hisGrowth = - pB.GrowthRate();
}
}
else {
/* if A do not win against B */
myLoss = pA.NumShips()/2;
if (pB.Owner()!=0)
hisLoss = pA.NumShips()/2;
myGrowth = 0;
hisGrowth = 0;
}
return hisLoss - myLoss + myGrowth - hisGrowth;
} |
65c66896-2139-465b-8eb5-c09845dde5a4 | 5 | protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String nextPage = request.getPathInfo();
if (nextPage != null) {
if (nextPage.substring(1).contentEquals("connexion")) {
connexion(request);
} else if (nextPage.substring(1).contentEquals("inscription")) {
if (!inscription(request)) {
request.setAttribute("page", "inscription");
}
} else if (nextPage.substring(1).contentEquals("commande")) {
commande(request);
}
}
getServletContext().getRequestDispatcher("/template").forward(request,
response);
} |
51572f2f-c100-4392-8a8a-395b4de23d90 | 8 | public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} |
ac0aa430-2b0c-435b-b46a-e717cfedb202 | 7 | public static boolean isSpecial(Pokemon.Type t)
{
switch(t)
{
case FIRE:
case WATER:
case ELECTRIC:
case GRASS:
case ICE:
case PSYCHIC:
case DRAGON:
return true;
default:
return false;
}
} |
8960e2dc-a430-43a7-8fc3-440997190e82 | 8 | @Override
public Object put(CycSymbol parameterName, Object value) {
// @Hack if the value is :UNKNOWN the parameter will not be set and it is assumed that
// Cyc uses its own default for that particular parameter
if (value instanceof CycSymbol && ((CycSymbol) value).toString().equals(":UNKNOWN")) {
return null;
}
if (":PROBLEM-STORE".equals(parameterName.toString())) {
if (value instanceof CycList || value instanceof CycSymbol || value instanceof Integer) {
return map.put(parameterName, value);
} else if (CycObjectFactory.nil.equals(value)) {
return map.put(parameterName, value);
} else {
throw new RuntimeException("Got invalid value " + value + " (" + value.getClass().getSimpleName() + ")"
+ " for parameter " + parameterName);
}
}
InferenceParameter param = getInferenceParameter(parameterName);
value = param.canonicalizeValue(value);
if (!param.isValidValue(value)) {
throw new RuntimeException("Got invalid value " + value + " for parameter " + parameterName);
}
return map.put(parameterName, value);
} |
48e3df57-b0fc-493f-8287-6cfabde44971 | 9 | public void startAnimation(Graphics2D g){
if(timerRepeats>100 && timerRepeats<102){g.setColor(Color.blue);g.fill(screen);loadImage(g,"CyrusAntiVirus.png");}
if(timerRepeats>200 && timerRepeats<203){ g.setColor(Color.blue);g.fill(screen);loadImage(g,"CyrusAntiVirus.png");}
if(timerRepeats>300 && timerRepeats<304){ g.setColor(Color.blue);g.fill(screen);loadImage(g,"CyrusAntiVirus.png");}
if(timerRepeats>400 && timerRepeats<451){ g.setColor(Color.blue);g.fill(screen);loadImage(g,"CyrusAntiVirus.png");}
if(timerRepeats>450){g.setColor(Color.blue);g.fill(screen);loadImage(g,"CyrusAntiVirus.png");}
} |
35778112-c67b-4aaa-a302-ff45570f7b11 | 9 | public Instances getDataSet() throws IOException {
Instances result;
double[] sparse;
double[] data;
int i;
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (getRetrieval() == INCREMENTAL)
throw new IOException("Cannot mix getting Instances in both incremental and batch modes");
setRetrieval(BATCH);
if (m_structure == null)
getStructure();
result = new Instances(m_structure, 0);
// create instances from buffered arrays
for (i = 0; i < m_Buffer.size(); i++) {
sparse = (double[]) m_Buffer.get(i);
if (sparse.length != m_structure.numAttributes()) {
data = new double[m_structure.numAttributes()];
// attributes
System.arraycopy(sparse, 0, data, 0, sparse.length - 1);
// class
data[data.length - 1] = sparse[sparse.length - 1];
}
else {
data = sparse;
}
// fix class
if (result.classAttribute().isNominal()) {
if (data[data.length - 1] == 1.0)
data[data.length - 1] = result.classAttribute().indexOfValue("+1");
else if (data[data.length - 1] == -1)
data[data.length - 1] = result.classAttribute().indexOfValue("-1");
else
throw new IllegalStateException("Class is not binary!");
}
result.add(new SparseInstance(1, data));
}
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return result;
} |
c4dbac16-2cfa-4408-85ba-7f87b080a412 | 4 | private static Method findSetScriptContextMethod(Class<?> clazz)
{
try
{
Method setCtxMethod = clazz.getMethod("setScriptContext", new Class[]
{
ScriptContext.class
});
int modifiers = setCtxMethod.getModifiers();
if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers))
{
return setCtxMethod;
}
}
catch (NoSuchMethodException nsme)
{
}
return null;
} |
5bcf73ea-edf2-4cc1-b913-023f351e5fae | 4 | public boolean containsPoint(Point p) {
if (p.x > getLeftEdge()) {
if (p.x < getRightEdge()) {
if (p.y > getTopEdge()) {
if (p.y < getBottomEdge()) {
return true;
}
}
}
}
return false;
} |
4029bf45-190b-4d67-83dd-ccca32908916 | 0 | void addAwaitingResume(DccFileTransfer transfer) {
synchronized (_awaitingResume) {
_awaitingResume.addElement(transfer);
}
} |
1e8c7824-2517-4ff5-b9d6-2b2d313454fc | 9 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Customer other = (Customer) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
if (!Objects.equals(this.lastName, other.lastName)) {
return false;
}
if (!Objects.equals(this.dateOfBirth, other.dateOfBirth)) {
return false;
}
if (!Objects.equals(this.age, other.age)) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.address, other.address)) {
return false;
}
return true;
} |
96051581-c5e6-454f-a00e-1a7ff6056b8b | 4 | public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {// parcour par colonne
case 0 :
return listClient.get(rowIndex).getId();
case 1://colonne type_vetement
return listClient.get(rowIndex).getNom();
case 2://colonne quantité
return listClient.get(rowIndex).getPrenom();
case 3:
return listClient.get(rowIndex).getAdresse_mail();
default:
return null;
}
} |
4f656381-b33c-4aae-b3e1-6a3dc9c58f9c | 4 | @Override
public void addBoats(ArrayList<Boat> boatList) throws SQLIntegrityConstraintViolationException, SQLException {
theConnection.open();
Connection conn = theConnection.getConn();
try {
int[] boatID = new int[boatList.size()];
conn.setAutoCommit(false);
for (int i = 0; i < boatList.size(); i++) {
String STMT = "SELECT COUNT(*) FROM Bateau WHERE IdPartie = '" + boatList.get(i).getGame().getGameID() + "'";;
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(STMT);
rset.next();
boatID[i] = rset.getInt(1);
rset.close();
stmt.close();
System.out.println("BOAT ID "+ boatID[i]);
STMT = "INSERT INTO Bateau VALUES (" + boatID[i] + ",'" + boatList.get(i).getGame().getGameID() + "','" + boatList.get(i).getSize() + "','" + boatList.get(i).getOwner().getPseudo() + "','" + boatList.get(i).getPosX() + "','" + boatList.get(i).getPosY() + "','" + boatList.get(i).getOrientation() + "','" + boatList.get(i).getLife() + "','" + boatList.get(i).getPosXInit() + "','" + boatList.get(i).getPosYInit() + "','" + boatList.get(i).getNbCoupRestant() + "')";
stmt = conn.createStatement();
stmt.executeUpdate(STMT);
stmt.close();
}
conn.commit();
for (int i = 0; i < boatList.size(); i++) {
boatList.get(i).setBoatID(boatID[i]);
}
} catch (SQLIntegrityConstraintViolationException e) {
Logger.getLogger(JDBCUpdater.class.getName()).log(Level.SEVERE, null, e);
conn.rollback();
throw new SQLIntegrityConstraintViolationException();
} catch (SQLException ex) {
Logger.getLogger(JDBCUpdater.class.getName()).log(Level.SEVERE, null, ex);
conn.rollback();
throw new SQLException();
} finally {
conn.setAutoCommit(true);
theConnection.close();
}
} |
81f35f66-2d16-4506-a911-080ddb11b420 | 2 | public int getIntInput(String promptMessage, String invalidInputMessage){
int userInput = 0;
boolean inputInvalid = true;
while (inputInvalid) {
System.out.print(promptMessage);
String response = Main.Scan.next();
Pattern digitPattern = Pattern.compile("([0-9]+)");
Matcher digitMatches = digitPattern.matcher(response);
if (digitMatches.find()) {
userInput = Integer.parseInt(digitMatches.group(1));
inputInvalid = false;
}else{
System.out.println(invalidInputMessage);
}
}
return userInput;
} |
d1ef3f47-c20f-47b0-ac2d-0cc41a1609f2 | 9 | public static void readStatement(String lexeme, SymbolTable currTable) throws IOException{
int[] offset = currTable.getOffsetByLexeme(lexeme);
String type = currTable.getTypeByLexeme(lexeme);
boolean byRef = false;
if(offset != null) {
//by copy
for (Symbol s: currTable.symbols) {
if(s.iden.equals(lexeme) && s.mode.equals("ref")) {
byRef = true;
break;
}
}
if(byRef) {
if(type.equals("MP_FLOAT") || type.equals("MP_FIXED")){
bw.write("RDF @" + offset[0] + "(D" + offset[1] + ")\n");
}else{
bw.write("RD @" + offset[0] + "(D" + offset[1] + ")\n");
}
} else {
if(type.equals("MP_FLOAT") || type.equals("MP_FIXED")){
bw.write("RDF " + offset[0] + "(D" + offset[1] + ")\n");
}else{
bw.write("RD " + offset[0] + "(D" + offset[1] + ")\n");
}
}
}
} |
d735204a-3fe7-41a4-b0db-cde2b48f337a | 4 | public static void main(String[] args) throws Exception{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fifa.com/worldcup/matches/index.html"); // matches
PrintWriter writer = new PrintWriter("/u/jeremiah/MatchStats.txt");
// gotta get a list of the countries, but like with CountryStatScrapper,
// have to copy the urls and names before we advance with the driver.
Integer date;
int startDate = 20140612;
String countryURL;
List<WebElement> countryLinks;
ArrayList<String> containerOfAllMatches = new ArrayList<String>();
for (int i = startDate; i < 20140714; i++) {
try {
date = new Integer(i); // need this to be able to cast the int to a string
countryLinks = driver.findElements(By.xpath(
"//div[@class='matches']//div[@id='" + date.toString() + "']//a"));
//countryLinks can contain multiple matches
for (int k = 0; k < countryLinks.size(); k++) {
countryURL = countryLinks.get(k).getAttribute("href"); // href attribute contains the link
containerOfAllMatches.add(countryURL);
}
} catch (NoSuchElementException e) {
// this is here for the bad links that will be created.
// the loop goes through invalid dates which will throw this exception
}
}
System.out.printf("%d\n", containerOfAllMatches.size());
assert (containerOfAllMatches.size() == 64);
String countryA;
String countryB;
System.out.print("{");
writer.print("{");
for (int i = 0; i < containerOfAllMatches.size(); i++) {
String url = containerOfAllMatches.get(i);
// the link stays the same for the match statistics except for the end (very handy)
url = url.replaceFirst("index.html#nosticky", "statistics.html#nosticky");
// don't know why, but using the same driver isn't working. Have to create a new one.
// it would navigate the pages but the information printed was the same.
// maybe it was a property of those certain pages? try commenting out the close and new to see what I mean
driver.close();
driver = new FirefoxDriver();
driver.get(url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> countryNames = driver.findElements(By.xpath(
"//div[@class='container']//div[@class='mh-m']//div[@class='t-n']"));
assert (countryNames.size() == 2);
countryA = countryNames.get(0).findElement(By.cssSelector("span")).getText().toLowerCase();
countryB = countryNames.get(1).findElement(By.cssSelector("span")).getText().toLowerCase();
System.out.print("\"" + countryA + "-" + countryB + "\" : [");
writer.print("\"" + countryA + "-" + countryB + "\":[");
getStatsFromTable(driver, "//div[@id='attacking' and @class='anchor']", writer);
getStatsFromTable(driver, "//div[@id='defending' and @class='anchor']", writer);
writer.print("],");
}
System.out.print("}");
writer.print("}");
driver.close();
writer.close();
} |
b3731e51-e076-4154-a996-38395606b60c | 9 | public static Texture getDude(boolean flip, Gun gun){
if(!flip){
if(gun == Gun.PISTOL){
return fpistol;
}else if(gun == Gun.SMG){
return fsmg;
}else if(gun == Gun.GRENADE){
return fgre;
}else if(gun == Gun.NONE){
return fdude;
}
}else{
if(gun == Gun.PISTOL){
return pistol;
}else if(gun == Gun.SMG){
return smg;
}else if(gun == Gun.GRENADE){
return gre;
}else if(gun == Gun.NONE){
return dude;
}
}
return dude;
} |
45fa610b-bb45-4ac4-9c8a-b1008454bff2 | 0 | private void printTime(double time) {
System.out.println("Average time taken: " + time + " ms");
} |
3bce19f7-e6a9-4e8f-bc00-46ebeb76ee81 | 3 | protected int getKnownAttributeCount() {
int count = 0;
if (constant != null)
count++;
if (syntheticFlag)
count++;
if (deprecatedFlag)
count++;
return count;
} |
d0f8fe2a-2e07-4f0a-b48d-4728014e7159 | 0 | private void setLinearity(int linearity) {
myLinearity = linearity;
} |
462ddcdc-a29d-480f-9e18-c785a7a15346 | 1 | private int getCharScore(char c) {
try {
return charScore[c - 97];
} catch (IndexOutOfBoundsException e) {
return 0;
}
} |
b653c318-c512-41be-95cd-7c4bed0f9335 | 5 | private void attackPlaceLeft(int position, char[] boardElements, int dimension) {
if (isPossibleToPlaceLeft(position, dimension)) {
if (isPossibleToPlaceOnNextLine(boardElements, position + dimension)
&& isBoardElementEmpty(boardElements[positionLeftBelow(position, dimension)])) {
boardElements[positionLeftBelow(position, dimension)] = FIELD_UNDER_ATTACK_CHAR;
}
if (isPossibleToPlaceOnPreviousLine(position - dimension)
&& isBoardElementEmpty(boardElements[positionLeftAbove(position, dimension)])) {
boardElements[positionLeftAbove(position, dimension)] = FIELD_UNDER_ATTACK_CHAR;
}
}
} |
1e139b91-7cf2-4887-a7e4-424eaee6bf46 | 8 | private TerminologyManager() {
try {
// user configuration
File userFile = new File(TERMINOLOGIES_FILE);
if (!userFile.exists()) {
File dir = new File(System.getProperty("user.home")
+ System.getProperty("file.separator") + "odml");
if (!dir.exists())
dir.mkdir();
userFile.createNewFile();
}
localTerminologies = new Properties();
localTerminologies.load(new FileInputStream(userFile));
} catch (NullPointerException e) {
out.println(e.toString());
e.printStackTrace();
} catch (IOException e) {
out.println(e.toString());
e.printStackTrace();
}
try {
// user configuration
File redirectFile = new File(REDIRECTIONS);
if (!redirectFile.exists()) {
File dir = new File(System.getProperty("user.home")
+ System.getProperty("file.separator") + "odml");
if (!dir.exists())
dir.mkdir();
redirectFile.createNewFile();
}
redirections = new Properties();
redirections.load(new FileInputStream(redirectFile));
} catch (NullPointerException e) {
out.println(e.toString());
e.printStackTrace();
} catch (IOException e) {
out.println(e.toString());
e.printStackTrace();
}
} |
59f96406-063f-4748-9f84-25ec2f21b83b | 1 | public int addToQueue(String channel, String message, int source)
{
if (source == 0)
{
acebotCore.printChannel(addHash(channel), "[" + BotCore.sdf.format(new Date()) + "] ", graphics.acebotsthree.TIMECOLOR);
acebotCore.printlnChannel(addHash(channel), message, new Color(230, 230, 230));
acebotCore.printAll("[" + BotCore.sdf.format(new Date()) + "] ", graphics.acebotsthree.TIMECOLOR);
acebotCore.printlnAll(message, new Color(230, 230, 230));
System.out.println(message);
return -1;
}
else
{
messagesQueue.add(channel + " " + message);
messageDelay.start();
return ++priorityPosition[4];
}
} |
c617a20a-c924-4b87-b9ab-1f7450c8d5bb | 4 | public void isBlackJack() throws PlayerEndOfGameException{
if (player.isBlackJack() && !dealer.isBlackJack()){
player.playerBlackJack();
throw new PlayerEndOfGameException("/photos/blackJack.gif");
}
if (player.isBlackJack() && dealer.isBlackJack())
throw new PlayerEndOfGameException("/photos/Its_a_Tie.png");
} |
0c8b3eb0-2d89-40e2-a3b4-86ab91f4dfff | 1 | private void loadLeaderboard(int currentPlayersPosition, int quantity) {
// TODO Auto-generated method stub
lobby.setStatus("Loading Leaderboards");
this.currentLeaderPosition = quantity;
String result = sendMessageToServer(GameSocketServer.GET_TOP_PLAYERS,
",startAt=" + currentPlayersPosition + ",quantity=" + quantity);
if (result.contains(GameSocketServer.GET_TOP_PLAYERS_SUCCESS)) {
lobby.setStatus("Updating Leaderboards");
String parameters = result.split("@")[1];
updateLeaderboard(parameters);
lobby.setStatus("Done");
} else
lobby.setStatus("Error loading leaderboards." + result);
} |
702825c4-b1b3-4631-b55d-4b60ddabef56 | 8 | public ArrayList<Shape> getRunwayLightings(Runway runway, AffineTransform at, Graphics2D g){
double runwayLength = runway.getLength();
double runwayWidth = runway.getWidth();
double runwayX = runway.getX();
double runwayY = runway.getY();
double runwayCenterX = runway.getCenterX();
double runwayCenterY = runway.getCenterY();
double runwayLDA = runway.getLength();
int diameter = 1;
Shape lighting;
Light tmpLight;
int thresh = 4;
ArrayList<Shape> lightings = new ArrayList<Shape>();
//Here is a light drawn at center with color black:
tmpLight = new Light(runwayCenterX-diameter/2, runwayCenterY, diameter);
//lighting = new Light (at.createTransformedShape(tmpLight),Color.black);
//lightings.add(lighting);
double width, length, spacing, offset;
// Lighting for the edge of the runaways and colour coding for the yellow caution zone.
double lightNo = runwayLength/60;
for (int i=0; i<=lightNo; i++){
tmpLight = new Light(runwayX, runwayY+(60*i), diameter);
if(i>=2*lightNo/3)
lighting =new Light (at.createTransformedShape(tmpLight),Color.yellow);
else
lighting =new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayX+runwayWidth-diameter, runwayY+(60*i), diameter);
if(i>=2*lightNo/3)
lighting =new Light (at.createTransformedShape(tmpLight),Color.yellow);
else
lighting =new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
}
// Lighting for the centre of the runaway.
int distanceBetweenLights = 30;
lightNo = runwayLength/distanceBetweenLights;
//System.out.println(runwayLength);
for (int i=0; i<=lightNo; i++){
tmpLight = new Light(runwayCenterX-diameter/2, runwayY+(distanceBetweenLights*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
}
// Supplementary approach lighting (cat II and III)
lightNo = 300/5;
for(int i= 0; i<=lightNo; i++){
tmpLight = new Light(runwayCenterX-diameter/2, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
}
// Lighting in Crossbars.
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*8*diameter/2, 9, runwayCenterY-runwayLength/2-150-thresh, 3));
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*10*diameter/2, 11, runwayCenterY-runwayLength/2-300-thresh, 3));
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*12*diameter/2, 13, runwayCenterY-runwayLength/2-450-thresh, 3));
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*14*diameter/2, 15, runwayCenterY-runwayLength/2-600-thresh, 3));
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*16*diameter/2, 17, runwayCenterY-runwayLength/2-750-thresh, 3));
lightNo = 300/5;
for(int i=0; i<=lightNo; i++)
{
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*2*diameter/2+2.5-diameter, 2, runwayCenterY-runwayLength/2-(300+5*i)-thresh, 3));
lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-3*3*diameter/2+2.5-diameter, 3, runwayCenterY-runwayLength/2-(600+5*i)-thresh, 3));
}
// High intensity coded centreline and crossbar approach lighting system.
lightNo = 300/5;
for(int i= 0; i<=lightNo; i++)
{
// The black lights in the middle.
tmpLight = new Light(runwayCenterX-diameter/2-2, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.black);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-3.2, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.black);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+2, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.black);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+3.2, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.black);
lightings.add(lighting);
// The edge light (4 red each side)
tmpLight = new Light(runwayCenterX-diameter/2-10, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-13, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-16, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-19, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
// The other side red lights.
tmpLight = new Light(runwayCenterX-diameter/2+10, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+13, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+16, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+19, runwayY-(5*i)-thresh, diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.red);
lightings.add(lighting);
}
//White lights in touch down zone (TDZ).
lightNo = 900/5;
for(int i= 0; i<=lightNo; i++)
{
// lightings.addAll(HorizLights(at, tmpLight, runwayCenterX-runwayWidth/2-diameter/2+3, 4, runwayY+(5*i), 4, Color.white));
// lightings.addAll(HorizLights(at, tmpLight, runwayCenterX+runwayWidth/4-diameter/2-3, 4, runwayY+(5*i), 4, Color.white));
// The edge light (4 red each side)
tmpLight = new Light(runwayCenterX-diameter/2-10, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-13, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-16, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2-19, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
// The other side red lights.
tmpLight = new Light(runwayCenterX-diameter/2+10, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+13, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+16, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
tmpLight = new Light(runwayCenterX-diameter/2+19, runwayY+(5*i), diameter);
lighting = new Light (at.createTransformedShape(tmpLight),Color.white);
lightings.add(lighting);
}
return lightings;
} |
65f020e7-8438-4154-9143-fc1300469db1 | 4 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (!number.equals(student.number)) return false;
return true;
} |
ee4ceb7c-77bd-4509-be32-c11e09dca1ac | 6 | public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
Debug.print("Action performed on: " + o);
if(o == okButton) {
Debug.print("Checking Yeast...");
// create a new Yeast object
Yeast i = new Yeast();
i.setName(txtName.getText());
i.setCost(txtCost.getText());
i.setDescription(txtDescr.getText());
i.setModified(bModified.isSelected());
int result = 1;
int found = 0;
// check to see if we have this fermentable already in the db
if((found = db.find(i)) >= 0){
// This already exists, do we want to overwrite?
result = JOptionPane.showConfirmDialog((Component) null,
"This ingredient exists, overwrite original?","alert", JOptionPane.YES_NO_CANCEL_OPTION);
switch(result) {
case JOptionPane.NO_OPTION:
setVisible(false);
dispose();
return;
case JOptionPane.YES_OPTION:
db.fermDB.remove(found);
break;
case JOptionPane.CANCEL_OPTION:
return;
}
}
Debug.print("Adding yeast: " + i.getName());
db.yeastDB.add(i);
db.writeYeast();
setVisible(false);
dispose();
} else if(o == cancelButton) {
dispose();
}
} |
175253fd-0673-4caf-b21c-c8670f4e3ad7 | 0 | public MultipleOutputSimulateAction(Automaton automaton,
Environment environment) {
super(automaton, environment);
putValue(NAME, "Multiple Run (Transducer)");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_T,
MAIN_MENU_MASK));
} |
66b0033f-efac-460e-8599-acb610e190e1 | 7 | public static void initScript(NativeFunction funObj, Scriptable thisObj,
Context cx, Scriptable scope,
boolean evalScript)
{
if (cx.topCallScope == null)
throw new IllegalStateException();
int varCount = funObj.getParamAndVarCount();
if (varCount != 0) {
Scriptable varScope = scope;
// Never define any variables from var statements inside with
// object. See bug 38590.
while (varScope instanceof NativeWith) {
varScope = varScope.getParentScope();
}
for (int i = varCount; i-- != 0;) {
String name = funObj.getParamOrVarName(i);
boolean isConst = funObj.getParamOrVarConst(i);
// Don't overwrite existing def if already defined in object
// or prototypes of object.
if (!ScriptableObject.hasProperty(scope, name)) {
if (!evalScript) {
// Global var definitions are supposed to be DONTDELETE
if (isConst)
ScriptableObject.defineConstProperty(varScope, name);
else
ScriptableObject.defineProperty(
varScope, name, Undefined.instance,
ScriptableObject.PERMANENT);
} else {
varScope.put(name, varScope, Undefined.instance);
}
} else {
ScriptableObject.redefineProperty(scope, name, isConst);
}
}
}
} |
e1fa4154-d2cf-4a78-969d-9afcdda12d93 | 8 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> @x1.",name().toLowerCase()));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),L(auto?"":"^S<S-NAME> "+prayWord(mob)+" for divine protection! ")+startStr());
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 for divine protection, but nothing happens.",prayWord(mob)));
// return whether it worked
return success;
} |
ed964ebb-3fa8-4d62-9130-3596e6e4b859 | 1 | public static String extractDate(String fullTitle) {
if (!fullTitle.contains("_URL_"))
return "incompatible text";
String dateTitle = fullTitle.replaceAll(".html", "").split("_URL_")[1];
return dateTitle;
} |
0cec4897-ac37-4ab4-9884-484f2f2243e7 | 6 | private void doEquip(ItemStack item) {
ItemMeta meta = item.getItemMeta();
if (meta == null) return;
if (!meta.hasLore()) return;
for (String lore : meta.getLore()) {
String name = ENameParser.parseName(lore);
int level = ENameParser.parseLevel(lore);
if (name == null) continue;
if (level == 0) continue;
if (EnchantAPI.isRegistered(name)) {
EnchantAPI.getEnchantment(name).applyEquipEffect(player, level);
}
}
} |
cfa8fe08-3703-4d47-b1bf-883cb9350940 | 6 | public int findShortestDistance(String[] words, String a, String b) {
Map<String, Integer> parityValueMap = new HashMap<String, Integer>();
parityValueMap.put(a, 0);
parityValueMap.put(b, 1);
Map<String, Integer> posMap = new HashMap<String, Integer>();
posMap.put(a, 0);
posMap.put(b, 0);
int[] min = new int[words.length];
int minDistance = Integer.MAX_VALUE;
Integer parityValue = Integer.MAX_VALUE;
int wordsLength = words.length;
for (int i = 0; i < wordsLength; i ++) {
if (parityValueMap.containsKey(words[i])) {
posMap.put(words[i], i);
// First time we see a required word
if (parityValue == Integer.MAX_VALUE) {
parityValue = parityValueMap.get(words[i]);
// we found the word other than the one found last time so lets calculate distance
} else if (!parityValue.equals(parityValueMap.get(words[i]))) {
parityValue = parityValueMap.get(words[i]);
int tempMin = posMap.get(words[i]) - posMap.get(words[i].equals(a)? b : a);
if (tempMin < minDistance) {
minDistance = tempMin;
}
}
}
}
return minDistance;
} |
9061e8a5-4475-48e3-9026-a25d02950bce | 6 | public static <E> E[] map(E[] a, Function<E> func){
assert a != null;
assert func != null;
assert a.length > 0;
E[] b = (E[]) Array.newInstance(a[0].getClass(), a.length);
assert b != null;
assert b.length != 0;
assert b.length == a.length;
for(int n = 0; n < b.length; n++){
assert 0 <= n && n <= b.length;
try{
Class<? extends Function<E>> f = (Class<? extends Function<E>>) func.getClass();
Constructor<?> con = f.getDeclaredConstructor(new Class[0]);
Function<E> exec = (Function<E>) con.newInstance();
b[n] = (E) exec.exec(a[n]);
}
catch(Exception e){
//Should never need to go here unless a malformed Map was passed.
e.printStackTrace();
}
}
return b;
} |
3f4a6400-8638-4d63-92cd-486a54992ee8 | 5 | public final void method44(int i, AbstractToolkit var_ha) {
anInt10008++;
Object object = null;
r var_r;
if (aR10036 != null || !aBoolean10003) {
var_r = aR10036;
aR10036 = null;
} else {
Class2 class2 = method2417(0, var_ha, 262144, true);
var_r = class2 != null ? ((Class2) class2).aR118 : null;
}
if (i != 836)
method41(-125);
if (var_r != null)
Class130.method1130(var_r, ((Class318_Sub1) this).mapHeightLevel,
((Class318_Sub1) this).xHash,
((Class318_Sub1) this).anInt6388, null);
} |
4c57033f-a082-4efa-8c89-795d35cb31f8 | 8 | public boolean isScramble(String s1, String s2) {
if (s1.length() != s2.length())
return false;
if (!hasSameChars(s1, s2))
return false;
if (s1.equals(s2))
return true;
for (int mid1 = 1; mid1 < s1.length(); mid1++) {
int mid2 = s1.length() - mid1;
String sub11 = s1.substring(0, mid1);
String sub12 = s1.substring(mid1);
// no swap
String sub21 = s2.substring(0, mid1);
String sub22 = s2.substring(mid1);
if (isScramble(sub11, sub21) && isScramble(sub12, sub22))
return true;
// swap
String bsub21 = s2.substring(0, mid2);
String bsub22 = s2.substring(mid2);
if (isScramble(sub11, bsub22) && isScramble(sub12, bsub21))
return true;
}
return false;
} |
f17d523d-05fb-4344-842a-aeaf24a0d5df | 3 | public boolean equals(Object obj) {
try {
if (!obj.getClass().equals(baseVideoClass.class)) {
throw new Exception();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (obj != null)
&& ((baseVideoClass) obj).getType().equals(this.type);
} |
ae52cba3-334c-4890-821f-763d8da18df5 | 5 | public void moveDown() {
if(!win && !m.getMap(p.getTileX(), p.getTileY() + 1).matches(pattern) && p.getTileY() != Maze.gridSize-1) {
if(yOffset < Maze.gridSize - 20 && p.getTileY() == yOffset + 10) {
Board.yOffset++;
p.move(0, 1);
} else {
p.move(0, 1);
}
}
} |
c0c39526-852f-4663-82f9-dd9ee01f3d0b | 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(Menu_Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu_Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu_Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu_Utama.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Menu_Utama().setVisible(true);
}
});
} |
7db2499b-e7ed-4876-beb1-b501e6489d85 | 2 | @Override
public ByteBuf serialize(O_02_MultipleAddressCallInput ucpOperation) {
ByteBuf bb = Unpooled.buffer();
Serialization.serializeString(bb, ucpOperation.getNpl());
Serialization.serializeString(bb, ucpOperation.getRads());
Serialization.serializeString(bb, ucpOperation.getOadc());
Serialization.serializeString(bb, ucpOperation.getAc());
char mt = ucpOperation.getMt();
Serialization.serializeCharacter(bb, ucpOperation.getMt());
if ('2' == mt) {
Serialization.serializeString(bb, ucpOperation.getnMsg());
} else if ('3' == mt) {
String amsgIra = IRA.unicodeToIra(ucpOperation.getaMsg());
Serialization.serializeString(bb, amsgIra);
} else {
throw new IllegalArgumentException("Illegal \"mt\" value: " + mt);
}
return bb;
} |
44b8e442-d796-4d7b-b511-87cfb9f0cbd9 | 5 | public void attach(String word) {
if (word.length() > 1) {
if (this.isRoot()) {
Character key = Character.valueOf(word.charAt(0));
MTrieNode node = (MTrieNode) this.children.get(key);
if (node != null) {
node.attach(word);
} else {
this.children.put(key, new MTrieNode(word, this.depth + 1));
}
}
else {
Character key = Character.valueOf(word.charAt(1));
String value = String.valueOf(word.substring(1).toCharArray());
if (value.length() > 0) {
MTrieNode node = (MTrieNode) this.children.get(key);
if (node != null) {
node.attach(value);
} else {
MTrieNode newNode = new MTrieNode(value, this.depth + 1);
this.children.put(key, newNode);
}
}
}
}
} |
a5a2c035-6857-445a-84e9-2a2144fe56f1 | 1 | static public void remove(String name) {
if (states.containsKey(name)) {
states.remove(name);
}
} |
9a7cbafa-df2e-442a-950d-2746ebc709d6 | 7 | @Override
public void accept(Metadata metadata, InputStream content) throws IOException {
// handling of service type messages
if (metadata.getType() == Metadata.Type.SERVICE) {
List<MessageReceiver> receivers = new ArrayList<>();
synchronized (consumers) {
Map<String, MessageReceiver> topicConsumers = this.consumers.row(metadata.getTopic());
// we need to filter receivers if the message is targeted only
if (metadata.hasTargets()) {
for (String target : metadata.getTargets()) {
MessageReceiver receiver = topicConsumers.get(target);
if (receiver != null) {
receivers.add(receiver);
}
}
} else {
receivers.addAll(topicConsumers.values());
}
}
// call all receivers
for (MessageReceiver receiver : receivers) {
receiver.accept(metadata, content);
}
}
// handling of callbacks
if (metadata.getType() == Metadata.Type.CALLBACK) {
MessageReceiver receiver;
synchronized (consumers) {
receiver = this.consumers.get(Metadata.CALLBACK_TOPIC, metadata.getReplyTo());
}
if (receiver != null) {
receiver.accept(metadata, content);
} else {
LOG.warn("No receiver for callback with replyTo {}", metadata.getReplyTo());
}
}
} |
4e618dd3-9f3d-4929-8254-c4b8219bf5e3 | 2 | public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException
{
if(!isGameOver)
{
if(!isPause)
{
}
else
{
}
}
else
{
}
} |
33d0a0a0-07fd-40ba-ad84-eaa168cc400d | 1 | public void mousePressed(MouseEvent event) {
State state = getDrawer().stateAtPoint(event.getPoint());
if (state == null)
return;
controller.expandState(state);
} |
deb06e4f-ca65-4ed7-9568-1757a364f62d | 3 | public PDFObject getDictRef(String key) throws IOException {
if (type == INDIRECT) {
return dereference().getDictRef(key);
} else if (type == DICTIONARY || type == STREAM) {
key = key.intern();
HashMap h = (HashMap) value;
PDFObject obj = (PDFObject) h.get(key.intern());
return obj;
}
// wrong type
return null;
} |
c3b65cbd-99fc-4cc0-ae3e-25d9ee776e01 | 4 | private boolean validPlacement(int x, int y, Entity entity){
int width = entity.getWidthInTiles();
int height = entity.getHeightInTiles();
boolean validPlacement = true;
for(int i = 0; i < height; i++){
for(int c = 0; c < width; c++){
if(gameMap[c+x][y-i] != null && gameMap[c+x][y-i] != entity){
validPlacement = false;
break;
}
}
}
return validPlacement;
} |
1cba4b39-1f19-4470-8fba-221da3b86fec | 5 | private static int sortUtil(int[] array, int low, int high) {
int key = array[low];
while(low < high) {
while(high > low && array[high] >= key) {
high--;
}
array[low] = array[high];
while(low < high && array[low] <= key) {
low++;
}
array[high] = array[low];
printArray(array);
}
array[high] = key;
return high;
} |
64d6194a-2f8d-4dec-93a7-157599d3814f | 9 | public void quickSort(int[] a, int begin, int end) {
int left = begin;
int right = end;
int temp = a[left];
while (left < right) {
while (left < right && a[right] >= temp)
right--;
if (left < right)
a[left] = a[right];
while (left < right && a[left] < temp)
left++;
if (left < right)
a[right] = a[left];
}
a[left] = temp;
if (left - begin > 1)
quickSort(a, begin, left - 1);
if (end - left > 1)
quickSort(a, left + 1, end);
} |
16da45f6-c9bc-45d9-b16e-2d49d96033b4 | 7 | @Override
public String execute() throws Exception {
PingjiaoService service = new PingjiaoService();
Map<String, Object> application = ActionContext.getContext()
.getApplication();
getSearchList(service, application);
// 设置表格第一行第一列的文本
firstTitle = "";
if (course == null && professionalName == null
&& executiveClass == null) {
statusList = service.getPingjiaoStatus(
(String) application.get("CURRENT_GRADE"),
(String) application.get("CURRENT_SEMESTER"), "总计", "全部",
"全部", 0, 10);
this.course = "总计";
this.professionalName = "全部";
this.executiveClass = "全部";
pageList.add(1);
pre = 1;
next = 1;
} else {
// 总页数
int totalLines = service.getPingjiaoStatusTotalPages(
(String) application.get("CURRENT_GRADE"),
(String) application.get("CURRENT_SEMESTER"), course,
professionalName, executiveClass);
statusList = service.getPingjiaoStatus(
(String) application.get("CURRENT_GRADE"),
(String) application.get("CURRENT_SEMESTER"), course,
professionalName, executiveClass, (page - 1) * lineNum,
page * lineNum);
// 最小分页下标
int left = (page - 1) / step * step;
// 最大分页下标
int right = (page - 1) / step * step + step;
// 最大页数
int max = (int) Math.ceil((totalLines * 1.0) / lineNum);
for (int i = left; i < right && i < max; i++) {
pageList.add(i + 1);
}
firstTitle = "行政班";
pre = left > 0 ? left : 1;
next = right + 1 > max ? max : right + 1;
}
return SUCCESS;
} |
5289080d-52ab-4dc9-9a53-4dbbae560a98 | 4 | private void modifyExtensionAnnotatedRefset(RefexChronicleBI<?> memberChron) throws ContradictionException, InvalidCAB, IOException {
RefexVersionBI<?> mem = memberChron.getVersion(vc);
RefexCAB bp = mem.makeBlueprint(vc, IdDirective.PRESERVE, RefexDirective.INCLUDE);
if (bp.getMemberUUID() == null) {
bp.setMemberUuid(mem.getPrimordialUuid());
}
// Change String
bp.put(ComponentProperty.STRING_EXTENSION_1, "Modified Testing String");
// Change Description to Pref Term
int parentRefsetPT = appDb.getRefsetIdentity().getVersion(vc).getPreferredDescription().getNid();
bp.put(ComponentProperty.COMPONENT_EXTENSION_1_ID, parentRefsetPT);
RefexChronicleBI<?> cabi = appDb.getBuilder().constructIfNotCurrent(bp);
ConceptVersionBI refCon = appDb.getDB().getConcept(mem.getReferencedComponentNid()).getVersion(appDb.getVC());
appDb.getDB().addUncommitted(refCon);
} |
38e979ba-98fc-4843-ab0d-3a36fcda6b97 | 4 | @Override
public void run() {
try {
packet = receivePacket();
stdOut.writeln(TAG + " received packet is: " + packet);
} catch (Exception e) {
stdOut.printError(e.getMessage());
cancelOnReceiveError();
return;
}
if (initiatorIsMe()) {
packetBackToInitiator();
} else {
moveMyNodeToVisited();
if (isMyNodeOnlyTransport()) {
send();
} else if (isResendImmediately()) {
send();
performAction();
} else {
performAction();
send();
}
}
stdOut.writeln(TAG + " packet after its processing: " + packet);
stdOut.writeln(TAG + " connection ended");
} |
bd673af1-9d99-4c5f-b3d3-58dd18365db2 | 1 | @SuppressWarnings("unused")
private int getLayerFromIndex(final int index) {
int layer = 0;
while (index > Math.pow(2, layer) - 1) {
layer++;
}
return layer;
} |
227f4272-e12f-4cb2-bdc9-5cc72de0ed71 | 3 | public ArrayList<ExternalUser> getAllExternalUsersFromDatabase(){
ArrayList<ExternalUser> externalUsers = new ArrayList<>();
ArrayList<HashMap<String, String>> externalUsers_raw = mySQLQuery.getAllRows("ExternalUser");
for(HashMap<String, String> externalUser_raw : externalUsers_raw){
String email = externalUser_raw.get("email");
int meetingID = Integer.parseInt(externalUser_raw.get("meetingID"));
String name = externalUser_raw.get("name") == null ? "" : externalUser_raw.get("name");
String phonenumber = externalUser_raw.get("phonenumber") == null ? "" : externalUser_raw.get("phonenumber");
externalUsers.add(new ExternalUser(email, meetingID, name, phonenumber));
}
return externalUsers;
} |
4a948d38-7516-4ead-90f6-95ebd85f368a | 5 | public static Product buscarCod(String cod) throws IOException{
try {
ObjectInputStream dataIn=new ObjectInputStream(Files.newInputStream(path));
while(true ){
Product product=(Product) dataIn.readObject();
if(product.getCod().equalsIgnoreCase(cod)){
System.out.println("Este cod ya existe");
return product;
}
}
} catch (ClassNotFoundException e) {
System.out.println("Error al leer el fichero binario "+e.getMessage());
}catch(EOFException e){
System.out.println("Final de fechero");
}catch(IOException e){
System.out.println("Fin de lectura");
}
return null;
} |
6262fe04-1deb-4a58-b748-f3c9976c1b91 | 1 | public SimpleStochasticLotSizingSolution(double totalSetupCosts, double totalInventoryCosts,
String amountVariableName, double[] amountVariableValues,
boolean[] setupPattern) {
//Check inputs
if (amountVariableValues.length != setupPattern.length) throw new IllegalArgumentException("Planning horizons did not match while constructing a simple stochastic lot sizing Solution");
this.totalSetupCosts = totalSetupCosts;
this.totalInventoryCosts = totalInventoryCosts;
this.amountVariableName = amountVariableName;
this.amountVariableValues = amountVariableValues;
this.setupPattern = setupPattern;
} |
089924fd-676d-4142-bf05-cefbf2d51735 | 3 | public String cutToSize(String o, int limit) {
if(o.length() > limit) {
o = o.substring(0, limit);
}
else if (o.length() < limit) {
while (o.length() < limit) {
o += " ";
}
}
return o;
} |
69875ece-e174-44ff-bac3-cfeadca93303 | 3 | @Override
public int willingnessToMoveHere(Hero hero, Player player, float distance,
int day) {
float moveRatio = hero.getMovePoints()/distance;
float result = 0;
Cost need = player.getBalancedBudget();
if (type == ResourceType.GOLD) {
result = 1.2f*(moveRatio + Math.min(3, need.gold/amount));
} else if (type == ResourceType.WOOD) {
result = 1.0f*(moveRatio + Math.min(3, need.wood/amount));
} else if (type == ResourceType.ORE) {
result = 1.0f*(moveRatio + Math.min(3, need.ore/amount));
}
return (int)(100*result);
} |
00ca909e-f4c6-48a1-81a0-ae115512c0d2 | 2 | private void drawAxis(int[] bits){
int pw = getPanelWidth();
int ph = getPanelHeight();
int xNull = getXnull();
int yNull = getYnull();
for (int i = 0; i < ph; i++){
bits[i*pw + xNull] = GUIStandarts.axisColor;
}
for (int i = 0; i < pw; i++){
bits[yNull*pw + i] = GUIStandarts.axisColor;
}
} |
77a322d0-8a7f-4dc6-8de0-65110adfa831 | 6 | public void magicComplex(int screen) {
if (screen == 1) {
clearMenu();
menuLine("", "You can see what each of the spells", 6949, 0);
menuLine("", "does by selecting the spellbook icon on", 0, 1);
menuLine("", "your side interface. Move the mouse", 0, 2);
menuLine("", "over the icon of the spell you want and", 0, 3);
menuLine("", "a description will be availabe", 0, 4);
optionTab("Magic", "Spells", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
else if (screen == 2) {
clearMenu();
menuLine("", "@cr1@Must have completed Desert Treasure", 6949, 0);
menuLine("", "", 0, 1);
menuLine("50", "Smoke Rush", 0, 2);
menuLine("52", "Shadow Rush", 0, 3);
menuLine("54", "Teleport to Paddewwa", 0, 4);
menuLine("56", "Blood Rush", 0, 5);
menuLine("58", "Ice Rush", 0, 6);
menuLine("60", "Teleport to Senntisten", 0, 7);
menuLine("62", "Smoke Burst", 0, 8);
menuLine("64", "Shadow Burst", 0, 9);
menuLine("66", "Teleport to Kharyrll", 0, 10);
menuLine("68", "Blood Burst", 0, 11);
menuLine("70", "Ice Burst", 0, 12);
menuLine("72", "Teleport to Lassar", 0, 13);
menuLine("74", "Smoke Blitz", 0, 14);
menuLine("76", "Shadow Blitz", 0, 15);
menuLine("78", "Teleport Dareeyak", 0, 16);
menuLine("80", "Blood Blitz", 0, 17);
menuLine("82", "Ice Blitz", 0, 18);
menuLine("84", "Teleport to Carrallangar", 0, 19);
menuLine("86", "Smoke Barrage", 0, 20);
menuLine("88", "Shadow Barrage", 0, 21);
menuLine("90", "Teleport to Annakarl", 0, 22);
menuLine("92", "Blood Barrage", 0, 23);
menuLine("94", "Ice Barrage", 0, 24);
menuLine("96", "Teleport to Ghorrock", 0, 25);
optionTab("Magic", "Ancients", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
else if (screen == 3) {
clearMenu();
menuLine("1", "Farseer Helm(With 45 Defence)", 3755, 0);
menuLine("1", "Elemental Shield", 2890, 1);
menuLine("1", "Skeletal Gloves", 6153, 2);
menuLine("1", "Skeletal Boots", 6147, 3);
menuLine("20", "Wizard Boots", 2579, 4);
menuLine("40", "Mystic Hat(With 20 Defence)", 4099, 5);
menuLine("40", "Mystic Robe Top(With 20 Defence)", 4101, 6);
menuLine("40", "Mystic Robe Bottom(With 20 Defence)", 4103, 7);
menuLine("40", "Mystic Gloves(With 20 Defence)", 4105, 8);
menuLine("40", "Mystic Boots(With 20 Defence)", 4107, 9);
menuLine("40", "Enchanted Hat(With 20 Defence)", 7400, 10);
menuLine("40", "Enchanted Top(With 20 Defence)", 7399, 11);
menuLine("40", "Enchanted Robe(With 20 Defence)", 7398, 12);
menuLine("40", "Splitbark Helm(With 40 Defence)", 3385, 13);
menuLine("40", "Splitbark Body(With 40 Defence)", 3387, 14);
menuLine("40", "Splitbark Legs(With 40 Defence)", 3389, 15);
menuLine("40", "Splitbark Gauntlets(With 40 Defence)", 3391, 16);
menuLine("40", "Splitbark Boots(With 40 Defence)", 3393, 17);
menuLine("40", "Skeletal Helmet(With 40 Defence)", 6137, 18);
menuLine("40", "Skeletal Top(With 40 Defence)", 6139, 19);
menuLine("40", "Skeletal Bottoms(With 40 Defence)", 6141, 20);
menuLine("50", "Infinity Hat(With 25 Defence)", 6918, 21);
menuLine("50", "Infinity Top(With 25 Defence)", 6916, 22);
menuLine("50", "Infinity Bottom(With 25 Defence)", 6924, 23);
menuLine("50", "Infinity Boots(With 25 Defence)", 6920, 24);
menuLine("50", "Infinity Gloves(with 25 Defence)", 6922, 25);
menuLine("70", "Ahrim's Hood(With 70 Defence)", 4708, 26);
menuLine("70", "Ahrim's Robe Top(With 70 Defence)", 4712, 27);
menuLine("70", "Ahrim's Robeskirt(With 70 Defence)", 4714, 28);
optionTab("Magic", "Armour", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
else if (screen == 4) {
clearMenu();
menuLine("1", "Staff", 1379, 0);
menuLine("1", "Magic staff", 1389, 1);
menuLine("1", "Staff of Air", 1381, 2);
menuLine("1", "Staff of Earth", 1385, 3);
menuLine("1", "Staff of Fire", 1387, 4);
menuLine("1", "Staff of Water", 1383, 5);
menuLine("30", "Air Battlestaff(With 30 Attack)", 1397, 6);
menuLine("30", "Earth Battlestaff(With 30 Attack)", 1399, 7);
menuLine("30", "Fire Battlestaff(With 30 Attack)", 1393, 8);
menuLine("30", "Water Battlestaff(With 30 Attack)", 1395, 9);
menuLine("30", "Lava Battlestaff(With 30 Attack)", 3053, 10);
menuLine("30", "Mud Battlestaff(With 30 Attack)", 6562, 11);
menuLine("40", "Mystic Air Staff(With 40 Attack)", 1405, 12);
menuLine("40", "Mystic Earth Staff(With 40 Attack)", 1407, 13);
menuLine("40", "Mystic Fire Staff(With 40 Attack)", 1401, 14);
menuLine("40", "Mystic Water Staff(With 40 Attack)", 1403, 15);
menuLine("40", "Mystic Lava Staff(With 40 Attack)", 3054, 16);
menuLine("40", "Mystic Mud Staff(With 40 Attack)", 6563, 17);
menuLine("50", "Slayer's Staff(With 55 Slayer)", 4170, 18);
menuLine("50", "Iban's Staff(With 50 Attack)", 1409, 19);
menuLine("50", "Ancient Staff(With 50 Attack)", 4675, 20);
menuLine("60", "Saradomin Staff", 2415, 21);
menuLine("60", "Guthix Staff", 2416, 22);
menuLine("60", "Zamorak Staff", 2417, 23);
menuLine("60", "TokTz-Mej-Tal(Obsidian Staff)", 6526, 24);
menuLine("70", "Ahrim's Staff(With 70 Attack)", 4710, 25);
optionTab("Magic", "Weapons", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
else if (screen == 5) {
clearMenu();
menuLine("45", "Beginner Wand", 6908, 0);
menuLine("50", "Apprentice Wand", 6910, 1);
menuLine("55", "Teacher Wand", 6912, 2);
menuLine("60", "Master Wand", 6914, 3);
menuLine("60", "Mage's Book", 6889, 4);
optionTab("Magic", "Special", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
else if (screen == 6) {
clearMenu();
menuLine("66", "Magic Guild", 4675, 0);
menuLine("99", "Skill Mastery", c.getItems().skillcapes[c.playerMagic][0], 1);
optionTab("Magic", "Milestones", "Spells", "Ancients", "Armour",
"Weapons", "Special", "Milestones", "", "", "", "", "", "",
"");
}
} |
66f9fac6-6971-443d-9d26-65e8704bbf32 | 8 | public String getFranchiseAirportName(int ID)
throws UnauthorizedUserException, BadConnectionException, DoubleEntryException
{
/* Variable Section Start */
/* Database and Query Preperation */
PreparedStatement statment = null;
ResultSet results = null;
String statString = "SELECT * FROM `airport` WHERE 'AirportID' = ?";
/* Return Parameter */
String AirName = null;
/* Variable Section Stop */
/* TRY BLOCK START */
try
{
/* Preparing Statment Section Start */
statment = con.prepareStatement(statString);
statment.setInt(1, ID);
/* Preparing Statment Section Stop */
/* Query Section Start */
results = statment.executeQuery();
/* Query Section Stop */
/* Metadata Section Start */
//ResultSetMetaData metaData = results.getMetaData();
/* Metadata Section Start*/
/* List Prepare Section Start */
while (results.next())
{
//Franchise temp = new Franchise();
//rs.getBigDecimal("AMOUNT")
AirName = (results.getString("AirportName"));
}
/* List Prepare Section Stop */
}
catch(SQLException sqlE)
{
if(sqlE.getErrorCode() == 1142)
throw(new UnauthorizedUserException("AccessDenied"));
else if(sqlE.getErrorCode() == 1062)
throw(new DoubleEntryException("DoubleEntry"));
else
throw(new BadConnectionException("BadConnection"));
}
finally
{
try
{
if (results != null) results.close();
}
catch (Exception e) {};
try
{
if (statment != null) statment.close();
}
catch (Exception e) {};
}
/* TRY BLOCK STOP*/
/* Return to Buisness Section Start */
return AirName;
/* Return to Buisness Section Start */
} |
86c6ed3f-c62a-41a1-adba-da7d3d54de5f | 9 | public boolean Open(String path)
{
try
{
FileInputStream open_file = new FileInputStream(path);
byte fileheader[] = new byte[14];
byte infoheader[] = new byte[40];
open_file.read(fileheader);
open_file.read(infoheader);
if (fileheader[bf_type] != 0x42 || fileheader[bf_type + 1] != 0x4d)
{
open_file.close();
throw new Exception("Not BMP File");
}
this.width = infoheader[bi_width + 3] & 0xff;
this.width = (this.width << 8) + ((int) infoheader[bi_width + 2] & 0xff);
this.width = (this.width << 8) + ((int) infoheader[bi_width + 1] & 0xff);
this.width = (this.width << 8) + ((int) infoheader[bi_width] & 0xff);
this.height = infoheader[bi_height + 3] & 0xff;
this.height = (this.height << 8) + ((int) infoheader[bi_height + 2] & 0xff);
this.height = (this.height << 8) + ((int) infoheader[bi_height + 1] & 0xff);
this.height = (this.height << 8) + ((int) infoheader[bi_height] & 0xff);
this.bit_count = infoheader[bi_bitcount];
int color_byte = this.bit_count == 32 ? 4 : 3;
int direction = 0;
if (this.height < 0)
{
this.height = -this.height;
direction = 1;
}
this.matrix = new ARGB[this.height][this.width];
InitColor(ARGB.Black);
byte argb[] = new byte[color_byte * this.height * this.width];
open_file.read(argb);
for (int i = 0; i < this.height; i++)
for (int j = 0; j < this.width; j++)
{
this.matrix[i][j].SetR(argb[bmp_r + (i * this.height + j) * color_byte]);
this.matrix[i][j].SetG(argb[bmp_g + (i * this.height + j) * color_byte]);
this.matrix[i][j].SetB(argb[bmp_b + (i * this.height + j) * color_byte]);
if (this.bit_count == 32)
this.matrix[i][j].SetA(argb[bmp_a + (i * this.height + j) * color_byte]);
}
if (direction == 1)
this.UpToDown();
open_file.close();
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
} |
a28fc242-f38b-4e0d-82a9-9029b4baae59 | 4 | public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new RuntimeException("half width can't be negative");
if (halfHeight < 0) throw new RuntimeException("half height can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} |
7f6a635d-45fe-4d88-8877-37d7d0f0d76b | 6 | protected static void rechercheTrajetsParticipant(Membre m){
ArrayList<Trajet> resConducteur = dbT.getTrajetByConducteur(m);
ArrayList<Trajet> resPassager = dbT.getTrajetsWithPassager(m);
System.out.println();
if(resConducteur.size()==0 && resPassager.size()==0){
System.out.println("Vous ne participez encore à aucun trajet");
}
else{
if(resConducteur.size()!=0){
System.out.println("Vous participez en tant que conducteur aux trajets suivants : ");
for(Trajet tl : resConducteur){
System.out.println(tl);
}
}
else{
System.out.println("Vous ne participez encore à aucun trajet en tant que conducteur.");
}
System.out.println();
if(resPassager.size()!=0){
System.out.println("Vous participez en tant que passager aux trajets suivants : ");
for(Trajet tl : resPassager){
System.out.println(tl);
}
}
else{
System.out.println("Vous ne participez encore à aucun trajet en tant que passager");
}
System.out.println();
}
} |
1918da27-2398-4408-a465-6fff13ca7997 | 0 | public final String getEmpty() {
return toSubstitute;
} |
181cb59a-19ee-45a1-b02d-040581524b41 | 3 | public void setVisible(boolean visible) {
if(frame == null) {
frame = new JFrame("About YAMG");
mainPanel = new JPanel(new GridLayout(18, 2));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
addRow("Game Version", Configurables.GAME_VERSION);
addRow("Lead Programmer", "Daniel Glus");
addRow("Assistant Programmer", "John Lhota");
addRow("Game Designer", "Daniel Glus");
addRow("Playtesters", "John Lhota");
for(String tester:new String[] {"Brent Morden",
"Alexander Chan", "Miles Shebar", "Jennifer Lee", "Andrew Glus",
"Vaughan McDonald", "Elliot Kahn", "Richard Zheng"}) {// rows 5 to 10
addRow("", tester);
}
addRow("Bug Finders", "Alexander Chan");
for(String finder:new String[] {"Johnston Jiaa", "Richard Zheng",
"Jennifer Lee", "John Lhota"}) {
addRow("", finder);
}
JPanel bottom = new JPanel();
JButton doneButton = new JButton("Done");
doneButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
}
});
bottom.add(doneButton);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(bottom, BorderLayout.SOUTH);
frame.setBounds(Helper.getCenteredBounds(500, 500));
}
frame.setVisible(visible);
} |
7ca2a61f-74d0-407d-acda-bc947778ec55 | 1 | private Ball getBall() {
if (networkGameType == NetworkGameType.MASTER)
return new Ball(100, 40, (int)(BALL_SCALE * width), (int)(BALL_SCALE * width));
else
return new Ball(width - 110, 40, (int)(BALL_SCALE * width), (int)(BALL_SCALE * width));
} |
d4df75a0-e12b-42ff-9c2b-6821c56fa464 | 4 | private void addDependent(JSRTargetInfo result) {
if (dependent == null || dependent == result)
dependent = result;
else if (dependent instanceof JSRTargetInfo) {
Set newDeps = new HashSet();
newDeps.add(dependent);
newDeps.add(result);
} else if (dependent instanceof Collection) {
((Collection) dependent).add(result);
}
} |
9cae64d2-6bf0-4efc-9012-b786d5dadc6a | 6 | @Override
public boolean shouldReact(Message message) {
String messageText = message.text.trim();
if (messageText.startsWith("movie") ||
messageText.startsWith("movies") ||
messageText.startsWith("vycsfdkuj") ||
messageText.startsWith("vyfilmuj")) {
reactionId = 1;
return true;
}
if (messageText.startsWith("http://www.csfd.cz/film") ||
messageText.startsWith("http://csfd.cz/film")) {
reactionId = 2;
return true;
}
reactionId = 0;
return false;
} |
5d108237-2f1d-4d91-9089-53225b7121bf | 8 | public static int[] mergeSort(int[] array)
{
if (array.length==1) return array;
int mid = (array.length) / 2;
int[] low = new int[mid];
int[] high = new int[array.length-mid];
for (int i=0;i<array.length;i++)
{
if (i<mid)
{
low[i]=array[i];
}
else
{
high[i-mid]=array[i];
}
}
low = mergeSort(low);
high = mergeSort(high);
int[]ordered = new int[array.length];
int i=0;
int j=0;
while ((i<low.length)&&(j<high.length))
{
if (low[i]<=high[j])
{
ordered[i+j]=low[i];
i++;
}
else
{
ordered[i+j]=high[j];
j++;
}
}
while (i<low.length)
{
ordered[i+j]=low[i];
i++;
}
while (j<high.length)
{
ordered[i+j]=high[j];
j++;
}
return ordered;
} |
43411adb-b5c6-4c18-a9f5-fa482b15865d | 2 | public void process(String tweet) throws IOException {
JSONParser jsonParser = new JSONParser();
String tweetText = null;
String tweetTimestamp = null;
String tweetId = null;
String tweetUserId = null;
String tweetInReplyToStatusId = null;
try {
JSONObject tweetJO = (JSONObject) jsonParser.parse(tweet);
JSONObject tweetDataJO = (JSONObject) jsonParser.parse((String) tweetJO.get("Data"));
tweetId = (String) tweetDataJO.get("IdStr");
tweetTimestamp = (String) tweetDataJO.get("CreatedAt");
tweetInReplyToStatusId = (String) tweetDataJO.get("InReplyToStatusIdStr");
tweetText = ((String) tweetDataJO.get("Text"));
tweetUserId = (String) ((JSONObject)tweetDataJO.get("User")).get("IdStr");
if(tweetText == null) {
nullWriter.write("$" + tweetId + "\n");
nullWriter.write("$" + tweetTimestamp + "\n");
nullWriter.write("$" + tweetText + "\n");
nullWriter.write("$" + tweetUserId + "\n");
nullWriter.write("$" + tweetInReplyToStatusId + "\n");
nullWriter.write("$\n");
return;
}
tweetText = tweetText.replaceAll("[\\n\\r\\t]" , " ");
fileWriter.write("$" + tweetId + "\n");
fileWriter.write("$" + tweetTimestamp + "\n");
fileWriter.write("$" + tweetText + "\n");
fileWriter.write("$" + tweetUserId + "\n");
fileWriter.write("$" + tweetInReplyToStatusId + "\n");
fileWriter.write("$\n");
}
catch (ParseException e) {
e.printStackTrace();
}
} |
e715ddac-feac-4160-b6ae-68f0577f3ff8 | 3 | public static void loadFile()
{
Scanner in = null;
try{
in = new Scanner(new FileReader(fileName));
}
catch(Exception e){System.out.println("File Doesn't Exist");}
for(int i=0; i<151; i++)
seen[i] = in.nextBoolean();
for(int i=0; i<151; i++)
caught[i] = in.nextBoolean();
totalSeen = Integer.parseInt(in.next());
totalCaught = Integer.parseInt(in.next());
JokemonDriver.testEncryption(fileName);
System.out.println("Pokedex load complete.");
} |
3690ef51-c903-40f8-b24c-8b43f3879622 | 5 | public void update() {
for(int y = 0; y < ySize; y++) {
for(int x = 0; x < ySize; x++) {
Site site = (Site)scape.grid[x][y];
JLabel label = labels[x][y];
Color background = new Color(255, 250, 205);
label.setBackground(background);
Agent a = site.getAgent();
if(a != null) {
label.setText("o");
//label.setText(""+a.getID());
for (int i = 0; i < scape.numStrategies; i++) {
if(a.getStrategy().equals(scape.strategies[i])) {
label.setForeground(colours[i]);
}
}
}
else {
label.setText("");
}
}
}
} |
ac012de0-faaa-4834-a824-45b394084501 | 3 | public int getPositionInRefereeClassArray(String name)
{
int positionInList = 0;
for (int i = 0; i < elementsInArray; i++)
if (refereeClassArray[i] != null && refereeClassArray[i].getRefereeName().equals(name))
positionInList = i;
return positionInList;
} |
3e455fa4-68b2-43c1-aece-a335bf2f7d03 | 6 | private void compute() {
if (computed) {
return;
}
float sum = 0;
int n = 0;
while (true) {
float val;
try {
val = floatVal(n);
} catch (ArrayIndexOutOfBoundsException e) {
break;
}
sum += val;
minVal = Float.isNaN(minVal) ? val : Math.min(minVal, val);
maxVal = Float.isNaN(maxVal) ? val : Math.max(maxVal, val);
++n;
}
avgVal = n == 0 ? Float.NaN : sum / n;
computed = true;
} |
848cb6fc-1574-4182-bde2-dafdc8a5ba03 | 3 | public boolean isClause(ArrayList<String> potentialClause, ArrayList<String> charIdentifier) {
for (int i = 0; i < this.subjectsOf(potentialClause, charIdentifier).size(); i++) {
if ((this.subjectsOf(potentialClause, charIdentifier).get(i).isEmpty())
|| (this.actionsOf(potentialClause, charIdentifier).get(i).isEmpty())) {
return false;
}
}
return true;
} |
7d92541f-ebca-4dea-9d26-1b218965855c | 5 | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!plugin.hasPerm(sender, "heal", false)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
if (args.length == 0) {
if (plugin.isPlayer(sender)) {
Player player = (Player) sender;
player.setHealth(20);
player.sendMessage(CraftEssence.premessage
+ "You are fully healed.");
return true;
}
return false;
} else if (args.length == 1) {
if (plugin.playerMatch(args[0]) != null) {
Player p = plugin.getServer().getPlayer(args[0]);
p.setHealth(20);
p.sendMessage(CraftEssence.premessage + "You are fully healed!");
sender.sendMessage(CraftEssence.premessage + "You healed "
+ args[0] + ".");
return true;
} else {
sender.sendMessage(CraftEssence.premessage
+ "Player not found.");
return true;
}
} else {
sender.sendMessage(CraftEssence.premessage
+ "Invalid heal command parameter.");
return true;
}
} |
974d4c42-cf97-43d6-a5f6-77b3b4108a05 | 8 | private void calcCuboidsMinMax() {
if (!(frameRenderer instanceof ExtendedFrameRenderer))
return;
Cuboids c = ((ExtendedFrameRenderer) frameRenderer).cuboids;
if (c.isEmpty())
return;
Point3f min = c.getMin();
Point3f max = c.getMax();
if (min.x < minBoundBox.x)
minBoundBox.x = min.x;
if (min.y < minBoundBox.y)
minBoundBox.y = min.y;
if (min.z < minBoundBox.z)
minBoundBox.z = min.z;
if (max.x > maxBoundBox.x)
maxBoundBox.x = max.x;
if (max.y > maxBoundBox.y)
maxBoundBox.y = max.y;
if (max.z > maxBoundBox.z)
maxBoundBox.z = max.z;
} |
403265d0-92e3-4d8d-8157-94f529e84267 | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SalesDetail other = (SalesDetail) obj;
if (idOrder == null) {
if (other.idOrder != null)
return false;
} else if (!idOrder.equals(other.idOrder))
return false;
return true;
} |
7751b197-f8ef-4723-bfd9-6e90fdbe3e42 | 5 | public String getTwoPair()
{
String stt = "0";
//same implementation idea as in isOnePair method.
//this time, when a pair is found, a second pair must be found too.
if (cards[0].getRank() == cards[1].getRank()) {
if (cards[2].getRank() == cards[3].getRank()) {
stt = Character.toString(cards[0].getCharCard()) + cards[2].getCharCard() + cards[4].getCharCard();
return stt;
}
if (cards[3].getRank() == cards[4].getRank()) {
stt = Character.toString(cards[0].getCharCard()) + cards[3].getCharCard() + cards[2].getCharCard();
return stt;
}
}
if (cards[1].getRank() == cards[2].getRank()) {
if (cards[3].getRank() == cards[4].getRank()) {
stt = Character.toString(cards[1].getCharCard()) + cards[3].getCharCard() + cards[0].getCharCard();
return stt;
}
}
return stt;
} |
32027888-b38d-42ee-b6d5-e0fb849bf6f0 | 6 | public void loadAllFFmpegArguments(List<FFmpegArguments> list)
{
if (connection == null || list == null)
return;
list.clear();
Statement stat = null;
try {
stat = connection.createStatement();
ResultSet rs = stat.executeQuery(
"SELECT Name, Arguments, FileExtension FROM "
+ FFmpegArgumentsTableName);
while (rs.next())
list.add(new FFmpegArguments(rs.getString(1), rs.getString(2), rs.getString(3)));
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (stat != null)
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
436552d3-d307-44d2-8f93-330e35262924 | 7 | public static <E> void reversedBFSWithLine(KAryTreeNode<E> root) {
if(root == null) {
return;
}
ArrayList<Integer> lineNodeCount = new ArrayList<Integer>();
Queue<KAryTreeNode<E>> queue = new LinkedList<KAryTreeNode<E>>();
Stack<KAryTreeNode<E>> stack = new Stack<KAryTreeNode<E>>();
queue.add(root);
lineNodeCount.add(1);
lineNodeCount.add(0);
int nextLine = 1;
int currLineNode = 0;
while(!queue.isEmpty()) {
KAryTreeNode<E> node = queue.poll();
stack.push(node);
currLineNode++;
for(int i=node.children.length-1;i>=0;i--) {
if(node.children[i] != null) {
queue.offer(node.children[i]);
lineNodeCount.set(nextLine, lineNodeCount.get(nextLine)+1);
}
}
if(currLineNode == lineNodeCount.get(nextLine-1)) {
nextLine++;
currLineNode = 0;
lineNodeCount.add(0);
}
}
int height = lineNodeCount.size()-3; // because there will be two 0s at the tail of line node count list
while(!stack.isEmpty()) {
KAryTreeNode<E> node = stack.pop();
System.out.print(node.value + " ");
lineNodeCount.set(height, lineNodeCount.get(height)-1);
if(lineNodeCount.get(height)==0) {
System.out.println();
height--;
}
}
} |
9168ae1a-38c0-431d-8c98-09dfc2bbbea1 | 6 | private void jButtonEliminarBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarBuscarActionPerformed
if (banco.longitud() == 0) {
mostrarOption("Error: No hay clientes registrados en el banco.\n Ingrese las cuentas antes de hacer esta operacion.", JOptionPane.ERROR_MESSAGE);
} else {
if (jRadioButtonEliminarNombre.isSelected()) {
if (jTextFieldNombreBuscar.getText().trim().compareToIgnoreCase("") == 0) {
mostrarOption("Error, ingrese el nombre a buscar", JOptionPane.ERROR_MESSAGE);
} else {
String nom = jTextFieldNombreBuscar.getText().trim();
int pos = banco.buscar(nom, 0);
if (pos == -1) {
jTextAreaEliminarVista.setText("\nError, cuenta no encontrada");
} else {
String t = banco.verCuenta(pos);
jTextAreaEliminarVista.setText("\nEncontrado! " + "\n" + t + "\nPresione eliminar para acabar con la accion.");
jButtonEliminarCuenta.setEnabled(true);
}
}
} else {
if (jTextFieldNumBuscar.getText().trim().compareToIgnoreCase("") == 0) {
mostrarOption("Error, ingrese el numero de cuenta a buscar", JOptionPane.ERROR_MESSAGE);
} else {
String cue = jTextFieldNumBuscar.getText().trim();
int pos = banco.buscar(cue, 0);
if (pos == -1) {
jTextAreaEliminarVista.setText("\nError, cuenta no encontrada");
} else {
String t = banco.verCuenta(pos);
jTextAreaEliminarVista.setText("\nEncontrado! " + "\n" + t + "\nPresione eliminar para acabar con la accion.");
jButtonEliminarCuenta.setEnabled(true);
}
}
}
}
}//GEN-LAST:event_jButtonEliminarBuscarActionPerformed |
4ec8ac7a-12e3-49bb-8fc6-b13b8478b000 | 7 | public boolean inAreaCapturable(Player p)
{
int x = p.getLocation().getBlockX();
int z = p.getLocation().getBlockZ();
int y = p.getLocation().getBlockY();
//inner 1/2
int capRadius = AreaRadius / 2;
if(capRadius*2 <= 50)
capRadius = 25;
String worldname = p.getWorld().getName();
boolean isInArea = false;
if(world.equalsIgnoreCase(worldname)) {
if(xLoc-capRadius <= x && x <= xLoc+capRadius) {
if(zLoc-capRadius <= z && z <= zLoc+capRadius) {
if(y > 50)
isInArea = true;
}
}
}
return isInArea;
} |
92819053-93e6-49a4-9b5f-d940c3e58d66 | 1 | @Override
protected void onConnect() {
if(addons.isEmpty())
registerAddons();
} |
7f32c5a4-7187-4f7a-b52c-ac2849d44954 | 0 | @Override
public void windowActivated(WindowEvent arg0)
{
} |
2bc27283-9c2d-47d7-b37e-647927f0cb20 | 2 | public int[][] getActualState()
{
int[][] gridState = new int[sudokuSize][sudokuSize];
for (int i = 0; i < sudokuSize; i++) {
for (int j = 0; j < sudokuSize; j++) {
gridState[i][j] = cells[i][j].valueState;
}
}
return gridState;
} |
32e0764f-2d10-4219-b62e-35a33c733946 | 5 | public static void backup(){
String fileDate = "";
String fileExt = ".bin";
//get parameters from GUI
getParametersFromGUI();
//check if the path ends with "/" or "\" - if not, display a Popup
if (!(filepath.endsWith("/") || filepath.endsWith("\\")))
OptionPanes.notifyFilepathEnd(gui);
//generate Date for fileName
if (gui.chckbx_Date.isSelected()){
DateGenerator myDate = new DateGenerator();
String[] dateArray = myDate.generateDate();
fileDate = " - " + dateArray[0]+ "-" + dateArray[1]+ "-" +dateArray[2];
}
//call the HttpBasicAuth class to handle the authentification and backup
HttpBasicAuth HttpAuthentication = new HttpBasicAuth();
try{
if(HttpAuthentication.getBackupFile(ipAddress, user, password, filepath, filename, fileExt, fileDate))
OptionPanes.notifyBackupSuccess(gui);
}
catch(IOException e){
OptionPanes.notifyConnectionError(gui, e.getMessage());
}
} |
6cdd5739-591f-428a-844a-197b0f36ce0a | 4 | public String createCalendar(String username, String calendar, boolean isPublic) {
try {
crs = qb.selectFrom("calendars").where("calendar", "=", calendar).executeQuery();
if(!crs.next()) {
if(isPublic)
{
String[] keys = {"calendar", "createdBy"};
String[] values = {calendar, username};
qb.insertInto("calendars", keys).values(values).execute();
} else {
String[] keys = {"calendar", "createdBy", "isPublic"};
String[] values = {calendar, username, "0"};
qb.insertInto("calendars", keys).values(values).execute();
String[] keys2 = {"username", "calendar"};
String[] values2 = {username, calendar};
qb.insertInto("usercalendars", keys2).values(values2).execute();
}
return "Calendar created";
} else {
return "Calendar exists";
}
} catch (SQLException e) {
return "error";
} finally {
try {
crs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} |
d009c49d-c994-4fd6-9460-103f2dc4d30c | 5 | @Override
public void visitEnd() {
boolean hasDummy = dummyArgument != 0;
String callerMethodDescriptor = hasDummy ? methodDescriptor.replace("I)", ")") : methodDescriptor;
Type[] argumentTypes = Type.getArgumentTypes(methodDescriptor);
MethodVisitor methodVisitor = cv.visitMethod(Opcodes.ACC_PUBLIC, callerMethodName, callerMethodDescriptor, null, null);
methodVisitor.visitCode();
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
for (int i = 0; i < argumentTypes.length - (hasDummy ? 1 : 0); i++) {
methodVisitor.visitVarInsn(argumentTypes[i].getOpcode(Opcodes.ILOAD), i + 1);
}
if (hasDummy) {
methodVisitor.visitLdcInsn(dummyArgument);
}
methodVisitor.visitMethodInsn(isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKEVIRTUAL, ownerName, methodName, methodDescriptor);
methodVisitor.visitInsn(Type.getReturnType(methodDescriptor).getOpcode(Opcodes.IRETURN));
methodVisitor.visitMaxs(0, 0);
methodVisitor.visitEnd();
cv.visitEnd();
} |
431b5ea9-5fb3-48a2-8a13-52727ae0c979 | 9 | private void process() {
Scanner in = new Scanner(System.in);
int hotkeys = in.nextInt();
HashMap<String,ArrayList<String>> operationsPerKey = new HashMap<String,ArrayList<String>>();
ArrayList<String> possible = new ArrayList<String>();
in.nextLine();
for (int i = 0; i < hotkeys; i++) {
String keyLine = in.nextLine();
String operation = in.nextLine().trim();
String[] keys = keyLine.split(" ");
for (String key : keys) {
if (!operationsPerKey.containsKey(key)) {
operationsPerKey.put(key, new ArrayList<String>());
}
operationsPerKey.get(key).add(operation);
}
possible.add(operation);
}
int tests = in.nextInt();
in.nextLine();
for (int i = 0; i < tests; i++) {
String keyLine = in.nextLine();
String[] keys = keyLine.split(" ");
ArrayList<String> possibleTest = (ArrayList<String>)possible.clone();
for (String key : keys) {
if (!operationsPerKey.containsKey(key)) {
continue;
}
ArrayList<String> operations = operationsPerKey.get(key);
int j = 0;
while (j < possibleTest.size() ) {
String operation = possibleTest.get(j);
if (!operations.contains(operation)) {
possibleTest.remove(operation);
} else {
j++;
}
}
}
if (possibleTest.size() != 1) {
System.out.println("Houston tenemos un problema");
}
System.out.println(possibleTest.get(0));
}
in.close();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.