method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
bcbd31c9-f015-4321-bd04-b13b28e81533 | 3 | @Override
public boolean equals(Object obj) {
if (!(obj instanceof Ball)) return false;
return (super.equals(obj)) && (this.xSpeed == ((Ball) obj).xSpeed) && (this.ySpeed == ((Ball)obj).ySpeed);
} |
f614b70e-54db-48fe-b1c5-9e9f16873006 | 8 | public void updateRanks(DB_Timers timer, Boolean all) {
if (all) {
List<DB_Timers> timers = this.plugin.database.getDatabase().find(DB_Timers.class).findList();
if (timers != null && timers.size() > 0) {
for (DB_Timers timerdata : timers) {
Integer TimerID = timerdata.getId();
HashMap<String, String> timerRanks = new LinkedHashMap<String, String>();
List<DB_Times> times = this.plugin.database.getDatabase().find(DB_Times.class).where().eq("TimerID", TimerID).order().asc("Time").findList();
this.plugin.rankList.put(TimerID, timerRanks);
if (times != null) {
int i = 1;
for (DB_Times time : times) {
String playerName = time.getPlayername();
Long playerTime = time.getTime();
timerRanks.put(playerName, i + "," + playerTime);
i++;
}
this.plugin.rankList.put(TimerID, timerRanks);
}
}
}
else {
this.plugin.log.log(Level.INFO, "Error: could not find any enabled timers in DB to update ranks.");
}
}
else {
Integer TimerID = timer.getId();
HashMap<String, String> timerRanks = new LinkedHashMap<String, String>();
List<DB_Times> times = this.plugin.database.getDatabase().find(DB_Times.class).where().eq("TimerID", TimerID).order().asc("Time").findList();
this.plugin.rankList.put(TimerID, timerRanks);
if (times != null) {
int i = 1;
for (DB_Times time : times) {
String playerName = time.getPlayername();
Long playerTime = time.getTime();
timerRanks.put(playerName, i + "," + playerTime);
i++;
}
this.plugin.rankList.put(TimerID, timerRanks);
}
}
} |
648a4911-5a70-46c3-addc-edef88edb156 | 7 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BoundingBox other = (BoundingBox) obj;
if (Double.doubleToLongBits(bottom) != Double
.doubleToLongBits(other.bottom))
return false;
if (Double.doubleToLongBits(left) != Double
.doubleToLongBits(other.left))
return false;
if (Double.doubleToLongBits(right) != Double
.doubleToLongBits(other.right))
return false;
if (Double.doubleToLongBits(top) != Double.doubleToLongBits(other.top))
return false;
return true;
} |
2520c65a-db0f-4dee-8215-ccfca8618f6d | 2 | private void testRead(){
String f_name = this.path + Params.nTests + ".txt";
long startTime = 0;
long endTime = 0;
File f = new File(f_name);
FileInputStream fin = null;
try{
fin = new FileInputStream(f);
byte[] buf = new byte[Params.packSize * Params.nPacks];
for(int i = 0 ; i < Params.nTests ; i++){
startTime = System.nanoTime();
fin.read(buf);
endTime = System.nanoTime();
this.graf.add(endTime - startTime);
}
fin.close();
}catch(IOException e){
//TODO: catch error
e.printStackTrace();
}
} |
9c047353-4b99-427e-a0f7-ca5aaf357261 | 7 | private void computeUidlCommand(String message) {
String[] cmd = message.split(" ");
// Auf Argument ueberpruefen
if (cmd.length > 1) {
// Es wurde ein Argument gefunden
int n = Integer.parseInt(cmd[1]);
// -ERR Antwort, wenn Mail geloescht wurde
if (mailIsDeleted(n)) {
try {
writeToClient("-ERR no such message");
} catch (IOException e) {
deleteMailsOnException();
sTrace.error("Connection aborted by client! Thread" + name);
}
} else {
// Sende Antwort der Form "+OK n s", fuer n = Nummer der
// Nachricht, s = UIDL (und Name) der Nachricht, zuruck
try {
writeToClient("+OK " + n + " " + mails.get(n));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// Es wurde kein Argument gefunden.
try {
// Positive Antwort schicken
writeToClient("+OK");
// Liste der UIDLs schicken
for (int i = 1; i <= mailCounter; i++) {
if (!mailIsDeleted(i)) {
String response = "" + i + " " + mails.get(i);
writeToClient(response);
}
}
// Ende der Mehrzeiligen Antwort senden
writeToClient(".");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
1272898a-bbfc-4880-9994-3e23cbf163b5 | 0 | public OSCPacket() {
} |
b645253d-b744-4fe6-b86a-d2447f3c551d | 9 | public boolean inBorders(Crossing c) { //Don't know if commenting out this makes it work. huh
double tolerance = 0.00001;
if (c.atInf()) {
if (c.atNegInf() && leftborder) {
return false;
}
if (!c.atNegInf() && rightborder) {
return false;
}
}
if (leftborder && c.crAt() < leftb-tolerance) { return false;}
if (rightborder && c.crAt() >= rightb+tolerance) { return false;}
return true;
} |
cc40dc15-0b24-4745-9543-de7d743ec3f3 | 6 | public Personaje(InterfazPersonaje tipo, Juego g, Ventana window, int x, int y) throws IOException{
this.posX = x;
this.posY = y;
this.game = g;
this.tipoPersonaje = tipo;
this.tipoPersonaje.cambiarPoder(this);
this.tipoPersonaje.cambiarImagenes(this);
this.escudo = this.espada = this.gema = false;
if(tipo.getClass() == (new HeroeNieve().getClass()) || tipo.getClass() == (new HeroeCueva().getClass()))
this.vida = VIDA_HEROE;
else if(tipo.getClass() == (new EnemigoNieve().getClass()) || tipo.getClass() == (new EnemigoCueva().getClass()))
this.vida = VIDA_ENEMIGO;
else if(tipo.getClass() == (new LocoNieve().getClass()) || tipo.getClass() == (new LocoCueva().getClass()))
this.vida = VIDA_LOCO;
} |
f40db1f4-e4ce-4a9d-938f-213e1cb8fe13 | 3 | public void openConnection() {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:@olimpia.lcc.uma.es:1521:edgar", "inftel14_40",
"psts");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
}
if (connection != null) {
System.out.println("Yeah! Conection with database succesful.");
this.con = connection;
} else {
System.out.println("Failed to make connection!");
}
} |
e957fa5f-f21e-438f-a72e-f5e7d6bbaef5 | 6 | public void run() {
/* if (Frame.clickButton.isVisible())
{
}
else
{
}
if (buttonHaveBeenClicked)
{
buttonHaveBeenClicked = false;
if (timer.get_ticks() == 1000 - (score * 100))
{
buttonHaveBeenClicked = false;
}
if((score >= 10) && (buttonSize >= 20)) {
buttonSize--;
}
Frame.clickButton.setBounds((int)(Math.random() * (Frame.frame.getWidth() - buttonSize)), (int)(Math.random() * (Frame.frame.getHeight() - buttonSize)) + 0, buttonSize, buttonSize);
Frame.clickButton.setVisible(true);
}
else
{
Frame.frame.getWidth() + Frame.frame.getHeight();
}
new Thread(new Sound()).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} */
// rudelune code /\ Luc14860 code \/
new Thread(new Sound()).start();
while(buttonHaveBeenClicked) {
buttonHaveBeenClicked = false;
if(1000 - (score * 100) > 0) {
try {
Thread.sleep(1000 - (score * 100)); //Avant de faire apparaitre le bouton
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if((score >= 10) && (buttonSize >= 20)) {
buttonSize--;
}
Frame.clickButton.setBounds((int)(Math.random() * (Frame.frame.getWidth() - buttonSize)), (int)(Math.random() * (Frame.frame.getHeight() - buttonSize)) + 0, buttonSize, buttonSize);
Frame.clickButton.setVisible(true);
try {
Thread.sleep((Frame.frame.getWidth() + Frame.frame.getHeight())); //Avant de cliquer dessus
} catch (InterruptedException e) {
e.printStackTrace();
}
}
OnlineManager.setScore(Frame.usernameField.getText(), score);
Frame.clickButton.setEnabled(false);
Frame.loseMessage.setVisible(true);
Frame.quitButton.setVisible(true);
Frame.quitButton.setBounds((Frame.frame.getWidth() / 2) - 100, (Frame.frame.getHeight() / 2) + 30, 200, 50);
} |
db15b005-bdd0-4574-b34e-7a94657245e6 | 9 | protected void calcIntegValue() {
double a = 0.0, b = 0.0;
double eps = 1e-4;
double result = 0.0;
try {
a = Double.parseDouble(lowTextField.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "积分下限输入错误,请检查重输。");
lowTextField.requestFocus();
lowTextField.selectAll();
}
try {
b = Double.parseDouble(topTextField.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "积分上限输入错误,请检查重输。");
topTextField.requestFocus();
topTextField.selectAll();
}
try {
eps = Double.parseDouble(accuracyComboBox.getSelectedItem()
.toString());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "精确度输入错误,请检查重输。");
accuracyComboBox.requestFocus();
accuracyComboBox.setSelectedIndex(0);
}
Details.ex = funcTextField.getText().replaceAll("\\s+", "");
if (!CheckString.isFuncRight(Details.ex)) {
JOptionPane.showMessageDialog(null, "函数输入错误,请检查重输。");
funcTextField.requestFocus();
funcTextField.selectAll();
} else {
run r = new run();
switch (methodsComboBox.getSelectedIndex()) {
case 0:
result = r.getValueTrapezia(a, b, eps);
break;
case 1:
result = r.getValueSimpson(a, b, eps);
break;
case 2:
result = r.getValueRomberg(a, b, eps);
break;
case 3:
result = r.getValueATrapezia(a, b, 0.0001, eps);
break;
case 4:
result = r.getValueLegdGauss(a, b, eps);
break;
}
}
integResultTextField.setText(result + "");
} |
84bf2949-e0a6-4b3f-bbee-7315e8bf03a5 | 0 | public void hideAll() {
defaultVisible = false;
visibleNodes.clear();
} |
5b0dafb6-64c2-427b-84f5-6521d0e724fe | 0 | public SimpleStringProperty cityCodeProperty() {
return cityCode;
} |
5f3d70f2-1022-4292-9159-5e4afaf11c7e | 3 | private void shutdownOpenGL() throws Exception
{
log("Shutting down OpenGL");
if (Keyboard.isCreated())
{
log("Destroying keyboard");
Keyboard.destroy();
}
if (Mouse.isCreated())
{
log("Destroying mouse");
Mouse.destroy();
}
if (Display.isCreated())
{
log("Destroying display");
Display.destroy();
}
} |
459fc3b5-cedb-4d6a-9bdc-0b26214acaaa | 0 | public UnboundGrammar() {
setStartVariable("S");
} |
5ff8b875-1fdc-45e1-a761-68d83141e8f3 | 2 | public void run() {
while (!generator.isCanceled()) {
int val = generator.next();
if (val % 2 != 0) {
System.out.println(val + " not even!");
generator.cancel(); // Cancels all EvenCheckers
}
}
} |
b81e4e9f-bb07-4bdf-b057-b185aa9eca26 | 1 | public void makeMove(int position, int player){
if (validMove(position,player)){
updateGameField(position,player);
this.changeTurn();
}
} |
54641307-5882-4b4c-a948-a1735ff48e05 | 5 | public static Color biomeToColor(byte b) {
switch (b) {
case DESERT:
return DESERT_COLOR;
case SAVANNAH:
return SAVANNAH_COLOR;
case SWAMP_RAIN_FOREST:
return SWAMP_RAIN_FOREST_COLOR;
case MODERATE:
return MODERATE_COLOR;
case TUNDRA:
return TUNDRA_COLOR;
default:
return MODERATE_COLOR;
}
} |
67146b03-8089-439d-ac71-6ac94a9c27c3 | 5 | public static int[] contains(String position) {
int[] v = new int[2];
for (int i = 2; i < 10; i++) {
for (int j = 2; j < 10; j++) {
for (int k = 2; k < 10; k++) {
for (int l = 2; l < 10; l++) {
if (position.equals(boardOfMoves[i][j] + boardOfMoves[k][l])) {
v[0] = board[i][j];
v[1] = board[k][l];
}
}
}
}
}
return v;
} |
4b512410-2419-4abf-872f-1081d2913727 | 6 | public void insertTag(Tag tag, int index) {
if (type != Type.TAG_List && type != Type.TAG_Compound)
throw new RuntimeException();
Tag[] subtags = (Tag[]) value;
if (subtags.length > 0)
if (type == Type.TAG_List && tag.getType() != getListType())
throw new IllegalArgumentException();
if (index > subtags.length)
throw new IndexOutOfBoundsException();
Tag[] newValue = new Tag[subtags.length + 1];
System.arraycopy(subtags, 0, newValue, 0, index);
newValue[index] = tag;
System.arraycopy(subtags, index, newValue, index + 1, subtags.length - index);
value = newValue;
} |
294043a4-1b96-4f82-9da6-8c04f41d9114 | 9 | @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(this.ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already wearing mage armor."));
return false;
}
if(target.freeWearPositions(Wearable.WORN_TORSO,(short)0,(short)0)==0)
{
mob.tell(L("You are already wearing something on your torso!"));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("A magical breast plate appears around <S-NAME>."):L("^S<S-NAME> invoke(s) a magical glowing breast plate!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
theArmor=CMClass.getArmor("GlowingMageArmor");
theArmor.basePhyStats().setArmor(theArmor.basePhyStats().armor()+super.getXLEVELLevel(mob));
theArmor.setLayerAttributes(Armor.LAYERMASK_SEETHROUGH);
mob.addItem(theArmor);
theArmor.wearAt(Wearable.WORN_TORSO);
theArmor.recoverPhyStats();
success=beneficialAffect(mob,target,asLevel,0)!=null;
mob.location().recoverRoomStats();
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> attempt(s) to invoke magical protection, but fail(s)."));
// return whether it worked
return success;
} |
5c65098c-366f-4b51-a170-ca0e768411e8 | 2 | private void updatePhysicalEntityList() {
allPhysicalEntities = new ArrayList<Mob>();
for (Mob m : dots)
allPhysicalEntities.add(m);
for (Mob m : polygons)
allPhysicalEntities.add(m);
} |
2fb222ba-5cb5-48c9-a46f-60aeef2da143 | 9 | public String runMacro(HTTPRequest httpReq, String parm)
{
final String last=httpReq.getUrlParameter("COMPONENT");
if(last==null)
return " @break@";
if(last.length()>0)
{
final String fixedCompID=last.replace(' ','_').toUpperCase();
final List<AbilityComponent> set=new Vector<AbilityComponent>();
int posDex=1;
while(httpReq.isUrlParameter(fixedCompID+"_PIECE_CONNECTOR_"+posDex) && httpReq.getUrlParameter(fixedCompID+"_PIECE_CONNECTOR_"+posDex).trim().length()>0)
{
final String mask=httpReq.getUrlParameter(fixedCompID+"_PIECE_MASK_"+posDex);
final String str=httpReq.getUrlParameter(fixedCompID+"_PIECE_STRING_"+posDex);
final String amt=httpReq.getUrlParameter(fixedCompID+"_PIECE_AMOUNT_"+posDex);
final String conn=httpReq.getUrlParameter(fixedCompID+"_PIECE_CONNECTOR_"+posDex);
final String loc=httpReq.getUrlParameter(fixedCompID+"_PIECE_LOCATION_"+posDex);
final String type=httpReq.getUrlParameter(fixedCompID+"_PIECE_TYPE_"+posDex);
final String consumed=httpReq.getUrlParameter(fixedCompID+"_PIECE_CONSUMED_"+posDex);
if(!conn.equalsIgnoreCase("DELETE"))
{
final AbilityComponent able=(AbilityComponent)CMClass.getCommon("DefaultAbilityComponent");
able.setAmount(CMath.s_int(amt));
if(posDex==1)
able.setConnector(AbilityComponent.CompConnector.AND);
else
able.setConnector(AbilityComponent.CompConnector.valueOf(conn));
able.setConsumed((consumed!=null)&&(consumed.equalsIgnoreCase("on")||consumed.equalsIgnoreCase("checked")));
able.setLocation(AbilityComponent.CompLocation.valueOf(loc));
able.setMask(mask);
able.setType(AbilityComponent.CompType.valueOf(type), str);
set.add(able);
}
posDex++;
}
if(CMLib.ableComponents().getAbilityComponentMap().containsKey(last.toUpperCase().trim()))
{
final List<AbilityComponent> xset=CMLib.ableComponents().getAbilityComponentMap().get(last.toUpperCase().trim());
xset.clear();
xset.addAll(set);
}
else
CMLib.ableComponents().getAbilityComponentMap().put(last.toUpperCase().trim(),set);
CMLib.ableComponents().alterAbilityComponentFile(last.toUpperCase().trim(),false);
}
return "";
} |
ca18b701-6b57-423d-9654-b05f45281028 | 2 | @Override
public Key select(int rank)
{
if (rank < 0 || rank >= N)
return null;
return keys[rank];
} |
462d0c52-8902-4476-bd37-ca6ab20ae790 | 0 | @Override
public void keyPressed(KeyEvent arg0) {
inputEvents.addLast(arg0);
} |
46cbdff6-e0a1-474c-aad7-44811df4052d | 3 | public static String getTime() {
Calendar cal = Calendar.getInstance();
String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
if (hour.length() == 1) {
hour = "0" + hour; //pad with zero for 0..9
}
String min = String.valueOf(cal.get(Calendar.MINUTE));
if (min.length() == 1) {
min = "0" + min; //pad with zero for 0..9
}
String sec = String.valueOf(cal.get(Calendar.SECOND));
if (sec.length() == 1) {
sec = "0" + sec; //pad with zero for 0..9
}
return hour + "_" + min + "_" + sec;
} |
584cb6dc-ddcd-4393-8850-9b6155282474 | 5 | public static boolean isPrime(long num)
{
if (num<2)
return false;
if (num==2)
return true;
if (num%2==0)
return false;
for (long i = 3; (i*i)<=(num); i+=2)
{
if (num%i == 0)
return false;
}
return true;
} |
2b5a20b0-f28e-403d-bd76-ebe43df34ac9 | 6 | public void drawSprite(int i, int k)
{
i += anInt1442;
k += anInt1443;
int l = i + k * DrawingArea.width;
int i1 = 0;
int j1 = myHeight;
int k1 = myWidth;
int l1 = DrawingArea.width - k1;
int i2 = 0;
if(k < DrawingArea.topY)
{
int j2 = DrawingArea.topY - k;
j1 -= j2;
k = DrawingArea.topY;
i1 += j2 * k1;
l += j2 * DrawingArea.width;
}
if(k + j1 > DrawingArea.bottomY)
j1 -= (k + j1) - DrawingArea.bottomY;
if(i < DrawingArea.topX)
{
int k2 = DrawingArea.topX - i;
k1 -= k2;
i = DrawingArea.topX;
i1 += k2;
l += k2;
i2 += k2;
l1 += k2;
}
if(i + k1 > DrawingArea.bottomX)
{
int l2 = (i + k1) - DrawingArea.bottomX;
k1 -= l2;
i2 += l2;
l1 += l2;
}
if(!(k1 <= 0 || j1 <= 0))
{
method349(DrawingArea.pixels, myPixels, i1, l, k1, j1, l1, i2);
}
} |
111cf8c1-5a17-4a17-9eea-5dd856025385 | 9 | public static void main(String[] args) throws Exception {
if (args != null && args.length > 0) {
ResourceBundleUtil.init(args[0].substring(0, args[0].lastIndexOf(".")));
}
TestRunner.rowCounter = new AtomicCounter(Integer.parseInt(get("base.row")));
rowCounter.getPrevousValue();
setLog();
logger.info("##### {} #########################################", "START");
if (args.length > 1) {
String cmd = args[1];
logger.info("COMMAND : {}", cmd) ;
if (StringUtils.equals("COPY", cmd)) {
File to = new File(get("mail.file.path") + get("output.file"));
if (to.exists()) {
logger.error("File already exists : {}", to.getAbsolutePath());
return;
} else {
try {
Files.createParentDirs(to);
File from = new File(get("output.dir") + get("output.file"));
Files.copy(from, to);
logger.info("COPY COMPLETED #######################");
logger.info("FROM : {}", from.getAbsolutePath());
logger.info("TO : {}", to.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
return;
} else if (StringUtils.equals("MAIL", cmd)) {
String h = get("mail.smtp.host");
String p = get("mail.smtp.port");
String u = get("mail.auth.user.name");
String up = get("mail.auth.user.pass");
MailSender ms = new MailSender(h, p, u, up);
String subject = get("mail.subject");
String body = get("mail.body");
String from = get("mail.address.from");
String to = get("mail.address.to");
String cc = get("mail.address.cc");
ms.send(subject, body, from, to, cc);
logger.info("MAIL SENT SUCCESSFULLY #######################");
return;
}
}
String f = get("input.file." + get("site"), false);
Workbook wb = ExcelUtil.getWorkbook(get("input.folder") + f);
logger.info("##### {} #########################################", "MAKE FIRST SHEET");
makeFirstSheet(wb);
logger.info("##### {} #########################################", "MAKE SVN INFO");
getSVNInfo(wb);
if (StringUtils.equals(get("modified.file.check"),"Y")) {
logger.info("##### {} #########################################", "MAKE MODIFIED FILE INFO");
List<File> modifiedFileList = ModifiedFileFilter.getModifiedFileList();
for (File f2 : modifiedFileList) {
writeRow("???", f2.getPath(), f2.getName(), "update", wb);
}
}
logger.info("##### {} #########################################", "MAKE EXCEL FILE");
writeWorkbook(wb);
logger.info("##### {} #########################################", "MAKE MAIL");
makeMailContent();
logger.info("##### {} #########################################", "END");
} |
9afd9f35-584b-4148-a027-01eb0ef093d2 | 8 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final DateDTO other = (DateDTO) obj;
if (!Objects.equals(this.year, other.year)) {
return false;
}
if (!Objects.equals(this.month, other.month)) {
return false;
}
if (!Objects.equals(this.day, other.day)) {
return false;
}
if (!Objects.equals(this.hour, other.hour)) {
return false;
}
if (!Objects.equals(this.minute, other.minute)) {
return false;
}
if (!Objects.equals(this.second, other.second)) {
return false;
}
return true;
} |
52034449-d2b2-4784-b8fc-ddb385fa31eb | 6 | private void fillTileArrays() {
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[0].length; j++) {
int value = mapImage.getRGB(i, j);
value = value & 255;
pixels[i][j] = value > 0 ? 3 : 0;
if (value == 0) {
navigationGraph[i][j] = new MapTile(i, j);
}
//System.out.print(pixels[i][j] + " ");
}
//System.out.println();
}
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[0].length; j++) {
pixels[i][j] = determineTileType(i, j);
}
}
} |
244bfbfc-2216-4ed7-81fa-67deced0c72c | 5 | private void encode(Object value)
{
this.value = value;
if (value==null)
{
type = 1;
return;
}
if (value instanceof Dubble) encodeDouble();
if (value instanceof Bool) encodeBool();
if (value instanceof VLQ) encodeVLQ();
if (value instanceof VLQString) encodeVLQString();
// if (value instanceof VariantArray) encodeVariantArray(); TODO
// if (value instanceof Dictionary) encodeDictionary(); TODO
} |
e01633b9-5532-4a8e-be4a-ddf5a6396761 | 9 | @Override
public void actionPerformed(ActionEvent arg0)
{
if (colorGain)
colorN += 3;
else
colorN -= 5;
if (colorN >= 200)
colorGain = false;
else if (colorN <= 30)
colorGain = true;
if (!seen)
{
if(frame.getTutorial() <= 4)
{
tutorial = true;
hero.setPaused(true);
if (tutorialX > 0)
{
tutorialX -= 15;
tutorialEnd = true;
}
if (tutorialMoved)
{
tutorialX -= 15;
if (tutorialX < -930)
{
tutorial = false;
hero.setPaused(false);
}
}
}
}
if (!tutorial)
{
setRunning(true);
}
else
{
setRunning(false);
}
super.actionPerformed(arg0);
} |
73266fe5-8859-4bd4-8a49-9e9b719c223b | 6 | @Override
public void mouseClicked(MouseEvent event) {
if (frame.getCurrentPlayer().getPlaysLeft() != 0 && !frame.isGameOver()) {
int row = (int) Math.round(4.0 / 3.0 * (event.getY() - 40.0)
/ HEX_HEIGHT);
int col = (int) Math.round((event.getX() - 40 - 0.5 * HEX_WIDTH
* (5 - row))
/ HEX_WIDTH);
Tile t = frame.getSelectedTile();
Player player = frame.getCurrentPlayer();
if (t != null) {
if (frame.play(t, row, col)) {
frame.setSelectedTile(null);
}
if (player.getPlaysLeft() == 0) {
if (!player.canSwapTiles()) {
player.refreshHand();
} else {
frame.setButtonEnabledness(true);
}
frame.setSelectedTile(null);
}
}
}
frame.repaint();
} |
4233d6ca-fce0-41d1-ad55-775a60fb64b9 | 5 | public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(int x = 0; x < maxFields; x++){
for(int y = 0; y < maxFields; y++) {
this.field = map.get(x).get(y);
int size = field.getTileSize();
size = miniscale > 0 ? (int) size/miniscale : size;
// draw tiles in rows
if(y==0){
xCrd[0] = space-size + size*x;
xCrd[1] = space + size*x;
xCrd[2] = space+size + size*x;
xCrd[3] = space + size*x;
yCrd[0] = space/2+size/2 + (size/2)*x;
yCrd[1] = space/2+0 + (size/2)*x;
yCrd[2] = space/2+size/2 + (size/2)*x;
yCrd[3] = space/2+size + (size/2)*x;
}
// draw tiles in colum
else{
xCrd[0] = space-size - size*y + size*x;
xCrd[1] = space - size*y + size*x;
xCrd[2] = space+size - size*y + size*x;
xCrd[3] = space - size*y + size*x;
yCrd[0] = space/2+size/2 + (size/2)*y + (size/2)*x;
yCrd[1] = space/2+0 + (size/2)*y + (size/2)*x;
yCrd[2] = space/2+size/2 + (size/2)*y + (size/2)*x;
yCrd[3] = space/2+size + (size/2)*y + (size/2)*x;
}
Polygon p = new Polygon(xCrd, yCrd, xCrd.length);
// draw tile
g2.setColor(field.getColor());
g2.fillPolygon(p);
// draw grid
if(grid){
g2.setStroke(new BasicStroke((int)size/32));
g2.setColor(Color.black);
}
g2.drawPolygon(p);
}
}
} |
4ce2ad29-225e-4efe-8e7a-8bf2d257ec4c | 0 | public ColorResource(int a, int r, int g, int b) {
this.a = a;
this.r = r;
this.g = g;
this.b = b;
} |
8bb2fdb6-2197-4f83-acff-a264d56bd077 | 5 | public boolean sLeft(){
boolean change = false;
//i -> y | j -> x
for (int i = 0 ; i < 4 ; i ++){
for (int j = 0; j < 4 ; j++) {
if(mLeft(j, i))
change = true;
}
if (aLeft(i))
change = true;
}
if (change){
//System.out.println(change); //debug
genTile();
}
return change;
} |
409488ed-0423-4376-886d-37374aadf448 | 8 | @EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
if (event.getFrom().getWorld() == event.getTo().getWorld() &&
event.getFrom().getBlockX() == event.getTo().getBlockX() &&
event.getFrom().getBlockY() == event.getTo().getBlockY() &&
event.getFrom().getBlockZ() == event.getTo().getBlockZ())
return;
Player player = event.getPlayer();
if (player.getHealth() <= 0.0D) return; // player is dead
Chunk oldChunk = event.getFrom().getChunk();
Chunk newChunk = event.getTo().getChunk();
// Only when the player moves a complete chunk:
if (oldChunk.getWorld() != newChunk.getWorld() || oldChunk.getX() != newChunk.getX() || oldChunk.getZ() != newChunk.getZ()) {
this.plugin.updatePlayerView(player);
}
} |
caa7b7ea-5445-46c3-989e-3400a565bef5 | 8 | @Override public SimOrgNode update( SimNode rootNode, long timestamp, Message m, List<Message> messageDest ) {
if( timestamp < nextAutoUpdateTime && !BitAddressUtil.rangesIntersect(m, minId, maxId) ) return this;
for( int i=0; i<childs.length; ++i ) {
SimNode newChild = childs[i].update( rootNode, timestamp, m, messageDest );
if( newChild != childs[i] ) {
// Something changed!
List<SimNode> newChilds = new ArrayList<SimNode>(childs.length);
for( int j=0; j<i; ++j ) newChilds.add( childs[j] );
if( newChild != null ) newChilds.add(newChild);
for( int j=i+1; j<childs.length; ++j ) {
if( (newChild = childs[j].update( rootNode, timestamp, m, messageDest )) != null ) {
newChilds.add(newChild);
}
}
return new SimOrgNode(newChilds.toArray(new SimNode[newChilds.size()]));
}
}
return this;
} |
56f409f8-e219-4aff-8ac9-d318b07e139d | 6 | public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == internalView.getNextMonthButton()) {
internalModel.getModel().addMonth(1);
}
else if (arg0.getSource() == internalView.getPreviousMonthButton()) {
internalModel.getModel().addMonth(-1);
}
else if (arg0.getSource() == internalView.getNextYearButton()) {
internalModel.getModel().addYear(1);
}
else if (arg0.getSource() == internalView.getPreviousYearButton()) {
internalModel.getModel().addYear(-1);
}
else {
for (int month = 0; month < internalView.getMonthPopupMenuItems().length; month++) {
if (arg0.getSource() == internalView.getMonthPopupMenuItems()[month]) {
internalModel.getModel().setMonth(month);
}
}
}
} |
c2382191-5632-4ce1-b8a6-d848aa513559 | 1 | public void setEscapes(String escapes, String replacements){
int length = escapes.length();
if (replacements.length() < length){
length = replacements.length();
}
this.escapes = escapes.substring(0, length);
this.replacements = replacements.substring(0, length);
} |
31e44d60-9f54-4b4f-a9f5-ed6af87c131b | 4 | private void JBEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBEditarActionPerformed
this.zerarModelo();
int crm;
try{
int linha = JTListaMedico.getSelectedRow();
if( linha >= 0){
crm = (int) JTListaMedico.getValueAt(linha,0);
}else{
throw new Exception("Nenhum medico foi selecionado");
}
for (Medico listaMedico1 : this.listaMedico) {
if (crm == listaMedico1.getCrm()) {
CadastrarMedicoUI cadastroMedico = new CadastrarMedicoUI(listaMedico1);
cadastroMedico.setVisible(true);
PrincipalUI.obterInstancia().obterTela().add(cadastroMedico);
cadastroMedico.toFront();
}
}
}catch(Exception ex){
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}//GEN-LAST:event_JBEditarActionPerformed |
8864e74c-5444-4c0b-b3b0-9785f5a98787 | 8 | public ArrayList<Employee> AllEmployeesInFranchise(int FranID)
throws UnauthorizedUserException, BadConnectionException
{
PreparedStatement pStmnt = null;
ArrayList<Employee> BPList = new ArrayList<Employee>();
// Get the employee type through JClIO instance
lio = JCGlIO.getInstance();
try {
if( "1".equals(lio.geteT())) {
pStmnt = con.prepareStatement(qs.owner_view_emp);
}else if("2".equals(lio.geteT())) {
pStmnt = con.prepareStatement(qs.man_view_emp);
}else
throw (new UnauthorizedUserException("AccessDenied"));
pStmnt.setInt(1, FranID);
resultSet = pStmnt.executeQuery();
while (resultSet.next())
{
Employee temp = new Employee();
temp.setAddress(resultSet.getString("Address"));
temp.setCity(resultSet.getString("City"));
temp.setEmail(resultSet.getString("Email"));
temp.setEmpType(resultSet.getInt("EmpType"));
temp.setFirstName(resultSet.getString("Fname"));
temp.setFranchiseNumber(resultSet.getInt("FranchiseNumber"));
temp.setLastName(resultSet.getString("Surname"));
temp.setPhone(resultSet.getString("Phone"));
temp.setState(resultSet.getString("State"));
temp.setEmployeeID(resultSet.getInt("EmployeeID"));
temp.setZip(resultSet.getInt("Zip"));
BPList.add(temp);
}
}catch(SQLException sqlE) {
if(sqlE.getErrorCode() == 1142)
throw(new UnauthorizedUserException("AccessDenied"));
else
throw(new BadConnectionException("BadConnection"));
}
finally {
try {
if (resultSet != null) resultSet.close();
if (pStmnt != null) pStmnt.close();
}
catch (Exception e) {};
}
return BPList;
} |
372b1a80-d702-46ca-8396-1375b80c0f2b | 2 | public static void main(String[] args) {
System.out.println("Which kind of connection should be established?");
System.out.println("typ 1 for a anonymous session");
System.out.println("typ 2 for a user+password session");
Scanner scanner = new Scanner(System.in);
int input;
input = scanner.nextInt();
switch(input) {
case(1): ApplicationFtpClient.testForServerWithAnonyoumsAccount();
break;
case(2): ApplicationFtpClient.testforServerWithUserPasswortAccount();
break;
}
} |
9b7466eb-f5d9-4bfa-bca0-e568077258ed | 0 | public void setContactName(String contactName) {
this.contactName = contactName;
} |
2ab2ea75-233f-48ac-a4ef-78e6b767b1bd | 1 | public int getRowDividerHeight() {
return mShowRowDivider ? 1 : 0;
} |
b9b904b7-8759-438c-96fb-7bc3626e9e1a | 6 | public void mouseReleased(MouseEvent evt) {
if (mousein == 1 && evt.getSource()==buy){
settle();
calcStats();
refresh();
}
if (mousein == 2 && evt.getSource()==ok){
settle();
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
}
if (mousein == 3 && evt.getSource()==close){
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
}
} |
520323ae-fd60-4d63-9e3d-1aef1ec05dcf | 8 | public float getHeight(float x, float y, float z)
{
if(x < 0 || y < 0 || z < 0 || x >= xyz[0] || y >= xyz[1] || z >= xyz[2])
{
return 1;
}
int tile = tiles[(int)x][(int)y][(int)z].type;
switch (tile)
{
case 0: //empty
return -1;
case 1://Solid block
return 1;
//case 2://Floor
// return 0;
default:
return -1;
}
} |
b884b06c-d2d7-41cd-83be-1dd92cc38ec4 | 6 | private boolean formatFilePaths(){
//If the inputFilePath is empty turn result false
boolean result = true;
if(inputFilePath.equals("")){
result = false;
} else {
String findExtension = "(.*)\\.txt$";
//String findSRC ="src\\/";
//String findFile = "(src\\/)?(.*)\\.txt$";
Pattern inputFilePattern = Pattern.compile(findExtension);
Matcher inputFileMatcher = inputFilePattern.matcher(inputFilePath);
Matcher outputRuleFileMatcher = inputFilePattern.matcher(outputRuleFilePath);
Matcher outputErrorFileMatcher = inputFilePattern.matcher(outputErrorFilePath);
if(inputFileMatcher.find()){
//System.out.println("GROUPED INPUT FILE NAME: " + inputFileMatcher.group(0));
inputFilePath = inputFileMatcher.group(0);
}else{
System.out.println("No input extension is found");
inputFilePath += ".txt";
}
if(outputRuleFileMatcher.find()){
//System.out.println("GROUPED OUTPUT RULE FILE NAME: " + outputRuleFileMatcher.group(0));
this.outputRuleFilePath = outputRuleFileMatcher.group(0);
}else if(outputRuleFilePath.equals("")){
//System.out.println("In this block");
this.outputRuleFilePath = "rules_of_" + this.inputFilePath;
}else{
System.out.println("No output rule extension is found");
this.outputRuleFilePath += ".txt";
}
if(outputErrorFileMatcher.find()){
//System.out.println("GROUPED OUTPUT ERROR FILE NAME: " + outputErrorFileMatcher.group(0));
this.outputErrorFilePath = outputErrorFileMatcher.group(0);
}else if(outputErrorFilePath.equals("")){
System.out.println("In this block");
this.outputErrorFilePath = "errors_of_" + this.inputFilePath;
}else{
System.out.println("No output error extension is found");
this.outputErrorFilePath += ".txt";
}
}
return result;
} |
f92074c5-fe5c-4027-81b6-e7409bf344d1 | 0 | @Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
setEnabled(false);
addActionListener(this);
Outliner.documents.addDocumentRepositoryListener(this);
} |
1ba82731-b12d-49ea-96f5-8171633fac38 | 5 | public boolean add(String key, int ttlSec, Object value, long timeoutMiliSec)
throws TimeoutException {
try {
StringBuilder sb = new StringBuilder();
byte valueBytes[] = null;
int flag = -1;
if (value instanceof String) {
String arg = (String) value;
valueBytes = arg.getBytes(charset);
flag = FLAGS_GENRIC_STRING;
} else {
valueBytes = getObjectBytes(value);
flag = FLAGS_GENRIC_OBJECT;
}
validateKey(key);
validateValue(key, valueBytes);
//<command name> <key> <flags> <exptime> <bytes> [noreply]\r\n
sb.append("add ").append(key).append(" ").append(flag);
sb.append(" ").append(ttlSec).append(" ").append(valueBytes.length);
sb.append("\r\n");
sb.append(new String(valueBytes, charset));
sb.append("\r\n");
String res = sendDataOut(key, sb.toString());
if (res == null) {
throw new TimeoutException("we got a null reply!");
}
if (res.equals("STORED") == false) {
return false;
} else {
return true;
}
} catch (TimeoutException ex) {
throw ex;
} catch (Exception ex) {
throw new TimeoutException("We had error " + ex);
}
} |
0942a26c-db40-4ad1-bcb2-031729dd57e0 | 0 | public JFrame getFrame() {
return frame;
} |
d702a0c3-927f-479e-a345-3c456a05e9ed | 6 | private static void loadLibraries() throws Exception {
/* load all software libraries */
int lwjgl = 0;
for(File file : new File("libs").listFiles()) {
String name = file.getName();
if(!name.endsWith(".jar")) {
continue;
}
if(name.contains("lwjgl")) {
++lwjgl;
}
addSoftwareLibrary(file);
}
if(lwjgl != 2 || !new File(NATIVE_DIR).exists()) {
int opt = JOptionPane.showConfirmDialog(null, "The LWJGL Library was incomplete or not found,\n" + ARTIFACT_NAME +
" requires this library to display the game.\n"
+ "Do you want to automatically download it?", "Library Not Found", JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
if(opt == JOptionPane.YES_OPTION) {
downloadLWJGL();
loadLibraries();
} else {
System.exit(0);
}
}
} |
66259a7d-ff16-4d89-a926-21e79d3be9ef | 6 | public static double estimateGoalCost(Proposition goal) {
{ Keyword testValue000 = goal.kind;
if ((testValue000 == Logic.KWD_ISA) ||
((testValue000 == Logic.KWD_FUNCTION) ||
(testValue000 == Logic.KWD_PREDICATE))) {
{ NamedDescription description = Logic.getDescription(((Surrogate)(goal.operator)));
if ((description == null) ||
(!Description.inferableP(description))) {
return (1.0);
}
else {
return (Logic.INFERABLE_PENALTY_COST);
}
}
}
else if (testValue000 == Logic.KWD_IMPLIES) {
return (Logic.SUBSET_OF_PENALTY_COST);
}
else {
return (1.0);
}
}
} |
b44a280b-b29c-4446-8bc3-8d5912d5a111 | 1 | public ChatPanel(User user){
Dimension channelListSize = new Dimension(190, 450);
this.dbCon = DatabaseConnection.getInstance();
this.user = user;
this.updater = new ChannelListUpdater();
this.imgLdr = new GUIImageLoader();
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel jpnlUpperPanel = new JPanel();
jpnlUpperPanel.setLayout(new BoxLayout(jpnlUpperPanel, BoxLayout.X_AXIS));
jtxtChannelName = new JTextField(20);
jtxtChannelName.setDocument(new LengthRestrictedDocument(20));
jtxtChannelName.setPreferredSize(new Dimension(100, 25));
jtxtChannelName.setMaximumSize(jtxtChannelName.getPreferredSize());
jtxtChannelName.addFocusListener(new FLChatChannel());
jtxtChannelName.setText("Deu-1");
jpnlUpperPanel.add(jtxtChannelName);
jbttnJoin = new JGCButton("Join");
jbttnJoin.setPreferredSize(new Dimension(50, 25));
jbttnJoin.addActionListener(new ALJoinChannel());
jpnlUpperPanel.add(jbttnJoin);
jbttnRefresh = new JButton();
bffredImgRefreshButtonInactive = imgLdr.loadBufferedImage(GUIImageLoader.REFRESH_BUTTON_INAKTIVE);
refreshButtonLabeled = (bffredImgRefreshButtonInactive == null);
if(refreshButtonLabeled){
jbttnRefresh.setText("Refresh");
jbttnRefresh.setPreferredSize(new Dimension(20, 25));
}else{
jbttnRefresh.setIcon(new ImageIcon(bffredImgRefreshButtonInactive));
jbttnRefresh.setPreferredSize(new Dimension(20, 25));
ImgRefreshButtonActive = imgLdr.loadImage(GUIImageLoader.REFRESH_BUTTON_AKTIVE);
}
jbttnRefresh.addMouseListener(new MLAutoRefresh());
jpnlUpperPanel.add(jbttnRefresh);
this.refreshing = false;
this.add(jpnlUpperPanel);
add(Box.createVerticalStrut(10));
jlstChannels = new JList<>();
jlstChannels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jlstChannels.addMouseListener(new MAChannelList());
loadChannel();
JScrollPane jscrllChannels = new JScrollPane(jlstChannels,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jscrllChannels.setPreferredSize(channelListSize);
this.add(jscrllChannels);
updater.start();
updater.setRunning(refreshing);
} |
02f258d3-b34c-45a4-93b5-488997aee52c | 4 | public static void SenderOTs(Circuit c, Formatter f, OT ot,
ObjectOutputStream oos, ObjectInputStream ois)
{
Vector<OTTASK> OTs = new Vector<OTTASK>(10, 10);
IO io = null;
// Construct vector of all OTs to be executed
for (int i = 0; i < f.FMT.size(); i++) {
io = f.FMT.elementAt(i);
// Only chooser's (= Alice) inputs are interesting here
if ((!io.isInput()) || (!io.isAlice())) {
continue;
}
// Gather all required OTs in a vector of OTTASKs
for (int j = 0; j < io.getNLines(); j++) {
// Get all the params required for making an OTTASK
int line_num = io.getLinenum(j);
Gate g = c.getGate(line_num);
// Make an OTTASK and add it to the vector
// (All our OTs are 1-out-of-2)
OTTASK ottask = new OTTASK(line_num, 2);
ottask.addElement(g.getPackedCode(0));
ottask.addElement(g.getPackedCode(1));
OTs.add(ottask);
}
}
// Execute all the required OTs
ot.executeSenderOTs(OTs, oos, ois);
} |
45ec43e8-5a58-4932-951a-d98b3ee2ed05 | 9 | public void onEnable() {
PluginDescriptionFile pdf = getDescription();
// Load configuration
FileConfiguration config = this.getConfig();
boolean configChanged = false;
if (config.get("build.message") == null) {
config.set("build.message", config.getString("message", "You don't have permission to build!"));
config.set("message", null);
configChanged = true;
}
if (config.get("build.messageCooldown") == null) {
config.set("build.messageCooldown", 3);
configChanged = true;
}
if (config.get("interaction.check") == null) {
config.set("interaction.check", config.getBoolean("interactCheck", false));
config.set("interactCheck", null);
configChanged = true;
}
if (config.get("interaction.message") == null) {
config.set("interaction.message", config.getString("interactMessage", "You don't have permission to interact with the world!"));
config.set("interactMessage", null);
configChanged = true;
}
if (config.get("interaction.messageCooldown") == null) {
config.set("interaction.messageCooldown", 3);
configChanged = true;
}
if (configChanged)
this.saveConfig();
// Register listeners
PluginManager pluginManager = getServer().getPluginManager();
String message = getConfigString("build.message");
MessageSender messageSender = (message == null) ? null : new MessageSender(message, config.getInt("build.messageCooldown", 3));
final BListener bl = new BListener(this, messageSender);
pluginManager.registerEvents(bl, this);
final EListener el = new EListener(this, messageSender);
pluginManager.registerEvents(el, this);
if (config.getBoolean("interaction.check", false)) {
message = getConfigString("interaction.message");
messageSender = (message == null) ? null : new MessageSender(message, config.getInt("interaction.messageCooldown", 3));
final PListener pl = new PListener(this, messageSender);
pluginManager.registerEvents(pl, this);
log.info("[" + pdf.getName() + "] registered interaction listener");
}
log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled.");
} |
5b7d66f6-1ba3-4041-b526-f0721b6c08f3 | 7 | @Override
protected boolean isDirty()
{
boolean dirty = super.isDirty();
if (dirty)
{
return true;
}
else if (isCheckingDirtyChildPainters())
{
for (Painter<T> p : painters)
{
if (p instanceof AbstractPainter)
{
AbstractPainter<?> ap = (AbstractPainter<?>) p;
if (ap.isDirty())
{
return true;
}
}
}
}
return false;
} |
4681a93f-c828-4a81-8049-4ba39db71460 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (available != other.available)
return false;
if (readingCounter != other.readingCounter)
return false;
if (restriction != other.restriction)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
} |
04660c47-7c07-4b6d-9e33-c13e349973cb | 5 | private List<PTM> remapParentPtms(PTM currentPTM) {
List<PTM> resultPTMs = new ArrayList<PTM>();
for(Comparable parent: ((PSIModPTM)currentPTM).getParentPTMList()){
PSIModPTM psiModPTM = (PSIModPTM) psiModController.getPTMbyAccession((String) parent);
if(psiModPTM.getUnimodId() != null && !psiModPTM.getUnimodId().isEmpty()){
resultPTMs.addAll(remapToUniMod(psiModPTM));
}else if(psiModPTM.getParentPTMList() != null && !psiModPTM.getParentPTMList().isEmpty()){
resultPTMs.addAll(remapParentPtms(psiModPTM));
}
}
return resultPTMs;
} |
42df9474-384d-4d6c-be6c-dbc3884c64e0 | 3 | @Override
public void run() {
while (!isExit)
{
lock.lock();
for(Map.Entry<Integer, PlayerConnection> entry : clients.entrySet())
{
PlayerConnection connection = entry.getValue();
connection.listenSocket();
}
try
{
await.awaitNanos(20);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
lock.unlock();
} |
9e317096-1ab1-4c49-b927-659562505c5f | 3 | private void findOpeningBracket(String str, boolean sign) throws ParseException
{
Matcher matcher = Pattern.compile(sign ? "\\s*([+-]?)\\(" : "\\s*\\(").matcher(str);
if (!matcher.lookingAt())
{
throw new ParseException("(", offset);
}
if (sign)
{
minus = (matcher.group(1).equals("-"));
}
offset += matcher.end();
length += matcher.end();
} |
718351f1-925c-4b89-a68a-6f1790885db5 | 8 | public Collision checkCollision(Game g)
{
int snakeX = g.getSnake().getX();
int snakeY = g.getSnake().getY();
GameBoard gb = g.getGameBoard();
String coordKey = g.getObjectRegister().createCoordinateKey(new Coordination(snakeX, snakeY));
// Kolize s herním objektem
if (g.getObjectRegister().getGameObjects().containsKey(coordKey)) {
return Collision.OBJECT;
}
// kolize hada s tělem
for (BodyPart b : g.getSnake().getBody()) {
if (snakeX == b.getX() &&
snakeY == b.getY()) {
return Collision.BODY;
}
}
// Kolize hada se stěnou herního pole
if (snakeX >= gb.getBoardWidth()||
snakeY >= gb.getBoardHeight() ||
snakeX <= -(gb.getBoardStatsHeight() / 2) ||
snakeY < gb.getBoardStatsHeight()) {
//System.out.println("Snake " + snakeX + " | " + snakeY);
return Collision.BORDER;
}
return Collision.NO_COLLISION;
} |
87eb1394-2d51-41f3-be35-4d287ef9289e | 3 | public Configuration loadEmbeddedConfig(final String resource) {
final YamlConfiguration config = new YamlConfiguration();
final InputStream defaults = this.getResource(resource);
if (defaults == null) return config;
final InputStreamReader reader = new InputStreamReader(defaults, CustomPlugin.CONFIGURATION_SOURCE);
final StringBuilder builder = new StringBuilder();
final BufferedReader input = new BufferedReader(reader);
try {
try {
String line;
while ((line = input.readLine()) != null)
builder.append(line).append(CustomPlugin.LINE_SEPARATOR);
} finally {
input.close();
}
config.loadFromString(builder.toString());
} catch (final Exception e) {
throw new RuntimeException("Unable to load embedded configuration: " + resource, e);
}
return config;
} |
c944d5e2-61b4-49f4-a531-60d8c2d9b86a | 4 | @Override
public String toString()
{
String result = "[";
Queue<MapNode> q = new Queue<>();
if (!isEmpty()) q.enqueue((MapNode)root);
while (!q.isEmpty())
{
MapNode n = q.dequeue();
if (n.left != null) q.enqueue((MapNode)n.left);
if (n.right != null) q.enqueue((MapNode)n.right);
result += n.key + "=" + n.value + ", ";
}
return result + "]";
} |
e54742b9-a18e-48e2-9453-dacd7c45bd24 | 7 | private void onStartFlush(Address flushStarter, Message msg, FlushHeader fh) {
if (stats) {
startFlushTime = System.currentTimeMillis();
numberOfFlushes += 1;
}
boolean proceed = false;
boolean amIFlushInitiator = false;
Tuple<Collection<? extends Address>,Digest> tuple=readParticipantsAndDigest(msg.getRawBuffer(),
msg.getOffset(),msg.getLength());
synchronized (sharedLock) {
amIFlushInitiator = flushStarter.equals(localAddress);
if(!amIFlushInitiator){
flushCoordinator = flushStarter;
flushMembers.clear();
if (tuple.getVal1() != null) {
flushMembers.addAll(tuple.getVal1());
}
flushMembers.removeAll(suspected);
}
proceed = flushMembers.contains(localAddress);
}
if (proceed) {
if (sentBlock.compareAndSet(false, true)) {
// ensures that we do not repeat block event
// and that we do not send block event to non participants
sendBlockUpToChannel();
blockMutex.lock();
try {
isBlockingFlushDown = true;
} finally {
blockMutex.unlock();
}
} else {
if (log.isDebugEnabled())
log.debug(localAddress + ": received START_FLUSH, but not sending BLOCK up");
}
Digest digest = (Digest) down_prot.down(Event.GET_DIGEST_EVT);
Message start_msg = new Message(flushStarter)
.putHeader(this.id, new FlushHeader(FlushHeader.FLUSH_COMPLETED, fh.viewID))
.setBuffer(marshal(tuple.getVal1(),digest));
down_prot.down(start_msg);
log.debug(localAddress + ": received START_FLUSH, responded with FLUSH_COMPLETED to " + flushStarter);
}
} |
dcd43309-02e8-4a59-88f3-17549796bf88 | 5 | @Override
public boolean processBuffer()
{
// Stream buffers can only be queued for streaming sources:
if( errorCheck( channelType != SoundSystemConfig.TYPE_STREAMING,
"Buffers are only processed for streaming sources." ) )
return false;
// Make sure we have a SourceDataLine:
if( errorCheck( sourceDataLine == null,
"SourceDataLine null in method 'processBuffer'." ) )
return false;
if( streamBuffers == null || streamBuffers.isEmpty() )
return false;
// Dequeue a buffer and feed it to the SourceDataLine:
SoundBuffer nextBuffer = streamBuffers.remove( 0 );
sourceDataLine.write( nextBuffer.audioData, 0,
nextBuffer.audioData.length );
if( !sourceDataLine.isActive() )
sourceDataLine.start();
nextBuffer.cleanup();
nextBuffer = null;
return true;
} |
2124bbbe-2a57-4419-9fa1-3847fbe3a144 | 9 | @Override
public void run() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
System.out.println("Cant load JDBC driver.");
}
DataInputStream in;
DataOutputStream out;
String message;
Connection link = Server.connectToDatabase();
try {
in = new DataInputStream(this.sock.getInputStream());
out = new DataOutputStream(sock.getOutputStream());
String userName;
String userPassword;
userName = in.readUTF();
userPassword = in.readUTF();
boolean isValidated = Server.validateUser(link, userName, userPassword);
if (!isValidated) {
Server.removeClient(sock);
} else {
out.writeUTF("Login successful.");
TwitterRefresher refresher = new TwitterRefresher(this.sock, userName);
refresher.start();
while (true) {
String task = in.readUTF();
switch (task) {
case "message" :
String userMessage = Server.getText(sock);
Server.saveMessageToDatabase(userName, userMessage);
break;
case "subscribe" :
String ownerOfNewChannel = Server.getText(sock);
Server.subscribeUserToAnotherChannel(userName, ownerOfNewChannel);
break;
case "quit" :
Server.removeClient(sock);
break;
}
}
}
} catch (IOException ioe) {
System.out.println("Problem occurred on data tranfer for user :" + this.sock.toString());
} finally {
try {
Server.removeClient(this.sock);
if (link != null) {
link.close();
}
} catch (SQLException sqle) {
System.out.println("Error closing link to database.");
}
}
} |
d7892856-d055-440b-9ab4-de32bb3c63ff | 2 | public boolean isChanged()
{
if (name != nameSave || sizeInformation() != sizeSave) {
nameSave = name;
sizeSave = sizeInformation();
return true;
}
return false;
} |
a673ef4a-261d-423e-9dea-9d4345691bef | 3 | public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
} |
31528d76-064a-40fd-a051-344921f41bd5 | 3 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
out = new StringBuilder();
ring = new int[16];
int times = 1;
while ((line = in.readLine()) != null && line.length() != 0) {
if (times != 1)
out.append("\n");
out.append("Case " + times++ + ":\n");
sizeRing = Integer.parseInt(line.trim());
ring[0] = 1;
back(1, 2, " 1");
}
System.out.print(out);
} |
5a321c4c-23db-4104-b811-a994cf04f1f3 | 1 | public void closeSession(){
try{
bf.close();
pf.close();
s.close();
}catch(IOException io){
System.out.println("echec de fermeture");
io.printStackTrace();
}
} |
1e0af998-73d5-4102-853e-9d3471b48ab5 | 7 | public void doInsert_jdbc6(ParamHolder myParamHolder) {
try {
PreparedStatement pstmt = myParamHolder.conn.prepareStatement("insert into "+myParamHolder.table.toUpperCase()+"( file_name, "+myParamHolder.clobFieldName.toUpperCase()+", file_tag) values ( ? ,? , ?)");
pstmt.setString(1, myParamHolder.file.getName());
pstmt.setString(3, myParamHolder.keyFieldValue);
Blob myblob = myParamHolder.conn.createBlob();
int bufSize = 4 * 1024;//myblob.getBufferSize();
OutputStream blobOutputStream = null;
InputStream buffIn = null;
FileInputStream inputFileInputStream = null;
try {
blobOutputStream = myblob.setBinaryStream(1);
inputFileInputStream = new FileInputStream(myParamHolder.file);
buffIn = new BufferedInputStream( inputFileInputStream, bufSize);
byte[] buffer = new byte[bufSize];
long filebytesize = 0;
filebytesize = myParamHolder.file.length();
System.out.println(" the filebytesize ="+ filebytesize);
int length = -1;
//int cnt = 0;
long bytedone = 0;
int pecentdone;
while ((length = buffIn.read(buffer)) != -1) {
blobOutputStream.write(buffer, 0, length);
//cnt=cnt+1;
bytedone = bytedone+length;
pecentdone = (int)(((double)bytedone / (double) filebytesize) * 100d);
printProgBar.printProgBar(pecentdone);
}
blobOutputStream.flush();
} finally {
if (buffIn != null) {
try {
buffIn.close();
} catch (Exception e) { }
}
if (blobOutputStream != null) {
try {
blobOutputStream.close();
} catch (Exception e) { }
}
}
pstmt.setBlob(2, myblob);
pstmt.executeUpdate();
System.out.println("insert into file_load of file_name="
+ myParamHolder.file.getName() + ", is ok");
inputFileInputStream.close();
blobOutputStream.close();
myParamHolder.conn.commit();
buffIn.close();
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} |
eae25065-fe9d-4a6d-9489-36d3efc61d90 | 0 | public VueVisiteur(CtrlAbstrait ctrl) {
super(ctrl);
initComponents();
modeleJComboBoxVisiteur = new DefaultComboBoxModel();
modeleJComboBoxLabo = new DefaultComboBoxModel();
modeleJComboBoxSecteur = new DefaultComboBoxModel();
jComboBoxVisiteur.setModel(modeleJComboBoxVisiteur);
jComboBoxLabo.setModel(modeleJComboBoxLabo);
jComboBoxSecteur.setModel(modeleJComboBoxSecteur);
} |
ccbcdc8a-72ee-4aad-8e7d-87aef06ef874 | 2 | public java.io.Serializable fromDOM(Document document) {
Map e2t = elementsToText(document.getDocumentElement());
String expression = (String) e2t.get(EXPRESSION_NAME);
if (expression == null)
if (e2t.containsKey(EXPRESSION_NAME))
throw new ParseException("Regular expression structure has no "
+ EXPRESSION_NAME + " tag!");
else
expression = "";
return new RegularExpression(expression);
} |
c0fa935d-5793-4fd3-b3f3-6fc595390fae | 4 | public static void changeMemberSurname(String surname, int memberID){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
PreparedStatement stmnt = conn.prepareStatement("UPDATE Members set first_name = ? WHERE member_id = ?");
stmnt.setString(1, surname);
stmnt.setInt(2, memberID);
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("update fail!! - " + e);
}
} |
dfed69f3-f74b-4be3-a3b0-d90a7f2cac3b | 8 | public List<PersonasDTO> getDataPersonas() throws Exception {
try {
List<Personas> personas = XMLHibernateDaoFactory.getInstance()
.getPersonasDAO()
.findAll();
List<PersonasDTO> personasDTO = new ArrayList<PersonasDTO>();
for (Personas personasTmp : personas) {
PersonasDTO personasDTO2 = new PersonasDTO();
personasDTO2.setIdPersona(personasTmp.getIdPersona());
personasDTO2.setFechaNacimiento(personasTmp.getFechaNacimiento());
personasDTO2.setGenero((personasTmp.getGenero() != null)
? personasTmp.getGenero() : null);
personasDTO2.setPrimerApellido((personasTmp.getPrimerApellido() != null)
? personasTmp.getPrimerApellido() : null);
personasDTO2.setPrimerNombre((personasTmp.getPrimerNombre() != null)
? personasTmp.getPrimerNombre() : null);
personasDTO2.setProfesion((personasTmp.getProfesion() != null)
? personasTmp.getProfesion() : null);
personasDTO2.setSegundoApellido((personasTmp.getSegundoApellido() != null)
? personasTmp.getSegundoApellido() : null);
personasDTO2.setSegundoNombre((personasTmp.getSegundoNombre() != null)
? personasTmp.getSegundoNombre() : null);
personasDTO.add(personasDTO2);
}
return personasDTO;
} catch (Exception e) {
throw e;
}
} |
974e7d55-4dfd-45a9-ad39-b5f5f614c0a5 | 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(SpravaFiltrovForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SpravaFiltrovForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SpravaFiltrovForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SpravaFiltrovForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
SpravaFiltrovForm dialog = new SpravaFiltrovForm(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
40045fda-05de-4821-894e-3e9501ad389f | 2 | private void alustaTaso(int i) {
/**
* Tason lukeminen ja parsiminen tiedostosta, ja sen asettaminen
* pelaajalle
*/
try {
Tiedostonlukija lukija = new Tiedostonlukija("src/tasot/" + i + ".txt");
TasonLuonti luonti = new TasonLuonti(lukija.getRivit());
this.pelaaja.setTaso(luonti.getTaso());
} catch (Exception ex) {
/**
* Jos tasot loppuvat, gg.txt :D
*/
try {
Tiedostonlukija lukija = new Tiedostonlukija("src/tasot/gg.txt");
TasonLuonti luonti = new TasonLuonti(lukija.getRivit());
this.pelaaja.setTaso(luonti.getTaso());
} catch (Exception ex1) {
/**
* Jos gg.txt loppuu, exception :(
*/
Logger.getLogger(Juoksu.class.getName()).log(Level.SEVERE,
null, ex1);
}
}
/**
* Sijoitetaan kamera sweet spottiin
*/
this.kamera.setXY(new Piste(pelaaja.getTaso().getPelaajanAlkusijainti().getX() - 405,
pelaaja.getTaso().getPelaajanAlkusijainti().getY() - 1000));
/**
* Määritetään uusi taso + siihen liittyvät systeemit ikkunan uudeksi
* sisällöksi
*/
this.ikkuna.setPiirtoalusta(new Piirtoalusta(pelaaja, kamera));
} |
4bc81539-45e7-45fb-a059-852c71015ded | 2 | public void makeMove(Location loc)
{
if (loc.equals(getLocation()))
{
double r = Math.random();
int angle;
if (r < 0.5)
angle = Location.LEFT;
else
angle = Location.RIGHT;
setDirection(getDirection() + angle);
}
else
super.makeMove(loc);
} |
d5d19027-ac68-4eaa-8460-85e26d021db3 | 5 | public static void main(String[] args) throws InterruptedException {
final BlockingQueue<Integer> blockingQueue = new BlockingQueue<>(10);
final Random random = new Random();
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
while (true) {
blockingQueue.put(random.nextInt(10));
}
} catch (InterruptedException ignored) {}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);//wait for putting to the queue first
} catch (InterruptedException ex) {
System.out.println("Exception " + ex.getMessage());
}
try {
while (true) {
blockingQueue.take();
}
} catch (InterruptedException ignored) {}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
} |
66495c02-cfa3-4309-82c1-d1895ae4e906 | 2 | public static void unsetFlag(BoardModel boardModel, Point point) {
Cell currentCell = boardModel.getBoard()[point.getPosX()][point.getPosY()];
if (boardModel.getNumberOfFlags() < boardModel.getNumberOfMines() && currentCell.isFlagged()) {
currentCell.setFlagged(false);
boardModel.setNumberOfFlags(boardModel.getNumberOfFlags() + 1);
}
} |
4ee8c0c9-3503-451b-9286-65d4e2dc9e2a | 8 | public List<Word> sentenceProcess(String sentence) {
List<Word> tokens = new ArrayList<Word>();
int N = sentence.length();
Map<Integer, List<Integer>> dag = createDAG(sentence);
Map<Integer, Pair<Integer>> route = calc(sentence, dag);
int x = 0;
int y = 0;
String buf = "";
while (x < N) {
y = route.get(x).key + 1;
String lWord = sentence.substring(x, y);
if (y - x == 1)
buf += lWord;
else {
if (buf.length() > 0) {
if (buf.length() == 1) {
tokens.add(Word.createWord(buf));
buf = "";
} else {
if (wordDict.containsWord(buf)) {
tokens.add(wordDict.getWord(buf));
} else {
finalSeg.cut(buf, tokens);
}
buf = "";
}
}
tokens.add(Word.createWord(lWord));
}
x = y;
}
if (buf.length() > 0) {
if (buf.length() == 1) {
tokens.add(Word.createWord(buf));
buf = "";
} else {
if (wordDict.containsWord(buf)) {
tokens.add(wordDict.getWord(buf));
} else {
finalSeg.cut(buf, tokens);
}
buf = "";
}
}
return tokens;
} |
0c557c00-67ec-4ee9-81f2-a23de96e6d8a | 8 | protected void insertRecords(PreparedStatement stmt, Importer importer) throws IOException, SQLException {
int recordCount = 0;
int insertedCount = 0;
int errorCount = 0;
while (true) {
Object[] row = importer.nextRow();
if (row == null || row.length == 0) {
break;
}
++recordCount;
try {
for (int i = 0; i < row.length; i++) {
int index = i + 1;
Object o = row[i];
stmt.setObject(index, o);
}
insertedCount += stmt.executeUpdate();
} catch (SQLException ex) {
String message = "error occurred at " + recordCount;
if (log.isTraceEnabled()) {
log.trace(message, ex);
} else if (log.isDebugEnabled()) {
log.debug(message + " : " + ex);
}
++errorCount;
}
}
if (log.isDebugEnabled()) {
log.debug("record = " + recordCount);
log.debug("inserted = " + insertedCount);
log.debug("error = " + errorCount);
}
outputMessage("i.loaded", insertedCount, recordCount);
} |
dc37cc1e-368a-4f21-9181-090ef42bf902 | 3 | @Override
public void keyReleased(int key, char c) {
if(key == 57) { //space
checkDialogs();
}
if(!inputEnabled)
return;
ArrayList<GameKeyListener> keyListenersCopy = new ArrayList<GameKeyListener>(keyListeners); //Create a copy because scripts can register keyrelease components.
System.out.println("Released key: " + key);
Iterator<GameKeyListener> it = keyListenersCopy.iterator();
while(it.hasNext()) {
GameKeyListener next = it.next();
next.KeyUp(key, c);
}
} |
0db922ef-2846-4560-a634-c39e35c4be9e | 4 | public static void main(String[] args) {
String[] sortedData;
SortOperations so = new SortOperations();
MyFileReader rf = new MyFileReader();
String fileContent;
if (args.length == 2 && 0 == args[0].compareTo("-r")) {
fileContent = rf.readFile(args[1]);
String[] reverse = so.reverseData(fileContent);
for (String s : reverse)
System.out.println(s);
} else {
fileContent = rf.readFile(args[0]);
sortedData = so.sortData(fileContent);
for (String s : sortedData)
System.out.println(s);
}
} |
b8d961ef-2d84-4aa6-92f7-dc72b08cbb18 | 0 | @Override
public void init(GameContainer container) throws SlickException {
board = new GameBoard();
selected = new int[2];
select = false;
wturn = true;
black = new chess_game.NPC(false);
//Create the players
players = new ChessPlayer[2];
players[0] = new HumanPlayer(true);
players[1] = new HumanPlayer(false);
} |
46b3a618-4e42-4292-80db-67d4761a4118 | 0 | @Override
public void extract() {
Thread extract = new ExtractThread();
extract.start();
} |
5286539b-a48e-4e50-a92a-d72a39668bce | 7 | public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
resetPath();
repaint();
return;
}
for (int i = e.getX() - pRadius; i<e.getX()+pRadius; i++) {
for (int j = e.getY() -pRadius; j<e.getY()+pRadius; j++) {
Node temp = myGraph.nodeAt(i, j);
if (temp != null) {
if (fromNode == null) {
fromNode = temp;
}
else if (toNode == null) {
toNode= temp;
if (myGraph.getEdges().length > 0) { // There is an MST
graphPanel.path = myGraph.nodeConnectionHelper(null, fromNode, toNode);
graphPanel.repaint();
graphPanel.pathInfo(); // NOTE: Turn on path info here!
}
}
else { // start new pair
fromNode = temp;
toNode = null;
graphPanel.path = null;
}
repaint();
return;
}
}
}
} |
936666d1-d928-425b-9077-f9f96f7fed7c | 1 | public void updateGemsInBag(String newTheme)
{
for(int loop = 0; loop<Bag.size(); loop++)
{
Gem temp = (Gem) Bag.get(loop);
temp.setNewImage(newTheme+"Gem.png");
}
} |
cfa77026-befe-4871-8dd4-7c10c432772a | 4 | public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int score = Integer.parseInt(in.next());
if (score > 85) {
System.out.println("A");
} else if (score > 75) {
System.out.println("B");
} else if (score > 65) {
System.out.println("C");
} else if (score > 55) {
System.out.println("D");
} else {
System.out.println("F");
}
} |
a53fa5a4-8fe3-4d9c-abcc-8ea62f9cdec7 | 8 | public void writeTableToFile(GetLectureTweets lt, GetTagTweet tt, GetToTweet totw, String tag, String tagStartDate, String tagStartTime, String tagEndDate, String tagEndTime, String svTwUni, String lectureStartDate, String lectureStartTime, String lectureEndDate, String lectureEndTime, String lectureName){
//lTweets = lt.getTweetArray("dmutv", "2011-11-01", "22:59:00", "2011-11-01", "23:01:00");
//tTweets = tt.getTweetArray("tsttwsv", "2011-11-01", "22:59:00", "2011-11-01", "23:01:00");
//FetchLectureProssesLabel.setText("Working...");
lTweets = lt.getTweetArray(svTwUni,lectureStartDate,lectureStartTime,lectureEndDate,lectureEndTime);
//FetchLectureProssesLabel.setText("Done");
//FetchtagProsseslabel.setText("Working...");
tTweets = tt.getTweetArray(tag,tagStartDate,tagStartTime,tagEndDate,tagEndTime);
//FetchtagProsseslabel.setText("Done");
toTweets = totw.getTweetArray(svTwUni,tagStartDate,tagStartTime,tagEndDate,tagEndTime);
//FetchtagProsseslabel.setText("Done");
/*
* Ta alla tweets från tt och totw slå ihop till en lista (tabort ev dubletter) och använd den listan
*/
mergeToAndTag();
Tweet[] ltArray = new Tweet[lTweets.size()];
lTweets.toArray(ltArray);
//Tweet[] ttArray = new Tweet[tTweets.size()];
//tTweets.toArray(ttArray);
Tweet[] ttArray = new Tweet[mergeTweets.size()];
mergeTweets.toArray(ttArray);
//Progressbaeren
// writeProgressBar.setMaximum(ltArray.length-1);
// writeProgressBar.setIndeterminate(true);
//start the writing
try {
// Create file
FileWriter fstream = new FileWriter(tag+".txt");
BufferedWriter outFile = new BufferedWriter(fstream);
outFile.write("<table border=1>\n");
outFile.write("<tr><td><h3>Tweeter</h3><h4>"+ lectureName + "</h4></td><td><h3>Room</h3><h4>#"+ tag + "</h4></td></tr>\n");
for (int i=0; i < ltArray.length;i++){
outFile.write("<tr>\n");
//outFile.write("<td valign='top' width='55%'>" + "<span style=\"font-size:x-small;\">" + ltArray[i].getCreatedAt() + "</span><br />" + URLInString.makeURLInString(ltArray[i].getText()) + "</td><td bgcolor='#E0E0E0' valign='top'> <td>\n</tr>\n");
outFile.write("<td valign='top' width='55%'>" + URLInString.makeURLInString(ltArray[i].getText()) + "<br />" + tweetDate(ltArray[i]) + "</td><td bgcolor='#E0E0E0' valign='top'> <td>\n</tr>\n");
//F8F8F8
//outFile.write("<tr><td> </td><td bgcolor='#E0E0E0' valign='top'>");
if (i < ltArray.length -1){
for (int j =0; j < ttArray.length; j++){
if (ttArray[j].getCreatedAt().after(ltArray[i].getCreatedAt())
&& ttArray[j].getCreatedAt().before(ltArray[i+1].getCreatedAt())){
outFile.write("<tr><td> </td><td bgcolor='#E0E0E0' valign='top'>");
//outFile.write("<span style=\"font-size:x-small;\">" + ttArray[j].getCreatedAt() + "</span><br />" + "<a href='https://twitter.com/#!/"
outFile.write("<a href='https://twitter.com/#!/"
+ ttArray[j].getFromUser()
+ "' target='_blank'>@" +ttArray[j].getFromUser() + "</a>\n");
outFile.write(URLInString.makeURLInString(ttArray[j].getText()) + "<br />" + tweetDate(ttArray[j]) + "</td></tr>\n");
}
}
}
else {
for (int j =0; j < ttArray.length; j++){
if (ttArray[j].getCreatedAt().after(ltArray[i].getCreatedAt())){
outFile.write("<tr><td> </td><td bgcolor='#E0E0E0' valign='top'>");
//outFile.write("<span style=\"font-size:x-small;\">" + ttArray[j].getCreatedAt() + "</span><br />" + "<a href='https://twitter.com/#!/"
outFile.write("<a href='https://twitter.com/#!/"
+ ttArray[j].getFromUser()
+ "' target='_blank'>@" +ttArray[j].getFromUser() + "</a>\n");
outFile.write(URLInString.makeURLInString(ttArray[j].getText()) + "<br />" + tweetDate(ttArray[j]) + "</td></tr>\n");
}
}
}
//outFile.write("</td>");
//outFile.write("</tr>\n");
// writeProgressBar.setValue(i);
// writeProgressBar.repaint();
}
outFile.write("</table>\n");
//Close the output stream
outFile.close();
//System.out.println("Done");
//writeProgressBar.setIndeterminate(false);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
} |
a6df4e11-a799-4c9f-ac50-0afe28dce24f | 7 | public int calculoElevacao(JButton button, String grausDigitado) {
int graus = Integer.parseInt(grausDigitado);
try {
if ("Elevação".equals(button.getActionCommand())) {
System.out.println("**************ELEVAÇÃO*********************");
if (graus >= 0 && graus <= 85) {
if (ElGraus < graus) {
int c = graus - ElGraus;
System.out.println("Calculo elevação =" + graus + "-" + ElGraus + " = " + c);
up(c);
} else if (ElGraus > graus) {
int dif = ElGraus - graus;
System.out.println("Calculo elevação =" + ElGraus + "-" + graus + " = " + dif);
down(dif);
} else if (graus == 0) {
int dif = ElGraus - ElGraus;
System.out.println("Calculo =" + ElGraus + "-" + ElGraus + " = " + dif);
down(dif);
}
}
ElGraus = graus;
}
System.out.println("Elevação digitado graus =" + ElGraus);
} catch (Exception e) {
System.out.println("*****Erro ao calcular azimute 0º a 340º* e Elevação 0 a 60º*****");
}
return 1;
} |
19657e0a-77a0-416c-89e1-793a5644533d | 1 | @Override
public String toString() {
return String.format("%1$-15s %2$-5d %3$-7s %4$13d",
getAddress().getHostAddress(), getPort(),
isOnline() ? "online" : "offline", getUsage());
} |
76925c84-10e3-46ef-85cf-4f4c064a25ee | 7 | public static void parser(File fIn, Socket sckIn, EzimContact ecIn)
{
Hashtable<String, String> htHdr = null;
InputStream isData = null;
String strCType = null;
String strCLen = null;
long lCLen = 0;
try
{
isData = sckIn.getInputStream();
htHdr = EzimDtxSemantics.getHeader(fIn);
strCType = htHdr.get(EzimDtxSemantics.HDR_CTYPE);
strCLen = htHdr.get(EzimDtxSemantics.HDR_CLEN);
if (strCType == null)
{
throw new Exception
(
"Header field \"Content-Type\" is missing."
);
}
else if (strCLen == null)
{
throw new Exception
(
"Header field \"Content-Length\" is missing."
);
}
else
{
lCLen = Long.parseLong(strCLen);
// receive incoming message
if (strCType.equals(EzimDtxSemantics.CTYPE_MSG))
{
EzimDtxMessageSemantics.messageParser
(
isData
, ecIn
, htHdr
, lCLen
);
}
else
{
EzimDtxFileSemantics.fileParser
(
isData
, sckIn
, ecIn
, htHdr
, strCType
, lCLen
);
}
}
}
catch(EzimException ee)
{
EzimLogger.getInstance().warning(ee.getMessage(), ee);
}
catch(Exception e)
{
EzimLogger.getInstance().severe(e.getMessage(), e);
}
finally
{
try
{
if (isData != null) isData.close();
}
catch(Exception e)
{
EzimLogger.getInstance().severe(e.getMessage(), e);
}
}
} |
23f4a99a-3369-4d28-be08-f4bdeef20a2a | 9 | private void verifyBranches() throws AssemblyException {
int maxLabelLength = 0;
for (int i = 0; i < lines.size(); ++i) {
String label = lines.get(i).label;
if (label != null) {
if (label.length() > maxLabelLength)
maxLabelLength = label.length();
if (branches.containsKey(label))
throw new AssemblyException("Duplicate label " + label);
if (lines.get(i).opCode != OpCode.DC)
branches.put(label, i);
}
}
for (InterpretedLine l : lines)
if (OpCode.isBranch(l.opCode) && !branches.containsKey(l.loc))
throw new AssemblyException("Undefined branch " + l.loc);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxLabelLength + 3; ++i)
sb.append(' ');
spaces = sb.toString();
} |
de7339a8-b4f4-46f4-87d8-53bce62ed89a | 6 | private void kingBottomLeftPossibleMove(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if((x1 >= 1 && y1 >= 1) && (x1 < maxWidth && y1 < maxHeight))
{
if(board.getChessBoardSquare(x1-1, y1-1).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
if(board.getChessBoardSquare(x1-1, y1-1).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print(" " + coordinateToPosition(x1-1, y1-1)+"*");
Position newMove = new Position(x1-1, y1-1);
piece.setPossibleMoves(newMove);
}
}
else
{
// System.out.print(" " + coordinateToPosition(x1-1, y1-1));
Position newMove = new Position(x1-1, y1-1);
piece.setPossibleMoves(newMove);
}
}
} |
442456ed-a21e-4ebb-b990-b4475c80b527 | 3 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.hotels");
try {
Criteria criteria = new Criteria();
Hotel currHotel = (Hotel) request.getSessionAttribute(JSP_CURRENT_HOTEL);
if (currHotel == null) {
throw new TechnicalException("message.errorNullEntity");
}
criteria.addParam(DAO_ID_HOTEL, currHotel.getIdHotel());
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
AbstractLogic hotelLogic = LogicFactory.getInctance(LogicType.HOTELLOGIC);
hotelLogic.doRestoreEntity(criteria);
page = new GoShowHotel().execute(request);
} catch (TechnicalException ex) {
request.setAttribute("errorRestoreReason", ex.getMessage());
request.setAttribute("errorRestore", "message.errorRestoreData");
request.setSessionAttribute(JSP_PAGE, page);
}
return page;
} |
5555e4ea-4acc-4d2d-b819-de9a60728ae0 | 7 | private void setType(int type) {
if (type == 0){
units1 = new JComboBox<Object>(LengthUnits.values());
units2 = new JComboBox<Object>(LengthUnits.values());
} else if (type == 1){
units1 = new JComboBox<Object>(AreaUnits.values());
units2 = new JComboBox<Object>(AreaUnits.values());
} else if (type == 2){
units1 = new JComboBox<Object>(VolumeUnits.values());
units2 = new JComboBox<Object>(VolumeUnits.values());
} else if (type == 3){
units1 = new JComboBox<Object>(MassUnits.values());
units2 = new JComboBox<Object>(MassUnits.values());
} else if (type == 4){
units1 = new JComboBox<Object>(TimeUnits.values());
units2 = new JComboBox<Object>(TimeUnits.values());
} else if (type == 5){
units1 = new JComboBox<Object>(AngleUnits.values());
units2 = new JComboBox<Object>(AngleUnits.values());
} else if (type == 6){
units1 = new JComboBox<Object>(TemperatureUnits.values());
units2 = new JComboBox<Object>(TemperatureUnits.values());
}
this.type = type;
} |
ba5b56c6-371f-4c62-97c2-d92357aed689 | 6 | private Object getIndexOf(Object o, int index) {
if (index == -1) {
return o;
}
if (o instanceof List<?>) {
List<?> list = (List<?>) o;
if (index < list.size()) {
return list.get(index);
} else {
return 0;
}
} else {
return null;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.