method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
4fd363ef-2d19-4b02-b0a0-efe85fea4a6e | 8 | public boolean placeToken(int _column)
{
if(checkIfValidColumn(_column) == true)
{
int win;
for (int i = 0; i < row; i ++)
{
if (i == row - 1)
{
gameGrid[i][_column - 1] = currentPlayer;
win = checkForAWinner();
notifyOfGameChange(i, _column);
if (win != 0)
{
System.out.println("Palyer " + win + " wins!");
notifyOfGameEnd();
}
else if(checkIfDraw())
{
notifyDraw();
}
return true;
}
else if (gameGrid[i + 1][_column - 1] != EMPTY)
{
gameGrid[i][_column - 1] = currentPlayer;
win = checkForAWinner();
notifyOfGameChange(i, _column);
if (win != 0)
{
System.out.println("Palyer " + win + " wins!");
notifyOfGameEnd();
}
else if(checkIfDraw())
{
notifyDraw();
}
return true;
}
}
}
return false;
} |
7afb8247-0624-4250-ae06-d1f82954dc8e | 5 | public static void populateFromMap(Object obj, Map<String, Object> properties,
Map<String, Method> setters) throws IllegalAccessException,
InvocationTargetException {
if (obj == null || setters == null || setters.isEmpty()) {
return;
}
for (Map.Entry<String, Method> stringMethodEntry : setters.entrySet()) {
Method setter = stringMethodEntry.getValue();
String prop = propertyFor(setter);
if (properties.containsKey(prop)) {
Object[] args = { properties.get(prop) };
setter.invoke(obj, args);
}
}
} |
25a72a2d-b628-4486-b05c-8241880b5e32 | 3 | @Override
public void render() {
GameActor a = Application.get().getLogic().getActor(Application.get().getLogic().getGame().getBaseID());
PhysicsComponent pc = null;
if(a != null) {
pc = (PhysicsComponent)a.getComponent("PhysicsComponent");
}
if(pc != null && (float)((float)pc.getHealth() / (float)pc.getMaxHealth()) <= 0.3) {
renderCrisis();
}
else {
super.render();
}
} |
76f0fd63-69fb-4c70-862c-fb782737ee9e | 3 | protected CycList substituteForBackquote(CycList messageCycList,
Timer timeout)
throws IOException, CycApiException {
if (messageCycList.treeContains(CycObjectFactory.backquote)) {
CycList substituteCycList = new CycList();
substituteCycList.add(CycObjectFactory.makeCycSymbol("read-from-string"));
String tempString = messageCycList.cyclify();
tempString = tempString.replaceAll("\\|\\,\\|", ",");
substituteCycList.add(tempString);
Object[] response = converseBinary(substituteCycList,
timeout);
if ((response[0].equals(Boolean.TRUE)) && (response[1] instanceof CycList)) {
CycList backquoteExpression = (CycList) response[1];
return backquoteExpression.subst(CycObjectFactory.makeCycSymbol("api-bq-list"),
CycObjectFactory.makeCycSymbol("bq-list"));
}
throw new CycApiException("Invalid backquote substitution in " + messageCycList +
"\nstatus" + response[0] + "\nmessage " + response[1]);
}
return messageCycList;
} |
ab19ad43-322e-4499-b0e1-02fa849f458a | 0 | public void setjButtonNew(JButton jButtonNew) {
this.jButtonNew = jButtonNew;
} |
1fde4490-ef33-483d-99e0-ed007f3da3b2 | 9 | private QueryPart parseRestrictions(String rql, AtomicInteger pos) {
ComplexPart part = new ComplexPart();
rql = rql.trim();
boolean isString = false; //if true, we are dealing with a string
boolean isMethodWithParenthesis = false; //if true, it is not a sub expression
char chr = '-'; //just any character
StringBuilder builder = new StringBuilder(); // this hold the level's expressions
String lowerRQL = null;
int i = pos.get();
while(i < rql.length()) {
chr = rql.charAt(i);
i = pos.incrementAndGet();
switch(chr) {
case '(':
if(isString) {
builder.append(chr);
continue;
}
lowerRQL = builder.toString().toLowerCase();
isMethodWithParenthesis = isMethodWithParameter(lowerRQL);
if(isMethodWithParenthesis) {
builder.append(chr);
i = pos.get();
continue;
}
lowerRQL = lowerRQL.trim();
if(lowerRQL.length() == 0) {
part.addPart(parseRestrictions(rql, pos));
i = pos.get();
continue;
}
parsePartial(part, rql, pos, builder.toString().trim());
part.addPart(parseRestrictions(rql, pos));
i = pos.get();
break;
case ')':
if(isString) {
builder.append(chr);
i = pos.get();
continue;
}
if(isMethodWithParenthesis) {
builder.append(chr);
isMethodWithParenthesis = false;
i = pos.get();
continue;
}
parsePartial(part, rql, pos, builder.toString());
return part;
case '\'':
isString = !isString;
builder.append(chr);
break;
default:
builder.append(chr);
}
}
parsePartial(part, rql, pos, builder.toString().trim());
return part;
} |
22a111df-dec5-40bb-96e2-934aff30629b | 0 | public UnitProductionRemover() {
} |
67141f6d-f3ae-409f-8006-cb0a78eadad1 | 2 | public static String[] parseAka(String data) {
Jmdb.log.debug("Parsing movie AKAs");
Matcher matcher = akaPattern.matcher(data);
String akas;
String[] aka = null;
if (matcher.find()) {
akas = htmlEntityDecode(matcher.group(1).trim());
akas = akas.replaceAll("\\([^\\)]+\\)", ""); // Replace everything within ()
if (akas.indexOf("<br>") != -1) {
aka = akas.split("<br>");
} else {
aka = new String[1];
aka[0] = akas;
}
} else {
aka = new String[0];
}
return aka;
} |
2685d881-7b70-459c-8a57-9eae62431dd0 | 2 | public int getAttributeSize() {
int size = 2; /* attribute count */
if (unknownAttributes != null) {
Iterator i = unknownAttributes.values().iterator();
while (i.hasNext())
size += 2 + 4 + ((byte[]) i.next()).length;
}
return size;
} |
6865c93d-20f6-438f-b129-f6d89daf1f15 | 0 | void showErrorMessage(String message) {
errorMessage.setVisible(true);
errorMessage.setText(message);
} |
be670709-bae4-4f67-b002-386775bb1952 | 9 | @Override
public boolean equals(Object obj){
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
PieceLocation other = (PieceLocation)obj;
if (this.location == null){
if (other.location != null) return false;
} else if (!this.location.equals(other.location)) return false;
if (this.piece == null){
if (other.piece != null) return false;
} else if (!this.piece.equals(other.piece)) return false;
return true;
} |
2790afc5-08a7-4e43-a005-74ca60c32ee8 | 8 | public static int countNeighbours(long world, int col, int row) {
int c = 0;
if (getCell(world, col - 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col, row - 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row - 1) == true) {
c += 1;
}
if (getCell(world, col - 1, row) == true) {
c += 1;
}
if (getCell(world, col + 1, row) == true) {
c += 1;
}
if (getCell(world, col - 1, row + 1) == true) {
c += 1;
}
if (getCell(world, col, row + 1) == true) {
c += 1;
}
if (getCell(world, col + 1, row + 1) == true) {
c += 1;
}
return c;
} |
f781a87f-964c-4e3d-8dc8-65ef90b6873f | 7 | private boolean isClassBox(String owner) {
if (!owner.startsWith("java/lang/")) {
return false;
}
String className = owner.substring("java/lang/".length());
return (className.equals("Integer") ||
className.equals("Double") ||
className.equals("Long") ||
className.equals("Char") ||
className.equals("Byte") ||
className.equals("Boolean")) ||
className.endsWith("Number");
} |
e3ae934c-616d-420a-92c0-f7e31fb73e77 | 0 | public Worker () {
//initial settings
isInputActive = true;
this.keyboard = new BufferedReader(new InputStreamReader(System.in));
System.out.println(MSG_WELCOME);
//start
this.lifeCycle();
} |
ad883029-fc40-4136-b779-c8e18b9e1b8a | 4 | public static int listCompare(ArrayList<Double> l1, ArrayList<Double> l2){
int size = l1.size();
int i;
double[] diff = new double[size];
for(i = 0; i < size; i++){
Double d1 = l1.get(i);
Double d2 = l2.get(i);
if(d1 - d2 > epsilon){
diff[i] = 1;
}
else{
diff[i] = 0;
}
}
for(i = 0; i < size; i++){
if(diff[i] == 1){
return 1;
}
}
return 0;
} |
551e0ef1-23db-4fee-bc2d-0ec8483eaa37 | 9 | public void drawPath(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
List<String> path = new ArrayList<>();
if (player.isSelected()) {
Field mouseOverField = null;
for (int i = 0; i < hexMap.length; i++) {
for (int j = 0; j < hexMap[i].length; j++) {
if (hexMap[i][j].isMouseOver()) {
mouseOverField = hexMap[i][j];
}
}
}
if (mouseOverField != null) {
NavigationMapUtils navigationMapUtils = new NavigationMapUtils();
List<String> tmpPath =
navigationMapUtils.calculateNavMapPath(player.getNavMapPos(), mouseOverField.getNavMapPos(), navMap);
Set<String> neighboursInRange = navigationMapUtils.calculateNavMapNeighboursInRange(player.getNavMapPos(), 3, navMap);
for (String navMapPos : tmpPath) {
if (neighboursInRange.contains(navMapPos)) {
path.add(navMapPos);
}
}
}
if (path.size() > 0) {
int[] xPoints = new int[path.size() + 1];
int[] yPoints = new int[path.size() + 1];
int nPoints = path.size() + 1;
Field currentField = navMap.get(player.getNavMapPos());
xPoints[0] = (int)currentField.getXCenterPixel();
yPoints[0] = (int)currentField.getYCenterPixel();
for (int i = 0; i < path.size(); i++) {
String navMapPos = path.get(i);
currentField = navMap.get(navMapPos);
xPoints[i + 1] = (int)currentField.getXCenterPixel();
yPoints[i + 1] = (int)currentField.getYCenterPixel();
}
g2.setColor(Color.ORANGE);
// g2.setStroke(new BasicStroke(5));
float[] dash = {5.0f};
BasicStroke dashedBasicStroke =
new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
g2.setStroke(dashedBasicStroke);
g2.drawPolyline(xPoints, yPoints, nPoints);
g2.setStroke(new BasicStroke(7));
double l = 10.0; // Pfeilspitzenlänge
double a = Math.PI / 4 - Math.atan2((yPoints[yPoints.length - 1] - yPoints[yPoints.length - 2]),
(xPoints[xPoints.length - 1] - xPoints[xPoints.length - 2]));
double c = Math.cos(a) * l;
double s = Math.sin(a) * l;
g.drawLine(xPoints[xPoints.length - 1], yPoints[yPoints.length - 1], (int) (xPoints[xPoints.length - 1] - s),
(int) (yPoints[yPoints.length - 1] - c));
g.drawLine(xPoints[xPoints.length - 1], yPoints[yPoints.length - 1], (int) (xPoints[xPoints.length - 1] - c),
(int) (yPoints[yPoints.length - 1] + s));
}
}
} |
5db09805-bbe5-4c1d-b991-694c9cd58ef7 | 1 | public static void deleteElement(ElementField element) {
if (element != null) {
_elements_sprite.remove(element);
}
} |
882bf316-bfcb-4cab-adfc-7759fa9b0946 | 1 | public ArrayList<Student> students(ResultSet rs) throws Exception {
DBConnector db = new DBConnector();
ArrayList<Student> data = new ArrayList<>();
while (rs.next()) {
data.add(new Student(db.getPerson(rs.getInt("personid"))));
}
return data;
} |
d3fe6c2c-207c-48d9-a2c7-208d6f6b738f | 5 | public Object getValueAt(int row, int column) {
try {
Class c = rows.get(row).getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(c, Object.class);
PropertyDescriptor pd = beanInfo.getPropertyDescriptors()[column];
Method m = pd.getReadMethod();
if( m!= null){
return m.invoke(rows.get(row), null);
}
} catch (IllegalAccessException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IntrospectionException ex) {
Logger.getLogger(GenericTableModel.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} |
a38b720e-6ff8-4a5e-a7ec-ae75f51e9e3d | 5 | @Override
public LevelData getData() throws LevelIOException
{
String leveltxt = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//odd: the Object param of getContents is not currently used
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =
(contents != null)
&& contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText)
try
{
leveltxt = (String) contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException | IOException ex)
{
throw new LevelIOException(ex);
}
if (!(leveltxt.startsWith(clipboardHeader) && leveltxt.endsWith(clipboardFooter)))
throw new LevelIOException("Clipboard contents aren't a NSMB level.");
leveltxt = leveltxt.substring(11, leveltxt.length() - 12);
byte[] leveldata = DatatypeConverter.parseBase64Binary(leveltxt);
leveldata = LZ.decompress(leveldata);
return new LevelData(leveldata);
} |
51bdb0ef-7cdc-4267-a49a-ef1d272b9dab | 2 | @Override
public T next() {
if (!mNextValid) {
if (!hasNext()) {
throw new NoSuchElementException();
}
}
mNextValid = false;
return mNext;
} |
ac1d98f7-cd5d-4045-90a9-b4278e8d01f9 | 7 | public void gameLoop() {
//Main game Loop of the game
boolean pieceFree = true;
while (true) {
if (!isSpawnFree()) {
System.out.println("\n\n\n\n GAME OVER \n\n\n");
this.grid.fireGameOver();
break;
} else {
grid.spawnPiece();
while (pieceFree) {
if (!_gameState) {
try {
synchronized (this) {
wait();
}
} catch (InterruptedException ex) {
Logger.getLogger(TetrisCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
Thread.currentThread().sleep((long) getTempo());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
break;
}
pieceFree = this.grid.isDownable();
if (pieceFree) {
this.grid.getCurrentPiece().setPosition(this.grid.getCurrentPiece().getPosition().getDownPosition());
this.grid.fireUpdatedGrid(grid.getColorTab(true));
}
}
this.grid.fixPiece();
getInfo().updateScore(grid.destroyLines());
updateSpeed();
this.nextPiece();
pieceFree = true;
}
}
} |
91b942ae-8077-4ca8-a2bc-bb34b00bf071 | 4 | public void setDialogButton(String[] buttons){
dialogButtonsPanel.removeAll();
dialogButtonsPanel.add(dialogFiller);
for(String buttonName : buttons){
if(buttonName.equals("ok")){
dialogButtonsPanel.add(okButton);
}
else if(buttonName.equals("cancel")){
dialogButtonsPanel.add(cancelButton);
}
else if(buttonName.equals("close")){
dialogButtonsPanel.add(closeButton);
}
}
} |
8d9f6393-2d45-4667-bc54-a1324f21b4f9 | 2 | public User getUserByEmail(String email) {
try {
String sql = "select * from user where email=" + email;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
User user = new User();
user.setUserId(Integer.parseInt(rs.getString("user_id")));
user.setEmail(rs.getString("email"));
user.setPassword(rs.getString("password"));
stmt.close();
rs.close();
closeConnection();
return user;
} else {
stmt.close();
rs.close();
closeConnection();
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} |
67d2fda1-6975-48c3-aa6c-42bff48bbf81 | 8 | public boolean has(Player player, String node) {
try {
if (vaultPerms != null) {
return vaultPerms.has(player, node);
} else if (nijPerms != null) {
return nijPerms.getHandler().has(player, node);
}
// System.out.println("no perm: checking superperm for " + player.getName() + ": " + node);
// System.out.println(player.hasPermission(node));
// for(PermissionAttachmentInfo i : player.getEffectivePermissions()){
// System.out.println(i.getPermission());
// }
if (player.hasPermission(node)) {
return true;
} else if (!node.contains("*") && Str.count(node, '.') >= 2) {
return player.hasPermission(node.substring(0, node.lastIndexOf('.') + 1) + "*");
}
return false;
} catch (Exception e) {
plugin.getLogger().log(Level.SEVERE, "Error Checking Permissions", e);
}
return node.length() < 16 // if invalid node, assume true
|| (!node.substring(0, 16).equalsIgnoreCase("BetterShop.admin") // only ops have access to .admin
&& !node.substring(0, 19).equalsIgnoreCase("BetterShop.discount"));
} |
6345042c-9799-404d-8c28-037e8c3a949c | 6 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if (customerID == null) {
if (other.customerID != null)
return false;
} else if (!customerID.equals(other.customerID))
return false;
return true;
} |
5234d916-3903-45cb-948f-b86e20b9c74c | 4 | @Override
public boolean activate() {
return (!Inventory.contains(Constants.BEAR_FUR)
&& !Bank.isOpen()
&& !Constants.BURTHOPE_BANK_AREA.contains(Players.getLocal())
&& !Constants.BEAR_AREA.contains(Players.getLocal())
&& !Constants.ESCAPE_AREA.contains(Players.getLocal()));
} |
7b394928-2bb9-449f-9f08-39ba1afeeec9 | 1 | @Override
public void removeObserver(IObserver observer) {
int index = this.observers.indexOf(observer);
if (index >= 0) {
this.observers.remove(index);
}
} |
699e644f-d73c-464b-b371-43707bbe01c0 | 5 | @Override
public void unsetResource(ResourceType resource) {
Player player = presenter.getClientModel().getServerModel().getPlayerByID(presenter.getPlayerInfo().getID());
switch(resource.name().toLowerCase()) {
case "brick":
this.brickState = 0;
this.desiredBrick = 0;
this.offeredBrick = 0;
this.availableBrick = player.getBrick();
getTradeOverlay().setResourceAmount(ResourceType.BRICK, "0");
break;
case "ore":
this.oreState = 0;
this.desiredOre = 0;
this.offeredOre = 0;
this.availableOre = player.getOre();
getTradeOverlay().setResourceAmount(ResourceType.ORE, "0");
break;
case "wheat":
this.wheatState = 0;
this.desiredWheat = 0;
this.offeredWheat = 0;
this.availableWheat = player.getWheat();
getTradeOverlay().setResourceAmount(ResourceType.WHEAT, "0");
break;
case "sheep":
this.sheepState = 0;
this.desiredSheep = 0;
this.offeredSheep = 0;
this.availableSheep = player.getSheep();
getTradeOverlay().setResourceAmount(ResourceType.SHEEP, "0");
break;
case "wood":
this.woodState = 0;
this.desiredWood = 0;
this.offeredWood = 0;
this.availableWood = player.getWood();
getTradeOverlay().setResourceAmount(ResourceType.WOOD, "0");
break;
default:
System.err.println("Error in unset resource for offer trade");
}
checkForValidTradeValues();
} |
16dd5c10-ca1e-4a4a-9d2f-8fe57c25ea91 | 7 | public Imagen traslacion(Imagen imgFuente, double factX, double factY) {
Imagen imgResultado = new Imagen();
imgResultado = imgFuente.clone();
short[][] matrizResultado = new short[imgFuente.getN()][imgFuente.getM()];
short[][] matrizFuente = imgFuente.getMatrizGris();
if(imgFuente.getFormato().equals("P2")) {
for(int i = 0; i < matrizFuente.length; i++) {
for(int j = 0; j < matrizFuente[0].length; j++) {
int iPrima = (int)(i + factX);
int jPrima = (int)(j + factY);
short pixelFuente = matrizFuente[i][j];
if(iPrima < 0) {
iPrima = 0;
}
if(jPrima < 0) {
jPrima = 0;
}
if(iPrima < matrizFuente.length && jPrima < matrizFuente[0].length) {
matrizResultado[iPrima][jPrima] = pixelFuente;
}
}
}
}
imgResultado.setMatrizGris(matrizResultado);
return imgResultado;
} |
ee606cc5-5919-49bb-bd42-b278e8fc2150 | 5 | public SlideShow parse(String aPathName) {
if (Debug.parser)
System.out.println("xmlPath"+aPathName);
xmlPath = aPathName;
xmlPath = xmlPath.replace('\\', '/');
// get schema and xml files
File inputFile = new File(aPathName);
if (!inputFile.exists()) {
System.out.println("Parser error: passed file does not exist");
return null;
}
// create a parser
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser;
// parse files
try {
saxParser = factory.newSAXParser();
mode = "getschema";
saxParser.parse(inputFile, this);
File schema = new File(schemaPath);
if (Debug.parser)
System.out.println("schemaPath"+schemaPath);
// validate passed xml against schema
if (!isValid(inputFile, schema)) {
System.out.println("Validation error!");
return null;
}
// get schema defaults
mode = "schemadefs";
saxParser.parse(schema, this);
// overwrite schema defaults when redefined in xml
mode = "xmldefs";
saxParser.parse(inputFile, this);
// get data
mode = "parse";
saxParser.parse(inputFile, this);
} catch (Exception e) {
// something went wrong
e.printStackTrace();
System.out.println("SAX Error! Unable to parse slideshow"
+ e.getMessage());
return null;
}
// sort slides into ascending order of id, name any slide with no name
sortSlides();
return (slideShow);
} |
364395bc-e9dc-430f-8690-93a026c171a0 | 0 | public final boolean isDefault() {
return this.equals(defaultFlags);
} |
d99268e0-85d9-4985-ab6a-426d8273b898 | 2 | private void checkEnoughCapacity(int number) {
// if (array.length - currentSize < number) {
// expandVectorCapacityBy(number - array.length + currentSize);
// }
if (array.length - currentSize < number) {
changeVectorCapacityBy(array.length);
} else if (currentSize < array.length / 4) {
changeVectorCapacityBy(-array.length / 2);
}
} |
1f152717-3c61-4045-9a8f-7d893eae0eea | 0 | public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
} |
365c7c84-ef25-4289-9a7a-4c4293deeae4 | 5 | private ItemStack getResult(ArrayList<String> holder){
ItemStack fail = new ItemStack(Material.SKULL);
ItemStack dish = null;
if(!this.recipeSpiceyChicken(holder,fail).isSimilar(fail)){
return this.recipeSpiceyChicken(holder,fail);
}
if(!this.recipeSeasonedChicken(holder,fail).isSimilar(fail)){
return this.recipeSeasonedChicken(holder,fail);
}
if(!this.recipeFurnaceSpiceyChicken(holder,fail).isSimilar(fail)){
return this.recipeFurnaceSpiceyChicken(holder,fail);
}
if(!this.recipeFurnaceSeasonedChicken(holder,fail).isSimilar(fail)){
return this.recipeFurnaceSeasonedChicken(holder,fail);
}
if(dish == null){
dish = fail;
}
return dish;
} |
820d4c46-f0b7-4281-96e8-034a2796c783 | 1 | public void makeOpAssign(int operatorIndex) {
setOperatorIndex(operatorIndex);
if (subExpressions[1] instanceof NopOperator)
subExpressions[1].type = Type.tUnknown;
opAssign = true;
} |
f6ddbe2c-73c0-4f40-a5d4-2935e4c94ac2 | 5 | public boolean movable(int x,int y,int xOrig, int yOrig){
if(thePlayer.getHitPoints() <= 0){
return false;
}
/* not movable, out of boundary*/
if (!inBounds(x, y))
return false;
//player isn't movable, start attack for player
if(floor[x][y] instanceof Monster){
/*if(floor[xOrig][yOrig] instanceof Player){
return false;
}else{
return false;
}*/
return false;
}
//monster isn't movable, start attack for monster
if(floor[x][y] instanceof Player && floor[xOrig][yOrig] instanceof Monster){
return false;
}
return true;
} |
d5d331a4-55e6-4d19-9233-340e22ff97db | 9 | @Override
protected void CustomRender(GameContainer gc, Graphics g) throws SlickException {
g.drawImage(fond, Ctes.CARACS_X_FOND, Ctes.CARACS_Y_FOND);
afficheClasse(perso, g);
g.drawString("Niveau " +perso.getNiveau(), Ctes.CARACS_X_NIVEAU, Ctes.CARACS_Y_NIVEAU);
if (perso.getNiveau() < 20) {
g.drawString("Expérience : " +perso.getXp()+ "/" +perso.getXpNeed(), Ctes.CARACS_X_XP, Ctes.CARACS_Y_XP);
int pourcentXp = perso.getXp() * 200 / perso.getXpNeed();
g.drawImage(barreXp.getSubImage(0, 0, pourcentXp, barreXp.getHeight()), Ctes.CARACS_X_BARREXP, Ctes.CARACS_Y_BARREXP);
}
else {
g.drawString("Expérience : MAX ", Ctes.CARACS_X_XP, Ctes.CARACS_Y_XP);
g.drawImage(barreXp, Ctes.CARACS_X_BARREXP, Ctes.CARACS_Y_BARREXP);
}
g.drawString("Honneur : " +perso.getFame(), Ctes.CARACS_X_FAME, Ctes.CARACS_Y_FAME);
g.drawString("Vie maximale : " +perso.getStatsAct().getHp()+ " (" +perso.getStatsMaxAct().getHp()+ " + "
+(perso.getStatsAct().getHp() - perso.getStatsMaxAct().getHp())+ ")", Ctes.CARACS_X_HP, Ctes.CARACS_Y_HP);
if (perso.getStatsMaxAct().getHp() == perso.getStatsMax().getHp())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_HP);
g.drawString("Mana maximale : " +perso.getStatsAct().getMp()+ " (" +perso.getStatsMaxAct().getMp()+ " + "
+(perso.getStatsAct().getMp() - perso.getStatsMaxAct().getMp())+ ")", Ctes.CARACS_X_MP, Ctes.CARACS_Y_MP);
if (perso.getStatsMaxAct().getMp() == perso.getStatsMax().getMp())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_MP);
g.drawString("Attaque : " +perso.getStatsAct().getAtk()+ " (" +perso.getStatsMaxAct().getAtk()+ " + "
+(perso.getStatsAct().getAtk() - perso.getStatsMaxAct().getAtk())+ ")", Ctes.CARACS_X_ATK, Ctes.CARACS_Y_ATK);
if (perso.getStatsMaxAct().getAtk() == perso.getStatsMax().getAtk())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_ATK);
g.drawString("Défense : " +perso.getStatsAct().getDef()+ " (" +perso.getStatsMaxAct().getDef()+ " + "
+(perso.getStatsAct().getDef() - perso.getStatsMaxAct().getDef())+ ")", Ctes.CARACS_X_DEF, Ctes.CARACS_Y_DEF);
if (perso.getStatsMaxAct().getDef() == perso.getStatsMax().getDef())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_DEF);
g.drawString("Vitesse : " +perso.getStatsAct().getSpd()+ " (" +perso.getStatsMaxAct().getSpd()+ " + "
+(perso.getStatsAct().getSpd() - perso.getStatsMaxAct().getSpd())+ ")", Ctes.CARACS_X_SPD, Ctes.CARACS_Y_SPD);
if (perso.getStatsMaxAct().getSpd() == perso.getStatsMax().getSpd())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_SPD);
g.drawString("Dextérité : " +perso.getStatsAct().getDex()+ " (" +perso.getStatsMaxAct().getDex()+ " + "
+(perso.getStatsAct().getDex() - perso.getStatsMaxAct().getDex())+ ")", Ctes.CARACS_X_DEX, Ctes.CARACS_Y_DEX);
if (perso.getStatsMaxAct().getDex() == perso.getStatsMax().getDex())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_DEX);
g.drawString("Vitalité : " +perso.getStatsAct().getVit()+ " (" +perso.getStatsMaxAct().getVit()+ " + "
+(perso.getStatsAct().getVit() - perso.getStatsMaxAct().getVit())+ ")", Ctes.CARACS_X_VIT, Ctes.CARACS_Y_VIT);
if (perso.getStatsMaxAct().getVit() == perso.getStatsMax().getVit())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_VIT);
g.drawString("Sagesse : " +perso.getStatsAct().getWis()+ " (" +perso.getStatsMaxAct().getWis()+ " + "
+(perso.getStatsAct().getWis() - perso.getStatsMaxAct().getWis())+ ")", Ctes.CARACS_X_WIS, Ctes.CARACS_Y_WIS);
if (perso.getStatsMaxAct().getWis() == perso.getStatsMax().getWis())
g.drawString("MAX", Ctes.CARACS_X_MAX, Ctes.CARACS_Y_WIS);
} |
35582307-53ca-4d9d-a038-f7b294774447 | 2 | protected void cascadingCut(Fibonaccinode y) {
Fibonaccinode z = y.parent;
if (z != null) {
if (!y.mark) {
//merkataan solmu
y.mark = true;
} else {
cut(y, z);
cascadingCut(z);
}
}
} |
02c74664-7858-49a8-8b96-89a8a0a58f11 | 6 | @Override
public void selectCourses(List<Integer> mainCourseList, List<Integer> additionalCourseList, int userId) throws SQLException {
Connection connect = null;
PreparedStatement statement = null;
try {
Class.forName(Params.bundle.getString("urlDriver"));
connect = DriverManager.getConnection(Params.bundle.getString("urlDB"),
Params.bundle.getString("userDB"), Params.bundle.getString("passwordDB"));
String getTeacherId = "select student.id from student " +
"where student.user_id = ?";
statement = connect.prepareStatement(getTeacherId);
statement.setInt(1, userId);
ResultSet studentIdSet = statement.executeQuery();
studentIdSet.next();
int studentId = studentIdSet.getInt("student.id");
String selectMarks = "insert into student (main_course_1_id, main_course_2_id, main_course_3_id, main_course_4_id," +
"add_course_1_id,add_course_2_id) values (?,?,?,?,?,?) where student.id=?";
statement = connect.prepareStatement(selectMarks);
int i = 0;
for(; i < mainCourseList.size(); i++)
statement.setInt(i + 1, mainCourseList.get(i));
for(; i < additionalCourseList.size(); i++)
statement.setInt(i + 1, additionalCourseList.get(i - mainCourseList.size()));
statement.setInt(i, studentId);
statement.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(connect != null)
connect.close();
if(statement != null)
statement.close();
}
} |
ed05a570-e82c-4473-9948-1ca80ad92d98 | 2 | public boolean equals(Node other) {
return other != null && x == other.getX() && y == other.getY();
} |
793199cd-7c77-491f-b149-dc0efc87ee2e | 7 | private void zoomOutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomOutButtonActionPerformed
diagramPanel.getScaleRatio()[0] -= 0.25;
diagramPanel.getScaleRatio()[1] -= 0.25;
diagramPanel.getScaleRatio()[0] = Math.max(0.3, getDiagramPanel().getScaleRatio()[0]);
diagramPanel.getScaleRatio()[1] = Math.max(0.3, getDiagramPanel().getScaleRatio()[1]);
int minX = Integer.MAX_VALUE;
int minY = Integer.MAX_VALUE;
int maxX = 0;
int maxY = 0;
Element e = null;
Element e2 = null;
ArrayList<Element> elements = new ArrayList<Element>();
if (this.graph instanceof PetriNet) {
PetriNet pn = (PetriNet) this.graph;
elements = new ArrayList<Element>();
elements.addAll(pn.getListOfArcs());
elements.addAll(pn.getListOfPlaces());
elements.addAll(pn.getListOfResources());
elements.addAll(pn.getListOfTransitions());
}
if (this.graph instanceof PrecedenceGraph) {
PrecedenceGraph pg = (PrecedenceGraph) this.graph;
elements = new ArrayList<Element>();
elements.addAll(pg.getListOfArcs());
elements.addAll(pg.getListOfNodes());
}
for (Element element : elements) {
if (minX > element.getX()) {
minX = element.getX();
e = element;
}
if (minY > element.getY()) {
minY = element.getY();
e2 = element;
}
if (maxX < element.getX()) {
maxX = element.getX();
}
if (maxY < element.getY()) {
maxY = element.getY();
}
}
int graphWidth = maxX - minX;
int graphHeight = maxY - minY;
int w = (int) (((this.diagramScrollPane.getWidth()/2)-(graphWidth/2))/this.getDiagramPanel().getScaleRatio()[0]);
int h = (int) (((this.diagramScrollPane.getHeight()/2)-(graphHeight/2))/this.getDiagramPanel().getScaleRatio()[1]);
int newX = (int) ((minX-w-50/this.getDiagramPanel().getScaleRatio()[0])*this.getDiagramPanel().getScaleRatio()[0]);
int newY = (int) ((minY-h-50/this.getDiagramPanel().getScaleRatio()[0])*this.getDiagramPanel().getScaleRatio()[1]);
this.diagramScrollPane.getViewport().setViewPosition(new java.awt.Point(newX,newY));
repaint();
} |
30c9a66f-dde7-48b0-8ec6-944edbeacdac | 5 | private void getNextPosition() {
// movement
if (left) {
dx -= moveSpeed;
if (dx < -maxSpeed) {
dx = -maxSpeed;
}
} else if (right) {
dx += moveSpeed;
if (dx > maxSpeed) {
dx = maxSpeed;
}
}
// falling
if (falling) {
dy += fallSpeed;
}
} |
86940cd1-abc2-4039-89ba-2624956c431a | 4 | private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
} else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
} |
de892be7-dec0-410a-8cd3-b2ed71b47417 | 2 | public static ArrayList<Kill> compaireEntityLoss(ArrayList<Kill> Kills,
String name) {
ArrayList<Kill> output = new ArrayList<Kill>();
for (Kill k : Kills) {
if (k.getVictim().findAttribute(name)) {
output.add(k);
}
}
return output;
} |
fe7cc4c2-e217-4d75-a1ef-eb4d4651a55a | 6 | void permute(int size) {
int M = size;
int poped = 0;
Stack<Integer> s = new Stack<Integer>();
s.push(0);
while (!s.empty()) {
int top = s.peek();
int i = 0;
for (i = 1; i <= M; ++i) {
if (find(top, i))
continue;
int no = top * 10 + i;
if (no > poped) {
s.push(no);
if(no > Math.pow(10, M-1)){
}
break;
}
}
if (i == M + 1) {
poped = s.pop();
}
}
} |
3e76e9f7-1bdc-4aac-85c5-d7c8aebfae81 | 9 | private void handleLineFragmentInDefaultState(String line) throws IOException {
// System.out.println("Handling line fragment: state=" + parsingState
// + ", vbLevel=" + verbatimMode
// + ", iLevel=" + indentLevel
// + ", line=" + line
// );
/* If not in verbatim, we'll indent the line as appropriate. This will be the
* current indent, unless it starts with an '\end' in which case we'll unindent
* immediately.
*/
boolean initialUnindent = false;
if (!verbatimMode) {
if (line.startsWith(END)) {
initialUnindent = true;
indentLevel--;
}
createIndent(indentLevel);
}
/* Now output line */
outputWriter.write(line);
outputWriter.write(LINE_SEPARATOR);
/* We now adjust the indentLevel and verbatimLevel.
*
* First find all of the \end{...}'s.
*/
Matcher matcher = END_PATTERN.matcher(line);
while (matcher.find()) {
if (!verbatimMode) {
indentLevel--;
}
else {
if (matcher.group(1).equals("verbatim")) {
/* (Leaving verbatim should apply to next line) */
verbatimMode = false;
}
}
}
/* Account for any initial unindent we found earlier */
if (initialUnindent) {
indentLevel++;
}
/* Then find all of the \begin{...}s */
matcher = BEGIN_PATTERN.matcher(line);
while (matcher.find()) {
if (!verbatimMode) {
if (matcher.group(1).equals("verbatim")) {
verbatimMode = true;
}
else {
indentLevel++;
}
}
}
} |
cb0ebcca-72b0-414b-bed0-191b9c544c61 | 3 | private void btnEditarClienteSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarClienteSalvarActionPerformed
try {
if (JOptionPane.showConfirmDialog(rootPane, "Deseja Salvar?") == 0) {
carregaObjeto();
if (dao.Salvar(cliente,0)) {
JOptionPane.showMessageDialog(rootPane, "Salvo com sucesso!");
//Chamar NOVAMENTE a janela de listagem de Produtos
frmClienteListar janela = new frmClienteListar();
this.getParent().add(janela);
janela.setVisible(true);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(rootPane, "Falha ao salvar! Consulte o administrador do sistema!");
}
} else {
JOptionPane.showMessageDialog(rootPane, "Operação cancelada!");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(rootPane, "Erro ao salvar! Consulte o administrador do sistema!");
}
}//GEN-LAST:event_btnEditarClienteSalvarActionPerformed |
f605345e-0ee5-47ff-bfa5-cc7c951ba981 | 4 | @Override
public E get(E e) {
if(contains(e)){
setIn = new Node(e);
current = root;
while(current!=null){
if(setIn.object.compareTo(current.object)<0){
current = current.right;
}else if(setIn.object.compareTo(current.object)>0){
current = current.left;
}else{
return current.object;
}
}
}
return null;
} |
7e2e7fc0-a288-4880-9c2e-b1434c20665c | 5 | public void getAllRecursion() throws MalformedURLException{
List<String> thisList = new ArrayList<>();
for(String l: links){
thisList.add(l);
}
links.clear();
for(String l: thisList){
URL url = new URL(l);
if(finishedLinks.indexOf(l) == -1 && verifyLink(url)){
finishedLinks.add(l);
String webPage = readHTML(url);
searchAllForGame(webPage);
searchLinkAndAddToList(webPage, "site");
}
System.out.println(count++);
}
if(count < 20){
getAllRecursion();
}
} |
db807988-7a8a-44a0-84b1-06aa6940c6c3 | 4 | public boolean move(List<Color> source, List<Color> dest) {
if (dest.size() == 0 || dest.contains(source.get(0))) {
// regular move
dest.add(source.remove(source.size() - 1));
return true;
} else if (dest.size() == 1 && !dest.contains(source.get(0))) {
// blot
// move opponent's piece to rail
this.move(dest, this.rails.get(dest.get(0)));
// move our piece to now-empty point
this.move(source, dest);
return true;
} else {
// illegal move?, do nothing
return false;
}
} |
9f642c97-2922-409b-8e01-8d42feb954ac | 8 | public final void addConnection(AbstractSelectableChannelConnection conn, Set<String> allowedEvents) throws ConnectionException {
if (conn.isClosed()) {
return;
}
final SelectableChannel channel = conn.getChannel();
try {
synchronized (guard) {
sel.wakeup();
int interestsOps = 0;
for (String eventName : allowedEvents) {
if (Event.EVENT_READ.equals(eventName)) {
interestsOps |= SelectionKey.OP_READ;
} else
if (Event.EVENT_WRITE.equals(eventName)) {
interestsOps |= SelectionKey.OP_WRITE;
} else {
LOGGER.error("unknown event name '" + eventName + "'");
throw new ConnectionException("Unknown event name '" + eventName + "'");
}
}
if (!channel.isRegistered()) {
channel.register(sel, interestsOps, conn);
} else {
try {
final SelectionKey key = channel.keyFor(sel);
if (key != null) {
key.interestOps(interestsOps);
} else {
sel.selectNow();
channel.register(sel, interestsOps, conn);
}
} catch (CancelledKeyException e) {
sel.selectNow();
channel.register(sel, interestsOps, conn);
}
}
}
} catch (Exception e) {
throw new ConnectionException("cannot add asynchronous context to dispatcher", e);
}
} |
c59dc60d-4d32-4705-b923-3857f05b8810 | 2 | public static <T extends DC> Similarity getPhiSim(Set<Pair<T,T>> done)
{ if(done!=null)
{ if(done.next!=null)
{ return new Similarity(done.a.fst().delta(done.a.snd()).simi().getValue()+(getPhiSim(done.next).getValue()));
}
else
{ return new Similarity(done.a.fst().delta(done.a.snd()).simi().getValue());
}
}
else
{ return new Similarity(0.0);}
} |
33612901-3a5c-4e92-94d3-cb28b90ddafc | 2 | @Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) {
try
{
if (e.getMessage() instanceof String)
{
Channels.write(ctx, e.getFuture(), ChannelBuffers.copiedBuffer(
(String) e.getMessage(), Charset.forName("UTF-8")));
}
else
{
EventResponse Message = (EventResponse) e.getMessage();
Channels.write(ctx, e.getFuture(), Message.Get());
}
}
catch (Exception ex)
{
}
} |
6ed1ed34-cd55-4c43-8cf3-ceb56f40cbf5 | 1 | @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (Exception ex) {
Logger.getLogger(ControlJsp.class.getName()).log(Level.SEVERE, null, ex);
}
} |
f41022f1-6669-443a-abe5-0038d904cc00 | 1 | public void reportFail(String service) throws RemoteException
{
//Splits service to get the server ID
String tmp[] = service.split("Acesso");
//Parse server ID to int
Integer pos = new Integer(Integer.parseInt(tmp[1]));
try
{
System.out.println("Client " + RemoteServer.getClientHost() + " reported down of service " +
service + " removing it from servers list");
}
catch (ServerNotActiveException e)
{
System.err.println("Controller.reportFail catched ServerNotActiveException");
e.printStackTrace();
}
//Remove the inactive server from servers list
// servers.remove(pos);
removeDeadServer(pos);
} |
da51f569-0391-41a5-8273-b9fd9ac80bc5 | 5 | @Override
public void report(final SortedMap<String, Gauge> gauges, final SortedMap<String, Counter> counters, final SortedMap<String, Histogram> histograms,
final SortedMap<String, Meter> meters, final SortedMap<String, Timer> timers) {
final long timestampClock = clock.getTime();
final Date timestamp = new Date(timestampClock);
for (final Map.Entry<String, Gauge> entry : gauges.entrySet()) {
reportGauge(entry.getKey(), entry.getValue(), timestamp);
}
for (final Map.Entry<String, Counter> entry : counters.entrySet()) {
reportCounter(entry.getKey(), entry.getValue(), timestamp);
}
for (final Map.Entry<String, Histogram> entry : histograms.entrySet()) {
reportHistogram(entry.getKey(), entry.getValue(), timestamp);
}
for (final Map.Entry<String, Meter> entry : meters.entrySet()) {
reportMetered(entry.getKey(), entry.getValue(), timestamp);
}
for (final Map.Entry<String, Timer> entry : timers.entrySet()) {
reportTimer(entry.getKey(), entry.getValue(), timestamp);
}
} |
c17319e0-e09a-4efb-b8fb-dce8a275935c | 1 | private void playAudio() {
try {
// Get everything set up for
// playback.
// Get the previously-saved data
// into a byte array object.
byte audioData[] = byteArrayOutputStream.toByteArray();
// Get an input stream on the
// byte array containing the data
InputStream byteArrayInputStream = new ByteArrayInputStream(
audioData);
AudioFormat audioFormat = getAudioFormat();
audioInputStream = new AudioInputStream(byteArrayInputStream,
audioFormat, audioData.length / audioFormat.getFrameSize());
DataLine.Info dataLineInfo = new DataLine.Info(
SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
// Create a thread to play back
// the data and start it
// running. It will run until
// all the data has been played
// back.
Thread playThread = new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}// end catch
}// end playAudio |
3554fa4a-c937-4285-8917-3ce3832484fc | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PeriodBrand other = (PeriodBrand) obj;
if (manufacture == null) {
if (other.manufacture != null)
return false;
} else if (!manufacture.equals(other.manufacture))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} |
1249ffdc-0e3c-432c-b357-703eeef8bad5 | 5 | public void startConnection() {
String host = plugin.getConfig().getString("hostname", "localhost");
String port = plugin.getConfig().getString("port", "3306");
String username = plugin.getConfig().getString("username", "root");
String password = plugin.getConfig().getString("password", "");
String db = plugin.getConfig().getString("database", "bans");
Connection connection = null;
try {
// load the database driver (make sure this is in your classpath!)
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
try {
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + db);
config.setUsername(username);
config.setPassword(password);
config.setMinConnectionsPerPartition(5);
config.setMaxConnectionsPerPartition(10);
config.setPartitionCount(1);
connectionPool = new BoneCP(config);
connection = connectionPool.getConnection();
if (connection != null) {
Statement statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS `backpacks` (\n" +
" `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
" `server` varchar(100) NOT NULL,\n" +
" `playerUUID` varchar(40) NOT NULL,\n" +
" PRIMARY KEY (`id`)\n" +
") ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} |
14e0ff8b-7909-4717-95f5-2af1c13667c5 | 2 | @Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Producer interrupted");
return;
}
buffer.put(i++);
}
} |
668116ab-f78a-45d3-ac37-7c8aac12034c | 3 | public void run()
{
init();
//For keeping track of nanoTime
long start;
long elapsed;
long wait;
while(running)
{
//The start time of the function call
start = System.nanoTime();
//update variables, create and draw images
update();
draw();
drawToScreen();
//set the amount of time the function took
elapsed = System.nanoTime()-start;
//pauses the thread to maintain 60 fps
wait = targetTime-elapsed/1000000;
if (wait < 0) wait = 5;
try
{
Thread.sleep(wait);
}
catch(Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
} |
e3c0ac8f-72d8-49c5-974c-ae955b6558a6 | 3 | public long update(HTSMsg msg) {
HTSMsg chann = channels.get(((Number)msg.get(CHANNELID)).longValue());
for (String name : msg.keySet()){
if (Arrays.asList(HTSMsgFields).contains(name)){
chann.put(name, msg.get(name));
}
else if (name.equals("method")){
//This is normal, do nothing...
}
else{
System.out.println("N.B. Unrecognized field: " + name);
}
}
return ((Number) msg.get(CHANNELID)).longValue();
} |
dfdfbc10-233e-448e-9036-47d011ae84cf | 8 | public static void main(String[] args) throws Exception {
CommandLine cmd = null;
String host = ClientApp.DEFAULT_HOST;
int port = ClientApp.DEFAULT_PORT;
cmd = ClientApp.parseArgs( args );
if( cmd != null ) {
if ( cmd.hasOption("host") ) {
host = cmd.getOptionValue("host");
}
if ( cmd.hasOption("port") ) {
port = Integer.parseInt( cmd.getOptionValue("port") );
}
boolean connected = ClientApp.connectToServer( host, port );
if( !connected ) {
System.out.println("Error connecting to RMI. Please see stack trace");
} else {
Scanner in = new Scanner( System.in );
IView view = new ConsoleView( in , System.out );
if ( cmd.hasOption("gui") ) {
view = new GraphicView();
}
Client client = new Client( ClientApp.server, view );
boolean exported = ClientApp.exportClient( client );
if( !exported ) {
System.out.println("Error exporting client to RMI. Please see stack trace");
} else {
client.connect();
if ( cmd.hasOption("gui") ) {
((GraphicView)view).setVisible(true);
}
//TODO: remove this
while( !client.isGameFinished() ) {
Thread.sleep( 2000 );
}
}
}
}
} |
add449e6-b255-48af-b8e0-e9f1cb36b009 | 4 | private boolean checkOutofBounds(Direction dir, int row, int col) {
if(dir == Direction.LEFT){
return col <0;
}
else if (dir == Direction.RIGHT){
return col> COLS - 1;
}
else if(dir == Direction.UP){
return row <0;
}
else if(dir == Direction.DOWN){
return row > ROWS - 1;
}
return false;
} |
742bd10b-e644-4072-9ba5-0e0ae2be8035 | 1 | private void checkfs() {
if (fsm != null) {
fsm.check();
}
} |
101f4258-5cc3-40f6-a325-db63080b35ac | 4 | private Face connectHalfEdges (
HalfEdge hedgePrev, HalfEdge hedge)
{
Face discardedFace = null;
if (hedgePrev.oppositeFace() == hedge.oppositeFace())
{ // then there is a redundant edge that we can get rid off
Face oppFace = hedge.oppositeFace();
HalfEdge hedgeOpp;
if (hedgePrev == he0)
{ he0 = hedge;
}
if (oppFace.numVertices() == 3)
{ // then we can get rid of the opposite face altogether
hedgeOpp = hedge.getOpposite().prev.getOpposite();
oppFace.mark = DELETED;
discardedFace = oppFace;
}
else
{ hedgeOpp = hedge.getOpposite().next;
if (oppFace.he0 == hedgeOpp.prev)
{ oppFace.he0 = hedgeOpp;
}
hedgeOpp.prev = hedgeOpp.prev.prev;
hedgeOpp.prev.next = hedgeOpp;
}
hedge.prev = hedgePrev.prev;
hedge.prev.next = hedge;
hedge.opposite = hedgeOpp;
hedgeOpp.opposite = hedge;
// oppFace was modified, so need to recompute
oppFace.computeNormalAndCentroid();
}
else
{ hedgePrev.next = hedge;
hedge.prev = hedgePrev;
}
return discardedFace;
} |
f6a80fa3-d741-4adb-a294-da9e055af3b5 | 8 | private void processPhil() {
ArrayList<String> line = new ArrayList<String>();
int indent = _firstLine ? _indent + _parindent : _indent;
for (String word : _wordLine) {
if (word == null || word.matches("\\s")
|| word.matches("\\n")) {
continue;
}
int nonBlankChars = charsIn(line);
if (word.length() > _textWidth) {
if (line.size() > 0) {
emitLine(line, indent);
indent = _indent;
line.clear();
}
line.add(word);
emitLine(line, indent);
indent = _indent;
line.clear();
continue;
}
if (nonBlankChars + word.length() + line.size() + indent
> _textWidth) {
emitLine(line, indent);
line.clear();
indent = _indent;
}
line.add(word);
}
boolean temp = _justify;
_justify = false;
emitLine(line, indent);
_justify = temp;
} |
9122eba4-8e6a-456d-94ae-f1bebfb4bcf7 | 6 | public void gen_for_controller(SemanticRec controllerRec, SemanticRec forDirection) {
boolean increment = false;
//determine whether or not to increment or decrement
switch (forDirection.getRecType()) {
case FOR_DIRECTION:
if (forDirection.getDatum(0).equalsIgnoreCase(TokenType.MP_TO.toString())) {
increment = true;
} else if (forDirection.getDatum(0).equalsIgnoreCase(TokenType.MP_DOWNTO.toString())) {
increment = false;
} else {
Parser.semanticError("Invalid FOR_DIRECTION: " + forDirection.getDatum(0));
}
break;
default:
Parser.semanticError("Cannot use non FOR_DIRECTION record type: " + forDirection.getRecType());
break;
}
switch (controllerRec.getRecType()) {
case IDENTIFIER:
if (controllerRec.getDatum(0).equalsIgnoreCase(Classification.VARIABLE.toString())) {
DataRow var = (DataRow) findSymbol(controllerRec.getDatum(1));
String memLoc = generateOffset(findSymbolTable(var), var);
if (increment) {
push(memLoc);
push("#1");
addStackI();
pop(memLoc);
} else {
push(memLoc);
push("#1");
subStackI();
pop(memLoc);
}
} else {
Parser.semanticError("Cannot use non-variable as control variable");
}
break;
default:
Parser.semanticError("Cannot use non-identifier for control variable");
break;
}
} |
7046b6cd-382b-4615-a0f5-73fa13c75dba | 9 | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if(cmd.getName().equalsIgnoreCase("delowner")){
if(args.length != 2){
sender.sendMessage("/delowner <ChannelName> <PlayerName>");
return true;
}
String ChanName = args[0].toLowerCase();
String PlayerName = player.getName().toLowerCase();
List<String> ChowList = plugin.getStorageConfig().getStringList(ChanName+".owner");
if (player == null || ChowList.contains(PlayerName) && player.hasPermission("scc.admin")) {
String AddPlayName = plugin.myGetPlayerName(args[1]);
Player target = plugin.getServer().getPlayer(args[1]);
boolean ChanTemp = plugin.getStorageConfig().contains(ChanName);
if(ChanTemp == false) {
plugin.NotExist(sender, ChanName);
return true;
} else {
if (!ChowList.contains(PlayerName)) {
sender.sendMessage(plugin.DARK_RED+"[SCC] "+plugin.GOLD + AddPlayName + plugin.DARK_RED + " does not have owner access to " + plugin.GOLD + ChanName);
return true;
} else {
ChowList.remove(PlayerName); // remove the player from the list
plugin.getStorageConfig().set(ChanName+".owner", ChowList); // set the new list
sender.sendMessage(plugin.DARK_GREEN+"[SCC] "+plugin.GOLD+ AddPlayName + plugin.DARK_GREEN + " removed From " + plugin.RED + ChanName + "'s" + plugin.DARK_GREEN + " owner list");
if (target != null) {
target.sendMessage(plugin.DARK_GREEN+"[SCC] "+"You have been removed from " + plugin.GOLD + ChanName + "'s" + plugin.DARK_GREEN + " owner list");
}
plugin.saveStorageConfig();
return true;
}
}
} else {
plugin.NotOwner(sender, ChanName);
return true;
}
}
return true;
} |
0c8735fa-b962-4f7a-a5dc-f7ade44e3766 | 2 | public static void main(String[] args) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
String name = "Compute";
try {
Registry registry = LocateRegistry.getRegistry(args[0]);
Compute comp = (Compute) registry.lookup(name);
Pi task = new Pi(Integer.parseInt(args[1]));
BigDecimal pi = comp.executeTask(task);
System.out.println(pi);
} catch (Exception e) {
e.printStackTrace();
}
} |
3795c60e-d995-418a-8935-8f1528873cc5 | 4 | public String Listen(String valide, String stop, int time){
TextToSpeech tts = new TextToSpeech();
Microphone mic = new Microphone(AudioFileFormat.Type.WAVE);
while (true)
{
try{
Thread.sleep(2000);
tts.playSynth("Please, Speak now...");
Thread.sleep(50);
mic.open();
mic.captureAudioToFile(filename);
System.out.println("Listening...");
Thread.sleep(time);
mic.close();
new Thread(new RecognizeThread()).start();
Thread.sleep(5000);
if (valide.contains(data))
{
tts.playSynth("The word accepted: " + data);
return data;
}
else if (stop.contains(data))
{
tts.playSynth("recognition stopped!!");
System.out.println("Exiting...");
break;
}
else {
tts.playSynth("Didn't get that.");
}
}
catch(Exception e){
e.printStackTrace();
}
}
return "wrong";
} |
b85bfceb-d72d-4531-87f7-2d7873f716c1 | 5 | public Hash get(long hash) throws IOException {
processQueue();
Reference<Hash> ref = map.get(hash);
Hash h = null;
if (ref != null) {
h = ref.get();
}
if (h != null) {
return h;
}
Hash[] hashes = fileStore.readHash(hash);
if (hashes == null) {
System.out.println("Readback failed, map contains " + map.containsKey(hash));
System.out.println("Readback failed, fileStore contains " + fileStore.hasKey(hash));
}
for (Hash hh : hashes) {
if (hh.getHash() == hash) {
h = hh;
}
add(hh);
}
return h;
} |
dfee53b9-5c97-42f7-81c1-f327a9d7532b | 7 | @EventHandler
public void WitherRegeneration(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Wither.Regeneration.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (damager instanceof WitherSkull) {
WitherSkull a = (WitherSkull) event.getDamager();
LivingEntity shooter = a.getShooter();
if (plugin.getWitherConfig().getBoolean("Wither.Regeneration.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, plugin.getWitherConfig().getInt("Wither.Regeneration.Time"), plugin.getWitherConfig().getInt("Wither.Regeneration.Power")));
}
}
} |
3fd53868-d850-4a31-b79d-dd8ffdb0c2d3 | 5 | public static void main(String[] args) {
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
List<Future<Integer>> results = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Future<Integer> submit =
newCachedThreadPool.submit(new MyCallable(5 + i));
results.add(submit);
}
for (Iterator<Future<Integer>> iterator = results.iterator(); iterator
.hasNext();) {
try {
Future<Integer> future = iterator.next();
Integer result = future.get(1, TimeUnit.SECONDS);
System.out.format("\nThe result of %s is %s\n", future, result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
} |
411a4452-8299-4672-a2c2-58798fcbffbc | 5 | public void sendResult(ParisModel paris) {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
String htmlBody = "<div style='background-color:#000000; color:#FFFFFF; padding:10px; font-size:16px;'>";
htmlBody += "<h1 style='text-align:center; color:#FF6600;'>Bonjour "+paris.getParis_user().getUser_pseudo()+"<br/>Heracles-Sport vous informe que votre paris est terminé</h1>";
if(paris.getResult()>0) {
htmlBody += "<h2 style='text-align:center; color:#33FF33;'>Paris gagné (+"+paris.getResult()+")</h2>";
}
else {
htmlBody += "<h2 style='text-align:center; color:#FF3333;'>Paris perdu. ("+paris.getResult()+")</h2>";
}
htmlBody += "<p>";
htmlBody += "<b>Sport:</b> <span style='color:#FF6600;'>"+paris.getParis_sched().getSched_sportName()+"</span><br/>";
htmlBody += "<b>Date: </b> <span style='color:#FF6600;'>"+paris.getParis_sched().getSched_dateClean()+"</span><br/>";
if(paris.getParis_sched() instanceof ScheduleTeamModel) {
htmlBody += "<b>Equipe Domicile: </b> <span style='color:#FF6600;'>"+((ScheduleTeamModel)paris.getParis_sched()).getSched_home_team().getTeam_name()+"</span><br/>";
htmlBody += "<b>Equipe Extérieur: </b> <span style='color:#FF6600;'>"+((ScheduleTeamModel)paris.getParis_sched()).getSched_away_team().getTeam_name()+"</span><br/>";
}
htmlBody += "</p>";
htmlBody += "<p><br/><center><a style='font-size:16px;font-weight:bold;color:#FF6600;' href='http://heracles-sport.appspot.com/histo'>Pour plus de détails sur vos paris terminés, cliquez ici.</a></center><br/></p>";
htmlBody += "</div>";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("clement.bar@gmail.com", "heracles-sport.appspot.com Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(paris.getParis_user().getUser_mail(), paris.getParis_user().getUser_name()));
msg.setSubject("[Heracles-Sport] - Resultats paris");
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlBody, "text/html; charset=utf-8");
mp.addBodyPart(htmlPart);
msg.setContent(mp);
Transport.send(msg);
} catch (AddressException e) {
// ...
} catch (MessagingException e) {
// ...
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
a718fd88-75a5-4747-a130-536914ba1ff4 | 9 | @Override
public void izvrsiAnalizu() {
// konstante u skladu sa formulama
int n = stepenMultiprogramiranja;
int k = brojKorisnickihDiskova + BROJ_SISTEMSKIH_DISKOVA + 1;
// izračunato Gordon-Njuelovom metodom i hardkodovano za ovaj konkretan zadatak
double[] x = { 1, 0.36, 0.45, 3.4 / brojKorisnickihDiskova };
double[] s = { 5, 12, 15, 20 };
// programska realizacija Bjuzenovog algoritma, optimizovana
double[] G = new double[n+1];
G[0] = 1;
// programska realizacija Bjuzenovog algoritma, optimizovana
for (int j = 0; j < k; j++) {
for (int i = 1; i <= n; i++) {
G[i] = G[i] + x[j<3?j:3] * G[i-1];
}
}
// iskorišćenje
double[] U = new double[4];
U[0] = G[n-1] / G[n];
for (int i=0; i<4; i++) U[i] = U[0] * x[i];
// protok
double[] X = new double[4];
for (int i=0; i<4; i++) X[i] = U[i] / s[i];
// prosečan broj poslova
double[] J = new double[4];
for (int i = 0; i < 4; i++)
for (int m = 1; m <= n; m++)
J[i] += (G[n-m] / G[n]) * Math.pow(x[i], m);
// vreme odaziva (relevantno samo za procesor)
//double R = J[0] / X[0];
double R = n / X[0];
/*
* Kada je sve izračunato, podaci se ubacuju u "dummy" komponente,
* da bi ih LogFajl klasa lakše pročitala
*/
// procesor
procesor.setDummy(true);
procesor.setDummyStatIskoriscenje(U[0]);
procesor.setDummyStatProtok(X[0]);
procesor.setDummyStatProsecanBrojPoslova(J[0]);
procesor.setDummyStatVremeOdaziva(R);
// sistemski diskovi
int i = 1;
for (Komponenta sDisk : sDiskArray) {
sDisk.setDummy(true);
sDisk.setDummyStatIskoriscenje(U[i]);
sDisk.setDummyStatProtok(X[i]);
sDisk.setDummyStatProsecanBrojPoslova(J[i]);
i++;
}
// korisnički diskovi
for (Komponenta kDisk : kDiskArray) {
kDisk.setDummy(true);
kDisk.setDummyStatIskoriscenje(U[3]);
kDisk.setDummyStatProtok(X[3]);
kDisk.setDummyStatProsecanBrojPoslova(J[3]);
}
} |
4a4ec7f2-1815-4a6c-855e-5c7d29d57bef | 7 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final PackageCoverageStatisticsKey other = (PackageCoverageStatisticsKey) obj;
if (keyName == null) {
if (other.keyName != null)
return false;
} else if (!keyName.equals(other.keyName))
return false;
if (numProcedures != other.numProcedures)
return false;
return true;
} |
70d7c0bd-39b0-4f5f-9f88-670fc9b30353 | 9 | static final public void FormParList() throws ParseException {
Token token;
Symbol sy;
formPar();
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COLON:
case VOID:
case INT:
case BOOL:
case BYREF:
;
break;
default:
jj_la1[7] = jj_gen;
break label_2;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case COLON:
jj_consume_token(COLON);
break;
default:
jj_la1[8] = jj_gen;
;
}
formPar();
}
} |
e4197919-c5d0-45cb-b932-6c489bad9c3e | 5 | public boolean laggTillAnvandareFranSkolDB(String anvandarnamnIn, String losenordIn){
ArrayList<String> dataFranPersondatabas = new ArrayList<String>();
try{
// H�mtar data om personen fr�n persondatabasen.
connection2 = getConnection2();
preparedStatement = connection2.prepareStatement("SELECT * FROM person WHERE Användarnamn = ? AND Lösenord = ?");
preparedStatement.setString(1, anvandarnamnIn);
preparedStatement.setString(2, losenordIn);
resultSet = preparedStatement.executeQuery();
if(!resultSet.next()){
return false;
}
// Sparar resultatet i en lista
dataFranPersondatabas.add(resultSet.getString(1));
dataFranPersondatabas.add(resultSet.getString(2));
dataFranPersondatabas.add(resultSet.getString(3));
dataFranPersondatabas.add(resultSet.getString(4));
dataFranPersondatabas.add(resultSet.getString(5));
dataFranPersondatabas.add(resultSet.getString(6));
dataFranPersondatabas.add(resultSet.getString(7));
dataFranPersondatabas.add(resultSet.getString(8));
dataFranPersondatabas.add(resultSet.getString(9));
dataFranPersondatabas.add(resultSet.getString(10));
// Sparar datan fr�n listan i str�ngar
String personnummer = dataFranPersondatabas.get(0);
String anvandarnamn = dataFranPersondatabas.get(1);
String losenord = dataFranPersondatabas.get(2);
String fornamn = dataFranPersondatabas.get(3);
String efternamn = dataFranPersondatabas.get(4);
String gatuadress = dataFranPersondatabas.get(5);
String stad = dataFranPersondatabas.get(6);
String postnummer = dataFranPersondatabas.get(7);
String telefon = dataFranPersondatabas.get(8);
String epost = dataFranPersondatabas.get(9);
// L�gger in datan i bibliotek informatikas databas
connection = getConnection();
preparedStatement = connection.prepareStatement("INSERT INTO person (Personnummer, Användarnamn, Lösenord, Förnamn, Efternamn, Gatuadress, Stad, Postnummer, Telefon, Epost) VALUES (?,?,?,?,?,?,?,?,?,?)");
preparedStatement.setString(1, personnummer);
preparedStatement.setString(2, anvandarnamn);
preparedStatement.setString(3, losenord);
preparedStatement.setString(4, fornamn);
preparedStatement.setString(5, efternamn);
preparedStatement.setString(6, gatuadress);
preparedStatement.setString(7, stad);
preparedStatement.setString(8, postnummer);
preparedStatement.setString(9, telefon);
preparedStatement.setString(10, epost);
int forandring = preparedStatement.executeUpdate();
// Om operationen lyckades s� returnerar vi sant
if(forandring > 0){
return true;
}
return false;
}
catch(SQLException se){
System.out.println(se.getMessage());
// Om operationen inte lyckades returnerar vi falskt
return false;
}
finally {
if (connection2 != null)
try {connection2.close();} catch (SQLException e) {}
}
} |
c2a117c7-0a16-42bd-b99f-3f25c145fd18 | 4 | public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (semiMajorAxis < 0) {
throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
}
if (semiMinorAxis < 0) {
throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
}
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2 * semiMajorAxis);
double hs = factorY(2 * semiMinorAxis);
if (ws <= 1 && hs <= 1) {
pixel(x, y);
} else {
offscreen.draw(new Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs));
}
draw();
} |
b12a7639-1fbe-4593-b9ac-83f6f9f94ccb | 2 | public void paint1(Graphics g) {
g.setColor(Color.YELLOW);
g.setFont(new Font("default", Font.BOLD, 20));
g.drawImage(principal.getImagenI(), principal.getPosX(), principal.getPosY(),this);
g.drawImage(obs1.getImagenI(),obs1.getPosX(), obs1.getPosY(),this);
for(int i = 0; i < listaAbajo.size(); i++){
g.drawImage(listaAbajo.get(i).getImagenI(), listaAbajo.get(i).getPosX(),listaAbajo.get(i).getPosY(), this);
}
for(int i = 0; i < listaArriba.size(); i++){
g.drawImage(listaArriba.get(i).getImagenI(), listaArriba.get(i).getPosX(),listaArriba.get(i).getPosY(), this);
}
} |
315f7b58-b0cd-4637-9753-70582c69ca71 | 3 | protected Rectangle getObjectRectangle()
{
boolean found = false;
Rectangle r = new Rectangle(0, 0, 0, 0);
for (LevelItem i : objs)
{
if(!(i instanceof NSMBObject))
continue;
NSMBObject o = (NSMBObject) i;
if (found)
Rectangle.union(r, o.getBlockRect(), r);
else
r = o.getBlockRect();
found = true;
}
return r;
} |
1a94a849-d414-4bed-a55c-ba252b3f7c5c | 2 | protected void writeError(String toWrite, boolean severe) {
if (toWrite != null) {
if (severe) {
this.log.severe(this.PREFIX + this.DATABASE_PREFIX + toWrite);
} else {
this.log.warning(this.PREFIX + this.DATABASE_PREFIX + toWrite);
}
}
} |
61bcd31f-8d34-4ddb-a0d6-8e475f9a6409 | 5 | @Override
public String getRandomQuestion() {
if (size() > 0) {
randomWord();
int randomIndex;
String randomWordText;
int index;
String randomWordTextFirst = "";
if (randomWordArray == 0) {
randomIndex = random.nextInt(wordArray1.size()); //NextInt er bestemt af size(), som er størrelsen på ArrayList.
Word randomWord = wordArray1.get(randomIndex);
randomWordText = randomWord.toString(); //Lægger Word objektet ned i en string med toString i Word klassen.
index = randomWordText.indexOf(",");
randomWordTextFirst = randomWordText.substring(0, index); //Laver en ny string, kun med ordet som ligger før kommaet i stringen hentet fra tekstfilen.
}
if (randomWordArray > 0 && randomWordArray < 3) {
randomIndex = random.nextInt(wordArray2.size()); //NextInt er bestemt af size(), som er størrelsen på ArrayList.
Word randomWord = wordArray2.get(randomIndex);
randomWordText = randomWord.toString(); //Lægger Word objektet ned i en string med toString i Word klassen.
index = randomWordText.indexOf(",");
randomWordTextFirst = randomWordText.substring(0, index); //Laver en ny string, kun med ordet som ligger før kommaet i stringen hentet fra tekstfilen.
}
if (randomWordArray > 2) {
randomIndex = random.nextInt(wordArray3.size()); //NextInt er bestemt af size(), som er størrelsen på ArrayList.
Word randomWord = wordArray3.get(randomIndex);
randomWordText = randomWord.toString(); //Lægger Word objektet ned i en string med toString i Word klassen.
index = randomWordText.indexOf(",");
randomWordTextFirst = randomWordText.substring(0, index); //Laver en ny string, kun med ordet som ligger før kommaet i stringen hentet fra tekstfilen.
}
return randomWordTextFirst;
} else {
String error = " Error.";
return error;
}
} |
0a30ca1c-dbf8-46b3-9b6e-c2c9395fd50f | 4 | public void registerAllMasterFiles() {
DataGridResource res = (DataGridResource) Sim_system
.get_entity(super.resourceID_);
AbstractRC rc = null;
if (res.hasLocalRC()) {
rc = res.getLocalRC();
} else {
rc = (AbstractRC) Sim_system.get_entity(super.rcID_);
}
if (rc == null) {
System.out.println(super.get_name() + ".registerAllMasterFiles(): "
+ "Warning - unable to register master files to a Replica "
+ "Catalogue entity.");
return;
}
Storage tempStorage = null;
for (int i = 0; i < storageList_.size(); i++) {
tempStorage = (Storage) storageList_.get(i);
ArrayList fileList = (ArrayList) tempStorage.getFileNameList();
for (int j = 0; j < fileList.size(); j++) {
String filename = (String) fileList.get(j);
File file = tempStorage.getFile(filename); // get file
FileAttribute fAttr = file.getFileAttribute(); // get attribute
// register before simulation starts, hence no uniqueID
rc.registerOriginalFile(fAttr, super.resourceID_);
}
}
} |
f15fc07f-7cfa-47b2-9ca1-f10cf1511b2c | 5 | public static void registerClient(final MapleClient c) {
if (c.finishLogin() == 0) {
c.getSession().write(LoginPacket.getAuthSuccessRequest(c));
c.setIdleTask(TimerManager.getInstance().schedule(new Runnable() {
public void run() {
c.getSession().close();
}
}, 10 * 60 * 10000));
} else {
c.getSession().write(LoginPacket.getLoginFailed(7));
return;
}
final LoginServer LS = LoginServer.getInstance();
if (System.currentTimeMillis() - lastUpdate > 300000) { // Update once every 5 minutes
try {
// Update once every 5 minutes
lastUpdate = System.currentTimeMillis();
final Map<Integer, Integer> load = LS.getWorldInterface().getChannelLoad();
if (load == null) {
// In an unfortunate event that client logged in before load
lastUpdate = 0;
c.getSession().write(LoginPacket.getLoginFailed(7));
return;
}
final double loadFactor = 1200 / ((double) LS.getUserLimit() / load.size());
for (Entry<Integer, Integer> entry : load.entrySet()) {
load.put(entry.getKey(), Math.min(1200, (int) (entry.getValue() * loadFactor)));
}
LS.setLoad(load);
} catch (RemoteException ex) {
System.err.println("Login Worker Error : " + ex);
}
}
c.getSession().write(LoginPacket.getServerList(6, LS.getServerName(), LS.getLoad()));
c.getSession().write(LoginPacket.getEndOfServerList());
mutex.lock();
try {
IPLog.add(new Pair<Integer, String>(c.getAccID(), c.getSession().getRemoteAddress().toString()));
} finally {
mutex.unlock();
}
} |
900f09a7-8ded-479f-a457-f764d26d3fd1 | 6 | void updatePair( double[][] A, edge nearEdge, edge farEdge, node v,
node root, double dcoeff, direction d )
{
edge sib;
//the various cases refer to where the new vertex has
//been inserted, in relation to the edge nearEdge
switch( d )
{
case UP:
//this case is called when v has been inserted above
//or skew to farEdge
//do recursive calls first!
if ( null != farEdge.head.leftEdge )
updatePair( A,nearEdge,farEdge.head.leftEdge,v,root,dcoeff,
direction.UP );
if ( null != farEdge.head.rightEdge )
updatePair(A,nearEdge,farEdge.head.rightEdge,v,root,
dcoeff,direction.UP);
A[farEdge.head.index][nearEdge.head.index] =
A[nearEdge.head.index][farEdge.head.index]
= A[farEdge.head.index][nearEdge.head.index]
+ dcoeff*A[farEdge.head.index][v.index]
- dcoeff*A[farEdge.head.index][root.index];
break;
case DOWN: //called when v has been inserted below farEdge
if ( null != farEdge.tail.parentEdge )
updatePair(A,nearEdge,farEdge.tail.parentEdge,v,root,
dcoeff,direction.DOWN);
sib = farEdge.siblingEdge();
if (null != sib)
updatePair(A,nearEdge,sib,v,root,dcoeff,direction.UP);
A[farEdge.head.index][nearEdge.head.index] =
A[nearEdge.head.index][farEdge.head.index]
= A[farEdge.head.index][nearEdge.head.index]
+ dcoeff*A[v.index][farEdge.head.index]
- dcoeff*A[farEdge.head.index][root.index];
}
} |
dbd2ac62-eb7f-42f1-b097-b3a427182060 | 6 | public void csNaturalDisasters(Random random, ChangeSet cs, int probability) {
if (Utils.randomInt(logger, "check for natural disasters", random, 100) < probability) {
int size = getNumberOfSettlements();
if (size < 1) return;
// randomly select a colony to start with, then generate
// an appropriate disaster if possible, else continue with
// the next colony
int start = Utils.randomInt(logger, "select colony", random, size);
for (int index = 0; index < size; index++) {
Colony colony = getColonies().get((start + index) % size);
List<RandomChoice<Disaster>> disasters = colony.getDisasters();
if (!disasters.isEmpty()) {
Disaster disaster = RandomChoice
.getWeightedRandom(logger, "select disaster", random, disasters);
List<ModelMessage> messages = csApplyDisaster(random, cs, colony, disaster);
if (!messages.isEmpty()) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.DEFAULT,
"model.disaster.strikes", this)
.addName("%colony%", colony.getName())
.addName("%disaster%", disaster));
for (ModelMessage message : messages) {
cs.addMessage(See.only(this), message);
}
return;
}
}
}
}
} |
0025c6bf-50d9-40ca-862c-507f6b9d8331 | 1 | public void addElement(AstronomicalObject element) {
if (!elements.contains(element)) {
elements.add(element);
log.info("{} added to {} system", element.getName(), name);
} else
log.warn("{} not added to {} system. Object with same name already exists", element.getName(), name);
} |
9313fb5e-7b00-4a0d-811d-c559029bca5d | 4 | @Override
public Match findMatchById(Long id) {
checkDataSource();
if (id == null) {
throw new IllegalArgumentException("id is null");
}
try (Connection conn = dataSource.getConnection();
PreparedStatement st = conn.prepareStatement("SELECT id, hometeamid, awayteamid, date, homeowngoals, awayowngoals"
+ ", homeadvantagegoals, awayadvantagegoals, homecontumationgoals, awaycontumationgoals, hometechnicalgoals, awaytechnicalgoals, matchresult"
+ " FROM MATCHES WHERE id = ?")) {
st.setLong(1, id);
ResultSet rs = st.executeQuery();
if (rs.next()) {
Match match = resultSetToMatch(rs);
if (rs.next()) {
throw new ServiceFailureException("Internal error: More entities with the same id found "
+ "(source id: " + id + ", found " + match + " and " + resultSetToMatch(rs));
}
return match;
} else {
return null;
}
} catch (SQLException ex) {
String msg = "error when selecting match with id" + id;
Logger.getLogger(TeamMngrImpl.class.getName()).log(Level.SEVERE, msg, ex);
throw new ServiceFailureException(msg);
}
} |
f9c034ee-f903-4e9e-bd49-8434c08b98cb | 0 | public static Tags fromString(String string) {
return TO_ENUM.get(string.toUpperCase());
} |
68c2a6ed-ef86-4bcb-b6a7-0e1d9bd3352d | 2 | @Override
public void collideWith(Element e) {
if (e instanceof Player) {
final Player playerEntered = (Player) e;
if (!player.equals(playerEntered)) {
player.setPlayerStatus(PlayerStatus.LOST);
playerEntered.setPlayerStatus(PlayerStatus.WON);
getGrid().getEventManager().sendEvent(new Event(EventType.END_GAME, playerEntered));
}
}
} |
28091ead-994f-430c-b155-90c7daf9b3db | 5 | public int getMossaMinNDMax(){
int ndmin = 12;
if(desmosse!=null)
//Trovo il minimo tra i vmax
for(DescrittoreMossa dm : desmosse)
if(dm!=null && dm.getNdmaxEnemyForest()<ndmin)
ndmin = dm.getNdmaxEnemyForest();
//Restituisco il vmin se è valido
return ndmin!=12?ndmin:-1;
} |
7462a2eb-359d-4694-bd8c-d3c21e412442 | 1 | @Override
public void render(Art art, Level level)
{
frame++;
frame %= 14;
if (invTimer % 10 == 0)
{
art.drawTile(art.spriteSheet, getX(), getY(), 6 + frame / 2, 8);
art.drawTile(art.spriteSheet, getX(), getY() + 8, 6 + frame / 2 + 32, 8);
}
} |
4a4a82c5-7a0b-495a-9b88-1e2f2e5d0fec | 9 | public boolean isMatched(String s) {
if (s == null) return false;
switch (this) {
case NONE: return s.isEmpty();
case STR: return !s.isEmpty();
case INT: return s.matches("\\d+");
case PRI: return s.matches(Priorite.REGEX);
case DAT: return Date.isMatched(s);
case HRE: return Heure.isMatched(s);
case REC: return Recurrence.isMatched(s);
case DEL: return s.matches(Suppression.REGEX);
}
return false;
} |
fe4b173a-7611-41db-b5f8-dc636d5d6681 | 4 | @Override
public boolean hasNext() {
// TODO Auto-generated method stub
boolean currentRowHasTokens = this.rowTokens > 0;
boolean hasNext = false;
assert(!(currentRow > maxRowNumber));
if(currentRowHasTokens){
hasNext = true;
}else{
if(currentRow < maxRowNumber){
int checkedRow = 0;
int checkedTokens;
boolean checkInProgress = true;
while(checkInProgress){
checkedRow = currentRow + 1;
checkedTokens = iteratedState.checkRow(checkedRow + 1);
boolean checkedBoolean = (checkedTokens > 0);
if(!checkedBoolean){
checkedBoolean = checkedRow == maxRowNumber;
}
checkInProgress = checkedBoolean;
}
}
}
return hasNext;
} |
6b6b5d3f-a1f3-4643-bb4e-fa345d283bb4 | 5 | @Override
public void buttonStateCheck(Input input) {
int mX = input.getMouseX();
int mY = input.getMouseY();
int farX = getX() + getStoredImage().getImage().getWidth();
int farY = getY() + getStoredImage().getImage().getHeight();
if (pointContains(getX(), mX, farX) && pointContains(getY(), mY, farY)) {
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)) {
setState(STATE_PRESSED);
setClicked(true);
} else {
setState(STATE_HOVER);
}
} else if (!(input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON)
&& getState() == STATE_PRESSED)) {
setState(STATE_IDLE);
setClicked(false);
}
} |
f0177261-03fe-4c16-8896-f261ae35ff54 | 6 | @Override
public boolean shadow_hit(Ray ray, FloatRef tmin) {
if (!bbox.hit(ray))
return false;
double x1 = ray.getOrigin().getX();
double y1 = ray.getOrigin().getY();
double z1 = ray.getOrigin().getZ();
double d1 = ray.getDirection().getX();
double d2 = ray.getDirection().getY();
double d3 = ray.getDirection().getZ();
double coeffs[] = new double[5]; // coefficient array for the quartic equation
double roots[] = new double[4]; // solution array for the quartic equation
// define the coefficients of the quartic equation
double sum_d_sqrd = d1 * d1 + d2 * d2 + d3 * d3;
double e = x1 * x1 + y1 * y1 + z1 * z1 - a * a - b * b;
double f = x1 * d1 + y1 * d2 + z1 * d3;
double four_a_sqrd = 4.0 * a * a;
coeffs[0] = e * e - four_a_sqrd * (b * b - y1 * y1); // constant term
coeffs[1] = 4.0 * f * e + 2.0 * four_a_sqrd * y1 * d2;
coeffs[2] = 2.0 * sum_d_sqrd * e + 4.0 * f * f + four_a_sqrd * d2 * d2;
coeffs[3] = 4.0 * sum_d_sqrd * f;
coeffs[4] = sum_d_sqrd * sum_d_sqrd; // coefficient of t^4
// find roots of the quartic equation
int num_real_roots = Solvers.solveQuartic(coeffs, roots);
boolean intersected = false;
double t = Double.MAX_VALUE;
if (num_real_roots == 0) // ray misses the torus
return false;
// find the smallest root greater than kEpsilon, if any
// the roots array is not sorted
for (int j = 0; j < num_real_roots; j++)
if (roots[j] > K_EPSILON) {
intersected = true;
if (roots[j] < t)
t = roots[j];
}
if (!intersected)
return false;
tmin.value = (float) t;
return true;
} |
c255b21f-0f6f-4153-8741-c7c5b68a8fcc | 4 | public static String getCharset(String page)
{
//
page = page.toLowerCase(Locale.getDefault());
int charsetIndex = page.indexOf("charset=");
Pattern pattern = Pattern.compile("[a-z0-9/-]{1}");
// 如果不存在charset=
if (charsetIndex < 0)
{
return "utf-8";
}
// 截取掉字符集前的所有字符
String indefiniteCharset = null;
String symbol = page.substring(charsetIndex + 8, charsetIndex + 9);
if (!pattern.matcher(symbol).matches())
{
indefiniteCharset = page.substring(charsetIndex + 9);
}
else
{
indefiniteCharset = page.substring(charsetIndex + 8);
}
// 读取字符集
StringBuffer charset = new StringBuffer();
for (int i = 0; i < indefiniteCharset.length(); i++)
{
if (!pattern.matcher(indefiniteCharset.substring(i, i + 1)).matches())
{
break;
}
charset.append(indefiniteCharset.substring(i, i + 1));
}
return charset.toString();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.