text stringlengths 14 410k | label int32 0 9 |
|---|---|
static private int jjMoveStringLiteralDfa4_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(2, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(3, active0);
return 4;
}
switch(curChar)
{
case 101:
return jjMoveStringLiteralDfa5_0(active0, 0x4000L);
default :
break;
}
return jjStartNfa_0(3, active0);
} | 3 |
public void printMatrix(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
switch(matrix[j][i].getState())
{
case defaultState:
System.out.print("[ ] ");
break;
case missedState :
System.out.print("[M] ");
break;
case placedState:
System.out.print("[P] ");
break;
case selectedState:
System.out.print("[S] ");
break;
case shotDownState :
System.out.print("[X] ");
break;
}
}
System.out.println("");
}
} | 7 |
private int tilestrToInt(String tilestr) {
if (tilestr==null) return 0;
switch (tilestr.length()) {
case 0: return 0;
case 1: return (int)tilestr.charAt(0);
case 2: return (int)tilestr.charAt(0)
+ (int)tilestr.charAt(1)*256;
case 3: return (int)tilestr.charAt(0)
+ (int)tilestr.charAt(1)*256
+ (int)tilestr.charAt(2)*256*256;
case 4: return (int)tilestr.charAt(0)
+ (int)tilestr.charAt(1)*256
+ (int)tilestr.charAt(2)*256*256
+ (int)tilestr.charAt(3)*256*256*256;
default:
System.out.println(
"Warning: string '"+tilestr+" has wrong size.");
// XXX no reference to dbg
//dbgPrint("Warning: string '"+tilestr+" has wrong size.");
return 0;
}
} | 6 |
public void nextPage() {
if (isHasNextPage()) {
page++;
}
} | 1 |
@Override
public Value evaluate(Value... arguments) throws Exception {
// Check the number of argument
if (arguments.length == 1) {
// get Value
Value value = arguments[0];
// If numerical
if (value.getType().isNumeric()) {
return new Value(new Double(Math.log(value.getDouble())));
}
if (value.getType() == ValueType.ARRAY) {
Value[] vector = value.getValues();
Value result[] = new Value[vector.length];
for (int i = 0; i < vector.length; i++) {
result[i] = evaluate(vector[i]);
}
return new Value(result);
}
// the type is incorrect
throw new EvalException(this.name() + " function does not handle "
+ value.getType().toString() + " type");
}
// number of argument is incorrect
throw new EvalException(this.name()
+ " function only allows one numerical parameter");
} | 4 |
public static void main(String[] args)
throws IOException, ProcessException
{
String simType = args[args.length - 6];
int linesToRead = Integer.parseInt(args[args.length - 5]);
String inFile = args[args.length - 4];
String uniFile = args[args.length - 3];
String triFile = args[args.length - 2];
String stg1Nm = args[args.length - 1];
System.out.println("------------------------------------------------------------------------------");
// System.out.println("SimType: " + simType);
// System.out.println("Unigram File: " + uniFile);
// System.out.println("Trigram File: " + triFile);
// System.out.println("Input File: " + inFile);
// System.out.println("Output File: " + stg1Nm);
// TODO: set correct parameter to PMI, NGD, and GTM.
Measure sim = null;
if (simType.equals("Jacard"))
sim = new Jaccard();
else if (simType.equals("Simpson"))
sim = new Simpson();
else if (simType.equals("Dice"))
sim = new Dice();
else if (simType.equals("PMI"))
sim = new PMI(0);
else if (simType.equals("NGD"))
sim = new NGD(0);
else if (simType.equals("GTM"))
sim = new GTM(0);
runtime.gc();
stage1Test(uniFile, triFile, inFile, stg1Nm, sim, linesToRead);
} | 6 |
public Pass2(File source, int labelCount) {
labelFile = new File(source.getName() + ".label.tmp"); // File that contains the label information
sourceFile = new File(source.getName() + ".tmp"); // File that holds the cleaned/analyzed source
this.labelCount = labelCount;
labelMap = new HashMap<String, Integer>(labelCount); // Create label address hashmap
readLabel(); // Load the labels & addresses into the hashmap
parseLabels(); // Process the labels and reparse the source file
labelFile.delete(); // Delete unneeded temp label file
sourceFile.delete(); // Delete unneeded temp source file
} | 0 |
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
StringBuilder out = new StringBuilder();
precal();
out.append("PERFECTION OUTPUT\n");
while (scan.hasNext()) {
int v = scan.nextInt();
if (v == 0)
break;
out.append(format(v) + " ");
if (v == dp[v])
out.append("PERFECT");
else if (v < dp[v])
out.append("ABUNDANT");
else
out.append("DEFICIENT");
out.append("\n");
}
out.append("END OF OUTPUT\n");
System.out.print(out);
} | 4 |
public void SetPersonNumber(int personNumber)
{
this.personNumber = personNumber;
} | 0 |
@Override
public boolean canSetTrapOn(MOB mob, Physical P)
{
if(!super.canSetTrapOn(mob,P))
return false;
if(mob!=null)
{
final Item I=findMostOfMaterial(mob.location(),RawMaterial.MATERIAL_ROCK);
if((I==null)
||(super.findNumberOfResource(mob.location(),I.material())<100))
{
mob.tell(L("You'll need to set down at least 100 pounds of stone first."));
return false;
}
if(numWaterskins(mob)<=10)
{
mob.tell(L("You'll need to set down at least 10 water containers first."));
return false;
}
}
if(P instanceof Room)
{
final Room R=(Room)P;
if((R.domainType()&Room.INDOORS)==0)
{
if(mob!=null)
mob.tell(L("You can only set this trap indoors."));
return false;
}
}
return true;
} | 8 |
public static boolean isLessPriority(String a, String b){
String[] operadores={a,b};
int[] valores=new int[2];
for (int i = 0; i < operadores.length; i++) {
switch(operadores[i]){
case "^":
valores[i] = -1;
break;
case "*":
valores[i] = -2;
break;
case "/":
valores[i] = -2;
break;
case "+":
valores[i]= -3;
break;
case "-":
valores[i] = -3;
break;
case "(":
valores[i] = 0;
break;
case ")":
valores[i] = 0;
break;
}
}
return valores[0]<=valores[1];
} | 8 |
@SuppressWarnings("RedundantIfStatement")
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SvnInfo svnInfo = (SvnInfo) o;
if (repositoryUrl != null ? !repositoryUrl.equals(svnInfo.repositoryUrl) : svnInfo.repositoryUrl != null)
return false;
if (svnPath != null ? !svnPath.equals(svnInfo.svnPath) : svnInfo.svnPath != null) return false;
return true;
} | 7 |
public void visit_lcmp(final Instruction inst) {
stackHeight -= 4;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 1;
} | 1 |
public void paint(Graphics g){
super.paint(g);
Room r = GameController.getRoom();
int rw = r.getSize().width + 2;//room width
int rh = r.getSize().height + 2;// and height
//draw background color
Color c = r.backgroundColor();
if (c != null){
g.setColor(c);
g.fillRect(0, 0, rw, rh);
}
//TODO make this be preloaded so it doesn't have to recalculate on every step
//draw background image
Image img = r.backgroundImage();
if (img != null){
int iw = img.getWidth(null);//image width
int ih = img.getHeight(null);//and height
AffineTransform transform = new AffineTransform();//default is position (0,0)
switch (r.backgroundType()){
case TILED:
for (int x = 0; x < rw; x += iw)
for (int y = 0; y < rh; y += ih){
transform.setToTranslation(x, y);
((Graphics2D)g).drawImage(img, transform, null);
}
break;
case SCALED:
transform.scale(((double) rw) / iw,
((double) rh) / ih);
((Graphics2D)g).drawImage(img, transform, null);
break;
case NEITHER:
((Graphics2D)g).drawImage(img, transform, null);
break;
}
}//drawingOrder
Comparator<GameObject> comparator = new DepthComparator(DepthComparator.SortOrder.DEEP_FIRST);
PriorityQueue<GameObject> queue = new PriorityQueue<GameObject>(10, comparator);
queue.addAll(ObjectController.getAllObjects());
for (GameObject obj : queue){//old: ObjectController.getAllObjects()){
obj.draw(g);
g.setColor(Color.BLACK);
}
fpsManager.update();
g.drawString("FPS: " + fpsManager.getFPS(), 10, 10);
} | 8 |
public Item sample() {
if (isEmpty())
throw new java.util.NoSuchElementException();
return a[new Random().nextInt(next)];
} | 1 |
private static String prepareSql(String sql, List<String> names) {
logger.info("Prepare sql: " + sql);
String parts[] = sql.split(":");
StringBuilder bld = new StringBuilder();
boolean first = true;
for (String part: parts) {
if (first) {
first = false;
bld.append(part);
}
else {
bld.append("?");
int space = part.indexOf(' ');
if (space > -1) {
names.add(part.substring(0, space));
bld.append(part.substring(space));
}
else {
names.add(part);
}
}
}
logger.info("Prepared sql: " + bld.toString());
logger.info("Found names: " + names.toString());
return bld.toString();
} | 3 |
@Test
public void testValue() {
System.out.println("value");
for (int i = 0; i < this._values.length; i++)
{
_equals.testValue(_instance, null, _values[i], false);
_equals.testValue(_instance, _values[0], _values[i], false);
_equals.testValue(_instance, _values[1], _values[i], false);
_equals.testValue(_instance, _values[2], _values[i], false);
_equals.testValue(_instance, _values[i], null, false);
_equals.testValue(_instance, _values[i], _values[0], false);
_equals.testValue(_instance, _values[i], _values[1], false);
_equals.testValue(_instance, _values[i], _values[2], false);
}
boolean expecteds[] = new boolean[5];
expecteds[0] = true;
expecteds[1] = true;
expecteds[2] = true;
expecteds[3] = false;
expecteds[4] = false;
for (int j = 8; j < 19; j += 5)
{
for (int i = 0; i < 5; i++)
{
assertEquals("j = " + Integer.toString(j) +
" i = " + Integer.toString(i),
expecteds[i],
_instance.value(_values[j], _values[j + i]));
}
}
// Due to zero being a multiplicative specialty
expecteds[1] = false;
expecteds[2] = false;
for (int j = 3; j < 4; j += 5)
{
for (int i = 0; i < 5; i++)
{
assertEquals("j = " + Integer.toString(j) +
" i = " + Integer.toString(i),
expecteds[i],
_instance.value(_values[j], _values[j + i]));
}
}
for (int j = 3; j < 19; j += 5)
{
for (int i = 3 - j; i + j < 16; i += 5)
{
assertEquals("j = " + Integer.toString(j) +
" i = " + Integer.toString(i),
i == 0,
_instance.value(_values[j], _values[j + i]));
}
}
} | 7 |
private void GuardarEstacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GuardarEstacionActionPerformed
frecue = miRadio.getFrecuencia();
if (frecue) {
miRadio.Guardar(posFM, a);
posFM++;
} else {
miRadio.Guardar(posAM, b);
posAM++;
}
if (posFM > 11) {
posFM = 0;
}
if (posAM > 11) {
posAM = 0;
}
JOptionPane.showMessageDialog(null, "Su estacion se Ha guardado", "Radio", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_GuardarEstacionActionPerformed | 3 |
public void setWrapIndices(int[] indices) {
checkWidget();
if (indices == null)
indices = new int[0];
int count = originalItems.length;
for (int i = 0; i < indices.length; i++) {
if (indices[i] < 0 || indices[i] >= count) {
error(SWT.ERROR_INVALID_ARGUMENT);
}
}
for (int i = 0; i < originalItems.length; i++) {
originalItems[i].wrap = false;
}
for (int i = 0; i < indices.length; i++) {
int index = indices[i];
for (int row = 0; row < items.length; row++) {
if (items[row].length > index) {
items[row][index].wrap = true;
break;
} else {
index -= items[row].length;
}
}
}
relayout();
} | 8 |
public void MainHelpMenu()
{
if(pHead == 0 && pBeard == 10 && pTorso == 18 && pArms == 26 && pLegs == 72 && pFeet == 42 && pHands == 33){
showInterface(3559); // Shows "design your player"-screen if you haven't already designed it.
}
} | 7 |
public float priorityFor(Actor actor) {
if ((! begun()) && nursery.belongs.personnel.assignedTo(this) > 0) {
return 0 ;
}
//
// Vary priority based on competence for the task and how many crops
// actually need attention-
final float min = sumHarvest() > 0 ? ROUTINE : 0 ;
final float need = nursery.needForTending() ;
if (need <= 0) return min ;
float chance = 1.0f ;
chance *= actor.traits.chance(HARD_LABOUR, ROUTINE_DC) * 2 ;
chance *= actor.traits.chance(CULTIVATION, MODERATE_DC) * 2 ;
return Visit.clamp(chance * (CASUAL + (need * ROUTINE)), min, URGENT) ;
} | 4 |
private void createItems() {
HashSet<String> itemPaths;
try {
itemPaths = KvReader.getKvFiles("./items/");
} catch (IOException e){
e.printStackTrace(System.err);
return;
}
for (String s : itemPaths) {
HashMap<String, String> itemAttributes = KvReader.readFile(s);
String name = itemAttributes.get("name");
float weight = 0;
try {
weight = Float.valueOf(itemAttributes.get("weight"));
} catch (NumberFormatException e){
System.err.println("NaN error with item " + name);
//Ignore this item and move on
continue;
}
Item i = new Item(weight, name);
if (itemAttributes.get("room") == null) {
orphanedItems.put(name, i);
} else {
Room room = rooms.get(itemAttributes.get("room"));
if(room instanceof SpecialRoom){
((SpecialRoom)room).setReward(i);
} else {
room.addItem(i);
}
}
}
} | 5 |
@Override
public void run() {
if( getChannels().length == 0 )
joinChannel(channel);
} | 1 |
public void busquedaDesordenada(T dato){
Nodo<T> nodoQ = this.inicio;
while(nodoQ != null && nodoQ.getInfo() != dato){
nodoQ = nodoQ.getLiga();
}
if(nodoQ == null){
System.out.println("El elmento no se encuentra en la lista");
}else{
System.out.println("EL elemento se encuentra en la lista");
}
} | 3 |
public boolean isUrlModified() {
return urlModified;
} | 0 |
public boolean checkAllPortalsFor(MoveableObject object, MazeGame maze) {
for (Portal portal : portals) {
if (portal.intersects(object) && portal.isActive) {
portal.lit = true;
portal.getEndPortal().lit = true;
if (!lights.contains(portal)) lights.add(portal);
if (!lights.contains(portal.getEndPortal())) lights.add(portal.getEndPortal());
object.setX(object.x + portal.getEndPortal().x - portal.x);
object.setY(object.y + portal.getEndPortal().y - portal.y);
portal.getEndPortal().isActive = false; // so that you're not automatically teleported back
if(maze.isSoundOn())
portal.playSoundEffect();
return true;
} else if (!portal.isActive && !portal.intersects(object)) portal.isActive = true; // reactivate portals once player exists it
}
return false;
} | 8 |
boolean isPostingSupported(OMMMsg ommMsg)
{
if (!ommMsg.has(OMMMsg.HAS_ATTRIB_INFO))
return false;
OMMAttribInfo ai = ommMsg.getAttribInfo();
if (!ai.has(OMMAttribInfo.HAS_ATTRIB))
return false;
OMMElementList elementList = (OMMElementList)ai.getAttrib();
OMMData data = null;
long supportOMMPost = 0;
for (Iterator<?> iter = elementList.iterator(); iter.hasNext();)
{
OMMElementEntry ee = (OMMElementEntry)iter.next();
if (ee.getName().equals(RDMUser.Attrib.SupportOMMPost))
{
data = ee.getData();
if (data instanceof OMMNumeric)
{
supportOMMPost = ((OMMNumeric)data).toLong();
}
}
}
if (supportOMMPost == 1)
return true;
else
return false;
} | 7 |
public static ArrayList<String> splitFile() throws IOException{
DataHandler.cleanDir(preprocessFolder);
ArrayList<String> fileList=DataHandler.getFileList(DataHandler.originFolder);
int fileTag=0;
int lineCnt=0;
BufferedReader br = null;
BufferedWriter bw = null;
for(int i=0;i<fileList.size();i++){
File file=new File(fileList.get(i));
try {
br = new BufferedReader(new FileReader(file));
//br.readLine();//discard the 1st line of csv file
} catch (IOException e) {
e.printStackTrace();
}
String line;
try {
File splitFile=new File(DataHandler.preprocessFolder+Integer.toString(fileTag)+"_"+Integer.toString(i)+".txt");
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(splitFile)));
while ((line = br.readLine()) != null ){
bw.write(line);
bw.write("\r\n");
lineCnt++;
if(lineCnt>=threshold){
bw.flush();
bw.close();
fileTag++;
splitFile=new File(DataHandler.preprocessFolder+Integer.toString(fileTag)+"_"+Integer.toString(i)+".txt");
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(splitFile)));
lineCnt=0;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bw.flush();
bw.close();
ArrayList<String> splitFileList=DataHandler.getFileList(DataHandler.preprocessFolder);
return splitFileList;
} | 6 |
@Override
public void initialize() {
try {
out = new File("src/main/resources/data/hw1-huatang.out");// Path to create my output file.
bw = new BufferedWriter(new FileWriter(out));
} catch (Exception e) {
e.printStackTrace();
}
testfile = new File("src/main/resources/data/sample.out");// Sample output file. Used for
// comparison.
Scanner dict = null;
try {
dict = new Scanner(testfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (dict.hasNext()) {
hash.put(dict.nextLine(), 0);
numbers++;
}
} | 3 |
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
scan.nextLine();
scan.nextLine();
scan.nextLine();
TreeMap<Integer, TreeMap<String, Double>> exam = new TreeMap<>();
while(true){
String input = scan.nextLine();
if (input.contains("-") ) {
break;
}
String[] info = input.split("[\\s|]+");
int score = Integer.parseInt(info[2]);
String name = info[0]+" "+info[1];
double grade = Double.parseDouble(info[3]);
if (!exam.containsKey(score)) {
exam.put(score, new TreeMap<>());
}
exam.get(score).put(name, grade);
}
for (int score : exam.keySet()) {
System.out.print(score + " -> ");
System.out.print(exam.get(score).keySet() + ";");
double sum = 0;
int count = 0;
for (String student : exam.get(score).keySet()) {
sum += exam.get(score).get(student);
count++;
}
double average = sum / count;
System.out.printf(" avg=%.2f", average);
System.out.println();
}
} | 5 |
@Override
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
ArrayList<String> workerList = new ArrayList<>();
// Read list of workers from configuration file
try(BufferedReader br = new BufferedReader(new FileReader( "./config/workers.conf" ))) {
for(String line; (line = br.readLine()) != null; ) {
workerList.add(line);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
}
// Initialize worker manager
try {
WorkerManager.useWorkerList(workerList);
} catch (Exception ex) {
Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
System.exit(-1);
}
WorkerManager.printWorkerMap();
//jobMap.put(1, new String[1000]);
Thread workerStatusThread = new UpdateWorkerStatusThread();
workerStatusThread.start();
System.out.println("ready for connections");
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
System.out.println("Incoming connection from " + socket.getInetAddress());
HttpServerConnection conn = this.connFactory.createConnection(socket);
// Initialize the pool
Thread connectionHandler = new ConnectionHandlerThread(this.httpService, conn);
connectionHandler.setDaemon(false);
connectionHandlerExecutor.execute(connectionHandler);
System.out.println("\tConnection Handler Thread created");
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
// when the listener is interupted shutdown the pool
// and wait for any Connection Handler threads still running
connectionHandlerExecutor.shutdown();
while (!connectionHandlerExecutor.isTerminated()) {}
System.out.println("Finished all connection handler threads");
} | 8 |
public ArrayList<Segmento> getSegmentoPorId(String ticket) throws SQLException{
Statement stm = getConnection().createStatement();
String sql = "SELECT * FROM segmentos WHERE ticket='"+ticket+"'";
ArrayList<Segmento> segmentos = new ArrayList();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
Segmento seg = new Segmento(rs.getString("ticket"));
seg.setNumeroSegmento(rs.getInt("nro_segmento"));
seg.setCodSalida(rs.getString("cod_salida"));
seg.setCodLlegada(rs.getString("cod_llegada"));
seg.setNomSalida(rs.getString("nom_salida"));
seg.setNomLlegada(rs.getString("nom_llegada"));
seg.setFechaSalida(rs.getString("fecha_salida"));
seg.setHorSalida(rs.getString("hora_salida"));
seg.setFechaLlegada(rs.getString("fecha_llegada"));
seg.setHorLLegada(rs.getString("hora_llegada"));
seg.setNumeroVuelo(rs.getString("nro_vuelo"));
seg.setLineaAerea(rs.getString("linea_aerea"));
seg.setCodClase(rs.getString("cod_clase"));
segmentos.add(seg);
}
return segmentos;
} | 1 |
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CmpPoint)) {
return false;
}
CmpPoint o = (CmpPoint) obj;
return this.x==o.x && this.y==o.y;
} | 3 |
public void close() throws IOException {
if (!this.stack.empty()) {
throw new InvalidObjectException("Tags are not all closed. " +
"Possibly, " + this.stack.pop() + " is unclosed. ");
}
if (thisIsWriterOwner)
{
this.writer.flush();
this.writer.close();
}
} | 2 |
public void moveLeft() {
setDirection(-90);
for (TetrisBug tb : blocks){
tb.setDirection(-90);
}
if (rotationPos==0){
if (canMove() && blocks.get(0).canMove() && blocks.get(1).canMove() && blocks.get(2).canMove()) {
for (TetrisBug tb: blocks){
tb.move();
}
move();
}
}
if (rotationPos == 1){
if (blocks.get(0).canMove()){
blocks.get(0).move();
move();
blocks.get(1).move();
blocks.get(2).move();
}
}
} | 9 |
public static void Update()
{
for(int i = 0; i < NUM_KEYCODES; i++)
m_lastKeys[i] = GetKey(i);
for(int i = 0; i < NUM_MOUSEBUTTONS; i++)
m_lastMouse[i] = GetMouse(i);
} | 2 |
protected String getLabel(Tree tree, Node node) {
if (displayAttribute.equalsIgnoreCase(TAXON_NAMES)) {
Taxon taxon = tree.getTaxon(node);
if (taxon != null) {
if (textDecorator != null) {
textDecorator.setItem(taxon);
}
return taxon.getName();
} else {
return "unlabelled";
}
}
if ( tree instanceof RootedTree) {
final RootedTree rtree = (RootedTree) tree;
if (textDecorator != null) {
textDecorator.setItem(node);
}
if (displayAttribute.equalsIgnoreCase(NODE_HEIGHTS) ) {
return getNumberFormat().format(rtree.getHeight(node));
} else if (displayAttribute.equalsIgnoreCase(BRANCH_LENGTHS) ) {
return getNumberFormat().format(rtree.getLength(node));
}
}
return formatValue(node.getAttribute(displayAttribute));
} | 7 |
public boolean canHaveAsBalance(BigInteger balance) {
return (balance != null) && (balance.compareTo(this.getCreditLimit()) >= 0);
} | 1 |
private void markVisitedLinks() {
if (!(textBody.getDocument() instanceof HTMLDocument))
return;
HTMLDocument doc = (HTMLDocument) textBody.getDocument();
ElementIterator i = new ElementIterator(doc);
Element e;
AttributeSet as;
Enumeration en;
Object name;
String str;
SimpleAttributeSet sas;
while ((e = i.next()) != null) {
as = e.getAttributes();
en = as.getAttributeNames();
while (en.hasMoreElements()) {
name = en.nextElement();
if (name == HTML.Tag.A) {
if (as != null)
as = (AttributeSet) as.getAttribute(name);
if (as == null)
continue;
str = (String) as.getAttribute(HTML.Attribute.HREF);
if (FileUtilities.isRelative(str))
str = page.resolvePath(str);
if (!FileUtilities.isRemote(str))
str = FileUtilities.useSystemFileSeparator(str);
if (HistoryManager.sharedInstance().wasVisited(str)) {
sas = new SimpleAttributeSet();
StyleConstants.setForeground(sas, Page.getVisitedColor());
doc.setCharacterAttributes(e.getStartOffset(), e.getEndOffset() - e.getStartOffset(), sas,
false);
}
break;
}
}
}
} | 9 |
public static void main(String[] args)
{
JFrame frame = new JFrame("Mandlebrot");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(816, 638);
frame.add(new MandelbrotPanelDouble());
frame.setVisible(true);
// System.out.println(BigDecimal.valueOf(1).divide(BigDecimal.valueOf(3),64,RoundingMode.CEILING));
} | 0 |
public static HashMap<Integer, Integer> backTracking(SchedulingProblem csp, ArrayList<Integer> assignmentCount)
{
if (isComplete(csp))
{
return csp.Assignment;
}
Integer selectedVar;
ArrayList<Integer> mostConstrainedVars = csp.getMostConstrainedMeeting();
if(mostConstrainedVars.size() != 1)
{
selectedVar = csp.getMostConstrainingMeeting(mostConstrainedVars);
}else
{
selectedVar = mostConstrainedVars.get(0);
}
ArrayList<Integer> slots = new ArrayList<Integer>();
slots.addAll(csp.OrderedTimeslots(selectedVar));
for (Integer valueSlot : slots)
{
if(csp.isValid(selectedVar, valueSlot)){
csp.addAssignment(selectedVar, valueSlot);
assignmentCount.set(0, assignmentCount.get(0) + 1);
// try {
// writer.write("ASSIGNMENT: " + csp.Assignment.toString() + "\n");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
if(csp.fowardChecking() == false)
{
csp.removeAssignment(selectedVar);
return null;
}
HashMap<Integer, Integer> result = backTracking(csp, assignmentCount);
if(result != null)
{
return result;
}
csp.removeAssignment(selectedVar);
}
}
return null;
} | 6 |
public static double [] boundLargestEigenValue( DenseMatrix64F A , double []bound ) {
if( A.numRows != A.numCols )
throw new IllegalArgumentException("A must be a square matrix.");
double min = Double.MAX_VALUE;
double max = 0;
int n = A.numRows;
for( int i = 0; i < n; i++ ) {
double total = 0;
for( int j = 0; j < n; j++ ) {
double v = A.get(i,j);
if( v < 0 ) throw new IllegalArgumentException("Matrix must be positive");
total += v;
}
if( total < min ) {
min = total;
}
if( total > max ) {
max = total;
}
}
if( bound == null )
bound = new double[2];
bound[0] = min;
bound[1] = max;
return bound;
} | 7 |
private FlagGUI() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
Script.stop();
dispose();
}
});
setResizable(false);
setTitle("Flag Viewer");
setBounds(100, 100, 766, 603);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
GridBagConstraints gbc_lblFlag = new GridBagConstraints();
gbc_lblFlag.anchor = GridBagConstraints.WEST;
gbc_lblFlag.insets = new Insets(0, 0, 5, 5);
gbc_lblFlag.gridx = 0;
gbc_lblFlag.gridy = 0;
contentPane.add(lblFlag, gbc_lblFlag);
GridBagConstraints gbc_lblFlagValue = new GridBagConstraints();
gbc_lblFlagValue.anchor = GridBagConstraints.WEST;
gbc_lblFlagValue.insets = new Insets(0, 0, 5, 5);
gbc_lblFlagValue.gridx = 1;
gbc_lblFlagValue.gridy = 0;
contentPane.add(lblFlagValue, gbc_lblFlagValue);
GridBagConstraints gbc_btnExpand = new GridBagConstraints();
gbc_btnExpand.insets = new Insets(0, 0, 5, 5);
gbc_btnExpand.gridx = 4;
gbc_btnExpand.gridy = 0;
btnExpand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FlagViewer.modifyArea(1);
FlagViewer.getSurrounding();
}
});
GridBagConstraints gbc_btnFollowPlayer = new GridBagConstraints();
gbc_btnFollowPlayer.insets = new Insets(0, 0, 5, 5);
gbc_btnFollowPlayer.gridx = 3;
gbc_btnFollowPlayer.gridy = 0;
btnFollowPlayer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FlagViewer.toggleFollowPlayer();
final Color c = btnFollowPlayer.getBackground();
btnFollowPlayer.setBackground(c.equals(Color.red) ? DEFAULT_BACKGROUND : Color.red);
}
});
GridBagConstraints gbc_btnDirection = new GridBagConstraints();
gbc_btnDirection.insets = new Insets(0, 0, 5, 5);
gbc_btnDirection.gridx = 2;
gbc_btnDirection.gridy = 0;
btnDirection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switch (direction) {
case NORTH:
direction = Direction.NORTHEAST;
btnDirection.setText("Northeast");
break;
case NORTHEAST:
direction = Direction.EAST;
btnDirection.setText("East");
break;
case EAST:
direction = Direction.SOUTHEAST;
btnDirection.setText("Southeast");
break;
case SOUTHEAST:
direction = Direction.SOUTH;
btnDirection.setText("South");
break;
case SOUTH:
direction = Direction.SOUTHWEST;
btnDirection.setText("Southwest");
break;
case SOUTHWEST:
direction = Direction.WEST;
btnDirection.setText("West");
break;
case WEST:
direction = Direction.NORTHWEST;
btnDirection.setText("Northwest");
break;
case NORTHWEST:
direction = Direction.NORTH;
btnDirection.setText("North");
break;
}
}
});
contentPane.add(btnDirection, gbc_btnDirection);
contentPane.add(btnFollowPlayer, gbc_btnFollowPlayer);
contentPane.add(btnExpand, gbc_btnExpand);
GridBagConstraints gbc_btnContract = new GridBagConstraints();
gbc_btnContract.insets = new Insets(0, 0, 5, 0);
gbc_btnContract.gridx = 5;
gbc_btnContract.gridy = 0;
btnContract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FlagViewer.modifyArea(-1);
FlagViewer.getSurrounding();
}
});
contentPane.add(btnContract, gbc_btnContract);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridwidth = 6;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 1;
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, gbc_scrollPane);
table.setModel(new DefaultTableModel(Fields.DATA, Fields.COLUMN_HEADS));
table.getColumnModel().getColumn(0).setMinWidth(200);
table.getColumnModel().getColumn(0).setMaxWidth(200);
table.getColumnModel().getColumn(1).setMinWidth(70);
table.getColumnModel().getColumn(1).setMaxWidth(70);
table.getColumnModel().getColumn(2).setMinWidth(200);
table.getColumnModel().getColumn(2).setMaxWidth(200);
table.getColumnModel().getColumn(3).setMinWidth(80);
table.getColumnModel().getColumn(3).setMaxWidth(80);
table.getColumnModel().getColumn(4).setMinWidth(200);
table.getColumnModel().getColumn(4).setMaxWidth(200);
scrollPane.setViewportView(table);
} | 9 |
public String getJson(String location, String city) {
try {
/*
* Create the query url from template
*/
city = city.replace(" ", "_");
location = location.replace(" ", "_");
String weatherQuery = String.format(QUERY_URL, location, city);
System.out.println("URL: " + weatherQuery);
url = new URL(weatherQuery);
System.out.println(fullUrl);
conn = url.openConnection();
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
json = json.concat(line);
}
rd.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return json;
} | 3 |
public Template waitForMatch(Template tpl) {
String queryString = "";
int i = 0;
for (i = 0; i < 9; i++) {
Integer min;
Integer max;
try {
min = (Integer) PropertyUtils.getSimpleProperty(tpl, "property" + i + "_min");
max = (Integer) PropertyUtils.getSimpleProperty(tpl, "property" + i + "_max");
if (min != null && max != null) {
if (!queryString.isEmpty()) {
queryString += " AND ";
}
queryString += " property" + i + "_current BETWEEN " + (min-1) + " AND " + (max+1);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
queryString += " AND price <= " + tpl.getPrice_max();
return space.read(new SQLQuery<Template>(Template.class, queryString), Integer.MAX_VALUE);
} | 7 |
protected Trait(int type, String... descriptors) {
this.traitID = nextID++ ;
this.type = type ;
this.descriptors = descriptors ;
this.descValues = new int[descriptors.length] ;
int zeroIndex = 0, min = 100, max = 0, val ;
for (String s : descriptors) { if (s == null) break ; else zeroIndex++ ; }
for (int i = descriptors.length ; i-- > 0 ;) {
val = descValues[i] = zeroIndex - i ;
final String desc = descriptors[i] ;
if (verboseInit && desc != null) {
I.say("Value for "+desc+" is "+val) ;
}
if (val > max) max = val ;
if (val < min) min = val ;
}
this.minVal = min ;
this.maxVal = max ;
traitsSoFar.add(this) ;
allTraits.add(this) ;
} | 7 |
public void add(int value) {
if (result.size() > 0 && result.getValue((int)result.size() - 1) == value) {
resultGroups.get(resultGroups.size() - 1).maxIteration++;
} else {
resultGroups.add(new ResultGroup((int)result.size(), (int)result.size()));
}
result.add(value);
fireTableRowsInserted(resultGroups.size() - 1, resultGroups.size() - 1);
} | 2 |
public double getSpawnX(DodgeballPlayer p) {
DodgeballTeam t = p.getTeam();
return t == TEAM_1 ? TEAM_1_SPAWN_X : TEAM_2_SPAWN_X;
} | 1 |
@Override
public void add(User userBean) {
try {
connection = getConnection();
ptmt = connection.prepareStatement("INSERT INTO user(Name, Login, email, DateOfRegistration, password) "
+ "VALUES(?,?,?,?,?);");
ptmt.setString(1, userBean.getName());
ptmt.setString(2, userBean.getLogin());
ptmt.setString(3, userBean.getEmail());
ptmt.setDate(4, (Date) userBean.getDateOfRegistration());
ptmt.setString(5, userBean.getPassword());
ptmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 5 |
public double evaluate(double x) {
return Math.pow(_base, x);
} | 0 |
public void write(String text)
{
textArea.append(text);
int length = textArea.getText().length();
textArea.setCaretPosition(length);
lastCommandOffset = length;
} | 0 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if((affected!=null)&&(affected instanceof MOB)&&(msg.amISource((MOB)affected)))
{
if((msg.sourceMinor()==CMMsg.TYP_ENTER)
&&(msg.target() instanceof Room)
&&((((Room)msg.target()).domainType()==Room.DOMAIN_INDOORS_AIR)
||(((Room)msg.target()).domainType()==Room.DOMAIN_OUTDOORS_AIR))
&&(!CMLib.flags().isFlying(msg.source())))
{
msg.source().tell(L("You can't seem to get there from here."));
return false;
}
}
return true;
} | 9 |
public void saveToFile() {
try {
FileOutputStream fileOut = new FileOutputStream(FILE);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 1 |
public void close() throws IOException {
if(r != null) {
r = null;
ogg.close();
ogg = null;
}
if(w != null) {
w.bufferPacket(firstPacket.write(), true);
w.bufferPacket(tags.write(), false);
// TODO Write the others
//w.bufferPacket(setup.write(), true);
long lastGranule = 0;
for(FlacAudioFrame fa : writtenAudio) {
// Update the granule position as we go
// TODO Track this
// if(fa.getGranulePosition() >= 0 &&
// lastGranule != fa.getGranulePosition()) {
// w.flush();
// lastGranule = fa.getGranulePosition();
// w.setGranulePosition(lastGranule);
// }
// Write the data, flushing if needed
w.bufferPacket(new OggPacket(fa.getData()));
if(w.getSizePendingFlush() > 16384) {
w.flush();
}
}
w.close();
w = null;
ogg.close();
ogg = null;
}
} | 4 |
public Square(int row, int col, Piece piece)
{
this.row = row;
this.col = col;
this.piece = piece;
y = row * 80;
x = col * 80;
rect = new Rectangle(x, y, 80, 80);
} | 0 |
public PacketManager getPacketManager(){
return packetManager;
} | 0 |
private boolean checkBack(int x, int y, int z){
int dx = x - 1;
if(dx < 0){
return false;
}else if(chunk[dx][y][z] != 0){
return true;
}else{
return false;
}
} | 2 |
private void percolateDown( int hole )
{
int child;
T tmp = array[ hole ];
for( ; hole * 2 <= currentSize; hole = child )
{
child = hole * 2;
if( child != currentSize &&
array[ child + 1 ].compareTo( array[ child ] ) < 0 )
child++;
if( array[ child ].compareTo( tmp ) < 0 )
array[ hole ] = array[ child ];
else
break;
}
array[ hole ] = tmp;
} | 4 |
public static boolean isSuccessResult(Option[] options){
for(int i=0,count=options.length ; i<count ; ++i){
if((options[i].getName().equals(ActionResult.RESULT)) &&
options[i].getValue().equals(ActionResult.SUCCESS))
return true;
}
return false;
} | 3 |
private void storeUpcommingEarningsPagesCustom() {
try {
long time = System.currentTimeMillis();
for (int i = 0; i < 14; i++) {
Date days = new Date(time + 1000 * 3600 * 24 * i);
String date = dateFormatForUrl.format(days);
String earnings = "http://biz.yahoo.com/research/earncal/"
+ date + ".html"; // /
try {
File htmlFile = new File(REPORTS_ROOT + dayString()
+ "_URL_" + date + ".html");
FileUtils.copyURLToFile(new URL(earnings), htmlFile);
System.out.println(new SimpleDateFormat("EEE").format(days)
+ " " + earnings);
rawHtmlData.add(htmlFile);
} catch (Exception e) {
System.out.println("Error: "
+ new SimpleDateFormat("EEE").format(days)
+ " " + earnings);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 3 |
@Override
public void onEnable() {
logger = new TPLogger(getLogger());
characterManager = new CharacterManager(this);
logger().log(Level.INFO, "Plugin enabled!");
} | 0 |
private void checkDerived(ClassScope subClass, ClassScope classScope)
{
for (Scope method : subClass.methods)
{
if (classScope.hasSymbol(method.getName()))
{
Scope sym = classScope.getSymbol(method.getName());
if (sym instanceof FieldScope)
throw new SemanticError("semantic error at line " + method.getLine()
+ ": " + "method " + sym.getName()
+ " shadows a field with the same name");
if (sym instanceof MethodScope
&& !((MethodScope) sym).signature(false).equals(
((MethodScope) method).signature(false)))
throw new SemanticError("semantic error at line " + method.getLine()
+ ": " + "method " + sym.getName()
+ " overloads a method with the same name");
}
}
for (Scope field : subClass.fields)
{
if (classScope.hasSymbol(field.getName()))
{
Scope sym = classScope.getSymbol(field.getName());
if (sym instanceof FieldScope)
throw new SemanticError("semantic error at line " + field.getLine()
+ ": " + "field " + sym.getName()
+ " shadows a field with the same name");
}
}
} | 8 |
@Override
public Boolean isValid() {
constraintViolations = new HashMap<String, String>();
// nom
if (this.nom.isEmpty()) {
constraintViolations.put("NomIsValid", "Le nom est obligatoire.");
} else {
if (this.nom.length() > 50) {
constraintViolations.put("NomIsValid", "Le nom doit comporter 50 caractères maximum.");
}
}
// prénom
if (this.prenom.isEmpty()) {
constraintViolations.put("PrenomIsValid", "Le prénom est obligatoire.");
} else {
if (this.prenom.length() > 50) {
constraintViolations.put("PrenomIsValid", "Le prénom doit comporter 50 caractères maximum.");
}
}
// email
if (!this.email.isEmpty()) {
if (this.email.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) {
constraintViolations.put("EmailIsValid", "Le format de l'email n'est pas valide.");
} else {
if (this.email.length() > 50) {
constraintViolations.put("EmailIsValid", "L'email doit comporter 50 caractères maximum.");
}
}
}
// téléphone
if (!this.telephone.isEmpty()) {
if (this.telephone.matches("^[0-9].[0-9].[0-9].[0-9].[0-9]$")) {
constraintViolations.put("TelephoneIsValid", "Le format de téléphone n'est pas valide.");
}
}
return constraintViolations.isEmpty();
} | 9 |
@Basic
@Column(name = "PCA_ESTADO")
public String getPcaEstado() {
return pcaEstado;
} | 0 |
public static int calcDistance(String s1, String s2){
if (s1.equals(s2)){
return 0;
}
else{
int n = s1.length();
int m = s2.length();
int e[][] = new int[n+1][m+1];
for (int i=0; i<=n; i++){
e[i][0] = i;
}
for (int j=1; j<=m; j++){
e[0][j] = j;
}
for (int i=1; i<=n; i++){
for (int j=1; j<=m; j++){
int diff = 1;
if (s1.charAt(i-1) == s2.charAt(j-1)){
diff = 0;
}
e[i][j] = Math.min(e[i-1][j]+1, Math.min(e[i][j-1] +1, e[i-1][j-1]+diff));
}
}
return e[n][m];
}
} | 6 |
public JSONWriter key(String s) throws JSONException {
if (s == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
if (this.comma) {
this.writer.write(',');
}
stack[top - 1].putOnce(s, Boolean.TRUE);
this.writer.write(JSONObject.quote(s));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch (IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
} | 4 |
public void updateUser(HttpServletRequest request, HttpServletResponse response,String updateUserinfo) throws ServletException, IOException
{
/*
* Here we initialize tools for making the database connection
* and reading from the database
*/
Connection conn=null;
Statement stmt=null;
String separator = System.getProperty("file.separator");
String imageDir = getServletContext().getRealPath(separator) + "images" + separator;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
ResultSet resultSetuser=null;
ResultSetMetaData resultSetuserMeatData=null;
try {
//Here we load the database driver for Oracle database
//Class.forName("oracle.jdbc.driver.OracleDriver");
//For mySQL database the above code would look like this:
Class.forName("com.mysql.jdbc.Driver");
//For mySQL database the above code would look like
//something this.
//Notice that here we are accessing mg_db database
String url="jdbc:mysql://mysql.cc.puv.fi:3306/e1100587_project";
//Here we create a connection to the database
conn=DriverManager.getConnection(url, "e1100587", "vxnB9ws3N5M7");
//Here we create the statement object for executing SQL commands.
stmt=conn.createStatement();
//Here we execute the SQL query and save the results to a ResultSet object
resultSetuser=stmt.executeQuery(updateUserinfo);
resultSetuserMeatData=resultSetuser.getMetaData();
int usercolumn=resultSetuserMeatData.getColumnCount();
out.println("<table border='1'><tr>");
//Here we print column names in table header cells
//Pay attention that the column index starts with 1
for(int i=1; i<=usercolumn; i++) {
out.println("<th> "+resultSetuserMeatData.getColumnName(i)+ "</th>");
}
out.println("</tr>");
while(resultSetuser.next())
{
out.println("<tr>");
//Here we print the value of each column
for(int i=1; i<=usercolumn; i++)
{
if (resultSetuser.getObject(i)!=null)
out.println("<td>" + resultSetuser.getObject(i).toString()+"</td>");
else
out.println("<td>---</td>");
}
out.println("</tr>");
}
}catch(Exception e){
/*---------------*/
out.println("<tr>"+ e.getMessage());
}finally {
try {
//Here we close all open streams
if(stmt !=null)
stmt.close();
if(conn!=null)
conn.close();
}catch(SQLException sqlexc){
/*----------------*/
out.println("EXception occurred while closing streams!");
}
}
} | 8 |
public void bake() {
if(pie.getDough().isEmpty()) {
BuilderClient.addOutput("error - no dough found!");
return;
}
if (pie.getFilling().isEmpty()) {
BuilderClient.addOutput("error - no filling found!");
return;
}
baked = true;
BuilderClient.addOutput("*oven sound*");
} | 2 |
public void updateGraphics() {
Tuple<BufferedImage[], Integer> stateSprites = this.animation.getStateSprites(this.state);
BufferedImage[] spriteFrames = stateSprites.getX();
if(disposeAfterAnimation && this.spriteFrame + 1 == spriteFrames.length * stateSprites.getY()) {
disposed = true;
} else {
this.spriteFrame = (this.spriteFrame + 1) % (spriteFrames.length * stateSprites.getY());
}
} | 2 |
public void step() {
for(int a = 0; a < agents.length; a++) {
agents[a].hasMoved = false;
}
for(int i = 0; i < numStrategies; i++) {
averageScoreStrat[i] = 0;
averageEncountersStrat[i] = 0;
}
for(int a = 0; a < agents.length; a++) {
agents[a].act();
String strategy = agents[a].getStrategy();
for(int i = 0; i < numStrategies; i++) {
if(strategy.equals(strategies[i])) {
averageScoreStrat[i] += agents[a].getScore();
averageEncountersStrat[i] += agents[a].getEncounters();
}
}
}
for(int i = 0; i < numStrategies; i++) {
if(agentsStrat[i] != 0) {
averageScoreStrat[i] = averageScoreStrat[i] / (double)agentsStrat[i];
}
if(averageEncountersStrat[i] != 0) {
averageEncountersStrat[i] = averageEncountersStrat[i] / (double)agentsStrat[i];
}
}
Arrays.sort(agents);
} | 8 |
@Override
public MouseAdapter thumbnailSelection() {
return new MouseAdapter () {
@Override
public void mouseClicked(MouseEvent event) {
if (selectedEMediumLabel != null)
selectedEMediumLabel.setBorder(null);
selectedEMediumLabel = (EMediumLabel) event.getSource();
selectedEMediumLabel.setBorder(new MatteBorder(3, 3, 3, 3, (Color) Color.YELLOW));
if (event.getButton() == MouseEvent.BUTTON1) {
if (event.getClickCount() >= 2) {
// on double click, view the document
if (canBeViewed(selectedEMediumLabel.getEMedium()))
if (selectedEMediumLabel.getEMediumViewer() != null) {
eMediumShow(selectedEMediumLabel);
} else
JOptionPane.showMessageDialog(bookshelfUI, "Cannot obtain a viewer for this type of document",
"Error obtaining viewer for document", JOptionPane.ERROR_MESSAGE);
else
JOptionPane.showMessageDialog(bookshelfUI, "You do not have a valid rental for the e-medium",
"Error viewing the e-medium", JOptionPane.ERROR_MESSAGE);
}
}
else if (event.getButton() == MouseEvent.BUTTON3) {
selectedEMediumLabel = (EMediumLabel) event.getSource();
JPopupMenu contextMenu = selectedEMediumLabel.getContextMenu();
contextMenu.show (selectedEMediumLabel, event.getX(), event.getY());
}
}
};
} | 6 |
public void rb_insert(RBNode z) {
RBNode y = nil;
RBNode x = root;
// System.out.println(z.getKey());
while (x != nil) {
y = x;
if (z.getKey() < x.getKey()) {
x = x.getLeft();
} else {
x = x.getRight();
}
}
z.setParrent(y);
// makeDotFile();
if (y == nil) {
root = z;
} else {
if (z.getKey() < y.getKey()) {
y.setLeft(z);
// makeDotFile();
} else {
y.setRight(z);
// makeDotFile();
}
}
z.setLeft(nil);
z.setRight(nil);
z.setColor(Color.RED);
rb_insert_fixup(z);
} | 4 |
public void actionPerformed(ActionEvent e)
{
if (e.getSource().equals(mPreview))
{
ImageIcon selectedIcon = (ImageIcon) mImageList.getSelectedValue();
String name = selectedIcon.getDescription();
ImageIcon realImage = RHImageLoader.getImageIcon(name);
JDialog jd = new JDialog(this);
jd.getContentPane().add(new JLabel(realImage));
jd.setTitle(realImage.getDescription());
jd.pack();
jd.setLocationRelativeTo(this);
jd.setVisible(true);
}
else
{
if (e.getSource().equals(mPreview))
{
mReturnCode = JOptionPane.OK_OPTION;
}
else
{
mReturnCode = JOptionPane.CANCEL_OPTION;
}
setVisible(false);
}
} | 2 |
public void Solve() {
HashMap<String, List<String>> hashMap = new HashMap<String, List<String>>();
String result = "";
for (int n = 1; n < _max; n++) {
String cube = Cube(n);
String key = SortString(cube);
List<String> cubes = hashMap.get(key);
if (cubes == null) {
cubes = new ArrayList<String>();
hashMap.put(key, cubes);
}
cubes.add(cube);
if (_permutations <= cubes.size()) {
Collections.sort(cubes);
String candidate = cubes.get(0);
if (result.equals("") || candidate.compareTo(result) < 0) {
result = candidate;
System.out.println("n=" + n + ", n^3=" + result);
}
}
}
System.out.println("Result=" + result);
} | 5 |
public String getIncompletedSeller() {
Map<String, Object> params = ActionContext.getContext().getParameters();
String seqID = ((String[]) params.get("seqID"))[0];
seller = this.cfService.getIncompletedSeller(seqID);
return SUCCESS;
} | 0 |
public boolean checkPath(String path, boolean isExistingFile) {
File test = new File(path);
if (isExistingFile && !test.isDirectory()) {
return test.exists();
} else {
if (!isExistingFile) {
return test.exists();
}
}
return false;
} | 3 |
private void drawBorder(Graphics g)
{
//First initialise colour
Color borderColour = slidePanel.getBackground();
//Set flags (for use in creating the border) for whether the zoomed
//image takes the full height and/or width of the slide area
Boolean isFullWidth = false;
Boolean isFullHeight = false;
if(hostSize.getWidth() == zoomedSize.width)
isFullWidth = true;
if(hostSize.getHeight() == zoomedSize.height)
isFullHeight = true;
//Check flags isFullWidth and isFullHeight to ensure border does not
//go outside slide area. If one of the flags is true, its corresponding
//size and position variables will omit the border thickness from
//their calculation (so the border will end at any image edge
//that contacts the slide edge
int borderWidth;
int borderHeight;
int x;
int y = zoomedPosition.y - borderThickness;
//Check horizontal
if(isFullWidth)
{
borderWidth = zoomedSize.width;
x = zoomedPosition.x;
}
else
{
borderWidth = zoomedSize.width + 2*borderThickness;
x = zoomedPosition.x - borderThickness;
}
//Check vertical
if(isFullHeight)
{
borderHeight = zoomedSize.height;
y = zoomedPosition.y;
}
else
{
borderHeight = zoomedSize.height + 2*borderThickness;
y = zoomedPosition.y - borderThickness;
}
//Debug messages to verify correct sizing and positioning of border
if(Debug.imagePlayer) System.out.println("Border panel will be drawn at ("+
x+","+y+") with dimensions "+
borderWidth+" x "+borderHeight);
//Draw the first rectangle which will define the border
g.setColor(borderColour);
g.fillRect(x, y, borderWidth, borderHeight);
//Draw the second rectangle which will give a white background to any
//image with transparency
g.setColor(Color.WHITE);
g.fillRect(zoomedPosition.x, zoomedPosition.y,
zoomedSize.width, zoomedSize.height);
} | 5 |
@Override
public boolean evaluate(T t) {
if(firstSearchString.evaluate(t) || secondSearchString.evaluate(t)){
return true;
}
else{
return false;
}
} | 2 |
private void btnQuitterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitterActionPerformed
((CtrlMenu)controleur).fichierQuitter();
}//GEN-LAST:event_btnQuitterActionPerformed | 0 |
public static void main(String[] args) {
Random rnd = new Random();
for (int step = 0; step < 100_000; step++) {
int n = rnd.nextInt(10) + 1;
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = rnd.nextInt(10);
int k = rnd.nextInt(n);
nth_element(a, 0, n, k);
int[] s = a.clone();
Arrays.sort(s);
if (a[k] != s[k])
throw new RuntimeException();
for (int i = 0; i < n; i++)
if (i < k && a[i] > a[k] || i > k && a[i] < a[k])
throw new RuntimeException();
}
} | 8 |
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException, NoSuchAlgorithmException {
boolean releaseMode = false;
if (args != null)
{
for (String arg : args) {
if (arg.equals("release"))
releaseMode = true;
}
}
if (releaseMode)
System.out.println("Starting verification of RELEASE mode!");
// will verify that the project at the current working folder is valid
// tests:
// 1) package name is valid
// 1.1) in AndroidManifest.xml
// 1.2) in any source file
// 2) any declared pack XML is valid
// 2.1) pack ID is unique and valid
final File currentFolder = new File(System.getProperty("user.dir"));
final PackDetails packDetails = verifyAndroidManifestAndGetPackageName(currentFolder);
System.out.println("Package name is " + packDetails.PackageName);
verifyStringsFileIsValid(currentFolder, packDetails);
verifyAntBuildFile(currentFolder, packDetails);
verifySourceCodeHasCorrectPackageName(currentFolder, packDetails);
if (packDetails.KeyboardSourceCodeFile != null)
verifyKeyboardDeclaration(currentFolder, packDetails);
if (packDetails.DictionarySourceCodeFile != null)
verifyDictionaryDeclaration(currentFolder, packDetails);
if (packDetails.ThemeSourceCodeFile != null)
verifyThemeDeclaration(currentFolder, packDetails);
//checking app icons have been changed
verifyFileCheckSumHasChanged(new File(currentFolder, "/res/drawable/app_icon.png"), true, "0e71ddf43d0147f7cacc7e1d154cb2f2a031d804", releaseMode);
verifyFileCheckSumHasChanged(new File(currentFolder, "/res/drawable-hdpi/app_icon.png"), false, "ea1f28b777177aae01fb0f717c4c04c0f72cac71", releaseMode);
verifyFileCheckSumHasChanged(new File(currentFolder, "/res/drawable-xhdpi/app_icon.png"), false, "862166a2f482b0a9422dc4ed8b293f93b04d6e20", releaseMode);
verifyFileCheckSumHasChanged(new File(currentFolder, "/StoreStuff/landscape.png"), true, "0b39e1c3824515ff2f406bd1ad811774306cdfe4", releaseMode);
verifyFileCheckSumHasChanged(new File(currentFolder, "/StoreStuff/portrait.png"), true, "cd995002d2ea98b16d1e1a1b981b0dadd996c6a6", releaseMode);
verifyFileCheckSumHasChanged(new File(currentFolder, "/StoreStuff/store_hi_res_icon.png"), true, "83d31f26cd4bb3dc719aaa739a82ab6fc5af1b82", releaseMode);
} | 7 |
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
String rest="ALL";
if(commands.size()>1)
rest=CMParms.combine(commands,1);
Environmental target=mob.location().fetchFromRoomFavorMOBs(null,rest);
if((target!=null)&&(!target.name().equalsIgnoreCase(rest))&&(rest.length()<4))
target=null;
if((target!=null)&&(!CMLib.flags().canBeSeenBy(target,mob)))
target=null;
if(target==null)
mob.tell(L("Fire whom?"));
else
{
final CMMsg msg=CMClass.getMsg(mob,target,null,CMMsg.MSG_SPEAK,L("^T<S-NAME> say(s) to <T-NAMESELF> 'You are fired!'^?"));
if(mob.location().okMessage(mob,msg))
mob.location().send(mob,msg);
}
return false;
} | 8 |
private boolean r_verb() {
int among_var;
int v_1;
// (, line 136
// [, line 137
ket = cursor;
// substring, line 137
among_var = find_among_b(a_4, 46);
if (among_var == 0)
{
return false;
}
// ], line 137
bra = cursor;
switch(among_var) {
case 0:
return false;
case 1:
// (, line 143
// or, line 143
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 143
if (!(eq_s_b(1, "\u0430")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 143
if (!(eq_s_b(1, "\u044F")))
{
return false;
}
} while (false);
// delete, line 143
slice_del();
break;
case 2:
// (, line 151
// delete, line 151
slice_del();
break;
}
return true;
} | 8 |
@EventHandler
public void GhastWeakness(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.getZombieConfig().getDouble("Ghast.Weakness.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Fireball) {
Fireball a = (Fireball) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getGhastConfig().getBoolean("Ghast.Weakness.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, plugin.getGhastConfig().getInt("Ghast.Weakness.Time"), plugin.getGhastConfig().getInt("Ghast.Weakness.Power")));
}
}
} | 7 |
public LOGLEVEL getLoglevel()
{
if(logLevel == -1)
{
return LOGLEVEL.Nothing;
}
else if(logLevel == 0)
{
return LOGLEVEL.Error;
}
else if(logLevel == 1)
{
return LOGLEVEL.Normal;
}
else if(logLevel == 2)
{
return LOGLEVEL.Debug;
}
else
{
return LOGLEVEL.Normal;
}
} | 4 |
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
saveFilePath=saveFilePath.substring(0,saveFilePath.indexOf("?"));
File f= new File(saveFilePath);
f.createNewFile();
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(f);
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("saveFilePath = " + saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} | 4 |
public Point getAutoPoint(){
return myAutoPoint;
} | 0 |
public void readInput(Data data) throws NumberFormatException, IllegalChoicesException {
data.resetChoices();
for (int i = 0; i < 4; i++) {
JComboBox<Subject> thisBox = examComboBoxes.get(i);
Subject selectedSubject = (Subject) thisBox.getSelectedItem();
resetBackground(thisBox);
//Check for multiple choices of the same subject
for (int j = 0; j < i; j++) {
if (examComboBoxes.get(j).getSelectedItem().equals(selectedSubject)) {
highlightTemporarily(examComboBoxes.get(j), null);
throw new IllegalChoicesException();
}
}
selectedSubject.abinote = Integer.parseInt(markInputField[i].getText());
if (i < 3) {
selectedSubject.writtenExamSubject = true;
} else {
selectedSubject.oralExamSubject = true;
}
}
} | 4 |
public final MiniParser.decl_return decl() throws RecognitionException {
MiniParser.decl_return retval = new MiniParser.decl_return();
retval.start = input.LT(1);
Object root_0 = null;
Token i=null;
ParserRuleReturnScope t =null;
Object i_tree=null;
RewriteRuleTokenStream stream_ID=new RewriteRuleTokenStream(adaptor,"token ID");
RewriteRuleSubtreeStream stream_type=new RewriteRuleSubtreeStream(adaptor,"rule type");
try {
// C:\\eclipse-workspaces\\workspace1\\Compiler\\src\\edu\\calpoly\\mwerner\\compiler\\Mini.g:138:4: (t= type i= ID -> ^( DECL ^( TYPE $t) $i) )
// C:\\eclipse-workspaces\\workspace1\\Compiler\\src\\edu\\calpoly\\mwerner\\compiler\\Mini.g:138:7: t= type i= ID
{
pushFollow(FOLLOW_type_in_decl1228);
t=type();
state._fsp--;
if (state.failed) return retval;
if ( state.backtracking==0 ) stream_type.add(t.getTree());
i=(Token)match(input,ID,FOLLOW_ID_in_decl1232); if (state.failed) return retval;
if ( state.backtracking==0 ) stream_ID.add(i);
// AST REWRITE
// elements: t, i
// token labels: i
// rule labels: retval, t
// token list labels:
// rule list labels:
// wildcard labels:
if ( state.backtracking==0 ) {
retval.tree = root_0;
RewriteRuleTokenStream stream_i=new RewriteRuleTokenStream(adaptor,"token i",i);
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.getTree():null);
RewriteRuleSubtreeStream stream_t=new RewriteRuleSubtreeStream(adaptor,"rule t",t!=null?t.getTree():null);
root_0 = (Object)adaptor.nil();
// 139:7: -> ^( DECL ^( TYPE $t) $i)
{
// C:\\eclipse-workspaces\\workspace1\\Compiler\\src\\edu\\calpoly\\mwerner\\compiler\\Mini.g:139:10: ^( DECL ^( TYPE $t) $i)
{
Object root_1 = (Object)adaptor.nil();
root_1 = (Object)adaptor.becomeRoot((Object)adaptor.create(DECL, "DECL"), root_1);
// C:\\eclipse-workspaces\\workspace1\\Compiler\\src\\edu\\calpoly\\mwerner\\compiler\\Mini.g:139:17: ^( TYPE $t)
{
Object root_2 = (Object)adaptor.nil();
root_2 = (Object)adaptor.becomeRoot((Object)adaptor.create(TYPE, "TYPE"), root_2);
adaptor.addChild(root_2, stream_t.nextTree());
adaptor.addChild(root_1, root_2);
}
adaptor.addChild(root_1, stream_i.nextNode());
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
}
retval.stop = input.LT(-1);
if ( state.backtracking==0 ) {
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
}
catch (RecognitionException re)
{
reportError(re);
recover(input, re);
_errors = true;
}
finally {
// do for sure before leaving
}
return retval;
} | 9 |
public void doOperation() throws ArithmeticException{
if(testOperation()){
BigDecimal result;
switch (operation){
case "X":
total = last.multiply(total).setScale(2, RoundingMode.HALF_UP);
last = null;
operation = null;
break;
case "/":
total = last.divide(total, 2, RoundingMode.HALF_UP);
last = null;
operation = null;
break;
case "+":
total = last.add(total).setScale(2, RoundingMode.HALF_UP);
last = null;
operation = null;
break;
case "-":
total = last.subtract(total).setScale(2, RoundingMode.HALF_UP);
last = null;
operation = null;
break;
}
}
} | 5 |
private boolean internalRemove(Investment investment) {
PortfolioIterator iterator = new PortfolioIterator();
Investment i;
boolean removed = false;
while (iterator.hasNext()) {
i = iterator.next();
// case where Investment to remove is a top-level investment
if (i.getUniqueId() == investment.getUniqueId()) {
this.children.remove(i);
removed = true;
break;
}
// case where investment may be in a Portfolio
// check the contents of the Portfolio for the Investment to remove
if (i.getClass() == Portfolio.class) {
Portfolio p = (Portfolio)i;
removed = p.internalRemove(investment);
}
if (removed) break;
}
return removed;
} | 4 |
public void readHex() {
if (pos < s.length() &&
((s.charAt(pos) >= '0' && s.charAt(pos) <= '9') ||
(s.charAt(pos) >= 'A' && s.charAt(pos) <= 'F') ||
(s.charAt(pos) >= 'a' && s.charAt(pos) <= 'f'))) {
pos++;
}
else {
throw new JSONParseException(s, pos);
}
} | 7 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
&&((msg.amITarget(affected))))
{
final MOB target=(MOB)msg.target();
if((!target.isInCombat())
&&(msg.source().getVictim()!=target)
&&(msg.source().location()==target.location())
&&(CMLib.dice().rollPercentage()>((msg.source().phyStats().level()-(target.phyStats().level()+getXLEVELLevel(invoker()))*10))))
{
msg.source().tell(L("You are too much in awe of @x1",target.name(msg.source())));
if(target.getVictim()==msg.source())
{
target.makePeace(true);
target.setVictim(null);
}
return false;
}
}
return super.okMessage(myHost,msg);
} | 8 |
public void bubbleSort(boolean printpasses) {
for (int pass = 1; pass < elements.length - 1; pass++) {
int swapcount = 0;
for (int i = 0; i < elements.length - pass; i++) {
T current = elements[i];
T other = elements[i + 1];
int compResult = current.compareTo(other);
if (compResult > 0) { //current is larger
elements[i] = other;
elements[i + 1] = current;
swapcount++;
}
if (compResult < 0) { //current is smaller
elements[i] = current;
elements[i + 1] = other;
}
}
if (swapcount == 0) {
return;
}
if (printpasses) {
System.out.println(this);
}
}
} | 6 |
void UploadFile( HttpServletRequest request, HttpServletResponse response, String login )
{
json = new JSONObject();
// Создаем фабрику для файлов хранимых на диске
DiskFileItemFactory factory = new DiskFileItemFactory();
// Настраиваем контейнер для хранения файлов
File repository = new File(uploadPath);
factory.setRepository(repository);
// Создаем новый обработчик загрузки файла
ServletFileUpload upload = new ServletFileUpload( factory );
upload.setHeaderEncoding("UTF-8");
//создаем слежку за прогрессом
ProgressListener progressListener = new ProgressListener()
{
public void update(long pBytesRead, long pContentLength, int pItems)
{
if (pContentLength == -1)
{
System.out.println("So far, " + pBytesRead + " bytes have been read.");
}
else
{
//высчитываем процен выполнения
percent = (int) ( (int) pBytesRead/( pContentLength/100 ) );
contentLength = pContentLength/1048576;
bytesRead = pBytesRead/1048576;
}
}
};
upload.setProgressListener(progressListener);
//Парсим запрос
try
{
List<FileItem> items = upload.parseRequest( request );
// Обрабатываем загруженные файлы
Iterator<FileItem> iter = items.iterator();
String fieldName = null;
String fileName = null;
String contentType;
boolean isInMemory;
long sizeInBytes = 0;
FileItem item = null;
String name = null;
String days = null;
FileItem uploadItem = null;
while ( iter.hasNext() )
{
item = iter.next();
if ( !item.isFormField() )
{
fieldName = item.getFieldName();
fileName = item.getName();
contentType = item.getContentType();
isInMemory = item.isInMemory();
sizeInBytes = item.getSize();
uploadItem = item;
}
else
{
name = item.getFieldName();
days = item.getString();
}
}
if ( uploadItem != null && fileName != null )
{
fileName = transliterator.transliterate(fileName);
uploadItem.write( new File( uploadPath + new String( fileName.getBytes("UTF-8" ) ) ) );
int random = mysql.addFile(fileName, login, sizeInBytes, Integer.parseInt(days) );
json.put( "result", random );
response.getWriter().print( json.toString() );
}
else
{
json.put( "result", "error" );
response.getWriter().print( json.toString() );
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
public Chara talkWith() {
int nextX = 0;
int nextY = 0;
// キャラクターの向いている方向の1歩となりの座標
switch (direction) {
case LEFT:
nextX = x - 1;
nextY = y;
break;
case RIGHT:
nextX = x + 1;
nextY = y;
break;
case UP:
nextX = x;
nextY = y - 1;
break;
case DOWN:
nextX = x;
nextY = y + 1;
break;
}
// その方向にキャラクターがいるか調べる
Chara chara;
chara = map.charaCheck(nextX, nextY);
// キャラクターがいれば話しかけたキャラクターの方へ向ける
if (chara != null) {
switch (direction) {
case LEFT:
chara.setDirection(RIGHT);
break;
case RIGHT:
chara.setDirection(LEFT);
break;
case UP:
chara.setDirection(DOWN);
break;
case DOWN:
chara.setDirection(UP);
break;
}
}
return chara;
} | 9 |
void dorestore ()
{
if (PGF != null) return;
FileDialog fd = new FileDialog(this,
Global.resourceString("Load_Game"), FileDialog.LOAD);
if ( !Dir.equals("")) fd.setDirectory(Dir);
fd.setFile("*.sto");
fd.show();
String fn = fd.getFile();
if (fn == null) return;
Dir = fd.getDirectory();
if (fn.endsWith(".*.*")) // Windows 95 JDK bug
{
fn = fn.substring(0, fn.length() - 4);
}
try
// print out using the board class
{
BufferedReader fi = new BufferedReader(
new InputStreamReader(new DataInputStream(new FileInputStream(
fd.getDirectory() + fn))));
Moves = new ListClass();
while (true)
{
String s = fi.readLine();
if (s == null) break;
StringParser p = new StringParser(s);
Out.println("@@@" + s);
moveinterpret(s, true);
}
if (PGF != null) Out.println("@@start");
fi.close();
}
catch (IOException ex)
{}
} | 8 |
private void updateResults() {
if (UpDown.getNumPlayers()==5 && table.getRowCount()==6) {
( (MyTableModel) table.getModel() ).removeRow();
( (MyTableModel) table.getModel() ).removeColumn();
setTableFormat(5);
}
else if (UpDown.getNumPlayers()==6 && table.getRowCount()==5) {
( (MyTableModel) table.getModel() ).addRow();
( (MyTableModel) table.getModel() ).addColumn();
setTableFormat(6);
}
for(int i=0;i<UpDown.getNumPlayers();++i) {
table.setValueAt("P"+(i+1),i,1); // set pid
table.setValueAt(UpDown.getPlayer(i).getName(),i,2); // set name
table.setValueAt(UpDown.getPlayer(i).getBeatSize(),i,3); // set wins
table.setValueAt(UpDown.getPlayer(i).getLostSize(),i,4); // set losses
for(int j=i;j<UpDown.getNumPlayers();++j) { // set result (1=won 0=lost null=not played)
if (i!=j)
if (UpDown.getPlayer(i).beatContains(UpDown.getPlayer(j))) {
table.setValueAt(1,i,(5+j));
table.setValueAt(0,j,(5+i));
}
else if (UpDown.getPlayer(i).lostContains(UpDown.getPlayer(j))) {
table.setValueAt(0,i,(5+j));
table.setValueAt(1,j,(5+i));
}
else {
table.setValueAt(null,i,(5+j));
table.setValueAt(null,j,(5+i));
}
}
table.setValueAt(UpDown.getRank(i),i,0); // set rank
}
} | 9 |
@Override
public void rotateClockwise(Board board) {
int rot = (getRotation()+1) % 4;
if (rotateAlgorithm(board, Point.translate(getBase(), BASES[rot]), RELS[rot], getKicks()[getRotation()])) {
addRotation(1);
}
System.out.print("Rotate " + this.toString() + "\n");
} | 1 |
@Override
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException {
if (arguments.size() != 1) {
throw new TemplateModelException("This function expects 1 parameter");
}
Object type = arguments.get(0);
String ret = "";
if (type instanceof StringModel) {
type = ((StringModel) type).getWrappedObject();
if (type instanceof Return) {
type = ((Return) type).getType();
}
}
if (type instanceof TypeRef) {
TypeRef typeRef = (TypeRef) type;
if (typeRef.getName().equals("boolean")) {
ret = "= false";
} else if (typeRef.getName().equals("float") || typeRef.getName().equals("int")) {
ret = "= 0";
}
} else {
throw new TemplateModelException("Class not expected " + type);
}
return ret;
} | 7 |
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.