text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
private void method289(Object5 class28)
{
for(int j = class28.anInt523; j <= class28.anInt524; j++)
{
for(int k = class28.anInt525; k <= class28.anInt526; k++)
{
Ground class30_sub3 = groundArray[class28.anInt517][j][k];
if(class30_sub3 != null)
{
for(int l = 0; l < class30_sub3.anInt1317; l++)
{
if(class30_sub3.obj5Array[l] != class28)
continue;
class30_sub3.anInt1317--;
for(int i1 = l; i1 < class30_sub3.anInt1317; i1++)
{
class30_sub3.obj5Array[i1] = class30_sub3.obj5Array[i1 + 1];
class30_sub3.anIntArray1319[i1] = class30_sub3.anIntArray1319[i1 + 1];
}
class30_sub3.obj5Array[class30_sub3.anInt1317] = null;
break;
}
class30_sub3.anInt1320 = 0;
for(int j1 = 0; j1 < class30_sub3.anInt1317; j1++)
class30_sub3.anInt1320 |= class30_sub3.anIntArray1319[j1];
}
}
}
}
| 7 |
public void setEcho(boolean echoToConsole) {this.echoToConsole = echoToConsole;}
| 0 |
public String multiply(String num1, String num2) {
int[] num = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
int carry = 0;
int a = num1.charAt(num1.length() - 1 - i) - '0';
for (int j = 0; j < num2.length(); j++) {
int b = num2.charAt(num2.length() - 1 - j) - '0';
num[i + j] += carry + a * b;
carry = num[i + j] / 10;
num[i + j] %= 10;
}
num[i + num2.length()] += carry;
}
int i = num.length - 1;
while (i > 0 && num[i] == 0) {
i--;
}
StringBuilder temp = new StringBuilder("");
while (i >= 0) {
temp.append((char) ('0' + num[i--]));
}
return temp.toString();
}
| 5 |
public void EndTurn() {
players.Base ply = Game.player.get(currentplayer);
for (units.Base unit : Game.units) {
unit.acted=false;
unit.moved=false;
}
currentplayer++;
if (currentplayer>=totalplayers) {currentplayer=0;day++;}
ply = Game.player.get(currentplayer);
if (day!=1) {
ply.money+=buildingmoney*Buildingcount(currentplayer);
}
for (units.Base unit : Game.units) {
if (unit.owner == currentplayer && unit.health<unit.maxhp && unit.bld!=-1) {
unit.Medic();
}
}
Game.pathing.LastChanged++;
}
| 7 |
@Override
public int getScale(final RoundingContext context)
{
final Integer decimalPlaces = map.get(SampleRoundingContext.narrow(context));
if (decimalPlaces == null)
{
return defaultDecimalPlaces;
}
else
{
return decimalPlaces;
}
}
| 1 |
SS_translation find_translation(String pref_lang_locale, String format)
{
String loc = pref_lang_locale;
do
{
// System.out.println("==locale=" + loc + " format=" + format);
/* see if this format string exists in the transsets */
SS_translationset ts = trans_by_lang.get(loc);
// System.out.println("== ts is " + ts);
if (ts != null)
{
/* see if this script is one of the scripts here */
SS_translation st = ts.by_format.get(format);
if (st != null)
{
return st;
}
}
loc = strip_locale(loc);
}
while( loc != null && loc.lastIndexOf('_') != -1 );
/* wait a minute, we really should revert to "en" if nothing else works */
if (loc != null && !loc.equals("en"))
return find_translation("en", format);
return null;
}
| 6 |
private Stmt parseStatement() {
//System.out.println("parseStatement");
Stmt node = null;
switch (showNext().getKind()) {
case "ident":
Identifier id = new Identifier(acceptIt());
Selector sel = parseSelector();
if (nextIs("assign")) {
node = parseAssignment(id,sel);
} else {
node = parseProcedureCall(id,sel);
}
break;
case "if":
node = parseIfStatement();
break;
case "while":
node = parseWhileStatement();
break;
default:
this.console.setText(this.console.getText() + "<br> Error at: L" +showNext().getPos()[0] +"c"+showNext().getPos()[1]+ " expecting one of : identifier, if, while");
break;
}
return node;
}
| 4 |
public T NextLargest2(T key) throws InvalidPositionException,
EmptyTreeException {
BTPosition<T> current = checkPosition(root());
Stack<BTPosition<T>> s = new Stack<>();
while (!s.isEmpty() || current != null) {
if (current != null) {
s.push(current);
current = current.getLeft();
} else {
current = s.pop();
if (comp.compare(key, current.element()) < 0)
return current.element();
current = current.getRight();
}
}
return null;
}
| 4 |
@Override
public void validate() {
super.validate();
if (SUBMIT.equals(getSubmit())) {
if (StringUtils.isBlank(bookVO.getBookName())
|| !(StringUtils.isAlphaSpace(bookVO.getBookName()))) {
addFieldError("bookVO.bookName", "Please enter valid book name");
}
if (StringUtils.isBlank(bookVO.getPublisher())
|| !(StringUtils.isAlphaSpace(bookVO.getPublisher()))) {
addFieldError("bookVO.publisher", "Please enter valid publisher name");
}
if (StringUtils.isBlank(bookVO.getAuthor())
|| !(StringUtils.isAlphaSpace(bookVO.getAuthor()))) {
addFieldError("bookVO.author", "Please enter valid author name");
}
}
}
| 7 |
private void processObject(Object o){
try {
MethodTransfer mt=(MethodTransfer)o;
//System.out.println ("method transfer");
MethodDetails md=mt.getMethodDetails();
Class<?> c=couple.getReceiver().getClass();
try {
Method m=c.getDeclaredMethod(md.getName(),md.getArgumentTypes());
Object ob=m.invoke(couple.getReceiver(),md.getArguments());
changeTransferTo(new ReturnTransfer(mt,ob));
} catch(Exception e){
changeTransferTo(new ExceptionTransfer(mt.getID(),e));
}
return;
} catch (ClassCastException e){ }
try {
try {
ReturnTransfer rt=(ReturnTransfer)o;
//System.out.println ("Return transfer");
Sender.Returner<Object> retu=couple.getSender().getReturner(rt.getID());
retu.getCountDownLatch().countDown();
retu.getExchanger().exchange(rt.getReturnedValue());
rt.getID().destroy();
} catch(InterruptedException e){
conn.exceptionEncountered(e,this);
}
return;
} catch (ClassCastException e){ }
try {
ExceptionTransfer et=(ExceptionTransfer) o;
conn.exceptionEncountered(et.getException(),this);
et.getID().destroy();
return;
} catch (ClassCastException e){ }
if (!(o instanceof NullTransfer))
conn.exceptionEncountered(new NullPointerException ("Unresolved object received - "+o),this);
}
| 7 |
public String getState() {
if(isValidState(this.state)){
return this.state;
}
return null;
}
| 1 |
public InnerClassInfo[] getExtraClasses() {
if ((status & INNERCLASSES) == 0)
loadInfo(INNERCLASSES);
return extraClasses;
}
| 1 |
public void relayerMessage(String user, long mesID){
int index = getMessageIndexFromID(recentMessages, mesID);
if(index != -1 ){
recentMessages.get(index).addAuthors(user);
} else {
int i = 0;
List<Message> old = null;
while(index == -1 && i < logs.size()){
old = loadLog(logs.get(i));
index = getMessageIndexFromID(old, mesID);
}
if(i<logs.size() && old != null){
old.get(index).addAuthors(user);
} else {
System.out.println("ERROR : message not found in database");
}
}
System.out.println("message relayé");
}
| 5 |
public void compExecTime() {
double newExeTime;
double newCost;
dEval = 0;
dTime = 0;
dCost = 0;
for (int i = 0; i < iClass; i++) {
newExeTime = 0;
// System.out.print("Cost[" + i + "]");
for (int j = 0; j < iSite; j++) {
if (dmAlloc[i][j] != -1) {
if (dmAlloc[i][j] < 1) {
newExeTime = 0;
} else {
newExeTime = (dmDist[i][j] * dmPrediction[i][j])
/ dmAlloc[i][j];
if (newExeTime > dDeadline + 1) {
newExeTime = Double.MAX_VALUE;
}
}
}
if (newExeTime > dDeadline + 1) {
// System.out.println("newExeTime - dDeadline="+ (newExeTime
// - dDeadline -1));
newCost = Double.MAX_VALUE;
} else {
newCost = dmDist[i][j] * dmPrediction[i][j]
* daPrice[j];
}
dTime += newExeTime;
dCost += newCost;
dEval += dmCost[i][j] - dCost;
dmExeTime[i][j] = newExeTime;
dmCost[i][j] = newCost;
// System.out.print(dmCost[i][j] + ", ");
}
// System.out.println();
}
for (int i = 0; i < iClass; i++) {
System.out.print("Time[" + i + "]");
for (int j = 0; j < iSite; j++) {
System.out.print(dmExeTime[i][j] + ", ");
}
System.out.println();
}
// System.out.println("AllTime = " + dTime + " AllCost = " + dCost);
// System.out.println();
}
| 8 |
private void setInvisibility(boolean invisible) {
Geometry geo = (Geometry)spatial;
MatParam param = geo.getMaterial().getParam("Diffuse");
ColorRGBA c;
if(param != null) {
c = (ColorRGBA)param.getValue();
} else {
c = ColorRGBA.White;
}
if(geo.getMaterial().getMaterialDef().getMaterialParam("Diffuse") != null) {
geo.getMaterial().setColor("Diffuse", new ColorRGBA(c.r, c.b, c.g, invisible ? 0.3f : 1f));
} else if(geo.getMaterial().getMaterialDef().getMaterialParam("Color") != null) {
geo.getMaterial().setColor("Color", new ColorRGBA(c.r, c.b, c.g, invisible ? 0.3f : 1f));
}
if(invisible) {
geo.getMaterial().getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha);
geo.setQueueBucket(RenderQueue.Bucket.Transparent);
} else {
geo.getMaterial().getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Off);
geo.setQueueBucket(RenderQueue.Bucket.Opaque);
}
isInvisible = invisible;
}
| 6 |
public void reload() {
if (!new File(plugin.getDataFolder(), "config.yml").exists()) {
plugin.saveDefaultConfig();
}
plugin.reloadConfig();
configLoader = (YamlConfiguration) plugin.getConfig();
}
| 1 |
public DbHelper() throws ClassNotFoundException {
Class.forName("org.sqlite.JDBC");
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:" + DATABASE_NAME);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
// finally
// {
// try
// {
// if(connection != null)
// connection.close();
// }
// catch(SQLException e)
// {
// // connection close failed.
// System.err.println(e);
// }
// }
}
| 1 |
void drawChip(Graphics g) {
int i;
Font f = new Font("SansSerif", 0, 10 * csize);
g.setFont(f);
FontMetrics fm = g.getFontMetrics();
for (i = 0; i != getPostCount(); i++) {
Pin p = pins[i];
setVoltageColor(g, volts[i]);
Point a = p.post;
Point b = p.stub;
drawThickLine(g, a, b);
p.curcount = updateDotCount(p.current, p.curcount);
drawDots(g, b, a, p.curcount);
if (p.bubble) {
g.setColor(sim.whiteBackground()
? Color.white : Color.black);
drawThickCircle(g, p.bubbleX, p.bubbleY, 1);
g.setColor(lightGrayColor);
drawThickCircle(g, p.bubbleX, p.bubbleY, 3);
}
g.setColor(whiteColor);
int sw = fm.stringWidth(p.text);
g.drawString(p.text, p.textloc.x - sw / 2,
p.textloc.y + fm.getAscent() / 2);
if (p.lineOver) {
int ya = p.textloc.y - fm.getAscent() / 2;
g.drawLine(p.textloc.x - sw / 2, ya, p.textloc.x + sw / 2, ya);
}
}
g.setColor(needsHighlight() ? selectColor : lightGrayColor);
drawThickPolygon(g, rectPointsX, rectPointsY, 4);
if (clockPointsX != null) {
g.drawPolyline(clockPointsX, clockPointsY, 3);
}
for (i = 0; i != getPostCount(); i++) {
drawPost(g, pins[i].post.x, pins[i].post.y, nodes[i]);
}
}
| 7 |
public void analyze(String source) {
int originalSize = source.length();
HtmlCompressor compressor = getCleanCompressor();
String compResult = compressor.compress(source);
printHeader();
System.out.println(formatLine("Compression disabled", originalSize, originalSize, originalSize));
int prevSize = originalSize;
//spaces inside tags
System.out.println(formatLine("All settings disabled", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove comments
compressor.setRemoveComments(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Comments removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove mulispaces
compressor.setRemoveMultiSpaces(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Multiple spaces removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove intertag spaces
compressor.setRemoveIntertagSpaces(true);
compResult = compressor.compress(source);
System.out.println(formatLine("No spaces between tags", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove min surrounding spaces
compressor.setRemoveSurroundingSpaces(HtmlCompressor.BLOCK_TAGS_MIN);
compResult = compressor.compress(source);
System.out.println(formatLine("No surround spaces (min)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove max surrounding spaces
compressor.setRemoveSurroundingSpaces(HtmlCompressor.BLOCK_TAGS_MAX);
compResult = compressor.compress(source);
System.out.println(formatLine("No surround spaces (max)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove all surrounding spaces
compressor.setRemoveSurroundingSpaces(HtmlCompressor.ALL_TAGS);
compResult = compressor.compress(source);
System.out.println(formatLine("No surround spaces (all)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//remove quotes
compressor.setRemoveQuotes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Quotes removed from tags", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//link attrib
compressor.setRemoveLinkAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("<link> attr. removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//style attrib
compressor.setRemoveStyleAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("<style> attr. removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//script attrib
compressor.setRemoveScriptAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("<script> attr. removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//form attrib
compressor.setRemoveFormAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("<form> attr. removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//input attrib
compressor.setRemoveInputAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("<input> attr. removed", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//simple bool
compressor.setSimpleBooleanAttributes(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Simple boolean attributes", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//simple doctype
compressor.setSimpleDoctype(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Simple doctype", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//js protocol
compressor.setRemoveJavaScriptProtocol(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Remove js pseudo-protocol", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//http protocol
compressor.setRemoveHttpProtocol(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Remove http protocol", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//https protocol
compressor.setRemoveHttpsProtocol(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Remove https protocol", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
//inline css
try {
compressor.setCompressCss(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Compress inline CSS (YUI)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
} catch (NoClassDefFoundError e){
System.out.println(formatEmptyLine("Compress inline CSS (YUI)"));
}
if(jsCompressor.equals(HtmlCompressor.JS_COMPRESSOR_YUI)) {
//inline js yui
try {
compressor.setCompressJavaScript(true);
compResult = compressor.compress(source);
System.out.println(formatLine("Compress inline JS (YUI)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
} catch (NoClassDefFoundError e){
System.out.println(formatEmptyLine("Compress inline JS (YUI)"));
}
} else {
//inline js yui
try {
compressor.setCompressJavaScript(true);
compressor.setJavaScriptCompressor(new ClosureJavaScriptCompressor());
compResult = compressor.compress(source);
System.out.println(formatLine("Compress JS (Closure)", originalSize, compResult.length(), prevSize));
prevSize = compResult.length();
} catch (NoClassDefFoundError e){
System.out.println(formatEmptyLine("Compress JS (Closure)"));
}
}
printFooter();
}
| 4 |
public void setSomeList(List<String> someList) {
this.someList = someList;
}
| 0 |
public int[] searchRange(int[] nums, int target) {
int[] pos = new int[]{-1, -1};
int start = 0, end = nums.length-1;
while(start < end) {
int mid = start + (end-start)/2;
if(nums[mid] < target) {
start = mid + 1;
} else {
end = nums[mid]>target?mid-1:mid;
}
}
if(nums[start] != target) {
return pos;
}
pos[0] = start;
end = nums.length-1;
while(start < end-1) {
int mid = start + (end-start)/2;
if(nums[mid] > target) {
end = mid -1;
} else {
start = mid;
}
}
pos[1] = nums[end]==target?end:start;
return pos;
}
| 7 |
public void update(int delta, boolean beat, int bpm) {
this.bpm = bpm;
if (beat) {
altBeat++;
if (game.getCurrentLevel().getLevelNumber() > 0) {
xPosition++;
}
if (altBeat % 4 == 0)
setupLavaGlow = true;
}
ArrayList<TileEffect> toRemove = new ArrayList<TileEffect>();
for (TileEffect t : tileEffectList) {
t.update(delta);
if (t.hasExpired()) {
toRemove.add(t);
Tile tile = tileMap.get(new Point(t.getX(), t.getY()));
tile.setCurrentlyHot(false);
}
}
for (ProjectileEmitter emitter : projectileEmitters) {
emitter.update(delta, beat, bpm);
}
Iterator<Projectile> projectileIterator = projectiles.iterator();
while (projectileIterator.hasNext()) {
Projectile projectile = projectileIterator.next();
if (projectile.hasExpired()) {
projectileIterator.remove();
} else {
projectile.update(delta);
}
}
tileEffectList.removeAll(toRemove);
}
| 8 |
public static Boolean[] wordsTrusts(boolean[] trusts, Boolean[] boundaries) {
if (boundaries.length == 0) {
// Trust anything with no boundaries
return new Boolean[] {true};
}
else {
List<Boolean> wordsTrusts = new LinkedList<Boolean>();
for (int i = 0; i < boundaries.length; i++) {
// Every time we see a boundary, note the trust of the word
// to its left
if (boundaries[i]) {
wordsTrusts.add(trusts[i]);
}
}
// Always add the last word as trusted (its boundary is the end
// of the utterance
wordsTrusts.add(true);
return wordsTrusts.toArray(DUMMY_BOOLEAN_ARRAY);
}
}
| 3 |
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT: Kontroller.left = true;
break;
case KeyEvent.VK_RIGHT: Kontroller.right = true;
break;
case KeyEvent.VK_UP: Kontroller.up = true;
break;
case KeyEvent.VK_DOWN: Kontroller.down = true;
break;
case KeyEvent.VK_C: Kontroller.c = true;
break;
case KeyEvent.VK_X: Kontroller.x = true;
}
}
| 6 |
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return String.class;
case 1:
return Integer.class;
case 2:
return Integer.class;
case 3:
return Integer.class;
case 4:
return Integer.class;
case 5:
return Integer.class;
case 6:
return Integer.class;
default:
return super.getColumnClass(columnIndex);
}
}
| 8 |
@Override
public List<CommandEntity> findCommandByLawnMowerIndex(LawnInformationVO information, int index) {
if (information instanceof TextFileLawnInformationVO) {
TextFileLawnInformationVO textFileInformation = (TextFileLawnInformationVO) information;
// Reading from file
setFileToRead(Paths.get(textFileInformation.getFilePath()));
if (Files.exists(getFileToRead())) {
try{
setReader(Files.newBufferedReader(
getFileToRead(), Charset.defaultCharset()));
return processLines(index);
}
catch (IOException exception) {
if (getLogger().isErrorEnabled()) {
getLogger()
.error("Error while opening file " + getFileToRead(), exception);
}
throw new RuntimeException("Error while opening file", exception);
}
finally
{
if(getReader() != null)
{
try {
getReader().close();
} catch (IOException e) {
if (getLogger().isErrorEnabled()) {
getLogger()
.error("Error while closing file " + getFileToRead(), e);
}
throw new RuntimeException("Error while closing file", e);
}
}
}
}
}
return null;
}
| 7 |
public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (end()) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
}
| 6 |
private Vector<String> createRankcapVector(int rank) {
Vector<String> rankcapVector = new Vector<String>();
if (rank<4)
{
rankcapVector.add("11");
rankcapVector.add("10");
rankcapVector.add("9");
rankcapVector.add("6");
rankcapVector.add("3");
}
else if (rank<7)
{
rankcapVector.add("11");
rankcapVector.add("10");
rankcapVector.add("9");
rankcapVector.add("6");
}
else if (rank<10)
{
rankcapVector.add("11");
rankcapVector.add("10");
rankcapVector.add("9");
}
else if (rank<11)
{
rankcapVector.add("11");
rankcapVector.add("10");
}
else if (rank<12)
{
rankcapVector.add("11");
}
else if (rank<13)
{
rankcapVector.add("12");
}
return rankcapVector;
}
| 6 |
public PrimitiveOperator combineMidNLeftOnLeft(PrimitiveOperator other) {
boolean[] newTruthTable = new boolean[8];
// the other gate is on the left side - on the MSB
newTruthTable[0] = truthTable[((other.truthTable[0]) ? 4 : 0) | 0]; //000
newTruthTable[1] = truthTable[((other.truthTable[0]) ? 4 : 0) | 1]; //001
newTruthTable[2] = truthTable[((other.truthTable[2]) ? 4 : 0) | 2]; //010
newTruthTable[3] = truthTable[((other.truthTable[2]) ? 4 : 0) | 3]; //011
newTruthTable[4] = truthTable[((other.truthTable[1]) ? 4 : 0) | 0]; //100
newTruthTable[5] = truthTable[((other.truthTable[1]) ? 4 : 0) | 1]; //101
newTruthTable[6] = truthTable[((other.truthTable[3]) ? 4 : 0) | 2]; //110
newTruthTable[7] = truthTable[((other.truthTable[3]) ? 4 : 0) | 3]; //111
return new PrimitiveOperator(newTruthTable);
}
| 8 |
@Override
public String toString(){
switch(status){
case 0:
return "["+formatDate(new Date())+"]"
+"[Unapproved]"+getSender().getName()
+": /"+getCommand();
case 1:
if(getOverseer() != null && getCompletionTime() != null)
return "["+formatDate(getCompletionTime())+"]"
+"[Approved: "+getOverseer().getName()+"]"
+getSender().getName()+": /"+getCommand();
case 2:
if(getCompletionTime() != null)
return "["+formatDate(getCompletionTime())+"]"
+"[Cancelled]"+getSender().getName()
+": "+getCommand();
case 3:
if(getOverseer() != null && getCompletionTime() != null)
return "["+formatDate(getCompletionTime())+"]"
+"[Denied: "+getOverseer().getName()+"]"
+getSender().getName()+": /"+getCommand();
}
return "malformed command";
}
| 9 |
private static ArrayList<int[]> readOrWriteNextRLE(RunLengthEncoding rle)
throws IOException, ClassNotFoundException {
if (WRITE_MODE) {
encodeRLE(rle, os);
return rleToList(rle);
} else {
return decodeRLE(is);
}
}
| 1 |
public boolean getBoolean(){
String value = this.value.trim().toLowerCase();
if( "true".equals( value ))
return true;
if( "on".equals( value ))
return true;
if( "1".equals( value ))
return true;
if( "yes".equals( value ))
return true;
if( "false".equals( value ))
return false;
if( "off".equals( value ))
return false;
if( "0".equals( value ))
return false;
if( "no".equals( value ))
return false;
throw new XException( "not a boolean: " + value );
}
| 8 |
int sizeOfNextSubPiece(String content) {
if (content.charAt(0) != openingBracket)
return -1;
int openBrackets = 0;
char c;
char[] chars = content.toCharArray();
for (int i = 1; i < chars.length; i++) {
c = chars[i];
if (c == openingBracket)
openBrackets++;
if (c == closingBracket) {
openBrackets--;
if (openBrackets == -1)
return i;
}
}
return content.lastIndexOf(closingBracket);
}
| 5 |
public int getMostEast() {
for (int c = matrix.length - 1; c >= 0; c--) {
for (int r = 0; r < matrix.length; r++) {
if (checkSlot(r, c))
return c;
}
}
return -1;
}
| 3 |
private Rectangle2D createShadow(RectangularShape bar, double xOffset,
double yOffset, RectangleEdge base, boolean pegShadow) {
double x0 = bar.getMinX();
double x1 = bar.getMaxX();
double y0 = bar.getMinY();
double y1 = bar.getMaxY();
if (base == RectangleEdge.TOP) {
x0 += xOffset;
x1 += xOffset;
if (!pegShadow) {
y0 += yOffset;
}
y1 += yOffset;
}
else if (base == RectangleEdge.BOTTOM) {
x0 += xOffset;
x1 += xOffset;
y0 += yOffset;
if (!pegShadow) {
y1 += yOffset;
}
}
else if (base == RectangleEdge.LEFT) {
if (!pegShadow) {
x0 += xOffset;
}
x1 += xOffset;
y0 += yOffset;
y1 += yOffset;
}
else if (base == RectangleEdge.RIGHT) {
x0 += xOffset;
if (!pegShadow) {
x1 += xOffset;
}
y0 += yOffset;
y1 += yOffset;
}
return new Rectangle2D.Double(x0, y0, (x1 - x0), (y1 - y0));
}
| 8 |
public static void init() throws IOException {
for (int i = 0; i < runAnimationLeft.length; i++) {
runAnimationLeft[i] = ((BufferedImage) image).getSubimage(i * 143, 0, 143, 178);
runAnimationRight[i] = ((BufferedImage) image).getSubimage(i * 143, 0, 143, 178);
}
image = ImageIO.read(ClassLoader.getSystemClassLoader().getResourceAsStream("resources/img/skel_attack.png"));
for (int i = 0; i < attackAnimationLeft.length; i++) {
attackAnimationLeft[i] = ((BufferedImage) image).getSubimage(i * 173, 0, 173, 167);
attackAnimationRight[i] = ((BufferedImage) image).getSubimage(i * 173, 0, 173, 167);
}
image = ImageIO.read(ClassLoader.getSystemClassLoader().getResourceAsStream("resources/img/skel_die.png"));
for (int i = 0; i < dieAnimationLeft.length; i++) {
dieAnimationLeft[i] = ((BufferedImage) image).getSubimage(i * image.getWidth(null) / dieAnimationLeft.length, 0, image.getWidth(null) / dieAnimationLeft.length, image.getHeight(null));
dieAnimationRight[i] = ((BufferedImage) image).getSubimage(i * image.getWidth(null) / dieAnimationLeft.length, 0, image.getWidth(null) / dieAnimationLeft.length, image.getHeight(null));
}
invertAnimation(attackAnimationLeft);
invertAnimation(dieAnimationLeft);
invertAnimation(runAnimationLeft);
}
| 3 |
@EventHandler
public void playerMove(PlayerMoveEvent event) {
PigTeam team = null;
for (CTFTeam t : Teams) {
if (t.inTeam( CTFPlugin.getTeamPlayer(event.getPlayer()) )) {
team = (PigTeam) t;
break;
}
}
if (team == null){
return;
}
Goal goal = team.getGoal();
if (goal == null){
return;
}
if (team.getGoal().isInGoal(event.getTo())){
if (team.getGoal().isValidScore(CTFPlugin.getTeamPlayer(event.getPlayer()))) {
team.addToScore(1);
System.out.println("GOOOAAALLL!");
}
}
}
| 6 |
public int specialHash(){
// EDebug.print(myAutoPoint.hashCode() + getText().hashCode());
return myAutoPoint == null? -1 : myAutoPoint.hashCode() + this.getText().hashCode();
}
| 1 |
public static void main(String[] args) {
List<String> list = new ArrayList<String>(
Arrays.asList("cat", "dog", "horse")
);
System.out.println(list);
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
it.remove();
System.out.println(list);
}
}
| 1 |
public void addClassDoc(ClassDoc classdoc) {
if (classdoc == null) {
return;
}
addClass(classdoc, allClasses);
if (classdoc.isOrdinaryClass()) {
addClass(classdoc, ordinaryClasses);
} else if (classdoc.isException()) {
addClass(classdoc, exceptions);
} else if (classdoc.isEnum()) {
addClass(classdoc, enums);
} else if (classdoc.isAnnotationType()) {
addClass(classdoc, annotationTypes);
} else if (classdoc.isError()) {
addClass(classdoc, errors);
} else if (classdoc.isInterface()) {
addClass(classdoc, interfaces);
}
}
| 7 |
private boolean add() throws UnsupportedEncodingException {
if(addStoreName == null || addStoreName.isEmpty())
return false ;
if(addStoreAddr == null || addStoreAddr.isEmpty())
return false ;
String tempName = new String(addStoreName.getBytes("ISO-8859-1"),"UTF-8") ;
String tempAddr = new String(addStoreAddr.getBytes("ISO-8859-1"),"UTF-8") ;
Session se = HibernateSessionFactory.getSession() ;
Criteria category_cri = se.createCriteria(Store.class) ;
category_cri.add(Restrictions.eq("name", tempName)) ;
if(!category_cri.list().isEmpty())
{
se.close() ;
return false ;
}
Transaction tran = se.beginTransaction() ;
tran.begin() ;
Store newStore = new Store() ;
newStore.setName(tempName) ;
newStore.setAddress(tempAddr) ;
se.save(newStore) ;
tran.commit() ;
se.close() ;
return true ;
}
| 5 |
IA(Parametre param){
this.listePossibles = new ListeCombinaison(param);
this.derniereCombiJouee = null;
}
| 0 |
public void makePersistentHumanProp() {
try {
this.humanProp = (HumanProp) cache.get("humanProp");
LinkedHashMap<String, LinkedHashMap<String, String>> lhm = humanProp
.getRootMap();
Element root = new Element("root");
for (String key : lhm.keySet()) {
if (key == null || lhm.get(key) == null
|| lhm.get(key).get("t") == null)
continue;
Element child = new Element("h");
child.setText(key);
child.setAttribute(new Attribute("t", lhm.get(key).get("t")));
if (lhm.get(key).get("g") != null)
child.setAttribute(new Attribute("g", lhm.get(key).get("g")));
root.addContent(child);
}
XMLPersistence(root,"humanProp");
} catch (InvalidValueException ive) {
}
}
| 6 |
public Player getOppositePlayer(Player player) {
return player == this.playerWhite ? this.playerBlack : this.playerWhite;
}
| 1 |
protected double updateAll(CorefInput input, CorefOutput outputCorrect,
CorefOutput outputPredicted, double learningRate) {
double loss = 0d;
// Update all false positive and all false negative edges.
for (int rightMention = 0; rightMention < input.getNumberOfTokens(); ++rightMention) {
int correctClusterOfRightMention = outputCorrect
.getClusterId(rightMention);
int predictedClusterOfRightMention = outputPredicted
.getClusterId(rightMention);
// Correct and predicted left mentions in the latent structure.
int correctLeftMention = outputCorrect.getHead(rightMention);
int predictedLeftMention = outputPredicted.getHead(rightMention);
if (correctLeftMention != predictedLeftMention) {
if (predictedLeftMention == root)
// Decrement incorrectly predicted root.
updateFeatures(input.getFeatures(predictedLeftMention,
rightMention), -learningRate);
else if (correctLeftMention == root)
// Increment correct root from latent structure.
updateFeatures(
input.getFeatures(correctLeftMention, rightMention),
learningRate);
}
for (int leftMention = 0; leftMention < rightMention; ++leftMention) {
// Skip artificial root mention.
if (leftMention == root)
continue;
int correctClusterOfLeftMention = outputCorrect
.getClusterId(leftMention);
int predictedClusterOfLeftMention = outputPredicted
.getClusterId(leftMention);
if (correctClusterOfLeftMention != correctClusterOfRightMention) {
if (predictedClusterOfLeftMention == predictedClusterOfRightMention)
/*
* Mentions from different clusters put together in the
* same cluster (false positive) by the predicted
* structure.
*/
updateFeatures(
input.getFeatures(leftMention, rightMention),
-learningRate);
} else {
if (predictedClusterOfLeftMention != predictedClusterOfRightMention)
/*
* Mentions from the same cluster put in different
* clusters (false negative) by the predicted
* structured.
*/
updateFeatures(
input.getFeatures(leftMention, rightMention),
learningRate);
}
}
}
return loss;
}
| 9 |
private MoveEvalScore minimax(BoardMove node, int depth, int hole)
{
//if depth = 0 or node is a terminal node
if(depth == 0 || Kalah.gameOver(node.getBoard()))
{
//heuristic value of node
return new MoveEvalScore(hole,evalFunc.compareScoringWells(node, initialDepth % 2 == 0 ?node.getNextSide(): node.getNextSide().opposite(), hole));
}
//if side == ourSide, initialise bestValue to Integer.MIN_VALUE as we want to find maximum and vice versa.
MoveEvalScore bestValue = new MoveEvalScore(hole,node.getNextSide().equals(ourSide)?Integer.MIN_VALUE:Integer.MAX_VALUE);
//for each child node
int numHoles = node.getBoard().getNoOfHoles();
for(int i = 1; i <= numHoles; i++) //wells start a 1 (0 = scoring well)
{
//if there are seeds in well, then make a clone
if(node.getBoard().getSeeds(node.getNextSide(), i) > 0)
{
try
{
Board child = node.getBoard().clone();
//make the move
Move move = new Move(node.getNextSide(), i);
BoardMove boardMove = makeMove(child, move);
child = boardMove.getBoard();
//recursively call minimax on child
MoveEvalScore val = minimax(boardMove, depth - 1, i);
//if side == ourSide, find maximum, else find minimum.
bestValue = node.getNextSide().equals(ourSide)?max(bestValue, val):min(bestValue, val);
}
catch(Exception e)
{
display(e.toString());
}
}
}
//display("jksdfhsminimax(" + node.toString() + ", " + depth + ", " + side.toString() + ", " + hole + ", " + prevHole + ")");
//display(depth + "\nthis move: " + hole + ", prev move: " + prevHole + "\nBest score = " + bestValue.getScore() + "\nMove: " + bestValue.getMove());
if(node.getBoard().equals(root)) //if we are returning back to Main, then return best move and the hole it came from.
{
return bestValue;
}
else //return best score and current hole.
{
return new MoveEvalScore(hole, bestValue.getScore());
}
}
| 9 |
@SuppressWarnings("empty-statement")
public void Show(String uname)
{
User moves = new User();
ASCII_Art a = new ASCII_Art();
ASCII_Tiles t = new ASCII_Tiles();
//Display EQ
delayASC(a.getEq(), 250);
Options o = new Options();
t.setTilePairs(o.getTilePairs());
t.setIntTiles(t.getTilePairs() * 2);
t.createTileArray(t.getIntTiles());
s.match = new boolean [t.getIntTiles()];
s.misses = new int [t.getIntTiles()];
s.matches = new int [t.getIntTiles()];
//s.matchTile = new int [t.intTiles];
System.out.println("Choose a tile number (1-" + (t.getIntTiles()) + "):");
System.out.println("(0 exits to Main Menu)");
String prompt1 = "Please specify the first tile.";
String prompt2 = "Please specify the second tile.";
String msgSuccess = "Match!"; String msgFailure = "Sorry!";
count = 0;
while (s.countMatches < t.getTilePairs())
{
// Get user input for first tile guess
try
{
t1 = (moves.getUserInt(prompt1) - 1);
System.out.println(t.returnTile2(t.getArrTiles(t1)) + "\n");
//System.out.println(t.pairOne[t1] + "\n");
checkExit(t1, uname); checkMatched(t1, uname);
}
catch (Exception x)
{
if (t1 == -1)
{
checkExit(-1, uname);
}
System.out.println("Invalid guess (" + t.getTilePairs() * 2 + " is the max.)");
s.countMatches = t.getTilePairs();
count = t.getIntTiles();
continue;
}
// Get user input for second tile guess
try
{
t2 = (moves.getUserInt(prompt2) - 1);
System.out.println(t.returnTile2(t.getArrTiles(t2)) + "\n");
//System.out.println(t.pairTwo[t2] + "\n");
checkExit(t2, uname); checkMatched(t2, uname);
}
catch (Exception x)
{
if (t2 == -1)
{
checkExit(-1, uname);
}
System.out.println("Invalid guess (" + t.getTilePairs() * 2 + " is the max.)");
s.countMatches = t.getTilePairs();
count = t.getIntTiles();
continue;
}
/*
* Compare user input; if dupes are disabled, alternate checking can be used with current random tile allocation
* X|aBBa|chiasmus (e.g. t1 + t2 = 9)
*/
System.out.println("");
if (t.getArrTiles(t1) == t.getArrTiles(t2))
{
try
{
s.match[t1] = true;
s.matchTile[t1] = (t1);
s.match[t2] = true;
s.matches[t1] = (s.matches[t1] + 1);
s.matches[t2] = (s.matches[t2] + 1);
count++;
s.countMatches++;
System.out.println(msgSuccess + " " + a.getMusic());
}
catch (Exception x)
{
System.out.println("Error: " + x + "\n");
this.Show(uname);
}
}
else
{
try
{
s.match[t1] = false;
s.match[t2] = false;
s.misses[t1] = (s.misses[t1] + 1);
s.misses[t2] = (s.misses[t2] + 1);
System.out.println(msgFailure + " " + a.getFish());
}
catch (Exception x)
{
System.out.println("Error: " + x + "\n");
this.Show(uname);
}
}
/* Temp comment - should be moved to Scores menu
//Patrick
s.copyArrBoo(s.match, s.matchCopy);
s.sortBubbleBoo(s.matchCopy);
System.out.println("\n" + "Current Matches (sorted status): \n");
try
{
int c = 0;
for(boolean b : s.matchCopy)
{
//System.out.println("Tile Rank/Matched: " + (s.matchTile[c] + 1) + "/" + b);
System.out.println(b);
c++;
//Track number of tiles matched
if(b == true)
{
s.countMatches++;
}
}
}
catch (Exception x)
{
System.out.println("Exception: " + x);
}
//Dawn
s.copyArrInt(s.misses, s.missesCopy);
s.sortNumBubble(s.missesCopy);
int missesMax = s.missesCopy.length;
System.out.println("\n" + "Current Misses (sorted by most missed): \n");
try
{
for(int i = 1; i < missesMax; i++)
{
//System.out.println("Tile " + i + ": " + s.missesCopy[i]);
System.out.println(s.missesCopy[i]);
}
}
catch (Exception x)
{
// Ignore
}
*/
System.out.println("");
//If matched tiles = tilePairs, exit loop via Continue
if(s.countMatches == t.getTilePairs())
{
count = t.getIntTiles();
continue;
}
continue;
}
//Moves answerMoves = new Moves();
//answerMoves.getMatch(moves.getInput(prompt1, true), moves.getInput(prompt2, true));
/*do
{
Show(uname);
}
while (t1 != 0 || t2 != 0);*/
// Score answerScore = new Score();
// answerScore.getScore();
// long endTime = System.currentTimeMillis();
// for(endTime, startTime){
// long totalTime = endTime - startTime;
// System.out.println("Your play time is " + totalTime);
// }
}
| 9 |
private static int merge(Candidate[] K, int k, int i, int[] equvalenceLines,
boolean[] equivalence, int p) {
int r = 0;
Candidate c = K[0];
do {
int j = equvalenceLines[p];
int s = binarySearch(K, j, r, k);
if (s >= 0) {
// j was found in K[]
s = k + 1;
} else {
s = -s - 2;
if (s < r || s > k) s = k + 1;
}
if (s <= k) {
if (K[s+1].b > j) {
Candidate newc = new Candidate(i, j, K[s]);
K[r] = c;
r = s+1;
c = newc;
}
if (s == k) {
K[k+2] = K[k+1];
k++;
break;
}
}
if (equivalence[p]) {
break;
} else {
p++;
}
} while (true);
K[r] = c;
return k;
}
| 8 |
public void tick()
{
if (this.currentScene == null) return;
synchronized (this.appletRef.getPaintLock())
{
Enumeration localEnumeration = this.currentScene.getActors().elements();
while (localEnumeration.hasMoreElements())
{
Actor localActor = (Actor)localEnumeration.nextElement();
if (((localActor instanceof Robot)) && (((Robot)localActor).isDead()))
{
deactivateRobot((Robot)localActor);
}
else
{
localActor.tick();
}
}
if (this.currentRobot != null)
this.currentRobot.getDetailContainer();
return;
}
}
| 5 |
public Node<K> getRight() {
return right;
}
| 0 |
protected HttpClient getHttpClient() {
if (this.caHTTPClient == null) {
this.caHTTPClient = createHttpClient();
}
return this.caHTTPClient;
}
| 1 |
private void compareButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compareButtonActionPerformed
if (compareFile == null) {
JOptionPane.showMessageDialog(this, "Compare file hasn't been set.");
return;
}
if (baseFile == null) {
JOptionPane.showMessageDialog(this, "Base file has not been set.");
}
compareButton.setEnabled(false);
try {
File tmpFile = doCompare();
Desktop.getDesktop().open(tmpFile);
} catch (Throwable ex) {
JOptionPane.showMessageDialog(this, "Unable to open diff file!");
logger.log(Level.SEVERE, "Problems comparing file", ex);
}
compareButton.setEnabled(true);
}//GEN-LAST:event_compareButtonActionPerformed
| 3 |
public static TreeMap<String,ArrayList<Integer>> SplitAttribute(Table table, String attribute) {
int attrSize = table.RowSize();
int attrIndex = table.GetAttributeIndex(attribute);
if (attrIndex==-1) return null;
// treemap contains subsets of Attribute splitted by TargetAttribute
TreeMap<String,ArrayList<Integer>> attributeIndexes= new TreeMap<String,ArrayList<Integer>>();
for (int row=0; row<attrSize; row++) {
String SplitValue = table.GetCellContent(attrIndex, row);
// initial construction of subset for given spit value
if (!attributeIndexes.containsKey(SplitValue)) {
ArrayList<Integer> indexes = new ArrayList<Integer>();
indexes.add(row);
attributeIndexes.put(SplitValue, indexes);
// add more values to the subset
} else {
ArrayList<Integer> indexes = attributeIndexes.get(SplitValue);
indexes.add(row);
}
}
return attributeIndexes;
}
| 3 |
public boolean check(int px, int py)
{
return px > this.x && px < (this.x + this.w) && py > this.y && py < (this.y + this.h);
}
| 3 |
public static void saveChannels() {
if (Channels == null || ChannelsFile == null) {
return;
}
try {
getChannels().save(ChannelsFile);
} catch (IOException ex) {
Messenger.severe("Could not save config to " + ChannelsFile);
}
}
| 3 |
private File toFile(final Properties azotProperties, final String key, final String defaultValue) {
File file = null;
if (azotProperties.getProperty(key) != null) {
try {
final String fileName = azotProperties.getProperty(key);
if(fileName != null) {
file = new File(fileName);
if(!file.exists()) {
file.mkdirs();
}
}
} catch (Exception e) {
e.printStackTrace();
file = null;
}
}
if (file == null) {
file = new File(defaultValue);
}
return file;
}
| 5 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ModifyMethodObjectView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModifyMethodObjectView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModifyMethodObjectView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModifyMethodObjectView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ModifyMethodObjectView().setVisible(true);
}
});
}
| 6 |
public Component getEditorComponent(final PropertyEditor editor)
{
String[] tags = editor.getTags();
String text = editor.getAsText();
if (editor.supportsCustomEditor())
{
return editor.getCustomEditor();
}
else if (tags != null)
{
// make a combo box that shows all tags
final JComboBox comboBox = new JComboBox(tags);
comboBox.setSelectedItem(text);
comboBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getStateChange() == ItemEvent.SELECTED)
editor.setAsText((String) comboBox.getSelectedItem());
}
});
return comboBox;
}
else
{
final JTextField textField = new JTextField(text, 10);
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void insertUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void removeUpdate(DocumentEvent e)
{
try
{
editor.setAsText(textField.getText());
}
catch (IllegalArgumentException exception)
{
}
}
public void changedUpdate(DocumentEvent e)
{
}
});
return textField;
}
}
| 5 |
private boolean r_Step_4() {
int among_var;
int v_1;
// (, line 140
// [, line 141
ket = cursor;
// substring, line 141
among_var = find_among_b(a_7, 18);
if (among_var == 0)
{
return false;
}
// ], line 141
bra = cursor;
// call R2, line 141
if (!r_R2())
{
return false;
}
switch(among_var) {
case 0:
return false;
case 1:
// (, line 144
// delete, line 144
slice_del();
break;
case 2:
// (, line 145
// or, line 145
lab0: do {
v_1 = limit - cursor;
lab1: do {
// literal, line 145
if (!(eq_s_b(1, "s")))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// literal, line 145
if (!(eq_s_b(1, "t")))
{
return false;
}
} while (false);
// delete, line 145
slice_del();
break;
}
return true;
}
| 9 |
public static PropertyResource getInstance(String propPath)
{
if (PROPERTY_RESOURCE == null)
{
PROPERTY_RESOURCE = new PropertyResource(propPath);
}
return PROPERTY_RESOURCE;
}
| 1 |
public void initEdge(){
for(Node n : this.getNodes()){
int x = Integer.parseInt(n.name.split(":")[0]);
int y = Integer.parseInt(n.name.split(":")[1]);
if(n.name.split(":")[2].equals("void")){
Node otherNode = this.getNode(x-1 + " : " + y );
if(otherNode != null){
if(!otherNode.name.equals("wall")){
}
}
}
}
}
| 4 |
void incrementalThreadStart() {
incrementalEvents = new Vector<ImageLoaderEvent>();
incrementalThread = new Thread("Incremental") {
public void run() {
// Draw the first ImageData increment.
while (incrementalEvents != null) {
// Synchronize so we don't try to remove when the vector is null.
synchronized (ImageAnalyzer.this) {
if (incrementalEvents != null) {
if (incrementalEvents.size() > 0) {
ImageLoaderEvent event = (ImageLoaderEvent) incrementalEvents.remove(0);
if (image != null) image.dispose();
image = new Image(display, event.imageData);
imageData = event.imageData;
imageCanvasGC.drawImage(
image,
0,
0,
imageData.width,
imageData.height,
imageData.x,
imageData.y,
imageData.width,
imageData.height);
} else {
yield();
}
}
}
}
display.wake();
}
};
incrementalThread.setDaemon(true);
incrementalThread.start();
}
| 4 |
public static void main(String[] args)
{
int distinct = 0, words = 0, processed = 0;
int minlen = Integer.parseInt(args[0]);
String lastWordInserted = null;
String filename = args[1];
BinarySearchST<String, Integer> st = new BinarySearchST<String, Integer>(
10000);
try
{
BufferedReader input = new BufferedReader(new FileReader(filename));
// compute frequency counts
String line;
while ((line = input.readLine()) != null)
{
String keys[] = line.split(" +");
for (int i = 0; i < keys.length; i++)
{
if (keys[i].length() < minlen)
continue;
words++;
Integer count = st.get(keys[i]);
if (count != null)
st.put(keys[i], count + 1);
else
{
lastWordInserted = keys[i];
processed = words;
st.put(keys[i], 1);
distinct++;
}
}
}
input.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(1);
}
// find a key with the highest frequency count
String max = "";
st.put(max, 0);
for (String word : st.keys())
{
if (st.get(word) > st.get(max))
max = word;
}
StdOut.println("Minimum length : " + minlen);
StdOut.println("Word with the maximum frequency : " + max);
StdOut.println("Frequency : " + st.get(max));
StdOut.println("distinct = " + distinct);
StdOut.println("words = " + words);
StdOut.println("Last word Inserted : " + lastWordInserted);
StdOut.println("No. of words processed until '" + lastWordInserted
+ "' was inserted : " + processed);
// StdOut.println(a);
// System.out.println("Number of comparisions = " + st.cmp);
}
| 7 |
@Override
public void mouseWheelMoved(MouseWheelEvent event) {
if (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
int amt = event.getUnitsToScroll();
JScrollBar bar = event.isShiftDown() ? mHSB : mVSB;
bar.setValue(bar.getValue() + amt * bar.getUnitIncrement());
}
}
| 2 |
@Override
public DataBuffers getFileData(HTTPRequest request) throws HTTPException
{
// split the uri by slashes -- the first char is always /!!
final String[] url = request.getUrlPath().split("/");
// first thing is to check for servlets
if(url.length > 1)
{
final Class<? extends SimpleServlet> servletClass = config.getServletMan().findServlet(url[1]);
if(servletClass != null)
{
return executeServlet(request,servletClass);
}
}
// not a servlet, so it must be a file path
final String reqPath = assembleFilePath(request);
DataBuffers buffers = checkAndExecuteCGI(reqPath,request,null);
if(buffers != null)
return buffers;
final File pathFile = createFile(request, reqPath);
final File pageFile;
if(pathFile.isDirectory())
{
pageFile=config.getFileManager().createFileFromPath(config.getBrowsePage());
//TODO: check this: throw HTTPException.standardException(HTTPStatus.S500_INTERNAL_ERROR);
}
else
{
pageFile = pathFile;
}
final MIMEType mimeType = MIMEType.All.getMIMETypeByExtension(pageFile.getName());
try
{
buffers = new CWDataBuffers(); // before forming output, process range request
final Class<? extends HTTPOutputConverter> converterClass=config.getConverters().findConverter(mimeType);
if(converterClass != null)
{
buffers=config.getFileCache().getFileData(pageFile, null);
//checkIfModifiedSince(request,buffers); this is RETARDED!!!
HTTPOutputConverter converter;
try {
converter = converterClass.newInstance();
return new CWDataBuffers(converter.convertOutput(config, request, pathFile, HTTPStatus.S200_OK, buffers.flushToBuffer()), System.currentTimeMillis(), true);
}
catch (final Exception e) { }
return buffers;
}
else
{
return config.getFileCache().getFileData(pageFile, null);
}
}
catch(final HTTPException e)
{
buffers.close();
throw e;
}
}
| 9 |
public void displayAllCandidates() {
if (nakeds == null) {
System.out.println("No Candidates Stored");
return;
}
for (int i=0; i < nakeds.size(); i++) {
NakedCandidates current = nakeds.get(i);
System.out.println("Eval at Coordinate x="+current.x+", y="+current.y);
for (int j=0; j < current.values.size(); j++) {
System.out.print(current.values.get(j) + " ");
}
System.out.println();
}
}
| 3 |
public static String postHtml(String url,String charSet,Map<String,String> param){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = postForm(url,param);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity rspEntity = null;
if (httpResponse != null) {
rspEntity = httpResponse.getEntity();
String html = null;
try {
html = InputStreamUtils.inputStream2String(rspEntity.getContent(),charSet);
} catch (IOException e) {
e.printStackTrace();
}
return html;
}
else {
MyLog.logINFO("httpResponse is null!");
return "";
}
}
| 3 |
public static void main(String[] args) throws Exception
{
new Main(new File("."), args).start();
}
| 0 |
private String copyOrCatUrl(String dst, String src) {
if (src != null) {
if (src.startsWith("http://")) {
dst = src;
} else {
if (!src.startsWith("/")) {
dst += "/";
}
dst += src;
}
}
return dst;
}
| 3 |
protected void setProperty(Object object, String name, String value)
throws SQLException {
Class<?> type = object.getClass();
PropertyDescriptor[] descriptors;
try {
descriptors = Introspector.getBeanInfo(type)
.getPropertyDescriptors();
} catch (Exception ex) {
SQLException sqlException = new SQLException();
sqlException.initCause(ex);
throw sqlException;
}
List<String> names = new ArrayList<String>();
for (int i = 0; i < descriptors.length; i++) {
if (descriptors[i].getWriteMethod() == null) {
continue;
}
if (descriptors[i].getName().equals(name)) {
Method method = descriptors[i].getWriteMethod();
Class<?> paramType = method.getParameterTypes()[0];
Object param = toBasicType(value, paramType.getName());
try {
method.invoke(object, new Object[] {param});
}
catch (Exception ex) {
SQLException sqlException = new SQLException();
sqlException.initCause(ex);
throw sqlException;
}
return;
}
names.add(descriptors[i].getName());
}
throw new SQLException("No such property: " + name +
", exists. Writable properties are: " + names);
}
| 7 |
private boolean getShipCoords() {
System.out.println("INSIDE GET SHIP COORDS");
this.validPoints = 0;
this.pointsOnBoard = 0;
int size = this.shipSelected.getSize(); //Gets tje size of the Ship from class Ship
int orientation = this.shipSelected.getOrientation(); //Gets the orientation of the ship
//Gets coords
int x = this.shipSelected.getX();
int y = this.shipSelected.getY();
int[][] shipCoords = this.shipSelected.getCoords(); //Gets the cordinates of the selected ship
for (int i = 0; i < size; i++) {
if (orientation == 0) {
if ((x + i >= 0) && (x + i < 10)) {
if (this.myBoard[(x + i)][y].getIcon().equals(this.sea)) {
this.validPoints += 1;
}
shipCoords[this.pointsOnBoard][0] = (x + i);
shipCoords[this.pointsOnBoard][1] = y;
this.pointsOnBoard += 1;
System.out.println("VALID POINTS: " + validPoints);
System.out.println("POINTS ON BOARD: " + pointsOnBoard);
}
} else if ((y + i >= 0) && (y + i < 10)) {
if (this.myBoard[x][(y + i)].getIcon().equals(this.sea)) {
this.validPoints += 1;
}
shipCoords[this.pointsOnBoard][0] = x;
shipCoords[this.pointsOnBoard][1] = (y + i);
this.pointsOnBoard += 1;
}
}
this.shipSelected.setCoords(shipCoords);
boolean valid;
// boolean valid;
if (this.validPoints < size) {
valid = false;
} else {
valid = true;
}
return valid;
}
| 9 |
protected void demo11() throws IOException, UnknownHostException, CycApiException {
if (cycAccess.isOpenCyc()) {
Log.current.println("\nThis demo is not available in OpenCyc");
}
else {
Log.current.println("Demonstrating getImpreciseParaphrase api function.\n");
CycFormulaSentence formula = cycAccess.makeCycSentence(
"(#$forAll ?PERSON1\n" +
" (#$implies\n" +
" (#$isa ?PERSON1 #$Person)\n" +
" (#$thereExists ?PERSON\n" +
" (#$and\n" +
" (#$isa ?PERSON2 #$Person)\n" +
" (#$loves ?PERSON1 ?PERSON2)))))");
String paraphrase = cycAccess.getImpreciseParaphrase(formula);
Log.current.println("\nThe obtained imprecise paraphrase for\n" + formula + "\nis:\n" + paraphrase);
}
}
| 1 |
public Coordinate shiftTarget(int direction, Coordinate c) {
int shiftWide = 1;
switch(direction) {
case 0: return new Coordinate(c.getXCoordinate() ,c.getYCoordinate()+shiftWide);
case 1: return new Coordinate(c.getXCoordinate()-shiftWide,c.getYCoordinate()+shiftWide);
case 2: return new Coordinate(c.getXCoordinate()-shiftWide,c.getYCoordinate());
case 3: return new Coordinate(c.getXCoordinate()-shiftWide,c.getYCoordinate()-shiftWide);
case 4: return new Coordinate(c.getXCoordinate() ,c.getYCoordinate()-shiftWide);
case 5: return new Coordinate(c.getXCoordinate()+shiftWide,c.getYCoordinate()-shiftWide);
case 6: return new Coordinate(c.getXCoordinate()+shiftWide,c.getYCoordinate());
case 7: return new Coordinate(c.getXCoordinate()+shiftWide,c.getYCoordinate()+shiftWide);
default: return c;
}
}
| 8 |
@Override
public boolean isValid( PositionValidator validator )
{
if (coordinates==null) return false;
if (coordinates.size()==0) return false;
for ( List<List<Double>> linearRing : coordinates )
{
if (linearRing==null) return false;
if (linearRing.size()<4) return false;
for ( List<Double> position : linearRing )
{
if ( !validator.isValid(position) ) return false;
}
List<Double> first = linearRing.get(0);
List<Double> last = linearRing.get(linearRing.size()-1);
if ( !validator.isEquivalent(first,last) ) return false;
}
return super.isValid(validator);
}
| 8 |
public static JButton getDefenceThrowButton() {
if (defenceThrowButton == null) {
defenceThrowButton = new JButton("Throw");
defenceThrowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// int dice = (Integer) defenceSpinner.getValue();
int dice = ((Dice) defenceSpinner.getValue())
.getDiceNumber();
if (dice > (Integer) ((Dice) attackSpinner.getValue())
.getDiceNumber()
&& GameData.SELECTED_PROVINCE.getArmy() < 3) {
getGameLabel().setText(
"You can only defend with one army!");
}
else if (dice > GameData.TARGET_PROVINCE.getArmy()) {
getGameLabel()
.setText("You do not have enough armies!");
} else {
GameData.defenceResult = null;
GameData.defenceResult = RiskGame.diceThrow(dice);
int[] defenceArray = new int[dice];
defenceArray = GameData.defenceResult;
for (int i = 0; i < defenceArray.length; i++) {
if (dice == 1) {
int resultnum = defenceArray[0];
ImageIcon resultimg = GameData.dices[resultnum - 1]
.getDiceIcon();
defenceResultLabel1.setIcon(resultimg);
game.repaint();
} else if (dice == 2) {
int resultnum1 = defenceArray[0];
int resultnum2 = defenceArray[1];
ImageIcon resultimg1 = GameData.dices[resultnum1 - 1]
.getDiceIcon();
ImageIcon resultimg2 = GameData.dices[resultnum2 - 1]
.getDiceIcon();
defenceResultLabel1.setIcon(resultimg1);
defenceResultLabel2.setIcon(resultimg2);
game.repaint();
}
}
defenceThrowButton.setEnabled(false);
RiskGame.attackInitiated();
game.repaint();
}
}
});
defenceThrowButton.setBounds(SCREEN_WIDTH - 130, 550, 100, 100);
defenceThrowButton.setEnabled(false);
}
return defenceThrowButton;
}
| 7 |
public Tile getTile(int x, int y) {
for (int i = 0; i < tiles.size(); i++) {
if (tiles.get(i).getX() == x && tiles.get(i).getY() == y) {
return tiles.get(i);
}
}
return null;
}
| 3 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
int MOD = 1000000, MAX = 101;
int[][] dp = new int[MAX][MAX];
dp[0][0] = 1;
for (int i = 1; i < dp.length; i++) {
dp[i][0] = dp[i - 1][0];
for (int j = 1; j < MAX; j++)
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD;
}
while ((line = in.readLine()) != null && line.length() != 0) {
int[] nk = readInts(line);
int n = nk[0], k = nk[1];
if (n == 0 && k == 0)
break;
out.append(dp[k][n] + "\n");
}
System.out.print(out);
}
| 6 |
@Override
public void focusLost(FocusEvent e) {
recordRenderer(e.getComponent());
textArea.hasFocus = false;
}
| 0 |
public static <E extends Comparable <E>> void subsets(E[] array) {
if (array == null)
return;
HeapSort.sort(array);
for (int i = 0; i < array.length - 2; i++) {
if (array[i] != array[i + 1]) {
for (int j = i + 1; j < array.length - 1; j++) {
if (array[j] != array[j + 1]) {
for (int k = j + 1; k < array.length; k++) {
if (k == array.length - 1 || array[k] != array[k + 1])
System.out.println(array[i] + " " + array[j] + " " + array[k]);
}
}
}
}
}
}
| 8 |
protected JPanel createPicrossPanel(boolean fileOpened){
JPanel panel = new JPanel();
// Calculate Parameters
int leftColumnWidth = maxSize(picross.left) * pixelSize;
int leftColumnHeight = picross.left.size() * pixelSize;
int upColumnWidth = picross.up.size() * pixelSize;
int upColumnHeight = maxSize(picross.up) * pixelSize;
int bodyWidth = upColumnWidth;
int bodyHeight = leftColumnHeight;
int width = (leftColumnWidth + bodyWidth);
int height = (upColumnHeight + bodyHeight);
// Set Absolute Layout
panel.setLayout(null);
panel.setSize(width, height);
if(!fileOpened){
return panel;
}
// Initialize
JPanel emptyColumn = new JPanel();
leftColumn = new JPanel();
upColumn = new JPanel();
body = new JPanel();
// Set Listeners
if(picrossListener == null){
picrossListener = new PicrossListener();
}
body.addMouseListener(picrossListener);
body.addMouseMotionListener(picrossListener);
// Set Bounds
emptyColumn.setBounds(0, 0, (width - bodyWidth), (height - bodyHeight));
leftColumn.setBounds(0, (height - bodyHeight), leftColumnWidth, leftColumnHeight);
upColumn.setBounds((width - bodyWidth), 0, upColumnWidth, upColumnHeight);
body.setBounds((width - bodyWidth), (height - bodyHeight), bodyWidth, bodyHeight);
// Set Border
emptyColumn.setBorder(null);
leftColumn.setBorder(BorderFactory.createMatteBorder(boldLineThickness, boldLineThickness, boldLineThickness, 0, Color.black));
upColumn.setBorder(BorderFactory.createMatteBorder(boldLineThickness, boldLineThickness, 0, boldLineThickness, Color.black));
body.setBorder(boldLine);
// Set Background
emptyColumn.setBackground( null );
leftColumn.setBackground( hsb(28, 14, 100) );
upColumn.setBackground( hsb(28, 14, 100) );
body.setBackground( hsb(28, 4, 100) );
// Prepare for Next
JPanel numRow;
JPanel numBox;
List<JPanel> numCell;
// Set Number Rows on the Left Column
leftNumberCells = new ArrayList<List<JPanel>>();
leftColumn.setLayout(new GridLayout(leftColumnHeight/pixelSize, 1, 0, 0));
for(int i=0; i<leftColumnHeight/pixelSize; i++) {
numRow = new JPanel();
numRow.setBackground(null);
numRow.setBorder(normalLine);
numRow.setLayout(new GridLayout(1, leftColumnWidth/pixelSize, 0, 0));
numCell = new ArrayList<JPanel>();
for (int j=0; j<leftColumnWidth/pixelSize; j++) {
numBox = new JPanel();
numBox.setLayout(new GridLayout(1,1,0,0));
numBox.setBackground(null);
numBox.setBorder(BorderFactory.createMatteBorder(0,normalLineThickness,0,0,Color.black));
numBox.add(leftNumberLabel(j,i,leftColumnWidth/pixelSize));
numRow.add(numBox);
numCell.add(numBox);
}
leftColumn.add(numRow);
leftNumberCells.add(numCell);
}
// Set Number Rows on the Up Column
upNumberCells = new ArrayList<List<JPanel>>();
upColumn.setLayout(new GridLayout(1, upColumnWidth/pixelSize, 0, 0));
for(int i=0; i<upColumnWidth/pixelSize; i++) {
numRow = new JPanel();
numRow.setBackground(null);
numRow.setBorder(new LineBorder(Color.black, normalLineThickness));
numRow.setLayout(new GridLayout(upColumnHeight/pixelSize, 1, 0, 0));
numCell = new ArrayList<JPanel>();
for (int j=0; j<upColumnHeight/pixelSize; j++) {
numBox = new JPanel();
numBox.setLayout(new GridLayout(1,1,0,0));
numBox.setBackground(null);
numBox.setBorder(BorderFactory.createMatteBorder(normalLineThickness,0,0,0,Color.black));
numBox.add(upNumberLabel(j,i,upColumnHeight/pixelSize));
numRow.add(numBox);
numCell.add(numBox);
}
upColumn.add(numRow);
upNumberCells.add(numCell);
}
// Set Cells on the Body
cells = new ArrayList<JPanel>();
body.setLayout(new GridLayout(bodyHeight/pixelSize, bodyWidth/pixelSize, 0, 0));
for(int i=0; i<(bodyWidth*bodyHeight)/(pixelSize*pixelSize); i++) {
numBox = new JPanel();
numBox.add(new JLabel(new ImageIcon(ImageUtil.cellImage(PixelType.NOFILL))));
numBox.setLayout(new GridLayout(1,1,0,0));
numBox.setBackground(null);
numBox.setBorder(normalLine);
body.add(numBox);
cells.add(numBox);
}
// Add Children
panel.add(emptyColumn);
panel.add(leftColumn);
panel.add(upColumn);
panel.add(body);
return panel;
}
| 7 |
public String getDescription() {
return delegate.getDescription();
}
| 0 |
private void drawPiece(Graphics2D g2) {
if (piece == null) return;
Pos center = piece.getCenter();
for (int x = 0; x < piece.getWidth(); x++) {
for (int y = 0; y < piece.getHeight(); y++) {
if (piece.get(x, y)) {
int cx = x + posX - center.x;
int cy = y + posY - center.y;
g2.setColor(grid.pieceFits(posX, posY, piece)
? pieceFitColor: pieceColor);
g2.fillRect(cx * BLOCK_SIZE, cy * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
}
}
}
}
| 5 |
public Class<? extends Tag> getListType() {
if (type.getName().equals("java.lang.Class"))
return CompoundTag.class;
else
return type;
}
| 2 |
public void tryProcessNewVehicles(int time,Simulator sim) throws VehicleException, SimulationException {
if(time > Constants.CLOSING_TIME || time < 0)
throw new VehicleException("Time violate constraints");
// try create new vehicle
if(sim.newCarTrial()){
if(sim.smallCarTrial()){
count++;
Car sc = new Car("C"+ count, time, true);
processVehicle(time, sim, sc);
}else{
count++;
Car car = new Car("C" + count, time, false);
processVehicle(time, sim, car);
}
}
if(sim.motorCycleTrial()){
count++;
MotorCycle mc = new MotorCycle("MC" + count, time);
processVehicle(time, sim, mc);
}
}
| 5 |
public static PlayerChoice randomChoice() {
double i = Math.rint(Math.random() * 100);
if(i<33)
return createPlayerChoiceFromCode(ChoiceCode.P);
if(i>66)
return createPlayerChoiceFromCode(ChoiceCode.R);
return createPlayerChoiceFromCode(ChoiceCode.S);
}
| 2 |
public void checkpoint(SegmentInfos segmentInfos, boolean isCommit) throws IOException {
if (infoStream != null) {
message("now checkpoint \"" + segmentInfos.getCurrentSegmentFileName() + "\" [" + segmentInfos.size() + " segments " + "; isCommit = " + isCommit + "]");
}
// Try again now to delete any previously un-deletable
// files (because they were in use, on Windows):
deletePendingFiles();
// Incref the files:
incRef(segmentInfos, isCommit);
if (isCommit) {
// Append to our commits list:
commits.add(new CommitPoint(commitsToDelete, directory, segmentInfos));
// Tell policy so it can remove commits:
policy.onCommit(commits);
// Decref files for commits that were deleted by the policy:
deleteCommits();
} else {
final List<String> docWriterFiles;
if (docWriter != null) {
docWriterFiles = docWriter.openFiles();
if (docWriterFiles != null)
// We must incRef these files before decRef'ing
// last files to make sure we don't accidentally
// delete them:
incRef(docWriterFiles);
} else
docWriterFiles = null;
// DecRef old files from the last checkpoint, if any:
int size = lastFiles.size();
if (size > 0) {
for(int i=0;i<size;i++)
decRef(lastFiles.get(i));
lastFiles.clear();
}
// Save files so we can decr on next checkpoint/commit:
lastFiles.add(segmentInfos.files(directory, false));
if (docWriterFiles != null)
lastFiles.add(docWriterFiles);
}
}
| 7 |
public void setBulletTimer(long timer){
this.bulletTimer = timer;
}
| 0 |
public void run() {
try {
boolean running = true;
while (running) {
// Small delay to prevent spamming of the channel
Thread.sleep(_bot.getMessageDelay());
String line = (String) _outQueue.next();
if (line != null) {
_bot.sendRawLine(line);
}
else {
running = false;
}
}
}
catch (InterruptedException e) {
// Just let the method return naturally...
}
}
| 3 |
protected void calcFATSz() {
if (BPB_FATSz16 != 0) {
FATSz = BPB_FATSz16;
} else {
FATSz = BPB_FATSz32;
}
}
| 1 |
private int xoff(int dir) {
switch (dir) {
case 0:
case 7:
case 6:
return -1;
case 1:
case 5:
return 0;
case 2:
case 3:
case 4:
return 1;
}
return 0;
}
| 8 |
protected int possiblyAddColVar(CycVariable colVar) {
String col = colVar.toString();
int colIndex = -1;
List<String> columnNames = getColumnNamesUnsafe();
if ((colIndex = columnNames.indexOf(col)) < 0) {
columnNames.add(col);
for (List<Object> row : getRS()) {
row.add(null);
}
return columnNames.size() - 1;
}
return colIndex;
}
| 2 |
public JPasswordField getjPasswordFieldMdp() {
return jPasswordFieldMdp;
}
| 0 |
public static void printAll()
{
try
{
PreparedStatement stmt = Main.EMART_CONNECTION.prepareStatement("select * " +
"from martitem");
ResultSet rs = stmt.executeQuery();
System.out.println("Mart Items:");
while (rs.next())
{
System.out.println("Item:");
System.out.println(rs.getString("stock_number") + " | " + rs.getInt("warranty") + " | " + rs.getDouble("price") + " | " + rs.getString("category") + " | " + rs.getString("manufacturer") + " | " + rs.getString("model_number"));
System.out.println("descriptions:");
PreparedStatement desstmt = Main.EMART_CONNECTION.prepareStatement("select attribute, attribute_value from description where stock_number = ?");
desstmt.setString(1, rs.getString("stock_number"));
ResultSet desrs = desstmt.executeQuery();
while(desrs.next())
{
System.out.println(desrs.getString("attribute") + ": " + desrs.getString("attribute_value"));
}
System.out.println("accessory to:");
PreparedStatement accStmt = Main.EMART_CONNECTION.prepareStatement("select child_stock_number from accessory where parent_stock_number = ?");
accStmt.setString(1, rs.getString("stock_number"));
ResultSet accrs = accStmt.executeQuery();
while(accrs.next())
{
System.out.println(accrs.getString("child_stock_number"));
}
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
| 4 |
protected void setVisibleComponent(Component component) {
if (visibleComponent != null && visibleComponent != component && visibleComponent.getParent() == tabPane) {
visibleComponent.setVisible(false);
}
if (component != null && !component.isVisible()) {
component.setVisible(true);
}
visibleComponent = component;
}
| 5 |
@Override
public double[] calculateFractal3DWithoutPeriodicity(Complex pixel) {
iterations = 0;
double temp = 0;
Complex[] complex = new Complex[1];
complex[0] = new Complex(pixel);//z
Complex zold = new Complex();
Complex zold2 = new Complex();
if(parser.foundS()) {
parser.setSvalue(new Complex(complex[0]));
}
if(parser2.foundS()) {
parser2.setSvalue(new Complex(complex[0]));
}
if(parser.foundP()) {
parser.setPvalue(new Complex());
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex());
}
for(; iterations < max_iterations; iterations++) {
if((temp = complex[0].distance_squared(zold)) <= convergent_bailout) {
Object[] object = {iterations, complex[0], temp, zold, zold2};
double[] array = {Math.abs(out_color_algorithm.getResult3D(object)) - 100800, out_color_algorithm.getResult(object)};
return array;
}
zold2.assign(zold);
zold.assign(complex[0]);
function(complex);
if(parser.foundP()) {
parser.setPvalue(new Complex(zold));
}
if(parser2.foundP()) {
parser2.setPvalue(new Complex(zold));
}
}
Object[] object = {complex[0], zold};
double temp2 = in_color_algorithm.getResult(object);
double result = temp2 == max_iterations ? max_iterations : max_iterations + Math.abs(temp2) - 100820;
double[] array = {result, temp2};
return array;
}
| 9 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Option)) {
return false;
}
Option other = (Option) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
| 5 |
public Overview(Adrianna adrianna) {
super(new BorderLayout());
this.adrianna = adrianna;
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.LINE_AXIS));
topPanel.add(new JLabel("Directory"));
topPanel.add(Box.createHorizontalBox());
pathField = new JTextField(adrianna.getBaseDirectory().getAbsolutePath(), 10);
topPanel.add(pathField);
browseButton = new JButton("Browse...");
topPanel.add(browseButton);
add(topPanel, BorderLayout.NORTH);
model = new AdriannaTreeModel(adrianna);
final JTree tree = new JTree(model);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
Object selectedComponent = e.getNewLeadSelectionPath().getLastPathComponent();
if (selectedComponent instanceof VCardOnDisk) {
VCardOnDisk selectedCard = (VCardOnDisk) selectedComponent;
for (OverviewSelectionListener listener : selectionListeners) {
listener.cardChanged(selectedCard);
}
} else {
for (OverviewSelectionListener listener : selectionListeners) {
listener.cardChanged(null);
}
}
}
});
tree.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// Nothing to do.
}
@Override
public void mousePressed(MouseEvent e) {
// Nothing to do.
}
@Override
public void mouseExited(MouseEvent e) {
// Nothing to do.
}
@Override
public void mouseEntered(MouseEvent e) {
// Nothing to do.
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
e.consume();
Object selectedComponent = tree.getSelectionPath().getLastPathComponent();
if (selectedComponent instanceof VCardOnDisk) {
CardFrame cardFrame = new CardFrame();
cardFrame.setCardOnDisk((VCardOnDisk) selectedComponent);
cardFrame.setVisible(true);
}
}
}
});
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane, BorderLayout.CENTER);
validate();
}
| 5 |
@Override
public String getDesc() {
return "Default";
}
| 0 |
public void characters(char ch[], int start, int length) throws SAXException {
if (title) {
document.setTitle(new String(ch, start, length));
title = false;
}
if (dateline) {
document.setDateline(new String(ch, start, length));
dateline = false;
}
//we don't actually do anything here... this method can be removed
if (topics) {
//document.setTopicList(new String(ch, start, length));
//topics = false;
}
//dispose of places
if (places) {
places = false;
}
//"d" contains the names of topics
if (d && topics) {
document.addTopic(new String(ch, start, length));
d = false;
}
if (body) {
bodytext = bodytext + new String(ch, start, length);
}
}
| 7 |
public static void createDisplay() {
try {
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAttribs = new ContextAttribs(3,2).withProfileCore(true);
Display.setDisplayMode(new DisplayMode(1280, 800));
Display.create(pixelFormat,contextAttribs);
System.out.println("Window: " + Display.getWidth() + "*" + Display.getHeight());
} catch (LWJGLException e) {
e.printStackTrace();
}
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(0, Display.getWidth(),0, Display.getHeight(), -1,1);
// glMatrixMode(GL_MODELVIEW);
// glClearColor(0,0,0,1);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
int vao = glGenVertexArrays();
glBindVertexArray(vao);
// glLoadIdentity();
// glPushMatrix();
// {
// glTranslatef(320,100,0);
// Square screenStart = new Square(600,600);
// screenStart.setTexture(ResourceLoader.loadTexture("lolz/doge"));
// screenStart.render();
// }
// glPopMatrix();
Display.update();
try {
Keyboard.create();
Mouse.create();
} catch (LWJGLException e) {
e.printStackTrace();
}
}
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.