method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
78e70008-6530-4701-9549-ab14e46e96b9 | 8 | public static boolean isConnected(mxAnalysisGraph aGraph)
{
Object[] vertices = aGraph.getChildVertices(aGraph.getGraph().getDefaultParent());
int vertexNum = vertices.length;
if (vertexNum == 0)
{
throw new IllegalArgumentException();
}
//data preparation
int connectedVertices = 1;
int[] visited = new int[vertexNum];
visited[0] = 1;
for (int i = 1; i < vertexNum; i++)
{
visited[i] = 0;
}
ArrayList<Object> queue = new ArrayList<Object>();
queue.add(vertices[0]);
//repeat the algorithm until the queue is empty
while (queue.size() > 0)
{
//cut out the first vertex
Object currVertex = queue.get(0);
queue.remove(0);
//fill the queue with neighboring but unvisited vertexes
Object[] neighborVertices = aGraph.getOpposites(aGraph.getEdges(currVertex, null, true, true, false, true), currVertex, true,
true);
for (int j = 0; j < neighborVertices.length; j++)
{
//get the index of the neighbor vertex
int index = 0;
for (int k = 0; k < vertexNum; k++)
{
if (vertices[k].equals(neighborVertices[j]))
{
index = k;
}
}
if (visited[index] == 0)
{
queue.add(vertices[index]);
visited[index] = 1;
connectedVertices++;
}
}
}
// if we visited every vertex, the graph is connected
if (connectedVertices == vertexNum)
{
return true;
}
else
{
return false;
}
}; |
4f850cf8-e4f2-4802-9958-d1643c899aa8 | 9 | private void generateLookupTable() {
for (int i = 0; i < 512; i++) {
boolean[] bits = toBinaryArray(i, 9);
int liveNeighbors = 0;
for (int j = 0; j < 9; j++) {
if (bits[j] && j != 4) {
liveNeighbors++;
}
}
boolean isLiving = bits[4];
if (!isLiving && liveNeighbors == 3) {
lookupTable[i] = true;
} else if (isLiving && (liveNeighbors == 2 || liveNeighbors == 3)) {
lookupTable[i] = true;
} else {
lookupTable[i] = false;
}
}
} |
5159d28d-49d1-4504-9859-9e365db743e8 | 9 | public static void binaryInsertionSort(Comparable[] a, int lo, int hi) {
for (int i = lo + 1; i <= (hi < lo + 7 ? hi : lo + 7); i++) {
for (int j = i; j > lo && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
}
for (int i = lo + 8; i <= hi; i++) {
// for (int i = lo + 1; i <= hi; i++) {
if (less(a[i], a[i-1])) {
// int k = binarySearch(a, lo, i-1);
Comparable v = a[i];
int lolo = lo;
int hihi = i-1;
int k = lo;
while (lolo <= hihi) {
int mid = lolo + (hihi - lolo) / 2;
if (less(v, a[mid])) hihi = mid - 1;
else if (less(v, a[mid+1])) { k = mid+1; break;}
else lolo=mid+1;
}
// for (int j = i; j > k; j--) {
// a[j] = a[j-1];
// }
System.arraycopy(a, k, a, k+1, i-k);
a[k] = v;
}
assert isSorted(a, lo, i);
}
assert isSorted(a, lo, hi);
} |
b945398a-9c0c-4a34-aa70-f0b497295615 | 0 | @Basic
@Column(name = "CTR_POS_ID")
public int getCtrPosId() {
return ctrPosId;
} |
d9a83f05-4155-4a01-a6d4-1a3bd93101ee | 9 | public void transformMove() {
System.out.println("Coin.transformMove()" + this);
lastMovedCoin = this;
LudoRegion region = null;
path = new Path();
// if region 4 than
Cordenate from = new Cordenate(this.getBlockNo().getX(), this
.getBlockNo().getY());
MoveTo to = new MoveTo(this.getCenterX(), this.getCenterY());
path.getElements().add(to);
if (onFinalPath()) {
moveOnFinalPath(move);
} else {
region = LudoRegion.values()[(this.getBlockNo().getRegion() - 1) % 11];
int movesReamaning = move;
switch (region.axics()) {
case 1:
movesReamaning = movesReamaning + this.getBlockNo().getX()
- region.getMinX() + 1;
break;
case 2:
movesReamaning = movesReamaning + this.getBlockNo().getY()
- region.getMinY() + 1;
break;
case 3:
movesReamaning = region.getMinX() - this.getBlockNo().getX()
+ movesReamaning + 1;
break;
case 4:
movesReamaning = region.getMinY() - this.getBlockNo().getY()
+ movesReamaning + 1;
break;
}
moveToNextRegion(this.getBlockNo().getRegion(), movesReamaning);
}
synchronized (path) {
PathTransition transition = PathTransitionBuilder.create()
.duration(Duration.millis(move * 50)).autoReverse(false)
.cycleCount(1).node(this).path(path).build();
transition.play();
}
Stack<SimpleCordinate> undoList = new Stack<SimpleCordinate>();
ObservableList<PathElement> pathElements = path.getElements();
List<PathElement> tempList = new ArrayList<PathElement>();
tempList.addAll(pathElements);
for (PathElement pathElement : tempList) {
if (pathElement instanceof LineTo) {
undoList.push(new SimpleCordinate(
((LineTo) pathElement).getX(), ((LineTo) pathElement)
.getY()));
} else if (pathElement instanceof MoveTo) {
undoList.push(new SimpleCordinate(
((MoveTo) pathElement).getX(), ((MoveTo) pathElement)
.getY()));
}
undoPath = new Path();
SimpleCordinate cordinate = undoList.pop();
path.getElements().add(new MoveTo(cordinate.x, cordinate.y));
while (!undoList.empty()) {
cordinate = undoList.pop();
path.getElements().add(new LineTo(cordinate.x, cordinate.y));
}
}
SpriteMap.updateSprite(from, this.getBlockNo(), this);
} |
93fb3df6-5b85-488b-bb17-a7906bcc7aff | 3 | @Override
public void sendAllNow() throws IOException
{
if (isNotReady()) {
return;
}
while (!outbound.isEmpty())
{
send();
}
while (!bufferOut.isEmpty())
{
write();
}
} |
2f12f1f3-b7ad-45de-81c7-b2e881d3a103 | 1 | public KeyNoncePair(byte[] key) {
byte[] nonce = new byte[NONCE_SIZE];
for(int i = 0; i < NONCE_SIZE; i++) {
nonce[i] = key[i];
}
this.key = key;
this.nonce = nonce;
} |
816fcd45-46ae-4155-be31-14526b9039f6 | 1 | private void quicksort(final int p, final int r) {
if (p < r) {
final int q = partition(p, r);
quicksort(p, q);
quicksort(q + 1, r);
}
} |
d80f5bee-7755-4d2d-a9a0-4c97b34ed59b | 3 | public void end (String name) {
if (warmup) return;
long e = System.nanoTime();
long time = e - s;
Long oldTime = testTimes.get(name);
if (oldTime == null || time < oldTime) testTimes.put(name, time);
System.out.println(name + ": " + time / 1000000f + " ms");
} |
68099eb2-7efa-46bf-ab57-c6af712b4a07 | 8 | public double historicalEventExecute( double historicalEventTime){
historicalEvent tempEvent;
double gen = historicalEventTime;
if(currentEvent == null){
System.out.println("Sorry no historical event to execute");
return 0;
}
else{
dem.dgLog(10 , currentEvent.getGen(), currentEvent.getLabel());
switch(currentEvent.getType()){
case HE_POP_SIZE:
dem.setPopSizeByName(currentEvent.getGen(), currentEvent.getPopIndex()[0], (int) currentEvent.getParams()[0]);
break;
case HE_POP_SIZE_EXP:
dem.setPopSizeByName(currentEvent.getGen(), currentEvent.getPopIndex()[0], (int) (currentEvent.getParams()[1]+.5));
historicalNextExp(currentEvent);
break;
case HE_BOTTLENECK:
bottleneck.bottleNeckExecute(currentEvent.getPopIndex()[0],currentEvent.getParams()[0], (int) currentEvent.getGen());
break;
case HE_ADMIX:
dem.moveNodesByName(currentEvent.getPopIndex()[0], currentEvent.getPopIndex()[1], currentEvent.getParams()[0], currentEvent.getGen());
break;
case HE_MIGRATION:
migFactory.migrateDelete(currentEvent.getPopIndex()[1], currentEvent.getPopIndex()[0]);
migFactory.migrateAdd(currentEvent.getPopIndex()[1],currentEvent.getPopIndex()[0], currentEvent.getParams()[0]);
break;
case HE_SPLIT:
dem.moveNodesByName(currentEvent.getPopIndex()[1], currentEvent.getPopIndex()[0], 1, currentEvent.getGen());
dem.endPopByName(currentEvent.getPopIndex()[1]);
break;
case HE_SWEEP:
gen = sweeper.sweepExecute(currentEvent.getPopIndex()[0], currentEvent.getParams()[0], currentEvent.getGen(), currentEvent.getParams()[1], currentEvent.getParams()[2]);
break;
}
tempEvent = currentEvent;
currentEvent = currentEvent.getNext();
this.historicalFree(tempEvent);
return gen;
}
} |
f19dd241-99f9-493e-a90d-100682faa620 | 5 | public String getIdName(){
if(id < 10){
return "000" + id;
}
else if(id >= 10 && id < 100){
return "00" + id;
}
else if(id >= 100 && id < 1000){
return "0" + id;
}
else{
return "" + id;
}
} |
b591d797-7eff-4a26-b7af-8d35d033b8e7 | 5 | public URI crawl(URI currentLocation, final String needle) throws URISyntaxException, MalformedURLException,
InterruptedException, ExecutionException {
String urlContents = downloadContents(currentLocation);
visitedUrls.add(currentLocation);
if (urlContents.contains(needle)) {
return currentLocation;
} else {
for (String link : getAllLinks(urlContents)) {
final URI asUri = normalizeLink(currentLocation, link);
if (!visitedUrls.contains(asUri) && isInsideDomain(currentLocation, asUri)) {
URI result = crawl(asUri, needle);
if (result != null) {
return result;
}
}
}
}
return null;
} |
e7a76812-bfef-4bc3-972c-e6176dcb0c78 | 1 | public Map<String, Object> getConfiguration() {
@SuppressWarnings("unchecked")
Map<String, Object> config = (HashMap<String, Object>) servletContext.getAttribute(Constants.CONFIG);
// so unit tests don't puke when nothing's been set
if (config == null) {
return new HashMap<String, Object>();
}
return config;
} |
4f6ecef7-b70c-47d8-bb91-9c0d31982a4c | 8 | public int Run(RenderWindow App){
boolean Running = true;
Text scenario = new Text();
Font Font = new Font();
try {
Font.loadFromFile(Paths.get("rsc/font/mrsmonsterrotal.ttf"));
} catch (IOException e) {
e.printStackTrace();
return (-1);
}
int taille_Font = 27;
scenario.setFont(Font);
scenario.setCharacterSize(taille_Font);
scenario.setString("Quand on parle de zombies on pense souvent\n" +
" à d'effroyables prédateurs en quête de matière \n" +
"grise à ingurgiter. En réalité ces pauvres zombies\n" +
" sont en fait les proies d'un nouveau grand \n" +
"prédateur: les POULETS. En effet la maladie qui \n" +
"touche le monde entier depuis quelques années ne \n" +
"contamine que les êtres vivants doués d'un minimum\n " +
"d'intelligence, ce qui n'est pas le cas de ces\n " +
"gallinacés. Ces volatiles sont donc logiquement\n " +
"devenus l'espèce majoritaire sur la planète et \n" +
"cherchent à éliminer toute trace de notre \n" +
"ancienne civilisation en commencant par les \n" +
"individus les plus lents: les zombies. C'est \n" +
"anisi que ces morts-vivants sont devenus sujets \n" +
"à l'alektorophobie (la phobie des poulets). \n" +
"Aidez-donc notre ami Robert à se débarasser \n" +
"de ces créatures malfaisantes et sournoises,\n" +
" le tout en musique!!\n");
scenario.setPosition( App.getSize().x/2-scenario.getLocalBounds().width/2, 100);
long debut_bootsplash = System.currentTimeMillis();
int duree=45000;
while (System.currentTimeMillis()-debut_bootsplash<duree && Running)
{
//Verifying events
for (Event event : App.pollEvents()) {
{
// Window closed
if (event.type == event.type.CLOSED)
{
return (-1);
}
if(event.type == Event.Type.MOUSE_BUTTON_RELEASED) {
return 1;
}
//Key pressed
if (event.type == Event.Type.KEY_PRESSED)
{
event.asKeyEvent();
if (Keyboard.isKeyPressed(Keyboard.Key.ESCAPE))
return (-1);
else
{
return 1;
}
}
}
}
App.draw(scenario);
App.display();
//Clearing screen
App.clear();
}
//Never reaching this point normally, but just in case, exit the application
System.out.println("bootsplash finit");
return (1);
} |
72b74b7a-d264-4ba4-ae26-399883071eb5 | 8 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if((msg.amITarget(affected))
&&(mobs.contains(msg.source())))
{
if((msg.targetMinor()==CMMsg.TYP_BUY)
||(msg.targetMinor()==CMMsg.TYP_BID)
||(msg.targetMinor()==CMMsg.TYP_SELL)
||(msg.targetMinor()==CMMsg.TYP_LIST)
||(msg.targetMinor()==CMMsg.TYP_VALUE)
||(msg.targetMinor()==CMMsg.TYP_VIEW))
{
msg.source().tell(L("@x1 looks unwilling to do business with you.",affected.name()));
return false;
}
}
return super.okMessage(myHost,msg);
} |
15745ec3-56ef-4b1f-9a03-a852ea6d73cb | 1 | public void run(String[] args) throws FileNotFoundException, IOException {
Card card = PCSCManager.getCard();
if (card != null) {
String atr = Hex.printBytesHexa(card.getATR()
.getBytes());
Logger.log(card.toString() + "\n");
Logger.log(PCSCManager.getCardName(atr) + "\n");
Logger.log("ATR: " + atr + "\n");
} else {
Logger.log("Cartao inteligente nao conectado");
}
} |
ee0cf549-6c00-4c2e-9bb9-13efddaabfe0 | 0 | public formHelp() {
initComponents();
} |
93837e1b-9fcd-415a-876c-d86437097a7a | 0 | public void start(String msgIn) {
MSG = msgIn;
reset();
} |
02416eb2-408a-4b18-9b38-a1b7b43ef4df | 2 | public void clear() {
do {
CacheableNode cacheableNode = recent.popFront();
if (cacheableNode != null) {
cacheableNode.unlink();
cacheableNode.unlinkSub();
} else {
capacity = srcCapacity;
return;
}
} while (true);
} |
0d920aad-7765-4444-a4c7-899f4abd2da0 | 6 | public static <E extends Comparable<E>> void sortWithStack(Stack<E> stack) {
if(stack.isEmpty()) {
return;
}
Stack<E> auxStack = new Stack<E>();
while(!stack.isEmpty()) {
E item = stack.pop();
while(!auxStack.isEmpty() && auxStack.peek().compareTo(item)>0) {
E tmpItem = auxStack.pop();
stack.push(tmpItem);
}
auxStack.push(item);
}
Queue<E> tmpQueue = new LinkedList<E>();
while(!auxStack.isEmpty()) {
tmpQueue.offer(auxStack.pop());
}
while(!tmpQueue.isEmpty()) {
stack.push(tmpQueue.poll());
}
} |
6df6ac50-8ade-471c-88ae-d4038f824795 | 4 | public void addNodeSorted(treeNode newNode, treeNode curRoot) {
if (newNode.value < curRoot.value) {// add to left child tree
if (curRoot.leftLeaf != null) {
addNodeSorted(newNode, curRoot.leftLeaf);
} else {
curRoot.leftLeaf = newNode;
newNode.parent = curRoot;
}
}
if (newNode.value > curRoot.value) { // add to right child tree
if (curRoot.rightLeaf != null) {
addNodeSorted(newNode, curRoot.rightLeaf);
} else {
curRoot.rightLeaf = newNode;
newNode.parent = curRoot;
}
}
} |
512130ae-9e48-4605-8f56-3449207dddff | 4 | public CycObject readNart()
throws IOException {
CycNart cycNart = null;
int cfaslOpcode = read();
if (cfaslOpcode == CFASL_NIL) {
cycNart = CycObjectFactory.INVALID_NART;
isInvalidObject = true;
} else if (cfaslOpcode != CFASL_LIST) {
if (cfaslOpcode == CFASL_SYMBOL) {
String name = (String) readObject();
System.err.println("readNart, symbol=" + name);
}
throw new RuntimeException("reading nart, expected a list, found " + cfaslOpcode);
} else {
cycNart = new CycNart(readCycList());
}
if (trace == API_TRACE_DETAILED) {
debugNote("readNart: " + cycNart.toString());
}
return cycNart;
} |
5c9bf790-2f53-43c5-b812-770c0e15a0b3 | 5 | public static int upperBound(int key) {
int lower = 0, upper = dig.length - 1, ans = -1;
while (lower <= upper) {
int mid = (lower + upper) / 2;
if (key < dig[mid].s)
upper = mid - 1;
else {
lower = mid + 1;
ans = mid;
}
}
if (ans >= 0 && key >= dig[ans].s && key <= dig[ans].e)
return ans;
return -1;
} |
9064702f-678e-4035-82e6-29e2bcd23d02 | 8 | private void qsort(Object[] items, Comparator comparator, int l, int r)
{
final int M = 4;
int i;
int j;
Object v;
if((r - l) > M)
{
i = (r + l) / 2;
if(comparator.compare(items[l], items[i]) > 0)
{
swap(items, l, i);
}
if(comparator.compare(items[l], items[r]) > 0)
{
swap(items, l, r);
}
if(comparator.compare(items[i], items[r]) > 0)
{
swap(items, i, r);
}
j = r - 1;
swap(items, i, j);
i = l;
v = items[j];
while(true)
{
while(comparator.compare(items[++i], v) < 0)
{
}
while(comparator.compare(items[--j], v) > 0)
{
}
if(j < i)
{
break;
}
swap(items, i, j);
}
swap(items, i, r - 1);
qsort(items, comparator, l, j);
qsort(items, comparator, i + 1, r);
}
} |
9ce64c24-797e-4a11-8db0-2fd50b4327ef | 0 | private void setupMaps(InputMap input_map, ActionMap action_map) {
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.SHIFT_MASK, false), "left");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.CTRL_MASK, false), "left");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.CTRL_MASK + Event.SHIFT_MASK, false), "left");
action_map.put("left", leftAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.SHIFT_MASK, false), "right");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.CTRL_MASK, false), "right");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.CTRL_MASK + Event.SHIFT_MASK, false), "right");
action_map.put("right", rightAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.SHIFT_MASK, false), "down");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK, false), "down");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.CTRL_MASK + Event.SHIFT_MASK, false), "down");
action_map.put("down", downAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.SHIFT_MASK, false), "up");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK, false), "up");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.CTRL_MASK + Event.SHIFT_MASK, false), "up");
action_map.put("up", upAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK, false), "cut");
action_map.put("cut", cutAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK, false), "paste");
action_map.put("paste", pasteAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK, false), "copy");
action_map.put("copy", copyAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0, false), "end");
action_map.put("end", endAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0, false), "home");
action_map.put("home", homeAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false), "delete");
action_map.put("delete", deleteAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0, false), "backspace");
action_map.put("backspace", backspaceAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK, false), "select_inverse");
action_map.put("select_inverse", selectInverseAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Event.CTRL_MASK, false), "select_all");
action_map.put("select_all", selectAllAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0, false), "change_focus");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, Event.SHIFT_MASK, false), "change_focus");
action_map.put("change_focus", changeFocusAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "insert_and_split");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, Event.SHIFT_MASK, false), "insert_and_split");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, Event.CTRL_MASK, false), "insert_and_split");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, Event.CTRL_MASK + Event.SHIFT_MASK, false), "insert_and_split");
action_map.put("insert_and_split", insertAndSplitAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false), "promote_demote");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, Event.SHIFT_MASK + Event.SHIFT_MASK, false), "promote_demote");
action_map.put("promote_demote", promoteDemoteAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK, false), "select_none");
action_map.put("select_none", selectNoneAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_M, Event.CTRL_MASK, false), "merge");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_M, Event.CTRL_MASK + Event.SHIFT_MASK, false), "merge");
action_map.put("merge", mergeAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0, false), "expansion");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.SHIFT_MASK, false), "expansion");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.CTRL_MASK, false), "expansion");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.CTRL_MASK + Event.SHIFT_MASK, false), "expansion");
action_map.put("expansion", toggleExpansionAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0, false), "comments");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.SHIFT_MASK, false), "comments");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.CTRL_MASK, false), "comments");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.CTRL_MASK + Event.SHIFT_MASK, false), "comments");
action_map.put("comments", toggleCommentAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0, false), "editable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, Event.SHIFT_MASK, false), "editable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, Event.CTRL_MASK, false), "editable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, Event.CTRL_MASK + Event.SHIFT_MASK, false), "editable");
action_map.put("editable", toggleEditableAction);
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0, false), "moveable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, Event.SHIFT_MASK, false), "moveable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, Event.CTRL_MASK, false), "moveable");
input_map.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, Event.CTRL_MASK + Event.SHIFT_MASK, false), "moveable");
action_map.put("moveable", toggleMoveableAction);
} |
37253f16-d0bb-4cdb-a11c-2261a2d7f7bd | 4 | protected HsqlDaoBase(HsqlUnitOfWork uow) {
super(uow);
try {
Connection connection = uow.getConnection();
ResultSet rs = connection.getMetaData().getTables(null, null, null, null);
boolean exist = false;
stmt =connection.createStatement();
while(rs.next())
{
if(rs.getString("TABLE_NAME").equalsIgnoreCase(getTableName()))
{
exist = true;
break;
}
}
if(!exist)
{
stmt.executeUpdate(getCreateQuery());
}
insert = connection.prepareStatement(getInsertQuery());
update = connection.prepareStatement(getUpdateQuery());
delete = connection.prepareStatement(""
+ "delete from "+getTableName()+" where id=?");
selectId = connection.prepareStatement(""
+ "select * from "+getTableName()+" where id=?");
select = connection.prepareStatement(""
+ "select * from "+getTableName());
} catch (SQLException e) {
e.printStackTrace();
}
} |
f6047091-1c83-4e93-bd54-888cdb3a13a9 | 5 | public int getLanguageID( TLanguageFile checkFile )
{
int back = UNDEFINED_LANG ;
if ( checkFile != null )
{
if (checkFile.hasLanguageExtension() )
{
boolean found = false ;
int t = 0 ;
int len = langVersions.size() ;
while ( ( !found ) && ( t < len ) )
{
if ( checkFile.isSameVersion( ( TLanguageFile ) langVersions.get( t ) ) )
{
found = true ;
back = t ;
}
else
{
t++ ;
}
}
}
else // no extension => default language
{
back = DEFAULT_LANG ;
}
}
return back ;
} |
ed70cfa2-c2c7-4b96-b065-76bd38c0e210 | 4 | @Test
public void adenAskEmployeePriceTest(){
LocalDate date = LocalDate.now();
int dayOfWeek = date.getDayOfWeek();
boolean weekend = false;
Canteen c2 = new Canteen(new CanteenData(CanteenNames.ADENAUERRING, 0));
int dayShift = (dayOfWeek + 2) % 7;
if(dayOfWeek == 0 || (dayOfWeek == 6)) { // weekends
c2 = new Canteen(new CanteenData(CanteenNames.ADENAUERRING, dayShift));
weekend = true;
}
userInput.add("hi");
userInput.add("random");
userInput.add("yes");
userInput.add("no");
if( !weekend ){
userInput.add("what's in canteen today");
}else {
if(dayShift == 1) {
userInput.add("what's in canteen next monday");
}else userInput.add("what's in canteen next tuesday");
}
String meal = c2.getCanteenData().getLines().get(0).getTodayMeals().get(0).getMealName(); // line one
userInput.add("how much is " + meal);
// line two is closed now
meal = c2.getCanteenData().getLines().get(2).getTodayMeals().get(0).getMealName();// line three
userInput.add("how much costs " + meal);
meal = c2.getCanteenData().getLines().get(3).getTodayMeals().get(0).getMealName();// line four
userInput.add("what's the price of " + meal);
meal = c2.getCanteenData().getLines().get(8).getTodayMeals().get(0).getMealName();// line six
userInput.add("what is the price of " + meal);
/*ArrayList<MealData> cafeMeals = c2.getCanteenData().getLines().get(6).getTodayMeals(); // cafeteria
for( MealData m : cafeMeals ){
meal = m.getMealName();
userInput.add("how much is " + meal);
}*/
/* side dish test */
userInput.add("how much is blattSalat");
//userInput.add("how much costs currywurst");
//userInput.add("what's the price of belgische pommes");
userInput.add("what is the price of country potatoes");
runMainActivityWithTestInput(userInput);
String strAmount = String.valueOf(3.65);
assertTrue(nlgResults.get(5).contains(strAmount));// line one price
float price = c2.getCanteenData().getLines().get(2).getTodayMeals().get(0).getE_price();
strAmount = String.valueOf(price);
assertTrue( nlgResults.get(6).contains(strAmount) );
price = c2.getCanteenData().getLines().get(3).getTodayMeals().get(0).getE_price();
strAmount = String.valueOf(price);
assertTrue(nlgResults.get(7).contains(strAmount));
price = c2.getCanteenData().getLines().get(8).getTodayMeals().get(0).getE_price();
strAmount = String.valueOf(price);
assertTrue(nlgResults.get(8).contains(strAmount));
/*boolean correct = false;
for(int i = 1; i <= cafeMeals.size(); i++) {
price = cafeMeals.get(i - 1).getE_price();
strAmount = String.valueOf(price);
if(nlgResults.get(i + 8).contains(strAmount)){
correct = true;
}else correct = false;
}
assertTrue(correct);
*/
strAmount = String.valueOf(0.95);
//System.out.println(nlgResults.get(7 + cafeMeals.size()));
assertTrue(nlgResults.get(9).contains(strAmount)); // blattsalat is always 0.75
/*// no record for curry wurst employee price
strAmount = String.valueOf(1.7);
assertTrue(nlgResults.get(10 + cafeMeals.size()).contains(strAmount));
strAmount = String.valueOf(1.15);// belgische pommes
assertTrue(nlgResults.get(10 + cafeMeals.size()).contains(strAmount));*/
strAmount = String.valueOf(1.1);// country potatoes
assertTrue(nlgResults.get(10).contains(strAmount));
} |
b8e2edfa-f6b5-40a7-81e2-4460672e483f | 7 | public Object readParamInXmlFile(String paramName){
ArrayList<String> params = new ArrayList<String>();
try{
File fXmlFile = new File(fileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc;
doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(paramName);
for (int i = 0; i < nList.getLength(); i++){
params.add(nList.item(i).getTextContent());
}
} catch (ParserConfigurationException e) {
Logger.getLogger(ReadConfigFile.class).debug("EXCEPTION while reading parameters : "+ e.getMessage()+
" Description : "+ e.toString());
} catch (SAXException | IOException e) {
Logger.getLogger(ReadConfigFile.class).debug("EXCEPTION while reading parameters : "+ e.getMessage()+
" Description : "+ e.toString());
}
if ((!paramName.equalsIgnoreCase("keyWordsInURL")) && (!paramName.equalsIgnoreCase("exclusionKeyWords"))){
if(params.size()>0){
if(params.get(0).length()>0){
return params.get(0);
}else{
return null;
}
} else {
return null;
}
}
return params;
} |
bb3247a2-4c1e-4efc-9fbb-32a5265d67b6 | 7 | public void foward(float delta, Level level, int currentRoom) {
Float x,y,z,minX,maxX,minY,maxY;
minY = level.getRoomList().get(currentRoom).getPos().getY();
maxY = level.getRoomList().get(currentRoom).getPos().getY() + level.getRoomList().get(currentRoom).getDy();
minX = level.getRoomList().get(currentRoom).getPos().getX();
maxX = level.getRoomList().get(currentRoom).getPos().getX() + level.getRoomList().get(currentRoom).getDx();
walking = true;
//Checking if the entity is inside the room boundery.
if(getPos().getX() + ((getSpeed() * Math.cos(getOrientation())) * delta) >= minX && getPos().getX() + ((getSpeed() * Math.cos(getOrientation())) * delta) <= maxX){
x = (float) ((getSpeed() * Math.cos(getOrientation()) * delta) + getPos().getX());
}else{
//Moving the payer 0.01f from the wall
if(getSpeed() * Math.cos(getOrientation()) * delta > 0){
x = level.getRoomList().get(currentRoom).getPos().getX() + level.getRoomList().get(currentRoom).getDx() - 0.01f;
}else{
x = level.getRoomList().get(currentRoom).getPos().getX() + 0.01f;
}
}
//Checking if the entity is inside the room boundery.
if(getPos().getY() + ((getSpeed() * Math.sin(getOrientation())) * delta) >= minY && getPos().getY() + ((getSpeed() * Math.sin(getOrientation())) * delta) <= maxY){
y = (float) ((getSpeed() * Math.sin(getOrientation()) * delta) + getPos().getY());
}else{
//Moving the payer 0.01f from the wall
if(getSpeed() * Math.sin(getOrientation()) * delta > 0){
y = level.getRoomList().get(currentRoom).getPos().getY() + level.getRoomList().get(currentRoom).getDy() - 0.01f;
}else{
y = level.getRoomList().get(currentRoom).getPos().getY() + 0.01f;
}
}
z = 0.0f + getPos().getZ();
//Checking if the new X,Y,Z is equal to the old X,Y,Z. If so then object haven't be walking.
if(getPos().equals(new Point(x,y,z)) == true){
walking = false;
}
setPos(x, y, z);
} |
57e9a382-9e3a-4f66-863d-2152ba7f48b6 | 6 | public void initialize() {
//finding out number of possible tiles
File tilelist;
try {
tilelist = new File(getClass().getResource("resources/tiles.txt").toURI());
} catch(URISyntaxException e) {
tilelist = new File(getClass().getResource("resources/tiles.txt").getPath());
}
int tilelength = 0;
Scanner scan;
try {
scan = new Scanner(tilelist);
while (scan.hasNextLine()) {
if (!(scan.nextLine()).isEmpty()) {
tilelength++;
}
}
scan.close();
} catch (FileNotFoundException e1) {
System.out.println("Tile declarations not found");
}
//setting image array size to number of tiles
baseimages = new Image[tilelength];
for (int i = 0; i < tilelength; i++) {
try {
baseimages[i] = ImageIO.read(getClass().getResource("resources/" + i + ".png"));
} catch (Exception e) {
System.out.println("Image not found");
}
}
} |
58455515-d239-43f5-8e49-ab8acaf757e0 | 9 | public static boolean start(RootDoc root) {
// Get some options
String title = "My Ant Tasks";
String[] templates = null;
String templatesDir = ".";
String[] outputdirs = new String[] { "."};
String[][] options = root.options();
for (int opt = 0; opt < options.length; opt++) {
if (options[opt][0].equalsIgnoreCase("-doctitle")) {
title = options[opt][1];
} else if (options[opt][0].equalsIgnoreCase("-templates")) {
templates = options[opt][1].split(","); // comma-separated
// filenames
} else if (options[opt][0].equalsIgnoreCase("-templatesdir")) {
templatesDir = options[opt][1]; // comma-separated filenames
} else if (options[opt][0].equalsIgnoreCase("-d")) {
outputdirs = options[opt][1].split(",");
}
}
// Init Velocity-template Generator
VelocityFacade velocity = null;
try {
velocity = new VelocityFacade(new File("."), templatesDir);
} catch (Exception e) {
e.printStackTrace();
}
// Set global parameters to the templates
velocity.setAttribute("velocity", velocity);
velocity.setAttribute("title", title);
velocity.setAttribute("antroot", new AntRoot(root));
for (int i = 0; i < templates.length; i++) {
try {
if (outputdirs.length > i)
velocity.setOutputDir(new File(outputdirs[i]));
velocity.eval(templates[i], new OutputStreamWriter(System.out));
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
} |
7267bf7e-d7b0-4b96-b22f-26c66cc59534 | 8 | public static List<Query> loadQueriesFromFile(String filePath) {
List<Query> queries = new ArrayList<Query>();
InputStream fis = null;
BufferedReader reader = null;
try {
// fis = ClassLoader.getSystemResourceAsStream(filePath);
fis = new FileInputStream(filePath);
reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().length() > 0 && !line.startsWith("#")) {
Query query = parseQuery(line);
if (query != null) {
queries.add(query);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (reader != null)
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return queries;
} |
0cbe6518-dbcd-434c-9893-07c19274a968 | 2 | public boolean estaEnExtremos(){
boolean resp= false;
if (siguiente==null || previo == null)
resp = true;
return resp;
} |
88cf500f-f075-4c99-be15-77a3480aec54 | 2 | public void applySortConfig(String config) {
int result = applySortConfigInternal(config);
if (result == 0) {
notifyOfSortCleared();
} else if (result == 1) {
sort();
}
} |
4376fa8e-4582-431f-8a0b-b8d4aa303d98 | 3 | @SuppressWarnings("unchecked")
@Override
public double getScore(Object userAnswer) {
if (userAnswer == null)
return 0;
String ans = (String) userAnswer;
ArrayList<String> trueAns = (ArrayList<String>) answer;
for (int i = 0; i < trueAns.size(); i++) {
if (trueAns.get(i).equals(ans))
return score;
}
return 0;
} |
57d1ce6f-cb71-42e3-9ccb-dfecc28dfb81 | 2 | private String[] letterPairs(String word)
{
String[] result = new String[0];
int numPairs = word.length() - 1;
if (numPairs > 0)
{
result = new String[numPairs];
for (int letterCounter = 0; letterCounter < numPairs; letterCounter++)
{
result[letterCounter] = word.substring(letterCounter, letterCounter + 2);
}
}
return result;
} |
f8eb12fd-fb99-44dd-b4e4-11265f9a0593 | 1 | public int deleteUser(String userID) {
try {
// Erforderlicher SQL-Befehl
String sqlStatement = "DELETE FROM bookworm_database.users WHERE id = "
+ userID + ";";
// SQL-Befehl wird ausgeführt
successful = mySQLDatabase.executeSQLUpdate(sqlStatement);
return successful;
} catch (Exception e) {
System.out.println(e.toString());
// Ein Dialogfenster mit entsprechender Meldung soll erzeugt werden
String errorText = "Datenbank-Fehler beim Löschen eines Datensatzes";
errorMessage.showMessage(errorText);
successful = 0;
return successful;
} finally {
// offene Verbindungen werden geschlossen
mySQLDatabase.closeConnections();
}
} |
a793ec8e-051d-426d-85ae-2458d0076939 | 4 | public int compareTo(Instruction instr) {
if (addr != instr.addr)
return addr - instr.addr;
if (this == instr)
return 0;
do {
instr = instr.nextByAddr;
if (instr.addr > addr)
return -1;
} while (instr != this);
return 1;
} |
73c41b13-b843-4d08-8846-07251e5ef131 | 8 | @Override
public String toString() {
String s = getSignature();
for (String perm : permissions)
s += " " + perm;
if (this.isSource || this.isSink || this.isNeitherNor)
s += " ->";
if (this.isSource)
s += " _SOURCE_";
if (this.isSink)
s += " _SINK_ ";
if (this.isNeitherNor)
s += " _NONE_";
if (this.category != null)
s += "|" + category;
return s;
} |
9bb3d6eb-7e4e-4a69-a822-9bc2f4f680ac | 3 | @Override
public void postInfo() {
//before the beginning of the game get all players to rotate and 'find' all of the
//in game components
if(playMode == PlayMode.BEFORE_KICK_OFF){
canSeeNothingAction();
}else if(playMode == PlayMode.CORNER_KICK_OWN || playMode == PlayMode.KICK_OFF_OTHER){
markOtherPlayer(); // move close to another player to help intercept the ball when play continues
}else{ // continue with normal behaviour
behaviour();
}
} |
46267ba6-4ea0-488d-9515-debe0bb78c4a | 5 | public void merge(int A[], int m, int B[], int n) {
int j = m-1;
int k = n-1;
for (int i =m + n -1 ;i>=0;i--)
{
if (j >=0 && k >=0)
{
if (A[j] >= B[k])
A[i] = A[j--];
else A[i] = B[k--];
}
else if (j >=0) A[i] = A[j--];
else A[i] = B[k--];
}
} |
bdd6b8af-08ff-49a1-bc15-1138dda3df13 | 0 | public void animate() {
Timeline mainAnimation = new Timeline();
mainAnimation.getKeyFrames().addAll(
new KeyFrame(Duration.millis(0), new KeyValue(
glow.radiusProperty(), 1d)),
new KeyFrame(Duration.millis(5000), new KeyValue(glow
.radiusProperty(), 13d)),
new KeyFrame(Duration.millis(10000), new KeyValue(glow
.radiusProperty(), 0d)),
new KeyFrame(Duration.millis(1000), new KeyValue(shadow
.radiusProperty(), 5d)),
new KeyFrame(Duration.millis(1000), new KeyValue(boxBlur
.iterationsProperty(), 10d)),
new KeyFrame(Duration.millis(0), new KeyValue(paths
.opacityProperty(), 0.6d)),
new KeyFrame(Duration.millis(5000), new KeyValue(paths
.opacityProperty(), 1d)),
new KeyFrame(Duration.millis(10000), new KeyValue(paths
.opacityProperty(), 0.6d))
);
mainAnimation.setCycleCount(-1);
animations.add(mainAnimation);
mainAnimation.play();
animateParticle(particle1, path);
animateParticle(particle2, path2);
animateParticle(particle3, path3);
animateParticle(particle4, path4);
animateParticle(particle5, path5);
} |
76814562-fb32-4070-913f-d87bb3743ce5 | 7 | private void initMap() {
int[] moves = { 0,-1, 1,0, 0,1, -1,0 };
for( int i = 0; i < 11; i++ ) {
for( int j = 0; j < 11; j++ ) {
Point currentPos = new Point( i, j );
ArrayList<Point> nextPoss = new ArrayList<Point>(5);
nextPoss.add( currentPos );
for( int p = 0; p < 8; p = p + 2 ) {
Point newPos = (Point) currentPos.clone();
newPos.translate( moves[p], moves[p+1] );
if( !(newPos.x >= 0) || !(newPos.x < 11) ) {
newPos.x = (newPos.x+11) % 11;
}
else {
if( !(newPos.y >= 0) || !(newPos.y < 11) ) {
newPos.y = (newPos.y+11) % 11;
}
}
nextPoss.add( newPos );
}
nextPosPositions.put( currentPos, nextPoss );
}
}
} |
bdb1a335-4ba4-4e3f-92c8-1e55b60a4737 | 4 | @Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
else if (obj == null || obj.getClass() != this.getClass())
return false;
CoordXZ test = (CoordXZ)obj;
return test.x == this.x && test.z == this.z;
} |
22cf5a54-0e73-4e53-b18c-ae5e5303d3cc | 7 | public void tick()
{
super.tick();
if(lifetime > 0)
{
lifetime--;
}
else
{
remove = true;
}
for(Entity e : level.entities)
{
if(this != e)
{
if(this.x <= (e.x+e.sx) && (this.x+this.sx) >= e.x && this.y >= (e.y+e.sy) && (this.y+this.sy) >= e.y)
{
this.remove = true;
e.health -= damage;
}
}
}
} |
cef61a05-9364-49fe-af73-cf183970ddf7 | 8 | public void init() {
if (el.winwidth==0) {
// get width/height from applet dimensions
el.winwidth=getWidth();
el.winheight=getHeight();
}
initCanvas();
if (!el.view_initialised) {
exitEngine("Canvas settings not initialised, use setCanvasSettings().");
}
if (!i_am_applet) {
jre.createWindow(this,jre.win_decoration);
}
//setAudioLatency(getAudioLatencyPlatformEstimate());
canvas = new JGCanvas(el.winwidth,el.winheight);
jre.canvas = canvas;
el.initPF();
jre.clearKeymap();
canvas.addMouseListener(jre);
canvas.addMouseMotionListener(jre);
canvas.addFocusListener(jre);
// set bg color so that the canvas's padding is in the proper color
canvas.setBackground(getAWTColor(el.bg_color));
if (jre.my_win!=null) jre.my_win.setBackground(getAWTColor(el.bg_color));
// determine default font size (unscaled)
el.msg_font = new JGFont("Helvetica",0,
(int)(16.0/(640.0/(el.tilex * el.nrtilesx))));
setLayout(new FlowLayout(FlowLayout.LEADING,0,0));
add(canvas);
if (!JGObject.setEngine(this)) {
/** yes, you see that right. I've used a random interface with a
* method that allows me to pass a Graphics. We shall move this
* stuff to JGCanvas later, i suppose */
canvas.setInitPainter(new ListCellRenderer () {
public Component getListCellRendererComponent(JList d1,
Object value, int d2, boolean initialise, boolean d4) {
Graphics g = (Graphics) value;
//if (initialise) {
// g.setColor(bg_color);
// g.fillRect(0,0,width,height);
//}
setFont(g,el.msg_font);
setColor(g,el.fg_color);
drawString(g,"JGame is already running in this VM",
el.viewWidth()/2,el.viewHeight()/3,0,false);
return null;
} } );
return;
}
el.is_inited=true;
canvas.setInitPainter(new ListCellRenderer () {
public Component getListCellRendererComponent(JList d1,
Object value, int d2, boolean initialise, boolean d4) {
Graphics g = (Graphics) value;
//if (initialise) {
// g.setColor(bg_color);
// g.fillRect(0,0,width,height);
//}
setFont(g,el.msg_font);
setColor(g,el.fg_color);
JGImage splash = el.existsImage("splash_image") ?
el.getImage("splash_image") : null;
if (splash!=null) {
JGPoint splash_size=getImageSize("splash_image");
drawImage(g,viewWidth()/2-splash_size.x/2,
viewHeight()/4-splash_size.y/2,"splash_image",
false);
}
drawString(g,canvas.progress_message,
viewWidth()/2,viewHeight()/2,0,false);
//if (canvas.progress_message!=null) {
//drawString(g,canvas.progress_message,
// viewWidth()/2,2*viewHeight()/3,0);
//}
// paint the right hand side black in case the bar decreases
setColor(g,el.bg_color);
drawRect(g,(int)(viewWidth()*(0.1+0.8*canvas.progress_bar)),
(int)(viewHeight()*0.6),
(int)(viewWidth()*0.8*(1.0-canvas.progress_bar)),
(int)(viewHeight()*0.05), true,false, false);
// left hand side of bar
setColor(g,el.fg_color);
drawRect(g,(int)(viewWidth()*0.1), (int)(viewHeight()*0.6),
(int)(viewWidth()*0.8*canvas.progress_bar),
(int)(viewHeight()*0.05), true,false, false);
// length stripes
drawRect(g,(int)(viewWidth()*0.1), (int)(viewHeight()*0.6),
(int)(viewWidth()*0.8),
(int)(viewHeight()*0.008), true,false, false);
drawRect(g,(int)(viewWidth()*0.1),
(int)(viewHeight()*(0.6+0.046)),
(int)(viewWidth()*0.8),
(int)(viewHeight()*0.008), true,false, false);
drawString(g,canvas.author_message,
viewWidth()-16,
viewHeight()-getFontHeight(g,el.msg_font)-10,
1,false);
return null;
} } );
if (jre.my_win!=null) {
jre.my_win.setVisible(true);
jre.my_win.validate();
// insets are known, resize window
jre.setWindowSize(jre.win_decoration);
}
// initialise keyboard handling
canvas.addKeyListener(jre);
canvas.requestFocus();
thread = new Thread(new JGEngineThread());
thread.start();
} |
e8c38d7b-a166-4017-af81-f6190c57b2ec | 8 | protected boolean meetsCriteria(Entity e) {
boolean works = true;
if(requiredComponents != null)
for(Class<? extends Component> comp : requiredComponents) {
if(!e.has(comp)) works = false;
}
if(bannedComponents != null)
for(Class<? extends Component> comp : bannedComponents) {
if(e.has(comp)) works = false;
}
return works;
} |
0b71ecd6-d74a-47d4-a9f2-7fa6ba35ade5 | 9 | @Override
public boolean equals(Object o) {
if (! (o instanceof PoliLine)) {
return false;
}
Iterator<Point> other = ((PoliLine) o).iterator();
boolean started = false;
Iterator<Point> me = this.iterator();
if (! me.hasNext()) {
return (! other.hasNext());
}
Point otherFirst = other.next();
while (other.hasNext()) {
if (! me.hasNext()) {
if (started) {
me = iterator();
} else {
return false;
}
}
Point mine = me.next();
if (started) {
if (!other.hasNext() || ! mine.equals(other.next())) {
return false;
}
} else {
if (mine.equals(otherFirst)) {
started = true;
}
}
}
return started;
} |
0471d22e-fc0c-4ed7-8bfc-d326a779a3a1 | 3 | public void addRoute(String path, Callback callback) {
URI uri;
try {
uri = new URI(path);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("invalid URI format of parameter `path`");
}
if (!TextUtils.isEmpty(uri.getScheme())) {
if (mRoutes.containsKey(uri.getScheme())) {
mRoutes.get(uri.getScheme()).add(new Route(uri, callback));
} else {
Vector<Route> urls = new Vector<Route>();
urls.add(new Route(uri, callback));
mRoutes.put(uri.getScheme(), urls);
}
}
} |
2fc4a2fa-f8e3-49ca-aa3e-97b53aa071ad | 8 | final void method3983(int i, int i_63_, int i_64_, boolean[][] bools,
boolean bool, int i_65_) {
anInt5151 = -1;
int i_66_ = 0;
float[] fs = new float[aClass262_5149.getSize(0)];
for (Class348_Sub1 class348_sub1
= (Class348_Sub1) aClass262_5149.getFirst(4);
class348_sub1 != null;
class348_sub1
= (Class348_Sub1) aClass262_5149.nextForward((byte) 40))
fs[i_66_++] = class348_sub1.method2721(-65);
q(fs);
for (int i_67_ = 0; i_67_ < i_64_ + i_64_; i_67_++) {
for (int i_68_ = 0; i_68_ < i_64_ + i_64_; i_68_++) {
if (bools[i_67_][i_68_]) {
int i_69_ = i - i_64_ + i_67_;
int i_70_ = i_63_ - i_64_ + i_68_;
if (i_69_ >= 0 && i_69_ < ((s) this).anInt4587
&& i_70_ >= 0 && i_70_ < ((s) this).anInt4590)
method3979(i_69_, i_70_);
}
}
}
} |
f9df3afe-adca-4b81-a659-74eeeb7c0613 | 1 | public String getDbProperty(String key) {
Properties properties = new Properties();
try {
FileInputStream fileInputStream = new FileInputStream(
getClass().getClassLoader().getResource(".").getPath() + File.separator
+ "resources" + File.separator
+ DB_CONFIGURATION_FILE);
properties.load(fileInputStream);
} catch (IOException e) {
m_logger.error(e.getMessage(), e);
}
String value = properties.getProperty(key);
return value;
} |
12945ad8-2232-4567-bdb7-17ee51667c6c | 1 | public static void deleteCustomer(Integer ID) {
Database db = dbconnect();
try {
String query = "UPDATE customer SET bDeleted = 1 "
+ "WHERE CID = ?";
db.prepare(query);
db.bind_param(1, ID.toString());
db.executeUpdate();
db.close();
} catch(SQLException e){
Error_Frame.Error(e.toString());
}
} |
350c39d9-49ce-434c-971d-0cc2600c85d2 | 2 | public Matrix4f mul(Matrix4f r){
Matrix4f res = new Matrix4f();
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
res.set(i,j,m[i][0] * r.get(0,j) +
m[i][1] * r.get(1,j) +
m[i][2] * r.get(2,j) +
m[i][3] * r.get(3,j));
}
}
return res;
} |
553578b1-1dee-4425-8f1d-26b18df6e22d | 9 | public static void main(String[] args) {
Scanner Terminal = new Scanner(System.in);
Scanner Terminal2 = new Scanner(System.in);
int choice1;
int choice2;
int pin = 0;
int pinCheck;
double balance = 0;
double deposit;
double withdrawal;
String firstName = null;
String lastName = null;
System.out.println("Welcome to Mike Banks Automated Teller Machine...");
System.out.println("Do you already have an account set up?");
System.out.println("Enter 1: Yes");
System.out.println("Enter 2: No");
choice1 = Terminal.nextInt();
if(choice1 == 2){
System.out.println("Enter Your First Name:");
firstName = Terminal2.nextLine();
System.out.println("Enter Your Last Name:");
lastName = Terminal2.nextLine();
System.out.println("Enter a 4 Digit Pin.");
pin = Terminal.nextInt();
System.out.println("Enter a starting balance. ex~ 123.45");
balance = Terminal.nextDouble();
}
Account user = new Account(firstName, lastName, pin, balance);
System.out.println("Verify your Pin:");
pinCheck = Terminal.nextInt();
if(pinCheck == user.getPin()){
System.out.println("What would you like to do?");
System.out.println("Enter 1: Check your Balance.");
System.out.println("Enter 2: Make a Deposit.");
System.out.println("Enter 3: Make a Withdrawal.");
System.out.println("Enter 6: LogOut");
choice2 = Terminal.nextInt();
while(choice2 != 6){
if(choice2 == 1){
System.out.println("Your current balance is: $" + user.getBalance());
}
if(choice2 == 2){
System.out.println("Enter the amount you wish to deposit. ex~ 123.45");
deposit = Terminal.nextDouble();
if(deposit < 0){
System.out.println("Your Transaction cannot be processed");
}
else{
user.deposit(deposit);
System.out.println("Your transaction completed successfully");
}
}
if(choice2 == 3){
System.out.println("Enter the amount you wish to withdraw. ex~ 123.45");
withdrawal = Terminal.nextDouble();
if(withdrawal < 0){
System.out.println("Your Transaction cannot be processed");
}
else if(withdrawal > user.getBalance()){
System.out.println("You don't have that much money in your account.");
System.out.println("Your Transaction cannot be processed. ");
}
else{
user.withdrawal(withdrawal);
System.out.println("Your transaction completed successfully");
}
}
System.out.println("What would you like to do now?");
System.out.println("Enter 1: Check your Balance.");
System.out.println("Enter 2: Make a Deposit.");
System.out.println("Enter 3: Make a Withdrawal.");
System.out.println("Enter 6: LogOut");
choice2 = Terminal.nextInt();
}
}
else{
System.out.println("The Pin you entered is incorrect.");
}
System.out.println("Thank you for your service. Goodbye!");
} |
6fa45866-f456-4a65-af89-36f278ba1786 | 3 | public final EsperParser.vartype_return vartype() throws RecognitionException {
EsperParser.vartype_return retval = new EsperParser.vartype_return();
retval.start = input.LT(1);
Object root_0 = null;
Token set44=null;
Object set44_tree=null;
try {
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:58:9: ( VARINT | VARSTRING | VARTRANSREAL )
// C:\\Users\\Alex\\Dropbox\\EclipseWorkspace\\esper-compiler\\src\\compiler\\Esper.g:
{
root_0 = (Object)adaptor.nil();
set44=(Token)input.LT(1);
if ( (input.LA(1) >= VARINT && input.LA(1) <= VARTRANSREAL) ) {
input.consume();
adaptor.addChild(root_0,
(Object)adaptor.create(set44)
);
state.errorRecovery=false;
}
else {
MismatchedSetException mse = new MismatchedSetException(null,input);
throw mse;
}
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
} |
10a79435-ac0c-412e-98a3-1a83126ddd34 | 4 | static String getPlatformFont() {
if(SWT.getPlatform() == "win32") {
return "Arial";
} else if (SWT.getPlatform() == "motif") {
return "Helvetica";
} else if (SWT.getPlatform() == "gtk") {
return "Baekmuk Batang";
} else if (SWT.getPlatform() == "carbon") {
return "Arial";
} else { // photon, etc ...
return "Verdana";
}
} |
a2754649-4b50-4017-8c6e-ff46541d0bd2 | 6 | public final Token readToken() {
while (this.position < this.expression.length()) {
if (Character.isWhitespace(this.expression.charAt(this.position)))
++this.position;
else
break;
}
if (this.position == this.expression.length())
return null;
String input = this.expression.substring(this.position);
/*
final class Match {
private final Matcher matcher;
private final TokenRule lexeme;
public Match(Matcher match, TokenRule lexeme) {
this.matcher = match;
this.lexeme = lexeme;
}
public Matcher getMatcher() {
return this.matcher;
}
public TokenRule getLexeme() {
return this.lexeme;
}
}
*/
for (TokenRule rule : this.tokenRules()) {
Matcher m = rule.regex().matcher(input);
if (!m.find())
continue;
//Match match = new Match(m, rule);
this.position += m.group().length();
String value = m.group();
if (rule.mutator() != null)
value = rule.mutator().mutate(value);
return new Token(rule.tokenType(), rule.tokenSubType(), value);
}
//StreamSupport.stream(this.tokenRules().spliterator(), false).
/*
var match = this.TokenRules.Select(l => new { Match = l.Regex.Match(input), Lexeme = l })
.Where(m => m.Match != null && m.Match.Success)
.GroupBy(m => m.Match.Length)
.OrderByDescending(g => g.Key)
.FirstOrDefault();
if (match == null)
throw new Exception("Could not identify token \"" + this._expression[this._position] + " at position " + this._position);
var matches = match.ToList();
this.position += matches[0].Match.Value.Length;
var value = matches[0].Match.Value;
var lex = matches[0].Lexeme;
*/
//if (lex.getMutator() != null)
// value = lex.getMutator(value);
//return new Token(lex.tokenType(), lex.tokenSubType(), value);
return null;
} |
ec5e7324-caa6-4c96-a76e-b500a32e336e | 0 | public int[] getAlpha() {
return alpha;
} |
6169cb11-93dc-46a7-a60e-69324d5f0d8c | 4 | public void test_02() {
String args[] = { "-v"//
, "-noStats" //
, "-i", "vcf", "-o", "vcf" //
, "-classic" //
, "-onlyTr", "tests/filterTranscripts_02.txt"//
, "testHg3765Chr22" //
, "tests/test_filter_transcripts_001.vcf" //
};
SnpEff cmd = new SnpEff(args);
SnpEffCmdEff cmdEff = (SnpEffCmdEff) cmd.snpEffCmd();
List<VcfEntry> vcfEntries = cmdEff.run(true);
for (VcfEntry ve : vcfEntries) {
System.out.println(ve);
// Get effect string
String effs = ve.getInfo(VcfEffect.VCF_INFO_EFF_NAME);
for (String effStr : effs.split(",")) {
VcfEffect veff = new VcfEffect(effStr);
System.out.println("\ttrId:" + veff.getTranscriptId() + "\t" + veff);
if (veff.getTranscriptId().equals("ENST00000400573") || veff.getTranscriptId().equals("ENST00000262608")) {
// OK
} else throw new RuntimeException("This transcript should not be here! " + veff);
}
}
} |
1d0d2395-7f19-4575-a5aa-57b59313c9a7 | 7 | private void selectNextItem() {
int i = 0;
boolean selectNext = true;
while(i<elements.size() && (! elements.get(i).isSelected()) ) {
i++;
}
if (i<elements.size()) {
if (elements.get(i) instanceof AxesElement && ((AxesElement)elements.get(i)).isXSelected()) {
((AxesElement)elements.get(i)).setSelected(true);
selectNext = false;
}
else
elements.get(i).setSelected(false);
}
if (i==elements.size()) {
i=0;
}
if (selectNext)
elements.get((i+1)%elements.size()).setSelected(true);
repaint();
} |
185a9373-ec0a-483c-9b1e-8aaaf110dfbc | 8 | public void processMsg(ServerMsg m) throws IOException{
String tag = m.getTag();
tag = tag.trim();
threadMessage("Processing Msg " + m.srcID + " " + m.destID + " " + m.tag + " " + m.getMessage());
//Messages received as worker
if(tag.equals("job_init")){
//set server worker object's coordinator ID field
mIsWorker = true;
mSW.InitJob(m.srcID);
}
else if(tag.equals("job_start")){
String payload = m.getMessage();
StringTokenizer st = new StringTokenizer(payload);
int XCoord = Integer.parseInt(st.nextToken());
int YCoord = Integer.parseInt(st.nextToken());
int JobItemID = Integer.parseInt(st.nextToken());
try {
mSW.StartJob(XCoord, YCoord, JobItemID);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if(tag.equals("job_stop")){
//call mSW.stopProcessing
//\todo add a message queue in ServerWorker
}
else if(tag.equals("job_uninit")){
mIsWorker=false;
}
//Message received as coordinator
else if(tag.equals("job_done")){
String payload = m.getMessage();
StringTokenizer st = new StringTokenizer(payload);
int jobid = Integer.parseInt(st.nextToken());
int featMatched = Integer.parseInt(st.nextToken());
int wid = m.getSrcId();
mSCoord.JobDone(jobid, wid, featMatched,false);
}
else if(tag.equals("image_received_ack")){
//add to coordinator queue
int wid = m.getSrcId();
mSCoord.ImageRcvAck(wid);
}
else if(tag.equals("timeout")){
//add to coordinator queue
int wid = m.getSrcId();
mSCoord.JobDone(0, wid, 0,true);
}
} |
3a2a75ac-057a-4d1a-8fea-2e8f3afcbbd6 | 0 | public playerDataSave(CreeperWarningMain plugin) {
this.plugin = plugin;
this.dir = new File(plugin.getDataFolder() + File.separator + "Players");
this.type = new File(plugin.getDataFolder() + File.separator + "Players" + File.separator + path + ".data");
} |
d0cf2765-b7aa-4e8e-afa1-88a554dd5235 | 0 | public void run(){
sort();
} |
4dbdb144-a150-4583-9d68-0d52dba52bba | 8 | private void method362(int i, int ai[], byte abyte0[], int j, int k, int l,
int i1, int ai1[], int j1)
{
int k1 = -(l >> 2);
l = -(l & 3);
for(int l1 = -i; l1 < 0; l1++)
{
for(int i2 = k1; i2 < 0; i2++)
{
byte byte1 = abyte0[i1++];
if(byte1 != 0)
ai[k++] = ai1[byte1 & 0xff];
else
k++;
byte1 = abyte0[i1++];
if(byte1 != 0)
ai[k++] = ai1[byte1 & 0xff];
else
k++;
byte1 = abyte0[i1++];
if(byte1 != 0)
ai[k++] = ai1[byte1 & 0xff];
else
k++;
byte1 = abyte0[i1++];
if(byte1 != 0)
ai[k++] = ai1[byte1 & 0xff];
else
k++;
}
for(int j2 = l; j2 < 0; j2++)
{
byte byte2 = abyte0[i1++];
if(byte2 != 0)
ai[k++] = ai1[byte2 & 0xff];
else
k++;
}
k += j;
i1 += j1;
}
} |
ffa7a0ae-902c-4da7-baab-6dabed75b87a | 5 | public JMenu getFileMenu(){
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem open = new JMenuItem("Open project");
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Assets project file (.assets.prj)", "prj", "Assets project file");
fileChooser.setFileFilter(filter);
fileChooser.setAcceptAllFileFilterUsed(false);
int returnValue = fileChooser.showOpenDialog(Display.this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
Map<String, String> infos = ProjectManager.getProjectInfos(selectedFile.toString());
if (infos != null){
onProjectOppened(infos);
projectFile = selectedFile;
resetTree(new File(infos.get("DIR")), infos.get("NAME"));
}
}
}
});
file.add(open);
JMenuItem newPrj = new JMenuItem("New project");
newPrj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FolderFilter());
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnValue = fileChooser.showOpenDialog(Display.this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (Utilities.getFileExtention(selectedFile) != null) {
JOptionPane.showMessageDialog(Display.this, "You must choose a folder for your new assets project. \nOnly directories are allowed in project saving...", "SLDT's AssetsManager", JOptionPane.ERROR_MESSAGE);
}
File contentFolder = new File(selectedFile, "content");
if (!contentFolder.exists()) {
contentFolder.mkdirs();
}
Map<String, String> content = new HashMap<String, String>();
content.put("DIR", contentFolder.toString());
content.put("NAME", "NewProject");
content.put("COMPILE_DIR", "NOT_DEFINED");
content.put("GAME_NAME", "NOT_DEFINED");
ProjectManager.saveProjectInfos(selectedFile + File.separator + "project.assets.prj", content);
projectFile = selectedFile;
}
}
});
file.add(newPrj);
JMenuItem close = new JMenuItem("Close project");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
projectFile = null;
thePanel.oldX = 0;
thePanel.oldY = 0;
thePanel.imagePath = null;
onProjectOppened(null);
resetTree(null, null);
repaint();
thePanel.repaint();
}
});
file.add(close);
return file;
} |
5fb4cfc4-2123-4520-8a60-ed6141023327 | 0 | public void setIdPerfil(Integer idPerfil) {
this.idPerfil = idPerfil;
} |
5129d430-8ae5-4f34-8355-6177fa424833 | 1 | private static boolean insertEmployee(Employee bean, PreparedStatement stmt) throws SQLException{
stmt.setString(1, bean.getName());
stmt.setString(2, bean.getUsername());
stmt.setString(3, bean.getPass());
stmt.setDate(4, bean.getDob());
stmt.setString(5, bean.getPhone());
stmt.setString(6, bean.getAddress());
stmt.setString(7, bean.getEmail());
stmt.setString(8, bean.getPosition());
int affected = stmt.executeUpdate();
if(affected == 1){
System.out.println("new employee added successfully");
}else{
System.out.println("error adding employee");
return false;
}
return true;
} |
faf025a8-480e-4614-9233-4f07136a9042 | 9 | public int compare(boolean[] class_list, int datapoint) throws BoostingAlgorithmException{
int c;
int class_index = -1;
int classification = -1;
//determine what class in the classlist the datapoint has
for (c = 0; c < classes; c++) {
if (data.classes[datapoint].equals(data.classlist[c])) {
class_index = c;
}
}
if (class_index == -1) {
throw new BoostingAlgorithmException("Class \"" + data.classes[datapoint] + "\" not found in class list");
}
//Check if the correct class is indicated
if (class_list[class_index]) {
//the correct class is selected
classification = 0;
} else {
//the correct class is not selected
classification = 3;
}
for (c = 0; c < classes; c++) {
//check if any other classes are indicated
if (c != class_index && class_list[c]) {
if (classification == 0) {
//the correct class is selected, but so are other classes
classification = 1;
} else if (classification == 3) {
//the correct class is not selected, but other classes are selected
classification = 2;
}
}
}
return classification;
} |
6b3c2fae-10b1-4f0f-988c-7ff9677e308d | 1 | @Override
public Class<?> getDataType() {
return superType.getDataType();
} |
6d86643a-166b-4026-bfeb-f058162ce8f5 | 4 | public void run()
{
while (this.running)
{
this.tickCount += 1L;
if (this.tickCount % 500L == 0L)
{
System.gc();
Debug.println("gc() called, freeMemory(): " + Runtime.getRuntime().freeMemory());
}
this.timestamp = System.currentTimeMillis();
tick();
long l1 = System.currentTimeMillis();
try
{
long l2 = 200L - (l1 - this.timestamp);
if (l2 > 0L) {
Thread.currentThread(); Thread.sleep(l2);
}
}
catch (InterruptedException localInterruptedException)
{
}
}
} |
96489fac-c2f3-4703-8b3c-e5960dd840e4 | 0 | public int getLength(){
return dataBaseFiles.size();
} |
8b119d37-82f0-4849-af62-c5f641fd7076 | 3 | public void paint(Graphics g)
{
if (first != null && current != null)
{
((Graphics2D) g).setStroke(new BasicStroke(lineWidth));
g.setColor(lineColor);
Rectangle rect = current.getRectangle();
if (rounded)
{
g.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 8, 8);
}
else
{
g.drawRect(rect.x, rect.y, rect.width, rect.height);
}
}
} |
3806a3b3-a970-4f75-88cf-4a9e16e7c2fe | 0 | private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
in.defaultReadObject();
// Reset those transient listener guys.
listeners = new HashSet();
} |
b590b68e-63b5-4ba5-9790-eab659380e74 | 8 | public void create(Workstation workstation) throws PreexistingEntityException, RollbackFailureException, Exception {
if (workstation.getComputadoraCollection() == null) {
workstation.setComputadoraCollection(new ArrayList<Computadora>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<Computadora> attachedComputadoraCollection = new ArrayList<Computadora>();
for (Computadora computadoraCollectionComputadoraToAttach : workstation.getComputadoraCollection()) {
computadoraCollectionComputadoraToAttach = em.getReference(computadoraCollectionComputadoraToAttach.getClass(), computadoraCollectionComputadoraToAttach.getIdComputadora());
attachedComputadoraCollection.add(computadoraCollectionComputadoraToAttach);
}
workstation.setComputadoraCollection(attachedComputadoraCollection);
em.persist(workstation);
for (Computadora computadoraCollectionComputadora : workstation.getComputadoraCollection()) {
Workstation oldWorkstationidWorkstationOfComputadoraCollectionComputadora = computadoraCollectionComputadora.getWorkstationidWorkstation();
computadoraCollectionComputadora.setWorkstationidWorkstation(workstation);
computadoraCollectionComputadora = em.merge(computadoraCollectionComputadora);
if (oldWorkstationidWorkstationOfComputadoraCollectionComputadora != null) {
oldWorkstationidWorkstationOfComputadoraCollectionComputadora.getComputadoraCollection().remove(computadoraCollectionComputadora);
oldWorkstationidWorkstationOfComputadoraCollectionComputadora = em.merge(oldWorkstationidWorkstationOfComputadoraCollectionComputadora);
}
}
em.getTransaction().commit();
} catch (Exception ex) {
try {
em.getTransaction().rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
if (findWorkstation(workstation.getIdWorkstation()) != null) {
throw new PreexistingEntityException("Workstation " + workstation + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
} |
3b953b51-1655-4dc9-b720-88c4317136b0 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Fraction other = (Fraction) obj;
if (denominator == null || other.denominator == null) return false;
if (numerator == null || other.numerator == null) return false;
Fraction thisSimplified = this.simplify();
Fraction otherSimplified = other.simplify();
return thisSimplified.numerator.equals(otherSimplified.numerator) && thisSimplified.denominator.equals(otherSimplified.denominator);
} |
6297eec8-e220-4d96-b73a-b4883ad4063d | 5 | public static void main(String args[]){
String frase1 ;
String frase2 ;
int tamano1,tamano2;
frase1 =JOptionPane.showInputDialog(null,"Ingrese una frase","Frase 1",JOptionPane.QUESTION_MESSAGE);
frase2= JOptionPane.showInputDialog(null,"Ingrese otra frase","Frase 2",JOptionPane.QUESTION_MESSAGE);
frase1=frase1.toLowerCase();
frase2=frase2.toLowerCase();
tamano2=frase2.length();
tamano1=frase1.length();
char [] cadenaS1=frase1.toCharArray();
char[] cadenaS2=frase2.toCharArray();
//String cadenaSalida = null;
for (int i = 0; i < tamano2; i++) {
for (int j = 0; j < tamano1; j++) {
if (cadenaS1[j]==cadenaS2[i]) {
cadenaS1[j]=' ';
}
}
}
String salida="";
for (int i=0;i<tamano1;i++)
if (cadenaS1[i]!=' ') {
salida=salida+cadenaS1[i];
//System.out.println(" " + cadenaS1[i]);
}
JOptionPane.showMessageDialog(null,salida,"Resultado",JOptionPane.INFORMATION_MESSAGE);
} |
21a7e516-4f1b-4616-962d-f05c8248e50e | 3 | private void moveOutgoingArcs( Node from, Node to ) throws MVDException
{
while ( !from.isOutgoingEmpty() )
{
Arc a = from.removeOutgoing( 0 );
to.addOutgoing( a );
}
// check if node is now isolated
if ( from.indegree()==0&&from.outdegree()==0 )
from.moveMatches( to );
} |
7209f0ca-9b0e-4558-a407-9ea75b89b400 | 6 | protected String addParameters(String path, Map<String, String> parameters) {
if (path == null) {
path = "";
}
StringBuffer sb = new StringBuffer(path);
if (parameters != null && parameters.size() > 0) {
try {
boolean hasParameters = path.indexOf("?") >= 0;
if (!hasParameters) {
sb.append('?');
}
for (String key : parameters.keySet()) {
String value = parameters.get(key);
sb.append(URLEncoder.encode(key, "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode(value, "UTF-8"));
sb.append('&');
}
sb.deleteCharAt(sb.length() - 1);// remove last '&'
} catch (UnsupportedEncodingException aeEx) {
throw new RuntimeException("Unsupported encoding", aeEx);
}
}
return sb.toString();
} |
99f78391-af05-4cdc-8fdc-2dbf0dcdbbdf | 5 | @SuppressWarnings({ "unchecked", "rawtypes" })
protected Object convert(Object oldObject, String property) {
Object result = oldObject;
Class<?> type = propertyTypes.get(property);
if (type.isEnum()) {
result = Enum.valueOf((Class<Enum>) type, (String) oldObject);
}
if (type.equals(BigInteger.class)) {
result = new BigInteger((oldObject).toString());
}
if (type.equals(BigDecimal.class) || type.equals(Number.class)) {
result = new BigDecimal((oldObject).toString());
}
return result;
} |
1d6dca35-232f-4172-931f-c14e56753f09 | 9 | @Override
public boolean validate(String str) {
try {
String[] data = str.split(",");
if (data.length < 3 || data.length > 3)
return false;
if (!data[0].equals("oo") || !data[0].equals("-oo"))
Double.parseDouble(data[0]);
if (!data[1].equals("oo") || !data[1].equals("-oo"))
Double.parseDouble(data[0]);
if (!data[2].equals("oo") || !data[2].equals("-oo"))
Double.parseDouble(data[0]);
return true;
} catch (Exception e) {
return false;
}
} |
96b9975f-d9c3-465c-9e89-8d40fa3384f9 | 1 | @Override
public void startOutline () {
// initialize the current node to the root node of the outline
this.currentNode = tree.getRootNode();
// clear out any existing children.
while (currentNode.numOfChildren() > 0) {
currentNode.removeChild(currentNode.getLastChild());
} // end while
// set the initial level to the root node's level
currentLevel = -1 ;
} // end startOutline |
85d415d2-98bf-49a1-bcd0-3067d3385880 | 1 | public void removeState(State state) {
if (this.states.contains(state)) {
this.states.remove(state);
state.setTray(null);
}
} |
9383ffb6-d389-456f-924d-d76717d4662f | 2 | void setDomParent(final Block block) {
// If this Block already had a dominator specified, remove
// it from its dominator's children.
if (domParent != null) {
domParent.domChildren.remove(this);
}
domParent = block;
// Add this Block to its new dominator's children.
if (domParent != null) {
domParent.domChildren.add(this);
}
} |
4f53b4ae-1be9-4da9-98de-f287db36b36b | 1 | public ResultSet getList(String whereString) {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT Question_ID,QType_ID");
sql.append(" FROM `Question`");
if (whereString.trim() != "") {
sql.append(" where " + whereString);
}
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
//sQLHelper.sqlClose();
return rs;
} |
5eeeafce-e581-47fb-ba08-efa4c15123d3 | 4 | public void run() {
String buffer;
while (this.isActive()) {
try {
while ((buffer = in.readLine()) != null) {
handleReceivedData(buffer);
if (dataQueue.length() > 0) {
out.write(dataQueue);
out.flush();
System.out.print("< " + dataQueue);
dataQueue = "";
}
}
} catch (java.io.IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
ce5271c2-1821-46c1-b3bf-a77da068a2c3 | 9 | public void run() {
PokerState currentState = new PokerState();
while( scan.hasNextLine() ) {
String line = scan.nextLine().trim();
if( line.length() == 0 ) { continue; }
String[] parts = line.split("\\s+");
if( parts.length == 2 && parts[0].equals("go") ) {
// we need to move
PokerMove move = bot.getMove(currentState, Long.valueOf(parts[1]));
System.out.printf("%s %d\n", move.getAction(), move.getAmount());
System.out.flush();
} else if( parts.length == 3 && parts[0].equals("Match") ) {
// update PokerState
currentState.updateMatch(parts[1], parts[2]);
} else if( parts.length == 3 && parts[0].equals("Settings") ) {
// update settings
currentState.updateSetting(parts[1], parts[2]);
} else if( parts.length == 3 ) {
// assume it's ``botX y z''
// also update PokerState
currentState.updateMove(parts[0], parts[1], parts[2]);
} else {
System.err.printf("Unable to parse line ``%s''\n", line);
}
}
} |
01af00b4-22a5-40f3-bd00-6eb095dc4184 | 5 | private void fillZipEntries(int nr) {
Enumeration zipEnum = zips[nr].entries();
zipEntries[nr] = new Hashtable();
while (zipEnum.hasMoreElements()) {
ZipEntry ze = (ZipEntry) zipEnum.nextElement();
String name = ze.getName();
// if (name.charAt(0) == '/')
// name = name.substring(1);
if (zipDirs[nr] != null) {
if (!name.startsWith(zipDirs[nr]))
continue;
name = name.substring(zipDirs[nr].length());
}
if (!ze.isDirectory() && name.endsWith(".class"))
addEntry(zipEntries[nr], name);
}
} |
5ff63d91-bdb3-40aa-aeca-f3977854e800 | 1 | public void draw() {
for(int x = 0; x<mapTiles.size(); x++) {
mapTiles.get(x).draw();
}
} |
c2e53c05-7ec2-4091-843c-874e1e6ac1b3 | 3 | @Override
public boolean update(DataRow parameters, DataRow row)
{
Boolean flaga = false;
String stm;
String tabelName = row.getTableName();
List<DataCell> cells = row.row;
List<DataCell> toUpdate = parameters.row;
String kolumny = "";
String doPodmiany = "";
for(DataCell c : cells)
{
kolumny += c.name + " = " + c.value + ", ";
}
for (DataCell x : toUpdate)
{
doPodmiany += x.name + " = " + x.value + " AND ";
}
kolumny = kolumny.substring(0, kolumny.length() - 2);
doPodmiany = doPodmiany.substring(0, doPodmiany.length() - 5);
stm = "UPDATE " + tabelName + " SET " + kolumny + " WHERE " + doPodmiany;
try
{
PreparedStatement prepStmt = conn.prepareStatement(stm);
prepStmt.execute();
flaga = true;
}
catch (Exception ex)
{
ErrorDialog errorDialog = new ErrorDialog(true, "Błąd operacji w lokalnej bazie danych: \n" + ex.getMessage(), "LocalDatabaseConnectorSQLite", "update(DataRow parameters, DataRow row)", "prepStmt");
errorDialog.setVisible(true);
}
return flaga;
} |
f9ea914c-ae98-4500-9d5d-830828d31623 | 3 | T select(T a[], int r, int i, int j)
{
int n = a.length;
int pIndex = findPivot(a, i, j);
int k = new QuickSorter<T>().partition(a, i, j, pIndex);
int rPivot = n - k + 1;
if (r == rPivot)
return a[r];
else if (r < rPivot)
return select(a, r, k + 1, j);
else if (r > rPivot)
return select(a, r - (n - k + 1), i, k - 1);
return null;
} |
60d07a42-faed-47e5-a751-5dd15f6f2260 | 9 | private void backTrackingAfter3() {
FeatureGenerator fg=new FeatureGenerator();
double result=0.0;
String antFeature=featureModelBruteForce;
double difference=0.0;
//ADD FEATURES TO THE POOL.
//If we have 3...
// {f1,f2,f3} => { {f1},{f2},{f3},{f1,f2},{f1,f3},{f2,f3},{f1,f2,f3} }
//
ArrayList<String> pool = new ArrayList<String>();
String structure="Stack";
if (bestAlgorithm.contains("cov"))
structure="Left";
String structureI="Input";
if (bestAlgorithm.contains("cov"))
structureI="Right";
if (bestAlgorithm.contains("stack"))
structureI="Lookahead";
pool=new ArrayList<String>();
if (bestAlgorithm.contains("stack")) {
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, "+structure+"[0]), OutputColumn(DEPREL, ldep("+structure+"[0])), OutputColumn(DEPREL, rdep("+structure+"[0])))</feature>");
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, "+structure+"[1]), OutputColumn(DEPREL, ldep("+structure+"[1])), OutputColumn(DEPREL, rdep("+structure+"[1])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Stack[1]), OutputColumn(DEPREL, ldep(Stack[1])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Stack[1]), OutputColumn(DEPREL, ldep(Stack[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Stack[2]), OutputColumn(DEPREL, ldep(Stack[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Lookahead[0]), OutputColumn(DEPREL, ldep(Stack[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Lookahead[0]), OutputColumn(DEPREL, rdep(Stack[0])))</feature>");
}
if (bestAlgorithm.contains("nivre")) {
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Stack[0]), OutputColumn(DEPREL, ldep(Stack[0])), OutputColumn(DEPREL, rdep(Stack[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Stack[0]), OutputColumn(DEPREL, Stack[0]))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Input[0]), OutputColumn(DEPREL, ldep(Input[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Input[0]), OutputColumn(DEPREL, rdep(Input[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Input[1]), OutputColumn(DEPREL, rdep(Input[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Input[2]), OutputColumn(DEPREL, rdep(Input[0])))</feature>");
}
if (bestAlgorithm.contains("cov")) {
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Left[0]), OutputColumn(DEPREL, ldep(Left[0])), OutputColumn(DEPREL, rdep(Left[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Left[0]), OutputColumn(DEPREL, Left[0]))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Right[0]), OutputColumn(DEPREL, ldep(Right[0])))</feature>");
pool.add("\t\t<feature>Merge(InputColumn(POSTAG, Right[0]), OutputColumn(DEPREL, Right[0]))</feature>");
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Left[1]), InputColumn(POSTAG, Left[0]), InputColumn(POSTAG, Right[0]))</feature>");
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Left[0]), InputColumn(POSTAG, Right[0]), InputColumn(POSTAG, Right[1]))</feature>");
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Right[0]), InputColumn(POSTAG, Right[1]), InputColumn(POSTAG, Right[2]))</feature>");
pool.add("\t\t<feature>Merge3(InputColumn(POSTAG, Right[1]), InputColumn(POSTAG, Right[2]), InputColumn(POSTAG, Right[3]))</feature>");
}
Iterator<String> it=pool.iterator();
String newFeature="deprelBT"+structure+structureI;
int a=0;
while(it.hasNext()){
newFeature="deprelMergeBT"+structure+structureI+a+".xml";
fg.addFeatureLineBefore(featureModelBruteForce,newFeature,it.next(),"Merge","DEPREL");
a++;
antFeature=newFeature;
System.out.println("Testing "+newFeature +" ...");
result=runBestAlgorithm(newFeature);
difference=0.0;
System.out.println(" "+result);
System.out.println(" Default: "+bestResult);
if (result>=(this.bestResultBruteForce+threshold)) {
this.featureModelBruteForce=antFeature; //dummy (just a matter of completity)
difference=result-bestResultBruteForce;
bestResultBruteForce=result;
String sDifferenceLabel=""+difference;
if (sDifferenceLabel.length()>5)
sDifferenceLabel=sDifferenceLabel.substring(0, 5);
/*System.out.println("New best feature model: "+featureModelBruteForce);
String s=""+this.bestResult;
if (s.length()==4) s+="0";
System.out.println("Incremental "+evaluationMeasure+" improvement: + "+sDifferenceLabel+"% ("+s+"%)");*/
}
}
} |
c391fa5c-ea15-4d66-a2a4-a423de9aaa44 | 9 | public static boolean validate(Stack<Character> p, char k) {
Iterator<Character> it = p.iterator();
ArrayList<Character> list = new ArrayList<Character>();
;
while (it.hasNext()) {
list.add(it.next());
}
int index = -1;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == index) {
index = i;
}
}
if (index == -1) {
if (p.peek() == 'X')
return true;
return false;
}
for (int i = index + 1; i < list.size(); i++) {
if (list.get(i) != 'X')
return false;
}
p.clear();
for (int i = 0; i < list.size(); i++) {
if (i != index)
p.add(list.get(i));
}
p.add('m');
return true;
} |
9f72f502-0459-48bf-ba70-f4bf18a2e0fd | 9 | public void doPaletteStuff() {
int palette;
//byte[] pal;
int cnt;
int bzc;
cnt = plyr.damagecount;
if (plyr.powers[pw_strength] != 0) {
// slowly fade the berzerk out
bzc = 12 - (plyr.powers[pw_strength] >> 6);
if (bzc > cnt)
cnt = bzc;
}
if (cnt != 0) {
palette = (cnt + 7) >> 3;
if (palette >= NUMREDPALS)
palette = NUMREDPALS - 1;
palette += STARTREDPALS;
} else if (plyr.bonuscount != 0) {
palette = (plyr.bonuscount + 7) >> 3;
if (palette >= NUMBONUSPALS)
palette = NUMBONUSPALS - 1;
palette += STARTBONUSPALS;
} else if (plyr.powers[pw_ironfeet] > 4 * 32
|| (plyr.powers[pw_ironfeet] & 8) != 0)
palette = RADIATIONPAL;
else
palette = 0;
if (palette != st_palette) {
st_palette = palette;
VI.SetPalette(palette);
}
} |
86ee2cdf-0a51-489a-b938-5fd69b632bb0 | 1 | protected void addGlied() {
if (nextGlied == null) {
//create/add new glied
Rectangle newMasse = (Rectangle) getBounds().clone();
newMasse.x -= getDirection().x * width;
newMasse.y -= getDirection().y * height;
SchlangenGlied newGlied = new SchlangenGlied(newMasse, unit, Zufallsgenerator.zufallsFarbe(color, 20));
setNextGlied(newGlied);
} else {
nextGlied.addGlied();
}
} |
0d5ba632-3b16-43a8-9065-ea4598ddb4ed | 8 | public String [] getOptions() {
// Currently no way to set custompropertyiterators from the command line
m_UsePropertyIterator = false;
m_PropertyPath = null;
m_PropertyArray = null;
String [] rpOptions = new String [0];
if ((m_ResultProducer != null) &&
(m_ResultProducer instanceof OptionHandler)) {
rpOptions = ((OptionHandler)m_ResultProducer).getOptions();
}
String [] options = new String [rpOptions.length
+ getDatasets().size() * 2
+ 11];
int current = 0;
options[current++] = "-L"; options[current++] = "" + getRunLower();
options[current++] = "-U"; options[current++] = "" + getRunUpper();
if (getDatasets().size() != 0) {
for (int i = 0; i < getDatasets().size(); i++) {
options[current++] = "-T";
options[current++] = getDatasets().elementAt(i).toString();
}
}
if (getResultListener() != null) {
options[current++] = "-D";
options[current++] = getResultListener().getClass().getName();
}
if (getResultProducer() != null) {
options[current++] = "-P";
options[current++] = getResultProducer().getClass().getName();
}
if (!getNotes().equals("")) {
options[current++] = "-N"; options[current++] = getNotes();
}
options[current++] = "--";
System.arraycopy(rpOptions, 0, options, current,
rpOptions.length);
current += rpOptions.length;
while (current < options.length) {
options[current++] = "";
}
return options;
} |
d795399f-01f7-4ee7-9a07-20db921c8f3b | 9 | private void parseInstruction(Program program) {
// Parse mnemonic (easy)
String mnemonic = tokenizer.next().text;
// Parse operands (hard)
List<Operand> operands = new ArrayList<Operand>();
boolean expectcomma = false;
while (!tokenizer.check(TokenType.NEWLINE)) {
if (!expectcomma) {
if (tokenizer.check(TokenType.COMMA))
throw new RuntimeException("Expected operand, got comma");
} else {
if (!tokenizer.check(TokenType.COMMA))
throw new RuntimeException("Expected comma");
tokenizer.next();
}
if (tokenizer.check(TokenType.REGISTER)) {
operands.add(parseRegister(tokenizer.next().text));
} else if (tokenizer.check(TokenType.DOLLAR)) {
tokenizer.next();
operands.add(parseImmediate());
} else if (canParseImmediate() || tokenizer.check(TokenType.LEFT_PAREN)) {
Immediate disp;
if (canParseImmediate())
disp = parseImmediate();
else
disp = ImmediateValue.ZERO;
operands.add(parseMemory(disp));
} else {
throw new RuntimeException("Expected operand");
}
expectcomma = true;
}
program.addStatement(new InstructionStatement(mnemonic, operands));
} |
4ffcad40-7d72-4d6f-b345-b6ee94c8eaf3 | 7 | public boolean setStance(Player player, Stance newStance) {
if (player == null) {
throw new IllegalArgumentException("Player must not be 'null'.");
}
if (player == this) {
throw new IllegalArgumentException("Cannot set the stance towards ourselves.");
}
if (newStance == null) {
stance.remove(player.getId());
return true;
}
Stance oldStance = stance.get(player.getId());
if (newStance.equals(oldStance)) return true;
boolean valid = true;;
if ((newStance == Stance.CEASE_FIRE && oldStance != Stance.WAR)
|| newStance == Stance.UNCONTACTED) {
valid = false;
}
stance.put(player.getId(), newStance);
return valid;
} |
4a168ca4-139f-493d-9541-09055e0aedca | 7 | private double minDist(Freckle[] freckles) {
double minDistance = 0;
boolean[] inTree = new boolean[freckles.length];
double[] minDists = new double[freckles.length];
for (int i = 0; i < freckles.length; i++) {
minDists[i] = Double.MAX_VALUE;
}
int newNode = 0;
while (inTree[newNode] == false) {
inTree[newNode] = true;
double minDist = Double.MAX_VALUE;
int nextNode = newNode;
for (int i = 0; i < freckles.length; i++) {
if (!inTree[i]) {
double dist = getDistance(freckles[i], freckles[newNode]);
if (dist < minDists[i]) {
minDists[i] = dist;
}
if (minDists[i] < minDist) {
minDist = minDists[i];
nextNode = i;
}
}
}
if (nextNode != newNode) {
newNode = nextNode;
minDistance += minDist;
}
}
return minDistance;
} |
d8dafc0c-ca91-44a4-a19f-50548a43dee9 | 5 | protected void rmBus (Object busname)
{
USB bus = (USB) busses.get (busname);
if (bus != null) {
if (trace)
System.err.println ("rmBus " + bus);
for (int i = 0; i < listeners.size (); i++) {
USBListener listener;
listener = (USBListener) listeners.elementAt (i);
try {
listener.busRemoved (bus);
} catch (Exception e) {
e.printStackTrace ();
}
}
busses.remove (busname);
bus.kill ();
} else {
if (trace)
System.err.println ("rmBus: could not find named bus to remove " + busname);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.