method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
f2d6dacb-382f-4e0f-bba5-d1b4bcbe9f60 | 8 | public int findNearestBondIndex(int x, int y) {
if (modelManager.frame == null)
return -1;
Bond[] bonds = modelManager.frame.bonds;
if (bonds == null)
return -1;
int bondCount = modelManager.frame.bondCount;
if (bondCount <= 0)
return -1;
int xA, yA, zA, xB, yB, zB;
double distSq;
float width;
Atom atom1, atom2;
int zmin = Integer.MAX_VALUE;
int zDepth;
int foundIndex = -1;
for (int i = 0; i < bondCount; i++) {
atom1 = bonds[i].atom1;
atom2 = bonds[i].atom2;
xA = atom1.screenX;
yA = atom1.screenY;
zA = atom1.screenZ;
xB = atom2.screenX;
yB = atom2.screenY;
zB = atom2.screenZ;
distSq = Line2D.ptSegDistSq(xA, yA, xB, yB, x, y);
if (distSq < 0.001) {
zDepth = zA + zB;
if (zDepth < zmin) {
zmin = zDepth;
foundIndex = i;
}
}
else {
width = scaleToScreen((zA + zB) >> 1, bonds[i].mad);
if (distSq < 2 * width) {
zDepth = zA + zB;
if (zDepth < zmin) {
zmin = zDepth;
foundIndex = i;
}
}
}
}
return foundIndex;
} |
1503bf27-52ce-4dca-90ec-d292986dde39 | 0 | public int getEventId() {
return eventId;
} |
2535d539-8561-4c56-8046-bc640941b92d | 0 | public void setCurrentMap(int map){
this.currentMap = map;
} |
c6bd3d6d-099f-49d8-bbb8-f1a5125a2dd9 | 1 | public double getUserBalance(String uid) {
Node userNode = getUserNode(uid);
if (userNode != null) {
NamedNodeMap attr = userNode.getAttributes();
Node nodeAttr = attr.getNamedItem("balance");
return Double.parseDouble(nodeAttr.getTextContent());
} else {
return 0;
}
} |
eba9990d-f90c-4ded-8aa9-2f53bad707f5 | 8 | public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int T = readInt();
while (T-- > 0) {
N = readInt();
int M = readInt();
map = new boolean[N][N];
for (int i = 0; i < M; i++) {
int a = readInt() - 1;
int b = readInt() - 1;
map[a][b] = true;
map[b][a] = true;
}
int start = 0, minDegree = N;
for (int i = 0; i < N; i++) {
int degree = 0;
for (int j = 0; j < N; j++) {
if (map[i][j]) {
degree++;
}
}
if (degree < minDegree) {
minDegree = degree;
start = i;
}
}
colored = new boolean[N];
result = new ArrayList<Integer>();
max = 0;
colored[start] = true;
System.arraycopy(map[start], 0, colored, 0, N);
List<Integer> temp = new ArrayList<Integer>();
recurse(temp);
pw.println(result.size());
for (int i = 0; i < result.size() - 1; i++) {
pw.print((result.get(i) + 1) + " ");
}
try {
pw.println(result.get(result.size() - 1) + 1);
} catch (Exception e) {
pw.println(0);
}
pw.flush();
}
pw.close();
} |
14f036f0-c8a6-49c0-a594-82c58937eaf5 | 4 | public static Pokemon useTMHM(Pokemon selectedPokemon, Item item)
{
if (!hasItem(item))
return selectedPokemon;
if (item.effect1 == Item.Effect.TM || item.effect1 == Item.Effect.HM)
{
selectedPokemon = Mechanics.teachMove(selectedPokemon,item,moveNo);
if (!itemCancel)
decrementItem(item);
else
itemCancel = false;
}
return selectedPokemon;
} |
44ac1e40-64f7-4c5e-84d6-8c25b28290a3 | 8 | public boolean removePop(StructuredBlock last) {
/*
* There are three possibilities:
*
* PUSH method_invocation() POP[sizeof PUSH] to: method_invocation()
*
* With java1.3 due to access$ methods the method_invocation can already
* be a non void store instruction.
*
* PUSH arg1 PUSH arg2 POP2 to: if (arg1 == arg2) empty
*
* PUSH arg1 POP to: if (arg1 != 0) empty
*/
if (last.outer instanceof SequentialBlock
&& last.outer.getSubBlocks()[0] instanceof InstructionBlock) {
if (jump != null && jump.destination == null)
return false;
InstructionBlock prev = (InstructionBlock) last.outer
.getSubBlocks()[0];
Expression instr = prev.getInstruction();
if (instr.getType().stackSize() == count) {
StructuredBlock newBlock;
if (instr instanceof InvokeOperator
|| instr instanceof StoreInstruction) {
Expression newExpr = new PopOperator(instr.getType())
.addOperand(instr);
prev.setInstruction(newExpr);
newBlock = prev;
} else {
Expression newCond = new CompareUnaryOperator(
instr.getType(), Operator.NOTEQUALS_OP)
.addOperand(instr);
IfThenElseBlock newIfThen = new IfThenElseBlock(newCond);
newIfThen.setThenBlock(new EmptyBlock());
newBlock = newIfThen;
}
// We don't move the definitions of the special block, but
// it shouldn't have any.
newBlock.moveDefinitions(last.outer, last);
newBlock.moveJump(jump);
if (this == last) {
newBlock.replace(last.outer);
flowBlock.lastModified = newBlock;
} else {
newBlock.replace(this);
last.replace(last.outer);
}
return true;
}
}
return false;
} |
d6016dcb-5e95-41d2-ae75-af9dc18710ff | 7 | private String readUTF(int index, final int utfLen, final char[] buf) {
int endIndex = index + utfLen;
byte[] b = this.b;
int strLen = 0;
int c;
int st = 0;
char cc = 0;
while (index < endIndex) {
c = b[index++];
switch (st) {
case 0:
c = c & 0xFF;
if (c < 0x80) { // 0xxxxxxx
buf[strLen++] = (char) c;
} else if (c < 0xE0 && c > 0xBF) { // 110x xxxx 10xx xxxx
cc = (char) (c & 0x1F);
st = 1;
} else { // 1110 xxxx 10xx xxxx 10xx xxxx
cc = (char) (c & 0x0F);
st = 2;
}
break;
case 1: // byte 2 of 2-byte char or byte 3 of 3-byte char
buf[strLen++] = (char) ((cc << 6) | (c & 0x3F));
st = 0;
break;
case 2: // byte 2 of 3-byte char
cc = (char) ((cc << 6) | (c & 0x3F));
st = 1;
break;
}
}
return new String(buf, 0, strLen);
} |
c750e69b-d2d0-401a-a77d-4765fc089000 | 1 | public void store() {
String content = HTML.formatXML(XML_HEADER + rootElement);
Path path = FileSystems.getDefault().getPath(".", FILENAME);
try {
Files.write(path, content.getBytes(), StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
emitChanges();
} catch (IOException ex) {
ClientLogger.log("Uložení souboru s nastavením se nezdařilo.", ClientLogger.ERROR);
}
} |
d74aa437-6860-4c2a-a3f1-8819e6fba658 | 6 | @Override
public void onEndPage(PdfWriter writer, Document document) {
boolean HeaderEnable = false;
boolean FooterEnable = false;
//Controllo se devo impostare l'header
for (int i = 0; i < this._MyHeaderItemList.size(); i++) {
HeaderEnable = ((HeaderEnable) || (this._MyHeaderItemList.get(i).GetEnable()));
}
//Controllo se devo impostare il footer
for (int i = 0; i < this._MyFooterItemList.size(); i++) {
FooterEnable = ((FooterEnable) || (this._MyFooterItemList.get(i).GetEnable()));
}
if (HeaderEnable) {
SetHeader(writer, document);
}
if (FooterEnable) {
SetFooter(writer, document);
}
} |
fe87b922-979b-4ef5-bd52-fca32f224774 | 5 | public static List<Laureate> filterByLivingYearRange(
List<Laureate> inputList, String startYear, String endYear) {
List<Laureate> outputList = new ArrayList<Laureate>();
int sYear = Integer.getInteger(startYear);
int eYear = Integer.getInteger(endYear);
// parse input, keep what matchs the terms.
for (Laureate Awinner : inputList) {
Integer birthYear = Integer.getInteger(Awinner.getBirth()); // if bad string, returns null.
if (birthYear >= sYear) {
Integer deathYear = Integer.getInteger(Awinner.getBirth());
if ((deathYear == null) || (deathYear <= ((eYear < 0) ? (deathYear + 1) : eYear))) {
outputList.add(Awinner);
}
}
}
return outputList;
} |
339eccc5-6656-494e-97ca-70627c63b7ba | 9 | public int maximalRectangle(char[][] matrix) {
int rows = matrix.length;
if (rows == 0) {
return 0;
}
int cols = matrix[0].length;
//create histogram matrix
int[][] histogram = new int[rows][cols];
int max = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
if (j == 0) {
histogram[i][j] = 1;
} else {
histogram[i][j] = histogram[i][j - 1] + 1;
}
}
}
}
//calculate
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (histogram[i][j] != 0) {
int minI = i;
int minRowWidth = histogram[i][j];
while (minI >= 0) {
minRowWidth = Math.min(minRowWidth, histogram[minI][j]);
int area = minRowWidth * (i - minI + 1);
max = Math.max(max, area);
minI--;
}
}
}
}
return max;
} |
3cf69b1f-21ab-4cbb-9d7b-ac6bf4a0f159 | 3 | @Override
public Status execute(String command) throws MenuException {
switch (command) {
case "E":
difficulty = "E";
break;
case "M":
difficulty = "M";
break;
case "H":
difficulty = "H";
break;
default:
throw new MenuException(NEW_GAME);
}
return PLAYING;
} |
fce14c12-98ee-4e67-93b9-c1b3b62166c9 | 2 | @Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value != null && value.trim().length() > 0) {
Long id = Long.parseLong(value);
return dao.Abrir(id) ;
}
else {
return null;
}
} |
bcff6783-3b43-4d2c-86fd-3d012303bb74 | 9 | public static String getMouseName(int mouseCode) {
switch (mouseCode) {
case MOUSE_MOVE_LEFT: return "Mouse Left";
case MOUSE_MOVE_RIGHT: return "Mouse Right";
case MOUSE_MOVE_UP: return "Mouse Up";
case MOUSE_MOVE_DOWN: return "Mouse Down";
case MOUSE_WHEEL_UP: return "Mouse Wheel Up";
case MOUSE_WHEEL_DOWN: return "Mouse Wheel Down";
case MOUSE_BUTTON_1: return "Mouse Button 1";
case MOUSE_BUTTON_2: return "Mouse Button 2";
case MOUSE_BUTTON_3: return "Mouse Button 3";
default: return "Unknown mouse code " + mouseCode;
}
} |
4d0deb86-6486-4adb-8d01-abb9dacf19bd | 2 | public void setMinCount(int newMin) {
if (headCount < newMin) {
GlobalOptions.err
.println("WARNING: something got wrong with scoped class "
+ clazzAnalyzer.getClazz() + ": " + newMin + ","
+ headCount);
new Throwable().printStackTrace(GlobalOptions.err);
headMinCount = headCount;
} else if (newMin > headMinCount)
headMinCount = newMin;
} |
7b7d2f27-371a-4d80-b1c5-7c3ae4736a1d | 4 | private void placeLives(int count) {
Random rand = new Random();
while (count > 0) {
int pos = rand.nextInt(WIDTH_FIELDS * HEIGHT_FIELDS);
IField field = fieldsMatrix[pos / WIDTH_FIELDS][pos % WIDTH_FIELDS];
if (field.getType().equals("building") && !field.hasLife()
&& !field.hasAmmo()) {
field.setLife(true);
count--;
}
}
} |
bafc1679-0be6-4b29-b963-538f7b576e62 | 6 | public void performAction() {
if (isConnected()) {
boolean first = getOutput()[0].getStatus();
if (this.isTurnedOn() && inputAction==1) {
if (getInput()[0].getStatus()) {getOutput()[0].setStatus(true);}
else {getOutput()[0].setStatus(false);}
}
else {
getOutput()[0].setStatus(false);
}
boolean second = getOutput()[0].getStatus();
if (first!=second && getCircuit()!=null) {
getCircuit().stack.add(getOutput()[0].getOutput());
}
}
} |
832b5547-a5b3-4f6c-aa44-6dcfa6f2e45b | 0 | @Override
public void setValue(Object o) {
// property of this frame must have data type Long
this.playCounter=(Long)this.convertObject(o);
} |
b219011e-d4a2-482a-bf17-1716f074c169 | 8 | final void method3643(Canvas canvas, int i, int i_177_) {
do {
try {
anInt7544++;
if (aCanvas7626 == canvas)
throw new RuntimeException();
if (aHashtable7577.containsKey(canvas))
break;
if (!canvas.isShowing())
throw new RuntimeException();
try {
Class var_class = Class.forName("java.awt.Canvas");
Method method
= var_class.getMethod("setIgnoreRepaint",
new Class[] { Boolean.TYPE });
method.invoke(canvas, new Object[] { Boolean.TRUE });
} catch (Exception exception) {
/* empty */
}
long l = anOpenGL7664.prepareSurface(canvas);
if (l == -1L)
throw new RuntimeException();
aHashtable7577.put(canvas, new Long(l));
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("qo.VF("
+ (canvas != null ? "{...}"
: "null")
+ ',' + i + ',' + i_177_
+ ')'));
}
break;
} while (false);
} |
807a8a32-14e8-41ac-bcd9-6666920abe62 | 2 | public void sendMessage(String message) {
try {
_remoteObj.sendMessage(_username, _receiver, message, ServerInterface.CLIENT);
} catch (RemoteException e) {
if(connect()) {
sendMessage(message);
return;
}
System.out.println("Error while sending message");
}
} |
f737157f-0a40-4005-9f42-409bfd436a02 | 9 | public final void atributos() throws RecognitionException {
try {
// fontes/g/CanecaSemantico.g:228:2: ( ^( ATRIBUTOS_ ( atributo )* ) )
// fontes/g/CanecaSemantico.g:228:4: ^( ATRIBUTOS_ ( atributo )* )
{
match(input,ATRIBUTOS_,FOLLOW_ATRIBUTOS__in_atributos690); if (state.failed) return ;
if ( input.LA(1)==Token.DOWN ) {
match(input, Token.DOWN, null); if (state.failed) return ;
// fontes/g/CanecaSemantico.g:228:17: ( atributo )*
loop8:
do {
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0==ATRIBUTO_) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// fontes/g/CanecaSemantico.g:228:18: atributo
{
pushFollow(FOLLOW_atributo_in_atributos693);
atributo();
state._fsp--;
if (state.failed) return ;
}
break;
default :
break loop8;
}
} while (true);
match(input, Token.UP, null); if (state.failed) return ;
}
}
}
catch (RecognitionException erro) {
throw erro;
}
finally {
// do for sure before leaving
}
return ;
} |
d2e82352-0871-4a88-a45b-2f33018fc685 | 3 | public AnimMissile(float width, float height, float size) {
anim_missile = new Animation();
SpriteSheet sp_fire = null;
try {
sp_fire = new SpriteSheet("resources/blue_fire_ball.png", 81, 46,
new Color(0, 0, 0), 1);
} catch (SlickException e1) {
e1.printStackTrace();
}
int frame_speed = 30;
for (int i = 0; i < 4; i++) {
anim_missile.addFrame(sp_fire.getSprite(i, 0), frame_speed);
}
anim_missile.setPingPong(true);
try {
smoke = ParticleIO.loadConfiguredSystem("resources/smoke.xml");
} catch (IOException e) {
e.printStackTrace();
}
this.size = size;
this.width = width + (size * 40);
this.height = height + (size * 16);
} |
6f3d5a19-244f-4700-9fa8-17b4fce1ea34 | 5 | public <T> T connect(Class<T> serviceInterface) throws IOException {
if (!serviceInterface.isInterface()) {
throw new IllegalArgumentException("serviceInterface must be of interface type!");
}
try {
socket = new Socket(this.serverHost, this.serverPort);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
} catch (IOException e) {
if (inputStream != null) {inputStream.close();}
if (outputStream != null) {outputStream.close();}
if (socket != null) {socket.close();}
throw e;
}
return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{serviceInterface}, this);
} |
1c27342d-7d9e-4474-a95f-e81b1270f6c6 | 4 | protected void fixBlock( Point pos, short[][] block, byte imageNo ) {
for ( int y = 0; y < Block.MAX_Y; y++ ) {
for ( int x = 0; x < Block.MAX_X; x++ ) {
if ( block[ y ][ x ] == 1 ) {
if ( pos.y + y < 0 ) {
continue;
}
_grid[ pos.y + y ][ pos.x + x ] = 1;
_gridColor[ pos.y + y ][ pos.x + x ] = imageNo;
}
}
}
} |
c812d54f-c16e-4c79-830b-db01f59effaf | 6 | public static void GetFieldValue(Persistent obj, Field field, Object nodeValue, String subscript, NodeReference node)
{
Object fieldAsObj = null;
try {
fieldAsObj = field.get(obj);
if (Persistent.class.isAssignableFrom(field.getType()))
{
Persistent fieldAsPersistentObject;
try {
fieldAsPersistentObject = (Persistent) field.getDeclaringClass().newInstance();
fieldAsPersistentObject.Id = Long.parseLong(nodeValue.toString());
fieldAsObj = DataWorker.Instance().LoadObjectById(fieldAsPersistentObject.Id, fieldAsPersistentObject);
field.set(obj, fieldAsObj);
return;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (nodeValue instanceof java.lang.Long)
{
Long nodeLongValue = node.getLong(subscript);
field.setLong(obj, nodeLongValue);
}
else
{
if(field.getType() == java.util.Date.class)
{
Date dateValue = new Date(nodeValue.toString());
field.set(obj, dateValue);
}
else
{
if (nodeValue instanceof java.lang.Integer)
{
field.setInt(obj, node.getInt(subscript));
}
else
{
field.set(obj, nodeValue);
}
}
}
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
6ca7ee0a-1e65-4b6f-b93f-c31edf0702fb | 6 | public void breadthFirstTraversal(){
LinkedQueueClass<Integer> queue =
new LinkedQueueClass<Integer>();
boolean[] visited;
visited = new boolean[gSize];
for (int ind = 0; ind < gSize; ind++)
visited[ind] = false; //initialize the array
//visited to false
for (int index = 0; index < gSize; index++){
if (!visited[index]){
queue.addQueue(index);
visited[index] = true;
while (!queue.isEmptyQueue()){
int u = queue.front();
queue.deleteQueue();
UnorderedLinkedList<Integer>.
LinkedListIterator<Integer> graphIt
= graph[u].iterator();
System.out.print(" " + graphIt.current.name + " ");
while (graphIt.hasNext()){
int w1 = graphIt.next();
if (!visited[w1]){
queue.addQueue(w1);
visited[w1] = true;
}
}
}
}
}
} |
63672dc7-be57-429b-9721-fc1cc57a35aa | 8 | public Problem(DataBean newDB) {
startTime = System.currentTimeMillis();
switch (newDB.alg) {//determine algorithm to run
case 1:
reachedGoal = DepthFirstSearch(newDB.initState);
break;
case 2:
reachedGoal = BreadthFirstSearch(newDB.initState);
break;
case 3:
reachedGoal = UniformCostSearch(newDB.initState);
break;
case 4:
reachedGoal = GreedyBestFirstSearch(newDB.initState);
break;
case 5:
reachedGoal = ASearch(newDB.initState);
break;
}
algTime = System.currentTimeMillis() - startTime;
switch (newDB.outputLev) {//determine output level
case 1:
p.printDistance(reachedGoal);
break;
case 2:
p.printActions(reachedGoal, -1);
break;
case 3:
p.printStateSequence(reachedGoal);
break;
}
totalTime = System.currentTimeMillis() - startTime;
System.out.printf("Time to run algorithm: " + algTime + " milliseconds\n");
System.out.printf("Time to execute Free Cell Solver: " + totalTime + " milliseconds\n");
} |
7e0ca8b5-498e-4cdc-8318-18b06919774f | 7 | public static void main (String args[]) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
int number = Integer.parseInt(line);
line = reader.readLine();
StringTokenizer st = new StringTokenizer(line);
Queue<String>[] queueNumber = new LinkedList[9];
for (int i=0; i<9; i++) {
queueNumber[i] = new LinkedList<String>();
}
Queue<String>[] queueLetter = new LinkedList[4];
for (int i=0; i<4; i++) {
queueLetter[i] = new LinkedList<String>();
}
for (int i=0; i<number; i++) {
String tempPoker = st.nextToken();
queueNumber[tempPoker.charAt(1)-49].add(tempPoker);
}
String strPrint;
for (int i=0; i<9; i++) {
strPrint = "Queue" + (i+1) + ":";
for (String currentPoker : queueNumber[i]) {
queueLetter[currentPoker.charAt(0)-65].add(currentPoker);
strPrint += currentPoker + " ";
}
System.out.println(strPrint);
}
String strOutput = "";
for (int i=0; i<4; i++) {
strPrint = "Queue" + (char)(i+65) + ":";
for (String currentPoker : queueLetter[i]) {
strPrint += currentPoker + " ";
strOutput += currentPoker + " ";
}
System.out.println(strPrint);
}
System.out.println(strOutput);
} |
27024ad7-0dd3-4f2f-a84e-a530106e1c87 | 6 | public static void main(String[] args)
{
CrazyProblem problem = new CrazyProblem();
// 1) Change default settings as needed
Genejector.getSettings().setScoreLimit(2);
Genejector.getSettings().setPopulationSize(500);
// [ListingStart][L1]
Genejector.getSettings().addClass("genejector.examples.CrazyKeyring", false);
Genejector.getSettings().addClass("genejector.examples.CrazySafe", true);
// [ListingEnd][L1]
while (!Genejector.isSolutionFound())
{
// 2) Request a new candidate solution
Genejector.geneject(problem.getClass());
// 3) Test candidate solution
long score = 0;
Genejector.execute(problem);
score += ((problem.getKeyring() != null && problem.getKeyring().getPassword() != null && problem.getKeyring().getPassword().equals("TopSecret")) ? 1 : 0);
score += ((problem.getNuclearLaunchCode() != null && problem.getNuclearLaunchCode().equals(542679985)) ? 1 : 0);
// 4) Send back score
Genejector.submitScore(score);
}
System.out.println("Solution: " + Genejector.getSolutionSourceCode());
} |
dfa9965d-ca8f-4919-8532-7ad1863ed18a | 6 | public void checkCollision(GameObject object) {
// check with other game objects
if (!object.dead) {
for (GameObject otherObject : objects) {
if (!(object instanceof Asteroid && otherObject instanceof EnergyShield)) {
if (object.hittable(otherObject)
&& overlap(object, otherObject)) {
object.hit(otherObject);
otherObject.hit(object);
return;
}
}
}
}
} |
989857cf-9516-4d97-8df1-f25b3512eda7 | 1 | private int score(int[] bowl){
int sum=0;
for(int i=0;i<12;i++){
sum+=pref[i]*bowl[i];
}
return sum;
} |
e454a6a6-4e1f-4fbd-833a-59fce0bfb4cc | 3 | public static void main(String[] args) {
SendPromotionMail sendPromotionMail = new SendPromotionMail();
Facade facade = Facade.getInstance();
Client client1 = new Client("Diego", "111", "diego.so@dce.ufpb.br", 28,
10, 1988);
Client client2 = new Client("Diego2", "222", "diego.sou@dce.ufpb.br",
29, 10, 1988);
Client client3 = new Client("Diego3", "333", "diego.sousa@dce.ufpb.br",
30, 10, 1988);
Product product1 = new Product("PenDriver", 123, 15.00, 100);
Product product2 = new Product("HD", 133, 12.00, 100);
Product product3 = new Product("Memory", 143, 20.00, 100);
Promotion promotion = new Promotion(product1, 10.00, 567);
Promotion promotion2 = new Promotion(product2, 8.00, 568);
Promotion promotion3 = new Promotion(product3, 2.00, 569);
facade.addClient(client1);
facade.addClient(client2);
facade.addClient(client3);
facade.addProduct(product1);
facade.addProduct(product2);
facade.addProduct(product3);
facade.addPromotion(promotion);
facade.addPromotion(promotion2);
facade.addPromotion(promotion3);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
facade.buyProduct(client1, product1, 5);
facade.buyProduct(client2, product2, 10);
facade.buyProduct(client2, product3, 20);
facade.buyProduct(client3, product1, 40);
facade.buyProduct(client3, product2, 80);
facade.buyProduct(client3, product3, 100);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
facade.getExecutor().execute(sendPromotionMail);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
facade.getExecutor().shutdown();
} |
f34b77b7-3194-4612-9575-80b305370358 | 7 | public void keyTyped(KeyEvent keyEvent) {
Iterator<PComponent> it = components.iterator();
while (it.hasNext()) {
PComponent comp = it.next();
if (shouldHandleKeys) {
if (comp.shouldHandleKeys())
comp.keyTyped(keyEvent);
}
else {
if (comp instanceof PFrame) {
for (PComponent component : ((PFrame) comp).getComponents())
if (component.forceKeys())
component.keyTyped(keyEvent);
}
else if (comp.forceKeys())
comp.keyTyped(keyEvent);
}
}
} |
9fee9d6d-c167-452f-8b49-d6addc5373a9 | 1 | private boolean jj_3R_29() {
if (jj_3R_77()) return true;
return false;
} |
f1988c89-a887-439c-b618-f90c0b7b8b1e | 7 | public void updateZoomMap(int zoomCell){
BufferedImage[] images = new BufferedImage[19];
images[0] = determineImage(zoomCell);
for (int k = 0; k < 6; k++){
images[k+1] = determineImage(match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), k).getCellID());
Cell interCell;
switch(k){
case 0:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 0);
images[7] = determineImage(match.getWorld().getNeighborCell(interCell, 5).getCellID());
images[8] = determineImage(match.getWorld().getNeighborCell(interCell, 0).getCellID());
images[9] = determineImage(match.getWorld().getNeighborCell(interCell, 1).getCellID());
break;
case 1:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 1);
images[10] = determineImage(match.getWorld().getNeighborCell(interCell, 1).getCellID());
images[11] = determineImage(match.getWorld().getNeighborCell(interCell, 2).getCellID());
break;
case 2:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 2);
images[12] = determineImage(match.getWorld().getNeighborCell(interCell, 2).getCellID());
images[13] = determineImage(match.getWorld().getNeighborCell(interCell, 3).getCellID());
break;
case 3:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 3);
images[14] = determineImage(match.getWorld().getNeighborCell(interCell, 3).getCellID());
images[15] = determineImage(match.getWorld().getNeighborCell(interCell, 4).getCellID());
break;
case 4:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 4);
images[16] = determineImage(match.getWorld().getNeighborCell(interCell, 4).getCellID());
images[17] = determineImage(match.getWorld().getNeighborCell(interCell, 5).getCellID());
break;
case 5:
interCell = match.getWorld().getNeighborCell(match.getWorld().getCell(zoomCell), 5);
images[18] = determineImage(match.getWorld().getNeighborCell(interCell, 5).getCellID());
break;
}
}
zoomWorld.setImages(images);
zoomWorld.repaint();
} |
2eaaa352-f5fd-4e54-a098-9f591cff0365 | 1 | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
Crossfire window = new Crossfire();
window.frmCrossfire.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
ab4452da-1884-4a31-9a70-c45dd7d86182 | 3 | @Override
public void update(GameContainer container, int delta) throws SlickException
{
Input input = container.getInput();
player1.move(input, walls, delta);
if (input.isKeyDown(Input.KEY_ENTER))
{
SendText();
}
send(player1.getUpdate());
for(int i = 0; i < OtherPlayers.size(); i++){
PlayerUpdate player2 = ((PlayerUpdate)OtherPlayers.get(i));
if(player2.Sprite != null) {
player2.Sprite.update(delta);
}
}
} |
35c1ca97-f0d4-42ed-99b4-3d48b1a165c6 | 5 | public String getLastSheetName()
{
String sheetname = this.sheetname; // 20100217 KSC: default to 1st sheet
if( parent_rec != null )
{
WorkBook wb = parent_rec.getWorkBook();
if( (wb != null) && (wb.getExternSheet() != null) )
{
String[] sheets = wb.getExternSheet().getBoundSheetNames( ixti );
if( (sheets != null) && (sheets.length > 0) )
{
sheetname = sheets[sheets.length - 1];
}
}
}
return sheetname;
} |
4f27990f-e1cb-4e62-808e-946e7e459c09 | 5 | private void collectNumbers()
{
mNumbers.clear();
mNumberId = 0;
TileValue value;
final int size = mField.getWidth() * mField.getHeight();
for (int tile = 0; tile < size; tile++ )
if (mField.getMaskValue(tile).isOpen())
{
value = mField.getTileValue(tile);
if ( !value.isBomb() && !value.isEmpty() && isBorder(tile)) addNumber(tile);
}
} |
59af061c-da70-4e3e-83b6-f35377f26b57 | 1 | public Mysql(){
/*
* kanei thn sundesh me thn vash sthn dimiourgia tou antikeimenou
*/
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/askisi9?useUnicode=true&characterEncoding=UTF-8&";
conn = DriverManager
.getConnection(url
+ "user="+user+"&password="+pass);
stmt=conn.createStatement();
stmt.execute("set names utf8");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Apotixia Epikoinwnias me tin vash!");
e.printStackTrace();
}
} |
bc0d2713-6e9a-4908-afd2-17d4f96b36f7 | 4 | private static String getSetString(String s) {
if (s == null)
return "{ }";
StringBuffer sb = new StringBuffer("{ ");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '!')
c = Universe.curProfile.getEmptyString().charAt(0);
sb.append(c);
if (i != s.length() - 1)
sb.append(',');
sb.append(' ');
}
sb.append('}');
return sb.toString();
} |
f6cfcf45-8637-4698-951d-a8deb3db4062 | 0 | private boolean isBundle() {
// only need the first 7 to check if it is a bundle
String bytesAsString = new String(bytes, 0, 7);
return bytesAsString.startsWith("#bundle");
} |
c422818f-0d4a-43d6-b083-2bbf88402479 | 5 | public String submit() {
// Calculate and save the ship date
int days = Integer.valueOf(shippingOption).intValue();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, days);
setShipDate(cal.getTime());
if ((cart.getTotal() > 100.00) && !specialOffer.isRendered()) {
specialOfferText.setRendered(true);
specialOffer.setRendered(true);
return null;
} else if (specialOffer.isRendered() && !thankYou.isRendered()) {
thankYou.setRendered(true);
return null;
} else {
try {
bookRequestBean.updateInventory(cart);
} catch (OrderException ex) {
return "bookordererror";
}
cart.clear();
return ("bookreceipt");
}
} |
ef7206ea-cb0b-4ffc-bca3-5024e2d75cb7 | 6 | @Override
public String[] extend(String basePreAlign, String basePostAlign, String extend, String[] table) {
ArrayList<Integer> inserts = new ArrayList<Integer>();
char[] basePost = basePostAlign.toCharArray();
char[] basePre = basePreAlign.toCharArray();
int j = 0;
for(int i = 0; i<basePost.length-1;i++){
if(basePost[i]=='-' && !(basePost[i]==basePre[j])){
inserts.add(i+ inserts.size());
}else {
j++;
}
}
for(int i=0; i<table.length;i++){
if(table[i] == null){
table[i]=extend;
break;
}
//insert gaps
for(int index : inserts){
table[i]=table[i].substring(0,index)+"-"+table[i].substring(index);
}
}
return table;
} |
198c1c3c-2fd7-4509-aad6-121ded4b4287 | 6 | public static void cleanUp() throws InterruptedException
{
boolean success = false;
int loop = 0;
traceln(STDOUT, DEBUG, "Cleaning...");
if( DOWNLOADS_TMP_DIRECTORY.exists() )
{
do {
success = FileUtils.recursiveDelete(Settings.DOWNLOADS_TMP_DIRECTORY);
Thread.sleep(50);
} while( success == false && loop < 3 );
}
loop = 0;
success = false;
if( UNZIP_DIRECTORY.exists() )
{
do {
success = FileUtils.recursiveDelete(Settings.UNZIP_DIRECTORY);
Thread.sleep(50);
} while( success == false && loop < 3 );
}
System.gc();
} |
7d850462-2861-4cc4-9041-6acf92f30f5c | 9 | @Override
public void run() {
boolean done = false;
int waitTime = 500;
try {
Packet pack = new Packet("GETCHUNK", "1.0", fileID, chunkNo, 0, null, null);
DistributedBackupSystem.cManager.sendPacket(pack, CommunicationManager.Channels.MC);
do {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {e.printStackTrace();}
for(Packet p : messages) {
if(p.getPacketType().equals("CHUNK") && Packet.bytesToHex(p.getFileID()).equals(Packet.bytesToHex(this.fileID)) && p.getChunkNo() == this.chunkNo) {
BackupChunk chunk = p.getChunk();
if(chunk.getSize() != 0)
DistributedBackupSystem.fManager.writeChunk(chunk);
/*if(chunk.getSize() < BackupChunk.maxSize )
DistributedBackupSystem.tManager.sendMessageToActiveTasks(new Packet("FINISHRESTORE", "", chunk.getFileID(), -1, 0, null, null));*/
done = true;
}
}
if (waitTime < 10000)
waitTime += waitTime;
else
done = true;
} while (!done);
} catch (IOException e) {e.printStackTrace();}
} |
bdd1c3bc-95ab-4f1f-9397-68485ebda8d9 | 1 | @Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
} |
71d5a2a8-8ded-4636-9d5b-5fdb0586e6ab | 0 | public Iterator getLoopedOpenDocumentIterator() {
return getOpenDocumentIterator(indexOfOpenDocument(mostRecentDocumentTouched));
} |
e52c5b6f-34df-4294-980c-df87e4eb5366 | 8 | private static String getStep(PathCell start, PathCell end,boolean isPushingBox){
if(end.getRow()-start.getRow()<0){
return isPushingBox?"N":"n";
}else if(end.getRow()-start.getRow()>0){
return isPushingBox?"S":"s";
}
if(end.getColumn()-start.getColumn()<0){
return isPushingBox?"E":"e";
}else if(end.getColumn()-start.getColumn()>0){
return isPushingBox?"W":"w";
}
return "";
} |
d7baf6b0-dbf1-4db8-8144-3e1a49ee0856 | 5 | public ArrayList<String> get_result_statement(StringBuilder sb) {
// Get Result From Each Block And Add Into An ArrayList, Update DB
Pattern p4 = Pattern
.compile(
"(/750)|((RESULT:)(.*?)\\.\\s\\.\\s\\.)|((RESULT: )((.*?)ORDN))|(/700)|((Result : )((.*?)\\s{5}))",
Pattern.DOTALL);
Matcher m4 = p4.matcher(sb);
//System.out.println(sb);
// int cnt = 1;
while (m4.find()) {
String result = m4.group().trim();
//System.out.println("Before : " + cnt + " " + result + " ---- END OF RECORD ---");
//cnt++;
/*if(cnt == 2){
System.out.println("Exiting ... ");
System.exit(-1);
}*/
// cnt++;
if (result.charAt(1) == '7') {
//System.out.println("END");
//System.exit(-1);
result = "NA";
} else {
if (result.contains("ORDN")) {
result = result.substring(8, result.lastIndexOf("O"))
.trim();
} else if(result.contains("Result"))
result = result.substring(8).trim();
else if(result.contains(". .")){
result = result.substring(7,result.length()-4).trim();
}
// result = result.substring(8, result.length()-1).trim();
}
//System.out.println("Result is : " + result + "END OF RES!");
// System.out.println("Adding : " + result);
result_array.add(result);
// System.out.println(result);
}
return result_array;
} |
f8189655-cc3b-42f4-982a-589d1c462ef8 | 7 | @Test
public void testCalculateSunVector() {
final TLE tle = new TLE(LEO_TLE);
Assert.assertFalse(tle.isDeepspace());
final Satellite satellite = SatelliteFactory.createSatellite(tle);
DateTime timeNow = new DateTime("2009-06-01T00:00:00Z");
for (int day = 0; day < 30; day++) {
final SatPos satPos = satellite.getPosition(GROUND_STATION,
timeNow.toDate());
switch (day) {
case 4:
case 9:
case 14:
case 19:
case 24:
case 29:
Assert.assertTrue("Satellite should have been eclipsed on day "
+ day, satPos.isEclipsed());
break;
default:
Assert.assertFalse(
"Satellite should not have been eclipsed on day " + day,
satPos.isEclipsed());
break;
}
timeNow = timeNow.plusDays(1);
}
} |
866b4176-8a0c-4be7-84f4-d956d39be834 | 7 | public void waitUntil(boolean v) throws InterruptedException{
// wait only if the value is not already v
if (value != v){
// set the until value (field) to v
until_value = v;
// mark waiting
waiting = true;
// recheck the condition
if (value != v){
// wait while the wait flag is true (ie the value differs from the conditional value)
while ( waiting ){
// wait is synchronized on this
synchronized(this){
g_syncWaits++;
if (waitTerminated){ waiting = false; throw new InterruptedException(); }
// recheck the wait flag
if (waiting){
// wait on this
try{ this.wait(); }
catch(InterruptedException interrupted){ waiting = false; throw interrupted; }
// catch(Throwable ignored){} // might be better handled in production quality
}
if (waitTerminated){ waiting = false; throw new InterruptedException(); }
}
}
}
// the condition so far became true
else{
// unset the wait flag
waiting = false;
}
}
} |
c888c6ea-fb7b-4c09-8e7d-a2b2863679ca | 0 | public void setPrpFecmod(Date prpFecmod) {
this.prpFecmod = prpFecmod;
} |
5376e0e3-2303-4e52-b0f8-96b6d0ed7ce4 | 4 | public static void insertSort(int[] array) {
for (int j = 1; j < array.length; j++) {
int key = array[j];
int i = j - 1;
while (i >= 0 && array[i] > key) {
array[i + 1] = array[i];
i--;
}
if (i != j - 1) {
array[i + 1] = key;
}
}
} |
0a71ec02-6830-4b1d-93f4-f4e5b95043f3 | 9 | public boolean effectiveBooleanValue(XPathContext context) throws XPathException {
int count = 0;
SequenceIterator iter = operand.iterate(context);
while (true) {
Item item = iter.next();
if (item == null) {
break;
}
if (item instanceof NodeInfo) {
Value atomizedValue = ((NodeInfo)item).atomize();
int length = atomizedValue.getLength();
count += length;
if (count > 1) {
return false;
}
if (length != 0) {
AtomicValue av = (AtomicValue)atomizedValue.itemAt(0);
if (!isCastable(av, targetType, context)) {
return false;
}
}
} else {
AtomicValue av = (AtomicValue)item;
count++;
if (count > 1) {
return false;
}
if (!isCastable(av, targetType, context)) {
return false;
}
}
}
return count != 0 || allowEmpty;
} |
0e45ccb3-a772-4c90-a33e-5dfb754509d5 | 3 | public void visitInnerClass(final String name, final String outerName,
final String innerName, final int access) {
cp.newUTF8("InnerClasses");
if (name != null) {
cp.newClass(name);
}
if (outerName != null) {
cp.newClass(outerName);
}
if (innerName != null) {
cp.newUTF8(innerName);
}
cv.visitInnerClass(name, outerName, innerName, access);
} |
67e5f834-1b67-492e-b890-b3379fb5d18b | 2 | public void solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
BigInteger[] a = new BigInteger[50];
a[0] = BigInteger.ZERO;
a[1] = BigInteger.ONE;
for (int i = 2; i < a.length; i++) {
a[i] = a[i - 1].add(a[i - 2]);
}
BigInteger res = BigInteger.ZERO;
for (int i = 1; i <= n; i++) {
res = res.add(a[i]);
}
System.out.println(res);
} |
db100761-523c-468e-b4d1-b29bc4ad1aed | 8 | public void initEngineAndBuffers() throws NoSuchAlgorithmException,
KeyStoreException, KeyManagementException, SSLException,
IOException {
if (mode == FTPConnection.AUTH_SSL_FTP_CONNECTION
|| mode == FTPConnection.IMPLICIT_SSL_FTP_CONNECTION)
context = SSLContext.getInstance("SSL");
else
context = SSLContext.getInstance("TLS");
if(trustManagers == null || trustManagers.length == 0)
trustManagers = new TrustManager[] { new EasyX509TrustManager(
null) };
context.init(keyManagers, trustManagers, null);
SSLSocketFactory sslFact = context.getSocketFactory();
sslSocket = (SSLSocket) sslFact.createSocket(socket, socket
.getInetAddress().getHostAddress(), socket.getPort(), true);
if (maxUpload == FTPConnection.MAX_UPLOAD_BANDWIDTH
|| isControllConnection()) {
out = sslSocket.getOutputStream();
} else {
out = new BandwidthControlledOutputStream(sslSocket
.getOutputStream(), maxUpload);
}
if (maxDownload == FTPConnection.MAX_DOWNLOAD_BANDWIDTH
|| isControllConnection()) {
in = sslSocket.getInputStream();
} else {
in = new BandwidthControlledInputStream(sslSocket.getInputStream(),
maxDownload);
}
sslSocket.setEnableSessionCreation(true);
sslSocket.setUseClientMode(true);
} |
bf2e5f43-8384-4a7b-ad8c-35d878679e1e | 8 | public double[] getMinMax(){
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
if(multiTrace)
{
for(int i = 0;i<multiColumnData.length;i++)
{
ArrayList<Double> l = (ArrayList<Double>)multiColumnData[i];
for(double d : l)
{
min = min < d ? min : d;
max = max > d ? max : d;
}
}
}
else
{
for(double d : columnData)
{
min = min < d ? min : d;
max = max > d ? max : d;
}
}
return new double[]{min,max};
} |
526da88c-9004-4e00-89c7-6483793ca3ca | 3 | private int select( int maxEingabe )
{
int eingabe = -1;
while ( eingabe < 0 || eingabe > maxEingabe )
{
Anzeige.zeigeStringAn( "Auswahl eingeben:" );
try
{
eingabe = Integer.parseInt( getEingabe() );
}
catch ( NumberFormatException nfEx )
{
System.out.println( "Es wurde keine Zahl eingegeben." );
}
}
return eingabe;
} |
3636cc22-6225-476c-8fdc-96c8387f6d9e | 7 | public Instances[] getEnsembleTrainingData(Instances classInstances, int noOfClasses) {
DoubleVector weights = new DoubleVector();
Instances[] resultData = new Instances[NoOfClusters];
ArrayList attList = Collections.list(classInstances.enumerateAttributes());
attList.add(classInstances.classAttribute());
try {
for (int i = 0; i < resultData.length; i++) {
resultData[i] = new Instances("resultData", attList, classInstances.size());
resultData[i].setClassIndex(attList.size() - 1);
}
Instance classCentroid = getClassCentroid(classInstances);
EuclideanDistance distanceFun = new EuclideanDistance();
int[] assignments = getClusterAssignments(classInstances);
int[] pointList = new int[Centroids.size()];
int[] orderedClusterList = new int[Centroids.size()];
Instances classCentroids = (Instances) MiscUtils.deepCopy(Centroids);
int idx = 0;
distanceFun.setInstances(classCentroids);
double distance;
for (int i = 0; i < Centroids.size(); i++) {
distance = distanceFun.distance(classCentroid, classCentroids.get(i));
weights.setValue(i, distance);
}
weights.normalize();
for (int i = 0; i < Centroids.size(); i++) {
pointList[i] = i;
}
//TODO: Fix the bug here
//When no points left in the pointlist, this code may throw an ArrayIndexOutOfBounds exception
for (int i = 0; i < Centroids.size(); i++) {
idx = distanceFun.closestPoint(classCentroid, classCentroids, pointList);
orderedClusterList[idx] = i;
pointList = MiscUtils.removeIntElement(pointList, idx);
}
for (int i = 0; i < classInstances.size(); i++) {
resultData[orderedClusterList[assignments[i]]].add(classInstances.get(i));
}
if (Weights.numValues() > 0) {
//Get average of them
Weights.addValues(weights);
Weights.scaleValues(0.5);
} else {
Weights = (DoubleVector) weights.copy();
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return resultData;
} |
6e92ccd2-c25b-4e91-89be-fcfac1d6c9dd | 1 | public int getLeftmostData( )
{
if (left == null)
return data;
else
return left.getLeftmostData( );
} |
335cd776-303e-4c23-bb22-451893a7b7f9 | 2 | public static boolean deleteInfo(String title){
boolean flag=false;
try{
contct=connector.getConnection();
Sttt=contct.prepareStatement("delete from bk where title ='"+title+"'");
if(Sttt.executeUpdate()==1)flag=true;
}catch(SQLException e){
System.out.println(e.getMessage());
}
connector.Close(contct, Sttt);
return flag;
} |
d6f39ae2-ef9f-4da1-807d-51232d931c14 | 7 | private static HashMap<Integer, Holder> getMap(File file, int dataColNum) throws Exception
{
HashMap<Integer, Holder> map = new HashMap<Integer, Holder>();
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.readLine();
for(String s = reader.readLine(); s != null && s.trim().length() > 0 ; s = reader.readLine())
{
String[] splits = s.split("\t");
Integer patientId = Integer.parseInt(splits[0]);
Holder h = map.get(patientId);
if( h == null)
{
h = new Holder();
map.put(patientId, h);
}
int time = Integer.parseInt(splits[1]);
if( time == 1)
{
if( h.time1 != null)
throw new Exception("no");
h.time1 = Double.parseDouble(splits[dataColNum]);
}
else if (time == 2)
{
if( h.time2 != null)
throw new Exception("no");
h.time2 = Double.parseDouble(splits[dataColNum]);
}
else throw new Exception("No");
}
reader.close();
return map;
} |
c703224f-9c04-4f41-aacd-ed47f784370c | 0 | @Override
public void componentMoved(ComponentEvent arg0) {
// TODO Auto-generated method stub
} |
cc12de6f-a33f-4e9a-9887-15ffcddd5e82 | 2 | @Override
public void onMessage( String message )
{
System.out.println( "SERVER: " + message );
ServerUser u = currentClient.attachment();
if (u == null)
{
currentClient.close();
}
else
{
for (ServerUser otherUser : userMap.values())
{
otherUser.service.onMessage( u.name, message );
}
}
} |
4d66bff9-8e9c-4217-bbb8-90f0a89a14b9 | 0 | public ConsoleTools() {} |
0c31657e-64e6-4641-949c-4fe87902932d | 8 | private int determineSquareKey(final int xPosition, final int yPosition) {
final List<Vehicle> groundVehicles = map.getGroundlevelVehicles(xPosition, yPosition);
final List<Vehicle> skyVehicles = map.getSkylevelVehicles(xPosition, yPosition);
switch (map.getType(xPosition, yPosition)) {
case SEA:
if (groundVehicles.isEmpty()) {
if (skyVehicles.isEmpty()) {
return SEA_KEY;
} else {
if (skyVehicles.size() > 1) {
return AIRCRAFTS_WATER_KEY;
} else {
return AIRCRAFT_WATER_KEY;
}
}
} else {
return CARRIER_KEY;
}
case LAND:
if (groundVehicles.isEmpty()) {
if (skyVehicles.isEmpty()) {
return LAND_KEY;
} else {
if (skyVehicles.size() > 1) {
return AIRCRAFTS_LAND_KEY;
} else {
return AIRCRAFT_LAND_KEY;
}
}
} else {
return CARRIER_KEY;
}
default:
return -1;
}
} |
59d051e9-cfb8-4b69-aa7f-783b88c0669c | 9 | @Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
// We're not interested in the postprocessing round.
return false;
}
Set<? extends Element> rootElements = roundEnv
.getElementsAnnotatedWith(SerializableClasses.class);
for (Element element : rootElements) {
// We're only interested in packages
if (element.getKind() != ElementKind.PACKAGE) {
continue;
}
// Get some info on the annotated package
PackageElement thePackage = elementUtils.getPackageOf(element);
String packageName = thePackage.getQualifiedName().toString();
// Test each class in the package for "serializability"
List<? extends Element> classes = thePackage.getEnclosedElements();
for (Element theClass : classes) {
// We're not interested in interfaces
if (theClass.getKind() == ElementKind.INTERFACE) {
continue;
}
// Check if the class is actually Serializable
boolean isSerializable = typeUtils.isAssignable(theClass.asType(), serializableType);
if (!isSerializable) {
messager.printMessage(Kind.ERROR,
"SerializableClasses: The following class is not Serializable: " + packageName + "."
+ theClass.getSimpleName());
}
}
}
// Prevent other processors from processing this annotation
return true;
} |
4d138c4d-b1f4-4c78-8954-b2b008267754 | 3 | public ArrayList<String> letterCombinations2(String digits) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
for (int i = 2; i <= 6; ++i) {
char base = (char) ((3 * (i - 2)) + 'a');
ArrayList<String> list = new ArrayList<String>();
list.add(base + "");
list.add((char) (base + 1) + "");
list.add((char) (base + 2) + "");
map.put(i, list);
}
ArrayList<String> list1 = new ArrayList<String>();
list1.add("p");
list1.add("q");
list1.add("r");
list1.add("s");
map.put(7, list1);
for (int i = 8; i <= 8; ++i) {
char base = (char) ((3 * (i - 8)) + 't');
ArrayList<String> list = new ArrayList<String>();
list.add(base + "");
list.add((char) (base + 1) + "");
list.add((char) (base + 2) + "");
map.put(i, list);
}
char base = (char) ((3 * (9 - 8)) + 't');
ArrayList<String> list = new ArrayList<String>();
list.add(base + "");
list.add((char) (base + 1) + "");
list.add((char) (base + 2) + "");
map.put(9, list);
if (digits.length() == 0) {
ArrayList<String> res = new ArrayList<String>();
res.add("");
return res;
}
return combine2(digits, map);
} |
b71638b2-6211-48f7-b4d8-f5330846ff34 | 1 | public void update(long deltaMs) {
onCurrentFrame += deltaMs;
if(onCurrentFrame >= frameDelay) {
currentFrame++;
currentFrame %= frames.size();
onCurrentFrame = 0;
}
} |
f69df213-1f49-4ffe-ab85-d0490765c4f1 | 0 | @Test
public void testGetRad() {
System.out.println("getSumm");
assertEquals(1.0, new Cylinder(3,1,2.8).getRad(), 0.00001);
} |
fc1df4ba-575b-418d-a3a4-7cb48bde1786 | 6 | public static Serializable getObject(byte[] data) {
if (data == null) {
return null;
}
ObjectInputStream readS;
Serializable c;
try {
readS = new ObjectInputStream(new ByteArrayInputStream(data));
c = (Serializable) readS.readObject();
} catch (ClassNotFoundException e) {
return null;
} catch (StreamCorruptedException e) {
return new String(data);
} catch (IOException e) {
if (data.length < 5){ //@TODO какая-то магия, 3-буквенные слова вываливались с IOE
return new String(data);
}else{
return null;
}
}
if (c instanceof byte[]) {
return new String((byte[]) c);
} else {
return c;
}
} |
36b4acc9-fe13-49ec-b700-72dedb4235bb | 0 | @Override
@XmlElement(name="vorname")
public String getVorname() {
return this.vorname;
} |
035aa669-e23e-4d7d-b29f-63cd5eebd3fc | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
if (obj.getClass() == ProductoCantidad.class) {
ProductoCantidad p = (ProductoCantidad) obj;
if (codigo == p.getProducto().getCodigo()) {
return true;
}
return false;
}
}
final Producto other = (Producto) obj;
if (this.codigo != other.codigo) {
return false;
}
return true;
} |
ef83e72f-a4fd-4cc5-b169-cece1fb7b7f5 | 4 | private void doUpdateCY(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String chengYuanId = StringUtil.toString(request.getParameter("chengYuanId"));
if(!StringUtil.isEmpty(chengYuanId)) {
boolean isSuccess = true;
// ObjectMapper mapper = new ObjectMapper();
// Map result = new HashMap();
try {
ChengYuan oldCY = manager.findCYById(chengYuanId);
ChengYuan newCY = getChengYuanModel(request, response);
int flag = manager.updateChengYuan(newCY);
if(flag > 0) {
logger.info("#########更新团队成员成功,新成员是:"+newCY+"\n"+"旧成员是:"+oldCY);
// result.put("success",true);
}else{
logger.info("#########更新团队成员失败,新成员是:"+newCY+"\n"+"旧成员是:"+oldCY);
// result.put("success",false);
isSuccess = false;
}
} catch (Exception e) {
isSuccess = false;
logger.error("更新团队成员失败", e);
} finally {
if(isSuccess) {
request.getRequestDispatcher("/admin/chengyuan.do?method=viewAllCYs").forward(request,response);
return;
}else{
request.getRequestDispatcher("/admin/error.jsp").forward(request,response);
return;
}
}
}
} |
b94eed65-cf8d-4613-bdca-f91186522b6b | 2 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd;
HttpSession session = request.getSession();
String eventId = request.getParameter("eventId");
int seatRequested = Integer.parseInt((String)request.getParameter("noOfTic"));
EventSearchBean search = new EventSearchBean();
search.setEventId(Integer.parseInt(eventId));
ArrayList<EventsBean> arrlBean = EventDao.getEvents(search);
StudentBean studentbean = (StudentBean)session.getAttribute("person");
EventsBean eventBean = new EventsBean();
if(arrlBean.size()>0){
eventBean=arrlBean.get(0);
int availableSeats = eventBean.getTotalNoOfSeats()-eventBean.getBookedSeats();
if(seatRequested>availableSeats){
String errorMessage = "Number of seats are more than available seats!! Seats available for this event are "+availableSeats+" Please enter valid number of seats!!";
session.setAttribute("errorMessage", errorMessage);
rd=request.getRequestDispatcher("booktickets.jsp");
rd.forward(request,response);
}else{
StudentBookingDao dao = new StudentBookingDao();
dao.insertStudentBooking(studentbean.getStudentId(), Integer.parseInt(eventId), seatRequested);
int bookedSeats = eventBean.getBookedSeats()+seatRequested;
eventBean.setBookedSeats(bookedSeats);
EventDao.updateEvents(eventBean);
updateEventInSession(session, eventBean.getEventId(), bookedSeats);
rd=request.getRequestDispatcher("thankyouinsert.jsp");
rd.forward(request,response);
}
}else{
String errorMessage = "Event was not selected appropriately! Please select the event and try again!!";
session.setAttribute("errorMessage", errorMessage);
rd=request.getRequestDispatcher("booktickets.jsp");
rd.forward(request,response);
}
} |
4369a346-973a-4fa6-aaca-75a58f57ef5a | 9 | private boolean findDepthSanityCheck(){
ArrayList<InputNeuron> inputs=findInputs();
ArrayList<OutputNeuron> outputs=findOutputs();
for(int i=0;i<inputs.size();i++)
if(inputs.get(i).getDepth()!=0){
System.out.println("Input depth not right");
return false;
}
for(int i=0;i<outputs.size();i++)
for(int f=0;f<neurons.size();f++){
if(neurons.get(f).getDepth()>outputs.get(i).getDepth()&&!outputs.contains(neurons.get(f))){
System.out.println("Output Neurons are not the max");
return false;
}
}
for(int i=0;i<neurons.size();i++)
if(neurons.get(i).getDepth()==0&&!(neurons.get(i)instanceof InputNeuron)){
System.out.println("A Neuron cannot have depth 0");
return false;
}
return true;
} |
db29083a-a6db-4ef8-a857-5f4871568d31 | 1 | private Text getField(String key) throws IOException {
try {
return new Text(next.getString(key));
} catch (JSONException ex) {
throw new IOException(ex);
}
} |
f63fd843-9a5c-4740-b589-69269f0c14a8 | 4 | void computeDisplayTexts (GC gc) {
if ((parent.getStyle () & SWT.VIRTUAL) != 0 && !cached) return; /* nothing to do */
int columnCount = parent.columns.length;
if (columnCount == 0) return;
for (int i = 0; i < columnCount; i++) {
gc.setFont (getFont (i, false));
computeDisplayText (i, gc);
}
} |
b597bb69-e86e-46c2-b0f9-6f68570f4c0b | 9 | @Override
public void run() {
Wrapper obj;
synchronized (this) {
while (true) {
if (que.isEmpty()) {
try {
System.out.println("start to wait");
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
Logger.getLogger(CallbackProxy.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("get notify");
obj = que.remove(0);
switch (obj.getType()) {
case PRE_CHAIN:
callback.preToolChain((ToolChain) obj.getObj());
break;
case AFTER_CHAIN:
callback.afterToolChain((ToolChain) obj.getObj());
break;
case PRE_SCRIPT:
callback.preToolScript((ToolScript) obj.getObj());
break;
case AFTER_SCRIPT:
callback.afterToolScript((ToolScript) obj.getObj());
que.clear();
return;
case FINISHED:
callback.finished((ToolScript) obj.getObj(), (Status) obj.getObj1());
break;
case PROGRESS:
callback.setProgress((int) obj.getObj());
break;
default:
Logger.getLogger(CallbackProxy.class.getName()).log(Level.SEVERE, "unkown type");
}
}
}
} |
460d95e8-4da0-491a-80d7-4be5828755ba | 8 | @Override
public String getToolTipForCell(Object cell)
{
String tip = "<html>";
mxGeometry geo = getModel().getGeometry(cell);
mxCellState state = getView().getState(cell);
if (getModel().isEdge(cell))
{
tip += "points={";
if (geo != null)
{
List<mxPoint> points = geo.getPoints();
if (points != null)
{
Iterator<mxPoint> it = points.iterator();
while (it.hasNext())
{
mxPoint point = it.next();
tip += "[x=" + numberFormat.format(point.getX())
+ ",y=" + numberFormat.format(point.getY())
+ "],";
}
tip = tip.substring(0, tip.length() - 1);
}
}
tip += "}<br>";
tip += "absPoints={";
if (state != null)
{
for (int i = 0; i < state.getAbsolutePointCount(); i++)
{
mxPoint point = state.getAbsolutePoint(i);
tip += "[x=" + numberFormat.format(point.getX())
+ ",y=" + numberFormat.format(point.getY())
+ "],";
}
tip = tip.substring(0, tip.length() - 1);
}
tip += "}";
}
else
{
tip += "geo=[";
if (geo != null)
{
tip += "x=" + numberFormat.format(geo.getX()) + ",y="
+ numberFormat.format(geo.getY()) + ",width="
+ numberFormat.format(geo.getWidth()) + ",height="
+ numberFormat.format(geo.getHeight());
}
tip += "]<br>";
tip += "state=[";
if (state != null)
{
tip += "x=" + numberFormat.format(state.getX()) + ",y="
+ numberFormat.format(state.getY()) + ",width="
+ numberFormat.format(state.getWidth())
+ ",height="
+ numberFormat.format(state.getHeight());
}
tip += "]";
}
mxPoint trans = getView().getTranslate();
tip += "<br>scale=" + numberFormat.format(getView().getScale())
+ ", translate=[x=" + numberFormat.format(trans.getX())
+ ",y=" + numberFormat.format(trans.getY()) + "]";
tip += "</html>";
return tip;
} |
44322c65-9f35-4082-8c93-a1312b9c9c03 | 8 | static int entrance(List<Point> points,int k){
int size=points.size();
Map<String,Integer> indexHash=new HashMap<>();//坐标hash
Map<String,Point> pointHash=new HashMap<>();//point hash
for(int i=0;i<size;++i){
Point p=points.get(i);
indexHash.put(p.x+","+p.y,i);
pointHash.put(p.x+","+p.y,p);
}
for(int i=size-1;i>=0;--i){
Point from=points.get(i);
int max=0;
Set<Point> rangePoints=rangePonints(from,k,pointHash);
for(Point p : rangePoints){
Integer index=indexHash.get(p.x+","+p.y);
if(index!=null && index>i && p.maxPathValue > max){
max=p.maxPathValue;
}
}
from.maxPathValue=max+from.value;
if(from.x==0 && from.y==0) return from.maxPathValue;
}
return -1;//never happen
} |
b6abc120-191c-4594-89fa-1a5c75c2b2a5 | 1 | private void startTimer()
{
btnCancel.setEnabled(true);
btnStart.setEnabled(false);
model.setTime(getTimeFromSPinners());
recentList.addItem(getTimeFromSPinners());
recentList.saveItems();
updateRecentMenu();
timer.start();
timeDirection = 0;
if (TimerPreferences.getInstance().getBoolean("minimize", true))
{
setState(JFrame.ICONIFIED);
}
} |
59256e92-dec9-486f-bfa7-a6795804446a | 5 | public static void main(String [] args) {
// assuming that 1-1-2 is not a triangle, (2-2-1 is not an AET) so starting with 2-2-3
long cumulativePerim = 0;
int countOfAETris = 0;
for (int i = 1; i < ((long) (1000000000/3)+2); i++) { // sloppy, see *** below
int j = i + 1;
double area = 0.0;
boolean isInt = false;
if (i + i + j > 1000000000) {
// low-budget check to handle approx roundoff, *** above
System.out.println("skipping: " + i + " + " + i + " + " + j); // a couple of these print out
continue;
}
area = triArea(i, i, j);
isInt = isInt(area);
if (isInt) {
countOfAETris += 1;
cumulativePerim += (i+i+j);
//System.out.println("i, i, j: " + i + ", " + i + ", " + j);
//System.out.println("area: " + area);
}
if (i + j + j > 1000000000) {
// low-budget check to handle approx roundoff, *** above
System.out.println("skipping: " + i + " + " + j + " + " + j);
continue;
}
area = triArea(i, j, j);
isInt = isInt(area);
if (isInt) {
countOfAETris += 1;
cumulativePerim += (i+j+j);
//System.out.println("i, j, j: " + i + ", " + j + ", " + j);
//System.out.println("area: " + area);
}
}
System.out.println("Cumulative Perim: " + cumulativePerim);
System.out.println("Number of AETs: " + countOfAETris);
} |
8b53a94e-f0f1-4d88-960c-e3a682dcbeaa | 9 | public void update(Observable observable, Object change) {
if (observable instanceof Board && change instanceof Turn) {
// A turn was had - was it by our player's team?
Turn turn = (Turn) change;
if (turn.getTeam() == player.getTeam()) {
if (turn instanceof Pass)
addPassText();
else if (turn instanceof Flip)
addFlipText((Flip) turn);
else
addMovementText((Move) turn); // includes Rescues
}
}
else if (observable instanceof Game && Game.NEW_ROUND.equals(change)) {
// A new round started
setText("");
moveCount = 0;
}
else if (observable instanceof Player && Player.TEAM.equals(change)) {
// The players changed teams
setBackground(player.getTeam());
}
} |
dbd51910-4df8-4657-a200-b5e8676b52e9 | 8 | public void run() {
Socket s = null;
try {
s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
model.addPlayer("Fred");
while (true) {
// read commands and return random response
char c = (char)dis.readByte();
while (c != '!') {
c = (char)dis.readByte();
}
int type = dis.readByte();
int length = dis.readShort();
char[] payload = new char[length];
String payloadString = "";
for (int i=0; i<length; i++) {
c = (char)dis.readByte();
payload[i] = c;
payloadString+= c;
}
if (type == 0) { // hello
model.addPlayer(payloadString);
startMsg(dos, 1, 2); //send type 1 msg
dos.writeByte(0); //game version
dos.writeByte((byte)model.getPlayers().size()); //player ID
} else if (type == 13) { // player calls set
startMsg(dos, 14, 1); //send type 14 msg
dos.writeByte(1); //player ID
} else if (type == 15) { // set call
startMsg(dos, 17, 1); //send type 17 msg
dos.writeByte(1); //player ID
} else { // anything else
startMsg(dos, 18, 2); //send type 18 msg
dos.writeByte(1); //player ID
dos.writeByte(2); //reason == NOTASET
}
}
} catch (EOFException e) {
// graceful termination on EOF
} catch (IOException e) {
System.out.println("Remote connection reset");
}
} |
55225848-f334-46ee-b0b1-90b21675864b | 7 | @Override
public void run() {
double unprocessedTicks = 0.0;
double nsPerTick = 1000000000.0/tps;
double unrenderedFrames = 0.0;
double nsPerFrame = 1000000000.0/fps;
long lastTime = System.nanoTime();
long lastFpsTime = System.currentTimeMillis();
int frameCount = 0;
int tickCount = 0;
while(running){
long now = System.nanoTime();
unprocessedTicks += (now - lastTime) / nsPerTick;
unrenderedFrames += (now - lastTime) / nsPerFrame;
lastTime = now;
if(unprocessedTicks >= 1.0 || !limitTPS){
tick();
unprocessedTicks -= 1.0;
tickCount++;
}
if(unrenderedFrames >= 1.0 || !limitFPS){
render();
unrenderedFrames -= 1.0;
frameCount++;
}
if(printFPS && System.currentTimeMillis() - lastFpsTime > 1000){
System.out.println(frameCount + " fps; " + tickCount + " tps");
frameCount = 0;
tickCount = 0;
lastFpsTime = System.currentTimeMillis();
}
}
} |
1acd5209-6099-4659-b92a-28eb0c6f55cd | 5 | private static int getCharWidth(char c) {
int charWidth = 6;
if(width5.indexOf(c) >= 0) {
charWidth = 5;
}
if(width4.indexOf(c) >= 0) {
charWidth = 4;
}
if(width3.indexOf(c) >= 0) {
charWidth = 3;
}
if(width2.indexOf(c) >= 0) {
charWidth = 2;
}
if(width1.indexOf(c) >= 0) {
charWidth = 1;
}
return charWidth;
} |
49b54d30-7a4d-45b1-911c-d1ebdee279d7 | 7 | private void nextRun() throws IOException {
out.setLength(0);
type = null;
token = null;
int c = in.peek();
if (c == -1) {
type = Type.END;
return;
}
clearSpace();
c = in.peek();
if (c == -1) {
type = Type.END;
return;
} else if ("/.(){}[]$%|:*?".indexOf(c) > -1) {
type = Type.SYMBOL;
out.append((char) in.read());
} else if (Character.isDigit(c)) {
type = Type.NUMBER;
parseNumber();
} else if (Character.isLetter(c) || c == '_' || c == '.') {
type = Type.NAME;
parseName();
} else {
error("Invalid character `" + (char) c + "'");
}
} |
c6a09159-0761-4262-95ad-874c162a1b50 | 4 | @Override
public String askForNewGame() {
HttpGet request;
try {
request = new HttpGet(new URI("http", null, SERVER, PORT, NEW_URL, null,
null));
} catch (URISyntaxException e1) {
throw new RuntimeException(e1);
}
HttpResponse response;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
String gameid;
try {
gameid = CharStreams.toString(new InputStreamReader(response.getEntity()
.getContent()));
} catch (IOException e) {
throw new RuntimeException(e);
}
return gameid;
} |
33330df9-2ebb-4bf3-8f2b-568e9dd5c768 | 6 | public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf()) {
BookInfo book = (BookInfo)nodeInfo;
displayData(book.bookData);
if (DEBUG) {
System.out.print(book.bookData + ": \n ");
}
} else if (node.getUserObject() instanceof BookInfo == true) {
BookInfo book = (BookInfo) node.getUserObject();
if (book.bookURL != null)
displayURL(book.bookURL);
else
displayData(book.bookData);
} else {
displayData(bookData);
}
if (DEBUG) {
System.out.println(nodeInfo.toString());
}
} |
6d8bbcd1-74e7-4e6d-9cb2-13fa264b4cc7 | 8 | static String toHex8String(int pValue)
{
String s = Integer.toString(pValue, 16);
//force length to be eight characters
if (s.length() == 0) {return "00000000" + s;}
else
if (s.length() == 1) {return "0000000" + s;}
else
if (s.length() == 2) {return "000000" + s;}
else
if (s.length() == 3) {return "00000" + s;}
else
if (s.length() == 4) {return "0000" + s;}
else
if (s.length() == 5) {return "000" + s;}
else
if (s.length() == 6) {return "00" + s;}
else
if (s.length() == 7) {return "0" + s;}
else{
return s;
}
}//end of Log::toHex8String |
ca865bb1-ef3e-4ad7-a0f5-9b3cb817c8da | 0 | public Object clone() {
return new Matrix(this);
} |
95d94fbc-395f-4fed-8014-4d4303c7e7d8 | 3 | public static void main(String[] args) {
// TODO Auto-generated method stub
int[] src = {7,6,8,3,4,5,3,2,1,8,9};
int start = 0;
int end = src.length-1;
int index = patition(src,start,end);
int k =4;
while( index != k){
if(index > k){
end = index - 1;
index = patition(src,start,end);
}else{
start = index + 1;
index = patition(src,start,end);
}
}
for(int i=0;i<=k;i++){
System.out.println(src[i]+" ");
}
int[] src1 = {7,6,8,3,4,5,3,2,1,8,9};
System.out.println("other");
otherMethod(src1,k);
} |
3dbe7605-f363-4fdd-b5a9-6007c49c744a | 7 | private LinkDecor getDecors2(String s) {
// System.err.println("s2=" + s);
if (s == null) {
return LinkDecor.NONE;
}
s = s.trim();
if ("|>".equals(s)) {
return LinkDecor.EXTENDS;
}
if (">".equals(s)) {
return LinkDecor.ARROW;
}
if ("^".equals(s)) {
return LinkDecor.EXTENDS;
}
if ("+".equals(s)) {
return LinkDecor.PLUS;
}
if ("o".equals(s)) {
return LinkDecor.AGREGATION;
}
if ("*".equals(s)) {
return LinkDecor.COMPOSITION;
}
return LinkDecor.NONE;
} |
022acf4f-9c2a-4501-bc06-e86175e33707 | 5 | public static int[] maxIndex(double[] __array) throws Exception {
ArrayList best_list = new ArrayList();
double best_val=Double.NEGATIVE_INFINITY;
double val;
int[] RET;
int _MAX = __array.length;
for (int i=0; i < _MAX; i++) {
val = __array[i];
if (val > best_val) {
best_val = val;
}
}
for (int i=0; i < _MAX; i++) {
if (__array[i] == best_val) {
best_list.add(new Integer(i));
}
}
_MAX = best_list.size();
RET = new int[_MAX];
for (int i=0; i < _MAX; i++) {
RET[i] = ((Integer) best_list.get(i)).intValue();
}
return RET;
} |
e7fe27b6-0219-46c7-af50-59338a789b4e | 7 | public ComponentState getState(){
CTaskState state = cTaskContext.getTaskState();
if(state.equals(CTaskState.CInit))
return ComponentState.INIT;
else if(state.equals(CTaskState.CPreOperational))
return ComponentState.PRE_OPERATIONAL;
else if(state.equals(CTaskState.CFatalError))
return ComponentState.FATAL_ERROR;
else if(state.equals(CTaskState.CException))
return ComponentState.EXCEPTION;
else if(state.equals(CTaskState.CStopped))
return ComponentState.STOPPED;
else if(state.equals(CTaskState.CRunning))
return ComponentState.RUNNING;
else if(state.equals(CTaskState.CRunTimeError))
return ComponentState.RUNTIME_ERROR;
else
return null;
} |
34378e44-e77d-4b26-b69a-b9e8ccd4d495 | 1 | public void inicio(InstituicaoCooperadora instituicaocooperadora)
throws Exception
{
salvar = new JButton("Salvar");
id = new JTextInt(instituicaocooperadora.getId());
id.setEditable(false);
id.setEnabled(false);
nome = new JTextField(instituicaocooperadora.getNome() == null ? ""
: instituicaocooperadora.getNome());
JPanel pp = new JPanel();
DesignGridLayout layout = new DesignGridLayout(pp);
layout.row().grid(new JLabel("ID:")).add(id);
layout.row().grid(new JLabel("Nome:")).add(nome);
layout.row().grid().add(salvar, 1);
getContentPane().add(new JScrollPane(pp));
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(400, 200);
setVisible(true);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.