text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void renderPlayerInventory(Graphics2D graphics){
int i = 0;
for (Item item: objectTron.getActivePlayer().getInventory()){
System.out.println("size: "+ objectTron.getActivePlayer().getInventory().size() + " i:" + i);
graphics.drawImage(lightgrenade, startPointXCoordinate + (i*40), + startPointYCoordinate + 460, 40, 40, null);
i ++;
}
} | 1 |
@Override
public boolean onCommand(CommandSender sender, Command arg1, String arg2,
String[] arg3) {
if (sender instanceof Player) {
Player player = (Player)sender;
if (!player.isOp()) {
return true;
}
Session session = HyperPVP.getSession(player);
if (HyperPVP.getMap().getType() != GameType.FFA) {
session.getTeam().killIncrease();
} else {
session.killIncrease();
}
}
return true;
} | 3 |
public ListWords(){
list = new HashSet<Word>();
} | 0 |
private void buttonBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBackActionPerformed
//Индексы названий и статуса заявки
final int indexColumnName = 0;
final int indexColumnStatus = 3;
//Определяем индекс выбранной строки в таблице
int selectedRowIndex = creditTable.getSelectedRow();
//Определяем статус выбранной заявки
String status = String.valueOf(creditTable.getValueAt(selectedRowIndex, indexColumnStatus));
//Если заявка активна - выход из метода (не можем ее удалить)
if (status.equals(CreditDAO.activeStatus)) {
JOptionPane.showMessageDialog(this, "Отменить активную заявку невозможно!");
return;
}
//Получаем название выбранной кредитной программы в таблице
String programName = String.valueOf(creditTable.getValueAt(selectedRowIndex, indexColumnName));
//Получаем идентификатор кредитной программы
CreditProgram crProg = crProgDAO.get(programName);
int selectedProgramId = crProg.getId();
//По идентификатору находим кредитную прорамму для данного клиента и удаляем ее
Statement statement = null;
ResultSet result = null;
try {
//Получаем общую выборку
statement = creditDAO.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
result = statement.executeQuery(creditDAO.getAllQuery());
//Ищем запись для текущего клиента и кредитной программы
while (result.next()) {
if ((result.getInt("CLIENTSID") == clientsId) &&
(result.getInt("CREDITPROGRAMID") == selectedProgramId)) {
break;
}
}
//Удаляем данную запись
result.deleteRow();
JOptionPane.showMessageDialog(this, "Заявка отменена");
//Обновляем таблицу для текущего клиента
creditDAO.initTableModel(creditTable, creditDAO.getCreditsByClientsId(clientsId));
} catch (SQLException exc) {
}
}//GEN-LAST:event_buttonBackActionPerformed | 5 |
public synchronized boolean write(final File file) {
if (file == null)
throw new IllegalArgumentException("null input file");
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
}
catch (IOException e) {
e.printStackTrace();
}
if (out == null)
return false;
if (progressBar != null) {
EventQueue.invokeLater(new Runnable() {
public void run() {
progressBar.setString("Writing......");
}
});
}
String text = null;
try {
text = page.getDocument().getText(0, page.getDocument().getLength());
}
catch (BadLocationException e) {
e.printStackTrace();
text = "Error in getting text from the document";
}
int clength = text.length();
byte[] c = new byte[clength];
c = text.getBytes();
try {
out.write(c, 0, clength);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (progressBar != null)
EventQueue.invokeLater(new Runnable() {
public void run() {
progressBar.setString("Done");
}
});
return true;
} | 8 |
private void degreejComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_degreejComboBoxActionPerformed
// TODO add your handling code here:
String itemText = (String)degreejComboBox.getSelectedItem( );
if(itemText.equals("Other")){
otherjLabel.setVisible(true);
otherjTextField.setVisible(true);
}
else{
otherjLabel.setVisible(false);
otherjTextField.setVisible(false);
}
}//GEN-LAST:event_degreejComboBoxActionPerformed | 1 |
public void justify(int x)
{
if(1 <= x && x <= 3)
myJustification = x;
} | 2 |
public byte[] encoder()
{
//Generates the type of client this is
char typ;
String hld;
if(baseCon != null)
typ = '1';
else if(remCon!= null)
typ = '2';
else
typ = '0';
//The state 1 client
if(state == 1)
{
hld = 1+";"+getName()+";"+typ+";"+getKey()+";"+getScreenChar()+";"+devCon();
}
//The state 2 client
else if(state == 2)
{
//if(baseCon != null)
// System.out.println(outbound.toString());
hld = 2+";"+getName()+";"+typ+";"+getKey()+";"+getScreenChar()+";"+prefCon();
}
else if(state == 3)
hld = 3+";"+getName()+";"+typ+";"+getKey()+";"+getScreenChar()+";"+state3Con();
//The state 0 client
else
hld = 0+";"+getName()+";"+typ+";";
byte[] tem = hld.getBytes();
byte[] out;
if(state == 2)
out = new byte[tem.length+outbound.length];
else
return tem;
int cnt = 0;
while(cnt<tem.length)
{
out[cnt] = tem[cnt];
cnt++;
}
cnt = 0;
while(cnt<outbound.length)
{
out[cnt+tem.length] = outbound[cnt];
cnt++;
}
return out;
} | 8 |
public void render(Graphics g){
// Draw History contents table
Font fnt0 = new Font("arial", Font.ITALIC, 10);
g.setFont(fnt0);
g.setColor(Color.green);
g.drawString("(LAST 15 GAMES)", (Cong.WIDTH * Cong.SCALE) / 2 - 45, start_y - 37);
Font fnt1 = new Font("arial", Font.BOLD, 12);
g.setFont(fnt1);
g.drawString("DATE", 25, start_y);
g.drawString("P1", 100, start_y);
g.drawString("P2", 300, start_y);
g.drawString("SCORE", 500, start_y);
g.drawString("DURATION", 550, start_y);
String line = "";
String cvsSplitBy = ",";
int gameCount = 0;
Font fnt2 = new Font("arial", Font.ITALIC, 10);
g.setFont(fnt2);
String[] record;
for (int i = 0; i< records.length; i++) {
if(records[i] != null){
gameCount++;
// use comma as separator
record = records[i].split(cvsSplitBy);
g.drawString(record[0], 25, start_y + (spacing_y * gameCount));
g.drawString(record[1], 100, start_y + (spacing_y * gameCount));
g.drawString(record[2], 300, start_y + (spacing_y * gameCount));
g.drawString(record[3], 500, start_y + (spacing_y * gameCount));
g.drawString(record[4], 550, start_y + (spacing_y * gameCount));
}
}
} | 2 |
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
// TODO add your handling code here:
try{
if(esCarga){
if((jTextField1==null)||(jTextField1.getText().equals("")))
jTextField1.requestFocus();
else
{
int numAsiento=Integer.parseInt(jTextField1.getText());
r_con.Connection();
ResultSet rs=r_con.Consultar("select ba_nro_asiento,ba_ok_registrado from borrador_asientos where ba_nro_asiento="+numAsiento);
if(rs.next()){
if(!rs.getBoolean(2)){
cargarCampos(rs.getInt(1));
jButton3.setEnabled(true);
mensajeError(" ");
}
else
{
deshabilitarCampos();
jTextField1.requestFocus();
mensajeError("El asiento ya se encuentra registrado");
}
}
else
{
deshabilitarCampos();
jTextField1.requestFocus();
mensajeError("El asiento ingresado no existe");
}
r_con.cierraConexion();
}
}
}
catch(Exception e){
r_con.cierraConexion();
System.out.println(e.getMessage());
}
}//GEN-LAST:event_jTextField1FocusLost | 6 |
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String requestContent = readRequestContent(request);
String ids = retriveIdsFromJson(requestContent);
if (null == ids) {
out.println(returnMsg(ReturnInfo.Status.err,
ReturnInfo.Reason.jsonFormatErr, ""));
out.flush();
out.close();
return;
}
else if (ids.equals("")) {
out.println(returnMsg(ReturnInfo.Status.err,
ReturnInfo.Reason.noIdErr, ""));
out.flush();
out.close();
return;
}
String[] id_array = ids.split(",");
DealsDAO dealsDAO = new DealsDAO();
MerchantsDAO merchantsDAO = new MerchantsDAO();
PicturesDAO picturesDAO = new PicturesDAO();
MerchantDealMapDAO merchantDealMapDAO = new MerchantDealMapDAO();
List<Deals> deals = new ArrayList<Deals>();
List<Merchants> merchantsList = new ArrayList<Merchants>();
List<String> dealPicURLList = new ArrayList<String>();
for (String s : id_array) {
int id = parseInteger(s);
if (id == -1) {
out.println(returnMsg(ReturnInfo.Status.err,
ReturnInfo.Reason.notNumbericIDErr, ""));
out.flush();
out.close();
return;
} else {
Deals deal = dealsDAO.selectById(id);
if (null == deal) {
out.println(returnMsg(ReturnInfo.Status.err,
ReturnInfo.Reason.idNotExistInDBErr, String.valueOf(id)));
out.flush();
out.close();
return;
}
merchantsList.add(merchantsDAO.selectById(merchantDealMapDAO.getMerchantIdByDealId(deal.getDealId())));
dealPicURLList.add(picturesDAO.selectById(deal.getPicId()).getPicLink());
deals.add(deal);
}
}
out.println(convertEncoding(convertDealsToJson(deals, merchantsList,
dealPicURLList)));
out.flush();
out.close();
} | 5 |
public void createOutline(Shape selected) {
selectedShape = selected;
if (selectedShape == null)
return;
if (selectedShape instanceof Square) {
createOutlineForSquare((Square) selectedShape);
}
else if (selectedShape instanceof Rectangle) {
createOutlineForRectangle((Rectangle)selectedShape);
}
else if (selectedShape instanceof Circle) {
createOutlineForCircle((Circle)selectedShape);
}
else if (selectedShape instanceof Ellipse) {
createOutlineForEllipse((Ellipse)selectedShape);
}
else if (selectedShape instanceof Line) {
}
else if (selectedShape instanceof Triangle) {
}
} | 7 |
public NumMatrix(int[][] matrix) {
this.matrix=matrix;
width=matrix[0].length;
height=matrix.length;
init();
} | 0 |
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("Sleeping thread for " + timeLeftMs + " ms.");
Thread.sleep(timeLeftMs);
System.out.println("The auction has been expired!");
System.out.println("auctionId = " + auctionId);
} catch (Exception e) {
System.out.println("Exception - " + e.getMessage());
e.printStackTrace();
}
Auction auction = emgr.find(Auction.class, auctionId);
System.out.println("OBtained auction object");
auction.setAuctionExpired((short)1);
/*emgr.persist(auction);*/
emgr.merge(auction);
emgr.flush();
int itemId = auction.getItemId();
Item item = emgr.find(Item.class, itemId);
String userName = item.getUserName();
User user = emgr.find(User.class, userName);
String userEmail = user.getEmail();
boolean bidExists;
TypedQuery<Bid> bidQuery = emgr.createNamedQuery("Bid.findBidByAuction", Bid.class);
try {
bid = (Bid) bidQuery.getSingleResult();
bid.getCurrentHighest();
bidExists = true;
} catch (NoResultException nre) {
bidExists = false;
}
// Obtain the email creditentials to the admin email from the database
EmailCredential emailCred = emgr.find(EmailCredential.class, "qif");
if (bidExists) {
// Send email to the owner of the auction
Runnable emailOwnerThread = new EmailSender(emailCred.getEmailLogin(), emailCred.getEmailPassword(), "MiniEbay - Your auction has finished", "Your auction has finished. The following are the auction details:\nAuction Name: "
+ auction.getAuctionName() + "\n Auction Description: " + auction.getAuctionDescription() + "\n Item Name: " + item.getItemName() + "\n Item Model: " + "\n The auction has been bid " + bid.getBidConsequence() + " times.\n The winning bid: " + bid.getCurrentHighest(),
emailCred.getEmailLogin(), userEmail);
new Thread(emailOwnerThread).start();
// Send email to the winner of the auction
Runnable emailWinnerThread = new EmailSender(emailCred.getEmailLogin(), emailCred.getEmailPassword(), "MiniEbay - You have won an auction!", "You have won the following auction:\nAuction Name: "
+ auction.getAuctionName() + "\n Auction Description: " + auction.getAuctionDescription() + "\n Item Name: " + item.getItemName() + "\n Item Model: " + "\n The auction has been bid " + bid.getBidConsequence() + " times.\n You won with a bid of: " + bid.getCurrentHighest(),
emailCred.getEmailLogin(), userEmail);
new Thread(emailWinnerThread).start();
} else { // Nobody won the auction
// Send email to the owner of the auction
Runnable emailOwnerThread = new EmailSender(emailCred.getEmailLogin(), emailCred.getEmailPassword(), "MiniEbay - Your auction has finished", "Your auction has finished, unfortunately nobody has won it. The following are the auction details:\nAuction Name: "
+ auction.getAuctionName() + "\n Auction Description: " + auction.getAuctionDescription() + "\n Item Name: " + item.getItemName() + "\n Item Model: " + " \n The start price: " + auction.getStartPrice(),
emailCred.getEmailLogin(), userEmail);
new Thread(emailOwnerThread).start();
}
} | 3 |
private void setLightSource() {
if (model.getLightSource().isOn()) {
ModelerUtilities.selectWithoutNotifyingListeners(lightSwitch, true);
boolean b1 = model.getLightSource().isMonochromatic();
ModelerUtilities.selectWithoutNotifyingListeners(monochromaticButton, b1);
ModelerUtilities.selectWithoutNotifyingListeners(whiteButton, !b1);
int nray = model.getLightSource().getNumberOfBeams();
boolean b2 = model.getLightSource().isSingleBeam(); // backward compatible
if (b2)
nray = 1;
nraySlider.setValue(nray);
enableEditor(true);
frequencySlider.setEnabled(b1);
setupFrequencySlider(model);
intensitySlider.setValue(intensitySlider.getMaximum() + 1 - model.getLightSource().getRadiationPeriod()
/ 100);
switch (model.getLightSource().getDirection()) {
case LightSource.WEST:
ModelerUtilities.selectWithoutNotifyingListeners(westButton, true);
break;
case LightSource.EAST:
ModelerUtilities.selectWithoutNotifyingListeners(eastButton, true);
break;
case LightSource.NORTH:
ModelerUtilities.selectWithoutNotifyingListeners(northButton, true);
break;
case LightSource.SOUTH:
ModelerUtilities.selectWithoutNotifyingListeners(southButton, true);
break;
case LightSource.OTHER:
ModelerUtilities.selectWithoutNotifyingListeners(otherButton, true);
angleField.setValue((int) Math.round(Math.toDegrees(model.getLightSource().getAngleOfIncidence())));
directionPanel.add(angleField);
directionPanel.add(degreeLabel);
directionPanel.validate();
directionPanel.repaint();
break;
}
}
else {
ModelerUtilities.selectWithoutNotifyingListeners(lightSwitch, false);
enableEditor(false);
}
} | 7 |
private static GameState weekLoop(GameState state)
{
for(int day = state.getDay(); day <= 5; day++)
{
state.setDay(day);
if(state.getTime() == Time.PICK_CARDS)
{
pickCards(state);
state.log("~DAY PHASE (" + (day+1) + ")~");
state.setTime(Time.DAY);
state.updateGUIs();
}
while(state.getTime() != Time.PICK_CARDS)
{
state = oneAction(state);
state.updateGUIs();
}
}
state = state.getCounter().score(new GameState(state), true);
weekendClear(state);
return state;
} | 3 |
void handleCutCopy() {
// Save the cut/copied style info so that during paste we will maintain
// the style information. Cut/copied text is put in the clipboard in
// RTF format, but is not pasted in RTF format. The other way to
// handle the pasting of styles would be to access the Clipboard directly and
// parse the RTF text.
cachedStyles = new Vector();
Point sel = text.getSelectionRange();
int startX = sel.x;
for (int i=sel.x; i<=sel.x+sel.y-1; i++) {
StyleRange style = text.getStyleRangeAtOffset(i);
if (style != null) {
style.start = style.start - startX;
if (!cachedStyles.isEmpty()) {
StyleRange lastStyle = (StyleRange)cachedStyles.lastElement();
if (lastStyle.similarTo(style) && lastStyle.start + lastStyle.length == style.start) {
lastStyle.length++;
} else {
cachedStyles.addElement(style);
}
} else {
cachedStyles.addElement(style);
}
}
}
} | 5 |
* @param xxx
* @param yyy
* @param zzz
* @param attached Are we attached to the piston body?
* @param override_sticky If attached, are we a sticky piston or a regular piston?
*/
public void renderPistonHead(int textureId, int xxx, int yyy, int zzz, BlockType block, int tex_offset, boolean attached, boolean override_sticky) {
float x = xxx + this.x*16;
float z = zzz + this.z*16;
float y = yyy;
byte data = getData(xxx, yyy, zzz);
boolean sticky = ((data & 0x8) == 0x8);
int direction = (data & 0x7);
float side_tex_x = precalcSpriteSheetToTextureX[block.texture_extra_map.get("body")+tex_offset];
float side_tex_y = precalcSpriteSheetToTextureY[block.texture_extra_map.get("body")+tex_offset];
// Matrix stuff
GL11.glPushMatrix();
GL11.glTranslatef(x, y, z);
// This routine draws the piston facing south, which is direction value 3
if (direction == 1)
{
// Up
GL11.glRotatef(-90f, 1f, 0f, 0f);
}
else if (direction == 2)
{
// North
GL11.glRotatef(180f, 0f, 1f, 0f);
}
else if (direction == 4)
{
// West
GL11.glRotatef(-90f, 0f, 1f, 0f);
}
else if (direction == 5)
{
// East
GL11.glRotatef(90f, 0f, 1f, 0f);
}
// Outside edges
renderNonstandardHorizontalTexRotate(side_tex_x, side_tex_y, TEX16, TEX128, -.49f, .25f, .49f, .49f, .49f);
renderNonstandardHorizontalTexRotate(side_tex_x, side_tex_y, TEX16, TEX128, -.49f, .25f, .49f, .49f, -.49f);
renderNonstandardVerticalTexRotate(side_tex_x, side_tex_y, TEX16, TEX128, -.49f, .49f, .25f, -.49f, -.49f, .49f);
renderNonstandardVerticalTexRotate(side_tex_x, side_tex_y, TEX16, TEX128, .49f, .49f, .25f, .49f, -.49f, .49f);
// Back face and post, if we're not attached
if (!attached)
{
// Back face first
renderVertical(textureId, -.49f, .25f, .49f, .25f, -.49f, .98f);
// Now the post
renderNonstandardHorizontal(side_tex_x, side_tex_y, TEX16, TEX128, -.125f, .25f, .125f, -.75f, .125f);
renderNonstandardHorizontal(side_tex_x, side_tex_y, TEX16, TEX128, -.125f, .25f, .125f, -.75f, -.125f);
renderNonstandardVertical(side_tex_x, side_tex_y, TEX16, TEX128, -.125f, .125f, .25f, -.125f, -.125f, -.75f);
renderNonstandardVertical(side_tex_x, side_tex_y, TEX16, TEX128, .125f, .125f, .25f, .125f, -.125f, -.75f);
}
// Front face
if (attached)
{
if (override_sticky)
{
textureId = block.texture_extra_map.get("head_sticky")+tex_offset;
}
}
else
{
if (sticky)
{
textureId = block.texture_extra_map.get("head_sticky")+tex_offset;
}
}
renderVertical(textureId, -.49f, .49f, .49f, .49f, -.49f, .98f);
// Pop the matrix
GL11.glPopMatrix();
} | 8 |
public static String[] allUpperCase(String... strings){
String[] tmp = new String[strings.length];
for(int idx=0;idx<strings.length;idx++){
if(strings[idx] != null){
tmp[idx] = strings[idx].toUpperCase();
}
}
return tmp;
} | 2 |
protected int getCorrectDirToOriginRoom(Room R, int v)
{
if(v<0)
return -1;
int dir=-1;
Room R2=null;
Exit E2=null;
int lowest=v;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
R2=R.getRoomInDir(d);
E2=R.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()))
{
final int dx=commonRoomSet.indexOf(R2);
if((dx>=0)&&(dx<lowest))
{
lowest=dx;
dir=d;
}
}
}
return dir;
} | 7 |
@Override
public void setValueAt(Object value, int row, int column) {
Object obj = this.items.get(row);
if(this.columnNames.size() > column) {
ColumnDefinition col = this.columnNames.get(column);
if(col != null) {
if(obj != null) {
try {
this.items.set(row, col.getName(), value);
} catch (Exception e) {
logger.error("Unable to set item.", e);
}
}
}
} else {
T item = this.items.get(row);
if(this.toRemove.contains(item)) {
this.toRemove.remove(item);
} else {
this.toRemove.add(item);
}
}
} | 5 |
public int getDiscId(String queryString) {
int i = 0;
for(String[] cd: this.cds) {
// queryString in den beiden ArrayElementen der CD suchen
if(cd[0]!=null && cd[1]!=null) {
if(cd[0].toLowerCase().indexOf(queryString.toLowerCase())!=-1 ||
cd[1].toLowerCase().indexOf(queryString.toLowerCase())!=-1) {
return i; //Index zurückgeben
}
}
i++;
}
return -1;
} | 5 |
public static HashMap<String, String> loadSourceMap( String sourceFile){
Repository repo = new SailRepository(new MemoryStore());
HashMap<String, String> cacheNameToSourceMap = new HashMap<String, String>();
try {
repo.initialize();
RepositoryConnection conn = repo.getConnection();
conn.add(new File(sourceFile), "", RDFFormat.TURTLE);
RepositoryResult<Statement> results = conn.getStatements(null, null, null, true);
while(results.hasNext()){
Statement curStatement = results.next();
String origSource = curStatement.getSubject().toString();
String localName = curStatement.getObject().toString().replaceAll("\"", "");
cacheNameToSourceMap.put(localName, origSource);
}
}
catch(Exception e){
e.printStackTrace();
}
return cacheNameToSourceMap;
} | 2 |
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} | 6 |
/**
* This function draw the circumscribed circle on the PPM object.
*
* @param PPM
*/
public void drawTo(PPMEC PPM) {
Vector v = new Vector(0, 0);
// Must scale x,y to final ppm dimensions
int c = (int) (xRatio * PPM.getWidth()); // get x-coord
int r = (int) (yRatio * PPM.getHeight()); // get y-coord
int radius = (int) (PPM.getWidth() * radiusP);
int count = 0;
while (!found) {
for (int j = 0; j < PPM.getHeight(); j++) {
for (int k = 0; k < PPM.getWidth(); k++) {
int d = (r - j) * (r - j) + (c - k) * (c - k);
if (radius * radius == d && count < points) {
Vector v0 = new Vector(k - c, j - r);
vectorList.add(v0);
count++;
}
}
}
Vector v10 = addVectors(vectorList);
if (v10.length() == 0) {
for (int i = 0; i < vectorList.size() / 2; i++) {
for (int j = 0; j < PPM.getHeight(); j++) {
for (int k = 0; k < PPM.getWidth(); k++) {
int c1 = crossProduct(c, r, k, j);
int c2 = crossProduct(vectorList.get(i).getX() + c,
vectorList.get(i).getY() + r, k, j);
int c3 = crossProduct(vectorList.get(i + 1).getX()
+ c, vectorList.get(i + 1).getY() + r, k, j);
PPM.setPixel(vectorList.get(i).getX() + c,
vectorList.get(i).getY() + r, color);
}
found = true;
}
}
}
}
} | 9 |
public String toString() {
if (root == null) {
return "There are no students registered";
}
StringBuilder sb = new StringBuilder();
/* inorder traverse the tree */
Stack<StudentNode> stack = new Stack<StudentNode>();
StudentNode currentNode = root;
while (true) {
/* push all the left child nodes to stack */
while (currentNode != null) {
stack.push(currentNode);
currentNode = currentNode.left;
}
if (stack.isEmpty()) {
break;
}
currentNode = stack.pop();
if(currentNode.courses.isEmpty()){
sb.append(currentNode.name+": no courses taken\n");
}else{
sb.append(currentNode.name + " has taken:");
for (String course : currentNode.courses) {
sb.append(" " + course + ",");
}
/* replace last "," */
sb.replace(sb.length() - 1, sb.length(), "\n");}
/* traverse to right child node */
currentNode = currentNode.right;
}
return sb.toString();
} | 6 |
public static String[] removeEmptyStrings(String[] data)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i < data.length; i++)
if(!data[i].equals(""))
result.add(data[i]);
String[] res = new String[result.size()];
result.toArray(res);
return res;
} | 2 |
public void tick(Enemy enemy) {
super.tick(enemy);
attackData.resetEnemiesTowerHasShoot(); // reset enemies it has shot this frame.
if (attackData.canShootAtThisFrame()) {
if (enemy.isActive() && enemy.isAlive()) { // can only handle active and alive enemies
if (canShoot() && isInRange(enemy) && isCorrectTarget(enemy)) {
shoot(enemy);
if (enemy.isAlive()) { // ie enemy still is alive
tower.addToCurrentTargets(enemy);
tower.addToCurrentPlaceablesInRangeOfThisTower(enemy);
} else {
tower.removeFromCurrentTargets(enemy);
}
}
}
}
} | 7 |
public void trimToSize(int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
if (size <= maxSize || map.isEmpty()) {
break;
}
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
} | 6 |
public PossibleState contains(CommunityState cs) {
for (PossibleState ps : possibleStates)
if (ps.getCommunityState().equals(cs))
return ps;
return null;
} | 2 |
public void run() {
logger.fine("X-Plane receiver listening on port " + datagram_socket.getLocalPort());
DatagramPacket packet = null;
while (this.keep_running) {
try {
// wait for packet or time-out
packet = receiveXPlanePacket();
if (this.has_reception == false) {
this.has_reception = true;
logger.info("UDP reception re-established");
}
for (int i=0; i<this.reception_observers.size(); i++) {
((XPlaneDataPacketObserver)this.reception_observers.get(i)).new_sim_data(packet.getData());
}
} catch (SocketTimeoutException ste) {
if (this.has_reception == true) {
logger.warning("No UDP reception");
this.has_reception = false;
}
} catch(IOException ioe) {
logger.warning("Caught I/O error while waiting for UDP packets! (" + ioe.toString() + ")");
} catch(Exception e) {
logger.warning("Caught error while waiting for UDP packets! (" + e.toString() + " / " + e.getMessage() + ")");
}
}
logger.fine("X-Plane receiver stopped");
} | 7 |
public Document getDocument( String url, String encode ) {
Document doc = null;
try {
if ( encode.equals("UTF-8") ) {
doc = Jsoup.connect(url)
.timeout(50000)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1")
.get();
}
else if ( encode.equals("GBK") ) {
try {
URL link = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
doc = Jsoup.parse(buffer.toString(), "utf-8");
}catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
NewsEyeSpider.logger.debug(baos.toString());
}
}
}catch (Exception e) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(baos));
NewsEyeSpider.logger.debug(baos.toString());
}
return doc;
} | 5 |
public static double ddot_f77 (int n, double dx[], int incx, double
dy[], int incy) {
double ddot;
int i,ix,iy,m;
ddot = 0.0;
if (n <= 0) return ddot;
if ((incx == 1) && (incy == 1)) {
// both increments equal to 1
m = n%5;
for (i = 1; i <= m; i++) {
ddot += dx[i]*dy[i];
}
for (i = m+1; i <= n; i += 5) {
ddot += dx[i]*dy[i] + dx[i+1]*dy[i+1] + dx[i+2]*dy[i+2] +
dx[i+3]*dy[i+3] + dx[i+4]*dy[i+4];
}
return ddot;
} else {
// at least one increment not equal to 1
ix = 1;
iy = 1;
if (incx < 0) ix = (-n+1)*incx + 1;
if (incy < 0) iy = (-n+1)*incy + 1;
for (i = 1; i <= n; i++) {
ddot += dx[ix]*dy[iy];
ix += incx;
iy += incy;
}
return ddot;
}
} | 8 |
public static long mult(long flongOne, long flongTwo)
throws FixedPointLongException {
boolean negative = false;
long a = flongOne;
long b = flongTwo;
if (flongOne < 0) {
a = -a;
negative = !negative;
}
if (flongTwo < 0) {
b = -b;
negative = !negative;
}
long intmult = (a >> OFFSET) * (b >> OFFSET);
if (intmult >> OFFSET != 0) {
throw new FixedPointLongException("Numbers too large to multiply: "
+ flongToString(flongOne) + ", " + flongToString(flongTwo));
}
long fracmult1 = (a >> OFFSET) * fracPart(b);
long fracmult2 = (b >> OFFSET) * fracPart(a);
long fracmult3 = (fracPart(a) >> 1) * (fracPart(b) >> 1);
// System.err.println("intmult " + intmult + " fracmult1 " + fracmult1 +
// " fracmult2 " + fracmult2 + " fracmult3 " + fracmult3);
// System.err.println("fracpart1 " + fracPart(a) + " fracpart2 " +
// fracPart(b) + " fracmult " + fracmult3);
long ret = intToFlong((int) intmult) + fracmult1 + fracmult2
+ (fracmult3 >> (OFFSET - 2));
if (ret < 0)
throw new FixedPointLongException(
"Numbers are too large to multiply: "
+ flongToString(flongOne) + ", "
+ flongToString(flongTwo));
if (negative)
ret = -ret;
// System.err.println("" + flongToString(flongOne) + " times " +
// flongToString(flongTwo) + " is " + flongToString(ret));
return ret;
} | 5 |
public int threeSumClosest(int[] num, int target) {
assert num.length > 2:"the number of integers < 3!";
if (num.length == 3)
return num[0]+num[1]+num[2];
Arrays.sort(num);
if (num[0] >= target)
return num[0]+num[1]+num[2];
if (num[num.length-1] <= target)
return num[num.length-1]+num[num.length-2]+num[num.length-3];
int index = 0; // target at [num[pre],num[post]]
while (num[index] < target){
index++;
}
int pre = index - 1;
int post = index;
int count = 0;
int[] indexes = new int[]{-1,-1,-1};
while (count < 3){
if (pre == 0){
for (int i = 0; i < indexes.length; i++) {
if (indexes[i]==-1){
indexes[i] = post;
post++;
}
}
break;
}
if (post == num.length){
for (int i = 0; i < indexes.length; i++) {
if (indexes[i]==-1){
indexes[i] = pre;
pre--;
}
}
break;
}
if (Math.abs(num[pre]-target) > Math.abs(num[post]-target)){
indexes[count] = post;
post ++;
count ++;
}
else {
indexes[count] = pre;
pre --;
count ++;
}
}
return num[indexes[0]]+num[indexes[1]]+num[indexes[2]];
} | 5 |
public static void main(String[] args) {
// TODO code application logic here
// Cuenta martin = Actions.create("2321321321", "Martin", 1);
//
// Ingreso ing = new Ingreso("paga navidad", 700);
// martin.doMovement(ing);
//
//
// Cuenta andrea = Actions.create("23213", "Andrea", 1);
//
//
// Cuenta jesus = Actions.create("232132", "Jesus", 1);
//
//
//
// martin.doMovement(new Transferencia(andrea, "Toma dinero", 300));
// Actions.borrar(jesus);
//
// System.out.println(Actions.getAll());
Navigation nav = new Navigation();
do{
}while(nav.mainMenu());
} | 1 |
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Podaj ilość produktów: ");
int ilosc = scanner.nextInt();
double suma0 = 0, suma7 = 0, suma23 = 0;
for (int i = 1; i <= ilosc; i++) {
int kod = -1;
while (kod < 0 || kod > 2) {
System.out.println("Podaj kod produktu " + i
+ "(0[0% VAT], 1[7% VAT], 2[23% VAT): ");
kod = scanner.nextInt();
if (kod < 0 || kod > 2) System.out.println("Bledny kod produktu");
}
System.out.print("Podaj cenę produktu " + i + ": ");
double cena = scanner.nextDouble();
if (kod == 0) {
suma0 = suma0 + cena;
} else if (kod == 1) {
suma7 = suma7 + cena;
} else {
suma23 = suma23 + cena;
}
}
double sumaVAT0, sumaVAT7, sumaVAT23, kosztCalkowity, VATCalkowity;
kosztCalkowity = suma0 + suma7 + suma23;
sumaVAT0 = 0;
sumaVAT7 = suma7 / 100 * 7;
sumaVAT23 = suma23 / 100 * 23;
VATCalkowity = sumaVAT0 + sumaVAT7 + sumaVAT23;
System.out
.println("-----------------------------------------------------------------------------------------");
System.out.println("Zatem podliczmy koszty...");
System.out
.println("-----------------------------------------------------------------------------------------");
System.out.println("A) Koszt produktów z VAT 23%: " + suma23 + " W tym sam VAT: "
+ sumaVAT23);
System.out.println("B) Koszt produktów z VAT 7%: " + suma7 + " W tym sam VAT: "
+ sumaVAT7);
System.out.println("C) Koszt produktów z VAT 0%: " + suma0 + " W tym sam VAT: "
+ sumaVAT0);
System.out
.println("-----------------------------------------------------------------------------------------");
System.out.println(" suma: " + kosztCalkowity
+ " suma: " + VATCalkowity);
} | 7 |
public static String compact(String str) {
char[] array=str.toCharArray();
char lastChar='a';
String carrRtn="\\n";
String tabRtn="\\t";
int counter=0;
StringBuffer sb=new StringBuffer();
for (int i=0;i<array.length;i++) {
if (i==0 || array[i]!=lastChar) {
if (counter>1) {
sb.append(counter);
}
lastChar=array[i];
counter=1;
if (lastChar=='\n') {
sb.append(carrRtn);
}
else if (lastChar=='\t') {
sb.append(tabRtn);
}
else {
sb.append(lastChar);
}
}
else {
counter++;
}
}
if (counter==2) {
sb.append(counter);
}
else if (counter>2) {
sb.append("3+");
}
return(sb.toString());
} | 8 |
public int getDirectionX(){
return directionX;
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MatriculaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MatriculaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MatriculaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MatriculaConsulta.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MatriculaConsulta().setVisible(true);
}
});
} | 6 |
@Override
public String execute() throws Exception {
try {
//camplist=(List<Dvddog>) myDao.getDbsession().createQuery("from Dvddog").list());
Map session = ActionContext.getContext().getSession();
Campaign camp = (Campaign) session.get("campa");
camplist = (List<Campaign>) myDao.getDbsession().createQuery("from Campaign").list();
Criteria crit = myDao.getDbsession().createCriteria(Campaign.class);
crit.add(Restrictions.like("user", camp.getCampaignName()));
crit.setMaxResults(10);
camplist = (List<Campaign>) crit.list();
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} | 3 |
@Override
public synchronized void activate()
{
if (m_lActive)
{
// Already active
return;
}
m_lActive = true;
// Starts the session running in it's own thread to handle it's own commands
Goliath.Threading.ThreadJob loThreadJob = new ThreadJob<SingleParameterArguments<ISession>>(new SingleParameterArguments(m_oSession))
{
@Override
protected void onRun(SingleParameterArguments<ISession> toCommandArgs)
{
try
{
// TODO: Optimise this method
ISession loSession = toCommandArgs.getParameter();
if (loSession == null)
{
loSession = Session.getCurrentSession();
m_oSession = loSession;
}
while (m_lActive && loSession != null && !loSession.isExpired())
{
if (!m_lPaused)
{
// Process the commands in the manager
process();
}
Goliath.Threading.Thread.sleep(getThreadDelay());
}
}
catch (Exception toException)
{
// TODO: See what needs to be done here
Application.getInstance().log(toException);
}
}
};
for (int i =0; i< m_nMaxThreads; i++)
{
String lcSessionID = m_oSession == null ? "Unknown Session" : m_oSession.getSessionID();
Goliath.Threading.Thread loThread = new Goliath.Threading.Thread(loThreadJob, lcSessionID);
loThread.start();
}
} | 9 |
public void buildFactory(Map map, Cell c, Boolean aiMove) {
if (aiMove || Teams.comparePlayers(this.getOwner(),game.getCurrentPlayer())) {
if (game.getCurrentPlayer().canAfford(Factory.cost)) {
if (getBuildableCells(map).contains(c)) {
Factory f = new Factory(c, this.getOwner(), this.game);
f.placeBuilding(f, c);
game.getCurrentPlayer().subMoney(Factory.cost);
} else {
game.mapPanel.Notify("You cannot place a Factory there!");
}
} else {
if (!aiMove) {
game.mapPanel.Notify("You cannot afford to purchace a Factory!");
}
}
} else {
game.mapPanel.Notify("You can only control your own Base!");
}
} | 5 |
public void exportService(Class<T> serviceClass) {
Map<String, String> params = new HashMap<String, String>();
params.put("iface", serviceClass.getName());
tpURL.setParams(params);
// 对一个实际的执行对象进行包装,变身Invoker
Invoker<T> invoker = null;
try {
invoker = proxyFactory.createProxyInvoker(serviceClass.newInstance(), serviceClass, tpURL);
} catch (RpcException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
// 把这个Invoker 发布出去 得到一个Exporter
exporter = protocol.export(invoker);
} | 3 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ShoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ShoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ShoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ShoreFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ShoreFrame().setVisible(true);
}
});
} | 6 |
private void drawShapes(GraphicsContext gc) {
gc.setFill(Color.GREEN);
gc.setStroke(Color.BLUE);
gc.setLineWidth(1);
gc.fillText(tl.name, 40, 20);
int begin = tl.timelineEvents.firstEntry().getValue().getStartYear();
int end = tl.timelineEvents.lastEntry().getValue().getStartYear();
Iterator iter = tl.timelineEvents.keySet().iterator();
while(iter.hasNext()){
Event next = tl.timelineEvents.get(iter.next());
if (next.getDuration()){
if(next.getEndYear() > end) end = next.getEndYear();
}
}
int length = end - begin;
System.out.println("begin "+begin+" end "+end+" length "+length);
gc.strokeLine(40, 100, (length+2)*100, 100);
for(int i = 0; i < length+2; i++){
gc.strokeLine(40+i*100, 80, 40+i*100, 120);
gc.fillText(""+(begin+i), 40+i*100, 60);
}
int vOffSet = 0;
int vOffSet2 = 0;
Iterator it = tl.timelineEvents.keySet().iterator();
for(int i = 0; i < tl.timelineEvents.size(); i++ ){
Event next = tl.timelineEvents.get(it.next());
if(!yearMap.containsKey(next.getStartYear())) yearMap.put(next.getStartYear(), 0);
vOffSet+=40*yearMap.get(next.getStartYear());
//not duration event
if(next.getDuration() == false){
gc.setStroke(Color.RED);
gc.setFill(Color.RED);
int offset = (next.getStartDay()+(next.getStartMonth()*30))/4;
gc.strokeLine(40+(next.getStartYear()-begin)*100+offset, 90, 40+(next.getStartYear()-begin)*100+offset, 110);
//clickSpace cls = new clickSpace(35+i*100, 25, next);
//csArray.add(cls);
gc.fillText(""+next.getStartYear()+"/"+next.getStartMonth()+"/"+next.getStartDay(), 50+(next.getStartYear()-begin)*100, 135+vOffSet);
gc.fillText(next.getName(), 50+(next.getStartYear()-begin)*100, 150+vOffSet);
//make purple duration event
}else{
if(!yearMap.containsKey(next.getEndYear())) yearMap.put(next.getEndYear(), 0);
vOffSet2+=40*yearMap.get(next.getEndYear());
gc.setStroke(Color.PURPLE);
gc.setFill(Color.PURPLE);
int boffset = (next.getStartDay()+(next.getStartMonth()*30))/4;
int eoffset = (next.getEndDay()+(next.getEndMonth()*30))/4;
//spaces duration events so they don't pile on top eachother
spacer +=20;
//draws the duration event timeline
gc.strokeLine(40+(next.getStartYear()-begin)*100+boffset, 90+vOffSet+spacer, 40+(next.getStartYear()-begin)*100+boffset, 110+vOffSet+spacer);
gc.strokeLine(40+(next.getEndYear()-begin)*100+eoffset, 90+vOffSet+spacer, 40+(next.getEndYear()-begin)*100+eoffset, 110+vOffSet+spacer);
gc.strokeLine(40+(next.getStartYear()-begin)*100+boffset, 99+vOffSet+spacer, 40+(next.getEndYear()-begin)*100+eoffset, 99+vOffSet+spacer);
System.out.println(""+next.getEndYear());
gc.fillText(""+next.getStartYear()+"/"+next.getStartMonth()+"/"+next.getStartDay(), 50+(next.getStartYear()-begin)*100, 135+vOffSet);
gc.fillText(next.getName(), 50+(next.getStartYear()-begin)*100, 150+vOffSet);
gc.fillText(""+next.getEndYear()+"/"+next.getEndMonth()+"/"+next.getEndDay(), 50+(next.getEndYear()-begin)*100, 135+vOffSet);
gc.fillText(next.getName(), 50+(next.getEndYear()-begin)*100, 150+vOffSet);
int k = yearMap.get(next.getEndYear());
k = k+1;
yearMap.put(next.getEndYear(), k);
}
int k = yearMap.get(next.getStartYear());
k = k+1;
yearMap.put(next.getStartYear(), k);
}
} | 8 |
public void NotifyPluginUpdateReceived(PluginUpdate update) {
for (IPluginUpdateNotification ti : pluginUpdateNotificationListeners) {
ti.onPluginUpdate(update);
}
} | 1 |
public void visit_dup2(final Instruction inst) {
// If top two values are both category 1, dup them both.
// Otherwise, dup the one category 2 value.
final Set top = atDepth(0);
final int category = checkCategory(top);
if (category == 1) {
final Set top1 = atDepth(1);
checkCategory(top1, 1);
// Form 1: Dup top two values
currStack.add(new HashSet(top1));
currStack.add(new HashSet(top));
} else {
// Form 2: Dup top value
currStack.add(new HashSet(top));
}
} | 1 |
public void testIterator8() {
List<Message> msgs=createMessages();
MessageBatch batch=new MessageBatch(msgs);
int index=0;
for(Iterator<Message> it=batch.iterator(); it.hasNext();) {
it.next();
if(index == 1 || index == 2 || index == 3 || index == 10 || index == msgs.size()-1)
it.remove();
index++;
}
System.out.println("batch = " + batch);
int count=0;
for(Message ignored : batch)
count++;
assert count == msgs.size() - 5;
} | 7 |
private String getPlayer(AccountManager manager) {
Player[] bufferPlayer = manager.getAllPlayer();
String s = "";
int counter = 0;
if(bufferPlayer[bufferPlayer.length -1] != null&&bufferPlayer[bufferPlayer.length -1].name.contentEquals("Bot")){
counter = 1;
}
for (int i = 0; i < bufferPlayer.length - counter;i++){
if (bufferPlayer[i] != null){
s += "Player name: " + bufferPlayer[i].name + "<br>" + bufferPlayer[i].getCashAccount().toString() + "<br>";
s += bufferPlayer[i].getShareDeposit().toString() + "<br>";
}
}
return s;
} | 4 |
@Override
public void ejecutar(Stack<Valor> st, MemoriaDatos md, Cp cp)
throws Exception {
if (st.size() < 2)
throw new Exception("DISTINTO: faltan operandos");
Valor op1 = st.pop();
Valor op2 = st.pop();
if (op1 instanceof Booleano && op2 instanceof Booleano) {
st.push(new Booleano(((boolean) op1.getValor()) != ((boolean) op2.getValor())));
cp.incr();
}
else if (op1 instanceof Entero && op2 instanceof Entero) {
st.push(new Booleano(((int) op1.getValor()) != ((int) op2.getValor())));
cp.incr();
}
else
throw new Exception("DISTINTO: operandos de distinto tipo");
} | 5 |
public static void main(String[] args) {
try {
Element company = new Element("company");
Document document = new Document();
document.setRootElement(company);
Element staff = new Element("staff");
staff.addContent(new Element("name").setText("Sergii"));
staff.addContent(new Element("age").setText("25"));
staff.addContent(new Element("language").setText("UKR"));
document.getRootElement().addContent(staff);
// new XMLOutputter().output(doc, System.out);
XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.setFormat(Format.getPrettyFormat());
xmlOutputter.output(document, new FileWriter("D:\\Java SE\\src\\xml\\jdom\\file.xml"));
System.out.println("File Saved!");
} catch (IOException io) {
System.out.println(io.getMessage());
}
} | 1 |
private void handleMouseMoved(int x, int y) {
x -= 50;
y -= 50;
x /= 16;
y /= 16;
if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
return;
}
if (selectedx != -1) {
if ((lastFindX != x) || (lastFindY != y)) {
lastFindX = x;
lastFindY = y;
path = finder.findPath(new UnitMover(map.getUnit(selectedx, selectedy)), selectedx, selectedy, x, y);
repaint(0);
}
}
} | 7 |
protected void checkRootDirectory() {
String rootText = selectRootText.getText();
if (rootText == null || rootText.isEmpty())
return;
root = new File(rootText);
if (root.exists() && root.isDirectory()) {
File projectDir = new File(root, "project");
File buildProperties = new File(projectDir, "build.properties");
if (buildProperties.exists() && buildProperties.isFile()) {
try {
if (fillProjectInfo(buildProperties)) {
projectFoundLabelResult.setText("Yes");
setPageComplete(true);
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
setPageComplete(false);
projectNameLabelResult.setText("");
projectOrganizationLabelResult.setText("");
projectFoundLabelResult.setText("No");
} | 8 |
protected void generatePackageFiles(ClassTree classtree) throws Exception {
PackageDoc[] packages = configuration.packages;
if (packages.length > 1) {
PackageIndexFrameWriter.generate(configuration);
}
PackageDoc prev = null, next;
for (int i = 0; i < packages.length; i++) {
// if -nodeprecated option is set and the package is marked as
// deprecated, do not generate the package-summary.html, package-frame.html
// and package-tree.html pages for that package.
if (!(configuration.nodeprecated && Util.isDeprecated(packages[i]))) {
PackageFrameWriter.generate(configuration, packages[i]);
next = (i + 1 < packages.length &&
packages[i + 1].name().length() > 0) ? packages[i + 1] : null;
//If the next package is unnamed package, skip 2 ahead if possible
next = (i + 2 < packages.length && next == null) ? packages[i + 2] : next;
AbstractBuilder packageSummaryBuilder =
configuration.getBuilderFactory().getPackageSummaryBuilder(
packages[i], prev, next);
packageSummaryBuilder.build();
if (configuration.createtree) {
PackageTreeWriter.generate(configuration,
packages[i], prev, next,
configuration.nodeprecated);
}
prev = packages[i];
}
}
} | 9 |
public void entering(final String name, final Object o, String... args) {
// info(StringUtils.shortName(o.getClass()) + "-" + o.hashCode() + " entering " + name + "(" + StringUtils.join(args, ", ") + ")");
} | 0 |
public boolean replaceResponseLine( HTTPHeaderLine statusLine )
throws NullPointerException,
HeaderFormatException {
if( statusLine == null )
throw new NullPointerException( "Cannot replace the response status line with null line." );
if( statusLine.getKey() == null )
throw new HeaderFormatException( "Cannot replace the response status line with this header line. Key is null: " + statusLine, statusLine );
if( !statusLine.getKey().startsWith("HTTP") )
throw new HeaderFormatException( "Cannot replace the response status line with this header line. Key does not start with 'HTTP': " + statusLine, statusLine );
// Response line seems OK (perform deep check?).
int index = this.locateStatusLine();
// Reset the respone fields for later re-evaluation!
this.responseStatus = null;
this.responseReasonPhrase = null;
// Replace?
if( index != -1 ) {
this.replaceLine( index, statusLine );
// Indicates that the old one existed and was reaplaced.
return true;
} else {
// And add the new line to the beginning :)
this.list.add( 0, statusLine );
this.registerToMap( statusLine );
// Indicates that is was added.
return false;
}
} | 4 |
@EventHandler
public void onInventoryClick(InventoryClickEvent e)
{
// If either item is null (caused by failure to immediately update inventories after cancelled events),
// return as to avoid big ugly errors in console that make me sad.
if(e.getCursor() == null)
return;
if(e.getCurrentItem() == null)
return;
if(e.getInventory() != e.getWhoClicked().getInventory())
{
if(e.getCursor().equals(QuestCompass.getCompass()) || e.getCurrentItem().equals(QuestCompass.getCompass()))
{
e.setResult(Result.DENY);
e.setCancelled(true);
return;
}
ItemStack questBook = QuestBook.getBook(e.getWhoClicked().getName());
if(questBook != null)
{
if(e.getCursor().equals(questBook) || e.getCurrentItem().equals(QuestCompass.getCompass()))
{
e.setResult(Result.DENY);
e.setCancelled(true);
return;
}
}
}
} | 8 |
protected synchronized CtClass get0(String classname, boolean useCache)
throws NotFoundException
{
CtClass clazz = null;
if (useCache) {
clazz = getCached(classname);
if (clazz != null)
return clazz;
}
if (!childFirstLookup && parent != null) {
clazz = parent.get0(classname, useCache);
if (clazz != null)
return clazz;
}
clazz = createCtClass(classname, useCache);
if (clazz != null) {
// clazz.getName() != classname if classname is "[L<name>;".
if (useCache)
cacheCtClass(clazz.getName(), clazz, false);
return clazz;
}
if (childFirstLookup && parent != null)
clazz = parent.get0(classname, useCache);
return clazz;
} | 9 |
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
DoTurn(pw);
pw.FinishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
}
} | 4 |
public static double[] lsolve(double[][] A, double[] b) {
int N = b.length;
for (int p = 0; p < N; p++) {
// find pivot row and swap
int max = p;
for (int i = p + 1; i < N; i++) {
if (Math.abs(A[i][p]) > Math.abs(A[max][p])) {
max = i;
}
}
double[] temp = A[p]; A[p] = A[max]; A[max] = temp;
double t = b[p]; b[p] = b[max]; b[max] = t;
// singular or nearly singular
if (Math.abs(A[p][p]) <= EPSILON) {
throw new ArithmeticException("Matrix is singular or nearly singular");
}
// pivot within A and b
for (int i = p + 1; i < N; i++) {
double alpha = A[i][p] / A[p][p];
b[i] -= alpha * b[p];
for (int j = p; j < N; j++) {
A[i][j] -= alpha * A[p][j];
}
}
}
// back substitution
double[] x = new double[N];
for (int i = N - 1; i >= 0; i--) {
double sum = 0.0;
for (int j = i + 1; j < N; j++) {
sum += A[i][j] * x[j];
}
x[i] = (b[i] - sum) / A[i][i];
}
return x;
} | 8 |
public static ItemInfo itemByStack(ItemStack itemStack) {
if (itemStack == null) {
return null;
}
for (ItemInfo item : items) {
if (itemStack.getType().equals(item.getType()) && item.isDurable()) {
return item;
} else if (itemStack.getType().equals(item.getType()) && item.getSubTypeId() == itemStack.getDurability()) {
return item;
}
}
return null;
} | 6 |
public String getId() {
return id;
} | 0 |
@Override
public boolean intersectsBounds(CollisionObject object) {
if (object instanceof PlaneObject) {
return false;
}
Vector3d min = new Vector3d();
Vector3d max = new Vector3d();
object.getBounds(min, max);
if (getLocalSignedDistance(position, rotation, min) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(min.x,
min.y, max.z)) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(min.x,
max.y, min.z)) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(min.x,
max.y, max.z)) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, max) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(max.x,
min.y, max.z)) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(max.x,
max.y, min.z)) < 0) {
return true;
}
if (getLocalSignedDistance(position, rotation, new Vector3d(max.x,
max.y, max.z)) < 0) {
return true;
}
return false;
} | 9 |
public static void main(String[] args) throws Exception
{
if( args.length != 5)
throw new Exception("Example d'appel : source <nom_DNS_du_destinataire> <numero_de_port_destination> <taille_de_fenetre> <fichier> <pourcentage_erreur_crc>");
// configurer le client
int port = Integer.parseInt(args[1]);
if (port <= 1024)
throw new Exception("Erreur : le port d'écoute doit être supérieur à 1024 pour éviter les problèmes de droit");
long WIN = Long.parseLong(args[2]);
if (WIN <= 0 || WIN > 8)
throw new Exception("Erreur : la taille de la fenêtre ne peut être nulle ou dépasser la valeur de 8.");
int errorCRC = 100-Integer.parseInt(args[4]);
if (errorCRC <= 0 || errorCRC > 100)
throw new Exception("Erreur : le pourcentage d'erreur ne peut être inférieur à 0% et ne doit pas être supérieur à 99%.");
byte[] buffer = new byte[1024];
// instancier le client
UDPClient client = new UDPClient(args[0],port, WIN, args[3], errorCRC);
} | 6 |
public void setChallengeFormat(AlgorithmParametersType.ChallengeFormat value) {
this.challengeFormat = value;
} | 0 |
private Rectangle getDragRowInsertionMarkerBounds(Row parent, int insertAtIndex) {
int rowCount = mModel.getRowCount();
Rectangle bounds;
if (insertAtIndex < 0 || rowCount == 0) {
bounds = new Rectangle();
} else {
int insertAt = getAbsoluteInsertionIndex(parent, insertAtIndex);
int indent = parent != null ? mModel.getIndentWidth(parent, mModel.getColumns().get(0)) + mModel.getIndentWidth() : 0;
if (insertAt < rowCount) {
bounds = getRowBounds(mModel.getRowAtIndex(insertAt));
if (mDrawRowDividers && insertAt != 0) {
bounds.y--;
}
} else {
bounds = getRowBounds(mModel.getRowAtIndex(rowCount - 1));
bounds.y += bounds.height;
}
bounds.x += indent;
bounds.width -= indent;
}
bounds.y -= 3;
bounds.height = 7;
return bounds;
} | 6 |
public Boolean connect()
{
try {
selectedPortIdentifier = CommPortIdentifier.getPortIdentifier( portname);
} catch (NoSuchPortException e1) {
setConnected(false);
error = "Port <"+portname+"> not found !";
trytolog(error);
return false;
}
//Required port found in system : We can think Ultra meter is plugged on system !
CommPort commPort = null;
try
{
//the method below returns an object of type CommPort
commPort = selectedPortIdentifier.open("GlucoMeter", TIMEOUT);
//the CommPort object can be casted to a SerialPort object
serialPort = (SerialPort)commPort;
if(this.mode == 0) {
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
} else {
System.out.println("Setting for CP2103");
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
//serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
//serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_XONXOFF_IN + SerialPort.FLOWCONTROL_XONXOFF_OUT);
}
//for controlling GUI elements
setConnected(true);
//logging
error = "Port <"+portname+"> opened successfully\n";
trytolog(error);
currbuf = new byte[256];
return true;
} catch (PortInUseException e) {
error = portname + " is in use. (" + e.toString() + ")\n";
trytolog(error);
} catch (Exception e) {
e.printStackTrace();
logText = "Failed to open " + portname + "(" + e.toString() + ")";
trytolog(logText);
}
return false;
} | 4 |
public Order getOrdine() {
return ordine;
} | 0 |
public static double getDamageModBash(WeaponMaterial type) {
switch (type) {
case COPPER:
return 1.25;
case BRONZE:
return 1.25;
case SILVER:
return 3;
case IRON:
return 1;
case STEEL:
return 1;
case ADAMANTINE:
return 0.25;
}
return 1;
} | 6 |
private boolean verifyResponse(byte[] peerHandshake, boolean newPeer)
{
if(peerHandshake == null)
{
return false;
}
else if(peerHandshake.length != 68)
{
return false;
}
// check bit torrent protocol and info hash
for (int i = 0; i < 48; i++)
{
// skip the 8 reserved bytes
if (i > 19 && i < 28)
{
continue;
}
if (peerHandshake[i] != handshake[i])
{
return false;
}
}
if (!newPeer)
{
// check the peerID
byte[] peerIdArray = this.peerId.getBytes();
for (int i = 48; i < peerHandshake.length; i++)
{
if (peerHandshake[i] != peerIdArray[i-48])
{
return false;
}
}
return true;
}
else
// this response checks out, set the new peers peer id to the peer id it sent in handshake
{
parsePeerId(peerHandshake);
return true;
}
} | 9 |
private void updateEntities(GameContext g) {
// UPDATE ALL ENTITIES
for (Mob m : dots) {
m.updateMob(g);
}
// for (Mob m : lines) {
// m.updateMob(g);
// }
for (Mob m : polygons) {
m.updateMob(g);
}
for (Mob m : explosions) {
m.updateMob(g);
}
} | 3 |
@Override
public Class getColumnClass(int indiceColonne){
//System.out.println("ModeleListeLocations::getColumnClass()") ;
switch(indiceColonne){
case 0 :
return String.class ;
case 1 :
return String.class ;
case 2 :
return String.class ;
case 3 :
return Date.class ;
case 4 :
return Date.class ;
case 5 :
return Byte.class ;
case 6 :
return JButton.class ;
default :
return Object.class ;
}
} | 7 |
@SuppressWarnings("unused")
private static void CollatzSequence(){
Scanner keyboard = new Scanner(System.in);
int n;
System.out.println("Starting number: ");
n = keyboard.nextInt();
int xPos = 0;
int steps = 0;
int largestValue = 0;
while(n > 1){
if(n > largestValue)
largestValue = n;
if(n % 2 == 0) // even numbers
n /= 2;
else
n =(3*(n)) + 1;; // odd numbers
System.out.print(n + "\t");
xPos += 1;
steps += 1;
if(xPos == 10){
System.out.print("\n");
xPos = 0;
}
}
if(n == 1)
System.out.print(1 + "\n\n");
System.out.println("The largest value was " + largestValue + ".");
System.out.println("Terminated after " + steps + " steps.");
keyboard.close();
} | 5 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final JPcodePK other = (JPcodePK) obj;
if (!Objects.equals(this.IdOrder, other.IdOrder)) {
return false;
}
if (!Objects.equals(this.Pcode, other.Pcode)) {
return false;
}
if (!Objects.equals(this.Salesman, other.Salesman)) {
return false;
}
return true;
} | 5 |
public static List<String> explodeToList(String delimiter, String string) {
if (delimiter == null || string == null)
throw new IllegalArgumentException("Null object");
ArrayList<String> v = new ArrayList<String>();
StringBuffer curToken = new StringBuffer();
StringBuffer delimReader = new StringBuffer();
int length = string.length();
int delimiterLength = delimiter.length();
for (int i = 0; i < length; i++) {
// get the character
char c = string.charAt(i);
// check if it could be the delimiter
delimReader.setLength(0);
if (c == delimiter.charAt(0)) {
// check the whole delimiter
boolean equals = true;
int j = 1;
for (; (j < delimiterLength) && ((j + i) < length); j++) {
if (string.charAt(i + j) != delimiter.charAt(j)) {
equals = false;
break;
}
}
// delimiter found !!
if (j == delimiterLength && equals) {
i = i + delimiterLength - 1;
v.add(curToken.toString());
curToken.setLength(0);
} else
curToken.append(c);
} else
curToken.append(c);
}
v.add(curToken.toString());
curToken.setLength(0);
return v;
} | 9 |
public void buildHierarchy() {
String[] keys;
int ancestorCount;
YagoCategoryNodeOld node;
ArrayList<YagoCategoryNodeOld> nodeArray;
// order nodes by how many ancestors they have. Nodes with more ancestors MUST be at a lower level
// than those with less
keys = this.nodeMap.keySet().toArray(new String[]{});
for(int i = 0; i < keys.length; i++) {
node = this.nodeMap.get(keys[i]);
ancestorCount = node.getNumOfAncestors();
nodeArray = this.buildMap.get(ancestorCount);
if(nodeArray == null) {
nodeArray = new ArrayList<YagoCategoryNodeOld>();
this.buildMap.put(ancestorCount, nodeArray);
}
nodeArray.add(node);
}
Integer[] buildKeys;
YagoCategoryNodeOld parent;
YagoCategoryNodeOld ancestor;
ArrayList<YagoCategoryNodeOld> ancestors;
// Start from 0 and work our way up, establish the immediate parents. Those with 0 are top level classes
// and must be attached to root
buildKeys = this.buildMap.keySet().toArray(new Integer[]{});
for(int i = 0; i < buildKeys.length; i++) {
nodeArray = this.buildMap.get(buildKeys[i]);
System.out.println(nodeArray.size());
}
for(int i = 0; i < buildKeys.length; i++) {
nodeArray = this.buildMap.get(buildKeys[i]);
for(int j = 0; j < nodeArray.size(); j++) {
node = nodeArray.get(j);
ancestors = node.getAncestors();
if(ancestors.size() == 0) {
node.setParent(this.rootNode);
this.rootNode.addChild(node);
} else {
parent = null;
for(int k = 0; k < ancestors.size(); k++) {
ancestor = ancestors.get(k);
if(parent == null) {
parent = ancestor;
// find lowest-ranked ancestor - that's the immediate parent
} else if (parent.getNumOfAncestors() > ancestor.getNumOfAncestors()){
parent = ancestor;
} // else do nothing
}
node.setParent(parent);
parent.addChild(node);
}
}
}
} | 9 |
private int getGroupPosition(String name, String fnmPrefix) {
ArrayList groupNames = (ArrayList) gNamesMap.get(name);
if (groupNames == null) {
EIError.debugMsg("No group names for " + name, EIError.ErrorLevel.Error);
return -1;
}
String nm;
for (int i = 0; i < groupNames.size(); i++) {
nm = (String) groupNames.get(i);
if (nm.equals(fnmPrefix)) {
return i;
}
}
EIError.debugMsg("No " + fnmPrefix + " group name found for " + name, EIError.ErrorLevel.Error);
return -1;
} | 3 |
public static void main(String[] args) throws Exception {
playerNo = Integer.parseInt(args[0].trim());
int port = portOffset + playerNo;
Socket socket = new Socket("localhost", port);
BufferedReader in =
new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.print("My name is " + name);
out.flush();
char[] cbuf = new char[inputLength];
String input;
while(true) {
try {
if (in.ready()) {
in.read(cbuf, 0, inputLength);
input = new String(cbuf);
input = input.trim();
receive(input);
if(inputPrompt.matcher(input).find()) {
out.print(getAction(input));
out.flush();
} else if (input.equals("SHUTDOWN")) {
socket.close();
System.exit(0);
}
}
} catch(Exception e) {
System.out.println("Caught exception: ");
e.printStackTrace();
socket.close();
System.exit(0);
}
}
} | 5 |
private void acao101(Token token) throws SemanticError {
try {
String nomePrograma = token.getLexeme();
IdentificadorPrograma idPrograma = new IdentificadorPrograma(
nomePrograma);
tabela.add(idPrograma, nivelAtual);
} catch (IdentificadorJaDefinidoException e) {
throw new SemanticError(e.getMessage(), token.getPosition());
}
} | 1 |
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info("WANcostResummingServlet3h Got a GET...");
caches.reload();
link[][] linkArr = new link[caches.lSources.size()][caches.lDestinations.size()];
for (int i = 0; i < caches.lSources.size(); i++)
for (int j = 0; j < caches.lDestinations.size(); j++)
linkArr[i][j] = new link();
// load data younger than 3 hours
Date currTime = new Date();
Date cutoffTime = new Date(currTime.getTime() - 3 * 3600l * 1000);
Filter f = new Query.FilterPredicate("timestamp", FilterOperator.GREATER_THAN, cutoffTime);
Query q = new Query("FAXcost1h").setFilter(f);
String res="";
List<Entity> lRes = datastore.prepare(q).asList(FetchOptions.Builder.withLimit(10000).chunkSize(3000));
res+="results in last 3 h: "+ lRes.size()+"\n";
log.warning("results in last 3h : "+ lRes.size());
for (Entity result : lRes) {
String s = (String) result.getProperty("source");
String d = (String) result.getProperty("destination");
int i = caches.lSources.indexOf(s);
int j = caches.lDestinations.indexOf(d);
if(i<0 || j<0) {
log.warning(s+" "+d+" "+i+" "+j);
continue;
}
linkArr[i][j].measurements++;
if (result.getProperty("rate")==null)
log.severe("rate is null");
else
linkArr[i][j].sum += ((Double)result.getProperty("rate")).floatValue();
}
log.info("putting new data");
List<Entity> lIns =new ArrayList<Entity>();
for (int i = 0; i < caches.lSources.size(); i++){
for (int j = 0; j < caches.lDestinations.size(); j++){
if (linkArr[i][j].getAvg()<0) continue;
Entity result = new Entity("FAXcost3h");
result.setProperty("timestamp", currTime);
result.setProperty("source", caches.lSources.get(i));
result.setProperty("destination", caches.lDestinations.get(j));
result.setUnindexedProperty("rate", linkArr[i][j].getAvg());
lIns.add(result);
}
}
datastore.put(lIns);
resp.getWriter().println(res);
} | 9 |
@Override
public Status execute(String command) throws MenuException {
switch (command) {
case "I":
displayInstructions();
return HELP;
case "H":
displayHints();
return HELP;
case "Q":
return MAIN_MENU;
default:
throw new MenuException(HELP);
}
} | 3 |
@Override
public void start() {
System.out.println("start the car");
super.start();
} | 0 |
private void checkForIdenticalElements(){
boolean test = false;
for(int i=0; i<this.nItems; i++){
int sum = 0;
double check = this.scores0[i][0];
for(int j=0; j<this.nPersons; j++)if(this.scores0[i][j]==check)sum++;
if(sum==this.nPersons){
this.sameCheck = 1;
test = true;
}
}
for(int i=0; i<this.nPersons; i++){
int sum = 0;
double check = this.scores0[0][i];
for(int j=0; j<this.nItems; j++)if(this.scores0[j][i]==check)sum++;
if(sum==this.nItems){
this.sameCheck = 2;
if(test)this.sameCheck = 3;
}
}
} | 9 |
public void listen() throws InvalidUIntException {
System.out.println("listening");
int available;
try {
Thread.sleep(2500);
while(true) {
while ((available = sis.available()) == 0)
{
Thread.sleep(100);
}
byte id = sis.readByte();
sVLQ payloadLength = new sVLQ(sis.readByte());
available = available - 1 - payloadLength.getBytes().length;
if(available < payloadLength.getLong()) {
Thread.sleep(100);
}
byte[] bytes = new byte[available];
for (int i = 0; i < available; i++)
{
bytes[i] = sis.readByte();
}
if (id == 0)
{
logger.Log("ID 0 = Protocol Version (" + available + " bytes available)");
logger.Log("Protocol Version is " + new UInt32(bytes).getInt());
//PacketClientConnect pcc = new PacketClientConnect();
//pcc.read(sis);
}
else
{
logger.Log("Packet: " + Packets.getName(id) + " ID: " + id + " rcvd");
logger.Log("available says " + available);
logger.Log("sVLQ length = " + payloadLength.getLong());
logger.Log("Created bytes["+available+"], but i dont know what to do with it");
}
Thread.sleep(100);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public void setwnd() {
GraphicsDevice dev = getGraphicsConfiguration().getDevice();
if (prefs == null)
return;
try {
dev.setDisplayMode(prefs);
dev.setFullScreenWindow(null);
setVisible(false);
dispose();
setUndecorated(false);
setVisible(true);
} catch (Exception e) {
throw (new RuntimeException(e));
}
prefs = null;
} | 2 |
@SuppressWarnings("unchecked")
private ArrayList<String>[] partFile(String fichier, int nbNodes) {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(fichier)));
String line = null;
ArrayList<String> parts[] = new ArrayList[nbNodes];
for(int i=0; i<nbNodes; i++)
parts[i] = new ArrayList<>();
int i=0;
if(mode==0){
System.out.println("mode "+mode);
while((line=br.readLine())!=null){
String[] tmp = line.split(" ");
for(String s: tmp){
parts[i].add(s);
i = (i+1)%nbNodes;
}
}
} else {
System.out.println("mode "+mode);
while((line=br.readLine())!=null){
String[] tmp = line.split(" ");
for(String s: tmp){
parts[i].add(s);
}
}
while(++i<nbNodes)
parts[i].addAll(parts[0]);
}
br.close();
return parts;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} | 8 |
public static void main(String argv[]) {
try {
File fXmlFile = new File("D:\\Java SE\\src\\xml\\staff.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for(int i = 0; i < nList.getLength(); i++){
Node nNode = nList.item(i);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if(nNode.getNodeType() == Node.ELEMENT_NODE){
Element eElement = (Element) nNode;
System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 3 |
private void addRowToTable(List<QuestDTO> usersList) {
for (QuestDTO quest : usersList) {
tableModel.addRow(quest.toArray());
}
} | 1 |
private boolean checkwalls(Location loc)
{
Location north = loc.add(0, -1);
Location east = loc.add(1, 0);
Location south = loc.add(0, 1);
Location west = loc.add(-1, 0);
int yes = 0;
if (north.getY() >= 0 && map[north.getX()][north.getY()] == nonWall)
yes++;
if (east.getX() < xSize && map[east.getX()][east.getY()] == nonWall)
yes++;
if (south.getY() < ySize && map[south.getX()][south.getY()] == nonWall)
yes++;
if (west.getX() >= 0 && map[west.getX()][west.getY()] == nonWall)
yes++;
return yes > 1;
} | 8 |
@Override
public boolean blocked(Node n) {
if (n == null || !walkable(n)) {
return true;
}
if (n.getPrev() == null) {
return false;
}
if (!walkable(n.getPrev())) {
return true;
}
final Node p = n.getPrev();
return checkBlocked(n, p) || checkBlocked(p, n);
} | 5 |
public FirstTask(List<Float> randomNumbers) throws IOException {
String choice = "";
while (!choice.equals("back")) {
printMenu();
randomNumbers.clear();
choice = reader.readLine();
if (choice.equals("1")) {
System.out.print("Равномерное распределение\n" +
"Введите a и b\n" +
"a = ");
int a = Integer.parseInt(reader.readLine());
System.out.print("b = ");
int b = Integer.parseInt(reader.readLine());
Uniform uniform = new Uniform(randomNumbers, a, b);
printDistr(uniform);
} else
if (choice.equals("2")) {
System.out.print("Экспотенциальное распределение с параметром λ\n" +
"Введите λ\n" +
"λ = ");
float lamda = Float.parseFloat(reader.readLine());
Expotential expotential = new Expotential(randomNumbers, lamda);
printDistr(expotential);
} else if (choice.equals("3")) {
System.out.print("Нормальное распределение с параметрами а и σ^2\n" +
"Введите a\n" +
"a = ");
float a = Float.parseFloat(reader.readLine());
Normal normal = new Normal(randomNumbers, a, Util.StandardDeviation(randomNumbers));
printDistr(normal);
} else if (choice.equals("4")) {
System.out.print("Логнормальное распределение\n" +
"Введите a\n" +
"a = ");
float a = Float.parseFloat(reader.readLine());
LogNorm logNorm = new LogNorm(randomNumbers, a);
printDistr(logNorm);
} else if (choice.equals("5")) {
System.out.print("Распределение вейбудла\n" +
"Введите а\n" +
"a = ");
float a = Float.parseFloat(reader.readLine());
Weibull weibull = new Weibull(randomNumbers, a, Util.StandardDeviation(randomNumbers));
printDistr(weibull);
} else if (choice.equals("a")) {
fullPrint = !fullPrint;
if (fullPrint) {
System.out.println("Полный вывод включен");
} else {
System.out.println("Полный вывод выключен");
}
}
}
} | 8 |
private void deleteSession()
{
System.out.println("Deleting a complete session ...");
// ---------------------------------------------------
// get list of features FESVo IDs:
int [] ids = this.loader.getFeaturesIDs();
// convert into array of Integer:
Integer [] idsInt = Utilities.toIntegerArray(ids);
// create a an input dialog for users to select a horizon source id:
Integer selectedSrc = (Integer) JOptionPane.showInputDialog(
null, "Please select a feature (e.g. horizon) source ID:", "Horizons source",
JOptionPane.QUESTION_MESSAGE, null, idsInt, null);
// exit if no source id was selected:
if (selectedSrc == null)
return;
// [TEST] print user's selection:
System.out.println("User selected: " + selectedSrc);
// ---------------------------------------------------
// get list of insertion type grouping effective time:
ArrayList<DataTimestamp> timestamps = this.loader.getInsertionTypeGroupingEffectiveTimestamps(selectedSrc);
// insert a "Baseline" timestamp
timestamps.add(timestamps.size(), new DataTimestamp(this.src.srdsSrcID));
// if need to reload; to be used in the loop:
boolean reload = false;
while (true){
// create a an input dialog for users to select a timestamp:
DataTimestamp ts = (DataTimestamp) JOptionPane.showInputDialog(
null, "Please select a session to completely delete:", "Timestamps of Data Input",
JOptionPane.QUESTION_MESSAGE, null, timestamps.toArray(), this.selectedTimestamp);
// exit if no source id was selected:
if (ts == null){
if (reload)
break;
else
return; //exit
}//if
// [TEST] print user's selection:
System.out.println("User selected: " + ts);
// load and render only selected timestamp:
// ----------------------------------------
// clear FESVo:
this.loader.clearFeaturesCache();
// set requested timestamp with an option to load only alone:
this.loader.setFeaturesTimestamp(ts, true);
// set requested feature ID:
this.loader.setFeaturesIDsToLoad(selectedSrc);
// reload and render:
this.renderer.reloadHorizons();
// ----------------------------------------
// verify with user:
int ans = JOptionPane.showConfirmDialog(
null,
"Is this the object you want to delete?",
"Confirmation of deletion",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (ans != JOptionPane.YES_OPTION){
reload = true; // need to reload
continue;
}//if
// [23.2.2013] check if user didn't sign in:
if (this.userID == 0){
this.userSignIn("You must sign in to complete this task. Please, enter your user ID.");
// if user decided not to sign in, exit:
if (this.userID == 0){
JOptionPane.showMessageDialog(
frame,
"This task was not completed as you didn't sign in!",
"Error!",
JOptionPane.ERROR_MESSAGE);
break;
}
}
// delete if user confirms:
this.loader.deleteHorizon(selectedSrc, ts, this.userID);
// exit the loop:
break;
}//while
// clear FESVo:
this.loader.clearFeaturesCache();
// set requested timestamp to latest:
this.loader.setFeaturesTimestamp(null);
// reload and render:
this.renderer.reloadHorizons();
}//deleteSession() | 7 |
public String getBacklink(String name) throws IOException {
String namelist = WakeBackends.namelist;
if (namelist.split(name.split("[ __]")[0] + ",").length == 2) {
if (namelist.split(name.split("[ __]")[0] + ",")[1].split(",")[0]
.equals("&i=1"))
; // ここ注意 &i=1を読み飛ばしている うかつに消さないように
else if (!namelist.split(name.split("[ __]")[0] + ",")[1]
.split(",")[0].isEmpty())
name = name.split("[ __]")[0]
+ namelist.split(name.split("[ __]")[0] + ",")[1]
.split(",")[0];
}
namelist = namelist
+ ",大沢事務所,81プロデュース,青二プロダクション,元氣プロジェクト,プロ・フィット,マウスプロモーション,賢プロダクション,ケンユウオフィス,アクセルワン,東京俳優生活協同組合,テアトル・エコー,シグマ・セブン,ぷろだくしょんバオバブ,ホーリーピーク,ゆーりんプロ,";
URL url = new URL(
"http://ja.wikipedia.org/w/api.php?action=query&format=xml&list=backlinks&bllimit=50000&blnamespace=0&bltitle="
+ name);
StringBuilder backlinkTitle = new StringBuilder();
StringBuilder backlinkSeriesTitle = new StringBuilder();
try {
// backlinksエレメントをターゲットに
Element element = new SAXBuilder().build(url).getRootElement()
.getChild("query").getChild("backlinks");
// 子要素であるblのイテレータを得る
Iterator<Element> itr = element.getChildren("bl").iterator();
// title属性のみをListへ格納 ns != 0 なら除外
ArrayList<String> al = new ArrayList<String>();
while (itr.hasNext()) {
Element e = (Element) itr.next();
al.add(e.getAttributeValue("title"));
}
// シリーズもの、登場人物は デリミタ <<>> の後へ回す
for (String s : al) {
if(namelist.indexOf("," + s.split("[ __]")[0] + ",",0) != -1)
continue;
if (p_s.matcher(s).find())
backlinkSeriesTitle.append("<>" + s);
else
backlinkTitle.append("<>" + s);
}
} catch (JDOMException e) {
}
return new String(backlinkTitle) + "<<>>"
+ new String(backlinkSeriesTitle);
} | 8 |
public LocationHeader(String rawHeader) throws MalformedHeaderException {
String[] data = rawHeader.split(" ");
if (!data[0].equals("GET")) {
throw new MalformedHeaderException("Expected get header, received " + data[0]);
}
if (!data[2].matches("HTTP/1.[0-1]")) {
throw new MalformedHeaderException("Expected get header, received " + data[0]);
}
String[] location = data[1].split("/");
if (location.length > 1) {
this.channel = location[1];
}
else throw new MalformedHeaderException("Invalid channel name");
} | 3 |
private boolean checkforLinearity(Production[] p)
{
int count=0;
for (int i=0; i<p.length; i++)
{
if (ProductionChecker.isRightLinear(p[i]))
count++;
}
if (count==p.length)
{
JOptionPane.showMessageDialog(environment.getComponent(0), "This is a right-linear Grammar (Regular Grammar and Context-Free Grammar)", "Grammar Type"
, JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
{
count=0;
for (int i=0; i<p.length; i++)
{
if (ProductionChecker.isLeftLinear(p[i]))
count++;
}
if (count==p.length)
{
JOptionPane.showMessageDialog(environment.getComponent(0), "This is a left-linear Grammar (Regular Grammar and Context-Free Grammar)", "Grammar Type"
, JOptionPane.INFORMATION_MESSAGE);
return true;
}
}
return false;
} | 6 |
private static void updateInnerEntry(int mod, String name, CtClass clazz, boolean outer) {
ClassFile cf = clazz.getClassFile2();
InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute(
InnerClassesAttribute.tag);
if (ica == null)
return;
int n = ica.tableLength();
for (int i = 0; i < n; i++)
if (name.equals(ica.innerClass(i))) {
int acc = ica.accessFlags(i) & AccessFlag.STATIC;
ica.setAccessFlags(i, mod | acc);
String outName = ica.outerClass(i);
if (outName != null && outer)
try {
CtClass parent = clazz.getClassPool().get(outName);
updateInnerEntry(mod, name, parent, false);
}
catch (NotFoundException e) {
throw new RuntimeException("cannot find the declaring class: "
+ outName);
}
break;
}
} | 6 |
void connectToServerActionPerformed(ActionEvent e) {
boolean allOk = true;
client.setHost(serverName.getText());
addHistoryItem(oldServers, "serverNameHistory.txt", serverName.getText());
if (!(client.loadGame(theGameClass.getText()))) {
allOk = false;
} else {
client.setProtocolName(theGameClass.getText());
printOutput("Protokoll " + theGameClass.getText() + " geladen !");
addHistoryItem(oldGames, "protocolHistory.txt", theGameClass.getText());
}
try {
client.setPort(Integer.parseInt(portNumber.getText()));
if ((Integer.parseInt(portNumber.getText()) < 1024) || (Integer.parseInt(portNumber.getText()) > 9999)) {
allOk = false;
printOutput("Keine gueltige Port Nummer!");
}
} catch (java.lang.NumberFormatException ex) {
System.err.print("Error:" + ex);
client.log("Error:" + ex + "\n invalid PortNumber");
printOutput("Keine gueltige Port Nummer!");
allOk = false;
} // catch
if (allOk) {
Thread t = new Thread(this);
t.start();
}
} | 5 |
public boolean isPossibleBreakpoint() {
return possibleBreakpoint;
} | 0 |
@Test
public void testGetS2() {
System.out.println("getS2");
Move instance = new Move(6,9);
int expResult = 9;
int result = instance.getS2();
assertEquals(expResult, result);
} | 0 |
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.