method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
eee689e7-e686-4fe3-9426-70cf53da835c | 9 | @Override
public void tick(LinkedList<GameObject> lstObj) {
super.tick();
if (this.isAlive()) {
velX = Math.signum(velX) * 3;
walkLeft.runAnimation();
walkRight.runAnimation();
for (GameObject tmpObj : lstObj) {
if (this != tmpObj) {
if (getBounds().intersects(tmpObj.getBounds())) {
if (tmpObj.getId() == ObjectId.Dirt ||
tmpObj.getId() == ObjectId.Grass ||
tmpObj.getId() == ObjectId.Stone ||
tmpObj.getId() == ObjectId.Ice ||
tmpObj.getId() == ObjectId.Mob) {
velX = -velX;
}
}
}
}
} else {
lstObj.remove(this);
}
} |
86b06d8a-8866-4b61-836b-f5cfb283cd50 | 1 | public boolean method284(int arg0, byte arg1, int arg2, int arg3, Entity entity, int arg5, int arg6, int arg7, int arg8, int arg9) {
if (entity == null) {
return true;
} else {
int i2 = arg9 * 128 + 64 * arg5;
int j2 = arg8 * 128 + 64 * arg3;
return method287(arg6, arg9, arg8, arg5, arg3, i2, j2, arg2, entity, arg7, false, arg0, arg1);
}
} |
24c8e9fa-834d-4d47-9341-d6e1ee291888 | 8 | public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s);
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
if (n == 0 && d == 0 && r == 0) {
break;
}
ArrayList<Integer> morning = new ArrayList<Integer>();
ArrayList<Integer> nigth = new ArrayList<Integer>();
StringTokenizer sc = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
morning.add(Integer.parseInt(sc.nextToken()));
}
sc = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
nigth.add(Integer.parseInt(sc.nextToken()));
}
Collections.sort(morning);
Collections.sort(nigth);
int m = 0;
int t = 0;
for (int i = 0; i < n; i++) {
m = morning.get(i) + nigth.get(n - 1 - i);
if (m > d) {
t += (m - d) * r;
}
}
System.out.println(t);
}
} |
d721691c-867f-4f52-bc49-72765dbde4ec | 9 | public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
if (intervals.isEmpty()) {
intervals.add(newInterval);
return intervals;
}
List<Interval> result = new ArrayList<>(intervals.size());
Iterator<Interval> iter = intervals.iterator();
Interval current = iter.next();
while (current != null && newInterval.start > current.end)
{
result.add(current);
if (iter.hasNext()) {
current = iter.next();
} else {
current = null;
}
}
while (current != null && newInterval.end >= current.start) {
newInterval.start = Math.min(newInterval.start, current.start);
newInterval.end = Math.max(newInterval.end, current.end);
if (iter.hasNext()) {
current = iter.next();
} else {
current = null;
}
}
result.add(newInterval);
if (current != null) {
result.add(current);
}
while (iter.hasNext()) {
result.add(iter.next());
}
return result;
} |
610c85bd-d8b0-4cd6-ad2a-a9d94fcf6817 | 4 | public void update(GameContainer container, StateBasedGame game, int delta,
int mouseX, int mouseY) {
if (contains(mouseX, mouseY) && !current.equals(mouseOver)) {
current = mouseOver;
currentColor = mouseOverTxtColor;
mouseEnter.play(1, RLGame.SOUND_VOLUME);
} else if (!contains(mouseX, mouseY) && !current.equals(basic)) {
current = basic;
currentColor = basicTxtColor;
}
} |
d3d1f17d-580e-41e0-b3dc-51d344ef1d6e | 0 | public byte[] getPgenCounter() {
return pgenCounter;
} |
772e583e-c7af-4eb8-82e8-8a0a9a49dd40 | 9 | @Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
System.out.println("Move up");
break;
case KeyEvent.VK_DOWN:
currentSprite = characterDown;
if (robot.isJumped() == false) {
robot.setDucked(true);
robot.setSpeedX(0);
}
break;
case KeyEvent.VK_LEFT:
robot.moveLeft();
robot.setMovingLeft(true);
break;
case KeyEvent.VK_RIGHT:
robot.moveRight();
robot.setMovingRight(true);
break;
case KeyEvent.VK_SPACE:
robot.jump();
break;
case KeyEvent.VK_CONTROL:
if (robot.isDucked() == false && robot.isJumped() == false) {
robot.shoot();
}
break;
}
} |
c37b2a90-ceb0-4808-a5d3-e54abed97309 | 7 | public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int a = Integer.parseInt(reader.readLine());
int b = Integer.parseInt(reader.readLine());
int c = Integer.parseInt(reader.readLine());
int d = Integer.parseInt(reader.readLine());
if (a > b){
if (a > c){
if (a > d){
System.out.println(a);
} else {
System.out.println(d);
}
} else if (c > d){
System.out.println(c);
}else {
System.out.println(d);
}
} else if (b > c){
if (b > d){
System.out.println(b);
}else {
System.out.println(d);
}
} else if (c > d){
System.out.println(c);
} else {
System.out.println(d);
}
} |
dfe22e5b-4273-49b6-9fbf-d08e89bcee9b | 3 | static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
} |
7d394c42-dbc6-4632-a752-a3b7f20fd6d6 | 1 | private TrainNumber CreateG101() {
TrainNumber rs = new TrainNumber();
rs.setId(UUID.randomUUID());
rs.setName("G101");
Route route = new Route();
route.setId(UUID.randomUUID());
route.setStartDate(new LocalDate(0L));
route.setEndDate(LocalDate.now().plusYears(10));
rs.getRoutes().add(route);
for(int i = 0; i <=7; i ++)
{
RouteStop stop = new RouteStop();
stop.setId(UUID.randomUUID());
stop.setSequence(i);
stop.setStation(this._stations[i]);
route.getStops().add(stop);
}
return rs;
} |
253ff9ac-bed5-4724-9978-c5cf92b81815 | 7 | @EventHandler(priority = EventPriority.MONITOR)
public void bucketEmpty(PlayerBucketEmptyEvent event){
if(plugin.getArena(event.getPlayer())!= null){
int a = plugin.getArena(event.getPlayer());
if(!event.isCancelled()){
if(plugin.canjoin.get(a)){
if(plugin.Playing.get(a).contains(event.getPlayer().getName())){
if(plugin.config.getStringList("worlds").isEmpty() || (!plugin.config.getStringList("worlds").isEmpty() && plugin.config.getStringList("worlds").contains(event.getPlayer().getWorld().getName()))){
Block b = event.getBlockClicked().getRelative(event.getBlockFace());
String w = b.getWorld().getName();
int x = b.getX();
int y = b.getY();
int z = b.getZ();
String coords = w + "," + x + "," + y + "," + z + "," + a;
List<String> blocks = plugin.data.getStringList("Blocks_Placed");
blocks.add(coords);
plugin.data.set("Blocks_Placed", blocks);
plugin.saveData();
}
}
}
}
}
} |
a2e94da0-2722-47af-844c-d10ea68fe1ac | 1 | public String toString(){
String str = identifier.getNewName(false) + "(";
if(argumentListOpt!=null)
str += argumentListOpt.toString();
str += ")";
return str;
} |
7ec3579c-de8a-4fb2-a6f5-8f9f27b4b7ad | 0 | @Id
@Column(name = "POP_PROVEEDOR_ID")
public Integer getPopProveedorId() {
return popProveedorId;
} |
f4a804e6-425b-4ad6-b805-519040e6429e | 4 | public PlayerShip getNewShip() {
switch(shipPreference) {
case BOMBER:
return new actor.ship.types.Bomber();
case FIGHTER:
return new actor.ship.types.Fighter();
case SCOUT:
return new actor.ship.types.Scout();
case SHOTGUNNER:
return new actor.ship.types.Shotgunner();
default:
return new actor.ship.types.Scout();
}
} |
4629f685-bbf8-4147-922a-974550204859 | 6 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null && line.length() != 0) {
int n = Integer.parseInt(line.trim());
if (n == 0)
break;
dig = new D[n];
int s = 0;
for (int i = 0; i < n; i++) {
int[] df = readInts(in.readLine().trim());
int d = df[0], f = df[1];
dig[i] = new D(s, s + f + 1, d, f);
s += f + 3;
}
int m = Integer.parseInt(in.readLine().trim());
for (int i = 0; i < m; i++) {
int[] rc = readInts(in.readLine());
int r = rc[0], c = rc[1];
int d = upperBound(r);
if (d < 0)
out.append(".\n");
else
out.append(solve(dig[d].n, r - dig[d].s, c, dig[d].f) + "\n");
}
}
System.out.print(out);
} |
01ed9363-88b1-4bb2-9eb8-e03f9b6c3277 | 1 | public String getInput() {
String str = "";
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
str = bufferedReader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
String returnStr = str.toLowerCase();
return returnStr;
} |
32241fe8-900c-4be9-8f6f-45de12699685 | 3 | public void setProductType(ProductType productType) {
if (this.productType == productType) return;
if (this.productType != null) {
this.productType.removeTray(this);
}
this.productType = productType;
if (productType != null) {
this.productType.addTray(this);
}
} |
d52ed276-b642-4ea5-b533-300f5df68b11 | 9 | public static void evaluateTwoParsers(File parserDataA, File parserDataB) {
BufferedReader brA = getReader(parserDataA);
BufferedReader brB = getReader(parserDataB);
String strLineA;
String strLineB;
int sentencesCounter = 1;
int partialMatches = 0;
int completeMatches = 0;
int wordCounter = 0;
try {
while ((strLineA = brA.readLine()) != null) {
strLineB = brB.readLine();
if (strLineB == null) {
System.err.println("Incompatible files.");
}
String [] relationA = strLineA.split(" ");
String [] relationB = strLineB.split(" ");
if (relationA.length == 0) {
sentencesCounter += 1;
continue;
}
wordCounter = 0;
if (relationA.length < 6 || relationB.length < 6) {
System.err.println("Corrupted data");
}
if (relationA[HEAD_INDEX].equals(relationB[HEAD_INDEX])) {
partialMatches += 1;
if (relationA[DEP_TYPE_INDEX].equals(relationB[DEP_TYPE_INDEX])) {
completeMatches += 1;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
brA.close();
brB.close();
} catch (IOException e) {
e.printStackTrace();
}
}
double partAcc = (double) partialMatches / (double) wordCounter;
double complAcc = (double) completeMatches / (double) wordCounter;
System.out.println("Evaluation on " + wordCounter
+ " in " + sentencesCounter + "sentences");
System.out.println("Equal(partially): " + partAcc);
System.out.println("Equal(completely): " + complAcc);
} |
e8220a75-279a-453f-8e13-479d63e26929 | 7 | public Triple getTriple(String identifier) throws InvalidRecordException{
Predicate pred = null;
Node sub = null;
Node obj = null;
//Check for the Triple, if not add it to the KnowledgeGraph
if (!(tripleMap.containsKey(identifier))){
StringTokenizer st = new StringTokenizer(identifier," ");
if (st.countTokens() != 3) throw new InvalidRecordException ("Skipped record: "+identifier+": Not a valid N-Triple record"); //Data validation
String tokens[] = new String[st.countTokens()];
while(st.hasMoreTokens()){
String curtoken = st.nextToken().trim();
if (curtoken.contains("?")) throw new InvalidRecordException ("Skipped record: "+identifier+": Input recored should not contain ?");//Data validation
if (st.countTokens() == 2) {tokens[2] = curtoken; sub = getNode(tokens[2]);}
if (st.countTokens() == 1) {tokens[1] = curtoken; pred = getPredicate(tokens[1]);}
if (st.countTokens() == 0) {tokens[0] = curtoken; obj = getNode(tokens[0]);}
}
tripleMap.put(identifier, new Triple(identifier, sub, pred, obj));
buildQueryMapSet(tripleMap.get(identifier));
}
return tripleMap.get(identifier);
} |
6f7d9f89-c8a4-4187-9cf3-a686c897bd2e | 5 | @Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
//刷新选中状态
selectNone();
for(int i = 0; i < model.size(); i++) {
CheckStore<E> store = model.get(i);
if(store.isSelected()) {
uiCheckBoxList.addCheckBoxListSelectedIndex(i);
}
}
//大小
if(popSize != null && popSize.height != 0 && popSize.width != 0) {
setPreferredSize(popSize);
} else {
setPreferredSize(new Dimension(textFieldShowed.getWidth(), 350));
}
//清空搜索框
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
uiSearchFiled.setText("");
uiSearchFiled.requestFocusInWindow();
}
});
} |
c4530ec1-5be8-4e4b-8e21-dd6f547130b3 | 6 | @EventHandler
public void CreeperRegeneration(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getCreeperConfig().getDouble("Creeper.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getCreeperConfig().getBoolean("Creeper.Regeneration.Enabled", true) && damager instanceof Creeper && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getCreeperConfig().getInt("Creeper.Regeneration.Time"), plugin.getCreeperConfig().getInt("Creeper.Regeneration.Power")));
}
} |
64dd1fed-3f89-4416-a133-a35e3e73cb7c | 3 | private static Map<String, String> parse(String fileName)
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Map<String, String> map = new HashMap<String, String>();
try
{
builder = builderFactory.newDocumentBuilder();
}
catch(ParserConfigurationException e)
{
// TODO: use logging engine instead
e.printStackTrace();
return null;
}
// Parsing the File
try
{
Document doc = builder.parse(new FileInputStream(new File(fileName)));
NodeList properties = doc.getElementsByTagName("property");
for(int i = 0; i < properties.getLength(); i++)
{
Node node = properties.item(i);
String name = node.getAttributes().getNamedItem("name").getNodeValue()
.trim().toLowerCase();
String value = node.getTextContent().trim();
map.put(name, value);
}
}
catch(Exception e)
{
// TODO: use logging engine instead
e.printStackTrace();
return null;
}
return map;
} |
ac690f63-c362-45fa-b435-75ef54a3a90c | 4 | public short getMinimumDifference_as_short(){
short diff = (short)0;
if(this.type==8 || this.type==9){
ArrayMaths am = this.sort();
short[] sorted = am.getArray_as_short();
diff = (short)(sorted[1] - sorted[0]);
short minDiff = diff;
for(int i=1; i<this.length-1; i++){
diff = (short)(sorted[i+1] - sorted[i]);
if(diff<minDiff)minDiff = diff;
}
}
else{
throw new IllegalArgumentException("Minimum difference may only be returned as the same type as the type of the internal array - you are trying to return as short or Short the difference for a " + this.typeName[this.type] +"[] array");
}
return diff;
} |
2ba4f4cd-4dd0-434d-8de6-2cd27770bc35 | 1 | @Override
public void windowClosed(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSED) {
this.setVisible(false);
this.dispose();
}
//To change body of implemented methods use File | Settings | File Templates.
} |
e40e7e9d-52c8-4f1c-aceb-a5f9adb3ef06 | 1 | @Override
public boolean interpret(String context) {
if (context.contains(data)) {
return true;
}
return false;
} |
db36c6fd-9c7c-4065-b295-30c84f95589a | 6 | private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
// TODO add your handling code here:
try{
if(esCarga){
if((jTextField1==null)||(jTextField1.getText().equals("")))
jTextField1.requestFocus();
else
{
int numAsiento=Integer.parseInt(jTextField1.getText());
r_con.Connection();
ResultSet rs=r_con.Consultar("select ba_nro_asiento,ba_ok_registrado from borrador_asientos where ba_nro_asiento="+numAsiento);
if(rs.next()){
if(!rs.getBoolean(2)){
cargarCampos(rs.getInt(1));
jButton3.setEnabled(true);
mensajeError(" ");
}
else
{
deshabilitarCampos();
jTextField1.requestFocus();
mensajeError("El asiento ya se encuentra registrado");
}
}
else
{
deshabilitarCampos();
jTextField1.requestFocus();
mensajeError("El asiento ingresado no existe");
}
r_con.cierraConexion();
}
}
}
catch(Exception e){
r_con.cierraConexion();
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jTextField1FocusLost |
627e0bd6-c18a-4734-b00f-15e2f095d426 | 5 | public String parse(String input){
String output = input.replace("(SERVERNAME)", pl.getServer().getName())
.replace("(BUKKITVERSIONLONG)", pl.getServer().getVersion())
.replace("(BUKKITVERSION)", pl.getServer().getBukkitVersion())
.replace("(MAXPLAYERS)", "" + pl.getServer().getMaxPlayers())
.replace("(ONLINEPLAYERS)", "" + pl.getServer().getOnlinePlayers().length)
.replace("(LOCALIP)", "" + pl.getServer().getIp())
.replace("(SERVERPORT)", "" + pl.getServer().getPort())
.replace("(ALLTIMEPLAYERS)", "" + pl.getServer().getOfflinePlayers().length)
.replace("(VERSION)", pl.getServer().getBukkitVersion().split("-")[0]);
if (!pl.getConfig().getString("variables").isEmpty()){
for(String var : pl.getConfig().getConfigurationSection("variables").getKeys(false)) {
String varValue = pl.getConfig().getString("variables." + var);
if (varValue.charAt(0) == '/'){
String varinput = output;
int index = varinput.indexOf("(" + var.toUpperCase() + ")");
int count = 0;
while (index != -1) {
count++;
varinput = varinput.substring(index + 1);
index = varinput.indexOf("(" + var.toUpperCase() + ")");
}
while (count > 0){
pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), varValue.replaceFirst("/", ""));
count--;
}
output = output.replace("(" + var.toUpperCase() + ")", "");
} else
output = output.replace("(" + var.toUpperCase() + ")", varValue);
}
}
return output;
} |
34a3e6d5-cb53-467a-ad50-ff85a0d6cbfd | 3 | @Override
public void setType(BlocType b) {
BlocType t = super.getType();
checkInvariants();
super.setType(b);
checkInvariants();
if(t==BlocType.MURMETAL){
if(!(super.getType() == BlocType.MURMETAL)){
throw new PostConditionError(
"getType(B) == BlocType::MURMETAL et "+
"getType(setType(B,t)) != BlocType :: MURMETAL");}
} else {
if(!(super.getType()==b))
throw new PostConditionError("getType(setType(B,t)) == t");
}
} |
c786f126-efc4-41c0-a252-0bc23d34e6c1 | 7 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((affected instanceof MOB)
&&(msg.target()==affected)
&&(msg.sourceMinor()==CMMsg.TYP_ADVANCE))
{
final MOB mob=(MOB)affected;
if((mob.getVictim()==msg.source())
&&(mob.location()!=null))
{
final CMMsg msg2=CMClass.getMsg(mob,mob.getVictim(),CMMsg.MSG_RETREAT,L("<S-NAME> predict(s) <T-YOUPOSS> advance and retreat(s)."));
if(mob.location().okMessage(mob,msg2))
mob.location().send(mob,msg2);
}
}
return true;
} |
be3d66a4-e51b-4c21-92a3-afa0bd34181b | 1 | public void fillInGenSet(Set in, Set gen) {
if (instr != null)
instr.fillInGenSet(in, gen);
} |
349eb276-7a3b-401a-831b-56deef3f0b10 | 6 | @Override
public void draw(Graphics g) {
int x = this.column * Board.CELL_SIZE;
int y = this.row * Board.CELL_SIZE;
g.setColor(Color.GRAY);
g.fillRect(x, y, Board.CELL_SIZE, Board.CELL_SIZE);
if (roomInitial == 'X'){
g.setColor(Color.RED.darker().darker());
g.fillRect(x, y, Board.CELL_SIZE, Board.CELL_SIZE);
}
if (this.isDoor) {
int height = 4;
int width = Board.CELL_SIZE;
switch (directionOfDoor){
case UP:
break;
case DOWN:
y = (y + Board.CELL_SIZE - height);
width = Board.CELL_SIZE;
break;
case RIGHT:
x = (x + Board.CELL_SIZE - height);
height = Board.CELL_SIZE;
break;
case LEFT:
height = Board.CELL_SIZE;
width = 4;
break;
}
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
}
} |
538a2a84-c18b-46b9-8de5-c9f51a036ddf | 0 | public static void main(String[] args) {
RecursionSteps r = new RecursionSteps();
System.out.println(r.Steps(4));
} |
38c51428-db0b-4c24-8be3-c620a2ba067b | 9 | protected synchronized void initializeJar() {
//Check to see if we are already initialized
if(isInitialized()) return;
//we can't initialize non-jar non-zip resources
if(!isJar() && !isZip()) {
initialized_flag = true;
return;
}
try {
File f = null;
if(resourceURL.getProtocol().equals("file")){
f = new File(resourceURL.getFile());
}
else {
f = Boot.getCacheManager().getCachedFileForURL(resourceURL);
}
if(!f.exists()) {
logger.log(Level.WARNING, "*** Resource file:"+f.toString()+" was not found!");
return;
}
jarFile = new JarFile(f);
jarEntryNames.clear();
Enumeration<JarEntry> entries = jarFile.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
jarEntryNames.put(entry.getName(), entry);
}
manifest = jarFile.getManifest();
if(manifest != null) {
Attributes mainAttrs = manifest.getMainAttributes();
if(mainAttrs != null) {
defaultSpecTitle = mainAttrs.getValue("Specification-Title");
defaultSpecVersion = mainAttrs.getValue("Specification-Version");
defaultSpecVendor = mainAttrs.getValue("Specification-Vendor");
defaultImplTitle = mainAttrs.getValue("Implementation-Title");
defaultImplVersion = mainAttrs.getValue("Implementation-Version");
defaultImplVendor = mainAttrs.getValue("Implementation-Vendor");
defaultSealed = Boolean.valueOf(mainAttrs.getValue("Sealed")).booleanValue();
}
}
}
catch(Exception ioExp) {
logger.log(Level.SEVERE, ioExp.getMessage(), ioExp);
}
finally {
initialized_flag = true;
}
} |
fde083cc-4b0f-4df5-9caa-b7c0f5a8e12a | 1 | public void setStatus(boolean status){
currentImage = status ? greenLamp : redLamp;
repaint();
} |
fecfc2a2-e746-435b-8b48-31ed42fc174e | 9 | public Object getValueAt(int rowIndex, int columnIndex) {
assert((columnIndex >= 0) && (columnIndex <= 2));
Iterator i = scoreSet.iterator();
int j = 0;
while(i.hasNext()) {
if(j == rowIndex) {
Object o = i.next();
assert(o instanceof ScoreWrapper);
ScoreWrapper s = (ScoreWrapper) o;
Client c = s.getClient();
if(columnIndex == 0) {
return c.getName();
} else if(columnIndex == 1) {
return new Integer(s.getScore());
} else if(columnIndex == 2) {
if(c instanceof GUIClient) {
return "GUI";
} else if(c instanceof RemoteClient) {
return "Remote";
} else if(c instanceof RobotClient) {
return "Robot";
} else {
return "Unknown";
}
}
} else {
i.next();
j++;
}
}
return null;
} |
424098f7-709e-45ff-9091-05747010a68c | 9 | protected void _socketReceivingMessage(ByteBuffer _buf)
{
//将数据放入缓冲中
try
{
_m_bByteBuffer.put(_buf);
}
catch (BufferOverflowException e)
{
//长度不足,此时提示
ALServerLog.Error("_socketReceivingMessage length is too long, Socket Buffer need more!");
_m_bByteBuffer.put(_buf.array(), 0, _m_bByteBuffer.remaining());
//放置待插入数据中指针位置为缓冲区读取指针,可在数据处理后再将数据放入缓存一次
_buf.position(_m_bByteBuffer.remaining());
}
if(0 == _m_sBufferLen)
{
//尚未读取长度前
if(_m_bByteBuffer.position() >= 4)
{
//当缓冲中字节大于2时可获取对应的消息长度
_m_sBufferLen = _m_bByteBuffer.getInt(0);
}
}
//当长度有效则判断是否到达消息末尾
int bufLen = _m_bByteBuffer.position();
int startPos = 0;
while(0 != _m_sBufferLen && bufLen >= startPos + _m_sBufferLen + 4)
{
//到达消息末尾,将消息取出,并清除缓存消息
ByteBuffer message = ByteBuffer.allocate(_m_sBufferLen);
message.put(_m_bByteBuffer.array(), startPos + 4, _m_sBufferLen);
message.flip();
//设置新的开始位置
startPos = startPos + _m_sBufferLen + 4;
//添加消息
if(null != _m_clListener)
{
_addRecMessage(message);
}
else
{
//处理登录操作
_login(message);
}
//根据长度设置对应消息长度
if(bufLen - startPos > 4)
{
//当缓冲中字节大于2时可获取对应的消息长度
_m_sBufferLen = _m_bByteBuffer.getInt(startPos);
}
else
{
_m_sBufferLen = 0;
break;
}
}
//判断数据经过了操作
//如数据经过了操作需要将剩余数据重新拷贝放入缓存
if(startPos != 0)
{
ByteBuffer tmpBuf = ByteBuffer.allocate(bufLen - startPos);
tmpBuf.put(_m_bByteBuffer.array(), startPos, bufLen - startPos);
tmpBuf.flip();
_m_bByteBuffer.clear();
_m_bByteBuffer.put(tmpBuf);
}
//如原先缓存数据未完全放入,此时将剩余数据放入
if(_buf.remaining() > 0)
{
_m_bByteBuffer.put(_buf);
}
} |
b452ef2d-b254-4843-aaa5-04e1fe1ba31e | 2 | public void update() {
Window window = vc.getFullScreenWindow();
if (window != null) {
BufferStrategy s = window.getBufferStrategy();
if (!s.contentsLost()) s.show();
}
} |
9088d995-d7d2-4d1c-8df0-c73069a4d3bb | 6 | @Override
public void keyPressed(KeyEvent e) {
if (isAlive) {
if (e.getKeyChar() == 'w') {
player.setDy(-4);
keyDown[2] = true;
} else if (e.getKeyChar() == 's') {
player.setDy(4);
keyDown[3] = true;
} else if (e.getKeyChar() == 'a') {
player.setDx(-4);
keyDown[0] = true;
} else if (e.getKeyChar() == 'd') {
keyDown[1] = true;
player.setDx(4);
} else if (e.getKeyChar() == ' ') {
server.sendMessage("GIVEMOB");
}
} else {
player = new Player();
player.setUsername(username);
players.add(player);
isAlive = true;
time = 0;
timer.start();
}
} |
3f7a4193-0059-4cab-ab66-d768b49734e1 | 5 | public static void disposeImages() {
// dispose loaded images
{
for (Image image : m_imageMap.values()) {
image.dispose();
}
m_imageMap.clear();
}
// dispose decorated images
for (int i = 0; i < m_decoratedImageMap.length; i++) {
Map<Image, Map<Image, Image>> cornerDecoratedImageMap = m_decoratedImageMap[i];
if (cornerDecoratedImageMap != null) {
for (Map<Image, Image> decoratedMap : cornerDecoratedImageMap.values()) {
for (Image image : decoratedMap.values()) {
image.dispose();
}
decoratedMap.clear();
}
cornerDecoratedImageMap.clear();
}
}
} |
6fbcf28b-6837-4438-b85f-b6109fef15bb | 4 | public int get(ParameterName variableName, int defaultValue){
if(map.containsKey(variableName)){
if(map.get(variableName) instanceof Integer || map.get(variableName) instanceof Float || map.get(variableName) instanceof Double){
return Math.round(((Number)map.get(variableName)).floatValue());
}
throw new IllegalArgumentException("Variable " + variableName + ", value=" + map.get(variableName) +
". Can't be cast to int");
}
return defaultValue;
} |
303951f4-4118-4d54-bc0b-b552325bbfe9 | 6 | private static MiniScriptValue readValue(CompileInfo ci, String p){
p = p.trim();
if(p.isEmpty()){
makeDiagnostic(ci, Kind.ERROR, "no.value.empty");//$NON-NLS-1$
return null;
}else{
if(p.charAt(0)=='['){
return readPtr(ci, p);
}else if(p.charAt(0)=='r' || p.charAt(0)=='R'){
if(p.length()>1 && isNum(p.charAt(1))){
return readReg(ci, p);
}else{
return readNum(ci, p);
}
}else{
return readNum(ci, p);
}
}
} |
13d0d975-223b-47b6-bfff-4390e6c382da | 0 | public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
} |
a20094af-a8eb-4653-b109-9bc783a4c927 | 1 | public void addLiens(List<ZLien> liens)
{
Iterator<ZLien> e = liens.iterator();
while (e.hasNext())
addLien((ZLien) e.next());
} |
ccc4385f-0834-4932-ad77-2731faa869f8 | 6 | private boolean validMove(int x, int y, ArrayDeque<Point> path){
if(avatar.getAvilableMoves() == 0)
return false;
//Return false if it out of bounds of the map array.
if(!inBounds(x,y))
return false;
//Returns false if the tile does not correspond to a accessible square
if(!worldMap[x][y].isIsTile())
return false;
//Return false if there is another player in that square
if(gameBoard[x][y] instanceof UnitPlayer)
return false;
//Return true if there is no path yet calculated for that square
if(worldMap[x][y].getPath() == null)
return true;
// Return false if the path calculated already for that square is more
// efficient than this one
if(worldMap[x][y].getPath().size() < path.size())
return false;
//Otherwise return true
return true;
} |
463a6f1d-5e4e-46b8-9869-b37cd6e554cb | 6 | public synchronized void serviceChanged(ServiceEvent event) {
String[] objectClass = (String[]) event.getServiceReference().getProperty("objectClass");
// If a dictionary service was registered, see if we
// need one. If so, get a reference to it.
if (event.getType() == ServiceEvent.REGISTERED) {
if (m_ref == null) {
// Get a reference to the service object.
m_ref = event.getServiceReference();
m_dictionary = (DictionaryService) m_context.getService(m_ref);
}
}
// If a dictionary service was unregistered, see if it
// was the one we were using. If so, unget the service
// and try to query to get another one.
else if (event.getType() == ServiceEvent.UNREGISTERING) {
if (event.getServiceReference() == m_ref) {
// Unget service object and null references.
m_context.ungetService(m_ref);
m_ref = null;
m_dictionary = null;
// Query to see if we can get another service.
ServiceReference[] refs = null;
try {
refs = m_context.getServiceReferences(DictionaryService.class.getName(), "(Language=*)");
} catch (InvalidSyntaxException ex) {
// This will never happen.
}
if (refs != null) {
// Get a reference to the first service object.
m_ref = refs[0];
m_dictionary = (DictionaryService) m_context.getService(m_ref);
}
}
}
} |
1f30bb69-dbd7-4fa6-9c51-cebff3a369be | 7 | public LoreBookPanel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException exception) {
exception.printStackTrace();
} catch (InstantiationException exception) {
exception.printStackTrace();
} catch (IllegalAccessException exception) {
exception.printStackTrace();
} catch (UnsupportedLookAndFeelException exception) {
exception.printStackTrace();
}
setBounds(0, 0, 960, 672);
setLayout(null);
leftPanel = new JPanel();
leftPanel.setBounds(0, 0, 480, 640);
add(leftPanel);
rightPanel = new JPanel();
rightPanel.setBounds(480, 0, 480, 640);
add(rightPanel);
btnNextPage = new JButton("Next page");
btnNextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
turnPageForward();
}
});
btnNextPage.setBounds(843, 643, 117, 29);
add(btnNextPage);
btnPreviousPage = new JButton("Previous page");
btnPreviousPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
turnPageBackward();
}
});
btnPreviousPage.setBounds(0, 643, 117, 29);
add(btnPreviousPage);
leftPageNumber = new JLabel("");
leftPageNumber.setBounds(129, 648, 61, 16);
add(leftPageNumber);
rightPageNumber = new JLabel("");
rightPageNumber.setBounds(770, 652, 61, 16);
add(rightPageNumber);
book = new BookImpl(this);
try {
loadBackgrounds();
} catch (IOException exception) {
exception.printStackTrace();
}
try {
book.loadPages();
} catch (IOException exception) {
exception.printStackTrace();
} catch (FontFormatException exception) {
exception.printStackTrace();
}
refreshPages();
} |
770ae682-329a-4b9d-a9ed-dc0c91b0f449 | 3 | public void init(){
//setup root
Root = new Node(null,new Point(0,0,TreeSize),new Point(TreeSize,0,TreeSize),new Point(0,0,0), new Point(TreeSize,0,0));
Root.Parent = null;
//not doing this recursively, because it's not jumping out at me, I think I'm seeing problems with initialization that way,
//you'd have to keep track of depth and that could be messy
ArrayList<Node> NodesToProcess = new ArrayList<Node>();
ArrayList<Node> NextNodesToProcess = new ArrayList<Node>();
NodesToProcess.add(Root);
for(int i = 0; i < TreeDepth; i ++){
//process dem nodes
for(Node CurrentNode : NodesToProcess){
//get the points for the child nodes corners
Point Up = new Point(CurrentNode.UpperLeft.X + ((CurrentNode.UpperRight.X - CurrentNode.UpperLeft.X)/2), 0 , CurrentNode.UpperLeft.Z);
Point Down = new Point(CurrentNode.LowerLeft.X + ((CurrentNode.LowerRight.X - CurrentNode.LowerLeft.X)/2),0,CurrentNode.LowerLeft.Z);
Point Left = new Point(CurrentNode.LowerLeft.X,0,CurrentNode.LowerLeft.Z +((CurrentNode.UpperLeft.Z - CurrentNode.LowerLeft.Z)/2));
Point Right = new Point(CurrentNode.LowerRight.X,0,CurrentNode.LowerRight.Z +((CurrentNode.UpperRight.Z - CurrentNode.LowerRight.Z)/2));
Point Center = new Point(CurrentNode.LowerLeft.X + ((CurrentNode.LowerRight.X - CurrentNode.LowerLeft.X)/2),0,CurrentNode.LowerRight.Z +((CurrentNode.UpperRight.Z - CurrentNode.LowerRight.Z)/2));
//create the Child Nodes
Node NorthWestChild = new Node(CurrentNode,CurrentNode.UpperLeft, Up, Left, Center);
Node NorthEastChild = new Node(CurrentNode, Up, CurrentNode.UpperRight, Center, Right);
Node SouthWestChild = new Node(CurrentNode, Left, Center, CurrentNode.LowerLeft, Down);
Node SouthEastChild = new Node(CurrentNode,Center,Right,Down, CurrentNode.LowerRight);
//set the children of the current node
CurrentNode.NorthWest = NorthWestChild;
CurrentNode.NorthEast = NorthEastChild;
CurrentNode.SouthWest = SouthWestChild;
CurrentNode.SouthEast = SouthEastChild;
//add those nodes to the next nodes to process
NextNodesToProcess.add(NorthWestChild);
NextNodesToProcess.add(NorthEastChild);
NextNodesToProcess.add(SouthWestChild);
NextNodesToProcess.add(SouthEastChild);
}
//copy over the next nodes to process into the current nodes to process
NodesToProcess.clear();
for(Node n : NextNodesToProcess){
NodesToProcess.add(n);
}
NextNodesToProcess.clear();
}
} |
799079db-b685-4b68-85f7-a26ee0a68174 | 5 | @Override
public boolean onPointerMove(int mX, int mY, int mDX, int mDY) {
if(mX > x && mX < x + width && mY > y && mY < y + height) {
pointerOver = true;
if(tooltip != null) {
tooltip.setLocation(mX+20, mY+20);
}
}
else {
pointerOver = false;
pointerHovered = 0;
renderTooltip = false;
Application.get().getHumanView().setTooltip(null);
}
return false;
} |
dbb7393c-ea16-4daf-aaf9-b4129c434169 | 6 | public static void getModsFrom(File dir, File parentFile) throws Exception
{
if (dir.isDirectory())
{
for (int i = 0; i < dir.listFiles().length; i++)
{
if (dir.listFiles()[i].isDirectory())
{
getModsFrom(dir.listFiles()[i], parentFile);
}
else if (dir.listFiles()[i].toString().endsWith(".class"))
{
final URLClassLoader cl = URLClassLoader.newInstance(new URL[] { parentFile.toURI().toURL() });
final Class<?> clazz = cl.loadClass(dir.listFiles()[i].toString().split(parentFile.getName() + "/")[1].replaceAll(".class", "").replaceAll("/", "."));
if (clazz.isAnnotationPresent(Mod.class))
{
final Object mod = clazz.newInstance();
final ModContainer mc = new ModContainer(mod);
mc.initMethod(State.PRE_INIT);
}
}
}
}
} |
c5e9cdb8-4a79-4fc8-8d8f-10a4eb5cfc10 | 0 | @Override
public void execute(VirtualMachine vm) {
System.out.println(vm.peekRunTimeStack());
} |
18f60d95-7164-4dd0-ba94-95235939d110 | 3 | public void render(Graphics g)
{
g.setColor(buttonColor);
g.fillRect(x, y, w, h);
if(disabled) {
g.setColor(disabledColor);
g.fillRect(x, y, w, h);
}
else if(shade) {
g.setColor(pressed ? shadeColor : hoverColor);
g.fillRect(x, y, w, h);
}
g.setColor(Color.BLACK);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
g.drawString(text, (int) (x + w/2 - fm.getStringBounds(text, g).getWidth()/2), (int) (y + h/2 + fm.getStringBounds(text, g).getHeight()/4));
} |
dbf95147-76de-492a-b60e-6a2a22edb335 | 1 | public static ArrayList<Score> get() {
try {
String data = "action=" + URLEncoder.encode("get", "UTF-8");
String result = connect(data);
return createScores(result);
} catch(Exception e) {
e.printStackTrace();
}
return null;
} |
bc9bd850-fdda-4537-9f52-ec5695ce47da | 4 | @Override
public void renameDirectory(String directory, String newname)
{
if (!dirEntries.containsKey(directory.toLowerCase())) return;
DirEntry de = dirEntries.get(directory.toLowerCase());
DirEntry parent = de.parentDir;
String parentpath = "";
if (parent != null)
{
if (fileEntries.containsKey((parent.fullName + "/" + newname).toLowerCase()) ||
dirEntries.containsKey((parent.fullName + "/" + newname).toLowerCase()))
return;
parentpath = parent.fullName;
}
dirEntries.remove(de.fullName.toLowerCase());
de.name = newname;
de.fullName = parentpath + "/" + newname;
dirEntries.put(de.fullName.toLowerCase(), de);
} |
e1bfdae1-1118-43d5-a680-9e26db23f8d6 | 3 | private static void checkForRuntimeRetention( Class<? extends Annotation> annotationType )
{
Retention retention = annotationType.getAnnotation( Retention.class );
if ( retention == null || RetentionPolicy.RUNTIME != retention.value() )
{
throw new IllegalArgumentException( "Annotation @" + annotationType.getName()
+ " is missing RUNTIME retention" );
}
} |
b98b16bc-6f3b-4e3f-9084-cebffce0b1d3 | 5 | public static WordSet generateSet(int tipo){
//Selección de la implementación a utilizar
switch (tipo){
case 1: return new SimpleSet();
case 2: return new RedBlackTree();
case 3: return new SplayTree();
case 4: return new HashTableSet();
case 5: return new TreeMapSet();
default: return null;
}
} |
df54fb62-60c2-4828-9af2-ddaa03066630 | 8 | public void fixSequence(SAMSequenceRecord sequenceRecord) throws MD5MismatchError {
String found_md5 = sequenceRecord.getAttribute(SAMSequenceRecord.MD5_TAG);
if (confirmMD5) {
if (found_md5 != null) {
byte[] bytes = referenceSource.getReferenceBases(sequenceRecord, true);
if (bytes == null) {
String message = String.format("Reference bases not found: name %s, length %d, md5 %s.",
sequenceRecord.getSequenceName(), sequenceRecord.getSequenceLength(), found_md5);
log.error(message);
throw new RuntimeException(message);
}
log.info("Confirming reference sequence md5: " + sequenceRecord.getSequenceName());
String md5 = Utils.calculateMD5String(bytes);
if (!md5.equals(found_md5)) {
if (ignoreMD5Mismatch) {
log.warn(String.format(
"Sequence id=%d, len=%d, name=%s has incorrect md5=%s. Replaced with %s.",
sequenceRecord.getSequenceIndex(), sequenceRecord.getSequenceLength(),
sequenceRecord.getSequenceName(), found_md5, md5));
sequenceRecord.setAttribute(SAMSequenceRecord.MD5_TAG, md5);
} else
throw new MD5MismatchError(sequenceRecord, md5);
}
if (sequenceRecord.getSequenceLength() != bytes.length) {
log.warn(String.format("Sequence id=%d, name=%s has incorrect length=%d. Replaced with %d.",
sequenceRecord.getSequenceIndex(), sequenceRecord.getSequenceName(),
sequenceRecord.getSequenceLength(), bytes.length));
sequenceRecord.setSequenceLength(bytes.length);
}
} else {
log.info("Reference sequence MD5 not found, calculating: " + sequenceRecord.getSequenceName());
byte[] bytes = referenceSource.getReferenceBases(sequenceRecord, true);
if (bytes == null) {
String message = String.format("Reference bases not found: name %s, length %d.",
sequenceRecord.getSequenceName(), sequenceRecord.getSequenceLength());
log.error(message);
throw new RuntimeException(message);
}
String md5 = Utils.calculateMD5String(bytes);
sequenceRecord.setAttribute(SAMSequenceRecord.MD5_TAG, md5);
}
}
if (injectURI) {
sequenceRecord.setAttribute(SAMSequenceRecord.URI_TAG,
String.format(sequenceUrlPattern, sequenceRecord.getAttribute(SAMSequenceRecord.MD5_TAG)));
}
} |
bc2e2ca6-7853-43f9-b60b-e1505add7454 | 3 | int syncHeader(byte syncmode) throws BitstreamException
{
boolean sync;
int headerstring;
// read additional 2 bytes
int bytesRead = readBytes(syncbuf, 0, 3);
if (bytesRead!=3) throw newBitstreamException(STREAM_EOF, null);
headerstring = ((syncbuf[0] << 16) & 0x00FF0000) | ((syncbuf[1] << 8) & 0x0000FF00) | ((syncbuf[2] << 0) & 0x000000FF);
do
{
headerstring <<= 8;
if (readBytes(syncbuf, 3, 1)!=1)
throw newBitstreamException(STREAM_EOF, null);
headerstring |= (syncbuf[3] & 0x000000FF);
sync = isSyncMark(headerstring, syncmode, syncword);
}
while (!sync);
//current_frame_number++;
//if (last_frame_number < current_frame_number) last_frame_number = current_frame_number;
return headerstring;
} |
80fe3158-05cc-496c-b80a-103098bde53a | 0 | String getMessage() {
return this.message;
} |
8f5d9532-aa86-48fa-94f5-0ee1b95ea2db | 2 | public static void inversion(Deck in){
int pos1 = (int) (Math.random() * (1+in.cards.size()));
int pos2 = (int) (Math.random() * (1+in.cards.size()));
if(pos1>pos2){
int temp = pos1;
pos1 = pos2;
pos2 = temp;
}
String temp;
int j = pos2;
for(int i=pos1; i<(j-1); i++){
j--;
temp = in.cards.get(i);
in.cards.set(i, in.cards.get(j));
in.cards.set(j, temp);
}
} |
cc444f7b-0064-4139-b3fc-61f157f439c8 | 0 | public String getManufacturerId() {
return manufacturerId;
} |
3ede1ebb-9dbb-499e-9f6b-bc1f6cec8d5c | 0 | public Logger() {
log = this;
} |
3cca2156-c601-4d34-98f4-1a041ffd505f | 0 | public String getDescription() {
return "JFLAP 3 File";
} |
3288d435-7125-442d-a820-d583a5bf2f99 | 2 | public String getNanopostsDir(boolean outbox) {
String nanopostsDir;
if (!outbox) {
nanopostsDir = MainClass.NANOPOSTS_DIR + System.getProperty("file.separator");
} else {
nanopostsDir = MainClass.OUTBOX_DIR + System.getProperty("file.separator");
}
if (!new File(nanopostsDir).exists()) {
new File(nanopostsDir).mkdir();
}
return nanopostsDir;
} |
9fda9a2b-2ff7-4342-9f61-999fdd527dde | 3 | @Override
public void show() {
System.out.println(name + ", type in the required information for a new auction item." + "\n");
System.out.println("Name of product:");
try {
productName = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Description of product:");
try {
description = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Price of product:");
try {
String stringToInt = br.readLine();
price = Integer.parseInt(stringToInt);
} catch (Exception e) {
System.out.println("The input wasn't a number or was out of bounds try again.");
}
int id = as.searches.size()+1;
Auction a = new Auction(id, productName, description, price);
as.create(a);
System.out.println();
System.out.println(productName + " has been added to the auction." + "\n");
} |
a579b0a4-6ac1-4d93-864f-64775261dedd | 9 | public Position findFirstEmptyCell(Direction direction) {
if (direction == Direction.DOWN) {
for (int x = 0; x < getWidth(); ++x) {
for (int y = 0; y < getHeight(); ++y) {
Cell cell = getCell(x, y);
if (cell.isAccessible() && cell.getContent().equals(Cell.EMPTY_CHARACTER)) {
return new Position(x, y);
}
}
}
} else {
for (int y = 0; y < getHeight(); ++y) {
for (int x = 0; x < getWidth(); ++x) {
Cell cell = getCell(x, y);
if (cell.isAccessible() && cell.getContent().equals(Cell.EMPTY_CHARACTER)) {
return new Position(x, y);
}
}
}
}
return null;
} |
bf8b29c8-a799-4ea9-ade4-9dea9d2c54a9 | 3 | public FeatureNode [] parseRow(String [] row) {
FeatureNode [] example = new FeatureNode[row.length-1];
int maxindex = 0;
for (int i=1; i<row.length; i++) {
String [] iv = row[i].split(":");
int index = Integer.parseInt(iv[0]);
if (index <= maxindex) {
throw new IllegalArgumentException("indices must be in increasing order!");
}
maxindex = index;
double value = Double.parseDouble(iv[1]);
example[i-1] = new FeatureNode(index, value);
}
if (n < maxindex)
n = maxindex;
return example;
} |
385b0ead-7464-44ad-88ab-ba04a94ab1f2 | 8 | public Exam(int examMark) {
if (examMark > 100 || examMark < -1) {
invalidCount++;
} else if (70 <= examMark && examMark <= 100) {
studentCount++;
distinctionCount++;
} else if (50 <= examMark && examMark <= 69) {
studentCount++;
passCount++;
} else if (0 <= examMark && examMark <= 49) {
studentCount++;
failCount++;
}
} |
5529bc64-634f-41df-ac38-22f0916f6234 | 2 | public void test_02() {
readFile("tests/indexer_test_01.fastq");
// Sort all references
String latest = "";
Collections.sort(references, seqIndex);
// Check that is was sorted correctly
for( Long ref : references ) {
DnaAndQualitySequence seq = seqIndex.get(SequenceReference.getSeqIdx(ref));
int start = SequenceReference.getStart(ref);
Math.min(seq.length() - start, latest.length());
String subseq = seq.getSequence().substring(start);
if( subseq.compareTo(latest) < 0 ) throw new RuntimeException("References out of order!\n\t" + SequenceReference.getSeqIdx(ref) + ":" + SequenceReference.getStart(ref) + "\t" + ref + "\t" + subseq + "\n\tLatest: " + latest);
latest = subseq;
}
} |
c55cd34f-7ee9-4009-bf21-307b6ebe2b76 | 2 | @Override
public void run() {
/*if (HyperPVP.games == 19) {
this.restart(30, 15);
this.restart(15, 5);
this.restart(10, 5);
this.restart(5, 1);
this.restart(4, 1);
this.restart(3, 1);
this.restart(2, 1);
this.restart(1, 1);
HyperPVP.needsRestart = true;
return;
} else {
HyperPVP.games = HyperPVP.games + 1;
}*/
try {
CraftServer craftServer = (CraftServer) Bukkit.getServer();
MinecraftServer server = craftServer.getServer();
server.setMotd(ChatColor.AQUA + "Cycling...");
} catch (Exception e1) {
e1.printStackTrace();
}
try {
/*this.cycleAnnounce(20, 1000, false);
this.cycleAnnounce(20, 1000, true);
this.cycleAnnounce(20, 1000, true);
this.cycleAnnounce(20, 1000, true);
this.cycleAnnounce(20, 1000, true);
this.cycleAnnounce(15, 1000, false);
this.cycleAnnounce(15, 1000, true);
this.cycleAnnounce(15, 1000, true);
this.cycleAnnounce(15, 1000, true);
this.cycleAnnounce(15, 1000, true);
this.cycleAnnounce(10, 1000, false);
this.cycleAnnounce(10, 1000, true);
this.cycleAnnounce(10, 1000, true);
this.cycleAnnounce(10, 1000, true);
this.cycleAnnounce(10, 1000, true);
this.cycleAnnounce(5, 1000, false);
this.cycleAnnounce(4, 1000, false);
this.cycleAnnounce(3, 1000, false);
this.cycleAnnounce(2, 1000, false);
this.cycleAnnounce(1, 1000, false);*/
/*for (int i = 10; i >= 0; i--) {
if (i == 0) {
continue;
}
if (this.isCancelled()) {
return;
}
this.cycleAnnounce(i, 1000);
}*/
HyperPVP.setCycling(false);
HyperPVP.setMatchBeenAnnounced(false);
HyperPVP.setNeedsGameThread(true);
HyperPVP.winningTeam = null;
HyperPVP.winningPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
} |
acbe6345-20bf-45e5-8f1d-92ef26ffd7dc | 0 | public void setX(int newX)
{
this.x = newX;
} |
a47543af-648e-440e-9f26-b79a24536824 | 9 | public boolean hasBooleanValue() {
switch (constType.type) {
case CodeConstants.TYPE_BOOLEAN:
case CodeConstants.TYPE_CHAR:
case CodeConstants.TYPE_BYTE:
case CodeConstants.TYPE_BYTECHAR:
case CodeConstants.TYPE_SHORT:
case CodeConstants.TYPE_SHORTCHAR:
case CodeConstants.TYPE_INT:
int value = ((Integer)this.value).intValue();
return value == 0 || (DecompilerContext.getOption(IFernflowerPreferences.BOOLEAN_TRUE_ONE) && value == 1);
}
return false;
} |
70eef941-6346-40a5-8160-22e383ffb576 | 8 | @SuppressWarnings("unchecked")
private void loadFile() {
if (fc.showOpenDialog(panel) != JFileChooser.APPROVE_OPTION) {
return;
}
File loadFile = fc.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(loadFile));
List<String[]> dataGrid = new ArrayList<String[]>();
String[] line = reader.readLine().split("\\s+");
int width = line.length;
dataGrid.add(line);
while (reader.ready()) {
line = reader.readLine().split("\\s+");
if (width != line.length) {
throw new IOException();
}
dataGrid.add(line);
}
Grid grid = controller.getAutomaton().initialize(width, dataGrid.size());
for (int i = 0; i < dataGrid.size(); i++) {
line = dataGrid.get(i);
for (int j = 0; j < width; j++) {
grid.setCell(controller.getAutomaton().readCellState(line[j]), new CellPos(j, i));
}
}
controller.setGrid(grid);
controller.setStatus("Brett geladen");
}
catch (FileNotFoundException e) {
controller.setError("Die angegebene Datei konnte nicht gefunden werden.");
}
catch (IOException e) {
controller.setError("Die angegebene Datei entspricht nicht dem erforderlichen Format.");
}
catch (Exception e) {
controller.setError("Die angegebene Datei entspricht nicht dem erforderlichen Format.");
}
} |
eb139564-c85c-450f-aeda-5b796b96614d | 5 | public static int searchHelper(int[] arr, int tgt, int p, int r) {
if ( p > r) {
return -1;
}
int m = (p + r) / 2;
int valMid = arr[m];
// trivial case
if ( valMid == tgt ) {
return m;
}
// non trivial cases
if ( valMid < tgt ) {
if ( arr[r] >= tgt ) {
return searchHelper(arr, tgt, m+1, r);
} else {
return searchHelper(arr, tgt, p, m-1);
}
} else {
if ( arr[p] <= tgt ) {
return searchHelper(arr, tgt, p, m-1);
} else {
return searchHelper(arr, tgt, m+1, r);
}
}
} |
922bdef3-48d0-40a6-9c04-95a2e018beeb | 2 | @Override
public void act() {
if (!checkLife()) {
removeSelfFromGrid();
}
while (this.exp > this.nextExp) {
this.exp -= this.nextExp;
levelUp();
}
} |
2bc3b60d-7070-453f-8200-475c644e758c | 5 | @Test(timeout = 500)
public void testParesAntesImpares() {
int par = 0;
int impar = 0;
int random = 0;
int tam = 0;
int ndx = 0;
int obtido = 0;
int esperado = 0;
List<Integer> lista = null;
String tmpl = null;
String msg = null;
random = getRandom();
if (random % 2 == 0) {
par = random;
impar = random - 1;
} else {
impar = random;
par = random + 1;
}
tam = getRandom();
ndx = rand.nextInt(tam - 1) + 1;
lista = new ArrayList<Integer>();
for (int i = 0; i < ndx; i++) {
lista.add(Integer.valueOf(impar));
}
for (int i = ndx; i < tam; i++) {
lista.add(Integer.valueOf(par));
}
Collections.sort(lista, obj);
tmpl = "Esperado na posição %d valor %d, mas obtido %d. Lista %s";
esperado = par;
for (int i = 0; i < tam - ndx; i++) {
obtido = lista.get(i).intValue();
msg = String.format(tmpl, i, esperado, obtido, lista.toString());
Assert.assertEquals(msg, esperado, obtido);
}
esperado = impar;
for (int i = tam - ndx; i < tam; i++) {
obtido = lista.get(i).intValue();
msg = String.format(tmpl, i, esperado, obtido, lista.toString());
Assert.assertEquals(msg, esperado, obtido);
}
} |
62a03bbb-8311-4993-9406-ee1bb913b93f | 4 | public static void refreshMessages() {
String lastMsg = Session.current().get("lastMsg");
ChatRoom chatRoom = getCurrentChatRoom();
if ( chatRoom == null )
return; //do something here ...
Date lastDate = new Date();
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
Session.current().put("lastMsg", formatter.format(new Date()));
if ( lastMsg != null && !lastMsg.isEmpty() ) {
try {
lastDate = formatter.parse(lastMsg);
} catch (ParseException e) {
e.printStackTrace();
}
}
String messages = chatRoom.getMessagesByDateAsString(lastDate);
List<User> activeUsers = chatRoom.getActiveUsers();
Map<String,Object> json = new HashMap<String,Object>();
json.put("messages", messages);
json.put("users", activeUsers);
renderJSON(json);
} |
65e21979-77c3-4fdf-9817-991e91ed0cb8 | 8 | public void drawLevel(Graphics g){
for(int y = (int) ((Game.cameraLocation.y*scale)/tileHeight), yLoc = (int) -((Game.cameraLocation.y*scale)%tileHeight); y < height && yLoc < game.window.getHeight(); y++, yLoc += tileHeight){
for(int x = (int) ((Game.cameraLocation.x*scale)/tileWidth), xLoc = (int) -((Game.cameraLocation.x*scale)%tileWidth); x < width && xLoc < game.window.getWidth(); x++, xLoc += tileWidth){
if(x < 0 || y < 0) continue;
if(terrain[x+y*width] != -1)
tileset.renderTile(xLoc, yLoc, g, terrain[x+y*width]);
}
}
for(Entity entity : entities.values()){
entity.render(g, scale);
}
} |
b87b93e6-e8d2-4e9f-95dc-1f07be941bd7 | 4 | public void loadWave(String name, String location, int concurrent) {
SoundWave wave = null;
URL waveLocation = Thread.currentThread().getContextClassLoader().getResource(location);
if (waveLocation != null) {
try {
wave = new SoundWave(waveLocation, concurrent);
} catch (SoundFileException e) {
System.err.println("Could not find sound file " + location);
} catch (SoundSystemUnavailableException e) {
System.err.println("Wave not available");
}
}
if (wave != null) {
this.waves.put(name, wave);
}
} |
6c84ef2f-66ab-41a2-a6a7-82a39d1e30a2 | 9 | private BeanKey findParameterKey(final Object parameterOwner, final Class<?> parameterClass,
final Type parameterType, final Annotation[] annotations) {
final String qualifier = qualifierHandler.getQualifier(parameterOwner, annotations);
if (isProvider(parameterClass)) {
final TypeLiteral<?> beanTypeFromProvider = getBeanTypeFromGenericType(parameterOwner, parameterType);
return new ProviderBeanKey(beanTypeFromProvider, qualifier);
}
else if (isCollection(parameterClass)) {
final TypeLiteral<?> actualBeanType = new InputBasedTypeLiteral(parameterType);
final TypeLiteral<?> beanTypeFromCollection = getBeanTypeFromGenericType(parameterOwner, parameterType);
return new CollectionBeanKey(actualBeanType, beanTypeFromCollection, qualifier);
}
else if (isCollectionProvider(parameterClass)) {
final TypeLiteral<?> beanTypeFromCollectionProvider = getBeanTypeFromGenericType(parameterOwner, parameterType);
return new CollectionProviderBeanKey(beanTypeFromCollectionProvider, qualifier);
}
else {
final TypeLiteral<?> beanType = new InputBasedTypeLiteral(parameterType);
return new BeanKey(beanType, qualifier);
}
} |
4da80a7c-4c56-4e14-9511-3408deb09ce2 | 7 | private void doDistrDEEMaster(int numMutable, int strandMut[][],
ParamSet sParams, String strandDefault[][],
String minPEM, String maxPEM, double initEw, PrunedRotamers<Boolean> prunedRotAtRes,
boolean doMinimize, RotamerSearch rs, String sfFile, String rotFile, boolean useSF,
int numSpPos, int typeDEE, boolean minimizeBB, boolean scaleInt, double maxIntScale,
boolean useEref, double eRef[][], boolean addWTRot){
//the total number of residues (active site + ligand, if present)
int totalNumRes = numMutable;
/*if (ligPresent) //ligand is present
totalNumRes++;*/
// Generate all combinations
int numMutRes = 1; //singles
if (typeDEE==optPairs)
numMutRes = 2; //pairs criterion
int numComb = factorial(totalNumRes).divide(factorial(totalNumRes-numMutRes).multiply(factorial(numMutRes))).intValue();
int residueMutatable[][] = new int[numComb][totalNumRes];
generateCombinations(residueMutatable,totalNumRes,numMutRes);
OneMutation mutArray[] = new OneMutation[numComb];
for (int curMut=0; curMut<mutArray.length; curMut++){
mutArray[curMut] = new OneMutation();
mutArray[curMut].mutNum = curMut;
mutArray[curMut].resMut = new int[totalNumRes];
for (int curRes=0; curRes<totalNumRes; curRes++)
mutArray[curMut].resMut[curRes] = residueMutatable[curMut][curRes];
}
boolean splitFlags[][][][][][] = null;
splitFlags = rs.getSplitFlags(splitFlags);//get the current DE pairs
outputObject(splitFlags,sfFile);
int numberOfStrands = strandMut.length;
String AAallowed[][] = new String[numberOfStrands][]; //the AA's to which each residue can mutate
for(int str=0;str<numberOfStrands;str++){
AAallowed[str] = new String[strandMut[str].length];
}
for(int str=0;str<numberOfStrands;str++){
for (int i=0; i<strandMut[str].length; i++)
AAallowed[str][i] = (String)sParams.getValue("RESALLOWED"+str+"_"+i);
}
MutationManager mutMan = new MutationManager(null,mutArray,false);
mutMan.setNumOfStrands(strandMut.length);
mutMan.setStrandMut(strandMut);
mutMan.setStrandDefault(strandDefault);
//mutMan.setLigType(ligType);
mutMan.setarpFilenameMin(minPEM);
mutMan.setarpFilenameMax(maxPEM);
mutMan.setParams(sParams);
mutMan.setStericThresh(stericThresh);
mutMan.setSoftStericThresh(softStericThresh);
mutMan.setMutableSpots(numMutable);
//mutMan.setnumLigRotamers(numLigRotamers);
mutMan.setComputeEVEnergy(true);
mutMan.setDoMinimization(doMinimize);
mutMan.setMinimizeBB(minimizeBB);
mutMan.setCalculateVolumes(false);
mutMan.setInitEw(initEw);
//mutMan.setLigPresent(ligPresent);
mutMan.setUseSF(useSF);
mutMan.setSpFlags(splitFlags);
mutMan.setPrunedRot(prunedRotAtRes);
mutMan.setSfFile(sfFile);
mutMan.setRotFile(rotFile);
mutMan.setDistrDACS(false);
mutMan.setDistrDEE(true);
mutMan.setAAallowed(AAallowed);
mutMan.setNumSpPos(numSpPos);
mutMan.setTypeDEE(typeDEE);
mutMan.setDistDepDielect(distDepDielect);
mutMan.setDielectConst(dielectConst);
mutMan.setDoDihedE(doDihedE);
mutMan.setDoSolvationE(doSolvationE);
mutMan.setSolvScale(solvScale);
mutMan.setVdwMult(softvdwMultiplier);
mutMan.setScaleInt(scaleInt);
mutMan.setMaxIntScale(maxIntScale);
mutMan.setUseEref(useEref);
mutMan.setEref(eRef);
mutMan.setRotamerLibrary(EnvironmentVars.aaRotLib);
mutMan.setDoPerturbations(rs.doPerturbations);
mutMan.setPertFile(rs.pertFile);
mutMan.setMinimizePerts(rs.minimizePerturbations);
mutMan.setAddWTRot(addWTRot);
mutMan.setIdealizeSC(Perturbation.idealizeSC);
try{
handleDoMPIMaster(mutMan,mutArray.length);
}
catch (Exception e){
System.out.println("ERROR: "+e);
System.exit(1);
}
} |
bab7ddd6-5e32-4c5c-8e78-b813b9e7d5de | 6 | @Override
protected boolean handleInternal(AbstractAction action, Agent agent) {
if (messageToSend == null) {
AbstractAction interestingPart = getInterestingPart(action);
if (interestingPart == null) {
// not interested in this action
return true;
}
values = new HashMap<String, String>();
if (interestingPart instanceof SpeakTo) {
values.put("speaker1", agent.toString());
values.put("speaker2", ((SpeakTo) interestingPart).getAgent()
.toString());
CASi.SIM_LOG.info(String.format(
"%s has detected voices of %s and %s", this.toString(),
agent.toString(), ((SpeakTo) interestingPart)
.getAgent().toString()));
} else if (interestingPart instanceof HaveAMeeting) {
HaveAMeeting meeting = (HaveAMeeting) interestingPart;
Random rand = new Random(System.currentTimeMillis());
int escape = 0;
int first = 0;
int second = 0;
int size = meeting.getAgentsInMeeting().size();
while (first == second && escape < 50) {
first = rand.nextInt(size);
second = rand.nextInt(size);
escape++;
}
values.put("speaker1", meeting.getAgentsInMeeting().get(first));
values.put("speaker2", meeting.getAgentsInMeeting().get(second));
CASi.SIM_LOG.info(String.format(
"%s has detected voices of %s and %s", this.toString(),
meeting.getAgentsInMeeting().get(first), meeting
.getAgentsInMeeting().get(second)));
lastValue = values;
} else {
log.warning("Unimplemented Case for action: " + interestingPart);
return true;
}
messageToSend = MACKProtocolFactory.generatePushMessage(agent,
"mike", values);
}
return true;
} |
2a6c7412-ded1-459d-a951-f54e8018f1f4 | 1 | public void setConditionalSentence(boolean b) {
final CycSymbol value = b ? CycObjectFactory.t : CycObjectFactory.nil;
put(CONDITIONAL_SENTENCE, value);
} |
b5eed19e-ccbe-45d8-84be-5c04afff5274 | 3 | public SingleTreeNode uct(StateObservation state) {
SingleTreeNode selected = null;
double bestValue = -Double.MAX_VALUE;
for (SingleTreeNode child : this.children)
{
double hvVal = child.totValue;
double childValue = hvVal / (child.nVisits + this.epsilon);
childValue = Utils.normalise(childValue, bounds[0], bounds[1]);
//System.out.println("norm child value: " + childValue);
double uctValue = childValue +
K * Math.sqrt(Math.log(this.nVisits + 1) / (child.nVisits + this.epsilon));
uctValue = Utils.noise(uctValue, this.epsilon, this.m_rnd.nextDouble()); //break ties randomly
// small sampleRandom numbers: break ties in unexpanded nodes
if (uctValue > bestValue) {
selected = child;
bestValue = uctValue;
}
}
if (selected == null)
{
throw new RuntimeException("Warning! returning null: " + bestValue + " : " + this.children.length + " " +
+ bounds[0] + " " + bounds[1]);
}
//Roll the state:
state.advance(actions[selected.childIdx]);
return selected;
} |
ab2e3b71-50a7-4e33-a708-59ba8613d0ca | 7 | public static TransactionExecutor newLockingExecutor() {
TransactionExecutor.Validator validator = new TransactionExecutor.Validator() {
@Override
public boolean validate() {
if (!WriteSet.getLocal().tryLock()) {
return false;
}
for (LockingTransactionalObject<?> object : ReadSet.getLocal().openedObjects()) {
if (object.isLockedByOtherThread() || !object.isValid()) {
return false;
}
}
return true;
}
};
TransactionExecutor.BeforeOperation beforeOperation = new TransactionExecutor.BeforeOperation() {
@Override
public void execute() {
LocalVersionClock.setCurrent();
}
};
TransactionExecutor.AfterOperation afterOperation = new TransactionExecutor.AfterOperation() {
@Override
public void execute() {
}
};
TransactionExecutor.OnCommit onCommit = new TransactionExecutor.OnCommit() {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void execute() {
long newVersion = GlobalVersionClock.increment();
LocalVersionClock.setCurrent();
WriteSet<?> writeSet = WriteSet.getLocal();
for (LockingTransactionalObject openedObject : writeSet.openedObjects()) {
Object current = openedObject.openForRead();
Copyable localCopy = writeSet.getLocalCopyOf(openedObject);
localCopy.copyTo(current);
openedObject.setVersion(newVersion);
}
writeSet.unlock();
writeSet.clear();
ReadSet.getLocal().clear();
}
};
TransactionExecutor.OnAbort onAbort = new TransactionExecutor.OnAbort() {
@Override
public void execute() {
WriteSet.getLocal().clear();
ReadSet.getLocal().clear();
}
};
TransactionExecutor te = new TransactionExecutor(validator, beforeOperation, afterOperation, onCommit, onAbort) {
@Override
public <E extends Copyable<E>> TransactionalObject<E> makeTransactional(E object) {
return new LockingTransactionalObject<E>(object);
}
};
return te;
} |
2b5e8935-ade4-4b21-9ed8-955b879018fb | 9 | public void load() {
config = new YamlConfiguration();
worldEntries = new HashSet<WorldEntry>();
worldProperties = new HashSet<WorldProperties>();
try {
config.load(new File(plugin.getDataFolder(), "config.yml"));
ConfigurationSection worldLinks = config.getConfigurationSection("world-links");
if(worldLinks == null) {
worldLinks = config.createSection("world-links");
}
for(World world : Bukkit.getWorlds()) {
if(worldLinks.getConfigurationSection(world.getName()) == null)
worldLinks.createSection(world.getName());
}
for(String key : worldLinks.getKeys(false)) {
ConfigurationSection worldLink = worldLinks.getConfigurationSection(key);
WorldEntry entry = new WorldEntry(key);
entry.setAbove(worldLink.getString("above-world"));
entry.setBeneath(worldLink.getString("below-world"));
entry.setDepth(worldLink.getDouble("world-minimum-height", 0));
entry.setHeight(worldLink.getDouble("world-maximum-height", 255));
worldEntries.add(entry);
}
ConfigurationSection worldPropertiesConfig = config.getConfigurationSection("world-properties");
if(worldPropertiesConfig == null) {
worldPropertiesConfig = config.createSection("world-properties");
}
for(World world : Bukkit.getWorlds()) {
if(worldPropertiesConfig.getConfigurationSection(world.getName()) == null)
worldPropertiesConfig.createSection(world.getName());
}
for(String key : worldPropertiesConfig.getKeys(false)) {
ConfigurationSection worldProperty = worldPropertiesConfig.getConfigurationSection(key);
WorldProperties entry = new WorldProperties(key);
entry.setBlockModifier(worldProperty.getDouble("block-modifier", 1));
worldProperties.add(entry);
}
config.save(new File(plugin.getDataFolder(), "config.yml"));
} catch(Exception e) {
e.printStackTrace();
}
} |
97689d5d-2d65-48d7-9269-9caa23be8041 | 3 | public Node nodeAt(int x, int y) {
String s = coordString(x, y);
if (node_map.containsKey(s)) {
Node n = node_map.get(s);
if (n.x == x && n.y == y)
return n;
}
return null;
} |
0a70f9aa-565c-411e-a2a2-ee4f350d4466 | 0 | public Liste getListe() {
return liste;
} |
0232f657-6fcf-49c4-9cc1-f9b3decba967 | 2 | @SuppressWarnings("unchecked")
public void loadDb() {
try {
this.setMusicBuffer((HashMap<String, MusicPersisted>)
this.getMusicDbIn().readObject());
this.setUserBuffer((HashMap<Email, UserPersisted>)
this.getUserDbIn().readObject());
} catch (IOException e) {
this.setMusicBuffer(new HashMap<String, MusicPersisted>());
this.setUserBuffer(new HashMap<Email, UserPersisted>());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} |
b4f4c0ca-3188-4c34-b998-4a04b273a2df | 8 | static public void compareStrings() {
String one = "one";
String two = "two";
String var1 = "one";
String var2 = "Two";
String pieceOne = "o";
String pieceTwo = "ne";
// Comparison is equal
if (one.equals(var1))
System.out.println("String one equals var1 using equals");
// Comparison is NOT equal
if (one.equals(two))
System.out.println("String one equals two using equals");
// Comparison is NOT equal
if (two.equals(var2))
System.out.println("String two equals var2 using equals");
// Comparison is equal, but is not directly comparing string values using ==
if (one == var1)
System.out.println("String one equals var1 using ==");
// Comparison is equal
if (two.equalsIgnoreCase(var2))
System.out.println("String two equals var2 using equalsIgnoreCase");
System.out.println("Trying to use == on Strings that are pieced together");
String piecedTogether = pieceOne + pieceTwo;
// Comparison is equal
if (one.equals(piecedTogether))
System.out.println("The strings contain the same value using equals");
// Comparison is NOT equal using ==
if (one == piecedTogether)
System.out.println("The strings contain the same value using ==");
// Comparison is equal
if (one.compareTo(var1) == 0)
System.out.println("One is equal to var1 using compareTo()");
} |
0c0eb558-cfb0-467d-bec1-78a1e953f3f0 | 0 | public void setSolFechaHora(Date solFechaHora) {
this.solFechaHora = solFechaHora;
} |
c166e2ab-3454-4634-87e2-ff03fba45608 | 0 | public ThreadingIT() throws FileNotFoundException {
out = new PrintStream(new OutputStream() {
@Override
public void write(int b) throws IOException {
// just do nothing
}
});
xmlRunListener = new TestLinkXmlRunListener(out, "donald");
loggingRunListener = new TestLinkLoggingRunListener(LoggerFactory.getLogger("THREADINGIT"),
URI.create("http://testlink.example.org/"));
} |
c466a20f-f6aa-45bb-8122-88f89465b0bc | 4 | private int digitalSum(int x) {
int[] number = new int[1000];
number[0] = 2;
int len = 1;
int high = 0;
for (int i = 2; i <= x; i++) {
for (int j = 0; j < len; j++) {
number[j] = number[j] * 2 + high;
high = number[j] / 10;
number[j] = number[j] % 10;
}
if (high > 0) {
number[len] = high;
len++;
high=0;
}
}
int res = 0;
for (int i = 0; i < len; i++) {
res += number[i];
}
return res;
} |
08db0af0-5bdc-4845-afe6-5aa9c8b082c8 | 8 | public int [][] multiResultsetWins(int comparisonColumn, int [][] nonSigWin)
throws Exception {
int numResultsets = getNumResultsets();
int [][] win = new int [numResultsets][numResultsets];
// int [][] nonSigWin = new int [numResultsets][numResultsets];
for (int i = 0; i < numResultsets; i++) {
for (int j = i + 1; j < numResultsets; j++) {
System.err.print("Comparing (" + (i + 1) + ") with ("
+ (j + 1) + ")\r");
System.err.flush();
for (int k = 0; k < getNumDatasets(); k++) {
try {
PairedStats pairedStats =
calculateStatistics(m_DatasetSpecifiers.specifier(k), i, j,
comparisonColumn);
if (pairedStats.differencesSignificance < 0) {
win[i][j]++;
} else if (pairedStats.differencesSignificance > 0) {
win[j][i]++;
}
if (pairedStats.differencesStats.mean < 0) {
nonSigWin[i][j]++;
} else if (pairedStats.differencesStats.mean > 0) {
nonSigWin[j][i]++;
}
} catch (Exception ex) {
//ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
}
}
return win;
} |
08486295-e3f0-4ebf-b42a-3375adcfd42b | 5 | @Override
public void update()
{
for (Input i : pressedKeys)
{
switch (i)
{
case PLR1RIGHT:
rp.playerGo(1, Const.right);
break;
case PLR1LEFT:
rp.playerGo(1, Const.left);
break;
case PLR1UP:
rp.playerGo(1, Const.up);
break;
case PLR1DOWN:
rp.playerGo(1, Const.down);
break;
default:
break;
}
}
} |
509a99a9-26f9-4925-8528-f1d7f9f1ce4d | 9 | @SuppressWarnings("unchecked")
public static LinkedHashMap<String,Object> objectToArray(Object object) {
LinkedHashMap<String,Object> data= new LinkedHashMap<String,Object>();
if (object == null) return data;
if (Functions.method_exists(object,"toArray")) {
Object retObj = Functions.call_method(object,"toArray");
if (retObj instanceof LinkedHashMap) return (LinkedHashMap<String,Object>) retObj;
}
Map<String,Object> vars = Functions.get_object_vars(object);
for (Map.Entry<String,Object> entry: vars.entrySet()) {
String key = (String) entry.getKey();
Object value = (Object) entry.getValue();
if (value instanceof Map) {
Map<String,Object> valueMap = (Map<String,Object>) value;
data.put(key,Functions.processArray(valueMap));
} else if (Functions.is_string(value)) {
data.put(key,value);
} else if (Functions.is_object(value)) {
if (!Functions.method_exists(value,"toArray")) {
data.put(key,Functions.objectToArray(value));
} else {
Object retObj = Functions.call_method(value,"toArray");
if (retObj instanceof LinkedHashMap) data.put(key, (LinkedHashMap<String,Object>) retObj);
}
} else {
data.put(key,value);
}
}
return data;
} |
6ac15225-db34-4a66-b5d9-bb2930b505ac | 3 | public static List<Node> bfs(double graph[][],int s)
{
int length=graph.length;
List<Node> nodeList=NodeUtil.generateNodeList(graph);
nodeList.get(s).distance=0;
nodeList.get(s).state=1;
Queue<Node> queue=new LinkedList<Node>();
queue.add(nodeList.get(s));
while(!queue.isEmpty())
{
Node u=queue.poll();
for(Node n:u.getAdjacentNodes())
{
if(n.state==0)
{
n.state=1;
n.distance=u.distance+1;
n.setParent(u);
queue.add(n);
}
}
u.state=2;
}
return nodeList;
} |
fc632135-c324-4fd5-9a7d-91e8daa737b9 | 7 | public void InitView() {
pane = new VBox();
//Stworzenie wykresu
lineChart = LinearChartManager.linear();
lineChart.setTitle("");
//Poczatkowo zakres dat to 3M
selectedRange = DataRange.THREEMONTH;
selectedChart = "line";
//Stworzenie tabelki
table = new TableView();
//Sciągamy dane dla tabelki z serwera i populujemy tabelke
try {
table.getItems().addAll(NetworkManager.show(DataType.WSK));
} catch (Exception e) {
System.out.println("Something went wrong when populating market indicisies view");
}
//Dodajemy kolumny do tabelki
table.getColumns().addAll(initColumns());
//Obsługa kliknięcia wiersza w tabelce
table.setRowFactory(tv -> {
TableRow<Index> row = new TableRow<Index>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
//Zapamiętujemy wybrany wiersz dla widoku
Index rowData = row.getItem();
selectedIndex = rowData;
//System.out.println(rowData);
try {
//Sciągamy dane z serwera dla danego wiersza i dodajemy je do wykresu
lastData = NetworkManager.showMore(rowData.getSymbol(), selectedRange);
System.out.println(lastData.length);
if (selectedChart.equals("line")) {
lineChart.getData().clear();
LinearChartManager.addSeries(lineChart, lastData, selectedRange);
lineChart.setTitle(rowData.getName());
if (pointerType != null && pointerType != "hide") {
OnPointerChange();
}
} else {
CandleChart.generateData(lastData);
candleChart = new CandleChart();
CandleChart.CandleStickChart chart = candleChart.createChart();
chart.setTitle(rowData.getName());
pane.getStylesheets().add("resources/css/CandleStickChart.css");
borderPane.setCenter(chart);
}
} catch (Exception ex) {
System.out.println("Error while downloading indicise " + ex.toString());
}
}
});
return row;
});
//table.setItems(initRows());
table.setEditable(false);
VBox vBox = (VBox) pane;
//Panel dla wykresu i przycisków konfiguracyjnych
borderPane = new BorderPane();
//Po środku wykres
borderPane.setCenter(lineChart);
//Na prawo przyciski konfiguracyjne
borderPane.setRight(addMenuButtons());
//Dodanie do panelu widoku tabelki
vBox.getChildren().add(table);
//Dodanie do panelu widoku panelu z wykresem i przyciskami konfiguracyjnymi
vBox.getChildren().add(borderPane);
} |
4d4af2b7-5d91-4409-881f-ebb442c7d65c | 9 | public void openWindow() throws IOException {
openedWindows++;
if (frame != null)
return;
frame = new JFrame(EditorPanel.WINDOW_NAME);
frame.setIconImage(U.getAppIcon());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
Point p = U.Config.readFrameSize();
U.setFrameSize(frame, p.x, p.y);
frame.getContentPane().add(this);
frame.setTransferHandler(new U.TH(this));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
private long lastWarning;
@Override
public void windowActivated(WindowEvent e) {
for (PlainPage pp : pageSet) {
if (U.changedOutside(pp)) {
long t = new File(pp.pageData.getFn()).lastModified();
if (t > lastWarning) {
lastWarning = t;
if (!pp.changedOutside) {
pp.changedOutside = true;
if (pp.pageData.history.size() == 0) {
U.readFile(pp.pageData, pp.pageData.getFn());// reload
U.showSelfDispMessage(pp, "File changed outside.(reloaded)", 4000);
pp.changedOutside = false;
} else {
U.showSelfDispMessage(pp, "File changed outside.", 4000);
}
// break;
}
}
}
}
// EditPanel.this.requestFocus();
}
public void windowClosed(WindowEvent e) {
System.out.println("closed");
openedWindows--;
}
@Override
public void windowClosing(WindowEvent e) {
for (PlainPage pp : pageSet) {
if (pp.pageData.getFn() != null) {
try {
U.saveFileHistory(pp.pageData.getFn(), pp.cy + 1);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
System.out.println("exit");
}
});
// frame.addWindowFocusListener(new WindowAdapter() {
// public void windowGainedFocus(WindowEvent e) {
// EditPanel.this.requestFocusInWindow();
// }
// });
changeTitle();
repaint();
} |
0da7ee8f-f2cb-41da-9258-39dcc021bc02 | 5 | public void HandleKeyboardEvent()
{
int key = Keyboard.getEventKey();
if (IsInKeyRange(key))
{
if (Keyboard.getEventKeyState())
{
if (mRecordingKeys)
{
if (key == 14)
{
if (inputString.length() > 0)
{
inputString = inputString.substring(0, inputString.length() - 1);
}
}
else
{
inputString += KeyToString(key);
}
}
KeyDown(key);
}
else
{
KeyUp(key);
}
}
} |
0288e640-c672-454c-8da5-5dd11f189cc1 | 9 | public boolean variable_declaration() {
// check format: type identifier ["[" "]"] ["=" assignment_expression ] ";"
boolean variableHasBeenAdded = false;
Variable_SAR variableSar = null;
typePush(new Type_SAR(lexicalAnalyzer.getToken(), scope));
if (!typeExists()) {
return false;
}
popSAS();
String type = lexicalAnalyzer.getToken().getName();
lexicalAnalyzer.nextToken();
Tuple variable = lexicalAnalyzer.getToken();
lexicalAnalyzer.nextToken();
if (lexicalAnalyzer.getToken().getType().equals(LexicalAnalyzer.tokenTypesEnum.ARRAY_BEGIN.name())) {
lexicalAnalyzer.nextToken();
variableSar = new Variable_SAR(variable, scope, "V" + variableId++, "@:" + type);
variablePush(variableSar);
variableHasBeenAdded = true;
lexicalAnalyzer.nextToken();
}
if (!variableHasBeenAdded) {
variableSar = new Variable_SAR(variable, scope, "V" + variableId++, type);
variablePush(variableSar);
}
String[] values = isInSymbolTable(variableSar);
if (values == null) {
errorList += "there is an error in class 'PassTwo' line: 665.\n";
return false;
}
SAS.peek().setSarId(values[1]);
if (values[0].equalsIgnoreCase(KeyConst.INT.getKey())) {
iCodeList.add(new ICode(values[1], ICodeOprConst.CREATE_OPR.getKey(), ".INT", "", "", ""));
} else {
iCodeList.add(new ICode(values[1], ICodeOprConst.CREATE_OPR.getKey(), ".BYT", "", "", ""));
}
if (lexicalAnalyzer.getToken().getType().equals(LexicalAnalyzer.tokenTypesEnum.ASSIGNMENT_OPR.name())) {
if (!operatorPush(new Opr_SAR(lexicalAnalyzer.getToken()))) {
return false;
}
lexicalAnalyzer.nextToken();
if (!assignment_expression()) {
return false;
}
} else {
popSAS();
}
if (!EOE()) {
return false;
}
lexicalAnalyzer.nextToken();
return true;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.