text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void allocatePoints(Contestant c) {
Iterator<User> itr = allUsers.iterator();
User u;
while (itr.hasNext()) {
u = itr.next();
if (u.getWeeklyPick().equals(c)) {
if (this.isFinalWeek()) // final week
u.addPoints(40);
else // normal week
u.addPoints(20);
}
// if the end of the game and the person gets the right ultimate pick
if (u.getUltimatePick().equals(c) && this.isFinalWeek()){
u.addPoints(u.getUltimatePoints());
}
u.addPoints(u.getNumBonusAnswer() * 10); // add week's correct bonus questions
u.setNumBonusAnswer(0); // clears the number of questions
}
notifyAdd(UpdateTag.ALLOCATE_POINTS);
} | 5 |
public UpdateQuery in(String... args) {
if (args.length == 1) {
for (String arg : args) {
if (arg.startsWith("(")) { // nested select
query.append(" IN ").append(arg);
} else { // just single value, same as below
query.append(" IN (").append("\'").append(arg).append("\'").append(")");
}
}
return this;
} else {
query.append(" IN (");
for (String arg : args) {
query.append("\'").append(arg).append("\'").append(", ");
}
query.delete(query.lastIndexOf(", "), query.length()).append(")");
return this;
}
} | 4 |
public ArrayList<Node> generateBridgedER(int n1,int n2, double p1, double p2, int b){
ArrayList<Node> c1 = generateConnectedER(n1,p1);
ArrayList<Node> c2 = generateConnectedER(n2,p2);
for(int i= 0;i<n2;i++)
{
c2.get(i).resetID(i+n1);
}
ArrayList<Node> nodes = new ArrayList<Node>();
for(int i=0;i<n1;i++)
{
nodes.add(c1.remove(0));
}
for(int i=0;i<n2;i++)
{
nodes.add(c2.remove(0));
}
Random gen = new Random();
Link link;
Set<Integer> usedNodes = new HashSet<Integer>();
int s,d;
while(usedNodes.size() < 2*b)
{
s = gen.nextInt(n1);
while(usedNodes.contains(s))
{
s = gen.nextInt(n1);
}
usedNodes.add(s);
d = n1 + gen.nextInt(n2);
while(usedNodes.contains(d))
{
d = n1 + gen.nextInt(n2);
}
usedNodes.add(d);
link = new Link(nodes.get(s));
nodes.get(d).addLink(link);
link = new Link(nodes.get(d));
nodes.get(s).addLink(link);
}
return nodes;
} | 6 |
protected void calculateCutPointsByEqualWidthBinning(int index) {
// Scan for max and min values
double max = 0, min = 1, currentVal;
Instance currentInstance;
for(int i = 0; i < getInputFormat().numInstances(); i++) {
currentInstance = getInputFormat().instance(i);
if (!currentInstance.isMissing(index)) {
currentVal = currentInstance.value(index);
if (max < min) {
max = min = currentVal;
}
if (currentVal > max) {
max = currentVal;
}
if (currentVal < min) {
min = currentVal;
}
}
}
double binWidth = (max - min) / m_NumBins;
double [] cutPoints = null;
if ((m_NumBins > 1) && (binWidth > 0)) {
cutPoints = new double [m_NumBins - 1];
for(int i = 1; i < m_NumBins; i++) {
cutPoints[i - 1] = min + binWidth * i;
}
}
m_CutPoints[index] = cutPoints;
} | 8 |
public static void main(String[] args) throws IOException {
String name = null,str = null;
int size = BUFSIZE,bufferSize = BUFSIZE;
for(int i = 0;i < args.length;i++){
switch(args[i]){
case "-s":
size = Integer.valueOf(args[++i]).intValue();
break;
case "-b":
bufferSize = Integer.valueOf(args[++i]).intValue();
break;
case "-n":
name = args[++i];
break;
case "-c":
str = args[++i];
break;
default:
System.out.println("unknown"+args[i]);
return;
}
}
if (str == null){
System.out.println("no output strings");
return;
}
String path = "/Users/e125716/test/"+name;
File file = new File(path);
file.createNewFile();
FileOutputStream outFile = new FileOutputStream(file);
BufferedOutputStream buf = new BufferedOutputStream(outFile);
for (int i = size; i > 0;i -= bufferSize){
int wirteSize = bufferSize > i ? i :bufferSize;
buf.write(str.getBytes(),0,wirteSize);
}
buf.flush();
outFile.close();
System.out.println(size);
System.out.println(bufferSize);
} | 8 |
public void addChromosome(Chromosome chrom) throws Exception {
if (chrom==null) {
throw new Exception("Error in addChromosome: chrom==null");
}
if ((ploidy==2 && chrom.getClass().equals(TetraploidChromosome.class)) ||
(ploidy>2 && !chrom.getClass().equals(TetraploidChromosome.class))) {
throw new Exception("Error in addChromosome: class of chrom does not match ploidy");
}
if (!this.equals(chrom.getPopdata())) {
throw new Exception("Error in addChromosome: popdata invalid");
}
chromosome.add(chrom);
//note that the same chromosome may be added multiple times, but
//each instance will be non-homologous to the others
} | 6 |
static public Var isMacro(Object op) throws Exception{
//no local macros for now
if(op instanceof Symbol && referenceLocal((Symbol) op) != null)
return null;
if(op instanceof Symbol || op instanceof Var)
{
Var v = (op instanceof Var) ? (Var) op : lookupVar((Symbol) op, false);
if(v != null && v.isMacro())
{
if(v.ns != currentNS() && !v.isPublic())
throw new IllegalStateException("var: " + v + " is not public");
return v;
}
}
return null;
} | 9 |
public void enter(String sqlstatement, int type){
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:" + DBName;
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
switch (type) {
case QUERY:
ResultSet rs = statement.executeQuery(sqlstatement);
new ServerResultFrame(rs);
break;
case UPDATE:
statement.executeUpdate(sqlstatement);
new ServerResultFrame("Query Executed");
break;
default:
break;
}
statement.close();
connection.close();
}
catch(Exception e){
new ServerResultFrame(e.getMessage());
}
} | 3 |
@Override
public void removeProperty(String key) {
this.default_values.remove(key);
this.current_values.remove(key);
this.filter_chains.remove(key);
} | 0 |
private static int isKingKong(ArrayList<Card> list) {
assert(list.size() == EFFECTIVE_CARD_NUM);
int change = 0;
int changePos = 0;
for ( int i = 1; i < 5; i++ ){
if (list.get(i).getPoint() != list.get(i - 1).getPoint()){
change++;
changePos = i;
if ( change > 1 || (changePos != 1 && changePos != 4) ){
return -1;
}
}
}
return list.get(changePos - 1).getPoint();
} | 5 |
public static ComplexNumber parseComplex(String s)
{
s = s.replaceAll(" ","");
ComplexNumber parsed = null;
if(s.contains(String.valueOf("+")) || (s.contains(String.valueOf("-")) && s.lastIndexOf('-') > 0))
{
String re = "";
String im = "";
s = s.replaceAll("i","");
s = s.replaceAll("I","");
if(s.indexOf('+') > 0)
{
re = s.substring(0,s.indexOf('+'));
im = s.substring(s.indexOf('+')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),Double.parseDouble(im));
}
else if(s.lastIndexOf('-') > 0)
{
re = s.substring(0,s.lastIndexOf('-'));
im = s.substring(s.lastIndexOf('-')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),-Double.parseDouble(im));
}
}
else
{
// Pure imaginary number
if(s.endsWith("i") || s.endsWith("I"))
{
s = s.replaceAll("i","");
s = s.replaceAll("I","");
parsed = new ComplexNumber(0, Double.parseDouble(s));
}
// Pure real number
else
{
parsed = new ComplexNumber(Double.parseDouble(s),0);
}
}
return parsed;
} | 7 |
private void removeFullLines(){
int numFullLines = 0;
for (int i = BoardHeight - 1; i >= 0; --i) {
boolean lineIsFull = true;
for (int j = 0; j < BoardWidth; ++j) {
if (shapeAt(j, i) == Tetrominoes.NoShape) {
lineIsFull = false;
break;
}
}
if (lineIsFull) {
++numFullLines;
for (int k = i; k < BoardHeight - 1; ++k) {
for (int j = 0; j < BoardWidth; ++j)
board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
}
}
}
if (numFullLines > 0) {
numLinesRemoved += numFullLines;
timer.setDelay(400-(2*numLinesRemoved));
statusbar.setText("Score: " + String.valueOf(numLinesRemoved));
isFallingFinished = true;
curPiece.setShape(Tetrominoes.NoShape);
repaint();
}
} | 7 |
@Override
public void run() {
while (!SH.get(tcn).isInterrupted()){
try {
String rtn=Tclient(tcn);
if (rtn.equals("reload")){
TNH.get(tcn).loggedin=0;
SH.get(tcn).interrupt();
TNH.get(tcn).killme();
}
} catch (SocketException e) {
dw.append("Server "+tcn+" offline.");
TNH.get(tcn).loggedin=0;
SH.get(tcn).interrupt();
}catch (IOException | InterruptedException e) {e.printStackTrace();System.out.println("thats me");}
}
SH.remove(tcn);
} | 4 |
public Instance cleanse(Instance before) throws Exception{
Instances insts = before.relationalValue(1).stringFreeStructure();
Instance after = new DenseInstance(before.numAttributes());
after.setDataset(m_Attributes);
for(int g=0; g < before.relationalValue(1).numInstances(); g++){
Instance datum = before.relationalValue(1).instance(g);
double[] minNoiDists = new double[m_Choose];
double[] minValDists = new double[m_Choose];
int noiseCount = 0, validCount = 0;
double[] nDist = new double[m_Mean.length];
double[] vDist = new double[m_Mean.length];
for(int h=0; h < m_Mean.length; h++){
if(m_ValidM[h] == null)
vDist[h] = Double.POSITIVE_INFINITY;
else
vDist[h] = distance(datum, m_ValidM[h], m_ValidV[h], h);
if(m_NoiseM[h] == null)
nDist[h] = Double.POSITIVE_INFINITY;
else
nDist[h] = distance(datum, m_NoiseM[h], m_NoiseV[h], h);
}
for(int k=0; k < m_Choose; k++){
int pos = Utils.minIndex(vDist);
minValDists[k] = vDist[pos];
vDist[pos] = Double.POSITIVE_INFINITY;
pos = Utils.minIndex(nDist);
minNoiDists[k] = nDist[pos];
nDist[pos] = Double.POSITIVE_INFINITY;
}
int x = 0,y = 0;
while((x+y) < m_Choose){
if(minValDists[x] <= minNoiDists[y]){
validCount++;
x++;
}
else{
noiseCount++;
y++;
}
}
if(x >= y)
insts.add (datum);
}
after.setValue(0, before.value( 0));
after.setValue(1, after.attribute(1).addRelation(insts));
after.setValue(2, before.value( 2));
return after;
} | 8 |
public TextBox(String text, boolean fill) {
parseText(text);
if(fill) {
addTimeListener(new TimeListener() {
public void timeStep(TimeEvent e) {
textFill += e.getDelta() * fillSpeed;
if(textFill >= TextBox.this.getLength()) {
TextBox.this.removeTimeListener(this);
}
}
});
} else {
textFill = getLength();
}
setBounds(0, 0, getWidth(), getHeight());
addKeybindListener(new DefaultKeybindAdapter());
} | 2 |
@EventHandler
public void onPlayerSpin(final PlayerInteractEvent event) {
final Block block = event.getClickedBlock();
if(block == null)
return;
if(FancyRoulette.instance.tableManager.isBlockSpinner(block)) {
if(! event.getPlayer().hasPermission("roulette.spin")) {
event.getPlayer().sendMessage(ChatColor.DARK_RED + "Error! " + ChatColor.WHITE + "You don't have enough permissions to spin the roulette!");
} if(spinning.contains(block)) {
event.getPlayer().sendMessage("This spinner is already spinning! Wait for it to finish first.");
return;
} event.getPlayer().sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + "The roulette is spinning!");
final Random rand = new Random();
spinning.add(block);
for(int i = 0; i < 30; ++i) {
Bukkit.getScheduler().scheduleSyncDelayedTask(FancyRoulette.instance, new Runnable() {
public void run() {
Wool woolColor = new Wool(block.getType(), block.getData());
int color = rand.nextInt(16);
woolColor.setColor(DyeColor.values()[color]);
event.getClickedBlock().setType(Material.WOOL);
event.getClickedBlock().setData(woolColor.getData());
}
}, (long)(5 * i));
}
Bukkit.getScheduler().scheduleSyncDelayedTask(FancyRoulette.instance, new Runnable() {
public void run() {
Wool winningColor = new Wool(block.getType(), block.getData());
onSpinEnd(winningColor, block);
spinning.remove(block);
}
}, (long)(160));
}
} | 5 |
private void updateLabels(int dummy)
{
labelGold.setText(sliderGold.value()+"/"+player.getResource(core.ResourceType.GOLD));
labelWood.setText(sliderWood.value()+"/"+player.getResource(core.ResourceType.WOOD));
labelOre.setText(sliderOre.value()+"/"+player.getResource(core.ResourceType.ORE));
try {
amount = (
convert((core.ResourceType)(toWhat.itemData(toWhat.currentIndex())), core.ResourceType.GOLD, sliderGold.value()) +
convert((core.ResourceType)(toWhat.itemData(toWhat.currentIndex())), core.ResourceType.WOOD, sliderWood.value()) +
convert((core.ResourceType)(toWhat.itemData(toWhat.currentIndex())), core.ResourceType.ORE, sliderOre.value())
);
howMany.setText(""+amount);
} catch (java.lang.NullPointerException e) {}
} | 1 |
public Object result() {
if (Protocol.Type.STRING == type) {
return StringUtils.toString(current, charset);
} else if (Protocol.Type.ERROR == type) {
return new RedisException(StringUtils.toString(current, charset));
} else if (Protocol.Type.INTEGER == type) {
return NumberUtils.toInt(StringUtils.toString(current, charset));
} else if (Protocol.Type.BULK_STRING == type) {
return current == null ? null : StringUtils.toString(current, charset);
} else if (Protocol.Type.ARRAY == type) {
return array;
} else {
throw new RuntimeException("parser not ready, parse error or parse not called!");
}
} | 6 |
public Item peek() {
if (isEmpty()) throw new NoSuchElementException("Queue underflow");
return first.item;
} | 1 |
public MooreStateTool(AutomatonPane view, AutomatonDrawer drawer)
{
super(view, drawer);
} | 0 |
public void setRollValue(int rollValue) {
if(rollValue > 1 && rollValue < 13) {
this.rollValue = rollValue;
}
else {
//throw exception
}
} | 2 |
private void printToFile(List<Citation> citations) {
File newFile;
while (true) {
String filename = io.getString("Name the new BibTex file (.bib is added automatically): ");
newFile = new File(filename + ".bib");
if (newFile.exists()) {
io.println("A file named " + filename + ".bib already exists!");
} else {
try {
creation = new GenerateBibtex(citations, new FileOutputStream(newFile));
creation.start();
io.println("File created succesfully!");
break;
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
} | 3 |
@Test
public void testFunctionality() {
GameConfiguration origConf = new GameConfiguration();
origConf.setAgentCount(1);
origConf.setFoodAmountIncrese(2);
origConf.setHiddenLayers(3);
origConf.setInitialFoodAmount(4);
origConf.setMutate(true);
origConf.setMutationAmount(5);
origConf.setMutationProb(0.312);
origConf.setNodesPerHiddenLayer(6);
origConf.setRecombine(false);
origConf.setWinnerCount(7);
origConf.setWorldSize(1024);
try
{
File f;
f = tempf.newFile("test.tmp");
JAXBConfigLoader loader = new JAXBConfigLoader(f);
loader.save(origConf);
GameConfiguration loadedConf = loader.load();
for (Method method : GameConfiguration.class.getMethods())
{
if (isGetter(method))
{
Object orig=method.invoke(origConf);
Object loaded=method.invoke(loadedConf);
if (!orig.equals(loaded)) fail("Values returned by "+method.getName()+" not match");
//assertEquals("Fields not match", method.invoke(origConf), method.invoke(loadedConf));
}
}
} catch (IOException e1) {
Assert.fail("Error while creating temporary file");
} catch (IllegalAccessException e) {
Assert.fail("Error while iterating through getters");
} catch (IllegalArgumentException e) {
Assert.fail("Error while iterating through getters");
} catch (InvocationTargetException e) {
Assert.fail("Error while iterating through getters");
}
} | 7 |
@Override
public void method2() {
} | 0 |
public void getTipitPrice(final int... ids) {
try {
for(int id : ids) {
String price;
final URL url = new URL("http://www.tip.it/runescape/json/ge_single_item?item=" + id);
final URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
if (line.contains("mark_price")) {
price = line.substring(line.indexOf("mark_price") + 13, line.indexOf(",\"daily_gp") - 1);
price = price.replace(",", "");
in.close();
prices.put(id, Integer.parseInt(price));
}
}
}
} catch (final Exception ignored) {
}
} | 4 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Artist that = (Artist) o;
if (idArtist != that.idArtist) return false;
if (description != null ? !description.equals(that.description) : that.description != null)
return false;
if (pseudonym != null ? !pseudonym.equals(that.pseudonym) : that.pseudonym != null)
return false;
return true;
} | 8 |
public boolean estDisponible(){
if(this.situation == DISPONIBLE){
return true ;
}
else {
return false ;
}
} | 1 |
private String col(String s, int width) {
if(s == null)
s = "";
if(s.length() >= width)
s = s.substring(0, width - 1);
while(s.length() < width)
s = s + " ";
return s;
} | 3 |
public boolean isOver() {
boolean over = false;
if (bLastMove == null || rLastMove == null) {
over = false;
} else if (this.bLastMove.isPass() && this.rLastMove.isPass()) {
over = true;
} else {
boolean neutral = false;
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
if (status[row][col] == Status.NEUTRAL) {
neutral = true;
break;
}
}
if (neutral) {
break;
}
}
if (!neutral) {
over = true;
}
}
return over;
} | 9 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String leave = request.getParameter("user");
System.out.println("Bye " + leave);
UsersSingleton users = UsersSingleton.getInstance();
ArrayList <User> userList = new ArrayList<User>(users.getUsr());
System.out.println("Bye " + userList);
for (User usr : userList){
if (usr.getName().equals(leave)){
users.getUsr().remove(users.getUsr().indexOf(usr));
}
}
System.out.println("ByeBye " + users.getUsr());
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
oos.writeObject("morti");
} | 2 |
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int v = scn.nextInt();
int e = scn.nextInt();
while (v != 0 || e != 0) {
// Initialize no incoming set
TreeSet<Integer> noIncoming = new TreeSet<Integer>();
for (int i = 1; i <= v; i++) {
noIncoming.add(i);
}
// Read edges
HashMap<Integer, Set<Integer>> in = new HashMap<Integer, Set<Integer>>();
HashMap<Integer, Set<Integer>> out = new HashMap<Integer, Set<Integer>>();
for (int i = 0; i < e; i++) {
int from = scn.nextInt();
int to = scn.nextInt();
put(out, from, to);
put(in, to, from);
noIncoming.remove(to);
}
// Main algorithm
LinkedList<Integer> ordering = new LinkedList<Integer>();
while (!noIncoming.isEmpty()) {
int from = noIncoming.pollFirst();
ordering.add(from);
// remove edges
Set<Integer> outgoing = out.remove(from);
if (outgoing != null) {
for (int to : outgoing) {
Set<Integer> fromSet = in.get(to);
fromSet.remove(from);
if (fromSet.isEmpty()) {
noIncoming.add(to);
in.remove(to);
}
}
}
}
output(ordering);
// new iteration
v = scn.nextInt();
e = scn.nextInt();
}
} | 8 |
public Production[] getItemSet(Set items, String message) {
restricted = items;
choiceTable.setModel(new ImmutableGrammarTableModel());
alreadyChosen = new HashSet();
while (true) {
int choice = JOptionPane.showConfirmDialog(parent, panel, message,
JOptionPane.OK_CANCEL_OPTION);
if (choice == JOptionPane.CANCEL_OPTION)
return null;
// Get those selected.
List selected = new ArrayList();
GrammarTableModel model = choiceTable.getGrammarModel();
for (int i = 0; i < model.getRowCount() - 1; i++)
selected.add(model.getProduction(i));
// Check if it's our target.
if (items != null) {
Set selectedSet = new HashSet(selected);
if (!selectedSet.equals(items)) {
JOptionPane.showMessageDialog(parent,
"Some items are missing!", "Items Missing",
JOptionPane.ERROR_MESSAGE);
continue;
}
}
return (Production[]) selected.toArray(new Production[0]);
}
} | 5 |
public BeanSerializer (Kryo kryo, Class type) {
this.kryo = kryo;
BeanInfo info;
try {
info = Introspector.getBeanInfo(type);
} catch (IntrospectionException ex) {
throw new KryoException("Error getting bean info.", ex);
}
// Methods are sorted by alpha so the order of the data is known.
PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
Arrays.sort(descriptors, new Comparator<PropertyDescriptor>() {
public int compare (PropertyDescriptor o1, PropertyDescriptor o2) {
return o1.getName().compareTo(o2.getName());
}
});
ArrayList<CachedProperty> cachedProperties = new ArrayList(descriptors.length);
for (int i = 0, n = descriptors.length; i < n; i++) {
PropertyDescriptor property = descriptors[i];
String name = property.getName();
if (name.equals("class")) continue;
Method getMethod = property.getReadMethod();
Method setMethod = property.getWriteMethod();
if (getMethod == null || setMethod == null) continue; // Require both a getter and setter.
// Always use the same serializer for this property if the properties' class is final.
Serializer serializer = null;
Class returnType = getMethod.getReturnType();
if (kryo.isFinal(returnType)) serializer = kryo.getRegistration(returnType).getSerializer();
CachedProperty cachedProperty = new CachedProperty();
cachedProperty.name = name;
cachedProperty.getMethod = getMethod;
cachedProperty.setMethod = setMethod;
cachedProperty.serializer = serializer;
cachedProperty.setMethodType = setMethod.getParameterTypes()[0];
cachedProperties.add(cachedProperty);
}
properties = cachedProperties.toArray(new CachedProperty[cachedProperties.size()]);
try {
access = MethodAccess.get(type);
for (int i = 0, n = properties.length; i < n; i++) {
CachedProperty property = properties[i];
property.getterAccessIndex = ((MethodAccess)access).getIndex(property.getMethod.getName(),
property.getMethod.getParameterTypes());
property.setterAccessIndex = ((MethodAccess)access).getIndex(property.setMethod.getName(),
property.setMethod.getParameterTypes());
}
} catch (Throwable ignored) {
// ReflectASM is not available on Android.
}
} | 8 |
public Line FindClosestEdge(Vector2 v)
{
double min = v.getDistance(new Vector2((edges[0].x0 + edges[0].x1) / 2, edges[0].y0));
int id = 0;
for (int i = 1; i < 4; i++)
{
double d = v.getDistance(new Vector2((edges[i].x0 + edges[i].x1) / 2, (edges[i].y0 + edges[i].y1) / 2));
if (d < min)
{
min = d;
id = i;
}
}
return edges[id];
} | 2 |
@Override
public int backlog(double e, double s, double c) {
double L = e + s + c;
double n = s + 2*c;
double next = 0;
double previous = -1;
while(previous < next) {
double p1 = Math.pow(1 - (e/L), n);
double p2 = Math.pow((L-e-s) / (L-e), (n-s));
for(int i = 0; i < s; i++) {
double calc = (n - i) / (L-e);
p2 = p2 * calc;
}
double p3 = 0.0;
for(double k = 0; k <= c; k++) {
for(double v = 0; v <= (c-k); v++) {
double sum = Math.pow(-1, k+v)*Math.pow((c-k-v) / (c), (n-s-k));
for(int i = 0; i < k; i++) {
sum = sum * (( (c-i)/(k-i) ) * ( (n-s-i)/c )) ;
}
p3 = p3 + sum;
}
}
previous = next;
next = combinatorial(p1, L, e) * combinatorial(p2, (L-e), s) * p3;
n++;
}
return (int)(n - 2);
} | 5 |
static void EscribirCacheAsociativa(int i, int v) {
int Etiqueta = Integer.parseInt(Integer.toBinaryString(0x1000 | i).substring(1).substring(0, 9));
int Palabra = Integer.parseInt(Integer.toBinaryString(0x1000 | i).substring(1).substring(9, 12), 2);
int Linea = leastRecentlyUsed.consult(Integer.parseInt(Integer.toBinaryString(Etiqueta),2));
leastRecentlyUsed.checkMap();
if (CacheMemoryD[Linea].isValid()) {
if (CacheMemoryD[Linea].getEtiqueta() == Etiqueta) {
CacheMemoryD[Linea].setModify(true);
CacheMemoryD[Linea].getPalabra()[Palabra] = v;
Time += 0.01;
} else {
if (CacheMemoryD[Linea].isModify()) {
int firstLine = Integer.parseInt(Integer.toString(Etiqueta), 2) * 8;
int firstLineM = Integer.parseInt(Integer.toString(CacheMemoryD[Linea].getEtiqueta()), 2) * 8;
int count = 0;
for (int j = firstLineM; j < firstLineM + 8; j++) {
RAM[j] = CacheMemoryD[Linea].getPalabra()[count];
count++;
}
count = 0;
for (int j = firstLine; j < firstLine + 8; j++) {
CacheMemoryD[Linea].getPalabra()[count] = RAM[j];
count++;
}
Time += 0.75;
CacheMemoryD[Linea].setValid(true);
CacheMemoryD[Linea].setModify(true);
} else {
int firstLine = Integer.parseInt(Integer.toString(Etiqueta), 2) * 8;
int count = 0;
for (int j = firstLine; j < firstLine + 8; j++) {
CacheMemoryD[Linea].getPalabra()[count] = RAM[j];
count++;
}
Time += 0.66;
CacheMemoryD[Linea].setModify(true);
}
CacheMemoryD[Linea].setEtiqueta(Etiqueta);
CacheMemoryD[Linea].getPalabra()[Palabra] = v;
}
} else {
int firstLine = Integer.parseInt(Integer.toString(Etiqueta), 2) * 8;
int count = 0;
for (int j = firstLine; j < firstLine + 8; j++) {
CacheMemoryD[Linea].getPalabra()[count] = RAM[j];
count++;
}
CacheMemoryD[Linea].setEtiqueta(Etiqueta);
CacheMemoryD[Linea].setValid(true);
CacheMemoryD[Linea].setModify(true);
CacheMemoryD[Linea].getPalabra()[Palabra] = v;
Time += 0.66;
}
} | 7 |
public boolean pass(int[] bowl, int bowlId, int round,
boolean canPick,
boolean musTake) {
bowlSize=sumOfArray(bowl);
if (musTake || !canPick) {
modifyDistribution(bowl);
roundInit(1);
return true;
}
double expectedScore=getExpectedScore();
double bowlScore=getBowlScore(bowl);
double deviation=getDeviation();
double meanPlus;
if(useLogisticFunctionDeviationFraction) //Chop off using logistic function
{
meanPlus=calculateDeviationThreshold()*scaledSigmoid(timesCanPass*1.0/timesCanPassInitial);
}
else //Linearly chop off
{
meanPlus=deviation*timesCanPass/(timesCanPassInitial-1);
}
if(debug)
{
print(String.format("timesCanPass %d timesCanPassInitial %d expected %f deviation %f deviationfraction %f", timesCanPass, timesCanPassInitial, expectedScore, deviation,calculateDeviationThreshold()));
print(String.format("Old expected=%f // bowlscore=%f ", (expectedScore+deviation*timesCanPass/(timesCanPassInitial-1)), bowlScore));
print(String.format("New expected=%f // bowlscore=%f ", (expectedScore+calculateDeviationThreshold()*scaledSigmoid(1.0*timesCanPass/timesCanPassInitial)), bowlScore));
print(String.format("stoppingthreshold=%d // passnumber=%d ", stoppingThreshold, passNumber));
}
boolean take = ((expectedScore+meanPlus) <= bowlScore || (takeReallyGoodBowl && bowlScore>=9*NFRUIT));
modifyDistribution(bowl);
if(useStopping && passNumber<=stoppingThreshold)
{
take=false;
}
if(!take)
timesCanPass--;
else
roundInit(1);
passNumber++;
return take;
} | 9 |
public Boolean process() {
// Permissions
if(!plugin.permission.canCreate(player)) {
noPermission();
return true;
}
// Correct command format
if(args.length == 2) {
// Slot exists
if(plugin.slotData.isSlot(args[1])) {
SlotMachine slot = plugin.slotData.getSlot(args[1]);
// Can access slot
if(isOwner(slot)) {
plugin.slotData.removeSlot(slot);
sendMessage("Slot machine removed.");
}
// No access
else {
plugin.sendMessage(player,"You do not own this slot machine.");
}
}
// Slot does not exist
else {
sendMessage("Invalid slot machine.");
}
}
// Incorrect command format
else {
sendMessage("Usage:");
sendMessage("/casino remove <name>");
}
return true;
} | 4 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Listing other = (Listing) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
return true;
} | 3 |
private void loadGameObjectType(IGameObjectType type) {
if (!gameObjectTypeCache.containsKey(type)) {
try {
// type was not loaded yet -> load it
Ini iniFile = new Ini(this.getClass().getResource("/" + type.getIniFilePath()));
Section section = iniFile.get(type.getIniFileSection());
if (section != null) {
// and store its default values in the unitTypeCache
Map<String, String> attributeKeyValueList = new HashMap<String, String>();
gameObjectTypeCache.put(type, attributeKeyValueList);
for (Entry<String, String> entry : section.entrySet()) {
String gameObjectAttribute = entry.getKey();
String gameObjectDefaultValue = entry.getValue();
attributeKeyValueList.put(gameObjectAttribute, gameObjectDefaultValue);
if (LOTDConstants.GAME_OBJECT_KEY_UNIT_LIFE_MAXIMUM.equals(gameObjectAttribute))
attributeKeyValueList.put(LOTDConstants.GAME_OBJECT_KEY_UNIT_LIFE_CURRENT, gameObjectDefaultValue);
else if (LOTDConstants.GAME_OBJECT_KEY_UNIT_ACTION_POINTS_MAXIMUM.equals(gameObjectAttribute))
attributeKeyValueList.put(LOTDConstants.GAME_OBJECT_KEY_UNIT_ACTION_POINTS_CURRENT, gameObjectDefaultValue);
}
} else
throw new Exception("Could not find section '" + type.getIniFileSection() + "' within .ini file '" + type.getIniFilePath() + "'");
} catch (Exception e) {
LOGGER.fatal("Error when trying to load gameObjectType " + type, e);
}
}
} | 6 |
private Box nextEmptyBox(char[][] board, int row, int column) {
int i = row;
int j = column;
for (; i < 9; i++) {
for (; j < 9; j++) {
if (board[i][j] == '.')
return new Box(i, j);
}
j = 0;
}
return done;
} | 3 |
public Integer getTotalCoffers(Player player){
if(player==null)
return null;
Integer total = 0;
Iterator<OfflinePlayer> itr = coffers.values().iterator();
while(itr.hasNext()){
if(itr.next().equals(player))
total++;
}
return total;
} | 3 |
public boolean containsAll(AbstractOrderedItemset itemset2){
// first we check the size
if(size() < itemset2.size()){
return false;
}
// we will use this variable to remember where we are in this itemset
int i = 0;
// for each item in itemset2, we will try to find it in this itemset
for(int j =0; j < itemset2.size(); j++){
boolean found = false; // flag to remember if we have find the item at position j
// we search in this itemset starting from the current position i
while(found == false && i< size()){
// if we found the current item from itemset2, we stop searching
if(get(i).equals(itemset2.get(j))){
found = true;
}// if the current item in this itemset is larger than
// the current item from itemset2, we return false
// because the itemsets are assumed to be lexically ordered.
else if(get(i) > itemset2.get(j)){
return false;
}
i++; // continue searching from position i++
}
// if the item was not found in the previous loop, return false
if(!found){
return false;
}
}
return true; // if all items were found, return true
} | 7 |
public static <T extends DC> Equality getPhiEqu(Set<Pair<T,T>> done)
{ if(done!=null)
{ if(done.next!=null)
{ return new Equality(done.a.fst().delta(done.a.snd()).equa().getValue()&&getPhiEqu(done.next).getValue());
}
else
{ return new Equality(done.a.fst().delta(done.a.snd()).equa().getValue());
}
}
else
{ return new Equality(false);
}
} | 3 |
private void doUpdateTrafficMask() {
if (trafficControllingSessions.isEmpty())
return;
for (;;) {
DatagramSessionImpl session = trafficControllingSessions.poll();
if (session == null)
break;
SelectionKey key = session.getSelectionKey();
// Retry later if session is not yet fully initialized.
// (In case that Session.suspend??() or session.resume??() is
// called before addSession() is processed)
if (key == null) {
scheduleTrafficControl(session);
break;
}
// skip if channel is already closed
if (!key.isValid()) {
continue;
}
// The normal is OP_READ and, if there are write requests in the
// session's write queue, set OP_WRITE to trigger flushing.
int ops = SelectionKey.OP_READ;
if (!session.getWriteRequestQueue().isEmpty()) {
ops |= SelectionKey.OP_WRITE;
}
// Now mask the preferred ops with the mask of the current session
int mask = session.getTrafficMask().getInterestOps();
key.interestOps(ops & mask);
}
} | 6 |
public void run() {
ThreadLocalRandom random = ThreadLocalRandom.current();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
bank.transfer(accounts[random.nextInt(0, ACCOUNTS_COUNT)],
accounts[random.nextInt(0, ACCOUNTS_COUNT)],
random.nextDouble(0, 320.d));
}
}
Thread[] threads = new Thread[THREADS_COUNT];
for (Thread thread : threads) {
thread = new Worker();
thread.start();
}
latch.countDown();
for (Thread thread : threads) {
if (thread != null && thread.isAlive()) thread.join();
} | 1 |
public double getEstimatedUtilityForDarkPlayer(CheckersSetup setup, boolean isDarkTurn) {
ArrayList<checkersSetup.Turn> turns = BasicCheckersAIFunctions.getAllPossiblePlayerOptionsFor1Turn(setup, isDarkTurn);
if(turns.size() == 0) {
if(isDarkTurn) {
return -BasicCheckersAIFunctions.DARK_WIN_UTILITY;
} else {
return BasicCheckersAIFunctions.DARK_WIN_UTILITY;
}
} else if(turns.get(0).getMovesFor1Turn().get(0).isJump()) {
double minUtility;
double currentUtility;
//TODO: TEST THIS!!
if(isDarkTurn) {
minUtility = BasicCheckersAIFunctions.DARK_WIN_UTILITY;
for(int i=0; i<turns.size(); i++) {
setup.playTurn(turns.get(i));
currentUtility = innerUtility.getEstimatedUtilityForDarkPlayer(setup, !isDarkTurn);
if(currentUtility < minUtility) {
minUtility = currentUtility;
}
setup.reverseTurn(turns.get(i));
}
} else {
minUtility = -BasicCheckersAIFunctions.DARK_WIN_UTILITY;
for(int i=0; i<turns.size(); i++) {
setup.playTurn(turns.get(i));
currentUtility = innerUtility.getEstimatedUtilityForDarkPlayer(setup, !isDarkTurn);
if(currentUtility > minUtility) {
minUtility = currentUtility;
}
setup.reverseTurn(turns.get(i));
}
}
//END TEST
return minUtility;
} else {
return innerUtility.getEstimatedUtilityForDarkPlayer(setup, isDarkTurn);
}
} | 8 |
@Test
public void cevTest1() {
userInput.add("hi");
userInput.add("my name is meng meng");
userInput.add("cavideria");
userInput.add("cavideria");
userInput.add("cavideria");
userInput.add("cavideria");
userInput.add("yes");
this.runMainActivityWithTestInput(userInput);
assertTrue((nlgResults.get(2).contains("cavideria") || nlgResults.get(2).contains("cafeteria"))
&& (nlgResults.get(4).contains("cavideria") || nlgResults.get(4).contains("cafeteria"))
&& nlgResults.get(5).contains("cafeteria")
&& (nlgResults.get(6).contains("cafeteria") || nlgResults.get(6).contains("there")));
} | 6 |
public void update(GameContainer gc, int delta) throws SlickException{
super.update(gc, delta);
move(gc.getInput());
executeStatusEffects(delta);
dt += delta;
if(dt > 1000) {
dt = 0;
float edx = enemy.dx;
float edy = enemy.dy;
float a = (edx * edx) + (edy * edy) - 25;
float b = ((enemy.x - x) * edx) + ((enemy.y - y) * edy);
float c = ((enemy.x - x) * (enemy.x - x)) + ((enemy.y - y) * (enemy.y - y));
float inside = (b * b) - (4 * a * c);
if(inside < 0) {
System.out.printf("%g\n", inside);
return;
}
float t = (float)Math.abs(((-b) + (float)Math.sqrt(inside)) / (2 * a));
dx = (enemy.x - x + (edx * t));
dy = (enemy.y - y + (edy * t));
float length = (float)Math.sqrt((dx * dx) + (dy * dy));
float mod = 5 / length;
dx *= mod;
dy *= mod;
//System.out.printf("t: %g, b: %g, edx: %g, edy: %g\n", t, b, edx, edy);
room.addSpell(new Fireball(room, this, x + (dx * 5) + 8, y + (dy * 5) + 8, enemy.x, enemy.y, dx, dy));
}
} | 2 |
protected void removeAnimal(Animal animal) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; i < grid[0].length; j++) {
if(grid[i][j].equals(animal)) {
grid[i][j] = null;
return;
}
}
}
} | 3 |
private boolean removeAllOnes() {
boolean happened = false;
for (final HashSet<MathsItem> hs : items) {
if (hs.size() < 2)
continue;
final HashSet<MathsItem> toremove = new HashSet<MathsItem>();
for (final MathsItem m : hs)
if (m.isOne())
toremove.add(m);
if (toremove.size() == hs.size()) {
int i = 0;
for (final MathsItem m : toremove) {
if (i != 0) hs.remove(m);
i++;
}
if (i <= 1)
continue;
} else {
for (final MathsItem m : toremove)
hs.remove(m);
}
happened |= !toremove.isEmpty();
}
return happened;
} | 9 |
public void initHauptmenue() {
clearContent();
loadFont();
spielNeu = new JButton("Neues Spiel");
spielNeu.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
initGame();
}
}
});
spielNeu.setFont(gothic);
spielNeu.setBackground(new Color(65, 142, 124));
spielNeu.setBorder(new LineBorder(Color.black, 3));
add(spielNeu, "2, 2");
spielLaden = new JButton("Spiel Laden");
spielLaden.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
}
}
});
spielLaden.setFont(gothic);
spielLaden.setBackground(new Color(65, 142, 124));
spielLaden.setBorder(new LineBorder(Color.black, 3));
add(spielLaden, "2, 4");
einstellungen = new JButton("Einstellungen");
einstellungen.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
}
}
});
einstellungen.setFont(gothic);
einstellungen.setBackground(new Color(65, 142, 124));
einstellungen.setBorder(new LineBorder(Color.black, 3));
add(einstellungen, "2, 6");
beenden = new JButton("Beenden");
beenden.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
System.exit(0);
}
}
});
beenden.setFont(gothic);
beenden.setBackground(new Color(65, 142, 124));
beenden.setBorder(new LineBorder(Color.black, 3));
add(beenden, "2, 8");
} | 4 |
protected void rootStored( File f, StoreResult sr ) {
if( sr.storedObjectCount > 0 && sr.fileInfo != null ) {
String message = LogUtil.formatStorageLogEntry(new Date(), sr.fileInfo.getFsObjectType(), sr.fileInfo.getPath(), sr.fileInfo.getUrn());
try {
FileOutputStream log = getIncomingLogStream();
log.write( (message + "\n\n").getBytes() );
log.flush();
} catch( IOException e ) {
System.err.println("Failed to write to log stream: "+e.getMessage());
}
}
if( shouldShowProgress ) {
showProgress();
}
if( shouldShowProgress && shouldReportResults ) {
if( shouldShowProgress ) hideProgress();
}
if( shouldReportResults ) {
System.err.println(f.getPath()+" -> "+(sr.fileInfo == null ? "(error)" : sr.fileInfo.getUrn()));
System.err.println(" "+sr.errorCount+" errors, "+sr.totalObjectCount+" objects read, "+sr.storedObjectCount+" objects stored");
}
} | 9 |
public String grailFormat(){
String output = "Grail Transitions:\n";
for(State s: startStates){
output += "(START) |- "+s.getName()+"\n";
}
for(State s: states){
for(String symbol: alphabet){
output += s.getName() + " " + symbol + " ";
for(State q: s.transition(symbol))
output += q.getName();
output += "\n";
}
}
for(State s: finalStates){
output += s.getName()+" -| (FINAL)"+"\n";
}
return output;
} | 5 |
public MemoryFrame(java.awt.Frame parent, final DCPU dcpu) {
super(parent, false);
initComponents();
this.ramTable.setModel(new DCPUMemoryTableModel(dcpu));
//disallow selection of column 0
this.ramTable.getColumnModel().setSelectionModel(new DefaultListSelectionModel() {
@Override
public void setSelectionInterval(int index0, int index1) {
if (index0 < 1 || index1 < 1) {
return;
}
super.setSelectionInterval(index0, index1);
}
});
//update the cell information panel
ListSelectionListener listSelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int col = ramTable.convertColumnIndexToModel(ramTable.getSelectedColumn()) - 1;
int row = ramTable.convertRowIndexToModel(ramTable.getSelectedRow());
final Word position = new Word();
position.setUnsignedInt(row * (ramTable.getModel().getColumnCount() - 1) + col);
memoryCellInformationPanel1.setMemoryCell("0x" + position.toHexString(), dcpu.getRam(position));
}
};
this.ramTable.getSelectionModel().addListSelectionListener(listSelectionListener);
this.ramTable.getColumnModel().getSelectionModel().addListSelectionListener(listSelectionListener);
//change selected and first cell design
this.ramTable.setDefaultRenderer(Word.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
int selectedCol = ramTable.convertColumnIndexToModel(ramTable.getSelectedColumn());
int selectedRow = ramTable.convertRowIndexToModel(ramTable.getSelectedRow());
if (isSelected || hasFocus || (selectedCol == column && selectedRow == row)) {
c.setBackground(new Color(107, 129, 137));
c.setForeground(new Color(255, 255, 255));
} else {
if (column == 0) {
c.setBackground(SystemColor.control);
c.setForeground(SystemColor.controlText);
} else {
final Color basicColor = table.getBackground();
final Color rowColor = row % 2 == 0 ? basicColor : basicColor.brighter();
final Color colColor = column % 2 == 0 ? basicColor : SwingUtils.shiftHue(basicColor);
c.setBackground(SwingUtils.mix(rowColor, colColor));
c.setForeground(table.getForeground());
}
}
return c;
}
});
ramTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ramTable.getSelectionModel().setSelectionInterval(0, 0);
ramTable.getColumnModel().getSelectionModel().setSelectionInterval(1, 1);
} | 9 |
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof InjectablePlugin)) {
return false;
}
return getName().equals(((InjectablePlugin) obj).getName());
} | 3 |
public SQLconnection conn()
{
SQLconnection sql=new SQLconnection("127.0.0.1", "root", "anika", "dblp");
try {
sql.connectMySql();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return sql;
} | 4 |
public String getCategoryName() {
return categoryName;
} | 0 |
public Widget find(int x, int y) {
Widget found = null;
// to augment height
int extraSpaceBetweenLines = 0;
if(numLines > 1){
extraSpaceBetweenLines = numLines - 1;
}
if (x >= this.x && x < this.x + W && y >= this.y && y < this.y + H * numLines + extraSpaceBetweenLines)
return this;
if (isOpen)
for (int i = 0 ; i < size() ; i++) {
Widget widget = child(i).find(x,y);
if (widget != null)
return widget;
}
return null;
} | 8 |
public static long differHowManyDays(Date arg0, Date arg1) {
long d1 = arg0.getTime();
long d2 = arg1.getTime();
return Math.abs(d1 - d2) / (60 * 60 * 24 * 1000);
} | 0 |
public void addListener(OutlineModelListener listener) {
if (!mListeners.contains(listener)) {
mListeners.add(listener);
}
} | 1 |
public static void saveChannels() {
File channelFolder = new File(System.getProperty("user.dir") + "\\channels");
File channelList = new File(channelFolder.getAbsolutePath() + "\\channels.txt");
if(categories.isEmpty()) {
channelList.delete();
}
try {
FileWriter writer = new FileWriter(channelList, false);
for(Map.Entry<String, Category> entry : categories.entrySet()) {
for(YTChannel channel : entry.getValue().getChannels())
writer.write(entry.getValue() + "&" + channel.channelName + "&" + channel.lastChecked.saveFormat() + "\n");
}
writer.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} | 4 |
static void testRange(int first, int last) {
print("Testing range from " + first + " to last " + last + ".");
long start = 0,end = 0;
Range range = new Range(first,last);
long normalDuration = 0;
long rangeDuration = 0;
long waste = 0;
start = System.nanoTime();
for (int curr = first; curr <= last; ++curr) {
waste += curr;
}
end = System.nanoTime();
normalDuration = end - start;
print("Normal iteration took " + normalDuration /1000 + " milliseconds.");
// Just to make sure that the value of waste is needed later on
// So it can't be ignored by the compiler or something
String s = new String("");
if ((waste & 1) != 0) s = ("Waste is odd");
else s = ("Waste is even");
start = System.nanoTime();
for (int i : range) {
waste +=i;
}
end = System.nanoTime();
rangeDuration = end - start;
print("Range iteration took " + rangeDuration /1000 + " milliseconds.");
// Just to make sure that the value of waste is needed later on
// So it can't be ignored by the compiler or something
if ((waste & 1) != 0) s = ("Waste is odd");
else s = ("Waste is even");
double ratio = rangeDuration/normalDuration;
print(" ================= Range version took " + ratio + " times as long as normal version. =================");
} | 4 |
private float calculatePositionValue(PositionType type, ROVector3f target, Coordinate currentCoordinate, Coordinate coordinate) {
float position = filterPosition(target, type);
boolean isInSameSystem = currentCoordinate.equals(coordinate);
if (hasParent() && !isInSameSystem) {
float parentValue = filterPosition(getParent().getPosition(), type);
switch (coordinate) {
case GLOBAL:
position += parentValue;
break;
case LOCAL:
position -= parentValue;
break;
}
}
return position;
} | 4 |
private ContentManager(){
this.blockManager = new BlockManager() ;
this.packetManager = new PacketManager();
} | 0 |
public static void main(String[] args) {
long start = System.nanoTime();
int sum = 0;
for (Integer i = 1; i < 1000000; i++) {
BigInteger binaryVal = new BigInteger((Integer.toBinaryString(i)));
if (isPalindromic(BigInteger.valueOf(i))
&& isPalindromic(binaryVal)) {
sum += i;
}
}
System.out.println(sum);
System.out.println("Done in " + (double) (System.nanoTime() - start)
/ 1000000000 + " seconds.");
} | 3 |
private CollectionPerson() {
Persons = new ArrayList<Person>();
CantPerson = 0;
} | 0 |
private static ByteBuffer toByteBuffer(byte[] data, boolean isStereo,
boolean isBigEndian) {
ByteBuffer dest = ByteBuffer.allocateDirect(data.length);
dest.order(ByteOrder.nativeOrder());
ByteBuffer src = ByteBuffer.wrap(data);
src.order(isBigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
if (isStereo) {
ShortBuffer destAsShort = dest.asShortBuffer();
ShortBuffer srcAsShort = src.asShortBuffer();
while (srcAsShort.hasRemaining()) {
destAsShort.put(srcAsShort.get());
}
} else {
while (src.hasRemaining()) {
dest.put(src.get());
}
}
dest.rewind();
return dest;
} | 4 |
@SuppressWarnings("unchecked")
public E pop() {
if (empty) return null;
E ret = (E)VALUES[begin];
VALUES[begin] = null;
begin++;
if (begin==MAX) begin=0;
if(begin == end){
empty = true;
begin = end = 0;
}
return ret;
} | 3 |
@Override
public boolean installPackage(String path) {
boolean result = false;
do {
long now = System.currentTimeMillis();
File tmp = new File(TMPPRE + now);
if(!tmp.exists()) {
tmp.mkdirs();
}
String tmpPath;
try {
tmpPath = tmp.getCanonicalPath();
} catch (IOException e1) {
e1.printStackTrace();
break;
}
String echo = AdbHelper.getInstance().executeCommand("tools/adb.exe", "devices");
System.out.println(echo);
String[] devs = echo.split("\n");
if(devs.length <= 2) {
System.out.println("no devices found");
break;
}
if(devs.length >= 4) {
System.out.println("only support one device now");
break;
}
try {
ZipUtils.unZip(path, tmpPath);
} catch (ZipException e1) {
e1.printStackTrace();
FileUtils.delFolder(tmpPath);
break;
} catch (IOException e1) {
e1.printStackTrace();
FileUtils.delFolder(tmpPath);
break;
}
byte[] rawBytes = SecurityUtils.decrypt(Base64Coder.decode(FileUtils.readFileAsString(tmpPath + File.separator + "mainifest.dat")));
String rawStr;
try {
rawStr = new String(rawBytes, "gbk");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
FileUtils.delFolder(tmpPath);
break;
}
GpkManifest manifest = ParseUtils.json2GpkManifest(rawStr);
echo = AdbHelper.getInstance().executeCommand("tools/adb.exe", "install", "-r", tmpPath + File.separator + "application.apk");
System.out.println(echo);
if(!echo.toLowerCase().contains("success")) {
FileUtils.delFolder(tmpPath);
System.out.println("install apk failed");
break;
}
String targetDataPackagePath = manifest.getCopyPath();
echo = AdbHelper.getInstance().executeCommand("tools/adb.exe", "push", tmpPath + File.separator + manifest.getPackageName(), targetDataPackagePath);
System.out.println(echo);
AdbHelper.getInstance().stop();
FileUtils.delFolder(tmpPath);
result = true;
} while(false);
return result;
} | 9 |
public static void main(String[] args)
{
System.out.println("Starting Test Cases");
try
{
// Parse the command line args
int policy = 0;
if ( args[0].equals("t") || args[0].equals("time") ) {
policy = ResourceCharacteristics.TIME_SHARED;
}
else if ( args[0].equals("s") || args[0].equals("space") ) {
policy = ResourceCharacteristics.SPACE_SHARED;
}
else {
System.out.println("Error -- Invalid allocation policy....");
return;
}
// determine which test case number to choose
int testNum = Integer.parseInt(args[1]);
if (testNum < MIN || testNum > MAX) {
testNum = MIN;
}
////////////////////////////////////////
// First step: Initialize the GridSim package. It should be called
// before creating any entities. We can't run this example without
// initializing GridSim first. We will get run-time exception
// error.
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // true means tracing GridSim events
// list of files or processing names to be excluded from any
// statistical measures
String[] exclude_from_file = { "" };
String[] exclude_from_processing = { "" };
// the name of a report file to be written. We don't want to write
// anything here.
String report_name = null;
// initialize all revelant variables
double baudRate[] = {1000, 5000}; // bandwidth for even, odd
int peRating[] = {10, 50}; // PE Rating for even, odd
double price[] = {3.0, 5.0}; // resource for even, odd
int gridletLength[] = {1000, 2000, 3000, 4000, 5000};
// Initialize the GridSim package
int totalUser = 2; // total Users for this experiment
GridSim.init(totalUser, calendar, trace_flag, exclude_from_file,
exclude_from_processing, report_name);
//////////////////////////////////////
// Second step: Creates one or more GridResource objects
int totalResource = 3; // total GridResources for this experiment
int totalMachine = 1; // total Machines for each GridResource
int totalPE = 3; // total PEs for each Machine
createResource(totalResource, totalMachine, totalPE, baudRate,
peRating, price, policy);
/////////////////////////////////////
// Third step: Creates grid users
int totalGridlet = 4; // total Gridlets for each User
createUser(totalUser, totalGridlet, gridletLength, baudRate,
testNum);
////////////////////////////////////
// Fourth step: Starts the simulation
GridSim.startGridSimulation();
}
catch (Exception e)
{
System.out.println("Unwanted errors happen");
System.out.println( e.getMessage() );
System.out.println("Usage: java Test [time | space] [1-8]");
}
System.out.println("=============== END OF TEST ====================");
} | 7 |
public IMessage crypter(IMessage clair, String key) {
/*
* Lecture de la clef, puis encodage des caractres un par un par
* des oprations elementaires
*/
long d=new Date().getTime();
String keyAdaptee=this.adapter(key);
int k;
char[] c=new char[clair.taille()];
for(int i=0;i<clair.taille();i++) {
k=keyAdaptee.charAt(i%keyAdaptee.length())-65;
if(clair.getChar(i)>=65 && clair.getChar(i)<=90) {
c[i]=(char)(65+((clair.getChar(i)-65+k)%26));
}
else {
if(clair.getChar(i)>=97 && clair.getChar(i)<=122) {
c[i]=(char)(97+((clair.getChar(i)-97+k)%26));
}
else{
c[i]=clair.getChar(i);
}
}
}
this.time=new Date().getTime()-d;
return Fabrique.fabriquerMessage(c);
} | 5 |
public static void main(String[] args) {
double num = -1;
String in = scan.nextLine();
// parse in by spaces and go through and find the first string that
// parsesDouble to a double, if it errors then try next.
boolean foundNum = false;
String[] splitBySpace = in.split(" ");
for (int sb = 0; sb < splitBySpace.length; sb++) {
try {
num = Double.parseDouble(splitBySpace[sb]);
foundNum = true;
} catch (Exception ex) {
}
}
if (foundNum) {
System.out.println("Your number is: " + num);
} else {
System.out.println("Cant find number");
}
} | 3 |
public static Automaton cleanAutomaton(Automaton a) {
Automaton ac = (Automaton) a.clone();
State[] s = ac.getStates();
Set useless = getUselessStates(ac);
for (int i = 0; i < s.length; i++) {
if (useless.contains(s[i]) && s[i] != ac.getInitialState())
ac.removeState(s[i]);
}
if (useless.contains(ac.getInitialState())) {
Transition[] t = ac.getTransitions();
for (int i = 0; i < t.length; i++)
ac.removeTransition(t[i]);
}
return ac;
} | 5 |
public void handleException(Throwable ex, Window window) {
if (ex instanceof YMethodNotFoundException) {
logger.info(ex.getMessage());
} else if (ex instanceof YInvalidMVCNameException ||
ex instanceof YCloneModelException ||
ex instanceof YEqualsModelException ||
ex instanceof YComponentValidationException) {
logger.warn(ex.getMessage());
} else {
if (ex instanceof YComponentModelCopyException) {
YComponentModelCopyException copyEx = (YComponentModelCopyException) ex;
logger.error(ex.getMessage());
logger.error("Original exception: ", copyEx.getOriginalException());
} else {
logger.error("Unknown error", ex);
}
// kommentoitu pois, koska esim. YTextFormatterin
// nostaman poikkeuksen n�ytt�minen virheikkunassa saa aikaan ikisilmukan...
// Window window = YUIToolkit.getCurrentWindow();
// JOptionPane.showOptionDialog(
// window,
// "Unknown application error.",
// "Error",
// JOptionPane.DEFAULT_OPTION,
// JOptionPane.ERROR_MESSAGE,
// null,
// new String[] {"Ok"},
// "Ok");
}
} | 6 |
public void onPluginMessageReceived(String string, Player player, byte[] arg2) {
if (string.equals("5ZIG")) {
try {
String response = new String(arg2);
if (response.startsWith("/l/connect")) {
response = response.replace("/l/connect", "");
ModUserLoginEvent e = new ModUserLoginEvent(player);
Bukkit.getPluginManager().callEvent(e);
if (!e.isCancelled()) {
int ver = Integer.parseInt(response);
if (ver == plugin.APIVER) {
player.sendPluginMessage(plugin, "5ZIG", "/l/connected".getBytes());
System.out.println("Player " + player.getName() + " connected using the 5zig Mod!");
if (!The5zigMod.getApi().isUsingMod(player)) {
The5zigModUser user = new The5zigModUser(player.getName());
plugin.users.add(user);
Bukkit.getPluginManager().callEvent(new ModUserLoggedInEvent(user));
} else {
The5zigModUser user = The5zigMod.getApi().getUser(player);
user.resendAll();
Bukkit.getPluginManager().callEvent(new ModUserLoggedInEvent(user));
}
} else {
player.sendPluginMessage(plugin, "5ZIG", "/l/outdated".getBytes());
}
} else {
player.sendPluginMessage(plugin, "5ZIG", "/l/cancelled".getBytes());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} | 6 |
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println(
"Usage: java RFS826_TcpClient <destination host> <destination port>");
System.exit(1);
}
// get the dest host + port from console
String dest_host = args[0];
int dest_port = Integer.parseInt(args[1]);
String sentence;
String modifiedSentence;
//input stream from the console
BufferedReader inFromUserConsole = new BufferedReader(new InputStreamReader(
System.in));
Socket clientSocket = new Socket(dest_host, dest_port);
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("Please input a message:");
sentence = inFromUserConsole.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println(modifiedSentence);
//close client socket
clientSocket.close();
} | 1 |
public static boolean existsName(Usuarios usu){
String sql = " SELECT * FROM usuarios WHERE usuario = '"+usu.getUsuario()+"' ";
if(!BD.getInstance().sqlSelect(sql)){
return false;
}
if(!BD.getInstance().sqlFetch()){
return false;
}
return true;
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof InstanceList)) {
return false;
}
InstanceList<?> other = (InstanceList<?>) obj;
if (clazz == null) {
if (other.clazz != null) {
return false;
}
} else if (!clazz.equals(other.clazz)) {
return false;
}
return true;
} | 8 |
protected IRemoteCallObject responseData(long connectionId, final IRemoteCallObject callObj)
throws RemoteCallException, EndOfConnectionException {
//..handler answer from client (with error or not)
IRemoteCallObject response = callObj.getResponseRemoteCallObject();
if (callObj != null) {
if (callObj.isError()) {
//..if receipt error, re-throw it
Object object = response.getDataObject().getData();
if (!(object instanceof Exception)) {
throw new IllegalArgumentException("Response data isn't Exception type");
}
throw new RemoteCallException((Exception)object);
}
else if (callObj.isDisconnect()) {
//..if disconnected, throw EndOfConnectionException
throw new EndOfConnectionException("Call <" + callObj.getMetaDataObject().getExecCommand() + "> is failure for disconnect");
}
else {
//..receive the result to the call
return response;
}
}
else {
//..receive null, not the result
ISocketServerConnection ssc = getConnectionById(connectionId);
if ((ssc != null) && (!ssc.isActive())) {
throw new EndOfConnectionException("End of connection for " + ssc.getRemoteAddress());
}
else {
throw new IllegalArgumentException("CallObject result is null");
}
}
} | 6 |
public static String convert(String s, int nRows) {
if(nRows == 1 || s.length()<=nRows || s.equals(""))
return s;
String rs = "";
for(int i = 0; i < nRows; i++) {
//in these rows, only exists primary elements
if(i == 0 || i == (nRows-1)) {
int index = i;
while(index < s.length()) {
rs = rs + s.charAt(index);
index = index + 2*nRows -2;
}
}
//in these rows, there exists primary elements and secondary elements
else {
int index = i;
rs += s.charAt(index);
index += 2*nRows -2;
//if the secondary element exists
while(index - 2*i < s.length()) {
//if the primary element after the secondary element exists
if(index < s.length())
rs = rs + s.charAt(index - 2*i) + s.charAt(index);
//if the primary element doesn't exist
else
rs = rs + s.charAt(index - 2*i);
index = index + 2*nRows -2;
}
}
}
return rs;
} | 9 |
public boolean kontroliertEuropa(Spieler s) {
boolean res = true;
if(!s.fraktion.equals(laenderGraph.getLaenderList().getLandByID(1).getOwner())) {
res = false;
}
return res;
} | 1 |
public void printStack(int stackId){
switch (stackId) {
case STACK_1:
System.out.print("\n\n\nPrinting STACK_1 Contents : [ ");
for(int i=0; i<head1; i++){
System.out.print(data[i*3]+",\t");
}
System.out.println("]");
break;
case STACK_2:
System.out.print("\n\n\nPrinting STACK_2 Contents : [ ");
for(int i=0; i<head2; i++){
System.out.print(data[(i*3)+1]+",\t");
}
System.out.println("]");
break;
case STACK_3:
System.out.print("\n\n\nPrinting STACK_3 Contents : [ ");
for(int i=0; i<head3; i++){
System.out.print(data[(i*3)+2]+",\t");
}
System.out.println("]");
break;
default:
break;
}
} | 6 |
private int getKthSmallestRecursion(int ai, int bi, int k)
{
printStatus(ai, bi, k);
if (k == 2) {
return get2ndSmallest(ai, bi);
}
int half_k = (k - 1) / 2;
int mid_ai = ai + half_k;
int mid_bi = bi + half_k;
int aval = a.get(mid_ai);
int bval = b.get(mid_bi);
if (aval == bval) {
// Early exit condition
return aval;
} else if (aval < bval) {
// Early exit condition
if (k % 2 == 0) {
if (bval < a.get(mid_ai+1)) return bval;
// if k is even then aval cannot be k-th smallest
++mid_ai;
} else {
if (aval > b.get(mid_bi-1)) return aval;
}
// Continue the search
return getKthSmallestRecursion(mid_ai, bi, k - half_k);
} else {
// Early exit condition
if (k % 2 == 0) {
if (aval < b.get(mid_bi+1)) return aval;
// if k is even then bval cannot be k-th smallest
++mid_bi;
} else {
if (bval > a.get(mid_ai-1)) return bval;
}
// Continue the search
return getKthSmallestRecursion(ai, mid_bi, k - half_k);
}
} | 9 |
public boolean insertAt(int index, E element) {
LinkedElement<E> oldElem = findElement(index);
if (index == total) {
addLast(element); // increments total
return true;
}
if (index == 0) {
addFirst(element); // increments total
return true;
}
if (oldElem != null) {
LinkedElement<E> newElem = new LinkedElement<E>(element);
LinkedElement<E> prev = oldElem.getPrev();
newElem.setPrev(prev);
prev.setNext(newElem);
newElem.setNext(oldElem);
oldElem.setPrev(newElem);
total++;
return true;
}
return false;
} | 3 |
@Override
public Buildable create(Object name, Object value) {
if (name.equals("model")) {
if (model != null) {
throw new IllegalArgumentException("Only one 'model' allowed.");
}
return model = new Model();
} else if (name.equals("output")) {
return output = new OutputDescriptor();
}
throw new IllegalArgumentException(name.toString());
} | 3 |
public String getPath()
{
return path;
} | 0 |
public boolean serieValoradaVistaSeguida(Serie serie){
// Se comprueba si la serie es seguida por algún usuario.
for (UsuarioRegistrado usuario : misUsuarios) {
try{
Serie serieuser = usuario.buscarSerieSeguida(serie.obtenerTitulo());
}catch(Exception e){
return false;
}
}
// Se comprueba si la serie tiene valoraciones de algún usuario.
for (UsuarioRegistrado usuario : misUsuarios) {
if (serie.existeContenidoValorado(usuario))
return false;
}
return true;
} | 4 |
public static void openEditor(IWorkbenchPage page, ISelection selection,
int lineNumber) {
// Get the first element.
if (!(selection instanceof IStructuredSelection))
return;
Iterator<?> iter = ((IStructuredSelection) selection).iterator();
if (!iter.hasNext())
return;
Object elem = iter.next();
// Adapt the first element to a file.
if (!(elem instanceof IAdaptable))
return;
IFile file = (IFile) ((IAdaptable) elem).getAdapter(IFile.class);
if (file == null)
return;
// Open an editor on that file.
try {
ITextEditor editor = (ITextEditor) IDE.openEditor(page, file);
IDocument document = editor.getDocumentProvider().getDocument(
editor.getEditorInput());
if (document != null) {
IRegion lineInfo = null;
try {
// line count internaly starts with 0, and not with 1 like in
// GUI
lineInfo = document.getLineInformation(lineNumber - 1);
} catch (BadLocationException e) {
// ignored because line number may not really exist in document,
// we guess this...
}
if (lineInfo != null) {
editor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
}
}
} catch (PartInitException e) {
e.printStackTrace();
}
} | 9 |
public static List<TokenType> parse(CSVObject csv){
List<TokenType> types = new Vector<TokenType>();
types = new Vector<TokenType>();
String[][] data = csv.getData();
for(String[] line : data){
types.add(new TokenType(line[0], line[1], line[2]));
}
System.out.println("TokenType.parse() -> " + types + ";");
return types;
} | 1 |
public void updateUserInfo() throws IOException {
if (config.isDebugOn())
System.err.println("Updating user info. "+"$MyINFO $ALL "+getUsername()+" "+config.getDescription()+"$ <++ V:0.673,M:P,H:0/1/0,S:2>$ $LAN(T3)0x31$"+config.getEmail()+"$1234$|");
//hubCommunicator.sendDataToHub("$Version 1.0|");
hubComm.sendDataToHub("$MyINFO $ALL "+getUsername()+" "+config.getDescription()+"$ <++ V:0.673,M:P,H:0/1/0,S:2>$ $LAN(T3)0x31$"+config.getEmail()+"$1234$|");
//TODO: most of the information being sent to the hub is not set anywhere. that should be fixed. a settings/configuration already exists. move it
} | 1 |
public static LinkedHashMap<String,Object> array_change_key_case(Map<String,Object> hm, String upperLower) {
LinkedHashMap<String,Object> output = new LinkedHashMap<String,Object>();
if (hm == null) return output;
if (upperLower == null) upperLower = "LOWER";
for (Map.Entry<String,Object> entry : hm.entrySet()) {
String key = (String) entry.getKey();
Object value = (Object) entry.getValue();
if (key == null) {
output.put(key, value);
} else if (upperLower.equals("LOWER")) {
output.put(key.toLowerCase(),value);
} else {
output.put(key.toUpperCase(),value);
}
}
return output;
} | 5 |
private static void getAccessAndRefreshTokensFromAuthorizationCode(
TokenType t) {
flagAccessToken = false;
// builds POST parameters
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("client_id", clientId));
parameters.add(new BasicNameValuePair("client_secret", apiKey));
if (t == TokenType.ACCESS) {
parameters.add(new BasicNameValuePair("grant_type",
"authorization_code"));
parameters.add(new BasicNameValuePair("code", authorizationCode));
}
if (t == TokenType.REFRESH) {
if (refreshToken == null) {
flagAccessToken = true;
return;
}
parameters
.add(new BasicNameValuePair("grant_type", "refresh_token"));
parameters
.add(new BasicNameValuePair("refresh_token", refreshToken));
}
// executes POST
String output = sendHttpPost(
"https://www.freesound.org/apiv2/oauth2/access_token/",
parameters);
// extracts access token and refresh token
try {
JsonObject response = JsonObject.readFrom(output);
accessToken = response.get("access_token").asString();
refreshToken = response.get("refresh_token").asString();
// saves refresh token
OutputLog o = new OutputLog("refresh_token.json");
JsonObject j = new JsonObject();
j.add("refresh_token", refreshToken);
o.writeJsonObjectToFile(j);
} catch (ParseException e) {
e.printStackTrace();
flagAccessToken = true;
return;
} catch (UnsupportedOperationException e) {
e.printStackTrace();
flagAccessToken = true;
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
flagAccessToken = true;
return;
}
} | 6 |
public Lemonade() {
this.setName("Lemonade");
this.setPrice(new BigDecimal(15));
} | 0 |
public boolean isLibre() {
if(controleur==null) return true;
else return false;
} | 1 |
private TileState stateFrom(boolean is_passable, boolean is_opaque) {
if (is_opaque) {
if (is_passable) {
return TileState.PASSABLE_OPAQUE;
}
return TileState.IMPASSABLE_OPAQUE;
} else {
if (is_passable) {
return TileState.PASSABLE_TRANSPARENT;
}
return TileState.IMPASSABLE_TRANSPARENT;
}
} | 3 |
private static void callRightMethod(CommandLine cli) throws FileNotFoundException, IOException
{
Mode mode = getMode(cli);
System.out.println("Starting with mode = " + mode);
final String sourceDirectory = cli.getOptionValue('s');
final String destDirectory = cli.getOptionValue('d');
final String sourcePdfFileOrDir = cli.getOptionValue('f');
System.out.println("Quellverzeichnis = " + sourceDirectory);
System.out.println("Zielverzeichnis = " + destDirectory);
System.out.println("PDF Dateiname = " + sourcePdfFileOrDir);
switch (mode)
{
case ZIPANDWRAP:
PdfWrapperExecutor.zipAndWrap(sourceDirectory, destDirectory);
break;
case ZIP:
PdfWrapperExecutor.zip(sourceDirectory, destDirectory);
break;
case UNWRAP:
PdfWrapperExecutor.unwrap(sourcePdfFileOrDir);
break;
default:
System.err.println("Mode wurde nicht erkannt");
break;
}
} | 3 |
@Override
public void actionPerformed(ActionEvent e) {
int dialogButton;
BmTestManager bmTestManager = BmTestManager.getInstance();
if ("start".equals(e.getActionCommand().toLowerCase())) {
if (bmTestManager.getUserKey().isEmpty()) {
JMeterUtils.reportErrorToUser("Please, set up user key.", "User key is not set.");
return;
}
dialogButton = JOptionPane.showConfirmDialog(TestPanel.getTestPanel().getMainPanel(), "Are you sure that you want to start the test?",
"Start test?",
JOptionPane.YES_NO_OPTION);
if (dialogButton == JOptionPane.YES_OPTION) {
GuiUtils.startInTheCloud(cloudPanel.getNumberOfUsersSlider(),
cloudPanel.getDurationSpinner(),
cloudPanel.getIterationsSpinner(),
cloudPanel.getRampupSpinner());
}
} else {
dialogButton = JOptionPane.showConfirmDialog(TestPanel.getTestPanel().getMainPanel(), "Are you sure that you want to stop the test? ",
"Stop test?",
JOptionPane.YES_NO_OPTION);
if (dialogButton == JOptionPane.YES_OPTION) {
BmTestManager.getInstance().stopTest();
}
}
} | 4 |
public String init() {
user_dao.regisUser("kimapiwat","1234");
project_dao.saveProject("Assasin creed");
project_dao.saveProject("Call of Duty 4");
project_dao.saveProject("Battlefield");
project_dao.saveProject("Walking Dead");
project_dao.saveProject("Breaking Dawn");
project_dao.saveProject("Taylor swift");
criteria_dao.saveCriteria("Best Design");
criteria_dao.saveCriteria("Best Game");
criteria_dao.saveCriteria("Best Coding");
criteria_dao.saveCriteria("Best of All");
criteria_dao.saveCriteria("Drunker");
criteria_dao.saveCriteria("Coruption");
//INIT : id1,name1 : id2,name2 : id3,name3
// #
//CAT : cat_id1,best coding : cat_id2,best GUI : cat_id3,best of all
List<Project_eXceed> projects_list = project_dao.findAllProjects();
List<Criteria> criteria_list = criteria_dao.findAllCriteria();
if (!(projects_list.size() == 0 && criteria_list.size() == 0)) {
StringBuilder sb = new StringBuilder("");
sb.append("INIT");
for (Project_eXceed p : projects_list) {
sb.append(":" + p.getProject_ID() + "," + p.getProject_Name());
}
sb.append("#");
sb.append("CRI");
for (Criteria c : criteria_list) {
sb.append(":" + c.getId() + "," + c.getName());
}
return sb.toString();
}
return "INIT_FAILED";
} | 4 |
private String getPropertyValue(final Properties properties, final String propertyTag, final String defaultValue) {
String value = properties.getProperty(propertyTag);
if (value == null) {
value = defaultValue;
} else if (value.isEmpty()) {
value = defaultValue;
}
return value;
} | 2 |
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.