text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public void setTargetItem( DefaultBox<?> targetItem ) {
if( comment == null ) {
super.setTargetItem( targetItem );
} else {
comment.setConnection( null );
super.setTargetItem( targetItem );
comment.setConnection( this );
}
} | 2 |
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String nextPage = request.getPathInfo();
if (nextPage != null && !nextPage.contentEquals("/")) {
if (nextPage.contentEquals("/article")) {
ajoutArticleEnSession(request);
request.getSession().setAttribute("handle", "succes");
((HttpServletResponse) response).sendRedirect(request
.getContextPath() + "/frontController/catalogue");
return;
} else if (!nextPage.contentEquals("/login")) {
nextPage = nextPage.substring(1);
} else {
nextPage = "/";
}
}
request.setAttribute("page", nextPage);
getServletContext().getRequestDispatcher("/template").forward(request,
response);
} | 4 |
private void appendDisclaimer(StringBuilder builder) {
try {
Document doc = Jsoup.parse(BakaTsuki.getResourceAsStream("resources/disclaimer.html"), "UTF-8", "");
Element table = doc.select("table#contributors").first();
// Append header row
if(!config.getTitle().equals(""))
table.append("<tr><th colspan='2' class='header'></th></tr>").select(".header").first().text(config.getTitle());
HashMap<String, List<String>> contributors = config.getContributors();
Set<String> keys = contributors.keySet();
for(String key : keys)
{
List<String> names = contributors.get(key);
key = key.substring(0, 1).toUpperCase() + key.substring(1);
if (names.size() == 1)
{
key = key.substring(0, key.length() - 1);
}
else if (names.size() == 0)
{
continue;
}
Element tr = doc.createElement("tr");
tr.appendElement("th").text(key);
tr.appendElement("td").text(BakaTsuki.join(names, ", "));
table.appendChild(tr);
}
if(!config.getProject().equals("")) {
table.append("<tr><th>Project page</th><td></td></tr>");
table.select("tr").last().select("td").append(String.format("<a href='%1$s'>%1$s</a>", config.getProject()));
}
DateFormat formatter = DateFormat.getDateInstance();
table.append(String.format("<tr><th>PDF creation date</th><td>%s</td>", formatter.format(new Date())));
builder.append(doc.body().html());
} catch (IOException e) {
e.printStackTrace();
}
} | 6 |
private void markSubroutineWalk(
final Subroutine sub,
final int index,
final BitSet anyvisited)
{
if (LOGGING) {
log("markSubroutineWalk: sub=" + sub + " index=" + index);
}
// First find those instructions reachable via normal execution
markSubroutineWalkDFS(sub, index, anyvisited);
// Now, make sure we also include any applicable exception handlers
boolean loop = true;
while (loop) {
loop = false;
for (Iterator it = tryCatchBlocks.iterator(); it.hasNext();) {
TryCatchBlockNode trycatch = (TryCatchBlockNode) it.next();
if (LOGGING) {
// TODO use of default toString().
log("Scanning try/catch " + trycatch);
}
// If the handler has already been processed, skip it.
int handlerindex = instructions.indexOf(trycatch.handler);
if (sub.instructions.get(handlerindex)) {
continue;
}
int startindex = instructions.indexOf(trycatch.start);
int endindex = instructions.indexOf(trycatch.end);
int nextbit = sub.instructions.nextSetBit(startindex);
if (nextbit != -1 && nextbit < endindex) {
if (LOGGING) {
log("Adding exception handler: " + startindex + '-'
+ endindex + " due to " + nextbit + " handler "
+ handlerindex);
}
markSubroutineWalkDFS(sub, handlerindex, anyvisited);
loop = true;
}
}
}
} | 8 |
@Override
public void onDraw(Graphics G, int viewX, int viewY) {
if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300)
{
G.setColor(Color.white);
int deg = r.nextInt(360);
G.fillArc((int)(X-1)-viewX, (int)(Y-1)-viewY, 2, 2, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-2)-viewX, (int)(Y-2)-viewY, 4, 4, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-3)-viewX, (int)(Y-3)-viewY, 6, 6, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-4)-viewX, (int)(Y-4)-viewY, 8, 8, deg, 60);
}
} | 4 |
private void checkValuePlacement() throws RrdException
{
Matcher m = VALUE_PATTERN.matcher(text);
if ( m.find() )
{
normalScale = (text.indexOf(SCALE_MARKER) >= 0);
uniformScale = (text.indexOf(UNIFORM_SCALE_MARKER) >= 0);
if ( normalScale && uniformScale )
throw new RrdException( "Can't specify normal scaling and uniform scaling at the same time." );
String[] group = m.group(1).split("\\.");
strLen = -1;
numDec = 0;
if ( group.length > 1 )
{
if ( group[0].length() > 0 ) {
strLen = Integer.parseInt(group[0]);
numDec = Integer.parseInt(group[1]);
}
else
numDec = Integer.parseInt(group[1]);
}
else
numDec = Integer.parseInt(group[0]);
}
else
throw new RrdException( "Could not find where to place value. No @ placeholder found." );
} | 5 |
private void highlightRemaining() {
editingGrammarView.dehighlight();
mainLabel.setText("Productions to convert are selected.");
for (int i = 0; i < need.length; i++)
editingGrammarView.highlight(need[i]);
} | 1 |
public synchronized static int countBrothers(ArrayList<Ant> ants) {
int brothers = 0;
for (int a = 0; a < ants.size(); a++) {
boolean brothersOk = false;
for (int b = 0; b < ants.size(); b++) {
if (a != b) {
if (!isTheBrother(ants.get(a), ants.get(b))) {
brothersOk = true;
}
}
}
if (brothersOk) {
brothers++;
}
}
return brothers;
} | 5 |
public void setId(int id) {
this.id = id;
} | 0 |
public String execute(String[] args){
return runList.toString();
} | 0 |
private boolean parseRooms(Document doc)
{
int x, y;
Tile elevatorTile = null;
NodeList nodes = doc.getElementsByTagName(XmlTag.ROOM_SECTION.toString());
NodeList rooms = ((Element)nodes.item(0)).getElementsByTagName(XmlTag.ROOM.toString());
for(int room_num = 0; room_num < rooms.getLength(); room_num++)
{
Element room = (Element) rooms.item(room_num);
NodeList tiles = room.getElementsByTagName(XmlTag.TILE.toString());
Room r = new Room();
//is elevator room?
String roomType = room.getAttribute(XmlTag.TYPE.toString());
for(int tile_num = 0; tile_num < tiles.getLength(); tile_num++)
{
Element tile = (Element) tiles.item(tile_num);
x = Integer.parseInt(tile.getAttribute(XmlTag.X.toString()));
y = Integer.parseInt(tile.getAttribute(XmlTag.Y.toString()));
Tile t = new Tile(new Point(x, y), r);
if(level.setTile(x, y, t))
{
if(tile_num == 0 && roomType.equalsIgnoreCase(XmlTag.ELEVATOR.toString()))
{
elevatorTile = t;
}
r.addTile(t);
}
if(elevatorTile != null)
{
//set the room as an elevator
level.setElevator(r, elevatorTile);
}
}
}
return (elevatorTile != null);
} | 6 |
public void print() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Gender " + gender);
System.out.println("Birthdate " + birthday + " " + birthyear);
System.out.println("Deathdate: " + deathday + " " + deathyear);
if (mother != null) {
System.out.println("Mother: " + mother.getName());
}
if (farther != null) {
System.out.println("Father: " + farther.getName());
}
if (children != null) {
for (int i = 0; i < children.size(); i++) {
System.out.println("Child: " + children.get(i).getName());
}
}
if (spouse != null) {
System.out.println("Spouse: " + spouse.getName());
}
System.out.println();
} | 5 |
public void paint(Graphics g){
super.paint(g);
Dimension size = getSize();
int boardTop = (int) size.getHeight() - BoardHeight * squareHeight();
//vykresleni uz dopadenych dilku
for (int i = 0; i < BoardHeight; ++i) {
for (int j = 0; j < BoardWidth; ++j) {
Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
if (shape != Tetrominoes.NoShape)
drawSquare(g, 0 + j * squareWidth(), boardTop + i * squareHeight(), shape);
}
}
//vykresleni prave padajiciho dilku
if (curPiece.getShape() != Tetrominoes.NoShape) {
for (int i = 0; i < 4; ++i) {
int x = curX + curPiece.x(i);
int y = curY - curPiece.y(i);
drawSquare(g, 0 + x * squareWidth(), boardTop + (BoardHeight - y - 1) * squareHeight(), curPiece.getShape());
}
}
} | 5 |
public void deleteArrow() {
synchronized(c) {
if (c.playerEquipment[c.playerCape] == 10499 && Misc.random(5) != 1 && c.playerEquipment[c.playerArrows] != 4740)
return;
if(c.playerEquipmentN[c.playerArrows] == 1) {
c.getItems().deleteEquipment(c.playerEquipment[c.playerArrows], c.playerArrows);
}
if(c.playerEquipmentN[c.playerArrows] != 0) {
c.getOutStream().createFrameVarSizeWord(34);
c.getOutStream().writeWord(1688);
c.getOutStream().writeByte(c.playerArrows);
c.getOutStream().writeWord(c.playerEquipment[c.playerArrows]+1);
if (c.playerEquipmentN[c.playerArrows] -1 > 254) {
c.getOutStream().writeByte(255);
c.getOutStream().writeDWord(c.playerEquipmentN[c.playerArrows] -1);
} else {
c.getOutStream().writeByte(c.playerEquipmentN[c.playerArrows] -1);
}
c.getOutStream().endFrameVarSizeWord();
c.flushOutStream();
c.playerEquipmentN[c.playerArrows] -= 1;
}
c.updateRequired = true;
c.setAppearanceUpdateRequired(true);
}
} | 6 |
private void createRecursively(IBlockNode node, Node sceneNode, int depth, Map<HingeJoint, JointProperties> jointsMap)
{
if(depth <= this.maxDepth && numNodes<=tempMaxNodes)
{
List<BlockNode> addedChildren = new ArrayList<BlockNode>();
for(int i=0; i<8; i++)
{
boolean ticketToPass = (numNodes==1 && i==7);
if(((r.nextInt(chanceToCreateNode)==0) && numNodes<tempMaxNodes) || ticketToPass)
{
boolean collidesWithOtherNodes = true;
Dimensions d = Util.getRandomDimensions();
JointProperties jp = Util.getRandomJointProps();
BlockNode newNode= new BlockNode(d, jp, i);
node.addChild(newNode, i);
Util.JmeObject jmeObject = Util.createJmeNode(newNode.getDimensions(), app, newNode.getGeometryId());
app.getMaterialsStore().add(jmeObject.material);
Geometry geometry = jmeObject.geometry;
Spatial parentSpatial = sceneNode.getChild(node.getGeometryId());
Position p = Position.getPosition(i);
Position pi = Position.getPosition(Util.getInversePosition(i));
translateGeometry(geometry, parentSpatial, node, newNode, p, pi);
collidesWithOtherNodes = Util.collidesWithOtherNodes(geometry, sceneNode, node.getGeometryId());
if(!collidesWithOtherNodes)
{
HingeJoint joint = makeJoint(geometry, parentSpatial, node, newNode, jp, p, pi);
jointsMap.put(joint, jp);
sceneNode.attachChild(geometry);
numNodes++;
addedChildren.add(newNode);
}
else
{
node.removeChild(i);
}
}
else
{
node.getChildren()[i] = null;
}
}
for(BlockNode child: addedChildren)
{
createRecursively(child, sceneNode, depth+1, jointsMap);
depth--;
}
}
} | 9 |
public void fillKeplerElements(OsculatoryElements[] _el) {
int body;
int i;
double s[] = new double[3];
double p[] = new double[3];
double r2[] = new double[3];
double v2[] = new double[3];
double rr[] = new double[3];
double vv[] = new double[3];
double b1[] = new double[3];
double b2[] = new double[3];
double e, costh, sinth, a, c, h, r;
if (getCentralBody() < 0) {
getPositionCOM(p);
getSpeedCOM(s);
} else {
}
for (body = 0; body < _el.length; body++) {
double axeFactor = _el[body].reducedMass;
if (getCentralBody() >= 0) {
for (i = 0; i < 3; i++) {
p[i] = (getPosition(getCentralBody(), i) - getPosition(
body, i))
* axeFactor + getPosition(body, i);
s[i] = (getSpeed(getCentralBody(), i) - getSpeed(body, i))
* axeFactor + getSpeed(body, i);
}
}
for (i = 0; i < 3; i++) {
r2[i] = getPosition(body, i);
v2[i] = getSpeed(body, i);
rr[i] = (r2[i] - p[i]) / (axeFactor);// r2[i]-r1[i];
vv[i] = (v2[i] - s[i]) / (axeFactor); // v2[i]-v1[i];
b1[i] = rr[i];
}
Funcions.Vect(rr, vv, _el[body].angularMomVec);
c = _el[body].angularMom = Math.sqrt(Funcions.scal(
_el[body].angularMomVec, _el[body].angularMomVec));
r = Math.sqrt(Funcions.scal(rr, rr));
Funcions.normaliser(b1);
Funcions.Vect(_el[body].angularMomVec, b1, b2);
Funcions.normaliser(b2);
double mu = _el[body].mu;
h = 0.5D * Funcions.scal(vv, vv) - mu / r;
e = Math.sqrt(1D + 2D * h * c * c / (mu * mu));
double aux;
aux = (mu * (1D - e * e));
if (Math.abs(aux) > this.paramTOL) {
a = c * c / aux;
aux = r * e;
if (Math.abs(aux) > this.paramTOL) {
costh = ((a * (1D - e * e) - r) / aux);
sinth = Math.sqrt(1D - costh * costh);
if (Funcions.scal(rr, vv) < 0D) {
sinth = -sinth;
}
} else {
costh = 1D;
sinth = 0D;
}
_el[body].angularMom = (axeFactor) * (axeFactor) * c;
_el[body].excentricity = e;
_el[body].major = (axeFactor) * a;
_el[body].minor = (axeFactor) * a * Math.sqrt(1D - e * e);
for (i = 0; i < 3; i++) {
_el[body].angularMomVec[i] = (axeFactor) * (axeFactor)
* _el[body].angularMomVec[i];
_el[body].majorVec[i] = (axeFactor) * a
* (costh * b1[i] - sinth * b2[i]);
_el[body].center[i] = p[i] - e * _el[body].majorVec[i];
_el[body].minorVec[i] = _el[body].minor
* (sinth * b1[i] + costh * b2[i]);
}
}
}
this.lastKeplerCalcTime = getTime();
} | 9 |
public String getLocation()
{
return location;
} | 0 |
private void addListeners() {
this.wordCountRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.print("Number of words in the above string is :\t");
System.out.println(StringDemo.wordCount(StringBasicPanel.this.textField.getText()));
}
});
this.spaceCountRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.print("Number of spaces in the above string is :\t");
System.out.println(StringDemo.spaceCount(StringBasicPanel.this.textField.getText()));
}
});
this.charCountRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.print("Number of spaces in the above string is :\t");
System.out.println(StringDemo.charCount(StringBasicPanel.this.textField.getText()));
}
});
this.reverseRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.print("Reverse of above string is :\t");
System.out.println(StringDemo.reverseString(StringBasicPanel.this.textField.getText()));
}
});
this.pallindromeRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.print("The above String is ");
if (!StringDemo.pallindrome(StringBasicPanel.this.textField.getText())) {
System.out.print("not ");
}
System.out.println("a pallindrome");
}
});
this.leftTrimRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above String after removing all the spaces from left :\t");
System.out.println(StringDemo.lTrim(StringBasicPanel.this.textField.getText()));
}
});
this.rightTrimRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above String after removing all the spaces from right :\t");
System.out.println(StringDemo.rTrim(StringBasicPanel.this.textField.getText()));
}
});
this.trimRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above String after removing all the spaces from all the sides :\t");
System.out.println(StringDemo.allTrim(StringBasicPanel.this.textField.getText()));
}
});
this.squeezeRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above String after removing all the spaces from everywhere :\t");
System.out.println(StringDemo.squeeze(StringBasicPanel.this.textField.getText()));
}
});
this.vowelCountRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Number of vowles in above string :\t");
System.out.println(StringDemo.vowelCount(StringBasicPanel.this.textField.getText()));
}
});
this.lengthRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Length of the above string:\t");
System.out.println(StringDemo.length(StringBasicPanel.this.textField.getText()));
}
});
this.sequenceCountRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("How many times a character is repeated (continuously) in above string:\n");
StringDemo.sequenceCount(StringBasicPanel.this.textField.getText());
}
});
this.freqCountCharRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("How many times a character is repeated in above string:\n");
StringDemo.frequencyCount(StringBasicPanel.this.textField.getText());
}
});
this.changeCaseRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above string after changing the case :\t");
System.out.println(StringDemo.changeCase(StringBasicPanel.this.textField.getText()));
}
});
this.singleOccuranceButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above string after removing continuous occurance of a letter/character :\t");
System.out.println(StringDemo.singleOccurance(StringBasicPanel.this.textField.getText()));
}
});
this.sortedOrderRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above String after sorting :\t");
System.out.println(StringDemo.sortedOrder(StringBasicPanel.this.textField.getText()));
}
});
this.sortedWordRadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
System.out.println("Above string after sorting (sorting according to words) :\t");
System.out.println(StringDemo.sortedWord(StringBasicPanel.this.textField.getText()));
}
});
this.wordTriangleType1RadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
StringDemo.triangle1(StringBasicPanel.this.textField.getText());
}
});
this.wordTriangleType2RadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
StringDemo.triangle2(StringBasicPanel.this.textField.getText());
}
});
this.wordTriangleType3RadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
StringDemo.triangle3(StringBasicPanel.this.textField.getText());
}
});
this.wordTriangleType4RadioButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringBasicPanel.this.main.clearOutput();
StringDemo.triangle4(StringBasicPanel.this.textField.getText());
}
});
} | 1 |
static private boolean jj_3R_88() {
if (jj_scan_token(FOR)) return true;
if (jj_scan_token(70)) return true;
if (jj_3R_20()) return true;
if (jj_scan_token(72)) return true;
if (jj_3R_20()) return true;
if (jj_scan_token(72)) return true;
if (jj_3R_20()) return true;
if (jj_scan_token(71)) return true;
if (jj_3R_17()) return true;
return false;
} | 9 |
public double heightAt(double x, double z) {
if (x < 0) {
x = 0;
}
if (x > this.getWidth() - 1) {
x = this.getWidth() - 1;
}
if (z < 0) {
z = 0;
}
if (z > this.getLength() - 1) {
z = this.getLength() - 1;
}
int leftX = (int) x;
if (leftX == this.getWidth() - 1) {
leftX--;
}
double fracX = x - leftX;
int outZ = (int) z;
if (outZ == this.getWidth() - 1) {
outZ--;
}
double fracZ = z - outZ;
float h11 = this.getHeight(leftX, outZ);
float h12 = this.getHeight(leftX, outZ + 1);
float h21 = this.getHeight(leftX + 1, outZ);
float h22 = this.getHeight(leftX + 1, outZ + 1);
return (1 - fracX) * ((1 - fracZ) * h11 + fracZ * h12) + fracX
* ((1 - fracZ) * h21 + fracZ * h22);
} | 6 |
public static void updateCalendar(int aMonth, int aYear){
String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int days;
int startOfMonth;
prev.setEnabled(true);
next.setEnabled(true);
// Prevents going backward or forward too far
if (aMonth == 0 && aYear <= theYear-10){
prev.setEnabled(false);
}
if (aMonth == 11 && aYear >= theYear+50){
next.setEnabled(false);
}
month.setText(months[aMonth]);
month.setBounds(418-month.getPreferredSize().width/2, 50, 360, 50);
yearBox.setSelectedItem(String.valueOf(aYear));
// Creates calendar for correctly adding days for a specific month
GregorianCalendar gregCal = new GregorianCalendar(aYear, aMonth, 1);
days = gregCal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
startOfMonth = gregCal.get(GregorianCalendar.DAY_OF_WEEK);
// Adds all days to a specific month
for (int i = 0; i < 6; i++){
for (int j = 0; j < 7; j++){
calendarTable.setValueAt(null, i, j);
}
}
generateDays(days, startOfMonth);
// Sets days of the month to the top of each cell
DefaultTableCellRenderer render = new DefaultTableCellRenderer();
render.setVerticalAlignment(JLabel.TOP);
for (int i = 0; i < 7; i++){
Calendar.getColumnModel().getColumn(i).setCellRenderer(render);
}
} | 7 |
@Override
protected long calculateBase(final long base, final long remainder, final int droppedDigits, final int layoutBase)
{
final long baseWithRemainder = base + (remainder == 0 ? 0 : remainder / DPU.getScale(droppedDigits - 1) / 5);
if (layoutBase != 1)
{
final long layoutRemainder = baseWithRemainder % layoutBase;
if (layoutRemainder != 0)
{
return baseWithRemainder + layoutBase - layoutRemainder;
}
}
return baseWithRemainder;
} | 3 |
public void addPlantsToWorld(final Grid g) {
Thread plantWatcher = new Thread(new Runnable() {
@Override
public void run() {
int n = 0;
while (true) {
while (Grid.plants.size() < nPlantsInWorld) {
if (nPlantsInWorld - Grid.plants.size() >= 4) {
n = 4;
} else {
n = nPlantsInWorld - Grid.plants.size();
}
addPlants(g, n);
}
}
}
});
plantWatcher.start();
} | 3 |
@EventHandler
public void onJoin(PlayerJoinEvent e) {
String channel = plugin.getConfig().getString("CustomChannels.Channel-on-Join");
ConfigurationSection s = ChannelsConfig.getChannels().getConfigurationSection("channels");
Player p = e.getPlayer();
/*
* Critical null-check. It is easy to mess this configuration setup and
* receive lots of errors.
*/
if (channel == null || s == null) return;
// Both set to lowercase to avoid case-sensitivity issues.
if (s.getKeys(false).contains(channel.toLowerCase())) {
plugin.CustomChat.put(p.getName(), channel);
return;
} else {
// Notify important players that there is an issue..
Messenger.severe("The default channel-on-join (in config.yml) is invalid!");
if (p.hasPermission("playerchat.mod")) Messenger.tell(p, "The default channel-on-join (in config.yml) is invalid!");
}
} | 4 |
public Move move(Field from, Field to) {
Move move = this.getMove(this.window.board, from, to, from.getPiece());
this.executeMove(move);
return move;
} | 0 |
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
} | 3 |
public static void main(String[] arsg) {
printOutGameStateTransition("", "");
} | 0 |
private Rectangle2D.Double DrawText(Graphics2D g2, Font font, Rectangle2D.Double r1, String text) {
Rectangle d = font.getStringBounds(text, g2.getFontRenderContext()).getBounds();
Rectangle2D.Double r2;
if (r1 == null)
r2 = new Rectangle2D.Double(width / 2 - d.width / 2 - (int) (0.04 * height),
height / 2 - d.height / 2, d.width + 2 * (int) (0.04 * height), d.height + (int) (0.04 * height));
else
r2 = new Rectangle2D.Double(r1.x,
r1.y + d.height + g2.getFontMetrics().getAscent() * 2, r1.width, r1.height);
g2.setPaint(Color.black);
g2.fill(r2);
g2.setColor(Color.WHITE);
g2.draw(r2);
g2.drawString(text, width / 2 - d.width / 2, (int) (r2.y + r2.height - d.height / 2));
return r2;
} | 1 |
public void actionPerformed( ActionEvent e )
{
// don't handle the keys in other components
TKeyLock.keys.lock() ;
TProject project = TGlobal.projects.getCurrentProject() ;
TProjectData current = project.getProjectData() ;
// project instance available
if ( current != null )
{
if ( current.hasData() )
{
String keyValue = JOptionPane.showInputDialog( "Please input the key",
"NewEntry" +counter ) ;
// null meaning the user canceled the input
if ( keyValue == null )
{
return ;
}
// key invalid
if ( keyValue.length() < 1 )
{
return ;
}
keyValue = Utils.normalizeIT(keyValue,
project.getSettings().getReplaceWhitespace(),
project.getSettings().getReplaceString() ) ;
TMultiLanguageEntry entry = current.getLanguageEntry( keyValue ) ;
// no entry
if ( entry == null )
{
entry = current.addLanguageEntry( keyValue ) ;
counter++ ;
}
else // entry allready defined
{
JOptionPane.showMessageDialog( null,
"key already defined, action aborted!",
"warning",
JOptionPane.WARNING_MESSAGE ) ;
}
// select the entry
if ( entry != null )
{
int index = current.getLanguageEntryIndex( entry.getKey() ) ;
//table.selectRow( index, true ) ;
GUIGlobals.oPanel.selectAndGrabIndex(index);
}
}
}
// unlock the key's handling of other components
TKeyLock.keys.unlock() ;
} | 6 |
public void winnings() {
//Divide exp amongst characters
int div = 0;
ArrayList<People> team = _user.getTeam();
for ( People p : team ) {
if ( !p.getDead() )
div += 1;
}
gainE = gainE/div;
for ( People p : team ) {
if ( !p.getDead() ) {
System.out.println(p.getName() + " gained " + gainE + " exp!");
p.gainExp( gainE );
}
}
System.out.println( "Earned " + gainM + " $!" );
_user.addMun( gainM );
} | 4 |
public final void run_startup_configurations() {
try {
FileReader fileReader = new FileReader(System.getProperty("net.sf.odinms.login.config"));
initialProp.load(fileReader);
fileReader.close();
Registry registry = LocateRegistry.getRegistry(initialProp.getProperty("net.sf.odinms.world.host"), Registry.REGISTRY_PORT, new SslRMIClientSocketFactory());
worldRegistry = (WorldRegistry) registry.lookup("WorldRegistry");
lwi = new LoginWorldInterfaceImpl();
wli = worldRegistry.registerLoginServer(ServerConstants.Login_Key, lwi);
Properties dbProp = new Properties();
fileReader = new FileReader("db.properties");
dbProp.load(fileReader);
fileReader.close();
DatabaseConnection.setProps(dbProp);
DatabaseConnection.getConnection();
prop = wli.getWorldProperties();
userLimit = Integer.parseInt(prop.getProperty("net.sf.odinms.login.userlimit"));
serverName = prop.getProperty("net.sf.odinms.login.serverName");
eventMessage = prop.getProperty("net.sf.odinms.login.eventMessage");
flag = Byte.parseByte(prop.getProperty("net.sf.odinms.login.flag"));
maxCharacters = Integer.parseInt(prop.getProperty("net.sf.odinms.login.maxCharacters"));
try {
fileReader = new FileReader("subnet.properties");
subnetInfo.load(fileReader);
fileReader.close();
} catch (FileNotFoundException e) {
System.err.println("'subnet.properties' not found. Fail to load subnet configuration, falling back to world defaults");
}
try {
final PreparedStatement ps = DatabaseConnection.getConnection()
.prepareStatement("UPDATE accounts SET loggedin = 0");
ps.executeUpdate();
ps.close();
} catch (SQLException ex) {
throw new RuntimeException("[EXCEPTION] Please check if the SQL server is active.");
}
} catch (RemoteException re) {
throw new RuntimeException("[EXCEPTION] Could not connect to world server.");
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("[EXCEPTION] File for login or database configuration not found, please check again.");
} catch (IOException ioe) {
throw new RuntimeException("[EXCEPTION] Failed or interrupted I/O operations.");
} catch (NotBoundException nbe) {
throw new RuntimeException("[EXCEPTION] Attempting lookup or unbind in the registry a name that has no associated binding.");
}
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
acceptor = new SocketAcceptor();
final SocketAcceptorConfig cfg = new SocketAcceptorConfig();
cfg.getSessionConfig().setTcpNoDelay(true);
cfg.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MapleCodecFactory()));
TimerManager.getInstance().start();
// TimerManager.getInstance().register(new RankingWorker(), 3600000);
LoginInformationProvider.getInstance();
try {
InetSocketadd = new InetSocketAddress(PORT);
acceptor.bind(InetSocketadd, new MapleServerHandler(ServerType.LOGIN), cfg);
System.out.println("Listening on port " + PORT + ".");
} catch (IOException e) {
System.err.println("Binding to port " + PORT + " failed" + e);
}
} | 7 |
@Override
public void Actualizar(Object value) {
Session session = null;
try {
Cuentas cuenta = (Cuentas) value;
session = NewHibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.update(cuenta);
session.getTransaction().commit();
} catch (HibernateException e) {
System.out.println(e.getMessage());
session.getTransaction().rollback();
} finally {
if (session != null) {
// session.close();
}
}
} | 2 |
void init(int n){
bitrev=new int[n/4];
trig=new float[n+n/4];
log2n=(int)Math.rint(Math.log(n)/Math.log(2));
this.n=n;
int AE=0;
int AO=1;
int BE=AE+n/2;
int BO=BE+1;
int CE=BE+n/2;
int CO=CE+1;
// trig lookups...
for(int i=0; i<n/4; i++){
trig[AE+i*2]=(float)Math.cos((Math.PI/n)*(4*i));
trig[AO+i*2]=(float)-Math.sin((Math.PI/n)*(4*i));
trig[BE+i*2]=(float)Math.cos((Math.PI/(2*n))*(2*i+1));
trig[BO+i*2]=(float)Math.sin((Math.PI/(2*n))*(2*i+1));
}
for(int i=0; i<n/8; i++){
trig[CE+i*2]=(float)Math.cos((Math.PI/n)*(4*i+2));
trig[CO+i*2]=(float)-Math.sin((Math.PI/n)*(4*i+2));
}
{
int mask=(1<<(log2n-1))-1;
int msb=1<<(log2n-2);
for(int i=0; i<n/8; i++){
int acc=0;
for(int j=0; msb>>>j!=0; j++)
if(((msb>>>j)&i)!=0)
acc|=1<<j;
bitrev[i*2]=((~acc)&mask);
// bitrev[i*2]=((~acc)&mask)-1;
bitrev[i*2+1]=acc;
}
}
scale=4.f/n;
} | 5 |
protected void appendQueue(Point curTileIJ,Point end) {
Point p[] = new Point[8];
int withOrWithoutDiag;
p[0] = new Point(curTileIJ.x, curTileIJ.y - 1);
p[1] = new Point(curTileIJ.x - 1, curTileIJ.y);
p[2] = new Point(curTileIJ.x + 1, curTileIJ.y);
p[3] = new Point(curTileIJ.x, curTileIJ.y + 1);
p[4] = new Point(curTileIJ.x - 1, curTileIJ.y - 1);
p[5] = new Point(curTileIJ.x + 1, curTileIJ.y - 1);
p[6] = new Point(curTileIJ.x - 1, curTileIJ.y + 1);
p[7] = new Point(curTileIJ.x + 1, curTileIJ.y + 1);
int loinEnd = curTileIJ.x-end.x+curTileIJ.y-end.y;
if(loinEnd > 10 || loinEnd < -10)
withOrWithoutDiag = 4;
else
withOrWithoutDiag = 8;
for (int i = 0; i < withOrWithoutDiag; i++) {
if (p[i] == null)
continue;
if (valide(p[i], marker)) {
QueueElement qe = new QueueElement(p[i], index);
queue.add(qe);
marker[p[i].x][p[i].y] = true;
}
}
} | 5 |
@Override
protected void initializationManagerGraphForm() {
ArrayList<GraphicForm> graphicForms = new ArrayList<GraphicForm>();
graphicForms.add(new InformationForm(900, 568, 1500, 600, 800, 200, "Information", this));
graphicForms.add(new Radar(900-800+256, 568, 500, 400, 256,200, "Radar", this));
manGraphForm = new ManagerGraphicForm(graphicForms);
} | 0 |
protected void genClanStatus(MOB mob, Clan C, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
mob.tell(L("@x1. Clan Status: @x2",""+showNumber,Clan.CLANSTATUS_DESC[C.getStatus()]));
if((showFlag!=showNumber)&&(showFlag>-999))
return;
switch(C.getStatus())
{
case Clan.CLANSTATUS_ACTIVE:
C.setStatus(Clan.CLANSTATUS_PENDING);
mob.tell(L("Clan '@x1' has been changed from active to pending!",C.name()));
break;
case Clan.CLANSTATUS_PENDING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell(L("Clan '@x1' has been changed from pending to active!",C.name()));
break;
case Clan.CLANSTATUS_FADING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell(L("Clan '@x1' has been changed from fading to active!",C.name()));
break;
default:
mob.tell(L("Clan '@x1' has not been changed!",C.name()));
break;
}
} | 7 |
private int getDir(char c) {
int d = 0;
switch (c) {
case 'L':
case 'l':
d = 2;
break;
case 'R':
case 'r':
d = 8;
break;
case 'F':
case 'f':
d = 1;
break;
case 'B':
case 'b':
d = 4;
break;
default:
System.out.println(c + " does not represent a valid direction!");
System.exit(-2);
}
return d;
} | 8 |
public AuthenticatedService(Server server, String name, String type, Map<?, ?> config) throws Exception {
super(server, name, type, config);
log.debug("Finding the authenticator");
Object obj = config.get("authenticator");
if (obj != null && !(obj instanceof String))
throw new Exception("Problem loading configuration: services > service > authenticator");
this.auth = (String) obj;
} | 4 |
public String format(LogRecord lr) {
Date date = new Date(lr.getMillis());
StringBuffer sb = new StringBuffer();
sb.append("<DebugAusgabe>").append(NEWLINE);
sb.append("<LfdNr>");
sb.append(_numberFormat.format(lr.getSequenceNumber()));
sb.append("</LfdNr>").append(NEWLINE);
sb.append("<Zeitpunkt>");
sb.append(_absoluteMillisecondsFormat.format(date));
sb.append("</Zeitpunkt>").append(NEWLINE);
sb.append("<DebugLevel>");
Level l = lr.getLevel();
if (l == Debug.ERROR)
sb.append("FEHLER");
else if (l == Debug.WARNING)
sb.append("WARNUNG");
else if (l == Debug.INFO)
sb.append("INFO");
else if (l == Debug.CONFIG)
sb.append("KONFIG");
else if (l == Debug.FINE)
sb.append("FEIN");
else if (l == Debug.FINER)
sb.append("FEINER");
else if (l == Debug.FINEST)
sb.append("DETAIL");
sb.append("</DebugLevel>").append(NEWLINE);
sb.append("<MeldungsText>");
sb.append(lr.getMessage());
sb.append("</MeldungsText>").append(NEWLINE);
sb.append("<DebugLogger>");
sb.append(lr.getLoggerName());
sb.append("</DebugLogger>").append(NEWLINE);
sb.append("<ThreadID>");
sb.append(_numberFormat.format(lr.getThreadID()));
sb.append("</ThreadID>").append(NEWLINE);
sb.append("</DebugAusgabe>").append(NEWLINE);
return (sb.toString());
} | 7 |
public static ArrayList<int[]> getBoxLocations(State state) {
ArrayList<int[]> boxList = new ArrayList<int[]>();
int[] boxPosition = {0, 0};
ArrayList<ArrayList<String>> temp;
temp = copy(state.getData());
for (int k = 0; k < temp.size(); k++) {
for(int m = 0; m < temp.get(k).size(); m++) {
if (temp.get(k).get(m).equals("$")) {
boxPosition[0] = k;
boxPosition[1] = m;
boxList.add(boxPosition);
continue;
}
}
for(int m = 0; m < temp.get(k).size(); m++) {
if (temp.get(k).get(m).equals("*")) {
boxPosition[0] = k;
boxPosition[1] = m;
boxList.add(boxPosition);
continue;
}
}
}
return boxList;
} | 5 |
private PickVO getList100PVO(PickVO pvo, ArrayList<LineAnaVO> list100) {
if (list100.size() > 7) {
LineAnaVO v = getGap(0, list100);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(3, list100);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(4, list100);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(7, list100);
if (v != null) {
pvo.add(v.getBnu());
}
} else {
LineAnaVO v = getGap(3, list100);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(1, list100);
if (v != null) {
pvo.add(v.getBnu());
}
v = getGap(2, list100);
if (v != null) {
pvo.add(v.getBnu());
}
}
return pvo;
} | 8 |
private int cheminPlusLongVersRacine(Model model, Generalization g) {
if(g == null){
return 0;
} else {
Generalization root = null;
for(Generalization g_root : model.getGeneralization()){
for(String str_enfant : g_root.getArrayIdent()){
if(str_enfant.equals(g.getIdentifier())){
root = g_root;
}
}
}
return 1 + cheminPlusLongVersRacine(model, root);
}
} | 4 |
private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscarActionPerformed
//se toma lo que hay en la caja de texto y sele asigna a nombre
String nombre = String.valueOf(txtNombreArchivo.getText());
//Se crea un objeto g de la clase General del Paquete Program
General g = new General();
//Se crean 2 String
String codigo;
String nota;
//Se mira que en nombre halla algo con un if
if( !nombre.equals("") ) {
//se busca el archivo
File f = new File(nombre);
Scanner informacionArchivo;
try {
//Encuentra el archivo y lo muestra
informacionArchivo = new Scanner(f);
while( informacionArchivo.hasNext()== true ) {
g.nombre = informacionArchivo.nextLine();
codigo = informacionArchivo.nextLine();
g.materia = informacionArchivo.nextLine();
nota = informacionArchivo.nextLine();
//Muestra lo que hay en el archivo buscado
txtMostrarInformacionArchivo.setText(g.nombre + "\n" + codigo +"\n"+ g.materia +"\n"+ nota);
}
informacionArchivo.close();
} catch (FileNotFoundException ex) {
//Si no encuentra el archivo muestra la excepcion
JOptionPane.showMessageDialog(null, "No se ha encontrado el archivo");
}
}
}//GEN-LAST:event_btnbuscarActionPerformed | 3 |
@Override
public List<T> findAll() throws DaoException {
waitCompete();
return new ArrayList<T>(getEntities().values());
} | 0 |
public void runUpdate(String sql) {
try {
stat.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(SQLHelper.class.getName()).log(Level.SEVERE, null, ex);
}
} | 1 |
private static boolean testPhylogenyBranch() {
try {
final PhylogenyNode a1 = new PhylogenyNode( "a" );
final PhylogenyNode b1 = new PhylogenyNode( "b" );
final PhylogenyBranch a1b1 = new PhylogenyBranch( a1, b1 );
final PhylogenyBranch b1a1 = new PhylogenyBranch( b1, a1 );
if ( !a1b1.equals( a1b1 ) ) {
return false;
}
if ( !a1b1.equals( b1a1 ) ) {
return false;
}
if ( !b1a1.equals( a1b1 ) ) {
return false;
}
final PhylogenyBranch a1_b1 = new PhylogenyBranch( a1, b1, true );
final PhylogenyBranch b1_a1 = new PhylogenyBranch( b1, a1, true );
final PhylogenyBranch a1_b1_ = new PhylogenyBranch( a1, b1, false );
if ( a1_b1.equals( b1_a1 ) ) {
return false;
}
if ( a1_b1.equals( a1_b1_ ) ) {
return false;
}
final PhylogenyBranch b1_a1_ = new PhylogenyBranch( b1, a1, false );
if ( !a1_b1.equals( b1_a1_ ) ) {
return false;
}
if ( a1_b1_.equals( b1_a1_ ) ) {
return false;
}
if ( !a1_b1_.equals( b1_a1 ) ) {
return false;
}
}
catch ( final Exception e ) {
e.printStackTrace( System.out );
return false;
}
return true;
} | 9 |
@Override
public boolean equals(Object o) {
if (o instanceof Triangle) {
Triangle t = (Triangle) o;
int[] sortedSelf = new int[] { v0, v1, v2 };
Arrays.sort(sortedSelf);
int[] sortedT = new int[] { t.v0, t.v1, t.v2 };
Arrays.sort(sortedT);
for (int i = 0; i < sortedSelf.length; i++) {
if (sortedSelf[i] != sortedT[i]) {
return false;
}
}
return true;
}
return super.equals(o);
} | 3 |
public Mp3Loader( String filePath ){
in = null;
valid = true;
try {
in = new FileInputStream( filePath );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int maxFrameCount = Integer.MAX_VALUE;
// int testing;
// maxFrameCount = 100;
//
stream = new Bitstream( in );
int error = 0;
int frame;
for (frame = 1; frame < maxFrameCount; frame++) {
// if (pause) {
// line.stop();
// while (pause && !stop) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// // ignore
// }
// }
// line.flush();
// line.start();
// }
try {
Header header = stream.readFrame();
if (header == null) {
break;
}
//if (decoder.channels == 0) {
int channels = (header.mode() == Header.MODE_SINGLE_CHANNEL) ? 1 : 2;
float sampleRate = header.frequency();
int sampleSize = 16;
audioFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, sampleRate,
sampleSize, channels, channels * (sampleSize / 8),
sampleRate, true);
// // big endian
// SourceDataLine.Info info = new DataLine.Info(
// SourceDataLine.class, format);
// line = (SourceDataLine) AudioSystem.getLine(info);
// if (BENCHMARK) {
// decoder.initOutputBuffer(null, channels);
// } else {
// decoder.initOutputBuffer(line, channels);
// }
// // TODO sometimes the line can not be opened (maybe not enough system resources?): display error message
// // System.out.println(line.getFormat().toString());
// line.open(format);
// line.start();
//}
// while (line.available() < 100) {
// Thread.yield();
// Thread.sleep(200);
// }
// decoder.decodeFrame(header, stream);
} catch (Exception e) {
System.out.println( e.toString() );
if (error++ > 1000) {
break;
}
// TODO should not write directly
System.out.println("Error at: " + " Frame: " + frame + " Error: " + e.toString());
// e.printStackTrace();
} finally {
stream.closeFrame();
}
}
frameCount = frame;
decoder = new Decoder();
stream = new Bitstream( in );
if (error > 0) {
System.out.println("errors: " + error);
}
} | 7 |
public void setNote(String note) {
this.note = note;
setDirty();
} | 0 |
public static final Ptg calculateFunction( Ptg[] ptgs ) throws FunctionNotSupportedException, CalculationException
{
// the function identifier
Ptg funk = ptgs[0];
int funkId = 0; //what function are we calling?
// if ptgs are missing parent_recs, populate from funk
XLSRecord bpar = funk.getParentRec();
if( bpar != null )
{
for( Ptg ptg : ptgs )
{
if( ptg.getParentRec() == null )
{
ptg.setParentRec( bpar );
}
}
}
int oplen = ptgs.length - 1;
// the ptgs acted upon by the function
Ptg[] operands = new Ptg[oplen];
System.arraycopy( ptgs, 1, operands, 0, oplen );
if( (funk.getOpcode() == 0x21) || (funk.getOpcode() == 0x41) || (funk.getOpcode() == 0x61) )
{ // ptgfunc
return calculatePtgFunc( funk, funkId, operands );
}
if( (funk.getOpcode() == 0x22) || (funk.getOpcode() == 0x42) || (funk.getOpcode() == 0x62) )
{ // ptgfuncvar
return calculatePtgFuncVar( funk, funkId, operands );
}
return null;
} | 9 |
@Override
public Map<String, ClassNode> load() throws IOException {
Map<String, ClassNode> classes = new HashMap<String, ClassNode>();
Enumeration<JarEntry> entries = jar.entries();
while(entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.endsWith(".class")) {
ClassNode node = new ClassNode();
ClassReader reader = new ClassReader(jar.getInputStream(entry));
reader.accept(node, ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
classes.put(node.name.replace(".class", ""), node);
} else {
if (name.contains("MANIFEST")) {
continue;
}
otherFiles.put(name, entry);
}
}
return classes;
} | 3 |
@Override
protected int analyzeRequestPOST(HttpServletRequest request) {
String timeString = request.getParameter("shutdown");
this.errors.clear();
if (timeString != null) {
// Ошибка пустого ввода
if (timeString.isEmpty()) {
this.errors.add("Empty Input");
return WRONG_INPUT;
}
try {
this.sleepBeforeShutdown = Integer.valueOf(timeString);
} catch (NumberFormatException e) {
// ошибка неправильного формата
this.errors.add("Wrong number format");
return WRONG_INPUT;
}
if (this.sleepBeforeShutdown < 0) {
// ошибка отрицательного ввода
this.errors.add("Negative number");
return WRONG_INPUT;
}
return REQ_SHUTDOWN;
}
return ENTRY;
} | 4 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String s = Double.toString(d);
if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
while (s.endsWith("0")) {
s = s.substring(0, s.length() - 1);
}
if (s.endsWith(".")) {
s = s.substring(0, s.length() - 1);
}
}
return s;
} | 7 |
public static List<String[]> readCSVFile(final String fileName, final String separator,
final int expectedColumns) {
final List<String[]> data = new ArrayList<String[]>();
FileReader fileReader = null;
BufferedReader in = null;
try {
final File file = new File(fileName);
if (!file.exists()) {
throw new IllegalArgumentException("File '" + fileName + "' does not exist");
}
fileReader = new FileReader(file);
in = new BufferedReader(fileReader);
String inputLine;
int lineNumber = 0;
inputLine = in.readLine();
while (inputLine != null) {
lineNumber++;
final String[] row = inputLine.split(separator);
if (expectedColumns == -1 || expectedColumns == row.length) {
data.add(row);
} else {
throw new AssertionError("Unexpected row length (line " + lineNumber + " ). "
+ "Expected:" + expectedColumns + " real " + row.length
+ ". CVS-file incorrectly formatted?");
}
inputLine = in.readLine();
}
} catch (final IOException i1) {
LOG.severe("Can't open file:" + fileName);
} finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
//ignore
}
}
}
return data;
} | 7 |
public Tuote haeKuljetusmaksu() throws DAOPoikkeus {
Tuote tuote = new Tuote();
// avataan yhteys
Connection yhteys = avaaYhteys();
try {
// Haetaan tietokannasta Kuljetusmaksu-niminen tuote
String kuljetusQuery = "select nimi, hinta, tuoteID from Tuote where nimi='Kuljetusmaksu'";
PreparedStatement haku = yhteys.prepareStatement(kuljetusQuery);
// Suoritetaan haku.
ResultSet tulos = haku.executeQuery();
while(tulos.next()) {
String nimi = tulos.getString("nimi");
double hinta = tulos.getDouble("hinta");
int tuoteId = tulos.getInt("tuoteID");
tuote = new Tuote(tuoteId, nimi, hinta);
}
} catch(Exception e) {
// Tapahtui jokin virhe?
throw new DAOPoikkeus("Tietokantahaku aiheutti virheen.", e);
} finally {
// Lopulta aina suljetaan yhteys!
suljeYhteys(yhteys);
}
return tuote;
} | 2 |
private void calculateVelocities() {
double r1 = Math.random();
double r2 = Math.random();
for(int i = 0; i < position.length; i++){
double[]cognitive = calculateCognitiveVelocity(i, r1);
double[]social = calculateSocialVelocity(i, r2);
for(int k = 0; k < position[i].length; k++){
velocities[i][k] = velocities[i][k] + cognitive[k] + social[k];
}
}
} | 2 |
public void remove(int wearID, int slot) {
if(addItem(playerEquipment[slot], playerEquipmentN[slot])) {
if(wearID == 6070) {
npcId = 0;
isNpc = false;
updateRequired = true;
appearanceUpdateRequired = true;
}
resetItems(3214); // THIS MIGHT STOP CLIENT HACKS HMM?
playerEquipment[slot] = -1;
playerEquipmentN[slot] = 0;
outStream.createFrame(34);
outStream.writeWord(6);
outStream.writeWord(1688);
outStream.writeByte(slot);
outStream.writeWord(0);
outStream.writeByte(0);
ResetBonus();
GetBonus();
WriteBonus();
if (slot == playerWeapon) {
SendWeapon(-1, "Unarmed");
}
SendWeapon((playerEquipment[playerWeapon]), GetItemName(playerEquipment[playerWeapon]));
updateRequired = true; appearanceUpdateRequired = true;
}
} | 3 |
public void findPath() {
chooser = new JFileChooser();
if(gamePath!= null) chooser.setCurrentDirectory(new java.io.File(gamePath));
else chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
con.log("Log","getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
con.log("Log","getSelectedFile() : "
+ chooser.getSelectedFile());
gamePath=""+chooser.getSelectedFile();
if(gamePath.endsWith("/mods")) {gamePath = gamePath.replace("/mods", "");}
con.log("Log",gamePath);
txtGamePath.setText(gamePath);
validatePath();
checkAccess();
getMods();
writeData();
}
else {
con.log("Log","No Selection ");
}
} | 3 |
public void actionPerformed(ActionEvent event) {
Component source = null;
lastFileOpened = false;
try {
source = (Component) event.getSource();
} catch (Throwable e) {
// Might not be a component, or the event may be null.
// Who cares.
}
// Apple is so stupid.
File tempFile = fileChooser.getCurrentDirectory();
fileChooser.setCurrentDirectory(tempFile.getParentFile());
fileChooser.setCurrentDirectory(tempFile);
fileChooser.rescanCurrentDirectory();
fileChooser.setMultiSelectionEnabled(true);
Codec[] codecs = null;
codecs = makeFilters();
// Open the dialog.
int result = fileChooser.showOpenDialog(source);
if (result != JFileChooser.APPROVE_OPTION)
return;
File[] files = fileChooser.getSelectedFiles();
for(int k = 0; k < files.length; k++){
File file = files[k];
if (!openOrRead) {
// Is this file already open?
if (Universe.frameForFile(file) != null) {
Universe.frameForFile(file).toFront();
return;
}
}
try {
openFile(file, codecs);
} catch (ParseException e) {
JOptionPane.showMessageDialog(source, e.getMessage(), "Read Error",
JOptionPane.ERROR_MESSAGE);
} catch (DataException e) {
JOptionPane.showMessageDialog(source, e.getMessage(), "Data Error",
JOptionPane.ERROR_MESSAGE);
}
}
Universe.CHOOSER.resetChoosableFileFilters();
lastFileOpened = true;
} | 7 |
public static boolean accept(AbstractSyntaxNode node, TokenReader reader)
{
boolean result = false;
if (Number.accept(node, reader) || FunctionCall.accept(node, reader)
|| Identifier.accept(node, reader))
{
result = true;
}
else if (reader.accept(Token.OPEN_PAREN))
{
Expression.accept(node, reader);
reader.expect(Token.CLOSE_PAREN, "factor block end");
result = true;
}
else if (MemGet.accept(node, reader))
{
result = true;
}
return result;
} | 5 |
public int process(int signal) throws MaltChainedException {
if (cachedGraph == null) {
marking_strategy = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "marking_strategy").toString().trim();
covered_root = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "covered_root").toString().trim();
lifting_order = OptionManager.instance().getOptionValue(getOptionContainerIndex(), "pproj", "lifting_order").toString().trim();
cachedGraph = (TokenStructure)flowChartinstance.getFlowChartRegistry(org.maltparser.core.syntaxgraph.TokenStructure.class, sourceName);
if (!marking_strategy.equalsIgnoreCase("none") || !covered_root.equalsIgnoreCase("none")) {
pprojActive = true;
}
}
if (pprojActive && cachedGraph instanceof DependencyStructure) {
if (taskName.equals("proj")) {
pproj.projectivize((DependencyStructure)cachedGraph);
} else if (taskName.equals("merge")) {
pproj.mergeArclabels((DependencyStructure)cachedGraph);
} else if (taskName.equals("deproj")) {
pproj.deprojectivize((DependencyStructure)cachedGraph);
} else if (taskName.equals("split")) {
pproj.splitArclabels((DependencyStructure)cachedGraph);
}
}
return signal;
} | 9 |
private void buttonSearchActionPerformed(ActionEvent pEvent) {
TableViewAdapter adapter = (TableViewAdapter) getModel();
List selection = getSelectedRowObjects();
if ("".equals(mTextFieldSearchTest.getText())) {
adapter.search(mCurrentCollumn, null);
}
else {
adapter.search(mCurrentCollumn, mTextFieldSearchTest.getText());
}
for (Iterator i = selection.iterator(); i.hasNext();) {
addRowSelection(i.next(), true);
}
if (getSelectedRowObjects().size() == 0 && getModel().getRowCount() > 0) {
addRowSelectionInterval(0, 0);
scrollRectToVisible(this.getCellRect(0, 0, true));
}
getTableHeader().repaint();
mDialogSearch.setVisible(false);
} | 4 |
public void paintComponent(Graphics g) {
if (isLocked)
return;
isLocked = true;
//g.setColor(Color.black);
//g.fillRect(0,0,DynamicConstants.WND_WDTH,DynamicConstants.WND_HGHT);
if (game != null) {
if (isWaving) {
PavoImage buffer = game.getBuffer();
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
ss += 1.2;
PavoImage buffer2 = new PavoImage(buffer.getWidth(),buffer.getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics m = buffer2.getGraphics();
m.setColor(Color.black);
m.fillRect(0,0,getWidth(),getHeight());
for (int c = 0; c < buffer.getWidth(); c++) {
int wh = (int)(Math.sin(ss+(c/8.0))*10);
for (int y = 0; y < buffer.getHeight(); y++) {
m.setColor(new Color(buffer.getRGB(c, y)));
m.fillRect(c,y+wh,1,1);
}
}
m.dispose();
g.drawImage(buffer2,0,0,null);
}
else {
g.drawImage(game.getBuffer(),0,0,null);
}
}
else {
g.setColor(Color.red);
g.fillRect(0,0,getWidth(),getHeight());
}
if (notifier != null)
g.drawImage(notifier,(Game.Settings.currentWidth/2)-(notifier.getWidth()/2),
(Game.Settings.currentHeight/2)-(notifier.getHeight()/2),null);
isLocked = false;
} | 6 |
public IndexedModel toIndexedModel(){
IndexedModel result = new IndexedModel();
IndexedModel normalModel = new IndexedModel();
HashMap<OBJIndex, Integer> resultIndexMap = new HashMap<>();
HashMap<Integer, Integer> normalIndexMap = new HashMap<>();
HashMap<Integer, Integer> indexMap = new HashMap<>();
for(int i=0; i<indices.size(); i++){
OBJIndex currentIndex = indices.get(i);
Vector3d currentPosition = positions.get(currentIndex.vertexIndex);
Vector2d currentTexCoord;
Vector3d currentNormal;
if(hasTexCoords)
currentTexCoord = texCoords.get(currentIndex.texCoordIndex);
else
currentTexCoord = new Vector2d(0,0);
if(hasNormals)
currentNormal = normals.get(currentIndex.normalIndex);
else
currentNormal = new Vector3d(0,0,0);
// Mesh optimisation (re-using vertices):
Integer modelVertexIndex = resultIndexMap.get(currentIndex);
if(modelVertexIndex == null){
// result.getPositions().size() acts as counter variable:
modelVertexIndex = result.getPositions().size();
resultIndexMap.put(currentIndex, result.getPositions().size());
result.getPositions().add(currentPosition);
result.getTexCoords().add(currentTexCoord);
if(hasNormals)
result.getNormals().add(currentNormal);
}
Integer normalModelIndex = normalIndexMap.get(currentIndex.vertexIndex);
if(normalModelIndex==null){
// normalModel.getPositions().size() acts as counter variable:
normalModelIndex = normalModel.getPositions().size();
normalIndexMap.put(currentIndex.vertexIndex, normalModel.getPositions().size());
normalModel.getPositions().add(currentPosition);
normalModel.getTexCoords().add(currentTexCoord);
normalModel.getNormals().add(currentNormal);
}
result.getIndices().add(modelVertexIndex);
normalModel.getIndices().add(normalModelIndex);
indexMap.put(modelVertexIndex, normalModelIndex);
}
if(!hasNormals){
normalModel.calculateNormals();
for(int i=0; i<result.getPositions().size(); i++)
result.getNormals().add(normalModel.getNormals().get(indexMap.get(i)));
//result.getNormals().get(i).set(normalModel.getNormals().get(indexMap.get(i)));
}
return result;
} | 8 |
int[] getRowGaps(ContainerWrapper parent,
BoundSize defGap, int refSize, boolean before) {
BoundSize gap = before ? gapBefore : gapAfter;
if (gap == null || gap.isUnset()) {
gap = defGap;
}
if (gap == null || gap.isUnset()) {
return null;
}
int[] ret = new int[3];
for (int i = LayoutUtil.MIN; i <= LayoutUtil.MAX;
i++) {
UnitValue uv = gap.getSize(i);
ret[i] =uv != null ? uv.getPixels(refSize, parent, null)
: LayoutUtil.NOT_SET;
}
return ret;
} | 7 |
public AnnotationVisitor visitAnnotation(final String name,
final String desc) {
if (name != null) {
cp.newUTF8(name);
}
cp.newUTF8(desc);
return new AnnotationConstantsCollector(av.visitAnnotation(name, desc),
cp);
} | 1 |
public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
} | 4 |
public void visitFieldExpr(final FieldExpr expr) {
expr.visitChildren(this);
genPostponed(expr);
if (expr.isDef()) {
boolean UC = false; // Do we need an UC?
// Look at the FieldExpr's object for a UCExpr
Node check = expr.object();
while (check instanceof CheckExpr) {
if (check instanceof UCExpr) {
UC = true;
break;
}
final CheckExpr c = (CheckExpr) check;
check = c.expr();
}
// Do we need to perform the write barrier?
if (!UC && CodeGenerator.USE_PERSISTENT) {
/*
* System.out.println("Emitting a putfield_nowb in " +
* this.method.declaringClass().classInfo().name() + "." +
* this.method.name());
*/
nowb = true;
// I commented out the next line because it generated a compiler
// error, and I figured it was just about some unimportant
// persistance stuff --Tom
// method.addInstruction(opcx_putfield_nowb, expr.field());
} else {
method.addInstruction(Opcode.opcx_putfield, expr.field());
}
stackHeight -= 1; // object
stackHeight -= expr.type().stackHeight();
} else {
method.addInstruction(Opcode.opcx_getfield, expr.field());
stackHeight -= 1; // pop object
stackHeight += expr.type().stackHeight();
}
} | 5 |
@Override
public List<Customer> getByName(String name) {
List<Customer> found = new ArrayList<>();
for (Customer c : findRange(0, count())) {
if (c.getFname().equals(name) || c.getLname().equals(name)) {
found.add(c);
}
}
return found;
} | 3 |
public static void main(String[] args) throws Exception
{
HashSet<String> set = getNamesWithCaseControl();
BufferedReader reader = new BufferedReader(new FileReader(
new File(
"C:\\Users\\corei7\\git\\metagenomicsTools\\src\\gamlssDemo\\genusPivotedTaxaAsColumnsNorm.txt")));
BufferedWriter writer = new BufferedWriter(new FileWriter(
new File("C:\\Users\\corei7\\git\\metagenomicsTools\\src\\gamlssDemo\\genusPivotedTaxaAsColumnsNormCaseContol.txt")));
writer.write(reader.readLine() + "\n");
for(String s= reader.readLine(); s != null ; s= reader.readLine())
{
String[] splits = s.split("\t");
String key = splits[0].replace("Tope_", "").replace(".fas", "");
if( set.contains(key+"case"))
{
writer.write(key+"case");
set.remove(key + "case");
}
else if (set.contains(key+"control") )
{
writer.write(key+"control");
set.remove(key + "control");
}
for( int x=1; x < splits.length; x++)
writer.write("\t" + splits[x]);
writer.write("\n");
}
for(String s : set )
System.out.println(s);
if( ! set.isEmpty())
throw new Exception("No " + set.size());
writer.flush(); writer.close();
} | 6 |
public Liste getListe() {
return liste;
} | 0 |
@Override
public void huolehdi(){
int maxXnopeus = Math.max((int) h1.getVaakaNopeus(), (int) h2.getVaakaNopeus());
int maxYnopeus = Math.max((int) h1.getPystyNopeus(), (int) h2.getPystyNopeus());
int maxNopeus = Math.max(maxXnopeus, maxYnopeus);
int maxNopeusVarmistettu = Math.max(1, maxNopeus);
int n = maxNopeusVarmistettu;
if (!h1.getSuojakilpi() && !h2.getSuojakilpi()){
for (int i=0; i<4; i++){
for (int j=0; j<4; j++){
leikkaaJosLeikkaavat(i, j, n);
}
}
}
} | 4 |
@SuppressWarnings("static-access")
private void ROUND1() {
System.out.println("Round1:)))))");
for (int i = 0; i < level.getWidth(); i++) {
for (int j = 0; j < level.getHeight(); j++) {
if ((level.getPixel(i, j) & 0x0000FF) == 128) {
Transform monsterTransform = new Transform();
monsterTransform.setTranslation((i + 0.5f) * Game.getLevel().SPOT_WIDTH, 0.4375f, (j + 0.5f) * Game.getLevel().SPOT_LENGTH);
enemises.add(new Enemies(monsterTransform));
}
}
}
} | 3 |
public static void main(String[] args) {
OptionBuilder.withArgName("Service");
OptionBuilder.hasArg();
OptionBuilder.withDescription("Service type Exchange (MX) or Vault (DX)");
Option numRecs = OptionBuilder.create("s");
Options options = new Options();
options.addOption(numRecs);
CommandLineParser parser = new PosixParser();
try {
CommandLine line = parser.parse( options, args);
if(line.hasOption("s"))
{
Service = line.getOptionValue('s');
}
else
{
Quit(options);
}
}
catch (ParseException e)
{
System.out.println("Parse Exception : " + e.getMessage());
}
Properties properties = new Properties();
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is;
try {
is = new FileInputStream("xio.properties");
try {
properties.load(is);
is.close();
} catch (IOException ioe) {
System.out.print(ioe.getMessage());
}
catch (Exception e){
System.out.print(e.getMessage());
}
VaultUserFolder= properties.getProperty("VaultUserFolder");
xioFolder = properties.getProperty("xioFolder");
// Added 24 Sept 2014
// First make sure the xio folder structure is in place
new File(xioFolder + "/loaded").mkdirs();
new File(xioFolder + "/send").mkdirs();
new File(xioFolder + "/sent").mkdirs();
new File(VaultUserFolder).mkdirs();
} catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
}
helper = new DatabaseHelper();
filesToProcess = listFilesForFolder(xioFolder + "/sent");
if(filesToProcess.isEmpty())
{
System.out.println("No Files to process");
}
else
{
for(Path p : filesToProcess)
{
try {
processInputFile(p);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
} | 8 |
public void dumpSource(TabbedPrintWriter writer) throws java.io.IOException {
if (predecessors.size() != 0) {
writer.untab();
writer.println(getLabel() + ":");
writer.tab();
}
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
writer.println("in: " + in);
}
block.dumpSource(writer);
if ((GlobalOptions.debuggingFlags & GlobalOptions.DEBUG_INOUT) != 0) {
Iterator iter = successors.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
FlowBlock dest = (FlowBlock) entry.getKey();
SuccessorInfo info = (SuccessorInfo) entry.getValue();
writer.println("successor: " + dest.getLabel() + " gen : "
+ info.gen + " kill: " + info.kill);
}
}
if (nextByAddr != null)
nextByAddr.dumpSource(writer);
} | 5 |
public void undo() {
if (!undo.empty()) {
ArrayList<Delta> toUndo = undo.pop();
for (Delta d : toUndo) {
d.undo(colorArr);
}
redo.push(toUndo);
}
} | 2 |
public boolean printCluster2(StringBuilder sb, Collection<Line> lines, StringBounder stringBounder) {
// Log.println("Cluster::printCluster " + this);
final Set<String> rankSame = new HashSet<String>();
for (Line l : lines) {
if (l.hasEntryPoint()) {
continue;
}
final String startUid = l.getStartUid();
final String endUid = l.getEndUid();
if (isInCluster(startUid) && isInCluster(endUid)) {
final String same = l.rankSame();
if (same != null) {
rankSame.add(same);
}
}
}
boolean added = false;
for (Shape sh : getShapesOrderedWithoutTop(lines)) {
sh.appendShape(sb);
added = true;
}
for (String same : rankSame) {
sb.append(same);
SvekUtils.println(sb);
}
for (Cluster child : getChildren()) {
child.printInternal(sb, lines, stringBounder);
}
return added;
} | 8 |
private int getLength () {
// the size of all the table directory entries
int length = 12 + (getNumTables () * 16);
// for each directory entry, get the size,
// and don't forget the padding!
for (Iterator i = tables.values ().iterator (); i.hasNext ();) {
Object tableObj = i.next ();
// add the length of the entry
if (tableObj instanceof TrueTypeTable) {
length += ((TrueTypeTable) tableObj).getLength ();
} else {
length += ((ByteBuffer) tableObj).remaining ();
}
// pad
if ((length % 4) != 0) {
length += (4 - (length % 4));
}
}
return length;
} | 3 |
@Override
public void onAudioSamples(IAudioSamplesEvent event) {
IAudioSamples samples = event.getAudioSamples();
for (int i = 0; i < samples.getNumSamples(); ++i) {
int index = (int) (event.getTimeStamp(TimeUnit.SECONDS) / granularity);
int amplitude = samples.getSample(i, 0, IAudioSamples.Format.FMT_S16);
if (maxes.get(index) < amplitude) {
maxes.set(index, amplitude);
}
}
super.onAudioSamples(event);
} | 2 |
public void setUniversity(String university) {
this.university = university;
} | 0 |
public boolean onCommand(CommandSender s, Command cmd, String commandLabel, String[] args){
Player player = (Player) s;
if (cmd.getName().equalsIgnoreCase("psetwarp")){
if (args.length == 1){
World cWorld = player.getWorld();
String warpName = args[0].toLowerCase();
WarpConfig.reloadWarpConfig(player.getName().toLowerCase());
if (WarpConfig.getWarpConfig(player.getName().toLowerCase()).getString(warpName) == null){
if (s.hasPermission("PrivateWarps.unlimited")){
double xLoc = player.getLocation().getX();
double yLoc = player.getLocation().getY();
double zLoc = player.getLocation().getZ();
float yaw = player.getLocation().getYaw();
float pitch = player.getLocation().getPitch();
int count = WarpConfig.getWarpConfig(player.getName().toLowerCase()).getInt("count");
count++;
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".x", xLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".y", yLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".z", zLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".yaw", yaw);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".pitch", pitch);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".world", player.getWorld().getName());
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set("count", count);
WarpConfig.saveWarpConfig(player.getName().toLowerCase());
WarpConfig.reloadWarpConfig(player.getName().toLowerCase());
player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GREEN + "PrivateWarps" + ChatColor.AQUA + "]" + ChatColor.WHITE + " Warp: " + warpName + " has ben set!");
}else{
WarpConfig.reloadWarpConfig(player.getName().toLowerCase());
int maxcount = PrivateWarps.pluginST.getConfig().getInt("PrivateWarps.Warps.Maximum-Allowed-Warps");
if (WarpConfig.getWarpConfig(player.getName().toLowerCase()).getInt("count") == maxcount || WarpConfig.getWarpConfig(player.getName()).getInt("count") > maxcount){
player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GREEN + "PrivateWarps" + ChatColor.AQUA + "]" + ChatColor.WHITE + " You have reached the maximum allowed warps!");
}else{
double xLoc = player.getLocation().getX();
double yLoc = player.getLocation().getY();
double zLoc = player.getLocation().getZ();
float yaw = player.getLocation().getYaw();
float pitch = player.getLocation().getPitch();
WarpConfig.reloadWarpConfig(player.getName().toLowerCase());
int count = WarpConfig.getWarpConfig(player.getName().toLowerCase()).getInt("count");
count++;
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".x", xLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".y", yLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".z", zLoc);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".yaw", yaw);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".pitch", pitch);
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set(warpName + ".world", player.getWorld().getName());
WarpConfig.getWarpConfig(player.getName().toLowerCase()).set("count", count);
WarpConfig.saveWarpConfig(player.getName().toLowerCase());
WarpConfig.reloadWarpConfig(player.getName().toLowerCase());
player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GREEN + "PrivateWarps" + ChatColor.AQUA + "]" + ChatColor.WHITE + " Warp: " + warpName + " has ben set!");
}
}
}else{
player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GREEN + "PrivateWarps" + ChatColor.AQUA + "]" + ChatColor.WHITE + " Warp: " + warpName + " already exist! Delete it first.");
}
}else{
player.sendMessage(ChatColor.AQUA + "[" + ChatColor.GREEN + "PrivateWarps" + ChatColor.AQUA + "]" + ChatColor.WHITE + " Usage: /psetwarp WarpName");
}
}
return true;
} | 6 |
public void writeNonTerminal(NonTerminalNode nt, String id) throws MaltChainedException {
try {
writer.write(" <nt");
writer.write(" id=\"");writer.write(id);writer.write("\" ");
for (ColumnDescription column : dataFormatInstance.getPhraseStructureNodeLabelColumnDescriptionSet()) {
if (nt.hasLabel(column.getSymbolTable())) {
writer.write(column.getName().toLowerCase());
writer.write("=");
writer.write("\"");
writer.write(Util.xmlEscape(nt.getLabelSymbol(column.getSymbolTable())));
writer.write("\" ");
}
}
writer.write(">\n");
for (int i = 0, n = nt.nChildren(); i < n; i++) {
PhraseStructureNode child = nt.getChild(i);
writer.write(" <edge ");
for (ColumnDescription column : dataFormatInstance.getPhraseStructureEdgeLabelColumnDescriptionSet()) {
if (child.hasParentEdgeLabel(column.getSymbolTable())) {
writer.write(column.getName().toLowerCase());
writer.write("=\"");
writer.write(Util.xmlEscape(child.getParentEdgeLabelSymbol(column.getSymbolTable())));
writer.write("\" ");
}
}
if (child instanceof TokenNode) {
if (!labeledTerminalID) {
tmpID.setLength(0);
tmpID.append(sentenceID);
tmpID.append('_');
tmpID.append(Integer.toString(child.getIndex()));
writer.write(" idref=\"");writer.write(tmpID.toString());writer.write("\"");
} else {
writer.write(" idref=\"");writer.write(child.getLabelSymbol(dataFormatInstance.getInputSymbolTables().get("ID")));writer.write("\"");
}
} else {
tmpID.setLength(0);
tmpID.append(sentenceID);
tmpID.append('_');
tmpID.append(Integer.toString(child.getIndex()+START_ID_OF_NONTERMINALS-1));
writer.write(" idref=\"");writer.write(tmpID.toString());writer.write("\"");
}
writer.write(" />\n");
}
writer.write(" </nt>\n");
} catch (IOException e) {
throw new DataFormatException("The TigerXML writer is not able to write. ", e);
}
} | 8 |
private static void infect(Organism o1, Organism o2) {
if ((o1.timeSick < 0 && o2.timeSick < 0) || (o1.timeSick > -1 && o2.timeSick > -1)) {
return;
}
if (o1.timeSick > -1 && o2.timeSick < DISEASE_RECURANCE_TIME) {
o2.timeSick = o1.random.nextDouble() < o1.diseaseVirulence ? 0 : -1;
} else if (o1.timeSick < DISEASE_RECURANCE_TIME) {
o1.timeSick = o2.random.nextDouble() < o2.diseaseVirulence ? 0 : -1;
}
} | 9 |
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
sender.sendMessage(new TextComponent(ChatColor.RED + "Usage: /pmreply <message ...>"));
return;
}
if (!IRC.sock.isConnected()) {
sender.sendMessage(new TextComponent(ChatColor.RED + "The proxy is not connected to IRC."));
return;
}
if (!IRC.replies.containsKey(sender)) {
sender.sendMessage(new TextComponent(ChatColor.RED + "You must be engaged within a conversation to use this."));
return;
}
String to = IRC.replies.get(sender);
String uid = Util.getUidByNick(to);
if (uid == null) {
sender.sendMessage(new TextComponent(ChatColor.RED + to + " is no longer on IRC."));
return;
}
StringBuilder msg = new StringBuilder();
for (String a : args) msg.append(a).append(" ");
IRC.out.println(":" + IRC.uids.get(sender) + " PRIVMSG " + uid + " :" + msg);
sender.sendMessage(new TextComponent(ChatColor.translateAlternateColorCodes('&', BungeeRelay.getConfig().getString("formats.privatemsg")
.replace("{SENDER}", sender.getName())
.replace("{MESSAGE}", msg.toString().trim()))));
} | 5 |
public static String getSuffix(IrcUser u)
{
System.out.println("getsuffix");//debug
for(String s : Suffixes)
{
System.out.println("suffixindb - " + s);//debug
String[] split = s.split(" ");
if(u.getSource().equalsIgnoreCase(split[0])) return split[1].replaceAll("&", "§");
else{//debug
System.out.println("getsuffix - no match");
System.out.println(s);
System.out.println(u.getSource());
}
}
return DefaultSuffix.replaceAll("&", "§");
} | 2 |
public void setEnabled(Boolean isEnabled) {
enabled = isEnabled;
if(enabled) {
rescheduleAlarm();
} else {
scheduledTask.cancel();
}
} | 1 |
@SuppressWarnings({ "unchecked", "rawtypes" })
private Object unmarshalClass(Class reflector, Node node)
throws InstantiationException, IllegalAccessException,
InvocationTargetException {
Constructor cons = null;
try {
cons = reflector.getConstructor((Class[]) null);
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
return null;
}
Object o = cons.newInstance((Object[]) null);
Node n;
Method[] methods = reflector.getMethods();
NamedNodeMap nnm = node.getAttributes();
if (nnm != null) {
for (int i = 0; i < nnm.getLength(); i++) {
n = nnm.item(i);
try {
int j = reflectFindMethodByName(reflector,
"set" + n.getNodeName());
if (j >= 0) {
reflectInvokeMethod(o,methods[j],
new String [] {n.getNodeValue()});
} else {
System.out.println("Unsupported attribute '" +
n.getNodeName() + "' on <" +
node.getNodeName() + "> tag");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return o;
} | 6 |
public Object getCellValue(HSSFCell cell) {
Object o = null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
o = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_STRING:
o = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
o = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
o = cell.getCellFormula();
break;
default:
break;
}
return o;
} | 4 |
public BigDecimal[] subtractMean_as_BigDecimal() {
BigDecimal[] arrayminus = new BigDecimal[length];
switch (type) {
case 1:
case 12:
BigDecimal meanb = this.mean_as_BigDecimal();
ArrayMaths amb = this.minus(meanb);
arrayminus = amb.getArray_as_BigDecimal();
meanb = null;
break;
case 14:
throw new IllegalArgumentException("Complex cannot be converted to BigDecimal");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
return arrayminus;
} | 3 |
public static void main(String[] args){
PropertyConfigurator.configure("rc\\log4j.properties");
Date d = new Date();
// Get config file
logger.info("");
logger.info("=========================================================================");
logger.info("------------------------------------------------------------------------");
logger.info("");
Constant.write2Log(":::::: Execution started at: " + d.toString());
logger.info("");
logger.info("------------------------------------------------------------------------");
configData.doReadConfig("conf.xml");
try {
// Connect to FTP
ConnectFTP connFTP=new ConnectFTP();
if (args.length == 0 || args[0].compareTo("import") == 0) {
if (connFTP.connectAndDownload()) {
Constant.write2Log("\nDownloaded file from FTP server successfully ...");
ReadCSV readCSV=new ReadCSV();
if (readCSV.getCSVFiles()){
Constant.write2Log("\nStart to process data from the CSV file into the Exos9300 database......");
readCSV.processCSV2DB();
} else {
Constant.write2LogError("Cannot read file or no data to be processed");
}
}
} else if (args[0].compareTo("export") == 0) {
if (args.length == 2) {
try {
int month = Integer.parseInt(args[1]);
configData.setMonth(month);
} catch (Exception e) {
}
}
if (connFTP.connectAndUpload()) {
Constant.write2Log("\nUpload file to FTP server successfully ...");
} else {
Constant.write2LogError("\nError while uploading file to FTP server ...");
}
}
} catch (Exception e) {
Constant.write2Log("An error occurred during the execution of Exos9300 Import CSV." + e);
}
d = new Date();
logger.info("------------------------------------------------------------------------");
logger.info("");
Constant.write2Log(":::::: Execution finished at: " + d.toString());
logger.info("");
logger.info("------------------------------------------------------------------------");
logger.info("=========================================================================");
logger.info("");
} | 9 |
public static Rule parseTableChanges(Rule rule, TableItem[] items) {
if (!items[1].getText(1).isEmpty())
rule.setDl_src(items[1].getText(1));
if (!items[2].getText(1).isEmpty())
rule.setDl_dst(items[2].getText(1));
if (!items[3].getText(1).isEmpty())
rule.setDl_type(items[3].getText(1));
if (!items[4].getText(1).isEmpty())
rule.setSrcIP(items[4].getText(1));
if (!items[5].getText(1).isEmpty())
rule.setDstIP(items[5].getText(1));
if (!items[6].getText(1).isEmpty())
rule.setNw_proto(items[6].getText(1));
if (!items[7].getText(1).isEmpty())
rule.setTp_src(items[7].getText(1));
if (!items[8].getText(1).isEmpty())
rule.setTp_dst(items[8].getText(1));
return rule;
} | 8 |
final public void Uop() throws ParseException {/*@bgen(jjtree) Uop */
SimpleNode jjtn000 = (SimpleNode)SimpleNode.jjtCreate(this, JJTUOP);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);Token t;
try {
switch ((jj_ntk==-1)?jj_ntk_f():jj_ntk) {
case FST:{
t = jj_consume_token(FST);
break;
}
case SND:{
t = jj_consume_token(SND);
break;
}
case HEAD:{
t = jj_consume_token(HEAD);
break;
}
case TAIL:{
t = jj_consume_token(TAIL);
break;
}
case LANG:{
t = jj_consume_token(LANG);
break;
}
case NOT:{
t = jj_consume_token(NOT);
break;
}
default:
jj_la1[13] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
jjtn000.jjtSetValue(t);
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
} | 8 |
public String getBestLink(int[] seedArray, int[] leechArray, String mediaType){
/*
* Determines the best link to pull the torrent from.
*/
float sizeMinimum;
float sizeMaximum;
if (mediaType.toLowerCase().equals("movie") || mediaType.toLowerCase().equals("movies")){
sizeMinimum = Variables.movieSizeMin;
sizeMaximum = Variables.movieSizeMax;
}
else if (mediaType.toLowerCase().equals("album") || mediaType.toLowerCase().equals("albums")){
sizeMinimum = Variables.albumSizeMin;
sizeMaximum = Variables.albumSizeMax;
}
else{
sizeMinimum = Variables.musicSizeMin;
sizeMaximum = Variables.musicSizeMax;
}
try{
String bestChoice = null;
int greatestDifference = 0;
for (int i = 0; i < seedArray.length; i++){
if (sizeArray[i] > sizeMinimum && sizeArray[i] < sizeMaximum){
if (seedArray[i] - leechArray[i] > greatestDifference){
greatestDifference = seedArray[i] - leechArray[i];
bestChoice = linkArray[i];
}
}
}
return bestChoice;
}catch (Exception e){
return null;
}
} | 9 |
public static String doPost(String urlString,
Map<String, String> nameValuePairs) throws IOException {
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
boolean first = true;
for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
if (first)
first = false;
else
out.print('&');
String name = pair.getKey();
String value = pair.getValue();
out.print(name);
out.print('=');
out.print(URLEncoder.encode(value, "UTF-8"));
}
out.close();
Scanner in;
StringBuilder response = new StringBuilder();
try {
in = new Scanner(connection.getInputStream());
} catch (IOException e) {
if (!(connection instanceof HttpURLConnection))
throw e;
InputStream err = ((HttpURLConnection) connection).getErrorStream();
if (err == null)
throw e;
in = new Scanner(err);
}
while (in.hasNextLine()) {
response.append(in.nextLine());
response.append("\n");
}
in.close();
return response.toString();
} | 6 |
private void openDialog(){
JFileChooser fileOpen = new JFileChooser("./");
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Algorythm workspace files .wks", "wks");
fileOpen.setFileFilter(filter);
int ret = fileOpen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
openingFile = fileOpen.getSelectedFile();
if(openWorkspace(openingFile))
JOptionPane.showMessageDialog(this, "File open!", "Open file",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(this, "Open filed!", "Open file",JOptionPane.ERROR_MESSAGE);
}
} | 2 |
public String[] getOptions() {
Vector result;
String[] options;
int i;
result = new Vector();
if (getDebug())
result.add("-D");
if (getSilent())
result.add("-S");
result.add("-N");
result.add("" + getNumInstances());
if (getEstimator() != null) {
result.add("-W");
result.add(getEstimator().getClass().getName());
}
if ((m_Estimator != null) && (m_Estimator instanceof OptionHandler))
options = ((OptionHandler) m_Estimator).getOptions();
else
options = new String[0];
if (options.length > 0) {
result.add("--");
for (i = 0; i < options.length; i++)
result.add(options[i]);
}
return (String[]) result.toArray(new String[result.size()]);
} | 7 |
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals(TRANSACTIONS_ELEMENT)) {
parentElement = ROOT_ELEMENT;
}
if (currentElement.equals("transaction")) {
xmlTransaction.append("</" + qName + ">");
}
if (qName.equals("transaction")) {
try {
Transaction transaction = TransactionParser.readTransaction(new ByteArrayInputStream(xmlTransaction
.toString().getBytes()));
TransactionSummary transactionSummary = buildTransactionSummary(transaction);
transactions.add(transactionSummary);
} catch (ParserConfigurationException e) {
throw new SAXException(e);
} catch (ParseException e) {
throw new SAXException(e);
} catch (IOException e) {
throw new SAXException(e);
}
}
} | 6 |
@Override
public boolean placeResearvation(int rowNum, Column column, Passenger passenger) throws ClassCastException, IndexOutOfBoundsException, IllegalArgumentException, NullPointerException {
if (!isInitialized) {
throw new NullPointerException("Passenger List has not been initialized");
}
if (rowNum < 0 || rowNum > passengerList.size()) {
throw new IndexOutOfBoundsException("The row# is out of bound");
}
if (column.index() < 0 || column.index() > passengerList.get(0).size()) {
throw new IndexOutOfBoundsException("The column# is out of bound");
}
List<Passenger> _passenger = passengerList.get(rowNum -1);
if (_passenger.get(column.index() -1) == null) {
_passenger.set(column.index() -1, passenger);
return true;
}else{
throw new IllegalArgumentException("A passenger is already in the list");
}
} | 6 |
public void setFilter(String filter){
if (captor != null)
try {
captor.setFilter(filter, true);
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
public void act()
{
// Add your action code here.
try {
if ( null != co ){
m = new Message("Check coin");
getWorld().addObject(m , getX(), getY());
Greenfoot.delay(delay);
getWorld().removeObject(m);
if ( co.isReal){
m = new Message("Coin is real");
getWorld().addObject(m , getX(), getY() );
Greenfoot.delay(delay);
getWorld().removeObject(m);
if ( co.getValue() == 25 ) {
m = new Message( "Thanks! Here is your gumball!");
getWorld().addObject( m , getX(), getY() );
if(Greenfoot.getRandomNumber(2) == 1){
gp.ejectGumball();
}else {
rp.ejectGumball();
}
Greenfoot.delay(100);
}else{
m = new Message( "Coin is less than quarter! Bye!" );
getWorld().addObject( m , getX(), getY() );
}
}else{
m = new Message( "Coin is fake! Bye!" );
getWorld().addObject( m , getX(), getY() );
}
co = null;
}
} catch ( Exception e ){
e.printStackTrace();
m = new Message( "Something is Wrong");
getWorld().addObject( m , getX(), getY() );
}
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.