text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public void setData(List<Integer> data) {
// System.out.println ("Setting display: " + this.id + " with data");
int[] elapsedTimeByteArray = new int[4];
int[] stopTimeByteArray = new int[4];
for (int i = 0; i < 4; i ++){
elapsedTimeByteArray[i]=data.get(i);
//System.out.println((byte)(int)data.get(i));
}
for (int i = 4; i <8; i ++){
stopTimeByteArray[i-4]=data.get(i);
//System.out.println((byte)(int)data.get(i));
}
System.out.print ("Stoptime: " + MarineControlJProxy.intArrayToInt(stopTimeByteArray));
System.out.println(" Elapsedtime: " + MarineControlJProxy.intArrayToInt(elapsedTimeByteArray));
int maxVal = MarineControlJProxy.intArrayToInt(stopTimeByteArray);
int elapsedVal = MarineControlJProxy.intArrayToInt(elapsedTimeByteArray);
//System.out.println((float)elapsedVal/maxVal);
if (elapsedVal>=maxVal) {this.setForeground(Color.RED);}
else if ((float)elapsedVal/maxVal > 0.7) {
progressMeter.setForeground(Color.YELLOW);
}
else {
progressMeter.setForeground(Color.GREEN);}
if (progressMeter.getValue()+1 != elapsedVal) System.out.println("Error in meter " + this.id +
" when meter was: " + progressMeter.getValue() + " request change to: " + elapsedVal );
progressMeter.setMaximum(maxVal);
progressMeter.setValue(elapsedVal);
if (autoUpdateStoptime){
stopTimeSpinner.setValue(maxVal);
}
elapsedOf.setText(""+elapsedVal +"/" + maxVal + "minutes." + (float)elapsedVal/60 + "/" + (float) maxVal/60 + " hours");
} | 6 |
protected void checkKey(K key) {
if (key == null)
throw new Error("Invalid key:null.");
} | 1 |
public Iterator<Item> iterator() {
return new ListIterator<Item>(first);
} | 0 |
public static void main(String[] args) {
int direction = (int) (Math.random() * 4);
switch (direction) {
case NORTH:
System.out.println("travelling north");
break;
case SOUTH:
System.out.println("travelling south");
break;
case EAST:
System.out.println("travelling east");
break;
case WEST:
System.out.println("travelling west");
default:
assert false;
}
} | 4 |
public static int[] insertionSort(int[] array) {
if(array == null || array.length <= 1) {
return array;
}
for(int i = 1; i < array.length; i++) {
int temp = array[i];
int j = i;
while(j > 0 && temp < array[j - 1]) {
array[j] = array[j - 1];
j--;
}
array[j] = temp;
}
return array;
} | 5 |
public int getFreeEntityId()
{
for (int i = 0; i < entities.length; i++)
{
if (entities[i] == null)
return i;
}
return -1;
} | 2 |
private void parseSettings( Token token ) {
if ( token.equals( "CLASS" ) ) {
token = getNextToken();
if ( isNewLine( token ) ) {
throwException( "Expected a class name, recieved new line." );
}
setClass( toCamelCase( token ) );
// check for optional table name
token = getNextToken();
if ( isNewLine( token ) )
return;
table.setTableName( token.getValue() );
}
else {
throwException( "Unexpected token, expected CLASS" );
}
} | 3 |
public GUI(ArrayList<ServerStatus> serverList, getStatus tStatus, Console tC){
status = tStatus;
c = tC;
this.setLayout(new BorderLayout());
this.setTitle("Diablo III - Server Status");
//menu Panel
JPanel menuPanel = new JPanel();
menuPanel.setLayout(new GridLayout(5,1));
// Refresh button
JButton bRefresh = new JButton("Refresh");
bRefresh.setActionCommand("refreshList");
bRefresh.addActionListener(this);
menuPanel.add(bRefresh);
// Sound Checkbox
cSound = new JCheckBox("Sound");
menuPanel.add(cSound);
// auto-refresh
JPanel timerPanel = new JPanel();
cRefresh = new JCheckBox();
cRefresh.setActionCommand("arClick");
cRefresh.addActionListener(this);
timerText = new JTextField(3);
timerText.setHorizontalAlignment(JTextField.RIGHT);
timerText.setText("120");
JLabel timerLabel = new JLabel("sec");
timerPanel.add(cRefresh);
timerPanel.add(timerText);
timerPanel.add(timerLabel);
menuPanel.add(timerPanel);
// Console Button
JButton bConsole = new JButton("Console");
bConsole.setActionCommand("console");
bConsole.addActionListener(this);
menuPanel.add(bConsole);
this.setSize(932, 360);
boolean showServerList = true;
if (showServerList)
{
serverPanel = createServerStatusPanel(serverList);
}
sBar = new Statusbar("starte...");
this.add(menuPanel, BorderLayout.WEST);
if (showServerList)
{
this.add(serverPanel, BorderLayout.CENTER);
}
this.add(sBar, BorderLayout.PAGE_END);
// optimiert die groesse des Fensters
this.pack();
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
c.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
String command = c.cinText();
String tCom = "/sBar ";
if (command.startsWith(tCom)){
sBar.setText(command.replaceFirst(tCom, ""));
}
tCom = "/refresh";
if (command.startsWith(tCom)){
}
tCom = "/changes";
if (command.startsWith(tCom)){
c.cout(status.getChangedServerList().toString());
}
tCom = "/new";
if (command.startsWith(tCom)){
c.cout(status.getServerList().toString());
}
tCom = "/old";
if (command.startsWith(tCom)){
c.cout(status.getServerListOld().toString());
}
tCom = "/sound";
if (command.startsWith(tCom)){
alarm.play();
}
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
sBar.clear();
} | 9 |
public void removeOnetimeLocals() {
cond = cond.removeOnetimeLocals();
if (type == FOR) {
if (initInstr != null)
initInstr.removeOnetimeLocals();
incrInstr.removeOnetimeLocals();
}
super.removeOnetimeLocals();
} | 2 |
public ViewPersonnelView(PayrollSystemModel model) {
this.model = model;
deleteBtn = new JButton(new ImageIcon(
getClass().getResource("/images/buttons/delete.png")));
statusLbl = new JLabel("Status: No Data Found!");
statusLbl.setIcon(loadScaledImage("/images/notifs/warning.png",.08f));
selectClientLbl = new JLabel("Select Client: ");
clientCBox = new JComboBox<Object>();
personnelTable = new JTable(30,12);
personnelTable.setRowHeight(32);
personnelTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
personnelTable.setColumnSelectionAllowed(true);
personnelTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
personnelTable.setEnabled(false);
ArrayList<String> columnName = model.getTableColumn("personnel");
columnName.add(0, "No.");
tableModel = new DefaultTableModel(columnName.toArray(),0);
personnelTable.setModel(tableModel);
header = personnelTable.getTableHeader();
header.setBackground(new Color(0xFAFAFA));
header.setPreferredSize(new Dimension(header.getPreferredSize().width * 999, 25));
header.setAlignmentX(JLabel.CENTER_ALIGNMENT);
header.setReorderingAllowed(false);
for(int i = 0; i < personnelTable.getColumnCount(); i++){
if(i == 0){
personnelTable.getColumnModel().getColumn(i).setCellRenderer(
new ColorfulCellRenderer(new Color(0xFAFAFA),
Color.BLACK,Utils.colorfulPColumn));
personnelTable.getColumnModel().getColumn(i).setPreferredWidth(40);
}else if(Utils.colorfulPColumn.contains(i)){
switch(i){
case 2:
personnelTable.getColumnModel().getColumn(i).setCellRenderer(
new ColorfulCellRenderer(new Color(0xbee1fe),
Color.BLACK,Utils.colorfulPColumn));
break;
default:
personnelTable.getColumnModel().getColumn(i).setCellRenderer(
new ColorfulCellRenderer(Color.ORANGE,Color.BLACK,
Utils.colorfulPColumn));
break;
};
}else
personnelTable.getColumnModel().getColumn(i).setCellRenderer(
new ColorfulCellRenderer(Color.WHITE,Color.BLACK,
Utils.colorfulPColumn));
}
personnelTable.addMouseListener(new TableMouseListener());
personnelPane = new JScrollPane(personnelTable,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
modifyUI();
} | 4 |
public String getStartCity() {
return startCity;
} | 0 |
public void setId(Long id)
{
Id = id;
} | 0 |
public <T> List<T> dumpResultSet(ResultSet rs, Class clazz) {
// get the field mapping
ArrayList<FieldMap> fieldMap = getFieldMap(rs, clazz);
List<T> elements = new ArrayList<T>();
try {
while (rs.next()) {
Object newInstance = clazz.newInstance();
for (int i = 0; i < fieldMap.size(); i++) {
int columnPosition = fieldMap.get(i).getTableFieldColumn();
Object value = rs.getObject(columnPosition);
BeanUtils.copyProperty(newInstance, fieldMap.get(i).getObjectFieldName(), value);
}
elements.add((T) newInstance);
}
} catch (SQLException e) {
StackUtil.logStackTrace(log, e);
} catch (InstantiationException e) {
StackUtil.logStackTrace(log, e);
} catch (IllegalAccessException e) {
StackUtil.logStackTrace(log, e);
} catch (InvocationTargetException e) {
StackUtil.logStackTrace(log, e);
} catch (Exception e) {
StackUtil.logStackTrace(log, e);
}
return elements;
} | 7 |
@Test
public void testNumDoors() {
int count = 0;
for (int i = 0; i < board.getCells().size(); i++) {
if (board.getCells().get(i).isDoorway()) {
count++;
}
}
Assert.assertEquals(NUM_DOORS, count);
} | 2 |
public void keyPressed(KeyEvent keyEvent) {
Iterator<PComponent> it = components.iterator();
while (it.hasNext()) {
PComponent comp = it.next();
if (shouldHandleKeys) {
if (comp.shouldHandleKeys())
comp.keyPressed(keyEvent);
}
else {
if (comp instanceof PFrame) {
for (PComponent component : ((PFrame) comp).getComponents())
if (component.forceKeys())
component.keyPressed(keyEvent);
}
else if (comp.forceKeys())
comp.keyPressed(keyEvent);
}
}
} | 7 |
public <V> Adapter.Getter<V> makeGetter(String methodName, Class<V> _class) {
try {
final Method method = version.getClass().getMethod(methodName);
return new Adapter.Getter<V>() {
public V call() {
try{
lock.lock();
if (firstTime) {
((Recoverable)version).backup();
firstTime = false;
}
Thread.onCommitOnce( new Runnable() {
public void run() {
lock.unlock();
}
});
Thread.onAbortOnce( new Runnable() {
public void run() {
lock.unlock();
((Recoverable)version).recover();
}
});
return (V)method.invoke(version);
} catch (IllegalArgumentException ex) {
throw new PanicException(ex);
} catch (IllegalAccessException ex) {
throw new PanicException(ex);
} catch (InvocationTargetException ex) {
throw new PanicException(ex);
}
}};
} catch (NoSuchMethodException e) {
throw new PanicException(e);
}
} | 5 |
public static void main(String args[])
{
Termio UserInput = new Termio(); // Termio IO Object
boolean Done = false; // Main loop flag
String Option = null; // Menu choice from user
Event Evt = null; // Event object
boolean Error = false; // Error flag
SCSMonitor Monitor = null; // The environmental control system monitor
boolean puertaRota = false; // Estos parametros se utilizaran para mostrar
boolean ventanaRota = false; // si existe alguna alerta de seguridad
boolean movimiento = false; //
/*float TempRangeHigh = (float)100.0; // These parameters signify the temperature and humidity ranges in terms
float TempRangeLow = (float)0.0; // of high value and low values. The ECSmonitor will attempt to maintain
float HumiRangeHigh = (float)100.0; // this temperature and humidity. Temperatures are in degrees Fahrenheit
float HumiRangeLow = (float)0.0; // and humidity is in relative humidity percentage.
*/
/////////////////////////////////////////////////////////////////////////////////
// Get the IP address of the event manager
/////////////////////////////////////////////////////////////////////////////////
if ( args.length != 0 )
{
// event manager is not on the local system
Monitor = new SCSMonitor( args[0] );
} else {
Monitor = new SCSMonitor();
} // if
// Here we check to see if registration worked. If ef is null then the
// event manager interface was not properly created.
if (Monitor.IsRegistered() )
{
Monitor.start(); // Here we start the monitoring and control thread
while (!Done)
{
// Here, the main thread continues and provides the main menu
System.out.println( "\n\n\n\n" );
System.out.println( "Security Control System (SCS) Command Console: \n" );
if (args.length != 0)
System.out.println( "Using event manger at: " + args[0] + "\n" );
else
System.out.println( "Using local event manger \n" );
System.out.println( "System status:" + (Monitor.isSystemStatus() ? "Enable":"Disable") + "\n");
// System.out.println( "Set Temperature Range: " + TempRangeLow + "F - " + TempRangeHigh + "F" );
// System.out.println( "Set Humidity Range: " + HumiRangeLow + "% - " + HumiRangeHigh + "%\n" );
System.out.println( "Select an Option: \n" );
System.out.println( "1: Enable system" );
System.out.println( "2: Disable System" );
System.out.println( "X: Stop System\n" );
System.out.print( "\n>>>> " );
Option = UserInput.KeyboardReadString();
//////////// option 1 ////////////
if ( Option.equals( "1" ) )
{
Monitor.setSystemStatus(true);
}
//////////// option 2 ////////////
if ( Option.equals( "2" ) )
{
Monitor.setSystemStatus(false);
}
/*
if ( Option.equals( "1" ) )
{
// Here we get the temperature ranges
Error = true;
while (Error)
{
// Here we get the low temperature range
while (Error)
{
System.out.print( "\nEnter the low temperature>>> " );
Option = UserInput.KeyboardReadString();
if (UserInput.IsNumber(Option))
{
Error = false;
TempRangeLow = Float.valueOf(Option).floatValue();
} else {
System.out.println( "Not a number, please try again..." );
} // if
} // while
Error = true;
// Here we get the high temperature range
while (Error)
{
System.out.print( "\nEnter the high temperature>>> " );
Option = UserInput.KeyboardReadString();
if (UserInput.IsNumber(Option))
{
Error = false;
TempRangeHigh = Float.valueOf(Option).floatValue();
} else {
System.out.println( "Not a number, please try again..." );
} // if
} // while
if ( TempRangeLow >= TempRangeHigh )
{
System.out.println( "\nThe low temperature range must be less than the high temperature range..." );
System.out.println( "Please try again...\n" );
Error = true;
} else {
Monitor.SetTemperatureRange(TempRangeLow, TempRangeHigh );
} // if
} // while
} // if
//////////// option 2 ////////////
if ( Option.equals( "2" ) )
{
// Here we get the humidity ranges
Error = true;
while (Error)
{
// Here we get the low humidity range
while (Error)
{
System.out.print( "\nEnter the low humidity>>> " );
Option = UserInput.KeyboardReadString();
if (UserInput.IsNumber(Option))
{
Error = false;
HumiRangeLow = Float.valueOf(Option).floatValue();
} else {
System.out.println( "Not a number, please try again..." );
} // if
} // while
Error = true;
// Here we get the high humidity range
while (Error)
{
System.out.print( "\nEnter the high humidity>>> " );
Option = UserInput.KeyboardReadString();
if (UserInput.IsNumber(Option))
{
Error = false;
HumiRangeHigh = Float.valueOf(Option).floatValue();
} else {
System.out.println( "Not a number, please try again..." );
} // if
} // while
if ( HumiRangeLow >= HumiRangeHigh )
{
System.out.println( "\nThe low humidity range must be less than the high humidity range..." );
System.out.println( "Please try again...\n" );
Error = true;
} else {
Monitor.SetHumidityRange(HumiRangeLow, HumiRangeHigh );
} // if
} // while
} // if
*/
//////////// option X ////////////
if ( Option.equalsIgnoreCase( "X" ) )
{
// Here the user is done, so we set the Done flag and halt
// the environmental control system. The monitor provides a method
// to do this. Its important to have processes release their queues
// with the event manager. If these queues are not released these
// become dead queues and they collect events and will eventually
// cause problems for the event manager.
Monitor.Halt();
Done = true;
System.out.println( "\nConsole Stopped... Exit monitor mindow to return to command prompt." );
Monitor.Halt();
} // if
} // while
} else {
System.out.println("\n\nUnable start the monitor.\n\n" );
} // if
} // main | 8 |
protected String dumpArray(final Object value) {
String result;
if (value.getClass() == byte[].class) {
result = Arrays.toString((byte[]) value);
}
else if (value.getClass() == short[].class) {
result = Arrays.toString((short[]) value);
}
else if (value.getClass() == char[].class) {
result = Arrays.toString((char[]) value);
}
else if (value.getClass() == int[].class) {
result = Arrays.toString((int[]) value);
}
else if (value.getClass() == long[].class) {
result = Arrays.toString((long[]) value);
}
else if (value.getClass() == float[].class) {
result = Arrays.toString((float[]) value);
}
else if (value.getClass() == double[].class) {
result = Arrays.toString((double[]) value);
}
else {
result = Arrays.deepToString((Object[]) value);
}
return result;
} | 7 |
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
} | 0 |
public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession(true);
String error = "";
Product product;
int sku = 0;
int price = 0;
int category = 0;
long owner = 0;
try {
// Checks if any attributes were blank
if (req.getParameter("name") == "") {
throw new SQLException("No name entered");
}
if (req.getParameter("sku") == "") {
throw new SQLException("No SKU entered");
}
if (req.getParameter("price") == "") {
throw new SQLException("No price entered");
}
if (req.getParameter("delete") == null) {
// need to set variables for posts that are not delete posts
sku = Integer.parseInt(req.getParameter("sku"));
price = Integer.parseInt(req.getParameter("price"));
category = Integer.parseInt(req.getParameter("category"));
}
if (req.getParameter("newProd") != null) {
// First Case: Inserting a new Product
// Create the product object
product = new Product(req.getParameter("name"), req.getParameter("sku"), category, price);
// Write the query string, with "?" to help avoid potential SQL injections
String query = "INSERT INTO products (name, sku, cid, price) " +
"VALUES (?, ?, ?, ?)";
ProductDAO.alter(query, req.getParameter("name"), req.getParameter("sku"), category, price, -1);
req.setAttribute("product", product);
req.getRequestDispatcher("productsOwnerConfirm.jsp").forward(req, res);
} else if (req.getParameter("update") != null) {
// Second Case: Updating an existing Product
String query = "UPDATE products SET name = ?, sku = ?, cid = ?, " +
"price = ? WHERE id = ?";
int temp = Integer.parseInt(req.getParameter("id"));
product = new Product(req.getParameter("name"), req.getParameter("sku"), category, price);
ProductDAO.alter(query,req.getParameter("name"), req.getParameter("sku"), category, price, temp);
/*HashMap<Product,Integer> map = (HashMap<Product,Integer>)session.getAttribute("cart");
map.put(product, map.remove(ProductDAO.find("id", temp)));*/
res.sendRedirect("products");
} else if (req.getParameter("delete") != null) {
// Third Case: Deleting an existing Product
int temp = Integer.parseInt(req.getParameter("id"));
String query = "DELETE FROM products WHERE id = ?";
ProductDAO.alter(query, null, null, -1, -1, temp);
HashMap<Product,Integer> map = (HashMap<Product,Integer>)session.getAttribute("cart");
res.sendRedirect("products");
}
} catch (SQLException | NumberFormatException e) {
// If anything went wrong, redirect to error page with an error
e.printStackTrace();
error = "Failure to insert new product";
req.setAttribute("error", error);
req.getRequestDispatcher("productsOwnerConfirm.jsp").forward(req, res);
}
} | 8 |
public Snake(Point p, Rectangle field){
if(p.x < field.x || p.y < field.y || p.x >= (field.x + field.width) || p.y >= (field.y + field.height))
throw new IllegalArgumentException();
points = new ArrayList<Point>();
points.add(p);
p = new Point(p.x - 1, p.y);
points.add(p);
p = new Point(p.x - 1, p.y);
points.add(p);
p = new Point(p.x - 1, p.y);
points.add(p);
p = new Point(p.x - 1, p.y);
points.add(p);
direction = Cardinal.EAST;
} | 4 |
public boolean removeImageButton(String name) {
for (ImageButton button : screenObjects) {
if (button.getText() == name) {
screenObjects.remove(button);
return true;
}
}
return false;
} | 2 |
public String getRightResult(long start_ts,long end_ts) {
String tempResult=null;
for (Map.Entry<String, String> entry : optimizedData.entrySet()) {
String times = entry.getValue();
String[] timespan = times.split(",");
Long firstTime = Long.parseLong(timespan[0]);
Long secondTime = Long.parseLong(timespan[1]);
if (end_ts >= firstTime && end_ts <= secondTime) {
return entry.getKey();
} else if(!(start_ts>secondTime || end_ts<firstTime)){
tempResult=entry.getKey();
}
}
return tempResult;
} | 5 |
@Override
public int hashCode() {
int result;
long temp;
result = itemId;
result = 31 * result + (name != null ? name.hashCode() : 0);
temp = percent != +0.0d ? Double.doubleToLongBits(percent) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
} | 2 |
@Override
public List<Packet> onContact(int selfID, Sprite interactor, int interactorID, List<Integer> dirtySprites, List<Integer> spritesPendingRemoveal, ChatBroadcaster chater) {
if (interactor instanceof AmmoPickup && isAlive()) {
weaponsDataDirty = true;
WeaponInfo wi = getWeaponDataModifyable(((AmmoPickup)interactor).getWeapon());//Update Localy
wi.setCartregesReamaining(wi.getCartregesReamaining() + ((AmmoPickup)interactor).getAmount());
spritesPendingRemoveal.add(interactorID);
dirtySprites.add(selfID);
//Use primatives to tell client to update
//setNewCartregesRemainingPendingInsertion(wi.getCartregesReamaining() + ((AmmoPickup)interactor).getAmount());
for (int i = 0; i < getWeaponsData().size(); i++) {
if (getWeaponsData().get(i).getWeapon().equals(wi.getWeapon())) {
//setWeaponIndexForPendingCartreges(i);
break;
}
}
}
return new ArrayList<Packet>();
} | 4 |
private Tree statementsPro(){
Tree statement = null,
statements = null;
if((statement = statementPro())!= null){
if((statements = statementsPro())!=null){
return new Statements(statement, statements);
}
return statement;
}
return null;
} | 2 |
void printSprite()
{
//Get the current sprite path
NodeList listOfMovesSprites = sprites_doc.getElementsByTagName("Move");
boolean sprite_found=false;
for(int s=0; s<listOfMovesSprites.getLength() ; s++)
{
Node move_node = listOfMovesSprites.item(s);
Element move_element = (Element)move_node;
if(move_element.getAttribute("name").equals(list_moves.getSelectedValue()))
{
for(Node sprite=move_node.getFirstChild();sprite!=null;sprite=sprite.getNextSibling())//Sprite loop
{
if(sprite.getNodeName().equals("Sprite"))
{
String frame_number = "frame " + ((Element)sprite).getAttribute("frame_number");
if(frame_number.equals((String)list_frames.getSelectedValue()) )
{
sprite_found=true;
String sprite_path="/"+((Element)sprite).getAttribute("path");
int align_x=Integer.parseInt(((Element)sprite).getAttribute("align_x"));
int align_y=Integer.parseInt(((Element)sprite).getAttribute("align_y"));
int scale=Integer.parseInt(((Element)sprite).getAttribute("scale"));
//Print sprite
((ImagePanel)image_panel).setImage(directory_path+sprite_path,align_x,align_y,scale,blue_hitboxes, red_hitboxes);
label_current_sprite.setText(sprite_path);
}
}
}
}
}
if(!sprite_found)
{
((ImagePanel)image_panel).setImage("assets/LogoEngine.png");
label_current_sprite.setText("assets/LogoEngine.png");
}
} | 6 |
private int valueIexpand(char[] charArray, int i) {
if ('I' == charArray[i]) {
if (charArray.length > i
& ('V' == charArray[i + 1] | 'X' == charArray[i + 1]
| 'L' == charArray[i + 1] | 'C' == charArray[i + 1]
| 'D' == charArray[i + 1] | 'M' == charArray[i + 1])) {
return -1;
} else if (charArray.length + 1 > i
& ('V' == charArray[i + 2] | 'X' == charArray[i + 2]
| 'L' == charArray[i + 2] | 'C' == charArray[i + 2]
| 'D' == charArray[i + 2] | 'M' == charArray[i + 2])) {
return -1;
} else if (charArray.length + 2 > i
& ('V' == charArray[i + 3] | 'X' == charArray[i + 3]
| 'L' == charArray[i + 3] | 'C' == charArray[i + 3]
| 'D' == charArray[i + 3] | 'M' == charArray[i + 3])) {
return -1;
} else if (charArray.length + 3 > i
& ('V' == charArray[i + 4] | 'X' == charArray[i + 4]
| 'L' == charArray[i + 4] | 'C' == charArray[i + 4]
| 'D' == charArray[i + 4] | 'M' == charArray[i + 4])) {
return -1;
} else if (charArray.length + 4 > i
& ('V' == charArray[i + 5] | 'X' == charArray[i + 5]
| 'L' == charArray[i + 5] | 'C' == charArray[i + 5]
| 'D' == charArray[i + 5] | 'M' == charArray[i + 5])) {
throw new RuntimeException();
}
return 1;
}
return 0;
} | 6 |
public void collectStatistics() {
String word;
int numAccurances;
int numAccurancesPerWord;
double statistics;
boolean accurance;
DecimalFormat formatter = new DecimalFormat("##.00");
for (int j = 0; j < alphabet.length; j++) {
numAccurances = 0;
numAccurancesPerWord = 0;
statistics = 0;
for (int k = 0; k < wordList.size(); k++) {
word = wordList.get(k);
accurance = false;
for (int i = 0; i < word.length(); i++) {
if (String.valueOf(word.charAt(i)).equals(alphabet[j])) {
numAccurances++;
accurance = true;
}
}
if (accurance) {
numAccurancesPerWord++;
}
}
statistics = numAccurancesPerWord * 100.0 / wordList.size();
System.out.println(alphabet[j] + "\t" + numAccurances + "\t"
+ formatter.format(statistics) + "%");
}
} | 5 |
private void recurseComments(JSONObject jobj, Properties more, HashMap<String, Properties> data) {
try {
Properties properties = pullComment(jobj, more);
if (properties != null) {
data.put(properties.getProperty("name"), properties);
if (!jobj.getJSONObject("data").isNull("replies") && !(jobj.getJSONObject("data").get("replies") instanceof String)) {
JSONObject replies = jobj.getJSONObject("data").getJSONObject("replies");
JSONArray array = replies.getJSONObject("data").getJSONArray("children");
for (int i = 0; i < array.length(); i++) {
recurseComments(array.getJSONObject(i), more, data);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println(jobj);
e.printStackTrace();
System.exit(1);
}
} | 6 |
public void pauseSimulation() {
if (sim != null)
sim.pause();
} | 1 |
public int gameTeamScore(int i) {
if (i >= 2 || i < 0)
throw new IllegalArgumentException();
int result = 0;
if (i == 0) {
result += players[0].getScore();
result += players[2].getScore();
} else if (i == 1) {
result += players[1].getScore();
result += players[3].getScore();
}
return result;
} | 4 |
private void saveStack() {
int height = 0;
for (int i = 0; i < stack.size(); i++) {
final Expr expr = stack.get(i);
if (Tree.USE_STACK) {
// Save to a stack variable only if we'll create a new
// variable there.
if (!(expr instanceof StackExpr)
|| (((StackExpr) expr).index() != height)) {
final StackExpr target = new StackExpr(height, expr.type());
// Make a new statement to store the expression that was
// part of the stack into memory.
final Stmt store = new ExprStmt(new StoreExpr(target, expr,
expr.type()));
appendStmt(store);
final StackExpr copy = (StackExpr) target.clone();
copy.setDef(null);
stack.set(i, copy);
}
} else {
if (!(expr instanceof LocalExpr)
|| !((LocalExpr) expr).fromStack()
|| (((LocalExpr) expr).index() != height)) {
final LocalExpr target = newStackLocal(nextIndex++, expr
.type());
final Stmt store = new ExprStmt(new StoreExpr(target, expr,
expr.type()));
appendStmt(store);
final LocalExpr copy = (LocalExpr) target.clone();
copy.setDef(null);
stack.set(i, copy);
}
}
height += expr.type().stackHeight();
}
} | 7 |
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null || username.length() < MIN_USERNAME_LENGTH || username.length() > MAX_USERNAME_LENGTH) {
response.getWriter().write(FAIL_STATUS_PARAMETERS_FORMAT_WRONG + "");
return;
}
if (password == null || password.length() < MIN_PASSWORD_LENGTH || password.length() > MAX_PAWWORD_LENGTH) {
response.getWriter().write(FAIL_STATUS_PARAMETERS_FORMAT_WRONG + "");
return;
}
String queryPassword;
try {
queryPassword = DBHelper.getPasswordFromDB(username);
if (queryPassword == null) {
boolean result = DBHelper.insertUserIntoDB(username, password);
if (result) {
response.getWriter().write(Contants.SUCCESS_STATUS + "");
} else {
response.getWriter().write(FAIL_STATUS_DATABASE_WRONG + "");
}
} else {
response.getWriter().write(FAIL_STATUS_USERNAME_EXISTED + "");
}
} catch (Exception e1) {
e1.printStackTrace();
response.getWriter().write(FAIL_STATUS_DATABASE_WRONG + "");
}
} | 9 |
public SimpleStringProperty phoneTypeProperty() {
return phoneType;
} | 0 |
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
accumulator.setLength(0);
if (qName.equals("servlet"))
temperature = attributes.getValue("id");
} | 1 |
public void setMouseListener(MouseListener mouseListener){
if(this.mouseListener != null){
gamePanel.removeMouseListener(this.mouseListener);
}
this.mouseListener = mouseListener;
gamePanel.addMouseListener(mouseListener);
} | 1 |
public void update() {
p.update();
for (Tile t : tiles) {
t.update();
p.collide(t.boundingBox);
}
if (p.Position.x > WIDTH - (WIDTH / 8)) {
p.Velocity.x *= -1;
p.Position.x = WIDTH - (WIDTH / 8);
xOffset+=32;
for (Tile t : tiles) {
t.Position.x -= 32;
}
}
if (p.Position.x < WIDTH / 8) {
p.Velocity.x *= -1;
p.Position.x = WIDTH / 8;
xOffset-=32;
for (Tile t : tiles) {
t.Position.x += 32;
}
}
if(p.Position.y < HEIGHT/64){
p.Position.y = 2*HEIGHT / 64;
yOffset-=32;
for (Tile t : tiles) {
t.Position.y += 32;
}
}
if(p.Position.y > 7*HEIGHT/8){
p.Velocity.y *= -1;
p.Position.y = 55*(HEIGHT / 64);
yOffset+=32;
for (Tile t : tiles) {
t.Position.y -= 32;
}
}
levelBuilder();
Game.origin.x = (int) Math.floor(xOffset / 32);
Game.origin.y = (int) Math.floor(yOffset / 32);
} | 9 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
int numero = Integer.valueOf(campoNumero.getText());
for (int i = 0; i <= numero; i++) {
textArea.append(" " + i);
if(i % 25 == 0 && i != 0)
textArea.append("\n");
}
}//GEN-LAST:event_jButton1ActionPerformed | 3 |
public boolean withdrawEvidence(Evidence evidence, String actionType) {
boolean flag = false;
Element evidenceE = (Element) document
.selectSingleNode("//" + actionType + "[@id='" + evidence.getId() + "']");
if (evidenceE != null) {
evidenceE.element("dialogState").setText(evidence.getDialogState());
// Write to xml
try {
XmlUtils.write2Xml(fileName, document);
flag = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Copy to public dialog
EvidenceDao evidenceDao = new EvidenceDao(publicFileName);
if (actionType.equals("evidence")) {
if (evidenceDao.deleteEvidence(evidence)) {
flag = true;
} else {
flag = false;
}
} else if (actionType.equals("counterevidence")) {
if (evidenceDao.deleteCounterevidence(evidence)) {
flag = true;
System.out.println("actionType added to the public: " + actionType);
} else {
flag = false;
}
}
}
return flag;
} | 6 |
public void set(Scanner scan){
System.out.println("SELECT FIELD:\nName\t1"
+ "\nAddress\t2\nEmail\t3\nPhone\t4\nCity\t5"
+ "\nState\t6\nZip\t7");
int field = scan.nextInt();
String newVal = "";
System.out.println("you have to enter the same value 3 times.");
while(1!=0){
System.out.println("Enter new value: ");
newVal = scan.nextLine();
System.out.println("Confirm new value: ");
String confVal = scan.nextLine();
if(confVal.equals(newVal)){
if(field == 0&&isId(newVal)){
break;
}
else if(field == 7&&isZip(newVal)){
break;
}
else if(field!=0&&field!=7){
break;
}
}
}
data[field] = newVal;
System.out.println("UPDATE COMPLETE");
} | 8 |
@Test
public void test() {
try{
XmlIdRegister register = new XmlIdRegister("pre");
//Generate and register ID with default prefix
Id id1 = register.generateId();
assertNotNull(id1);
assertTrue(id1.toString().startsWith("pre"));
try {
register.registerId(id1);
} catch (InvalidIdException e1) {
e1.printStackTrace();
fail();
}
//Generate and register ID with custom prefix
Id id2 = register.generateId("bla");
assertNotNull(id2);
assertTrue(id2.toString().startsWith("bla"));
try {
register.registerId(id2);
} catch (InvalidIdException e1) {
e1.printStackTrace();
fail();
}
//Try to register existing ID
try {
register.registerId(register.getId(id1.toString()));
fail("Exception expected");
} catch (InvalidIdException e) {
}
//Register unused IDs
try {
register.registerId(register.getId("pre2"));
register.registerId("pre3");
} catch (InvalidIdException e) {
e.printStackTrace();
fail();
}
//Register and unregister
try {
register.registerId("pre4", id1);
} catch (InvalidIdException e) {
e.printStackTrace();
fail();
}
//Register or create (ID exists already)
Id id3 = register.registerOrCreateNewId("pre4");
assertNotNull(id3);
assertFalse(id3.toString().equals("pre4"));
//Register or create (ID does not exist already)
Id id4 = register.registerOrCreateNewId("blub1");
assertNotNull(id4);
assertTrue(id4.toString().equals("blub1"));
//Unregister
register.unregisterId(id4);
Id id5 = register.registerOrCreateNewId("blub1");
assertNotNull(id5);
assertTrue(id5.toString().equals("blub1"));
//Invalid ID format
try {
register.registerId("123");
fail("Exception expected");
} catch (InvalidIdException e) {
}
} catch(Exception exc) {
exc.printStackTrace();
fail();
}
} | 7 |
public void setFirstName(String firstName) throws Exception{
if (firstName.length() < MIN_INT_VALUE || firstName.toString() == null || firstName.length() > MAX_CHAR){
throw new IllegalArgumentException(NAME_ERR);
}
this.firstName = firstName;
} | 3 |
public static void saveFixture(DB db, String name, FixtureResource resource) throws IOException {
log.info("Saving [" + db.getName() + "." + db.getCollection(name) + "] to " + resource);
int savedIndexes = 0;
int savedDocuments = 0;
PrintWriter output = new PrintWriter(resource.getWriter());
output.println(name);
output.println("");
DBCollection collection = db.getCollection(name);
List<DBObject> indexes = collection.getIndexInfo();
for (DBObject index : indexes) {
log.debug("Found index with keys: " + index.get("key"));
output.println(INDEX_PREFIX + index.get("key"));
savedIndexes++;
}
if (indexes.size() > 0)
output.println("");
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
output.println(cursor.next());
savedDocuments++;
}
log.info("Saved [" + savedDocuments + "] documents with [" + savedIndexes + "] indexes form [" + db.getName() + "." + name + "] in " + resource);
resource.close();
} | 3 |
public static boolean isChestEmpty(Inventory i){
for(ItemStack is:i.getContents()){
if(is!=null){
return false;
}
}
return true;
} | 2 |
public SimplifyResult simplify(AdditiveExpression expression) {
Multimap<String, ASTElement> mapping = LinkedListMultimap.create();
for (ASTElement term : expression.getChildren()) {
MathExpression expr = (MathExpression) term;
mapping.put(expr.getSignature(), term);
}
boolean simplified = false;
for (String key : mapping.keySet()) {
Collection<ASTElement> elements = mapping.get(key);
if (elements.size() > 1) {
MultiplicativeExpression joinedExpression = null;
for (ASTElement astElement : elements) {
if (!(astElement instanceof MultiplicativeExpression) && !(astElement instanceof PowerOperation)) {
throw new RuntimeException("Must be a MultiplicativeExpression or a PowerOperation");
}
if (joinedExpression == null) {
joinedExpression = (MultiplicativeExpression) astElement;
} else {
joinedExpression.join((MultiplicativeExpression) astElement);
expression.removeChild(astElement);
}
}
simplified = true;
}
}
// convert to multiplicative expression
ASTElement newElement = expression;
if (expression.getChildren().size() == 1) {
newElement = expression.getChildren().get(0);
}
return new SimplifyResult(simplified, newElement);
} | 8 |
private Result(Level level, String message) {
this.level = level;
this.message = message;
} | 0 |
public Auth_frame() {
int selection = JOptionPane.showConfirmDialog(
null
, "Authentication Failed!"
, "Input Error"
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.INFORMATION_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
new Login();
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
System.exit(ABORT);
}
} | 2 |
public static Vector performSearch(Graph searchGraph, int nStartNodeID, int nGoalNodeID)
{
// create the open and closed lists
Vector vOpenList = new Vector();
Vector vClosedList = new Vector();
// create the start node as an AstarNode
Astar.AstarNode currNode = new Astar.AstarNode();
currNode.m_Node = searchGraph.getNode(nStartNodeID);
currNode.m_nCost = 0;
currNode.m_parentNode = null;
currNode.m_nHeuristic = getHeuristic(searchGraph, nStartNodeID, nGoalNodeID);
currNode.m_nScore = currNode.m_nCost + currNode.m_nHeuristic;
// add the start node to the open list
vOpenList.add(currNode);
// while the open list is not empty loop through list searching for the
// final path
while (vOpenList.size() != 0)
{
// Pick the current node to be the node in the open list
// with the least cost
currNode = getLowestCostNode(vOpenList);
// if we found the goal node then we're done - HOORAY!
if (currNode.m_Node.getID() == nGoalNodeID)
{
// we found the right node so break out of the search
break;
}
// otherwise this isn't the right one so move it to the closed list
removeNodeFromList(vOpenList, currNode);
vClosedList.add(currNode);
// examine each adjacent node to it
Vector vAdjNodes = currNode.m_Node.getAdjacentNodes();
for (int i = 0; i < vAdjNodes.size(); i++)
{
// if not in the open list
if (!isInList(vOpenList, (Node)vAdjNodes.get(i)))
{
// and not in the closed list
if (!isInList(vClosedList, (Node)vAdjNodes.get(i)))
{
// we found a node to put in the open list so calculate its data
Astar.AstarNode newOpenNode = new Astar.AstarNode();
newOpenNode.m_Node = (Node)vAdjNodes.get(i);
newOpenNode.m_nCost =
currNode.m_nCost + currNode.m_Node.costToTravel(newOpenNode.m_Node);
newOpenNode.m_parentNode = currNode;
newOpenNode.m_nHeuristic =
getHeuristic(searchGraph, newOpenNode.m_Node.getID(), nGoalNodeID);
newOpenNode.m_nScore = currNode.m_nCost + currNode.m_nHeuristic;
// now add it to the open list
vOpenList.add(newOpenNode);
}
}
}// end adjacent node check
}
Vector vResults = new Vector();
// did we find the path?
if (vOpenList.size() == 0)
{
// no we ran out of nodes to check there is no path
return vResults;
}
if (currNode.m_Node.getID() != nGoalNodeID)
{
// something went wrong!
return vResults;
}
// now we've found the path and it is the currNode so we just need to
// trace it back and fill up the results vector
while (currNode.m_Node.getID() != nStartNodeID)
{
vResults.add(new Integer(currNode.m_Node.getID()));
currNode = currNode.m_parentNode;
}
// add the start node
vResults.add(new Integer(currNode.m_Node.getID()));
// return the path results
return vResults;
} | 8 |
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String comando=e.getActionCommand();
if(comando.equals("explorar")){
principal.mostrarExploracion();
}else if(comando.equals("buscar")){
principal.mostrarBusqueda();
}else if(comando.equals("historial")){
principal.darHistorial();
}else if(comando.equals("ayuda")){
JOptionPane.showMessageDialog(this, "Ayuda");
}else if(comando.equals("acerca")){
JOptionPane.showMessageDialog(this, "Acerca De");
}else if(comando.equals("estadisticas")){
principal.darHistorial();
}else if(comando.equals("categorias")){
principal.mostrarCategorias();
}else if(comando.equals("recursos")){
principal.mostrarRecursos();
}
} | 8 |
public double evaluate(Individual ind) {
IntegerIndividual iind = (IntegerIndividual) ind;
Strategy es = strategies.get((Integer) iind.get(0));
int score = 0;
for (int i = 0; i < maxEncounters; i++) {
Strategy s = strategies.get(rnd.nextInt(strategies.size()));
int sc1 = 0;
int sc2 = 0;
String str1 = "";
String str2 = "";
int iters = 150 + rnd.nextInt(100);
for (int m = 0; m < iters; m++) {
Move s1Move = null;
Move s2Move = null;
try {
s1Move = es.nextMove();
} catch (Exception e) {
sc1 = 0;
}
try {
s2Move = s.nextMove();
} catch (Exception e) {
sc2 = 0;
}
str1 += (s1Move == null) ? "E" : s1Move.getLabel();
str2 += (s2Move == null) ? "E" : s2Move.getLabel();
Result r1 = new Result(s1Move, s2Move);
Result r2 = new Result(s2Move, s1Move);
sc1 += r1.getMyScore();
sc2 += r2.getMyScore();
try {
es.reward(r1);
} catch (Exception e) {
sc1 = 0;
}
try {
s.reward(r2);
} catch (Exception e) {
sc2 = 0;
}
}
score += sc1;
}
iind.setObjectiveValue(score);
return score;
} | 8 |
public void update(String line, LineStatus status, Scanner fileScan) throws IOException
{
boolean isUrlObjectComplete = false;
do {
switch (status)
{
case BlankLine: {
add("", BookmarkWorkbench.mainManifest);
isUrlObjectComplete = true;
}
break;
case TitleLine: {
add(line, BookmarkWorkbench.mainManifest);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case UrlLine: {
add(line, BookmarkWorkbench.mainManifest);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case CategoryLine: {
add(line, BookmarkWorkbench.mainManifest);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case TodoLine: {
add(line, BookmarkWorkbench.mainManifest);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case NoteLine: {
add(line, BookmarkWorkbench.mainManifest);
iterate(fileScan);
isUrlObjectComplete = true; //'recursive base case' to eventually break out of loop
}
break;
case OtherLine: {
Ui userInterface = new UiCli(); //decouple this from model (observer pattern?)
userInterface.warningMessage(MessageType.ProblemParsingSessionFile); //decouple this from model (observer pattern?)
}
break;
}
} while(isUrlObjectComplete==false);
add("", BookmarkWorkbench.mainManifest); //extra line break after the object finishes
} | 8 |
public void refresh() {
zoeker.resetMap(accounts.getBusinessObjects());
combo.removeAllItems();
for(Project project : projects.getBusinessObjects()) {
((DefaultComboBoxModel<Project>) combo.getModel()).addElement(project);
}
Project[] result = new Project[projects.getBusinessObjects().size()];
projects.getBusinessObjects().toArray(result);
if (projects.getBusinessObjects().size() != 0) {
combo.setSelectedItem(project);
} else {
project = null;
allAccountsModel.removeAllElements();
for(Account account : accounts.getBusinessObjects()){
allAccountsModel.addElement(account);
}
}
} | 3 |
public synchronized void addRule(Rule newRule) throws TheoryException {
if (newRule == null) throw new TheoryException(ErrorMessage.RULE_NULL_RULE);
// throw exception if rule contains no head literals
if (newRule.getHeadLiterals().size() == 0)
throw new RuleException(ErrorMessage.RULE_NO_HEAD_LITERAL, new Object[] { newRule.getLabel() });
// add rule to the theory if it does not already exist
if (factsAndAllRules.containsKey(newRule.getLabel()))
throw new TheoryException(ErrorMessage.RULE_ALREADY_EXISTS, new Object[] { newRule.getLabel() });
switch (newRule.getRuleType()) {
case FACT:
factsAndAllRules.put(newRule.getLabel(), newRule);
break;
case STRICT:
factsAndAllRules.put(newRule.getLabel(), newRule);
break;
case DEFEASIBLE:
factsAndAllRules.put(newRule.getLabel(), newRule);
break;
case DEFEATER:
factsAndAllRules.put(newRule.getLabel(), newRule);
break;
default:
throw new TheoryException(ErrorMessage.RULE_UNRECOGNIZED_RULE_TYPE, new Object[] { newRule.getRuleType() });
}
// update literal-rule type association list
updateRuleTypeAssociationList_addRule(newRule);
// update literal-rule association list
updateLiteralRuleAssociationList_addRule(newRule);
// update mixed literals sets
updateMixedLiteralsSets_add(newRule);
} | 7 |
public static double compute(double a) throws ArithmeticException {
double MAXLOG = 7.09782712893383996732E2;
double x, y, z, p, q;
double P[] = { 2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0,
4.86371970985681366614E1, 1.96520832956077098242E2, 5.26445194995477358631E2, 9.34528527171957607540E2,
1.02755188689515710272E3, 5.57535335369399327526E2 };
double Q[] = {
// 1.0
1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2,
1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2 };
double R[] = { 5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0,
6.16021097993053585195E0, 7.40974269950448939160E0, 2.97886665372100240670E0 };
double S[] = {
// 1.00000000000000000000E0,
2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1, 1.70814450747565897222E1,
9.60896809063285878198E0, 3.36907645100081516050E0 };
if (a < 0.0)
x = -a;
else x = a;
if (x < 1.0)
return 1.0 - ErrorFunction.compute(a);
z = -a * a;
if (z < -MAXLOG) {
if (a < 0)
return (2.0);
return (0.0);
}
z = Math.exp(z);
if (x < 8.0) {
p = ErrorFunction.polevl(x, P, 8);
q = ErrorFunction.p1evl(x, Q, 8);
}
else {
p = ErrorFunction.polevl(x, R, 5);
q = ErrorFunction.p1evl(x, S, 6);
}
y = (z * p) / q;
if (a < 0)
y = 2.0 - y;
if (y == 0.0) {
if (a < 0)
return 2.0;
return (0.0);
}
return y;
} | 8 |
public void saveLaTeXTable(String fileName, List<List<String>> compact, List<List<String>> full) {
if (!fileName.contains(".txt")) {
fileName += ".txt";
}
FileWriter writer = null;
try {
writer = new FileWriter(fileName);
PrintWriter fout = new PrintWriter(writer);
fout.println("%");
fout.println("% FULL TABLE");
fout.println("%");
fout.println();
writeTable(fout, compact);
fout.println("%");
fout.println("% COMPACT TABLE");
fout.println("%");
fout.println();
writeTable(fout, full);
} catch (IOException e) {
System.out.println("ERROR writing files");
} finally {
try {
writer.close();
} catch (IOException ex) {
System.out.println("ERROR closing file");
}
}
} | 3 |
private String formatMonome(int exponent, int coeficient) {
if (coeficient == 0) {
return "";
}
if (exponent == 0) {
if (exponent == this.getMaximumExponent())
return "" + coeficient;
else return (coeficient > 0) ? "+" + coeficient : coeficient + "";
}
String exponentString = (exponent == 1) ? "" : exponent + "";
String coeficientString;
if (coeficient == 1) {
coeficientString = "+";
} else if (coeficient == -1) {
coeficientString = "-";
} else {
coeficientString = (coeficient > 0) ? "+" + coeficient : coeficient + "";
}
return coeficientString + "x" + exponentString;
} | 8 |
private static void showScreen(final AbstractScreen screenToShow) {
for (AbstractScreen screen : screenRef) {
screen.setVisible(false);
}
screenToShow.reset();
screenToShow.loadFields();
screenToShow.setVisible(true);
} | 1 |
@Override
public void characters(char ch[], int start, int length) throws SAXException {
super.characters(ch, start, length);
} | 0 |
@Override
public int castingQuality(MOB mob, Physical target)
{
if((mob!=null)&&(target!=null))
{
if((CMLib.flags().isSitting(target)||CMLib.flags().isSleeping(target)))
return Ability.QUALITY_INDIFFERENT;
if((target instanceof MOB)&&(((MOB)target).riding()!=null))
return Ability.QUALITY_INDIFFERENT;
if(CMLib.flags().isInFlight(target))
return Ability.QUALITY_INDIFFERENT;
}
return super.castingQuality(mob,target);
} | 7 |
public StrongRenamer() {
charsets = new String[idents.length][parts.length];
for (int i = 0; i < idents.length; i++)
for (int j = 0; j < parts.length; j++)
charsets[i][j] = "abcdefghijklmnopqrstuvwxyz";
} | 2 |
private List<String> getProperties() {
List<String> properties = new ArrayList<String>();
for (Map.Entry<String, String> field: metadata.getEnvironment().entrySet()) {
String fieldKey = field.getKey();
String fieldValue = field.getValue();
if (includeDeprecatedEntries || !isDeprecated(fieldKey)) {
properties.add(formatProperty(fieldKey, fieldValue));
}
}
return properties;
} | 3 |
public Vector2f(float x, float y) {
this.x = x;
this.y = y;
} | 0 |
public void quick(int[] array, int left, int right) {
if (left < right) {
int i = left, j = right, x = array[left];
while (i < j) {
while (i < j && array[j] >= x) j --;
if (i < j) array[i++] = array[j];
while(i < j && array[i] < x) i ++;
if (i < j) array[j--] = array[i];
}
array[i] = x;
quick(array, left, i - 1);
quick(array, i + 1, right);
}
} | 8 |
public String getNonPHr(int i){
String hr, min;
try{
hr = Integer.toString(nonPeakHr[i].get(11));
if (hr.length()==1)
hr = "0" + hr;
min = Integer.toString(nonPeakHr[i].get(12));
if (min.length()==1)
min = "0" + min;
return hr + ":" + min;
} catch(NullPointerException e){
}
return null;
} | 3 |
@Override
public byte[] runBinaryMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) throws HTTPServerException
{
String filename=getFilename(httpReq,"");
if(filename==null)
filename="FileData";
final int x=filename.lastIndexOf('/');
if((x>=0)&&(x<filename.length()-1))
filename=filename.substring(x+1);
final MIMEType mimeType = MIMEType.All.getMIMEType(filename);
if(mimeType != null)
httpResp.setHeader("Content-Type", mimeType.getType());
httpResp.setHeader("Content-Disposition", "attachment; filename="+filename);
if(filename.length()==0)
return null;
final MOB M = Authenticate.getAuthenticatedMob(httpReq);
if(M==null)
return null;
final CMFile F=new CMFile(getFilename(httpReq,""),M);
if((!F.exists())||(!F.canRead()))
return null;
return F.raw();
} | 8 |
protected HTTPResponse handleUriRes(HTTPRequest req) {
Matcher m;
String urn;
String filenameHint;
if( (m = rawPattern.matcher(req.path)).matches() ) {
urn = urlDecodeString(m.group(1));
filenameHint = m.group(2);
} else if( (m = n2rPattern.matcher(req.path)).matches() ) {
urn = urlDecodeString(m.group(1));
} else {
return null;
}
for( Repository r : repositories ) {
ByteBlob b;
try {
b = r.getBlob(urn);
} catch( IOException e ) {
continue;
}
if( b != null ) {
return new HTTPResponse("HTTP/1.0", 200, "Okay",
WebServer.mkHeaders("content-type","text/plain"),
b
);
}
}
return null;
} | 5 |
private static long count(long n){
long twon = n*2;
String N = Long.toBinaryString(n);
String twoN = Long.toBinaryString(twon);
if(N.length()<k) return 0;
String smallest = findSmall(N);
String largest = findLarge(twoN);
if(Long.parseLong(smallest, 2) < n || Long.parseLong(largest, 2) > twon) return 0;
long count = 0;
int firstZero = smallest.indexOf('0');
String sub = smallest.substring(firstZero);
count+=fac(sub.length())/fac(countOnes(sub))/fac(sub.length()-countOnes(sub));
if(largest.length()>smallest.length()){
int firstOne = largest.indexOf('1', 1);
String sub2 = largest.substring(firstOne);
count+=fac(sub2.length())/fac(countOnes(sub2))/fac(sub2.length()-countOnes(sub2));;
}
return count;
} | 4 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
} | 0 |
@Override
public Iterator<List<S>> iterator() {
TreeNode<S> rootIntermediate = this;
while (this.parent != null) {
rootIntermediate = this.parent;
}
final ArrayDeque<TreeNode<S>> stack = new ArrayDeque<TreeNode<S>>();
stack.add(rootIntermediate);
List<List<S>> paths = new ArrayList<>();
while (!stack.isEmpty()) {
TreeNode<S> node = seekAccept(stack);
if (node == null) {
break;
}
paths.add(node.getPath());
}
;
return paths.iterator();
} | 3 |
public InvalidPageNumberException(Exception ex, String name)
{
super(ex, name);
} | 0 |
private final Object[] loadScriptParameters(ByteBuffer class348_sub49, int i) {
if (i != -1)
return null;
anInt691++;
int i_33_ = class348_sub49.getUByte();
if (i_33_ == 0)
return null;
Object[] objects = new Object[i_33_];
for (int i_34_ = 0; i_34_ < i_33_; i_34_++) {
int i_35_ = class348_sub49.getUByte();
if ((i_35_ ^ 0xffffffff) != -1) {
if ((i_35_ ^ 0xffffffff) == -2)
objects[i_34_] = class348_sub49.getJstr();
} else
objects[i_34_] = new Integer(class348_sub49.getDword());
}
((Widget) this).aBoolean682 = true;
return objects;
} | 5 |
public boolean delete(String zipPath, boolean delDirs) throws IOException
{
boolean failed = true;
Path path = fileSystem.getPath(zipPath);
if(!Files.exists(path) && !delDirs)
{
return false;
}
if(delDirs)
{
for(int i = path.getNameCount(); i > 0; i--)
{
Path p = path.subpath(0, i);
try
{
Files.delete(p);
}
catch(DirectoryNotEmptyException e)
{
break;
}
}
}
else
{
Files.delete(path);
}
return !failed;
} | 5 |
private JsonElement jNull() throws MalformedJsonException{
if(next()=='u' && next()=='l' && next()=='l'){
next();
return null;
}else{
throw jsonError("invalid comment", true);
}
} | 3 |
private void overlayFragment(final long pos, long otherOffset,
long length, DeltaSource source, FragmentFactory factory)
throws IOException, DeltaFormatException
{
// There is a top layer, find its intersecting common fragments
CommonFragment topFragment = commonCursor.next();
if (pos > topFragment.oldOffset && common != topFragment)
throw new IllegalStateException("Unexpected common fragment at " + topFragment.oldOffset
+ " listed before " + pos);
long endPos = pos + length;
long lastPos = pos;
CommonFragment endFragment = null;
// For each intersecting common fragment
while (endPos > topFragment.oldOffset && common != topFragment)
{
// Remove this fragment
commonCursor.removeNext();
if (0 < commonCount)
commonCount--;
else if (0 == commonCount)
throw new IllegalStateException("Underflow of commonCount after removing " + topFragment);
// Update the forward cursor
forwardCursor = topFragment.previousDirectional;
// Calculate intersection boundaries
long intEnd = topFragment.oldOffset + topFragment.length;
// Does it fit within bottom layer fragment?
if (endPos < intEnd)
{
// No, adjust the boundary and save this fragment
intEnd = endPos;
endFragment = topFragment;
}
factory.createOverlay(pos, lastPos, otherOffset, length, intEnd, source, topFragment);
// Select next fragment
topFragment = commonCursor.next();
// advance pos past the new overlay
lastPos = intEnd;
}
// Was there leftover from last fragment?
if (null != endFragment)
{
// Yes, make another fragment from it
endPos -= endFragment.oldOffset;
endFragment.length -= endPos;
endFragment.offset += endPos;
endFragment.previousDirectional = forwardCursor;
endFragment.oldOffset += endPos;
commonCursor.add(endFragment);
commonCount++;
}
} | 8 |
public static int lengthOfPrimeSum(int[] primes, int n) {
int currLength = 0, sum = 0, maxLength = 0;
boolean foundSum = false;
for (int i = 0; i < primes.length && primes[i] <= Math.sqrt(n); i++) {
currLength = 0;
foundSum = false;
sum = 0;
for (int j = i; j < primes.length && !foundSum && sum < n; j++) {
++currLength;
sum += primes[j];
if (sum == n) {
foundSum = true;
if (currLength > maxLength) {
maxLength = currLength;
}
}
}
}
return maxLength;
} | 7 |
public static void loadLevel(String levelFile, GameState parentState,
ArrayList<GameObject> gameObjectList) {
try {
BufferedReader in = new BufferedReader(new FileReader(levelFile));
String line = null;
int y = 0;
while ((line = in.readLine()) != null) {
for (int i = 0; i < line.length(); i++) {
char currentChar = line.charAt(i);
int x = i * GameConstants.GRID_SIZE;
}
y += GameConstants.GRID_SIZE;
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("Level file not found: " + levelFile);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Problem loading level: " + levelFile);
e.printStackTrace();
}
} | 4 |
public boolean[] classify(int datapoint) {
double hypothesis;
boolean[] class_list = new boolean[classes];
int c, f, i;
//System.out.println("Classifying:");
for (c = 0; c < classes; c++) {
hypothesis = 0;
//System.out.println(" "+data.classlist[c]+":");
for (f = 0; f < features; f++) {
//System.out.print(" "+data.storage[datapoint][f]+": [");
for (i = 0; i < iterations; i++) {
if (classifiers[c][f][i].classify(data.storage[datapoint][f])) {
//System.out.print("true, ");
hypothesis += classifier_weights[c][f][i];
} else {
//System.out.print("false, ");
hypothesis -= classifier_weights[c][f][i];
}
}
//System.out.println("]");
}
class_list[c] = hypothesis > 0;
}
return class_list;
} | 4 |
private void sort_notes() {
if (!notes.isEmpty()) {
int min = notes.get(0);
for (int i = 0; i < notes.size(); i++) {
min = i;
for (int j = i + 1; j < notes.size(); j++) {
if (notes.get(j) < notes.get(min)) min = j;
}
if (min != i) {
int temp = notes.get(i);
notes.set(i, notes.get(min));
notes.set(min, temp);
}
}
}
} | 5 |
public int getHole(){
if(hole > -1){
return hole;
}
boolean[][] map = copyArray(imageMap);
//first, paint the background to black
paintBlack(map,0,0);
//then, start counting
int e = 0;
int i = 0;
int height = map.length;
int width = map[0].length;
for (int h = 0; h < height - 1 ; h++) {
for (int w = 0; w < width - 1 ; w++) {
int black = 0;
if(map[h][w]) black += 1;
if(map[h+1][w]) black += 1;
if(map[h][w+1]) black += 1;
if(map[h+1][w+1]) black += 1;
if(black == 3){
e += 1;
}else if(black == 1){
i += 1;
}
}
}
hole = (e-i)/4;
return hole;
} | 9 |
public Point computeSize (int wHint, int hHint, boolean changed) {
checkWidget ();
int width = 0, height = 0;
if (wHint != SWT.DEFAULT) {
width = wHint;
} else {
if (columns.length == 0) {
for (int i = 0; i < itemsCount; i++) {
Rectangle itemBounds = items [i].getBounds (false);
width = Math.max (width, itemBounds.x + itemBounds.width);
}
} else {
CTableColumn[] orderedColumns = getOrderedColumns ();
CTableColumn lastColumn = orderedColumns [orderedColumns.length - 1];
width = lastColumn.getX () + lastColumn.width;
}
}
if (hHint != SWT.DEFAULT) {
height = hHint;
} else {
height = getHeaderHeight () + itemsCount * itemHeight;
}
Rectangle result = computeTrim (0, 0, width, height);
return new Point (result.width, result.height);
} | 4 |
public GClicker() throws Exception
{
super("gClicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(30, 30);
model = new GClickerModel();
myAddress = InetAddress.getLocalHost();
ipAddress = new int[4];
for (int i = 0; i < 4; i++)
ipAddress[i] = (0x000000FF & myAddress.getAddress()[i]);
ipPanel = new JPanel();
ipPanel.setBorder(BorderFactory.createTitledBorder("IP Address:"));
JLabel ipInfo = new JLabel("This server's IP address is: " + ipAddress[0]+"."+
ipAddress[1]+"."+ipAddress[2]+"."+ipAddress[3], JLabel.CENTER);
ipInfo.setFont(GClickerModel.bigFont);
ipPanel.add(ipInfo);
question = new JTextArea("Enter question here...", 13, 25);
question.setFont(GClickerModel.smallerFont);
question.setLineWrap(true);
questionPane = new JScrollPane(question);
questionPanel = new JPanel();
questionPanel.setBorder(BorderFactory.createTitledBorder("Question:"));
questionPanel.add(questionPane);
answerPanel = new AlignedPanel("RIGHT");
answerPanel.setBorder(BorderFactory.createTitledBorder("Answers:"));
answers = new AnswerField[GClickerModel.MAX_ANSWERS];
for (int i = 0; i < GClickerModel.MAX_ANSWERS; i++){
answers[i] = new AnswerField((char)('A' + i));
answerPanel.add(answers[i]);
answerPanel.add(Box.createVerticalStrut(5));
}
timer = new VisibleTimer(30);
timer.addListener(this);
AlignedPanel eastPanel = new AlignedPanel("LEFT");
eastPanel.add(answerPanel);
eastPanel.add(timer);
int numClickRows = GClickerModel.NUM_CLICK_POSS / GClickerModel.NUM_CLICK_COLS;
if ((GClickerModel.NUM_CLICK_POSS % GClickerModel.NUM_CLICK_COLS) != 0){
numClickRows++;
}
clickerRows = new JPanel[numClickRows];
for (int i = 0; i < numClickRows; i++)
{
clickerRows[i] = new JPanel();
clickerRows[i].setLayout(new BoxLayout(clickerRows[i], BoxLayout.X_AXIS));
}
clickerBox = new ClickerBox[GClickerModel.NUM_CLICK_POSS];
for (int numAdded = 0; numAdded < clickerBox.length; numAdded++)
{
clickerBox[numAdded] = new ClickerBox(numAdded);
clickerRows[numAdded / GClickerModel.NUM_CLICK_COLS].add(Box.createHorizontalStrut(1));
clickerRows[numAdded / GClickerModel.NUM_CLICK_COLS].add(clickerBox[numAdded]);
clickerRows[numAdded / GClickerModel.NUM_CLICK_COLS].add(Box.createHorizontalStrut(1));
}
clickerPanel = new AlignedPanel("CENTER");
clickerPanel.setBorder(BorderFactory.createTitledBorder("Clickers:"));
for (int i = 0; i < clickerRows.length; i++)
{
clickerPanel.add(clickerRows[i]);
clickerPanel.add(Box.createVerticalStrut(2));
}
content = new JPanel(new BorderLayout());
content.add(ipPanel, BorderLayout.NORTH);
content.add(questionPanel, BorderLayout.WEST);
content.add(eastPanel, BorderLayout.CENTER);
content.add(clickerPanel, BorderLayout.SOUTH);
getContentPane().add(content);
pack();
setVisible(true);
model.addObserver(this);
} | 6 |
public void setAvailablePieces(List<? extends Piece> availablePieces) {
this.availablePieces = availablePieces;
} | 1 |
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
token = x.nextToken();
if (token.toUpperCase().startsWith("HTTP")) {
// Response
jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0'));
x.next();
} else {
// Request
jo.put("Method", token);
jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken());
}
// Fields
while (x.more()) {
String name = x.nextTo(':');
x.next(':');
jo.put(name, x.nextTo('\0'));
x.next();
}
return jo;
} | 2 |
public void setWord(Word newWord, int index){
words.set(index, newWord);
} | 0 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
AnsatDTO ansat = ansatList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = ansat.getmedArbId();
break;
case 1:
value = ansat.getfornavn();
break;
case 2:
value = ansat.getefternavn();
break;
case 3:
value = ansat.getTelefonNr();
break;
case 4:
value = ansat.getRolleId();
break;
case 5:
value = ansat.getFunktion();
break;
case 6:
value = ansat.getStatus();
break;
}
return value;
} | 7 |
public int getLeftnumberByPID(Statement statement,String PID)//根据PID获取剩余车位数
{
int result = -1;
sql = "select leftnumber from Park where PID = '" + PID +"'";
try
{
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
result = rs.getInt("leftnumber");
}
}
catch (SQLException e)
{
System.out.println("Error! (from src/Fetch/Park.getLeftnumberByPID()");
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} | 2 |
public static boolean box_box(double ax0, double ay0, double ax1, double ay1, double bx0, double by0, double bx1, double by1){
double topA = FastMath.min(ay0, ay1);
double botA = FastMath.max(ay0, ay1);
double leftA = FastMath.min(ax0, ax1);
double rightA = FastMath.max(ax0, ax1);
double topB = FastMath.min(by0, by1);
double botB = FastMath.max(by0, by1);
double leftB = FastMath.min(bx0, bx1);
double rightB = FastMath.max(bx0, bx1);
if(botA <= topB || botB <= topA || rightA <= leftB || rightB <= leftA)
return false;
return true;
} | 4 |
public ListDataOut(){
listDataOut = new ArrayList<DataOut>();
} | 0 |
public void drawSphere(float r, int scalex, int scaley)
{
BufferData data = RobotRace.VBOUtil.bufferHalfSphere(1F, scalex, scaley);
if(r != 1F)
gl.glScalef(r, r, r);
RobotRace.VBOUtil.drawBufferedObject(data);
gl.glScaled(1, -1, 1);
RobotRace.VBOUtil.drawBufferedObject(data);
if(r != 1F)
gl.glScaled(1/r, -1/r, 1/r);
else
gl.glScaled(1, -1, 1);
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Familia other = (Familia) obj;
if (!Objects.equals(this.idFamilia, other.idFamilia)) {
return false;
}
return true;
} | 3 |
public static int adminSearch(Db db, LogAc logAc, String Username){
int i = 0;
while (logAc.getAdmin(i) != null)
{
if (Username.equals(logAc.getAdmin(i).userName))
return i;
i++;
}
return -1;
} | 2 |
@Override
public Map<String, Long> startExperiment(int amount, int maxRange,
final int iterations, List<SortingAlgorithm> list) {
System.out.printf("\n%s", "Starting experiment");
setPause(2);
// parameters check
if (amount == 0 || maxRange == 0 || iterations == 0) {
getSettingsForExperiment();
}
if (amount > maxRange) {
System.out.printf("%s", "Max range must be bigger or equal to amount: ");
setPause(3);
getSettingsForExperiment();
}
// initiate all algorithms by default
if (list == null) {
list = initAllAlgorithms();
}
final List<SortingAlgorithm> finalList = list;
// initiating executor
executor = Executors.newFixedThreadPool(MYTHREADS);
// generating list of unsorted random numbers
targetList = appUtil.getRandomNumbers(amount, maxRange);
// initiating
resultMap = new HashMap<String, Long>();
// iteration of list with algorithms objects
System.out.printf("\n%s", "Measuring ...\n");
// starting multiple threads to speed processing
for (final SortingAlgorithm foo : finalList) {
executor.submit(new Runnable() {
@Override
public void run() {
// init list for results for current algorithm
List<Long> timerResultList = new ArrayList<Long>();
// iteration to get average time result
for (int i = 1; i <= iterations; i++) {
List<Integer> testList = new ArrayList<Integer>(targetList);
appTimer.start();
foo.sort(testList);
appTimer.stop();
// saving current result to list
timerResultList.add(appTimer.getTotalTime());
}
// saving average time per algorithm type
String currentClassName = foo.getClass().getName();
resultMap.put(currentClassName, getAverageStatistical(timerResultList));
System.out.printf("\n\t%s", "completed for: " + currentClassName);
} // run()
}); // executor
} // for
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.printf("\n%s", "Experiment completed\n");
return resultMap;
} | 8 |
private void initElements(String title, int size, Actor actor,
boolean editable) {
// labels
lName = new JLabel("Name");
lForename = new JLabel("Vorname");
lFamilyname = new JLabel("Nachname");
lNationality = new JLabel("Nationalität");
lBirthday = new JLabel("Geburtstag");
lMovie = new JLabel("Filme");
lAward = new JLabel("Auszeichnungen");
// title in frame
lTitle = new JLabel(title);
// settings
lTitle.setFont(new Font("Serif", Font.BOLD, size));
if (actor != null) {
tfName = new JTextField(actor.getName(), 15);
tfForename = new JTextField(actor.getForename(), 15);
tfFamilyname = new JTextField(actor.getFamilyname(), 15);
tfNationality = new JTextField(actor.getNationality(), 15);
tfBirthday = new JTextField(actor.getBirthday(), 15);
// there can be more movies
taMovie = new JTextArea(5, 15);
if (actor.getMovies() != null) {
firstIteration = true;
for (Movie movie : actor.getMovies()) {
if (firstIteration) {
taMovie.setText(movie.getTitle() + " ("
+ movie.getYear() + ")");
firstIteration = false;
} else {
taMovie.append("\n" + movie.getTitle() + " ("
+ movie.getYear() + ")");
}
}
}
// there can be more awards
taAward = new JTextArea(5, 15);
if (actor.getAwards() != null) {
firstIteration = true;
for (Award award : actor.getAwards()) {
if (firstIteration) {
taAward.setText(award.getAward() + " ("
+ award.getYear() + ")");
firstIteration = false;
} else {
taAward.append("\n" + award.getAward() + " ("
+ award.getYear() + ")");
}
}
}
} else {
// textfields
tfName = new JTextField(15);
tfForename = new JTextField(15);
tfFamilyname = new JTextField(15);
tfNationality = new JTextField(15);
tfBirthday = new JTextField(15);
// textareas
taMovie = new JTextArea(5, 15);
taAward = new JTextArea(5, 15);
}
// scrollpane
spMovie = new JScrollPane(taMovie);
spAward = new JScrollPane(taAward);
// settings of textfields
tfName.setEditable(editable);
tfForename.setEditable(editable);
tfFamilyname.setEditable(editable);
tfNationality.setEditable(editable);
tfBirthday.setEditable(editable);
// settings of textarea
taMovie.setEditable(false);
taAward.setEditable(false);
// settings of scrollpane
spMovie.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spMovie.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
spAward.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
spAward.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
} | 7 |
private void writeChunkToImage(RegionFile region, BufferedImage image,
int chunkX, int chunkZ) {
if (chunkZ == 0)
System.out.print(".");
DataInputStream chunkDataInputStream = region.getChunkDataInputStream(chunkX, chunkZ);
if (chunkDataInputStream == null)
return;
try {
Tag tag = Tag.readFrom(chunkDataInputStream);
Tag[] sections = (Tag[]) tag.findTagByName("Sections").getValue();
byte[][] sectionData = new byte[sections.length][];
for (int i = 0; i < sections.length; i++)
sectionData[i] = (byte[]) sections[i].findTagByName("Blocks").getValue();
int maxY = sections.length * 16 - 1;
int blockID;
byte[] section;
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
for (int y = maxY; y >= 0; y--) {
section = sectionData[y / 16];
blockID = (int)section[(y % 16) * 256 + z * 16 + x];
if (colors.containsKey(blockID)) {
image.setRGB(chunkX * 16 + x, chunkZ * 16 + z, colors.get(blockID));
break;
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 8 |
public void addResultToEvent(String eventIdentifier, Result newResult)
{
for(Event e: events){
if(e.getIdentifier().equals(eventIdentifier))
{
//We check if the result is already there
for(Result r: e.getResults()){
if(r.getIdentifier().equals(newResult.getIdentifier()))
throw new IllegalArgumentException("There's already a result with that identifier. Identifiers for results need to be unique per event.");
}
//If not, just add it
e.getResults().add(newResult);
return;
}
}
throw new IllegalArgumentException("There's no event with the identifier '"+eventIdentifier+"'.");
} | 4 |
@Test
public void resolve() {
print(squaresOfSum(1,100)-sumOfSquares(1,100));
} | 0 |
@Override
void processStatus(Status status) {
if (_startDate == null) {
_startDate = new Date();
}
StringTokenizer tokenizer = new StringTokenizer(status.getText());
while (tokenizer.hasMoreElements()) {
String word = tokenizer.nextToken();
if ((_onlyHashtags == false && _stopWords.contains(word))
|| (_onlyHashtags == true && word.startsWith("#"))) {
synchronized (_topWords) {
_topWords.offer(word);
}
}
++_numberOfWordsProcessesd;
}
} | 6 |
private void button13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button13ActionPerformed
if (order2code2tf.getText().equals("1001"))
{
o2c2destf.setText("Chicken Nugget");
}
if (order2code2tf.getText().equals("1002"))
{
o2c2destf.setText("Fries");
}
if (order2code2tf.getText().equals("1003"))
{
o2c2destf.setText("Salad");
}
if (order2code2tf.getText().equals("1004"))
{
o2c2destf.setText("Cheese Burger");
}
if (order2code2tf.getText().equals("1005"))
{
o2c2destf.setText("Bacon Cheese Burger");
}
if (order2code2tf.getText().equals("1006"))
{
o2c2destf.setText("Hamburger");
}
if (order2code2tf.getText().equals("1007"))
{
o2c2destf.setText("Soda");
}
if (order2code2tf.getText().equals("1008"))
{
o2c2destf.setText("Tea");
}
if (order2code2tf.getText().equals("1009"))
{
o2c2destf.setText("Coffee");
}
}//GEN-LAST:event_button13ActionPerformed | 9 |
protected void FillBuff() throws java.io.IOException
{
if (maxNextCharInd == available)
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = maxNextCharInd = 0;
available = tokenBegin;
}
else if (tokenBegin < 0)
bufpos = maxNextCharInd = 0;
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
}
int i;
try {
if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1)
{
inputStream.close();
throw new java.io.IOException();
}
else
maxNextCharInd += i;
return;
}
catch(java.io.IOException e) {
--bufpos;
backup(0);
if (tokenBegin == -1)
tokenBegin = bufpos;
throw e;
}
} | 9 |
Subsets and Splits