text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void settip(String t) {
tooltip = t;
q2 = -1;
if (tooltip != null) {
try {
Matcher m = patt.matcher(tooltip);
while (m.find()) {
q2 = Integer.parseInt(m.group(1));
}
Matcher valm = pattVal.matcher(tooltip);
if (valm.find()) {
count_of_value = Double.parseDouble(valm.group(1));
count_of_maximum = Double.parseDouble(valm.group(2));
}
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
} | 4 |
public void testGetFieldType() {
YearMonthDay test = new YearMonthDay(COPTIC_PARIS);
assertSame(DateTimeFieldType.year(), test.getFieldType(0));
assertSame(DateTimeFieldType.monthOfYear(), test.getFieldType(1));
assertSame(DateTimeFieldType.dayOfMonth(), test.getFieldType(2));
try {
test.getFieldType(-1);
} catch (IndexOutOfBoundsException ex) {}
try {
test.getFieldType(3);
} catch (IndexOutOfBoundsException ex) {}
} | 2 |
public void run() {
while (true) {
if (myDestinations.size() > 0) {
// System.out.println("About to visit floor");
int dir = getMyDirection();
if (dir == DIRECTION_UP || dir == DIRECTION_NEUTRAL) {
VisitFloor(myDestinations.first());
}
if (dir == DIRECTION_DOWN) {
VisitFloor(myDestinations.last());
}
// System.out.println("Finished visiting floor");
}
if (CheckDoors(myFloor)) {
// System.out.println("About to open doors");
OpenDoors();
ClosedDoors();
}
if (myDestinations.size() == 0) myDirection = DIRECTION_NEUTRAL;
}
} | 7 |
@Override
public int awardPoints(boolean[] sv,int objectSize) {
if(objectSize>thresh){
for (boolean b : sv) {
if(b) return 0; //If any part is touching
}
return 1;
}
else{ //Tracker should catch it
int c = 0;
for (boolean b : sv) {
if(b) c++;
}
return c == objectSize ? 1 : 0;
}
} | 6 |
private boolean interact(int x0, int y0, int x1, int y1) {
List<Entity> entities = level.getEntities(x0, y0, x1, y1);
for (int i = 0; i < entities.size(); i++) {
Entity e = entities.get(i);
if (e != this) if (e.interact(this, activeItem, attackDir)) return true;
}
return false;
} | 3 |
private static void printRLE(ArrayList<int[]> runs) {
System.out.println(" Here is the correct encoding:");
for (int[] run : runs) {
System.out.println(run[0] + "x[red=" + run[1] + ",green=" + run[2]
+ ",blue=" + run[3] + "]");
}
} | 1 |
public Integer getPrice(Chest chest,MaterialData data){
if(chest==null || data==null)
return null;
Object price = stores.get(chest).getPrice(data);
if(price instanceof Integer)
return (Integer) price;
else
return 0;
} | 3 |
public void accept(final MethodVisitor mv) {
int[] keys = new int[this.keys.size()];
for (int i = 0; i < keys.length; ++i) {
keys[i] = ((Integer) this.keys.get(i)).intValue();
}
Label[] labels = new Label[this.labels.size()];
for (int i = 0; i < labels.length; ++i) {
labels[i] = ((LabelNode) this.labels.get(i)).getLabel();
}
mv.visitLookupSwitchInsn(dflt.getLabel(), keys, labels);
} | 2 |
private void endActionUpdate() {
numberOfActionsAlreadyPassed++;
if (numberOfActionsAlreadyPassed >= numberOfActionsToSwitchStatus) {
numberOfActionsAlreadyPassed = 0;
if (isActive())
deactivate();
else
activate();
}
} | 2 |
private void createFromParseList(ParseList list) throws CriticalFailure
{
list.insertBlockIDs(blockMap);
Hashtable<String,TreeNodeArea> areas = list.createAreaNodes();
Hashtable<String,Modifier> modifiers = list.createModifiers();
Hashtable<String,ModifierGroup> modifierGroups = list.createModifierGroups();
for (Enumeration<String> e = areas.keys(); e.hasMoreElements();)
{
String areaName = e.nextElement();
ArrayList<String> modNames = areas.get(areaName).getModifierGroupNames();
for (String name : modNames)
{
ModifierGroup mod = modifierGroups.get(name);
if (mod != null)
{
ExceptionLogger.log("Adding ModifierGroup \""+name+"\"", LoggerLevel.FINEST);
mod.addModifiers(modifiers);
areas.get(areaName).addModifierGroup(mod.clone());
}
else
{
ExceptionLogger.logException(new UnknownIdentifier(name), LoggerLevel.ERROR);
}
}
}
for (Enumeration<String> e = areas.keys(); e.hasMoreElements();)
{
String areaName = e.nextElement();
ExceptionLogger.log("Parsing Area \""+areaName+"\"", LoggerLevel.FINE);
ArrayList<String> subNames = areas.get(areaName).getSubAreaNames();
for (String name : subNames)
{
TreeNodeArea area = areas.get(name);
if (area != null)
{
ExceptionLogger.log("Adding SubArea \""+name+"\"", LoggerLevel.FINEST);
areas.get(areaName).addSubArea(area.clone());
}
else
{
ExceptionLogger.logException(new UnknownIdentifier(name), LoggerLevel.ERROR);
}
}
}
world = areas.get("World");
if (world == null)
{
ExceptionLogger.logException(new NoWorldException(), LoggerLevel.CRITICAL);
}
else
{
world.setAsRootNode();
}
} | 7 |
private Color parseRGBA(String str) {
int i0 = str.indexOf("[");
if (i0 == -1)
i0 = str.indexOf("(");
int i1 = str.indexOf("]");
if (i1 == -1)
i1 = str.indexOf(")");
str = str.substring(i0 + 1, i1);
String[] s = str.split(REGEX_SEPARATOR + "+");
if (s.length < 3) {
out(ScriptEvent.FAILED, "Cannot parse color from less than 3 parameters: " + str);
return null;
}
double x = parseMathExpression(s[0]);
if (Double.isNaN(x)) {
out(ScriptEvent.FAILED, "Cannot parse red color: " + s[0]);
return null;
}
int r = (int) Math.round(x);
x = parseMathExpression(s[1]);
if (Double.isNaN(x)) {
out(ScriptEvent.FAILED, "Cannot parse green color: " + s[1]);
return null;
}
int g = (int) Math.round(x);
x = parseMathExpression(s[2]);
if (Double.isNaN(x)) {
out(ScriptEvent.FAILED, "Cannot parse blue color: " + s[2]);
return null;
}
int b = (int) Math.round(x);
if (s.length < 4)
return new Color(r % 256, g % 256, b % 256);
x = parseMathExpression(s[3]);
if (Double.isNaN(x)) {
out(ScriptEvent.FAILED, "Cannot parse alpha value: " + s[3]);
return null;
}
int a = (int) Math.round(x);
return new Color(r % 256, g % 256, b % 256, a % 256);
} | 8 |
public void fire(ArrayList<Sprite> spriteList)
{
// Only fire if we're loaded.
if (_ammo != null)
{
Vector2d fireImpulse = new Vector2d(_impulseMagnitude, 0);
Vector2d initialTranslation = new Vector2d(_radius / 2, 0);
fireImpulse.setAngle(getAngle());
initialTranslation.setAngle(getAngle());
_ammo.setPosition(getPosition().plus(initialTranslation));
_ammo.applyImpulse(fireImpulse);
spriteList.add(_ammo);
// Now that we've sent it off, sever our reference.
_ammo = null;
}
} | 1 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node otherNode = (Node) obj;
if (edges.size() != otherNode.edges.size())
return false;
/*if (suffixLink == null) {
if (otherNode.suffixLink != null)
return false;
} else if (suffixLink.hashCode() != otherNode.suffixLink.hashCode())
return false;
*/
if (leafIndex != otherNode.leafIndex)
return false;
for (Map.Entry<Tuple, Node> edge : edges.entrySet()) {
if (otherNode.edges.containsKey(edge.getKey())) {
boolean result = edge.getValue().equals(otherNode.edges.get(edge.getKey()));
if (!result)
return false;
} else
return false;
}
return true;
} | 8 |
public static boolean equalsIgnoreCaseInString(String longer, int ai, String shorter, int bi) {
int chkLen = shorter.length() - bi;
if (longer.length() - ai < chkLen) return false;
for (int c = 0; c < chkLen; ai++, bi++, c++) {
char ac = longer.charAt(ai);
char bc = shorter.charAt(bi);
if (ac == bc
|| ac == Character.toUpperCase(bc)
|| ac == Character.toLowerCase(bc)) {
continue;
} else {
return false;
}
}
return true;
} | 5 |
@Override
public void tick() {
super.tick();
if (input.escape.clicked) System.exit(0);
if (input.enter.clicked) {
if (selected == 0) System.exit(0);
}
if (input.backspace.clicked) {
if (input.keyboardString.length() > 0) {
input.keyboardString = input.keyboardString.substring(0, input.keyboardString.length() - 1);
}
}
if (connected) game.setMenu(null);
} | 6 |
public Item SwapWeapon(Item willBeSwappedItem) {
return weaponSlot.swap(willBeSwappedItem);
//return false;// swap failed
} | 0 |
public OneFlower(GameMode mode)
{
this.mode = mode;
frame = new JFrame();
frame.setTitle("OneFlower - Playing - Score: 0");
frame.setLocationRelativeTo(null);
frame.setSize(390, 410);
frame.setResizable(false);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addKeyListener(this);
showInfo = new JLabel();
showInfo.setFont(Main.font);
showInfo.setBounds(0, frame.getHeight() - 50, frame.getWidth(), 25);
frame.add(showInfo);
character = new JLabel();
character.setIcon(ImageInitializer.imageCharacterDown);
character.setBounds(0, 0, 32, 32);
frame.add(character);
flower = new JLabel();
flower.setIcon(ImageInitializer.imageFlower);
flower.setBounds(0, 0, 32, 32);
frame.add(flower);
// Overdraw.. Oops. Totally not a bug.
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
JLabel l = new JLabel();
l.setBounds(i * 32, j * 32, 32, 32);
l.setIcon(ImageInitializer.imageBackground);
frame.add(l);
}
}
} | 2 |
public void setTotalNumberOfMatches(int totalNumberOfMatches) {this.totalNumberOfMatches = totalNumberOfMatches;} | 0 |
public static void testMethod(int led)
{
int number;
if(led>=0 && led <8)
{
number = led;
}
else
{
number = 7;
}
for (int j = 2; j >=0 ; j--)
{
for (int i = number; i >=0 ; i--)
{
switch(j)
{
case 2:leds[i].setColor(LEDColor.RED);break;
case 1:leds[i].setColor(LEDColor.WHITE);break;
case 0: leds[i].setColor(LEDColor.GREEN);break;
}
leds[i].setOn();
}
Utils.sleep(300);
for (int i = number; i >=0 ; i--)
{
leds[i].setOff();
}
Utils.sleep(100);
}
} | 8 |
public final void attrSplit(int attr, Instances inst) throws Exception {
int i;
int len;
int part;
int low = 0;
int high = inst.numInstances() - 1;
PairedStats full = new PairedStats(0.01);
PairedStats leftSubset = new PairedStats(0.01);
PairedStats rightSubset = new PairedStats(0.01);
int classIndex = inst.classIndex();
double leftCorr, rightCorr;
double leftVar, rightVar, allVar;
double order = 2.0;
initialize(low, high, attr);
if (m_number < 4) {
return;
}
len = ((high - low + 1) < 5) ? 1 : (high - low + 1) / 5;
m_position = low;
part = low + len - 1;
// prime the subsets
for (i = low; i < len; i++) {
full.add(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
leftSubset.add(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
}
for (i = len; i < inst.numInstances(); i++) {
full.add(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
rightSubset.add(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
}
full.calculateDerived();
allVar = (full.yStats.stdDev * full.yStats.stdDev);
allVar = Math.abs(allVar);
allVar = Math.pow(allVar, (1.0 / order));
for (i = low + len; i < high - len - 1; i++) {
rightSubset.subtract(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
leftSubset.add(inst.instance(i).value(attr),
inst.instance(i).value(classIndex));
if (!Utils.eq(inst.instance(i + 1).value(attr),
inst.instance(i).value(attr))) {
leftSubset.calculateDerived();
rightSubset.calculateDerived();
leftCorr = Math.abs(leftSubset.correlation);
rightCorr = Math.abs(rightSubset.correlation);
leftVar = (leftSubset.yStats.stdDev * leftSubset.yStats.stdDev);
leftVar = Math.abs(leftVar);
leftVar = Math.pow(leftVar, (1.0 / order));
rightVar = (rightSubset.yStats.stdDev * rightSubset.yStats.stdDev);
rightVar = Math.abs(rightVar);
rightVar = Math.pow(rightVar, (1.0 / order));
double score = allVar - ((leftSubset.count / full.count) * leftVar)
- ((rightSubset.count / full.count) * rightVar);
// score /= allVar;
leftCorr = (leftSubset.count / full.count) * leftCorr;
rightCorr = (rightSubset.count / full.count) * rightCorr;
double c_score = (leftCorr + rightCorr) - Math.abs(full.correlation);
// c_score += score;
if (!Utils.eq(score, 0.0)) {
if (score > m_maxImpurity) {
m_maxImpurity = score;
m_splitValue =
(inst.instance(i).value(attr) + inst.instance(i + 1)
.value(attr)) * 0.5;
m_position = i;
}
}
}
}
} | 8 |
public static ArrayList<Achievement> updateAchievement(User user) {
ArrayList<Achievement> records = AchievementRecord.getAchievementsByUserID(user.userID, QUIZ_TAKEN_TYPE);
ArrayList<Achievement> newAchievements = new ArrayList<Achievement>();
int totalTakenQuiz = QuizTakenRecord.getQuizHistoryByUserID(user.userID).size(); // TODO can be simplified using COUNT in database
for (int i = 0; i < getAllAchievements().size(); i++) {
Achievement achievement = getAllAchievements().get(i);
boolean found = false;
for (int j = 0; j < records.size(); j++)
if (records.get(j).name.equals(achievement.name)) {
found = true;
break;
}
if (found) continue;
if (totalTakenQuiz >= achievement.threshold) {
AchievementRecord record = new AchievementRecord(user, achievement);
record.addRecordToDB();
newAchievements.add(achievement);
}
}
return newAchievements;
} | 5 |
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(GUIsportsBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIsportsBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIsportsBook.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIsportsBook.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 GUIsportsBook().setVisible(true);
}
});
} | 6 |
@Override
protected TerminalSize calculatePreferredSize() {
if(preferredSizeOverride != null)
return preferredSizeOverride;
int maxWidth = 5; //Set it to something...
for(int i = 0; i < items.size(); i++) {
String itemString = createItemString(i);
if(itemString.length() > maxWidth)
maxWidth = itemString.length();
}
return new TerminalSize(maxWidth + 1, items.size());
} | 3 |
public synchronized String toString(){
String stringgedField = "";
for (int i = 0; i < this.getYLength(); i++) {
stringgedField = stringgedField + '\n';
for (int j = 0; j < this.getXLength(); j++) {
if (field[j][i] == null) {
stringgedField = stringgedField + " ";
}else{
stringgedField = stringgedField + field[j][i].getType();
}
}
}
return stringgedField;
} | 3 |
public void draw(Graphics g)
{
int minx = (int) (worldx / Texture.tilesize);
int maxx = (int) ((worldx + Main.width) / Texture.tilesize) + 1;
int miny = (int) (worldy / Texture.tilesize);
int maxy = (int) ((worldy + Main.height) / Texture.tilesize) + 1;
if(maxx > width) maxx = width;
if(maxy > height) maxy = height;
for(int x = minx; x < maxx; x++)
{
for (int y = miny; y < maxy; y++)
{
tiles[x][y].draw(g, (int) -worldx, (int) -worldy);
}
}
for(int i = 0; i < bullets.size(); i++)
{
bullets.get(i).draw(g, (int) -worldx, (int) -worldy);
}
for (int i = 0; i < enemies.size(); i++)
{
enemies.get(i).draw(g, (int) -worldx, (int) -worldy);
}
player.draw(g);
} | 6 |
public String getHtmlTr() {
try {
JSONObject file = new JSONObject(read());
StringBuffer output = new StringBuffer("<tr><td>");
// Datum
Date d = new Date(file.getLong("datetime"));
output.append(String.format("%tF %tR", d, d));
output.append("</td><td>");
// Informationen
if (file.has("file")) {
output.append("<a href=\"" + file.getString("file") + "\">");
}
output.append(file.getString("information"));
if (file.has("file")) {
output.append("</a>");
}
output.append("</td><td");
// Farbe
if (file.has("good")) {
if (file.getBoolean("good")) {
output.append(" class=\"good\"");
} else {
output.append(" class=\"bad\"");
}
}
output.append(">" + file.getString("type") + "</td></tr>");
return output.toString();
} catch (JSONException e) {
return "";
} catch (FileNotFoundException e) {
return "";
}
} | 6 |
public boolean accept(File file)
{
if (file.isDirectory())
{
return true;
}
else
{
return false;
}
} | 1 |
@Test
public void RandomRotatingGrid() {
//Make two identical models but one parallel and one sequential
AbstractModel paraModel=DataSetLoader.getRandomRotatingGrid(100, 800, 40, new ModelParallel());
AbstractModel seqModel=DataSetLoader.getRandomRotatingGrid(100, 800, 40, new Model());
//Step through each model stepNumber
stepModel(paraModel);
stepModel(seqModel);
//An error check that makes sure there models passed in have some particles
if(paraModel.p.size() == 0 || seqModel.p.size() == 0)
fail("Error the model had nothing in it");
//success or fail check
if(!checkModels(paraModel.p , seqModel.p)){
fail("The particles were not equal between the two models");
}
} | 3 |
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(Analysis.imageA == null || Analysis.imageB == null) return;
Graphics2D g2d = (Graphics2D)g;
Image A = Analysis.imageA;
Image B = Analysis.imageB;
double w = getWidth();
double h = getHeight();
double wCoeffIm1 = w / (2 * A.source.getWidth(null));
double hCoeffIm1 = h / A.source.getHeight(null);
double ratio1 = (wCoeffIm1 < hCoeffIm1) ? wCoeffIm1 : hCoeffIm1;
double x1 = 0, y1 = 0;
double w1 = ratio1 * A.source.getWidth(null),
h1 = ratio1 * A.source.getHeight(null);
double wCoeffIm2 = w / (2 * B.source.getWidth(null));
double hCoeffIm2 = h / B.source.getHeight(null);
double ratio2 = (wCoeffIm2 < hCoeffIm2) ? wCoeffIm2 : hCoeffIm2;
double x2 = w / 2, y2 = 0;
double w2 = ratio2 * B.source.getWidth(null),
h2 = ratio2 * B.source.getHeight(null);
g2d.drawImage(A.source, (int)x1, (int)y1, (int)w1, (int)h1, Color.WHITE, null);
g2d.drawImage(B.source, (int)x2, (int)y2, (int)w2, (int)h2, Color.WHITE, null);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(255,0,128, 128));
g2d.setStroke(new BasicStroke(1));
if(showNearest && Analysis.doneNearest) {
drawNearest(g2d, A, B, x1, y1, w1, h1, x2, y2, w2, h2);
}
if(showPoints) {
drawPoints(g2d, A, x1, y1, w1, h1);
drawPoints(g2d, B, x2, y2, w2, h2);
}
if(showStats) {
g2d.setColor(new Color(198, 198, 198));
g2d.setStroke(new BasicStroke(1));
g2d.fillRect(0, 0, (int) w1, 30);
g2d.setColor(new Color(0, 0, 0));
g2d.drawString("Matched pairs: " + Analysis.matchedPairs, 0, 12);
g2d.drawString("Similarity: " + String.format("%.2f %%", Analysis.percent), 0, 27);
}
} | 8 |
public synchronized void reap()
{
_log.trace("Running the reaper.");
// DON'T FEAR THE REAPPER!!!!!
long now = System.currentTimeMillis();
List<String> mapRemovalList = new LinkedList<String>();
for(List<DNSRecord> list : _Cache.values()) {
List<DNSRecord> removalList = new LinkedList<DNSRecord>();
String key = list.get(0).getName();
for(DNSRecord rec : list) {
if(rec.isExpired(now)) {
removalList.add(rec);
}
}
for(DNSRecord rec : removalList) {
_log.debug("Removing expired record: " + rec);
list.remove(rec);
}
if(list.size() == 0)
mapRemovalList.add(key);
}
for(String key : mapRemovalList) {
_log.debug("Removing expired key: " + key);
_Cache.remove(key);
}
} | 6 |
public void visitSwitchStmt(final SwitchStmt stmt) {
if (stmt.index == from) {
stmt.index = (Expr) to;
((Expr) to).setParent(stmt);
} else {
stmt.visitChildren(this);
}
} | 1 |
private Value runMethod(CodeBlock i) throws InterpreterException {
if (method_.equals(Length)) {
try {
return new Value(var_.getValue().getArray().size());
} catch (Exception e) {
throw new InterpreterException(e.getMessage(), getLine());
}
} else if (method_.equals(Add)) {
try {
Value v = args_[0].run(i);
if (args_.length == 2) {
int ind = args_[1].run(i).getInt();
// if (v.getType().isArray()) {
// for (int j = 0; j < v.getValues().length; j++) {
// var_.getValue().getArray().add(j+ind, v.getValues()[j]);
// }
// } else {
var_.getValue().getArray().add(ind, v);
// }
} else {
// if (v.getType().isArray()) {
// for (int j = 0; j < v.getValues().length; j++) {
// var_.getValue().getArray().add(v.getValues()[j]);
// }
// } else
var_.getValue().getArray().add(v);
}
return var_.getValue();
} catch (Exception e) {
throw new InterpreterException(e.getMessage(), getLine());
}
} else if (method_.equals(Remove)) {
try {
Value v = args_[0].run(i);
int ind = v.getInt();
var_.getValue().getArray().remove(ind);
return var_.getValue();
} catch (Exception e) {
throw new InterpreterException(e.getMessage(), getLine());
}
}
throw new InterpreterException("No method : " + method_ + " found",
getLine());
} | 7 |
private void split(Node node){
Node nodeL=new Node(ORDER);
Node nodeR=new Node(ORDER);
MyRecord keyUp=node.getKeys().get(HALF_KEY);
//already full and one more entered to be split
for(int i=0;i<HALF_KEY;i++){
nodeL.getKeys().add(node.getKeys().get(i));
}
for(int i=HALF_KEY+1;i<ORDER;i++){
nodeR.getKeys().add(node.getKeys().get(i));
}
if(!node.isLeaf()){//if not leaf, have to re allocate children. There should be one more child than ORDER
for(int i=0;i<=HALF_KEY;i++){
nodeL.getChildren().add(node.getChildren().get(i));
}
for(int i=HALF_KEY+1;i<=ORDER;i++){
nodeR.getChildren().add(node.getChildren().get(i));
}
}
if(node.getParent()==null){//create new parent, also the new root of the btree
nodeL.setParent(node);
nodeR.setParent(node);
node.getKeys().clear();
node.getKeys().add(keyUp);
node.getChildren().clear();
node.getChildren().add(nodeL);
node.getChildren().add(nodeR);
this.root=node;
}
else{//add to current parent. Might cause parent having too many (one more) keys and children
nodeL.setParent(node.getParent());
nodeR.setParent(node.getParent());
node.getParent().getKeys().add(keyUp);//keyUp
DataHandler.sortMyRecord(node.getKeys());//sort current keys (might be one more than KEY_MAX)
node.getParent().getChildren().set(node.getParent().getKeys().indexOf(keyUp), nodeL);//node's position is the new Left Node's place.
node.getParent().getChildren().add(node.getParent().getKeys().indexOf(keyUp)+1,nodeR);//add one more position for new right node.
if(node.getParent().getKeys().size()==(MAX_KEY+1)){//If parent is full, split it.
split(node.getParent());
}
}
} | 7 |
private String decodePapPassword(byte[] encryptedPass, byte[] sharedSecret)
throws RadiusException {
if (encryptedPass == null || encryptedPass.length < 16) {
// PAP passwords require at least 16 bytes
logger.warn("invalid Radius packet: User-Password attribute with malformed PAP password, length = " +
encryptedPass.length + ", but length must be greater than 15");
throw new RadiusException("malformed User-Password attribute");
}
MessageDigest md5 = getMd5Digest();
byte[] lastBlock = new byte[16];
for (int i = 0; i < encryptedPass.length; i+=16) {
md5.reset();
md5.update(sharedSecret);
md5.update(i == 0 ? getAuthenticator() : lastBlock);
byte bn[] = md5.digest();
System.arraycopy(encryptedPass, i, lastBlock, 0, 16);
// perform the XOR as specified by RFC 2865.
for (int j = 0; j < 16; j++)
encryptedPass[i + j] = (byte)(bn[j] ^ encryptedPass[i + j]);
}
// remove trailing zeros
int len = encryptedPass.length;
while (len > 0 && encryptedPass[len - 1] == 0)
len--;
byte[] passtrunc = new byte[len];
System.arraycopy(encryptedPass, 0, passtrunc, 0, len);
// convert to string
return RadiusUtil.getStringFromUtf8(passtrunc);
} | 7 |
public static void TakesScreenshot(WebDriver driver, String FailedAt){
try{
// driver is your WebDriver
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// screenshot is the file we have acquired
// fileName is the name of the image file
FileUtils.copyFile(screenshot, new File(FailedAt+".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
} | 1 |
public boolean controlErroresHorarios(Object datos)
{
boolean correcto=false;
ArrayList<Object> entrada = (ArrayList<Object>)datos;
String empleado=(String)entrada.get(0);
String turno=(String)entrada.get(1);
if(!turno.isEmpty() && !empleado.isEmpty())
{
if(Integer.parseInt(empleado)>0)
{
if(Integer.parseInt(turno)>0)
{
correcto=true;
}
}
}
return correcto;
} | 4 |
public void start() throws JSchException{
Session _session=getSession();
try{
Request request;
if(xforwading){
request=new RequestX11();
request.request(_session, this);
}
if(pty){
request=new RequestPtyReq();
request.request(_session, this);
}
request=new RequestSubsystem();
((RequestSubsystem)request).request(_session, this, subsystem, want_reply);
}
catch(Exception e){
if(e instanceof JSchException){ throw (JSchException)e; }
if(e instanceof Throwable)
throw new JSchException("ChannelSubsystem", (Throwable)e);
throw new JSchException("ChannelSubsystem");
}
if(io.in!=null){
thread=new Thread(this);
thread.setName("Subsystem for "+_session.host);
if(_session.daemon_thread){
thread.setDaemon(_session.daemon_thread);
}
thread.start();
}
} | 7 |
private static void registrarTienda()
{
boolean salir;
String nombre, cif;
float deuda;
Tienda tienda;
do
{
try
{
System.out.print( "Introduce el nombre de la tienda: ");
nombre = scanner.nextLine();
System.out.print( "Introduce el cif de la tienda: ");
cif = scanner.nextLine();
System.out.print( "Introduce la deuda lmite por cliente admitida en la tienda: ");
deuda = (float)Double.parseDouble( scanner.nextLine());
tienda = Tienda.registrar( nombre, cif, deuda);
salir = true;
System.out.println( "- Tienda registrada con id " + tienda.getId() + " -");
}
catch (Exception e)
{
System.out.println( e.getMessage());
salir = !GestionTiendas.preguntaReintentar( "Deseas intentarlo de nuevo?");
}
} while (!salir);
} | 2 |
public void addNote(String channel, String sender, String message) {
String[] split = message.split(" ");
if(message.equalsIgnoreCase(Config.getCommandPrefix() + "note")) {
this.bot.sendMessage(channel, "No receiver specified, please try again.");
return;
}
if(split[1].equalsIgnoreCase(this.bot.getNick())) {
this.bot.sendMessage(channel, "I don't take notes...");
return;
}
if(message.equalsIgnoreCase(split[0] + " " + split[1])) {
this.bot.sendMessage(channel, "You didn't give me a message to store, please try again.");
return;
}
sqlConnect();
// This is probably stupid but woo who cares :D
String noteToDB = Util.combineSplit(2, split, " ").replace("'", "<APOSTROPHE>").replace("\\", "<BACKSLASH>");
Statement statement;
try {
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO notes (sender, receiver, message, channel) VALUES ('" + sender + "','" + split[1] + "','" + noteToDB + "','" + channel + "')");
this.bot.sendMessage(channel, "Note Stored.");
Log.consoleLog("Storing note from: " + sender);
} catch (SQLException e) {
Log.consoleLog("Error", "Failed to check for notes.");
this.bot.sendMessage(channel, "Woops, I broke something, try again.");
e.printStackTrace();
}
sqlDisconnect();
} | 4 |
public static void main ( String[] args ) {
String xmldata = "<loadcell> <sensor id='loadcellid1'/> <weight>156</weight> </loadcell>";
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
StringReader sr = new StringReader(xmldata);
XMLEventReader eventReader = null;
try {
eventReader = inputFactory.createXMLEventReader(sr);
} catch (XMLStreamException e) {
e.printStackTrace();
}
while ( eventReader.hasNext() ) {
XMLEvent event = null;
try {
event = eventReader.nextEvent();
} catch (XMLStreamException e) {
e.printStackTrace();
}
if (event.isStartElement() ) {
StartElement se = event.asStartElement();
System.out.println(se.getName());
if (event.asStartElement().getName().getLocalPart().equals("weight")) {
try {
event = eventReader.nextEvent();
} catch (XMLStreamException e) {
e.printStackTrace();
}
System.out.println(event.asCharacters().getData());
}
}
if ( event.isEndElement() ) {
EndElement ee = event.asEndElement();
System.out.println(ee.getName());
}
}
} | 7 |
private void writeFolder(Folder folder) throws IOException {
writeNumber(folder.getCoders().size());
int i;
for (i = 0; i < folder.getCoders().size(); i++) {
CoderInfo coder = folder.getCoders().get(i);
{
int propsSize = coder.getProps().getCapacity();
long id = coder.getMethodID();
int idSize;
for (idSize = 1; idSize < 8; idSize++)
if ((id >> (8 * idSize)) == 0)
break;
byte[] longID = new byte[15];
for (int t = idSize - 1; t >= 0; t--, id >>= 8)
longID[t] = (byte) (id & 0xFF);
byte b;
b = (byte) (idSize & 0xF);
boolean isComplex = !coder.isSimpleCoder();
b |= (isComplex ? 0x10 : 0);
b |= ((propsSize != 0) ? 0x20 : 0);
writeByte(b);
writeBytes(longID, idSize);
if (isComplex) {
writeNumber(coder.getNumInStreams());
writeNumber(coder.getNumOutStreams());
}
if (propsSize == 0)
continue;
writeNumber(propsSize);
writeBytes(coder.getProps(), propsSize);
}
}
} | 8 |
public String say(String str){
String result = "";
int count =1;
for(int i=0;i< str.length();i++){
if(i==str.length() -1){//因为最后一个没有被计入,需要单独处理
result += count + str.substring(i,i+1);
count = 1;
}
else if(str.charAt(i) ==str.charAt(i+1)){
count++;
}else{
result += count +str.substring(i,i+1);
count = 1;
}
}
return result;
} | 3 |
public String processInput(String input) {
stringParts = input.split(" ");
try {
cmdPart = stringParts[0];
} catch (NullPointerException e) {
System.out.println("Error: found no Command");
}
if (input.equals("SYN")) {
return ack;
}
if (cmdPart.equals("!login")) {
return logginUser();
}
if (cmdPart.equals("!logout")) {
return loggoutUser();
}
if (cmdPart.equals("!list")) {
return listAuctions();
}
if (cmdPart.equals("!create")) {
return createAuction();
}
if (cmdPart.equals("!bid")) {
return bidForAuction();
}
return "Error: Unknown command: " + input;
} | 7 |
private static String getOS() {
if (os == null) {
os = System.getProperty("os.name");
}
return os;
} | 1 |
public VenueRemovalFinalized(Venue venue)
{
this.venue = venue;
} | 0 |
public static void main(String[] args) {
System.out.println("This is a binary to decimal converter.");
System.out.println("Please choose your option:");
System.out.println("1. Convert binary to decimal.");
System.out.println("2. Convert decimal to binary.");
System.out.println();
System.out.print("Enter your choice now: ");
int choice = s.nextInt();
s.nextLine();
if(choice == 1){
Bin2Dec();
}
else if(choice == 2){
Dec2Bin();
}
else{
System.out.println("You did not make a valid choice.");
}
} | 2 |
private void knightTopTopRightPossibleMove(Piece piece, Position position)
{
int x1 = position.getPositionX();
int y1 = position.getPositionY();
if((x1 >= 0 && y1 >= 0) && (x1 < 7 && y1 <= 5))
{
if(board.getChessBoardSquare(x1+1, y1+2).getPiece().getPieceType() != board.getBlankPiece().getPieceType())
{
if(board.getChessBoardSquare(x1+1, y1+2).getPiece().getPieceColor() != piece.getPieceColor())
{
// System.out.print(" " + coordinateToPosition(x1+1, y1+2)+"*");
Position newMove = new Position(x1+1, y1+2);
piece.setPossibleMoves(newMove);
}
}
else
{
// System.out.print(" " + coordinateToPosition(x1+1, y1+2));
Position newMove = new Position(x1+1, y1+2);
piece.setPossibleMoves(newMove);
}
}
} | 6 |
public double getSimRevenue(int s2,int s3,int s4){
int phantom_capacity = max_capacity;
int phantom_rev = 0;
int phantom_level = 1;
for(int t=1;t<=no_weeks;t++){
if(t>=s4){
phantom_level = 4;
}
else if(t<s4 && t >= s3){
phantom_level = 3;
}
else if(t<s3 && t >= s2){
phantom_level = 2;
}
else{
phantom_level = 1;
}
double phantom_demand = demand[t-1][phantom_level-1];
double phantom_sales = (int)Math.min(phantom_demand,phantom_capacity);
phantom_capacity -= phantom_sales;
phantom_rev += phantom_sales*price[phantom_level-1];
}
return phantom_rev;
} | 6 |
public boolean isCardPlayable(Card card) {
return card != null &&
(playPile.isEmpty() ||
card.value == Card.EIGHT ||
card.value == playPile.peek().value ||
((playPile.getComponent().hasCardFacade()) ? card.suite == playPile.getComponent().getCardFacade().suite : card.suite == playPile.peek().suite)
);
} | 5 |
public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
this.back();
return c;
} | 3 |
@Test
public void testTrafficLights() {
for (TrafficLight trafficLight : TrafficLight.values()) {
System.out.println(trafficLight);
System.out.println(trafficLight.getDuration());
}
} | 1 |
public JLabel getjLabelNom() {
return jLabelNom;
} | 0 |
public void paintComponent(Graphics g)
{
if(drag==true)
{
if(startDragX-xMouse < 0 & startDragY- yMouse < 0)
{
dragRect = new Rectangle(startDragX,startDragY,xMouse-startDragX,yMouse-startDragY);
}
else if(startDragX-xMouse < 0 & yMouse - startDragY < 0)
{
dragRect = new Rectangle(startDragX,yMouse,xMouse-startDragX,startDragY-yMouse);
}
else if(xMouse-startDragX < 0 & startDragY- yMouse < 0)
{
dragRect = new Rectangle(xMouse,startDragY,startDragX-xMouse,yMouse-startDragY);
}
else if(xMouse-startDragX < 0 & yMouse - startDragY < 0)
{
dragRect = new Rectangle(xMouse,yMouse,startDragX-xMouse,startDragY-yMouse);
}
else {
dragRect = new Rectangle(0,0,0,0);
}
g.setColor(new Color(0, 170, 255, 50));
g.fillRect((int)dragRect.getX(), (int)dragRect.getY(), (int)dragRect.getWidth(), (int)dragRect.getHeight());
g.setColor(new Color(0, 170, 255, 255));
g.drawRect((int)dragRect.getX(), (int)dragRect.getY(), (int)dragRect.getWidth(), (int)dragRect.getHeight());
}
} | 5 |
public boolean alreadyInFile(String name) {
File file = new File("Users.txt");
Scanner scanner;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(name)) {
JOptionPane.showMessageDialog(null, "Username has already been chosen. Pick another.", "Error", JOptionPane.ERROR_MESSAGE);
scanner.close();
return true;
}
}
scanner.close();
return false;
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "System Error: Contact administrator.", "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
} | 3 |
public StringBuffer startTable(StringBuffer org, MutableAttributeSet attrSet) {
originalBuffer = org;
ret = new StringBuffer();
tblno = tblcnt++;
tc = ""+(char)('a'+(tblno/(26*26)))+
(char)((tblno/26)+'a')+
(char)((tblno%26)+'a');
String val = (String)attrSet.getAttribute(HTML.Attribute.BORDER);
border = false;
if( val != null ) {
border = true;
bordwid = 2;
if( val.equals("") == false ) {
try {
bordwid = Integer.parseInt( val );
} catch( Exception ex ) {
}
if( bordwid == 0 )
border = false;
}
}
String bgcolor = (String)attrSet.getAttribute(HTML.Attribute.BGCOLOR);
if (bgcolor != null) {
try {
if (bgcolor.length() != 7 && bgcolor.charAt(0) == '#')
throw new NumberFormatException();
red = Integer.decode("#"+bgcolor.substring(1,3)).doubleValue();
blue = Integer.decode("#"+bgcolor.substring(3,5)).doubleValue();
green = Integer.decode("#"+bgcolor.substring(5,7)).doubleValue();
red /= 255.0;
blue /= 255.0;
green /= 255.0;
} catch (NumberFormatException e) {
red = 1.0;
blue = 1.0;
green = 1.0;
}
}
return ret;
} | 8 |
private void loadGame(){
try{
contrlSaveLoad.load();
}catch(Exception e){
e.printStackTrace();
}
//load main
currentCity = contrlSaveLoad.getCity();
contrlSaveLoad.getSec();
setHandCash(contrlSaveLoad.getCash());
setBankCash(contrlSaveLoad.getBankCash());
setCurrentQuest(contrlSaveLoad.getQuest());
//load levels
lvl.cityDeaths = contrlSaveLoad.getDeaths();
lvl.loadCity(currentCity);
lvl.ownerHouse = contrlSaveLoad.getOwners();
//load player
player.playerInitialize(currentCity);
player.setCurrentCity(currentCity);
player.setCurrentSec(contrlSaveLoad.getSec());
player.entBuilding(contrlSaveLoad.getBuilding(),0,0);
player.loadPosition(contrlSaveLoad.getXLoc(), contrlSaveLoad.getYLoc());
player.setDeathsForColl(contrlSaveLoad.getDeaths());
//load HUD
player.HUD.HUDInitialize();
player.HUD.setCityName(player.getCurrentCity());
player.HUD.setQuest(getCurrentQuest());
player.HUD.cash = getHandCash();
int[] tempSlist = contrlSaveLoad.getInv();
//Reset all items
for(int i = 0; i < tempSlist.length; i++){
//TODO finish adding all items. How to implement damage and strength??
if(tempSlist[i] == 000){
try {
player.HUD.inventory[i] = new Item(tempSlist[i],0,0,rl.getIcon("blankIcon.png"),"",0,0,0,0);
} catch (IOException e) {
e.printStackTrace();
}
}
if(tempSlist[i] == 001){
try {
player.HUD.inventory[i] = new Item(001,5,100,rl.getIcon("spoonIcon.png"),"spoon",0,0,10,4);
} catch (IOException e) {
e.printStackTrace();
}
}
if(tempSlist[i] == 020){
try{
player.HUD.inventory[i] = new Item(020,25,100,rl.getIcon("daggerIcon.png"),"dagger",0,0,10,5);
}catch(IOException e){
e.printStackTrace();
}
}
}
randomGuy.playerInitialize(currentCity);
randomGuy.setCurrentCity(currentCity);
randomGuy.setCurrentSec(contrlSaveLoad.getSec());
randomGuy.entBuilding(contrlSaveLoad.getBuilding(),0,0);
randomGuy.loadPosition(contrlSaveLoad.getXLoc(), contrlSaveLoad.getYLoc());
randomGuy.setDeathsForColl(contrlSaveLoad.getDeaths());
//load HUD
randomGuy.HUD.HUDInitialize();
randomGuy.HUD.setCityName(randomGuy.getCurrentCity());
randomGuy.HUD.setQuest(getCurrentQuest());
randomGuy.HUD.cash = getHandCash();
} | 8 |
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(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Inicio.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 Inicio().setVisible(true);
}
});
} | 6 |
public boolean jumpMayBeChanged() {
return (thenBlock.jump != null || thenBlock.jumpMayBeChanged())
&& elseBlock != null
&& (elseBlock.jump != null || elseBlock.jumpMayBeChanged());
} | 4 |
private void createSocketAndSend(String msg, int flag) throws IOException{
DatagramSocket clientSocket = new DatagramSocket();
String[] ipNumbers = hostIP.split("\\.");
byte[] ip = {(byte) Integer.parseInt(ipNumbers[0]),
(byte) Integer.parseInt(ipNumbers[1]),
(byte) Integer.parseInt(ipNumbers[2]),
(byte) Integer.parseInt(ipNumbers[3]) };
InetAddress IPAddress = InetAddress.getByAddress(ip);
byte[] sendData = new byte[2048*8];
byte[] receiveData = new byte[2048*8];
String requestMessage = msg;
sendData = requestMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress,
P2PUDPServer.UDPSERVER_PORT);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String peerList = new String(receivePacket.getData());
System.out.println("Response Message From Server : " + peerList);
if (flag == CONNECT){
unpackList(peerList);
}
clientSocket.close();
} | 1 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
boolean unSpring=false;
if((!sprung)
&&(affected instanceof Room)
&&(msg.amITarget(affected))
&&((msg.targetMinor()==CMMsg.TYP_ENTER)
&&(!msg.source().isMine(affected)))
&&(msg.tool() instanceof Exit))
{
final Room room=(Room)affected;
if((room.getExitInDir(Directions.DOWN)==msg.tool())
||(room.getReverseExit(Directions.DOWN)==msg.tool()))
{
unSpring=true;
sprung=true;
}
}
super.executeMsg(myHost,msg);
if(unSpring)
sprung=false;
} | 9 |
public boolean needShuffle() // ->brought from DeckArrayManager
{
if (count == 52)
return true;
else
return false;
} | 1 |
public Bag getDiscsWithStability(Stability stability) {
LOGGER.log(Level.INFO, "Getting discs with stability " + stability);
Bag discBag = new Bag();
for (int i = 0; i < discs.size(); i++) {
if (discs.get(i).getStability() == stability) {
discBag.addDisc(discs.get(i));
}
}
LOGGER.log(Level.INFO, "Found " + discBag.size() + " discs with stability " + stability);
return discBag;
} | 2 |
private void paivitaJaLinkitaSolu(int x, int y) {
Solu solu = solut[x][y];
for (int i=x-1;i<x+2;i++){
for (int k=y-1;k<y+2;k++){
if (onKartalla(i, k) && solut[i][k]==solu){
k++;
}
if (onKartalla(i, k)){
solu.lisaaVierusSolu(solut[i][k]);
if (solut[i][k].isMiina() && !solu.isMiina()){
solu.lisaaViereenMiinoja();
}
}
}
}
} | 7 |
public void setSeatType(long value) {
this._seatType = value;
} | 0 |
private boolean send(String mediaId, List<String> recipients, boolean story, int time) {
try {
// Prepare parameters
Long timestamp = getTimestamp();
String requestToken = TokenLib.requestToken(authToken, timestamp);
int snapTime = Math.min(10, time);
// Create comma-separated recipient string
StringBuilder sb = new StringBuilder();
if (recipients.size() == 0 && !story) {
// Can't send to nobody
return false;
}else if(recipients.size() == 0 && story){
// Send to story only
//TODO : Send to story only
return false;
}
JSONArray recipientsArray = new JSONArray();
for(String recipient : recipients){
recipientsArray.put(recipient);
}
// Make parameter map
Map<String, Object> params = new HashMap<String, Object>();
params.put(USERNAME_KEY, username);
params.put(TIMESTAMP_KEY, timestamp.toString());
params.put(REQ_TOKEN_KEY, requestToken);
params.put(MEDIA_ID_KEY, mediaId);
params.put(TIME_KEY, Double.toString(snapTime));
params.put(RECIPIENTS_KEY, recipientsArray.toString());
params.put(ZIPPED_KEY, "0");
params.put(FEATURES_MAP_KEY, new JSONObject().toString());
// Sending path
String path = SEND_PATH;
// Add to story, maybe
if (story) {
path = DOUBLE_PATH;
params.put(CAPTION_TEXT_DISPLAY_KEY, "My Story");
params.put(CLIENT_ID_KEY, mediaId);
params.put(TYPE_KEY, "0");
}
// Execute request
HttpResponse<String> resp = requestString(path, params, null);
if (resp.getStatus() == 200 || resp.getStatus() == 202) {
return true;
} else {
return false;
}
} catch (UnirestException e) {
return false;
}
} | 9 |
public PwdItem GetItem(int id) {
PwdItem item = new PwdItem();
if (this.connection == null) {
return null;
}
try {
Statement stmt = null;
stmt = this.connection.createStatement();
int count = 0;
//find the max id
ResultSet rs = stmt.executeQuery("SELECT * FROM PASSWD WHERE ID=" + id + ";");
while (rs.next()) {
item.setId(rs.getInt("ID"));
item.setDomain(rs.getString("DOMAIN"));
item.setUsername(rs.getString("USERNAME"));
item.setPassword(rs.getString("PASSWORD"));
item.setComment(rs.getString("COMMENT"));
count++;
}
rs.close();
stmt.close();
//no item found
if (count == 0) {
return null;
}
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return item;
} | 4 |
@Override
public LinkedList<Item> getItems(String[] params) {
LinkedList<Item> foundItems = new LinkedList<Item>();
for(Item item : items){
boolean addItem = true;
//Test against Name
if(!params[0].isEmpty() && !params[0].equals(item.getName())){
addItem = false;
}
//Test against Category
if(!params[1].equals("Any Category") && !params[1].equals(item.getCategory())){
addItem = false;
}
//Add item if it passed tests
if(addItem){
foundItems.add(item);
}
}
return foundItems;
} | 6 |
public void writeSrcCoor(String projN, String cycle){
ArrayList<String> srcCoor=rfa.readInputStream(GenerateInitScripts.class.getResourceAsStream("config/common/coordinator.xml"),"UTF-8");
StringBuffer content=new StringBuffer();
String cycleTag="${coord:days(1)}";
if(cycle.equalsIgnoreCase("months"))
cycleTag="${coord:months(1)}";
for(int i=0; i<srcCoor.size(); ++i){
if(srcCoor.get(i).contains("{project-name-config-generate}")){
content.append("<coordinator-app name=\""+projN+"-cd\"\n");
content.append(" frequency=\""+cycleTag+"\" ");
}else if(srcCoor.get(i).contains("{dataset-config-generate}")){
content.append(" <dataset name=\""+projN+"_dataset\" frequency=\""+cycleTag+"\"\n");
content.append(" initial-instance=\"${job_start}\" timezone=\"GMT+08:00\">\n");
content.append(" <uri-template>${hdfs_address_prefix}/Pad-dbw/"+projN+"/${YEAR}${MONTH}${DAY}/\n");
content.append(" </uri-template>\n");
content.append(" </dataset>\n");
}else if(srcCoor.get(i).contains("{input-output-config-generate}")){
content.append(" <output-events>\n");
content.append(" <data-out name=\"output\" dataset=\""+projN+"_dataset\">\n");
content.append(" <instance>${coord:current(0)}</instance>\n");
content.append(" </data-out>\n");
content.append(" </output-events>\n");
}
else
content.append(srcCoor.get(i)+"\n");
}
String initPath=System.getProperty("user.dir")+ File.separator+projN;
wfa.mkdirs(initPath);
wfa.writeFromStringBuffer(initPath+File.separator+"coordinator.xml","UTF-8",content);
} | 5 |
public static int triangleBmax(int x[][]) {
int max = x[0][0];
for (int i = 0; i < x.length; i++) {
System.out.print("\n");
for (int j = 0; j < x[i].length; j++) {
if (i >= j) {
System.out.print(x[i][j] + " ");
if (max < x[i][j]) {
max = x[i][j];
}
}
}
}
System.out.println();
return max;
} | 4 |
private double gcf(double x, double a) {
int i;
double gold = 0, g, a0 = 1, a1 = x, b0 = 0, b1 = 1, fac = 1, anf, ana;
for (i = 1; i <= ITER_MAX; i++) {
ana = i - a;
a0 = (a1 + a0 * ana) * fac;
b0 = (b1 + b0 * ana) * fac;
anf = i * fac;
a1 = x * a0 + anf * a1;
b1 = x * b0 + anf * b1;
if (a1 != 0.0) {
fac = 1 / a1;
g = b1 * fac;
if (Math.abs((g - gold) / g) < EPS)
return (g * Math.exp(-x + a * Math.log(x) - logGamma(a)));
gold = g;
}
}
return 2; // gamcdf will return -1
} | 3 |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
LinkedList<ListNode> lists3 = new LinkedList<ListNode>();
int flag = 0;
int sum = 0;
ListNode pre = new ListNode(0);
// first step
sum = l1.val + l2.val;
if (sum > 9) {
flag = 1;
}
else{
flag = 0;
}
pre.val = sum - flag*10;
lists3.add(pre);
// main loop
while ((l1.next != null)&&(l2.next != null)){
l1 = l1.next;
l2 = l2.next;
sum = l1.val + l2.val + flag;
if (sum > 9) {
flag = 1;
}
else{
flag = 0;
}
ListNode post = new ListNode(sum - flag*10);
pre.next = post;
lists3.add(post);
pre = post;
}
// last step
if (l2.next == null) l2 = l1;
while (l2.next != null){
l2 = l2.next;
sum = l2.val + flag;
if (sum > 9) {
flag = 1;
}
else{
flag = 0;
}
ListNode post = new ListNode(sum - flag*10);
pre.next = post;
lists3.add(post);
pre = post;
}
if (flag == 1){
ListNode post = new ListNode(1);
pre.next = post;
lists3.add(post);
}
return lists3.element();
} | 8 |
public static void deleteCompte(Compte compte) {
Statement stat;
try {
stat = ConnexionDB.getConnection().createStatement();
stat.executeUpdate("delete from compte where id_compte="+ compte.getId_compte());
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} | 2 |
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length <= 0) {
return false;
}
if (args[0].equalsIgnoreCase("debug-mode")) {
if (args.length == 2) {
boolean newDebugMode = Boolean.parseBoolean(args[1]);
config.debugMode = newDebugMode;
config.saveConfig();
if (newDebugMode) {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": Debug mode is now " + ChatColor.GOLD + "enabled" + ChatColor.WHITE + ".");
} else {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": Debug mode is now " + ChatColor.GOLD + "disabled" + ChatColor.WHITE + ".");
}
} else {
if (config.debugMode) {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": Debug mode is " + ChatColor.GOLD + "enabled" + ChatColor.WHITE + ".");
} else {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": Debug mode is " + ChatColor.GOLD + "disabled" + ChatColor.WHITE + ".");
}
}
} else if (args[0].equalsIgnoreCase("debug-action")) {
if (args.length == 2) {
int newActionId = Integer.parseInt(args[1]);
config.actionId = newActionId;
config.saveConfig();
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": The debug action ID is now " + ChatColor.GOLD + newActionId + ChatColor.WHITE + ".");
} else {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": The debug action ID is " + ChatColor.GOLD + config.actionId + ChatColor.WHITE + ".");
}
} else if (args[0].equalsIgnoreCase("reload-config")) {
config.reloadConfig();
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": The configuration was reloaded.");
} else {
sender.sendMessage(ChatColor.YELLOW + "UnexpectedFishing" + ChatColor.WHITE + ": Incorrect command.");
}
return true;
} | 8 |
public void spawnEnemy()
{
int x = random.nextInt(width);
int y = random.nextInt(height);
if(tiles[x][y].isObstacle())
{
spawnEnemy();
return;
}
Enemy e = new Enemy(x * Texture.tilesize, y * Texture.tilesize, 0, 0);
e.setPath(graph.astar(graph.getNodeID(x, y), graph.getNodeID(getPlayerTilePosX(), getPlayerTilePosY())));
enemies.add(e);
} | 1 |
private void setDialogActionListeners() {
//handles when the initial dialog is closed; kills the client
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
client.kill();
}
});
//handles what happens when the user presses start
//enters the user is possible and sets up the canvas
startButton.addActionListener(new ActionListener() {
public synchronized void actionPerformed(ActionEvent e) {
//if the username is empty
if (usernameTextField.getText().equals("")) {
JOptionPane.showMessageDialog(dialog, "Please enter a username.", "Try again", JOptionPane.ERROR_MESSAGE);
}
//if no board is selected
else if (boardList.isSelectionEmpty()) {
JOptionPane.showMessageDialog(dialog, "Please select a board.", "Try again", JOptionPane.ERROR_MESSAGE);
} else
try {
//if the user has entered successfully
if (client.createUser(usernameTextField.getText(), boardList.getSelectedValue())) {
dialog.dispose();
setupCanvas();
client.makeRequest("switch "+client.getUsername()+" "+client.getCurrentBoardName()+" "+client.getCurrentBoardName());
} else {
JOptionPane.showMessageDialog(dialog, "Sorry, this username is already taken currently.", "Try again", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
//handles making a new board and adding it to the list
newBoardButton.addActionListener(new ActionListener() {
public synchronized void actionPerformed(ActionEvent e) {
if (!newBoard.getText().equals("")) {
NewBoardWorker worker = new NewBoardWorker(newBoard.getText());
worker.execute();
}
//if the name is empty
else {
JOptionPane.showMessageDialog(dialog, "Please enter a board name.", "Try again", JOptionPane.ERROR_MESSAGE);
}
}
});
} | 5 |
public void playSound(String path)
{
try
{
in = new FileInputStream(path);
as = new AudioStream(in);
ap.player.start(as);
}
catch(Exception e)
{
System.out.println("Got an IOException: " + e.getMessage());
e.printStackTrace();
}
} | 1 |
public boolean isExistingProfil(String nom) {
Iterator iterator = this.getAllProfils().keySet().iterator();
while (iterator.hasNext()) {
if (((Profil) this.getAllProfils().get(iterator.next())).getNom().equals(nom)) {
return true;
}
}
return false;
} // isExistingProfil(String nom) | 2 |
@Override
public void onEnter() {
Bukkit.getWorlds().get(0).setDifficulty(Difficulty.PEACEFUL);
for (Player player : Bukkit.getOnlinePlayers()) {
player.teleport(Util.parseLocation(getGame().getPlugin().getConfig().getString("game.respawn"), true));
}
for (Entity entity : Bukkit.getWorlds().get(0).getEntities()) {
if(!(entity instanceof Player)){
entity.remove();
}
}
Bukkit.getPluginManager().registerEvents(new GameListener(getGame()), getGame().getPlugin());
this.playerActionManager = new PlayerActionManager(getGame());
//Loading DelayedPlayerWeightedPlatforms
for (String target : getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.player-weighted").getKeys(false)) {
DelayedPlayerWeightedPlatformAction.DelayedPlayerWeightedPlatformActionLoader loader = new DelayedPlayerWeightedPlatformAction.DelayedPlayerWeightedPlatformActionLoader();
playerActionManager.registerAction(loader.load(getGame(), getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.player-weighted").getConfigurationSection(target)));
}
//Loading PlayerElevatorPlatforms
for (String target : getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.elevator").getKeys(false)) {
PlayerElevatorPlatform.PlayerElevatorPlatformLoader loader = new PlayerElevatorPlatform.PlayerElevatorPlatformLoader();
playerActionManager.registerAction(loader.load(getGame(), getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.elevator").getConfigurationSection(target)));
}
//Loading PlayerCanonPlatforms
for (String target : getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.canon").getKeys(false)){
PlayerCanonPlatformAction.PlayerCanonPlatformActionLoader loader = new PlayerCanonPlatformAction.PlayerCanonPlatformActionLoader();
playerActionManager.registerAction(loader.load(getGame(), getGame().getPlugin().getConfig().getConfigurationSection("game.platforms.canon").getConfigurationSection(target)));
}
} | 6 |
public List<FoodDataBean> getArticleList(int start, int end) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<FoodDataBean> articleList = null;
String sql = "";
try{
conn = getConnection();
/*추천지수 불러오는sql*/
sql = "update food set recommand_count = recommand - non_recommand ";
pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
sql = "select a.* from (select ROWNUM as RNUM, b.* from (select * from food" +
" order by idx desc) b order by ref desc, step asc) a where a.RNUM >=? and a.RNUM <=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, start);
pstmt.setInt(2, end);
rs = pstmt.executeQuery();
if(rs.next()){
articleList = new ArrayList<FoodDataBean>(end);
do{
FoodDataBean article = new FoodDataBean();
article.setIdx(rs.getInt("idx"));
article.setArea_idx(rs.getInt("area_idx"));
article.setTitle(rs.getString("title"));
article.setContent(rs.getString("content"));
article.setNickname(rs.getString("nickname"));
article.setId(rs.getString("id"));
article.setWdate(rs.getTimestamp("wdate"));
article.setRead_count(rs.getInt("read_count"));
article.setRecommand_count(rs.getInt("recommand_count"));
article.setRecommand(rs.getInt("recommand"));
article.setNon_recommand(rs.getInt("non_recommand"));
article.setCategory(rs.getString("category"));
article.setDepth(rs.getInt("depth"));
articleList.add(article);
}
while(rs.next());
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs != null){
try{rs.close();}
catch(SQLException e){e.printStackTrace();}
}
if(pstmt != null){
try{pstmt.close();}
catch(SQLException e){e.printStackTrace();}
}
if(conn != null){
try{conn.close();}
catch(SQLException e){e.printStackTrace();}
}
}
return articleList;
} | 9 |
public String toString(StringBuilder all, StringBuilder word) {
if (this.value > 0) {
all.append(word.toString()).append(" ").append(this.value).append("\n");
}
if (this.nodes != null) {
for (int i = 0; i < this.nodes.length; i++) {
if (this.nodes[i] != null) {
char c = (char) (i + (int) 'a');
word.append(c);
this.nodes[i].toString(all, word);
}
}
}
try {
word.deleteCharAt(word.length() - 1);
}
catch (IndexOutOfBoundsException e) {}
return all.toString();
} | 5 |
public int[] randomTags(int L, int n) {
int[] slots = new int[L];
for(int i = 0; i < n; i ++) slots[(int)(Math.random()*L)]++;
int[] status = new int[3];
for(int i : slots) {
if(i == 0) status[0]++;
else if( i == 1) status[1]++;
else status[2]++;
}
return status;
} | 4 |
private void updateShip(Info info) {
Node nodeOne;
Node nodeTwo;
Set<Node> nodes;
// visit every edge in the actual ship
for (Edge e : info.adjacentEdges) {
nodeOne = info.location;
nodeTwo = Node.getOtherNode(e, nodeOne);
nodes = new HashSet<Node>();
nodes.add(nodeOne);
nodes.add(nodeTwo);
Edge predEdge = predatorShip.edgeMap.get(nodes);
// compare it to the predators memory, makes necessary
// adjustments
if (predEdge != null) {
if (e.getEdgeState() != predEdge.getEdgeState()) {
predEdge.setEdgeState(e.getEdgeState());
}
}
else {
Node predsNodeOne = predatorShip.getNodeAt(nodeOne.getRow(), nodeOne.getCol());
Node predsNodeTwo = predatorShip.getNodeAt(nodeTwo.getRow(), nodeTwo.getCol());
Set<Node> nodesForEdge = new HashSet<Node>();
nodesForEdge.add(predsNodeOne);
nodesForEdge.add(predsNodeTwo);
predatorShip.edgeMap.put(nodesForEdge, new Edge(e.getEdgeState(), predsNodeOne, predsNodeTwo));
}
}
} | 3 |
@Override
public void run() {
try {
serverSocket = new ServerSocket(SERVER_DATA_SOCKET);
while (true) {
// wait for a client request and when received assign it to the
// client socket
// when u wanna send data to that client u'll use this socket
Socket clientConnection = serverSocket.accept();
logger.debug("Incomming connection from: " + clientConnection.getInetAddress().getHostAddress());
ConnectionHandler handler = null;
// Find an empty spot for handling data;
for (int i = 0; i < datahandlers.length; i++) {
if (datahandlers[i] == null) {
datahandlers[i] = new ConnectionHandler(i, this);
handler = datahandlers[i];
break;
}
}
// Check if we are full
if (handler != null) {
logger.debug("Connection accepted, send to handler.");
clientConnection.getOutputStream().write(ConnectionMessages.SERVER_RESPONSE_ACCEPT.getBytes());
clientConnection.getOutputStream().flush();
handler.handle(clientConnection);
} else {
// Server is busy, reject
try {
logger.debug("Connection refused, server to busy!");
clientConnection.getOutputStream().write(ConnectionMessages.SERVER_RESPONSE_BUSY.getBytes());
clientConnection.close();
} catch (IOException ex) {
logger.error("Could not close client connection!", ex);
}
}
clientConnection = null;
}
} catch (IOException ex) {
logger.fatal("Could not open serversocket for data connections.");
}
} | 6 |
public Collection<T> readAll() {
SQLStrings.INSTANCE.getReadAllElementsString();
Collection<T> result = null;
Connection conn = hsqlh.createConnection();
try {
/*
PreparedStatement prep_stmt = conn.prepareStatement(SQLStrings.INSTANCE.getReadAllElementsString());
prep_stmt.clearParameters();
for (Integer position : ORMReflectionsMapper.INSTANCE.getFieldPositionMap().keySet()) {
String fieldName = ORMReflectionsMapper.INSTANCE.getFieldPositionMap().get(position);
Field f = clazz.getDeclaredField( fieldName );
Method prep_stmt_setter = ORMReflectionsMapper.INSTANCE.getFieldAccessorMethodMap().get( f ).get("set");
f.setAccessible(true);
Object toSet = f.get(data);
prep_stmt_setter.invoke(prep_stmt, position, toSet);
}*/
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStrings.INSTANCE.getReadAllElementsString());
//if (rs!=null) {
// System.out.println("HsqlDAO:366 "+rs.toString());
Collection<T> lResult = new ArrayList<T>();
//}
Collection<String> fieldsOrdered = ORMReflectionsMapper.INSTANCE.getFieldPositionMap().values();
while (rs.next()) {
T data_new = clazz.newInstance();
for (String fieldName: fieldsOrdered ) {
Field f = ORMReflectionsMapper.INSTANCE.getFieldMap().get(fieldName);
Method method = ORMReflectionsMapper.INSTANCE.getFieldAccessorMethodMap().get(f).get("get");
f.setAccessible(true);
Object toSet = method.invoke(rs, f.getName());
f.set(data_new, toSet );
}
lResult.add(data_new);
}
if (!lResult.isEmpty()) result = lResult;
rs.close();
stmt.close();
}
catch (SQLException e) {
System.err.println(this.getClass().getName()+".readAll(): failed to retrieve any element with \n"+e);
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
finally {
hsqlh.closeConnection(conn);
}
return result;
} | 9 |
public boolean addWord(String word){
CharNode temporary_node;
CharNode temporary_child;
int i=1;
if(word.length() <= 0)
return false;
if(this.head.getChar() != word.charAt(0))
return false;
temporary_node = this.head;
for(i=1; i < word.length(); ++i){
if((temporary_child = temporary_node.getChild(word.charAt(i))) == null)
break;
temporary_node = temporary_child;
}
for(int j=i; j < word.length(); ++j){
temporary_child = new CharNode(word.charAt(j), temporary_node);
temporary_node.addChild(temporary_child);
temporary_node = temporary_child;
}
temporary_node.updateEnd();
return true;
} | 5 |
public void fulfillOrder()
{
try
{
PreparedStatement stmt = connection.prepareStatement("select sum(i.price * c.amount * d.percent) as total " +
" from martitem i " +
"join cartitem c on i.stock_number = c.stock_number " +
"join discount d on d.status = ? " +
"where trim(c.cid) = ? ");
stmt.setString(1, currentModel.getStatus());
stmt.setString(2, customerIdentifier);
ResultSet cartresult = stmt.executeQuery();
cartresult.next();
double total = cartresult.getDouble("total");
if (total <= 100)
{
stmt = connection.prepareStatement("select percent from discount where status = 'Shipping'");
ResultSet srs = stmt.executeQuery();
srs.next();
total *= srs.getDouble("percent");
}
SaleModel saleModel = new SaleModel(connection);
int ordnum = getNextOrderId();
Calendar cal = Calendar.getInstance();
saleModel.setAll(ordnum, customerIdentifier, total, new Timestamp(new Date().getTime()), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR));
saleModel.insert();
cartresult = getCartItems();
OrderedItemModel orderModel = new OrderedItemModel(connection);
while (cartresult.next())
{
PreparedStatement pstmt = connection.prepareStatement("select (price * ?) as total from martitem where stock_number = ?");
pstmt.setInt(1, cartresult.getInt("amount"));
pstmt.setString(2, cartresult.getString("stock_number"));
ResultSet prs = pstmt.executeQuery();
prs.next();
orderModel.setAll(ordnum, cartresult.getString("stock_number"), prs.getDouble("total"), cartresult.getInt("amount"));
orderModel.insert();
}
clearCart();
checkStatus();
WarehouseController wcon = new WarehouseController(connection);
wcon.fillCustomerOrder(ordnum);
} catch (SQLException e)
{
e.printStackTrace();
}
} | 3 |
public synchronized void handle(String userID, int ID, String input) {
StringTokenizer in = new StringTokenizer(input, " ");
String command = in.nextToken();
System.out.println(command);
if (command.equals(".bye")) {
clients[findClient(ID)].send(".bye");
remove(ID);
} else if (command.equals(".create")) {// .createGroup gID
String gID = in.nextToken();
Group g = new Group(gID);
groups.add(g);
g.joinGroup(userID);
getUser(userID).addGroup(gID);
System.out.println("create");
} else if (command.equals(".join")) {// .joinGroup gID
String gID = in.nextToken();
Group g = getGroup(gID);
g.joinGroup(userID);
getUser(userID).addGroup(gID);
clients[findClient(ID)].setGroupID(gID);
System.out.println("join");
} else if (command.equals(".leave")) {
String gID = in.nextToken();
Group g = getGroup(gID);
g.leaveGroup(userID);
getUser(userID).deleteGroup(gID);
clients[findClient(ID)].setGroupID("");
System.out.println("leave");
} else if (command.equals(".enter")) {
String gID = in.nextToken();
Group g = getGroup(gID);
g.enterGroup(userID);
clients[findClient(ID)].setGroupID(gID);
clients[findClient(ID)].send(g.getUnread(userID));
System.out.println("enter");
} else if (command.equals(".exit")) {
String gID = in.nextToken();
Group g = getGroup(gID);
g.exitGroup(userID);
clients[findClient(ID)].setGroupID("");
System.out.println("exit");
} else if (command.equals(".login")) {
String uID = in.nextToken();
UserInfo loginUser = new UserInfo(uID);
if (users.contains(loginUser)) {
String gListString = users.get(users.indexOf(uID))
.getGroupList().toString();
clients[findClient(ID)].send(".groupList " + gListString);
} else {
users.add(loginUser);
clients[findClient(ID)].send(".newUser");
}
System.out.println("login");
} else {
String gID = clients[findClient(ID)].getGroupID();
ArrayList<String> sendList = getGroup(gID).sendMsg(
new Message(input, userID, dateFormat.format(time)));
for (int i = 0; i < sendList.size(); i++)
clients[findUser(sendList.get(i))].send(ID + ": " + input);
System.out.println(ID + ": " + input);
}
} | 9 |
public ArrayList<String> theatricalsToList(){
ArrayList<String> temp = new ArrayList<>();
for (Theatrical theatrical : theatricals) {
temp.add(theatrical.getName());
}
return temp;
} | 1 |
public int readInput() {
System.out.println("Vad vill du göra? ");
System.out
.println("1) Visa alla journaler \n 2) Visa en journal \n 3) ändra journal(er) \n 4) Skapa ny journal \n 5) Ta bort ");
String input = scan.nextLine();
String addText = "";
if (input.equals( "1")) {
System.out.println(sendJournalRequest(input).replace("#", "\n"));
} else if(input.equals("2")){
System.out.println("Mata in ID på den journalen du vill visa: ");
addText = input + "!" + scan.nextLine();
System.out.println(sendJournalRequest(addText).replace("#", "\n"));
} else if (input.equals("3")) {
System.out.println("Mata in ID på den journalen du vill ändra: ");
addText = input + "!" +scan.nextLine();
System.out.println("Skriv in det du vill lägga till: ");
addText = addText + "!" +scan.nextLine();
sendJournalRequest(addText);
}else if(input.equals("4")){
System.out.println("Mata in ID på den journalen du vill skapa: ");
addText =input + "!" +scan.nextLine();
System.out.println("Mata in namnet på patienten: ");
addText = addText + "!" +scan.nextLine();
System.out.println("Mata in namnet på din sjuksköterska: ");
addText = addText + "!" +scan.nextLine();
System.out.println(sendJournalRequest(addText).replace("#", "\n"));
}else if(input.equals("5")){
System.out.println("Mata in ID på den journalen du vill ta bort: ");
System.out.println(sendJournalRequest(input + "!" + scan.nextLine()).replace("#", "\n"));
}
return Integer.parseInt(input);
} | 5 |
final boolean isValidHost() {
anInt40++;
String string = getDocumentBase().getHost().toLowerCase();
if (string.equals("jagex.com") || string.endsWith(".jagex.com"))
return true;
if (string.equals("runescape.com")
|| string.endsWith(".runescape.com"))
return true;
if (string.endsWith("127.0.0.1"))
return true;
for (/**/;
(string.length() > 0 && string.charAt(-1 + string.length()) >= '0'
&& (string.charAt(-1 + string.length()) ^ 0xffffffff) >= -58);
string = string.substring(0, string.length() - 1)) {
/* empty */
}
if (string.endsWith("192.168.1."))
return true;
method82(53, "invalidhost");
return false;
} | 9 |
public void editDataLevel(String name, double totalPoints) {
path = name;
File f = new File(plugin.getDataFolder() + File.separator + "Players" + File.separator + name + ".data");
try {
if (!f.exists()) {
saveDataFirst(name);
}
BufferedReader br = new BufferedReader(new FileReader(f));
FileWriter fw = new FileWriter(new File(f + "_TMP.data"), true);
PrintWriter pw = new PrintWriter(fw);
BufferedWriter bw = new BufferedWriter(pw);
String line;
String[] line2;
while ((line = br.readLine()) != null) {
if (line.contains("Level")) {
String replace = line.replace(line, "Level|" + totalPoints);
pw.println(replace);
} else {
pw.println(line);
}
}
bw.close();
br.close();
} catch (Exception e) {
////e.printStackTrace();
}
File oldData = f;
oldData.delete();
File newData = new File(f + "_TMP.data");
newData.renameTo(f);
} | 4 |
private List expandContext(List symbols) {
List ne = new ArrayList();
for (int i = 0; i < symbols.size(); i++) {
String s = (String) symbols.get(i);
ArrayList replacementsList = new ArrayList();
for (int j = 0; j < contexts.length; j++) {
List[] l = contexts[j].matches(symbols, i);
for (int k = 0; k < l.length; k++)
replacementsList.add(l[k]);
}
List[] replacements = (List[]) replacementsList
.toArray(EMPTY_ARRAY);
List replacement = null;
switch (replacements.length) {
case 0:
// This cannot be replaced, so we skip to the next symbol.
ne.add(s);
continue;
case 1:
// There is only one replacement possibility.
replacement = replacements[0];
break;
default:
// If there's more than one possibility, we choose one
// nearly at random.
replacement = replacements[stochiastic
.nextInt(replacements.length)];
break;
}
Iterator it2 = replacement.iterator();
while (it2.hasNext())
ne.add(it2.next()); // Add replacements!
}
return ne;
} | 6 |
public void imc_process_call_outs()
{
if (call_outs.size() < 1)
{
return;
}
for (int i = 0; i < call_outs.size(); i++)
{
final Vector call_out = (Vector) call_outs.get(i);
final String fun = (String) call_out.elementAt(0);
final long hbeat = ( (Long) call_out.elementAt(1)).longValue();
final Object param = call_out.elementAt(2);
if (hbeat == HeartBeat)
{
final Object o = this;
final Class<?> cl = o.getClass();
final java.lang.reflect.Method funcs[] = cl.getMethods();
if (funcs.length > 1)
{
for (final Method func : funcs)
{
final String m_name = func.getName();
if (m_name.equals(fun))
{
try
{
func.invoke(o, new Object[] {param});
}
catch (final Exception e)
{
tracef(0,
"imc: call_out failed with error: "
+ e.toString());
}
}
}
}
call_outs.remove(i);
i--;
}
}
} | 8 |
public boolean imageUpdate(Image img, int flags, int x, int y, int width, int height) {
String add = ", img: " + img + ", flags: " + flags + ", x/y: " + x + "," + y + ", width: " + width + ", height: " + height;
if ((flags & ABORT) != 0)
CoffeeSaint.log.add("Image aborted" + add);
if ((flags & ALLBITS) != 0)
CoffeeSaint.log.add("Image complete" + add);
if ((flags & ERROR) != 0)
CoffeeSaint.log.add("Image error" + add);
if ((flags & FRAMEBITS) != 0)
CoffeeSaint.log.add("Image framebits " + add);
if ((flags & HEIGHT) != 0)
CoffeeSaint.log.add("Image framebits " + add);
if ((flags & PROPERTIES) != 0)
CoffeeSaint.log.add("Image framebits " + add);
if ((flags & SOMEBITS) != 0)
CoffeeSaint.log.add("Image framebits " + add);
if ((flags & WIDTH) != 0)
CoffeeSaint.log.add("Image framebits " + add);
// If status is not COMPLETE then we need more updates.
return (flags & (ALLBITS|ABORT)) == 0;
} | 8 |
void writeRequest(OutputStream out) throws IOException {
DataOutputStream data = new DataOutputStream(new BufferedOutputStream(out));
if ((doOutput) && (output == null)) {
throw new IOException(Messages.getString("HttpsURLConnection.noPOSTData")); //$NON-NLS-1$
}
if (ifModifiedSince != 0) {
Date date = new Date(ifModifiedSince);
SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss z"); //$NON-NLS-1$
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
setRequestProperty("If-Modified-Since", formatter.format(date)); //$NON-NLS-1$
}
if (doOutput) {
setRequestProperty("Content-length", "" + output.size()); //$NON-NLS-1$ //$NON-NLS-2$
}
data.writeBytes((doOutput ? "POST" : "GET") + " " + (url.getFile().equals("") ? "/" : url.getFile()) + " HTTP/1.0\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
for (int i = 0; i < requestKeys.size(); ++i) {
String key = (String) requestKeys.elementAt(i);
if (!key.startsWith("Proxy-")) { //$NON-NLS-1$
data.writeBytes(key + ": " + requestValues.elementAt(i) + "\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
data.writeBytes("\r\n"); //$NON-NLS-1$
data.flush();
if (doOutput) {
output.writeTo(out);
}
out.flush();
} | 9 |
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(Start.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Start.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Start.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Start.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException ce) {
System.out.println(ce);
}
new Start().setVisible(true);
} | 7 |
public void changeCase(boolean upper)
{
for (int x = 0; x < grid.length; x++)
{
for (int y = 0; y < grid[x].length; y++)
{
String c = String.valueOf(grid[x][y]);
c = upper ? c.toUpperCase() : c.toLowerCase();
grid[x][y] = c.charAt(0);
}
}
} | 3 |
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile | 2 |
public Object next() {
Object o = null;
// Block if the Queue is empty.
synchronized(_queue) {
if (_queue.size() == 0) {
try {
_queue.wait();
}
catch (InterruptedException e) {
return null;
}
}
// Return the Object.
try {
o = _queue.firstElement();
_queue.removeElementAt(0);
}
catch (ArrayIndexOutOfBoundsException e) {
throw new InternalError("Race hazard in Queue object.");
}
}
return o;
} | 3 |
public void hit(GroupOfUnits target)
{
int no = 0;
try {
no = target.getNumber();
} catch (NullPointerException e) {
return;
}
if (humanPlaying()) {
if (currentUnit.type.shooting) {
gui.Sound.play("sound/shot.wav");
} else {
gui.Sound.play("sound/attk.wav");
}
}
QApplication.processEvents();
boolean isDead = currentUnit.hit(target);
String l = currentUnit.type.name+" ("+currentUnit.getOwner().getColor().name+") uderzył "+target.type.name+" i zabił "+(no-target.getNumber())+" jednostek";
log.emit(l);
QApplication.processEvents();
core.Point pos = p2u.get(target);
if (isDead) {
mapWidget.objectAt(pos.y, pos.x).setLayer(3, null);
mapWidget.objectAt(pos.y, pos.x).setLayer(4, null);
p2u.remove(target);
units.remove(target);
if (humanPlaying()) {
gui.Sound.play("sound/kill.wav");
}
QApplication.processEvents();
} else {
mapWidget.objectAt(pos.y, pos.x).setLayer(4, new gui.WidgetLabel(""+target.getNumber(), target.getOwner().getColor()));
}
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.