text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals("Next")){
SlideShow.this.counter++;
if(SlideShow.this.counter==SlideShow.this.numberPhotos)
SlideShow.this.counter=0;
SlideShow.this.slideArea.remove(picture);
SlideShow.this.slideArea.remove(SlideShow.this.nextBtn);
SlideShow.this.picture = SlideShow.this.photosEffect.get(SlideShow.this.counter);
SlideShow.this.slideArea.add(picture);
SlideShow.this.slideArea.add(SlideShow.this.nextBtn);
if(SlideShow.this.photos!=null){
SlideShow.this.photoNameLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getFilename());
SlideShow.this.captionLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getCaption());
SlideShow.this.dateLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getStringDate());
}
else{
SlideShow.this.photoNameLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getFilename());
SlideShow.this.captionLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getCaption());
SlideShow.this.dateLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getStringDate());
}
SlideShow.this.repaint();
}
if(action.equals("Previous")){
SlideShow.this.counter--;
if(SlideShow.this.counter==-1)
SlideShow.this.counter=SlideShow.this.numberPhotos-1;
SlideShow.this.slideArea.remove(picture);
SlideShow.this.slideArea.remove(SlideShow.this.nextBtn);
SlideShow.this.picture = SlideShow.this.photosEffect.get(SlideShow.this.counter);
SlideShow.this.slideArea.add(picture);
SlideShow.this.slideArea.add(SlideShow.this.nextBtn);
if(SlideShow.this.photos!=null){
SlideShow.this.photoNameLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getFilename());
SlideShow.this.captionLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getCaption());
SlideShow.this.dateLbl.setText(SlideShow.this.photosSlide.get(SlideShow.this.counter).photo.getStringDate());
}
else{
SlideShow.this.photoNameLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getFilename());
SlideShow.this.captionLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getCaption());
SlideShow.this.dateLbl.setText(SlideShow.this.photosSlideSearchResult.get(SlideShow.this.counter).getStringDate());
}
SlideShow.this.slideArea.repaint();
SlideShow.this.slideArea.revalidate();
}
if(action.equals("Back")){
SlideShow.this.photosScreen.setVisible(true);
SlideShow.this.setVisible(false);
}
} | 7 |
Long hash(Path file) throws IOException
{
if (NOHASH_FILES.contains(getFileEnding(file)))
{
return Files.size(file);
}
InputStream inputStream = null;
try
{
inputStream = Files.newInputStream(file);
byte[] currentChunk = new byte[8192];
while (inputStream.read(currentChunk) > -1)
{
adler.update(currentChunk, 0, currentChunk.length);
}
long value = adler.getValue();
adler.reset();
return value;
} catch (IOException ex)
{
Logger.getLogger(DirectorySyncer.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally
{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
} | 4 |
public void generateLevel() {
for (int y = 0; y < Height; y++) {
for (int x = 0; x < Width; x++) {
if (x * y %17 <15) {
tiles[x + y * Width] = Tile.Grass.getid();
} else {
tiles[x+y * Width] = Tile.TallGrass.getid();
}
}
}
} | 3 |
public static void endThread(final int ThreadId){
for(ArrayList Me : ServerThreadList){
Object Targ = Me.get(0);
int ObjId = (Integer)Targ;
if (ObjId == ThreadId){
AliveThreadsID[ObjId] = 0;
Thread Threaded = (Thread)Me.get(1);//the thread
SenderServer cServer = (SenderServer)Me.get(2);
//cServer.endSocket();
System.out.println("Closing server with id:" + ObjId );
//remove old thread from list?
}
}
} | 2 |
public void insertStructuredBlock(StructuredBlock insertBlock) {
if (methodHeader != null) {
insertBlock.setJump(new Jump(FlowBlock.NEXT_BY_ADDR));
FlowBlock insertFlowBlock = new FlowBlock(this, 0);
insertFlowBlock.appendBlock(insertBlock, 0);
insertFlowBlock.setNextByAddr(methodHeader);
insertFlowBlock.doT2(methodHeader);
methodHeader = insertFlowBlock;
} else {
throw new IllegalStateException();
}
} | 1 |
protected byte[] findBases(SAMSequenceRecord record, boolean tryNameVariants) {
{ // check cache by sequence name:
String name = record.getSequenceName();
byte[] bases = findInCache(name);
if (bases != null) {
log.debug("Reference found in memory cache by name: " + name);
return bases;
}
}
String md5 = record.getAttribute(SAMSequenceRecord.MD5_TAG);
{ // check cache by md5:
if (md5 != null) {
byte[] bases = findInCache(md5);
if (bases != null) {
log.debug("Reference found in memory cache by md5: " + md5);
return bases;
}
}
}
byte[] bases;
{ // try to fetch sequence by name:
bases = findBasesByName(record.getSequenceName(), tryNameVariants);
if (bases != null) {
Utils.upperCase(bases);
return bases;
}
}
{ // try to fetch sequence by md5:
if (md5 != null)
try {
bases = findBasesByMD5(md5);
} catch (Exception e) {
if (e instanceof RuntimeException)
throw (RuntimeException) e;
throw new RuntimeException(e);
}
if (bases != null) {
return bases;
}
}
{ // try @SQ:UR file location
if (record.getAttribute(SAMSequenceRecord.URI_TAG) != null) {
ReferenceSequenceFromSeekable s = ReferenceSequenceFromSeekable
.fromString(record.getAttribute(SAMSequenceRecord.URI_TAG));
bases = s.getSubsequenceAt(record.getSequenceName(), 1, record.getSequenceLength());
Utils.upperCase(bases);
return bases;
}
}
return null;
} | 9 |
public boolean containsKey (K key) {
int hashCode = key.hashCode();
int index = hashCode & mask;
if (!key.equals(keyTable[index])) {
index = hash2(hashCode);
if (!key.equals(keyTable[index])) {
index = hash3(hashCode);
if (!key.equals(keyTable[index])) return containsKeyStash(key);
}
}
return true;
} | 3 |
public void setBackgroundColor(String s) {
final String BGCOLOR_PLACEHOLDER = owner.getResource("splitter.placeholder.transparent", "Transparent");
String prevText = this.bgcolor.getText().trim().isEmpty() ? BGCOLOR_PLACEHOLDER : this.bgcolor.getText();
Color col = null;
if (!IOSImageUtil.isNullOrWhiteSpace(s)) {
while (s.length() < 6) s = "0".concat(s);
if (s.length() > 8) s = s.substring(0, 8);
if (s.length() == 7) s = "0".concat(s);
try {
col = new Color(Long.valueOf(s, 16).intValue(), true);
bgcolor.setText(s);
bgcolor.setBackground(new Color(col.getRed(), col.getGreen(), col.getBlue()));
float[] hsb = Color.RGBtoHSB(col.getRed(), col.getGreen(), col.getBlue(), null);
//bgcolor.setForeground(new Color(Color.HSBtoRGB(hsb[0], hsb[1], (float)Math.floor(Math.acos(hsb[2])))));
bgcolor.setForeground(new Color(Color.HSBtoRGB(hsb[0], 1.0f - hsb[1], 1.0f - hsb[2])));
} catch (Exception ex) {
bgcolor.setBackground(Color.WHITE);
bgcolor.setForeground(Color.LIGHT_GRAY);
ex.printStackTrace();
}
}
if (col == null) {
bgcolor.setText(BGCOLOR_PLACEHOLDER);
bgcolor.setForeground(Color.LIGHT_GRAY);
bgcolor.setBackground(Color.WHITE);
}
if (!prevText.equals(this.bgcolor.getText())) {
owner.setStorePropertiesRequested(true);
}
} | 8 |
public void upgrade(File file) throws IOException {
LinkedHashMap<String, String> nodes = new LinkedHashMap<String, String>();
if (this.tpl.getString("error.bank.exists") == null) {
nodes.put("tag.money", "<green>[<white>Money<green>] ");
nodes.put("tag.bank", "<green>[<white>Bank<green>] ");
nodes.put("banks.create", "<green>Created bank <white>+name<green>.");
nodes.put("banks.remove", "<rose>Deleted bank <white>+name<rose>.");
nodes.put("banks.purge.bank", "<rose>Bank <white>+name<rose> was purged of inactive accounts.");
nodes.put("banks.purge.all", "<rose>All banks were purged of inactive accounts.");
nodes.put("error.bank.fee", "<rose>Sorry, this banks fee is more than you are holding.");
nodes.put("error.bank.exists", "<rose>Sorry, that bank already exists.");
nodes.put("error.bank.doesnt", "<rose>Sorry, that bank doesn't exist.");
nodes.put("error.bank.couldnt", "<rose>Sorry, bank <white>+name <rose>couldn't be created.");
nodes.put("error.bank.account.none", "<rose>Sorry, you do not have any bank accounts.");
nodes.put("error.bank.account.exists", "<rose>Sorry, an account like that already exists with us.");
nodes.put("error.bank.account.doesnt", "<rose>Sorry, you do not have an account with <white>+name<rose>.");
nodes.put("error.bank.account.maxed", "<rose>Sorry, you already have a bank account.");
nodes.put("error.bank.account.failed", "<rose>Sorry, failed to create account. Try again...");
nodes.put("error.bank.account.none", "<rose>Sorry, no accounts found.");
nodes.put("accounts.bank.create", "<green>Created account for <white>+name<green> with <white>+bank<green>.");
nodes.put("accounts.bank.remove", "<green>Deleted account <white>+name<green> from <white>+bank<green>.");
nodes.put("personal.bank.charge", "<green>Created account for <white>+name<green> with <white>+bank<green>.");
nodes.put("personal.bank.sent", "<green>You sent <white>+amount<green> from <white>+bank<green> to <white>+name<green>.");
nodes.put("personal.bank.transfer", "<green>Transferred <white>+amount<green> from <white>+bank<green> to <white>+name<green> at <white>+bankAlt<green>.");
nodes.put("personal.bank.between", "<green>Transferred <white>+amount<green> from <white>+bank<green> to <white>+bankAlt<green>.");
nodes.put("personal.bank.change", "<green>Changed main bank to <white>+bankAlt</green>.");
nodes.put("list.banks.opening", "<green>Page #<white>+amount<green> of <white>+total<green> pages (<white>F: Fee<green>, <white>I: Initial Holdings<green>)");
nodes.put("list.banks.empty", "<white> No Banks Exist.");
nodes.put("list.banks.all-entry", "<green> +name [F: <white>+fee<green>] [I: <white>+initial<green>] [<white>+major<green>/<white>+minor<green>]");
nodes.put("list.banks.fee-major-entry", "<green> +name [F: <white>+fee<green>] [I: <white>+initial<green>] [<white>+major<green>]");
nodes.put("list.banks.major-entry", "<green> +name [I: <white>+initial<green>] [<white>+major<green>]");
nodes.put("accounts.empty", "<rose>Deleted <white>all<rose> accounts.");
nodes.put("accounts.purge", "<rose>All inactive accounts were purged.");
nodes.put("accounts.remove-total", "<green>Fully deleted account <white>+name<green>.");
}
if (this.tpl.getString("accounts.create") == null) {
nodes.put("accounts.create", "<green>Created account with the name: <white>+name<green>.");
nodes.put("accounts.remove", "<green>Deleted account: <white>+name<green>.");
nodes.put("error.exists", "<rose>Account already exists.");
}
if (this.tpl.getString("accounts.status") == null) {
nodes.put("error.online", "<rose>Sorry, nobody else is online.");
nodes.put("accounts.status", "<green>Account status is now: <white>+status<green>.");
}
if (this.tpl.getString("interest.announcement") == null) {
nodes.put("interest.announcement", "+amount <green>interest gained.");
}
if (!nodes.isEmpty()) {
System.out.println(" - Upgrading Template.yml");
int count = 1;
for (String node : nodes.keySet()) {
System.out.println(" Adding node [" + node + "] #" + count + " of " + nodes.size());
this.tpl.set(node, nodes.get(node));
count++;
}
this.tpl.save(file);
System.out.println(" + Messages Upgrade Complete.");
}
} | 6 |
public void nextInternPhase(){
internPhase=(internPhase+1)%3;
currentPlayer=0;
if(internPhase==1){
checkOrder();
}else if (internPhase==2){
System.out.println("Consolidation !");
//on retire les ordres consolidations(sans étoiles) pour chaque familles
for(Family family : families){
for (Territory territory : family.getTerritories()){
if(territory.getOrder()!=null && !territory.getOrder().getStar() && territory.getOrder().getType()==OrderType.CON){
family.addInflu(territory.consolidation());
territory.rmOrder();
}
}
}
updateLabel();
checkOrder();
}else if (internPhase==0){
nextPhase();
}
//System.out.println("nextInternPhase");
} | 8 |
public Map<String, Object> getExecutionResults() {
Map<String, Object> map = new HashMap<String, Object>();
int status = -1;
try {
status = process.waitFor();
outReader.join();
errReader.join();
StringWriter outWriter = outReader.getResult();
outResult = outWriter.toString();
outWriter.close();
StringWriter errWriter = errReader.getResult();
errResult = errWriter.toString();
errWriter.close();
map.put(KEY_STATUS, (failed ? -1: status));
} catch (InterruptedException e) {
map.put(KEY_STATUS, (failed ? -1: status));
} catch (IOException e) {
map.put(KEY_STATUS, status);
}
map.put(KEY_OUT_RESULT, outResult);
map.put(KEY_ERR_RESULT, errResult);
if (t != null) {
t.cancel();
}
return map;
} | 5 |
public void writeNart(CycNart cycNart)
throws IOException {
if (trace == API_TRACE_DETAILED) {
Log.current.println("writeNart = " + cycNart.toString());
}
write(CFASL_EXTERNALIZATION);
write(CFASL_NART);
writeList(cycNart.toCycList());
} | 1 |
private Method getInterfaceMethod(Class<?> clazz, String methodName,
Class<?>[] parameterTypes) {
do {
// Get interfaces
Class<?>[] interfaces = clazz.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
// Ignore non-public interfaces
if (!Modifier.isPublic(interfaces[i].getModifiers())) {
continue;
}
// Find method in the current interface
try {
return interfaces[i].getDeclaredMethod(methodName,
parameterTypes);
} catch (NoSuchMethodException e) {
// Not found
}
// Check superinterfaces
Method method = getInterfaceMethod(interfaces[i], methodName,
parameterTypes);
if (method != null) {
return method;
}
}
// Check superclass
clazz = clazz.getSuperclass();
} while (clazz != null);
// Not found
return null;
} | 8 |
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
int x = e.getX ();
int y = e.getY ();
if (back.contains (x, y))
back.setState (1);
else
back.setState (0);
if (help.contains (x, y))
help.setState (1);
else
help.setState (0);
if (earthquake.contains(x, y))
earthquake.setState(1);
else
earthquake.setState(0);
if (melt.contains(x, y))
melt.setState(1);
else
melt.setState(0);
if (pollution.contains(x, y))
pollution.setState(1);
else
pollution.setState(0);
if (addEgg.contains (x,y))
addEgg.setState(1);
else
addEgg.setState(0);
if (addPenguin.contains (x,y))
addPenguin.setState(1);
else
addPenguin.setState(0);
if (addBear.contains (x,y))
addBear.setState(1);
else
addBear.setState(0);
} | 8 |
public static boolean isPrime(long n) {
if (n < 2)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
long sqrtN = (long) Math.sqrt(n) + 1;
for (long i = 6L; i <= sqrtN; i += 6) {
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return false;
}
return true;
} | 8 |
private static void playBackgroundMusic()
{
try
{
new Thread()
{
public void run()
{
try
{
while(true)
{
int choose = random.nextInt(SOUNDTRACK_PATHS.length);
soundtrackClip = Applet.newAudioClip(SoundsOfEmpire.class.getResource(SOUNDTRACK_PATHS[choose]));
soundtrackClip.play();
Thread.sleep(SOUNDTRACK_TIMES[choose]*1000);
soundtrackClip = null;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
} | 3 |
public void setDescription(String description) {
this.description = description;
} | 0 |
public boolean WriteToFile(String data)
{
boolean result = false;
try
{
//write data to file
br.write(data);
br.newLine();
//set the status flag
result = true;
}
catch(Exception e){}
return result;
} | 1 |
public Grid drawWorld(int i, int killed) {
ArrayList<Background> BackGrounds = new ArrayList<Background>();
if (i == 1) {
BackGrounds = this.world1();
}
Background a = BackGrounds.get(0);
Grid g = new Grid(killed);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int d = 0; d < 101; d++) {
for (int j = 0; j < 25; j++) {
GridSpace f = new GridSpace(new ArrayList<Thing>());
if (d == 100) {
f.add(new Terrain(false, Color.BLACK));
} else if (j >= 22) {
f.add(new Terrain(true, a.getGroundColor()));
} else if (j > 2) {
} else {
f.add(new Terrain(true, a.getTopColor()));
}
// needs to check if there is a hill in the background then
// call
// the draw hill method
f.sortArrayOfThings();
grid.put(new Point(d, j), f);
}
}
if (a.getHill()) {
this.drawHill(g);
}
g.setGrid(grid);
return g;
} | 7 |
/* package */TrackerRequest (
Sha1Hash infoHash, PeerId peerId, int port, long uploaded, long downloaded, long left, Boolean compact,
boolean noPeerId, Event event, InetAddress ip, int numWant, int key, byte[] trackerId)
{
if (infoHash == null)
throw new NullPointerException("Null Hash");
if (peerId == null)
throw new NullPointerException("Null PeerId");
if (event == null)
throw new NullPointerException("Null Event");
if (port < 0 | port >= 65535 | uploaded < 0 | downloaded < 0 | left < 0)
throw new IllegalArgumentException();
this.infoHash = infoHash;
this.peerId = peerId;
this.port = port;
this.uploaded = uploaded;
this.downloaded = downloaded;
this.left = left;
this.compact = compact;
this.noPeerId = noPeerId;
this.event = event;
this.ip = ip;
this.numWant = numWant;
this.key = key;
this.trackerId = (trackerId == null) ? null : Arrays.copyOf(trackerId, trackerId.length);
} | 5 |
public String simplifyPath(String path) {
String[] paths = path.split("/");
Stack<String> stack = new Stack<String>();
for(int i=0; i<paths.length; i++){
if(paths[i].equals(".") || paths[i].equals("")) continue;
else if(paths[i].equals("..")){
if(!stack.isEmpty())
stack.pop();
}
else stack.push(paths[i]);
}
String result = "";
if(stack.isEmpty()) return "/";
while(!stack.isEmpty()){
result = "/" + stack.pop() + result;
}
return result;
} | 7 |
protected boolean disconnectInput(NeuralConnection i, int n) {
int loc = -1;
boolean removed = false;
do {
loc = -1;
for (int noa = 0; noa < m_numInputs; noa++) {
if (i == m_inputList[noa] && (n == -1 || n == m_inputNums[noa])) {
loc = noa;
break;
}
}
if (loc >= 0) {
for (int noa = loc+1; noa < m_numInputs; noa++) {
m_inputList[noa-1] = m_inputList[noa];
m_inputNums[noa-1] = m_inputNums[noa];
m_weights[noa] = m_weights[noa+1];
m_changeInWeights[noa] = m_changeInWeights[noa+1];
m_inputList[noa-1].changeOutputNum(m_inputNums[noa-1], noa-1);
}
m_numInputs--;
removed = true;
}
} while (n == -1 && loc != -1);
return removed;
} | 8 |
public void CreatePopulation(int popSize)
throws Exception{
InitPopulation(popSize);
/** Delimit the best attributes from the worst*/
int segmentation =m_numAttribs/2;
/*TEST*/
/* System.out.println ("AttributeRanking");
for (int i = 0; i <attributeRanking.size (); i++){
if(i ==segmentation)System.out.println ("-------------------------SEGMENTATION------------------------");
printSubset (attributeRanking.get (i));
}
*/
for (int i = 0; i<m_popSize; i++) {
List<Subset> attributeRankingCopy = new ArrayList<Subset>();
for (int j = 0; j<m_attributeRanking.size (); j++) attributeRankingCopy.add (m_attributeRanking.get (j));
double last_evaluation =-999;
double current_evaluation =0;
boolean doneAnew =true;
while (true) {
// generate a random number in the interval[0..segmentation]
int random_number = m_random.nextInt (segmentation+1) /*generateRandomNumber (segmentation)*/;
if(doneAnew && i <=segmentation)random_number =i;
doneAnew =false;
Subset s1 =((Subset)attributeRankingCopy.get (random_number)).clone ();
Subset s2 =((Subset)m_population.get (i)).clone ();
// trying to add a new gen in the chromosome i of the population
Subset joiners =joinSubsets (s1, s2 );
current_evaluation =joiners.merit;
if(current_evaluation > last_evaluation){
m_population.set (i,joiners);
last_evaluation =current_evaluation;
try {
attributeRankingCopy.set (random_number, attributeRankingCopy.get (segmentation+1));
attributeRankingCopy.remove (segmentation+1);
}catch (IndexOutOfBoundsException ex) {
attributeRankingCopy.set (random_number,new Subset(new BitSet(m_numAttribs),0));
continue;
}
}
else{
// there's not more improvement
break;
}
}
}
//m_population =bubbleSubsetSort (m_population);
} | 7 |
@Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
calculateEnabledState(e.getDocument());
} | 0 |
private void initTimeline() {
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
KeyFrame kf = new KeyFrame(Config.ANIMATION_TIME, new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
if (state == STATE_SHOW_TITLE) {
stateArg++;
int center = Config.SCREEN_WIDTH / 2;
int offset = (int)(Math.cos(stateArg / 4.0) * (40 - stateArg) / 40 * center);
brick.setTranslateX(center - brick.getImage().getWidth() / 2 + offset);
breaker.setTranslateX(center - breaker.getImage().getWidth() / 2 - offset);
if (stateArg == 40) {
stateArg = 0;
state = STATE_SHOW_STRIKE;
}
return;
}
if (state == STATE_SHOW_STRIKE) {
if (stateArg == 0) {
strike.setTranslateX(breaker.getTranslateX() + brick.getImage().getWidth());
strike.setScaleX(0);
strike.setScaleY(0);
strike.setVisible(true);
}
stateArg++;
double coef = stateArg / 30f;
brick.setTranslateX(breaker.getTranslateX() +
(breaker.getImage().getWidth() - brick.getImage().getWidth()) / 2f * (1 - coef));
strike.setScaleX(coef);
strike.setScaleY(coef);
strike.setRotate((30 - stateArg) * 2);
if (stateArg == 30) {
stateArg = 0;
state = STATE_SUN;
}
return;
}
// Here state == STATE_SUN
if (pressanykey.getOpacity() < 1) {
pressanykey.setOpacity(pressanykey.getOpacity() + 0.05f);
}
stateArg--;
double x = SUN_AMPLITUDE_X * Math.cos(stateArg / 100.0);
double y = SUN_AMPLITUDE_Y * Math.sin(stateArg / 100.0);
if (y < 0) {
for (Node node : NODES_SHADOWS) {
// Workaround RT-1976
node.setTranslateX(-1000);
}
return;
}
double sunX = Config.SCREEN_WIDTH / 2 + x;
double sunY = Config.SCREEN_HEIGHT / 2 - y;
sun.setTranslateX(sunX - sun.getImage().getWidth() / 2);
sun.setTranslateY(sunY - sun.getImage().getHeight() / 2);
sun.setRotate(-stateArg);
for (int i = 0; i < NODES.length; i++) {
NODES_SHADOWS[i].setOpacity(y / SUN_AMPLITUDE_Y / 2);
NODES_SHADOWS[i].setTranslateX(NODES[i].getTranslateX() +
(NODES[i].getTranslateX() + NODES[i].getImage().getWidth() / 2 - sunX) / 20);
NODES_SHADOWS[i].setTranslateY(NODES[i].getTranslateY() +
(NODES[i].getTranslateY() + NODES[i].getImage().getHeight() / 2 - sunY) / 20);
}
}
});
timeline.getKeyFrames().add(kf);
} | 9 |
public boolean hasPotentialAvailableSpace(int fileSize) {
if (fileSize <= 0) {
return false;
}
// check if enough space left
if (getAvailableSpace() > fileSize) {
return true;
}
Iterator it = fileList_.iterator();
File file = null;
int deletedFileSize = 0;
// if not enough space, then if want to clear some files
boolean result = false;
while (it.hasNext()) {
file = (File) it.next();
if (!file.isReadOnly()) {
deletedFileSize += file.getSize();
}
if (deletedFileSize > fileSize) {
result = true;
break;
}
}
return result;
} | 5 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((decodedValue == null) ? 0 : decodedValue.hashCode());
result = prime * result + ((encodedValue == null) ? 0 : encodedValue.hashCode());
result = prime * result + ((symmetricKey == null) ? 0 : symmetricKey.hashCode());
return result;
} | 3 |
@Override
public boolean interpret(String context) {
return expression1.interpret(context) && expression2.interpret(context);
} | 1 |
private static List<ChunkHolder> getChunks( List<Holder> list )
{
List<ChunkHolder> chunks = new ArrayList<ChunkHolder>();
ChunkHolder currentChunk = null;
int lastIndex = 0;
while(lastIndex < list.size())
{
Holder thisHolder = list.get(lastIndex);
if( currentChunk == null)
{
if(thisHolder.spearman <= INITIATION_THRESHOLD)
{
currentChunk = new ChunkHolder();
chunks.add(currentChunk);
currentChunk.firstStart = thisHolder.startPos;
currentChunk.lastStart = thisHolder.startPos;
currentChunk.n = 1;
currentChunk.spearmanSum += thisHolder.spearman;
int lookBack = lastIndex -1;
boolean stop = false;
while(lookBack > 0 && ! stop)
{
Holder previous = list.get(lookBack);
if( previous.spearman <= EXTENSION_THRESHOLD &&
! positionIsInChunk(chunks, previous.startPos))
{
currentChunk.firstStart = previous.startPos;
currentChunk.n = currentChunk.n + 1;
currentChunk.spearmanSum += thisHolder.spearman;
lookBack--;
}
else
{
stop = true;
}
}
}
}
else
{
if( thisHolder.spearman <= EXTENSION_THRESHOLD)
{
currentChunk.lastStart = thisHolder.startPos;
currentChunk.n = currentChunk.n + 1;
currentChunk.spearmanSum+= thisHolder.spearman;
}
else
{
currentChunk = null;
}
}
lastIndex++;
}
return chunks;
} | 8 |
public String getResponseString(String url) {
String lineText;
StringBuilder sb = new StringBuilder();
InputStreamReader isr = null;
int failCount = 0;
do {
try {
getMethod.setURI(new URI(url));
HttpResponse response = httpClient.execute(getMethod);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (status != HttpStatus.SC_OK || entity == null) {
return null;
}
isr = new InputStreamReader(entity.getContent());
BufferedReader bufReader = new BufferedReader(isr);
while ((lineText = bufReader.readLine()) != null) {
sb.append(lineText);
}
break;
} catch (Exception e) {
failCount++;
if(_DEBUG){
System.err.println("对于链接:" + url + " 第" + failCount
+ "次抓取失敗,正在尝试重新抓取...");
}
} finally {
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
// e.printStackTrace();
}
}
} while (failCount < MAX_FAILCOUNT);
return sb.toString();
} | 8 |
public int GetFirstTicks()
{
//get the tick time the person got to the stop for the bus
return firstTicks;
} | 0 |
@Override
public void Redo()
{
Rectangle obr = getObjectRectangle();
for (LevelItem obj : objs)
{
Rectangle r = obj.getRect();
r.x += XDelta;
r.y += YDelta;
r.width += XSDelta;
r.height += YSDelta;
obj.setRect(r);
if (obj instanceof NSMBObject && (this.XSDelta != 0 || this.YSDelta != 0))
((NSMBObject) obj).UpdateObjCache();
}
Rectangle.union(obr, getObjectRectangle(), obr);
EdControl.level.repaintTilemap(obr.x, obr.y, obr.width, obr.height);
} | 4 |
protected void setPosition(Position position) {
if (position == null)
throw new IllegalArgumentException("Position can't be null");
if (position.xCoordinate < 0 || position.yCoordinate < 0)
throw new IllegalArgumentException("The given position is invalid!");
this.position = position;
} | 3 |
public void setIdSolicitud(int idSolicitud) {
this.idSolicitud = idSolicitud;
} | 0 |
private void insertDemoProducts(){
try {
db = new DataBase();
Random randomNumbers;
int n=0;
for(int i=0;i<=20;i++){
con = db.getConnection();
statement = con.createStatement();
randomNumbers = new Random();
int number = 190 + randomNumbers.nextInt( 300 - 200 + 1 );
int av = 20 + randomNumbers.nextInt( 50 - 20 + 1 );
String quality;
if(av%2==0){
quality="Good";
}else{
quality="Normal";
}
String query = "INSERT INTO `products` (`product_name` , `brand` , `model` , `quality` , `price` , `available` ) \n" +
"VALUES (\n" +
"'Monitor', 'Samsung', 'Md-d"+i+"-4df', '"+quality+"', '"+number+"', '"+av+"'\n" +
");";
statement.executeUpdate(query);
}
for(int i=0;i<=10;i++){
con = db.getConnection();
statement = con.createStatement();
randomNumbers = new Random();
int number = 100 + randomNumbers.nextInt( 200 - 150 + 1 );
int av = 20 + randomNumbers.nextInt( 50 - 20 + 1 );
String quality;
if(av%2==0){
quality="Good";
}else{
quality="Normal";
}
String query = "INSERT INTO `products` (`product_name` , `brand` , `model` , `quality` , `price` , `available` ) \n" +
"VALUES (\n" +
"'Printer', 'Samsung', 'Md-dow-a"+i+"', '"+quality+"', '"+number+"', '"+av+"'\n" +
");";
statement.executeUpdate(query);
}
for(int i=0;i<=18;i++){
con = db.getConnection();
statement = con.createStatement();
randomNumbers = new Random();
int number = 100 + randomNumbers.nextInt( 200 - 150 + 1 );
int av = 20 + randomNumbers.nextInt( 50 - 20 + 1 );
String quality;
if(av%2==0){
quality="Good";
}else{
quality="Normal";
}
String query = "INSERT INTO `products` (`product_name` , `brand` , `model` , `quality` , `price` , `available` ) \n" +
"VALUES (\n" +
"'Printer', 'LG', 'b-"+i+"', '"+quality+"', '"+number+"', '"+av+"'\n" +
");";
statement.executeUpdate(query);
n++;
}
for(int i=0;i<=22;i++){
con = db.getConnection();
statement = con.createStatement();
randomNumbers = new Random();
int number = 100 + randomNumbers.nextInt( 200 - 150 + 1 );
int av = 20 + randomNumbers.nextInt( 50 - 20 + 1 );
String quality;
if(av%2==0){
quality="Good";
}else{
quality="Normal";
}
String query = "INSERT INTO `products` (`product_name` , `brand` , `model` , `quality` , `price` , `available` ) \n" +
"VALUES (\n" +
"'NoteBook', 'Samsung', 'bm-"+i+"20', '"+quality+"', '"+number+"', '"+av+"'\n" +
");";
statement.executeUpdate(query);
n++;
}
con.close();
} catch (Exception ex) {
Logger.getLogger(InitializationForm.class.getName()).log(Level.SEVERE, null, ex);
}
} | 9 |
public ArrayList<Vertex> gpsrPath(int sourceIndex, int sinkIndex) {
DijkstraVertex sourceVertex = new DijkstraVertex();
DijkstraVertex sinkVertex = new DijkstraVertex();
DijkstraVertex currentVertex = new DijkstraVertex();
DijkstraVertex tempVertex = new DijkstraVertex();
ArrayList<Vertex> GPSRPath = new ArrayList<Vertex>();
boolean flag = true;
sourceVertex = newLocation.get(sourceIndex);
sinkVertex = newLocation.get(sinkIndex);
currentVertex = sourceVertex;
GPSRPath.add(sourceVertex);
while(!currentVertex.equals(sinkVertex) && flag == true){
tempVertex = currentVertex;
int CVIndex = newLocation.indexOf(currentVertex);
for(int counter = 0; counter < adjList.get(CVIndex).size(); counter++){
if(currentVertex.distance(adjList.get(CVIndex).get(counter)) <= transmissionRange && tempVertex.distance(sinkVertex) > sinkVertex.distance(adjList.get(CVIndex).get(counter))){
tempVertex = adjList.get(CVIndex).get(counter);
}
}
if(currentVertex.equals(tempVertex) && !tempVertex.equals(sinkVertex)){
flag = false;
}else{
currentVertex = tempVertex;
GPSRPath.add(currentVertex);
}
}
if(flag == false){
return new ArrayList<Vertex>(0); // empty array list | return if GPSR fails
}else{
return GPSRPath; // empty array list | return if GPSR fails
}
} | 8 |
void calcVelocity(float dT){
SimpleVector dVelocity = new SimpleVector(this.acceleration);
dVelocity.scalarMul(dT);
this.velocity.add(dVelocity);
} | 0 |
public boolean removeBalance(int num, double monto){
boolean state=false;
if(!activo.validateTipo(Usuario.LIMITADO)){
if(num>0 && monto>0){
int index = searchIndex(num, !state);
if(index>=0){
return remove(index, monto);
}
}
}
return false;
} | 4 |
public void quit() {
for (Player player : players) {
player.stop();
}
} | 1 |
public static void maxheap(int array[], int i) {
int left = 2 * i;
int right = 2 * i + 1;
int parent = i;
if (left <= N && array[left] > array[i])
parent = left;
if (right <= N && array[right] > array[parent])
parent = right;
if (parent != i) {
swap(array, i, parent);
maxheap(array, parent);
}
} | 5 |
@Override
public void keyPressed(KeyEvent k) {
//System.out.println("Key pressed: " + k.getKeyCode());
if (k.getKeyCode() != 17 && !this.ctrl) {
this.saved = false;
}
else if (k.getKeyCode() == 17)
this.ctrl = true;
} | 3 |
/* */ public void paintComponent(Graphics paramGraphics)
/* */ {
/* 37 */ int i = getWidth() / 2 + 1;
/* 38 */ int j = getHeight() / 2 + 1;
/* 39 */ if ((this.img == null) || (this.img.getWidth(null) != i) || (this.img.getHeight(null) != j)) {
/* 40 */ this.img = createImage(i, j);
/* */
/* 42 */ Graphics localGraphics = this.img.getGraphics();
/* */ int m;
/* 43 */ for (int k = 0; k <= i / 32; k++) {
/* 44 */ for (m = 0; m <= j / 32; m++)
/* 45 */ localGraphics.drawImage(this.bgImage, k * 32, m * 32, null);
/* */ }
/* 47 */ if ((localGraphics instanceof Graphics2D)) {
/* 48 */ Graphics2D localGraphics2D = (Graphics2D)localGraphics;
/* 49 */ m = 1;
/* 50 */ localGraphics2D.setPaint(new GradientPaint(new Point2D.Float(0.0F, 0.0F), new Color(553648127, true), new Point2D.Float(0.0F, m), new Color(0, true)));
/* 51 */ localGraphics2D.fillRect(0, 0, i, m);
/* */
/* 53 */ m = j;
/* 54 */ localGraphics2D.setPaint(new GradientPaint(new Point2D.Float(0.0F, 0.0F), new Color(0, true), new Point2D.Float(0.0F, m), new Color(1610612736, true)));
/* 55 */ localGraphics2D.fillRect(0, 0, i, m);
/* */ }
/* 57 */ localGraphics.dispose();
/* */ }
/* 59 */ paramGraphics.drawImage(this.img, 0, 0, i * 2, j * 2, null);
/* */ } | 6 |
public void run() {
try {
while (true) {
int n = selector.select();
if (n == 0) {
continue;
}
keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
if (key.isValid()) {
/**config*/
if (count.compareAndSet(0, 1)) {
validOperation(key);
}
if (key.isReadable()) {
readOperation(key);
}else if(key.isWritable()){
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
@Override
public void startDocument () {} | 0 |
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String fromname = request.getParameter("fromname");
Date date = new Date();
String dates = " -at " + date;
String all = date + "!" +fromname;
String toname = request.getParameter("toname");
String filename = toname + ".ser";
String message = request.getParameter("message");
String[] data = { fromname, message, dates};
HashMap<String , String[]> e = null;
File f = new File(filename);
if(f.isFile()) {
try
{
FileInputStream fileIn = new FileInputStream(filename);
ObjectInputStream infil = new ObjectInputStream(fileIn);
e = (HashMap<String , String[]>) infil.readObject();
infil.close();
fileIn.close();
}catch(IOException i)
{
ErrorHandling.printMessage("Sorry your operation canot be compleated, Please try again",response);
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
ErrorHandling.printMessage("Sorry your operation canot be compleated, Please try again",response);
c.printStackTrace();
return;
}
if(e != null)
{
statushm = e;
}
}
statushm.put(all,data);
try
{
FileOutputStream fileOut = new FileOutputStream(filename);
ObjectOutputStream outfil = new ObjectOutputStream(fileOut);
outfil.writeObject(statushm);
outfil.close();
fileOut.close();
}catch(IOException i)
{
ErrorHandling.printMessage("Sorry your operation canot be compleated, Please try again",response);
i.printStackTrace();
}
response.sendRedirect("messages.jsp?name=" + fromname);
} | 5 |
public void generateMineshaft(int x,int y){
int length = rand.nextInt(SIZE/2);
boolean up = rand.nextBoolean(); // false if in left-right
for(int i=x;i<length+x;i++){
if(i>=SIZE || y+1>=SIZE || y+2>=SIZE) return;
if(up){
world[y][i] = TileType.WOOD;
world[y+1][i] = TileType.AIR;
world[y+2][i] = TileType.WOOD;
}else{
world[i][y] = TileType.WOOD;
world[i][y+1] = TileType.AIR;
world[i][y+2] = TileType.WOOD;
}
}
} | 5 |
private char getElement(Coordinate current) {
MazeNode currentNode = game.getNode(current);
if (game.isMouseAtLocation(current) && game.isCatAtLocation(current)) {
return DEAD;
}
else if (game.isMouseAtLocation(current)) {
return MOUSE;
}
else if (game.isCatAtLocation(current)) {
return CAT;
}
else if (game.isCheeseAtLocation(current)) {
return CHEESE;
}
else if (currentNode.hasFOG()) {
return FOG;
}
else if (currentNode.isWall()) {
return WALL;
}
else {
return PATH;
}
} | 7 |
*/
public static void createSingleton(String[] args) {
//modifications by Zerbetto 05-12-2007
String fileName = null;
boolean showFileMenu = true;
if ((args != null) && (args.length > 0)) {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("file=")) {
fileName = arg.substring("file=".length());
} else if (arg.startsWith("showFileMenu=")) {
showFileMenu = Boolean.parseBoolean(arg.substring(
"showFileMenu=".length()));
}
}
}
if (m_knowledgeFlow == null) {
m_knowledgeFlow = new KnowledgeFlowApp(showFileMenu);
}
// end modifications by Zerbetto
// notify listeners (if any)
for (int i = 0; i < s_startupListeners.size(); i++) {
((StartUpListener) s_startupListeners.elementAt(i)).startUpComplete();
}
//modifications by Zerbetto 05-12-2007
if (fileName != null) {
m_knowledgeFlow.loadInitialLayout(fileName);
}
// end modifications
} | 8 |
public LSystemInputEvent(LSystemInputPane input) {
super(input);
} | 0 |
public Note setNote( final Note newNote ) {
if( null == newNote ) {
return null;
}
final long noteId = newNote.getId();
final Note oldNote = notes.put( noteId, newNote );
if( null == oldNote ) {
notifyNotesChangedListeners();
}
if( !newNote.equals( oldNote ) ) {
notifyNoteChangedListeners( newNote );
}
return oldNote;
} | 3 |
public StackState constructorCall(int initializedValueStackPosition, StackEntry entry) {
List<StackEntry> newContents = new ArrayList<StackEntry>(contents.size());
if (entry.getType() == StackEntryType.UNINITIALIZED_THIS) {
for (int i = 0; i < contents.size() - 1 - initializedValueStackPosition; ++i) {
StackEntry stackEntry = contents.get(i);
if (stackEntry.getType() == StackEntryType.UNINITIALIZED_THIS) {
newContents.add(StackEntry.of(stackEntry.getDescriptor(), constPool));
} else {
newContents.add(stackEntry);
}
}
return new StackState(newContents, constPool);
} else if (entry.getType() == StackEntryType.UNITITIALIZED_OBJECT) {
for (int i = 0; i < contents.size() - 1 - initializedValueStackPosition; ++i) {
StackEntry stackEntry = contents.get(i);
if (stackEntry.getType() == StackEntryType.UNITITIALIZED_OBJECT
&& stackEntry.getNewInstructionLocation() == entry.getNewInstructionLocation()) {
newContents.add(StackEntry.of(stackEntry.getDescriptor(), constPool));
} else {
newContents.add(stackEntry);
}
}
return new StackState(newContents, constPool);
} else {
throw new InvalidBytecodeException("Object at position " + initializedValueStackPosition
+ " is not an unitialized object. " + toString());
}
} | 7 |
private final void progressCheck(boolean useTime, double progressFactor, double progressOffset) {
Matcher m = ProgressCallbackThread.progressPattern.matcher(this.progressScanner);
Matcher m2;
int start = 0, pos;
long time;
int flags;
int frame;
while (m.find(start)) {
// Parse
time = 0L;
frame = 0;
flags = 0;
m2 = ProgressCallbackThread.progressLine.matcher(m.group(0));
pos = start;
while (m2.find(pos)) {
if (m2.group(1).equals("out_time_ms")) {
time = Long.parseLong(m2.group(2));
}
else if (m2.group(1).equals("frame")) {
frame = Integer.parseInt(m2.group(2));
}
else if (m2.group(1).equals("progress")) {
if (m2.group(2).equals("end")) flags |= GeneratorProgressCallback.COMPLETE;
}
pos = m2.end();
}
// Event
this.triggerCallback(
useTime ? ((time / (this.targetLength * 1000000.0)) * progressFactor + progressOffset) : ((frame / ((double) maxFrames)) * progressFactor + progressOffset),
flags
);
// Next
start = m.end();
}
// Remove
this.progressScanner.delete(0, start);
} | 7 |
protected void showClassInfo (StringBuffer buf)
{
try {
buf.append ("<b>Rio Status</b><br>\n");
if (getRio () == null) {
buf.append ("<em>Device claimed by another driver.</em>");
buf.append ("<br><br>\n");
return;
}
rio.start ();
showStorage (buf, false);
if (rio.hasExternalMemory ())
showStorage (buf, true);
} catch (IOException e) {
buf.append ("\n<br>");
buf.append (e.getClass ().getName ());
buf.append (": ");
buf.append (e.getMessage ());
buf.append ("<br>\n");
} finally {
if (rio != null)
rio.finish ();
}
} | 4 |
public static int getDaysNumber(int m, int y) {
switch(m) {
case 2:
return isALeapYear(y) ? 29 : 28;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
default:
return 30;
}
} | 9 |
public static void main(String[] args) throws Exception {
args = new String[] { "-c" };
try {
File collectionFile = new File(args[1]);
if (args[0].equals("-c")) {
assert !collectionFile.exists();
collectData(collectionFile);
} else if (args[0].equals("-ag")) {
assert collectionFile.exists();
File gpsFile = new File(args[2]);
assert gpsFile.exists();
augmentDataGPS(collectionFile, gpsFile);
} else if (args[0].equals("-ac")) {
assert collectionFile.exists();
augmentDataCell(collectionFile);
} else if (args[0].equals("-e")) {
assert collectionFile.exists();
File outputDirectory = new File(args[2]);
assert outputDirectory.isDirectory();
exportData(collectionFile, outputDirectory);
}
} catch (AssertionError | ArrayIndexOutOfBoundsException e) {
showUsage();
}
} | 5 |
public void insertionSort (int[] array, int a, int b) {
int i = a, j = a-1;
while (i <= b) {
int key = array[i];
int k = i-1;
while (k > -1 && array[k] > key) {
array[k+1] = array[k];
k--;
}
if (k+1 != i) {
array[k+1] = key;
}
i++;
}
} | 4 |
public static void checkCost(String s) throws Exception {
for (char c : s.toCharArray()) {
if (!((c >= '0' && c <= '9') || c == ',' || c == '.')) {
throw new Exception("В поле с ценой недопустимые символы: ");
}
}
} | 5 |
public String getStatus(int status) {
try {
isAValidKey(status);
} catch (Exception e) {
e.printStackTrace();
}
return getStatusCodesMap().get(status);
} | 1 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(target==null)
return false;
if(target.fetchEffect(this.ID())!=null)
{
mob.tell(L("@x1 is already unbreakable.",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> appear(s) unbreakable!"):L("^S<S-NAME> chant(s) to <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(!target.subjectToWearAndTear())
maintainCondition=-1;
else
maintainCondition=target.usesRemaining();
beneficialAffect(mob,target,asLevel,0);
mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,L("<T-NAME> is unbreakable!"));
target.recoverPhyStats();
mob.recoverPhyStats();
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) to <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
} | 7 |
private static void checkIntWordRange(Token token, int value)
throws TokenCompileError {
if((value >= 0 && (value & 0xffff0000) != 0)
|| (value < 0 && (value & 0xffff8000) != 0xffff8000)) {
throw new TokenCompileError("Value can not fit in 16 bits", token);
}
} | 4 |
public static void insertEntreprise(int idville,String nom, String adresse1, String adresse2) throws SQLException {
String query;
try {
query = "INSERT INTO ENTREPRISE (ID_VILLE,ENTNOM,ENTADRESSE1,ENTADRESSE2) VALUES (?,?,?,?);";
PreparedStatement pStatement = ConnectionBDD.getInstance().getPreparedStatement(query);
pStatement.setInt(1, idville);
pStatement.setString(2, nom.toUpperCase());
pStatement.setString(3, adresse1.toLowerCase());
pStatement.setString(4, adresse2.toLowerCase());
pStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(RequetesEntreprise.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
public void ticRefreshSpace(int space)
{
if (space == 1) {
button1.setText("");
button1.setEnabled(true);
}
else if (space == 2) {
button2.setText("");
button2.setEnabled(true);
}
else if (space == 3) {
button3.setText("");
button3.setEnabled(true);
}
else if (space == 4) {
button4.setText("");
button4.setEnabled(true);
}
else if (space == 5) {
button5.setText("");
button5.setEnabled(true);
}
else if (space == 6) {
button6.setText("");
button6.setEnabled(true);
}
else if (space == 7) {
button7.setText("");
button7.setEnabled(true);
}
else if (space == 8) {
button8.setText("");
button8.setEnabled(true);
}
else if (space == 9) {
button9.setText("");
button9.setEnabled(true);
}
// Resets that space in the local taken spaces array
takenSpaces[space-1] = 0;
// Alerts the player to the move having been undone
moveLabel.setText("Previous move has been undone!");
turn--;
// Resets that specific spot in the array in TicTacToeGame class
tic.resetArraySpace(space);
} | 9 |
static void processArgs(String args, Config config) {
String[] split = args.split(",\\s*");
for (String s : split) {
if (s.equals("debug")) {
DEBUG = true;
}
if (s.equals("tty")) {
config.setTty(true);
}
if (s.startsWith("context=")) {
CONTEXT = s.replace("context=", "");
}
if (s.equals("windowsTrust")) {
config.setUseWindowsTrust(true);
}
if (s.equals("help")) {
showHelp();
}
}
} | 6 |
public boolean hasText() {
for (Node child: childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
if (!textNode.isBlank())
return true;
} else if (child instanceof Element) {
Element el = (Element) child;
if (el.hasText())
return true;
}
}
return false;
} | 5 |
public void updateDB() {
if (succLogin) {
try {
openConnection();
st.execute("UPDATE Player SET Coins='" + coins + "' WHERE Name='" + user + "'");
st.execute("UPDATE Player SET Unlocked='" + unlocked + "' WHERE Name='" + user + "'");
st.execute("UPDATE Player SET Playtime='" + playtime + "' WHERE Name='" + user + "'");
closeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("[NetworkManager] Not Logged in!");
}
} | 2 |
private boolean isClassInDir(File file)
{
String []files;
files = file.list();
for(int i=0; i< files.length; i++)
{
if(files[i].equals(this.className)) return true;
}
return false;
} | 2 |
public void colision (int ancho, int alto){
//no dejo que bueno salga por la derecha
if (this.getPosX() + this.getAncho() >= ancho) {
this.setPosX(ancho - this.getAncho());
}
//no dejo que bueno salga por izquierda
else if (this.getPosX() <= ancho/2) {
this.setPosX(ancho/2);
}
//no dejo que bueno salga por abajo
if (this.getPosY() + this.getAncho() >= alto) {
this.setPosY(alto - this.getAncho());
} else if (this.getPosY() <= 0) {
this.setPosY(0);
}
} | 4 |
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column
) {
return this;
} | 0 |
public static void end() {
Printer.printToConsole("End");
Printer.printToConsole(String.format("%d Victims killed", killedVictims));
Printer.printToConsole(String.format("%d Victims spawned", spawnedVictims));
Printer.printToConsole(String.format("Victims in pool %d", Initialization.numberVictims));
Printer.printToConsole(String.format("Predators in pool %d", Initialization.numberPredators));
} | 0 |
public static String lcp(String v, String w) {
int n = Math.min(v.length(), w.length());
for (int i = 0; i < n; i++) {
if (v.charAt(i) != w.charAt(i)) return v.substring(0, i);
}
return v.substring(0, n);
} | 2 |
public float getAttackBonus(Point p) {
float bonus = 0;
Placeable placeable = null;
try {
for (String key : placeables.keySet()) {
placeable = (Placeable) placeables.get(key);
if (placeable != null) {
bonus += placeable.getAttackBonus(p);
}
}
} catch (ConcurrentModificationException concEx) {
//another thread was trying to modify placeables while iterating
//we'll continue and the new item can be grabbed on the next update
}
return bonus;
} | 3 |
void createExampleWidgets () {
/* Compute the widget style */
int style = getDefaultStyle();
if (shadowInButton.getSelection ()) style |= SWT.SHADOW_IN;
if (shadowNoneButton.getSelection ()) style |= SWT.SHADOW_NONE;
if (shadowOutButton.getSelection ()) style |= SWT.SHADOW_OUT;
if (leftButton.getSelection ()) style |= SWT.LEFT;
if (centerButton.getSelection ()) style |= SWT.CENTER;
if (rightButton.getSelection ()) style |= SWT.RIGHT;
/* Create the example widgets */
label1 = new CLabel (textLabelGroup, style);
label1.setText(ControlExample.getResourceString("One"));
label1.setImage (instance.images[ControlExample.ciClosedFolder]);
label2 = new CLabel (textLabelGroup, style);
label2.setImage (instance.images[ControlExample.ciTarget]);
label3 = new CLabel (textLabelGroup, style);
label3.setText(ControlExample.getResourceString("Example_string") + "\n" + ControlExample.getResourceString("One_Two_Three"));
} | 6 |
private void replace(Node seNode,HashSet<String> names,HashSet<Integer> excludedIds,Associator assoc){
Iterator<String> it = names.iterator();
String seName = seNode.getName();
SynSE oldSE = null;
SynSE se = ses.get(seName);
while(it.hasNext()){
String name = it.next();
while(replacedSEs.containsKey(name)){
name = replacedSEs.get(name);
}
for(Map.Entry<Integer, Path> en : this.paths.entrySet()){
if(excludedIds.contains(en.getKey())){
continue;
}
Path path = en.getValue();
LinkedList<Node> newNodes = new LinkedList<Node>();
LinkedList<Node> oldNodes = path.getNodes();
Iterator<Node> itP = oldNodes.iterator();
boolean changed = false;
while(itP.hasNext()){
Node node = itP.next();
String nodeName = node.getName();
if(nodeName.equals(name)){
newNodes.add(seNode);
changed = true;
}
else{
newNodes.add(node);
}
}
if(changed){
path.setNodes(newNodes);
}
}
if(ses.containsKey(name)){
oldSE = ses.get(name);
HashSet<String> seMember = oldSE.getMembers();
Iterator<String> memberIt = seMember.iterator();
se.add(oldSE);
while(memberIt.hasNext()){
String member = memberIt.next();
inSE.put(member,seName);
}
this.ses.remove(name);
this.replacedSEs.put(name,seName);
}
}
} | 9 |
private void createGUIComponents() {
CardTreeNode treeRoot = new CardTreeNode(Main.CARDS);
cardsTree = new JTree(treeRoot);
cardsTree.setRootVisible(false);
cardsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
cardsTree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
lcv.setDirectory(
((CardTreeNode) e.getPath().getLastPathComponent())
.getFile());
}
});
cardsFound = new JLabel("Cards found: " + treeRoot.countFiles());
cardsFound.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardsFound.setHorizontalAlignment(SwingConstants.CENTER);
scv = new SmallCardsViewer(this);
lcv = new LargeCardsViewer(this);
lcv.setDirectory(Main.CARDS);
back = new JButton("Back");
back.setFocusable(false);
back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
scv.close();
DeckCreator.this.dispose();
parentFrame.setVisible(true);
}
});
deckName = new JLabel("Deck: new");
load = new JButton("Load");
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dfc.showOpenDialog(DeckCreator.this)
== JFileChooser.APPROVE_OPTION) {
File f = dfc.getSelectedFile();
Deck t = Deck.load(f);
if (t == null) {
JOptionPane.showMessageDialog(DeckCreator.this,
"Deck could not be loaded", Main.TITLE_SHORT,
JOptionPane.ERROR_MESSAGE);
} else {
deck = t;
deckName.setText("Deck: "
+ Utilities.getName(f));
scv.refresh();
stats.refresh();
}
}
}
});
save = new JButton("Save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dfc.showSaveDialog(DeckCreator.this) == JFileChooser.APPROVE_OPTION) {
File f = dfc.getSelectedFile();
if (!"txt".equals(Utilities.getExtension(f))) {
f = new File(f.toString() + ".txt");
}
if (deck.save(f)) {
deckName.setText("Deck: "
+ Utilities.getName(f));
} else {
JOptionPane.showMessageDialog(DeckCreator.this,
"Deck could not be saved", Main.TITLE_SHORT,
JOptionPane.ERROR_MESSAGE);
}
}
}
});
stats = new Stats(this);
} | 5 |
@Override
public void remove(T t) {
DInfo<T> op;
SearchReturnValues ret;
LockFreeNode<T> newNode=new LockFreeNode<T>(t);//node to find
while(true){
ret=search(newNode);
if(newNode.compareTo(ret.l)!=0){
//In case something change during the search and
// we miss the element, we try it again one more time.
ret=search(newNode);
if(newNode.compareTo(ret.l)!=0){
return;
}
}
if(!ret.gsi.isClean())
Help(ret.gsi);
else if(!ret.si.isClean())
Help(ret.si);
else{
boolean res;
op= new DInfo<T>(ret.gp,ret.p,ret.l,ret.si,ret.stamps);
StateInfo<T> newStateInfo = new StateInfo<T>(StateInfo.DFlag,op);
res=ret.gp.si.compareAndSet(ret.gsi, newStateInfo , op.stamps.gsiStamp, ++op.stamps.gsiStamp);
if(res){
if(HelpDelete(op))
return;
}else{
Help(ret.gp.si.getReference());
}
}
}
} | 7 |
private static void addSettersClass(Class<?> cls) {
List<FastMethod> setters = new ArrayList<FastMethod>();
classToSetters.put(cls, setters);
FastClass fastClass = FastClass.create(cls);
while (cls != null) {
for (Method method : cls.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) && method.getName().startsWith("set") && !method.isAnnotationPresent(Skip.class)) {
setters.add(fastClass.getMethod(method));
}
}
cls = cls.getSuperclass();
}
} | 6 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
if((msg.targetMinor()==CMMsg.TYP_WEAPONATTACK)
&&(msg.tool()==this)
&&(requiresAmmunition())
&&(ammunitionCapacity()>0))
{
if(ammunitionRemaining()>ammunitionCapacity())
setAmmoRemaining(ammunitionCapacity());
if(ammunitionRemaining()<=0)
return false;
else
setUsesRemaining(usesRemaining()-1);
}
return true;
} | 7 |
@Override
protected void onAction(String sender, String login, String hostname, String target, String action)
{
super.onAction(sender, login, hostname, target, action);
int i = 0;
while(true)
{
Main.debug("Action check: " + serverid + " - " + Main.gui.tabs.get(i).serverid, false);
if(Main.gui.tabs.get(i).serverid == serverid && Main.gui.tabs.get(i).title.equalsIgnoreCase(target))
{
Main.gui.tabs.get(i).addMessage("<< " + sender + " " + action + " >>");
Main.gui.tabs.get(i).onUpdate();
i++;
}
else
{
if(i > Main.gui.tabs.size())
{
break;
}
i++;
}
}
} | 4 |
@Test
public void testReadyStateTransition() throws ProcessExecutionException, ProcessRollbackException {
IProcessComponent<?> comp = TestUtil.executionSuccessComponent(true);
assertTrue(comp.getState() == ProcessState.READY);
// test valid operation
TestUtil.setState(comp, ProcessState.READY);
try {
comp.execute();
} catch (InvalidProcessStateException ex) {
fail("This operation should have been allowed.");
}
// test invalid operations
TestUtil.setState(comp, ProcessState.READY);
try {
comp.rollback();
fail("InvalidProcessStateException should have been thrown.");
} catch (InvalidProcessStateException ex) {
// should happen
}
TestUtil.setState(comp, ProcessState.READY);
try {
comp.pause();
fail("InvalidProcessStateException should have been thrown.");
} catch (InvalidProcessStateException ex) {
// should happen
}
TestUtil.setState(comp, ProcessState.READY);
try {
comp.resume();
fail("InvalidProcessStateException should have been thrown.");
} catch (InvalidProcessStateException ex) {
// should happen
}
} | 5 |
private int parseOption(String option) {
if(option.equals("1")) {
return MAKE_CELL_ALIVE;
}
else if (option.equals("2")) {
return NEXT_GENERATION;
}
else if (option.equals("3")) {
return UNDO;
}
else if (option.equals("4")) {
return REDO;
}
else if (option.equals("5")) {
return HALT;
}
else return INVALID_OPTION;
} | 5 |
@Override
public void componentResized(ComponentEvent arg0) {
HEIGHT = this.getHeight();
WIDTH = this.getWidth();
resize();
} | 0 |
public void add(Integer k, Integer v) {
int nHeight = 1;
Node<Integer, Integer> x = root, y = null;
while (x != null) {
int cmp = k.compareTo(x.key);
if (cmp == 0) {
x.value = v;
return;
} else {
y = x;
if (cmp < 0) {
x = x.left;
} else {
x = x.right;
}
nHeight++;
}
}
Node<Integer, Integer> newNode = new Node<Integer, Integer>(k, v);
if (y == null) {
root = newNode;
} else {
if (k.compareTo(y.key) < 0) {
y.left = newNode;
} else {
y.right = newNode;
}
}
size++;
if (nHeight > height) {
height = nHeight;
}
} | 6 |
public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
//TODO Configurations to be added
//ConfigurationFactory factory = new ConfigurationFactory("config.xml");
//Configuration config = factory.getConfiguration();
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new DirectoryWatchService(dir, recursive).start();
} | 4 |
public void generateDataforCassandra(int uID, int noOfReplicas,
int noOfSamples, int rate) { // to measure Cassandra replicating
// performance
int tsID = 0;
long executedTime = 0;
// String test = "";
try {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
InsertRowsForDataCF iRFCF = new InsertRowsForDataCF();
Double Value = 0.0;
int minute = noOfSamples / (rate * 60);
// System.out.println(rate);
// System.out.println(noOfSamples);
// System.out.println(minute);
long firstStartTime = System.currentTimeMillis();
// double[] values = new double[rate];
// for (int i = 0; i < rate; i++) {
// values[i] = 1;
// }
if (rate > 1000) {
// System.out.println("Here");
String startTime = dateFormat.format(date); // get the time when
// sensor starts to put
// data to the backend
System.out.println("startTime-" + startTime);
while (tsID < noOfSamples - rate + 1) {
// long timeStart2 = System.currentTimeMillis();
// Random randomGenerator = new Random();
// for (int i = 0; i < rate; i++) { //comment if need to use
// the execute2 function
long timeStart = System.currentTimeMillis();
// while (System.currentTimeMillis() - timeStart < 1000 /
// rate) {
// }
// System.out.println(timeStart + " " + currentTime + " " +
// 1.0*1000 / rate);
// System.out.println(1.0*(currentTime - timeStart) + " " +
// (1.0)*1000 / rate);
// tsID++;
// Value = 1.0;
// iRFCF.execute(uID, tsID++);
// create an array of values then put the whole array to the
// backend
executedTime += iRFCF.executeMultiColumns(uID, tsID, rate);
// test += tsID;
tsID += rate;
if ((System.currentTimeMillis() - timeStart) < 1000)
Thread.sleep(1000 - (System.currentTimeMillis() - timeStart));
// end of this module
// }
// System.out.println("Took " + (System.currentTimeMillis()
// - timeStart2));
// System.out.println(tsID + " " + Value);
// if (tsID % 1000 == 0) {
// System.out.println(Value);
// // break;
// }
// if (tsID == end) {
// break;
// }
//
if ((System.currentTimeMillis() - firstStartTime) > minute * 60 * 1000) {
System.out.println("Finish putting " + tsID + " "
+ noOfSamples + " " + rate + " in "
+ executedTime + " microSec");
System.out.println("rate:" + rate);
System.out.println("drop:" + (noOfSamples - tsID));
System.out.println("ratio:" + 1.0*(tsID / noOfSamples));
break;
}
}
} else {
while (tsID < noOfSamples) {
long timeStart = System.currentTimeMillis();
// Random randomGenerator = new Random();
for (int i = 0; i < rate; i++) {
// Thread.sleep(1000 / rate);
// Value = 1.0;
iRFCF.executeOneColumn(uID, tsID++);
}
// long timeStart2 = System.currentTimeMillis();
while ((System.currentTimeMillis() - timeStart) < 1000) {
}
// System.out.println("Took " + (System.currentTimeMillis()
// - timeStart));
// System.out.println(tsID + " " + Value);
// if (tsID % 1000 == 0) {
// System.out.println(Value);
// // break;
// }
// if (tsID == end) {
// break;
// }
//
if ((System.currentTimeMillis() - firstStartTime) > minute * 60 * 1000) {
System.out.println("Finish putting " + tsID + " "
+ noOfSamples + " " + rate + " in "
+ executedTime + " microSec");
break;
}
}
}
// Close the input stream
// System.out.println("Length string is " + test.length());
System.out.println("Finish putting " + tsID + " " + noOfSamples
+ " " + rate + " in " + executedTime + " microSec");
System.out.println("rate:" + rate);
System.out.println("drop:" + (noOfSamples - tsID));
System.out.println("ratio:" + 1.0*(tsID / noOfSamples));
} catch (Exception e) {// Catch exception if any
System.out.println("Finish putting " + tsID + " " + noOfSamples
+ " " + rate + " in " + executedTime + " microSec");
System.out.println("rate:" + rate);
System.out.println("drop:" + (noOfSamples - tsID));
System.out.println("ratio:" + 1.0*(tsID / noOfSamples));
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
} | 9 |
public static void main(String[] args) {
try {
// Creating a server
ServerSocket theConnection;
theConnection = new ServerSocket(5001);
// A new socket to pick up the "request"
Socket theConversation;
theConversation = theConnection.accept();
// We create a reader on this socket as well as a writer
BufferedReader in = new BufferedReader(new InputStreamReader(
theConversation.getInputStream()));
PrintStream out = new PrintStream(new BufferedOutputStream(
theConversation.getOutputStream()));
// Reading the input from the browser
String line = in.readLine();
// get the filename
String fileName = retrieveFileName(line);
while (true) {
if (line.equals("") | line.equals("\n") | line.equals("\r")
| line.equals("\r\n"))
break;
System.out.println(line);
line = in.readLine();
}
System.out.println("Question is read");
// Answering the browser
out.println("HTTP 200 OK");
out.println("Content-type: text/html\n");
out.println(""); // this line is very important
// out.print("<html><body>I sleep!</body></html>");
BufferedReader f = new BufferedReader(new InputStreamReader(
new FileInputStream(fileName)));
String l = f.readLine();
while (l != null) {
out.println(l);
l = f.readLine();
}
// Closing the output stream
out.flush();
out.close();
in.close();
theConversation.close();
// free the serverport
theConnection.close();
} catch (IOException e) {
System.out.println("IO problem");
}
} | 4 |
protected void addMissing(Instances data, int level,
boolean attributeMissing, boolean classMissing,
int attrIndex) {
int classIndex = data.classIndex();
Random random = new Random(1);
for (int i = 0; i < data.numInstances(); i++) {
Instance current = data.instance(i);
for (int j = 0; j < data.numAttributes(); j++) {
if (((j == classIndex) && classMissing) ||
((j == attrIndex) && attributeMissing)) {
if (Math.abs(random.nextInt()) % 100 < level)
current.setMissing(j);
}
}
}
} | 7 |
@Override
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
if (getValueAt(0, column) == null) {
return String.class;
}
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
} | 3 |
public AbstractTestLinkRunListener(final T testLinkRunListener) {
this.inTestLinkListener = testLinkRunListener;
} | 0 |
@Override
public void execute(double t) {
if (hist != null && input.isConnected()) {
Matrix u = input.getInput();
hist.store(u, t);
double v = u.norm1();
if (v > maxv)
maxv = v;
}
} | 3 |
public static void main(String[] args){
f = new FrameManager();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(width, height);
f.setTitle("Nightmare");
f.setLocationRelativeTo(null);
Image icon;
try {
icon = ImageIO.read(WindowManager.class.getResourceAsStream("/images/BoyStandFront.gif"));
f.setIconImage(icon);
}
catch (IOException e){
e.printStackTrace();
}
} | 1 |
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
Funcionario f = new Funcionario();
if (!(txCodigo.getText().equals("")) || (txCodigo.getText().equals(null))){
f.setId_funcionario(Integer.parseInt(txCodigo.getText()));
}
if (txNome.getText().equals("") || txNome.getText().equals(null)){
JOptionPane.showMessageDialog(null,"Informe um nome antes de salvar!");
//btSalvarActionPerformed();
}
f.setNome(txNome.getText());
f.setTelefone(txTelefone.getText());
f.setBairro(txBairro.getText());
f.setCidade(txCidade.getText());
f.setRg(txRg.getText());
f.setCpf(txCpf.getText());
f.setEndereco(txEndereco.getText());
f.setSalario(Double.parseDouble(txSalario.getText()));
f.setCtps(txCtps.getText());
f.setFuncao(txFuncao.getText());
f.setLOJA_id_loja(Integer.parseInt(txLoja.getText()));
f.setUSUARIO_id_usuario(Integer.parseInt(txUsuario.getText()));
FuncionarioController fc = new FuncionarioController();
if (f.getId_funcionario()== 0){
int id = fc.salvar(f);
if(id > 0){
modelo.addRow(new Object[]{id, f.getNome(), f.getTelefone(), f.getBairro(), f.getCidade(), f.getRg(), f.getCpf(), f.getEndereco(), f.getSalario(), f.getCtps(), f.getFuncao(), f.getLOJA_id_loja(), f.getUSUARIO_id_usuario()});
JOptionPane.showMessageDialog(null,"Funcionário cadastrado com sucesso!");
}
}else{
int id = fc.salvar(f);
if(id > 0){
modelo.removeRow(linhaSelecionada);
modelo.addRow(new Object[]{id, f.getNome(), f.getTelefone(), f.getBairro(), f.getCidade(), f.getRg(), f.getCpf(), f.getEndereco(), f.getSalario(), f.getCtps(), f.getFuncao(), f.getLOJA_id_loja(), f.getUSUARIO_id_usuario()});
JOptionPane.showMessageDialog(null, "Funcionário atualizado com sucesso!");
}
}
dispose();
}//GEN-LAST:event_btSalvarActionPerformed | 7 |
public static void saveBubbleDiagram(File file)
{
try {
PrintWriter writer = new PrintWriter(file);
writer.println("Bubbles:");
for(Bubble bubble : Main.flowChart.getBubbles())
{
Point loc = bubble.getLocation();
writer.println("bubble:"+bubble.getId()+":"+loc.x+":"+loc.y+":"+bubble.getRadius()+":"+bubble.getText());
}
for(Bubble bubble : Main.flowChart.getBubbles())
{
for(Arrow arrow : bubble.getArrows())
{
//Both start and end hold the arrow, so only add an arrow if it is start
//to prevent duplicate arrows.
if(arrow.getStart() == bubble)
writer.println("arrow:"+arrow.getStart().getId()+":"+arrow.getEnd().getId());
}
}
writer.println("end");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
@SuppressWarnings("rawtypes")
public static SingleColumnComparator createDoubleComparator(NumberName numberName, boolean ascending, String defaultString) throws Exception
{
final String type="double";
if (ascending)
{
if (defaultString.equals(""))
{
return new SingleColumnComparator(numberName,ascending,type,defaultString)
{
public Comparable generateKey(String[] parts) throws Exception
{
return new Double(getDoubleValue(parts));
}
};
}
else
{
final Double defaultKey = Double.valueOf(defaultString);
return new SingleColumnComparator(numberName,ascending,type,defaultString)
{
public Comparable generateKey(String[] parts) throws Exception
{
try
{
return new Double(getDoubleValue(parts));
}
catch (Exception e)
{
return defaultKey;
}
}
};
}
}
else
{
if (defaultString.equals(""))
{
return new SingleColumnComparator(numberName,ascending,type,defaultString)
{
public Comparable generateKey(String[] parts) throws Exception
{
return new Double(-getDoubleValue(parts));
}
};
}
else
{
final Double defaultKey = new Double(-Double.parseDouble(defaultString));
return new SingleColumnComparator(numberName,ascending,type,defaultString)
{
public Comparable generateKey(String[] parts) throws Exception
{
try
{
return new Double(-getDoubleValue(parts));
}
catch (Exception e)
{
return defaultKey;
}
}
};
}
}
} | 5 |
@Test
public void testAsteroidVelocityInfluencedByGameSpeed() {
ArrayList<Asteroid> astX = new ArrayList<Asteroid>();
ArrayList<Asteroid> astY = new ArrayList<Asteroid>();
p.setGameSpeed(1.2);
for (int i = 0; i < 20; i++) {
p.spawnAsteroids();
}
for (Asteroid a : p.getAsteroids()) {
if (a.getVelX() > 2.5 || a.getVelX() < -2.5) {
astX.add(a);
}
if (a.getVelY() > 2.5 || a.getVelY() < -2.5) {
astY.add(a);
}
}
if(astX.size()<1||astY.size()<1){
assertTrue(false);
}
} | 8 |
public void removeShadow(Player player)
{
for (Castle c: player.getCastles()) {
core.Point p = p2o.get(c);
player.removeShadowRadius(p.x, p.y, 3);
}
} | 1 |
@Override
public void deactivateFrame(JInternalFrame f) {
//System.out.println("deactivateFrame");
super.deactivateFrame(f);
} | 0 |
public void btnConfirmarAgendamento() {
facesContext = FacesContext.getCurrentInstance();
Solicitacoes solicitacao = solicitacaoSelecionada.getSolicitacao();
solicitacao.setSol_status("Autorizado");
autorizar.setAut_data_horaAtual(new Timestamp(System.currentTimeMillis()));
autorizar.setAut_profAgendamento(SecurityContextHolder.getContext().getAuthentication().getName());
autorizar.setSolicitacoes(solicitacaoSelecionada);
try {
List<Controle> listControle = genericDAO.searchObject(Controle.class, "controle", null, null,
new String[]{"exame"}, new Object[]{solicitacaoSelecionada.getDescricaoExames()});
if (listControle.isEmpty()) {
genericDAO.save(autorizar);
genericDAO.update(solicitacao);
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso", "Autorizado com sucesso"));
} else {
Controle controle = listControle.get(0);
if (controle.getCtrl_limiteUnitario() > 0
&& controle.getCtrl_limiteValor() > solicitacaoSelecionada.getDescricaoExames().getDes_valor()) {
controle.setCtrl_limiteUnitario(controle.getCtrl_limiteUnitario() - 1);
controle.setCtrl_limiteValor(controle.getCtrl_limiteValor() - solicitacaoSelecionada.getDescricaoExames().getDes_valor());
genericDAO.save(autorizar);
genericDAO.update(solicitacao);
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Sucesso", "Autorizado com sucesso"));
} else {
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Limite", "o limite para esse procedimento já foi alcançado!"));
}
}
} catch (Exception ex) {
Logger.getLogger(AutorizarMB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
init();
}
} | 4 |
public static String authenticateToken(String username, String token)
throws SQLException {
String auth_pass = getPassword(username);
String plain_token = UserServices.decrypt(token,
UserServices.generateKeys(auth_pass));
Statement statement = mysqlDB.createStatement();
ResultSet result = statement
.executeQuery("select * from v_user_info where Username = '"
+ username + "'");
String[] columns = new String[] { "Token" };
result.first();
String ret = "";
for (int i = 0; i < columns.length; i++) {
ret = result.getString(columns[i]);
}
if (plain_token.equals(ret)) {
if (result.getDate("Start").before(new Date())
&& result.getDate("End").after(new Date())) {
return "1";
}
}
statement.close();
return "0";
} | 4 |
public static void main(String[] args) {
DWT _dwt = new DWT();
/* ----------------- Test for zigzag --------------------*/
double[][] _input = {{49, 61, 69, 61, 78, 89, 100, 112}
, {68, 60, 51, 42, 62, 69, 80, 89}
, {90, 81, 58, 49, 69, 72, 68, 69}
, {100, 91, 79, 72, 69, 68, 59, 58}
, {111, 100, 101, 91, 82, 71, 59, 49}
, {131, 119, 120, 102, 90, 90, 81, 59}
, {148, 140, 129, 99, 92, 78, 59, 39}
, {151, 140, 142, 119, 98, 90, 72, 39}};
ArrayList<Double> _output = _dwt.DwtZigzag(_input, 8, 0, 0, 64);
for (Double _tem : _output) {
System.out.print(_tem + " ");
}
/*-----------------end Test for zigzag-----------------------*/
/* ----------------- Test for Izigzag --------------------*/
System.out.println("\n Output the Origin: \n");
for (int i = 0; i < _input.length; i++) {
System.out.print("\n");
for (int j = 0; j < _input[0].length; j++) {
System.out.print(_input[i][j] + " ");
}
}
double[][] _IDWZout = _dwt.IDwtZigzag(_output, 8, 0);
System.out.println("\n Output the matrix: \n");
for (int i = 0; i < _IDWZout.length; i++) {
System.out.print("\n");
for (int j = 0; j < _IDWZout[0].length; j++) {
System.out.print(_IDWZout[i][j] + " ");
}
}
} | 5 |
@Override
public void draw(Pixel pixel, SinglePlayerGame game, Graphics g) {
MortalEntity entity = (MortalEntity) game.getEntity(pixel.x, pixel.y);
if (entity != null) {
float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
Color c = Color.getHSBColor(hsb[0], hsb[1],
(float) entity.getHealth() / entity.getMaxHP() * hsb[2]);
g.setColor(c);
g.fillRect(game.getPixelSize() * pixel.x, game.getPixelSize() * pixel.y, game.getPixelSize(), game.getPixelSize());
}
} | 1 |
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.