text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Node popNode() {
if (--sp < mk) {
mk = marks.remove(marks.size()-1);
}
return nodes.remove(nodes.size()-1);
} | 1 |
@Test
public void testAvoidance() {
Random r = new Random(260379);
/* First create some data */
ArrayList<Integer> workArr = new ArrayList<Integer>();
TreeMap<Integer, Integer> countToId = new TreeMap<Integer, Integer>(new Comparator<Integer>() {
public int compare(Integer integer, Integer integer1) {
return -integer.compareTo(integer1);
}
});
for(int i=1; i < 200; i++) {
int n;
do {
n = r.nextInt(10000);
} while (countToId.containsKey(n)); // Unique count keys
countToId.put(n, i);
insertMultiple(workArr, i, n);
}
DiscreteDistribution dist = new DiscreteDistribution(toIntArray(workArr));
/* Then insert some edges to avoid */
int[] avoids = new int[] {0, 2, 4, 32,33, 66, 67,68, 99, 102, 184};
DiscreteDistribution avoidDistr = DiscreteDistribution.createAvoidanceDistribution(avoids);
// Test the merge works both ways
DiscreteDistribution mergedL = DiscreteDistribution.merge(dist, avoidDistr);
DiscreteDistribution mergedR = DiscreteDistribution.merge(avoidDistr, dist);
for(int a : avoids) {
assertEquals(-1, avoidDistr.getCount(a));
assertEquals(-1, mergedL.getCount(a));
assertEquals(-1, mergedR.getCount(a));
}
IdCount[] top = dist.getTop(10);
int j = 0;
HashSet<Integer> avoidSet = new HashSet<Integer>();
for(int a : avoids) avoidSet.add(a);
for(Map.Entry <Integer, Integer> e : countToId.entrySet()) {
IdCount topEntryJ = top[j];
if (!avoidSet.contains(e.getKey())) {
assertEquals((int)e.getValue(), topEntryJ.id);
assertEquals((int)e.getKey(), topEntryJ.count);
j++;
if (top.length <= j) {
assertEquals(10, j);
break;
}
}
}
} | 7 |
@Override
public void onKeyPressed(char key, int keyCode, boolean coded)
{
// Doesn't react to coded keys
if (coded)
return;
// If backspace was pressed, removes the last character
if (key == KeyEvent.VK_BACK_SPACE && this.input.length() >= 1)
this.input = this.input.substring(0, this.input.length()-1);
// If other (SPACE, TAB, ENTER, ESC, and DELETE), doesn't react
else if (key == KeyEvent.VK_DELETE || key == KeyEvent.VK_TAB ||
key == KeyEvent.VK_ENTER || key == KeyEvent.VK_ESCAPE
|| key == KeyEvent.VK_SPACE)
return;
// Otherwise adds the character to the string
else
this.input += key;
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
QName other = (QName) obj;
if (localName == null) {
if (other.localName != null) {
return false;
}
} else if (!localName.equals(other.localName)) {
return false;
}
if (qualifier == null) {
if (other.qualifier != null) {
return false;
}
} else if (!qualifier.equals(other.qualifier)) {
return false;
}
return true;
} | 9 |
private void listLastTransactions(CommandSender sender, int amount) {
if (TransactionManager.getInstance().getTransactions().isEmpty()) {
sender.sendMessage(EdgeCore.errorColor + "No transactions found!");
return;
}
for (int i = TransactionManager.getInstance().amountOfTransactions() -1; i < TransactionManager.getInstance().getTransactions().size(); i--) {
sender.sendMessage(EdgeCore.sysColor + i + ") " + TransactionManager.getInstance().getTransaction(i).getGist());
if (i <= amount) break;
}
} | 3 |
public TripTimeLabelComponent (Trip trip) {
super (new FlowLayout (FlowLayout.LEADING));
JPanel labelPanel = new JPanel (new GridLayout (2,1));
River r = trip.getRiver();
String riverName;
if (r == null) {
riverName = "<?>";
}
else {
riverName = r.getRiverName();
}
addLabelWithBorder (labelPanel, "Gruppe " + trip.getGroupNumber());
addLabelWithBorder (labelPanel, riverName);
Border raisedbevel = BorderFactory.createRaisedBevelBorder();
this.setBorder(raisedbevel);
add (labelPanel, BorderLayout.CENTER);
} | 1 |
public Production getLambdaProductionForFinalState(Automaton automaton,
State state) {
/** Check if state is a final state. */
if (!automaton.isFinalState(state)) {
System.err.println(state + " IS NOT A FINAL STATE");
return null;
}
String llhs = (String) MAP.get(state);
String lrhs = LAMBDA;
Production lprod = new Production(llhs, lrhs);
return lprod;
} | 1 |
private void instantiate(int size) {
try {
DBConnection con;
for (int i = 0; i < size; i++) {
con = new DBConnection();
con.connect(driver, url, db, usr, pw);
free.add(con);
}
} catch (Exception e) {
e.printStackTrace();
}
} | 2 |
public void initialiseWithInfected(int numI) {
if ((numI < N) && (numI > 0)) {
states[0].setStateValue(N-numI);
for (int i = 1; i < states.length; i++) {
if (states[i].getStateName().equals("I")) {
states[i].setStateValue(numI);
} else {
states[i].setStateValue(0);
}
}
} else {
log.error("BasicSIR - Sorry cannot get numI="+numI+" with N="+N);
}
} | 4 |
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.clearRect(0, 0, this.getWidth(), this.getHeight());
g2.scale(scale, scale);
g2.translate(translateX, translateY);
world.paint(g2);
int count = 0;
for (ClickFrame clickFrame : world.clickFrameList) {
count++;
g2.setColor(Color.getHSBColor((float) ((count * Math.E) % 1), 1f, 0.8f));
Object object = clickFrame.object;
Shape shape = clickFrame.object.shapes.get(clickFrame.shapeIndex);
double x1 = (clickFrame.getX() - this.getLocationOnScreen().x) / scale - translateX;
double y1 = (clickFrame.getY() - this.getLocationOnScreen().y) / scale - translateY;
double x2 = object.position.x;
double y2 = object.position.y;
Vector2D v = new Vector2D(new Point.Double(x1, y1), new Point.Double(x2, y2));
double kx = Math.min(1, Math.max(v.point.x / clickFrame.getWidth(), 0));
double ky = Math.min(1, Math.max(v.point.y / clickFrame.getHeight(), 0));
x1 += (clickFrame.getWidth() * kx) / scale;
y1 += (clickFrame.getHeight() * ky) / scale;
v = new Vector2D(new Point.Double(x1, y1), new Point.Double(x2, y2));
Vector2D diagonal;
if (Math.abs(v.point.x) < Math.abs(v.point.y)) {
double dx = v.point.x / Math.abs(v.point.x);
double dy = v.point.y / Math.abs(v.point.y);
diagonal = new Vector2D(new Point.Double(Math.abs(v.point.x) * dx, Math.abs(v.point.x) * dy));
} else {
double dx = v.point.x / Math.abs(v.point.x);
double dy = v.point.y / Math.abs(v.point.y);
diagonal = new Vector2D(new Point.Double(Math.abs(v.point.y) * dx, Math.abs(v.point.y) * dy));
}
if (shape instanceof RectangleShape) {
RectangleShape rs = (RectangleShape) shape;
if (v.point.x == 0 || v.point.y == 0) {
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
} else {
g2.drawLine((int) x1, (int) y1, (int) (x1 + diagonal.point.x), (int) (y1 + diagonal.point.y));
g2.drawLine((int) (x1 + diagonal.point.x), (int) (y1 + diagonal.point.y), (int) (x2), (int) (y2));
}
} else if (shape instanceof CircleShape) {
CircleShape cs = (CircleShape) shape;
if (v.point.x == 0 || v.point.y == 0) {
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
} else {
g2.drawLine((int) x1, (int) y1, (int) (x1 + diagonal.point.x), (int) (y1 + diagonal.point.y));
g2.drawLine((int) (x1 + diagonal.point.x), (int) (y1 + diagonal.point.y), (int) (x2), (int) (y2));
}
}
}
g2.translate(-translateX, -translateY);
} | 8 |
private static boolean dragBetween(WidgetChild start, WidgetChild end) {
if (start == null || end == null || !start.visible() || !end.visible())
return false;
if (!hoverChild(start))
return false;
Mouse.drag(end.getNextViewportPoint());
return true;
} | 5 |
@Test
public void WhenUnionBothHavingLevels_ExpectChange()
throws UnknownHostException {
int level = localhost_.getHostPath().length();
RoutingTable table = new RoutingTable();
table.setLocalhost(localhost_);
Host host = new PGridHost("127.0.0.1", 3333);
table.addReference(0, host);
Assert.assertTrue(table.levelNumber() == level);
Assert.assertTrue(table.uniqueHostsNumber() == 1);
RoutingTable other = new RoutingTable();
Host otherHost = new PGridHost("127.0.0.1", 1234);
otherHost.setHostPath("0000");
other.setLocalhost(otherHost);
int otherLevel = otherHost.getHostPath().length();
Host host1 = new PGridHost("127.0.0.1", 1111);
other.addReference(0, host1);
Assert.assertTrue(other.levelNumber() == otherLevel);
Assert.assertTrue(other.uniqueHostsNumber() == 1);
table.unionLevel(0, other);
Assert.assertTrue(table.levelNumber() == level);
Assert.assertTrue(table.contains(host) && table.contains(host1));
Assert.assertTrue(table.uniqueHostsNumber() == 2);
} | 1 |
public boolean reserve(long id) {
if(enemyID == NO_ENEMY) {
enemyID = id;
return true;
}
else {
return false;
}
} | 1 |
@Test
public void testIterativeSearch() throws Exception
{
PersistenceManager pm = new PersistenceManager(driver, database, login, password);
// drop all tables
pm.dropTable(Object.class);
// create 42 simpleobjects
final int testCount = 42;
for (int x = 0; x < testCount; x++)
{
SimpleObject so = new SimpleObject();
// reverse order of COUNT column relative to C__ID
so.setCount(testCount - x);
pm.saveObject(so);
}
// make sure all objects are still there
assertEquals(testCount, pm.getCount(SimpleObject.class, new All()));
// use an array to get around inner class limitations
final int[] numberFound = new int[2];
// find all objects
pm.getObjects(SimpleObject.class, new SearchListener<SimpleObject>()
{
@Override
public void objectFound(SimpleObject object)
{
if (numberFound[0] > 0)
{
// check that we're going descending order
assertEquals(numberFound[1] - 1, object.getCount());
}
numberFound[0]++;
numberFound[1] = object.getCount();
}
}, new All());
assertEquals(testCount, numberFound[0]);
// get a subset of finds, ordered by COUNT column
final int startAt = 5;
final int totalCount = 26;
SimpleObject orderObject = new SimpleObject();
orderObject.setCount(1);
numberFound[0] = 0;
numberFound[1] = startAt;
pm.getObjects(SimpleObject.class, new SearchListener<SimpleObject>()
{
@Override
public void objectFound(SimpleObject object)
{
// check that we're going ascending order
assertEquals(numberFound[1] + 1, object.getCount());
numberFound[0]++;
numberFound[1] = object.getCount();
}
}, new All(), new Order(totalCount, startAt, new Ascending(orderObject)));
assertEquals(totalCount, numberFound[0]);
//make sure we get the all objects when we search by superclass
numberFound[0] = 0;
numberFound[1] = 0;
pm.getObjects(Object.class, new SearchListener<Object>()
{
@Override
public void objectFound(Object o)
{
if (o instanceof SimpleObject)
{
SimpleObject object = (SimpleObject) o;
if (numberFound[0] > 0)
{
// check that we're going descending order
assertEquals(numberFound[1] - 1, object.getCount());
}
numberFound[0]++;
numberFound[1] = object.getCount();
}
}
}, new All());
assertEquals(testCount, numberFound[0]);
pm.close();
//make sure we get the all objects when we search by superclass, even from a new PM
pm = new PersistenceManager(driver, database, login, password);
numberFound[0] = 0;
numberFound[1] = 0;
pm.getObjects(Object.class, new SearchListener<Object>()
{
@Override
public void objectFound(Object o)
{
if (o instanceof SimpleObject)
{
SimpleObject object = (SimpleObject) o;
if (numberFound[0] > 0)
{
// check that we're going descending order
assertEquals(numberFound[1] - 1, object.getCount());
}
numberFound[0]++;
numberFound[1] = object.getCount();
}
}
}, new All());
assertEquals(testCount, numberFound[0]);
pm.close();
} | 6 |
public static void adjustModuleCMakeLists(File moduleDirName, String fileName, boolean fileWasCreated, IOutput output)
{
output.writeLine(" Registering file in module specific CMakeLists");
File cmakelistsFile = new File(moduleDirName, Constants.CMAKELISTS_FILENAME);
if (!cmakelistsFile.exists())
{
try
{
cmakelistsFile.createNewFile();
}
catch (IOException e)
{
throw new IllegalStateException(e);
}
}
String[] lines = readAllLines(cmakelistsFile);
Map<String, String> variables = new HashMap<String, String>();
variables.put("fileName", fileName);
String addFileCommand = TemplateHandling.getProperty("FileContents.properties", "ADD_FILE_TEMPLATE", variables, moduleDirName);
if (lineAlreadyExists(lines, addFileCommand))
{
// no need to write, but we need to "change" the file so that a rebuild is performed
if (fileWasCreated)
{
cmakelistsFile.setLastModified(System.currentTimeMillis());
}
output.writeLine(" No need to adjust CMakeLists, because file entry already exists.");
return;
}
String[] newlines = new String[lines.length + 1];
for (int i = 0; i < newlines.length; i++)
{
newlines[i] = "";
}
int index = 0;
String addModulePrefix = TemplateHandling.getProperty("FileContents.properties", "ADD_MODULE_PREFIX_TEMPLATE", null, moduleDirName);
boolean found = false;
for (int i = 0; i < lines.length; i++)
{
newlines[index] = lines[i];
index++;
// insert right after module definition
if (lines[i].trim().toLowerCase().contains(addModulePrefix.toLowerCase()))
{
// add our entry right after it!
newlines[index] = addFileCommand;
index++;
found = true;
}
}
if (found)
{
writeAllLines(cmakelistsFile, newlines);
}
else
{
output.writeLine(" Could not insert text in the CMakeLists file. It remains unchanged.");
}
} | 8 |
public static URL convertToURL(String path) {
if(path==null || path.isEmpty()){
return null;
}
URL url = null;
try {
url = new URL(path);
} catch (MalformedURLException e) {
url = Thread.currentThread().getContextClassLoader().getResource(
path);
if (url == null) {
File file = new File(path);
if (file.exists()) {
try {
url = file.toURI().toURL();
} catch (MalformedURLException e1) {
Logger.getLogger(Util.class.getName())
.log(Level.SEVERE, path + " is Not valid", e);
}
}
}
}
return url;
} | 6 |
private void upload(File source) throws Exception {
if (source.isDirectory()) {
String[] list = source.list();
for (int index = 0; index < list.length; index++) {
File newSource = new File(source, list[index]);
upload(newSource);
}
if (count.containsKey("Directory")) {
count.put("Directory", Integer.sum(count.get("Directory").intValue(),1));
} else {
count.put("Directory", 1);
}
System.out.println(count);
} else {
StringTokenizer st = new StringTokenizer(source.getParent(), " /-");
Collection<String> tags = new ArrayList<String>();
while (st.hasMoreElements()) {
tags.add(st.nextElement().toString());
}
tags.add("Importado"+tagTime);
String mimeType = Files.probeContentType(Paths.get(source.getPath()));
if (count.containsKey(mimeType)) {
count.put(mimeType, Integer.sum(count.get(mimeType).intValue(),1));
} else {
count.put(mimeType, 1);
}
System.out.println(count);
String contentType;
if (mimeType.equals("image/jpeg")) {
contentType = Flickr.CONTENTTYPE_PHOTO;
} else {
contentType = Flickr.CONTENTTYPE_OTHER;
}
if (mimeType.equals("image/jpeg") || mimeType.equals("video/mpeg") || mimeType.equals("video/quicktime")) {
Upload up = new Upload();
up.execute(source, tags, contentType, mimeType);
}
System.out.println(count);
}
} | 9 |
public static String[] getFileContents(String fileName)
{
final ArrayList<String> lines = new ArrayList<String>();
String line = "";
try
{
final BufferedReader reader = Files.newBufferedReader(Paths.get(fileName), Charset.forName("US-ASCII"));
while (true)
{
line = reader.readLine();
if (line != null)
{
lines.add(line);
continue;
}
break;
}
}
catch (final IOException e)
{
e.printStackTrace();
}
return lines.toArray(new String[0]);
} | 3 |
@Override
public void execute(Player player, String[] args)
{
if(args.length == 1)
{
Player other = player.getServer().getPlayer(args[0]);
if(other != null)
{
player.setPos(other.getX(), other.getY(), other.getZ());
} else {
player.sendMessage(args[1] + " is not online.");
}
} else if(args.length == 2) {
Player otherTPing = player.getServer().getPlayer(args[0]);
Player otherTPto = player.getServer().getPlayer(args[1]);
if(otherTPing != null && otherTPto != null)
{
otherTPing.setPos(otherTPto.getX(), otherTPto.getY(), otherTPto.getZ());
} else {
player.sendMessage("Either " + args[0] + " or " + args[1] + " is not online.");
}
} else {
help(player);
}
} | 5 |
protected Value getSimpleDefaultValue(String t) {
if (t.equals("java.lang.String"))
return StringConstant.v("");
if (t.equals("char"))
return DIntConstant.v(0, CharType.v());
if (t.equals("byte"))
return DIntConstant.v(0, ByteType.v());
if (t.equals("short"))
return DIntConstant.v(0, ShortType.v());
if (t.equals("int"))
return IntConstant.v(0);
if (t.equals("float"))
return FloatConstant.v(0);
if (t.equals("long"))
return LongConstant.v(0);
if (t.equals("double"))
return DoubleConstant.v(0);
if (t.equals("boolean"))
return DIntConstant.v(0, BooleanType.v());
//also for arrays etc.
return G.v().soot_jimple_NullConstant();
} | 9 |
public static int HSBtoRGB(float hue, float saturation, float brightness) {
int r = 0, g = 0, b = 0;
if (saturation == 0) {
r = g = b = (int) (brightness * 255.0f + 0.5f);
} else {
float h = (hue - (float)Math.floor(hue)) * 6.0f;
float f = h - (float)java.lang.Math.floor(h);
float p = brightness * (1.0f - saturation);
float q = brightness * (1.0f - saturation * f);
float t = brightness * (1.0f - (saturation * (1.0f - f)));
switch ((int) h) {
case 0:
r = (int) (brightness * 255.0f + 0.5f);
g = (int) (t * 255.0f + 0.5f);
b = (int) (p * 255.0f + 0.5f);
break;
case 1:
r = (int) (q * 255.0f + 0.5f);
g = (int) (brightness * 255.0f + 0.5f);
b = (int) (p * 255.0f + 0.5f);
break;
case 2:
r = (int) (p * 255.0f + 0.5f);
g = (int) (brightness * 255.0f + 0.5f);
b = (int) (t * 255.0f + 0.5f);
break;
case 3:
r = (int) (p * 255.0f + 0.5f);
g = (int) (q * 255.0f + 0.5f);
b = (int) (brightness * 255.0f + 0.5f);
break;
case 4:
r = (int) (t * 255.0f + 0.5f);
g = (int) (p * 255.0f + 0.5f);
b = (int) (brightness * 255.0f + 0.5f);
break;
case 5:
r = (int) (brightness * 255.0f + 0.5f);
g = (int) (p * 255.0f + 0.5f);
b = (int) (q * 255.0f + 0.5f);
break;
}
}
return 0xff000000 | (r << 16) | (g << 8) | (b << 0);
} | 7 |
public boolean prob(double x) {
if (x >= 1) {
return true;
}
if (x <= 0) {
return false;
}
double eps = 0.000000001;
double a = 0, b = 1;
do {
boolean pb = prob();
double center = (a + b) / 2;
if (Math.abs(x - center) < eps) {
return pb;
}
if (x > center && pb) {
return true;
}
if (x < center && !pb) {
return false;
}
if (x > center) {
a = center;
}
else {
b = center;
}
// x = (x>0.5? (x-0.5):x)*2;
eps *= 2;
exp_value++;
}
while (true);
} | 9 |
protected void appendDescriptor(final int type, final String desc) {
if (type == CLASS_SIGNATURE || type == FIELD_SIGNATURE
|| type == METHOD_SIGNATURE) {
if (desc != null) {
buf.append("// signature ").append(desc).append('\n');
}
} else {
buf.append(desc);
}
} | 4 |
public Collection<LineUp> getLineUps(Groop grp) throws SQLException
{
Collection<LineUp> lineups = new LinkedList<LineUp>();
// Get a statement and run the query
String sql = "SELECT LineUp.LineUpNumber, ArtistNumber FROM LineUp,LineUpDetails WHERE LineUp.GroopNumber = ? AND LineUp.LineUpNumber = LineUpDetails.LineUpNumber ORDER BY LineUp.LineUpNumber ASC";
PreparedStatement ps = Connect.getConnection().getPreparedStatement(sql);
ps.setInt(1, grp.getNumber());
ps.execute();
ResultSet rs = ps.getResultSet();
LineUp currLineUp = null;
while (rs.next())
{
// Read the info
int lineUpNumber = rs.getInt(1);
int artistNumber = rs.getInt(2);
if (currLineUp == null)
{
currLineUp = new LineUp(lineUpNumber, new TreeSet<Artist>(), grp);
currLineUp.addArtist(GetArtists.create().getArtist(artistNumber));
}
else if (currLineUp.getLineUpNumber() != lineUpNumber)
{
// Add the line up
lineups.add(currLineUp);
// Construct the new line up
currLineUp = new LineUp(lineUpNumber, new TreeSet<Artist>(), grp);
currLineUp.addArtist(GetArtists.create().getArtist(artistNumber));
}
else
currLineUp.addArtist(GetArtists.create().getArtist(artistNumber));
}
if (currLineUp != null && currLineUp.getArtists().size() > 0)
lineups.add(currLineUp);
return lineups;
} | 5 |
private String getResponse() {
String result;
try {
result = _in.readLine();
} catch (IOException e) {
throw new UIError(); // re-throw UIError
}
if (result == null) {
throw new UIError(); // input closed
}
return result;
} | 2 |
public void doStuff() {
if (!hsa.done) {
hsa.doAlg();
int step = hsa.step;
switch (step) {
case 1:
l.setText("step 1: divided in intervals");
break;
case 2:
l.setText("step 2: found interval with odd intersection property");
break;
case 3:
l.setText("step 3: constructed trapeze");
break;
case 4:
l.setText("zoomed in on trapeze");
lp.followTrapeze();
case 0:
l.setText("step 4: removed lines outside the trapeze");
break;
}
if (hsa.getVisualPoints().size() == 0) {
l.setText("step 0: place points");
} else {
applet.setPlacingEnabled(false);
}
if (hsa.done) {
applet.setStepsEnabled(false);
if (hsa.validSol(false)) {
l.setText("found valid solution!");
} else {
l.setText("found invalid solution");
}
}
pp.setAddingAllowed(false);
List<VisualPoint> vpoints = hsa.getVisualPoints();
pp.setVisualPoints(vpoints);
lp.setVisualPoints(vpoints);
pp.revalidate();
pp.repaint();
lp.revalidate();
lp.repaint();
}
} | 9 |
public Knapsack executeOnce(Knapsack knapsack) {
int neighbours = generateRandomNumberOfNeighbours();
Knapsack best = null;
for (int i=0; i<neighbours; i++) {
Knapsack candidate = generateNeighbour(knapsack);
if (best == null) {
best = candidate;
} else if (candidate.compareWith(best) > 0) {
best = candidate;
}
}
if (best.compareWith(knapsack) >= 0) {
heatTemperature();
return best;
} else {
if (Math.random() >= calculateProbability(best, knapsack)) {
freezeTemperature();
return best;
} else {
return knapsack;
}
}
} | 5 |
public void method354(Background background, int i, int j)
{
j += anInt1442;
i += anInt1443;
int k = j + i * DrawingArea.width;
int l = 0;
int i1 = myHeight;
int j1 = myWidth;
int k1 = DrawingArea.width - j1;
int l1 = 0;
if(i < DrawingArea.topY)
{
int i2 = DrawingArea.topY - i;
i1 -= i2;
i = DrawingArea.topY;
l += i2 * j1;
k += i2 * DrawingArea.width;
}
if(i + i1 > DrawingArea.bottomY)
i1 -= (i + i1) - DrawingArea.bottomY;
if(j < DrawingArea.topX)
{
int j2 = DrawingArea.topX - j;
j1 -= j2;
j = DrawingArea.topX;
l += j2;
k += j2;
l1 += j2;
k1 += j2;
}
if(j + j1 > DrawingArea.bottomX)
{
int k2 = (j + j1) - DrawingArea.bottomX;
j1 -= k2;
l1 += k2;
k1 += k2;
}
if(!(j1 <= 0 || i1 <= 0))
{
method355(myPixels, j1, background.aByteArray1450, i1, DrawingArea.pixels, 0, k1, k, l1, l);
}
} | 6 |
public static boolean visible(WidgetChild... wc) {
if (wc == null || wc.length == 0)
return false;
for (WidgetChild c : wc) {
if (c == null || !c.visible())
return false;
}
return true;
} | 5 |
@Override
protected String readLineInternal() throws IOException {
if (skippingDone == false) {
skippingDone = true;
do {
final String s = readLine();
if (s == null) {
return null;
}
Matcher m = endifPattern.matcher(s);
if (m.find()) {
return null;
}
m = elsePattern.matcher(s);
if (m.find()) {
break;
}
} while (true);
}
final String s = super.readLineInternal();
if (s == null) {
return null;
}
Matcher m = endifPattern.matcher(s);
if (m.find()) {
return null;
}
return s;
} | 7 |
public static List<String> readTextFile(Path file) {
if (!FileUtil.control(file)) {
IllegalArgumentException iae = new IllegalArgumentException("The filepath is null or points to an invalid location!");
Main.handleUnhandableProblem(iae);
}
return FileReader.readFile(file);
} | 1 |
protected void drawMapTiles(final Graphics g, final int zoom, Rectangle viewportBounds)
{
int size = getTileFactory().getTileSize(zoom);
Dimension mapSize = getTileFactory().getMapSize(zoom);
// calculate the "visible" viewport area in tiles
int numWide = viewportBounds.width / size + 2;
int numHigh = viewportBounds.height / size + 2;
// TilePoint topLeftTile = getTileFactory().getTileCoordinate(
// new Point2D.Double(viewportBounds.x, viewportBounds.y));
TileFactoryInfo info = getTileFactory().getInfo();
// number of tiles in x direction
int tpx = (int) Math.floor(viewportBounds.getX() / info.getTileSize(0));
// number of tiles in y direction
int tpy = (int) Math.floor(viewportBounds.getY() / info.getTileSize(0));
// TilePoint topLeftTile = new TilePoint(tpx, tpy);
// p("top tile = " + topLeftTile);
// fetch the tiles from the factory and store them in the tiles cache
// attach the tileLoadListener
for (int x = 0; x <= numWide; x++)
{
for (int y = 0; y <= numHigh; y++)
{
int itpx = x + tpx;// topLeftTile.getX();
int itpy = y + tpy;// topLeftTile.getY();
// TilePoint point = new TilePoint(x + topLeftTile.getX(), y + topLeftTile.getY());
// only proceed if the specified tile point lies within the area being painted
if (g.getClipBounds().intersects(
new Rectangle(itpx * size - viewportBounds.x, itpy * size - viewportBounds.y, size, size)))
{
Tile tile = getTileFactory().getTile(itpx, itpy, zoom);
int ox = ((itpx * getTileFactory().getTileSize(zoom)) - viewportBounds.x);
int oy = ((itpy * getTileFactory().getTileSize(zoom)) - viewportBounds.y);
// if the tile is off the map to the north/south, then just don't paint anything
if (isTileOnMap(itpx, itpy, mapSize))
{
if (isOpaque())
{
g.setColor(getBackground());
g.fillRect(ox, oy, size, size);
}
}
else if (tile.isLoaded())
{
g.drawImage(tile.getImage(), ox, oy, null);
}
else
{
// Use tile at higher zoom level with 200% magnification
Tile superTile = getTileFactory().getTile(itpx / 2, itpy / 2, zoom + 1);
if (superTile.isLoaded())
{
int offX = (itpx % 2) * size / 2;
int offY = (itpy % 2) * size / 2;
g.drawImage(superTile.getImage(), ox, oy, ox + size, oy + size, offX, offY, offX + size / 2, offY + size / 2, null);
}
else
{
int imageX = (getTileFactory().getTileSize(zoom) - getLoadingImage().getWidth(null)) / 2;
int imageY = (getTileFactory().getTileSize(zoom) - getLoadingImage().getHeight(null)) / 2;
g.setColor(Color.GRAY);
g.fillRect(ox, oy, size, size);
g.drawImage(getLoadingImage(), ox + imageX, oy + imageY, null);
}
}
if (isDrawTileBorders())
{
g.setColor(Color.black);
g.drawRect(ox, oy, size, size);
g.drawRect(ox + size / 2 - 5, oy + size / 2 - 5, 10, 10);
g.setColor(Color.white);
g.drawRect(ox + 1, oy + 1, size, size);
String text = itpx + ", " + itpy + ", " + getZoom();
g.setColor(Color.BLACK);
g.drawString(text, ox + 10, oy + 30);
g.drawString(text, ox + 10 + 2, oy + 30 + 2);
g.setColor(Color.WHITE);
g.drawString(text, ox + 10 + 1, oy + 30 + 1);
}
}
}
}
} | 8 |
public static void main(String args[]) {
//<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(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Principal().setVisible(true);
}
});
} | 6 |
public static boolean zmq_proxy (SocketBase frontend_, SocketBase backend_, SocketBase control_)
{
if (frontend_ == null || backend_ == null) {
ZError.errno (ZError.EFAULT);
throw new IllegalArgumentException();
}
return Proxy.proxy (
frontend_,
backend_,
control_);
} | 2 |
@Override
public int getSlotSpacingX() {
return isNotPlayerInventory() ? 32 : 18;
} | 1 |
public static void reallyDeleteObject(PaintBox box) {
Rectangle redrawBounds = null;
if (box instanceof FTLRoom) {
FTLRoom r = (FTLRoom) box;
Point oldLow = null;
Point oldHigh = null;
if (Main.ship != null) {
oldLow = Main.ship.findLowBounds();
oldHigh = Main.ship.findHighBounds();
oldLow.x = oldLow.x + (oldHigh.x - oldLow.x) / 2;
oldLow.y = oldLow.y + (oldHigh.y - oldLow.y) / 2;
}
redrawBounds = r.getBounds();
r.dispose();
ship.rooms.remove(r);
removeUnalignedDoors();
r = null;
if (Main.ship != null) {
Point p = Main.ship.findLowBounds();
Point pt = Main.ship.findHighBounds();
p.x = p.x + (pt.x - p.x) / 2;
p.y = p.y + (pt.y - p.y) / 2;
pt.x = p.x - oldLow.x;
pt.y = p.y - oldLow.y;
p = shieldBox.getLocation();
shieldBox.setLocation(p.x + pt.x, p.y + pt.y);
}
if (ship.rooms.size() == 0) {
btnShields.setEnabled(false);
}
} else if (box instanceof FTLDoor) {
FTLDoor d = (FTLDoor) box;
redrawBounds = d.getBounds();
d.dispose();
ship.doors.remove(d);
d = null;
} else if (box instanceof FTLMount) {
FTLMount m = (FTLMount) box;
redrawBounds = m.getBounds();
m.dispose();
ship.mounts.remove(m);
m = null;
redrawBounds.x -= 40;
redrawBounds.y -= 40;
redrawBounds.width += 80;
redrawBounds.height += 80;
} else if (box instanceof FTLGib) {
FTLGib g = (FTLGib) box;
if (gibWindow.isVisible())
gibWindow.escape();
g.deselect();
gibDialog.removeGibFromList(g);
g.dispose();
Main.ship.gibs.remove(g);
gibDialog.letters.remove(g.ID);
Main.canvas.redraw(g.getBounds().x - 1, g.getBounds().y - 1, g.getBounds().width + 2, g.getBounds().height + 2, false);
}
if (redrawBounds != null)
canvasRedraw(redrawBounds, false);
} | 9 |
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs){
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} | 7 |
public void draw(Graphics g){
Color c = g.getColor();
g.setColor(Color.DARK_GRAY);
g.fillRect(x,y,w,h);
g.setColor(c);
} | 0 |
public int minHeight(int[] height,int sta,int end){
int min =0Xffff;
int index =sta;
for(int i= sta; i<=end ;i++){
if(min > height[i]){
min = height[i];
index = i;
}
}
return index;
} | 2 |
public void init() {
int a, b, c, d, e, f, g, h;
a = b = c = d = e = f = g = h = 0x9e3779b9;
for (int i = 0; i < 4; i++) {
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
}
for (int j = 0; j < 256; j += 8) {
a += results[j];
b += results[j + 1];
c += results[j + 2];
d += results[j + 3];
e += results[j + 4];
f += results[j + 5];
g += results[j + 6];
h += results[j + 7];
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
memory[j] = a;
memory[j + 1] = b;
memory[j + 2] = c;
memory[j + 3] = d;
memory[j + 4] = e;
memory[j + 5] = f;
memory[j + 6] = g;
memory[j + 7] = h;
}
for (int k = 0; k < 256; k += 8) {
a += memory[k];
b += memory[k + 1];
c += memory[k + 2];
d += memory[k + 3];
e += memory[k + 4];
f += memory[k + 5];
g += memory[k + 6];
h += memory[k + 7];
a ^= b << 11;
d += a;
b += c;
b ^= c >>> 2;
e += b;
c += d;
c ^= d << 8;
f += c;
d += e;
d ^= e >>> 16;
g += d;
e += f;
e ^= f << 10;
h += e;
f += g;
f ^= g >>> 4;
a += f;
g += h;
g ^= h << 8;
b += g;
h += a;
h ^= a >>> 9;
c += h;
a += b;
memory[k] = a;
memory[k + 1] = b;
memory[k + 2] = c;
memory[k + 3] = d;
memory[k + 4] = e;
memory[k + 5] = f;
memory[k + 6] = g;
memory[k + 7] = h;
}
isaac();
count = 256;
} | 3 |
@Test
public void testNull() {
StaticIntervalTree<Double, Interval<Double>> tree = new StaticIntervalTree<Double, Interval<Double>>();
try {
tree.buildTree(null);
Assert.fail();
} catch (NullPointerException e) {
}
try {
tree.fetchContainingIntervals(new ArrayList<Interval<Double>>(),
(Double) null);
Assert.fail();
} catch (NullPointerException e) {
}
try {
tree.fetchContainingIntervals((Collection<Interval<Double>>) null, 0.0);
Assert.fail();
} catch (NullPointerException e) {
}
try {
tree.fetchOverlappingIntervals(new ArrayList<Interval<Double>>(),
(Interval<Double>) null);
Assert.fail();
} catch (NullPointerException e) {
}
try {
tree.fetchOverlappingIntervals((Collection<Interval<Double>>) null,
new Interval<Double>(0.0, true, 1.0, true));
Assert.fail();
} catch (NullPointerException e) {
}
Assert.assertFalse(tree.delete(null));
Set<Interval<Double>> list = new HashSet<Interval<Double>>(masterClosed);
list.add(null);
try {
tree.buildTree(list);
Assert.fail();
} catch (NullPointerException e) {
}
tree.buildTree(new HashSet<Interval<Double>>(masterClosed));
try {
tree.insert(null);
Assert.fail();
} catch (NullPointerException e) {
}
} | 7 |
public ArrayList<Pair<File,Tag>> load(File file) throws FileNotFoundException,IOException {
ArrayList<Pair<File,Tag>> pairs = new ArrayList<Pair<File,Tag>>();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String strLine;
if (br.readLine().equals("#EXTM3U")) {
while ((strLine = br.readLine()) != null) {
if (strLine.isEmpty()) continue;
Tag stag = new Tag();
if (strLine.startsWith("#EXTINF")) {
strLine = strLine.substring(8);
stag.title = strLine = strLine.substring(strLine.indexOf(',')+1);
strLine = br.readLine();
}
File sfile = new File(strLine);
if (!sfile.isAbsolute()) sfile = new File(file.getParentFile(),strLine);
if (stag.title.isEmpty()) {
TagID3v1 id3 = new TagID3v1();
id3.read(sfile);
if (stag.artist.isEmpty()) stag.artist = id3.artist;
if (stag.title.isEmpty()) stag.title = id3.title;
}
pairs.add(new Pair<File,Tag>(sfile,stag));
}
}
br.close();
fr.close();
return pairs;
} | 8 |
public static void addBoilerFuel(Fluid fluid, int heatValuePerBucket) {
ModContainer mod = Loader.instance().activeModContainer();
String modName = mod != null ? mod.getName() : "An Unknown Mod";
if (fluid == null) {
FMLLog.log("Railcraft", Level.WARN, String.format("An error occured while %s was registering a Boiler fuel source", modName));
return;
}
boilerFuel.put(fluid, heatValuePerBucket);
FMLLog.log("Railcraft", Level.DEBUG, String.format("%s registered \"%s\" as a valid Boiler fuel source with %d heat.", modName, fluid.getName(), heatValuePerBucket));
} | 2 |
@Override
public boolean execute(WorldChannels plugin, CommandSender sender,
Command command, String label, String[] args) {
final Map<Flag, String> info = new EnumMap<Flag, String>(Flag.class);
info.put(Flag.TAG, WorldChannels.TAG);
if(!(sender instanceof Player)) {
sender.sendMessage(Localizer.parseString(
LocalString.NO_CONSOLE, info));
} else {
try {
final Channel channel = parseChannel(sender, args[0], plugin.getModuleForClass(ConfigHandler.class));
final String playerName = expandName(args[1]);
if(playerName != null) {
final Player target = plugin.getServer().getPlayer(
playerName);
if(target != null) {
if(channel != null) {
if(sender.hasPermission(channel
.getPermissionMute()) || channel.getPermissionMute().isEmpty()) {
channel.removeMutedPlayer(target
.getName());
target.sendMessage(ChatColor.YELLOW
+ WorldChannels.TAG
+ " You have been unmuted in channel '"
+ channel.getName() + "' by "
+ sender.getName());
sender.sendMessage(ChatColor.GREEN
+ WorldChannels.TAG
+ " Unmuted "
+ target.getName()
+ " in channel "
+ channel.getName());
} else {
info.put(Flag.EXTRA,
channel.getPermissionMute());
sender.sendMessage(Localizer
.parseString(
LocalString.PERMISSION_DENY,
info));
}
} else {
info.put(Flag.EXTRA, args[0]);
info.put(Flag.REASON, "channel");
sender.sendMessage(Localizer.parseString(
LocalString.UNKNOWN, info));
}
} else {
info.put(Flag.EXTRA, args[1]);
info.put(Flag.REASON, "player");
sender.sendMessage(Localizer.parseString(
LocalString.UNKNOWN, info));
}
} else {
info.put(Flag.EXTRA, args[1]);
info.put(Flag.REASON, "player");
sender.sendMessage(Localizer.parseString(
LocalString.UNKNOWN, info));
}
} catch(ArrayIndexOutOfBoundsException e) {
info.put(Flag.EXTRA, "channel name");
sender.sendMessage(Localizer.parseString(
LocalString.MISSING_PARAM, info));
}
}
return true;
} | 7 |
public int compare(Object arg1, Object arg2) {
if (!map.containsKey(arg1) || !map.containsKey(arg2)) { return 0; }
Comparable value1 = (Comparable) map.get(arg1);
Comparable value2 = (Comparable) map.get(arg2);
return -value1.compareTo(value2); // Note: We use a minus because we want decreasing order (high values first)
} | 2 |
public boolean _setHp(int hp)
{
if(hp > -1)
{
this.hp = hp; // Set HP to the provided value.
return true; // Return true, HP updated.
}
else
{
return false; // Couldn't update HP (probably invalid HP value).
}
} | 1 |
public T set(T newValue, int index)
{
if(index < 0 || index > size())
throw new ArrayIndexOutOfBoundsException();
T old = item[index];
item[index] = newValue;
return old;
} | 2 |
private Dockable getDockableInDrag(DropTargetDragEvent dtde) {
if (dtde.getDropAction() == DnDConstants.ACTION_MOVE) {
try {
if (dtde.isDataFlavorSupported(DockableTransferable.DATA_FLAVOR)) {
Dockable dockable = (Dockable) dtde.getTransferable().getTransferData(DockableTransferable.DATA_FLAVOR);
DockContainer dc = dockable.getDockContainer();
if (dc != null && dc.getDock() == this) {
return dockable;
}
}
} catch (Exception exception) {
Log.error(exception);
}
}
return null;
} | 5 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Funcionario other = (Funcionario) obj;
if (this.IdFuncionario != other.IdFuncionario && (this.IdFuncionario == null || !this.IdFuncionario.equals(other.IdFuncionario))) {
return false;
}
return true;
} | 5 |
public Iterable<WeightedEdge> edges()
{
List<WeightedEdge> edges = new LinkedList<WeightedEdge>();
for (int v = 0; v < V(); v++)
for (WeightedEdge e : adj[v])
if (e.other(v) > v)
edges.add(e);
return edges;
} | 3 |
public ArrayList<Double> getSeparateLengths()
{
ArrayList<Double> lengths = new ArrayList<Double>();
for (Edge edge : edges)
lengths.add(edge.getLength());
return lengths;
} | 1 |
public ScaledResolution(GameSettings var1, int var2, int var3) {
this.scaledWidth = var2;
this.scaledHeight = var3;
this.scaleFactor = 1;
int var4 = var1.guiScale;
if(var4 == 0) {
var4 = 1000;
}
while(this.scaleFactor < var4 && this.scaledWidth / (this.scaleFactor + 1) >= 320 && this.scaledHeight / (this.scaleFactor + 1) >= 240) {
++this.scaleFactor;
}
this.scaledWidthD = (double)this.scaledWidth / (double)this.scaleFactor;
this.scaledHeightD = (double)this.scaledHeight / (double)this.scaleFactor;
this.scaledWidth = (int)Math.ceil(this.scaledWidthD);
this.scaledHeight = (int)Math.ceil(this.scaledHeightD);
} | 4 |
public void setLocation_id(String location_id) {
this.location_id = location_id;
setDirty();
} | 0 |
double playGame(Player black, Player white) {
System.out.println(black + " vs " + white);
long[] elapsedTime = new long[2];
State board = new State();
while (!board.gameOver()) {
int move;
long before = System.nanoTime();
if (board.getColorToPlay() == 'X') {
move = black.move(board);
elapsedTime[0] += System.nanoTime() - before;
if (elapsedTime[0] > TIME_LIMIT) {
System.out.println("BLACK FORFEITS ON TIME");
return 0;
}
} else {
move = white.move(board);
elapsedTime[1] += System.nanoTime() - before;
if (elapsedTime[1] > TIME_LIMIT) {
System.out.println("WHITE FORFEITS ON TIME");
return 1;
}
}
if (board.legalMoves().contains(move)) {
board.play(move);
} else {
System.out.println("Illegal move!");
}
}
System.out.println("Elapsed time (nanoseconds):");
System.out.println("Black: " + elapsedTime[0]);
System.out.println("White: " + elapsedTime[1]);
if (board.score() > 0) {
return 1.0;
} else if (board.score() < 0) {
return 0.0;
} else {
return 0.5;
}
} | 7 |
public boolean isLargerThan(Domino other, int suit) {
// Shortcut edge case
if (other == null) {
return true;
}
if (isSuit(suit) && !other.isSuit(suit)) {
// The other domino doesn't match the given suit
return true;
}
// Determine which side of the other domino we match
if (isSuit(other.littleEnd())) {
if (isDouble())
return true;
if (other.isDouble())
return false;
// Same suit as the other's little end
return bigEnd() > other.bigEnd();
} else if (isSuit(other.bigEnd())) {
if (isDouble())
return true;
if (other.isDouble())
return false;
return littleEnd() > other.littleEnd();
} else {
// The two dominoes share no suit, so this domino can't be larger
return false;
}
} | 9 |
public void driver() {
System.out.println("bmw bus drive");
} | 0 |
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
} | 8 |
@Override
public String getColumnName(int col) {
switch (col) {
case 0: return Localization.getInstance().get("wordColumnName");
case 1: return Localization.getInstance().get("definitionColumnName");
case 2: return Localization.getInstance().get("categoryColumnName");
case 3: return Localization.getInstance().get("notesColumnName");
default:
return null;
}
} | 4 |
public void savePatient(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException{
log.debug("PatientManager savePatient method called...");
Map<String, String> validationMap=new HashMap<String, String>();
Map<String, String> resultsMap;
String action=req.getParameter("action");
String healthRec =req.getParameter("healthrec");
validationMap.put("healthrec", healthRec);
String age =req.getParameter("age");
validationMap.put("age", age);
//Validating fields
resultsMap=validateFields(validationMap);
req.setAttribute("validateResults", resultsMap);
if(resultsMap.size()<1){
log.info("Fields validation success...");
//Creating Patient POJO
Patient patient=new Patient();
patient.setHealthRecNo(Integer.parseInt(healthRec));
patient.setAge(Integer.parseInt(age));
patient.setFirstName(req.getParameter("fname"));
patient.setLastName(req.getParameter("lname"));
patient.setGender(req.getParameter("gender"));
PatientService patientService=new PatientServiceImpl();
try {
patientService.savePatient(patient,action);
req.setAttribute("result", "Saved Successfully...");
log.info("Patient saved successfully...");
} catch (Exception e) {
req.setAttribute("result", "Error :"+e.toString());
log.error(e.toString());
}
}else{
log.error("Fields validation failed...");
}
// Dispatch request object to AddPatient.jsp
RequestDispatcher view=req.getRequestDispatcher("AddPatient.jsp");
view.forward(req, res);
} | 2 |
public Macro(File macro, RecordModel model) {
BufferedReader br = null;
this.model = model;
try {
br = new BufferedReader(new FileReader(macro));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
script = sb.toString();
br.close();
try {
jsbot = new JsBot(new SmartRobot());
} catch (AWTException ex) {
Console.Log("Couldn't created the robot.");
}
js = new ScriptEngineManager().getEngineByName("JavaScript");
} catch (FileNotFoundException ex) {
Console.Log("Couldn't find the .js file.");
} catch (IOException ex) {
Console.Log("Oops! IOException in Macro constructor.");
}finally {
try {
br.close();
} catch (IOException | NullPointerException ex) {
Console.Log("Failed to close the .js file stream.");
}
}
} | 5 |
public final void testBoundaryPlacement() {
int gridSize = q8cb.getSize();
// Bottom left hand corner.
q8cb.clearTheBoard();
assertTrue(q8cb.placePiece(0, 0));
assertTrue(q8cb.getBoard()[0][0] == PositionStatus.OCCUPIED);
for (int j = 1; j < gridSize; j++) {
assertTrue(q8cb.getBoard()[0][j] == PositionStatus.UNSAFE);
}
for (int i = 1; i < gridSize; i++) {
assertTrue(q8cb.getBoard()[i][0] == PositionStatus.UNSAFE);
}
for (int i = 1, j = 1; (i < gridSize) && (j < gridSize); i++, j++) {
assertTrue(q8cb.getBoard()[i][j] == PositionStatus.UNSAFE);
}
// Top Right Hand Corner
q8cb.clearTheBoard();
assertTrue(q8cb.placePiece(gridSize - 1, gridSize - 1));
assertTrue(q8cb.getBoard()[gridSize - 1][gridSize - 1] == PositionStatus.OCCUPIED);
for (int j = gridSize - 2; j > 0; j--) {
assertTrue(q8cb.getBoard()[gridSize - 1][j] == PositionStatus.UNSAFE);
}
for (int i = 0; i < gridSize - 2; i++) {
assertTrue(q8cb.getBoard()[i][gridSize - 1] == PositionStatus.UNSAFE);
}
for (int i = gridSize - 2, j = gridSize - 2; (i >= 0) && (j >= 0); i--, j--){
assertTrue(q8cb.getBoard()[i][j] == PositionStatus.UNSAFE);
}
// TODO: Check that for correct setting of unsafe markers
q8cb.clearTheBoard();
assertTrue(q8cb.placePiece(0, q8cb.getGridSize() - 1));
assertTrue(q8cb.getBoard()[0][q8cb.getGridSize() - 1] == PositionStatus.OCCUPIED);
q8cb.clearTheBoard();
assertTrue(q8cb.placePiece(q8cb.getGridSize() - 1, 0));
assertTrue(q8cb.getBoard()[q8cb.getGridSize() - 1][0] == PositionStatus.OCCUPIED);
} | 8 |
@Override
public void newAttribute(String key, Object value, boolean isReadOnly, AttributeTableModel model) {
model.keys.add(key);
model.values.add(value);
model.readOnly.add(new Boolean(isReadOnly));
Node node = doc.tree.getEditingNode();
node.setAttribute(key, value, isReadOnly);
// undo
CompoundUndoable undoable = new CompoundUndoablePropertyChange(doc.tree);
undoable.setName("New Node Attribute");
Undoable primitive = new PrimitiveUndoableAttributeChange(node, null, null, false, key, value, isReadOnly);
undoable.addPrimitive(primitive);
doc.getUndoQueue().add(undoable);
model.fireTableDataChanged();
} | 0 |
public void validateMove(Team movingTeam, int fromX, int fromY, int toX, int toY)
throws IllegalMoveException
{
// Check that inputs make sense at all
validateCoordsOnBoard(fromX, fromY);
validateDestination(toX, toY);
if (Team.NEUTRAL.equals(movingTeam)) {
throw new IllegalArgumentException("Moving team can't be neutral.");
}
// Check there is a tile to move
if (getTile(fromX, fromY) == null)
throw new IllegalMoveException("Can't move a tile that isn't there.");
// Check the moving tile is face-up
if (!getTile(fromX, fromY).isFaceUp())
throw new IllegalMoveException("Can't move a face-down tile.");
// Check the tile is moving to another square
if (fromX == toX && fromY == toY)
throw new IllegalMoveException("Tile must move at least one square.");
// Check the move is in the same rank or file (i.e. straight)
// N.B. some of the subsequent checks depend on this assumption
if (fromX != toX && fromY != toY)
throw new IllegalMoveException("Tiles can't move diagonally.");
// Check the tile has sufficient range
validateRange(fromX, fromY, toX, toY);
// Check there's no tiles in the way
validateNoInterveningTiles(fromX, fromY, toX, toY);
// Check the destination tile is valid prey
validatePrey(fromX, fromY, toX, toY);
// Check the tile doesn't belong to the other player
validateNotOtherTeamsTile(movingTeam, fromX, fromY);
// Check the tile isn't a neutral tile that was just flipped
validateNotJustFlippedNeutralTile(fromX, fromY);
// Check the player isn't reversing a previous move of their own tile
validateNotReversingPreviousOwnTile(movingTeam, fromX, fromY, toX, toY);
// Check the player isn't trying to rescue a neutral tile
validateNotRescuingNeutralTile(fromX, fromY, toX, toY);
} | 7 |
public AutomatonSizeSlider(AutomatonPane view, AutomatonDrawer drawer) {
super(AUTOMATON_SIZE_MIN, AUTOMATON_SIZE_MAX, AUTOMATON_SIZE_INIT);
this.view = view;
this.drawer = drawer;
this.addChangeListener(new SliderListener());
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), AUTOMATON_SIZE_TITLE));
} | 0 |
public String getCode() {
return code;
} | 0 |
protected Function(Dictionary d) {
Vector dom = (Vector) d.getObject("Domain");
domain = new float[dom.size()];
for (int i = 0; i < dom.size(); i++) {
domain[i] = ((Number) dom.elementAt(i)).floatValue();
}
Vector r = (Vector) d.getObject("Range");
if (r != null) {
range = new float[r.size()];
for (int i = 0; i < r.size(); i++) {
range[i] = ((Number) r.elementAt(i)).floatValue();
}
}
} | 3 |
@Override
public int read(char[] cbuf, int off, int len) throws IOException
{
if (len == 0)
{
return 0;
}
int c = read();
if (c == -1)
{
return -1;
}
int result = 0;
do
{
cbuf[result + off] = (char) c;
result++;
c = read();
}
while (c != -1 && result < len);
return result;
} | 4 |
public void printIdentificationNumberStr(String enteredIdentificationNumber, boolean lineSeparator) {
if (lineSeparator) {
System.out.printf("Identification number: %s\n", enteredIdentificationNumber);
} else {
System.out.printf("Identification number: %s", enteredIdentificationNumber);
}
} | 1 |
private void process() {
if (intervals.size() < 2) {
throw new IndexOutOfBoundsException("Processing requires at least two intervals");
}
// addressing to the first non-fictitious interval
double y_min = intervals.get(1).getY();
MatterInterval inl;
for (int i = 1; i < intervals.size(); i++) {
inl = intervals.get(i);
if (inl.getY() < y_min) {
y_min = inl.getY();
}
}
y_shift = y_min;
for (int i = 1; i < intervals.size(); i++) {
inl = intervals.get(i);
inl.setY(inl.getY() - y_shift);
}
getFictitiousInterval().setY(0);
// System.out.println("After process:\n" + this);
} | 4 |
public Set<T> concat(Set<T> s)
{ Set<T> res=this;
if(s==null)
{ return res;
}
else
{ if(s.next==null)
{ return res.append(s.a);}
else//s.next!=null
{ return res.append(s.a).concat(s.next);}
}
} | 2 |
@Override
public boolean onCommand(CommandSender commandSender, Command cmd, String lbl, String[] args) {
if(commandSender instanceof Player) {
Player pl = (Player) commandSender;
if(cmd.getName().equalsIgnoreCase("challenge")) {
if(args[0].equalsIgnoreCase("ironarmor")) {
Bukkit.getPluginManager().registerEvents(new IronArmorGoal(pl), this);
}
else if(args[0].equalsIgnoreCase("stonetools")) {
Bukkit.getPluginManager().registerEvents(new StoneToolsGoal(pl), this);
}
return true;
}
}
return false;
} | 4 |
private void removeHost(Host host) {
HostPanel hp = hostsMap.remove(host.getName());
if (hp != null) {
ClientConnectionManager.getInstance().removeClientChangedListener(
hp);
if ((hostList.size() > 1)
&& (hostList.indexOf(hp) == (hostList.size() - 1))) {
GridBagConstraints newLastConstraints = hostListLayout
.getConstraints(hostList.get(hostList.size() - 2));
newLastConstraints.weighty = 1;
hostListLayout.setConstraints(
hostList.get(hostList.size() - 2), newLastConstraints);
}
remove(hp);
revalidate();
repaint();
}
} | 3 |
public static double regularisedBetaFunction(double z, double w, double x) {
if (x < 0.0D || x > 1.0D) throw new IllegalArgumentException("Argument x, " + x + ", must be lie between 0 and 1 (inclusive)");
double ibeta = 0.0D;
if (x == 0.0D) {
ibeta = 0.0D;
} else {
if (x == 1.0D) {
ibeta = 1.0D;
} else {
// Term before continued fraction
ibeta = Math.exp(Stat.logGamma(z + w) - Stat.logGamma(z) - logGamma(w) + z * Math.log(x) + w * Math.log(1.0D - x));
// Continued fraction
if (x < (z + 1.0D) / (z + w + 2.0D)) {
ibeta = ibeta * Stat.contFract(z, w, x) / z;
} else {
// Use symmetry relationship
ibeta = 1.0D - ibeta * Stat.contFract(w, z, 1.0D - x) / w;
}
}
}
return ibeta;
} | 5 |
public void deleteProperty(String section, String var) {
if (map.containsKey(section + '.' + var)) map.remove(section + '.' + var);
} | 1 |
public String toString() {
if (Double.isNaN(im) || Double.isInfinite(im)) {
return re + " + " + "i" + im;
}
if (im == 0) {
return re + "";
}
if (re == 0) {
return im + "i";
}
if (im < 0) {
return re + " - " + (-im) + "i";
}
return re + " + " + im + "i";
} | 5 |
private static void dumpImageToSheet(SegmentedImage image, Workbook wb){
Sheet s = wb.createSheet();
generateHeader(s);
for(int rownum = 1; rownum <= image.numCells(); rownum++){
fillData(s, rownum, image.getCell(rownum-1));
}
} | 1 |
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null)
return false;
ListNode oneStep = head;
ListNode twoStep = head.next;
while (twoStep != null) {
if (oneStep == twoStep)
return true;
twoStep = twoStep.next;
if (twoStep == null)
break;
oneStep = oneStep.next;
twoStep = twoStep.next;
}
return false;
} | 5 |
@Test
public void testBasicMethodSmall() {
final float[] weights = initWeights(18);
ChiVertex<Integer, Float> vert = new ChiVertex<Integer, Float>(0, new VertexDegree(0, weights.length)) {
public Float getOutEdgeValue(int i) {
return weights[i];
}
@Override
public int getOutEdgeId(int i) {
return i;
}
@Override
public int numOutEdges() {
return weights.length;
}
};
int n = 10000000;
int[] hops = WeightedHopper.generateRandomHopsOut(new Random(260379), vert, n);
assertEquals(hops.length, n);
/* Now check the distribution makes sense */
int[] counts = new int[weights.length];
for(int i=0; i < hops.length; i++) {
assertTrue(hops[i] >= 0 && hops[i] < weights.length);
counts[hops[i]]++;
}
float totalWeight = 0.0f;
for(int j=0; j < weights.length; j++) totalWeight += weights[j];
for(int j=0; j < weights.length; j++) {
int expected = (int) (n * weights[j] / totalWeight);
assertTrue(Math.abs(expected - counts[j]) < n / weights.length); // dubious
}
} | 4 |
public void handleCollisions(CollisionHandler... handlers)
{
for (int i = 0; i < size(); i++)
{
for (int j = 0; j < size(); j++)
{
if (i != j)
{
Sprite s1 = get(i);
Sprite s2 = get(j);
if (s1.intersects(s2))
{
Collision c = new Collision(s1, s2);
Loader.addEventToAll(new SpriteCollisionEvent(c));
for (CollisionHandler handler : handlers)
{
handler.collided(c);
}
s1.collidedWith(s2);
}
}
}
}
} | 5 |
public void initialize() {
if(Configuration.hasParameter("DistributionModel/Line/FromX") &&
Configuration.hasParameter("DistributionModel/Line/FromY") &&
Configuration.hasParameter("DistributionModel/Line/ToX") &&
Configuration.hasParameter("DistributionModel/Line/ToY")) {
try {
previousPositionX = Configuration.getDoubleParameter("DistributionModel/Line/FromX");
previousPositionY = Configuration.getDoubleParameter("DistributionModel/Line/FromY");
dx = Configuration.getDoubleParameter("DistributionModel/Line/ToX") - previousPositionX;
dy = Configuration.getDoubleParameter("DistributionModel/Line/ToY") - previousPositionY;
} catch(CorruptConfigurationEntryException e) {
sinalgo.runtime.Main.fatalError(e);
}
if(numberOfNodes <= 1) { // place the single node in the middle
dx /= 2;
dy /= 2;
} else {
dx /= (numberOfNodes -1);
dy /= (numberOfNodes -1);
previousPositionX -= dx;
previousPositionY -= dy;
}
} else { // default horizontal line
dy = 0;
dx = ((double) Configuration.dimX) / (this.numberOfNodes + 1);
previousPositionX = 0;
previousPositionY = Configuration.dimY / 2;
}
} | 6 |
public DialogWindowView(String title) {
dialog = new JDialog((JFrame) null, title);
dialog.setResizable(false);
dialog.setSize(200, 100);
dialog.setLocation(MainWindowView.WIDTH/2, MainWindowView.HEIGHT/2 - dialog.getHeight()/2);
init();
addActionListeners();
} | 0 |
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
BigDecimal percentage = null;
List<String> fouten = new ArrayList<>();
try {
percentage = new BigDecimal(request.getParameter("percentage"));
if (percentage.compareTo(BigDecimal.ZERO) <= 0) {
fouten.add("Percentage moet een positief getal zijn");
}
} catch (NumberFormatException ex) {
fouten.add("Percentage moet een getal zijn");
}
long docentNr = Long.parseLong(request.getParameter("docentNr"));
if (fouten.isEmpty()) {
try {
docentService.opslag(docentNr, percentage);
} catch (DocentNietGevondenException ex) {
fouten.add("Docent niet gevonden");
} catch (RecordAangepastException ex) {
fouten.add("Een andere gebruiker heeft deze docent gewijzigd");
}
}
if (fouten.isEmpty()) {
response.sendRedirect(response.encodeRedirectURL(request
.getContextPath()));
} else {
request.setAttribute("fouten", fouten);
request.getRequestDispatcher(VIEW).forward(request, response);
}
} | 6 |
public String catchInfo(String url) {
this.url = url;
String html = null;
try {
getMethod = new GetMethod(url);
int statusCode = httpclient.executeMethod(getMethod);
System.out.println("StatusCode:" + statusCode + ">>>>URL:"
+ url);
if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
|| (statusCode == HttpStatus.SC_SEE_OTHER)
|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
System.out.println("**************URL Redirect**************");
html = this.isRedirect();
}
if (statusCode == HttpStatus.SC_OK) {
html = this.isOK();
}
} catch (Exception e) {
e.printStackTrace();
}
return html;
} | 6 |
protected List<Actor> actors() {
if (!(model instanceof Factional)) {
return new ArrayList<Actor>(model.actors);
}
// If we're interacting with a Factional model,
// only neutral actors and actors from the current
// team should have a chance to act:
List<Actor> ret = new ArrayList<Actor>();
int currentTeam = ((Factional)model).team();
for(Actor a : model.actors) {
if (a instanceof Factional) {
if (((Factional)a).team() != currentTeam) { continue; }
}
ret.add(a);
}
return ret;
} | 4 |
@Override
public Object getPreviousValue() {
int n = getNumber().intValue();
if (n == 1) {
return n;
}
return n-1;
} | 1 |
public Class<?> getColumnClass(int col) {
return getValueAt(0, col).getClass();
} | 1 |
protected GeneralPath renderSimpleGlyph (GlyfSimple g) {
// the current contour
int curContour = 0;
// the render state
RenderState rs = new RenderState ();
rs.gp = new GeneralPath ();
for (int i = 0; i < g.getNumPoints (); i++) {
PointRec rec = new PointRec (g, i);
if (rec.onCurve) {
addOnCurvePoint (rec, rs);
} else {
addOffCurvePoint (rec, rs);
}
// see if we just ended a contour
if (i == g.getContourEndPoint (curContour)) {
curContour++;
if (rs.firstOff != null) {
addOffCurvePoint (rs.firstOff, rs);
}
if (rs.firstOn != null) {
addOnCurvePoint (rs.firstOn, rs);
}
rs.firstOn = null;
rs.firstOff = null;
rs.prevOff = null;
}
}
return rs.gp;
} | 5 |
public void push(IntegerNode newNode) {
if (this.top == null){
this.top = newNode;
} else {
IntegerNode nextInLine = this.top;
this.top = newNode;
this.top.setNextTop(nextInLine);
}
count++;
} | 1 |
public void paint(Graphics g) {
double dx = this.getWidth() / (double) a.getWorld().getWidth();
double dy = this.getHeight() / (double) a.getWorld().getHeight();
dx = Math.min(dx, dy);
dy = Math.min(dx, dy);
for (int x = 0; x < a.getWorld().getWidth(); x++) {
for (int y = 0; y < a.getWorld().getHeight(); y++) {
switch (a.getState(x, y)) {
case unknown:
g.setColor(Color.LIGHT_GRAY);
break;
case empty:
g.setColor(Color.WHITE);
break;
case solid:
g.setColor(Color.BLACK);
break;
}
if (a.isGoal(x, y)) {
g.setColor(Color.GREEN);
}
if (a.isMyPosition(x, y)) {
g.setColor(Color.RED);
}
g.fillRect((int) (x * dx), (int) (y * dy), (int) dx, (int) dy);
g.setColor(Color.black);
g.drawRect((int) (x * dx), (int) (y * dy), (int) dx, (int) dy);
}
}
} | 7 |
private JPanel placeTextFields(){
final int ROWS = 2;
final int COLUMNS = 2;
GridLayout layout = new GridLayout(ROWS, COLUMNS);
layout.setHgap(10);
layout.setVgap(10);
JPanel panel = new JPanel(layout);
oldValue = new JTextField("Old value");
oldValue.setEditable(false);
oldTranslation = new JTextField("Old translation");
oldTranslation.setEditable(false);
newValue = new JTextField();
newTranslation = new JTextField();
panel.add(oldValue);
panel.add(oldTranslation);
panel.add(newValue);
panel.add(newTranslation);
return panel;
} | 0 |
@Override
public void run() {
final GameObject obelisk = ctx.objects.select().id(OBELISK).nearest().poll();
if (obelisk.valid() && IMovement.Euclidean(obelisk, ctx.players.local()) < 5) {
renewPoints();
} else {
if (!locationAttribute.isInObeliskArea(ctx)) {
if (doSmall()) {
ctx.sleep(666);
}
}
}
ctx.sleep(300);
} | 4 |
public boolean buttonDown(Controller controller, int code) {
switch(code){
case XBox360Pad.BUTTON_A: MyInput.setKey(Input.JUMP, true); break;
case XBox360Pad.BUTTON_X:
if(!menu)
MyInput.setKey(Input.INTERACT, true);
break;
case XBox360Pad.BUTTON_RB: MyInput.setKey(Input.ATTACK, true); break;
case XBox360Pad.BUTTON_Y: MyInput.setKey(Input.USE, true); break;
case XBox360Pad.BUTTON_BACK: MyInput.setKey(Input.RESPAWN, true); break;
case XBox360Pad.BUTTON_START: MyInput.setKey(Input.PAUSE, true); break;
case XBox360Pad.BUTTON_LB:
if(menu)
MyInput.setKey(Input.INTERACT, true);
else
MyInput.setKey(Input.DOWN, true);
break;
}
return false;
} | 9 |
public void setPreNote(String preNote) {
this.preNote = preNote;
} | 0 |
public boolean available(int num)
{
boolean availablity = false;
try
{
if(!seat[num])//= if seat is false, then condition will be true
availablity = true;
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Error:" + ex);
availablity = false;
}
return availablity;
} | 2 |
@EventHandler
public void GhastJump(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Ghast.Jump.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof Fireball) {
Fireball a = (Fireball) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getGhastConfig().getBoolean("Ghast.Jump.Enabled", true) && shooter instanceof Ghast && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, plugin.getGhastConfig().getInt("Ghast.Jump.Time"), plugin.getGhastConfig().getInt("Ghast.Jump.Power")));
}
}
} | 7 |
@Override
public String process(HttpServletRequest request)
throws MissingRequiredParameter {
ResultSet resultSet = null;
String ciudad = request.getParameter("ciudad");
JSONArray result = new JSONArray();
//String result;
try {
// Get Connection and Statement
connection = dataSource.getConnection();
statement = connection.createStatement();
String query = "SELECT * FROM farmacias WHERE ciudad = '"+ciudad+"'";
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Farmacia farm = new Farmacia();
farm.setId(resultSet.getInt("id_farmacia"));
if (resultSet.getString("nombre") != null)
farm.setName(resultSet.getString("nombre"));
farm.setciudad(resultSet.getString("ciudad"));
farm.setdireccion(resultSet.getString("direccion"));
farm.sethorario(resultSet.getString("horario"));
// farm.setlongitud(resultSet.getString("longitud"));
// farm.setlatitud(resultSet.getString("latitud"));
result.add(farm);
}
} catch (SQLException e) {
return "{\"status\":\"KO\", \"result\": \"Error en el acceso a la base de datos.\"}";
} finally {
try {
if (null != resultSet)
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != statement)
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != connection)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return "{\"status\":\"OK\", \"result\":" +result.toString() + "}";
} | 9 |
private String readline(InputStream is) {
StringBuilder rtn = new StringBuilder();
int temp;
do {
try {
temp = is.read();
} catch (Exception e) {
return null;
}
if (temp == -1) {
String str = rtn.toString();
if (str.length() == 0) {
return null;
}
return str;
}
if (temp != 0 && temp != '\n' && temp != '\r') {
rtn.append((char) temp);
}
} while (temp != '\n' && temp != '\r');
return rtn.toString();
} | 8 |
public double getValue() {
return value;
} | 0 |
public void closeConnection(){
if (stmt!=null) { try { stmt.close(); } catch (Exception ignore) {} }
if (conn!=null) { try { conn.close(); } catch (Exception ignore) {} }
} | 4 |
@Test
public void testSearchAndUpdateCollection() {
gcPrintUsed();
int repeats = 1000; // five seconds.
HugeArrayBuilder<MutableTypes> mtb = new HugeArrayBuilder<MutableTypes>() {
};
HugeArrayList<MutableTypes> mts = mtb.create();
mts.setSize(length);
for (MutableTypes mt : mts) {
mt.setBoolean2(true);
mt.setByte2((byte) 1);
}
gcPrintUsed();
long start = System.nanoTime();
for (int i = 0; i < repeats; i++) {
for (MutableTypes mt : mts) {
mt.setInt(mt.getInt() + 1);
}
}
long time = System.nanoTime() - start;
printUsed();
System.out.printf("Huge Collection update one field, took an average %.1f ns.%n", (double) time / length / repeats);
} | 3 |
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.