method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
c384b937-ab2c-4bba-9282-890f579742c4
| 8
|
public Square move(PieceDirection direction, int diff) {
switch (direction) {
case Back:
return this.moveBack(diff);
case Front:
return this.moveFront(diff);
case Left:
return this.moveLeft(diff);
case LeftBack:
return this.moveLeftBack(diff);
case LeftFront:
return this.moveLeftFront(diff);
case Right:
return this.moveRight(diff);
case RightBack:
return this.moveRightBack(diff);
case RightFront:
return this.moveRightFront(diff);
default:
return null;
}
}
|
8e6cbc05-1f29-4772-8dcb-37f2e6649f7f
| 8
|
private static String printClusterStats(Clusterer clusterer,
String fileName)
throws Exception {
StringBuffer text = new StringBuffer();
int i = 0;
int cnum;
double loglk = 0.0;
int cc = clusterer.numberOfClusters();
double[] instanceStats = new double[cc];
int unclusteredInstances = 0;
if (fileName.length() != 0) {
DataSource source = new DataSource(fileName);
Instances structure = source.getStructure();
Instance inst;
while (source.hasMoreElements(structure)) {
inst = source.nextElement(structure);
try {
cnum = clusterer.clusterInstance(inst);
if (clusterer instanceof DensityBasedClusterer) {
loglk += ((DensityBasedClusterer) clusterer).
logDensityForInstance(inst);
// temp = Utils.sum(dist);
}
instanceStats[cnum]++;
}
catch (Exception e) {
unclusteredInstances++;
}
i++;
}
/*
// count the actual number of used clusters
int count = 0;
for (i = 0; i < cc; i++) {
if (instanceStats[i] > 0) {
count++;
}
}
if (count > 0) {
double[] tempStats = new double [count];
count=0;
for (i=0;i<cc;i++) {
if (instanceStats[i] > 0) {
tempStats[count++] = instanceStats[i];
}
}
instanceStats = tempStats;
cc = instanceStats.length;
} */
int clustFieldWidth = (int) ((Math.log(cc) / Math.log(10)) + 1);
int numInstFieldWidth = (int) ((Math.log(i) / Math.log(10)) + 1);
double sum = Utils.sum(instanceStats);
loglk /= sum;
text.append("Clustered Instances\n");
for (i = 0; i < cc; i++) {
if (instanceStats[i] > 0) {
text.append(Utils.doubleToString((double) i,
clustFieldWidth, 0)
+ " "
+ Utils.doubleToString(instanceStats[i],
numInstFieldWidth, 0)
+ " ("
+ Utils.doubleToString((instanceStats[i] / sum * 100.0)
, 3, 0) + "%)\n");
}
}
if (unclusteredInstances > 0) {
text.append("\nUnclustered Instances : " + unclusteredInstances);
}
if (clusterer instanceof DensityBasedClusterer) {
text.append("\n\nLog likelihood: "
+ Utils.doubleToString(loglk, 1, 5)
+ "\n");
}
}
return text.toString();
}
|
3edd0410-6ad1-4046-94ad-a132b3c3b423
| 4
|
private void add(E e) {
Rect rect = e.getAABB();
int beginx = (int) (rect.x - rect.w2) / width;
int beginy = (int) (rect.y - rect.h2) / height;
int endx = (int) (rect.x + rect.w2) / width;
int endy = (int) (rect.y + rect.h2) / height;
//Vec2i pos = new Vec2i(0, 0);
for (int y = beginy; y <= endy; y++) {
for (int x = beginx; x <= endx; x++) {
Vec2i newVec = new Vec2i(x, y);
ArrayList<E> mapList = map.get(newVec);
if (mapList == null) {
mapList = new ArrayList<E>();
mapList.add(e);
map.put(newVec, mapList);
} else {
mapList.add(e);
}
ArrayList<Vec2i> vec2iArr = entities.get(e);
if (vec2iArr == null) {
vec2iArr = new ArrayList<Vec2i>();
vec2iArr.add(newVec);
entities.put(e, vec2iArr);
} else {
vec2iArr.add(newVec);
}
}
}
}
|
18927fbf-1e95-4592-b7b2-dc7ad7a849b4
| 6
|
private boolean isCorrectTarget(Placeable currentEnemy) {
if (tower.getLastTarget() != null || !isInRange(currentEnemy)) { // if no last target skip below and return
if (attackData.isRememberOldTarget()) { //if it does not care about keeping track of old target
if (tower.getLastTarget().isActive() || tower.getLastTarget().isAlive() ) { // if enemy is dead, skip
if (currentEnemy.equals(tower.getLastTarget())) {
return true;
}
return false;
}
}
}
return true;
}
|
b5ac0b2f-9721-4b58-a2cd-c589fe0254eb
| 5
|
public static void tulostaYhteydet(Sitsit sitsit) {
System.out.println("\n" + "Yhteydet" + "\n");
Hakemisto<Sitsaaja, Hakemisto> kaikkiYhteydet = sitsit.palautaYhteydet();
int moneskoYhteys = 0;
int moneskoSitsaaja = 0;
int moneskoyhteydellinen = 0;
for (Vektori<Sitsaaja, Hakemisto> sitsaajanYhteydet : kaikkiYhteydet) {
Sitsaaja sitsaaja = (Sitsaaja) sitsaajanYhteydet.getKey();
if (sitsaaja.avecIsSet()) {
System.out.println(sitsaaja.getNimi() + " haluaa olla sitsaajan " + sitsaaja.getAvec().getNimi() + " avec");
}
if (sitsaaja.puolisoIsSet()) {
System.out.println(sitsaaja.getNimi() + " haluaa olla sitsaajan " + sitsaaja.getPuoliso().getNimi() + " puoliso");
}
Hakemisto<Sitsaaja, Integer> yhteydet = (Hakemisto<Sitsaaja, Integer>) sitsaajanYhteydet.getValue();
moneskoSitsaaja++;
boolean eka = true;
for (Vektori<Sitsaaja, Integer> yhteys : yhteydet) {
Sitsaaja kohdeSitsaaja = (Sitsaaja) yhteys.getKey();
int arvo = (Integer) yhteys.getValue();
System.out.println(sitsaaja.getNimi() + " pit\u00e4\u00e4 sitsaajasta " + kohdeSitsaaja.getNimi() + " arvolla " + arvo);
moneskoYhteys++;
if (eka) {
moneskoyhteydellinen++;
eka = false;
}
}
}
System.out.println("\n" + "----" + moneskoYhteys + "-" + moneskoSitsaaja + "-" + moneskoyhteydellinen + "--" + "\n");
}
|
384b2c46-7711-4bbb-bcc3-7ee3b493fb27
| 0
|
public HttpPlayer() {
client = new DefaultHttpClient();
}
|
745a5efa-b52f-424b-a31a-ebd7bf34d76c
| 7
|
public void testRemoveManyWithNulling() {
RingBufferSeqno<Integer> buf=new RingBufferSeqno<>(10, 0);
for(int i: Arrays.asList(1,2,3,4,5,6,7,9,10))
buf.add(i, i);
List<Integer> list=buf.removeMany(true, 3);
System.out.println("list = " + list);
assert list != null && list.size() == 3;
for(int i: list)
assert buf._get(i) == null;
list=buf.removeMany(true, 0);
System.out.println("list = " + list);
assert list != null && list.size() == 4;
for(int i: list)
assert buf._get(i) == null;
list=buf.removeMany(false, 10);
assert list == null;
buf.add(8, 8);
list=buf.removeMany(true, 0);
System.out.println("list = " + list);
assert list != null && list.size() == 3;
for(int i: list)
assert buf._get(i) == null;
}
|
9efcb38a-c27a-43f7-b0fe-78ae3f73a865
| 4
|
public void testEmptyClass () {
FieldAccess access = FieldAccess.get(EmptyClass.class);
try {
access.getIndex("name");
fail();
} catch (IllegalArgumentException expected) {
// expected.printStackTrace();
}
try {
access.get(new EmptyClass(), "meow");
fail();
} catch (IllegalArgumentException expected) {
// expected.printStackTrace();
}
try {
access.get(new EmptyClass(), 0);
fail();
} catch (IllegalArgumentException expected) {
// expected.printStackTrace();
}
try {
access.set(new EmptyClass(), "foo", "moo");
fail();
} catch (IllegalArgumentException expected) {
// expected.printStackTrace();
}
}
|
80bea9c0-b200-421a-a3e2-b620870cd15b
| 0
|
public String getNombre() {
return nombre;
}
|
fb93826c-1a31-4bb7-884e-db35cdeacb68
| 3
|
public int Run()
{
char c = 0;
System.out.println("Please enter a command:");
do{
try {
c = (char) System.in.read();
if ( CurrentRoom.Options.get(c)!=null){
//CurrentRoom.Options.get(c).runCommand(c);
DoTheOption(c);
System.out.println("Please enter a command:");
}
} catch (IOException e) {
e.printStackTrace();
return 1;
}
}
while (c!='q');
System.out.print("\nThank you for playing! Good bye!\n");
return 0;
}
|
e3e43b5c-cfb2-406c-ad24-5310999d2765
| 0
|
float getZ(int x) {
return x * 2.0f;
}
|
fc647ebf-4d51-43b6-a5bc-7f3929ba6abd
| 2
|
public String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
|
82de3b98-f64b-4146-a180-4df46cc07f16
| 4
|
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) { //Presiono flecha arriba 1
direccion = 1;
buenoMov = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) { //Presiono flecha abajo 2
direccion = 2;
buenoMov = false;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) { //Presiono flecha izquierda 3
direccion = 3;
buenoMov = true;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { //Presiono flecha derecha 4
direccion = 4;
buenoMov = true;
}
}
|
c908e632-d05b-4315-869e-9a3814d341fa
| 8
|
@Override
public void run() {
double unproccessedSeconds = 0;
long lastTime = System.nanoTime();
double secondsPerTick = 1 / 60.0;
int tickCount = 0;
while (running) {
long now = System.nanoTime();
long passedTime = now - lastTime;
lastTime = now;
if (passedTime < 0) {
passedTime = 0;
}
if (passedTime > 1_000_000_000) {
passedTime = 1_000_000_000;
}
unproccessedSeconds += passedTime / 1_000_000_000.0;
ticked = false;
while (unproccessedSeconds > secondsPerTick) {
tick();
unproccessedSeconds -= secondsPerTick;
ticked = true;
tickCount++;
if (tickCount % 60 == 0) {
avgFPSCount++;
avgFPS += frames;
System.out.println("Ticks: " + tickCount + ", Fps: " + frames);
if (avgFPSCount == 5) {
System.out.println("=========================\nAVERAGE FPS: " + avgFPS / avgFPSCount + "\n=========================");
avgFPSCount = 0;
avgFPS = 0;
}
lastTime += 1000;
frames = 0;
tickCount = 0;
}
}
//Updates frames independently from the game logic (ticks).
DisplayCarrier.getCanvas().render();
KeyInputManager.processInput();
if (ticked) {
this.currentWorld.getPlayer().setCurrentSpeed();
if (currentWorld.getPlayer().isWalking()) {
PlayerCamera.movePlayer();
}
}
frames++;
}
}
|
173ad6f4-647a-413b-afbf-e3bfea6d834a
| 7
|
@Override
public void visitIincInsn(final int var, final int increment) {
if (currentBlock != null) {
if (compute == FRAMES) {
currentBlock.frame.execute(Opcodes.IINC, var, null, null);
}
}
if (compute != NOTHING) {
// updates max locals
int n = var + 1;
if (n > maxLocals) {
maxLocals = n;
}
}
// adds the instruction to the bytecode of the method
if ((var > 255) || (increment > 127) || (increment < -128)) {
code.putByte(196 /* WIDE */).put12(Opcodes.IINC, var)
.putShort(increment);
} else {
code.putByte(Opcodes.IINC).put11(var, increment);
}
}
|
bd940523-0c28-4b1a-814a-071516219f46
| 0
|
public int[] getDecomposition()
{
return myDecomposition;
}
|
5ad04f21-f321-4b2a-9b53-4fe27f85b9fe
| 5
|
@Override
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == MouseEvent.BUTTON1)
{
if (down)
{
if (Hub.simWindow.loadGenesButton.isChecked())
loadGenes(file.getName());
else if (Hub.simWindow.deleteGenesButton.isChecked()
&& JOptionPane.showConfirmDialog(Hub.simWindow.getObserver(), "Are you sure you want to delete this gene?", "Delete Confirmation",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
file.delete();
}
active = down = false;
}
}
|
0136a356-cfa0-4a2f-be28-63f363f99539
| 6
|
private void Run()
{
isRunning = true;
int frames = 0;
long frameCounter = 0;
final double frameTime = 1.0 / FRAME_CAP;
long lastTime = Time.GetTime();
double unprocessedTime = 0.0;
while(isRunning)
{
boolean render = false;
long startTime = Time.GetTime();
long passedTime = startTime - lastTime;
lastTime = startTime;
unprocessedTime += passedTime / (double)Time.SECOND;
frameCounter += passedTime;
while (unprocessedTime > frameTime)
{
render = true;
unprocessedTime -= frameTime;
if (Window.IsCloseRequested())
Stop();
Time.SetDelta(frameTime);
Input.Update();
game.Input();
game.Update();
if (frameCounter >= Time.SECOND)
{
System.out.println("FPS: " + frames);
frames = 0;
frameCounter = 0;
}
}
if (render)
{
Render();
frames++;
}
else
{
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
CleanUp();
}
|
37fdb09f-d00b-4eee-9d0b-6ed3ef7ba122
| 4
|
public boolean accept(File dir, String name){
File f = new File(dir.getAbsolutePath() + name);
BufferedReader br = null;
String s = null;
try {
br = new BufferedReader(new FileReader(f));
while((s=br.readLine())!=null ){
if(pattern.matcher(name).matches() == true)
return true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
|
312f2266-19f4-4669-ac57-ebadc3ab0bf8
| 3
|
public static ArrayList<Double> averageChunks(List<Double> ary,
int numChunks) {
ArrayList<Double> result = new ArrayList<Double>();
double chunkSize = ((double) ary.size()) / (double) numChunks;
int start = 0; // index of start of current chunk
double bound = 0; // decimal value of upper bound for current chunk
while (start < ary.size()) { // REDUNDANT??
bound += chunkSize; // get upper bound for next chunk
double sum = 0; // to store sum of values in the chunk
double numValues = 0; // number of values in the chunk (to divide by
// to get the average value for the chunk)
for (int i = start; i < bound && i < ary.size(); i++) {
sum += ary.get(i);
numValues++;
}
result.add(sum / numValues);
start += numValues;
}
return result;
}
|
579f3c04-d235-4432-b268-fcc57c4be85e
| 9
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (lat == null) {
if (other.lat != null)
return false;
} else if (!lat.equals(other.lat))
return false;
if (lon == null) {
if (other.lon != null)
return false;
} else if (!lon.equals(other.lon))
return false;
return true;
}
|
0685eb07-6acb-4860-8d82-40f46ef5d39b
| 8
|
static void checkSyntax(String attrName, Expr value) throws InvalidAttributeValueException, IllegalArgumentException {
if (value.type == Expr.ERROR) {
throw new IllegalArgumentException(attrName + ": syntax error, unable to parse the value");
} else if (value.type == Expr.STRING) {
checkAttribute(attrName, ((Constant) value).stringValue());
} else if (value.type == Expr.REAL) {
checkAttribute(attrName, ((Constant) value).realValue());
} else if (value.type == Expr.INTEGER) {
checkAttribute(attrName, ((Constant) value).intValue());
} else if (value.type == Expr.BOOLEAN) {
checkAttribute(attrName, ((Constant) value).isTrue());
} else if (value.type == Expr.RECORD) {
try {
checkAttribute(attrName, new Ad((RecordExpr) value));
} catch (JobAdException exc) {
exc.printStackTrace();
throw new InvalidAttributeValueException(attrName + ": Fatal Error caught");
}
} else if (!Jdl.findExpr(attrName)) {
throw new InvalidAttributeValueException(attrName + ": expression type not allowed"); // Unexpected type
}
}
|
bde4cdb9-c370-4fc6-9486-138ef017d39c
| 4
|
public Packet read(short id, ByteBuffer buf) {
try {
/*short id = buf.getShort();
short len = buf.getShort();
ByteBuffer data = buf.slice();
data.limit(len);
buf.position(len);*/
Class<? extends Packet> packetClass = packetMapping.get((int)id);
if (packetClass == null) throw new IllegalArgumentException("Unknown packet id: " + id);
Packet packet;
try {
packet = packetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
packet.deserialize(buf);
return packet;
} catch (BufferUnderflowException e) {
e.printStackTrace();
return null;
}
}
|
1262406e-61a5-4372-9d10-7ba9a0b282ed
| 2
|
public void save() {
try {
sql.Query.save(this);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
c9505da9-19b3-40dc-b784-eebc26942947
| 6
|
public boolean hayLugarEnPlan (int id_padre, String codigo_plan_padre){
boolean haylugar = false;
try {
r_con.Connection();
ResultSet rs = r_con.Consultar("select COUNT(*) from "+nameTable+" where pc_id_padre="+id_padre);
rs.next();
int futuroHijo = rs.getInt(1);
futuroHijo++;
if ((codigo_plan_padre.length()==1) && (codigo_plan_padre.equals("0"))){
haylugar = futuroHijo<=9;
}
else{
//caso hijo de Activo, etc
if (codigo_plan_padre.length()==1){
haylugar = futuroHijo<=9;
}
else{
//caso de hijo en que ya son 1.1, 1.2. etc
if ((codigo_plan_padre.length()>=1)&&((codigo_plan_padre.length()<3))){
haylugar = futuroHijo<=9;
}
else{
//caso de hijo en que ya son .11, .12. etc
haylugar = futuroHijo<=99;
}
}
}
r_con.cierraConexion();
} catch (SQLException ex) {
r_con.cierraConexion();
Logger.getLogger(GUI_Plan_Cuentas.class.getName()).log(Level.SEVERE, null, ex);
}
return haylugar;
}
|
d02782fd-3f93-47bf-aee5-14a848c0de57
| 5
|
@Override
public void paintComponent(Graphics g) {
Graphics2D graph = (Graphics2D) g;
graph.setBackground(new Color(1, 0, 0));
graph.clearRect(0, 0, this.getWidth(), this.getHeight());
if (entityList != null) {
for (Entity e : entityList) {
int eCenterX = Math.round(e.getxPos()) - xPos;
int eCenterY = Math.round(e.getyPos()) - yPos;
if (e.getClass().equals(FoodEntity.class)) {
graph.setColor(new Color(255, 255, 0));
graph.fillOval(eCenterX - e.radius, eCenterY - e.radius,
2 * e.radius, 2 * e.radius);
} else if (e.getClass().equals(Agent.class)) {
double rad = Math.toRadians(((Agent) e).getHeading());
double hunger = ((Agent) e).getHunger();
if (hunger > 1)
hunger = 1;
graph.setColor(new Color((int) Math.round(250 * hunger),
(int) Math.round(250 * (1 - hunger)), (int) 0));
graph.fillOval(eCenterX - e.radius, eCenterY - e.radius,
2 * e.radius, 2 * e.radius);
graph.setColor(new Color(255, 255, 255));
graph.drawLine(
eCenterX,
eCenterY,
(int) Math.round(eCenterX + e.radius
* Math.cos(rad)),
(int) Math.round(eCenterY + e.radius
* Math.sin(rad)));
}
}
}
}
|
4da04c16-c49c-40cf-bb58-9bf0b653ca82
| 3
|
@Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
setUser((User) session.get("User"));
Criteria ucri = myDao.getDbsession().createCriteria(Campaign.class);
ucri.setMaxResults(100);
allcamplist = (List<Campaign>) (ucri.list());
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Try Again ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Try Again ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Try Again ");
e.printStackTrace();
return "error";
}
}
|
5f3b0711-ce8e-4ebb-a9c3-2097ee2da56f
| 9
|
public void transform(JavaMethod javaMethod) {
String shortName = javaMethod.getName();
String fullName = javaMethod.getQualifiedName();
String parameterName = javaMethod.getQualifiedSignature();
if (!javaMethod.isStatic() && (INSTANCE_METHODS.contains(shortName) || INSTANCE_METHODS.contains(fullName) || INSTANCE_METHODS.contains(parameterName))
|| javaMethod.isStatic() && (STATIC_METHODS.contains(shortName) || STATIC_METHODS.contains(fullName) || STATIC_METHODS.contains(parameterName))
//TODO include inspect in lookup mechanism
|| javaMethod.name.startsWith("inspect")) {
javaMethod.shouldInclude = false;
}
}
|
20dbaf0a-8ec1-4eb8-abc4-eece0b15046a
| 2
|
public int getWallDecorationUid(int z, int x, int y) {
GroundTile groundTile = groundTiles[z][x][y];
if (groundTile == null || groundTile.wallDecoration == null) {
return 0;
} else {
return groundTile.wallDecoration.uid;
}
}
|
bda5c49d-4784-4dc9-b55b-440a15b6fe64
| 0
|
public void fireKeyEvent(KeyEvent event) {
processKeyEvent(event);
}
|
3b8549e2-0f61-4144-b5b9-b7cdda8eb2d3
| 1
|
public ClientGUI() {
try {
UnicastRemoteObject.exportObject(this, 0);
mInstance = this;
} catch(RemoteException ex) {
System.out.println(ex.getMessage());
}
mUserName = "";
mUserPass = "";
mMessageWindows = new HashMap<String, MessageWindow>();
mListWindow = new UserListWindow(this);
}
|
ceac03fd-160f-419d-a58c-f859f687652c
| 6
|
public Type intersection(Type type) {
if (type == tError)
return type;
if (type == Type.tUnknown)
return this;
Type top, bottom, result;
bottom = bottomType.getSpecializedType(type);
top = topType.getGeneralizedType(type);
if (top.equals(bottom))
result = top;
else if (top instanceof ReferenceType
&& bottom instanceof ReferenceType)
result = ((ReferenceType) top)
.createRangeType((ReferenceType) bottom);
else
result = tError;
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_TYPES) != 0) {
GlobalOptions.err.println("intersecting " + this + " and " + type
+ " to " + result);
}
return result;
}
|
9be8887e-f238-4131-b283-f98c9693690a
| 4
|
@Test
public void insertTest() {
final int n = 10_000;
Array<Integer> seq = emptyArray();
for(int i = 0; i < n; i++) seq = seq.snoc(i);
assertEquals(n, seq.size());
for(int i = 0; i <= n; i++) {
final Array<Integer> seq2 = seq.insertBefore(i, n);
assertEquals(Integer.valueOf(n), seq2.get(i));
assertEquals(n + 1L, seq2.size());
for(int j = 0; j < n; j++) {
assertEquals(Integer.valueOf(j), seq2.get(j < i ? j : j + 1));
}
}
}
|
725ae304-878f-4b0f-84fe-22ba02133e8a
| 2
|
@Override
public void setLoadStatus(double d) {
if (d >= 0 && d <= 1)
loadStatus = d;
}
|
f092ab65-560c-4b66-af02-d0da605b721e
| 6
|
@Override
public void executeTask() {
System.out.println(this.getClass().getSimpleName() + " EXECUTING");
if (m_ServerSocket == null) {
try {
m_ServerSocket = new ServerSocket(PORT);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
do {
String m_Input;
String response;
try {
// m_ServerSocket.setSoTimeout(1000);
m_RecievingSocket = m_ServerSocket.accept();
PrintWriter out = new PrintWriter(
m_RecievingSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
m_RecievingSocket.getInputStream()));
while ((m_Input = in.readLine()) != null) {
System.out.println("ECHO FROM REGISTRATION SERVLET: "
+ m_Input);
break;
}
Client client = new Client();
client.setUsername(m_Input);
client.setReceivingPort(1337);
System.out.println("Got client: " + client.getUsername());
if (RoutingTable.getInstance().registerClient(client)) {
response = "200";
} else {
response = "401";
}
System.out.println("Response: " + response);
out.println(response);
out.flush();
out.close();
in.close();
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (isExecuting());
onFinished();
}
|
8a847d7a-1179-43c3-90e1-e2977f24b1fe
| 2
|
public RootPane getRootPane() {
if (rootPane == null) {
rootPane = createRootPane();
if (rootPane.getState() != this) {
throw new IllegalStateException("rootPane.getState() != this");
}
}
return rootPane;
}
|
c2e9028e-c05f-4f71-8592-baf07fdcdaf9
| 6
|
public static OS getPlatform() {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win")) return OS.windows;
if (osName.contains("mac")) return OS.macos;
if (osName.contains("solaris")) return OS.solaris;
if (osName.contains("sunos")) return OS.solaris;
if (osName.contains("linux")) return OS.linux;
if (osName.contains("unix")) return OS.linux;
return OS.unknown;
}
|
9170b568-c2ba-4c89-add9-9d49f02996a6
| 1
|
private boolean checkPngEncodingSupport() {
String encodings = System.getProperty("video.snapshot.encodings");
return (encodings != null) && (encodings.indexOf("jpeg") != -1);
}
|
db920750-d87e-4ece-a532-47a539ce405a
| 7
|
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if((mob.isMonster())&&(mob.isInCombat()))
return Ability.QUALITY_INDIFFERENT;
final Room R=mob.location();
if(R!=null)
{
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_MOONALTERING))
return Ability.QUALITY_INDIFFERENT;
}
}
}
return super.castingQuality(mob,target);
}
|
aab90ade-4046-4677-a533-5e5ea0819199
| 8
|
private void renderUnits(Graphics g){
if (settings.isDisplayAllPaths()){
for (int i = 0; i < world.getPlayer().getUnits().size(); i ++){
Unit u = world.getPlayer().getUnits().get(i);
int speed = u.getMaxMovement();
for (int j= 0; j< u.getPath().size(); j ++){
Color color = j == 0 ? PathGenerator.TURN_1_COLOR : PathGenerator.getTurnColor(j / speed);
g.setColor(u.getOwner().getColor());
g.drawString(""+j, u.getPath().get(j).getX() * Tile.SIZE - xOffset + 10, u.getPath().get(j).getY() * Tile.SIZE - yOffset + 10);
g.setColor(color);
g.draw(u.getPath().get(j).getRectangle(xOffset, yOffset));
}
}
}
else if (selectedUnit != null){
for (int i = 0; i < selectedUnit.getPath().size(); i ++){
Color color = i == 0 ? PathGenerator.TURN_1_COLOR : PathGenerator.getTurnColor(i / selectedUnit.getMaxMovement());
g.setColor(color);
g.draw(selectedUnit.getPath().get(i).getRectangle(xOffset, yOffset));
}
}
for (Faction f: world.getFactions()){
f.renderArmies(g, xOffset, yOffset, mouseX, mouseY);
}
}
|
14376d3d-25c5-4057-be5b-93e96cf60e30
| 7
|
public void deathAni()
{
switch (aniNum)
{
case 0:
sprt = imgD1.getImage();
if(Game.tickCount2 == game.DELAY){
aniNum = 1;
}
break;
case 1:
sprt = imgD2.getImage();
if(Game.tickCount2 == game.DELAY){
aniNum = 2;
}
break;
case 2:
sprt = imgD5.getImage();
if(Game.tickCount2 == game.DELAY){
aniNum = 3;
}
break;
case 3:
sprt = sad.getImage();
}
}
|
119810f9-301e-46ed-a506-3535591b8870
| 0
|
public String getUserId() {
return userId;
}
|
a128e78b-2051-49b7-80d4-03ea23a5f582
| 2
|
public int nbMaxCercle (){
Coord dim = this.env.getDimension();
int[] dist = new int[4];
dist[0] = this.coord.distance(Coord.NULL);
dist[1] = this.coord.distance(new Coord(dim.x, 0));
dist[2] = this.coord.distance(new Coord(0, dim.y));
dist[3] = this.coord.distance(dim);
int gdist = 0;
for(int i = 0 ; i < 4 ; i++){
if(dist[i] > gdist)
gdist = dist[i];
}
return cercleChampsVision(gdist);
}
|
971a3a47-10f3-4357-9cd2-6d4ea8d53270
| 5
|
protected long packChildren(String destination, long parentDirOffset, long nextAddrOffset) {
long currentOffset = nextAddrOffset;
Iterator<VDKInnerDirectory> it = getChildren().iterator();
List<VDKInnerDirectory> directoryList = new ArrayList<VDKInnerDirectory>();
while (it.hasNext()) {
VDKInnerDirectory d = it.next() ;
if(d instanceof VDKInnerFile) {
if(!it.hasNext())
d.setNextAddrOffset(-1);
currentOffset = d.packChildren(destination, 0, currentOffset);
}
else directoryList.add(d);
}
for(VDKInnerDirectory d : directoryList) {
// Determines offsets and write the directory.
d.setOffset(currentOffset);
d.setParentDirOffset(currentOffset + VDK1FilePattern.getDirectoryHeaderLength());
currentOffset += VDK1FilePattern.getDirectoryHeaderLength();
// Determines offsets and write the dot directory next to the directory.
d.getDotDirectory().setOffset(currentOffset);
d.getDotDirectory().setParentDirOffset(currentOffset);
d.getDotDirectory().setNextAddrOffset(currentOffset + VDK1FilePattern.getDirectoryHeaderLength());
currentOffset = writeDirectory(destination, d.getDotDirectory(), currentOffset);
// Determines offsets and write the parent accessor directory next to the dot directory.
d.getParentAccessorDirectory().setOffset(currentOffset);
d.getParentAccessorDirectory().setParentDirOffset(parentDirOffset);
d.getParentAccessorDirectory().setNextAddrOffset(d.getDotDirectory().getOffset() + VDK1FilePattern.getHeaderLength());
currentOffset = writeDirectory(destination, d.getParentAccessorDirectory(), currentOffset);
currentOffset = d.packChildren(destination, d.getDotDirectory().getOffset(), currentOffset);
// Write the directory's next address offset.
if(!((directoryList.indexOf(d) + 1) == directoryList.size()))
d.setNextAddrOffset(currentOffset);
else d.setNextAddrOffset(VDK1FilePattern.getFinalDirectoryToken());
writeDirectory(destination, d, d.getOffset());
}
return currentOffset;
}
|
3c0a42fc-a1d1-4722-a8ff-816074abb1cc
| 4
|
public static void main(String[] args) {
Treap<Integer> t;
Random rand = new Random();
double sommeLog = 0.0;
int sommeHauteur = 0;
for (int j = 0; j < 100; j++) {
for (int nombreElement = 1; nombreElement < 100; nombreElement++) {
t = new Treap<>();
for (int i = 0; i < nombreElement; i++) {
try {
t.insererClefTreap(rand.nextInt(1000));
} catch (Exercice1Exception ex) {
Logger.getLogger(VerificationHauteurTreap.class.getName()).log(Level.SEVERE, null, ex);
}
}
double log = Math.log(nombreElement);
int hauteur = t.computeHauteur();
sommeLog = sommeLog + log;
sommeHauteur = sommeHauteur + hauteur;
System.out.println("O(log("+nombreElement+")) = O("+log+") = ? "+hauteur);
}
System.out.println("sommeHauteur/sommeLog = " + sommeHauteur + "/" + sommeLog + " = " + sommeHauteur / sommeLog);
System.out.println("O(hauteur) = " + sommeHauteur / sommeLog + " * nombreElement");
}
}
|
f049a1d8-d5b4-4bd5-a8fb-b36934be8f5f
| 5
|
public void readFeat(String path) throws IOException {
FileInputStream is = null;
DataInputStream dis = null;
try{
is = new FileInputStream(path);
dis = new DataInputStream(new BufferedInputStream(is));
int frames = (dis.readInt())/39;
//System.out.println(frames);
feat = new float[frames][39];
for(int i = 0; i < frames; i++)
for(int j = 0; j < 39; j++)
feat[i][j] = dis.readFloat();
}catch(Exception e){
System.out.println(path + " file missing");
e.printStackTrace();
}
finally{
if(is != null)is.close();
if(dis != null)dis.close();
}
}
|
39f63653-8c5e-4089-9a38-c61b6cf120ed
| 5
|
@SuppressWarnings("unchecked")
public synchronized long generateRelationId(String key, List<Long> ids, List<String> types, List<String> roles, List<String[]> tags, List<String> shapesId){
Long id = null;
if (totalRelations.get(key) == null)
totalRelations.put(key, new ConcurrentHashMap<RelationOsm, Long>());
if (!totalRelations.isEmpty())
id = totalRelations.get(key).get(new RelationOsm(ids,types,roles));
if (id != null){
if (tags != null)
((RelationOsm) getKeyFromValue((Map< String, Map<Object, Long>>) ((Object)totalRelations), key, id)).addTags(tags);
return id;
}
else{
idrelation--;
RelationOsm r = new RelationOsm(ids,types,roles);
r.setShapes(shapesId);
if (tags != null)
r.addTags(tags);
totalRelations.get(key).putIfAbsent(r, idrelation);
return idrelation;
}
}
|
72a4b7f1-598b-4b6c-a8ca-7fe7bbfc29e7
| 6
|
public boolean lisaaTunnusPari(Tunnus tunnus1, Tunnus tunnus2) {
for (TunnusPari tunnusPari : getTunnusParit()) {
if ((tunnusPari.getTunnus1().equals(tunnus1) || tunnusPari.getTunnus2().equals(tunnus1))
&& (tunnusPari.getTunnus1().equals(tunnus2) || tunnusPari.getTunnus2().equals(tunnus2))
&& (!tunnus1.equals(tunnus2))) {
return false;
}
}
this.getTunnusParit().add(new TunnusPari(tunnus1, tunnus2));
return true;
}
|
42f9c0fe-bf8c-4b15-883c-ad0413a2ba7b
| 0
|
@Override
public void run() {/**/}
|
e4b966e6-dbc4-40a5-8d79-73fb764c4d4c
| 9
|
static int longestPalSubstr(char[] str)
{
int maxLength = 1; // The result (length of LPS)
int start = 0;
int len = str.length;
int low, high;
// One by one consider every character as center point of
// even and length palindromes
for (int i = 1; i < len; ++i)
{
// Find the longest even length palindrome with center points
// as i-1 and i.
low = i - 1;
high = i;
while (low >= 0 && high < len && str[low] == str[high])
{
if (high - low + 1 > maxLength)
{
start = low;
maxLength = high - low + 1;
}
--low;
++high;
}
// Find the longest odd length palindrome with center
// point as i
low = i - 1;
high = i + 1;
while (low >= 0 && high < len && str[low] == str[high])
{
if (high - low + 1 > maxLength)
{
start = low;
maxLength = high - low + 1;
}
--low;
++high;
}
}
System.out.printf("Longest palindrome substring is: ");
printSubStr(str, start, start + maxLength - 1);
return maxLength;
}
|
c5fc5980-7642-4ded-a9c8-8ada7fa899f9
| 1
|
public MOCOM_Comparator(int col, boolean decreasing_order) {
this.col = col;
if (decreasing_order) {
order = -1;
} else {
order = 1;
}
}
|
5a30e49e-bb25-4f20-9b43-2fea8c954604
| 9
|
public boolean batchFinished() throws Exception {
if (getInputFormat() == null) {
throw new IllegalStateException("No input instance format defined");
}
if (m_removeFilter == null) {
// establish attributes to remove from first batch
Instances toFilter = getInputFormat();
int[] attsToDelete = new int[toFilter.numAttributes()];
int numToDelete = 0;
for(int i = 0; i < toFilter.numAttributes(); i++) {
if (i==toFilter.classIndex()) continue; // skip class
AttributeStats stats = toFilter.attributeStats(i);
if (stats.distinctCount < 2) {
// remove constant attributes
attsToDelete[numToDelete++] = i;
} else if (toFilter.attribute(i).isNominal()) {
// remove nominal attributes that vary too much
double variancePercent = (double) stats.distinctCount
/ (double)(stats.totalCount - stats.missingCount) * 100.0;
if (variancePercent > m_maxVariancePercentage) {
attsToDelete[numToDelete++] = i;
}
}
}
int[] finalAttsToDelete = new int[numToDelete];
System.arraycopy(attsToDelete, 0, finalAttsToDelete, 0, numToDelete);
m_removeFilter = new Remove();
m_removeFilter.setAttributeIndicesArray(finalAttsToDelete);
m_removeFilter.setInvertSelection(false);
m_removeFilter.setInputFormat(toFilter);
for (int i = 0; i < toFilter.numInstances(); i++) {
m_removeFilter.input(toFilter.instance(i));
}
m_removeFilter.batchFinished();
Instance processed;
Instances outputDataset = m_removeFilter.getOutputFormat();
// restore old relation name to hide attribute filter stamp
outputDataset.setRelationName(toFilter.relationName());
setOutputFormat(outputDataset);
while ((processed = m_removeFilter.output()) != null) {
processed.setDataset(outputDataset);
push(processed);
}
}
flushInput();
m_NewBatch = true;
return (numPendingOutput() != 0);
}
|
ba1af83a-b1cd-41fa-ad6d-9c0ce13ebfe6
| 9
|
private void setMine(int mineNum){
unknowArea = this.ROWS * this.COLS - mineNum;
Random random = new Random();
int count = 0;
//初始化并放入MineField
for(int i = 0;i<cas.length;i++){
for(int j = 0;j<cas[i].length;j++){
cas[i][j] = new CurrentArea();
cas[i][j].setVx(i);
cas[i][j].setVy(j);
cas[i][j].addMouseListener(new click());
this.add(cas[i][j]);
}
}
//初始化地雷,并放入mineArray,并初始化unknowArea
for (int i = 0;i<mineNum;i++){ // 小于等于号导致多布一颗雷
int x = random.nextInt(this.ROWS-1);
int y = random.nextInt(this.ROWS-1);
if(cas[x][y].getState()==9) {
i-- ; //没有此处 导致判断胜利错误
continue;
}
else
cas[x][y].setState(9);
minesArray.add(cas[x][y]);
}
//初始化非雷的区域数字
for(int i = 0;i<cas.length;i++){
for(int j = 0;j<cas[i].length;j++){
if(cas[i][j].getState()==9) continue;
else{
ArrayList<CurrentArea> al =getNeighbours(cas[i][j]);
for(Iterator<CurrentArea> it = al.iterator();it.hasNext();){
CurrentArea neighbour = it.next();
if(neighbour.getState()==9) count++;
}
}
cas[i][j].setState(count);
count = 0;
}
}
}
|
3e6c9969-0f65-4914-8110-2ce15ce0a132
| 9
|
private void jLabelAceptarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabelAceptarMouseReleased
try {
//Asigna en variables los jTextField
String nombreCancion = jTextFieldNombre.getText().trim();
String nombreAlbum = jTextFieldAlbum.getText().trim();
String nombreArtista = jTextFieldArtista.getText().trim();
String year = jFormattedTextFieldYear.getText().trim();
String nombreGenero = jTextFieldGenero.getText().trim();
if (DireccionMusica==null){
mostrarMensajeError("No seleccionó el archivo mp3", "MusicTECPlayer");
jLabelCancelarMouseReleased(evt);
return;
}
String rutaCancion = DireccionMusica.trim();
String rutaImagenCancion = DireccionFoto.trim();
//Condiciona si los datos están bien scritos
if (nombreAlbum.equals(Parametros.SIN_ASIGNAR)
|| nombreArtista.equals(Parametros.SIN_ASIGNAR)
|| nombreCancion.equals(Parametros.SIN_ASIGNAR)
|| nombreGenero.equals(Parametros.SIN_ASIGNAR)
|| year.equals(Parametros.SIN_ASIGNAR)
|| rutaCancion.equals(Parametros.SIN_ASIGNAR)
|| year.length() != 4) {
mostrarMensajeError("Por favor completar todos los datos",
"MusicTECPlayer");
} else {
//Instancia a la clase para almacenar los datos.
Cancion nuevaCancion = new Cancion(nombreCancion, nombreArtista,
nombreGenero, nombreAlbum, year, rutaCancion,rutaImagenCancion);
//Funciones que se le asignan al frame Reproductor.java.
Reproductor.listaCanciones.agregarAlInicio(nuevaCancion);
reproductor.actualizarListaCanciones();
mostrarMensajeInformacion("La canción fue agregada "
+ "correctamente", "Correcto");
//Método de cierre de la ventana
jLabelCancelarMouseReleased(evt);
}
} catch (HeadlessException e) {
mostrarMensajeError("Error en el registro de los datos", "Error");
}
}//GEN-LAST:event_jLabelAceptarMouseReleased
|
bc93ec0d-57b0-4514-8243-10193f2508f5
| 5
|
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Cliente)) {
return false;
}
Cliente other = (Cliente) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
f1f9399f-5ce8-42c9-afb0-86692baecea9
| 0
|
public String getSpeech() {
return speech;
}
|
19a6dd5d-fac5-4f0d-a50b-9e4863747097
| 7
|
private String translateTransitions(STS sts, Object translatedEntity) {
String translation = "";
Set<Set<Transition>> transitionGroups = new HashSet<Set<Transition>>();
for (State state : sts.getStates()) {
// System.out.println("Looking at state " + state);
Set<Transition> transitions =
sts.getTransitionsFromState(state);
// System.out.println(transitions.size() + " outgoing transitions ");
List<Transition> remainingTrans = new ArrayList<Transition>(transitions);
while (!remainingTrans.isEmpty()) {
Transition trans1 = remainingTrans.remove(0);
Set<Transition> newGroup = new HashSet<Transition>();
newGroup.add(trans1);
for (Transition trans2 : transitions) {
if (!trans1.getTarget().equals(trans2.getTarget()) &&
trans1.getAction().equals(trans2.getAction()) &&
trans1.getCondition().equals(trans2.getCondition())) {
newGroup.add(trans2);
remainingTrans.remove(trans2);
}
}
transitionGroups.add(newGroup);
}
}
for (Set<Transition> trGroup : transitionGroups) {
translation += translateTransitionGroup(trGroup, translatedEntity);
}
return translation;
}
|
aab77ed6-020a-4da1-b68a-694ad484680a
| 5
|
@Override
public boolean wipeTable(String table) {
Statement statement = null;
String query = null;
try {
if (!this.checkTable(table)) {
this.writeError("Error at Wipe Table: table, " + table + ", does not exist", true);
return false;
}
statement = connection.createStatement();
query = "DELETE FROM " + table + ";";
statement.executeQuery(query);
return true;
} catch (SQLException ex) {
if (!(ex.getMessage().toLowerCase().contains("locking") || ex.getMessage().toLowerCase().contains("locked")) && !ex.toString().contains("not return ResultSet"))
this.writeError("Error at SQL Wipe Table Query: " + ex, false);
return false;
}
}
|
b920800e-58d5-44b4-9995-6ac4e251760b
| 1
|
public void calculateTotalsW() {
for (double w : consumptionWatt)
systemConsumptionW += w;
systemConsumptionW=Math.round(systemConsumptionW*100)/100000.0;
}
|
0cf94f5b-a7a7-4327-a52c-30ee7b128f61
| 2
|
public void updateIO(Elem tek)
{
for(int i = 0; i < inputNo; i++)
inputNodes[i].setActivation(tek.X[i]);
for(int i = 0; i < outputNo; i++)
outputNodes[i].setYAccuali(tek.actualY[i]/scale);
}
|
cf330269-a16f-46f7-a3fe-8c877395aadd
| 0
|
public int GetTime()
{
return TIME;
}
|
725174dc-33d0-4e8b-b318-bf05873509cb
| 3
|
public void step() {
Grid<Actor> gr = getGrid();
ArrayList<Actor> actors = new ArrayList<Actor>();
for (Location loc : gr.getOccupiedLocations())
actors.add(gr.get(loc));
for (Actor a : actors) {
// only act if another actor hasn't removed a
if (a.getGrid() == gr)
a.act();
}
}
|
aa1c62bc-5d8c-4919-9738-aa9349c2a5db
| 7
|
public String[] getOptions() {
int i;
Vector result;
String[] options;
File file;
result = new Vector();
options = super.getOptions();
for (i = 0; i < options.length; i++)
result.add(options[i]);
if (getOutputClassification())
result.add("-classification");
if (getRemoveOldClass())
result.add("-remove-old-class");
if (getOutputDistribution())
result.add("-distribution");
if (getOutputErrorFlag())
result.add("-error");
file = getSerializedClassifierFile();
if ((file != null) && (!file.isDirectory())) {
result.add("-serialized");
result.add(file.getAbsolutePath());
}
else {
result.add("-W");
result.add(getClassifierSpec());
}
return (String[]) result.toArray(new String[result.size()]);
}
|
9bc26483-14eb-4a10-854f-9dacb8c282d5
| 1
|
private static History HistoryObject(ResultSet rs) {
History newHistory = null;
try {
newHistory = new History(rs.getInt(rs.getMetaData().getColumnName(1)),
rs.getString(rs.getMetaData().getColumnName(2)),
rs.getString(rs.getMetaData().getColumnName(3)),
rs.getString(rs.getMetaData().getColumnName(4)));
} catch (SQLException e) {
Error_Frame.Error(e.toString());
}
return newHistory;
}
|
c194aff7-a682-4286-9bf3-e2f500c1a521
| 1
|
public void gananciaDelDia(){
for (int len = ventas.size(), i = 0; i < len; i++) {
Venta unaVenta = ventas.get(i);
ganancias+= unaVenta.prenda.precioFinal();
}
System.out.println("Las ganancias del dia son:" +ganancias);
}
|
3ff510a6-fc58-4c71-95b2-a3b2ba075339
| 1
|
private final void addUser(String channel, User user) {
channel = channel.toLowerCase();
synchronized (_channels) {
Hashtable users = (Hashtable) _channels.get(channel);
if (users == null) {
users = new Hashtable();
_channels.put(channel, users);
}
users.put(user, user);
}
}
|
3e0e9d84-3f48-4c40-a6fd-0ea8647f0116
| 4
|
@Override
public void calculate(Loan loan)
{
if (loan.getCalculationWanted() == CalculationAction.MONTHLY_PAYMENT)
{
// increment the payment number
loan.setPaymentNumber(loan.getPaymentNumber() + 1);
// only perform the monthly payment calcuation once
if(loan.getMonthlyPayment().doubleValue() == 0) {
double monthlyInterest = (loan.getAnnualPercentageRage() != 0)?
loan.getAnnualPercentageRage() / 12 : 0;
double payment = 0;
if (monthlyInterest > 0)
{
payment = loan.getPrinciple().doubleValue() *
(monthlyInterest / (1 - Math.pow((1/(1 + monthlyInterest))
, loan.getNumberOfMonths()))) ;
} else {
payment =
loan.getPrinciple().doubleValue() /
loan.getNumberOfMonths();
}
loan.setMonthlyPayment(new BigDecimal(payment));
}
// set the total amount paid so far
BigDecimal total =
loan.getTotalPayments().add(loan.getMonthlyPayment());
loan.setTotalPayments(total);
// next component to evaluate the interest paid
loan.setCalculationWanted(CalculationAction.INTEREST_PAYMENT);
} else {
getNextChain().calculate(loan);
}
}
|
998ddf7d-b615-4518-8b18-139461b474a8
| 2
|
@Test
public void testReadCluster() throws UnsupportedEncodingException {
System.out.println("extractFile");
boolean expResult = true;
boolean result = false;
f32Extractor.openFAT(new File(PATH));
f32Extractor.searchFAT32Element();
byte[] actualArr = f32Extractor.readCluster(0);
for (int i = 0; i < actualArr.length - 1; i++) {
if (actualArr[i] != 0)
result = true;
}
assertEquals(expResult, result);
}
|
b080696a-6e91-4076-820d-274d6386b13d
| 2
|
public MainForm(String[] args) {
initComponents();
try {
List<QueryDefinition> queries = Settings.getInstance().getQueries();
for(QueryDefinition query : queries) {
this.addServiceTab(query);
}
} catch (Exception e) {
logger.error("Error loading tabs.", e);
}
this.setTitle("Test Bench: " + Version.VERSION);
}
|
18bff43e-0a8c-4679-be94-cc78dca9fddd
| 9
|
public void Update(ArrayList<Sprite> targets) {
checkLives();
arrowtimer++;
if (arrowtimer > 200) {
arrowtimer = 0;
if (target == Window.blankSprite) {
for (int i = 0; i < 4; i++) {
try {
target = targets.get(num - i);
boolean tmoving = target.moving;
double dis = Math.sqrt(Math.pow(x-target.x, 2) + Math.pow(y-target.y, 2));
double xaim = 0;
if (tmoving == true) {
if (target.name != "GKing") {
xaim = target.x + (dis/3);
} else {
xaim = target.x + dis/2;
}
} else {
xaim = target.x;
}
if (xaim < x) {
setImage("/quest2/archer.gif");
facing = 0;
} else {
setImage("/quest2/archer2.png");
facing = 1;
}
if (facing == 0) {
arrows.add(new Arrow("/quest2/arrow.gif", x - 15, y + 10, 32, 7, xaim, target.y, this, facing));
} else {
arrows.add(new Arrow("/quest2/arrow.gif", x + 15, y + 10, 32, 7, xaim, target.y, this, facing));
}
target = Window.blankSprite;
break;
} catch (Exception e) {
//pass
}
}
}/* else {
boolean tmoving = target.moving;
double dis = Math.sqrt(Math.pow(x-target.x, 2) + Math.pow(y-target.y, 2));
double xaim = 0;
if (tmoving == true) {
if (target.name != "GKing") {
xaim = target.x + (dis/3);
} else {
xaim = target.x + dis/2;
}
} else {
xaim = target.x;
}
if (xaim < x) {
setImage("/quest2/archer.gif");
facing = 0;
} else {
setImage("/quest2/archer2.png");
facing = 1;
}
if (facing == 0) {
arrows.add(new Arrow("/quest2/arrow.gif", x - 15, y + 10, 32, 7, xaim, target.y, this, facing));
} else {
arrows.add(new Arrow("/quest2/arrow.gif", x + 15, y + 10, 32, 7, xaim, target.y, this, facing));
}
}*/
}
for (int i = 0; i < arrows.size(); i++) {
arrows.get(i).Update();
}
}
|
0f11ea0c-59f6-4e5d-8a65-dc0d98a561c2
| 9
|
*/
protected int scoreTradeOutcome(ResourceSet tradeOutcome)
{
int score = 0;
ResourceSet tempTO = tradeOutcome.copy();
if ((ourPlayerData.getNumPieces(PlayingPiece.SETTLEMENT) >= 1) && (ourPlayerData.hasPotentialSettlement()))
{
while (tempTO.contains(Game.SETTLEMENT_SET))
{
score += 2;
tempTO.subtract(Game.SETTLEMENT_SET);
}
}
if ((ourPlayerData.getNumPieces(PlayingPiece.ROAD) >= 1) && (ourPlayerData.hasPotentialRoad()))
{
while (tempTO.contains(Game.ROAD_SET))
{
score += 1;
tempTO.subtract(Game.ROAD_SET);
}
}
if ((ourPlayerData.getNumPieces(PlayingPiece.CITY) >= 1) && (ourPlayerData.hasPotentialCity()))
{
while (tempTO.contains(Game.CITY_SET))
{
score += 2;
tempTO.subtract(Game.CITY_SET);
}
}
//D.ebugPrintln("Score for "+tradeOutcome+" : "+score);
return score;
}
|
8f5438ef-1678-4799-a116-9b650a1d7862
| 9
|
public void testResetAfterTimeout() {
try {
final CyclicBarrier start = new CyclicBarrier(3);
final CyclicBarrier barrier = new CyclicBarrier(3);
for (int i = 0; i < 2; i++) {
Thread t1 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS); }
catch(TimeoutException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
Thread t2 = new Thread(new Runnable() {
public void run() {
try { start.await(); }
catch (Exception ie) {
threadFail("start barrier");
}
try { barrier.await(); }
catch(BrokenBarrierException ok) {}
catch (Throwable thrown) {
unexpectedException();
}}});
t1.start();
t2.start();
try { start.await(); }
catch (Exception ie) { threadFail("start barrier"); }
t1.join();
t2.join();
assertTrue(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
barrier.reset();
assertFalse(barrier.isBroken());
assertEquals(0, barrier.getNumberWaiting());
}
}
catch (Exception ex) {
unexpectedException();
}
}
|
83c71ab6-ee56-4570-a8b1-36df17d30201
| 7
|
public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and when the
// cumulative sum is less than 1.0 (as a result of floating-point roundoff error)
while (true) {
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum > r) return i;
}
}
}
|
eac0d173-6606-4b93-ab96-8edff03201e0
| 2
|
private void save(String litraV,String oximaV){
/*
* apothikeuei ta stoixia sthn vash elegxei an apothikeutikan kai emfanizei minima epituxia i apotuxias antistoixa
*/
String query="insert into anefodiasmoi(litra,oxima_id) values(?,?)"; //dhmiourgia query
try {
con.pS=con.conn.prepareStatement(query);
con.pS.setString(1, litraV);
con.pS.setInt(2, Integer.parseInt(oximaV));
} catch (SQLException e) {
e.printStackTrace();
}
if(con.makeQuery(query)){ //ektelei to query me thn vohthia tiw function makeQuery(String query)
JOptionPane.showMessageDialog(null, "Saved!"); //an den upardxei lathos emfanizei to minima epituxias
litra.setText("");
}else{
JOptionPane.showMessageDialog(null, "Something went wrong Please Try later!"); //an uparxei lathos tote emfanizei minima lathous
}
}
|
0348454d-25f1-4f50-aa43-1da621436e73
| 9
|
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
if (!p.isOp()) return;
if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
if (p.getItemInHand().getType() == Material.CARROT_STICK) {
event.setCancelled(true);
Database db = new Database();
Block b = event.getClickedBlock();
int worldId = 1;
switch (b.getWorld().getEnvironment()) {
case NETHER:
worldId = 2;
break;
case THE_END:
worldId = 3;
break;
}
int locationId = db.getLocationId(b.getX(), b.getY(), b.getZ(), worldId);
if (locationId == 0) {
p.sendMessage(ChatColor.RED + "No History for this block");
return;
}
ArrayList<LocationHistory> history = db.getHistory(locationId);
if (history.size() == 0) {
p.sendMessage(ChatColor.RED + "No History for this block");
return;
}
boolean alt = false;
p.sendMessage("Block History for X: " + b.getX() + " Y: " + b.getY() + " Z:" + b.getZ());
for (LocationHistory h : history) {
p.sendMessage((alt ? ChatColor.GOLD : ChatColor.LIGHT_PURPLE) + h.toString());
alt = !alt;
}
}
}
}
|
98cc7efc-b603-4214-bbbe-cc7df23ffd62
| 9
|
public static void doPagination(String table, String where, Class clazz, HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if ((request.getParameter("page") != null) && (request.getParameter("rows") != null)
&& (request.getParameter("sidx") != null) && (request.getParameter("sord") != null)) {
int page = Integer.parseInt(request.getParameter("page"));
int rows = Integer.parseInt(request.getParameter("rows"));
ArrayList<BusinessObject> list = new ArrayList<BusinessObject>();
int count = Dal.getCount(table, where);
int total_pages = (int) ((count > 0) ? Math.ceil((double) count / rows) : 0);
if (page > total_pages) {
page = total_pages;
}
int start = rows * page - rows;
if (start < 0) start = 0;
ResultSet records = Dal.doQuery(String.format("SELECT * FROM %s%s ORDER BY %s %s LIMIT %d, %d", table, where, request.getParameter("sidx"), request.getParameter("sord"), start, rows));
Constructor constructor = clazz.getConstructor(ResultSet.class);
while (records.next()) {
list.add((BusinessObject) constructor.newInstance(records));
}
out.append(new GsonBuilder().create().toJson(new ResponseList(page, total_pages, list)).replace("\"[", "[").replace("]\"", "]").replace("\\", ""));
out.close();
}
} catch (Exception ex) {
Logger.getLogger(Pagination.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
b0c65ab4-cf37-4549-b236-de57a70a0273
| 8
|
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String methodType = request.getParameter("action"); //get action value from the URL
if (methodType.equalsIgnoreCase(PLAYLISTS))
{
// A good test to see if your S3Service can connect to S3 is to list all the buckets you own.
// Fetching all the buckets that you own and return them as a JSON array for client to process
S3Bucket[] myBuckets = TransferManager.listAllBuckets(s3Service); //get all buckets
JSONArray jarray = new JSONArray();
for (S3Bucket bucket : myBuckets)
{
jarray.add(bucket.getName()); //put bucket list into JSON array
}
out.println(jarray.toString());
} else if (methodType.equalsIgnoreCase(CREATEPLAYLIST))
{
String bucketName = request.getParameter("bucketname");
S3Bucket myBucket = TransferManager.createBucket(s3Service, bucketName); //get all buckets
if (myBucket == null)
{
JSONObject jObj = new JSONObject();
jObj.put("result", "error");
out.println(jObj.toString());
} else
{
JSONObject jObj = new JSONObject();
jObj.put("result", "playlistcreated");
out.println(jObj.toString());
}
} else if (methodType.equalsIgnoreCase(DELETEPLAYLIST))
{
//Leave to the students to complete
} else if (methodType.equalsIgnoreCase(DELETEMUSIC))
{
//Leave to the students to complete
} else if (methodType.equalsIgnoreCase(MUSICLISTS))
{
String playListName = request.getParameter("playlistname");
S3Object[] s3Objects = TransferManager.listAllObjects(s3Service, playListName);
JSONArray jArray = new JSONArray();
for (S3Object s3Object : s3Objects)
{
JSONObject musicJson = new JSONObject();
musicJson.put("musicname", s3Object.getName());
//Think about what more information you will need on your music player side for each individual music file?
jArray.add(musicJson);
}
out.println(jArray.toString());
}
} finally
{
out.close();
}
}
|
443758e1-a5f7-4216-9677-6e26ebcd5e71
| 6
|
public void write(int i, byte abyte0[]) throws IOException {
if (closed)
return;
if (hasIOError) {
hasIOError = false;
throw new IOException("Error in writer thread");
}
if (buffer == null)
buffer = new byte[5000];
synchronized (this) {
for (int l = 0; l < i; l++) {
buffer[buffIndex] = abyte0[l];
buffIndex = (buffIndex + 1) % 5000;
if (buffIndex == (writeIndex + 4900) % 5000)
throw new IOException("buffer overflow");
}
if (!isWriter) {
isWriter = true;
rsApplet.startRunnable(this, 3);
}
notify();
}
}
|
df0fecc1-79b9-40c6-b243-a5b1ecf95c01
| 9
|
protected void filter()
{ // if we are in the comment state
if(state.equals(State.COMMENT))
{ // if we are just entering this state
if(comment == null)
{ // The token is supposed to be a comment.
// We keep a reference to it and set the count to one
comment = (TComment) token;
//text = new StringBuffer(comment.getText());
count = 1;
token = null; // continue to scan the input.
}
else
{
boolean no_exception = true;
// we were already in the comment state
//text.append(token.getText()); // accumulate the text.
if(token instanceof TComment)
count++;
else if(token instanceof TCommentEnd)
count--;
else if(token instanceof EOF){
if(count != 0){
try {
no_exception = false;
token = comment;
throw new parser.ParserException(token, "Parêntesis não balanceados!");
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(count != 0 && no_exception)
token = null; // continue to scan the input.
else
{ //comment.setText(text.toString());
token = comment; //return a comment with the full text.
state = State.NORMAL; //go back to normal.
comment = null; // We release this reference.
} }
} }
|
0306ce3f-e86c-4fe1-bc6c-03514f9fb7d5
| 3
|
public void remove( BKnoop<E> aChild ) {
if( aChild == null )
throw new IllegalArgumentException(
"Argument is null" );
if( !isChild( aChild ) )
throw new IllegalArgumentException(
"Argument is geen kind" );
if( aChild == leftChild ) {
leftChild.parent = null;
leftChild = null;
}
else {
rightChild.parent = null;
rightChild = null;
}
}
|
8987a850-16a1-4784-a811-b17ed5ae6160
| 3
|
@DBCommand
public boolean leave(CommandSender sender, Iterator<String> args) {
if(!sender.hasPermission("db.leave")) {
sender.sendMessage(ChatColor.RED + "You don't have permission to use this command!");
return true;
}
if(!(sender instanceof Player)) {
sender.sendMessage("This command must be used by player");
return true;
}
if(!mm.hasPlayer(sender.getName())) {
return true;
}
mm.removePlayer(mm.getMinigamePlayer(sender.getName()));
sender.sendMessage(GREEN + "Left current minigame.");
return true;
}
|
a1e0fd6d-d671-4ab6-a70b-4f2e6b8e32ed
| 1
|
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
reload();
} catch (IOException ex) {
logger.log(level.ERROR, "Error while loading devices! Stack trace will be printed to console...");
JOptionPane.showMessageDialog(null, "An error occured while loading currently connected devices.\n"
+ "Please terminate and re-run the erronious step to determine where the error has occurred.", "Error While Loading Devices.", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_jButton2ActionPerformed
|
e490f1ce-c727-4973-bbed-ba0f89e09c47
| 9
|
private JButton getBoton() {
if (boton == null) {
boton = new JButton();
boton.setText("Anular");
boton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int[] res;
String[] anulaciones;
int selec=0;
boolean b;
for(int i=0;i<vectReservas.size();i++){
b = ((Boolean)tabla.getValueAt(i,3)).booleanValue();
if (b){selec++;}
}
//alerta si no se selecciona ninguna reserva
if(selec==0){
JFrame alerta = new JFrame();
try {
JOptionPane.showMessageDialog(alerta,
"Selecciona alguna reserva para anular",
"Alerta", JOptionPane.WARNING_MESSAGE);
} catch (Exception a) {
System.out.println("error mostrando dialogo");
a.printStackTrace();
}
}else{
res = new int[selec];
anulaciones = new String[selec];
int pos=0;
for(int i=0;i<vectReservas.size();i++){
b = ((Boolean)tabla.getValueAt(i,3)).booleanValue();
if (b){
anulaciones[pos]=(String)tabla.getValueAt(i, 0);
pos++;
}
}
try {
res = PantallaInicio.interfazfachada.anularReservas(anulaciones);
} catch (RemoteException e1) {
System.out.println("Error en la conexi*n remota. ListadoReservas");
e1.printStackTrace();
} catch (Exception e1) {
System.out.println("Error al anular reservas");
e1.printStackTrace();
}
ResultadosAnular resu = new ResultadosAnular(anulaciones,res);
ListadoReservas.this.setVisible(false);
resu.setVisible(true);
}
}
});
}
return boton;
}
|
5e79b38c-fc04-4281-bd78-aa9fe5f2ce8c
| 2
|
public boolean peutSupprimer(Utilisateur utilisateur) {
return utilisateur != null && (utilisateur.equals(getAuteur()) || utilisateur.getRole().getValeur() >= Role.Moderateur.getValeur());
}
|
3df32e70-1eee-498c-9417-781d9a2008e0
| 3
|
public static boolean libraryCompatible( Class libraryClass )
{
if( libraryClass == null )
{
errorMessage( "Parameter 'libraryClass' null in method" +
"'librayCompatible'" );
return false;
}
if( !Library.class.isAssignableFrom( libraryClass ) )
{
errorMessage( "The specified class does not extend class " +
"'Library' in method 'libraryCompatible'" );
return false;
}
Object o = runMethod( libraryClass, "libraryCompatible",
new Class[0], new Object[0] );
if( o == null )
{
errorMessage( "Method 'Library.libraryCompatible' returned " +
"'null' in method 'libraryCompatible'" );
return false;
}
return( ( (Boolean) o ).booleanValue() );
}
|
86699281-6463-4448-8b6c-69a0a4366ac2
| 5
|
protected void updateView(String machineFileName, String input, JTableExtender table) {
ArrayList machines = this.getEnvironment().myObjects;
Object current = null;
if(machines != null) current = machines.get(0);
else current = this.getEnvironment().getObject();
if(current instanceof Automaton && ((InputTableModel)table.getModel()).isMultiple){
int spot = this.getMachineIndexBySelectedRow(table);
Automaton cur = null;
if(spot != -1) cur = (Automaton)machines.get(spot);
else cur = (Automaton)this.getEnvironment().getObject();
AutomatonPane newAP = new AutomatonPane(cur);
newAP.addMouseListener(new ArrowDisplayOnlyTool(newAP, newAP.getDrawer()));
JSplitPane split = SplitPaneFactory.createSplit(getEnvironment(), true,
0.5, newAP, myPanel);
MultiplePane mp = new MultiplePane(split);
EnvironmentFrame frame = Universe.frameForEnvironment(getEnvironment());
String newTitle = cur.getFileName();
if(newTitle != "") frame.setTitle(newTitle);
getEnvironment().remove(getEnvironment().getActive());
getEnvironment().add(mp, getComponentTitle(), new CriticalTag() {
});
getEnvironment().setActive(mp);
}
}
|
1ed13f7c-72ff-4ee9-bcb2-37556e6a66fb
| 0
|
public TMConfiguration(State state, TMConfiguration parent, Tape[] tapes, AcceptanceFilter[] filters) {
super(state, parent);
this.myTapes = tapes;
myFilters = filters;
}
|
f1d25d2e-5f14-4246-9087-6915bc28ad58
| 8
|
public Player2ColorSelectMenu(Game game, JFrame frame, int stateToNotShow) {
super(game, frame);
this.stateToNotShow = stateToNotShow;
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
header = new JLabel(" Player 2: Choose Color");
header.setFont(smallFont);
blackButton = new JButton("Black");
blackButton.addActionListener(new blackButtonListener());
blackButton.setFont(largeFont);
blueButton = new JButton("Blue");
blueButton.addActionListener(new blueButtonListener());
blueButton.setFont(largeFont);
magentaButton = new JButton("Magenta");
magentaButton.addActionListener(new magentaButtonListener());
magentaButton.setFont(largeFont);
brownButton = new JButton("Brown");
brownButton.addActionListener(new brownButtonListener());
brownButton.setFont(largeFont);
pinkButton = new JButton("Pink");
pinkButton.addActionListener(new pinkButtonListener());
pinkButton.setFont(largeFont);
redButton = new JButton("Red");
redButton.addActionListener(new redButtonListener());
redButton.setFont(largeFont);
yellowButton = new JButton("Yellow");
yellowButton.addActionListener(new yellowButtonListener());
yellowButton.setFont(largeFont);
//Fix Issue #58
if(game.getGameMode() == 1)
{
nameInst = new JLabel("Enter Player 2 name:");
}
else
{
nameInst = new JLabel("Enter Computer name:");
}
nameInst.setFont(smallFont);
nameText = new JTextField("Player 2");
nameText.setFont(smallFont);
nameText.setFocusable(true);
nameText.requestFocus();
this.add(header);
if (stateToNotShow != 1) {
this.add(redButton);
}
if (stateToNotShow != 2) {
this.add(yellowButton);
}
if (stateToNotShow != 4) {
this.add(blackButton);
}
if (stateToNotShow != 5) {
this.add(blueButton);
}
if (stateToNotShow != 6) {
this.add(magentaButton);
}
if (stateToNotShow != 7) {
this.add(brownButton);
}
if (stateToNotShow != 8) {
this.add(pinkButton);
}
this.add(nameInst);
this.add(nameText);
}
|
5f7a3ae9-313a-48c6-a5b3-162ef8ef9c9d
| 6
|
@Override
public AttributeValue getExampleAttributeValue(Example e) {
int playerToken = e.getResult().currentTurn;
int height = e.getBoard().height; // 6
int width = e.getBoard().width; // 7
int numTokensCountingFor = 2; // checking for 2 in a row
int countOfTokensEncounteredVertically = 0; // counter
// bottom index is (5, 0)
for (int i = height - 1; i > -1; i--) {
for (int j = 0; j < width; j++) {
if (e.getBoard().boardArray[i][j] == playerToken) { // current
// player's
// tokens
for (int k = i; k > -1; k--) {
if (e.getBoard().boardArray[i][j] == e.getBoard().boardArray[k][j]) {
countOfTokensEncounteredVertically++;
} else { // since the continuity between tokens is
// broken, stop
break;
}
}
}
}
}
if (countOfTokensEncounteredVertically >= numTokensCountingFor) {
return affirm;
} else {
return nega;
}
}
|
4853138d-826f-4e67-bde5-e1937b8cec71
| 6
|
public void Guerra() {
General.Reclutar(exerc1, pantalla);
General.Reclutar(exerc2, pantalla);
Formacio(exerc1);
Formacio(exerc2);
while (exerc1.size() != 0 && exerc2.size() != 0) {
if (General.Acorrer(exerc1, pantalla) == exerc1.size() && !exerc1.get(0).getTipus().equals("Mag")) {
General.Perdre(exerc1, pantalla);
General.GireuVos(exerc1);
General.Reclutar(exerc1, pantalla);
Formacio(exerc1);
}
if (General.Acorrer(exerc2, pantalla) == exerc2.size() && !exerc2.get(0).getTipus().equals("Mag")) {
General.Perdre(exerc2, pantalla);
General.GireuVos(exerc2);
General.Reclutar(exerc2, pantalla);
Formacio(exerc2);
}
comprovaMort();
}
}
|
dafdc145-9100-4120-af3f-96352d6b0a0c
| 6
|
@SuppressWarnings("unused")
public boolean eval(LinkedHashMap<Variable,Value> row, JTextArea console) throws TypeException{
boolean result = true;
LinkedHashMap<Variable,Value> localvar = new LinkedHashMap<Variable,Value> ( row);
Iterator<Statement> i = statement.iterator();
while (i.hasNext() && result) {
Statement s = i.next();
Value v = s.getValue(localvar);
if(v.getType().equals("error")){
int numError = Integer.parseInt(v.getVal());
Errors e = new Errors(numError, console);
throw new TypeException();
}
else if (s.isBinding ()) {
String vname = ((Binding) s).getName();
Variable var = new Variable(vname, v.getType(), v.getVal());
Value val = new Value(v.getVal(),v.getType() );
localvar.put(var, val);
} else {
if (v.getType() != "boolean") {
result = false;
}
else if (v.getVal()=="false") result = false;// bool
}
}
return result;
}
|
478e3a1b-6b7c-4a63-9528-fb2c766810a5
| 0
|
@Subscribe
public void when( ApplicationEvent applicationEvent )
{
eventNotified = true;
}
|
ac0aaf16-605a-4aec-bd02-d226ebad6b34
| 9
|
@Override
public void recoverPhyStats()
{
super.recoverPhyStats();
if(mode!=null)
switch(mode)
{
case STUN:
phyStats().setDamage(1);
break;
case NORMAL:
case MAIM:
case KILL:
case LASER:
case SONIC:
break;
case DISINTEGRATE:
case DISRUPT:
phyStats().setDamage(1+(phyStats().damage()*2));
break;
}
}
|
34abeb4d-0877-4a08-994f-b5ea43c3fcb8
| 3
|
public int getPlacesBooked(Booking b) {
DiningHall dh = b.getDiningHall();
int countBookings = 0;
Iterator<Booking> iter;
iter = bookings.iterator();
while (iter.hasNext()) {
Booking booking = iter.next();
if (booking.getDiningHall().equals(dh)
&& (booking.getDate().compareTo(b.getDate()) == 0)) {
countBookings++;
}
}
return countBookings;
}
|
6a262d8a-1dc5-459c-85d0-e3842e3658a4
| 2
|
public void setFullScreen(boolean f) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice dev = env.getDefaultScreenDevice();
this.setBackground(Color.BLACK);
if (f) {
this.setResizable(false);
this.removeNotify();
this.setUndecorated(true);
this.addNotify();
this.pack();
dev.setFullScreenWindow(this);
isFullScreen = true;
} else {
if(isFullScreen) {
this.setResizable(false);
this.removeNotify();
this.setUndecorated(false);
this.addNotify();
this.pack();
dev.setFullScreenWindow(null);
this.validate();
isFullScreen = false;
}
}
}
|
d50e806a-1429-4d55-93fa-cdd56fc81211
| 0
|
public void setNom(String value) {
nom = value;
}
|
215d5f42-e0f7-42bf-98e6-7ce8a8522507
| 7
|
public SpellGroup getSpellGroup(String NAME)
{
SpellGroup grpStore;
for (int i=0;i<vctSpellGroups.size();i++)
{
grpStore = (SpellGroup)vctSpellGroups.elementAt(i);
if (NAME.equalsIgnoreCase(grpStore.strName))
{
return grpStore;
}
}
try
{
grpStore = new SpellGroup(NAME);
RandomAccessFile rafSpellGroup = new RandomAccessFile("defSpellGroups/"+NAME,"r");
try
{
String strStore = rafSpellGroup.readLine();
while (strStore != null && !strStore.equals("") && !strStore.equals("."))
{
grpStore.vctSpells.addElement(strStore);
strStore = rafSpellGroup.readLine();
}
}catch (Exception e)
{
LOG.printError("getSpellGroup():While trying to read spell group file for \""+NAME+"\"", e);
}
rafSpellGroup.close();
vctSpellGroups.addElement(grpStore);
return grpStore;
}catch(Exception e)
{
LOG.printError("getSpellGroup():While trying to get spell group info for \""+NAME+"\"", e);
}
return null;
}
|
4f6d65a3-91d8-4f9f-8d92-62b576512958
| 8
|
public void draw(Graphics g)
{
if (!settings.isActive())
{
if (drawingImage.getWidth() != size.x || drawingImage.getHeight() != size.y)
{
drawingImage = new BufferedImage(size.x, size.y, BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g2d = drawingImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, size.x, size.y);
for (TwinklingStarChunk s : stars)
{
if (s.getBoundingRect().intersects(screenRect))
{
s.draw(g2d);
}
}
g2d.setColor(Color.BLACK);
g2d.fillRect(0, size.y - 100, size.x, size.y - 100);
g2d.setColor(new Color(119, 119, 119));
g2d.setFont(fonts.get(FONT));
g2d.drawString("START", startDrawPoint.x, startDrawPoint.y);
g2d.drawString("CLOSE", closeDrawPoint.x, closeDrawPoint.y);
g2d.drawString("SETTINGS", settingsDrawPoint.x, settingsDrawPoint.y);
// g2d.setColor(Color.red);
// g2d.draw(settingsRectangle);
// g2d.draw(startRectangle);
// g2d.draw(closeRectangle)
if (startHover)
{
g2d.drawImage(images.get(HOVER), startDrawPoint.x - (images.get(HOVER).getWidth() - TEXTWIDTHSTART) / 2, startDrawPoint.y, null);
}
if (closeHover)
{
g2d.drawImage(images.get(HOVER), closeDrawPoint.x - (images.get(HOVER).getWidth() - TEXTWIDTHCLOSE) / 2, closeDrawPoint.y, null);
}
if (settingsHover)
{
g2d.drawImage(images.get(LONGHOVER), settingsDrawPoint.x - (images.get(LONGHOVER).getWidth() - TEXTWIDTHSETTINGS) / 2, settingsDrawPoint.y, null);
}
g2d.setColor(Color.CYAN);
g2d.drawLine(0, size.y - 100, size.x, size.y - 100);
//g2d.drawLine(settingsRectangle.x, settingsRectangle.y + settingsRectangle.height, size.x, settingsRectangle.y + settingsRectangle.height);
// g2d.setColor(Color.RED);
// g2d.draw(startRectangle);
// g2d.draw(closeRectangle);
// g2d.draw(settingsRectangle);
g.drawImage(drawingImage, 0, 0, null);
}
else
{
settings.draw(g);
}
}
|
16546834-59ba-463f-8392-6bb6a291fc7c
| 4
|
public void replaceSeq(String newSeq) {
if (newSeq.length() != seq.length()) throw new RuntimeException("Cannot replace by a sequence with different length: Operation not supported!");
seq = newSeq;
// Invalidate some tags
for (int i = 0; i < tags.length; i++) {
if (tags[i].startsWith("MD:Z:")) tags[i] = null;
else if (tags[i].startsWith("NM:i:")) tags[i] = null;
}
}
|
4d1fdb00-cc94-40cf-a6d3-54fb015be10c
| 4
|
public void run()
{
ItemStack[] p1OfferedItems = p1inv.getOwnItems();
ItemStack[] p2PendingItems = p2inv.getOthersItems();
if (!Arrays.equals(p1OfferedItems, p2PendingItems)) {
p2inv.setPendingItems(p1OfferedItems);
try {
cancelAccept(p2);
} catch (PlayerNotFoundExeption exception) {
forceStopTrading();
exception.printStackTrace();
}
}
ItemStack[] p2OfferedItems = p2inv.getOwnItems();
ItemStack[] p1PendingItems = p1inv.getOthersItems();
if (!Arrays.equals(p2OfferedItems, p1PendingItems)) {
p1inv.setPendingItems(p2OfferedItems);
try {
cancelAccept(p1);
} catch (PlayerNotFoundExeption exception) {
forceStopTrading();
exception.printStackTrace();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.