text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
sb = new StringBuilder();
String line = in.readLine();
for ( ; line!=null; ) {
int n = Integer.parseInt(line);
if(n==0)break;
vAx = new ArrayList<Integer>();
vAy = new ArrayList<Integer>();
vAs = new ArrayList<Integer>();
vDx = new ArrayList<Integer>();
vDy = new ArrayList<Integer>();
vDs = new ArrayList<Integer>();
m = new String[n][n];
for (int i = 0; i < n; i++) {
line = in.readLine();
for (int j = 0; j < line.length(); j++) {
m[i][j] = line.charAt(j)+"";
if(m[i][j].equals(".")) dot++;
}
}
in.readLine();
for ( ;(line=in.readLine())!=null && !line.equals("Down"); ) {
StringTokenizer st = new StringTokenizer(line);
int y = (Integer.parseInt(st.nextToken()))-1;
int x = (Integer.parseInt(st.nextToken()))-1;
int sum = Integer.parseInt(st.nextToken());
vAx.add(x);
vAy.add(y);
vAs.add(sum);
}
for ( ;(line=in.readLine())!=null && line.trim().contains(" "); ) {
StringTokenizer st = new StringTokenizer(line);
int y = Integer.parseInt(st.nextToken())-1;
int x = Integer.parseInt(st.nextToken())-1;
int sum = Integer.parseInt(st.nextToken());
vDx.add(x);
vDy.add(y);
vDs.add(sum);
}
solve( );
imprimir();
}
System.out.print(new String(sb));
} | 9 |
protected synchronized void deliverObserverEvents(
Vector<TSEvent> _eventList, boolean snapshot) {
String tsEventLog = null;
if (_eventList == null)
return;
int metaCode;
int cause;
if (snapshot) {
metaCode = 135;
cause = 110;
} else {
metaCode = 136;
cause = 100;
}
int nextMetaEventIndex = this.observerEventList.size();
Object privateData = null;
log.debug("meta event BEGIN: cause (" + cause + ") metaCode ("
+ metaCode + ")" + " for " + this.observer);
for (int i = 0; i < _eventList.size(); i++) {
TSEvent ev = (TSEvent) _eventList.elementAt(i);
privateData = ev.getPrivateData();
switch (ev.getEventType()) {
case 1:
tsEventLog = "PROVIDERINSERVICEEVENT for "
+ (TSProvider) ev.getEventTarget();
addEv(new TsapiProviderInServiceEvent(
createProvider((TSProviderImpl) ev.getEventTarget()),
cause, metaCode, privateData), tsEventLog);
break;
case 2:
tsEventLog = "PROVIDEROUTOFSERVICEEVENT for "
+ (TSProvider) ev.getEventTarget();
addEv(new TsapiProviderOutOfServiceEvent(
createProvider((TSProviderImpl) ev.getEventTarget()),
cause, metaCode, privateData), tsEventLog);
break;
case 3:
tsEventLog = "PROVIDERSHUTDOWNEVENT for "
+ (TSProvider) ev.getEventTarget();
addEv(new TsapiProviderShutdownEvent(
createProvider((TSProviderImpl) ev.getEventTarget()),
cause, metaCode, privateData), tsEventLog);
break;
case 9999:
tsEventLog = "PRIVATEEVENT for "
+ (TSProvider) ev.getEventTarget();
addEv(new TsapiPrivateProviderEvent(
createProvider((TSProviderImpl) ev.getEventTarget()),
cause, metaCode, privateData), tsEventLog);
}
}
synchronized (this.observerEventList) {
log.debug("meta event END for " + this.observer
+ " eventList size=" + this.observerEventList.size());
if (this.observerEventList.size() == 0) {
log.debug("no events to send to " + this.observer);
return;
}
if (nextMetaEventIndex < this.observerEventList.size()) {
((TsapiObserverEvent) this.observerEventList
.elementAt(nextMetaEventIndex)).setNewMetaEventFlag();
}
}
} | 9 |
public float nextRatio() {
float u, v, x, xx;
do {
// u and v are two uniformly-distributed random values
// in [0, 1), and u != 0.
while ((u = gen.nextFloat()) == 0); // try again if 0
v = gen.nextFloat();
float y = C1*(v - 0.5f); // y coord of point (u, y)
x = y/u; // ratio of point's coords
xx = x*x;
} while (
(xx > 5f - C2*u) // quick acceptance
&&
( (xx >= C3/u + 1.4f) || // quick rejection
(xx > (float) (-4*Math.log(u))) ) // final test
);
return stddev*x + mean;
} | 4 |
@Override
public void invalidateLayout(Container target) {
for (PrecisionLayoutData one : mConstraints.values()) {
one.clearCache();
}
} | 1 |
private void computeGridCountAndCentroids(HashMap<ArrayList<Integer>, Integer> data) {
// create the number of grid for each dimension
dimSize = new int[numDimension]; // the number of grids for each dimension
for (int i=0; i<numDimension; i++) {
int rangeDimension = maxList[i] - minList[i];
dimSize[i] = rangeDimension / gridSize + 1;
}
// we can store gridCount inside Hashmap as:
// key = [d1, d2, d3] --> arrayList
// value = count --> the count of points in grid[d1,d2,d3] --> grid score
gridCount = new HashMap<ArrayList<Integer>,Integer>();
HashMap<ArrayList<Integer>,ArrayList<Integer>> gridSumPoints = new HashMap<ArrayList<Integer>,ArrayList<Integer>>();
// iterate over all elements of data
for (Map.Entry<ArrayList<Integer>, Integer> entry : data.entrySet()) {
// get the elements of data
ArrayList<Integer> key = entry.getKey();
Integer value = entry.getValue();
// find out the index of each key (or points)
ArrayList<Integer> gridIndexes = intToGridIndex(key);
// put into gridCount
if ( gridCount.containsKey(gridIndexes) ) {
// adding additional (number of) points
int prevValue = gridCount.get(gridIndexes);
gridCount.put(gridIndexes, prevValue+value);
ArrayList<Integer> prevSum = gridSumPoints.get(gridIndexes);
gridSumPoints.put(gridIndexes,Util.additionArrayList(prevSum, Util.multiplicationArrayList(key, value)));
} else {
// put the first number of points here
gridCount.put(gridIndexes, value);
// first sum of coordinate points
gridSumPoints.put(gridIndexes, Util.multiplicationArrayList(key,value));
}
}
// finalize the grid centroids
gridCentroids = new HashMap<ArrayList<Integer>, ArrayList<Double> > ();
for (Map.Entry<ArrayList<Integer>, ArrayList<Integer>> entry : gridSumPoints.entrySet()) {
ArrayList<Integer> key = entry.getKey();
int count = gridCount.get(key);
ArrayList<Integer> initialCentroids = gridSumPoints.get(key);
gridCentroids.put(key, Util.divisionArrayList(initialCentroids, count) );
}
} | 4 |
public void desconectar(){
connection = null;
} | 0 |
private static void calcNoOfNodes(Node node) {
if (node instanceof Parent) {
if (((Parent) node).getChildrenUnmodifiable().size() != 0) {
ObservableList<Node> tempChildren = ((Parent) node).getChildrenUnmodifiable();
noOfNodes += tempChildren.size();
for (Node n : tempChildren) {
calcNoOfNodes(n);
//System.out.println(n.getStyleClass().toString());
}
}
}
} | 3 |
public static void createLocalDatabaseAndUser(MySQLIdentity root, MySQLIdentity newIdentity) throws SQLException, MySQLException {
if((root.host == null) || (newIdentity.host == null)) { throw new MySQLException("Host not specified");}
if(root.host.equals(newIdentity.host) == false) { throw new MySQLException("Hosts must not be different");}
MySQLService.quickExec(root, "CREATE DATABASE " + newIdentity.databaseName);
MySQLService.quickExec(root, "CREATE USER '" + newIdentity.user + "'@'" + newIdentity.host + "' IDENTIFIED BY '" + newIdentity.password + "';");
MySQLIdentity rootAtNewDatabase = MySQLService.createMyIdentity(root.host, newIdentity.databaseName, root.user, root.password);
MySQLService.quickExec(rootAtNewDatabase, "GRANT ALL PRIVILEGES ON " + newIdentity.databaseName + " .* TO '" + newIdentity.user + "'@'" + newIdentity.host + "';");
} | 3 |
public static void main(String[] args)
{
long start = System.currentTimeMillis();
try
{
ObjectInputStream inputFile =
new ObjectInputStream( new
FileInputStream("myBInaryIntegers.dat"));
for (int i = 1; i <= 1000000; i++){
int tempInt = inputFile.readInt();
System.out.println(tempInt);
}
System.out.println("Numbers have been written to the file.");
inputFile.close();
}
catch(IOException e)
{
//e.getStackTrace();
System.out.println("Exception caught when input.");
}
long end = System.currentTimeMillis();
System.out.println("Took: " + ((end - start)) + "ms");
} | 2 |
public int[] searchRange(int[] A, int target) {
int mid = 0;
int start = 0, end = A.length - 1;
int[] index = { -1, -1 };
boolean flag = true;
while (start <= end) {
mid = (start + end) >> 1;
if (A[mid] == target) {
flag = false;
break;
}
if (A[mid] > target)
end = mid - 1;
else
start = mid + 1;
}
if (flag)
return index;
int right = mid;
while (right < A.length && A[right] == target)
right++;
int left = mid;
while (left >= 0 && A[left] == target)
left--;
index[0] = left + 1;
index[1] = right - 1;
return index;
} | 8 |
@Override
protected void setBounds(Rectangle bounds) {
super.setBounds(bounds);
map = new Tile[bounds.height][bounds.width];
// Tile instance properties is null when this method is called from
// the constructor of MapLayer
if (tileInstanceProperties != null) {
tileInstanceProperties.clear();
}
} | 1 |
public void helper(BoggleBoard board, int r, int c, ArrayList<BoardCell> list,
StringBuilder searchWord, ILexicon lex) {
if(r < 0 || r>= board.size() || c < 0 || c >= board.size()) {
return;
}
BoardCell init = new BoardCell(r,c);
if(list.contains(init)) {
return;
}
String letterHere = board.getFace(r, c);
searchWord.append(letterHere);
if(lex.wordStatus(searchWord)!= LexStatus.NOT_WORD) {
list.add(init);
if(lex.wordStatus(searchWord) == LexStatus.WORD) {
add(searchWord.toString()); // here add is referring to the AbstractPlayer
//not the list of boardcells
}
int[] rdelta = {-1,-1,-1, 0, 0, 1, 1, 1};
int[] cdelta = {-1, 0, 1,-1, 1,-1, 0, 1};
//If the string is either a word or the prefix of a word in the lexicon then the search is
//continued by calling the helper method for each adjacent cube with the string built so far.
for(int k=0; k < rdelta.length; k++){
helper(board, r+rdelta[k], c+cdelta[k], list, searchWord, lex);
}
//If the string is not a prefix (or a word) then the
//search is cut-off at this point and the recursion will unwind/backtrack
list.remove(init);
}
//since you're backtracking, be sure to undo the marking of a board cell both in the string being
//built and in the structure storing which board cells contributed to the string
for(int pl = 0; pl < letterHere.length(); pl++) {
searchWord.deleteCharAt(searchWord.length() - 1);
}
return;
} | 9 |
static void preprocess(char[] p) {
int i = 0, j = -1, m = p.length;
b = new int[p.length + 1];
b[0] = -1;
while (i < m) {
while (j >= 0 && p[i] != p[j])
j = b[j];
b[++i] = ++j;
}
} | 3 |
public static void main(String[] args) {
MainWindowModel mainWindowModel = new MainWindowModel();
MainWindowView mainWindowView = new MainWindowView();
InterpolatorModel interpolatorModel = new InterpolatorModel();
PlotBuilder plotBuilder = new PlotBuilder();
plotBuilder.setInterpolatorModel(interpolatorModel);
MainWindowController mainWindowController = new MainWindowController();
mainWindowController.setMainWindowView(mainWindowView);
mainWindowController.setMainWindowModel(mainWindowModel);
mainWindowController.setPlotBuilder(plotBuilder);
mainWindowController.setxStream(new XStream(new DomDriver()));
DialogWindowView dialogWindowView = new DialogWindowView("Progress");
DialogWindowController dialogWindowController = new DialogWindowController();
dialogWindowController.setPlotBuilder(plotBuilder);
dialogWindowController.setDialogWindowView(dialogWindowView);
mainWindowView.display();
} | 0 |
public AutoTotaalDienst getATD() {
ArrayList<AutoTotaalDienst> alleATDDB = new ArrayList<AutoTotaalDienst>();
try {
this.leesDatabase();
output = statement.executeQuery("SELECT * FROM autototaaldienst");
while (output.next()){
double lp = output.getDouble("literprijs");
double wup = output.getDouble("werkuurprijs");
double mp = output.getDouble("maandprijs");
double wp = output.getDouble("weekprijs");
double dp = output.getDouble("dagprijs");
AutoTotaalDienst atd = new AutoTotaalDienst();
atd.setLiterPrijs(lp);
atd.setWerkUurPrijs(wup);
atd.setMaandPrijs(mp);
atd.setWeekPrijs(wp);
atd.setDagPrijs(dp);
alleATDDB.add(atd);
}
} catch (SQLException e) {
e.printStackTrace();
}
AutoTotaalDienst atd = alleATDDB.get(0);
return atd;
} | 2 |
private boolean OpenFile()
{
//read status
boolean status = false;
try
{
//open the file output stream
FileOutputStream outStream = new FileOutputStream(System.getProperty("user.dir")+"\\"+fileName);
//set the data stream for the file
out = new DataOutputStream(outStream);
//open write stream to file
br = new BufferedWriter(new OutputStreamWriter(out));
}
catch(Exception e){
//get the error message
System.out.println("Error opening file: " + e.getMessage());
status = false;
}
//return status of file read
return status;
} | 1 |
public void stopLoop(){
isRunning = false;
// Stop the game-loop:
try {
game_loop_executor.shutdown();
game_loop_executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (SecurityException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop all scenes if they're running:
for (Scene scene : scenes.values())
if (scene.getSceneState() != Scene.State.PENDING)
scene.onStopCall();
// Hide the game-window:
Viewport.setWindowVisibility(false);
} | 4 |
private boolean r_postlude() {
int among_var;
int v_1;
// repeat, line 62
replab0: while(true)
{
v_1 = cursor;
lab1: do {
// (, line 62
// [, line 63
bra = cursor;
// substring, line 63
among_var = find_among(a_1, 3);
if (among_var == 0)
{
break lab1;
}
// ], line 63
ket = cursor;
switch(among_var) {
case 0:
break lab1;
case 1:
// (, line 64
// <-, line 64
slice_from("\u00E3");
break;
case 2:
// (, line 65
// <-, line 65
slice_from("\u00F5");
break;
case 3:
// (, line 66
// next, line 66
if (cursor >= limit)
{
break lab1;
}
cursor++;
break;
}
continue replab0;
} while (false);
cursor = v_1;
break replab0;
}
return true;
} | 8 |
private final void read(SelectionKey key) {
@SuppressWarnings("resource")
SocketChannel socketChannel = (SocketChannel) key.channel();
Session session = (Session) key.attachment();
mReadBuffer.clear();
int amount;
try {
amount = socketChannel.read(mReadBuffer);
if (amount > 0) {
session.requestHandleInput(mReadBuffer);
} else if (amount == -1) {
session.requestClose(false);
}
} catch (Throwable throwable) {
session.requestClose(true);
}
} | 3 |
private void printBezochteVelden(RouteMetaData[][] bezochtevelden) {
System.out.println("");
System.out.println("");
for (int i = 0; i < bezochtevelden.length; i++) {
for (int j = 0; j < bezochtevelden[i].length; j++) {
if (bezochtevelden[i][j] != null) {
System.out.print(bezochtevelden[i][j].afstand + " ");
} else {
System.out.print("X ");
}
}
System.out.println("");
}
} | 3 |
private boolean booleanOption(String s) {
if (s == null) return true;
switch (s) {
case "true": case "yes": case "on": case "1": return true;
case "false": case "no": case "off": case "0": return false;
}
throw new IllegalArgumentException("unrecognized boolean flag="+s);
} | 9 |
private void insertEmployeeIntoTable(Employee employee) {
Object[] fields = new Object[7];
fields[0] = employee.getEmployeeNumber();
fields[1] = employee.getFirstName();
fields[2] = employee.getInsertion().isEmpty() ? "" : employee.getInsertion();
fields[3] = employee.getFamilyName();
fields[4] = employee.getContractType().toString();
fields[5] = employee.getEmployeeType().toString();
fields[6] = employee.getContractHours();
model.addRow(fields);
for (int i = 0; i < tblEmployee.getColumnCount(); i++) {
tblEmployee.getColumnModel().getColumn(i).setCellRenderer(new WhiteRenderer());
}
} | 2 |
synchronized void delayAndPrint(int cnt)
{
try{
System.out.print("Thread:"+cnt+",Mehod:1-Am in");
Thread.sleep(2000);
System.out.println(", After 2 sec out");
}
catch(Exception e)
{
System.out.println("Error-"+e);
}
} | 1 |
private void recoleccion() {
int estado;
boolean cont=carro.evaluarActHuerto();
while(!carro.getCargado() && cont)
{
estado=carro.evaluarRecoleccion();
if(estado==Huerto.DISPONIBLE){
carro.recolectar();
try {
sleep(harvestTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if(estado==Huerto.EN_RECOLECCION){
try {
sleep(waitingTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if(estado==Huerto.VACIO){
//TODO: Diseñar el accionar a seguir cuando el huerto se encuentra vacio.
cont=false;
runningThread=false;
}
else if(estado==Huerto.ERROR)
{
cont=false;
runningThread=false;
}
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Column other = (Column) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (table == null) {
if (other.table != null)
return false;
} else if (!table.equals(other.table))
return false;
return true;
} | 9 |
public Void visitConditionDirective(ConditionDirectiveContext ctx) {
if (ctx.LEFT_PAREN() != null)
appendCode("(");
switch (ctx.conditionDirective().size()) {
case 0:
if (ctx.definedCondition() != null)
visitDefinedCondition(ctx.definedCondition());
break;
case 1:
// TODO: Fix the bug! COMMENT token will interfere with this
// negative condition.
if (ctx.EXCAL() != null)
appendCode("! ");
visitConditionDirective(ctx.conditionDirective(0));
break;
case 2:
visitConditionDirective(ctx.conditionDirective(0));
if (ctx.CPP_AND() != null)
appendCode(" && ");
else if (ctx.CPP_OR() != null)
appendCode(" || ");
visitConditionDirective(ctx.conditionDirective(1));
break;
}
if (ctx.RIGHT_PAREN() != null)
appendCode(")");
return null;
} | 9 |
private void verifyUser(String username, String password) throws Exception{
schema = (FdotSchemaImpl) factory.getBean("connection_specs");
SdeConnection conn = new SdeConnection(schema.getServer(),
schema.getInstance(),
schema.getDatabase(),
username,
password);
try{
try {
_log.info("Verifying credentials...");
conn.open_connection();
} catch (SeException se){
JOptionPane.showMessageDialog(this, "Failed to verify your credentials! Please try again.");
if(conn!=null) {
_log.info("Failed to verify your credentials! Please try again.");
conn.close_connection();
}
throw new Exception("Connection Failed!!");
}
Test.mainUsername = username;
Test.mainPassword = password;
if(conn!=null){
// _log.info("Close connection");
conn.close_connection();
}
_log.info("Complete verifying credentials!");
} catch (SeException e) {
_log.error(e.getMessage());
_log.error(e.getSeError().getErrDesc());
_log.error(e.getSeError().getSdeErrMsg());
}
} | 4 |
private ChatSocketServer() {
super();
for (int i = 0; i < rooms.length; i++) {
if (i == DEFAULT_ROOM)
rooms[i] = ChatRoom
.getInstance(ManagerSocketServer.MAX_CLIENTS);
else
rooms[i] = ChatRoom
.getInstance(GameSocketServer.MAX_NUMBER_OF_USERS_PER_GAME);
}
} | 2 |
public Map<String, Constructor<? extends ICreature>> getConstructorMap() {
return constructorMap;
} | 1 |
public int getEast(){
return this.east;
} | 0 |
protected void change()
{
Integer tickets = ticketsBox.getValue();
Integer friends = friendsBox.getValue();
Integer winners = winnersBox.getValue();
Integer limit = limitBox.getValue();
if (validate(tickets, 1000, 1, ticketsBox) &&
validate(winners, tickets, 1, winnersBox) &&
validate(limit, 100, 1, limitBox) &&
validate(friends, tickets, 1, friendsBox))
{
if (tickets != null && friends != null && winners != null && limit != null)
{
resultLabel.setText("");
if (serverCheckBox.getValue())
{
GwtLotteryCalculatorAsync asyncCalculator = GWT.create(GwtLotteryCalculator.class);
busyImage.setVisible(true);
asyncCalculator.calculate(tickets, winners, friends, limit, new AsyncCallback<Double>()
{
@Override
public void onFailure(Throwable caught)
{
Window.alert("Failed to communicate with server");
busyImage.setVisible(false);
}
@Override
public void onSuccess(Double result)
{
updateResult(result);
busyImage.setVisible(false);
}
});
}
else
{
LotteryCalculator calculator = new StandardLotteryCalculator();
double result = calculator.calculate(tickets, winners, friends, limit);
updateResult(result);
}
}
}
} | 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Role other = (Role) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} | 9 |
@EventHandler
public void onHit(EntityDamageByEntityEvent e ){
if(e.getEntity() instanceof Player && e.getDamager() instanceof Player){
Player p = (Player) e.getEntity();
Player d = (Player) e.getDamager();
if(PlayerListener.getGhostMode(d)){
PlayerListener.toggleGhostMode(p);
Main.getAPI().startSpectating(d, (CraftPlayer) p, true);
e.setCancelled(true);
}
}
} | 3 |
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
switch (opcao) {
case 'm':
jp = new ExibeAtracoes('m', linguagem, utilizador);
//System.out.println("FrPrincipal - utilizador" + utilizador);
break;
case 'e':
jp = new ExibeAtracoes('e', linguagem, utilizador);
break;
case 'h':
jp = new ExibeAtracoes('h', linguagem, utilizador);
break;
case 'r':
jp = new ExibeAtracoes('r', linguagem, utilizador);
break;
case 'p':
jp = new PnTabelaTodos(linguagem, utilizador);
break;
case 't':
jp = new PnlTops(linguagem, utilizador);
break;
case 'u':
jp = new PnTabelaUtilizador(linguagem);
break;
default:
throw new AssertionError();
}
panel.add(jp, BorderLayout.CENTER);
panel.revalidate();
panel.repaint();
} else if (ie.getStateChange() == ItemEvent.DESELECTED) {
panel.remove(layout.getLayoutComponent(BorderLayout.CENTER));
panel.revalidate();
panel.repaint();
}
} | 9 |
public ParseTreeNode rexp3() throws SyntaxError {
ParseTreeNode node = new ParseTreeNode("<rexp3>");
if (symbol == '.' || symbol == '[' || isDefinedClass()) {
node.addChild(charClass());
return node;
}
return node;
} | 3 |
public Rectangle boundingBox(){
BufferedImage bi = animation.getImage();
Rectangle rect = new Rectangle();
switch(spikeDir){
case top:
rect.x = (int) position.x();
rect.y = (int) position.y();
rect.width = bi.getWidth();
rect.height = 10;
break;
case bottom:
rect.x = (int) position.x();
rect.y = (int) (position.y()+bi.getHeight()-10);
rect.width = bi.getWidth();
rect.height = 10;
break;
case left:
rect.x = (int) position.x();
rect.y = (int) position.y();
rect.width = 10;
rect.height = bi.getHeight();
break;
case right:
rect.x = (int) (position.x()+bi.getWidth()-10);
rect.y = (int) position.y();
rect.width = 10;
rect.height = bi.getHeight();
break;
default:
rect.x = (int) position.x();
rect.y = (int) position.y();
rect.width = bi.getWidth();
rect.height = bi.getHeight();
break;
}
return rect;
} | 4 |
public static void makeRandomInteger(Matrix matrix) throws MatrixIndexOutOfBoundsException {
int rows = matrix.getRowsCount();
int cols = matrix.getColsCount();
double temp = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// fill with random values
temp = (int) (Math.random() * maxNumber);
matrix.setValue(i, j, temp);
}
}
} | 2 |
@Override
public boolean removeAll(Collection<?> list) {
boolean changed = false;
for (Object o: list)
if (remove(o))
changed = true;
return changed;
} | 3 |
public static void offerOrDropItem(EntityMinecart cart, ItemStack stack) {
stack = transferHelper.pushStack(cart, stack);
if (stack != null && stack.stackSize > 0)
cart.entityDropItem(stack, 1);
} | 2 |
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event){
Action action = event.getAction();
if (action.equals(Action.RIGHT_CLICK_BLOCK)){
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if ((block.getType().equals(Material.SIGN) || block.getType().equals(Material.SIGN_POST) || block.getType().equals(Material.WALL_SIGN))) {
Casino.conf = Casino.plugin.getConfig();
String i = Casino.makeString(block.getLocation());
if(Casino.conf.contains("slots."+i)) {
slotGo(block, player);
}
}
}
} | 5 |
int readCorner4(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 3, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 2, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(2, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(3, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
} | 8 |
public boolean getIsFinished() {
return finished;
} | 0 |
public static void main(String[] args) {
try {
String input = null, output = "out.s";
for(int i = 0; i<args.length; i++) {
switch(args[i]) {
case "-o":
// next item will be the filename of the disassembler
// output
i++;
output = args[i];
break;
default:
// default is intput file name
input = args[i];
break;
}
}
if(input == null) {
System.out.println("No input file provided");
System.exit(1);
}
int[] code = DLXutil.readCode(input);
FileWriter w = new FileWriter(output);
for(int i : code) {
w.write(DLX.disassemble(i));
}
w.close();
System.exit(0);
} catch (Exception e) {
System.out.println("An error occured");
System.exit(-1);
}
} | 5 |
public void ResetPlayer() {
//booleans to control win and lose conditions
raceWin = false;
crashed = false;
//place the car on the canvas
x = (int) (Framework.frameWidth * 0.20);
y = (int) (Framework.frameHeight * 0.70);
//speed of the car
speedX = 0;
speedY = 0;
} | 0 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
char[] m = line.trim().toCharArray();
int n = m.length;
long row = 0, col = 0;
long all = 1L << n;
for (int i = 0; i < n; i++) {
switch (m[i]) {
case '1':
row += all / 2;
break;
case '2':
col += all / 2;
break;
case '3':
row += all / 2;
col += all / 2;
break;
}
all /= 2L;
}
out.append(n + " " + row + " " + col + "\n");
}
System.out.print(out);
} | 5 |
public Set<T> less(Set<T> s)
{ Set<T> res=this;
if(s==null)
{ return res;}
else
{ if(res.next!=null)
{ return res.del(s.a).less(s.next);}
else//res.next==null
{ return null;
}
}
} | 2 |
private void evalArrayStore(Type expectedComponent, Frame frame) throws BadBytecode {
Type value = simplePop(frame);
Type index = frame.pop();
Type array = frame.pop();
if (array == Type.UNINIT) {
verifyAssignable(Type.INTEGER, index);
return;
}
Type component = array.getComponent();
if (component == null)
throw new BadBytecode("Not an array! [pos = " + lastPos + "]: " + component);
component = zeroExtend(component);
verifyAssignable(expectedComponent, component);
verifyAssignable(Type.INTEGER, index);
// This intentionally only checks for Object on aastore
// downconverting of an array (no casts)
// e.g. Object[] blah = new String[];
// blah[2] = (Object) "test";
// blah[3] = new Integer(); // compiler doesnt catch it (has legal bytecode),
// // but will throw arraystoreexception
if (expectedComponent == Type.OBJECT) {
verifyAssignable(expectedComponent, value);
} else {
verifyAssignable(component, value);
}
} | 3 |
public static Ability getMyPlantsSpell(Item I, MOB mob)
{
if((I!=null)
&&(I.rawSecretIdentity().equals(mob.Name()))
&&(I.owner()!=null)
&&(I.owner() instanceof Room))
{
for(final Enumeration<Ability> a=I.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&((A.invoker()==mob)||(A.text().equals(mob.Name())))
&&(A instanceof Chant_SummonPlants))
return A;
}
}
return null;
} | 9 |
private boolean uhattuVasemmalta(int pelaajaNumero, int x, int y) {
int i = 1;
while(y-i >= 0 && kentta[x][y-i].onTyhja()) i++;
if(y-i == -1) return false;
if(kentta[x][y-i].getNappula().omistajanPelinumero() != pelaajaNumero) {
if(i == 1 && kentta[x][y-i].getNappula().getClass() == new Kuningas().getClass()) return true;
if(kentta[x][y-i].getNappula().getClass() == new Kuningatar().getClass()) return true;
if(kentta[x][y-i].getNappula().getClass() == new Torni().getClass()) return true;
}
return false;
} | 8 |
void getCommands()
{
ArrayList<Commands> commands;
DBase dbase = new DBase();
commands = dbase.getParserCommands();
for (Commands c : commands)
{
if (c.type.equalsIgnoreCase("Move"))
{
movement.add(c.word);
} else if (c.type.equalsIgnoreCase("Direction"))
{
direction.add(c.word);
} else if (c.type.equalsIgnoreCase("Use"))
{
use.add(c.word);
} else if (c.type.equalsIgnoreCase("Collect"))
{
itemCollect.add(c.word);
} else if (c.type.equalsIgnoreCase("Inventory"))
{
inventory.add(c.word);
} else if (c.type.equalsIgnoreCase("Drop"))
{
itemDrop.add(c.word);
}
}
} | 7 |
public KeyFrame getNextKey() {
Iterator<KeyFrame> itr = keys.iterator();
while (itr.hasNext()) {
KeyFrame k = itr.next();
if (k == currentKey) {
if (itr.hasNext())
return itr.next();
}
}
return keys.get(0);
} | 3 |
public void terminate() {
stop = true;
try {
socket.close();
in.interrupt();
out.interrupt();
} catch (final IOException ioe) {
// Ignore
}
logger.debug("Terminated peer exchange with " + peer + "...");
} | 1 |
public void constructPieWithPieBuilder(PieBuilder pb) {
this.pb = pb;
constructed = false;
if (this.pb != null) {
this.pb.createNewPie();
this.pb.buildDough();
this.pb.buildFilling();
constructed = true;
} else {
BuilderClient.addOutput("error - no pie builder found!");
}
} | 1 |
protected void render() {
if (allEntries.size() == 0) return ;
//
// First, determine a 'viewing window' for the text, if larger than the
// visible pane-
final Box2D textArea = new Box2D().set(0, 0, xdim(), ydim()) ;
if (scrollbar != null) {
final float lineHigh = 0 ;// alphabet.map[' '].height * scale ;
textArea.ypos(
(0 - lineHigh) -
(fullSize.ydim() - ydim()) * (1 - scrollbar.scrollPos())
) ;
}
//
// See what was clicked, if anything-
// TODO: Move this to the selection method?
final Clickable link = getTextLink(myHUD.mousePos(), textArea) ;
final Batch <ImageEntry> bullets = new Batch <ImageEntry> () ;
//
// Begin the rendering pass...
alphabet.fontTex.bindTex() ;
GL11.glEnable(GL11.GL_SCISSOR_TEST) ;
GL11.glScissor((int) xpos(), (int) ypos(), (int) xdim(), (int) ydim()) ;
GL11.glBegin(GL11.GL_QUADS) ;
for (Box2D entry : allEntries) {
if (entry instanceof TextEntry) {
renderText(textArea, (TextEntry) entry, link) ;
}
else bullets.add((ImageEntry) entry) ;
}
GL11.glEnd() ;
for (ImageEntry entry : bullets) {
renderImage(textArea, entry) ;
}
GL11.glDisable(GL11.GL_SCISSOR_TEST) ;
// TODO: Move this to the selection method?
if (myHUD.mouseClicked() && link != null) link.whenClicked() ;
} | 7 |
public Color convertToColor(SquareColor color) {
if (color == null) {
return Color.WHITE;
}
switch (color) {
case BLUE:
return Color.BLUE;
case RED:
return Color.RED;
case YELLOW:
return Color.YELLOW;
case GRAY:
return Color.GRAY;
case GREEN:
return Color.GREEN;
case ORANGE:
return Color.ORANGE;
case BLACK:
return Color.BLACK;
default:
return Color.WHITE;
}
} | 8 |
private void receiveAndDispatch() throws Exception {
try {
Session session = receiveTemplate.getSession();
MessageConsumer consumer = receiveTemplate.getMessageConsumer();
Message msg = consumer.receive(500);
if (msg != null) {
if (MSG_TYPE_REQUEST.equals(msg.getJMSType())) {
// Handle decoding the message in the dispatch thread.
getDispatchThreads().execute(new DispatchTask(this, (ObjectMessage) msg, false));
} else if (MSG_TYPE_ONEWAY.equals(msg.getJMSType())) {
// Handle decoding the message in the dispatch thread.
getDispatchThreads().execute(new DispatchTask(this, (ObjectMessage) msg, true));
} else if (MSG_TYPE_RESPONSE.equals(msg.getJMSType())) {
try {
long request = msg.getLongProperty(MSG_PROP_REQUEST);
RequestExchange target = requests.remove(request);
if (target != null) {
Response response = null;
try {
Thread.currentThread().setContextClassLoader(getUserClassLoader(target));
response = (Response) ((ObjectMessage) msg).getObject();
response.fromRemote = true;
} catch (JMSException e) {
target.setResponse(new Response(request, null, new UnmarshalException("Could not unmarshall response: " + e.getMessage(), e)));
}
target.setResponse(response);
}
} catch (JMSException e) {
e.printStackTrace();
}
}
}
} catch (TemplateClosedException tce) {
//TODO we should probably just eat this.
tce.printStackTrace();
throw tce;
} catch (Exception e) {
e.printStackTrace();
receiveTemplate.reset();
throw e;
}
} | 9 |
private static void clearBuffer() {
if (N == 0) return;
if (N > 0) buffer <<= (8 - N);
try { out.write(buffer); }
catch (IOException e) { e.printStackTrace(); }
N = 0;
buffer = 0;
} | 3 |
public boolean canMove(int i, int j, Direction d) throws CellDoesNotExistException {
checkCellExists(i, j);
if (isWallUp(i, j, d)) {
// There is a wall that is blocking us, so we cannot move that way.
return false;
} else {
// No wall, so let's see if we can move that way.
int i1 = i;
int j1 = j;
switch (d) {
case NORTH:
i1--;
break;
case SOUTH:
i1++;
break;
case WEST:
j1--;
break;
case EAST:
j1++;
break;
}
// Cell (i1,j1) is the new position. Is it in the maze?
if (cellExists(i1, j1)) {
// New position is in the maze. Is it filled?
if (isFilled(i1, j1)) {
// Yes, so we cannot move.
return false;
} else {
// No, we can move.
return true;
}
} else {
// No, the new position is out of the maze. We can then move (an exit!).
return true;
}
}
} | 7 |
public static <T extends DC> Set<Pair<PT<Integer>,T>> dom(Set<Pair<Pair<PT<Integer>,T>,Pair<PT<Integer>,T>>> phiMax)
{ if(phiMax!=null)
{ if(phiMax.getNext()!=null)
{ return new Set(phiMax.getFst().fst(),dom(phiMax.getNext()));
}
else
{ return new Set(phiMax.getFst().fst(),null);
}
}
else
{ return null;
}
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple3 tuple3 = (Tuple3) o;
if (_0 != null ? !_0.equals(tuple3._0) : tuple3._0 != null) return false;
if (_1 != null ? !_1.equals(tuple3._1) : tuple3._1 != null) return false;
if (_2 != null ? !_2.equals(tuple3._2) : tuple3._2 != null) return false;
return true;
} | 9 |
@Override
public void enumerate(String uid, String connectedUid, char position,
short[] hardwareVersion, short[] firmwareVersion,
int deviceIdentifier, short enumerationType) {
// configure bricks on first connect (ENUMERATION_TYPE_CONNECTED)
// or configure bricks if enumerate was raised externally (ENUMERATION_TYPE_AVAILABLE)
if (enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED
|| enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE) {
// configure master brick
if (deviceIdentifier == BrickMaster.DEVICE_IDENTIFIER) {
master = new BrickMaster(connectedUid, ipcon);
try {
master.setWifiPowerMode(BrickMaster.WIFI_POWER_MODE_LOW_POWER);
} catch (Exception e) {
e.printStackTrace();
}
}
// configure servo brick
if(deviceIdentifier == BrickServo.DEVICE_IDENTIFIER){
servo = new BrickServo(connectedUid, ipcon);
try {
// configure the drive servos (ESC)
servo.setAcceleration(Constants.servo0And1, 50000);
// configure the camera servos
servo.setVelocity(Constants.servo2And3, 20000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} | 6 |
public CheckReport1(File file) throws Exception {
this.file = file;
fileName = file.getName();
fileNameSections = fileName.split("\\.")[0].split("_");
if (fileNameSections.length == 4) {
// 记录期数
monthDate = fileNameSections[3];
} else if (fileNameSections.length == 3) {
// 记录期数
monthDate = fileNameSections[2];
}
} | 2 |
@Override
public SQLExceptionConverter buildSQLExceptionConverter() {
return new SQLExceptionConverter() {
private static final long serialVersionUID = 1L;
public JDBCException convert(SQLException sqlException,
String message, String sql) {
final int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException);
if (errorCode == SQLITE_CONSTRAINT) {
final String constraintName = EXTRACTER
.extractConstraintName(sqlException);
return new ConstraintViolationException(message,
sqlException, sql, constraintName);
} else if (errorCode == SQLITE_TOOBIG
|| errorCode == SQLITE_MISMATCH) {
return new DataException(message, sqlException, sql);
} else if (errorCode == SQLITE_BUSY
|| errorCode == SQLITE_LOCKED) {
return new LockAcquisitionException(message, sqlException,
sql);
} else if ((errorCode >= SQLITE_IOERR && errorCode <= SQLITE_PROTOCOL)
|| errorCode == SQLITE_NOTADB) {
return new JDBCConnectionException(message, sqlException,
sql);
}
return new GenericJDBCException(message, sqlException, sql);
}
};
} | 8 |
public void WGStatus(String channel, String sender) {
Integer setwords = 0;
String availablewords = new String();
HashMap<String, Integer> setusers = new HashMap<String, Integer>();
Game game;
game = games.get(getServer() + " " + channel);
if(game == null) {
sendMessageWrapper(channel, sender, MSG_NOGAME);
return;
}
// The users that have words left to set, are added to a seperate map which will be ordered later on
for(User user : game.users) {
setwords += user.wordobjs.size(); // Also calculate the total of set words
if(user.hasUnsetWords()) {
setusers.put(user.nick, user.unsetwordobjs.size());
}
}
// Java does not support sorting a map by it's value instead of it's keys, so here comes the solution
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(setusers.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
Integer diff = e2.getValue().compareTo(e1.getValue());
if(diff == 0) {
return e1.getKey().compareTo(e2.getKey());
}
else {
return diff;
}
}
});
// Now we create the string that will have the users ordered.
for(Map.Entry<String, Integer> setuser : list) {
availablewords += setuser.getKey() + " (" + setuser.getValue() + "), ";
}
sendMessage(channel, sender + ": " + setwords + " words have been set.");
if(!"".equals(availablewords)) {
sendMessageWrapper(channel, null, "The following users can set words: " + availablewords.substring(0, availablewords.length()-2));
}
} | 6 |
public Boolean isFinished() {
return isFinished;
} | 0 |
public Deck() {
init();
} | 0 |
public void startGame(List<Player> players, MenuPanel menu){
this.allGameFrames = new HashMap<Player,GameFrame>();
getContentPane().remove(menu);
setVisible(false);
dispose();
if(players == null || players.size() <2){
throw new IllegalArgumentException("Invalid players number. Can't start the game.");
}
try {
game = new Game(players);
for(int i=0; i< players.size();i++){
Player p = players.get(i);
GameFrame frame = new GameFrame(p.getName(),game,this);
frame.setLocation(i*200, 200);
allGameFrames.put(p, frame);
}
//bring the first player's window to the front
allGameFrames.get(players.get(0)).toFront();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
private double checkTransform() {
if(getLoc().nextTile != null) {
if(getLoc().getCoordinates().x - getLoc().nextTile.getCoordinates().x > 0)
return (-Math.PI/2);
else if(getLoc().getCoordinates().y - getLoc().nextTile.getCoordinates().y < 0)
return (Math.PI);
else if(getLoc().getCoordinates().x - getLoc().nextTile.getCoordinates().x < 0)
return (Math.PI/2);
else
return 0.;
}
else {
if(getLoc().getCoordinates().x - TilePanel.getInstance().tileMap.getBaseX() > 0)
return (-Math.PI/2);
else if(getLoc().getCoordinates().y - TilePanel.getInstance().tileMap.getBaseY() < 0)
return (Math.PI);
else if(getLoc().getCoordinates().x - TilePanel.getInstance().tileMap.getBaseX() < 0)
return (Math.PI/2);
else
return 0.;
}
} | 7 |
boolean resolve(final MethodWriter owner, final int position,
final byte[] data) {
boolean needUpdate = false;
this.status |= RESOLVED;
this.position = position;
int i = 0;
while (i < referenceCount) {
int source = srcAndRefPositions[i++];
int reference = srcAndRefPositions[i++];
int offset;
if (source >= 0) {
offset = position - source;
if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE) {
/*
* changes the opcode of the jump instruction, in order to
* be able to find it later (see resizeInstructions in
* MethodWriter). These temporary opcodes are similar to
* jump instruction opcodes, except that the 2 bytes offset
* is unsigned (and can therefore represent values from 0 to
* 65535, which is sufficient since the size of a method is
* limited to 65535 bytes).
*/
int opcode = data[reference - 1] & 0xFF;
if (opcode <= Opcodes.JSR) {
// changes IFEQ ... JSR to opcodes 202 to 217
data[reference - 1] = (byte) (opcode + 49);
} else {
// changes IFNULL and IFNONNULL to opcodes 218 and 219
data[reference - 1] = (byte) (opcode + 20);
}
needUpdate = true;
}
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
} else {
offset = position + source + 1;
data[reference++] = (byte) (offset >>> 24);
data[reference++] = (byte) (offset >>> 16);
data[reference++] = (byte) (offset >>> 8);
data[reference] = (byte) offset;
}
}
return needUpdate;
} | 5 |
DeclarationsNode declaration() {
// Declarations = [�CONST� ident �=� Expression �;� {ident �=�
// Expression �;�}]
// [�TYPE� ident �=� Type �;� {ident �=� Type �;�}]
// [�VAR� IdentList �:� Type �;� {IdentList �:� Type �;�}]
// {ProcedureDeclaration �;�}
ArrayList<ConstDeclarationNode> consts = new ArrayList<ConstDeclarationNode>();
List<TypeDeclarationNode> types = new ArrayList<TypeDeclarationNode>();
List<VarDeclarationNode> vars = new ArrayList<VarDeclarationNode>();
List<AbstractNode> procDeclarations = new ArrayList<AbstractNode>();
AbstractNode arg1;
AbstractNode arg2;
if (test(CONST)) {
read(CONST, "const");
arg1 = constIdent();
read(EQ, "=");
arg2 = expr();
read(SEMICOLON, ";");
consts.add(new ConstDeclarationNode(arg1,arg2));
while (test(IDENT)) {
arg1 = constIdent();
read(EQ, "=");
arg2 = expr();
read(SEMICOLON, ";");
consts.add(new ConstDeclarationNode(arg1,arg2));
}
} if (test(TYPE)) {
read(TYPE, "type");
arg1 = constIdent();
read(EQ, "=");
arg2 = type();
read(SEMICOLON, ";");
types.add(new TypeDeclarationNode(arg1,arg2));
while (test(IDENT)) {
arg1 = constIdent();
read(EQ, "=");
arg2 = type();
read(SEMICOLON, ";");
types.add(new TypeDeclarationNode(arg1,arg2));
}
} if (test(VAR)) {
read(VAR, "var");
arg1 = identList();
read(COLON, ":");
arg2 = type();
read(SEMICOLON, ";");
vars.add(new VarDeclarationNode(arg1,arg2));
while (test(IDENT)) {
arg1 = identList();
read(COLON, ":");
arg2 = type();
read(SEMICOLON, ";");
vars.add(new VarDeclarationNode(arg1,arg2));
}
}
while (test(PROCEDURE)) {
// procDeclarations.add(procedureDeclaration());
procDeclarations.add(procedure());
read(SEMICOLON, ";");
}
// failExpectation("const, type, var or procedure declaration");
return new DeclarationsNode(consts,types,vars,procDeclarations);
} | 7 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((tickID==Tickable.TICKID_MOB)
&&(statue!=null)
&&(affected instanceof MOB))
{
final MOB mob=(MOB)affected;
mob.makePeace(true);
if((statue.owner()!=null)&&(statue.owner()!=mob.location()))
{
Room room=null;
if(statue.owner() instanceof MOB)
room=((MOB)statue.owner()).location();
else
if(statue.owner() instanceof Room)
room=(Room)statue.owner();
if((room!=null)&&(room!=mob.location()))
room.bringMobHere(mob,false);
}
}
return super.tick(ticking,tickID);
} | 9 |
public boolean loadPanel(){
try{
/*fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();*/
BufferedReader br = new BufferedReader(new FileReader(new File("panels.xml")));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
String everything = sb.toString();
System.out.println(everything);
br.close();
xstream = new XStream(new DomDriver());
xstream.alias("panels", XMLPanelList.class);
xstream.alias("panel", XMLPanel.class);
xstream.alias("component", XMLComponent.class);
xstream.addImplicitArray(XMLPanelList.class, "xmlPanels", "panel");
xstream.addImplicitArray(XMLPanel.class, "xmlComps", "component");
xmlList = (XMLPanelList) xstream.fromXML(everything);
System.out.println(xstream.toXML(xmlList));
for(int i = 0; i < xmlList.xmlPanels.size(); i++){
//TODO:Seperate xmlObj creation into it's own button.
Vector<XMLObj> tempObjs = new Vector<XMLObj>();
xmlObjs.add(tempObjs);
XMLPanel p = xmlList.xmlPanels.get(i);
p.setup(this, i);
}
return true;
//}
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
return false;
}
catch(IOException e)
{
System.out.println("IO Exception");
e.printStackTrace();
return false;
}
catch(Exception e)
{
System.out.println("Exception");
e.getCause();
e.printStackTrace();
JOptionPane.showMessageDialog(this, "" + e.getMessage() , "Error!", JOptionPane.ERROR_MESSAGE);
return false;
}
// return false;
} | 5 |
public long getSeatType() {
return this._seatType;
} | 0 |
public static void main(String[] args) throws IOException {
File f = new File("src/IntegerArray.txt");
Scanner s = new Scanner(f);
int i = 0;
while(s.hasNext()){
array[i] = s.nextInt();
i++;
}
// BruteForceMethod();
int n = array.length;
Mergeforcemethod(0 , n);
} | 1 |
public static int countAdjecentTracks(World world, int x, int y, int z) {
int i = 0;
if (isTrackFuzzyAt(world, x, y, z - 1))
++i;
if (isTrackFuzzyAt(world, x, y, z + 1))
++i;
if (isTrackFuzzyAt(world, x - 1, y, z))
++i;
if (isTrackFuzzyAt(world, x + 1, y, z))
++i;
return i;
} | 4 |
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
String name = "" + dir;
if (!name.toLowerCase().contains("sopa")) {
return CONTINUE;
}
if (name.equalsIgnoreCase(ROOTDIR))
return CONTINUE;
String[] comps = name.split("/");
String tmp = comps[comps.length - 1].toLowerCase();
func.setForegroundCorpus(docs);
Sentence.resetSeen();
if (related.length == 0) {
p.addColumn(tmp, Printer.Type.BOTH);
} else {
p.addColumn(StringUtils.join(related, " "), Printer.Type.BOTH);
}
p.addColumn(docs.documents.size(), Printer.Type.BOTH);
p.addColumn(docs.numSentences(), Printer.Type.BOTH);
long totalWords = 0;
List<String> summary = new ArrayList<String>();
while (totalWords < 100) {
List<Sentence> sentences;
if (mode == ScoreFunctionFactory.Mode.KLSUM) {
((KLSumPlusScoreFunction) func).printTopTerms(10);
sentences = docs.getBestSnippet(func, 2, 5, 35, 90);
} else {
((SumBasicScoreFunction) func).printTopTerms(5);
sentences = docs.getBestSnippet(func, 1, 1, 0, 99999999);
}
if (sentences == null) break;
for (Sentence sentence : sentences) {
summary.add(sentence.sentence);
totalWords += sentence.terms.size();
sentence.setSeen();
func.update(sentence.terms);
System.out.println(sentence);
}
System.out.println("-----------------------------------------------------");
}
long executionTime = System.currentTimeMillis() - dirStart;
p.addColumn(totalWords, Printer.Type.BOTH);
p.addColumn(executionTime, Printer.Type.TIMING);
p.addColumn(StringUtils.join(summary, " "), Printer.Type.TEXT);
p.endRow();
return CONTINUE;
} | 7 |
public static int indexOf(Object[] arr, Object obj)
{
if (obj == null)
{
for (int c = 0; c < arr.length; c++)
{
if (arr[c] == null)
{
return c;
}
}
}
else
{
for (int c = 0; c < arr.length; c++)
{
if (obj.equals(arr[c]))
{
return c;
}
}
}
return -1;
} | 5 |
public void init(int nplayers, int[] pref)
{
this.nplayers = nplayers;
this.index = getIndex();
this.pref = pref;
length = pref.length;
transform = new int[length];
distribution = new int[length];
observedlist = new int[length];
distsum = new int[length];
choicelist = new int[nplayers + 1][length];
for(int i = 0; i < length; i++)
transform[length - pref[i]] = i;
/*
if(createLog)
{
try{
FileWriter fstream = new FileWriter("fruit/g5/log.txt", true);
outfile = new PrintWriter(fstream);
} catch (IOException e){ }
outfile.println("Players : " + Integer.toString(nplayers));
outfile.println("Index : " + Integer.toString(index));
outfile.println("Pref : " + Arrays.toString(pref));
outfile.println("Transform : " + Arrays.toString(transform));
outfile.flush();
} */
} | 1 |
private String formatKey(String key){
if(!caseSensitiveLookup){
key = key.toLowerCase();
}
if(asciiFoldingLookup){
key = StringUtils.stripAccents(key);
}
return key;
} | 2 |
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 |
public static long getLong(ByteBuffer in)
{
int a = in.get() & 0xFF;
int sign = (a & BYTE_SIGN_NEG);
long value = (a & 0x3fL);
int shift = -1;
while ((a & BYTE_MORE) != 0)
{
a = in.get() & 0xFF;
value |= (a & 0x7FL) << (shift += 7);
}
if (sign != 0)
{
value = -value;
}
return value;
} | 2 |
private static void makeTet6(SquareColor[][] tet) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (((i == 1 || i == 2) && j == 0) || ((i == 2 || i == 3) && j == 1)) {
tet[i][j] = SquareColor.RED;
} else tet[i][j] = null;
}
}
} | 8 |
public void setDim(int dim) throws ConnectException {
int maxDim = dim;
for (InputConnector ic : inputs) {
if (ic.isConnected()) {
if (dim != 0 && ic.getSource().getDim() != dim)
throw new ConnectException(ic.getSource(), dim);
if (maxDim < ic.getDim())
maxDim = ic.getDim();
}
}
if (output.getDim() != maxDim) {
output.setDim(maxDim);
for (InputConnector ic : output.getConnected()) {
ic.getParent().setDim(maxDim);
}
}
} | 7 |
static <T> Class<T> boxClass(Class<T> type) {
if (type == boolean.class) {
return (Class<T>) Boolean.class;
} else if (type == byte.class) {
return (Class<T>) Byte.class;
} else if (type == char.class) {
return (Class<T>) Character.class;
} else if (type == double.class) {
return (Class<T>) Double.class;
} else if (type == float.class) {
return (Class<T>) Float.class;
} else if (type == int.class) {
return (Class<T>) Integer.class;
} else if (type == long.class) {
return (Class<T>) Long.class;
} else if (type == short.class) {
return (Class<T>) Short.class;
} else {
return type;
}
} | 8 |
public boolean atBP()
{
double predictedTemp = getBPTemp();
if(temp <= predictedTemp+2 && temp >= predictedTemp-2)
return true;
return false;
} | 2 |
@Test
public void testPausedState() throws ProcessExecutionException, ProcessRollbackException {
IProcessComponent<?> comp = TestUtil.executionSuccessComponent(true);
// use reflection to set internal process state
TestUtil.setState(comp, ProcessState.PAUSED);
assertTrue(comp.getState() == ProcessState.PAUSED);
// test valid operations
TestUtil.setState(comp, ProcessState.PAUSED);
try {
comp.execute();
} catch (InvalidProcessStateException ex) {
fail("This operation should have been allowed.");
}
TestUtil.setState(comp, ProcessState.PAUSED);
try {
comp.rollback();
} catch (InvalidProcessStateException ex) {
fail("This operation should have been allowed.");
}
TestUtil.setState(comp, ProcessState.PAUSED);
try {
comp.resume();
} catch (InvalidProcessStateException ex) {
fail("This operation should have been allowed.");
}
// test invalid operations
TestUtil.setState(comp, ProcessState.PAUSED);
try {
comp.pause();
fail("InvalidProcessStateException should have been thrown.");
} catch (InvalidProcessStateException ex) {
// should happen
}
} | 5 |
public void printMessageContainer() {
System.out.println("MessageContainer for round " + round);
for (int i = 0; i < msgs.length; i++) {
if (msgs[i] == null) {
}
else if (i != (pid - 1)) {
System.out.println("Pid: " + msgs[i].pid + " Round: " + msgs[i].round);
msgs[i].printMessage();
}
}
} | 3 |
private static Vector<Integer> checkNeighbourhood(BufferedImage img, int x,
int y, int r) {
Vector<Integer> vect = new Vector<>();
for (int i = x - r; i <= x + r; i++) {
for (int j = y - r; j <= y + r; j++) {
if (i >= 0 && j >= 0 && i < img.getWidth()
&& j < img.getHeight()) {
if (img.getRGB(i, j) == -1 && !(i == x && j == y)) {
vect.addElement(i);
vect.addElement(j);
return vect;
}
}
}
}
return vect;
} | 9 |
public static HtmlRedirect parse(String content, VariableMap variables) {
HtmlRedirect ret = new HtmlRedirect();
int semi = content.indexOf(";");
if (semi == -1) { // Just a number, no URL, e.g., MRTG does this
ret.seconds = Integer.parseInt(content);
return ret;
}
Matcher match = META_REFRESH_CONTENT_REGEX_PATTERN.matcher(content);
if (match.matches()) {
try {
String secondsString = match.group(1);
ret.seconds = Integer.parseInt(secondsString);
String urlPattern = match.group(2);
if (variables != null) {
ret.url = Utilities.qualifyURL(variables, urlPattern);
} else {
ret.url = new URL(urlPattern);
}
return ret;
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Html Meta Refresh: bad URL: " + e);
}
} else {
throw new IllegalArgumentException("can't parse META refresh pattern " + content);
}
} | 4 |
public int lengthOfLongestSubstring(String s) {
int longest, mindex, n = s.length(), startindex = 0, endindex = 1, lastindex;
int[] map = new int[26];
char[] c = s.toCharArray();
if (n == 0) {
return 0;
} else {
longest = 1;
}
for (int m = 0; m < 26; m++) {
map[m] = -1;
}
while (startindex < n - 1) {
map[c[startindex] - 'a'] = startindex;
// System.out.println(startindex);
while (endindex < n) {
mindex = c[endindex] - 'a';
lastindex = map[mindex];
if (lastindex != -1) {
if (longest < endindex - startindex) {
longest = endindex - startindex;
// startindex = lastindex + 1;
}
for (int i = startindex; i <= lastindex; i++) {
map[c[i] - 'a'] = -1;
}
startindex = lastindex + 1;
map[mindex] = endindex;
endindex++;
} else {
map[c[endindex] - 'a'] = endindex;
endindex++;
}
}
if (endindex == n) {
return longest <= endindex - startindex ? endindex - startindex
: longest;
}
}
return longest;
} | 9 |
public RoomCell(int i, int numRows, int numCols, String config) {
super(i, numRows, numCols);
// Door handling.
doorDirection = DoorDirection.NONE;
roomInitial = config.charAt(0);
String roomSpec = config;
if(roomSpec.length() > 1) { // Then we have a door.
char door = roomSpec.charAt(1);
if(door == 'U') doorDirection = DoorDirection.UP;
else if(door == 'R') doorDirection = DoorDirection.RIGHT;
else if(door == 'D') doorDirection = DoorDirection.DOWN;
else if(door == 'L') doorDirection = DoorDirection.LEFT;
}
} | 5 |
public void calculateInitialScore(ROB_entry entry) {//calculate the score based on which heuristic we use for the score function
if(heuristic.type == HeuristicType.heuristic_LATENCY_SNR ) {//sum of sequence number and multiplier * latency
entry.score += latencyMultiplier * entry.theUop.exec_latency;
}
else if(heurType != 3){//the latency is not the base score
if(heuristic.type == HeuristicType.heuristic_LOADS_FIRST) {//give special score to loads (bigger than usual)
LOAD_SCORE = PRIORITY_LOADS_SCORE;
calculateBasicScore(entry);//on top of the basic score
}
else if(heuristic.type == HeuristicType.heuristic_LOAD_MISSED ){//special score to loads plus extra points if previous load missed
if (entry.theUop.type == UopType.insn_LOAD && lastLoadMissed) {
entry.score += MISSED_LOADS_SCORE;
}
calculateBasicScore(entry);//on top of the basic score
}
else if(heuristic.type == HeuristicType.heuristic_LOADS_FIRST_MISSED ){//special score to loads plus extra points if previous load missed
LOAD_SCORE = PRIORITY_LOADS_SCORE;//also assign the priority score
if (entry.theUop.type == UopType.insn_LOAD && lastLoadMissed) {
entry.score += MISSED_LOADS_SCORE;
}
calculateBasicScore(entry);//on top of the basic score
}
else //default score is the instruction type score
calculateBasicScore(entry);
}
else
calculateBasicScoreSpecial(entry);//for latenccy
} | 9 |
public void llenarTabla(JTable tabla)throws Exception{
ResultSetMetaData rsm;
DefaultTableModel dtm;
Menu menu = new Menu();
Statement consulta = menu.conexion();
ResultSet resultado = consulta.executeQuery("SELECT * FROM tblproductos ");
rsm=resultado.getMetaData();
if(resultado.next() == true){
ArrayList<Object[]> datos=new ArrayList<>();
while (resultado.next()) {
Object[] filas=new Object[rsm.getColumnCount()];
for (int i = 0; i < filas.length; i++) {
filas[i]=resultado.getObject(i+1);
}
datos.add(filas);
}
dtm=(DefaultTableModel)tabla.getModel();
for (int i = 0; i <datos.size(); i++) {
dtm.addRow(datos.get(i));
}
}
} | 4 |
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(TelaVenderProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaVenderProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaVenderProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaVenderProduto.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 TelaVenderProduto().setVisible(true);
}
});
} | 6 |
protected void requireConfigKey(final String key) {
if (config.getProperty(key) == null) {
throw new Error("missing required configuration key: '" + key + "'");
}
} | 1 |
public static <T extends Model> List<T> createSQLQuery(final Class<T> cls, final String sql, final String... params) {
final List<T> result = new ArrayList<T>();
synchronized (Lock) {
final DBOpenHelper helper = Beans.getBean(DBOpenHelper.class);
SQLiteDatabase database = helper.getReadableDatabase();
final Cursor cursor = database.rawQuery(sql, params);
while (cursor.moveToNext()) {
T model = Reflection.instantiate(cls);
model.transform(cursor);
result.add(model);
}
cursor.close();
database.close();
}
return result;
} | 1 |
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 ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Tela().setVisible(true);
}
});
} | 3 |
protected boolean disconnectInput(NeuralConnection i, int n) {
int loc = -1;
boolean removed = false;
do {
loc = -1;
for (int noa = 0; noa < m_numInputs; noa++) {
if (i == m_inputList[noa] && (n == -1 || n == m_inputNums[noa])) {
loc = noa;
break;
}
}
if (loc >= 0) {
for (int noa = loc+1; noa < m_numInputs; noa++) {
m_inputList[noa-1] = m_inputList[noa];
m_inputNums[noa-1] = m_inputNums[noa];
m_weights[noa] = m_weights[noa+1];
m_changeInWeights[noa] = m_changeInWeights[noa+1];
m_inputList[noa-1].changeOutputNum(m_inputNums[noa-1], noa-1);
}
m_numInputs--;
removed = true;
}
} while (n == -1 && loc != -1);
return removed;
} | 8 |
public void checkBattle() {
if (noBattle == false) {
if (stepscount >= rndwildmodify) {
lastBGM = currentBGM;
currentBGM.stop();
currentBGM = wildbattle;
currentBGM.start();
enemylvl = (byte) (first.getLevel() * (9 / 10));
if (r == 1) {
wildPokemon.create(198, enemylvl);
} else if (r == 2) {
wildPokemon.create(4, enemylvl); //Creates a wild Charmander
} else if (r == 3) {
wildPokemon.create(25, enemylvl);
} else if (r == 4) {
wildPokemon.create(100, enemylvl);
} else {
wildPokemon.create(101, enemylvl);
}
enemyparty[0] = wildPokemon;
enemyparty[1] = null;
enemyparty[2] = null;
enemyparty[3] = null;
enemyparty[4] = null;
enemyparty[5] = null;
wait(1);
inBattle = true;
PokedexIndex[wildPokemon.getNumber()][0]++;
Battle = new Battle(this, pokemonparty, enemyparty, null, true);
stepscount = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
} | 7 |
public void printSquares(List<Point2D> list, Point2D p1, Point2D p2, Game game)
{
Square origin = squareAt(p1);
Square goal = squareAt(p2);
System.out.println(" == MAP SIZE: "
+ (xArraySize*TILE_SIZE) + "x" + (yArraySize*TILE_SIZE) + " == ");
for (int y = 0; y < yArraySize ; y++) {
for (int x = 0; x < xArraySize ; x++) {
String printChar = "\033[31m" + "0" + "\033[0m";
if (sqGrid[x][y].isOccupiable())
printChar = "1";
if (sqGrid[x][y].getTerrainCost() > 0)
printChar = "\033[35m" + "1" + "\033[0m";
if (getTreasureSquares(game).contains(sqGrid[x][y]))
printChar = "\033[33m" + "T" + "\033[0m";
if (list.contains(sqGrid[x][y].getCenter()))
printChar = "\033[32m" + "X" + "\033[0m";
if (sqGrid[x][y].equals(origin))
printChar = "\033[34m" + "O" + "\033[0m";
if (sqGrid[x][y].equals(goal))
printChar = "\033[34m" + "G" + "\033[0m";
System.out.print(printChar);
}
System.out.println();
}
} | 8 |
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.