method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
3997ff71-f285-4d45-ab97-b5a82a512189 | 4 | public static Path writeMatrix(double[][] matrix, Path path,
HamaConfiguration conf) {
SequenceFile.Writer writer = null;
try {
FileSystem fs = FileSystem.get(conf);
writer = new SequenceFile.Writer(fs, conf, path, IntWritable.class,
VectorWritable.class);
for (int i = 0; i < matrix.length; i++) {
DenseDoubleVector rowVector = new DenseDoubleVector(matrix[i]);
writer.append(new IntWritable(i), new VectorWritable(rowVector));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return path;
} |
5aed241f-3484-445c-94fe-3adc86d33639 | 5 | private SQLiteDriver(Plugin p, HashMap<String, String> c) {
plugin = p;
this.db = c.get("database");
this.prefix = c.get("prefix");
this.user = c.get("user");
this.pass = c.get("password");
this.dbg = (c.containsKey("debug")) ? this.parseBool(c.get("debug"), false) : false;
String dbPath = "jdbc:sqlite:" + plugin.getDataFolder() + java.io.File.separator + this.db + ".db";
try{
Class.forName("org.sqlite.JDBC");
this.con = DriverManager.getConnection(dbPath, this.user, this.pass);
}catch(SQLException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to connect to database: SQL error!");
if(this.dbg) {
plugin.getLogger().log(Level.INFO, e.getMessage(), e);
}
}catch(ClassNotFoundException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to connect to database: SQLite library not found!");
if(this.dbg) {
plugin.getLogger().log(Level.INFO, e.getMessage(), e);
}
}
} |
820ff520-7046-4954-becc-6257d0010842 | 3 | public String delete(String id){
HttpClient httpClient = new DefaultHttpClient();
HttpDelete httpDelete = new HttpDelete(Url+"&id="+id);
String backRes = "-1";
try {
HttpResponse httpResponse = httpClient.execute(httpDelete);
int backCode = httpResponse.getStatusLine().getStatusCode();
if(backCode == HttpStatus.SC_OK){
String strBack = InputStreamUtils.inputStream2String(httpResponse.getEntity().getContent());
JSONObject jsonBack = JSONObject.fromObject(strBack);
backRes = jsonBack.getString("status");
if(backRes.equals("0"))
return backRes;
else
return "-1";
}
} catch (IOException e) {
e.printStackTrace();
}
return backRes;
} |
e81dbe0f-a01d-4ce2-9bfc-29f55d671fcb | 3 | private static void printGridletList(GridletList list, String name,
boolean detail)
{
int size = list.size();
Gridlet gridlet = null;
String indent = " ";
System.out.println();
System.out.println("============= OUTPUT for " + name + " ==========");
System.out.println("Gridlet ID" + indent + "STATUS" + indent +
"Resource ID" + indent + "Cost");
// a loop to print the overall result
int i = 0;
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.print(indent + gridlet.getGridletID() + indent
+ indent);
System.out.print( gridlet.getGridletStatusString() );
System.out.println( indent + indent + gridlet.getResourceID() +
indent + indent + gridlet.getProcessingCost() );
}
if (detail == true)
{
// a loop to print each Gridlet's history
for (i = 0; i < size; i++)
{
gridlet = (Gridlet) list.get(i);
System.out.println( gridlet.getGridletHistory() );
System.out.print("Gridlet #" + gridlet.getGridletID() );
System.out.println(", length = " + gridlet.getGridletLength()
+ ", finished so far = " +
gridlet.getGridletFinishedSoFar() );
System.out.println("======================================\n");
}
}
} |
6019fe1d-b803-4c8c-87d3-dd6a6b8d5d99 | 5 | public PointGame findAStupidPlace() {
PointGame pointToPlace = null;
// High Priority: form a mill.
for (PointGame pt : Board.validPoints) {
if (!Board.isOccupied(pt) && hasMills(pt)) {
pointToPlace = pt;
//System.out.println(pointToPlace);
return pointToPlace;
}
}
for (PointGame pt : Board.validPoints) {
if (!Board.isOccupied(pt)) {
System.out.println(pt);
System.out.println(hasMills(pt));
pointToPlace = pt;
return pointToPlace;
}
}
return pointToPlace;
} |
56e62b51-f243-48c2-b0da-bf004e256d32 | 8 | public static Hashtable getLargestConnectedSubgraph(GraphEltSet ges) {
int nodeCount = ges.nodeCount();
if(nodeCount==0) return null;
Vector subgraphVector = new Vector();
for(int i=0; i<nodeCount; i++) {
Node n = ges.nodeAt(i);
boolean skipNode=false;
for (int j = 0; j<subgraphVector.size();j++) {
if(((Hashtable) subgraphVector.elementAt(j)).contains(n)) {
skipNode=true;
}
}
// Collection subgraph = calculateDistances(ges,n,1000).keySet();
Hashtable subgraph = calculateDistances(ges,n,1000);
if(subgraph.size()>nodeCount/2) return subgraph; //We are done
if (!skipNode) subgraphVector.addElement(subgraph);
}
int maxSize=0;
int maxIndex=0;
for (int j = 0; j<subgraphVector.size();j++) {
if(((Hashtable) subgraphVector.elementAt(j)).size()>maxSize) {
maxSize = ((Hashtable) subgraphVector.elementAt(j)).size();
maxIndex = j;
}
}
return (Hashtable) subgraphVector.elementAt(maxIndex);
} |
d6618e64-fe0b-40e6-b115-167b4892d4eb | 8 | public List<Entity> getEntities(int x0, int y0, int x1, int y1) {
List<Entity> result = new ArrayList<Entity>();
int xt0 = (x0 >> 4) - 1;
int yt0 = (y0 >> 4) - 1;
int xt1 = (x1 >> 4) + 1;
int yt1 = (y1 >> 4) + 1;
for (int y = yt0; y <= yt1; y++) {
for (int x = xt0; x <= xt1; x++) {
if (x < 0 || y < 0 || x >= w || y >= h) continue;
List<Entity> entities = entitiesInTiles[x + y * this.w];
for (int i = 0; i < entities.size(); i++) {
Entity e = entities.get(i);
if (e.intersects(x0, y0, x1, y1)) result.add(e);
}
}
}
return result;
} |
af53f26b-5534-4c68-af69-d82a722a2646 | 2 | private void mergeReports() {
File firstReportDir = config.getMergeDirs().get(0);
ioUtils.copyDir(firstReportDir, config.getMergeDestDir());
String[] data = new String[config.getMergeDirs().size()];
for (int i = 0; i < data.length; i++) {
File dataFile = new File(config.getMergeDirs().get(i), "jscoverage.json");
data[i] = ioUtils.loadFromFileSystem(dataFile);
}
SortedMap<String, FileData> mergedMap = jsonDataMerger.mergeJSONCoverageStrings(data);
config.getMergeDestDir().mkdirs();
File mergedJson = new File(config.getMergeDestDir(), "jscoverage.json");
ioUtils.copy(jsonDataMerger.toJSON(mergedMap), mergedJson);
File srcDir = new File(config.getMergeDestDir(), jscover.Main.reportSrcSubDir);
for (int i = 1; i < config.getMergeDirs().size(); i++)
ioUtils.copyDir(new File( config.getMergeDirs().get(i), jscover.Main.reportSrcSubDir), srcDir);
} |
215e4088-7e2e-494b-855d-a6f7369ebc46 | 7 | @Override
public Coordinates nextMove(GameBoard gb) {
oldTime = System.currentTimeMillis() - timeoutOffset;
timeoutHasOccured = false;
boardSize = gb.getSize();
int alpha = LOOSE;
Coordinates bestMove = null;
int bestScore = 0;
ArrayList<Coordinates> openCoordinatesList = getOpenCoordinates(gb, player);
if (openCoordinatesList.size() == 0) {
return null;
}
int depth = beginningDepth;
//try
//{
while (!timeoutHasOccured) {
checkTimeout();
alpha = LOOSE;
Coordinates depthBestMove = null;
for (Coordinates coord : openCoordinatesList) {
GameBoard gbClone = gb.clone();
gbClone.checkMove(player, coord);
gbClone.makeMove(player, coord);
int score = RecursionStep(gbClone, alpha, WIN, depth - 1, -1);
//System.out.print(score+": ");
if (score > alpha) {
alpha = score;
depthBestMove = coord;
//System.out.println("no failure atm");
}
//else
//System.out.println("failure while trying depth "+depth);
}
if (depthBestMove != null) {
bestMove = depthBestMove;
bestScore = alpha;
}
depth++;
}
//}
//catch(Exception e)
//{}
if (timeoutHasOccured) {
long timer = System.currentTimeMillis() - oldTime;
if (bestMove != null) {
System.out.println("Ingwer got till depth "
+ (depth - 1)
+ ", and is expecting a approximate score of "
+ String.valueOf(bestScore)
+ ". "
+ "It needed "
+ (timer)
+ " milliseconds.");
return bestMove;
} else {
System.out.println("Ingwer couldn't finish lowest depth "
+ depth + " and is therefore returning a pseudo-random coord. "
+ "It needed "
+ (timer)
+ " milliseconds.");
return openCoordinatesList.get(0);
}
} else {
return null;
}
} |
0a50dd86-041a-4662-99ec-5defe4dd45a1 | 2 | void collisionCheck(){
inBounds();
for(collidableObject tempObj : listWrecks){
if(tempObj.isColliding(posX, posY)){ reset(); break; }
}
} |
0918e7ea-f855-4bb4-a5f4-9b8c06bb4ee8 | 9 | @Override public void init() {
// 234 : 402 => 0.5820895522
// 402 : 234 => 1.7179487179
dayLeft = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
dayMid = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
dayRight = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
dateLeft = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.NUMERIC).textColor(Color.WHITESMOKE).build();
dateRight = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.NUMERIC).textColor(Color.WHITESMOKE).build();
monthLeft = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
monthMid = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
monthRight = SplitFlapBuilder.create().prefWidth(146).prefHeight(250).flipTime(300).selection(SplitFlap.ALPHA).textColor(Color.WHITESMOKE).build();
hourLeft = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_5).textColor(Color.WHITESMOKE).build();
hourRight = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_9).textColor(Color.WHITESMOKE).build();
minLeft = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_5).textColor(Color.WHITESMOKE).build();
minRight = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_9).textColor(Color.WHITESMOKE).build();
secLeft = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_5).textColor(Color.ORANGERED).build();
secRight = SplitFlapBuilder.create().prefWidth(200).prefHeight(343).flipTime(300).selection(SplitFlap.TIME_0_TO_9).textColor(Color.ORANGERED).build();
lastTimerCall = System.nanoTime();
timer = new AnimationTimer() {
@Override public void handle(long now) {
if (now > lastTimerCall + 500_000_000l) {
String day = WEEK_DAYS[LocalDateTime.now().getDayOfWeek().getValue()];
if (day.equals("SAT") || day.equals("SUN")) {
if (!dayLeft.getTextColor().equals(Color.CRIMSON)) {
dayLeft.setTextColor(Color.CRIMSON);
dayMid.setTextColor(Color.CRIMSON);
dayRight.setTextColor(Color.CRIMSON);
}
} else {
if (!dayLeft.getText().equals(Color.WHITESMOKE)) {
dayLeft.setTextColor(Color.WHITESMOKE);
dayMid.setTextColor(Color.WHITESMOKE);
dayRight.setTextColor(Color.WHITESMOKE);
}
}
dayLeft.setText(day.substring(0, 1));
dayMid.setText(day.substring(1, 2));
dayRight.setText(day.substring(2));
date = LocalDateTime.now().getDayOfMonth();
String dateString = Integer.toString(date);
if (date < 10) {
dateLeft.setText("0");
dateRight.setText(dateString.substring(0, 1));
} else {
dateLeft.setText(dateString.substring(0, 1));
dateRight.setText(dateString.substring(1));
}
String month = MONTHS[LocalDateTime.now().getMonthValue()];
monthLeft.setText(month.substring(0, 1));
monthMid.setText(month.substring(1, 2));
monthRight.setText(month.substring(2));
hours = LocalDateTime.now().getHour();
String hourString = Integer.toString(hours);
if (hours < 10) {
hourLeft.setText("0");
hourRight.setText(hourString.substring(0, 1));
} else {
hourLeft.setText(hourString.substring(0, 1));
hourRight.setText(hourString.substring(1));
}
minutes = LocalDateTime.now().getMinute();
String minutesString = Integer.toString(minutes);
if (minutes < 10) {
minLeft.setText("0");
minRight.setText(minutesString.substring(0, 1));
} else {
minLeft.setText(minutesString.substring(0, 1));
minRight.setText(minutesString.substring(1));
}
seconds = LocalDateTime.now().getSecond();
String secondsString = Integer.toString(seconds);
if (seconds < 10) {
secLeft.setText("0");
secRight.setText(secondsString.substring(0, 1));
} else {
secLeft.setText(secondsString.substring(0, 1));
secRight.setText(secondsString.substring(1));
}
lastTimerCall = now;
}
}
};
} |
47b2574c-178a-49dc-9022-2a854a6cdf31 | 6 | public ListNode removeNthFromEnd(ListNode head, int n) {
if (n <= 0) {
return head;
}
ListNode first = head;
while (head != null && n > 0) {
head = head.next;
n--;
}
if (n != 0) {
return first;
}
ListNode cur = new ListNode(0);
cur.next = first;
while (head != null) {
head = head.next;
cur = cur.next;
}
//remove cur
if (cur.next == first) {
return cur.next.next;
} else {
cur.next = cur.next.next;
return first;
}
} |
23aa5946-79e0-43ad-aaf7-5184c48d167c | 4 | private void toggleAutoRestart(int level, String[] keywords) {
if (isAccountTypeOf(level, ADMIN, MODERATOR)) {
if (keywords.length == 2) {
if (Functions.isNumeric(keywords[1])) {
Server s = getServer(Integer.parseInt(keywords[1]));
if (s.auto_restart) {
s.auto_restart = false;
sendMessage(cfg_data.irc_channel, "Autorestart disabled on server.");
}
else {
s.auto_restart = true;
sendMessage(cfg_data.irc_channel, "Autorestart set up on server.");
}
}
}
else
sendMessage(cfg_data.irc_channel, "Correct usage is .autorestart <port>");
}
else
sendMessage(cfg_data.irc_channel, "You do not have permission to use this command.");
} |
7dbfc306-5a10-4816-844c-8616a82ec8a1 | 0 | public FiniteStateAutomaton() {
super();
} |
3bda5780-f905-4e47-88f2-3ad832743871 | 1 | public void updateDiscDisplay(Disc disc) {
tDiscName.setText(disc.getName());
switch(disc.getManufacturer()) {
case INNOVA:
tManufacturer.setText("Innova");
break;
default:
tManufacturer.setText("?");
break;
}
tManufacturer.setText(disc.getManufacturer().toString());
tDiscType.setText(disc.getDiscType().toString());
tSpeed.setText("" + disc.getSpeed());
tGlide.setText("" + disc.getGlide());
tTurn.setText("" + disc.getTurn());
tFade.setText("" + disc.getFade());
} |
5f0d099a-58d2-4cc1-93ad-d89248ffb723 | 4 | private void saveSession() {
if (this.lastTime != null && this.curRawData.getTime() - this.lastTime >= 0.001) {
if (this.i >= 99) {
this.curSession = new SessionDao().createOrUpdateSession(this.curSession);
this.slf4j.info("curSession :");
this.slf4j.info(" Session Id :" + this.curSession.getId());
this.slf4j.info(" Nb Lap :" + this.curSession.getLapSet().size());
this.slf4j.info("curLap :");
this.slf4j.info(" Lap Id :" + this.curLap.getId());
this.slf4j.info(" Nb Data :" + this.curLap.getRawDataSet().size());
this.i = 0;
}
this.lastTime = this.curRawData.getTime();
this.i++;
} else if (this.lastTime == null) {
this.lastTime = this.curRawData.getTime();
}
} |
733c85ea-22ba-4314-b803-7c8a9ab423e3 | 1 | private void backClicked()
{
WindowStack ws = WindowStack.getLastInstance();
if (ws != null) {
ws.pop();
}
} |
efe492ed-1b64-4286-bcd0-323ce670832f | 5 | private void revealArea(int position)
{
if (isFlagged(position)) {
return;
}
changeState(position, BoxState.SAFE);
for (int i : map.getNeighbors(position)) {
int v = map.getValueAt(i);
boolean recursivelyReveal = v == 0 && boxStates[i] == BoxState.UNEXPLORED;
if (recursivelyReveal) {
revealArea(i);
}
else {
if (isFlagged(i)) {
continue;
}
changeState(i, BoxState.SAFE);
}
}
} |
3efe7077-2bf4-4cc8-bf65-adfbf0a1e4d6 | 1 | public void setMatrix(Matrix set, int i){
if(set.getRowDimension() == dimension){
XMatrix[i] = set.copy();
return;
}
else{
return;
}
} |
148a97da-626b-4a14-a199-5b1525767f7d | 7 | private void addIgnore(long target) {
try {
if (target == 0L)
return;
if (ignoreCount >= 100) {
pushMessage("Your ignore list is full. Max of 100 hit", 0, "");
return;
}
String targetName = TextClass.formatName(TextClass
.longToName(target));
for (int p = 0; p < ignoreCount; p++)
if (ignoreListAsLongs[p] == target) {
pushMessage(targetName + " is already on your ignore list",
0, "");
return;
}
for (int p = 0; p < friendsCount; p++)
if (friendsListAsLongs[p] == target) {
pushMessage("Please remove " + targetName
+ " from your friend list first", 0, "");
return;
}
ignoreListAsLongs[ignoreCount++] = target;
redrawTab = true;
stream.putOpcode(133);
stream.putLong(target);
return;
} catch (RuntimeException runtimeexception) {
signlink.reporterror("45688, " + target + ", " + 4 + ", "
+ runtimeexception.toString());
}
throw new RuntimeException();
} |
858b504b-3b2b-4fa5-b542-b483a424ecb2 | 1 | synchronized void shutdown() {
try {
mClientSocket.close();
} catch (Exception exception) {
Log.error(exception);
}
mServer.remove(this);
} |
89417fa6-bafe-49b8-9f49-e8f27f42ea60 | 3 | @Override
public void run() {
try {
isRunning = true;
while (isRunning) {
Thread.sleep(5L);
if (network.hasMessageToSend()) {
writer.write(network.poll(EnumMessageType.SEND).toString() + "\r\n");
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} |
28c301ce-f44c-4ae8-bbc5-139bacc5576a | 7 | static final Class348_Sub21 method199(int i) {
anInt8369++;
if (Class75.aClass262_1254 == null || r.aClass312_9716 == null)
return null;
r.aClass312_9716.method2328(Class75.aClass262_1254, 75);
Class348_Sub21 class348_sub21
= (Class348_Sub21) r.aClass312_9716.method2327((byte) -53);
if (class348_sub21 == null)
return null;
Class42 class42
= Class75.aClass153_1238.method1225(((Class348_Sub21)
class348_sub21).anInt6847,
(byte) 50);
if (i != 1)
anInt8370 = -75;
if (class42 != null && ((Class42) class42).aBoolean609
&& class42.method373(Class75.anInterface17_1244, 98))
return class348_sub21;
return HashTable.method3479(-1);
} |
c351aa97-db59-4d62-8ff9-c41237eef5d1 | 4 | public List<Integer> findMatchingPatterns() {
List<Integer> patternList = new ArrayList<Integer>();
int count = 0;
while (this.text.length() > 0) {
Tree.Node<String, Integer> parent = trie.getRoot();
for (int i = 0; i < text.length(); i++) {
if (isPatternPresent(parent, 0)) {
patternList.add(count);
}
this.text = this.text.substring(1);
this.recursive = true;
count++;
}
}
for (Integer i : patternList) {
System.out.print(i + " ");
}
return patternList;
} |
49a4839e-e060-4f96-abbe-2207a740e587 | 6 | public void setDrawable (Drawable drawable) {
if (drawable != null) {
if (this.drawable == drawable) return;
if (getPrefWidth() != drawable.getMinWidth() || getPrefHeight() != drawable.getMinHeight()) invalidateHierarchy();
} else {
if (getPrefWidth() != 0 || getPrefHeight() != 0) invalidateHierarchy();
}
this.drawable = drawable;
} |
631d66f5-0f9c-41c5-8f22-5018bb544791 | 2 | public static void init()
{
Date currentDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("dd_MM_yy_hh_mm_ss");
outPutfolder = df.format(currentDate);
String strBrowserType = conf.getString("BrowserType");
if(strBrowserType.equals("InternetExplorer"))
{
System.setProperty("webdriver.ie.driver","D:\\bin\\drivers\\IEDriver.exe");
driver=new InternetExplorerDriver();
}
else if(strBrowserType.equals("Chrome")){
System.setProperty("webdriver.chrome.driver","D:\\bin\\drivers\\chromedriver.exe");
driver=new ChromeDriver();
}else{
driver = new FirefoxDriver();
}
} |
6bd57f64-8258-4eb8-8602-8bb33edec5ae | 6 | 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(session.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(session.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(session.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(session.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 session().setVisible(true);
}
});
} |
05304248-a008-4151-aba6-f55fa82d408c | 3 | @Override
public List<MedicineDTO> getAllMedicines() throws SQLException {
Session session = null;
List<MedicineDTO> medicines = new ArrayList<MedicineDTO>();
try {
session = HibernateUtil.getSessionFactory().openSession();
medicines = session.createCriteria(MedicineDTO.class).list();
}
catch (Exception e) {
System.err.println("Error while adding an illness!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
return medicines;
} |
8a059f60-a9a3-4f1b-ae16-a206ae29bd19 | 0 | public Object getData(){
return this.data;
} |
ecb3801b-7765-4143-b37c-62829ec396af | 6 | @Override
public synchronized void run() {
while (!done) {
try {
while (!paused) {
if (count > 0) {
Core.cycle(1);
count--;
updatecount--;
} else if (infloop) {
Core.cycle(1);
updatecount--;
} else {
tv.updateDisplay(); // update when we pause/stop running code
paused = true;
}
if (updatecount<=0) {
tv.updateDisplay();
updatecount=UPDATECOUNT;
}
Thread.yield();
}
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
43dd2d2c-d9b5-420a-a226-77155c526792 | 4 | public static int smallestSuccessor( int n ) {
// get p, get c0 and c1
// p is the position of the first non-trailing zero
// c0 is the length of the trailing zeros
// c1 is the length the 1's left to the trailing zeros
//c0
int num = n;
int c0 = 0;
while ( isLastDigitZero( num ) ) {
c0++;
num = num >> 1;
}
if ( c0 >= 30 ) { return -1; } // no such successsor exists
int c1 = 0;
while ( isLastDigitOne( num ) ) {
c1++;
num = num >> 1;
}
if ( c0 + c1 >= 31 ) {
return -1;
}
int p = c0 + c1;
// set pth digit to 1
n = n | (1 << p);
// set the c0 + c1 digits to 0s
n = n & ( -1 << p );
// set the last c1-1 digits to 1s
n = n | ~(-1 << c1-1);
return n;
} |
14962a22-6bab-45c0-b06b-80ef4021cc35 | 9 | private static boolean bestPermutation (Tour tour, int a, int b, int c, int d, int e, int f) {
City A = tour.getCity(a);
City B = tour.getCity(b);
City C = tour.getCity(c);
City D = tour.getCity(d);
City E = tour.getCity(e);
City F = tour.getCity(f);
double[] dist = new double[8];
dist[0] = A.distanceTo(B) + C.distanceTo(E) + D.distanceTo(F);
dist[1] = A.distanceTo(C) + B.distanceTo(D) + E.distanceTo(F);
dist[2] = A.distanceTo(C) + B.distanceTo(E) + D.distanceTo(F);
dist[3] = A.distanceTo(D) + E.distanceTo(B) + C.distanceTo(F);
dist[4] = A.distanceTo(D) + E.distanceTo(C) + B.distanceTo(F);
dist[5] = A.distanceTo(E) + D.distanceTo(B) + C.distanceTo(F);
dist[6] = A.distanceTo(E) + D.distanceTo(C) + B.distanceTo(F);
dist[7] = A.distanceTo(B) + C.distanceTo(D) + E.distanceTo(F);
int index = 0;
double min = Double.MAX_VALUE;
for (int i = 0; i < dist.length; i++)
if (dist[i] < min) {
index = i;
min = dist[i];
}
if (index == 0) {
tour.setCity(d, E);
tour.setCity(e, D);
exchange(tour, c+2, e-1);
return false;
} else if (index == 1) {
tour.setCity(b, C);
tour.setCity(c, B);
exchange(tour, a+2, c-1);
return false;
} else if (index == 2) {
tour.setCity(b, C);
tour.setCity(c, B);
tour.setCity(d, E);
tour.setCity(e, D);
exchange(tour, a+2,c-1);
exchange(tour, c+2,e-1);
return false;
} else if (index == 3) {
tour.setCity(b, D);
tour.setCity(c, E);
tour.setCity(d, B);
tour.setCity(e, C);
exchange(tour, a+2,e-1);
exchange(tour, a+2,c-1);
exchange(tour, c+2,e-1);
return false;
} else if (index == 4) {
tour.setCity(b, D);
tour.setCity(c, E);
tour.setCity(d, C);
tour.setCity(e, B);
exchange(tour, c+2,e-1);
exchange(tour, a+2,e-1);
return false;
} else if (index == 5) {
tour.setCity(b, E);
tour.setCity(c, D);
tour.setCity(d, B);
tour.setCity(e, C);
exchange(tour, a+2,c-1);
exchange(tour, a+2,e-1);
return false;
} else if (index == 6) {
tour.setCity(b, E);
tour.setCity(e, B);
exchange(tour, a+2,e-1);
return false;
} else {
return true;
}
} |
cc2da0a2-7668-4a33-a5aa-fd59d124917d | 4 | public int oneSidedBinarySearch(int[] arr, int K) {
int log2 = getLog(arr.length);
int currentI = 0;
while (log2 >= -1) {
System.out.println("currentI: " + currentI);
System.out.println("arr[currentI]: " + arr[currentI]);
if (arr[currentI] == K) {
return arr[currentI];
} else if (arr[currentI] < K) { // jump right
int newIndex = currentI + (1 << log2);
if (newIndex < arr.length) {
currentI = newIndex;
}
} else { // jump left
currentI = currentI - (1 << log2);
}
log2--;
}
return -1;
} |
301b7a4f-7960-4749-a7f5-edc8ed719855 | 7 | public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
dao.imp.DatabaseBean db = null;
synchronized (_jspx_page_context) {
db = (dao.imp.DatabaseBean) _jspx_page_context.getAttribute("db", PageContext.PAGE_SCOPE);
if (db == null){
db = new dao.imp.DatabaseBean();
_jspx_page_context.setAttribute("db", db, PageContext.PAGE_SCOPE);
}
}
out.write("\n");
out.write("<!DOCTYPE html>\n");
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
out.write(" <title>JSP Page</title>\n");
out.write(" </head>\n");
out.write(" <body>\n");
out.write(" <h1>Hello World!</h1>\n");
out.write(" ");
if (_jspx_meth_c_choose_0(_jspx_page_context))
return;
out.write("\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
} |
5375bc51-b9ef-4e70-9e85-858f7a4980da | 2 | public void uploadFiles(final String localDirectory, final Collection<String> filenames) throws IOException {
new Thread(new Runnable() {
@Override
public void run() {
try {
connect();
InputStream is;
for (String filename : filenames) {
is = new FileInputStream(localDirectory + File.separator + filename);
client.storeFile(filename, is);
is.close();
}
disconnect();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}).start();
} |
4abc10ae-a0b5-43d1-ad44-3b5c2444e825 | 0 | @Override
public Iterator<AbstractPlay> iterator() {
return plays.iterator();
} |
6a585604-0d06-4678-ac96-6dba0c5247ca | 3 | public Id addOrComplete(Element<?> element) {
for (Element actual : elements) {
if (actual.isSameElementAs(element)) {
actual.completeWith(element);
return actual.getId();
}
}
// still there? one doesn't find it, so let's create it
Id id = nextId();
elements.add(element.usingId(id));
return id;
} |
4f41d3bf-3578-4d10-ab4c-b06367f54976 | 6 | private void btnGoResaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGoResaActionPerformed
if (txtDate.getText().equals("")) {
JOptionPane.showMessageDialog(null, "La date est obligatoire.", "Erreur", JOptionPane.ERROR_MESSAGE);
return;
}
String oeuvre = "";
if (txtNomOeuvre.getText().equals("")) {
oeuvre = cmbOeuvres.getSelectedItem().toString();
} else {
oeuvre = txtNomOeuvre.getText();
}
String nom, prenom;
if (txtNom.getText().equals("") && txtPrenom.getText().equals("")) {
String utilisateur = cmbUsager.getSelectedItem().toString();
String[] util = utilisateur.split(" ");
nom = util[0];
prenom = util[1];
} else {
nom = txtNom.getText();
prenom = txtPrenom.getText();
}
try {
Date date = new SimpleDateFormat("dd/MM/yy", Locale.FRANCE).parse(txtDate.getText());
int ret = ihm.reserverOeuvre(nom, prenom, oeuvre, date);
if (ret < 0) {
JOptionPane.showMessageDialog(null, "Oeuvre ou Utilisateur incorrect.", "Erreur", JOptionPane.ERROR_MESSAGE);
} else {
MainWindow mw = new MainWindow();
mw.setVisible(true);
mw.setLocationRelativeTo(null);
this.setVisible(false);
}
} catch (ParseException ex) {
JOptionPane.showMessageDialog(null, "Le format de date ne correspond pas. (xx/xx/xxxx)", "Erreur", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnGoResaActionPerformed |
5914529f-87e2-4450-aee8-455e01d3123a | 9 | void updateStorage(double time, int site) {
println("st0 before= " + daStorageUsed[0]);
println("st1 before= " + daStorageUsed[1]);
int size = vUnreleased.size();
println("size=" + size + "; iMinClass=" + iMinClass);
ReleaseStorage rs1 = null, rs2 = null;
Vector<ReleaseStorage> vRemove = new Vector<ReleaseStorage>();
for (int i = 0; i < size; i++) {
rs1 = vUnreleased.elementAt(i);
if ((rs1.releaseTime <= time & rs1.site == site) | site == -1) {
// get the input storage;
daStorageUsed[rs1.site] -= daStorageInput[rs1.activityNo];
vRemove.add(rs1);
/* release space from the completed workflow */
if (rs1.lastActivity) {
// find the last one which have been compeleted
for (int k = 0; k < size; k++) {
rs2 = vUnreleased.elementAt(k);
// exchange the position
if (rs2.activityNo == rs1.activityNo & rs2.releaseTime > rs1.releaseTime) {
rs1.lastActivity = false;
rs2.lastActivity = true;
}
}
if (rs1.lastActivity || (rs2.lastActivity & rs2.releaseTime <= time))
for (int j = 0; j < iSite; j++) {
// get the output storage;
daStorageUsed[j] -= daStorageOutput[rs1.activityNo] * dmDist[rs1.activityNo][j];
}
}
}
}
println("st0 after= " + daStorageUsed[0]);
println("st1 after= " + daStorageUsed[1]);
println("===============================");
for (Iterator<ReleaseStorage> iter = vRemove.iterator(); iter.hasNext();) {
ReleaseStorage element = iter.next();
vUnreleased.remove(element);
}
} |
51379dae-fb21-4c02-a18e-fa7bb82d61bd | 6 | public void buildTipMap() {
tipMap.clear();
for (AIColony aic : getAIColonies()) {
for (TileImprovementPlan tip : aic.getTileImprovementPlans()) {
if (!validateTileImprovementPlan(tip)) {
aic.removeTileImprovementPlan(tip);
continue;
}
if (tip.getPioneer() != null) continue;
TileImprovementPlan other = tipMap.get(tip.getTarget());
if (other == null || other.getValue() < tip.getValue()) {
tipMap.put(tip.getTarget(), tip);
}
}
}
} |
fcc19986-c479-4457-98ef-e61fcc90d28c | 8 | @Override
public void cover(ImageBit[][] list) {
ImageBit ib = new ImageBit();
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
ib = list[i][j];
if (ib.isCovered()) {
continue;
}
LegoUtil.cover(ib, list, this.width, this.height,
BlockType.FourAndOne);
if (ib.isCovered()) {
System.out.println(ib.getX() + "," + ib.getY() + ","
+ ib.getRGB() + "," + ib.isCovered() + ","
+ ib.getBlockType());
fourAndOneList.add(ib);
draw(g, ib, this.width, this.height);
}
}
}
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
ib = list[i][j];
if (ib.isCovered()) {
continue;
}
LegoUtil.cover(ib, list, this.height, this.width, BlockType.OneAndFour);
if (ib.isCovered()) {
System.out.println(ib.getX() + "," + ib.getY() + "," + ib.getRGB() + ","
+ ib.isCovered() + "," + ib.getBlockType());
oneAndFourList.add(ib);
draw(g, ib, this.height, this.width);
}
}
}
} |
beff5f73-9605-468d-8213-cec1cff7afb3 | 6 | static GregorianCalendar datum (Component parent, String datumaanduiding){
try {
String[] datumSplit = datumaanduiding.split("-");
if (datumSplit.length != 3) {
JOptionPane.showMessageDialog(parent, "Ongeldige datum", "",
JOptionPane.ERROR_MESSAGE);
return null;
}
int dag = Integer.parseInt(datumSplit[0]);
if (dag <= 0 || dag > 31) {
JOptionPane.showMessageDialog(parent,
"Ongeldige dag", "",
JOptionPane.ERROR_MESSAGE);
return null;
}
int maand = Integer.parseInt(datumSplit[1]);
if (maand <= 0 || maand > 12) {
JOptionPane.showMessageDialog(parent,
"Ongeldige maand", "",
JOptionPane.ERROR_MESSAGE);
return null;
}
int jaar = Integer.parseInt(datumSplit[2]);
// maanden zijn binnen GregorianCalendar van 0 t/m 11 gecodeerd:
return new GregorianCalendar(jaar, maand - 1, dag);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(parent, "Ongeldige datum", "",
JOptionPane.ERROR_MESSAGE);
return null;
}
} |
cb22ba3a-b4a2-4d02-b8a3-32a20faf83db | 0 | public int getBalance() {
return this.balance;
} |
3884cd55-e40e-4d7b-9e03-bb2798d4b087 | 7 | public void removeOnetimeLocals() {
StructuredBlock secondBlock = subBlocks[1];
if (secondBlock instanceof SequentialBlock)
secondBlock = ((SequentialBlock) secondBlock).subBlocks[0];
if (subBlocks[0] instanceof InstructionBlock
&& secondBlock instanceof InstructionContainer) {
InstructionBlock first = (InstructionBlock) subBlocks[0];
InstructionContainer second = (InstructionContainer) secondBlock;
/*
* check if subBlocks[0] writes to a local, second reads that local,
* the local is only used by this two blocks, and there are no side
* effects. In that case replace the LoadLocal with the
* righthandside of subBlocks[0] and replace subBlocks[1] with this
* block. Call removeOnetimelLocals on subBlocks[1] afterwards and
* return.
*/
if (first.getInstruction() instanceof StoreInstruction) {
StoreInstruction store = (StoreInstruction) first
.getInstruction();
if (store.getLValue() instanceof LocalStoreOperator
&& (((LocalStoreOperator) store.getLValue())
.getLocalInfo().getUseCount() == 2)
&& (second.getInstruction().canCombine(store) > 0)) {
System.err.println("before: " + first + second);
second.setInstruction(second.getInstruction()
.combine(store));
System.err.println("after: " + second);
StructuredBlock sb = subBlocks[1];
sb.moveDefinitions(this, sb);
sb.replace(this);
sb.removeOnetimeLocals();
return;
}
}
}
super.removeOnetimeLocals();
} |
a1cf744c-6b26-4459-904e-fa1639e49410 | 1 | @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return connection.isWrapperFor(iface);
} |
1bf40232-1915-4958-b1ee-63a04e03b3a3 | 8 | public void doRun(int run) throws Exception {
if (getRawOutput()) {
if (m_ZipDest == null) {
m_ZipDest = new OutputZipper(m_OutputFile);
}
}
if (m_Instances == null) {
throw new Exception("No Instances set");
}
// Randomize on a copy of the original dataset
Instances runInstances = new Instances(m_Instances);
Random random = new Random(run);
runInstances.randomize(random);
if (runInstances.classAttribute().isNominal()) {
runInstances.stratify(m_NumFolds);
}
for (int fold = 0; fold < m_NumFolds; fold++) {
// Add in some fields to the key like run and fold number, dataset name
Object [] seKey = m_SplitEvaluator.getKey();
Object [] key = new Object [seKey.length + 3];
key[0] = Utils.backQuoteChars(m_Instances.relationName());
key[1] = "" + run;
key[2] = "" + (fold + 1);
System.arraycopy(seKey, 0, key, 3, seKey.length);
if (m_ResultListener.isResultRequired(this, key)) {
Instances train = runInstances.trainCV(m_NumFolds, fold, random);
Instances test = runInstances.testCV(m_NumFolds, fold);
try {
Object [] seResults = m_SplitEvaluator.getResult(train, test);
Object [] results = new Object [seResults.length + 1];
results[0] = getTimestamp();
System.arraycopy(seResults, 0, results, 1,
seResults.length);
if (m_debugOutput) {
String resultName = (""+run+"."+(fold+1)+"."
+ Utils.backQuoteChars(runInstances.relationName())
+"."
+m_SplitEvaluator.toString()).replace(' ','_');
resultName = Utils.removeSubstring(resultName,
"weka.classifiers.");
resultName = Utils.removeSubstring(resultName,
"weka.filters.");
resultName = Utils.removeSubstring(resultName,
"weka.attributeSelection.");
m_ZipDest.zipit(m_SplitEvaluator.getRawResultOutput(), resultName);
}
m_ResultListener.acceptResult(this, key, results);
} catch (Exception ex) {
// Save the train and test datasets for debugging purposes?
throw ex;
}
}
}
} |
ace6a289-bd16-4e2a-82d5-14f255be9a98 | 8 | private void setupNeighbours() {
int edgeCount = 0;
for(int i = 0; i < this.gridCellContents.size(); i ++)
{
//if reached end of row start again
if(edgeCount == xSize){
edgeCount = 0;
}
//adds below neighbour
if(i+xSize < this.gridCellContents.size())
{
this.gridCellContents.get(i).addNeighbour(this.gridCellContents.get(i+xSize));
}
//add right neighbours
if(edgeCount != xSize-1)
{
this.gridCellContents.get(i).addNeighbour(this.gridCellContents.get(i+1));
}
//adds bottom left
if(i + xSize < this.gridCellContents.size() && edgeCount != 0)
{
this.gridCellContents.get(i).addNeighbour(this.gridCellContents.get(i+xSize-1));
}
//adds bottom right neighbours
if(i + xSize < this.gridCellContents.size() && edgeCount != xSize-1)
{
this.gridCellContents.get(i).addNeighbour(this.gridCellContents.get(i+xSize+1));
}
edgeCount++;
}
} |
76c5b499-003d-444c-8038-3c2a55da099c | 5 | public static void resetBall(boolean global)
{
if (!global)
{
Game.countdown.setVisible(true);
for (int i = 3; i != 0; i--)
{ // Counts down from 3
Game.countdown.setText("" + i);
Game.countdown.setFont(Game.countdownFont1); // Big font
UPF.pause(750);
Game.countdown.setFont(Game.countdownFont2); // Small font
UPF.pause(250);
}
Game.countdown.setVisible(false);
Game.toMenu.setEnabled(true);
Game.ball.setVisible(true);
}
xV = 0; // Resets velocity so that the ball can randomly be given a new
// velocity
yV = 0;
while (xV == 0 || yV == 0) // So that x or y will never be 0
{
xV = (int) (Math.random() * 13 - 6); // Assigns x a random number from -6 to 6
if (Math.random() < 0.5)
// negative
yV = 8 - Math.abs(xV);
else
yV = -(8 - Math.abs(xV));
}
xC = 140; // Resets initial x and y coordinates
yC = 266;
} |
5abd84a1-8c71-4498-8aa3-b15f3cbb7685 | 6 | public static void boot() {
try {
// 1. Step: Init the application configuration.
ApplicationConfigurationManager.setup();
ApplicationConfiguration appConfig = ApplicationConfigurationManager.get();
int serverPort = Integer.parseInt(appConfig.getServerPort());
// 2. Init the server.
new MinervaServerEngine(appConfig.getServerName(), serverPort);
// 3. Show the server welcome message.
Bootstrapper.showWelcomeMessage();
} catch (AppConfigurationNotFoundException e) {
Bootstrapper.error(e.getMessage());
} catch (AppConfigurationNotReadableException e) {
Bootstrapper.error(e.getMessage());
} catch (UnknownHostException e) {
Bootstrapper.error(e.getMessage());
} catch (IOException e) {
Bootstrapper.error(e.getMessage());
} catch (NameBindingException e) {
Bootstrapper.error(e.getMessage());
} catch (DataAccessException e) {
Bootstrapper.error(e.getMessage());
}
} |
7a6496f8-eae1-44cf-9445-ce30e9bf8879 | 0 | protected String addIGameFeatures()
{
myIDisplay = new JTextArea(1, 5);
myIDisplay.setEditable(false);
return new String(DESCRIBE_I);
} |
0e204b47-7d3f-4baa-9656-e446546d84d5 | 5 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + port;
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
result = prime * result + ((ssid == null) ? 0 : ssid.hashCode());
result = prime * result + ((uid == null) ? 0 : uid.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
result = prime * result + ((debug == null) ? 0 : debug.hashCode());
return result;
} |
81c1dffd-1df2-46ea-aa45-894a90349c55 | 9 | public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random randomizer = new Random();
int actual = randomizer.nextInt(10) + 1;
int guess = 0;
boolean answer = false;
int current_play = 1;
int attempts = 1;
int gameplays = 0;
System.out.println("Welcome to the Guess A Number Game!");
System.out.print("How many games do you want to play? ");
gameplays = input.nextInt();
int[] cpu_input = new int[gameplays];
int[] tries = new int[gameplays];
System.out.println("Let the games begin." + "\n");
for (int i = 0; i < gameplays; i++)
{
System.out.println("Game " + current_play);
System.out.print("I am thinking of a number between 1 and 10. Can you guess what it is? ");
cpu_input[i] = actual;
attempts = 1;
answer = false;
do
{
guess = input.nextInt();
if (guess == actual)
{
System.out.println("You guessed my number. Great Job!");
current_play++;
tries[i] = attempts;
answer = true;
}
else if (guess > actual)
{
System.out.println("Sorry! The number you entered is too big.");
if (guess > 10)
{
System.out.println(guess + " is a number outside the range." );
attempts++;
}
else
{
attempts++;
}
}
else if (guess < actual)
{
System.out.println("Sorry! The number you entered is too small.");
attempts++;
}
if (answer == false)
{
System.out.print("Please try again. Enter a number between 1 and 10. ");
}
else
{
if (i == gameplays - 1)
{
System.out.println("That is all the games. Computing your Game History..." + "\n");
}
else
{
System.out.println("Get ready for the next game." + "\n");
actual = randomizer.nextInt(10) + 1;
}
}
}
while(answer == false);
}
System.out.println("Game History");
System.out.println("------------");
for (int j = 1; j <= gameplays; j++)
{
System.out.println("Game " + j);
System.out.println("CPU number for this game: " + cpu_input[j - 1]);
System.out.println("Number of attempts for this game: " + tries[j - 1] + "\n");
}
input.close();
} |
70e3387c-fabd-487f-93fa-0a4cbb1c9392 | 4 | public void update() {
if (fired) {
v = c;
u = u + d;
fired = false;
} else {
//Simulate 1 ms frame step (can be repeated for larger frame step size)
v += 0.5f*((0.04f * v + 5.0f) * v + 140.0f - u + getI());
u += 0.5f*a * (b * v - u);
v += 0.5f*((0.04f * v + 5.0f) * v + 140.0f - u + getI());
u += 0.5f*a * (b * v - u);
if(v >= fThresh){
v = fThresh;
fired = true;
}
}
if (Float.isNaN(v) || Float.isNaN(u)) {
v = c;
u = b * v;
fired = false;
}
updateHistory(getFired(), selfHistory);
updateInputHistory();
updateSTDP();
} |
38a9e8f3-f6b9-414b-8920-71b370391619 | 8 | public boolean recurSearch(int[] A, int target, int start, int end){
if(start > end) return false;
int center = (start + end)/2;
if(A[center] == target) return true;
if(A[center] > A[start] ){
if(A[start] <= target && target <= A[center])
return recurSearch(A, target, start, center-1);
else return recurSearch(A, target, center+1, end);
}else if(A[center] < A[start]){
if(A[center] <= target && target <= A[end])
return recurSearch(A, target, center+1, end);
else return recurSearch(A, target, start, center-1);
}else return recurSearch(A, target, start+1, end);
} |
3abba285-476d-4e37-83cd-148ab64d73a0 | 2 | @Override
public void propertyChange(PropertyChangeEvent evt) {
propertyName = evt.getPropertyName();
oldValue = evt.getOldValue() instanceof String ? (String) evt.getOldValue() : "";
newValue = evt.getNewValue() instanceof String ? (String) evt.getNewValue() : "";
} |
d11e0d6b-f9ef-4c71-9d56-484c95c9f08a | 1 | public static void listEmployeesProjectsPhoneNumbers(EntityManager entityManager) {
TypedQuery<Employee> query = entityManager.createQuery(
"select e from Employee e left join fetch e.projects p left join fetch e.phoneNumbers",
Employee.class);
List<Employee> resultList = query.getResultList();
entityManager.close();
for (Employee employee : resultList) {
System.out.println(employee + " - " + employee.getProjects() + " - " + employee.getPhoneNumbers());
}
} |
d6999f95-527c-41d8-8a70-e8a3203d28ea | 6 | public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} |
dd274d25-93ed-411a-a2c3-72c0c0b1df3f | 9 | @Override
public void deposito(BigDecimal valor) {
switch(status) {
case Silver:
saldo = saldo.add(valor);
if(saldo.compareTo(new BigDecimal("200000.0")) == 0 || saldo.compareTo(new BigDecimal("200000.0")) == 1) {
status = Categorias.Platinum;
}
else if(saldo.compareTo(new BigDecimal("50000.0")) == 0 || saldo.compareTo(new BigDecimal("50000.0")) == 1) {
status = Categorias.Gold;
}
break;
case Gold:
saldo = saldo.add(valor.multiply(new BigDecimal("0.01")));
if(saldo.compareTo(new BigDecimal("200000.0")) == 0 || saldo.compareTo(new BigDecimal("200000.0")) == 1) {
status = Categorias.Platinum;
}
break;
case Platinum:
saldo = saldo.add(valor.multiply(new BigDecimal("0.025")));
}
} |
32e8ab78-724a-404c-86ab-fce1f31e39d1 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(mob.location().getArea().properSize()<2)
{
mob.tell(L("This area is too small to cast this spell."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final Physical target = mob.location();
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg = CMClass.getMsg(mob, target, this, somanticCastCode(mob,target,auto), auto?"":L("^S<S-NAME> speak(s) and gesture(s) dramatically!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("The appearance of this place changes..."));
if(CMLib.law().doesOwnThisLand(mob,mob.location()))
{
final Ability A=(Ability)copyOf();
A.setInvoker(mob);
newRoom=mob.location().getArea().getRandomProperRoom();
if((newRoom!=null)&&(newRoom.roomID().length()>0)&&(!(newRoom instanceof GridLocale)))
{
A.setMiscText(CMLib.map().getExtendedRoomID(newRoom));
mob.location().addNonUninvokableEffect(A);
CMLib.database().DBUpdateRoom(mob.location());
}
}
else
beneficialAffect(mob,mob.location(),asLevel,0);
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> speak(s) and gesture(s) dramatically, but the spell fizzles."));
// return whether it worked
return success;
} |
c8d69b6d-c2dc-4934-bb4c-0109f900a4e9 | 4 | public void update() {
centerX += speedX;
speedX = bg.getSpeedX()*5;
getHeliBoy1().setBounds(centerX - 25, centerY - 25,50,60);
getHeliBoy2().setBounds(centerX - 25, centerY - 25,50,60);
if (getHeliBoy1().intersects(Robot.yellowRed) || getHeliBoy2().intersects(Robot.yellowRed)){
checkCollision();
}
centerY += speedUpdown;
maxRange += 1;
if (maxRange >= 20) {
maxRange = 0;
if (speedUpdown == -1) {
speedUpdown = 1;
} else {
speedUpdown = -1;
}
}
} |
7f056b5f-ccf7-4936-aa8e-7bcb991c9709 | 3 | @Override
public boolean removeAll(Collection<?> arg0) {
boolean result = list.removeAll(arg0);
if (result)
try {
save();
} catch (IOException ex) {
System.err.println("Autosave failed - " + ex.getMessage());
ex.printStackTrace();
return false;
}
return result;
} |
07919dd5-f50b-416b-87b0-91bc950c5269 | 8 | private static void callOrderBook(){
try {
Vector<Vector<Double>> array = OrderBookAPI.HttpGetOrderBook();
int n = array.get(0).size();
DefaultTableXYDataset dataset = new DefaultTableXYDataset();
XYSeries data = new XYSeries("Bids", true, false);
for(int i=0; i<n; i++){
if(array.get(0).get(i)<1000 && array.get(1).get(i)<10000)
data.add(array.get(0).get(i),array.get(1).get(i));
}
//
int n1 = array.get(2).size();
XYSeries data1 = new XYSeries("Asks", true, false);
for(int i=0; i<n1; i++){
if(array.get(2).get(i)<1000 && array.get(3).get(i)<10000)
data1.add(array.get(2).get(i),array.get(3).get(i));
}
//
dataset.addSeries(data);
dataset.addSeries(data1);
/*JFreeChart chart = ChartFactory.createScatterPlot(
"Order Book", // chart title
"Price/USD", // x axis label
"Value", // y axis label
dataset, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
renderer.setSeriesLinesVisible(0, true);
plot.setRenderer(renderer);
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
*/
JFreeChart chart = ChartFactory.createStackedXYAreaChart(
"Order Book", "Price/USD", "Value", dataset, PlotOrientation.VERTICAL, true, true, false);
StackedXYAreaRenderer render = new StackedXYAreaRenderer();
render.setSeriesPaint(0, Color.YELLOW);
render.setSeriesPaint(1, Color.BLUE);
XYPlot plot = (XYPlot) chart.getPlot();
plot.setRenderer(render);
plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
/*plot.setForegroundAlpha(0.5f);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setNumberFormatOverride(new DecimalFormat("#,###.#"));
rangeAxis.setAutoRange(true);*/
ChartPanel chartPanel = new ChartPanel(chart);
// clear previews display, update with new display
int componentCount = contentPane.getComponentCount();
if(componentCount > 1){
contentPane.remove(1);
}
contentPane.add(chartPanel, BorderLayout.CENTER);
contentPane.revalidate();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} |
6fae4879-0490-43c8-ab44-f98470d6eca7 | 2 | public boolean GiveMoney(String player, int money) {
if (VaultEnabled) {
EconomyResponse resp = econ.depositPlayer(player, money);
if (resp.type == ResponseType.SUCCESS) {
Log(player + " has been given $" + resp.amount + " (new balance $" + resp.balance + ")");
return true;
} else {
Warn("Vault payment failed! Error: " + resp.errorMessage);
}
}
return false;
} |
3b282908-d762-46c9-830f-2c1703c60eec | 6 | public static HashMap<String, Integer> rareWordMarker(String countFile,
String dataFile) throws IOException {
HashMap<String, Integer> wordToCount = new HashMap<String, Integer>();
FileReader in = new FileReader(countFile);
BufferedReader br = new BufferedReader(in);
StringTokenizer stk;
String input;
String wordTag;
String currentWord;
/*
* Compute the word counts for each word
*/
while ((input = br.readLine()) != null) {
stk = new StringTokenizer(input);
int currentWordCount = Integer.parseInt(stk.nextToken());
wordTag = stk.nextToken();
if (wordTag.equals("WORDTAG")) {
// System.out.println(input);
stk.nextToken();
currentWord = stk.nextToken();
if (wordToCount.containsKey(currentWord)) {
currentWordCount += wordToCount.get(currentWord).intValue();
}
wordToCount.put(currentWord, currentWordCount);
}
}
in = new FileReader(dataFile);
br = new BufferedReader(in);
String tag;
String write;
File rareCounts = new File("ner_train_rare.dat");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(
rareCounts));
while ((input = br.readLine()) != null) {
stk = new StringTokenizer(input);
if (input.length() > 1) {
currentWord = stk.nextToken();
tag = stk.nextToken();
if (wordToCount.get(currentWord).intValue() < 5) {
currentWord = "_RARE_";
}
write = currentWord + " " + tag;
// System.out.println(write);
bufferedWriter.write(write);
bufferedWriter.write("\n");
} else {
bufferedWriter.write("\n");
}
}
bufferedWriter.close();
return wordToCount;
} |
f78f373a-4f08-4659-9557-db0164272872 | 4 | public synchronized void release(Object user, MemoryManageable mm) {
if (user == null || mm == null)
return;
//System.out.println("+-+ MM.release() user: " + user + ", mm: " + mm);
HashSet inUse = locked.get(user);
if (inUse != null) {
boolean removed = inUse.remove(mm);
// remove locked reference if it no longer holds any mm objects.
if (inUse.size() == 0) {
locked.remove(user);
}
//if( removed ) System.out.println("+-+ MM.release() mm was removed");
}
} |
36a62ef1-088c-4494-a597-3cea60302752 | 9 | @Override
public void handlePinEvent(PinEvent event) {
// only process listeners and triggers if the received interrupt event
// matches the pin number being tracked my this class instance
if (this.pin.getPin().equals(event.getPin())) {
if (event.getEventType() == PinEventType.DIGITAL_STATE_CHANGE) {
PinState state = ((PinDigitalStateChangeEvent)event).getState();
// process event callbacks for digital listeners
for (GpioPinListener listener : pin.getListeners()) {
if (listener instanceof GpioPinListenerDigital) {
((GpioPinListenerDigital)listener).handleGpioPinDigitalStateChangeEvent(new GpioPinDigitalStateChangeEvent(event.getSource(), pin, state));
}
}
// process triggers
for (GpioTrigger trigger : pin.getTriggers()) {
if (trigger.hasPinState(state)) {
trigger.invoke(pin, state);
}
}
} else if(event.getEventType() == PinEventType.ANALOG_VALUE_CHANGE) {
double value = ((PinAnalogValueChangeEvent)event).getValue();
// process event callbacks for analog listeners
for (GpioPinListener listener : pin.getListeners()) {
if (listener instanceof GpioPinListenerAnalog) {
((GpioPinListenerAnalog)listener).handleGpioPinAnalogValueChangeEvent(new GpioPinAnalogValueChangeEvent(event.getSource(), pin, value));
}
}
}
}
} |
aea0e3e5-ef65-471f-9ab1-8a6dcfb91904 | 5 | @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 Policestation)) {
return false;
}
Policestation other = (Policestation) object;
if ((this.policeStationID == null && other.policeStationID != null) || (this.policeStationID != null && !this.policeStationID.equals(other.policeStationID))) {
return false;
}
return true;
} |
1b458cfd-9def-4527-909d-327a936b6a7e | 9 | public String toString(){
String str ="distSegment: "+distSegments.size()+"\n";
str+="Active State ("+pActiveState+", "+tActiveState+")\n";
str+="Predictive State ("+pPredictiveState+", "+tPredictiveState+")\n";
str+="Learn State ("+pLearnState+", "+tLearnState+")\n";
if(this.distSegments.size()>0){
int row = this.parent.parentRegion.row;
int column = this.parent.parentRegion.column;
int layer = this.parent.cells.length;
double[][][] outputMatrix=new double[row][column][layer];
for(Synapse s : this.distSegments.get(0).synapses){
if(outputMatrix[s.destCoor[0]][s.destCoor[1]][s.destCoor[2]]>0) str+="Duplicate Synapse!";
else if(s.isConnected()) outputMatrix[s.destCoor[0]][s.destCoor[1]][s.destCoor[2]]=s.permanence;
else outputMatrix[s.destCoor[0]][s.destCoor[1]][s.destCoor[2]]=-1;
}
for(int i=0; i< row;i++){
for(int j=0; j< column; j++){
str+="(";
for(int k=0; k<layer; k++){
if(outputMatrix[i][j][k]>0)str+=String.format("%.1f", outputMatrix[i][j][k]);
else if(outputMatrix[i][j][k]==-1) str+="-";
else str+=" ";
}
str+=")";
}
str+="\n";
}
}
return str;
} |
f522d6b3-68c0-403a-9bcd-937c16aa7ae8 | 6 | private boolean wincheck3() {
for (int column = 0; column < (gv.getColSize()-THREE); column++) {
for (int row = 0; row < (gv.getRowSize()-THREE); row++) {
if (cells[row][column].getValue() != 0
&& cells[row][column].getValue() == cells[row + 1][column + 1]
.getValue()
&& cells[row][column].getValue() == cells[row + 2][column + 2]
.getValue()
&& cells[row][column].getValue() == cells[row + THREE][column
+ THREE].getValue()) {
return true;
}
}
}
return false;
} |
36bd8c59-453e-4831-a341-b93a25c1396e | 7 | public Component getComponents() {
if(!sort) {
setPositions();
return Header;
}
else if(HashTable == null) {
return null;
}
boolean HeaderSet = false;
for(int i = 0; i < 28; i++) {
if(HashTable[i] != null && !HeaderSet) {
Header = HashTable[i];
HeaderSet = true;
}
int j = linkNext(i);
if(j > 0) {
i = j - 1;
}
else if(j == -2) {
break;
}
}
setPositions();
return Header;
} |
b56bfc61-7179-4a0d-ad0f-a6d09466ad27 | 7 | private static void quicksortusingmedianpivot(int l, int k) {
// TODO Auto-generated method stub
if(l==k){
return;
}
if (k>l){
int i=l+1; // startelement
int j=l+1; //
int temp;
int arrayr[] = new int[3];
arrayr[0] = array[l];
arrayr[1] = array[k];
arrayr[2] = array[(l+k)/2];
Arrays.sort(arrayr);
int pivot = 0;
if(arrayr[1] == array[l]){
pivot = array[l];
}
if(arrayr[1] == array[k]){
temp = array[k];
array[k] = array[l];
array[l]=temp;
pivot = array[l];
}
if(arrayr[1] == array[(l+k)/2]){
temp = array[(l+k)/2];
array[(l+k)/2] = array[l];
array[l]=temp;
pivot = array[l];
}
for(j=l+1;j<k+1;j++){
int vella = array[j];
counter++;
if(array[j]<pivot){
temp = array[i];
array[i] = array[j];
array[j]=temp;
i++;
}
}
i--;
temp = array[i];
array[i] = array[l];
array[l] = temp;
quicksortusingmedianpivot(l,i-1);
quicksortusingmedianpivot(i+1,k);
return;
}else{
return;
}
} |
7d2525ea-83cc-434b-9fed-33e266651b4a | 3 | public void test_06_fisher_vs_chi2() {
int n11 = 25, n12 = 5;
int n21 = 15, n22 = 15;
int k = n11;
int D = n11 + n12;
int N = n11 + n12 + n21 + n22;
int n = n11 + n21;
// Chi square approximation (without Yates correction)
double pChi = FisherExactTest.get().chiSquareApproximation(k, N, D, n);
if (verbose) System.out.println("Chi^2 p-value: " + pChi);
Assert.assertEquals(pChi, 0.00617, 0.00001);
// Fisher exact test
double pFish = FisherExactTest.get().fisherExactTestUp(k, N, D, n);
if (verbose) System.out.println("Fisher p-value: " + pFish);
Assert.assertEquals(pFish, 0.006349, 0.000001);
double ratio = pFish / pChi;
if (verbose) System.out.println("Ratio: " + ratio);
} |
00492ae6-8e39-46fc-8705-31c648ae1e2e | 4 | public Component draw() throws ParseException {
final JFrame item = new JFrame();
item.setAlwaysOnTop(true);
item.setSize(new Dimension(300, 250));
item.setResizable(false);
item.setTitle("Order conformation");
JPanel popUp = new JPanel();
popUp.setLayout(new GridBagLayout());
popUp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
popUp.setSize(300, 250);
GridBagConstraints c = new GridBagConstraints();
final Fields moneyBack = new Fields();
moneyBack.setEditable(false);
JLabel sumWindow = new JLabel("The cost of your order is: "
+ String.format(Locale.ENGLISH, "%.2f", totalSum));
final Fields payMoney = new Fields();
item.add(popUp);
payMoney.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent arg0) {
data();
}
public void insertUpdate(DocumentEvent arg0) {
data();
}
public void removeUpdate(DocumentEvent arg0) {
data();
}
private void data() {
try {
if (!payMoney.getText().isEmpty()) {
double changeBack = Double.parseDouble(payMoney
.getText()) - totalSum;
changeBack = Math.round(changeBack * 100.0) / 100.0;
moneyBack.setText(String.format(Locale.ENGLISH, "%.2f",
changeBack));
}
} catch (NumberFormatException e) {
}
}
});
sumWindow.setSize(300, 75);
c.gridx = 0;
c.gridy = 0;
popUp.add(sumWindow, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
popUp.add(payMoney, c);
c.gridx = 0;
c.gridy = 2;
JLabel dp = new JLabel("Payment amount");
popUp.add(dp, c);
c.gridx = 1;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
popUp.add(moneyBack, c);
c.gridx = 0;
c.gridy = 3;
JButton confirm = new JButton("Confirm buy");
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
if (Double.parseDouble(moneyBack.getText()) >= 0.0) {
log.info("Purchase completed");
// save order to history tab
AcceptedOrder ao = new AcceptedOrder();
ao.setId(new Long(1));
ao.setDate(new Date());
ao.setTotal(new Float(totalSum));
model.getCurrentHistoryTableModel().addItem(ao);
// actually finish sale process
pTab.endSale();
model.getCurrentPurchaseTableModel().clear();
item.dispose();
}
} catch (NumberFormatException e) {
}
}
});
popUp.add(confirm, c);
c.gridx = 1;
c.gridy = 3;
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
item.dispose();
log.info("Payment canceled");
pTab.continueSale();
}
});
popUp.add(cancel, c);
item.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
item.dispose();
log.info("Payment canceled");
pTab.continueSale();
}
});
return item;
} |
e13aa0bd-78ad-44ed-acb6-069868e5d6d6 | 1 | public double getSuojakilvenHalkaisija(){
if (suojakilpi){
return getMahdSuojakilvenHalkaisija();
} else {
return vartalo.getHalkaisija();
}
} |
708b7bc4-8c86-4930-a818-24d77e90a88c | 3 | @Override
protected void paintComponent(Graphics g) {
// use all pictures from the array
g.drawImage(backgroundImages[currentBackground % backgroundImages.length], 0, 0, null);
g.setColor(Color.GREEN);
g.drawString(String.format("Score: %d\t Level: %d \tLives: %d", score, level, health), 10 , 600);
g.setColor(Color.BLUE);
g.drawImage(ship, xShip, yShip, ship.getWidth() / 3, ship.getHeight() / 3, null);
for (Bullet b : bullets) {
g.drawImage(b.sprite, b.pointX, b.pointY, b.width, b.height, null);
}
for (EnemyBullet eb : enemyBullets) {
g.drawImage(eb.sprite, eb.pointX, eb.pointY, eb.sprite.getWidth(), eb.sprite.getHeight(), null);
}
for (Enemy e : enemies) {
g.drawImage(e.sprite, e.locX, e.locY, e.sprite.getWidth(), e.sprite.getHeight(), null);
}
} |
69c89a83-0d00-4a95-8b25-9c3a8450344b | 5 | public BigDecimal kurtosis_as_BigDecimal() {
boolean hold = Stat.nFactorOptionS;
if (nFactorReset) {
if (nFactorOptionI) {
Stat.nFactorOptionS = true;
} else {
Stat.nFactorOptionS = false;
}
}
BigDecimal kurtosis = BigDecimal.ZERO;
switch (type) {
case 1:
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
kurtosis = Stat.kurtosis(bd);
bd = null;
break;
case 14:
throw new IllegalArgumentException("Complex kurtosis is not supported");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
Stat.nFactorOptionS = hold;
return kurtosis;
} |
c3711228-c525-4248-8338-5c983745c480 | 2 | public void performInterferenceTestBeforeRemove() {
if(!Configuration.interferenceIsAdditive) {
return;
}
if(newAdded) {
testForInterference();
newAdded = false;
}
} |
391ad269-5d78-4146-bbc6-cd6e092e6c0c | 3 | public void updateNums()
{
for(int i = 0; i < fleet.size(); i++)
{
Ship ship = fleet.get(i);
for(int x = ship.x; x < ship.x+ship.xSize; x++)
for(int y = ship.y; y < ship.y+ship.ySize; y++)
sea[x][y] = SHIP;
}
} |
0c684b63-c0b3-40ba-9096-c9eaea632d92 | 6 | public void adjustChildren() {
//Will crash if it exceeds around 2k objects for some reason and doesn't have size limit
if(noChildren() && props.size() + rects.size() > size && container.getWidth() > 80) {
propChildren = new PropQuad[4];
addChildren(0);
} else if(!noChildren() && props.size() + rects.size() <= size && parent != null) {
propChildren = null;
PropQuad.totalChildren -= 4;
}
} |
1ea2a4e4-760b-4153-b9c2-407f65edcffa | 2 | private static boolean isNameUnique(String name, ArrayList list) {
for (int i = 0, limit = list.size(); i < limit; i++) {
if (name.equals(list.get(i).toString())) {
return false;
}
}
return true;
} |
97ee8b88-324e-49c2-98d8-e695b301ef80 | 5 | private Node addToTree(Node root, int v) {
if (root == null) {
return new Node(v);
}
Node curr = root;
Node prev = null;
int left = -1;
while (curr != null) {
if (curr.v < v) {
prev = curr;
curr = curr.right;
left = 0;
} else if (curr.v == v) {
return root;
} else {
prev = curr;
curr = curr.left;
left = 1;
}
}
if (left == 1) {
prev.left = new Node(v);
} else {
prev.right = new Node(v);
}
return root;
} |
7c95ade7-d19e-40aa-b3d4-4ae7c8c702ef | 3 | public static void saveGif(BufferedImage[] images, String fname) {
new File("output images/").mkdir();
try {
new File("output images").mkdir();
ImageOutputStream output = new FileImageOutputStream(new File("output images/" + fname));
GifSequenceWriter writer = new GifSequenceWriter(output, images[0].getType(), 100, true);
for (BufferedImage bi : images) {
writer.writeToSequence(bi);
}
writer.close();
output.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Perlin2d.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Perlin2d.class.getName()).log(Level.SEVERE, null, ex);
}
} |
d5f4eff6-9b9f-4b02-9025-86a7c0d9bbf6 | 8 | private String funcionarioCargo() {
String cargo = null;
int opcao = 0;
boolean confirma = false;
boolean valido = false;
String resposta;
in = new Scanner(System.in);
while (!confirma) { // enquanto o usuario nao confirmar
valido = false;
System.out.println("Selecione cargo do funcionario:");
while (!valido) { // enquanto o Cargo nao for valido
System.out.println("1-Caixa");
System.out.println("2-Estoquista");
System.out.println("3-Gerente");
System.out.println("4-Vendedor");
opcao = in.nextInt();
switch (opcao) {
case 1:
cargo = "Caixa";
valido = true;
break;
case 2:
cargo = "Estoquista";
valido = true;
break;
case 3:
cargo = "Gerente";
valido = true;
break;
case 4:
cargo = "Vendedor";
valido = true;
break;
default:
System.out
.println("Comando invalido.\nPor favor responda \"1\", \"2\", \"3\" ou \"4\".\n\n");
valido = false;
break;
}
}
System.out.println("Cargo = " + cargo + "\nTem certeza? (s/n)");
resposta = in.next();
if (resposta.equals("s") || resposta.equals("S")) {
confirma = true;
return cargo;
} else {
confirma = false;
}
}
in.close();
return cargo;
} |
eb02b875-15ec-451f-9a46-16603911c134 | 6 | 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(EkranZaPracenjeRaspolozivostiSobaAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSobaAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSobaAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EkranZaPracenjeRaspolozivostiSobaAdmin.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 EkranZaPracenjeRaspolozivostiSobaAdmin().setVisible(true);
}
});
} |
d7a0e282-a07c-4cd8-9f1a-0f11d190049d | 0 | public Ex1() {
System.out.println("Inside Mustang()");
name = "Ford";
year = "1976";
color= "Black";
} |
7c74be18-f7b2-4260-a640-d1a3656a0649 | 8 | public void update() {
String latestTweet = getLatestTweetFrom(twitterQuery);
if (latestTweet == null) {
return;
}
clearBoard();
String [] lines = splitToLines(latestTweet, CHARACTERS_IN_LINE - colorCodes.length());
int noOfLines = lines.length;
if (noOfLines > 0) {
int signIndex = 0;
int numberOfSigns = (int) Math.ceil((double)noOfLines / LINES_IN_A_SIGN);
Location signLoc = block.getLocation();
Block blockBelow;
if (isOppositeConfiguration == false) {
blockBelow = block.getWorld().getBlockAt(signLoc.subtract(0, 1, 0));
} else {
blockBelow = block;
}
while ((blockBelow.getType() == Material.AIR || blockBelow.getType() == Material.WALL_SIGN) && signIndex < numberOfSigns) {
if (blockBelow.getType() != Material.WALL_SIGN) {
blockBelow.setType(Material.WALL_SIGN);
}
blockBelow.setData(block.getData());
Sign nextSign = (Sign) blockBelow.getState();
int startLine = signIndex * LINES_IN_A_SIGN;
for (int j = 0; startLine + j < Math.min(lines.length, startLine + LINES_IN_A_SIGN); j++) {
nextSign.setLine(j, colorCodes + lines[startLine + j]);
}
nextSign.update();
signIndex++;
blockBelow = block.getWorld().getBlockAt(signLoc.subtract(0, 1, 0));
}
}
} |
08632e12-2ae8-4397-8dec-16452b93b0a8 | 3 | public void paint(Graphics arg0) {
Graphics2D g2d = (Graphics2D) arg0;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (show) {
g2d.setColor(Constants.BLACK_TRANS);
g2d.fill(Constants.CHATBOX_AREA);
g2d.setColor(Color.PINK);
g2d.setFont(Constants.PAINT_TITLE_FONT);
g2d.drawString("Tornado Item Magician", 170, 410);
g2d.drawString("Time running: "+ timer.toElapsedString(), 158, 425);
g2d.setColor(Color.PINK);
g2d.setFont(Constants.PAINT_TEXT_FONT);
g2d.drawString("Combined: " + Misc.perHourInfo(startTime, combined), 10, 482);
g2d.drawString("- Tornado", 435, 506);
g2d.setFont(new Font("Calibri", Font.PLAIN, 14));
int x = 8, y = 436;
for(int i = 0; i < PaintUtils.SKILL_NAMES.length -1; i++) {
if(sd.experience(i) > 0) {
PaintUtils.drawProgressBar(g2d, x, y, 487, 17, Color.BLACK, PaintUtils.getSkillColor(i), 150, PaintUtils.getPercentToNextLevel(i));
g2d.setColor(Color.WHITE);
g2d.drawString(PaintUtils.generateString(sd, i), x + 5, y + 13);
y += 18;
}
}
}
} |
6e14123d-b32d-4654-a9fb-2a2dc026113f | 8 | public static void main(String[] args) {
// Queue<TaskArg> taskQueue = new LinkedBlockingQueue<TaskArg>();
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
Insets noSpace = new Insets(0, 0, 0, 0);
Insets space = new Insets(5, 0, 0, 0);
JFrame f = new JFrame();
f.setSize(new Dimension(500, 300));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(new Point(100, 100));
Container c = f.getContentPane();
c.setLayout(new GridBagLayout());
GridBagConstraints gbco = new GridBagConstraints();
gbco.gridx = 0;
gbco.gridy = 0;
gbco.fill = GridBagConstraints.HORIZONTAL;
gbco.weightx = 1.0;
gbco.weighty = 0.0;
List<EditorSection> sections = XMLGUIBuilder.parseGUIXML("com/deepnighttwo/julia/argseditor/juliaset.xml");
final JuliaSetArgs bean = new JuliaSetArgs();
for (EditorSection section : sections) {
JPanel sectionPanel = new JPanel();
sectionPanel.setBorder(new TitledBorder(section.getSectionLabel()));
sectionPanel.setLayout(new GridBagLayout());
List<PropertyLine> props = section.getProps();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
for (PropertyLine prop : props) {
// prop.setBeanInst(bean);
prop.setArgs(bean);
Component label = prop.getLabel();
Component content = prop.getContent();
if (label == null && content != null) {
gbc.gridx = 0;
gbc.insets = noSpace;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.gridwidth = 2;
sectionPanel.add(content, gbc);
} else if (label != null && content == null) {
gbc.gridx = 0;
gbc.insets = noSpace;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.gridwidth = 2;
sectionPanel.add(label, gbc);
} else {
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.insets = space;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
sectionPanel.add(label, gbc);
gbc.gridx = 1;
gbc.insets = noSpace;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
sectionPanel.add(content, gbc);
}
gbc.gridy++;
}
c.add(sectionPanel, gbco);
gbco.gridy++;
}
f.setVisible(true);
} |
28f1cb61-a067-4f36-a9f2-c523839c17dc | 0 | public ZeroFilter(final ConnectionProcessor proc, final Properties config) {
super(proc, config);
} |
71bc0bd7-65ea-4757-b8eb-48170350c877 | 2 | public List<KeyRegistrationRecord> getPeers(String inBase64Key) {
long start = System.currentTimeMillis();
List<KeyRegistrationRecord> out;
int maxFriendsToReturn = 26;
try {
maxFriendsToReturn = Integer.parseInt(System.getProperty(EmbeddedServer.Setting.MAX_FRIENDS_RETURNED.getKey()));
} catch( Exception e ) {
e.printStackTrace();
}
if( mVPN_ids.size() == 0 ) {
// out = getNearestPeers(inBase64Key, maxFriendsToReturn, true);
out = getRandomPeers(inBase64Key, maxFriendsToReturn, (int)Math.round(1.5 * (double)maxFriendsToReturn), true);
} else {
out = getVPNList(inBase64Key);
}
logger.finer("getPeers() took: " + (System.currentTimeMillis()-start));
return out;
} |
cbb9c810-dd80-413c-aac7-011573922c03 | 2 | private void savePath(Vector<Integer> Row)
{
//Path-Objekt erstellen
Path P = new Path();
//Der Weg beginnt mit der aktuellen Position
P.addPoint(position);
for(int z=0; z<Row.size(); z++)
{
//Vector I enthaelt den Weg von 0 bis z
Vector<Integer> I = new Vector<Integer>();
for(int u=0; u<=z; u++)
{
int f = Row.elementAt(u);
I.add(f);
}
//Referenz auf ausgerechneten Wegpunkt
float[] point = null;
point = getPoint(I);
//Wegpunkt dem Path-Objekt hinzufuegen
float[] pf = new float[2];
pf[0] = point[0];
pf[1] = point[1];
P.addPoint(pf);
}
//Pfad zu Wegen hinzufuegen
Ways.add(P);
} |
13f45886-d52e-4cb4-b95e-a2c4cecbbd37 | 5 | private boolean jj_3R_47()
{
if (jj_scan_token(LEFTB)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(COMMA)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(RIGHTB)) return true;
return false;
} |
fcac7cda-0c1f-4fc0-b155-092ecb4cb534 | 6 | private void processEncodedTable(Decoder dec) throws ASN1DecoderFail {
/*
Table ::= SEQUENCE {
name TableName,
fields SEQUENCE OF FieldName,
fieldTypes SEQUENCE OF FieldType,
rows SEQUENCE OF SEQUENCE OF NULLOCTETSTRING
}
*/
dec=dec.getContent();
// Get all stuff
String tableName=dec.getFirstObject(true).getString();
String[] columnNames=dec.getFirstObject(true).getSequenceOf(Encoder.TAG_UTF8String);
// Skip names
dec.getFirstObject(true);
ArrayList<String[]> rows=new ArrayList<String[]>();
Decoder rowsDec=dec.getFirstObject(true);
rowsDec=rowsDec.getContent();
// Load all rows
while (rowsDec.contentLength()>0){
rows.add(rowsDec.getFirstObject(true).getSequenceOf(Encoder.TAG_UTF8String));
}
// Print Received table
if (LOG) {
System.out.println("Table Name: "+tableName);
System.out.println("Column Names: ");
// Print out all column names
for (int i=0;i<columnNames.length;i++){
System.out.println(" "+columnNames[i]);
}
System.out.println("Field Values: ");
for (int i=0;i<rows.size();i++){
for (int j=0;j<rows.get(i).length;j++){
System.out.print(" "+rows.get(i)[j]);
}
System.out.println();
}
}
// Now update database, this depends on what table we have
if (tableName.equals("peer")){
this.receivedPeerRows=rows;
} else {
this.receivedPeerAddressRows=rows;
}
} |
28e72642-8695-4984-b9d5-92c0651f06e1 | 9 | public static final FieldObjectInstantiator getResolver(final Class<?> field_origin, final Class<?> resolver_enclosing_class, final String resolver_function) throws NoSuchMethodException {
if (resolver_function == null) {
return getDefaultInstantiator(field_origin);
} else {
for (final Method method : ReflectionUtil.getVisibleMethods(resolver_enclosing_class, VisibilityConstraint.INHERITED_CLASS_VIEWPOINT, resolver_function, null, (Class<?>[]) null)) {
if (isFullArgumentsMethod(method)) {
if (method.getReturnType().equals(Class.class)) {
return new InstantiatorWithConcreteClassResolver_FullArguments(method);
} else {
return new WrappedInstantiator_FullArguments(method);
}
} else if (method.getParameterTypes().length == 0) {
if (method.getReturnType().equals(Class.class)) {
return new InstantiatorWithConcreteClassResolver(method);
} else {
return new WrappedInstanceResolver(method);
}
}
}
throw new NoSuchMethodException("No applicable method " + resolver_function + " is found");
}
} |
450b798e-bf12-4a7a-9dc7-eca784718caa | 2 | public void update() {
if(XboxController.controller != null)
XboxController.update();
if (gameStates[currentState] != null)
gameStates[currentState].update();
} |
24962675-4adf-45a2-915a-9786ca57ea30 | 4 | public boolean isLastState(State state) {
if (state == null) return false;
reSortSubProcesses();
SubProcess sp = state.getSubProcess();
if (sp == null || !this.subProcesses.contains(sp)) return false;
if (this.subProcesses.indexOf(sp) == this.subProcesses.size() - 1) return true;
return false;
} |
80ff2669-0c31-4452-9386-ffe7c10c0b1c | 4 | private void testParseText() {
String TEXT = "A beginning is the time for taking the most delicate care that the balances are \n" +
"correct";
StanfordParser sp = new StanfordParser("parser");
ArrayList<ArrayList<Tuple>> parsedText = sp.parseText(TEXT);
assert parsedText.size() == 0; // should correspond to only 1 sentence
ArrayList<Tuple> sentence = parsedText.get(0);
System.out.println(TEXT);
for (Tuple tup : sentence) {
System.out.println(tup.pos);
System.out.println(tup.cnt);
System.out.println(" ");
}
TEXT = "This every sister of the Bene Gesserit knows";
parsedText = sp.parseText(TEXT);
assert parsedText.size() == 0; // should correspond to only 1 sentence
sentence = parsedText.get(0);
System.out.println(TEXT);
for (Tuple tup : sentence) {
System.out.println(tup.pos);
System.out.println(tup.cnt);
System.out.println(" ");
}
TEXT = "to begin your study of the life of Muad'Dib, then, take care that you first place him in his time: born in the 57th year of the Padishah Emperor, Shaddam IV";
parsedText = sp.parseText(TEXT);
assert parsedText.size() == 0; // should correspond to only 1 sentence
sentence = parsedText.get(0);
System.out.println(TEXT);
for (Tuple tup : sentence) {
System.out.println(tup.pos);
System.out.println(tup.cnt);
System.out.println(" ");
}
StanfordParser spsplitter = new StanfordParser("sentence-splitter");
TEXT = "A beginning is the time for taking the most delicate care that the balances are correct. This every sister of the Bene Gesserit knows. To begin your study of the life of Muad'Dib, then, take care that you first place him in his time: born in the 57th year of the Padishah Emperor, Shaddam IV. And take the most special care that you locate Muad'Dib in his place: the planet Arrakis. Do not be deceived by the fact that he was born on Caladan and lived his first fifteen years there. Arrakis, the planet known as Dune, is forever his place.\n" +
"-from \"Manual of Muad'Dib\" by the Princess Irulan\n" +
"In the week before their departure to Arrakis, when all the final scurrying about had reached a nearly unbearable frenzy, an old crone came to visit the mother of the boy, Paul.\n" +
"It was a warm night at Castle Caladan, and the ancient pile of stone that had served the Atreides family as home for twenty-six generations bore that cooled-sweat feeling it acquired before a change in the weather.\n" +
"The old woman was let in by the side door down the vaulted passage by Paul's room and she was allowed a moment to peer in at him where he lay in his bed.\n" +
"By the half-light of a suspensor lamp, dimmed and hanging near the floor, the awakened boy could see a bulky female shape at his door, standing one step ahead of his mother. The old woman was a witch shadow -- hair like matted spiderwebs, hooded 'round darkness of features, eyes like glittering jewels.\n" +
"\"Is he not small for his age, Jessica?\" the old woman asked. Her voice wheezed and twanged like an untuned baliset.\n" +
"Paul's mother answered in her soft contralto: \"The Atreides are known to start late getting their growth, Your Reverence.\"\n" +
"\"So I've heard, so I've heard,\" wheezed the old woman. \"Yet he's already fifteen.\"\n" +
" \"Yes, Your Reverence.\"\n" +
"\"He's awake and listening to us,\" said the old woman. \"Sly little rascal.\" She chuckled. \"But royalty has need of slyness. And if he's really the Kwisatz Haderach . . . well . . .\"\n" +
"Within the shadows of his bed, Paul held his eyes open to mere slits. Two bird-bright ovals -- the eyes of the old woman -- seemed to expand and glow as they stared into his.";
Annotation document = new Annotation(TEXT);
spsplitter.pipeline.annotate(document);
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
ArrayList<ArrayList<Tuple>> sentenceParses = new ArrayList<ArrayList<Tuple>>();
for(CoreMap sent: sentences) {
// this is the parse tree of the current sentence
System.out.println(sent);
}
} |
4324d9e8-352d-4bd4-b44c-906a1bac53eb | 5 | @Override
public double getImportance(List<Example> exampleCollection) {
// assume winner 1 as positive, winner 2 as negative
double startEntropy = getEntropy(exampleCollection);
double entropyReminder = 0;
List<AttributeValue> aValueList = getAttributeValues();
List<Double> entropyList = new ArrayList<Double>();
List<Double> sizeRatioList = new ArrayList<Double>();
List<ArrayList<Example>> exampleSplit = new ArrayList<ArrayList<Example>>();
for (AttributeValue aValue : aValueList) {
exampleSplit.add(new ArrayList<Example>());
int index = aValueList.indexOf(aValue);
for (Example e : exampleCollection) {
if (getExampleAttributeValue(e).equals(aValue)) {
exampleSplit.get(index).add(e);
}
}
}
for (ArrayList<Example> eList : exampleSplit) {
double subEntropy = getEntropy(eList);
entropyList.add(subEntropy);
sizeRatioList.add(((double) eList.size())
/ exampleCollection.size());
}
for (int i = 0; i < aValueList.size(); i++) {
entropyReminder += sizeRatioList.get(i) * entropyList.get(i);
}
return startEntropy - entropyReminder;
} |
131565f6-a4ab-4145-92e8-b4fc5c3913e6 | 7 | @Override
public void handle(SocketChannel channel, Packet packet) {
if (packet instanceof GameInfoPacket) {
handleGameInfo((GameInfoPacket)packet);
} else if (packet instanceof PlayerJoinGamePacket) {
handleJoinGame((PlayerJoinGamePacket)packet);
} else if (packet instanceof SpawnPacket) {
handleSpawn((SpawnPacket)packet);
} else if (packet instanceof RemovePacket) {
handleRemove((RemovePacket)packet);
} else if (packet instanceof PosVelUpdatePacket) {
handlePosVelUpdate((PosVelUpdatePacket)packet);
} else if (packet instanceof PlayerAdjustShooterAnglePacket) {
handleAdjustShooterAngle((PlayerAdjustShooterAnglePacket)packet);
} else if (packet instanceof ScorePacket) {
handleScore((ScorePacket)packet);
}
} |
38bf68b0-a424-49d9-918e-8f8852aca549 | 7 | public void doRender(Graphics2D g, double interpolation, long renderCount) {
// Call the superclass' doRender, including the user defined render() function
super.doRender(g, interpolation, renderCount);
float opacity = (float)__getOpacity();
if (opacity <= 0.001) {
return; // If the Component is invisible, then return without rendering anything!
} else {
g.setComposite(getAlphaComposite());
}
double width = __getWidth();
double height = __getHeight();
int iWidth = (int)width;
int iHeight = (int)height;
if (this.buffer == null ||
this.bufferWidth != iWidth ||
this.bufferHeight != iHeight) {
recreateBuffer(g, iWidth, iHeight);
}
if (needsRender)
renderContainer(iWidth, iHeight, interpolation, renderCount);
this.currentRotationRad = __getRotation();
boolean needToRotate = this.currentRotationRad % (Math.PI*2) != 0.0;
if (needToRotate) {
this.currentCenterX = currentFrameX + (width / 2d);
this.currentCenterY = currentFrameY + (height / 2d);
g.rotate(this.currentRotationRad, this.currentCenterX, this.currentCenterY);
}
g.drawImage(this.buffer, (int)currentFrameX, (int)currentFrameY, iWidth, iHeight, null);
if (needToRotate) {
g.rotate(-this.currentRotationRad, this.currentCenterX, this.currentCenterY);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.