method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
3be4b1dd-be0c-4d25-af10-f611fef42cee
| 0 |
public Sun(){
setDirection((new Vector3f(-0.5f, -0.5f, -0.5f)).normalizeLocal());
setColor(ColorRGBA.White.set(1.6f, 1.6f, 1f, 0f));
this.setName("Sun");
}
|
95381cbc-47f5-4962-8f71-aaa2bcac6fd0
| 6 |
public void stop() {
for (Player p : players) {
if (p != null) {
p.disconnect();
}
}
if (discoveryThread.isAlive()) {
discovery.close();
}
if (server != null && !server.isClosed()) {
try {
server.close();
} catch (IOException e) {
}
}
}
|
e3f186a0-58bc-4cf3-b0d2-ba5e34f83cfa
| 9 |
private SocketFace getSocket(byte[] data, int off, int len)
throws SocketException
{
if (mSocket != null) {
return mSocket;
}
if (mClosed) {
throw new SocketException("Socket is closed");
}
long timeout = mTimeout;
long start;
if (timeout > 0) {
start = System.currentTimeMillis();
}
else {
start = 0;
}
try {
mSocket = mFactory.getSocket(mSession, timeout);
applyOptions();
OutputStream out = mSocket.getOutputStream();
out.write(data, off, len);
out.flush();
}
catch (Exception e) {
if (mSocket != null) {
try {
mSocket.close();
}
catch (Exception e2) {
}
}
if (timeout > 0) {
timeout = timeout - (System.currentTimeMillis() - start);
if (timeout < 0) {
timeout = 0;
}
}
mSocket = mFactory.createSocket(mSession, timeout);
applyOptions();
try {
OutputStream out = mSocket.getOutputStream();
out.write(data, off, len);
out.flush();
}
catch (IOException e2) {
throw new SocketException(e2.getMessage());
}
}
return mSocket;
}
|
d3c44658-3a2d-4c90-a2ef-569b84d300fe
| 3 |
public void verify() throws VerifyException {
try {
doVerify();
} catch (VerifyException ex) {
for (Iterator i = bi.getInstructions().iterator(); i.hasNext();) {
Instruction instr = (Instruction) i.next();
VerifyInfo info = (VerifyInfo) instr.getTmpInfo();
if (info != null)
GlobalOptions.err.println(info.toString());
GlobalOptions.err.println(instr.getDescription());
instr.setTmpInfo(null);
}
throw ex;
}
}
|
b5ed056c-36d9-43a4-ab6d-6e5aac106ad0
| 3 |
public void updateControls()
{
if(pModel.getProperty(PRP_MODE).equals(CMD_PLAYBACK_MODE))
{
massInput.setEnabled(false);
radiusInput.setEnabled(false);
xCord.setEnabled(false);
yCord.setEnabled(false);
vx.setEnabled(false);
vy.setEnabled(false);
fix.setEnabled(false);
angle.setEnabled(false);
name.setEnabled(false);
MaterialCombo.setEnabled(false);
colorBox.setEnabled(false);
del.setEnabled(false);
}
else
{
massInput.setEnabled(true);
radiusInput.setEnabled(true);
xCord.setEnabled(true);
yCord.setEnabled(true);
vx.setEnabled(true);
vy.setEnabled(true);
fix.setEnabled(true);
angle.setEnabled(true);
if (!pModel.hasMultiSelectionObjects())
{
name.setEnabled(true);
}
else
{
name.setEnabled(false);
}
MaterialCombo.setEnabled(true);
colorBox.setEnabled(true);
del.setEnabled(true);
}
if (pModel.hasMultiSelectionObjects())
{
selObjectsLabel.setVisible(true);
}
else
{
selObjectsLabel.setVisible(false);
}
}
|
ca290aeb-cc7f-4fcb-b4ed-f6be50fd4d8a
| 9 |
public static HTTPRequest mergeRoomFields(final HTTPRequest httpReq, Pair<String,String> setPairs[], Room R)
{
final Hashtable<String,String> mergeParams=new XHashtable<String,String>(httpReq.getUrlParametersCopy());
final HTTPRequest mergeReq=new HTTPRequest()
{
public final Hashtable<String,String> params=mergeParams;
@Override
public String getHost()
{
return httpReq.getHost();
}
@Override
public String getUrlPath()
{
return httpReq.getUrlPath();
}
@Override
public String getFullRequest()
{
return httpReq.getFullRequest();
}
@Override
public Map<String,String> getUrlParametersCopy()
{
return new XHashtable<String,String>(params);
}
@Override
public String getUrlParameter(String name)
{
return params.get(name.toLowerCase());
}
@Override
public boolean isUrlParameter(String name)
{
return params.containsKey(name.toLowerCase());
}
@Override
public Set<String> getUrlParameters()
{
return params.keySet();
}
@Override
public HTTPMethod getMethod()
{
return httpReq.getMethod();
}
@Override
public String getHeader(String name)
{
return httpReq.getHeader(name);
}
@Override
public InetAddress getClientAddress()
{
return httpReq.getClientAddress();
}
@Override
public int getClientPort()
{
return httpReq.getClientPort();
}
@Override
public InputStream getBody()
{
return httpReq.getBody();
}
@Override
public String getCookie(String name)
{
return httpReq.getCookie(name);
}
@Override
public Set<String> getCookieNames()
{
return httpReq.getCookieNames();
}
@Override
public List<MultiPartData> getMultiParts()
{
return httpReq.getMultiParts();
}
@Override
public double getSpecialEncodingAcceptability(String type)
{
return httpReq.getSpecialEncodingAcceptability(type);
}
@Override
public String getFullHost()
{
return httpReq.getFullHost();
}
@Override
public List<long[]> getRangeAZ()
{
return httpReq.getRangeAZ();
}
@Override
public void addFakeUrlParameter(String name, String value)
{
params.put(name.toLowerCase(), value);
}
@Override
public void removeUrlParameter(String name)
{
params.remove(name.toLowerCase());
}
@Override
public Map<String,Object> getRequestObjects()
{
return httpReq.getRequestObjects();
}
@Override
public float getHttpVer()
{
return httpReq.getHttpVer();
}
@Override
public String getQueryString()
{
return httpReq.getQueryString();
}
};
for(final String[] pair : STAT_CHECKS)
{
if(mergeReq.isUrlParameter(pair[1]) && (mergeReq.getUrlParameter(pair[1]).length()==0))
mergeReq.addFakeUrlParameter(pair[1].toLowerCase(), R.getStat(pair[0]));
}
CMLib.map().resetRoom(R);
R=(Room)R.copyOf();
final RoomStuff stuff=new RoomStuff(R);
final Pair<String,String>[] activePairs = makePairs(stuff,new Vector<Pair<String,String>>());
final List<Pair<String,String>> submittedRoomPairsList = toPairs(mergeParams);
final List<Pair<String,String>> commonRoomsPairsList=Arrays.asList(setPairs);
final List<Pair<String,String>> currentRoomPairsList=new XVector(Arrays.asList(activePairs));
RoomData.mergeRoomField(currentRoomPairsList,commonRoomsPairsList,submittedRoomPairsList,new String[]{"AFFECT","ADATA"});
RoomData.mergeRoomField(currentRoomPairsList,commonRoomsPairsList,submittedRoomPairsList,new String[]{"BEHAV","BDATA"});
RoomData.mergeRoomField(currentRoomPairsList,commonRoomsPairsList,submittedRoomPairsList,new String[]{"MOB"});
RoomData.mergeRoomField(currentRoomPairsList,commonRoomsPairsList,submittedRoomPairsList,new String[]{"ITEM","ITEMWORN","ITEMCONT"});
for(final Pair<String,String> p : currentRoomPairsList)
{
if(p.second==null)
mergeParams.remove(p.first);
else
mergeParams.put(p.first, p.second);
}
if(!mergeParams.containsKey("AFFECT1"))
mergeParams.put("AFFECT1", "");
if(!mergeParams.containsKey("BEHAV1"))
mergeParams.put("BEHAV1", "");
if(!mergeParams.containsKey("MOB1"))
mergeParams.put("MOB1", "");
if(!mergeParams.containsKey("ITEM1"))
mergeParams.put("ITEM1", "");
return mergeReq;
}
|
bdf47104-7462-4092-b7a2-cf872db788de
| 9 |
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
int quantity = 1;
Player target;
if (args.length == 0) {
sender.sendMessage(ChatColor.RED + "/spawnhead [username] <quantity> <player>");
return true;
}
if (!args[0].matches("[A-Za-z0-9_]{2,16}")) {
sender.sendMessage(ChatColor.RED + "That doesn't appear to be a valid username");
return true;
}
if (args.length > 1) {
try {
quantity = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "That's not a number");
return true;
}
if (quantity < 1) {
quantity = 1;
} else if (quantity > 64) {
quantity = 64;
}
}
if (args.length > 2) {
try {
target = getPlayer(args[2], sender);
} catch (BadPlayerMatchException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return true;
}
} else {
if (sender instanceof Player) {
target = (Player) sender;
} else {
sender.sendMessage(ChatColor.RED + "Specify a player to give the weapon to");
return true;
}
}
ItemStack i = new ItemStack(Material.SKULL_ITEM, quantity, (short) 3);
SkullMeta meta = (SkullMeta) i.getItemMeta();
meta.setOwner(args[0]);
i.setItemMeta(meta);
target.getInventory().addItem(i);
return true;
}
|
553c33c8-edca-4248-95b2-9de62937981a
| 2 |
public void close() throws IOException {
if (!this.stack.empty()) {
throw new InvalidObjectException("Tags are not all closed. " +
"Possibly, " + this.stack.pop() + " is unclosed. ");
}
if (thisIsWriterOwner)
{
this.writer.flush();
this.writer.close();
}
}
|
bb85d54e-a676-4280-800d-6df30385469e
| 3 |
@Override
public void setAccounting(Accounting accounting) {
accounts=accounting==null?null:accounting.getAccounts();
accountTypes=accounting==null?null:accounting.getAccountTypes();
projects=accounting==null?null:accounting.getProjects();
}
|
dda6b10f-3dd4-4366-9c2e-f2d797a7eaee
| 1 |
public StartRenderer()
{
try
{
Start3 = ImageIO.read(new File(Main.loc + "/Textures/Game.png"));
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null, new File(Main.loc + "Textures/Game.png").getAbsolutePath(), "UNABLE TO LOAD IMAGES",JOptionPane.ERROR_MESSAGE);
}
}
|
403b8445-c2f2-4f2c-9e11-7543f563351b
| 9 |
private ArrayList<Sentence> caseOne(String endGoto,int startIndex,HashMap<String,String> cases){
ArrayList<Sentence> ls = new ArrayList<Sentence>();
for (int i = startIndex; i < this.senList.size();) {
Sentence s = this.senList.get(i);
//if (s.getName().equals("goto") || s.getName().equals("switch_goto")) {
if (s.getName().equals("goto")) {
GotoSentence gt = (GotoSentence)s;
if (gt.getTarget().equals(endGoto)) {
//FIXME 这里暂时用out中是否包含return 判断,未判明return是否是有效java语句
boolean hasReturn = false;
if (this.senList.get(i-1).getOut().indexOf("return ")>-1) {
hasReturn = true;
}
if (hasReturn) {
gt.setOut("//break;");
}else{
gt.setOut("break;");
}
//此处将goto彻底变为switch语句,不再if处理中受影响
// gt.setSwitch();
gt.over();
ls.add(gt);
this.senList.remove(i);
break;
}else{
//FIXME 应该是return或while内的continue,break,仍需要跳出
gt.setOut("goto somewhere; //maybe return,continue,break: "+gt.getLine());
gt.over();
ls.add(gt);
this.senList.remove(i);
break;
}
}else if(s.getName().equals("return")){
//将return的注释去掉
if (s.getOut().startsWith("//")) {
s.setOut(s.getOut().substring(2));
}
ls.add(s);
this.senList.remove(i);
// hasReturnCase = true;
break;
}else if(s.getName().equals("switch")){
String t = s.getLine();
if (cases.containsKey(t)) {
break;
}
}
ls.add(this.senList.remove(i));
}
return ls;
}
|
9ba8b83f-34c3-4100-aa18-8cdc2ba31906
| 6 |
private BoundingBox calculateBoundingBox(Cluster center, Direction direction) {
if (Direction.CENTER == direction) {
return center.getBoundingBox();
}
BoundingBox oldBoundingBox = center.getBoundingBox();
double oldWidth = oldBoundingBox.getWidth();
double oldHeight = oldBoundingBox.getHeight();
GeoPosition oldTopLeftPosition = oldBoundingBox.getTopLeft();
GeoPosition oldTopRightPosition = oldBoundingBox.getTopRight();
GeoPosition oldBottomRightPosition = oldBoundingBox.getBottomRight();
GeoPosition oldBottomLeftPosition = oldBoundingBox.getBottomLeft();
GeoPosition newTopLeftPosition = null;
GeoPosition newBottomRightPosition = null;
switch (direction) {
case BOTTOM:
// y-height
newTopLeftPosition = oldBottomLeftPosition;
newBottomRightPosition = CoordinateUtil.positionAt(
oldBottomRightPosition, directionToDirection(direction),
oldHeight);
break;
case LEFT:
// x-width
newTopLeftPosition = CoordinateUtil.positionAt(oldTopLeftPosition,
directionToDirection(direction), oldWidth);
newBottomRightPosition = oldBottomLeftPosition;
break;
case RIGHT:
// x+width
newTopLeftPosition = oldTopRightPosition;
newBottomRightPosition = CoordinateUtil.positionAt(
oldBottomRightPosition, directionToDirection(direction),
oldHeight);
break;
case TOP:
// y+width
newTopLeftPosition = CoordinateUtil.positionAt(oldTopLeftPosition,
directionToDirection(direction), oldWidth);
newBottomRightPosition = oldTopRightPosition;
break;
default:
throw new RuntimeException("unknwon direction: " + direction);
}
BoundingBox newBoundingBox = boundingBoxFromGeoPositions(
newTopLeftPosition, newBottomRightPosition);
if (MapsRacer.DEBUG) {
System.out.println("old width: " + oldWidth + " vs new width: "
+ newBoundingBox.getWidth());
System.out.println("old height: " + oldHeight + " vs new height: "
+ newBoundingBox.getHeight());
}
return newBoundingBox;
}
|
2bec2f59-6a0b-45c7-ae97-254f60786f5f
| 2 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
|
b6c37996-e45a-44b3-b2b6-2866342e24af
| 6 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Vertex))
return false;
Vertex other = (Vertex) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
|
59de1203-d678-4554-842a-6c10173f2ba3
| 6 |
private GameState gunnerDay(GameState state, Card card, boolean output)
{
Color faction = card.getFaction();
String log = "";
//First, we pay the gunner
log = log + Faction.getPirateName(faction) + " paid ";
int payment = 0;
if(state.getPlayer(faction).getGold() > 3)
{
payment = 3;
}
else
{
payment = state.getPlayer(faction).getGold();
}
GameState endState = new GameState(state);
endState.getPlayer(faction).addGold(-payment);
log = log + payment + " gold to their Gunner (" + card.abbreviate() + ") and";
//Next we kill the appropriate card (or don't)
Card[] possibleArray = new Card[0];
HashSet<Card> possibleSet = new HashSet<Card>();
for(Player p : endState.getPlayerList())
{
possibleSet.addAll(p.getDen());
}
if(possibleSet.isEmpty())
{
log = log + " wasn't able to kill anybody!";
if(output)
{
endState.log(log);
}
return endState;
}
possibleArray = possibleSet.toArray(possibleArray);
if(endState.getPlayer(faction).checkCPU())
{
HashMap<GameState, String> map = allKillOutcomes(state, possibleArray);
endState = endState.getPlayer(faction)
.chooseState(map.keySet().toArray(new GameState[0]), card);
log = log + " killed " + map.get(endState) + "!";
}
else
{
Card choice = endState.getPlayer(faction).getGUI()
.makeChoice("Choose a card for the Gunner to shoot:", possibleArray);
Player widower = endState.getPlayer(choice.getFaction());
widower.removeFromDen(choice);
widower.addToDiscard(choice);
log = log + " killed " + choice.abbreviate() + "!";
}
if(output)
endState.log(log);
return endState;
}
|
8c79cc53-7587-4c23-ae2a-843783bf6578
| 2 |
@Test
public void test() {
Question1 it = new Question1();
for (int b = 0; b < 10; b++) {
Question1NumGenerator g = new Question1NumGenerator(1, b);
for (int i = 1; i < 10000; i++) {
int aa = g.next();
int bb = it.largestLable(i, b);
Assert.assertEquals(aa, bb);
}
}
}
|
86d72fe5-dc8b-4181-99f3-687147b38b1c
| 0 |
public Card(String cardRank, String cardSuit, int cardPointValue) {
rank = cardRank;
suit = cardSuit;
pointValue = cardPointValue;
}
|
b22ef032-aa66-4d1f-8e87-c36521c24981
| 8 |
private int addNeighbours(Point target, List<Point> list){
int count = 0;
if (target.y - 2 >= 0) if (this.maze[target.x][target.y - 2] == true) {list.add(new Point(target.x, target.y - 1));count++;}
if (target.y + 2 <= this.length - 2) if (this.maze[target.x][target.y + 2] == true) {list.add(new Point(target.x, target.y + 1));count++;}
if (target.x - 2 >= 0) if (this.maze[target.x - 2][target.y] == true) {list.add(new Point(target.x - 1, target.y));count++;}
if (target.x + 2 <= this.width - 2) if (this.maze[target.x + 2][target.y] == true) {list.add(new Point(target.x + 1, target.y));count++;}
return count;
}
|
27509fa0-4f65-44e7-9234-89eb624cf027
| 3 |
public LogisticClassifier() {
// option value for gradient descent
gd_iteration = 20;
if (CommandLineUtilities.hasArg("gd_iterations"))
gd_iteration = CommandLineUtilities.getOptionValueAsInt("gd_iterations");
gd_eta = .01;
if (CommandLineUtilities.hasArg("gd_eta"))
gd_eta = CommandLineUtilities.getOptionValueAsFloat("gd_eta");
num_of_features = -1;
if (CommandLineUtilities.hasArg("num_features_to_select"))
num_of_features = CommandLineUtilities.getOptionValueAsInt("num_features_to_select");
linearParam = new FeatureVector();
}
|
21f2369d-2f3d-42b7-a54e-d2c878d665a0
| 3 |
public List<Effect> getEffectsOnPosition(Position position) {
if (!validPosition(position))
throw new IllegalArgumentException("The given position isn't valid!");
List<Effect> posElements = new ArrayList<Effect>();
for (Effect effect : effects) {
if (effect.getPosition().equals(position))
posElements.add(effect);
}
return Collections.unmodifiableList(posElements);
}
|
90c4782c-8dcd-4575-a95b-4a1187e95a03
| 2 |
public static MobilityEnumeration fromValue(String v) {
for (MobilityEnumeration c: MobilityEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
|
0eeb091f-e571-42e4-9d0f-1d319287aae3
| 4 |
@Test
public void popsByHeapRules()
{
for (int i = 1; i < 16; i++)
heap.insert(i);
heap.pop();
int[] ar = new int[heap.size()];
for (int i = 0; i < heap.size(); i++)
ar[i] = i + 1;
ar[0] = 2;
ar[1] = 4;
ar[3] = 8;
ar[7] = 15;
boolean test = true;
for (int i = 0; i < heap.size(); i++)
if (ar[i] != (int)heap.getArray()[i]) test = false;
assertTrue(test);
}
|
b068159c-4397-4a7a-a909-36d6aba1d1fa
| 2 |
public Boolean isStaff( Player p )
{
if ( isAdmin( p ) || p.hasPermission( "iNations.staff" ) )
return true;
return false;
}
|
101d0e2f-a049-4845-8000-4650187d8fda
| 6 |
public int lengthOfLastWord(String s) {
int i =0;
if(s==null || s.length() == 0)
return 0;
while(s.charAt(s.length()-1) == ' '){
if(s.length()-1 <= 0)
break;
s = s.substring(0, s.length()-1);
}
while(i<s.length()){
if(s.charAt(i) == ' '){
s = s.substring(i+1);
i = -1;
}
i++;
}
return s.length();
}
|
90325d52-466a-4a69-b241-58cdba848aab
| 8 |
public String[] compileAssembler(String text) {
opcodeTable.clear();
addOpcode();
String[] lines = text.split("\\r?\\n");
String[] maschin = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
String[] args = line.split(" ");
if (args.length == 0) continue;
if (opcodeTable.containsKey(args[0])) {
String opcode = opcodeTable.get(args[0]);
int argA = (args.length >= 2) ? Integer.valueOf(args[1]) : 0;
int argB = (args.length >= 3) ? Integer.valueOf(args[2]) : 0;
//System.out.println(argA+" "+argB);
String argA4 = toBinary(argA, 4);
//System.out.println(argA4);
String argB4 = toBinary(argB, 4);
String argA16 = toBinary(argA, 16);
String argB16 = toBinary(argB, 16);
if (argA4 == null) argA4 = "";
if (argB4 == null) argB4 = "";
//if (argA4 == null) System.out.println("argA4 Fehler in "+line);
//if (argB4 == null) System.out.println("argB4 Fehler in "+line);
//if (argA16 == null) System.out.println("argA16 Fehler in "+line);
//if ( argB16 == null) System.out.println("argB16 Fehler in "+line);
opcode = opcode.replace("A4", argA4);
opcode = opcode.replace("B4", argB4);
opcode = opcode.replace("A16", argA16);
opcode = opcode.replace("B16", argB16);
maschin[i] = opcode;
} else {
System.out.println("unknown command: "+line);
}
}
String[] hex = new String[maschin.length];
for (int i = 0; i < maschin.length; i++) {
hex[i] = Integer.toHexString(Integer.parseInt(maschin[i], 2));
}
return hex;
}
|
402c2a7d-3ed3-47cd-8e05-9b79757dc790
| 9 |
public static void loadModelTowers(){
File file = new File("resources/saves/towersSave.txt");
GameData.modelTowers = new ArrayList<Tower>();
try{
Scanner loadScanner = new Scanner(file);
while(loadScanner.hasNext() && GameData.modelTowers.size() < 7){
Tower tower = new Tower();
String barrelName = loadScanner.nextLine();
String ammoName = loadScanner.nextLine();
String baseName = loadScanner.nextLine();
for(Barrel barrel : GameData.barrels){
if(barrel.getName().equals(barrelName)){
tower.setBarrel(barrel);
}
}
for(Ammo ammo : GameData.ammo){
if(ammo.getName().equals(ammoName)){
tower.setAmmo(ammo);
}
}
for(Base base : GameData.bases){
if(base.getName().equals(baseName)){
tower.setBase(base);
}
}
tower.updateProperties();
GameData.modelTowers.add(tower);
loadScanner.close();
}
}catch (Exception e) {}
}
|
65062272-2173-471b-90bf-48b8b82f5841
| 2 |
public void push(QWidget widget)
{
if (layout.currentWidget() == null || layout.currentWidget().getClass() != widget.getClass()) {
layout.addWidget(widget);
layout.setCurrentIndex(layout.count()-1);
}
}
|
2846e583-b6d6-496d-91a6-18232b60ae70
| 3 |
public void onBlockRemoval(World var1, int var2, int var3, int var4) {
byte var5 = 2;
for(int var6 = var2 - var5; var6 <= var2 + var5; ++var6) {
for(int var7 = var3 - var5; var7 <= var3 + var5; ++var7) {
for(int var8 = var4 - var5; var8 <= var4 + var5; ++var8) {
var1.notifyBlocksOfNeighborChange(var6, var7, var8, var1.getBlockId(var6, var7, var8));
}
}
}
}
|
41318cf7-58f1-4a07-bd1a-f5ec56f29e75
| 2 |
public void setGravity(boolean gravity) {
GRAVITY = gravity;
if(gravity) {
if(gravityThread == null) {
Runnable gravityJob = new GravityJob(this);
gravityThread = new Thread(gravityJob);
gravityThread.start();
}
} else {
gravityThread = null;
}
}
|
b46096ca-7bbf-45ab-a157-d9cc194a73dd
| 6 |
public void act()
{
if(isAtEdge() && checkLoadingState()){
//MiniGame2 w = (MiniGame2) getWorld();
//w.removeFromList(index);
getWorld().removeObject(this);
return;
}
if(atTruckStop())
{
return;
}
if(canAddTruck())
{
addTruck();
}
if(getTruckState())
{
moveContainer();
return;
}
if(checkLoadingState())
{
this.allowTruckToMove();
getPullingTruck().allowTruckToMove();
return;
}
}
|
b3a9a8f4-b9fd-4af1-9377-d9baf3818610
| 4 |
Arc[] split( int offset ) throws MVDException
{
Arc[] arcs=null;
// handle simple cases first
if ( offset == 0 || offset == dataLen())
{
arcs = new Arc[1];
arcs[0] = this;
}
else if ( parent == null )
{
if ( children == null )
arcs = splitDataArc( offset );
else
arcs = splitParent( offset, null );
}
else
arcs = splitChild( offset );
return arcs;
}
|
42c277a1-915c-4712-8ada-99c1d0b4d9ec
| 9 |
public void clickUpdate(Point p) { //bit messy but C'est la vie.
if (p.y >= (pickY-20) && p.y <= (pickY+20) ) { //kinda near the axis?
if (Math.abs(pick1 - p.x) < Math.abs(pick2 - p.x)) { //move picker 1, it's closer
if (21 > p.x) {
pick1 = 21;
}
else if ((20+256) < p.x) {
pick1 = (20+256);
}
else {
pick1 = p.x;
}
super.repaint();
}
else { //mover picker 2
if (21 > p.x) {
pick2 = 21;
}
else if ((20+256) < p.x) {
pick2 = (20+256);
}
else {
pick2 = p.x;
}
super.repaint();
}
}
if (Color.RED.equals(col)) {
src.setRed(pick1-21, pick2-21);
}
else if (Color.BLUE.equals(col)) {
src.setBlue(pick1-21, pick2-21);
}
else {
src.setGreen(pick1-21, pick2-21);
}
}
|
ca09a3cf-c884-4d72-90ba-4228fba34c1a
| 4 |
private ArrayList<MapTile> CalculateTowerRange(int x, int y, int radius) {
ArrayList<MapTile> area = new ArrayList<>();
Comparator<MapTile> compareDistance = new TileRangeComparator(x + 0.5, y + 0.5);
for (int i = Math.max(x - radius, 0); i < Math.min(x + radius + 2, map.getPixels().length); i++) {
for (int j = Math.max(y - radius, 0); j < Math.min(y + radius + 2, map.getPixels()[0].length); j++) {
if (map.getTile(i, j) != null) {
if (Point2D.distance(x + 0.5, y + 0.5, map.getTile(i, j).getX(), map.getTile(i, j).getY()) <= radius) {
area.add(map.getTile(i, j));
}
}
}
}
Collections.sort(area, compareDistance);
return area;
}
|
c57653b1-3a47-41c2-b71b-1cd6582c2868
| 9 |
public String getDirectionTowards(Location otherLoc) {
int xDist = x - otherLoc.getX();
int yDist = y - otherLoc.getY();
if(xDist > 0) {
if(yDist > 0) {
return SOUTH + WEST;
} else if(yDist < 0) {
return NORTH + WEST;
} else {
return WEST;
}
} else if(xDist < 0) {
if(yDist > 0) {
return SOUTH + EAST;
} else if(yDist < 0) {
return NORTH + EAST;
} else {
return EAST;
}
} else if(xDist == 0) {
if(yDist > 0) {
return SOUTH;
} else if(yDist < 0) {
return NORTH;
}
}
return "ERROR: Same Location!";
}
|
04667170-e4b9-4f9f-b491-afe464c07977
| 2 |
public Map<String, Double> splitWord(String line) throws IOException{
Map<String, Double> fileMap = new HashMap<String, Double>();
Analyzer analyzer = new IKAnalyzer(true);
StringReader reader = new StringReader(line);
TokenStream ts = analyzer.tokenStream("", reader);
CharTermAttribute term = ts.getAttribute(CharTermAttribute.class);
ts.reset();
while(ts.incrementToken()){
String word = term.toString();
if (fileMap.containsKey(word)) {
fileMap.put(word, fileMap.get(word) + 1);
} else {
fileMap.put(word, (double) 1);
}
}
analyzer.close();
return fileMap;
}
|
d5e498f2-5131-4446-b734-dbcafc52aa17
| 6 |
public static Tile GRASS() {
if (random.nextInt(100) == 0) {
return GRASS_FLOWER;
} else if (random.nextInt(100) == 0) {
return GRASS_POPPY;
} else if (random.nextInt(6) == 0) {
return GRASS2;
} else if (random.nextInt(6) == 0) {
return GRASS3;
} else if (random.nextInt(6) == 0) {
return GRASS4;
} else if (random.nextInt(6) == 0) {
return GRASS5;
} else {
return GRASS;
}
}
|
ce47c4c4-c5d8-4e8c-ac39-f0acc813b4cc
| 2 |
public void simpleCornerElimination() {
int size = _smooth_path.size();
Path new_path = new Path();
new_path.add(_smooth_path.start());
for (int i = 1; i < size - 1; i++) {
Point p1 = _smooth_path.get(i - 1);
Point p2 = _smooth_path.get(i + 1);
//System.out.println("DIST from " + p1 + " to " + p2 + " = " + Point.pixelDistance(p1,p2));
if(PixelFunc.pixelDistance(p1, p2) > 1) {
new_path.add(_smooth_path.get(i));
} else {
new_path.add(p2);
i++;
}
}
new_path.add(_smooth_path.end());
_smooth_path = new_path;
}
|
d11d8b80-8c98-4209-8b2c-e436d0894b93
| 7 |
public static void Abstractor(){
while(myList.size() > 37){
double minSigValue = Double.MAX_VALUE;
PointStorage minSigPoint = null;
int index;
ListIterator iterator = myList.listIterator();
// Saves the points of the current List
getPoints();
// Checks to see the list has a next node and if it does checks to see if its sig value
// is less then the least sig value
while(iterator.hasNext()){
PointStorage p = (PointStorage) iterator.next();
if(p.getSigValue() < minSigValue){
minSigValue = p.getSigValue();
minSigPoint = p;
}
}
// Finds the position of the object to be removes
index = myList.indexOf(minSigPoint);
PointStorage previous = null;
PointStorage A = null;
PointStorage B = null;
PointStorage next = null;
// Finds the Nodes around the node to be removed
// If the node isnt the second or the second to last node then it
// Resets all surrounding points sigValues
if(index > 1 && index < (myList.size()-2)){
previous = (PointStorage) myList.get(index - 2);
A = (PointStorage) myList.get(index - 1);
B = (PointStorage) myList.get(index + 1);
next = (PointStorage) myList.get(index + 2);
// Removes point with the least sig value
myList.remove(index);
resetSigValues(previous, A, B, next);
}
// If it is the second value in the list it only resets the next nodes sigValue
if(index == 1){
A = (PointStorage) myList.get(index + 1);
previous = (PointStorage) myList.get(index -1);
next = (PointStorage) myList.get(index + 2);
// Removes point with the least sig value
myList.remove(index);
// Resets the sigValue of object A
A.setSigValue(findSigValue(previous, A, next));
}
// If it is the second to last value in the list it only resets the previous nodes sigValue
if(index == (myList.size()-2)){
A = (PointStorage) myList.get(index - 1);
previous = (PointStorage) myList.get(index - 2);
next = (PointStorage)myList.get(index + 1);
// Removes point with the least sig value
myList.remove(index);
// Resets the sigValue of object A
A.setSigValue(findSigValue(previous, A, next));
}
}
}
|
fa4b19c6-b4b0-4213-a4bd-2c85aa2d0227
| 6 |
final int[][] getTriangleGroups() {
anInt1854++;
int[] groupCount = new int[256];
int maximumGroup = 0;
for (int triangle = 0; ((Model) this).polygons.length > triangle; triangle++) {
int group = (((ModelPolygon) ((Model) this).polygons[triangle]).tGroup);
if (group >= 0) {
groupCount[group]++;
if (maximumGroup < group)
maximumGroup = group;
}
}
int[][] groups = new int[1 + maximumGroup][];
for (int i_7_ = 0; (maximumGroup ^ 0xffffffff) <= (i_7_ ^ 0xffffffff); i_7_++) {
groups[i_7_] = new int[groupCount[i_7_]];
groupCount[i_7_] = 0;
}
for (int triangle = 0; triangle < ((Model) this).polygons.length; triangle++) {
int group = (((ModelPolygon) ((Model) this).polygons[triangle]).tGroup);
if (group >= 0)
groups[group][groupCount[group]++] = triangle;
}
return groups;
}
|
709d918e-58cf-430f-bb52-680554efae24
| 5 |
@Override
public int hashCode() {
int tId;
if (userId == 0) {
tId = 33;
}
else {
tId = userId;
}
int tFirst;
if (firstName == null) {
tFirst = 41;
}
else {
tFirst = firstName.length();
}
int tLast;
if (lastName == null) {
tLast = 37;
}
else {
tLast = lastName.length();
}
int tNum;
if (recordsIndexed == 0) {
tNum = 49;
}
else {
tNum = recordsIndexed;
}
if (valid) {
return tId * tFirst * tLast * tNum * tNum;
}
else {
return tId + tFirst + tLast * tNum * tNum;
}
}
|
7e109cf6-4357-4a11-849d-6a74b24bfbb2
| 8 |
protected void addCommandJournalsVar(final HTTPRequest httpReq, final String index, final StringBuilder str)
{
final String name=httpReq.getUrlParameter("COMMANDJOURNAL_"+index+"_NAME");
final String mask=httpReq.getUrlParameter("COMMANDJOURNAL_"+index+"_MASK");
if((name!=null)&&(name.trim().length()>0)
&&(!name.trim().equalsIgnoreCase("auction")))
{
if(str.length()>0)
str.append(", ");
str.append(name.trim().replace(',',' ').toUpperCase()).append(" ");
for(final JournalsLibrary.CommandJournalFlags flag : JournalsLibrary.CommandJournalFlags.values())
{
final String val=httpReq.getUrlParameter("COMMANDJOURNAL_"+index+"_FLAG_"+flag.name());
if((val!=null)&&(val.trim().length()>0))
str.append(flag.name()).append("=").append(val.replace(',', ' ')).append(" ");
}
if(mask.trim().length()>0)
str.append(mask.trim().replace(',',' ')).append(" ");
str.setLength(str.length()-1);
}
}
|
934e7003-67e8-4a17-8c2c-95662ce191c6
| 6 |
public XMLOrderImporter(File XMLFile){
MesController myController = new MesController();
ProductDAO proDAO = new ProductDAO();
OrderDAO ordDAO = new OrderDAO();
Order myOrder = new Order();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
try {
doc = dBuilder.parse(XMLFile);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("b2mml:MaterialInformation");
System.out.println("radis-mes$ \t adding a new order");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
// get Product ID and set
String elementProductInfo = eElement.getElementsByTagName("b2mml:ID").item(0).getTextContent();
String[] elementProductInfos = elementProductInfo.split("O");
// Checks if product exist in DB!
product = proDAO.getProductById(Integer.valueOf(elementProductInfos[0]));
productID = product.getId();
// get Order Date and set it, awaiting approval - added with 2 days.
String timeStamp = new SimpleDateFormat("dd-MM-yy").format(Calendar.getInstance().getTime());
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
try {
c.setTime(sdf.parse(timeStamp));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 2); // number of days to add
timeStamp = sdf.format(c.getTime()); // dt is now the new date
orderDate = timeStamp;
// get Quantity and set it.
int orderQuantityX = Integer.valueOf(eElement.getElementsByTagName("b2mml:QuantityString").item(0).getTextContent());
// add waste. (Missing implementation)
orderQuantity = orderQuantityX;
// System.out.println(orderQuantity);
// get order status and set it
queueStatus = eElement.getElementsByTagName("b2mml:Status").item(0).getTextContent();
// System.out.println(orderStatus);
}
myOrder.setProduct(productID);
myOrder.setQuantity(orderQuantity);
myOrder.setStartDate(orderDate);
myOrder.setStatus(0);
try {
myController.addOrder(myOrder);
} finally {
System.out.println("radis-mes$ \t Order added to DB");
}
System.out.println(myOrder.getId());
//
}
}
|
11fd9ccc-1120-49e7-a6fb-00054d016719
| 0 |
public void preInit(FMLPreInitializationEvent event)
{
}
|
4d92cc7c-d095-4d0c-873f-e8b195796a01
| 1 |
@Override
public void hoistDepthChanged(OutlinerDocumentEvent e) {
if (e.getOutlinerDocument() == Outliner.documents.getMostRecentDocumentTouched()) {
calculateEnabledState(e.getOutlinerDocument());
}
}
|
ec265685-38ae-42f1-85ac-39d2b88d8bd5
| 3 |
public boolean isVariableLocked(int index) {
for (Transaction t: locks.keySet()) {
ArrayList<Lock> lockListT = locks.get(t);
for (Lock lock: lockListT) {
if(lock.getIndex()==index) {
return true;
}
}
}
return false;
}
|
f7081cc8-ff65-4551-92e3-899f502708a7
| 5 |
public void keepItem3() {
for(int i = 0; i < playerItems.length; i++) {
int highest = 0;
int value = (int)Math.floor(GetItemShopValue(playerItems[i]-1, 0, i));
if(value > highest && playerItems[i]-1 != keepItem && playerItems[i]-1 != keepItem2 && playerItems[i]-1 != -1) {
highest = value;
keepItem3 = playerItems[i]-1;
keepItemAmount3 = playerItemsN[i];
}
}
}
|
bbf6076b-d6a3-46b3-a766-e9dbd63e2297
| 7 |
public static void runMainMenu() {
// Track the menu start time so that buttons aren't clicked accidentally
menuStartTime = Sys.getTime();
try {
// While the program isn't told to leave the main menu
while (!exit && !goToCouchMenu && !goToInstructions && !goToAbout) {
// If the display is not visible (minimised), add much more
// delay
if (!Display.isVisible()) {
Thread.sleep(200);
}
// If the display is requested to close, exit the program
else if (Display.isCloseRequested())
exit = true;
// Otherwise, make the thread delay for a bit to let other
// threads catch up
else
Thread.sleep(10);
// Update the timer, handle the inputs, draw and update the
// screen
updateTimer();
handleMainMenuInputs();
drawMainMenu();
Display.update();
}
} catch (Exception exception) {
System.out
.println("KouchKarting.runMainMenu() error: " + exception);
}
}
|
9e91fa98-f3bb-4678-a4cb-6cb3e5bd9fcb
| 0 |
@Test
public void testDraw()
{
// first its assumed to be default:
assertNotNull(_underTest.draw());
// set the draw-output, test changed draw-functionality:
_underTest.setDrawOutput(Output.Paper);
assertEquals(Output.Paper, _underTest.draw());
_underTest.setDrawOutput(Output.Rock);
assertEquals(Output.Rock, _underTest.draw());
_underTest.setDrawOutput(Output.Scissors);
assertEquals(Output.Scissors, _underTest.draw());
}
|
d2117975-a79a-4ade-8db0-92665c7993cf
| 9 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result
+ ((facebook == null) ? 0 : facebook.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((note == null) ? 0 : note.hashCode());
result = prime * result
+ ((thumbnail == null) ? 0 : thumbnail.hashCode());
result = prime * result + ((twitter == null) ? 0 : twitter.hashCode());
result = prime * result + ((website == null) ? 0 : website.hashCode());
return result;
}
|
185e02d2-c1fd-4770-9fbe-5baa74f12164
| 6 |
@Override
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Game ID";
case 1:
return "Map size";
case 2:
return "Turn time";
case 3:
return "Extra turn";
case 4:
return "Players count";
case 5:
return "Players";
}
return null;
}
|
acf16b2a-3061-4b80-9514-515d3b2cf1ee
| 5 |
public static boolean isSubstring(String a, String b) {
if(a == null || b == null || a == "" || b == "")
return false;
String temp = a + a;
if(temp.contains(b))
return true;
return false;
}
|
f656d588-51c6-4457-bfc8-28fc21ba6806
| 3 |
private void showMainMenu() {
System.out.println("\n---------------------------------------");
System.out.println("Please select an option :");
System.out.println("1. Library contents overview.");
System.out.println("2. Add a new item.");
System.out.println("3. Stop the application.");
System.out.println("---------------------------------------");
int result = readInt(1, 3);
switch (result) {
case 1:
showItemsOverview();
break;
case 2:
showAddItemWizard();
break;
case 3:
showExitMessage();
break;
}
}
|
3dc27ca2-0809-4b64-976d-fa93ccf968b9
| 7 |
boolean valid(Graph G)
{
return G.getEdgeWeight(1, 0) == 1&&
G.getEdgeWeight(1, 2) == 3 &&
G.getEdgeWeight(2,4) == 1 &&
G.getEdgeWeight(3, 4)== 2 &&
G.getEdgeWeight(3, 6) == 3 &&
G.getEdgeWeight(7, 6) == 2 &&
G.getEdgeWeight(7, 8) == 4 &&
G.getEdgeWeight(4, 5) == 3;
}
|
6ff59ada-cf3f-440a-9d9a-f69e79b603ab
| 0 |
public String getColor() {
return myColor;
}
|
d83846bb-cf2f-4d1f-b120-616cf7646a07
| 9 |
public void broadcastMessage()
{
Player[] players = Bukkit.getOnlinePlayers();
Random rand = new Random();
ConfigurationSection conf = getConfig().getConfigurationSection( "messages" );
Map<String, Object> msgs = conf.getValues( true );
String broadcast = "";
if ( msgs.size() > 0 )
{
int choice = -1;
int x = 0;
while ( lastId == choice )
{
choice = rand.nextInt( msgs.size() );
}
lastId = choice;
for ( Object msg : msgs.values() )
{
if ( x == choice )
{
broadcast = msg.toString();
break;
}
x++;
}
if ( broadcast.equals( "" ) )
return;
/*
* for (Player p : players) { p.sendMessage( ChatColor.RED + "[Announcement] " + ChatColor.RESET +
* broadcast.toString() ); }
*/
Boolean playersOnline = false;
for ( Player p : players )
if ( !p.hasPermission( "inations.admin" ) && !p.isOp() )
playersOnline = true;
if ( playersOnline )
getServer().broadcastMessage( ChatColor.translateAlternateColorCodes( '&', getConfig().getString( "global.msgTitle", "&d[Announcement]" ) ) + " " + ChatColor.RESET + ChatColor.translateAlternateColorCodes( "&".charAt( 0 ), broadcast.toString() ) );
// getServer().getConsoleSender().sendMessage( ChatColor.RED +
// "[Announcement] " + ChatColor.RESET + broadcast.toString() );
}
}
|
afd30557-4d74-413a-9345-dee3a55fc208
| 5 |
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for(Map.Entry<? extends K, ? extends V> me : m.entrySet()) {
this.put(me.getKey(), me.getValue());
}
}
|
966b3e95-9666-4058-8bc3-36bfb603cb9d
| 5 |
@Override
public Void doInBackground() {
String response;
try {
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
try {
urlConn.connect();
} catch (ProtocolException e) {
taskOutput.append("Couldn't open connection: " + e.getMessage());
closeButton.setEnabled(true);
return null;
}
OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
writer.write(xmlString);
writer.flush();
response = urlConn.getResponseMessage();
if (response.equals("Bad Request")) {
// Couldn't upload. Duplicated.
String err = "Couldn't upload. The Recipe name is already uploaded.";
taskOutput.append(err);
JOptionPane.showMessageDialog(null, err);
urlConn.disconnect();
closeButton.setEnabled(true);
return null;
}
// Read back to make sure it uploaded OK.
InputStream inputStream;
int responseCode = urlConn.getResponseCode();
if ((responseCode >= 200) && (responseCode<=202)) {
inputStream = urlConn.getInputStream();
int j;
Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A");
String recipeString = s.next();
String recipeID = recipeString.replace("recipe id: ", url.toString());
taskOutput.append("Upload Completed! \n URL is " + recipeID + "\n");
} else {
inputStream = urlConn.getErrorStream();
}
progressBar.setVisible(false);
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
closeButton.setEnabled(true);
return null;
}
|
a47d5ca5-ea33-4b9a-9b41-c6522f570983
| 4 |
private List<Integer> findSharedUsers(int movie1, int movie2) {
List<Integer> sharedUsers = new ArrayList<Integer>();
HashSet<Integer> movie1Raters = usersByMovie.get(movie1);
HashSet<Integer> movie2Raters = usersByMovie.get(movie2);
// Return empty list if one user didn't rate any movies
if (movie1Raters == null || movie2Raters == null) {
return sharedUsers;
}
Iterator<Integer> it = movie1Raters.iterator();
while (it.hasNext()) {
Integer value = (Integer) it.next();
if (movie2Raters.contains(value)) {
sharedUsers.add(value);
}
}
return sharedUsers;
}
|
67066529-6beb-4d7e-b00d-210331f9d244
| 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(startFrameSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(startFrameSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(startFrameSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(startFrameSimple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
}
|
bdf3d3ec-6186-44c7-b5f0-3b755c651c46
| 4 |
public void saveConfig() {
FileConfiguration c = this.gm.getConfig();
String orderString = "";
Level lvl = this.level;
while (lvl != null)
{
orderString = orderString + lvl.Name;
c.set(this.arenaName + ".level." + lvl.Name + ".neededPoints", Integer.valueOf(lvl.neededPoints));
c.set(this.arenaName + ".level." + lvl.Name + ".weaponId", Integer.valueOf(lvl.WeaponId));
lvl = lvl.nextLevel;
if (lvl != null)
orderString = orderString + ",";
}
c.set(this.arenaName + ".level.order", orderString);
c.set(this.arenaName + ".allowTeamkill", Boolean.valueOf(this.allowTeamkill));
if (!c.contains(this.arenaName + ".saveInventory"))
c.set(this.arenaName + ".saveInventory", Boolean.valueOf(false));
for (Team t : this.teams)
{
c.set(this.arenaName + ".teams.team" + (t.TeamId + 1) + ".name", t.getTeamName());
c.set(this.arenaName + ".teams.team" + (t.TeamId + 1) + ".color", Character.valueOf(t.color.getChar()));
}
c.set(this.arenaName + ".world", this.mainArea.P1.getWorld().getName());
this.mainArea.save();
this.warmUpArea.save();
this.winArea.save();
this.looseArea.save();
this.gm.saveConfig();
}
|
cd7b7f48-d1b2-4c61-84ad-08090bf71707
| 7 |
private int resolveUnit(String unit) {
if(unit.equalsIgnoreCase("second")) {
return TimeAxisUnit.SECOND;
}
else if(unit.equalsIgnoreCase("minute")) {
return TimeAxisUnit.MINUTE;
}
else if(unit.equalsIgnoreCase("hour")) {
return TimeAxisUnit.HOUR;
}
else if(unit.equalsIgnoreCase("day")) {
return TimeAxisUnit.DAY;
}
else if(unit.equalsIgnoreCase("week")) {
return TimeAxisUnit.WEEK;
}
else if(unit.equalsIgnoreCase("month")) {
return TimeAxisUnit.MONTH;
}
else if(unit.equalsIgnoreCase("year")) {
return TimeAxisUnit.YEAR;
}
else {
throw new IllegalArgumentException("Invalid unit specified: " + unit);
}
}
|
dc7886b4-da65-4ed9-bf6f-50872c29c61a
| 2 |
public boolean equals(Object other) {
if (!(other instanceof Resource) || (other == null))
return (false);
return (compareTo((Resource) other) == 0);
}
|
2e5d07f9-843d-4c52-969a-e104a5059b36
| 6 |
public void softDrop() {
Boolean ableToMove = true;
for (Block b : currentTetromino.getBlocks()) {
if ((b.getMapIndexY() == boardSizeY)
|| (tetrisMap[b.getMapIndexX()][b.getMapIndexY() + 1] == 1)) {
ableToMove = false;
}
}
if (ableToMove) {
for (Block b : currentTetromino.getBlocks()) {
tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = 0;
}
for (Block b : currentTetromino.getBlocks()) {
b.translateDown();
tetrisMap[b.getMapIndexX()][b.getMapIndexY()] = currentTetromino
.getKey();
}
score += 1;
}
notifyObservers();
}
|
467ef994-6e8b-4ba0-8d54-55341421f6ec
| 9 |
@Override
int afterName() throws IOException {
int n = in.next();
switch (n) {
case ' ':
case '\t':
case '\r':
case '\n':
in.back();
String ws = parseWhitespace(in);
if (!isIgnoreWhitespace()) {
set(JSONEventType.WHITESPACE, ws, false);
}
return AFTER_NAME;
case '/':
in.back();
String comment = parseComment(in);
if (!isIgnoreWhitespace()) {
set(JSONEventType.COMMENT, comment, false);
}
return AFTER_NAME;
case ':':
return BEFORE_VALUE;
case -1:
throw createParseException(in, "json.parse.ObjectNotClosedError");
default:
throw createParseException(in, "json.parse.UnexpectedChar", (char)n);
}
}
|
a5db1564-87a7-4c45-875a-94deff9265ec
| 3 |
@SuppressWarnings("unchecked")
public void addResource(Object arg) {
if (arg == null) {
throw new ComponentException("No resource string provided.");
}
if (arg.getClass() == String.class) {
l.add((String) arg);
} else if (arg instanceof Collection) {
l.addAll((Collection) arg);
} else {
l.add(arg.toString());
}
}
|
fe9b8957-ac2b-4508-92d3-2e73ab63105c
| 9 |
public ArrayList<Integer> spiralOrder(int[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> res = new ArrayList<Integer>();
int m = matrix.length;
if (m < 1)
return res;
int n = matrix[0].length;
if (n < 1)
return res;
int round = Math.min((m + 1) / 2, (n + 1) / 2);
int i = 0, j = 0;
for (i = 0; i < round; i++) {
for (j = i; j <= n - i - 1; j++)
res.add(matrix[i][j]); // 全
for (j = i + 1; j < m - i - 1; j++)
res.add(matrix[j][n - i - 1]); // 去头尾
if (m - i - 1 > i) {
for (j = n - i - 1; j >= i; j--)
res.add(matrix[m - i - 1][j]); // 全
}
if (n - i - 1 > i) {
for (j = m - i - 2; j > i; j--)
res.add(matrix[j][i]); // 去头尾
}
}
return res;
}
|
0abe8e5c-6179-44fc-8e9d-d0e5cdfd0de4
| 0 |
@Override
public String getEmail() {
return super.getEmail();
}
|
466f3401-77d4-43d5-9d9a-189f1b051cfe
| 5 |
public HashMap<Team, List<Player>> getPlayers(){
HashMap<Team, List<Player>> players = new HashMap<Team, List<Player>>();
players.put(Team.RED, new ArrayList<Player>());
players.put(Team.BLUE, new ArrayList<Player>());
for(Player p : Bukkit.getOnlinePlayers()){
if(p.getLocation().distance(point) <= radius){
PlayerData data = PluginData.getPlayerData(p);
Team playerTeam = data.getTeam();
if(playerTeam != null && playerTeam != Team.NONE){
if(playerOnPoint(p)) players.get(playerTeam).add(p);
}
}
}return players;
}
|
15b26a8b-c078-446e-b5b9-fff5bb591375
| 7 |
public void simulatePeer() {
Random random = new Random();
int selectedFileId = random.nextInt(Main.MAX_NO_OF_FILES) + 1;
int selectedActionIndex = random.nextInt(Main.MAX_NO_OF_ACTIONS);
PeerAction selectedPeerAction = PeerAction.values()[selectedActionIndex];
String selectedAction = selectedPeerAction.getAction();
if (shareRatio == Main.MIN_SHARE_RATIO) {
selectedPeerAction = PeerAction.SHARE;
selectedAction = PeerAction.SHARE.getAction();
}
if (selectedPeerAction == PeerAction.DOWNLOAD && sharedFiles.containsKey(selectedFileId)) {
return;
} else if (selectedPeerAction == PeerAction.SHARE && sharedFiles.containsKey(selectedFileId)) {
return;
} else if (selectedPeerAction == PeerAction.STOP && !sharedFiles.containsKey(selectedFileId)) {
return;
}
tracker.sendMessage(this, selectedAction, selectedFileId);
}
|
6ab61250-16dc-4c3e-9206-81686ed977ab
| 6 |
private boolean DL(String palabra){
switch(palabra){
case "(":
return true;
case ")":
return true;
case "[":
return true;
case "]":
return true;
case "{":
return true;
case "}":
return true;
}
return false;
}
|
4dc5ee29-d44f-4b61-bd73-cfd0f13153d2
| 0 |
void flip() {
Vertex temporary = this.start;
this.start = end;
this.end = temporary;
}
|
a0b8f5cc-9282-4699-b556-33b0495c3798
| 1 |
private boolean jj_2_49(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_49(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(48, xla); }
}
|
af0dbc24-2298-4da7-a0ee-569841510a1c
| 2 |
@Override
public void mouseReleased(MouseEvent e) {
// Make sure zoom area isn't a ridiculously small size
if (zoomArea != null) {
// Make sure zoom area isn't a ridiculously small size
Dimension size = zoomArea.getSize();
if (size.getWidth() * size.getHeight() > 50) {
// Get rectangle vertices as complex numbers
// Min x and min y
Complex point1 = fractal.getCartesian(zoomArea.x, zoomArea.y);
// Max x and max y
Complex point2 = fractal.getCartesian(zoomArea.x + zoomArea.width, zoomArea.y + zoomArea.height);
// Set the viewport via the AxisSpinners (to update both
// spinners and graph)
realFrom.setValue(point1.real());
realTo.setValue(point2.real());
imaginaryFrom.setValue(point1.imaginary());
imaginaryTo.setValue(point2.imaginary());
// Reset zoom area
zoomArea = null;
fractal.paintZoom(zoomArea);
}
}
}
|
ea785dc3-e83f-4e76-8238-43401933ef41
| 0 |
public String getStepThrough()
{
return stepThrough;
}
|
e7c4d387-bcc0-402c-bbb4-0385cb4168a9
| 7 |
@Override
public boolean isInWilderness(Physical P)
{
if(P instanceof MOB)
return isInWilderness(((MOB)P).location());
else
if(P instanceof Item)
return isInWilderness(((Item)P).owner());
else
if(P instanceof Room)
{
return (((Room)P).domainType()!=Room.DOMAIN_OUTDOORS_CITY)
&&(((Room)P).domainType()!=Room.DOMAIN_OUTDOORS_SPACEPORT)
&&(((Room)P).domainType()!=Room.DOMAIN_OUTDOORS_WATERSURFACE)
&&(((Room)P).domainType()!=Room.DOMAIN_OUTDOORS_UNDERWATER)
&&((((Room)P).domainType()&Room.INDOORS)==0);
}
else
return false;
}
|
865b7e4f-cee5-4ce8-923e-670c355e8322
| 8 |
public boolean displayModesMatch(DisplayMode m1, DisplayMode m2) {
//resolution, bitdepth, refreshrate
if (m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()){
return false;
}
if (m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) {
return false;
}
if (m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()){
return false;
}
return true;
}
|
0727f317-e0ca-4017-8404-b366e28b78c5
| 3 |
private Collection<? extends Long> notIn(FiniteSequence<Long> factors, List<Long> result) {
List<Long> copy = new LinkedList<Long>(result);
List<Long> toAdd = new LinkedList<Long>();
while (factors.hasNext()) {
Long x = factors.next();
if (!copy.remove(x)) {
toAdd.add(x);
}
}
return toAdd;
}
|
38acba9f-ce6a-42dc-965f-371c52a2b388
| 0 |
public void setDescription(String description) {
this.description = description;
}
|
c90170ef-337d-4b6a-af05-30d1cb3cceda
| 8 |
public int getCostByDemand(int demand) {
int result = CostFunction.MAX_COST;
if(costByDemandMap.containsKey(demand)){
result = costByDemandMap.get(demand);
} else {
int[] demands = getDemands();
int i = 0;
while(i < demands.length){
if(demands[i] < 0 && demands[i] > demand){
result = costByDemandMap.get(demands[i]);
break;
}
if (demands[i] > 0 && demands[i] > demand){
if (i > 0)
result = costByDemandMap.get(demands[i-1]);
break;
}
i++;
}
if(i == demands.length)
result = costByDemandMap.get(demands[i-1]);
}
return result;
}
|
28093d26-b7dc-4d05-bd77-3ff06747ea5b
| 5 |
public String flagsToString() {
String s = "[";
s += (isSyn()) ? "SYN " : " ";
s += (isPsh()) ? "PSH " : " ";
s += (isFin()) ? "FIN " : " ";
s += (isRst()) ? "RST " : " ";
s += (isAck()) ? "ACK " : " ";
return s.trim() + "]";
}
|
3d71bc77-5812-4c2e-bb3a-efa1a76752e6
| 4 |
private void checkBoardDimension(int row, int col) {
rowBoard=row;
colBoard=col;
if (row>10)rowBoard=10;
if (row<6)rowBoard=6;
if (col>10)colBoard=10;
if (col<4)colBoard=4;
}
|
0f18c77d-ec59-483b-9689-174f8c1f9fb8
| 5 |
private boolean skipTo(String toFind) throws IOException {
outer:
for (; pos + toFind.length() <= limit || fillBuffer(toFind.length()); pos++) {
if (buffer[pos] == '\n') {
lineNumber++;
lineStart = pos + 1;
continue;
}
for (int c = 0; c < toFind.length(); c++) {
if (buffer[pos + c] != toFind.charAt(c)) {
continue outer;
}
}
return true;
}
return false;
}
|
d6b3fbee-f5de-4d6b-8502-e059084b94ff
| 6 |
public static void drawFilledAlphaPixels(int x, int y, int w, int h, int color, int alpha) {
if (x < startX) {
w -= startX - x;
x = startX;
}
if (y < startY) {
h -= startY - y;
y = startY;
}
if (x + w > endX) {
w = endX - x;
}
if (y + h > endY) {
h = endY - y;
}
int alphaValue = 256 - alpha;
int red = (color >> 16 & 0xff) * alpha;
int green = (color >> 8 & 0xff) * alpha;
int blue = (color & 0xff) * alpha;
int offset = width - w;
int pixel = x + y * width;
for (int heightPointer = 0; heightPointer < h; heightPointer++) {
for (int widthPointer = -w; widthPointer < 0; widthPointer++) {
int r = (pixels[pixel] >> 16 & 0xff) * alphaValue;
int g = (pixels[pixel] >> 8 & 0xff) * alphaValue;
int b = (pixels[pixel] & 0xff) * alphaValue;
int pixelColor = ((red + r >> 8) << 16) + ((green + g >> 8) << 8) + (blue + b >> 8);
pixels[pixel++] = pixelColor;
}
pixel += offset;
}
}
|
f0c2a438-ef10-44c1-aaa3-c591734d055f
| 2 |
@Test
public void testClientQueueCounts() throws LuaScriptException {
String jid1 = addJob();
String jid2 = addJob();
String jid3 = addJob(UUID.randomUUID().toString(), "another-queue");
// Pop job to simulate worker
popJob();
List<Map<String, Object>> queueDetails = _clientQueues.counts();
for (Map<String, Object> queue : queueDetails) {
if (queue.get("name").equals(TEST_QUEUE)) {
assertEquals("1", queue.get("running").toString());
assertEquals("1", queue.get("waiting").toString());
} else {
assertEquals("0", queue.get("running").toString());
assertEquals("1", queue.get("waiting").toString());
}
assertEquals("0", queue.get("scheduled").toString());
}
removeJob(jid1);
removeJob(jid2);
removeJob(jid3);
}
|
98848df7-793f-45c3-8362-47d1c00d22fe
| 8 |
protected void initVerifiers(int currVerSet) {
int currVerifierSet ;
if (currVerSet >=0 && currVerSet < NO_OF_LANGUAGES ) {
currVerifierSet = currVerSet ;
}
else {
currVerifierSet = nsPSMDetector.ALL ;
}
mVerifier = null ;
mStatisticsData = null ;
if ( currVerifierSet == nsPSMDetector.TRADITIONAL_CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsBIG5Verifier(),
new nsISO2022CNVerifier(),
new nsEUCTWVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
new Big5Statistics(),
null,
new EUCTWStatistics(),
null,
null,
null
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.KOREAN ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsEUCKRVerifier(),
new nsISO2022KRVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.SIMPLIFIED_CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.JAPANESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsSJISVerifier(),
new nsEUCJPVerifier(),
new nsISO2022JPVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.CHINESE ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsBIG5Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsEUCTWVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
new GB2312Statistics(),
null,
new Big5Statistics(),
null,
null,
new EUCTWStatistics(),
null,
null,
null
};
}
//==========================================================
else if ( currVerifierSet == nsPSMDetector.ALL ) {
mVerifier = new nsVerifier[] {
new nsUTF8Verifier(),
new nsSJISVerifier(),
new nsEUCJPVerifier(),
new nsISO2022JPVerifier(),
new nsEUCKRVerifier(),
new nsISO2022KRVerifier(),
new nsBIG5Verifier(),
new nsEUCTWVerifier(),
new nsGB2312Verifier(),
new nsGB18030Verifier(),
new nsISO2022CNVerifier(),
new nsHZVerifier(),
new nsCP1252Verifier(),
new nsUCS2BEVerifier(),
new nsUCS2LEVerifier()
};
mStatisticsData = new nsEUCStatistics[] {
null,
null,
new EUCJPStatistics(),
null,
new EUCKRStatistics(),
null,
new Big5Statistics(),
new EUCTWStatistics(),
new GB2312Statistics(),
null,
null,
null,
null,
null,
null
};
}
mClassRunSampler = ( mStatisticsData != null ) ;
mClassItems = mVerifier.length ;
}
|
3f0e0567-444a-42d9-81a8-3245064be640
| 0 |
public void lanchFrame(){
initial();
this.setLocation(400,300);
this.setSize(GAME_WIDTH,GAME_HEIGHT);
this.setBackground(Color.GREEN);
this.setTitle("TankWar");
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setResizable(false);
this.addKeyListener(new KeyMonitor());
this.setVisible(true);
new Thread(new PaintThread()).start();
}
|
1431005b-e395-4044-a756-75ba18abe235
| 8 |
private Monitor() {
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("ThermRonStat GUI");
guiFrame.setSize(300, 250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] targetTempOptions = {
"40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
"60", "61", "62", "63", "64", "65", "66", "67", "68", "69",
"70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
};
String[] statusOptions = {"Off", "On"};
//The first JPanel contains a JLabel and JCombobox
final JPanel mainPanel = new JPanel();
JLabel statusL = new JLabel("System Status:");
final JComboBox statusCB = new JComboBox(statusOptions);
String systemStatusValue = "Off";
try {
if (statusControl.read()) {
systemStatusValue = "On";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
statusCB.setSelectedItem(systemStatusValue);
statusCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println("Change System Status due to event:" + statusCB.getSelectedItem());
try {
if (((String) statusCB.getSelectedItem()).equalsIgnoreCase("on"))
statusControl.write(1.0);
else {
statusControl.write(0.0);
stage1Control.write(0.0);
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
JLabel targetL = new JLabel("Target Temperature:");
final JComboBox targetCB = new JComboBox(targetTempOptions);
try {
targetCB.setSelectedItem(Integer.toString((int) targetControl.readDouble()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
targetCB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println("Change Target Temp: " + targetCB.getSelectedItem());
try {
targetControl.write(Double.parseDouble((String) targetCB.getSelectedItem()));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
SensorLabel indoorTemp = new SensorLabel("Indoor Temp.", indoorSensor);
SensorLabel outdoorTemp = new SensorLabel("Outdoor Temp.", outdoorSensor);
SensorLabel plenumTemp = new SensorLabel("Plenum Temp.", plenumSensor);
SensorLabel returnTemp = new SensorLabel("Return Temp.", returnSensor);
ValueFileLabel relayValue = new ValueFileLabel("Running:", stage1Control, true);
mainPanel.add(relayValue);
mainPanel.add(statusL);
mainPanel.add(statusCB);
mainPanel.add(targetL);
mainPanel.add(targetCB);
mainPanel.add(indoorTemp);
mainPanel.add(outdoorTemp);
mainPanel.add(plenumTemp);
mainPanel.add(returnTemp);
guiFrame.add(mainPanel);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
|
f457d374-ffd7-48e3-a4b9-a7dcaf085133
| 6 |
public void testSearchForColony() {
Game game = getStandardGame();
Map map = getCoastTestMap(plainsType, true);
game.setMap(map);
Player dutchPlayer = game.getPlayer("model.nation.dutch");
Player frenchPlayer = game.getPlayer("model.nation.french");
Tile unitTile = map.getTile(15, 5);
Tile colonyTile = map.getTile(9, 9); // should be on coast
Unit galleon = new ServerUnit(game, unitTile, dutchPlayer, galleonType);
Unit artillery = new ServerUnit(game, galleon, dutchPlayer, artilleryType);
FreeColTestUtils.getColonyBuilder().player(frenchPlayer)
.colonyTile(colonyTile).build();
assertTrue("French colony not on the map",
colonyTile.getSettlement() != null);
dutchPlayer.setStance(frenchPlayer, Stance.WAR);
frenchPlayer.setStance(dutchPlayer, Stance.WAR);
// Test a GoalDecider with subgoals.
// The scoring function is deliberately simple.
GoalDecider gd = new GoalDecider() {
private PathNode found = null;
private int score = -1;
private int scoreTile(Tile tile) {
return tile.getX() + tile.getY();
}
public PathNode getGoal() {
return found;
}
public boolean hasSubGoals() {
return true;
}
public boolean check(Unit u, PathNode pathNode) {
Settlement settlement = pathNode.getLocation().getSettlement();
if (settlement != null) {
int value = scoreTile(pathNode.getTile());
if (value > score) {
score = value;
found = pathNode;
return true;
}
}
return false;
}
};
PathNode path = map.search(artillery, unitTile, gd,
CostDeciders.avoidIllegal(),
FreeColObject.INFINITY, galleon);
assertTrue("Should find the French colony via a drop off",
path != null && path.getTransportDropNode() != null
&& path.getLastNode().getTile() == colonyTile);
// Add another colony
Tile colonyTile2 = map.getTile(5, 5); // should score less
FreeColTestUtils.getColonyBuilder().player(frenchPlayer)
.colonyTile(colonyTile2).build();
assertTrue("French colony not on the map",
colonyTile2.getSettlement() != null);
path = map.search(artillery, unitTile, gd,
CostDeciders.avoidIllegal(),
FreeColObject.INFINITY, galleon);
assertTrue("Should still find the first French colony via a drop off",
path != null && path.getTransportDropNode() != null
&& path.getLastNode().getTile() == colonyTile);
}
|
35fcd2e1-fdc1-41bc-bb34-330da8ca0fd6
| 9 |
private static void addToMap(File file, HashMap<String, HashMap<String, Integer>> countMap,
String level)
throws Exception
{
String name = file.getName().replace("standardReport_for_Sample_", "").replace(".txt", "")
.replace("_to16S", "").replace("standardReport_for_", "");
String[] splits = name.split("_");
String sampleID = splits[0];
boolean needToTrim = true;
if( splits[1].equals("all1") || splits[1].equals("all2"))
{
needToTrim = false;
sampleID = sampleID + "_" + splits[1];
}
if( needToTrim)
{
if( splits[1].equals("MSHRM1"))
sampleID = sampleID + "_all1";
else if( splits[1].equals("MSHRM2"))
sampleID = sampleID + "_all2";
else throw new Exception("Unexpected " + splits[1]);
}
if( countMap.containsKey(sampleID))
throw new Exception("Duplicate " + sampleID);
HashMap<String, Integer> innerMap = new HashMap<String, Integer>();
countMap.put(sampleID, innerMap);
BufferedReader reader = new BufferedReader(new FileReader(file));
for(String s = reader.readLine(); s != null; s = reader.readLine())
{
StringTokenizer sToken = new StringTokenizer(s);
sToken.nextToken();
int counts = Integer.parseInt(sToken.nextToken());
sToken.nextToken();
String charString = sToken.nextToken();
if( charString.equals(level))
{
sToken.nextToken();
String taxaName = new String(sToken.nextToken());
if (innerMap.containsKey(taxaName))
{
//System.out.println("Waring duplicate " + taxaName + " "
// + innerMap.get(taxaName));
counts = counts + innerMap.get(taxaName);
}
innerMap.put(taxaName, counts);
}
}
reader.close();
}
|
211bb62a-c006-470e-a6bf-34e1dd0bd094
| 3 |
@Override
public void parse() throws IllegalArgumentException
{
try
{
setEncoding(Encoding.getEncoding(buffer[0]));
}
catch (IllegalArgumentException ex)
{ // ignore the bad value and set it to ISO-8859-1 so we can continue parsing the tag
setEncoding(Encoding.ISO_8859_1);
}
try
{
setLanguage(Language.getLanguage(new String(buffer, 1, 3, Encoding.ISO_8859_1.getCharacterSet())));
}
catch (IllegalArgumentException ex)
{ // ignore the bad value and set it to english so we can continue parsing the tag
setLanguage(Language.ENG);
}
nullTerminatorIndex = getNextNullTerminator(4, encoding.getCharacterSet());
description = new String(buffer, 4, nullTerminatorIndex-4, encoding.getCharacterSet()).trim();
nullTerminatorIndex += encoding.getNumBytesInNullTerminator();
text = (nullTerminatorIndex == buffer.length ? "" : new String(buffer, nullTerminatorIndex, buffer.length - nullTerminatorIndex, encoding.getCharacterSet()).trim());
dirty = false; // we just read in the frame info, so the frame body's internal byte buffer is up to date
}
|
80b5168f-1efb-4e35-b4c5-8c7dfb0b94f5
| 0 |
@Override
public String toString()
{
return "This is OverrideTest !";
}
|
76a9f285-1103-4994-a17c-8d4457c5cb0e
| 2 |
public EntradaBean get(EntradaBean oEntradaBean) throws Exception {
try {
oMysql.conexion(enumTipoConexion);
HiloBean oHiloBean = new HiloBean();
UsuarioBean oUsuarioBean = new UsuarioBean();
oEntradaBean.setTitulo(oMysql.getOne("entrada", "titulo", oEntradaBean.getId()));
oEntradaBean.setContenido(oMysql.getOne("entrada", "contenido", oEntradaBean.getId()));
oHiloBean.setId(Integer.parseInt(oMysql.getOne("entrada", "id_hilo", oEntradaBean.getId())));
oUsuarioBean.setId(Integer.parseInt(oMysql.getOne("entrada", "id_usuario", oEntradaBean.getId())));
String strFecha = oMysql.getOne("entrada", "fecha", oEntradaBean.getId());
if (strFecha != null) {
Date dFecha = new SimpleDateFormat("yyyy-MM-dd").parse(strFecha);
oEntradaBean.setFecha(dFecha);
} else {
oEntradaBean.setFecha(new Date(0));
}
HiloDao oHiloDao = new HiloDao(enumTipoConexion);
UsuarioDao oUsuarioDao = new UsuarioDao(enumTipoConexion);
oHiloBean = oHiloDao.get(oHiloBean);
oUsuarioBean = oUsuarioDao.get(oUsuarioBean);
oEntradaBean.setHilo(oHiloBean);
oEntradaBean.setUsuario(oUsuarioBean);
oMysql.desconexion();
} catch (Exception e) {
throw new Exception("EntradaDao.get: Error: " + e.getMessage());
} finally {
oMysql.desconexion();
}
return oEntradaBean;
}
|
bdcc8270-7293-4374-82de-6b3276f19bc1
| 9 |
private ZuseBinaryFloatingPoint24Bit divisor(ZuseBinaryFloatingPoint24Bit A, ZuseBinaryFloatingPoint24Bit B, boolean[] s) {
boolean[] Af = A.getExp().getCopiedBoolArr();
boolean[] Ag = B.getExp().getCopiedBoolArr();
boolean[] Bf = A.getMan().getCopiedBoolArr();
boolean[] Bg = B.getMan().getCopiedBoolArr();
boolean[] Aa = new boolean[ZuseBinaryFloatingPoint24Bit.EXPONENT];
boolean[] Ab = new boolean[ZuseBinaryFloatingPoint24Bit.EXPONENT];
boolean[] Ba = new boolean[ZuseBinaryFloatingPoint24Bit.MANTISSE];
boolean[] Bb = new boolean[ZuseBinaryFloatingPoint24Bit.MANTISSE];
boolean[] Ae = new boolean[ZuseBinaryFloatingPoint24Bit.EXPONENT];
boolean[] Be = new boolean[ZuseBinaryFloatingPoint24Bit.MANTISSE];
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Start");
boolean lz = false;
boolean ph = false;
// determine the difference d of the exponents
while (!ph) {
Aa = BinaryHelper.copy(Af);
Ab = neg(Ag);
Bb = BinaryHelper.copy(Bf);
ph = true;
Ae = BinaryHelper.normAddBinaryBoolArray(Aa, Ab, ZuseBinaryFloatingPoint24Bit.EXPONENT);
Be = BinaryHelper.normAddBinaryBoolArray(Ba, Bb, ZuseBinaryFloatingPoint24Bit.MANTISSE);
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Phase 0");
reset(Aa,Ab,Ba,Bb);
} // PH 0
ph = false;
boolean uPlus2 = true;
while (!ph) {
Aa = BinaryHelper.copy(Ae);
Ba = BinaryHelper.copy(Be);
Bb = neg(Bg);
ph = true;
Ae = BinaryHelper.normAddBinaryBoolArray(Aa, Ab, ZuseBinaryFloatingPoint24Bit.EXPONENT);
Be = BinaryHelper.normAddBinaryBoolArray(Ba, Bb, ZuseBinaryFloatingPoint24Bit.MANTISSE);
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Phase 1");
reset(Aa,Ab,Ba,Bb);
} // PH 1
ph = false;
for (int phase = 1; phase <= 17; phase++) {
while (!ph) {
Aa = BinaryHelper.copy(Ae);
if(Be[0]) {
uPlus2 = true;
} else {
uPlus2 = false;
}
if(uPlus2 == true) {
Bb = BinaryHelper.copy(Bg);
Bf = BinaryHelper.shiftLeft(Bf, 1, false);
} else {
Bb = neg(Bg);
Bf = BinaryHelper.shiftLeft(Bf, 1, true);
}
Ba = BinaryHelper.shiftLeft(Be, 1);
ph = true;
Ae = BinaryHelper.normAddBinaryBoolArray(Aa, Ab, ZuseBinaryFloatingPoint24Bit.EXPONENT);
Be = BinaryHelper.normAddBinaryBoolArray(Ba, Bb, ZuseBinaryFloatingPoint24Bit.MANTISSE);
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Phase "+phase);
reset(Aa,Ab,Ba,Bb);
} // PH 2...17
ph = false;
}
ph = false;
while (!ph) {
Aa = BinaryHelper.copy(Ae);
Bb = BinaryHelper.copy(Bf);
ph = true;
Ae = BinaryHelper.normAddBinaryBoolArray(Aa, Ab, ZuseBinaryFloatingPoint24Bit.EXPONENT);
Be = BinaryHelper.normAddBinaryBoolArray(Ba, Bb, ZuseBinaryFloatingPoint24Bit.MANTISSE);
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Phase 19");
reset(Aa,Ab,Ba,Bb);
} // PH 19
ph = false;
while (!ph) {
if(Be[1] == false) {
Aa = BinaryHelper.copy(Ae);
Ab = _minus1();
Ba = BinaryHelper.shiftLeft(Be, 1);
} else {
Aa = BinaryHelper.copy(Ae);
Bb = BinaryHelper.copy(Be);
lz = true;
break;
}
ph = true;
Ae = BinaryHelper.normAddBinaryBoolArray(Aa, Ab, ZuseBinaryFloatingPoint24Bit.EXPONENT);
Be = BinaryHelper.normAddBinaryBoolArray(Ba, Bb, ZuseBinaryFloatingPoint24Bit.MANTISSE);
printRegisters(Af, Ag, Bf, Bg, Aa, Ab, Ba, Bb, Ae, Be, "Phase 20");
reset(Aa,Ab,Ba,Bb);
} // PH 20
ph = false;
return new ZuseBinaryFloatingPoint24Bit(new Exponent(Ae), new Mantissa(Be));
}
|
2a38db75-ca29-4107-a49c-58ab26b60454
| 7 |
@Override
public void changedUpdate(DocumentEvent arg0) {
try{
if(Integer.parseInt(textRow.getText()) < 1){
JOptionPane.showMessageDialog(this, "Rows need to be higher than 0!");
textRow.setText("10");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!");
this.textRow.setText("10");
}
try{
if(Integer.parseInt(textCol.getText()) < 1){
JOptionPane.showMessageDialog(this, "Cols need to be higher than 0!");
textCol.setText("10");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!");
this.textCol.setText("10");
}
try{
if(Integer.parseInt(textBombs.getText()) < 1){
JOptionPane.showMessageDialog(this, "Bomb Percentage need to be higher than 0!");
textBombs.setText("10");
}
if(Integer.parseInt(textBombs.getText()) > 100){
JOptionPane.showMessageDialog(this, "Bombs Percentage need to be lower than 100!");
textBombs.setText("10");
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(this, "All Fields need to be filled with integers!");
this.textBombs.setText("10");
}
}
|
1b604042-afe2-47e3-be46-bd9e703e44a8
| 6 |
@Override
public Class<?> getColumnClass(int columnIndex){
Class type = String.class;
switch (columnIndex){
case 0:
type = Integer.class;
break;
case 1:
type = String.class;
break;
case 2:
type = String.class;
break;
case 3:
type = String.class;
break;
case 4:
type = Boolean.class;
break;
}
return type;
}
|
289e96cf-3158-479e-aae8-06b7d298b22e
| 8 |
public boolean movimientoCorrecto(Movimiento m, int color) {
boolean correcto = true;
if (tablero[m.fila][m.columna] != 0)
correcto = false;
else {
return (direccionCorrecta(m.fila, m.columna, -1,-1,color) ||
direccionCorrecta(m.fila, m.columna, -1,0,color) ||
direccionCorrecta(m.fila, m.columna, -1,1,color) ||
direccionCorrecta(m.fila, m.columna, 0,1,color) ||
direccionCorrecta(m.fila, m.columna, 1,1,color) ||
direccionCorrecta(m.fila, m.columna, 1,0,color) ||
direccionCorrecta(m.fila, m.columna, 1, -1,color) ||
direccionCorrecta(m.fila, m.columna,0,-1,color));
}
return correcto;
}
|
8327f1fe-9ba9-4995-87a5-20137794e1f1
| 3 |
public static int createTexture(String name, BufferedImage image) {
if (!ProjUtils.isPowerOf2(image.getWidth()) || !ProjUtils.isPowerOf2(image.getHeight())) {
System.out.println(name + " texture must have dimension values of a power of 2");
System.exit(1);
}
int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
for (int pixel : pixels) {
buffer.put((byte)((pixel >> 16) & 0xFF));
buffer.put((byte)((pixel >> 8) & 0xFF));
buffer.put((byte)(pixel & 0xFF));
buffer.put((byte)((pixel >> 24) & 0xFF));
}
buffer.flip();
int textureID = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL42.glTexStorage2D(GL11.GL_TEXTURE_2D, ProjUtils.log2(image.getWidth()), GL11.GL_RGBA8, image.getWidth(), image.getHeight());
GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, 0, 0, image.getWidth(), image.getHeight(), GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
textureIDMap.put(name, textureID);
return textureID;
}
|
cfc5b995-d60a-4782-ab12-fef7df393737
| 7 |
public String able(int a, int b, int c, int d) {
LinkedList<Integer> queue = new LinkedList<Integer>();
int s = a * 10000 + b;
queue.add(s);
while (!queue.isEmpty()) {
int ss = queue.removeFirst();
int aa = ss / 10000;
int bb = ss % 10000;
if (aa == c && bb == d) {
return "Able to generate";
} else {
if (aa + bb <= c && bb <= d)
queue.addLast((aa + bb) * 10000 + bb);
if (aa <= c && aa + bb <= d)
queue.addLast(aa * 10000 + (aa + bb));
}
}
return "Not able to generate";
}
|
684f4468-d2c6-44b0-b9a5-72030e0c4265
| 5 |
@SuppressWarnings("unchecked")
public void setPackages(List<Package> packages) {
String serverAddress = "localhost";
Element packagesElement = root.getChild("packages");
if (packagesElement == null )
{
packagesElement = new Element("packages");
root.addContent(packagesElement);
}
List<Element> serverElements = packagesElement.getChildren("server");
Element serverElement = null;
for ( Element s : serverElements ) {
if ( serverAddress.equals(s.getAttribute("address").getValue()) ) {
serverElement = s;
}
}
if (serverElement != null)
{
serverElement.removeChildren("package");
} else {
serverElement = new Element("server");
serverElement.setAttribute("address", serverAddress);
packagesElement.addContent(serverElement);
}
for ( Package p : packages ) {
serverElement.addContent(p.toXML());
}
}
|
1cfe9035-568a-49a3-b803-ffff9d20ad22
| 5 |
public static boolean isNeeded(String entryText) {
/*
* If 'stack' is zero at the end of the method: * The lastTime point to
* the end of "Nituach Dikduki" section. * The open curly bracket equals
* to the close curly bracket.
*/
int stack = 0;
NituachDikduki.lastTime.start = 0;
NituachDikduki.lastTime.end = 0;
int index;
if (!entryText.contains("ניתוח דקדוקי")) { // No Nituach Dikduki found.
NituachDikduki.isNeeded = false;
return false;
} else {
NituachDikduki.lastTime.start = entryText.indexOf("{{ניתוח דקדוקי", 0);
NituachDikduki.lastTime.end = NituachDikduki.lastTime.start;
index = NituachDikduki.lastTime.end;
NituachDikduki.isNeeded = true;
}
do {
if (Util.stringAt(entryText, index).equals("{{")) {// Push stack
stack++;
} else if (Util.stringAt(entryText, index).equals("}}")) { // Pop stack
stack--;
}
if (stack == 0) {// The stack is empty
break;
}
index++;
} while (index < entryText.length());
index++;
NituachDikduki.lastTime.end = index;
return true;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.