method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
f8fd6b15-0d26-45c5-bebd-f5a6fdaaea4e | 0 | public PooledThread() {
super(ThreadPool.this,
"PooledThread-" + (threadID++));
} |
1cafa1fd-c87f-4047-a63b-fab3aef7e6c5 | 6 | public AbstractInsnNode clone(final Map labels) {
FrameNode clone = new FrameNode();
clone.type = type;
if (local != null) {
clone.local = new ArrayList();
for (int i = 0; i < local.size(); ++i) {
Object l = local.get(i);
if (l instanceof LabelNode) {
l = labels.get(l);
}
clone.local.add(l);
}
}
if (stack != null) {
clone.stack = new ArrayList();
for (int i = 0; i < stack.size(); ++i) {
Object s = stack.get(i);
if (s instanceof LabelNode) {
s = labels.get(s);
}
clone.stack.add(s);
}
}
return clone;
} |
fe3d503c-6e98-4d95-85fe-c0ef5d8ccd3d | 7 | private void computeArcSlots(Digraph<SugiyamaNode<V>,SugiyamaArc<V,E>> graph) {
List<SugiyamaArc<V,E>> arcs = new ArrayList<SugiyamaArc<V,E>>(graph.getEdgeCount());
// collect arcs
for (SugiyamaNode<V> source : graph.vertices()) {
for (SugiyamaNode<V> target : graph.targets(source)) {
arcs.add(graph.get(source, target));
}
}
// sort arcs
Collections.sort(arcs, new Comparator<SugiyamaArc<V,E>>() {
@Override
public int compare(SugiyamaArc<V,E> e1, SugiyamaArc<V,E> e2) {
double key1 = e1.getSource().getIndex() + e1.getTarget().getIndex();
double key2 = e2.getSource().getIndex() + e2.getTarget().getIndex();
return key1 < key2 ? -1 : key1 > key2 ? 1 : 0;
}
});
// assign slot numbers
for (SugiyamaArc<V,E> arc : arcs) {
arc.setSourceSlot(arc.getSource().nextLowerSlot());
arc.setTargetSlot(arc.getTarget().nextUpperSlot());
if ((int)arc.getSource().getPosition() == (int)arc.getTarget().getPosition()) { // assign center slot
arc.getSource().setLowerCenterSlot(arc.getSourceSlot());
arc.getTarget().setUpperCenterSlot(arc.getTargetSlot());
}
arc = arc.getBackArc();
if (arc != null) {
arc.setSourceSlot(arc.getSource().nextLowerSlot());
arc.setTargetSlot(arc.getTarget().nextUpperSlot());
}
}
} |
2c34d133-0b6e-4b9d-8c99-f1c9249e2264 | 2 | public void step() {
parentFrame.getWorld().step();
parentFrame.repaint();
if (++numStepsSoFar == numStepsToRun)
stop();
Grid<T> gr = parentFrame.getWorld().getGrid();
for (Location loc : gr.getOccupiedLocations())
addOccupant(gr.get(loc));
} |
0bcb142a-394b-450f-9fc2-c4af3681c758 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ComprarJuego3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ComprarJuego3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ComprarJuego3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ComprarJuego3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ComprarJuego3().setVisible(true);
}
});
} |
2fed3c91-242f-4560-8728-f8a735c6d339 | 3 | public static void main(String[] args){
int[] fac = new int[10];
for (int i=0;i<10;i++) fac[i] = factorial(i);
int sum=0;
for(int i=10;i<2e7;i++){
if (i == facSum(i, fac)) sum+=i;
}
System.out.println(sum);
} |
0e236d90-2674-4815-a3ef-cb77603521d4 | 8 | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((assentos == null) ? 0 : assentos.hashCode());
result = prime * result
+ ((horarioChegada == null) ? 0 : horarioChegada.hashCode());
result = prime * result
+ ((horarioSaida == null) ? 0 : horarioSaida.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((numeroVoo == null) ? 0 : numeroVoo.hashCode());
result = prime * result + ((preco == null) ? 0 : preco.hashCode());
result = prime * result
+ ((reservas == null) ? 0 : reservas.hashCode());
return result;
} |
d67f36dd-e215-453c-983f-a17f14f4d47c | 7 | @Override
public void gotoDetail(GoodsStatus gs, String goodUrl) {
Document doc = null;
try {
doc = Jsoup.connect(goodUrl).timeout(0).get();
} catch (IOException e) {
logger.error(e.getMessage(), e);
gs.setStatus(GoodsStatus.NOT_FOUND);
gs.setResult(GoodsStatus.SEARCH_EXCEPTION);
return;
}
Elements items = doc.select("#listall_ll");
if(items.size()!=1){
logger.warn("listall_ll is not primary:"+gs.getGoodsId());
gs.setStatus(GoodsStatus.NOT_FOUND);
gs.setResult(GoodsStatus.SEARCH_EXCEPTION);
return;
}
Element tbodyItem = items.get(0);
Elements trs = tbodyItem.select("tr");
StringBuilder resultSb = new StringBuilder();
int skuNum = trs.size();
int noStoreSkuNum = 0;
for (Element tr : trs) {
boolean noFlag = false;
Elements tdNo = tr.select("td:has(a)");
if(tdNo.size()!=0){
noFlag = true;
noStoreSkuNum++;
}
if (noFlag) {
Elements sku = tr.select("[style]");
resultSb.append(sku.get(0).html()+"|");
}
}
if(noStoreSkuNum==0){
//全部有货
gs.setStatus(GoodsStatus.ALL_HAVE_STORE);
}else{
if(skuNum==noStoreSkuNum){
//全部缺货
gs.setStatus(GoodsStatus.ALL_NO_STORE);
}else{
//部分缺货
String result = resultSb.toString().substring(0, resultSb.toString().length()-1);
gs.setStatus(2);
gs.setResult(result);
}
}
} |
945474a2-64c3-4ae5-af89-c20153833821 | 9 | public static AbstractCommand createCommand(TimeBan plugin, String cmd) {
AbstractCommand result = new NullCommand(plugin);
TimeBanCommands command;
try {
command = TimeBanCommands.valueOf(cmd.toUpperCase());
} catch (IllegalArgumentException e) {
return result;
} catch (NullPointerException e) {
return result;
}
switch (command) {
case BAN:
result = new TimeBanBanCommand(plugin);
break;
case UNBAN:
result = new TimeBanUnbanCommand(plugin);
break;
case LIST:
result = new TimeBanListCommand(plugin);
break;
case INFO:
result = new TimeBanInfoCommand(plugin);
break;
case RM:
result = new TimeBanRmCommand(plugin);
break;
case HELP:
result = new TimeBanHelpCommand(plugin);
break;
case RUN:
result = new TimeBanRunCommand(plugin);
break;
}
return result;
} |
5c0255cc-b2b2-43b8-a154-53328e84c9a7 | 3 | public void run() {
T current;
while (!isInterrupted()) {
/* select next thread */
current = queue.getNext();
if ((current != null) && (current.isAlive())) {
/* Print Log */
reportThreadState();
current.setPriority(Thread.MAX_PRIORITY);
System.err.println("********* New High Priority: "
+ current.getName());
/* wait until time slice is over */
schedulerSleep();
current.setPriority(Thread.MIN_PRIORITY);
}
}
} |
8225f8f9-c04a-41e2-ac92-b30c655787aa | 2 | public static byte[] decrypt(byte[] encoded_message) throws Exception {
if (encoded_message[0] == (byte) 0x02) {
int padding;
for (padding = 1; encoded_message[padding] != (byte) 0x00; padding++) ;
byte[] decoded_message = new byte[encoded_message.length - 1 - padding];
System.arraycopy(encoded_message, padding + 1, decoded_message, 0, decoded_message.length);
return decoded_message;
} else return new byte[0];
} |
0701ac71-be84-4ed9-9857-44452c184463 | 4 | public String GetNextString(){
if (text.length() == 0) return null;
int nextSeperator = text.indexOf("|");
if (nextSeperator == -1) return null;
String currentString = text.substring(0, nextSeperator);
text = text.substring(nextSeperator+1);
if (currentString.startsWith("\n")) currentString = currentString.substring(1);
if (currentString.endsWith("\n")) currentString = currentString.substring(0,currentString.length()-1);
return currentString;
} |
9324077b-dded-4ca1-9fd6-8786596415ac | 5 | public static void run() {
final String dir = "E:\\DropBox\\DEV\\AdCleaner\\adcleaner\\~\\.adcelaner\\screens\\";
ImageSimilarityComparer comparer = new ImageSimilarityComparer();
ArrayList<File> files = new ArrayList<File>() {{
add(new File(dir + "video1_10.png"));
add(new File(dir + "video1_30.png"));
add(new File(dir + "video1_60.png"));
add(new File(dir + "video1_70.png"));
add(new File(dir + "video1_100.png"));
add(new File(dir + "video1_105.png"));
add(new File(dir + "video1_110.png"));
add(new File(dir + "video1_115.png"));
//add(new File(dir + "video1_out_135.png"));
//add(new File(dir + "video1_out_180.png"));
//add(new File(dir + "video1_out_170.png"));
//add(new File("img/cac1.jpg"));
//add(new File("img/cac2.jpg"));
//add(new File("img/cac3.jpg"));
//add(new File("img/dexter1.jpg"));
}};
int length = 0;
HashMap<String, HashMap<String, List<double[]>>> descriptors = new HashMap<>();
for(File from : files){
for (ImageDescriptor descriptor : comparer.getAllDescriptors())
{
String key = descriptor.getDescriptorName();
if (!descriptors.containsKey(key))
descriptors.put(key, new HashMap<String, List<double[]>>());
descriptors.get(key).put(from.getName(), descriptor.run(from));
}
}
for(File from : files){
for (File to : files){
comparer.areImagesSimilar(from, to);
}
}
} |
285444d3-8da5-477f-9ed1-d793926fef2e | 1 | public static TestcaseFactory getInstance() {
if (instance == null) {
instance = new TestcaseFactory();
}
return instance;
} |
0295f9f5-7e22-4e4e-824e-b738947c6041 | 3 | @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(commandLabel.equalsIgnoreCase("smite")) {
Player target = (Bukkit.getServer().getPlayer(args[0]));
if (target == null) {
sender.sendMessage(args[0] + " is not online!");
return false;
}
if (args.length < 2) {
sender.sendMessage("Not enough arguments!");
return false;
}
else{
String reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " ");
target.getWorld().strikeLightning(target.getLocation());
target.getWorld().strikeLightning(target.getLocation());
target.getWorld().strikeLightning(target.getLocation());
target.setHealth(0.0);
target.sendMessage(ChatColor.RED + "You have been a BAD person... read the rules below now!");
Bukkit.getServer().dispatchCommand(target, "rules");
Bukkit.broadcastMessage(ChatColor.GOLD + target.getName() + " has been smitten for " + ChatColor.RED + reason + ChatColor.GOLD + " by " + ChatColor.DARK_PURPLE + sender.getName() + ChatColor.GOLD + "!");
return true;
}
}
return false;
} |
d83d0718-881a-429b-b0a0-d4a708f27073 | 9 | public void setTileDamage(){
for(int xx=0;xx<SIZE;xx++){
for(int yy=0;yy<SIZE;yy++){
switch(world[xx][yy]){
case STONE:
worldDamage[xx][yy]=10;
break;
case WOOD:
worldDamage[xx][yy]=5;
break;
case STEEL:
worldDamage[xx][yy]=15;
break;
case URANIUM:
worldDamage[xx][yy]=30;
break;
case COAL:
worldDamage[xx][yy]=12;
break;
case DIRT:
worldDamage[xx][yy]=3;
break;
case AIR:
worldDamage[xx][yy]=0;
break;
default:
worldDamage[xx][yy]=2;
break;
}
}
}
} |
fbea38fb-b5bf-4abe-be15-23bef661e5d3 | 8 | public void confirmClicked(boolean par1, int par2)
{
if (this.deleteClicked)
{
this.deleteClicked = false;
if (par1)
{
this.serverList.remove(par2);
this.saveServerList();
}
this.mc.displayGuiScreen(this);
}
else if (this.directClicked)
{
this.directClicked = false;
if (par1)
{
this.joinServer(this.tempServer);
}
else
{
this.mc.displayGuiScreen(this);
}
}
else if (this.addClicked)
{
this.addClicked = false;
if (par1)
{
this.serverList.add(this.tempServer);
this.saveServerList();
}
this.mc.displayGuiScreen(this);
}
else if (this.editClicked)
{
this.editClicked = false;
if (par1)
{
ServerNBTStorage var3 = (ServerNBTStorage)this.serverList.get(this.selectedServer);
var3.name = this.tempServer.name;
var3.host = this.tempServer.host;
this.saveServerList();
}
this.mc.displayGuiScreen(this);
}
} |
f71e1513-0dc0-4a85-b947-3d0ee11f61d6 | 2 | public MinimapPanel(Coord c, Coord sz, Widget parent) {
super(c, sz, parent, "Minimap");
mrgn = Coord.z;
fbtn.visible = true;
cbtn.visible = false;
{
vcl = new IButton(new Coord(0, -2), this, Resource.loadimg("gfx/hud/slen/dispauth"), Resource.loadimg("gfx/hud/slen/dispauthd")) {
private boolean v = false;
public void click() {
MapView mv = ui.mapview;
BufferedImage tmp = down;
down = up;
up = tmp;
hover = tmp;
if(v) {
mv.disol(2, 3);
v = false;
} else {
mv.enol(2, 3);
v = true;
}
}
};
vcl.tooltip = "Show village authority";
}
{
pcl = new IButton(new Coord(0, 4), this, Resource.loadimg("gfx/hud/slen/dispclaim"), Resource.loadimg("gfx/hud/slen/dispclaimd")) {
private boolean v = false;
public void click() {
MapView mv = ui.mapview;
BufferedImage tmp = down;
down = up;
up = tmp;
hover = tmp;
if(v) {
mv.disol(0, 1);
v = false;
} else {
mv.enol(0, 1);
v = true;
}
}
};
pcl.tooltip = "Show claims";
}
ui.minimappanel = this;
mm = new MiniMap(new Coord(0, 32), minsz, this, ui.mapview);
/*(new CheckBox(new Coord(110, 15), this, "Use simple map") {
public void changed(boolean val) {
Config.useSimpleMap = val;
this.setfocus(this);
Config.saveOptions();
}
}).a = Config.useSimpleMap;*/
new IButton(new Coord(45, 8), this, Resource.loadimg("gfx/hud/buttons/gridu"), Resource.loadimg("gfx/hud/buttons/gridd")) {
public void click() {
BufferedImage tmp = down;
down = up;
up = tmp;
hover = tmp;
mm.grid = !mm.grid;
}
}.tooltip = "Show minimap grid";
new IButton(new Coord(65, 8), this, Resource.loadimg("gfx/hud/buttons/centeru"), Resource.loadimg("gfx/hud/buttons/centerd")) {
public void click() {
mm.off = new Coord();
UI.instance.mapview.resetcam(); //Kerrigan
}
}.tooltip = "Focus minimap and character";
new IButton(new Coord(88, 12), this, Resource.loadimg("gfx/hud/charsh/plusup"), Resource.loadimg("gfx/hud/charsh/plusdown")) {
public void click() {
mm.setScale(mm.scale+1);
}
};
new IButton(new Coord(103, 12), this, Resource.loadimg("gfx/hud/charsh/minusup"), Resource.loadimg("gfx/hud/charsh/minusdown")) {
public void click() {
mm.setScale(mm.scale-1);
}
};
btncave = new IButton(new Coord(121, 8), this, Resource.loadimg("gfx/hud/buttons/saveu"), Resource.loadimg("gfx/hud/buttons/saved")) {
public void click() {
mm.saveCaveMaps();
}
};
btncave.tooltip = "Save cave minimaps";
KerriUtils.makeButtonSC();
KerriUtils.makeButtonOP();
KerriUtils.makeButtonVR();
KerriUtils.makeButtonOH();
pack();
this.c = new Coord( MainFrame.getInnerSize().x - this.sz.x, 7);
loadpos();
} |
922a7b9c-9df7-45df-8eaa-54c85c38ea2a | 0 | public synchronized int getSharedCounter() {
return sharedCounter;
} |
6d8864b5-0936-4a8f-8ccb-7eeab1591401 | 3 | public boolean canTeach(Field aField, Group aGroup) {
//System.out.println("Teacher.canTeach() : " + this + " " + aField + " " + aGroup + " " + this.maxWeekWorkedHours.substract(this.currentWeekWorkedHours) + " " + aGroup.classes.get(aField));
boolean res = false;
if (aGroup.getClasses().get(aField).add(this.currentWeekWorkedHours).isMoreThan((this.maxWeekWorkedHours)))
return false;
for (int i = 0 ; i < this.fields.size() ; i++)
if (this.fields.get(i) == aField)
res = true;
//
// if (res)
// this.currentWeekWorkedHours = this.currentWeekWorkedHours.add(aGroup.getClasses().get(aField));
//
//System.out.println("Res (Teacher.canTeach()) : --> " + res);
return res;
} |
9949f2ba-ef78-43f5-86a8-3e23313ebdf2 | 8 | public static void main(String... args) {
String makefileName;
String fileInfoName;
if (args.length == 0) {
usage();
}
makefileName = "Makefile";
fileInfoName = "fileinfo";
int a;
for (a = 0; a < args.length; a += 1) {
if (args[a].equals("-f")) {
a += 1;
if (a == args.length) {
usage();
} else {
makefileName = args[a];
}
} else if (args[a].equals("-D")) {
a += 1;
if (a == args.length) {
usage();
} else {
fileInfoName = args[a];
}
} else if (args[a].startsWith("-")) {
usage();
} else {
break;
}
}
ArrayList<String> targets = new ArrayList<String>();
for (; a < args.length; a += 1) {
targets.add(args[a]);
}
make(makefileName, fileInfoName, targets);
} |
4b74d9d0-d8f6-4e0a-a646-f8d722e76b85 | 5 | @Override
protected void Work(double time_sec)
{
if (IsAlive())
{
LifeCalc(time_sec);
if (thirst > 0)
{
if(target==null)
target = GetNearestObjectByMat(Enums.GMaterials.Woter);
if (target instanceof LandObject)
{
LandObject o = (LandObject)target;
Vec3d delta = new Vec3d(o.GetPos());
delta.sub(GetPos());
double dist = delta.length();
Vec3d pos = new Vec3d(o.GetPos());
if (dist < 2)
{
Move(0d);
Eat(target);
thirst = 0;
target = null;
}
else
{
LookTo(target);
Move(1d);
}
}
}
else
Move(0d);
}
} |
ad59be0f-d686-438e-a122-86d763706528 | 2 | public boolean superClassOf(ClassInfo son) {
while (son != this && son != null) {
son = son.getSuperclass();
}
return son == this;
} |
8d153d55-cb81-4036-b43f-0f45b0db32ae | 9 | public static void removebAndacFromStrinInplace(char[] str) {
int i = -1, j = 0;
int len = str.length;
while(j < len) {
if(j < len-1 && str[j] == 'a' && str[j+1] == 'c') {
j += 2;
} else if(str[j] == 'b') {
j++;
} else if(i >= 0 && str[i] == 'a' && str[j] == 'c') {
i--;
j++;
} else {
str[++i] = str[j++];
}
}
str[++i] = '\0';
System.out.println("string after removal of b and ac :");
for (int k = 0; str[k] != '\0'; k++) {
System.out.print(str[k]);
}
} |
0df30d89-01b8-4b6c-b10a-c7c3bdd1dc35 | 3 | public void coeff(double[][] dct_coef, int n) {
double sqrt_1 = 1.0 / Math.sqrt(2.0);
for (int i = 0; i < n; i++) {
dct_coef[0][i] = sqrt_1;
}
//Initialize coefficient
for (int i = 1; i < n; i++) {
for (int j = 0; j < n; j++) {
dct_coef[i][j] = this.a* Math.cos(i * Math.PI * (j + 0.5) / ((double) n));
}
}
} |
bae5c446-23da-4cf4-b4db-18c11e2b53fd | 9 | public boolean doTransformations() {
if (instr == null)
return false;
/*
* Do on the fly access$ transformation, since some further operations
* need this.
*/
if (instr instanceof InvokeOperator) {
Expression expr = ((InvokeOperator) instr).simplifyAccess();
if (expr != null)
instr = expr;
}
StructuredBlock last = flowBlock.lastModified;
return CreateNewConstructor.transform(this, last)
|| CreateAssignExpression.transform(this, last)
|| CreateExpression.transform(this, last)
|| CreatePrePostIncExpression.transform(this, last)
|| CreateIfThenElseOperator.create(this, last)
|| CreateConstantArray.transform(this, last)
|| CreateCheckNull.transformJavac(this, last);
} |
9bf84e3b-1a14-4450-bcb2-ec29ee3352d7 | 5 | public SQLManager(String context)
{
try
{
Context initCtx = new InitialContext();
Object obj = initCtx.lookup(context);
ds = (DataSource)obj;
if (ds == null)
throw new Exception("PAWS-Core: Failure to Create Datasource");
}
catch(SQLException ex)
{
while (ex != null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException ();
}
}
catch(NamingException ex) { ex.printStackTrace(); }
catch(Exception ex) { ex.printStackTrace(); }
}// end of -- SQLManager |
8da3f881-7d97-403d-b1cb-c539d522f52a | 8 | public static Object escape(Object original) {
if (original instanceof Character) {
char u = (char) ((Character) original);
int idx = "\b\t\n\f\r\"\'\\".indexOf(u);
if (idx >= 0)
return "\\" + "btnfr\"\'\\".charAt(idx);
if (u < 32)
return "\\" + Integer.toOctalString(u);
if (u > 126)
return "\\u" + String.format("%04X", (int) u);
return original;
} else if (original instanceof String) {
StringBuilder result = new StringBuilder();
for (char c : ((String) original).toCharArray())
result.append(escape(c));
return "\"" + result.toString() + "\"";
} else if (original.getClass().isArray()) {
StringBuilder result = new StringBuilder("[");
int len = Array.getLength(original);
for (int i = 0; i < len; i++)
result.append(" ").append(escape(Array.get(original, i)));
return result.append("]").toString();
}
return original;
} |
ad7039dc-7d4d-4f04-81d8-f1e2741d210a | 9 | public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
} |
b330368d-caf8-4101-80c6-bbe64442d8a5 | 6 | public void handleLine(List<String> line) throws Exception {
if (line.size() == 0)
return;
if (_trimValues) {
for (int i = 0; i < line.size(); i++)
line.set(i, line.get(i).trim());
}
if (!_initialized) {
readSchema(line);
_initialized = true;
} else {
readEntity(line);
}
_line++;
if (_verbose && _line % 1000 == 0)
System.out.println("entities=" + _line);
} |
e1058a59-54af-45da-8b07-498e5c00139b | 2 | public void testValues(int id) {
ArrayList<Float> stats = new ArrayList<Float>();
long time = System.currentTimeMillis();
for (Entry<Float, float[][]> ent : DB_ARRAY.entrySet()) {
float[][] dats = ent.getValue();
for (float[] d : dats) {
stats.add(d[id]);
}
}
StatInfo show = new StatInfo(stats, id);
// //show.setTitle(labels[id]);
System.out.println(show);
} |
e3a05709-88b7-4e5b-9fe1-f14da5601d1b | 4 | private String read_col(char[][] trans_block,int start_pos,int end_pos)
{
if(start_pos>end_pos)
return "";
StringBuilder sb=new StringBuilder();
int row=trans_block.length;
int col=trans_block[0].length;
assert(end_pos<col);
for(int i=1;i<row;i++)
{
for(int j=start_pos;j<=end_pos;j++)
{
if(trans_block[i][j]!='\0')
{
sb.append(trans_block[i][j]);
}
}
}
return sb.toString();
} |
e3c8f3ea-b52a-41ae-8f47-10469eabf721 | 4 | public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} |
912eb82a-e255-4c5c-960e-8b2d4b1903c1 | 0 | public CellTest() {
} |
c66a06a3-41ad-42b4-bedf-220ce3f20aab | 6 | public static List<List<Intersection>> getGroups(Board board, int player) {
int boardSize = board.boardSize;
int[][] intersections = board.intersections;
List<List<Intersection>> groups = new ArrayList<>();
for (int x = 0; x < boardSize; ++x) {
for (int y = 0; y < boardSize; ++y) {
if (intersections[x][y] == player) {
Intersection intersection = Intersection.getInstance(x, y);
boolean alreadyFound = false;
for (List<Intersection> group : groups) {
if (group.contains(intersection)) {
alreadyFound = true;
break;
}
}
if (!alreadyFound) {
groups.add(getGroup(board, x, y));
}
}
}
}
return groups;
} |
7dab0012-7acc-4182-af65-5631b0316229 | 5 | @Override
public Object getValueAt(int row, int column) {
switch(column) {
case ID : return listRdvAnciens.get(row).getId();
case MEDECIN : return listRdvAnciens.get(row).getMedecin();
case SPECIALISATION : return listRdvAnciens.get(row).getTypeRdv().getLabel();
case DATE : return ctrl.getSdf().format(listRdvAnciens.get(row).getDateRdv());
case HEURE : return listRdvAnciens.get(row).getHeure().getLabel();
default: return "NO DATA";
}
} |
a9e4da64-7190-46df-8fd3-468b28aeaf5d | 7 | public boolean isOnPF(int marginx,int marginy) {
if (!getTileBBox(temp_bbox_copy)) {
temp_bbox_copy.x = (int)x;
temp_bbox_copy.y = (int)y;
temp_bbox_copy.width = 0;
temp_bbox_copy.height = 0;
}
if (!pfwrapx) {
if (temp_bbox_copy.x+temp_bbox_copy.width < -marginx) return false;
if (temp_bbox_copy.x >pfwidth + marginx) return false;
}
if (!pfwrapy) {
if (temp_bbox_copy.y+temp_bbox_copy.height < -marginy) return false;
if (temp_bbox_copy.y > pfheight + marginy) return false;
}
return true;
} |
f3c6b8a9-7b6d-4516-88c7-0ed8a632a103 | 8 | public static List<FreightBean> getFreightBeans(String firstPageHtmlString) {
// TODO Auto-generated method stub
List<FreightBean> retFreightBeans = new ArrayList<FreightBean>();
try {
Parser divParser = new Parser(firstPageHtmlString);
NodeList divNodeList = divParser.parse(new HasAttributeFilter("class", "mainBox"));
if (divNodeList.size() == 0) {
return null;
}
int divNodeListSize = divNodeList.size();
for (int divNodelistIndex = 0; divNodelistIndex < divNodeListSize; divNodelistIndex++) {
Node divNode = divNodeList.elementAt(divNodelistIndex);
FreightBean freightBean = new FreightBean();
//get carrier
Parser carrierParser = new Parser(divNode.toHtml());
NodeList carrierNodeList = carrierParser.parse(new HasAttributeFilter("name", "accountName"));
if (carrierNodeList.size()==0) {
continue;
}
Node node = carrierNodeList.elementAt(0);
String carrierString = node.toPlainTextString().trim();
carrierString = Converter.sinotransbookingCarrier2SoushippingCarrier(carrierString);
if (carrierString == null) {
continue;
}
freightBean.setCarrier(carrierString);
//get price
Parser ulParser = new Parser(divNode.toHtml());
NodeList ulNodeList = ulParser.parse(new HasAttributeFilter("class","price"));
if (ulNodeList.size()==0) {
continue;
}
Node ulNode = ulNodeList.elementAt(0);
Parser liParser = new Parser(ulNode.toHtml());
NodeList liNodeList = liParser.parse(new TagNameFilter("li"));
int liNodeListSize = liNodeList.size();
if ( liNodeListSize != 3) {
continue;
}
// set FreightBean;
freightBean.setGp20(liNodeList.elementAt(0).toPlainTextString().trim());
freightBean.setGp40(liNodeList.elementAt(1).toPlainTextString().trim());
freightBean.setHq40(liNodeList.elementAt(2).toPlainTextString().trim());
//get valid data
Parser invalidParser = new Parser(divNode.toHtml());
NodeList invalidNodeList = invalidParser.parse(new HasAttributeFilter("name", "validTimeTo"));
if (invalidNodeList.size()==0) {
continue;
}
Node invalidnode = invalidNodeList.elementAt(0);
String invalidString = invalidnode.toPlainTextString().trim();
//SimpleDateFormat sdfDateFormat = new SimpleDateFormat("MM-dd");
//Date invalidDate = sdfDateFormat.parse(invalidString);
//sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//freightBean.setInvalid(sdfDateFormat.format(invalidDate));
Calendar cal = Calendar.getInstance();
invalidString = cal.get(Calendar.YEAR)+"-"+invalidString;
freightBean.setInvalid(invalidString);
SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date currentDate = new Date();
String validDate = sdfDateFormat.format(currentDate);
freightBean.setValid(validDate);
retFreightBeans.add(freightBean);
}
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retFreightBeans;
} |
df352bcb-b6dd-4835-a8e4-2dbf5ddab597 | 4 | public int setLeadership(String playerName, double leadership) {
String SQL = "UPDATE " + tblSkills + " SET " + "`leadership` = ? WHERE `player` LIKE ? ;";
int updateSuccessful = 0;
Connection con = getSQLConnection();
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQL);
statement.setDouble(1, leadership);
statement.setString(2, playerName);
updateSuccessful = statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
if (updateSuccessful == 0) {
SQL = "INSERT INTO " + tblSkills + " (`id` ,`player` ,`leadership` ,`loyalty`) VALUES (NULL , ?, ?, NULL);";
try {
statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
statement.setDouble(2, leadership);
updateSuccessful = statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
statement.close();
con.close();
} catch (SQLException e) {
}
leadershipCache.put(playerName, leadership);
return updateSuccessful;
} |
788d836a-ada2-4934-8d3f-4fb52153b0fa | 5 | public void initialise(World world) throws PatternFormatException
{
String[] cellParts = cells.split(" ");
for (int i=0;i<cellParts.length;i++)
{
char[] currCells = cellParts[i].toCharArray();
for (int j=0;j<currCells.length;j++)
{
if (currCells[j] != '1' && currCells[j] != '0') throw new PatternFormatException("Error: incorrect format of cell description");
if (currCells[j] == '1') world.setCell(j+startCol,i+startRow,true);
}
}
} |
b873fb90-05f9-4f5e-9a09-3ab16283b4ff | 4 | public static void simpleExpression(Item i, Operation actOperation) {
if(i.getSym() == Constants.SEMICOLON) {
return;
}
if(i.getSym() == Constants.PLUS) {
actOperation.setOperator(Constants.PLUS);
Expression.simpleExpression(Scanner.get(), actOperation);
}
else if(i.getSym() == Constants.MINUS) {
actOperation.setOperator(Constants.MINUS);
Expression.simpleExpression(Scanner.get(), actOperation);
}
else {
if(Expression.term(i, actOperation)) {
return;
}
}
} |
a44f0587-2169-44cf-9cec-747b8b8a8bab | 3 | public synchronized void update(long elapsedTime) {
if (frames.size() > 1) {
animTime += elapsedTime;
if (animTime >= totalDuration) {
animTime = animTime % totalDuration;
currFrameIndex = 0;
}
while (animTime > getFrame(currFrameIndex).endTime) {
currFrameIndex++;
}
}
} |
6c5f9c4e-729e-4433-b8c5-5d961644cfd6 | 4 | private boolean saveAs() {
FileDialog saveDialog = new FileDialog(shell, SWT.SAVE);
saveDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
saveDialog.setFilterNames(new String[] {"Address Books (*.adr)", "All Files "});
saveDialog.open();
String name = saveDialog.getFileName();
if(name.equals("")) return false;
if(name.indexOf(".adr") != name.length() - 4) {
name += ".adr";
}
File file = new File(saveDialog.getFilterPath(), name);
if(file.exists()) {
MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO);
box.setText(resAddressBook.getString("Save_as_title"));
box.setMessage(resAddressBook.getString("File") + file.getName()+" "+resAddressBook.getString("Query_overwrite"));
if(box.open() != SWT.YES) {
return false;
}
}
this.file = file;
return save();
} |
d40ea893-50eb-43ab-a7aa-ac113c8273cc | 4 | @Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
DefaultContentRect other = (DefaultContentRect) obj;
if (id != other.id) return false;
return true;
} |
948c7e42-7f80-4c51-bd89-7cbced62c308 | 1 | public void testRandomNumber() {
int number = MathUtils.getRandomNumber(0, 10);
assertTrue(number >= 0 && number < 10);
number = MathUtils.getRandomNumber(0, 1);
assertEquals(0, number);
number = MathUtils.getRandomNumber(10, 11);
assertEquals(10, number);
} |
5012c877-215a-4b42-8afd-544195a00bbc | 5 | public String formatWaitTimeLeft(Player p, int hour, int min, int sec){
if(p.hasPermission(DeityNether.OVERRIDE_PERMISSION)){
return cu.format(lang.getString("nether.time.wait.override").replaceAll("%header", getHeader()));
}else if(p.hasPermission(DeityNether.GENERAL_PERMISSION)){
String h = "";
String m = "";
String s = "";
if(hour != 0)
h = hour + "h";
if(min != 0)
m = min + "m";
if(sec != 0)
s = sec + "s";
return cu.format(lang.getString("nether.time.wait.time_left").replaceAll("%header", getHeader()))
.replaceAll("%numHour", h)
.replaceAll("%numMin", m)
.replaceAll("%numSec", s);
}else{
return cu.format(lang.getString("nether.time.wait.perm_error").replaceAll("%header", getHeader()));
}
} |
6ae83c90-0f39-4261-95d2-2ab289c3a7e5 | 2 | public static SquareTag getName(char tag) {
if (mapping == null) {
mapping = new HashMap<Character, SquareTag>();
for (SquareTag ut : values()) {
mapping.put(ut.tag, ut);
}
}
return mapping.get(tag);
} |
058ebe95-eb78-4fbb-bc07-6a9284d62aef | 7 | public void options(int option) {
switch (option) {
case 1: // Getting an order
for (;;) {
System.out.println();
printAll();
System.out.println("GETTING AN SPECIFIC ORDER\n");
System.out.println("Order id: ");
int orderId = input.nextInt();
input.nextLine();
retrievedOrder = eCommerceOrder.getOrder(new Order(orderId, null, -1, null, null, null, null, null, -1));
retrievedUser = eCommerceUser.getUser(new User(retrievedOrder.getUserId(), null, null, null, null, null, null));
System.out.println(retrievedOrder.toStringDate());
System.out.println(retrievedUser.toStringOrder() + "\n");
int total = 0, profit, cost, rrp;
productList.clear();
productList.addAll(eCommerceCart.getAllProducts(retrievedUser));
for (Product product : productList) {
cost = product.getCost();
rrp = product.getRRP();
profit = rrp - cost;
System.out.println(product.toStringCart() + ", Profit: " + profit);
total = total + cost;
}
System.out.println("\nTOTAL COST OF THE ORDER: " + total);
System.out.println("\n1. Get another order");
System.out.println("0. Go back to ORDER MENU");
option = input.nextInt();
input.nextLine();
if (option == 0) break;
else continue;
}
break;
case 2: // Get all orders
for (;;) {
System.out.println("GETTING ALL THE ORDERS\n");
printAll();
System.out.println("\n0. Go back to ORDER MENU");
option = input.nextInt();
input.nextLine();
if (option == 0) break;
else continue;
}
break;
}
System.out.println();
} |
394e9c96-2472-4b96-bd40-cfddda9f6e89 | 1 | public static GameModel loadFromFile(String filename)
throws MapLoaderException {
try (Scanner scanner = new Scanner(new File(filename))) {
GameField field = parseSquares(scanner);
parseBuildings(field, scanner);
parseUnits(field, scanner);
return new GameModel(field);
} catch (IOException e) {
throw new MapLoaderException(e.getMessage());
}
} |
00ba7b22-4074-49c9-a8a2-e96b8d06fc28 | 8 | public static final Vector<Object> loadClassList(final String defaultPath, String requestedPathList, final String subDir, final Class<?> ancestorC1, final boolean quiet)
{
final Vector<Object> v=new Vector<Object>();
int x=requestedPathList.indexOf(';');
while(x>=0)
{
String path=requestedPathList.substring(0,x).trim();
requestedPathList=requestedPathList.substring(x+1).trim();
if(path.equalsIgnoreCase("%default%"))
loadListToObj(v,defaultPath, ancestorC1, quiet);
else
{
if((subDir!=null)&&(subDir.length()>0))
path+=subDir;
loadListToObj(v,path,ancestorC1, quiet);
}
x=requestedPathList.indexOf(';');
}
if(requestedPathList.equalsIgnoreCase("%default%"))
loadListToObj(v,defaultPath, ancestorC1, quiet);
else
{
if((subDir!=null)&&(subDir.length()>0))
requestedPathList+=subDir;
loadListToObj(v,requestedPathList,ancestorC1, quiet);
}
return v;
} |
0bad0a31-8508-4b59-bea0-f37eed20106f | 5 | public static void main(String[] args) {
int[] array = { 18, -2, 29, 66, 23, 142, -34, 0, 13 };
System.out.println("Input Array: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("\n");
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
System.out.println("Sorted Array: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
} |
fc711bb9-b621-4de5-9513-702b93da820b | 6 | private void FallDown() {
if (fallSpeed <= 20)
fallSpeed = fallSpeed * 1.05;
for (int i = 0; i < collisionRange.size(); i++) {
if (getRectangle().intersects(collisionRange.get(i))) {
if (collisionRange.get(i).getY() > this.getY()
&& collisionRange.get(i).getY() <= this.getY()
+ this.getHeight()) {
this.setLocation(getX(), (int) (collisionRange.get(i)
.getY() - this.getHeight()));
fallSpeed = 3;
break;
}
}
if (i == collisionRange.size() - 1) {
setLocation(getX(), getY() + (int) fallSpeed);
}
}
} |
99b61fb9-de9e-4423-a313-6a206ac3a25c | 4 | public static int numberOfDoubledPawns(Board b, int color) {
int doubledPawns = 0;
for (int file = 0; file < b.board.length; file++) {
boolean firstPawnFound = false;
for (int rank = 0; rank < b.board[file].length; rank++) {
if (b.board[rank][file] == 1 * color) {
if (!firstPawnFound) {
firstPawnFound = true;
} else {
doubledPawns++;
break;
}
}
}
}
return doubledPawns;
} |
e3f7f1a4-0b9c-40cc-822b-3900afb7c28a | 6 | private void checkDiscipline() {
int period = (isRude() ? 1 : 2) * DECLINEPERIOD;
if (getAge() % period == 0) {
if (--shittingDiscipline < 0) {
shittingDiscipline = 0;
}
if (--excitingDiscipline < 0) {
excitingDiscipline = 0;
}
if (--furifuriDiscipline < 0) {
furifuriDiscipline = 0;
}
if (--messageDiscipline < 0) {
messageDiscipline = 0;
}
}
} |
0e771671-08eb-456c-a32b-c79fbc44c6fc | 6 | public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source.equals(menuItemExport)) {
// Menu Item "Export as CSV has been selected"
if (controller.getState() == ApplicationState.INITIALIZED_WITH_DATA) {
// Exportable Data is available
System.out.println("Save as CVS");
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
// save to file
controller.exportCSV(file);
}
} else {
// No exportable Data is available
JOptionPane.showMessageDialog(this, "No exportable Data.", "",
JOptionPane.ERROR_MESSAGE);
}
}
if (source.equals(connectButton)) {
// Connect Button has been clicked
int port = Integer.parseInt(portTextField.getText());
String ip = ipTextField1.getText()+"."
+ ipTextField2.getText()+"."
+ ipTextField3.getText()+"."
+ ipTextField4.getText();
// call Controller to connect
boolean result = controller.connect(ip, port);
System.out.println("connecting...");
if (result) {
// Data has been read in, updating CSV View
JOptionPane.showMessageDialog(this, "Data has been read", "",
JOptionPane.INFORMATION_MESSAGE);
textArea.setText(controller.getCSVData());
Data[] data = controller.parseCSV();
for (Data d : data) {
series_temp_p.add(d.getHours(), d.getPond_temp());
series_temp_w.add(d.getHours(), d.getWeather_temp());
series_light.add(d.getHours(), d.getLight());
}
} else {
// Connection Failed for some reason
JOptionPane.showMessageDialog(this, "Connection Failed", "",
JOptionPane.ERROR_MESSAGE);
}
}
} |
7cd3c666-1e46-490c-b3e9-085bf0cc51ba | 2 | public TileReader(){
Properties prop= new Properties();
try{
InputStream in = getClass().getResourceAsStream("/res/tiles.txt");
prop.load(in);
String stri[] = prop.getProperty("pictures").replaceAll("\\s+","").split(",");
Tile.scenePics= new Image[stri.length];
for(int i=0;i<stri.length;i++){
Tile.scenePics[i]=Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/res/"+stri[i]+".png"));
}
in.close();
}catch(IOException ex){
ex.printStackTrace();
}
} |
8257aea1-23da-4a00-9783-0faac13767c0 | 3 | public void play( ) {
synchronized( this ) {
if( !paused )
return;
double offset = ( System.currentTimeMillis( ) - pauseTime ) / 1000.0;
for( Message m : waitQueue )
m.bumpReceiveTime( offset );
for( Message m : sendQueue )
m.bumpSendTime( offset );
paused = false;
}
ssi.statusChanged( );
} |
f808644b-c8bc-4a17-bdd3-52d92c6d4b99 | 0 | @Override
public void hhhh() {
hello.hhhh();
} |
5ebf0171-fafc-45f3-b0be-2627dd2af361 | 1 | public OutputStream store(String name) throws IOException {
final File nm = forres(name);
File dir = nm.getParentFile();
final File tmp = new File(dir, nm.getName() + ".new");
dir.mkdirs();
tmp.delete();
OutputStream ret = new FilterOutputStream(new FileOutputStream(tmp)) {
public void close() throws IOException {
super.close();
if(!tmp.renameTo(nm)) {
/* Apparently Java doesn't support atomic
* renames on Windows... :-/ */
nm.delete();
tmp.renameTo(nm);
}
}
};
return(ret);
} |
8caf5e3a-c922-4e6d-a321-f8c148fc7c20 | 5 | public void render(GameContainer arg0, StateBasedGame arg1, Graphics arg2)
throws SlickException {
page.render();
land.draw(4,4,848,759);
if (dragHeadingState) {
arg2.setColor(Color.red);
shapeRenderer.fill(shape);
}
Iterator i = airportList.iterator();
while (i.hasNext()) {
((Airport) i.getCurrent()).draw();
i.next();
}
if (selectedPlane != null) {
//Input input = arg0.getInput();
//Line line = new Line(input.getMouseX(), input.getMouseY(), selectedPlane.getCenterX(), selectedPlane.getCenterY());
//ShapeRenderer.draw(line);
}
if (!planeList.isEmpty()) {
i = planeList.iterator();
while (i.hasNext()) {
((Airplane) i.getCurrent()).draw();
i.next();
}
}
//arg1.draw(arrow);
//shapeRenderer.draw(arrow);
//shapeRenderer.fill(arrow);
//arg1.fill(arrow);
//arg1.draw(polygon);
} |
a2bf4d07-0e7d-469d-98a2-6f01fc4e8c7a | 2 | public ArrayList<Coche> searchCoches(String mat){
ArrayList<Coche> cList = new ArrayList();
ArrayList<Coche> res = new ArrayList();
cList.addAll(cjtCoches.values());
for(int i=0; i<cList.size(); ++i){
if(cList.get(i).getMatricula().contains(mat))
res.add(cList.get(i));
}
return res;
} |
12d5a345-60a6-4f87-85be-1c247264ced5 | 9 | private Future<?> display(final boolean error) {
final String msg = this.getMessage();
if (error) {
getLogger().log(Level.SEVERE, null, this);
} else {
if (this.getCause() != null) {
getLogger().log(Level.INFO, null, this);
}
}
if (!GraphicsEnvironment.isHeadless() || forceUI) {
if (SwingUtilities.isEventDispatchThread()) {
showMsg(msg, error);
} else {
final FutureTask<?> run = new FutureTask<Object>(new Runnable() {
public void run() {
showMsg(msg, error);
}
}, null);
if (error) {
try {
SwingUtilities.invokeAndWait(run);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
} else {
SwingUtilities.invokeLater(run);
}
return run;
}
}
return null;
} |
648e45fb-91c8-4ac6-8d46-220f9594a4d9 | 2 | public static CharSeq ApplyToAll1 (Main.AA1 fun, CharSeq s)
{
CharSeqIt csi = new CharSeqIt(s); //initialize iterator
String NewSeq = ""; //initialize string to stick th result of fun.go into
char currentval = 0; //current char
while(csi.hasNext())
{
try
{
currentval = csi.next(); //currentval = current value
NewSeq = NewSeq + fun.go(currentval); //fun.go results go into NewSeq
}catch (UsingIteratorPastEndException e){}
}//end while
return new CharSeq(NewSeq);
}//end ApplyToAll1 |
b0795d50-9857-4670-af9e-33d885a16ec9 | 3 | public void addProperty(Space p) {
property.add(p);
// Change the property's font color to player's color
if(number == 1)
p.buttLabel.setForeground(GameBoard.PLAYER1);
else if(number == 2)
p.buttLabel.setForeground(GameBoard.PLAYER2);
else if(number == 3)
p.buttLabel.setForeground(GameBoard.PLAYER3);
else
p.buttLabel.setForeground(GameBoard.PLAYER4);
// Make it bold too
Font font = new Font(GameBoard.FONT_STYLE, Font.BOLD, 16);
p.buttLabel.setFont(font);
} |
a04ff6f7-2f22-4760-9320-cbebe43520ad | 0 | public Set<Being> getBeings() {
return new HashSet<Being>(beings);
} |
fe75f967-7ada-4980-9756-b44215055c6e | 9 | private void addToCounts(Instance instance) {
double [] countsPointer;
double [] countsNoClassPointer;
if(instance.classIsMissing())
return; // ignore instances with missing class
int classVal = (int)instance.classValue();
double weight = instance.weight();
m_ClassCounts[classVal] += weight;
m_SumInstances += weight;
// store instance's att val indexes in an array, b/c accessing it
// in loop(s) is more efficient
int [] attIndex = new int[m_NumAttributes];
for(int i = 0; i < m_NumAttributes; i++) {
if(i == m_ClassIndex)
attIndex[i] = -1; // we don't use the class attribute in counts
else {
if(instance.isMissing(i))
attIndex[i] = m_StartAttIndex[i] + m_NumAttValues[i];
else
attIndex[i] = m_StartAttIndex[i] + (int)instance.value(i);
}
}
for(int Att1 = 0; Att1 < m_NumAttributes; Att1++) {
if(attIndex[Att1] == -1)
continue; // avoid pointless looping as Att1 is currently the class attribute
m_Frequencies[attIndex[Att1]] += weight;
// if this is a missing value, we don't want to increase sumforcounts
if(!instance.isMissing(Att1))
m_SumForCounts[classVal][Att1] += weight;
// save time by referencing this now, rather than repeatedly in the loop
countsPointer = m_CondiCounts[classVal][attIndex[Att1]];
countsNoClassPointer = m_CondiCountsNoClass[attIndex[Att1]];
for(int Att2 = 0; Att2 < m_NumAttributes; Att2++) {
if(attIndex[Att2] != -1) {
countsPointer[attIndex[Att2]] += weight;
countsNoClassPointer[attIndex[Att2]] += weight;
}
}
}
} |
3718e63f-8df2-4c5f-8766-9a7c9cc6256b | 8 | @Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getActionCommand() == "exportLogins"){
ExportFile export = new ExportFile("usuariosOnline.txt");
export.export(textlogin.getText());
} else if (arg0.getActionCommand() == "exportInfo"){
ExportFile export = new ExportFile("infoServidor.txt");
export.export(textInfo.getText());
} else if (arg0.getActionCommand() == "cerrar"){
try {
try {
Naming.unbind("rmi://" + reg0 + ":" + ServicioAutenticacionInterface.PUERTO + "/" + ServicioAutenticacionInterface.NAME);
Naming.unbind("rmi://" + reg1 + ":" + ServicioGestorInterface.PUERTO + "/" + ServicioGestorInterface.NAME);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
} else if (arg0.getActionCommand() == "info"){
} else if (arg0.getActionCommand() == "login"){
try {
textlogin.setText(gestor.getUsuariosConectados());
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
c33aa55d-eeb8-4e5c-aab7-647b19e85e5c | 1 | @Override
public void free() {
try {
fileChannel.truncate(0);
} catch (IOException e){/**/}
} |
d30d3742-2e1d-40ee-845e-1d0c994bf401 | 2 | public static void main(String args[]){
long start = System.currentTimeMillis();
PrintWriter outputStream = null;
try{
outputStream =
new PrintWriter (new FileOutputStream("myIntegers.txt"));
}
catch(FileNotFoundException e){
System.out.println("Error opening the file.");
}
for(int i = 1; i <= 1000000; i++){
outputStream.println(i);
}
outputStream.close();
long end = System.currentTimeMillis();
System.out.println("Took: " + ((end - start)) + "millis");
} |
58a6a1ee-d4aa-4015-b638-5e9efc5731c6 | 7 | @Override
public String perform(HttpServletRequest request) {
List<String> errors = new ArrayList<String>();
HttpSession session = request.getSession();
request.setAttribute("errors", errors);
String success;
try {
CreateUserForm form = formBeanFactory.create(request);
request.setAttribute("form", form);
request.setAttribute("userType", Global.getUserType(session));
request.setAttribute("username", Global.getUserName(session));
logger.debug("CreateUserAction called");
if (!form.isPresent())
return "createUser.jsp";
errors.addAll(form.getValidationErrors());
if (errors.size() > 0)
return "createUser.jsp";
if (form.getUserType().equals("Employee")) {
if (Init.employeeDAO.lookup(form.getUsername()) == null) {
saveEmployee(form);
} else {
errors.add("Employee with the same username already exists, change the username and try again.");
return "createUser.jsp";
}
} else {
if (Init.customerDAO.lookup(form.getUsername()) == null) {
saveCustomer(form);
} else {
errors.add("Customer with the same username already exists, change the username and try again.");
return "createUser.jsp";
}
}
success = "The user account was created succesfully";
request.setAttribute("success", success);
} catch (MyDAOException e) {
logger.error(e.getMessage());
errors.add("Internal error, please try again later.");
return "createUser.jsp";
} catch (FormBeanException e) {
logger.error(e.getMessage());
errors.add("Internal error, please try again later.");
return "createUser.jsp";
}
return "createUser.jsp";
} |
dca09b38-e32e-493a-b8a9-46e611cf7e64 | 5 | @Test
public void findsCorrectUnobstructedPoints()
{
VertexContainer vc = new VertexContainer();
Vertex src = vc.addVertex(0, 0);
Point p1 = vc.addPoint(-1, -4);
Point p2 = vc.addPoint(2, -1);
Point p3 = vc.addPoint(3, 3);
Point p4 = vc.addPoint(-4, -3);
Point p5 = vc.addPoint(-4, 3);
addTriangle(p1, vc.addPoint(2, -4), p2);
addTriangle(vc.addPoint(3, -3), vc.addPoint(5, 0), p3);
addTriangle(vc.addPoint(-7, 5), vc.addPoint(7, 5), vc.addPoint(0, 7));
addTriangle(p4, p5, vc.addPoint(-7, 0));
addTriangle(vc.addPoint(-8, 2), vc.addPoint(-9, 3), vc.addPoint(-9, 1));
addTriangle(vc.addPoint(-8, -3), vc.addPoint(-8, -1), vc.addPoint(-9, -2));
LinkedList<Vertex> list =
AngleElimination.findUnobstructedPoints(src, vc.getVertices().toLinkedList(), null);
Tree<Vertex> tree = new Tree<>(new VertexComparator());
while (list.hasNext())
tree.add(list.getNext());
assertTrue(tree.contains(p1) && tree.contains(p2) &&
tree.contains(p3) && tree.contains(p4) && tree.contains(p5));
} |
6361d017-d93c-4aac-b8c8-6c8d165fda1a | 3 | public void addService(Service newService){
boolean exists = false;
for (Service service : services) {
if(service.getName().equalsIgnoreCase(newService.getName())){
exists = true;
}
}
if(!exists){
services.add(newService);
}
} |
431c1c26-9f97-4a06-b961-48d478bdd967 | 8 | private void createAnd(String in1, String in2, String out)
{
AndGate and = new AndGate();
// Connect the first input
// Check if the in wire is an input
if (stringToInput.containsKey(in1))
{
Wire inWire = new Wire();
stringToInput.get(in1).connectOutput(inWire);
and.connectInput(inWire);
}
// Check if the in wire is an output
else if (stringToOutput.containsKey(in1))
{
Wire inWire = new Wire();
stringToOutput.get(in1).connectOutput(inWire);
and.connectInput(inWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(in1))
and.connectInput(stringToWire.get(in1));
else
MainFrame.showError("Error, the wire " + in1
+ " isn't in the circuit");
// Connect the Second input
// Check if the in2 wire is an input
if (stringToInput.containsKey(in2))
{
Wire inWire = new Wire();
stringToInput.get(in2).connectOutput(inWire);
and.connectInput(inWire);
}
// Check if the in wire is an output
else if (stringToOutput.containsKey(in2))
{
Wire inWire = new Wire();
stringToOutput.get(in2).connectOutput(inWire);
and.connectInput(inWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(in2))
and.connectInput(stringToWire.get(in2));
else
MainFrame.showError("Error, the wire " + in2
+ " isn't in the circuit");
// Connect the output
// Check if the in wire is an output
if (stringToOutput.containsKey(out))
{
Wire outWire = new Wire();
stringToOutput.get(out).connectInput(outWire);
and.connectOutput(outWire);
}
// Check if the in wire is just a wire already known to the circuit
else if (stringToWire.containsKey(out))
and.connectOutput(stringToWire.get(out));
else
MainFrame.showError("Error, the wire " + out
+ " isn't in the circuit");
gates.add(and);
} |
bf74ff1b-a921-455c-8939-058b191716a5 | 6 | private String getFile(String link)
{
String download = null;
try
{
// Open a connection to the page
URL url = new URL(link);
URLConnection urlConn = url.openConnection();
InputStreamReader inStream = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(inStream);
int counter = 0;
String line;
while((line = buff.readLine()) != null)
{
counter++;
// Search for the download link
if(line.contains("<li class=\"user-action user-action-download\">"))
{
// Get the raw link
download = line.split("<a href=\"")[1].split("\">Download</a>")[0];
}
// Search for size
else if (line.contains("<dt>Size</dt>"))
{
sizeLine = counter+1;
}
else if(counter == sizeLine)
{
String size = line.replaceAll("<dd>", "").replaceAll("</dd>", "");
multiplier = size.contains("MiB") ? 1048576 : 1024;
size = size.replace(" KiB", "").replace(" MiB", "");
totalSize = (long)(Double.parseDouble(size)*multiplier);
}
}
urlConn = null;
inStream = null;
buff.close();
buff = null;
}
catch (Exception ex)
{
ex.printStackTrace();
plugin.getLogger().warning("The auto-updater tried to contact dev.bukkit.org, but was unsuccessful.");
result = Updater.UpdateResult.FAIL_DBO;
return null;
}
return download;
} |
20784703-3a1c-4711-8e7a-7c539b76cbab | 4 | public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
} |
699f4f5c-9328-4b70-ace7-11819e1800b0 | 0 | public void matchesContainsMethodWithNoArguments()
{
Filter containsMethod = containsMethod( "usingDefaultClassLoader" );
assert containsMethod.matches( ClassLoaderBuilder.class );
assert !containsMethod.matches( Filter.class );
} |
236b929f-6f40-45ba-99b1-bbda6a81b333 | 3 | public boolean isBalanced2(BTPosition<T> current)
throws InvalidPositionException {
if (current == null)
return true;
int diff = treeHeight(current.getLeft())
- treeHeight(current.getRight());
if (Math.abs(diff) > 1)
return false;
else
return isBalanced(current.getLeft())
&& isBalanced(current.getRight());
} |
8236e009-4ff2-43bc-8402-bdbdde0d7633 | 0 | public final void addDragListeners(final Node n) {
n.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
startDragX = me.getSceneX();
startDragY = me.getSceneY();
root.setStyle("-fx-opacity:.7;");
}
});
n.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
root.setStyle("-fx-opacity:1;");
}
});
n.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
stage.setX(me.getScreenX() - startDragX);
stage.setY(me.getScreenY() - startDragY);
}
});
} |
494190b8-20a8-464d-b698-1c9e2748c3db | 3 | private ArrayList<Integer> generateUpDownDestinations( int position, int[] directions ) {
ArrayList<Integer> destinations = new ArrayList<Integer>();
for ( int direction : directions ) {
for ( int i = 1; isValidDestination( position + i*direction ); i++ ) {
if ( enemyPieceAt( position + i*direction ) ) {
destinations.add( position + i*direction );
break;
}
destinations.add( position + i*direction );
}
}
return ( destinations );
} |
99bd84bc-593d-4c10-8f11-edc31192989d | 6 | public void disablePlayerOneSpaces()
{
for (int x = 0; x < checkersSpaces.length; x++) {
for (int y = 0; y < checkersSpaces.length; y++) {
if(checkersSpaces[x][y].getIcon() != null && checkersSpaces[x][y].getIcon().equals(playerOneCheckerPiece))
{
checkersSpaces[x][y].setDisabledIcon(playerOneCheckerPiece);
checkersSpaces[x][y].setEnabled(false);
}
else if(checkersSpaces[x][y].getIcon() != null && checkersSpaces[x][y].getIcon().equals(playerOneKingCheckerPiece))
{
checkersSpaces[x][y].setDisabledIcon(playerOneKingCheckerPiece);
checkersSpaces[x][y].setEnabled(false);
}
}
}
} |
c1f1fd54-e5c0-4837-948a-5f7b6e92dd5c | 3 | public int cellAt(int x, int y) {
for (int i = 0; i < body.size(); i ++) {
if (body.get(i).x == x && body.get(i).y == y) {
return i;
}
}
return -1;
} |
f44c6045-aad0-46bd-a6b5-caa5895ca9ef | 9 | public static HereditaryProperty merge2(final HereditaryProperty a, final HereditaryProperty b) {
return new HereditaryProperty() {
@Override
public Collection<Permutation> getBasis() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Permutation> getBasisTo(int n) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isSatisfiedBy(Permutation p) {
return isSatisfiedBy(p.elements);
}
@Override
public boolean isSatisfiedBy(int[] values) {
int n = values.length;
if (n > 31) {
throw new UnsupportedOperationException("Not supported on sequences of length 32 or greater");
}
if (!a.isSatisfiedBy(new int[]{0})) {
return b.isSatisfiedBy(values);
}
if (!b.isSatisfiedBy(new int[]{0})) {
return a.isSatisfiedBy(values);
}
HashSet<Integer> thisLevel = new HashSet<Integer>();
for (int i = 0; i < values.length; i++) {
thisLevel.add(1 << i);
}
int k = 2;
while (!thisLevel.isEmpty() && k < values.length) {
for(int[] c : new Combinations(values.length, k)) {
HashSet<Integer> nextLevel = new HashSet<Integer>();
int cCode = testCombination(c, thisLevel);
if (cCode > 0) nextLevel.add(cCode);
}
}
return false;
}
private int testCombination(int[] c, HashSet<Integer> thisLevel) {
int cCode = 0;
for(int i : c) cCode += (1 << i);
return cCode;
}
};
} |
f67665f4-97be-4ed8-8052-7822dd79c2da | 2 | public void setLocation(int x, int y) {
List l = getWorld().getObjectsAt(x, y, null);
for (int i = 0; i < l.size(); i++) {
Actor actor = (Actor) l.get(i);
if (actor != this) {getWorld().removeObject(actor);}
}
super.setLocation(x,y);
} |
3eecb7c8-8cd1-4ac7-9ba9-e751e740ba9d | 4 | public void setValueAt(Object value, int row, int col) {
try {
switch (col) {
case 0 :
try {
Date d = SBStringUtils.dateFormatShort.parse(value.toString());
myRecipe.setNoteDate(row, d);
} catch (ParseException e) {
System.out.println("Unable to parse " + value.toString());
}
break;
case 1 :
myRecipe.setNoteType(row, value.toString());
break;
}
} catch (Exception e) {
};
fireTableCellUpdated(row, col);
fireTableDataChanged();
} |
af9f41e6-7b3b-4591-b49c-6ea7d0ac3b76 | 5 | private static boolean modifySchedule(Schedule bean, PreparedStatement stmt, String field) throws SQLException{
String sql = "UPDATE prescriptions SET "+field+"= ? WHERE work_day = ? and username = ?";
stmt = conn.prepareStatement(sql);
if(field.toLowerCase().equals("work_from"))
stmt.setTime(1, bean.getFrom());
if(field.toLowerCase().equals("work_till"))
stmt.setTime(1, bean.getTo());
if(field.toLowerCase().equals("hourly_rate"));
stmt.setBigDecimal(1, bean.getHourRate());
if(field.toLowerCase().equals("vac_day"))
stmt.setInt(1, bean.getVacationDays());
stmt.setDate(2, bean.getWorkDay());
stmt.setString(3, bean.getUsername());
int affected = stmt.executeUpdate();
if (affected == 1) {
System.out.println("prescription info updated");
return true;
} else {
System.out.println("error: no update applied");
return false;
}
} |
c4924f00-5870-4774-9d1d-33ab6aedbfcb | 5 | @Override
public void run( ) {
this.running = true;
while ( this.running ) {
if ( this.listeners.size( ) != 0 ) {
final EventType elem = this.queue.poll( );
if ( elem != null )
for (final IListener<EventType> li : this.listeners)
li.handle(elem);
}
try {
Thread.sleep(5);
} catch ( final InterruptedException e ) {
e.printStackTrace( );
}
}
} |
7dbcbdc3-360a-4621-a0fa-a07c9ba34056 | 1 | public void addInvalidConstantName(String constantName) {
if (invalidConstantNames == null) {
invalidConstantNames = new ArrayList();
}
invalidConstantNames.add(constantName);
} |
896e581c-7e26-4650-921d-996e27563771 | 1 | private int getMaxStats(int idx){
int max = stats[PROGRESSION]+bonusStart[idx];
if(stats[PROGRESSION] <= 1) return bonusStart[idx];
else return (int)(max*coeffStats[idx]);
} |
1d3915e0-f261-4cd3-bb0e-a9d92b96eb55 | 3 | public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.browse){
Chooser frame = new Chooser();
url.setText(frame.fileName);
filePath = frame.fileName;
}
else if (e.getSource() == this.checkUrl){
new Listview("List of bad URLs", new CheckUrls(filePath).get_list(), filePath, atf,this).setVisible(true);
this.setVisible(false);
}
else if (e.getSource() == this.listChecked){
new Checkedview("List of checked files", atf,this).setVisible(true);
this.setVisible(false);
}
} |
4a5c8d17-b48e-4168-b048-8892f7c97e7a | 2 | public static void stop() {
if (task != null && !task.isDone()) {
task.cancel(true);
task = null;
BmLog.info("TestInfoController is stopped");
}
} |
8a04aebf-9ff0-421c-bd07-bb2446e584ad | 5 | public void handleRequest(ServerRequestEvent event)
{
JSONObject request = event.getRequest();
try
{
if(!ChunkyTransactions.getInstance().getAPI().checkAPIKey(request.getString("APIKey")))
{
ChunkyTransactions.getInstance().getMessage().debug("Connection Refused!");
DataOutputStream out = new DataOutputStream(this.getSocket().getOutputStream());
out.writeBytes(APICodes.FORBIDDEN.toString());
}
try
{
ChunkyTransactions.getInstance().getMessage().debug("Connection Accepted");
DataOutputStream out = new DataOutputStream(this.getSocket().getOutputStream());
out.writeBytes(ChunkyTransactions.getInstance().getRequestManager().getRequest(request.getString("request"), "ServerRequest(" + this.getSocket().getInetAddress() + ")").perform(request).toString());
}
catch (JSONException e)
{
DataOutputStream out = new DataOutputStream(this.getSocket().getOutputStream());
out.writeBytes(APICodes.INTERNAL_SERVER_ERROR.toString());
ChunkyTransactions.getInstance().getMessage().spitError(e);
}
catch (NullRequestException e)
{
DataOutputStream out = new DataOutputStream(this.getSocket().getOutputStream());
out.writeBytes(APICodes.NO_CONTENT.toString());
ChunkyTransactions.getInstance().getMessage().spitError(e);
}
catch (UnknownRequestException e)
{
DataOutputStream out = new DataOutputStream(this.getSocket().getOutputStream());
out.writeBytes(APICodes.NOT_FOUND.toString());
ChunkyTransactions.getInstance().getMessage().spitError(e);
}
this.getSocket().close();
}
catch (IOException e)
{
ChunkyTransactions.getInstance().getMessage().spitError(e);
}
} |
8917988d-c440-4dda-bd48-69e2e46ff355 | 5 | private Object handleNote(Object tos, String id, String ref) {
if (tos instanceof NoteContainer) {
if (ref == null) {
Note note = new Note();
((NoteContainer)tos).addNote(note);
return note;
}
else {
NoteRef noteRef = new NoteRef();
noteRef.setRef(ref);
((NoteContainer)tos).addNoteRef(noteRef);
return noteRef;
}
}
else if (tos instanceof Gedcom) {
Note note = new Note();
if (id != null) {
note.setId(id);
}
if (ref != null) {
// ref is invalid here, so store it as value - another geni-ism
note.setValue("@"+ref+"@");
}
((Gedcom)tos).addNote(note);
return note;
}
return null;
} |
6196a862-258b-4678-b9cf-a58601d75fa1 | 3 | public List<String> findSubstring(String s, List<String> allKUniversals) {
List<String> foundSubstrings = new ArrayList<String>();
for (String string : allKUniversals) {
int length = s.length();
if (string.substring(0, length).equals(s) && !string.equals(s)) {
foundSubstrings.add(string);
}
}
return foundSubstrings;
} |
bf888a7b-5c30-4117-98a5-50c39161eff1 | 5 | @Override
public void mousePressed(MouseEvent e) {
if ( e.getSource() instanceof PlacementTile) {
//Creation et initialisation de la tuile
PlacementTile pt = (PlacementTile)e.getSource();
Tile tile = new Tile(selected.getType(), pt.getOrientation());
tile.setLocation(pt.getX(), pt.getY());
//Envoi du placement au serveur
try { client.sendMessage("POSET:"+ pt.getNeighboor().getType() + ":" + pt.getPosition() + ":" + pt.getOrientation()); } catch ( IOException ex) { System.out.println("Failed!"); }
this.addTile(tile); //Ajout au plateau
this.removeAllPlacementTile(); //Retrait des PlacementTile
this.selected.setSelectedTile(null); //Retrait de la selection
}
//Placement d'un champ
else if ( e.getSource() instanceof Tile) {
Tile t = (Tile)e.getSource();
//Envoi du placement au serveur
try {
client.sendMessage("FIELD:"+ t.getType());
} catch ( IOException ex) { System.out.println("Failed!"); }
}
//Clic sur une zone du plateau
else if ( e.getSource() == this.board) {
this.isBoardSelected = true;
//Position de la souris au clic
this.cX = e.getX();
this.cY = e.getY();
}
} |
1a7c4840-07c1-4433-8cd2-756ae1714ea3 | 7 | @Override
public double timeToReach(Node startNode, Node endNode, Message msg) {
// TODO Auto-generated method stub
double dist = startNode.getPosition().distanceTo(endNode.getPosition());
/* Link rate | time arrive mSec | dist
* ----------------------------------------------------
* 11 | 2542 | 399
* 5.5 | 3673 | 531
* 2 | 7634 | 669
* 1 | 13858 | 796
* */
//System.out.println("MTM distancia: "+Math.sqrt(dist));
System.out.println("MTM Sem sqrt distancia: "+dist);
if(dist < 399) return 0.002542;
if(dist >= 399 && dist < 531) return 0.003673;
if(dist >= 531 && dist < 669) return 0.007634;
if(dist >= 669 && dist <= 796) return 0.013858;
return 1;
} |
60de913b-096a-4838-b92a-cd3087a05da0 | 7 | public void bouwSpeelveld() throws AngryTanksException { //bouwt het speelveld op basis van level
if(!isSpeelveldBouwKlaar()) throw new AngryTanksException("Speelveld kan niet gebouwd worden. Stel eerst een level in.");
laatsteSchot = new Schot(Orientatie.RECHTS, 0, 0, new Positie(0,0), 0, new HashMap<String, HashSet<Positie>>()); //dummy schot
schutterAPositie = null;
schutterBPositie = null;
obstructie = new Obstructie();
schutterAZone = new HashSet<Positie>();
schutterBZone = new HashSet<Positie>();
HashMap<Positie, Onderdeel> opbouw = new HashMap<Positie, Onderdeel>(level.getOpbouw());
for(Positie p : opbouw.keySet()){
if(opbouw.get(p) == Onderdeel.OBSTRUCTIE){
obstructie.add(new Positie(p.getX(), p.getY()));
} else if(opbouw.get(p) == Onderdeel.SCHUTTER_A){
schutterAPositie = new Positie(p.getX(), p.getY());
schutterAZone.add(new Positie(p.getX(), p.getY()));
} else if(opbouw.get(p) == Onderdeel.SCHUTTER_B) {
schutterBPositie = new Positie(p.getX(), p.getY());
schutterBZone.add(new Positie(p.getX(), p.getY()));
} else if(opbouw.get(p) == Onderdeel.SCHUTTER_A_ZONE){
schutterAZone.add(new Positie(p.getX(), p.getY()));
} else if(opbouw.get(p) == Onderdeel.SCHUTTER_B_ZONE){
schutterBZone.add(new Positie(p.getX(), p.getY()));
}
}
} |
21b464d4-d2bb-490c-bdc3-504174ee43d1 | 1 | @Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
} |
28376114-5cd9-4a4c-970c-3730640b223c | 1 | private void renderPlayerInventory(Graphics2D graphics) {
for (int i = 0; i < objectTron.getActivePlayerInfo().getInventoryItems().size(); i++) {
int xCoordinate = startPointXCoordinate + (i%3 * 40);
int yCoordinate = startPointYCoordinate + 350 + (i/3 * 40);
List<ElementInfo> item = new ArrayList<ElementInfo>();
item.add(objectTron.getActivePlayerInfo().getInventoryItems().get(i));
drawGameElement(graphics, item, new Position(xCoordinate, yCoordinate));
}
} |
673c1ef9-94d2-4cd8-9c8f-6f1f8bd58024 | 4 | @Test
public void savenowtest() throws ClassNotFoundException, IOException{
try{
@SuppressWarnings("resource")
ObjectInputStream osb = new ObjectInputStream(new FileInputStream("bookcollection.txt"));///óϾ , Ͼ׳ϴ° ҽ߰
bookcollectb.setBookCount(osb.readInt());
bookcollectb.collectionb.clear();
for( int i= 0; i< bookcollectb.getBookCount();i++){
Book ms = (Book)osb.readObject();
bookcollectb.collectionb.add(i,ms);
}
}catch(IOException e){
}
bookcollectb.savenow();
int count=0;
ObjectInputStream osb = new ObjectInputStream(new FileInputStream("bookcollection.txt"));///óϾ , Ͼ׳ϴ° ҽ߰
int endnnum = osb.readInt();
for( int i= 0; i< endnnum;i++){
Book ms = (Book)osb.readObject();
if(bookcollectb.collectionb.elementAt(i).equals(ms) != true)
count++;
}
assertTrue(endnnum == count);
} |
df6dc65b-2be3-4941-adf8-457f6bd05097 | 5 | private boolean camposNecesarios () {
boolean rta;
if ((jTextField1.getText().equals("")))
{
JOptionPane.showMessageDialog(null, "Complete el campo nombre!","Atención",JOptionPane.WARNING_MESSAGE);
jTextField1.requestFocus();
rta = false;
}
else{
if ((jTextField2.getText().equals("")))
{
jTextField2.requestFocus();
JOptionPane.showMessageDialog(null, "Complete el campo apellido!","Atención",JOptionPane.WARNING_MESSAGE);
rta = false;
}
else{
if ((jTextField3.getText().equals("")))
{
jTextField3.requestFocus();
JOptionPane.showMessageDialog(null, "Complete el campo usuario!","Atención",JOptionPane.WARNING_MESSAGE);
rta = false;
}
else{
if (((jPasswordField1.getText().equals("")))||((jPasswordField2.getText().equals(""))))
{
jTextField3.requestFocus();
JOptionPane.showMessageDialog(null, "Complete el campo contraseña!","Atención",JOptionPane.WARNING_MESSAGE);
rta = false;
}
else{
rta = true;
}
}
}
}
return rta;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.