text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) {
Miner miner = new Miner(458, "Bob");
MinersWife wife = new MinersWife(82, "Elsa");
MinersSon son = new MinersSon(50, "Billy");
try {
for(int i=0; i<40; ++i){
miner.update();
wife.update();
son.update();
Thread.sleep(800);
}
// System.err.println is used only so that the text is red
System.err.println(miner.getName() + ", " + wife.getName() + " and their son " + son.getName() + " have stopped");
}
catch(InterruptedException ex){System.out.println("Main thread interrupted");}
} | 2 |
public void setRight(Node child) {
right = child;
if (child != null) {
child.parent = this;
}
} | 1 |
private void doAction(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String forwardPage = errorPage;
Map<String, String[]> params = request.getParameterMap();
String action = request.getParameter("action");
session.setAttribute("userfile", user_file);
if (action != null && action.length() > 0) {
// Forward to web application to page indicated by action
ActionHandler handler = handlers.get(action);
if (handler != null) {
String result = handler.handleIt(params, session, request, response);
if (result != null && result.length() > 0) {
forwardPage = pageViews.get(result);
}
if (forwardPage == null || forwardPage.length() == 0) {
forwardPage = errorPage;
}
}
}
request.getRequestDispatcher(forwardPage).forward(request, response);
} | 7 |
public Vector<String[]> getData() {
return data;
} | 0 |
@Override
public void dispose() {
this.listModel = null;
this.previewList = null;
this.lblPreviewLabel = null;
this.lblBaseInfoLabel = null;
this.btnApplyButton = null;
this.btnEditButton = null;
this.btnDeleteButton = null;
this.list = null;
this.listPanel = null;
this.btnRefreshListButton = null;
this.previewPanel = null;
this.lblWarningLabel = null;
this.btnNewButton = null;
if (this.menubar != null) {
this.menubar.shutdown();
}
this.menubar = null;
super.dispose();
} | 1 |
public void setPersonId(int personId) {
this.personId = personId;
} | 0 |
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = new int[]{0,0,0,2,5,7,40,50,100,120,200,300,350,370,380,355,390,400,800,432,450,500};
int n = A.length;
int[] B = new int[n+1];
int INF = 100000000;
int cur_lis_len = 1;
B[0] = 1;
for(int i = 1; i < n; i++ ){
int max_len = 0;
for(int j = 0; j < i; j++) {
if(A[i] >= A[j] && B[j] > max_len) {
max_len = B[j];
}
}
B[i] = max_len+1;
}
int l = INF;
int lb = B[n-1]+1;
for(int j = n-1; j >= 0; j--) {
System.out.print(A[j] + "\t" + B[j]);
if( A[j] <= l && B[j] == lb-1) {
l = A[j];
lb = B[j];
System.out.println("");
} else {
System.out.println("-");
}
}
String test = "";
System.out.println(test.equals(""));
} | 7 |
public static void launchScoreDialog(final Context context, final String score, final String displayScore, final String levelId, final Drawable gameIcon,
final String gamePackage, final boolean fromSdk, final boolean skipModalDialog) {
final Float scoreF = Float.parseFloat(score);
final SharedPreferences scoresPrefs = context.getSharedPreferences(SCORES, 0);
final SharedPreferences displayScoresPrefs = context.getSharedPreferences(DISPLAY_SCORES, 0);
final SharedPreferences orderPrefs = context.getSharedPreferences(ORDER, 0);
if (scoresPrefs.contains(levelId) && orderPrefs.contains(levelId)) {
// Determine which dialog to show without doing the request
Float personalBest = scoresPrefs.getFloat(levelId, 0.0f);
String personalBestDisplay = displayScoresPrefs.getString(levelId, "");
boolean lowestScoreFirst = orderPrefs.getBoolean(levelId, false);
boolean newBest;
if (lowestScoreFirst) {
newBest = scoreF < personalBest;
} else {
newBest = scoreF > personalBest;
}
if (newBest) {
saveLeaderboardInfoOnPhone(context, scoreF, displayScore, levelId, null, true);
personalBestDisplay = displayScore;
}
if (newBest && !skipModalDialog) {
// Show full dialog immediately, and the dialog will make the request to save it and get leaderboard
LeaderboardScoreDialogFull d = new LeaderboardScoreDialogFull(context, null, gamePackage, score, displayScore, levelId);
d.setFromSdk(fromSdk);
d.show();
} else {
// Show top dialog immediately, and make the request to save it in the background
LeaderboardScoreDialogTop d = new LeaderboardScoreDialogTop(context, null, gamePackage, score, displayScore, levelId, personalBestDisplay,
gameIcon);
if (newBest && skipModalDialog) {
d.setPersonalBest(true);
}
d.setFromSdk(fromSdk);
d.show();
}
} else {
// Immediately show personal best dialog (technically, their device may have a better score on the server, e.g. if they cleared their shared prefs,
// but that should be rare).
// The dialog will post this score in the background and fetch and save the true personal best.
saveLeaderboardInfoOnPhone(context, scoreF, displayScore, levelId, null, true);
if (skipModalDialog) {
LeaderboardScoreDialogTop d = new LeaderboardScoreDialogTop(context, null, gamePackage, score, displayScore, levelId, displayScore, gameIcon);
d.setPersonalBest(true);
d.setFromSdk(fromSdk);
d.show();
} else {
LeaderboardScoreDialogFull d = new LeaderboardScoreDialogFull(context, null, gamePackage, score, displayScore, levelId);
d.setFromSdk(fromSdk);
d.show();
}
}
} | 9 |
public CardType getType() {
return type;
} | 0 |
@Override
public SquareMatrix getIdentityMatrix() {
int size = getRowsNumber();
try {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (i == j) {
setElementAt(i + 1, j + 1, 1);
} else {
setElementAt(i + 1, j + 1, 0);
}
}
}
} catch (OutOfBoundsException e) {
e.printStackTrace();
}
return this;
} | 4 |
@Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
if (state == 0) { //main menu
} else if (state == 1) { //load save menu
g.drawRect(0, 0, getWidth(), getHeight());
} else if (state == 2) { //options screen
} else if (state == 3) { //game play
} else if (state == 4) { //pause menu
}
} | 5 |
*/
public Iterator iterator() {
final Iterator iter = super.iterator();
return new Iterator() {
Object last = null;
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
last = iter.next();
return last;
}
public void remove() {
if (last == null) {
throw new NoSuchElementException();
}
((Stmt) last).cleanup();
last = null;
iter.remove();
}
};
}
}
/**
* Returns the last non-Label statement in the statement list.
*/
public Stmt lastStmt() {
final ListIterator iter = stmts.listIterator(stmts.size());
while (iter.hasPrevious()) {
final Stmt s = (Stmt) iter.previous();
if (s instanceof LabelStmt) {
continue;
}
return s;
}
return null;
}
/**
* Returns the operand stack.
*/
public OperandStack stack() {
return stack;
}
/**
* Inserts a statement into the statement list after another given
* statement.
*
* @param stmt
* The statement to add.
* @param after
* The statement after which to add stmt.
*/
public void addStmtAfter(final Stmt stmt, final Stmt after) {
if (Tree.DEBUG) {
System.out.println("insert: " + stmt + " after " + after);
}
final ListIterator iter = stmts.listIterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
if (s == after) {
iter.add(stmt);
stmt.setParent(this);
return;
}
}
throw new RuntimeException(after + " not found");
}
/**
* Inserts a statement into the statement list before a specified statement.
*
* @param stmt
* The statement to insert
* @param before
* The statement before which to add stmt.
*/
public void addStmtBefore(final Stmt stmt, final Stmt before) {
if (Tree.DEBUG) {
System.out.println("insert: " + stmt + " before " + before);
}
final ListIterator iter = stmts.listIterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
if (s == before) {
iter.previous();
iter.add(stmt);
stmt.setParent(this);
return;
}
}
throw new RuntimeException(before + " not found");
}
/**
* Add an statement to the statement list before the first non-Label
* statement.
*
* @param stmt
* The statement to add.
*/
public void prependStmt(final Stmt stmt) {
if (Tree.DEBUG) {
System.out.println("prepend: " + stmt + " in " + block);
}
final ListIterator iter = stmts.listIterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
if (!(s instanceof LabelStmt)) {
iter.previous();
iter.add(stmt);
stmt.setParent(this);
return;
}
}
appendStmt(stmt);
}
/**
* When we build the expression tree, there may be items left over on the
* operand stack. We want to save these items. If USE_STACK is true, then we
* place these items into stack variables. If USE_STACK is false, then we
* place the items into local variables.
*/
private void saveStack() {
int height = 0;
for (int i = 0; i < stack.size(); i++) {
final Expr expr = stack.get(i);
if (Tree.USE_STACK) {
// Save to a stack variable only if we'll create a new
// variable there.
if (!(expr instanceof StackExpr)
|| (((StackExpr) expr).index() != height)) {
final StackExpr target = new StackExpr(height, expr.type());
// Make a new statement to store the expression that was
// part of the stack into memory.
final Stmt store = new ExprStmt(new StoreExpr(target, expr,
expr.type()));
appendStmt(store);
final StackExpr copy = (StackExpr) target.clone();
copy.setDef(null);
stack.set(i, copy);
}
} else {
if (!(expr instanceof LocalExpr)
|| !((LocalExpr) expr).fromStack()
|| (((LocalExpr) expr).index() != height)) {
final LocalExpr target = newStackLocal(nextIndex++, expr
.type());
final Stmt store = new ExprStmt(new StoreExpr(target, expr,
expr.type()));
appendStmt(store);
final LocalExpr copy = (LocalExpr) target.clone();
copy.setDef(null);
stack.set(i, copy);
}
}
height += expr.type().stackHeight();
}
}
/**
* Add a statement to this Tree statement list and specify that this is the
* statement's parent.
*/
private void appendStmt(final Stmt stmt) {
if (Tree.DEBUG) {
System.out.println(" append: " + stmt);
}
stmt.setParent(this);
stmts.add(stmt);
}
/**
* Save the contents of the stack and add stmt to the statement list.
*
* @param stmt
* A statement to add to the statement list.
*/
public void addStmt(final Stmt stmt) {
saveStack();
appendStmt(stmt);
}
/**
* Adds a statement to the statement list before the last jump statement. It
* is assumed that the last statement in the statement list is a jump
* statement.
*
* @see JumpStmt
*/
public void addStmtBeforeJump(final Stmt stmt) {
final Stmt last = lastStmt();
Assert.isTrue(last instanceof JumpStmt, "Last statement of " + block
+ " is " + last + ", not a jump");
addStmtBefore(stmt, last);
}
/**
* Throw a new ClassFormatException with information about method and class
* that this basic block is in.
*
* @param msg
* String description of the exception.
*
* @see ClassFormatException
*/
private void throwClassFormatException(final String msg) {
final MethodEditor method = block.graph().method();
throw new ClassFormatException("Method "
+ method.declaringClass().type().className() + "."
+ method.name() + " " + method.type() + ": " + msg);
}
/**
* The last instruction we saw. addInst(Instruction) needs this information.
*/
Instruction last = null;
/**
* Adds an instruction that jumps to another basic block.
*
* @param inst
* The instruction to add.
* @param next
* The basic block after the jump. Remember that a jump ends a
* basic block.
*
* @see Instruction#isJsr
* @see Instruction#isConditionalJump
*/
public void addInstruction(final Instruction inst, final Block next) {
Assert.isTrue(inst.isJsr() || inst.isConditionalJump(),
"Wrong addInstruction called with " + inst);
Assert.isTrue(next != null, "Null next block for " + inst);
this.next = next;
addInst(inst);
}
/**
* Adds an instruction that does not change the control flow (a normal
* instruction).
*
* @param inst
* Instruction to add.
*/
public void addInstruction(final Instruction inst) {
Assert.isTrue(!inst.isJsr() && !inst.isConditionalJump(),
"Wrong addInstruction called with " + inst);
this.next = null;
addInst(inst);
}
/**
* Add an instruction such as <i>ret</i> or <i>astore</i> that may involve
* a subroutine.
*
* @param inst
* Instruction to add.
* @param sub
* Subroutine in which inst resides. The <i>ret</i> instruction
* always resides in a Subroutine. An <i>astore</i> may store
* the return address of a subroutine in a local variable.
*
* @see Instruction#isRet
*/
public void addInstruction(final Instruction inst, final Subroutine sub) {
Assert.isTrue(inst.isRet()
|| (inst.opcodeClass() == Opcode.opcx_astore),
"Wrong addInstruction called with " + inst);
this.sub = sub;
this.next = null;
addInst(inst);
}
/**
* Add a label to the statement list. A label is inserted before a dup
* statement, but after any other statement.
*
* @param label
* Label to add.
*/
public void addLabel(final Label label) {
// Add before a dup, but after any other instruction.
if (last != null) {
switch (last.opcodeClass()) {
case opcx_dup:
case opcx_dup2:
case opcx_dup_x1:
case opcx_dup2_x1:
case opcx_dup_x2:
case opcx_dup2_x2:
break;
default:
addInst(last, false);
last = null;
break;
}
}
addStmt(new LabelStmt(label));
}
/**
* Private method that adds an instruction to the Tree. The visit method of
* the instruction is called with this tree as the visitor. The instruction,
* in turn, calls the appropriate method of this for adding the instruction
* to the statement list.
*
* @param inst
* The <tt>Instruction</tt> to add to the <tt>Tree</tt>
* @param saveValue
* Do we save expressions on the operand stack to stack variables
* or local variables.
*/
private void addInst(final Instruction inst, final boolean saveValue) {
if (Tree.DEBUG) {
// Print the contents of the stack
for (int i = 0; i < stack.size(); i++) {
final Expr exp = stack.peek(i);
System.out.println((i > 0 ? "-" + i : " " + i) + ": " + exp);
}
}
if (Tree.DEBUG) {
System.out.println(" add " + inst + " save=" + saveValue);
}
try {
this.saveValue = saveValue;
if (Tree.FLATTEN) {
saveStack();
}
inst.visit(this);
} catch (final EmptyStackException e) {
throwClassFormatException("Empty operand stack at " + inst);
return;
}
}
/**
* Private method that adds an instruction to the tree. Before dispatching
* the addition off to addInst(Instruction, boolean), it optimizes(?) dup
* instructions as outlined below:
*/
// (S0, S1) := dup(X)
// L := S1 --> use (L := X)
// use S0
//
// (S0, S1, S2) := dup_x1(X, Y)
// S1.f := S2 --> use (X.f := Y)
// use S0
//
// (S0, S1, S2, S3) := dup_x2(X, Y, Z)
// S1[S2] := S3 --> use (X[Y] := Z)
// use S0
//
private void addInst(final Instruction inst) {
// Build the tree, trying to convert dup-stores
if (last == null) {
last = inst;
} else {
switch (last.opcodeClass()) {
case opcx_dup:
switch (inst.opcodeClass()) {
case opcx_astore:
case opcx_fstore:
case opcx_istore:
case opcx_putstatic:
addInst(inst, true);
last = null;
break;
}
break;
case opcx_dup2:
switch (inst.opcodeClass()) {
case opcx_dstore:
case opcx_lstore:
case opcx_putstatic:
addInst(inst, true);
last = null;
break;
}
break;
case opcx_dup_x1:
switch (inst.opcodeClass()) {
case opcx_putfield:
case opcx_putfield_nowb:
addInst(inst, true);
last = null;
break;
}
break;
case opcx_dup2_x1:
switch (inst.opcodeClass()) {
case opcx_putfield:
case opcx_putfield_nowb:
addInst(inst, true);
last = null;
break;
}
break;
case opcx_dup_x2:
switch (inst.opcodeClass()) {
case opcx_aastore:
case opcx_bastore:
case opcx_castore:
case opcx_fastore:
case opcx_iastore:
case opcx_sastore:
addInst(inst, true);
last = null;
break;
}
break;
case opcx_dup2_x2:
switch (inst.opcodeClass()) {
case opcx_dastore:
case opcx_lastore:
addInst(inst, true);
last = null;
break;
}
break;
}
if (last != null) {
addInst(last, false);
last = inst;
}
}
// We should have dealt with the old last instruction
Assert.isTrue((last == null) || (last == inst));
if (inst.isJump() || inst.isSwitch() || inst.isThrow()
|| inst.isReturn() || inst.isJsr() || inst.isRet()) {
addInst(inst, false);
last = null;
}
}
/**
* Returns a new StackExpr for the top of the operand stack.
*/
public StackExpr newStack(final Type type) {
return new StackExpr(Tree.stackpos++, type);
}
/**
* Returns a new LocalExpr that represents an element of the stack. They are
* created when the USE_STACK flag is not set.
*
* @param index
* Stack index of variable.
* @param type
* The type of the LocalExpr
*/
public LocalExpr newStackLocal(final int index, final Type type) {
if (index >= nextIndex) {
nextIndex = index + 1;
}
return new LocalExpr(index, true, type);
}
/**
* Returns a new LocalExpr that is not allocated on the stack.
*
* @param index
* Stack index of variable.
* @param type
* The type of the LocalExpr
*/
public LocalExpr newLocal(final int index, final Type type) {
return new LocalExpr(index, false, type);
}
/**
* Returns a local variable (<tt>LocalExpr</tt>) located in this method.
*
* @param type
* The type of the new LocalExpr.
*/
public LocalExpr newLocal(final Type type) {
final LocalVariable var = block.graph().method().newLocal(type);
return new LocalExpr(var.index(), type);
}
/**
* Returns a String representation of this Tree.
*/
public String toString() {
String x = "(TREE " + block + " stack=";
for (int i = 0; i < stack.size(); i++) {
final Expr expr = stack.get(i);
x += expr.type().shortName();
}
return x + ")";
}
/**
* Adds no statements to the statement list.
*/
public void visit_nop(final Instruction inst) {
}
/**
* Pushes a ConstantExpr onto the operand stack.
*
* @see ConstantExpr
*/
public void visit_ldc(final Instruction inst) {
final Object value = inst.operand();
Type type;
if (value == null) {
type = Type.NULL;
} else if (value instanceof Integer) {
type = Type.INTEGER;
} else if (value instanceof Long) {
type = Type.LONG;
} else if (value instanceof Float) {
type = Type.FLOAT;
} else if (value instanceof Double) {
type = Type.DOUBLE;
} else if (value instanceof String) {
type = Type.STRING;
}
// FIXME this won't work - check usages
else if (value instanceof Type) {
type = Type.CLASS;
} else {
throwClassFormatException("Illegal constant type: "
+ value.getClass().getName() + ": " + value);
return;
}
final Expr top = new ConstantExpr(value, type);
stack.push(top);
}
/**
* All <tt>visit_<i>x</i>load</tt> push a LocalExpr onto the operand
* stack.
*
* @see LocalExpr
*/
public void visit_iload(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr top = new LocalExpr(operand.index(), Type.INTEGER);
stack.push(top);
}
public void visit_lload(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr top = new LocalExpr(operand.index(), Type.LONG);
stack.push(top);
}
public void visit_fload(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr top = new LocalExpr(operand.index(), Type.FLOAT);
stack.push(top);
}
public void visit_dload(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr top = new LocalExpr(operand.index(), Type.DOUBLE);
stack.push(top);
}
public void visit_aload(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr top = new LocalExpr(operand.index(), Type.OBJECT);
stack.push(top);
db(" aload: " + top);
}
/**
* All <tt>visit_<i>x</i>aload</tt> push an ArrayRefExpr onto the
* operand stack.
*/
public void visit_iaload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.INTEGER.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.INTEGER,
Type.INTEGER);
stack.push(top);
}
public void visit_laload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.LONG.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.LONG, Type.LONG);
stack.push(top);
}
public void visit_faload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.FLOAT.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.FLOAT, Type.FLOAT);
stack.push(top);
}
public void visit_daload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.DOUBLE.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.DOUBLE,
Type.DOUBLE);
stack.push(top);
}
public void visit_aaload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.OBJECT.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.OBJECT,
Type.OBJECT);
stack.push(top);
}
public void visit_baload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.BYTE.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.BYTE, Type.BYTE);
stack.push(top);
}
public void visit_caload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.CHARACTER.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.CHARACTER,
Type.CHARACTER);
stack.push(top);
}
public void visit_saload(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.SHORT.arrayType());
final Expr top = new ArrayRefExpr(array, index, Type.SHORT, Type.SHORT);
stack.push(top);
}
/**
* Deals with an expression that stores a value. It either pushes it on the
* operand stack or adds a statement depending on the value of saveValue.
*
* @param target
* The location to where we are storing the value.
* @param expr
* The expression whose value we are storing.
*/
private void addStore(final MemExpr target, final Expr expr) {
if (saveValue) {
stack.push(new StoreExpr(target, expr, expr.type()));
} else {
addStmt(new ExprStmt(new StoreExpr(target, expr, expr.type())));
}
}
/**
* All <tt>visit_<i>x</i>store</tt> add a LocalExpr statement to the
* statement list.
*/
public void visit_istore(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr expr = stack.pop(Type.INTEGER);
final LocalExpr target = new LocalExpr(operand.index(), expr.type());
addStore(target, expr);
}
public void visit_lstore(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr expr = stack.pop(Type.LONG);
final LocalExpr target = new LocalExpr(operand.index(), expr.type());
addStore(target, expr);
}
public void visit_fstore(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr expr = stack.pop(Type.FLOAT);
final LocalExpr target = new LocalExpr(operand.index(), expr.type());
addStore(target, expr);
}
public void visit_dstore(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
final Expr expr = stack.pop(Type.DOUBLE);
final LocalExpr target = new LocalExpr(operand.index(), expr.type());
addStore(target, expr);
}
/**
* Visit an <i>astore</i> instruction. If the type of the operand to the
* instruction is an address add an AddressStoreStmt to the tree, else add a
* StoreStmt to the tree consisting of a LocalExpr and the top Expr on the
* operand stack.
*
* @see AddressStoreStmt
* @see LocalExpr
* @see StoreExpr
*/
public void visit_astore(final Instruction inst) {
final LocalVariable operand = (LocalVariable) inst.operand();
Expr expr = stack.peek();
if (expr.type().isAddress()) {
Assert.isTrue(sub != null);
Assert.isTrue(!saveValue);
expr = stack.pop(Type.ADDRESS);
sub.setReturnAddress(operand);
addStmt(new AddressStoreStmt(sub));
} else {
expr = stack.pop(Type.OBJECT);
final LocalExpr target = new LocalExpr(operand.index(), expr.type());
addStore(target, expr);
}
}
public void visit_iastore(final Instruction inst) {
final Expr value = stack.pop(Type.INTEGER);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.INTEGER.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index,
Type.INTEGER, Type.INTEGER);
addStore(target, value);
}
public void visit_lastore(final Instruction inst) {
final Expr value = stack.pop(Type.LONG);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.LONG.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.LONG,
Type.LONG);
addStore(target, value);
}
public void visit_fastore(final Instruction inst) {
final Expr value = stack.pop(Type.FLOAT);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.FLOAT.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.FLOAT,
Type.FLOAT);
addStore(target, value);
}
public void visit_dastore(final Instruction inst) {
final Expr value = stack.pop(Type.DOUBLE);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.DOUBLE.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.DOUBLE,
Type.DOUBLE);
addStore(target, value);
}
public void visit_aastore(final Instruction inst) {
final Expr value = stack.pop(Type.OBJECT);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.OBJECT.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.OBJECT,
Type.OBJECT);
addStore(target, value);
}
public void visit_bastore(final Instruction inst) {
final Expr value = stack.pop(Type.BYTE);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.BYTE.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.BYTE,
Type.BYTE);
addStore(target, value);
}
public void visit_castore(final Instruction inst) {
final Expr value = stack.pop(Type.CHARACTER);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.CHARACTER.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index,
Type.CHARACTER, Type.CHARACTER);
addStore(target, value);
}
public void visit_sastore(final Instruction inst) {
final Expr value = stack.pop(Type.SHORT);
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.SHORT.arrayType());
final ArrayRefExpr target = new ArrayRefExpr(array, index, Type.SHORT,
Type.SHORT);
addStore(target, value);
}
/**
* Pop the expression off the top of the stack and add it as an ExprStmt to
* the statement list.
*
* @see ExprStmt
*/
public void visit_pop(final Instruction inst) {
final Expr expr = stack.pop1();
addStmt(new ExprStmt(expr));
}
public void visit_pop2(final Instruction inst) {
final Expr[] expr = stack.pop2();
if (expr.length == 1) {
addStmt(new ExprStmt(expr[0]));
} else {
addStmt(new ExprStmt(expr[0]));
addStmt(new ExprStmt(expr[1]));
}
}
/**
* When processing the <i>dup</i> instructions one of two situations can
* occur. If the <tt>USE_STACK</tt> flag is set, then a StackManipStmt is
* created to represent the transformation that the <i>dup</i> instruction
* performs on the stack. If the <tt>USE_STACK</tt> flag is not set, then
* the transformation is simulated by creating new local variables
* containing the appropriate element of the stack.
*
* @see LocalExpr
* @see StackExpr
* @see StackManipStmt
*/
public void visit_dup(final Instruction inst) {
// 0 -> 0 0
db(" dup");
if (Tree.USE_STACK) {
saveStack();
final StackExpr s0 = (StackExpr) stack.pop1();
final StackExpr[] s = new StackExpr[] { s0 };
manip(s, new int[] { 0, 0 }, StackManipStmt.DUP);
} else {
final Expr s0 = stack.pop1();
final LocalExpr t0 = newStackLocal(stack.height(), s0.type());
db(" s0: " + s0);
db(" t0: " + t0);
if (!t0.equalsExpr(s0)) {
db(" t0 <- s0");
addStore(t0, s0);
}
Expr copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
}
}
public void visit_dup_x1(final Instruction inst) {
// 0 1 -> 1 0 1
if (Tree.USE_STACK) {
saveStack();
final StackExpr s1 = (StackExpr) stack.pop1();
final StackExpr s0 = (StackExpr) stack.pop1();
final StackExpr[] s = new StackExpr[] { s0, s1 };
manip(s, new int[] { 1, 0, 1 }, StackManipStmt.DUP_X1);
} else {
final Expr s1 = stack.pop1();
final Expr s0 = stack.pop1();
final LocalExpr t0 = newStackLocal(stack.height(), s0.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s1.type());
if (!t0.equalsExpr(s0)) {
addStore(t0, s0);
}
if (!t1.equalsExpr(s1)) {
addStore(t1, s1);
}
Expr copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
}
}
public void visit_dup_x2(final Instruction inst) {
// 0 1 2 -> 2 0 1 2
// 0-1 2 -> 2 0-1 2
db(" dup_x2");
if (Tree.USE_STACK) {
saveStack();
final StackExpr s2 = (StackExpr) stack.pop1();
final Expr[] s01 = stack.pop2();
if (s01.length == 2) {
// 0 1 2 -> 2 0 1 2
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s01[1], s2 };
manip(s, new int[] { 2, 0, 1, 2 }, StackManipStmt.DUP_X2);
} else {
// 0-1 2 -> 2 0-1 2
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0], s2 };
manip(s, new int[] { 1, 0, 1 }, StackManipStmt.DUP_X2);
}
} else {
final Expr s2 = stack.pop1();
final Expr[] s01 = stack.pop2();
db(" s2: " + s2);
db(" s01: " + s01[0] + (s01.length > 1 ? " " + s01[1] : ""));
if (s01.length == 2) {
// 0 1 2 -> 2 0 1 2
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s01[1]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s2
.type());
db(" t0: " + t0);
db(" t1: " + t1);
db(" t2: " + t2);
if (!t0.equalsExpr(s01[0])) {
db(" t0 <- s01[0]");
addStore(t0, s01[0]);
}
if (!t1.equalsExpr(s01[1])) {
db(" t1 <- s01[1]");
addStore(t1, s01[1]);
}
if (!t2.equalsExpr(s2)) {
db(" t2 <- s2");
addStore(t2, s2);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
} else {
// 0-1 2 -> 2 0-1 2
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s2
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t2.equalsExpr(s2)) {
addStore(t2, s2);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
}
}
}
public void visit_dup2(final Instruction inst) {
// 0 1 -> 0 1 0 1
// 0-1 -> 0-1 0-1
if (Tree.USE_STACK) {
saveStack();
final Expr[] s01 = stack.pop2();
if (s01.length == 1) {
// 0-1 -> 0-1 0-1
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0] };
manip(s, new int[] { 0, 0 }, StackManipStmt.DUP2);
} else {
// 0 1 -> 0 1 0 1
Assert.isTrue(s01.length == 2);
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s01[1] };
manip(s, new int[] { 0, 1, 0, 1 }, StackManipStmt.DUP2);
}
} else {
final Expr[] s01 = stack.pop2();
if (s01.length == 1) {
// 0-1 -> 0-1 0-1
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
Expr copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
} else {
// 0 1 -> 0 1 0 1
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s01[1]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t1.equalsExpr(s01[1])) {
addStore(t1, s01[1]);
}
Expr copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
}
}
}
public void visit_dup2_x1(final Instruction inst) {
// 0 1 2 -> 1 2 0 1 2
// 0 1-2 -> 1-2 0 1-2
if (Tree.USE_STACK) {
saveStack();
final Expr[] s12 = stack.pop2();
final StackExpr s0 = (StackExpr) stack.pop1();
if (s12.length == 2) {
// 0 1 2 -> 1 2 0 1 2
final StackExpr[] s = new StackExpr[] { s0, (StackExpr) s12[0],
(StackExpr) s12[1] };
manip(s, new int[] { 1, 2, 0, 1, 2 }, StackManipStmt.DUP2_X1);
} else {
// 0 1-2 -> 1-2 0 1-2
final StackExpr[] s = new StackExpr[] { s0, (StackExpr) s12[0] };
manip(s, new int[] { 1, 0, 1 }, StackManipStmt.DUP2_X1);
}
} else {
final Expr[] s12 = stack.pop2();
final StackExpr s0 = (StackExpr) stack.pop1();
if (s12.length == 2) {
// 0 1 2 -> 1 2 0 1 2
final LocalExpr t0 = newStackLocal(stack.height(), s0.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s12[0]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s12[1]
.type());
if (!t0.equalsExpr(s0)) {
addStore(t0, s0);
}
if (!t1.equalsExpr(s12[0])) {
addStore(t1, s12[0]);
}
if (!t2.equalsExpr(s12[1])) {
addStore(t2, s12[1]);
}
Expr copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
} else {
// 0 1-2 -> 1-2 0 1-2
final LocalExpr t0 = newStackLocal(stack.height(), s0.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s12[0]
.type());
if (!t0.equalsExpr(s0)) {
addStore(t0, s0);
}
if (!t1.equalsExpr(s12[0])) {
addStore(t1, s12[0]);
}
Expr copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
}
}
}
public void visit_dup2_x2(final Instruction inst) {
// 0 1 2 3 -> 2 3 0 1 2 3
// 0 1 2-3 -> 2-3 0 1 2-3
// 0-1 2 3 -> 2 3 0-1 2 3
// 0-1 2-3 -> 2-3 0-1 2-3
if (Tree.USE_STACK) {
saveStack();
final Expr[] s23 = stack.pop2();
final Expr[] s01 = stack.pop2();
if ((s01.length == 2) && (s23.length == 2)) {
// 0 1 2 3 -> 2 3 0 1 2 3
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s01[1], (StackExpr) s23[0],
(StackExpr) s23[1] };
manip(s, new int[] { 2, 3, 0, 1, 2, 3 }, StackManipStmt.DUP2_X2);
} else if ((s01.length == 2) && (s23.length == 1)) {
// 0 1 2-3 -> 2-3 0 1 2-3
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s01[1], (StackExpr) s23[0] };
manip(s, new int[] { 2, 0, 1, 2 }, StackManipStmt.DUP2_X2);
} else if ((s01.length == 1) && (s23.length == 2)) {
// 0-1 2 3 -> 2 3 0-1 2 3
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s23[0], (StackExpr) s23[1] };
manip(s, new int[] { 1, 2, 0, 1, 2 }, StackManipStmt.DUP2_X2);
} else if ((s01.length == 1) && (s23.length == 2)) {
// 0-1 2-3 -> 2-3 0-1 2-3
final StackExpr[] s = new StackExpr[] { (StackExpr) s01[0],
(StackExpr) s23[0] };
manip(s, new int[] { 1, 0, 1 }, StackManipStmt.DUP2_X2);
}
} else {
final Expr[] s23 = stack.pop2();
final Expr[] s01 = stack.pop2();
if ((s01.length == 2) && (s23.length == 2)) {
// 0 1 2 3 -> 2 3 0 1 2 3
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s01[1]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s23[0]
.type());
final LocalExpr t3 = newStackLocal(stack.height() + 3, s23[1]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t1.equalsExpr(s01[1])) {
addStore(t1, s01[1]);
}
if (!t2.equalsExpr(s23[0])) {
addStore(t2, s23[0]);
}
if (!t3.equalsExpr(s23[1])) {
addStore(t3, s23[1]);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t3.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t3.clone();
copy.setDef(null);
stack.push(copy);
} else if ((s01.length == 2) && (s23.length == 1)) {
// 0 1 2-3 -> 2-3 0 1 2-3
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s01[1]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s23[0]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t1.equalsExpr(s01[1])) {
addStore(t1, s01[1]);
}
if (!t2.equalsExpr(s23[0])) {
addStore(t2, s23[0]);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
} else if ((s01.length == 1) && (s23.length == 2)) {
// 0-1 2 3 -> 2 3 0-1 2 3
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s23[0]
.type());
final LocalExpr t3 = newStackLocal(stack.height() + 3, s23[1]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t2.equalsExpr(s23[0])) {
addStore(t2, s23[0]);
}
if (!t3.equalsExpr(s23[1])) {
addStore(t3, s23[1]);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t3.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t3.clone();
copy.setDef(null);
stack.push(copy);
} else if ((s01.length == 1) && (s23.length == 2)) {
// 0-1 2-3 -> 2-3 0-1 2-3
final LocalExpr t0 = newStackLocal(stack.height(), s01[0]
.type());
final LocalExpr t2 = newStackLocal(stack.height() + 2, s23[0]
.type());
if (!t0.equalsExpr(s01[0])) {
addStore(t0, s01[0]);
}
if (!t2.equalsExpr(s23[0])) {
addStore(t2, s23[0]);
}
Expr copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t2.clone();
copy.setDef(null);
stack.push(copy);
}
}
}
public void visit_swap(final Instruction inst) {
// 0 1 -> 1 0
if (Tree.USE_STACK) {
saveStack();
final StackExpr s1 = (StackExpr) stack.pop1();
final StackExpr s0 = (StackExpr) stack.pop1();
final StackExpr[] s = new StackExpr[] { s0, s1 };
manip(s, new int[] { 1, 0 }, StackManipStmt.SWAP);
} else {
final Expr s1 = stack.pop1();
final Expr s0 = stack.pop1();
final LocalExpr t0 = newStackLocal(stack.height(), s0.type());
final LocalExpr t1 = newStackLocal(stack.height() + 1, s1.type());
if (!t0.equalsExpr(s0)) {
addStore(t0, s0);
}
if (!t1.equalsExpr(s1)) {
addStore(t1, s1);
}
Expr copy = (Expr) t1.clone();
copy.setDef(null);
stack.push(copy);
copy = (Expr) t0.clone();
copy.setDef(null);
stack.push(copy);
}
}
/**
* Produces a StackManipStmt that represents how the stack is changed as a
* result of a dup instruction. It should only be used when USE_STACK is
* true.
* <p>
* dup instructions change the top n elements of the JVM stack. This method
* takes the original top n elements of the stack, an integer array
* representing the transformation (for instance, if s[0] = 1, then the top
* element of the new stack should contain the second-from-the-top element
* of the old stack), and integer representing the dup instruction.
*
* @param source
* The interesting part of the stack before the dup instruction
* is executed.
* @param s
* An integer array representing the new order of the stack.
* @param kind
* The kind of stack manipulation taking place. (e.g.
* StackManipStmt.DUP_X1)
*
* @see StackManipStmt
*/
private void manip(final StackExpr[] source, final int[] s, final int kind) {
Assert.isTrue(Tree.USE_STACK);
int height = 0; // Height of the stack
// Calculate current height of the stack. Recall that the stack
// elements in source have already been popped off the stack.
for (int i = 0; i < stack.size(); i++) {
final Expr expr = stack.get(i);
height += expr.type().stackHeight();
}
// Create the new portion of the stack. Make new StackExpr
// representing the stack after the dup instruction. Push those
// new StackExprs onto the operand stack. Finally, create a
// StackManipStmt that represent the transformation of the old
// stack (before dup instruction) to the new stack (after dup
// instruction).
final StackExpr[] target = new StackExpr[s.length];
for (int i = 0; i < s.length; i++) {
target[i] = new StackExpr(height, source[s[i]].type());
final StackExpr copy = (StackExpr) target[i].clone();
copy.setDef(null);
stack.push(copy);
height += target[i].type().stackHeight();
}
appendStmt(new StackManipStmt(target, source, kind));
}
/**
* All <tt>visit_<i>x</i>add</tt>, <tt>visit_<i>x</i>sub</tt>,
* <tt>visit_<i>x</i>mul</tt>, <tt>visit_<i>x</i>div</tt>, etc.
* push an ArithExpr onto the operand stack.
*
* @see ArithExpr
*/
public void visit_iadd(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.ADD, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_ladd(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.ADD, left, right, Type.LONG);
stack.push(top);
}
public void visit_fadd(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.ADD, left, right, Type.FLOAT);
stack.push(top);
}
public void visit_dadd(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.ADD, left, right, Type.DOUBLE);
stack.push(top);
}
public void visit_isub(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.SUB, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_lsub(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.SUB, left, right, Type.LONG);
stack.push(top);
}
public void visit_fsub(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.SUB, left, right, Type.FLOAT);
stack.push(top);
}
public void visit_dsub(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.SUB, left, right, Type.DOUBLE);
stack.push(top);
}
public void visit_imul(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.MUL, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_lmul(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.MUL, left, right, Type.LONG);
stack.push(top);
}
public void visit_fmul(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.MUL, left, right, Type.FLOAT);
stack.push(top);
}
public void visit_dmul(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.MUL, left, right, Type.DOUBLE);
stack.push(top);
}
public void visit_idiv(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr check = new ZeroCheckExpr(right, Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.DIV, left, check, Type.INTEGER);
stack.push(top);
}
public void visit_ldiv(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr check = new ZeroCheckExpr(right, Type.LONG);
final Expr top = new ArithExpr(ArithExpr.DIV, left, check, Type.LONG);
stack.push(top);
}
public void visit_fdiv(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.DIV, left, right, Type.FLOAT);
stack.push(top);
}
public void visit_ddiv(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.DIV, left, right, Type.DOUBLE);
stack.push(top);
}
public void visit_irem(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr check = new ZeroCheckExpr(right, Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.REM, left, check, Type.INTEGER);
stack.push(top);
}
public void visit_lrem(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr check = new ZeroCheckExpr(right, Type.LONG);
final Expr top = new ArithExpr(ArithExpr.REM, left, check, Type.LONG);
stack.push(top);
}
public void visit_frem(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.REM, left, right, Type.FLOAT);
stack.push(top);
}
public void visit_drem(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.REM, left, right, Type.DOUBLE);
stack.push(top);
}
/**
* All <tt>visit_<i>x</i>neg</tt> push a NegExpr onto the stack.
*
* @see NegExpr
*/
public void visit_ineg(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new NegExpr(expr, Type.INTEGER);
stack.push(top);
}
public void visit_lneg(final Instruction inst) {
final Expr expr = stack.pop(Type.LONG);
final Expr top = new NegExpr(expr, Type.LONG);
stack.push(top);
}
public void visit_fneg(final Instruction inst) {
final Expr expr = stack.pop(Type.FLOAT);
final Expr top = new NegExpr(expr, Type.FLOAT);
stack.push(top);
}
public void visit_dneg(final Instruction inst) {
final Expr expr = stack.pop(Type.DOUBLE);
final Expr top = new NegExpr(expr, Type.DOUBLE);
stack.push(top);
}
/**
* All <tt>visit_<i>x</i>sh<i>d</i></tt> push a ShiftExpr onto the
* operand stack.
*
* @see ShiftExpr
*/
public void visit_ishl(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ShiftExpr(ShiftExpr.LEFT, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_lshl(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ShiftExpr(ShiftExpr.LEFT, left, right, Type.LONG);
stack.push(top);
}
public void visit_ishr(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ShiftExpr(ShiftExpr.RIGHT, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_lshr(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ShiftExpr(ShiftExpr.RIGHT, left, right, Type.LONG);
stack.push(top);
}
public void visit_iushr(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ShiftExpr(ShiftExpr.UNSIGNED_RIGHT, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_lushr(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ShiftExpr(ShiftExpr.UNSIGNED_RIGHT, left, right,
Type.LONG);
stack.push(top);
}
/**
* All <tt>visit_<i>x op</i></tt> push an ArithExpr onto the stack.
*
* @see ArithExpr
*/
public void visit_iand(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.AND, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_land(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.AND, left, right, Type.LONG);
stack.push(top);
}
public void visit_ior(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.IOR, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_lor(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.IOR, left, right, Type.LONG);
stack.push(top);
}
public void visit_ixor(final Instruction inst) {
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.XOR, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_lxor(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.XOR, left, right, Type.LONG);
stack.push(top);
}
/**
* Visiting an iinc involves creating a ConstantExpr, LocalExpr, ArithExpr
* StoreExpr, and a ExprStmt.
*/
public void visit_iinc(final Instruction inst) {
final IncOperand operand = (IncOperand) inst.operand();
int incr = operand.incr();
if (incr < 0) {
final Expr right = new ConstantExpr(new Integer(-incr),
Type.INTEGER);
final Expr left = new LocalExpr(operand.var().index(), Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.SUB, left, right,
Type.INTEGER);
final LocalExpr copy = (LocalExpr) left.clone();
copy.setDef(null);
addStmt(new ExprStmt(new StoreExpr(copy, top, left.type())));
} else if (incr > 0) {
final Expr right = new ConstantExpr(new Integer(incr), Type.INTEGER);
final Expr left = new LocalExpr(operand.var().index(), Type.INTEGER);
final Expr top = new ArithExpr(ArithExpr.ADD, left, right,
Type.INTEGER);
final LocalExpr copy = (LocalExpr) left.clone();
copy.setDef(null);
addStmt(new ExprStmt(new StoreExpr(copy, top, left.type())));
}
}
/**
* All cast visitors push a CastExpr onto the operand stack.
*/
public void visit_i2l(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.LONG, Type.LONG);
stack.push(top);
}
public void visit_i2f(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.FLOAT, Type.FLOAT);
stack.push(top);
}
public void visit_i2d(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.DOUBLE, Type.DOUBLE);
stack.push(top);
}
public void visit_l2i(final Instruction inst) {
final Expr expr = stack.pop(Type.LONG);
final Expr top = new CastExpr(expr, Type.INTEGER, Type.INTEGER);
stack.push(top);
}
public void visit_l2f(final Instruction inst) {
final Expr expr = stack.pop(Type.LONG);
final Expr top = new CastExpr(expr, Type.FLOAT, Type.FLOAT);
stack.push(top);
}
public void visit_l2d(final Instruction inst) {
final Expr expr = stack.pop(Type.LONG);
final Expr top = new CastExpr(expr, Type.DOUBLE, Type.DOUBLE);
stack.push(top);
}
public void visit_f2i(final Instruction inst) {
final Expr expr = stack.pop(Type.FLOAT);
final Expr top = new CastExpr(expr, Type.INTEGER, Type.INTEGER);
stack.push(top);
}
public void visit_f2l(final Instruction inst) {
final Expr expr = stack.pop(Type.FLOAT);
final Expr top = new CastExpr(expr, Type.LONG, Type.LONG);
stack.push(top);
}
public void visit_f2d(final Instruction inst) {
final Expr expr = stack.pop(Type.FLOAT);
final Expr top = new CastExpr(expr, Type.DOUBLE, Type.DOUBLE);
stack.push(top);
}
public void visit_d2i(final Instruction inst) {
final Expr expr = stack.pop(Type.DOUBLE);
final Expr top = new CastExpr(expr, Type.INTEGER, Type.INTEGER);
stack.push(top);
}
public void visit_d2l(final Instruction inst) {
final Expr expr = stack.pop(Type.DOUBLE);
final Expr top = new CastExpr(expr, Type.LONG, Type.LONG);
stack.push(top);
}
public void visit_d2f(final Instruction inst) {
final Expr expr = stack.pop(Type.DOUBLE);
final Expr top = new CastExpr(expr, Type.FLOAT, Type.FLOAT);
stack.push(top);
}
public void visit_i2b(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.BYTE, Type.INTEGER);
stack.push(top);
}
public void visit_i2c(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.CHARACTER, Type.INTEGER);
stack.push(top);
}
public void visit_i2s(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
final Expr top = new CastExpr(expr, Type.SHORT, Type.INTEGER);
stack.push(top);
}
/**
* All <tt>visit_<i>x</i>cmp</tt> push an ArithExpr onto the stack.
*
* @see ArithExpr
*/
public void visit_lcmp(final Instruction inst) {
final Expr right = stack.pop(Type.LONG);
final Expr left = stack.pop(Type.LONG);
final Expr top = new ArithExpr(ArithExpr.CMP, left, right, Type.INTEGER);
stack.push(top);
}
public void visit_fcmpl(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.CMPL, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_fcmpg(final Instruction inst) {
final Expr right = stack.pop(Type.FLOAT);
final Expr left = stack.pop(Type.FLOAT);
final Expr top = new ArithExpr(ArithExpr.CMPG, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_dcmpl(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.CMPL, left, right,
Type.INTEGER);
stack.push(top);
}
public void visit_dcmpg(final Instruction inst) {
final Expr right = stack.pop(Type.DOUBLE);
final Expr left = stack.pop(Type.DOUBLE);
final Expr top = new ArithExpr(ArithExpr.CMPG, left, right,
Type.INTEGER);
stack.push(top);
}
/**
* All <tt>visit_<i>x</i>eg</tt> add an IfZeroStmt to the statement
* list.
*
* @see IfZeroStmt
*/
public void visit_ifeq(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.EQ, left, t, next));
}
public void visit_ifne(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.NE, left, t, next));
}
public void visit_iflt(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.LT, left, t, next));
}
public void visit_ifge(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.GE, left, t, next));
}
public void visit_ifgt(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.GT, left, t, next));
}
public void visit_ifle(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.LE, left, t, next));
}
/**
* All <tt>visit_if_<i>x</i>cmp<i>y</i></tt> add a IfCmpStmt to the
* statement list.
*/
public void visit_if_icmpeq(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.EQ, left, right, t, next));
}
public void visit_if_icmpne(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.NE, left, right, t, next));
}
public void visit_if_icmplt(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.LT, left, right, t, next));
}
public void visit_if_icmpge(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.GE, left, right, t, next));
}
public void visit_if_icmpgt(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.GT, left, right, t, next));
}
public void visit_if_icmple(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.INTEGER);
final Expr left = stack.pop(Type.INTEGER);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.LE, left, right, t, next));
}
public void visit_if_acmpeq(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.OBJECT);
final Expr left = stack.pop(Type.OBJECT);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.EQ, left, right, t, next));
}
public void visit_if_acmpne(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr right = stack.pop(Type.OBJECT);
final Expr left = stack.pop(Type.OBJECT);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfCmpStmt(IfStmt.NE, left, right, t, next));
}
/**
* Adds a GotoStmt to the statement list.
*
* @see GotoStmt
*/
public void visit_goto(final Instruction inst) {
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new GotoStmt(t));
}
/**
* Adds a JsrStmt to the statement list.
*
* @see JsrStmt
*/
public void visit_jsr(final Instruction inst) {
// Push the return address after we add the statement.
// This prevents it from being saved to a local variable.
// It's illegal to load a return address from a local variable,
// so we can't save it.
final Subroutine sub = block.graph().labelSub((Label) inst.operand());
addStmt(new JsrStmt(sub, next));
stack.push(new ReturnAddressExpr(Type.ADDRESS));
}
/**
* Adds a RetStmt to the statement list.
*
* @see RetStmt
*/
public void visit_ret(final Instruction inst) {
Assert.isTrue(sub != null);
addStmt(new RetStmt(sub));
}
/**
* Add a SwitchStmt to the statement list.
*
* @see SwitchStmt
*/
public void visit_switch(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr index = stack.pop(Type.INTEGER);
final Switch sw = (Switch) inst.operand();
final Block defaultTarget = (Block) block.graph().getNode(
sw.defaultTarget());
Assert.isTrue(defaultTarget != null, "No block for " + inst);
final Block[] targets = new Block[sw.targets().length];
for (int i = 0; i < targets.length; i++) {
targets[i] = (Block) block.graph().getNode(sw.targets()[i]);
Assert.isTrue(targets[i] != null, "No block for " + inst);
}
addStmt(new SwitchStmt(index, defaultTarget, targets, sw.values()));
}
/**
* All <tt>visit_<i>x</i>return</tt> add a ReturnExprStmt to the
* statement list.
*
* @see ReturnExprStmt
*/
public void visit_ireturn(final Instruction inst) {
final Expr expr = stack.pop(Type.INTEGER);
addStmt(new ReturnExprStmt(expr));
}
public void visit_lreturn(final Instruction inst) {
final Expr expr = stack.pop(Type.LONG);
addStmt(new ReturnExprStmt(expr));
}
public void visit_freturn(final Instruction inst) {
final Expr expr = stack.pop(Type.FLOAT);
addStmt(new ReturnExprStmt(expr));
}
public void visit_dreturn(final Instruction inst) {
final Expr expr = stack.pop(Type.DOUBLE);
addStmt(new ReturnExprStmt(expr));
}
public void visit_areturn(final Instruction inst) {
final Expr expr = stack.pop(Type.OBJECT);
addStmt(new ReturnExprStmt(expr));
}
/**
* Adds a ReturnStmt to the statement list.
*/
public void visit_return(final Instruction inst) {
addStmt(new ReturnStmt());
}
/**
* Pushes a StaticFieldExpr onto the operand stack.
*/
public void visit_getstatic(final Instruction inst) {
final MemberRef field = (MemberRef) inst.operand();
final Type type = field.nameAndType().type();
try {
final EditorContext context = block.graph().method()
.declaringClass().context();
final FieldEditor e = context.editField(field);
if (e.isFinal()) {
if (e.constantValue() != null) {
final Expr top = new ConstantExpr(e.constantValue(), type);
stack.push(top);
context.release(e.fieldInfo());
return;
}
}
context.release(e.fieldInfo());
} catch (final NoSuchFieldException e) {
// No field found. Silently assume non-final.
}
final Expr top = new StaticFieldExpr(field, type);
stack.push(top);
}
public void visit_putstatic(final Instruction inst) {
final MemberRef field = (MemberRef) inst.operand();
final Type type = field.nameAndType().type();
final Expr value = stack.pop(type);
final StaticFieldExpr target = new StaticFieldExpr(field, type);
addStore(target, value);
}
public void visit_putstatic_nowb(final Instruction inst) {
visit_putstatic(inst);
}
/**
* Pushes a FieldExpr onto the operand stack.
*/
public void visit_getfield(final Instruction inst) {
final MemberRef field = (MemberRef) inst.operand();
final Type type = field.nameAndType().type();
final Expr obj = stack.pop(Type.OBJECT);
final Expr check = new ZeroCheckExpr(obj, obj.type());
final Expr top = new FieldExpr(check, field, type);
stack.push(top);
}
public void visit_putfield(final Instruction inst) {
final MemberRef field = (MemberRef) inst.operand();
final Type type = field.nameAndType().type();
final Expr value = stack.pop(type);
final Expr obj = stack.pop(Type.OBJECT);
Expr ucCheck = obj;
if (Tree.USE_PERSISTENT) {
ucCheck = new UCExpr(obj, UCExpr.POINTER, obj.type());
}
final Expr check = new ZeroCheckExpr(ucCheck, obj.type());
final FieldExpr target = new FieldExpr(check, field, type);
addStore(target, value);
}
// Don't insert UCExpr
public void visit_putfield_nowb(final Instruction inst) {
final MemberRef field = (MemberRef) inst.operand();
final Type type = field.nameAndType().type();
final Expr value = stack.pop(type);
final Expr obj = stack.pop(Type.OBJECT);
final Expr check = new ZeroCheckExpr(obj, obj.type());
final FieldExpr target = new FieldExpr(check, field, type);
addStore(target, value);
}
/**
* All <tt>visit_invoke<i>x</i></tt> deal with a CallMethodExpr or a
* CallStaticExpr.
*
* @see CallMethodExpr
* @see CallStaticExpr
*/
public void visit_invokevirtual(final Instruction inst) {
addCall(inst, CallMethodExpr.VIRTUAL);
}
public void visit_invokespecial(final Instruction inst) {
addCall(inst, CallMethodExpr.NONVIRTUAL);
}
public void visit_invokestatic(final Instruction inst) {
addCall(inst, 0);
}
public void visit_invokeinterface(final Instruction inst) {
addCall(inst, CallMethodExpr.INTERFACE);
}
/**
* Creates either a CallMethodExpr or a CallStaticExpr to represent a method
* call. After obtaining some information about the method. The parameters
* to the methods are popped from the operand stack. If the method is not
* static, the "this" object is popped from the operand stack. A
* CallMethodExpr is created for a non-static method and a CallStaticExpr is
* created for a static method. If the method returns a value, the Call*Expr
* is pushed onto the stack. If the method has no return value, it is
* wrapped in an ExprStmt and is added to the statement list.
*/
private void addCall(final Instruction inst, final int kind) {
final MemberRef method = (MemberRef) inst.operand();
final Type type = method.nameAndType().type();
final Type[] paramTypes = type.paramTypes();
final Expr[] params = new Expr[paramTypes.length];
for (int i = paramTypes.length - 1; i >= 0; i--) {
params[i] = stack.pop(paramTypes[i]);
}
Expr top;
if (inst.opcodeClass() != Opcode.opcx_invokestatic) {
final Expr obj = stack.pop(Type.OBJECT);
top = new CallMethodExpr(kind, obj, params, method, type
.returnType());
} else {
top = new CallStaticExpr(params, method, type.returnType());
}
if (type.returnType().equals(Type.VOID)) {
addStmt(new ExprStmt(top));
} else {
stack.push(top);
}
}
/**
* Pushes a NewExpr onto the operand stack.
*
* @see NewExpr
*/
public void visit_new(final Instruction inst) {
final Type type = (Type) inst.operand();
final Expr top = new NewExpr(type, Type.OBJECT);
stack.push(top);
db(" new: " + top);
}
/**
* Pushes a NewArrayExpr onto the operand stack.
*/
public void visit_newarray(final Instruction inst) {
final Type type = (Type) inst.operand();
final Expr size = stack.pop(Type.INTEGER);
final Expr top = new NewArrayExpr(size, type, type.arrayType());
stack.push(top);
}
/**
* Pushes an ArrayLengthExpr onto the operand stack.
*
* @see ArrayLengthExpr
*/
public void visit_arraylength(final Instruction inst) {
final Expr array = stack.pop(Type.OBJECT);
final Expr top = new ArrayLengthExpr(array, Type.INTEGER);
stack.push(top);
}
/**
* Adds a ThrowStmt to the statement list.
*
* @see ThrowStmt
*/
public void visit_athrow(final Instruction inst) {
final Expr expr = stack.pop(Type.THROWABLE);
addStmt(new ThrowStmt(expr));
}
/**
* Pushes a CastExpr onto the operand stack.
*
* @see CastExpr
*/
public void visit_checkcast(final Instruction inst) {
final Expr expr = stack.pop(Type.OBJECT);
final Type type = (Type) inst.operand();
final Expr top = new CastExpr(expr, type, type);
stack.push(top);
}
/**
* Pushes an InstanceOfExpr onto the operand stack.
*
* @see InstanceOfExpr
*/
public void visit_instanceof(final Instruction inst) {
final Type type = (Type) inst.operand();
final Expr expr = stack.pop(Type.OBJECT);
final Expr top = new InstanceOfExpr(expr, type, Type.INTEGER);
stack.push(top);
}
/**
* Both <tt>monitor</tt> visitors add a MonitorStmt to the statement list.
*
* @see MonitorStmt
*/
public void visit_monitorenter(final Instruction inst) {
final Expr obj = stack.pop(Type.OBJECT);
addStmt(new MonitorStmt(MonitorStmt.ENTER, obj));
}
public void visit_monitorexit(final Instruction inst) {
final Expr obj = stack.pop(Type.OBJECT);
addStmt(new MonitorStmt(MonitorStmt.EXIT, obj));
}
/**
* Push a NewMultiArrayExpr onto the operand stack.
*
* @see NewMultiArrayExpr
*/
public void visit_multianewarray(final Instruction inst) {
final MultiArrayOperand operand = (MultiArrayOperand) inst.operand();
final Expr[] dim = new Expr[operand.dimensions()];
for (int i = dim.length - 1; i >= 0; i--) {
dim[i] = stack.pop(Type.INTEGER);
}
final Type type = operand.type();
final Expr top = new NewMultiArrayExpr(dim, type
.elementType(dim.length), type);
stack.push(top);
}
/**
* Both <tt>visit_<i>x</i>null</tt> add an IfZeroStmt to the statement
* list.
*
* ssee IfZeroStmt
*/
public void visit_ifnull(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.OBJECT);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.EQ, left, t, next));
}
public void visit_ifnonnull(final Instruction inst) {
// It isn't necessary to saveStack since removing critical edges
// guarantees that no code will be inserted before the branch
// since there cannot be more than one predecessor of either of
// the successor nodes (and hence no phi statements, even in SSAPRE).
// saveStack();
final Expr left = stack.pop(Type.OBJECT);
final Block t = (Block) block.graph().getNode(inst.operand());
Assert.isTrue(t != null, "No block for " + inst);
addStmt(new IfZeroStmt(IfStmt.NE, left, t, next));
}
/**
* Replaces the expression on the top of the stack with an RCExpr.
*
* @see RCExpr
*/
public void visit_rc(final Instruction inst) {
final Integer depth = (Integer) inst.operand();
final Expr object = stack.peek(depth.intValue());
stack.replace(depth.intValue(), new RCExpr(object, object.type()));
}
/**
*
*/
public void visit_aupdate(final Instruction inst) {
Integer depth = (Integer) inst.operand();
if (Tree.AUPDATE_FIX_HACK) {
// Hack to fix a bug in old bloat-generated code:
if (depth.intValue() == 1) {
final Expr object = stack.peek();
if (object.type().isWide()) {
depth = new Integer(2);
inst.setOperand(depth);
Tree.AUPDATE_FIX_HACK_CHANGED = true;
}
}
}
final Expr object = stack.peek(depth.intValue());
stack.replace(depth.intValue(), new UCExpr(object, UCExpr.POINTER,
object.type()));
}
/**
* Replace the expression at the stack depth specified in the instruction
* with a UCExpr.
*
* @see UCExpr
*/
public void visit_supdate(final Instruction inst) {
final Integer depth = (Integer) inst.operand();
final Expr object = stack.peek(depth.intValue());
stack.replace(depth.intValue(), new UCExpr(object, UCExpr.SCALAR,
object.type()));
}
/**
* Add a SCStmt to the statement list
*
* @see SCStmt
*/
public void visit_aswizzle(final Instruction inst) {
final Expr index = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.OBJECT.arrayType());
addStmt(new SCStmt(array, index));
}
/**
* Add a SRStmt to the statement list.
*
* @see SRStmt
*/
public void visit_aswrange(final Instruction inst) {
final Expr end = stack.pop(Type.INTEGER);
final Expr start = stack.pop(Type.INTEGER);
final Expr array = stack.pop(Type.OBJECT.arrayType());
addStmt(new SRStmt(array, start, end));
}
/**
* Visit all the statements in the statement list.
*/
public void visitForceChildren(final TreeVisitor visitor) {
final LinkedList list = new LinkedList(stmts);
if (visitor.reverse()) {
final ListIterator iter = list.listIterator(stmts.size());
while (iter.hasPrevious()) {
final Stmt s = (Stmt) iter.previous();
s.visit(visitor);
}
} else {
final ListIterator iter = list.listIterator();
while (iter.hasNext()) {
final Stmt s = (Stmt) iter.next();
s.visit(visitor);
}
}
}
public void visit(final TreeVisitor visitor) {
visitor.visitTree(this);
}
public Node parent() {
return null;
} | 1 |
private void updateStateTellNotExist(List<Keyword> keywords, List<String> terms, List<String> approval, boolean inAden, boolean askPrice) throws WrongStateClassException {
if( approval.isEmpty()) {
if( keywords.isEmpty() ) {
DialogManager.giveDialogManager().setInErrorState(true);
return;
}
CanteenInfo subState = matchSubState(keywords, terms, inAden, askPrice);
CanteenInformationState nextState = new CanteenInformationState();
nextState.setCurrentState(subState);
setCurrentDialogState(nextState);
return;
}
if( approval.size() != 1) {
DialogManager.giveDialogManager().setInErrorState(true);
return;
}
if( approval.get(0).equals("yes")) { //user wants another information
if( keywords.isEmpty() && (terms.isEmpty())) {
DialogManager.giveDialogManager().setInErrorState(true);
return;
}
CanteenInfo subState = matchSubState(keywords, terms, inAden, askPrice);
CanteenInformationState nextState = new CanteenInformationState();
nextState.setCurrentState(subState);
setCurrentDialogState(nextState);
return;
} else { // user don't need anything from canteen info
CanteenInformationState next = new CanteenInformationState();
next.setCurrentState(CanteenInfo.CI_EXIT);
setCurrentDialogState(next);
}
} | 6 |
public static void comp() {
int i1 = 123;
int i2 = 123;
int i3 = 456;
if (i1 == i2) {
System.out.println("i1とi2は等しい");
}
if (i1 != i3) {
System.out.println("i1とi3は等しくない");
}
if (i1 < i3) {
System.out.println("i3はi1より大きい");
}
String s1 = "123";
String s2 = new String("123");
if (s1 == s2) {
System.out.println("s1とs2の参照が等しい");
}
if (s1.equals(s2)) {
System.out.println("s1とs2の値が等しい");
}
// 値の大小を比較
int result = s1.compareTo(s2);
if (result == 0) {
System.out.println("値が等しい");
} else if (result < 0) {
System.out.println("s1はs2より小さい");
} else if (result > 0) {
System.out.println("s1はs2より大きい");
}
} | 8 |
@Before
public void setUp() throws Exception
{
_underTest = new Player("Tester");
} | 0 |
private static int runProcess(String[] cmd, String[] environment,
InputStream in, OutputStream out,
OutputStream err)
throws IOException
{
Process p;
if (environment == null) {
p = Runtime.getRuntime().exec(cmd);
} else {
p = Runtime.getRuntime().exec(cmd, environment);
}
try {
PipeThread inThread = null;
if (in != null) {
inThread = new PipeThread(false, in, p.getOutputStream());
inThread.start();
} else {
p.getOutputStream().close();
}
PipeThread outThread = null;
if (out != null) {
outThread = new PipeThread(true, p.getInputStream(), out);
outThread.start();
} else {
p.getInputStream().close();
}
PipeThread errThread = null;
if (err != null) {
errThread = new PipeThread(true, p.getErrorStream(), err);
errThread.start();
} else {
p.getErrorStream().close();
}
// wait for process completion
for (;;) {
try {
p.waitFor();
if (outThread != null) {
outThread.join();
}
if (inThread != null) {
inThread.join();
}
if (errThread != null) {
errThread.join();
}
break;
} catch (InterruptedException ignore) {
}
}
return p.exitValue();
} finally {
p.destroy();
}
} | 9 |
private String setFax( String line){
Pattern p = Pattern.compile("(fax)?.*[0-9\\.\\s]+(fax)?", Pattern.CASE_INSENSITIVE);
Pattern p2 = Pattern.compile("([0-9])");
Matcher m, m2;
int nbNumeric = 0;
String result=null;
if(null!=line && line.length()>0){
m = p.matcher(line);
if(m.find() && line.length()>0){
m2 = p2.matcher(line);
if(m2.find()){
while(m2.find()){
nbNumeric++;
}
if(nbNumeric > 5){
result = line;
result = result.replaceAll("([0-9])O","$10");
result = result.replaceAll("O([0-9])","0$1");
result = result.replaceAll("[\\p{L}\\:\\s\\.\\-]+", "");
result = result.replaceAll("[^0-9\\-\\+\\(\\)]+", "");
result = result.replaceAll("^\\.", "");
result = ToolBox.cleanString(result, true, true);
if(card_telephone!=null && card_telephone.contains(result)){
result=null;
}
}
}
}
}
return result;
} | 9 |
public static void shellSort(Comparable [] array,int increment){
int index=0;
int bounder=index+increment;
int innerIndex=0;
while(index < array.length && index < bounder)
{
//单次的插入排序程序
for(innerIndex = index+increment;innerIndex<array.length-increment;innerIndex=innerIndex+increment){
Comparable key = array[innerIndex];
int position =index;
//升序排列
while( position < array.length-increment
&& array[position].compareTo(key) < 0)
position+=increment;
Comparable temp=array[position];
array[position]=key;
for(int i=position;i<array.length;i=i+increment)
{
Comparable tem=array[position];
array[position]=temp;
temp=tem;
}
}
index++;
}
} | 6 |
public void keyPressed(KeyEvent w) {
int code = w.getKeyCode();
if (code == KeyEvent.VK_A) {
left = true;
right = false;
dx = -SPEED;
} else if (code == KeyEvent.VK_D) {
right = true;
left = false;
dx = SPEED;
} else if (code == KeyEvent.VK_W) {
up = true;
down = false;
dy = -SPEED;
} else if (code == KeyEvent.VK_S) {
down = true;
up = false;
dy = SPEED;
}
} | 4 |
public int hashCode()
{
final int MOD_ADLER = 65521;
int a = 1;
int b = 0;
String nodeStr = Integer.toString(startIndex);
String offsetStr = Integer.toString(startOffset);
String vStr = versions.toString();
int hDataLen = data.length+nodeStr.length()
+offsetStr.length()+vStr.length();
char[] hashData = new char[hDataLen];
int j = 0;
for ( int i=0;i<nodeStr.length();i++ )
hashData[j++] = nodeStr.charAt(i);
for ( int i=0;i<offsetStr.length();i++ )
hashData[j++] = offsetStr.charAt(i);
for ( int i=0;i<vStr.length();i++ )
hashData[j++] = vStr.charAt(i);
for ( int i=0;i<data.length;i++ )
hashData[j++] = data[i];
for ( int i=0;i<hashData.length;++i )
{
a = (a+hashData[i])%MOD_ADLER;
b = (a+b)%MOD_ADLER;
}
return (b<<16)|a;
} | 5 |
public static void aesOfbCrypt(byte[] data, byte[] iv) {
//Maple's OFB is done in piecemeal every 1460 bytes (I'm guessing it has
//to deal with maximum segment size). First piece is only 1456 bytes
//because the header, although not encrypted, adds 4 blocks to the first
//segment.
BlockCipher ciph = aes256.get();
//loops through each 1460 byte piece (with first piece only 1456 bytes)
for (
int remaining = data.length, offset = 0, pieceSize = Math.min(1456, remaining);
remaining > 0;
remaining -= pieceSize, offset += pieceSize, pieceSize = Math.min(1460, remaining)) {
byte[] myIv = ByteTool.multiplyBytes(iv, 4, 4);
//OFB (which is just input block XOR'd with encrypted IV and key) each full block (block size is equal to IV size)
int fullBlocks = pieceSize / myIv.length;
for (int i = 0; i < fullBlocks; i++) {
ciph.processBlock(myIv, 0, myIv, 0); //encrypt IV with key and copy output back to IV
for (int j = 0; j < myIv.length; j++)
data[offset + i * myIv.length + j] ^= myIv[j]; //XOR input block with encrypted IV and key
}
//OFB the final, incomplete block - OFB doesn't need block size aligned input
ciph.processBlock(myIv, 0, myIv, 0);
for (int i = pieceSize % myIv.length - 1; i >= 0; i--)
data[offset + fullBlocks * myIv.length + i] ^= myIv[i];
}
} | 4 |
@Override
public void handleMessages(Inbox inbox) {
while (inbox.hasNext()) {
Message msg = inbox.next();
if (msg instanceof PackHelloOldBetEtx) {
PackHelloOldBetEtx a = (PackHelloOldBetEtx) msg;
handlePackHello(inbox.getSender(), inbox.getReceiver(), a);
}else if (msg instanceof PackReplyOldBetEtx) {
PackReplyOldBetEtx b = (PackReplyOldBetEtx) msg;
handlePackReply(inbox.getSender(), inbox.getReceiver(), b);
}
}
} | 3 |
static final void method3385(int i, int i_0_, int i_1_, int i_2_, int i_3_, int i_4_, int i_5_, boolean bool, int i_6_) {
anInt3582++;
if (!CacheNode_Sub15.method2379(7015, i)) {
if ((i_4_ ^ 0xffffffff) == 0) {
for (int i_7_ = 0; i_7_ < 100; i_7_++)
Class195.aBooleanArray2387[i_7_] = true;
} else {
Class195.aBooleanArray2387[i_4_] = true;
}
} else {
if (bool != true) {
method3385(-73, 124, 90, 10, 48, 28, -80, false, -91);
}
int i_8_ = 0;
int i_9_ = 0;
int i_10_ = 0;
int i_11_ = 0;
int i_12_ = 0;
if (Class71.aBoolean967) {
i_11_ = Class308.anInt3914;
i_12_ = Node_Sub53.anInt7669;
i_8_ = Node_Sub33.anInt7405;
i_9_ = Class168.anInt2046;
i_10_ = Class320_Sub28.anInt8469;
Node_Sub53.anInt7669 = 1;
}
if (Class79.aWidgetArrayArray1082[i] == null) {
Node_Sub6.method2416(-1, i_5_, Class134_Sub3.aWidgetArrayArray9035[i], i_0_, i_2_, i_6_, i_4_, i_4_ < 0, 90, i_1_, i_3_);
} else {
Node_Sub6.method2416(-1, i_5_, Class79.aWidgetArrayArray1082[i], i_0_, i_2_, i_6_, i_4_, (i_4_ ^ 0xffffffff) > -1, 27, i_1_, i_3_);
}
if (Class71.aBoolean967) {
if (i_4_ >= 0 && Node_Sub53.anInt7669 == 2) {
Class362.method4053(Class168.anInt2046, Class308.anInt3914, Node_Sub33.anInt7405, (byte) -115, Class320_Sub28.anInt8469);
}
Class168.anInt2046 = i_9_;
Class308.anInt3914 = i_11_;
Node_Sub33.anInt7405 = i_8_;
Node_Sub53.anInt7669 = i_12_;
Class320_Sub28.anInt8469 = i_10_;
}
}
} | 9 |
public void startServer(){
//read network configuration
Configuration config;
try{
config = new PropertiesConfiguration("network.cfg");
} catch (ConfigurationException e) {
try{
config = new PropertiesConfiguration("network.cfg.default");
} catch (ConfigurationException e2) {
LOGGER.error("Cannot read network configuration");
throw new RuntimeException(e2);
}
}
//instantiating InetAddress to resolve local IP
try{
inetAddress = InetAddress.getLocalHost();
} catch (UnknownHostException e){
LOGGER.error("Cannot instantiate IP resolver");
throw new RuntimeException(e);
}
String[] urls = config.getStringArray("node.url");
processes = new ArrayList<DA_Byzantine_RMI>();
//bind local processes and locate remote ones
int processIndex = 0;
for (String url : urls){
try{
DA_Byzantine_RMI process;
if (isProcessLocal(url)){
process = new DA_Byzantine(urls, processIndex);
LOGGER.debug("Process " + processIndex + " is local.");
new Thread((DA_Byzantine)process).start();
Naming.bind(url, process);
} else {
process = (DA_Byzantine_RMI)Naming.lookup(url);
LOGGER.debug("Looking up for process with URL " + url);
}
processIndex++;
processes.add(process);
} catch (RemoteException e1){
throw new RuntimeException(e1);
} catch (AlreadyBoundException e2){
throw new RuntimeException(e2);
} catch (NotBoundException e3){
throw new RuntimeException(e3);
} catch (MalformedURLException e4){
throw new RuntimeException(e4);
}
}
} | 9 |
public static String pad(String s) {
if (s.length() == 0) return " ";
char first = s.charAt(0);
char last = s.charAt(s.length()-1);
if (first == ' ' && last == ' ') return s;
if (first == ' ' && last != ' ') return s + " ";
if (first != ' ' && last == ' ') return " " + s;
if (first != ' ' && last != ' ') return " " + s + " ";
// impossible
return s;
} | 9 |
public static void playSound(String filename) {
try {
// From file.
AudioInputStream stream = AudioSystem.getAudioInputStream(
filename.getClass().getResource(filename));
// At present, ALAW and ULAW encodings must be converted to
// PCM_SIGNED before they can be played.
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(),
true); // big endian
stream = AudioSystem.getAudioInputStream(format, stream);
}
DataLine.Info info = new DataLine.Info(Clip.class,
stream.getFormat(), ((int) stream.getFrameLength() *
format.getFrameSize()));
Clip clip = (Clip) AudioSystem.getLine(info);
// This method does not return until the audio file is completely
// loaded.
clip.open(stream);
// Start playing.
clip.start();
} catch (IOException ioe) {
cat.error(ioe);
} catch (LineUnavailableException lue) {
cat.error(lue);
} catch (UnsupportedAudioFileException uafe) {
cat.error(uafe);
}
} | 4 |
public void clear() {
accessTimes.clear();
map.clear();
}//clear | 0 |
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (int) (this.id ^ (this.id >>> 32));
hash = 97 * hash + this.numeroEtudiant;
hash = 97 * hash + (this.prenom != null ? this.prenom.hashCode() : 0);
hash = 97 * hash + (this.nom != null ? this.nom.hashCode() : 0);
hash = 97 * hash + (this.email != null ? this.email.hashCode() : 0);
hash = 97 * hash + (this.telephone != null ? this.telephone.hashCode() : 0);
hash = 97 * hash + (this.notificationsActives ? 1 : 0);
hash = 97 * hash + (int) (this.idPromotion ^ (this.idPromotion >>> 32));
hash = 97 * hash + (int) (this.idSpecialite ^ (this.idSpecialite >>> 32));
return hash;
} | 5 |
public int GetCLFishing(int ItemID) {
if (ItemID == 10755) {
return 100;
}
if (ItemID == 10757) {
return 100;
}
if (ItemID == -1) {
return 1;
}
String ItemName = GetItemName(ItemID);
if (ItemName.startsWith("Fishing cape")) {
return 100;
}
if (ItemName.startsWith("Fishing hood")) {
return 100;
}
return 1;
} | 5 |
@Override
public NormalLikeDistribution[] getOrderDistributions(double mean, double sd) {
double periodMean = mean/(forerun+1);
double periodSd = Math.sqrt(((sd*sd)/(forerun+1)));
NormalDistribution orderDistribution = new NormalDistribution(periodMean, periodSd);
RealSinglePointDistribution emptyOrder = new RealSinglePointDistribution(0);
NormalLikeDistribution[] orderDistributions = new NormalLikeDistribution[forerun+1+offSet];
for (int i = 0; i < orderDistributions.length; i++){
if (i < offSet) orderDistributions[i] = emptyOrder;
else orderDistributions[i] = orderDistribution;
}
return orderDistributions;
} | 2 |
public boolean accountMatch(String name, String password) {
if (User.getUserByUsername(name) == null)
return false;
Encryption e = new Encryption();
String hashedPassword = e.generateHashedPassword(password);
try {
String statement = new String("SELECT password FROM " + DBTable +" WHERE username = ?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setString(1, name);
ResultSet rs = DBConnection.DBQuery(stmt);
rs.next();
String storedPassword = rs.getString("password");
if(hashedPassword.equals(storedPassword))
return true;
} catch (SQLException e1) {
e1.printStackTrace();
}
return false;
} | 3 |
public static void main(String arg[]) {
try {
MmsParamsReader mp = new MmsParamsReader(new java.io.FileReader(arg[0]));
ParameterSet mps = mp.read();
System.out.println ("Dimensions = " + mps.getDims());
System.out.println ("Parameters = " + mps.getParams());
} catch (java.io.FileNotFoundException e) {
System.out.println(arg[0] + " not found");
} catch (java.io.IOException e) {
System.out.println(arg[0] + " io exception");
}
} | 2 |
public void breadthFirst() {
int start = 0;
int end = 0;
graph[0].setIdentified();
queue[end] = graph[0];
end++;
while (start != end) {
Node u = queue[start];
start++;
for (int i = 0; i < size; i++) {
Node v = u.getNode(i);
if (v != null && !v.identified() && !v.visited()) {
v.setIdentified();
queue[end] = v;
end++;
}
}
u.setVisited();
}
for (int i = 0; i < size; i++) {
if (queue[i] != null) {
System.out.println(queue[i].getItem());
}
}
} | 7 |
public void setWait(){
wait = true;
} | 0 |
public Collection interfaces(final Type type) {
final TypeNode node = getImplementsNode(type);
if (node != null) {
final List list = new ArrayList(implementsGraph.succs(node));
final ListIterator iter = list.listIterator();
while (iter.hasNext()) {
final TypeNode v = (TypeNode) iter.next();
iter.set(v.type);
}
return list;
}
return new ArrayList();
} | 2 |
public boolean conditionMatches(CombineableOperator combinable) {
return (type == POSSFOR || cond.containsMatchingLoad(combinable));
} | 1 |
public void saveSimulation(String fname) {
if (sim != null) {
try {
Path td = Files.createTempDirectory("PDTemp_");
List<WorldDescriptor> worldsToSave = sim.getWDStack();
for (int i = 0; i < worldsToSave.size(); i++) {
WDLoader loader = new JAXBWDLoader(td + "/"
+ Integer.toString(i) + ".xml");
loader.save(worldsToSave.get(i));
}
/* Output Stream - that will hold the physical TAR file */
OutputStream tar_output = new FileOutputStream(new File(fname));
/*
* Create Archive Output Stream that attaches File Output Stream
* / and specifies TAR as type of compression
*/
ArchiveOutputStream my_tar_ball = new ArchiveStreamFactory()
.createArchiveOutputStream(ArchiveStreamFactory.TAR,
tar_output);
/* Create Archieve entry - write header information */
for (int i = 0; i < worldsToSave.size(); i++) {
File tar_input_file = new File(td + "/"
+ Integer.toString(i) + ".xml");
TarArchiveEntry tar_file = new TarArchiveEntry(
tar_input_file, Integer.toString(i) + ".xml");
tar_file.setSize(tar_input_file.length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(tar_input_file),
my_tar_ball);
my_tar_ball.closeArchiveEntry();
}
my_tar_ball.finish();
tar_output.close();
} catch (IOException e) {
logger.error("IO error while saving simulation.");
ui.error("Exception occured while saving simulation.");
} catch (ArchiveException e) {
logger.error("Error while creating TAR archive");
ui.error("Exception occured while saving simulation.");
}
}
} | 5 |
public void damage(int amt)
{
if(state == STATE_IDLE)
state = STATE_CHASE;
health -= amt;
if(health <= 0)
state = STATE_DYING;
} | 2 |
private void btnFinalizarVendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarVendActionPerformed
try {
if (JOptionPane.showConfirmDialog(rootPane, "Deseja Salvar?") == 0) {
Funcionario f = (Funcionario) jcbFuncionarioVend.getSelectedItem();
Cliente c = (Cliente) jbcClienteVend.getSelectedItem();
Pagamento pgt = (Pagamento) jcbPagamentoVend.getSelectedItem();
//=============
venda.setAtendente(f);
venda.setConsumidor(c);
venda.setTipo_paga(pgt);
if (dao.Salvar(venda)) {
JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!");
} else {
JOptionPane.showMessageDialog(rootPane, "Falha ao salvar! Consulte o administrador do sistema!");
}
} else {
JOptionPane.showMessageDialog(rootPane, "Operação cancelada!");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(rootPane, "Erro ao salvar! Consulte o administrador do sistema!");
}
}//GEN-LAST:event_btnFinalizarVendActionPerformed | 3 |
public void actionPerformed(ActionEvent arg0) {
Component apane = environment.tabbed.getSelectedComponent();
JComponent c=(JComponent)environment.getActive();
SaveGraphUtility.saveGraph(apane, c,"GIF files", "gif");
} | 0 |
public void init(Map attributes) throws InvalidKeyException {
synchronized(lock) {
if (currentKey != null) {
throw new IllegalStateException();
}
Integer bs = (Integer) attributes.get(CIPHER_BLOCK_SIZE);
if (bs == null) { // no block size was specified.
if (currentBlockSize == 0) { // happy birthday
currentBlockSize = defaultBlockSize;
} // else it's a clone. use as is
} else {
currentBlockSize = bs.intValue();
// ensure that value is valid
Iterator it;
boolean ok = false;
for (it = blockSizes(); it.hasNext(); ) {
ok = (currentBlockSize == ((Integer) it.next()).intValue());
if (ok) {
break;
}
}
if (!ok) {
throw new IllegalArgumentException(IBlockCipher.CIPHER_BLOCK_SIZE);
}
}
byte[] k = (byte[]) attributes.get(KEY_MATERIAL);
currentKey = makeKey(k, currentBlockSize);
}
} | 6 |
public static void main(String args[]){
//Creating a colour scheme to test the renderer with
Colour[] colours = new Colour[5];
final int MAP_SIZE = 5;
for (int i=0; i<MAP_SIZE; i++) {
switch (i) {
case 0: Colour black = new Colour("#000000");
colours[i] = black;
break;
case 1: Colour darkgrey = new Colour("#222222");
colours[i] = darkgrey;
break;
case 2: Colour grey = new Colour("#555555");
colours[i] = grey;
break;
case 3: Colour lightgrey = new Colour("#BBBBBB");
colours[i] = lightgrey;
break;
case 4: Colour white = new Colour("#EEEEEE");
colours[i] = white;
break;
}
}
ColourMap greyscale = new ColourMap(colours, "Greyscale");
CustomPieRenderer testCustomPieRenderer =
new CustomPieRenderer(greyscale);
//Test GetMap method
testCustomPieRenderer.GetMap();
System.out.println("CustomPieRenderer:: GetMap() - Test Passed");
//Test SetMap method
testCustomPieRenderer.SetMap(greyscale);
System.out.println("CustomPieRenderer:: SetMap() - Test Passed");
} | 6 |
public static void printGRNToFile(final String fileName, final Grn grn, final double[][] results) {
NumberFormat formatter = new DecimalFormat("###.#########");
try{
File file =new File(fileName);
//if file doesnt exists, then create it
boolean created = false;
if(!file.exists()){
file.createNewFile();
created = true;
}
//true = append file
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
if (created) {
for (int i = 0; i < grn.tfProteins.length - grn.numberOfInputs; i++)
bufferWritter.write("TF"+i+" ");
for (int i = 0; i < grn.numberOfInputs; i++)
bufferWritter.write("I"+i+" ");
for (int i = 0; i < grn.pProteins.length; i++)
bufferWritter.write("P"+i+" ");
bufferWritter.write("\n");
}
for (int t = 0; t < results.length; t++) {
for (int i = 0; i < results[t].length; i++)
bufferWritter.write(formatter.format(results[t][i])+" ");
bufferWritter.write("\n");
}
bufferWritter.close();
fileWritter.close();
}
catch(IOException e){
e.printStackTrace();
}
} | 8 |
private void ConvertToCell(int x, int y)
{
Color basic = this.grid[x][y].getBackground();
Color a = new Color(255, 255, 255);
Color b = new Color(147, 208, 81);
Color c = new Color(52, 153, 51);
Color d = new Color(1, 73, 0);
Color e = new Color(231, 31, 27);
Color f = new Color(129, 130, 129);
Color g = new Color(109, 58, 150);
if (basic.equals(a)) {
this.tabToShow[x][y].setEtat(Etat.vide);//vide -- blanc -- 255,255,255 -- 0
} else if(basic.equals(b)){
this.tabToShow[x][y].setEtat(Etat.jeunePousse);//jeune pousse -- vert clair -- 147,208,81 -- 1
} else if(basic.equals(c)) {
this.tabToShow[x][y].setEtat(Etat.arbuste);//arbuste -- vert -- 52,153,51 -- 2
} else if(basic.equals(d)) {
this.tabToShow[x][y].setEtat(Etat.arbre);//arbre -- vert foncée -- 1,73,0 -- 3
} else if(basic.equals(e)) {
this.tabToShow[x][y].setEtat(Etat.feu);//feu -- rouge -- 231,31,27 -- 4
} else if(basic.equals(f)) {
this.tabToShow[x][y].setEtat(Etat.cendre);//cendre -- gris -- 129,130,129 -- 5
} else if(basic.equals(g)) {
this.tabToShow[x][y].setEtat(Etat.infecte);//infecte -- violet -- 109,58,150 -- 6
}
} | 7 |
public static void main(String[] args) throws Exception {
String env = null;
if (args != null && args.length > 0) {
env = args[0];
}
if (! "dev".equals(env))
if (! "prod".equals(env)) {
System.out.println("Usage: $0 (dev|prod)\n");
System.exit(1);
}
// Topology config
Config conf = new Config();
// Load parameters and add them to the Config
Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");
conf.putAll(configMap);
log.info(JSONValue.toJSONString((conf)));
// Set topology loglevel to DEBUG
conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));
// Create Topology builder
TopologyBuilder builder = new TopologyBuilder();
// if there are not special reasons, start with parallelism hint of 1
// and multiple tasks. By that, you can scale dynamically later on.
int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");
// Create Stream from RabbitMQ messages
// bind new queue with name of the topology
// to the main plan9 exchange (from properties config)
// consuming only CBT-related events by using the rounting key 'cbt.#'
String badgeName = StumbleBlunderBadgeTopology.class.getSimpleName();
String rabbitQueueName = badgeName; // use topology class name as name for the queue
String rabbitExchangeName = JsonPath.read(conf, "$.deck36_storm.StumbleBlunderBolt.rabbitmq.exchange");
String rabbitRoutingKey = JsonPath.read(conf, "$.deck36_storm.StumbleBlunderBolt.rabbitmq.routing_key");
// Get JSON deserialization scheme
Scheme rabbitScheme = new SimpleJSONScheme();
// Setup a Declarator to configure exchange/queue/routing key
RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey);
// Create Configuration for the Spout
ConnectionConfig connectionConfig =
new ConnectionConfig(
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat"));
ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig)
.queue(rabbitQueueName)
.prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"))
.requeueOnFail()
.build();
// add global parameters to topology config - the RabbitMQSpout will read them from there
conf.putAll(spoutConfig.asMap());
// For production, set the spout pending value to the same value as the RabbitMQ pre-fetch
// see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md
if ("prod".equals(env)) {
conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"));
}
// Add RabbitMQ spout to topology
builder.setSpout("incoming",
new RabbitMQSpout(rabbitScheme, rabbitDeclarator),
parallelism_hint)
.setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks"));
// construct command to invoke the external bolt implementation
ArrayList<String> command = new ArrayList(15);
// Add main execution program (php, hhvm, zend, ..) and parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));
// Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));
// Add main route to be invoked and its parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.StumbleBlunderBolt.main"));
List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.StumbleBlunderBolt.params");
if (boltParams != null)
command.addAll(boltParams);
// Log the final command
log.info("Command to start bolt for StumbleBlunder badge: " + Arrays.toString(command.toArray()));
// Add constructed external bolt command to topology using MultilangAdapterBolt
builder.setBolt("badge",
new MultilangAdapterBolt(command, "badge"),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("incoming");
builder.setBolt("rabbitmq_router",
new Plan9RabbitMQRouterBolt(
(String) JsonPath.read(conf, "$.deck36_storm.StumbleBlunderBolt.rabbitmq.target_exchange"),
"StumbleBlunder" // RabbitMQ routing key
),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("badge");
builder.setBolt("rabbitmq_producer",
new Plan9RabbitMQPushBolt(),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("rabbitmq_router");
if ("dev".equals(env)) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
Thread.sleep(2000000);
}
if ("prod".equals(env)) {
StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology());
}
} | 8 |
void readFrequencies() throws Exception {
int totalFrequencyCount = 0;
int atomCountInFirstModel = atomSetCollection.atomCount;
float[] xComponents = new float[5];
float[] yComponents = new float[5];
float[] zComponents = new float[5];
discardLinesUntilContains("FREQUENCY:");
while (line != null && line.indexOf("FREQUENCY:") >= 0) {
int lineBaseFreqCount = totalFrequencyCount;
ichNextParse = 17;
int lineFreqCount;
for (lineFreqCount = 0; lineFreqCount < 5; ++lineFreqCount) {
float frequency = parseFloat(line, ichNextParse);
//Logger.debug("frequency=" + frequency);
if (Float.isNaN(frequency))
break;
++totalFrequencyCount;
if (totalFrequencyCount > 1)
atomSetCollection.cloneFirstAtomSet();
}
Atom[] atoms = atomSetCollection.atoms;
discardLinesUntilBlank();
for (int i = 0; i < atomCountInFirstModel; ++i) {
readLine();
readComponents(lineFreqCount, xComponents);
readLine();
readComponents(lineFreqCount, yComponents);
readLine();
readComponents(lineFreqCount, zComponents);
for (int j = 0; j < lineFreqCount; ++j) {
int atomIndex = (lineBaseFreqCount + j) * atomCountInFirstModel + i;
Atom atom = atoms[atomIndex];
atom.vectorX = xComponents[j];
atom.vectorY = yComponents[j];
atom.vectorZ = zComponents[j];
}
}
discardLines(12);
readLine();
}
} | 7 |
public void read(BufferedReader buff)
{
try
{
while(buff.ready())
{
line = buff.readLine();
piecePlace = pattern[0].matcher(line);
pieceMove = pattern[2].matcher(line);
castle = pattern[1].matcher(line);
if(piecePlace.find())
{
String chessPiece = piecePlace.group("ChessPiece");
String chessColor = piecePlace.group("ChessColor");
String chessLetter = piecePlace.group("Column");
String chessNum = piecePlace.group("Row");
if(chessColor.equals("d"))
{
chessPiece = chessPiece.toLowerCase();
}
placePiece(numberTranslation(chessNum),letterTranslation(chessLetter), chessPiece);
System.out.println("Chess piece "+ chessPiece +" has been placed");
}
else if(castle.find())
{
String kingSpaceLetter1 = castle.group("KingOriginColumn");
String kingSpaceNum1 = castle.group("KingOriginRow");
String kingSpaceLetter2 = castle.group("KingNewColumn");
String kingSpaceNum2 = castle.group("KingNewRow");
String rookSpaceLetter1 = castle.group("RookOriginColumn");
String rookSpaceNum1 = castle.group("RookOriginRow");
String rookSpaceLetter2 = castle.group("RookNewColumn");
String rookSpaceNum2 = castle.group("RookNewRow");
moveTwoPieces(letterTranslation(kingSpaceLetter1), numberTranslation(kingSpaceNum1), letterTranslation(kingSpaceLetter2), numberTranslation(kingSpaceNum2),
letterTranslation(rookSpaceLetter1), numberTranslation(rookSpaceNum1), letterTranslation(rookSpaceLetter2), numberTranslation(rookSpaceNum2));
System.out.println("Castling has occured");
}
else if(pieceMove.find())
{
String firstSpaceLetter = pieceMove.group("OriginColumn");
String firstSpaceNum = pieceMove.group("OriginRow");
String secondSpaceLetter = pieceMove.group("NewColumn");
String secondSpaceNum = pieceMove.group("NewRow");
moveChessPiece(letterTranslation(firstSpaceLetter), numberTranslation(firstSpaceNum), letterTranslation(secondSpaceLetter), numberTranslation(secondSpaceNum));
System.out.println("Piece "+ b.checkBoard(numberTranslation(secondSpaceNum),letterTranslation(secondSpaceLetter)) +" has been moved");
}
else
{
System.err.println(line + " is not a valid input");
}
}
}
catch (IOException e)
{
System.err.println("IO exception");
}
} | 6 |
exact(int N, int[][] m){
this.sets = new ArrayList();
nodes = new HashSet();
for (int i = 0;i < N; i++)
nodes.add(i);
matr = m;
size = N;
ss = new int[size];
} | 1 |
private static boolean updateJoinCardinality(Join j,
Map<String, Integer> tableAliasToId,
Map<String, TableStats> tableStats) {
DbIterator[] children = j.getChildren();
DbIterator child1 = children[0];
DbIterator child2 = children[1];
int child1Card = 1;
int child2Card = 1;
String[] tmp1 = j.getJoinField1Name().split("[.]");
String tableAlias1 = tmp1[0];
String pureFieldName1 = tmp1[1];
String[] tmp2 = j.getJoinField2Name().split("[.]");
String tableAlias2 = tmp2[0];
String pureFieldName2 = tmp2[1];
boolean child1HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias1))
.equals(pureFieldName1);
boolean child2HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias2))
.equals(pureFieldName2);
if (child1 instanceof Operator) {
Operator child1O = (Operator) child1;
boolean pk = updateOperatorCardinality(child1O, tableAliasToId,
tableStats);
child1HasJoinPK = pk || child1HasJoinPK;
child1Card = child1O.getEstimatedCardinality();
child1Card = child1Card > 0 ? child1Card : 1;
} else if (child1 instanceof SeqScan) {
child1Card = (int) (tableStats.get(((SeqScan) child1)
.getTableName()).estimateTableCardinality(1.0));
}
if (child2 instanceof Operator) {
Operator child2O = (Operator) child2;
boolean pk = updateOperatorCardinality(child2O, tableAliasToId,
tableStats);
child2HasJoinPK = pk || child2HasJoinPK;
child2Card = child2O.getEstimatedCardinality();
child2Card = child2Card > 0 ? child2Card : 1;
} else if (child2 instanceof SeqScan) {
child2Card = (int) (tableStats.get(((SeqScan) child2)
.getTableName()).estimateTableCardinality(1.0));
}
j.setEstimatedCardinality(JoinOptimizer.estimateTableJoinCardinality(j
.getJoinPredicate().getOperator(), tableAlias1, tableAlias2,
pureFieldName1, pureFieldName2, child1Card, child2Card,
child1HasJoinPK, child2HasJoinPK, tableStats, tableAliasToId));
return child1HasJoinPK || child2HasJoinPK;
} | 9 |
protected boolean checkIfDivide(int previousToken){
if (previousToken == TokenNameIdentifier || previousToken == TokenNameStringLiteral ||
previousToken == TokenNameCharacterLiteral ||
previousToken == TokenNameIntegerLiteral ||
previousToken == TokenNameDoubleLiteral ||
previousToken == TokenNameLongLiteral ||
previousToken == TokenNameRPAREN ||
previousToken == TokenNameRBRACKET ||
previousToken == TokenNameUNKNOWN) {
return true;
}
return false;
} | 9 |
@Override
public void actionPerformed(ActionEvent ae) {
String comm = ae.getActionCommand();
switch (comm) {
case START_SERVER_AC:
if (electionsServer != null) {
System.err.println("Duplicate StartServer request in ServerFrame.actionPerformed(ActionEvent)-\n " + comm);
return;
}
try {
electionsServer = new ElectionsServer(PORT, new PrintStream(taWriter));
electionsServer.addObserver(this);
startMI.setEnabled(false);
} catch (Exception e) {
e.printStackTrace(System.err);
}
break;
case UNLOCK_ALL_AC:
lockedClientsLM.removeAll();
updateButtons();
break;
case UNLOCK_SELECTION_AC:
int idx = lockedClientsL.getSelectedIndex();
lockedClientsLM.remove(idx);
lockedClientsL.clearSelection();
updateButtons();
break;
default:
System.err.println("Unknown ACtionCommand received in ServerFrame.actionPerformed(ActionEvent)-\n " + comm);
}
} | 5 |
public int parseSDStatus(){
if(len<17) return 0;
//Starts with SD
int sdtext=17;
if(startsWithSD()){
int idx = indexOf('/');
if(idx == -1) return 0;
int done;
int total;
try {
done = Integer.parseInt(subSequence(sdtext, idx).toString());
int idx2 = indexOf('\n',idx+1);
if(idx2 == -1){
return 0;
}
String remain = subSequence(idx+1,idx2).toString();
total = Integer.parseInt(remain);
} catch (NumberFormatException e) {
return 0; //todo
}
if(total == 0 || (total/100) == 0) return 100;
if(done == 0) return 0;
return done/(total/100);
}
return 0; //ASCII
} | 8 |
private boolean save() {
String name = informationPanel.getName().trim();
String source = informationPanel.getSource().trim();
int time = informationPanel.getTime();
int calories = informationPanel.getCalories();
int portions = informationPanel.getPortions();
if ( name == null || name.equals("")){
showErrorMessage("You need to specify a name for the recipe", "Missing Name");
return false;
}
if ( portions < 0 ){
showErrorMessage("You need to specify the number of portions for the recipe.", "Missing portions");
return false;
}
Recipe newRecipe = assembleRecipe(name, time, calories, source, portions);
List<Recipe> recipes;
try{
recipes = db.retrieveAllRecipes();
} catch (DataStoreException e){
showErrorMessage("The database contains corrupted data.\n" +
"You cannot continue until this is fixed.\n" +
"Error message: " + e.getMessage(), "Fatal Database Error");
return false;
}
if(recipes.contains(newRecipe) && ! newRecipe.equals(oldRecipe)){
showErrorMessage("There already exists an recipe with this name,\n" +
"please choose a new name", "Duplicate Recipe Name");
return false;
}
//First time we save this recipe
if(oldRecipe == null){
if(db.addRecipe(newRecipe)){
notChanged();
oldRecipe = newRecipe;
return true;
} else {
showErrorMessage("There was an error saving the recipe to the database.", "Database Error");
return false;
}
} else { //This recipe has been saved before and is now being updated
if(db.updateRecipe(oldRecipe, newRecipe)){
notChanged();
oldRecipe = newRecipe;
return true;
} else {
showErrorMessage("There was an error saving the recipe to the database." , "Database Error");
return false;
}
}
} | 9 |
protected void receive(String line) {
if(line.startsWith(FILE_START_MAP)){
String name = TEMP_FOLDER_PATH+"map.smap";
FileTools.saveFromInput(new File(name), in, bufferSize);
Map map = new Map(new File(name));
game.init(map, this);
send(READY);
msg = "Now waiting for other players to be ready";
}
else if(line.startsWith(FILE_START_SKIN)){
String name = TEMP_FOLDER_PATH+line.substring(FILE_START_SKIN.length())+".sskin";
FileTools.saveFromInput(new File(name), in, bufferSize);
game.addPlayer(new File(name), line.substring(FILE_START_SKIN.length()));
}else if(line.startsWith(READY)){
game.start();
}else if (line.startsWith(PLAYER_NUM)){
player_connected = Integer.parseInt(line.split(" ")[1]);
max_players = Integer.parseInt(line.split(" ")[2]);
msg = "Currently "+player_connected+"/"+max_players+" players connected...";
}else{
if(line.contains(MORE)){
String[] lines = line.split(MORE);
for( String s : lines){
game.input(s);
}
}else
game.input(line);
}
} | 6 |
private void addChildren(JsonElement fromElement, JsonElement toElement) {
if (fromElement instanceof JsonObject && toElement instanceof JsonObject) {
JsonObject fromObject = (JsonObject) fromElement;
JsonObject toObject = (JsonObject) toElement;
for (Entry<String, JsonElement> entry : fromObject.entrySet()) {
toObject.add(entry.getKey(), entry.getValue());
}
} else if (fromElement instanceof JsonArray && toElement instanceof JsonArray) {
JsonArray fromArray = (JsonArray) fromElement;
JsonArray toArray = (JsonArray) toElement;
toArray.addAll(fromArray);
}
} | 5 |
public static MoodleGroup[] getGroupsFromCourseId(long id) throws MoodleRestGroupException, UnsupportedEncodingException, MoodleRestException {
Vector v=new Vector();
MoodleGroup group=null;
StringBuilder data=new StringBuilder();
String functionCall=MoodleCallRestWebService.isLegacy()?MoodleServices.MOODLE_GROUP_GET_COURSE_GROUPS:MoodleServices.CORE_GROUP_GET_COURSE_GROUPS;
if (MoodleCallRestWebService.getAuth()==null)
throw new MoodleRestGroupException();
else
data.append(MoodleCallRestWebService.getAuth());
data.append("&").append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING)).append("=").append(URLEncoder.encode(functionCall, MoodleServices.ENCODING));
if (id<1) throw new MoodleRestGroupException(); else data.append("&").append(URLEncoder.encode("courseid", MoodleServices.ENCODING)).append("=").append(id);
NodeList elements=MoodleCallRestWebService.call(data.toString());
for (int j=0;j<elements.getLength();j++) {
String content=elements.item(j).getTextContent();
String nodeName=elements.item(j).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.equals("id")) {
if (group==null)
group=new MoodleGroup(Long.parseLong(content));
else {
v.add(group);
group=new MoodleGroup(Long.parseLong(content));
}
}
group.setMoodleGroupField(nodeName, content);
}
if (group!=null)
v.add(group);
MoodleGroup[] groups=new MoodleGroup[v.size()];
for (int i=0;i<v.size();i++) {
groups[i]=(MoodleGroup)v.get(i);
}
v.removeAllElements();
return groups;
} | 8 |
@Override
public void solve(DenseMatrix64F b, DenseMatrix64F x) {
if( b.numCols != x.numCols || b.numRows != numRows || x.numRows != numCols) {
throw new IllegalArgumentException("Unexpected matrix size");
}
int numCols = b.numCols;
double dataB[] = b.data;
double dataX[] = x.data;
double []vv = decomp._getVV();
// for( int j = 0; j < numCols; j++ ) {
// for( int i = 0; i < this.numCols; i++ ) vv[i] = dataB[i*numCols+j];
// decomp._solveVectorInternal(vv);
// for( int i = 0; i < this.numCols; i++ ) dataX[i*numCols+j] = vv[i];
// }
for( int j = 0; j < numCols; j++ ) {
int index = j;
for( int i = 0; i < this.numCols; i++ , index += numCols ) vv[i] = dataB[index];
decomp._solveVectorInternal(vv);
index = j;
for( int i = 0; i < this.numCols; i++ , index += numCols ) dataX[index] = vv[i];
}
if( doImprove ) {
improveSol(b,x);
}
} | 7 |
public boolean isBreakpointSet() {
return breakpointSet;
} | 0 |
public ByteVector putByte(final int b) {
int length = this.length;
if (length + 1 > data.length) {
enlarge(1);
}
data[length++] = (byte) b;
this.length = length;
return this;
} | 1 |
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
} | 0 |
public void setHorasteoricas(Tempo horasteoricas) {
this.horasteoricassemanais = horasteoricas;
} | 0 |
void Expr() {
printer.startProduction("Expr");
if (StartOf(3)) {
BaseExpr();
if (StartOf(4)) {
op();
BaseExpr();
this.generator.commandOp(this.currentContext.previousOp);
printer.endProduction("Expr");
} else if (la.kind == 6 || la.kind == 10) {
printer.endProduction("Expr");
} else SynErr(34);
} else if (la.kind == 17) {
Get();
printer.print("!");
this.expected = BOOLEAN;
// @SLX: Negation here
BaseExpr();
if (this.lastType != BOOLEAN) {
// Error, negating non-boolean
this.SemErr("trying to negate non-boolean");
}
else {
this.generator.commandNegation();
}
} else SynErr(35);
} | 6 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if(((msg.targetMinor()==CMMsg.TYP_GET)||(msg.targetMinor()==CMMsg.TYP_PUSH)||(msg.targetMinor()==CMMsg.TYP_PULL))
&&(msg.target() instanceof Item)
&&(juggles.contains(msg.target()))
&&(affected instanceof MOB)
&&(CMLib.dice().rollPercentage()<90)
&&(msg.source()!=affected))
{
msg.source().tell(msg.source(),msg.target(),null,L("<T-NAME> is moving too fast for you to grab it."));
return false;
}
return true;
} | 9 |
public static String translate(String str) {
if(!turnedon)
return str;
String res = "";
URL url = url(str);
if(url == null)
return str;
try {
final HttpURLConnection uc = (HttpURLConnection) url
.openConnection();
uc.setRequestMethod("GET");
uc.setDoOutput(true);
try {
String result;
try {
result = inputStreamToString(uc.getInputStream());
} catch (Exception e) {
return str;
}
JSONObject o = new JSONObject(result);
res = o.getJSONObject("data").getJSONArray("translations").getJSONObject(0).getString("translatedText");
str = res;
res = o.getJSONObject("data").getJSONArray("translations").getJSONObject(0).getString("detectedSourceLanguage");
res = "[" + res + "] " + str;
} catch (JSONException e) {
return str;
} finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
uc.getInputStream().close();
if (uc.getErrorStream() != null) {
uc.getErrorStream().close();
}
}
} catch (IOException e) {
return str;
}
return res;
} | 6 |
public static List<Field> inVars(Class<?> comp) {
List<Field> f = new ArrayList<Field>();
for (Field field : comp.getFields()) {
In in = field.getAnnotation(In.class);
if (in != null) {
Role r = field.getAnnotation(Role.class);
if (r != null && Annotations.plays(r, Role.PARAMETER)) {
continue;
}
f.add(field);
}
}
return f;
} | 5 |
public void add(int[] bowl) {
assert(nkindfruits == bowl.length);
if (nfruits == 0)
nfruits = sum(bowl);
assert(nfruits == sum(bowl));
nround++;
history.add(bowl);
scoreHistory.add(dot(bowl, pref));
assert(nround == history.size());
} | 1 |
public boolean isOptOut() {
synchronized(optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} | 4 |
static public boolean isWrapperClass (Class type) {
return type == Integer.class || type == Float.class || type == Boolean.class || type == Long.class || type == Byte.class
|| type == Character.class || type == Short.class || type == Double.class;
} | 7 |
@Override
public FREObject call(FREContext c, final FREObject[] args) {
final InAppPurchaseExtensionContext context = (InAppPurchaseExtensionContext) c;
context.executeWithService(new Runnable() {
@Override
public void run() {
InAppPurchaseExtension.logToAS("Getting products from the native store ...");
// The local variables have to be final, so it can be used in the async task.
final Activity activity = context.getActivity();
final ArrayList<String> productsIds = FREArrayToArrayList((FREArray) args[0]);
final IInAppBillingService iapService = context.getInAppBillingService();
InAppPurchaseExtension.logToAS("Executing in background ... Activity : " + activity + " (activity package name : " + activity.getPackageName() + ") ; Service : " + iapService);
// The getSkuDetails method is synchronous, so it has to be executed in an asynchronous task to avoid blocking the main thread.
(new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Converts the given data to a bundle of products IDs.
Bundle products = new Bundle();
products.putStringArrayList(ITEM_ID_LIST, productsIds);
InAppPurchaseExtension.logToAS("Requesting the store for the products " + productsIds.toString());
// Retrieves the products details.
Bundle skuDetails = null;
try {
skuDetails = iapService.getSkuDetails(InAppPurchaseExtension.API_VERSION, activity.getPackageName(), "inapp", products);
}
catch(Exception e) {
InAppPurchaseExtension.logToAS("Error while retrieving the products details : " + e.toString());
return null;
}
if(skuDetails == null) {
InAppPurchaseExtension.logToAS("Error while retrieving the products details : The returned products bundle is null!");
return null;
}
InAppPurchaseExtension.logToAS("Processing the received products bundle from the store ...");
// Parsing the received JSON if the response code is success.
int responseCode = skuDetails.getInt(RESPONSE_CODE);
InAppPurchaseExtension.logToAS("Response code : " + ERRORS_MESSAGES.get(responseCode));
ArrayList<String> detailsJson;
String finalJSON = null;
if(responseCode == 0) {
detailsJson = skuDetails.getStringArrayList(DETAILS_LIST);
if(detailsJson == null || detailsJson.size() == 0) {
InAppPurchaseExtension.logToAS("No products details retrieved!");
if(productsIds.size() > 0)
dispatchInvalidProducts(productsIds, context);
return null;
}
int i, length = detailsJson.size();
ArrayList<JSONObject> details = new ArrayList<JSONObject>();
JSONObject currentObject;
JSONObject currentJsonObject;
// Number formatter used to format the localized price returned by Google to a normal double.
NumberFormat format = NumberFormat.getInstance();
format.setMinimumFractionDigits(2);
Number number;
for(i = 0 ; i < length ; i++) {
try {
currentJsonObject = new JSONObject(detailsJson.get(i));
currentObject = new JSONObject();
currentObject.put("id", currentJsonObject.get("productId"));
currentObject.put("title", currentJsonObject.get("title"));
currentObject.put("description", currentJsonObject.get("description"));
// Formats the price to an amount rounded to 2 decimals.
number = format.parse(currentJsonObject.get("price_amount_micros").toString());
currentObject.put("price", format.parse(String.format("%.2f", number.doubleValue() / 1000000.0)).doubleValue());
currentObject.put("priceCurrencyCode", currentJsonObject.get("price_currency_code"));
currentObject.put("priceCurrencySymbol", currentJsonObject.get("price").toString().replaceAll("[0-9.,\\s]", ""));
// The fully formated price to display in your app, with the currency symbol.
currentObject.put("displayPrice", currentJsonObject.get("price").toString());
details.add(currentObject);
// removes the current product ID from the ids received as parameters.
productsIds.remove(currentObject.get("id"));
}
catch (Exception e) {
InAppPurchaseExtension.logToAS("Error while parsing the products JSON! " + e.toString());
return null;
}
}
InAppPurchaseExtension.logToAS("Processed.");
InAppPurchaseExtension.logToAS("Found " + details.size() + " products.");
JSONArray data = new JSONArray(details);
finalJSON = data.toString();
InAppPurchaseExtension.logToAS("Returning " + finalJSON + " to the app.");
// Check if there is IDs left in productIds. If this is the case, there were invalid products in the parameters.
if(productsIds.size() > 0) {
dispatchInvalidProducts(productsIds, context);
}
}
else {
InAppPurchaseExtension.logToAS("Error while loading the products : " + ERRORS_MESSAGES.get(responseCode));
return null;
}
context.dispatchStatusEventAsync(InAppPurchaseMessages.PRODUCTS_LOADED, finalJSON);
return null;
}
}).execute();
}
});
return null;
} | 9 |
@Override
public void mouseClick(double x, double y) {
_tempToClick.clear();
for (MenuButton but : _buttons) {
if (but.isMouseWithin(x, y)) {
_tempToClick.add(but);
}
}
if (_tempToClick.size()==0)
return;
_tempToClick.get(_tempToClick.size()-1).actionOnClick();
} | 3 |
private static Move BackwardLeftForWhite(int r, int c, Board board){
Move backwardLeft = null;
if( r>=1 && c>=1 &&
board.cell[r-1][c-1] == CellEntry.empty
)
{
backwardLeft = new Move(r,c, r-1, c-1);
}
return backwardLeft;
} | 3 |
private void scanDir(File dir, List<LessFileStatus> lstAddedLfs) {
if (!dir.isDirectory())
throw new BugError("Bad directory: " + dir);
File[] subf = dir.listFiles();
if (subf != null) {
for (File f : subf) {
if (f.isFile())
scanFile(f.getName(), f, lstAddedLfs);
}
}
} | 4 |
private void addNewWormSprites() {
Collection<Worm> worms = getFacade().getWorms(getWorld());
if (worms != null) {
for (Worm worm : worms) {
WormSprite sprite = getWormSprite(worm);
if (sprite == null) {
createWormSprite(worm);
}
}
}
} | 3 |
@Override
public void paintComponent(final Graphics g) {
// Check if we have a running game
super.paintComponent(g);
g.setColor(this.getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (this.model != null) {
// Draw all tiles by going over them x-wise and y-wise.
for (int i = 0; i < this.modelSize.width; i++) {
for (int j = 0; j < this.modelSize.height; j++) {
GameTile tile = this.model.getGameboardState(i, j);
tile.draw(g, i * this.tileSize.width, j
* this.tileSize.height,
this.tileSize);
}
}
} else {
g.setFont(new Font("Sans", Font.BOLD, 24));
g.setColor(Color.BLACK);
final char[] message = "No model chosen.".toCharArray();
g.drawChars(message, 0, message.length, 50, 50);
}
} | 3 |
public static AIMerger getInstance() {
return instance;
} | 0 |
private void updateNPCs(Buffer stream, int amount) {
actorsToUpdateCount = 0;
playersObservedCount = 0;
updateNPCMovement(stream);
updateNPCList(amount, stream);
updateNPCBlock(stream);
for (int k = 0; k < actorsToUpdateCount; k++) {
int npcId = actorsToUpdateIds[k];
if (npcs[npcId].lastUpdateTick != tick) {
npcs[npcId].npcDefinition = null;
npcs[npcId] = null;
}
}
if (stream.position != amount) {
signlink.reporterror(enteredUsername
+ " size mismatch in getnpcpos - pos:"
+ stream.position + " psize:" + amount);
throw new RuntimeException("eek");
}
for (int n = 0; n < npcCount; n++)
if (npcs[npcIds[n]] == null) {
signlink.reporterror(enteredUsername
+ " null entry in npc list - pos:" + n + " size:"
+ npcCount);
throw new RuntimeException("eek");
}
} | 5 |
@EventHandler
public void MagmaCubeHunger(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getMagmaCubeConfig().getDouble("MagmaCube.Hunger.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if (plugin.getMagmaCubeConfig().getBoolean("MagmaCube.Hunger.Enabled", true) && damager instanceof MagmaCube && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getMagmaCubeConfig().getInt("MagmaCube.Hunger.Time"), plugin.getMagmaCubeConfig().getInt("MagmaCube.Hunger.Power")));
}
} | 6 |
public void dribbleToGoal(ObjBall ball) {
if(stayInBounds()) {
ObjGoal goal = mem.getOppGoal();
if((goal != null) && (mem.getPosition().x < 35.0)) {
kickToPoint(ball, new Polar(5.0, (goal.getDirection() - ball.getDirection())));
}
else if((goal != null) && (mem.getPosition().x >= 35.0)) {
System.out.println("Ready to shoot");
kickToGoal(ball);
}
else if(goal == null) {
try {
rc.kick(5.0, mem.getNullGoalAngle());
} catch (UnknownHostException e) {
System.out.println("Error in Action.dribbleToGoal() at null goal turn");
e.printStackTrace();
}
}
}
} | 7 |
public ShipChassis readChassis(InputStream stream) throws IOException, JAXBException {
log.trace("Reading ship chassis XML");
// Need to clean invalid XML and comments before JAXB parsing
BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF8"));
StringBuilder sb = new StringBuilder();
String line;
boolean comment = false;
while( (line = in.readLine()) != null ) {
line = line.replaceAll("<!--.*-->", "");
line = line.replaceAll("<(/?)gib[0-9]*>", "<$1gib>");
// Remove multiline comments
if (comment && line.contains("-->"))
comment = false;
else if (line.contains("<!--"))
comment = true;
else if (!comment)
sb.append(line).append("\n");
}
in.close();
if ( sb.substring(0, BOM_UTF8.length()).equals(BOM_UTF8) )
sb.replace(0, BOM_UTF8.length(), "");
// XML has multiple root nodes so need to wrap.
sb.insert(0, "<shipChassis>\n");
sb.append("</shipChassis>\n");
// Parse cleaned XML
ShipChassis sch = (ShipChassis)unmarshalFromSequence( ShipChassis.class, sb.toString() );
return sch;
} | 6 |
public JSONArray toJSONArray(JSONArray names) throws JSONException {
if (names == null || names.length() == 0) {
return null;
}
JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
}
return ja;
} | 3 |
public float getImporte() {
return importe;
} | 0 |
protected CityHall() {} | 0 |
@Override
public boolean verifier() throws SemantiqueException {
super.verifier();
if(gauche.isBoolean()){
setBoolean();
if(!droite.isBoolean()) GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression droite arithmetique, booleenne attendue pour le ET ligne:"+line+" colonne:"+col));
}else
if(droite.isBoolean()) GestionnaireSemantique.getInstance().add(new SemantiqueException("Expression droite booléenne, arithmetique attendue pour la multiplication ligne:"+line+" colonne:"+col));
return true;
} | 3 |
public void solicitudRealizada(final int idSolicitud){
logger.info("Id Solicitud " + idSolicitud);
getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query query = session.createQuery("update PosSolicitud set solEstado = 'A' where idSolicitud = ?");
query.setLong(0, idSolicitud);
query.executeUpdate();
return null; //To change body of implemented methods use File | Settings | File Templates.
}
});
getHibernateTemplate().flush();
} | 0 |
public List<PwdItem> GetItems() {
List<PwdItem> pwdlist=new ArrayList<PwdItem>();
if (this.connection == null) {
return null;
}
try {
Statement stmt = null;
stmt = this.connection.createStatement();
int count = 0;
//find the max id
ResultSet rs = stmt.executeQuery("SELECT * FROM PASSWD;");
while (rs.next()) {
PwdItem item = new PwdItem();
item.setId(rs.getInt("ID"));
item.setDomain(rs.getString("DOMAIN"));
item.setUsername(rs.getString("USERNAME"));
item.setPassword(rs.getString("PASSWORD"));
item.setComment(rs.getString("COMMENT"));
pwdlist.add(item);
count++;
}
rs.close();
stmt.close();
//no item found
if (count == 0) {
return null;
}
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return pwdlist;
} | 4 |
public boolean checkEntrance(Vehicle vehicle)
{
for (int i = 0; i < vehicleCount(); i++)
{
if (m_vehicles.get(i).getState() == Vehicle.State.INSIDE)
{
float theta = m_vehicles.get(i).getTheta();
float dist = getRadius() * (theta - vehicle.getTheta());
float dist2 = getRadius() * (float) Math.abs(theta - vehicle.getTheta() + 2 * Math.PI);
if ((dist - Vehicle.LENGTH <= 7.0f && dist + Vehicle.LENGTH >= -0.0f)
|| (dist2 - Vehicle.LENGTH <= 7.0f && dist2 + Vehicle.LENGTH >= -0.0f)) return true;
}
}
return false;
}// checkEntrance | 6 |
public char firstNonRepeating(String s) {
char return_char = 0;
if (s == null || s.isEmpty()) {
return 0;
}
int[] arr = new int[256];
for (char i : s.toCharArray()) {
int index = (int) i;
arr[index]++;
}
for (char i : s.toCharArray()) {
int index = (int) i;
if (arr[index] == 1) {
return_char = Character.toChars(index)[0];
break;
}
}
return return_char;
} | 5 |
public CheckResultMessage checkTF04(int day) {
int r1 = get(20, 2);
int c1 = get(21, 2);
int r2 = get(23, 2);
int c2 = get(24, 2);
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
if (0 != getValue(r1 + 3, c1 + day, 2).abs().compareTo(
getValue(r2 + 3, c2 + day, 2).abs())) {
return error("支付机构单个账户报表<" + fileName + ">非活期转活期 :" + day
+ "日错误");
}
in.close();
} catch (Exception e) {
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
if (0 != getValue(r1 + 3, c1 + day, 2).abs().compareTo(
getValue(r2 + 3, c2 + day, 2).abs())) {
return error("支付机构单个账户报表<" + fileName + ">非活期转活期 :" + day
+ "日错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构单个账户报表<" + fileName + ">非活期转活期 :" + day + "日正确");
} | 5 |
public static UnitType getTier(int tier, CastleType type)
{
for (UnitType i: UnitType.values()) {
System.out.println ("unit "+i.level+", "+i.castle);
if (i.level == tier && i.castle == type) {
return i;
}
}
return null;
} | 3 |
Welcome() throws PropertyVetoException {
setResizable(false);
setTitle("BOLSA DE EMPLEOS REP.DOM");
setIconImage(Toolkit.getDefaultToolkit().getImage(Welcome.class.getResource("/InterfazGrafica/Images/Encontrar-Trabajo.jpg")));
setForeground(new Color(0, 0, 0));
setFont(new Font("Tahoma", Font.BOLD, 15));
setBackground(new Color(176, 224, 230));
setBounds(100, 100, 450, 300);
dim = super.getToolkit().getScreenSize();
super.setSize(dim);
contentPane = new JPanel();
contentPane.setBackground(new Color(248, 248, 255));
contentPane.setForeground(new Color(255, 255, 255));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(174, 181, 46, 14);
contentPane.add(lblNewLabel);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(new Color(176, 224, 230));
menuBar.setBounds(0, 0, 1360, 90);
contentPane.add(menuBar);
JMenu menu = new JMenu("");
menuBar.add(menu);
JMenu menu_1 = new JMenu(" ");
menu_1.setEnabled(false);
menuBar.add(menu_1);
JMenu mnInicio = new JMenu(" INICIO ");
mnInicio.setFocusTraversalKeysEnabled(false);
mnInicio.setFocusPainted(true);
mnInicio.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1416514885_home.png")));
mnInicio.setFont(new Font("Tahoma", Font.BOLD, 12));
menuBar.add(mnInicio);
JMenu mnNuevo = new JMenu("Nuevo Cliente");
mnNuevo.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Add32.png")));
mnInicio.add(mnNuevo);
JMenuItem mntmSolicitante = new JMenuItem("Solicitante");
mntmSolicitante.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
personRegister = new PersonRegister();
personRegister.setVisible(true);
}
});
mntmSolicitante.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile32.png")));
mnNuevo.add(mntmSolicitante);
JMenuItem mntmEmpresa_3 = new JMenuItem("Empresa");
mntmEmpresa_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
companyRegister = new CompanyRegister();
companyRegister.setVisible(true);
}
});
mntmEmpresa_3.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Company32.png")));
mnNuevo.add(mntmEmpresa_3);
JMenu mnNuevaSolicitud_1 = new JMenu("Nueva Solicitud");
mnNuevaSolicitud_1.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417568890_new-file.png")));
mnInicio.add(mnNuevaSolicitud_1);
JMenuItem mntmNewMenuItem = new JMenuItem("Solicitante");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
personApplication = new PersonApplicationVisual();
personApplication.setVisible(true);
}
});
mntmNewMenuItem.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile32.png")));
mnNuevaSolicitud_1.add(mntmNewMenuItem);
JMenuItem mntmEmpresa_4 = new JMenuItem("Empresa");
mntmEmpresa_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
companyApplicationVisual = new CompanyApplicationVisual();
companyApplicationVisual.setVisible(true);
}
});
mntmEmpresa_4.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Company32.png")));
mnNuevaSolicitud_1.add(mntmEmpresa_4);
JMenu mnBuscar = new JMenu("Buscar");
mnBuscar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Search32.png")));
mnInicio.add(mnBuscar);
JMenuItem mntmSolicitante_1 = new JMenuItem("Solicitante");
mntmSolicitante_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
searchPerson = new SearchPerson();
searchPerson.setVisible(true);
}
});
mntmSolicitante_1.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile32.png")));
mnBuscar.add(mntmSolicitante_1);
JMenuItem mntmEmpresa_5 = new JMenuItem("Empresa");
mntmEmpresa_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
searchCompany = new SearchCompany();
searchCompany.setVisible(true);
}
});
mntmEmpresa_5.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Company32.png")));
mnBuscar.add(mntmEmpresa_5);
JMenuItem mntmAyuda = new JMenuItem("Ayuda");
mntmAyuda.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
help = new Help();
help.setVisible(true);
}
});
mntmAyuda.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Ayuda32.png")));
mnInicio.add(mntmAyuda);
JMenuItem mntmCerrar = new JMenuItem("Cerrar");
mntmCerrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
closeProgram = new CloseProgram();
closeProgram.setVisible(true);
}
});
mntmCerrar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Delete32.png")));
mnInicio.add(mntmCerrar);
JMenu mnRegistrar = new JMenu("REGISTRAR ");
menuBar.add(mnRegistrar);
mnRegistrar.setHideActionText(true);
mnRegistrar.setFont(new Font("Tahoma", Font.BOLD, 12));
mnRegistrar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Modify.png")));
JMenuItem menuItemSolicitante = new JMenuItem("Solicitante");
menuItemSolicitante.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
personRegister = new PersonRegister();
personRegister.setVisible(true);
}
});
menuItemSolicitante.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile.png")));
mnRegistrar.add(menuItemSolicitante);
JMenuItem mntmEmpresa = new JMenuItem("Empresa");
mntmEmpresa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
companyRegister = new CompanyRegister();
companyRegister.setVisible(true);
}
});
mntmEmpresa.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1416396195_Company.png")));
mnRegistrar.add(mntmEmpresa);
JMenu mnNuevaSolicitud = new JMenu("Solicitud");
mnNuevaSolicitud.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Info.png")));
mnRegistrar.add(mnNuevaSolicitud);
JMenuItem mntmEmpleado = new JMenuItem("Solicitante");
mntmEmpleado.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile32.png")));
mntmEmpleado.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
personApplication = new PersonApplicationVisual();
personApplication.setVisible(true);
}
});
mnNuevaSolicitud.add(mntmEmpleado);
JMenuItem mntmEmpresa_2 = new JMenuItem("Empresa");
mntmEmpresa_2.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Company32.png")));
mntmEmpresa_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
companyApplicationVisual = new CompanyApplicationVisual();
companyApplicationVisual.setVisible(true);
}
});
mnNuevaSolicitud.add(mntmEmpresa_2);
JMenu mnBaseDeDatos = new JMenu("BASE DE DATOS ");
menuBar.add(mnBaseDeDatos);
mnBaseDeDatos.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1416395841_archive.png")));
mnBaseDeDatos.setFont(new Font("Tahoma", Font.BOLD, 12));
JMenuItem mntmAreasDisponibles = new JMenuItem("Areas Disponibles");
mntmAreasDisponibles.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
disponibleAreas = new DisponibleAreas();
disponibleAreas.setVisible(true);
}
});
mntmAreasDisponibles.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/areas.png")));
mnBaseDeDatos.add(mntmAreasDisponibles);
JMenu mnRegistros = new JMenu("Registros ");
mnRegistros.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Modify.png")));
mnBaseDeDatos.add(mnRegistros);
JMenuItem mntmNewMenuItemSolicitantes = new JMenuItem("Solicitantes");
mntmNewMenuItemSolicitantes.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828816_testimonials.png")));
mntmNewMenuItemSolicitantes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seePersons = new SeePersons();
seePersons.setVisible(true);
}
});
mnRegistros.add(mntmNewMenuItemSolicitantes);
JMenuItem mntmEmpresas_2 = new JMenuItem("Empresas");
mntmEmpresas_2.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828832_companies.png")));
mntmEmpresas_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seeCompanies = new SeeCompanies();
seeCompanies.setVisible(true);
}
});
mnRegistros.add(mntmEmpresas_2);
JMenu mnSolicitudes = new JMenu("Solicitudes");
mnSolicitudes.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Info.png")));
mnBaseDeDatos.add(mnSolicitudes);
JMenuItem mntmEmpleados = new JMenuItem("Solicitantes");
mntmEmpleados.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828816_testimonials.png")));
mntmEmpleados.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seePersonApplication = new SeePersonApplication();
seePersonApplication.setVisible(true);
}
});
mnSolicitudes.add(mntmEmpleados);
JMenuItem mntmEmpresas2 = new JMenuItem("Empresas");
mntmEmpresas2.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828832_companies.png")));
mntmEmpresas2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seeCompanyApplication = new SeeCompanyApplication();
seeCompanyApplication.setVisible(true);
}
});
mnSolicitudes.add(mntmEmpresas2);
JMenu mnReportes = new JMenu("REPORTES ");
menuBar.add(mnReportes);
mnReportes.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Bar Chart.png")));
mnReportes.setFont(new Font("Tahoma", Font.BOLD, 12));
JMenu mnPendientes = new JMenu("Solicitudes Pendientes");
mnPendientes.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/pendientes.png")));
mnReportes.add(mnPendientes);
JMenuItem mntmSolicitantes_1 = new JMenuItem("Solicitantes");
mntmSolicitantes_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
personPendingApplication = new PersonPendingApplication();
personPendingApplication.setVisible(true);
}
});
mntmSolicitantes_1.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828816_testimonials.png")));
mnPendientes.add(mntmSolicitantes_1);
JMenuItem mntmEmpresas_1 = new JMenuItem("Empresas");
mntmEmpresas_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
companyPendingApplication = new CompanyPendingApplication();
companyPendingApplication.setVisible(true);
}
});
mntmEmpresas_1.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828832_companies.png")));
mnPendientes.add(mntmEmpresas_1);
JMenu mnSatisfechos = new JMenu("Solicitudes Satisfechos");
mnSatisfechos.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/cheking.png")));
mnReportes.add(mnSatisfechos);
JMenuItem mntmSolicitantes = new JMenuItem("Solicitantes");
mntmSolicitantes.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828816_testimonials.png")));
mntmSolicitantes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seeSatisfiedPerson = new SeeSatisfiedPerson();
seeSatisfiedPerson.setVisible(true);
}
});
mnSatisfechos.add(mntmSolicitantes);
JMenuItem mntmEmpresas = new JMenuItem("Empresas");
mntmEmpresas.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1417828832_companies.png")));
mntmEmpresas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
seeSatisfiedCompany = new SeeSatisfiedCompany();
seeSatisfiedCompany.setVisible(true);
}
});
mnSatisfechos.add(mntmEmpresas);
JMenu mnConsultas = new JMenu("CONSULTAR ");
mnConsultas.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Search48.png")));
mnConsultas.setFont(new Font("Tahoma", Font.BOLD, 12));
menuBar.add(mnConsultas);
JMenuItem mntmConsultaEmpresa = new JMenuItem("Empresa");
mntmConsultaEmpresa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchCompany = new SearchCompany();
searchCompany.setVisible(true);
}
});
mntmConsultaEmpresa.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1416396195_Company.png")));
mnConsultas.add(mntmConsultaEmpresa);
JMenuItem mntmConsultaSolicitante = new JMenuItem("Solicitante");
mntmConsultaSolicitante.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchPerson = new SearchPerson();
searchPerson.setVisible(true);
}
});
mntmConsultaSolicitante.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Profile.png")));
mnConsultas.add(mntmConsultaSolicitante);
JMenu mnAsignar = new JMenu("ASIGNAR ");
mnAsignar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
personAssignation = new PersonAssignation();
personAssignation.setVisible(true);
}
});
mnAsignar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/si.png")));
mnAsignar.setFont(new Font("Tahoma", Font.BOLD, 12));
menuBar.add(mnAsignar);
JMenu mnAyuda = new JMenu("AYUDA ");
mnAyuda.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
mnAyuda.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
help = new Help();
help.setVisible(true);
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
mnAsignar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/si.png")));
mnAsignar.setFont(new Font("Tahoma", Font.BOLD, 12));
menuBar.add(mnAsignar);
menuBar.add(mnAyuda);
mnAyuda.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/1416396005_FAQ.png")));
mnAyuda.setFont(new Font("Tahoma", Font.BOLD, 12));
JButton btnCerrar = new JButton("CERRAR ");
btnCerrar.setBounds(new Rectangle(0, 0, 20, 10));
btnCerrar.setBorder(new EmptyBorder(0, 0, 0, 0));
btnCerrar.setAutoscrolls(true);
btnCerrar.setAlignmentX(Component.CENTER_ALIGNMENT);
btnCerrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
closeProgram = new CloseProgram();
closeProgram.setVisible(true);
}
});
btnCerrar.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/Delete.png")));
btnCerrar.setBackground(new Color(176, 224, 230));
btnCerrar.setFont(new Font("Tahoma", Font.BOLD, 12));
btnCerrar.setForeground(SystemColor.inactiveCaptionText);
menuBar.add(btnCerrar);
JLabel lblBolsaDeEmpleos_1 = new JLabel("BOLSA DE EMPLEOS ");
lblBolsaDeEmpleos_1.setForeground(Color.BLUE);
lblBolsaDeEmpleos_1.setFont(new Font("Tahoma", Font.BOLD, 40));
lblBolsaDeEmpleos_1.setHorizontalAlignment(SwingConstants.CENTER);
lblBolsaDeEmpleos_1.setBounds(270, 116, 845, 49);
contentPane.add(lblBolsaDeEmpleos_1);
JLabel lblSolucionesEmpresarialesY = new JLabel("SOLUCIONES EMPRESARIALES Y LABORALES ");
lblSolucionesEmpresarialesY.setForeground(Color.BLUE);
lblSolucionesEmpresarialesY.setHorizontalAlignment(SwingConstants.CENTER);
lblSolucionesEmpresarialesY.setFont(new Font("Tahoma", Font.BOLD, 35));
lblSolucionesEmpresarialesY.setBackground(new Color(248, 248, 255));
lblSolucionesEmpresarialesY.setBounds(243, 658, 873, 71);
contentPane.add(lblSolucionesEmpresarialesY);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(243, 159, 834, 550);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setIcon(new ImageIcon(Welcome.class.getResource("/InterfazGrafica/Images/iconowelcome.png")));
} | 0 |
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out
.println("Please type in your score in percentage (0 to 100).");
float score = s.nextFloat();
s.close();
if (score >= 100) {
System.out.println("Your grade is A+");
} else if (score >= 90) {
System.out.println("Your grade is A");
} else if (score >= 80) {
System.out.println("Your grade is B");
} else if (score >= 70) {
System.out.println("Your grade is C");
} else if (score >= 60) {
System.out.println("Your grade is D");
} else if (score < 60) {
System.out.println("Your grade is F");
}
} | 6 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost, msg);
if ((System.currentTimeMillis() - lastClanCheck) > TimeManager.MILI_HOUR / 2)
{
if ((clanID().length() > 0)
&& (owner() instanceof MOB)
&& (!amDestroyed()))
{
if ((CMLib.clans().getClan(clanID()) == null)
|| ((getClanItemType() != ClanItem.ClanItemType.PROPAGANDA)
&& (((MOB) owner()).getClanRole(clanID()) == null)))
{
final Room R = CMLib.map().roomLocation(this);
setRightfulOwner(null);
unWear();
removeFromOwnerContainer();
if (owner() != R)
R.moveItemTo(this, ItemPossessor.Expire.Player_Drop);
if (R != null)
R.showHappens(CMMsg.MSG_OK_VISUAL, L("@x1 is dropped!", name()));
}
}
lastClanCheck = System.currentTimeMillis();
}
} | 9 |
public String toString() {
Stack<String> stack = new Stack<>();
StringBuilder full = new StringBuilder();
Set<Integer> powers = terms.keySet();
for (int power : powers) {
StringBuilder sb = new StringBuilder();
double coefficient = terms.get(power);
sb.append("+");
if (Math.abs(coefficient) != 1) {
sb.append(coefficient);
}
if (power == 1) {
sb.append("x");
} else if (power > 1) {
sb.append("x^" + power);
}
stack.push(sb.toString());
}
while (!(stack.empty())) {
full.append(stack.pop());
}
return full.toString().replace("+-", "-");
} | 5 |
public void showTable() {
waitlb1.setVisible(true);
l.remove(0);
if (!l.isEmpty()) {
content = new String[l.size()][l.get(0).split(";").length];
for (int i = 0; i < l.size(); i++) {
content[i] = l.get(i).split(";");
}
for (int i = 0; i < l.size(); i++) {
for (int j = 0; j < content[i].length; j++) {
if (content[i][j].equals("null")) {
content[i][j] = "";
}
}
}
dtm.setDataVector(content, head);
if (!pathFieldf.getText().equals("")) {
finishBtn.setEnabled(true);
} else {
finishBtn.setEnabled(false);
}
} else {
finishBtn.setEnabled(false);
}
waitlb1.setVisible(false);
} | 6 |
@Override
public void serialEvent(SerialPortEvent event) {
if(event.isBREAK())
{
if(state!=SerialState.Disconnected)
{
disconnect();
System.out.println(">>Break);"); //$NON-NLS-1$
}
}
if(event.isERR())
{
if(state!=SerialState.Disconnected)
{
disconnect();
System.out.println(">>Error"); //$NON-NLS-1$
}
}
if(serialPort == null)
System.out.println(">>Null"); //$NON-NLS-1$
} | 5 |
public void switchPanel(Screen screen)
{
cardLayout.show(cardPanel, screen.name());
switch (screen)
{ case CAMPUS:
campus.requestFocus();
campus.continueClasses();
break;
case CLASS:
classroom.requestFocus();
break;
case MINISPLASH:
miniSplash.requestFocus();
break;
case BATTLE:
battle.requestFocus();
break;
case FINALBATTLE:
finalBattle.requestFocus();
break;
case WELCOME:
campus.reset();
welcome.requestFocus();
break;
case LIBRARY:
library.requestFocus();
break;
case TRANSCRIPT:
transcript.requestFocus();
break;
case ABOUT:
about.requestFocus();
break;
}
} | 9 |
public Boolean secondUp()
{
if (time.getSeconds() < 59)
{
time.setSeconds(time.getSeconds() + 1);
} else
{
if (time.getMinutes() < 59)
{
time.setSeconds(0);
time.setMinutes(time.getMinutes() + 1);
} else
{
if (time.getHours() < 23)
{
time.setHours(time.getHours() + 1);
time.setMinutes(0);
time.setSeconds(0);
} else
{
return false;
}
}
}
return true;
} | 3 |
public void setOptions(String[] options) throws Exception {
String tmpStr;
String[] tmpOptions;
setChecksTurnedOff(Utils.getFlag("no-checks", options));
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0)
setC(Double.parseDouble(tmpStr));
else
setC(1.0);
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0)
setToleranceParameter(Double.parseDouble(tmpStr));
else
setToleranceParameter(1.0e-3);
tmpStr = Utils.getOption('P', options);
if (tmpStr.length() != 0)
setEpsilon(Double.parseDouble(tmpStr));
else
setEpsilon(1.0e-12);
tmpStr = Utils.getOption('N', options);
if (tmpStr.length() != 0)
setFilterType(new SelectedTag(Integer.parseInt(tmpStr), TAGS_FILTER));
else
setFilterType(new SelectedTag(FILTER_NORMALIZE, TAGS_FILTER));
setBuildLogisticModels(Utils.getFlag('M', options));
tmpStr = Utils.getOption('V', options);
if (tmpStr.length() != 0)
setNumFolds(Integer.parseInt(tmpStr));
else
setNumFolds(-1);
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() != 0)
setRandomSeed(Integer.parseInt(tmpStr));
else
setRandomSeed(1);
tmpStr = Utils.getOption('K', options);
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length != 0) {
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setKernel(Kernel.forName(tmpStr, tmpOptions));
}
super.setOptions(options);
} | 7 |
public boolean insertAt(int index, E element) {
if (indexOK(index)) {
if (index == 0) {
addFirst(element);
} else {
expandArrayCapacityBy(1);
System.arraycopy(array, index, array, index+1, array.length - index - 1);
array[index] = element;
}
return true;
}
return false;
} | 2 |
public static String compileAlgorythm(String commandLine){
BufferedReader bufDone;
BufferedReader bufError;
String stringDone = "";
String stringError = "";
try{
Process compile = Runtime.getRuntime().exec(commandLine);
bufDone = new BufferedReader(new InputStreamReader(compile.getInputStream()));
bufError = new BufferedReader(new InputStreamReader(compile.getErrorStream()));
String lineDone;
while ((lineDone = bufDone.readLine())!=null)
stringDone = stringDone + lineDone + "\n";
bufDone.close();
String lineError;
while ((lineError = bufError.readLine())!=null)
stringError = stringError +lineError + "\n";
bufError.close();
}catch(IOException ex){
JOptionPane.showMessageDialog(frames.getFrameCreateAlgo(),
ex.getMessage() , "Compile error", JOptionPane.ERROR_MESSAGE);
return null;
}catch(IllegalArgumentException ex){
JOptionPane.showMessageDialog(frames.getFrameCreateAlgo(),
ex.getMessage() , "Compile error", JOptionPane.ERROR_MESSAGE);
return null;
}
if (!stringError.equals(""))
return stringError;
return "Done";
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.