text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (args.length == 1 && args[0].equalsIgnoreCase("help")) {
showHelp(sender);
return true;
}
if (args.length == 1 && args[0].equalsIgnoreCase("list")) {
sender.sendMessage(StringUtils.join(Sound.values(), ", "));
return true;
}
if (args.length > 0) {
try {
parseCommand(sender, args);
} catch (SoundError e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
}
return true;
}
return false;
} | 6 |
@Override
public boolean singleStep() {
return false;
} | 0 |
public int compareTo(IdCount idCount) {
return (idCount.count > this.count ? 1 : (idCount.count != this.count ? -1 : (idCount.id < this.id ? -1 : 1)));
} | 3 |
protected String normalize(String s) {
StringBuilder str = new StringBuilder();
int len = (s != null) ? s.length() : 0;
for ( int i = 0; i < len; i++ ) {
char ch = s.charAt(i);
switch ( ch ) {
case '<': {
str.append("<");
break;
}
case '>': {
str.append(">");
break;
}
case '&': {
str.append("&");
break;
}
case '"': {
str.append(""");
break;
}
case '\r':
case '\n': {
if ( canonical ) {
str.append("&#");
str.append(Integer.toString(ch));
str.append(';');
break;
}
// else, default append char
}
default: {
str.append(ch);
}
}
}
return (str.toString());
} // normalize(String):String | 9 |
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("numtri.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("numtri.out")));
int n = Integer.parseInt(f.readLine());
int[][] triangle = new int[n][n];
int[][] path = new int[n][n];
for(int i=0; i<n; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
for(int j=0; j<i+1; j++) {
triangle[i][j] = Integer.parseInt(st.nextToken());
}
}
path[0][0] = triangle[0][0];
for(int i=1; i<n; i++) {
for(int j=0; j<i+1; j++) {
if(j==0) { path[i][j] = path[i-1][j] + triangle[i][j]; }
else if(j==i) { path[i][j] = path[i-1][j-1] + triangle[i][j]; }
else { path[i][j] = Math.max(path[i-1][j-1], path[i-1][j]) + triangle[i][j]; }
}
}
int max = 0;
for(int i=0; i<n; i++) {
if(path[n-1][i] > max) { max = path[n-1][i]; }
}
out.write(max + "\n");
out.close();
System.exit(0);
} | 8 |
public GameStates()
{
currentState = States.Start;
} | 0 |
private void init(OutputStream out, String encoding)
throws UnsupportedEncodingException, IOException {
internalOut = new OutputStreamWriter(out, encoding);
// Write the proper BOM if they specified a Unicode encoding.
// NOTE: Creating an OutputStreamWriter with encoding "UTF-16" DOES
// DOES write out the BOM; "UTF-16LE", "UTF-16BE", "UTF-32", "UTF-32LE"
// and "UTF-32BE" don't.
if ("UTF-8".equals(encoding)) {
if (getWriteUtf8BOM()) {
out.write(UTF8_BOM, 0, UTF8_BOM.length);
}
}
else if ("UTF-16LE".equals(encoding)) {
out.write(UTF16LE_BOM, 0, UTF16LE_BOM.length);
}
else if (/*"UTF-16".equals(encoding) || */"UTF-16BE".equals(encoding)) {
out.write(UTF16BE_BOM, 0, UTF16BE_BOM.length);
}
else if ("UTF-32LE".equals(encoding)) {
out.write(UTF32LE_BOM, 0, UTF32LE_BOM.length);
}
else if ("UTF-32".equals(encoding) || "UTF-32BE".equals(encoding)) {
out.write(UTF32BE_BOM, 0, UTF32BE_BOM.length);
}
} | 7 |
private boolean handleNoSync() {
try {
if (readByte() == 0) {
return false;
}
} catch (IOException e) {
stats.incrementStat(statPrefix + STAT_CONNECTION_FAIL);
log.info("RxThread: exception caught while trying to read "
+ "from server", e);
currentState = RxThreadStates.RESET;
return true;
}
if (buffer.position() > 0 && buffer.get(buffer.position() - 1)
== LegacyOCPMessage.OCP_EOM_FIRST_BYTE
&& buffer.hasRemaining()) {
// Found the first EOM byte, and have enough space for the
// second EOM byte.
currentState = RxThreadStates.SECOND_EOM_BYTE;
}
return true;
} | 5 |
@Before
public void setUp() {
this.p = new Piste(5, 5);
this.e = new Este(0, 0, 10, 10);
this.t = new Taso();
} | 0 |
public LinkedList<Instance> getInstances() {
return instances;
} | 0 |
@Override
public String toString()
{
if (size() == 0) return "[]";
String string = "[";
boolean first = false;
for (int tile : this)
{
string += (first ? ", " : "") + tile;
first = true;
}
string += "]";
return string;
} | 3 |
public static String assertRationalRotationMatrix(double[][] matrix,
int decimalPlaces) {
String rational = assertRationalMatrix(matrix);
if (rational != null) {
return rational;
}
if (matrix.length != 3) {
return "The rotation matrix does not comprise three rows:"
+ NEWLINE + representMatrix(matrix, decimalPlaces);
}
if (matrix[0].length != 3) {
return "The rotation matrix does not comprise three columns:"
+ NEWLINE + representMatrix(matrix, decimalPlaces);
}
rational = assertRationalUnitVector(matrix[0], decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the first row: "
+ rational;
}
rational = assertRationalUnitVector(matrix[1], decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the second row: "
+ rational;
}
rational = assertRationalUnitVector(matrix[2], decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the third row: "
+ rational;
}
rational = assertRationalUnitVector(new double[] { matrix[0][0],
matrix[1][0], matrix[2][0] }, decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the first column: "
+ rational;
}
rational = assertRationalUnitVector(new double[] { matrix[0][1],
matrix[1][1], matrix[2][1] }, decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the second column: "
+ rational;
}
rational = assertRationalUnitVector(new double[] { matrix[0][2],
matrix[1][2], matrix[2][2] }, decimalPlaces);
if (rational != null) {
return "The rotation matrix does not comprise a rational unit vector along the third column: "
+ rational;
}
return null;
} | 9 |
private synchronized static void deleteTaskByID(String id, String mail) {
try {
XStream xstream = new XStream(new DomDriver());
File remFile = new File((String) Server.prop.get("taskFilePath"));
Task[] allTask = (Task[]) xstream.fromXML(remFile);
List<Task> retList = new ArrayList<Task>(Arrays.asList(allTask));
for (int i = 0; i < allTask.length; i++) {
if (allTask[i].getId().equals(id) && allTask[i].getCreator().equals(mail)) {
retList.remove(i);
}
}
FileOutputStream fos = new FileOutputStream(remFile);
xstream.toXML(retList.toArray(new Task[0]), fos);
fos.close();
} catch (Exception e) {
}
} | 4 |
private Constructor<?> getXMLConstructor(Class<? extends OVComponent> c) {
for (Constructor<?> con : c.getConstructors()) {
if (con.getGenericParameterTypes().length == 2) {
if (con.getGenericParameterTypes()[0] == Element.class
&& con.getGenericParameterTypes()[1] == OVContainer.class) {
return con;
}
}
}
return null;
} | 7 |
public void beforePhase(PhaseEvent event)
{
FacesContext facesContext = event.getFacesContext();
HttpServletResponse response = (HttpServletResponse) facesContext
.getExternalContext().getResponse();
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
// Stronger according to blog comment below that references HTTP spec
response.addHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "must-revalidate");
// some date in the past
response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT");
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormularioEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormularioEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormularioEmpleado.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormularioEmpleado.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 FormularioEmpleado().setVisible(true);
}
});
} | 6 |
public MediaWiki endMove(final MediaWiki.EditToken moveToken, final String newFullName, final String reason, final boolean suppressRedirect, final boolean moveTalk, final boolean moveSubpages) throws IOException, MediaWiki.MediaWikiException {
final Map<String, String> getParams = paramValuesToMap("action", "move", "format", "xml");
final Map<String, String> postParams = paramValuesToMap("from", moveToken.getFullPageName(), "to", newFullName, "token", moveToken.getTokenText(), "starttimestamp", iso8601TimestampParser.format(moveToken.getStartTime()), "reason", reason);
if (suppressRedirect) {
postParams.put("noredirect", "true");
}
if (moveTalk) {
postParams.put("movetalk", "true");
}
if (moveSubpages) {
postParams.put("movesubpages", "true");
}
if (moveToken.getLastRevisionTime() != null) {
postParams.put("basetimestamp", iso8601TimestampParser.format(moveToken.getLastRevisionTime()));
}
final String url = createApiGetUrl(getParams);
networkLock.lock();
try {
final InputStream in = post(url, postParams);
final Document xml = parse(in);
checkError(xml);
checkError(xml, "talkmove-error-code", "talkmove-error-info");
final NodeList moveTags = xml.getElementsByTagName("move");
if (moveTags.getLength() > 0)
return this;
else
throw new MediaWiki.ResponseFormatException("expected <move> tag not present");
} finally {
networkLock.unlock();
}
} | 5 |
@Override
public void addAllInner(Set<? extends IObject> interfaces,
Set<? extends IObject> classes) {
try {
long biggestId = Integer.MIN_VALUE;
// Add the objects
if (interfaces != null) {
for (IObject interf : interfaces) {
tree.addObject(interf);
// IdManager part of UI, will not show up in design
IdManager.getInstance().loadInfo(interf.getId(), interf.getPackage(), interf.getName());
if (interf.getId() > biggestId) {
biggestId = interf.getId();
}
}
}
if (classes != null) {
for (IObject clazz : classes) {
tree.addObject(clazz);
// IdManager part of UI, will not show up in design
IdManager.getInstance().loadInfo(clazz.getId(), clazz.getPackage(), clazz.getName());
if (clazz.getId() > biggestId) {
biggestId = clazz.getId();
}
}
}
// IdManager part of UI, will not show up in design
IdManager.getInstance().setNextId(biggestId + 1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
} | 9 |
@Override
public void removeSubProcess(ProductType productType, SubProcess subProcess) {
productType.removeSubProcess(subProcess);
tx.begin();
for (Stock s : subProcess.getStocks()) {
subProcess.removeStock(s);
}
TypedQuery<State> q = em.createQuery(
"SELECT s FROM states s WHERE s.subProcess=:sp", State.class);
q.setParameter("sp", subProcess);
List<State> states = q.getResultList();
for (State state : states) {
em.remove(state);
}
em.merge(subProcess);
em.remove(subProcess);
tx.commit();
} | 2 |
@Override
public int read() throws IOException {
int c;
// If we have a block in here, start feeding that out.
if ((c = outBuffer.read()) != -1)
return c;
// Otherwise, time to make a block.
while (inBuffer.size() < ConCh.Delta(source.length, codeabet.length, ConCh.BLOCK_LIMIT)
&& (c = input.read()) != -1) {
int b = 0xFF & c;
// Ignore bytes not in the code alphabet.
if (ConCh.indexOf(codeabet, (byte) b) != -1)
inBuffer.write(b);
}
byte[] block = inBuffer.toByteArray();
inBuffer.reset();
// We tried to get a block, but we failed.
if (block.length == 0)
return -1;
// Or we succeeded.
outBuffer = new ByteArrayInputStream(ConCh.decode(source, codeabet, block));
return outBuffer.read();
} | 5 |
private BeanstreamResponse process(HttpUriRequest http,
ResponseHandler<BeanstreamResponse> responseHandler) throws IOException {
HttpClient httpclient;
if (customHttpClient != null)
httpclient = customHttpClient;
else
httpclient = HttpClients.createDefault();
// Remove newlines from base64 since they can bork the header.
// Some base64 encoders will append a newline to the end
String auth = Base64.encode((merchantId + ":" + apiPasscode).trim().getBytes());
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", "Passcode " + auth);
BeanstreamResponse responseBody = httpclient.execute(http, responseHandler);
return responseBody;
} | 1 |
@Override
public void setReceiveException(IReceiveException exception) {
receiveException = exception;
} | 0 |
public void copyFileToZip(File src, String dest) throws IOException {
if (!src.exists()) return;
createDirectory(dest);
for (File f : src.listFiles()) {
String target = dest + f.getName();
if (f.isDirectory()) copyFileToZip(f, target + "/");
if (f.isFile()) createFile(target, f);
}
} | 4 |
public int[][] left(int grid[][]) {
score = 0;
for (int yIndex = 0; yIndex < 4; yIndex++) {
for (int xIndex = 3; xIndex > 0; xIndex--) {
if (grid[yIndex][xIndex - 1] == 0) {
for (int a = xIndex - 1; a < 3; a++) {
grid[yIndex][a] = grid[yIndex][a + 1];
}
grid[yIndex][3] = 0;
}
}
for (int xIndex = 0; xIndex < 3; xIndex++) {
if (grid[yIndex][xIndex] == grid[yIndex][xIndex + 1]) {
score += grid[yIndex][xIndex];
grid[yIndex][xIndex + 1] += grid[yIndex][xIndex];
grid[yIndex][xIndex] = 0;
}
}
for (int xIndex = 3; xIndex > 0; xIndex--) {
if (grid[yIndex][xIndex - 1] == 0) {
for (int a = xIndex - 1; a < 3; a++) {
grid[yIndex][a] = grid[yIndex][a + 1];
}
grid[yIndex][3] = 0;
}
}
}
return grid;
} | 9 |
public boolean checkTurn(ConnectionToClient player) {
if (player == playerX && currentMove == Move.X) {
return true;
} else if (player == playerX && currentMove == Move.O) {
return false;
} else if (player == playerO && currentMove == Move.X) {
return false;
} else if (player == playerO && currentMove == Move.O) {
return true;
}
return true;
} | 8 |
public int minDepth(TreeNode root) {
if(root == null) return 0;
LinkedList<TreeNode> que = new LinkedList<TreeNode>();
que.offer(root);
que.offer(null);
int res = Integer.MAX_VALUE;
int dep = 0;
while(!que.isEmpty()){
TreeNode n = que.poll();
if(n == null){
++dep;
if(que.isEmpty()) break;
que.offer(n);
}else{
if(n.left == null && n.right == null){
res = Math.min(res, dep+1);
}
if(n.left != null) que.offer(n.left);
if(n.right != null) que.offer(n.right);
}
}
return res;
} | 8 |
public int indexOf(T theElement)
{
for(int i = 0; i < size; i++)
if(element[i].equals(theElement))
return i;
return -1;
} | 2 |
public static void UpperGenre(){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
conn.setAutoCommit(false);
PreparedStatement stmnt = conn.prepareStatement("UPDATE Media set genre = CONCAT( UPPER( LEFT( genre, 1 ) ) , SUBSTRING( genre, 2 ))");
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
} | 4 |
protected LegatoTokenResponse tokenizeCard(HttpsConnector connector, String cardNum, String cvd, int expiryMonth, int expiryYear) {
LegatoTokenRequest tokenRequest = new LegatoTokenRequest();
tokenRequest.number = cardNum;
tokenRequest.expiryMonth = expiryMonth;
tokenRequest.expiryYear = expiryYear;
tokenRequest.cvd = cvd;
String url = "https://www.beanstream.com/scripts/tokenization/tokens";
String output = "";
try {
output = connector.ProcessTransaction(HttpMethod.post, url,
tokenRequest);
} catch (BeanstreamApiException ex) {
Logger.getLogger(SampleTransactions.class.getName()).log(
Level.SEVERE, null, ex);
}
Gson gson = new Gson();
LegatoTokenResponse tokenResponse = gson.fromJson(output,
LegatoTokenResponse.class);
System.out.println("token: " + output);
return tokenResponse;
} | 1 |
double getResult() {
//trim redundant spaces
String nums = getNumbers().trim();
//split <Numbers> string in tokens
StringTokenizer st = new StringTokenizer(nums, " ");
//add tokens to List
ArrayList<Double> al = new ArrayList<Double>();
while(st.hasMoreTokens())
try {
al.add(Double.parseDouble(st.nextToken()));
}catch(NumberFormatException nfe) {
System.out.println("\nInvalid number format in <Numbers>.");
}
// Determine type of operation and compute
if(getName().equalsIgnoreCase("sum")) {
double sum = 0;
for(int i = 0; i < al.size(); i++) {
sum += al.get(i);
}
result = sum;
}
else if(getName().equalsIgnoreCase("avg")) {
double sum = 0;
double avg;
for(int i = 0; i < al.size(); i++) {
sum += al.get(i);
}
avg = sum / al.size();
result = avg;
}
else if(getName().equalsIgnoreCase("min")) {
double min = Collections.min(al);
result = min;
}
return result;
} | 7 |
public static void updateBoard(int nr) {
Game.updateMap(nr);
for (int i = 0; i < BSIZE; i++) {
for (int j = 0; j < BSIZE; j++) {
MapObject temp = Game.getMapObject(i, j);
if (temp instanceof Worm) {
Worm worm = (Worm) Game.getMapObject(i, j);
Direction wormDir = worm.getDirection();
if (wormDir == null) {
board[i][j] = "W:" + worm.getWeight();// + ":";
} else {
board[i][j] = "W:" + worm.getWeight();// + ":" + wormDir.toString();
}
}
if (temp instanceof Bacteria) {
board[i][j] = "(B)";
}
if (temp == null) {
board[i][j] = EMPTY;
}
}
}
panel.repaint();
} | 6 |
static public void decodeAllFilesInDirectory(String src)
{
File folder = new File(src);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
decodeFile(file.getPath());
}
}
} | 2 |
public void update(){
if(add.size() > 0){
for(Entity ent : add){
entity.add(ent);
}
add.clear();
}
if(remove.size() > 0){
for(Entity ent : remove){
entity.remove(ent);
}
remove.clear();
}
for(Entity ent : entity){
ent.update();
}
} | 5 |
private void setMapBoundries() {
if (!(intersections.isEmpty())) {
boolean first = true;
for (Intersection i : intersections) {
if (first) {
north = i.getLocation().y;
south = i.getLocation().y;
west = i.getLocation().x;
east = i.getLocation().x;
first = false;
} else {
if (north < i.getLocation().y) {
north = i.getLocation().y;
}
if (south > i.getLocation().y) {
south = i.getLocation().y;
}
if (west > i.getLocation().x) {
west = i.getLocation().x;
}
if (east < i.getLocation().x) {
east = i.getLocation().x;
}
}
}
this.origin = new Location(west, north);
this.scale = 800 / (east - west);
}
} | 7 |
public Card[] pickCards(SelectCardOptions sco, Card[] allcards) {
GameQuery p = new GameQuery(QueryType.GETCARD, QueryType.CARD)
.setObject(sco);
p = query(p);
if (p == null)
return null;
if (p.t != QueryType.CARD)
return null;
if (p.o instanceof Card[] || p.o instanceof String[]) {
String[] selected;
if (p.o instanceof Card[]) {
ArrayList<String> a = new ArrayList<String>();
for (Card c : (Card[]) p.o)
a.add(c.getName());
selected = a.toArray(new String[0]);
} else
selected = (String[])p.o;
ArrayList<Card> ret = new ArrayList<Card>();
ArrayList<Card> all = new ArrayList<Card>(Arrays.asList(allcards));
for (int i = 0; i < selected.length; i++) {
for (int j = 0; j < all.size(); j++) {
if (all.get(j).equals(selected[i])) {
ret.add(all.get(j));
all.remove(j);
break;
}
}
}
return ret.toArray(new Card[0]);
}
return null;
} | 9 |
public Dimension getPreferredSize() {
final String text = getText();
boolean isEmpty = text.length() == 0
|| (HtmlTools.isHtmlNode(text) && text.indexOf("<img") < 0 && HtmlTools
.htmlToPlain(text).length() == 0);
if (isEmpty) {
setText("!");
}
Dimension prefSize = super.getPreferredSize();
final float zoom = getNodeView().getMap().getZoom();
if (zoom != 1F) {
// TODO: Why 0.99? fc, 23.4.2011
prefSize.width = (int) (0.99 + prefSize.width * zoom);
prefSize.height = (int) (0.99 + prefSize.height * zoom);
}
if (isCurrentlyPrinting() && MapView.NEED_PREF_SIZE_BUG_FIX) {
prefSize.width += getNodeView().getMap().getZoomed(10);
}
prefSize.width = Math.max(
getNodeView().getMap().getZoomed(MIN_HOR_NODE_SIZE),
prefSize.width);
if (isEmpty) {
setText("");
}
prefSize.width += getNodeView().getMap().getZoomed(12);
prefSize.height += getNodeView().getMap().getZoomed(4);
// /*@@@@@@@@@@@@@@*/
// prefSize.width = 150;
// prefSize.height = 20;
return prefSize;
} | 8 |
public boolean getContainer(Container container, InlandShip ship,float tpf, int location) {
switch (getContainerInt) {
case 0:
if ((int) this.getLocalTranslation().x < location) {
this.move(tpf * 8 / 3f, 0, 0);
} else if ((int) this.getLocalTranslation().x > location) {
this.move(-tpf * 8 / 3f, 0, 0);
}
if ((int) this.getLocalTranslation().x == location) {
getContainerInt++;
}
break;
case 1:
if (timer.counter(240, tpf)) {
getContainerInt++;
this.attachChild(container);
container.setLocalTranslation(7, 13.5f, 3);
container.rotate(0, FastMath.PI / 2, 0);
}
break;
case 2:
if ((int) container.getLocalTranslation().x > -10f) {
container.move(-5f / 3f * tpf, 0, 0);
} else if (timer.counter(240, tpf)) {
getContainerInt++;
this.detachChild(container);
ship.attachContainer(container);
return true;
}
return false;
}
return false;
} | 9 |
public Connection getConnection(){
if(sqlite){
if(!this.getFile().exists()){
plugin.getLogger().info("CRITICAL: Database does not exist");
try {
this.getFile().createNewFile();
Class.forName("org.sqlite.JDBC");
Connection dbCon = DriverManager.getConnection("jdbc:sqlite:" + this.getFile());
return dbCon;
}
catch (IOException e) {
e.printStackTrace();
plugin.getLogger().info("Could not create file " + this.getFile().toString());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
plugin.getLogger().info("You need the SQLite JBDC library. Put it in MinecraftServer/lib folder.");
} catch (SQLException e) {
e.printStackTrace();
plugin.getLogger().info("SQLite exception on initialize " + e);
}
}
try{
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection("jdbc:sqlite:" + this.getFile());
}
catch(SQLException e){
e.printStackTrace();
plugin.getLogger().info("SQLite exception on initialize.");
}
catch(ClassNotFoundException e){
e.printStackTrace();
plugin.getLogger().info("SQLite library not found, was it removed?");
}
}
else{
try{
return DriverManager.getConnection("jdbc:mysql://"+this.host+":"+this.port+"/"+this.dbName, user, pass);
}
catch(SQLException e){
e.printStackTrace();
return null;
}
}
return null;
} | 8 |
public ListNode partition(ListNode head, int x) {
ListNode dummyBack = new ListNode(0);
ListNode dummyFront = new ListNode(0);
dummyBack.next = head;
ListNode p1 = dummyBack, p2 = dummyFront;
// 1. go from dummy
// 2. use p1.next != null
// can avoid using pre-pointer
while(p1.next != null){
if(p1.next.val < x){
p2.next = p1.next;
p2 = p2.next;
p1.next = p1.next.next;
}else{
p1 = p1.next;
}
}
p2.next = dummyBack.next;
return dummyFront.next;
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final RestaurantServer other = (RestaurantServer) obj;
if (this.customersOrder != other.customersOrder && (this.customersOrder == null || !this.customersOrder.equals(other.customersOrder))) {
return false;
}
return true;
} | 5 |
private boolean checkAllRows() {
boolean changed = false;
int numberChanged = 0;
//goes down so that rows aren't skipped
for(int z = height - SAFE_HEIGHT; z >= 0; z--) {
if(checkSingleRow(z)) {
changed = true;
numberChanged++;
for(int i = z + 1; i < height; i++) {
// z + 1 so that the deleted plane is overwritten first
lowerPlane(i);
}
}
}
score += 100 * numberChanged * numberChanged;
return changed;
} | 3 |
public String getType(){
if(type==SSHDSS){ return Util.byte2str(sshdss); }
if(type==SSHRSA){ return Util.byte2str(sshrsa);}
return "UNKNOWN";
} | 2 |
public static void main(final String[] args) throws Exception {
if (args.length < 2) {
showUsage();
return;
}
int inRepresentation = getRepresentation(args[0]);
int outRepresentation = getRepresentation(args[1]);
InputStream is = System.in;
OutputStream os = new BufferedOutputStream(System.out);
Source xslt = null;
// boolean computeMax = true;
for (int i = 2; i < args.length; i++) {
if ("-in".equals(args[i])) {
is = new FileInputStream(args[++i]);
} else if ("-out".equals(args[i])) {
os = new BufferedOutputStream(new FileOutputStream(args[++i]));
} else if ("-xslt".equals(args[i])) {
xslt = new StreamSource(new FileInputStream(args[++i]));
// } else if( "-computemax".equals( args[ i].toLowerCase())) {
// computeMax = true;
} else {
showUsage();
return;
}
}
if (inRepresentation == 0 || outRepresentation == 0) {
showUsage();
return;
}
Processor m = new Processor(inRepresentation,
outRepresentation,
is,
os,
xslt);
long l1 = System.currentTimeMillis();
int n = m.process();
long l2 = System.currentTimeMillis();
System.err.println(n);
System.err.println((l2 - l1) + "ms " + 1000f * n / (l2 - l1)
+ " resources/sec");
} | 7 |
public Essay getModel(int Question_ID) {
Essay essayQuestion = new Essay();
try {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT QuestionID,QuestionType,noofwords, instructions");
sql.append(" FROM `Essay`");
sql.append(" where QuestionID=" + Question_ID);
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
while (rs.next()) {
essayQuestion.setQtype_ID(rs.getInt("QuestionType"));
essayQuestion.setQuestion_ID(rs.getInt("QuestionID"));
essayQuestion.setNoofwords(rs.getInt("noofwords"));
essayQuestion.setInstructions(rs.getString("instructions"));
}
} catch (SQLException ex) {
Logger.getLogger(Essay.class.getName()).log(Level.SEVERE, null, ex);
}
return essayQuestion;
} | 2 |
public void alta(){
String dni,cuenta;
int titulares=0,salir=0;
cuenta=calcularCuenta();//Llamo al método para que me devuelva un número de cuenta a usar
do{//Do while para incluir varios titulares
do{//do while para pedir un DNI correcto de 9 caracteres. No optimizado para la letra
dni=Pantalla.pideCadena("Introduce el DNI del titular: " );
if (dni.length()!=9){
Pantalla.muestra("El DNI tiene que tener 8 dígitos y una letra: ");
}
}while(dni.length()!=9);//fin 2 do while
int pos=buscaDNI(dni);//Llamo a método buscaDNI
CCliente cl;
if (pos==-1){//Si busca DNI me devuelve -1 (no existe)
cl=new CCliente(dni,cuenta);//Creo objeto con un constructor que me devolverá el nombre
}else{//Si existe me devuelve pos
String nombre=leer(pos).getNombre(); //Consigo el nombre con el método leer que me ha devuelto un objeto
cl=new CCliente(dni, nombre, cuenta);//Creo el objeto, con el constructor en el que ya le paso todos los datos.
}
if (escribirCliente (nregs,cl)){//Escribo cliente y si va todo bien, sumo 1 registro más (el que se ha creado).
nregs++;
}
if (titulares<4){//if para añadir hasta 4 titulares
salir=Pantalla.pideInt ("\n¿La cuenta tiene más titulares?.\n SI-1 \tNO-0 ");
if (salir!=0){
titulares++;
}
}
}while ((titulares<4) && (salir!=0)) ;//fin primer do while
creaCuenta(cuenta);//Llamo a método crear cuenta, pasándole como parámetro el nº de cuenta que hemos creado.
Pantalla.muestra("Enhorabuena, ya tenemos un trocito de su alma con el nº "+cuenta);
} | 8 |
public void gestionHabitaciones(int reservaEco, int reservaVip) {
while (true) {
int parada = (int) ((Math.random() * 10000 + 1000));
try {
Thread.sleep(parada);
} catch (InterruptedException ex) {
Logger.getLogger(Vip.class.getName()).log(Level.SEVERE, null, ex);
}
synchronized (ha) {
while (!ha.disponibleEco(reservaEco) || !ha.disponibleVip(reservaVip)) {
try {
System.out.println(Thread.currentThread().getName() + " Se pone en cola ");
ha.wait();
System.out.println(Thread.currentThread().getName() + " sale de cola");
//Thread.sleep((int) ((Math.random()*10000+1000)));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
checkIn(reservaVip, reservaEco);
}
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Economico.class.getName()).log(Level.SEVERE, null, ex);
}
synchronized (ha) {
checkOut(reservaVip, reservaEco);
}
}
} | 6 |
public Class<? extends Annotation> getScope() {
return metadata.getScope();
} | 1 |
public void setSaleId(int saleId) {
this.saleId = saleId;
} | 0 |
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
switch (action) {
case "Exit":
String exitMessage = "Are you sure you wish to exit?";
int doExit = JOptionPane.showConfirmDialog(null, exitMessage, action, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
// Close the program.
if (doExit == JOptionPane.YES_OPTION)
System.exit(0);
break;
case "Help":
String helpMessage = "Double-click on the SwiftSnap icon located in your notification area (where the clock is on the bottom-right)"
+ " to take a picture of the current screen.\n\nTo change where pictures are stored and to toggle"
+ " cropping, right-click the SwiftSnap icon and find the settings option.";
JOptionPane.showMessageDialog(null, helpMessage, action, JOptionPane.INFORMATION_MESSAGE);
break;
case "Settings":
Configuration config = Configuration.loadConfiguration();
String dialogMsg1 = "Enter a directory to save your screenshots to:";
String dialogMsg2 = "Allow cropping option?";
// Get the file path from the user.
// Make sure the path can be written to and is valid.
String path;
File file;
do {
path = JOptionPane.showInputDialog(null, dialogMsg1, config.getProperty("savePath"));
if (path == null) {
path = config.getProperty("savePath");
break;
}
file = new File(path);
// Incase the loop re-iterates, send a message.
dialogMsg1 = "The directory is invalid or doesn't exist!\n\nEnter a directory to save your screenshots to:";
} while(!file.canRead() || !file.isDirectory());
// Ask the user if they want the cropping feature.
String allowCrop = "false";
int doCrop = JOptionPane.showConfirmDialog(null, dialogMsg2, "SwiftSnap", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if (doCrop == JOptionPane.YES_OPTION) {
allowCrop = "true";
}
// Set all the configuration settings filled in by the user.
config.setProperty("savePath", path);
config.setProperty("enableAutoCropping", allowCrop);
config.saveConfiguration();
JOptionPane.showMessageDialog(null, "Settings saved!");
break;
}
} | 8 |
public String attempt(String gameid, String combi) {
Game game = games.getGame(gameid);
List<Token<Colors>> colors = getColors(combi);
Combination<Colors> combination = new Combination<Colors>(colors);
Answer answer = game.giveAnswer(combination);
return answer.toJson();
} | 0 |
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 2; i <= 9; i += 4) {
for (int j = 1; j <= 9; j++) {
for (int k = 0; k < 4; k++) {
System.out.print((i + k) + " * " + j + " = " + (i + k) * j + "\t");
}
System.out.println();
}
System.out.println();
}
} | 3 |
public void exception(){
long result = a.getTimeLeftInMillis();
if(result <= 0){
System.out.println("The bid for " + a.getName() + " has expired.");
}
} | 1 |
public double getActionPower(Instance vision, String powerType) throws Exception {
// Make the decision by model
if (powerType == StringUtil.DASH_POWER && dashPowerCls != null) {
return dashPowerCls.classifyInstance(vision);
} else if (powerType == StringUtil.KICK_POWER && kickPowerCls != null) {
return kickPowerCls.classifyInstance(vision);
} else {
System.err.println("There is no power parameter for this action. Use default value 0.");
return 0;
}
} | 4 |
public Point3 minus(Point3 p){
return new Point3(this.x - p.x, this.y - p.y, this.z - p.z);
} | 0 |
private void removeEntity(int x, int y, Entity e) {
if (x < 0 || y < 0 || x >= w || y >= h) return;
entitiesInTiles[x + y * w].remove(e);
} | 4 |
private Chromo<T> rouletteSelection(){
Chromo<T> selected = null;
double totalFitness = individuals.stream()
.mapToDouble(chromo -> chromo.getFitness()).sum();
double slice = rand.nextDouble() * totalFitness;
double fitnessSoFar = 0;
if (totalFitness == 0){
selected = getRandomChromoFromPopulation();
}
for (int i=0; i<size; i++){
fitnessSoFar += individuals.get(i).getFitness();
if (fitnessSoFar >= slice){
selected = new Chromo<>(individuals.get(i).getGenes(), individuals.get(i).getFitness());
break;
}
}
return selected;
} | 3 |
public DataModel(String path) {
this.classSet = new TreeSet<>();
this.classValuesMap = new HashMap<>();
try(BufferedReader br = new BufferedReader(new InputStreamReader(
new BufferedInputStream(new FileInputStream(new File(path)))))) {
String line = br.readLine();
String[] parts = line.split("\\s+");
int rows = Integer.parseInt(parts[0]);
int row = 0;
this.entries = rows;
this.classes = new String[rows];
this.nClasses = Integer.parseInt(parts[1]);
while(true) {
line = br.readLine();
if(line == null) {
break;
}
line = line.trim();
if(line.isEmpty()) {
continue;
}
parts = line.split("\\s+");
if(this.data == null) {
this.data = new Matrix(rows, parts.length - 1);
}
this.nVariables = parts.length - 1;
String cl = parts[this.nVariables];
for(int i = 0; i < parts.length; i++) {
if(i != parts.length - 1) {
this.data.set(row, i, Double.parseDouble(parts[i]));
} else {
classes[row] = cl;
classSet.add(cl);
}
}
List<Integer> indexesList = classValuesMap.get(cl);
if(indexesList == null) {
indexesList = new ArrayList<>();
classValuesMap.put(cl, indexesList);
}
indexesList.add(row);
row++;
}
} catch(IOException e) {
e.printStackTrace();
}
} | 8 |
public MiniXMLToken getTokenTagName(MiniXMLToken oMiniXMLToken, int type) {
bInsideTag = true;
int token = getNext();
oMiniXMLToken.setValue(token);
if (isFirstNameChar(token)) {
oMiniXMLToken.setType(type);
while (true) {
if (!isNameChar(testNext()))
return oMiniXMLToken;
oMiniXMLToken.append(getNext());
}
}
return oMiniXMLToken;
} | 3 |
public List<String> getSubNodes(String node)
{
List<String> ret=new ArrayList<String>();
try
{
for(Object o:fconfig.getConfigurationSection(node).getKeys(false))
{
ret.add((String) o);
}
}
catch(Exception e){}
return ret;
} | 2 |
@Override
public HashMap<String,String> getAvailableCommands()
{
HashMap<String,String> toRet = new HashMap<String,String>();
ArrayList<Class<?>> availableCommands = (ArrayList<Class<?>>) ReflectionHelper.getCommandClasses();
for(Class<?> comm:availableCommands)
{
try
{
Command currComm = (Command)comm.newInstance();
toRet.put(currComm.toString(), ReflectionHelper.getCommandVersion(currComm));
}
catch(Exception e)
{
Logger.logException("Problem occured while trying to get command information", e);
}
}
return toRet;
} | 5 |
int method328(int arg0) {
if (anInt545 >= anInt541) {
anInt544 = anIntArray537[anInt542++] << 15;
if (anInt542 >= anInt535) {
anInt542 = anInt535 - 1;
}
anInt541 = (int) (anIntArray536[anInt542] / 65536D * arg0);
if (anInt541 > anInt545) {
anInt543 = ((anIntArray537[anInt542] << 15) - anInt544) / (anInt541 - anInt545);
}
}
anInt544 += anInt543;
anInt545++;
return anInt544 - anInt543 >> 15;
} | 3 |
@Test
public void testLuoHarjoitusJaTarkistaTehtavat() {
boolean oikeinMeni = true;
try {
this.kone.luoHarjoitus("m", lkm);
} catch (Exception exception) {// EXCEPTION
System.out.println("Airmetiikkakone.luoHarjoitus-virhe");// EXCEPTION
}
for (int i = 0; i < lkm; i++) {
this.kone.getAktiivinenHarjoitus().setVastaus(i, this.kone.getAktiivinenHarjoitus().getTehtavat()[i].oikeaVastaus());
}
this.kone.getAktiivinenHarjoitus().tarkistaTehtavat();
for (int i = 0; i < lkm; i++) {
if (!this.kone.getAktiivinenHarjoitus().getTulokset()[i].equals("Oikein!")) {
oikeinMeni = false;
}
}
this.kone.lopetus(lkm);
assertEquals(true, oikeinMeni);
} | 4 |
/* */ public void moveToBest()
/* */ {
/* 211 */ Random r = new Random();
/* 212 */ if ((Math.abs(this.x - this.bestPosX) < 2) && (Math.abs(this.y - this.bestPosY) < 2)) {
/* 213 */ this.speedX = 0.0F;
/* 214 */ this.speedY = 0.0F;
/* 215 */ setMoveTo(false);
/* 216 */ return;
/* */ }
/* */
/* 219 */ if (this.x - this.bestPosX > 0)
/* 220 */ this.speedX = -1.0F;
/* */ else {
/* 222 */ this.speedX = 1.0F;
/* */ }
/* */
/* 225 */ if (this.y - this.bestPosY > 0)
/* 226 */ this.speedY = -1.0F;
/* */ else {
/* 228 */ this.speedY = 1.0F;
/* */ }
/* */
/* 231 */ if (this.x - this.bestPosX > 40)
/* 232 */ this.speedX = (-2 + r.nextInt(2) * -1);
/* 233 */ else if (this.x - this.bestPosX < -40) {
/* 234 */ this.speedX = (2 + r.nextInt(2));
/* */ }
/* */
/* 237 */ if (this.y - this.bestPosY > 40)
/* 238 */ this.speedY = (-2 + r.nextInt(2) * -1);
/* 239 */ else if (this.y - this.bestPosY < -40)
/* 240 */ this.speedX = (2 + r.nextInt(2));
/* */ } | 8 |
public String[] getVariablesOnLHS() {
ArrayList list = new ArrayList();
if(myLHS == null) return new String[0];
for(int i = 0; i < myLHS.length(); i++) {
char c = myLHS.charAt(i);
if (ProductionChecker.isVariable(c))
list.add(myLHS.substring(i, i + 1));
}
return (String[]) list.toArray(new String[0]);
} | 3 |
private static String date_format(double t, int methodId)
{
StringBuffer result = new StringBuffer(60);
double local = LocalTime(t);
/* Tue Oct 31 09:41:40 GMT-0800 (PST) 2000 */
/* Tue Oct 31 2000 */
/* 09:41:40 GMT-0800 (PST) */
if (methodId != Id_toTimeString) {
appendWeekDayName(result, WeekDay(local));
result.append(' ');
appendMonthName(result, MonthFromTime(local));
result.append(' ');
append0PaddedUint(result, DateFromTime(local), 2);
result.append(' ');
int year = YearFromTime(local);
if (year < 0) {
result.append('-');
year = -year;
}
append0PaddedUint(result, year, 4);
if (methodId != Id_toDateString)
result.append(' ');
}
if (methodId != Id_toDateString) {
append0PaddedUint(result, HourFromTime(local), 2);
result.append(':');
append0PaddedUint(result, MinFromTime(local), 2);
result.append(':');
append0PaddedUint(result, SecFromTime(local), 2);
// offset from GMT in minutes. The offset includes daylight
// savings, if it applies.
int minutes = (int) Math.floor((LocalTZA + DaylightSavingTA(t))
/ msPerMinute);
// map 510 minutes to 0830 hours
int offset = (minutes / 60) * 100 + minutes % 60;
if (offset > 0) {
result.append(" GMT+");
} else {
result.append(" GMT-");
offset = -offset;
}
append0PaddedUint(result, offset, 4);
if (timeZoneFormatter == null)
timeZoneFormatter = new java.text.SimpleDateFormat("zzz");
// Find an equivalent year before getting the timezone
// comment. See DaylightSavingTA.
if (t < 0.0 || t > 2145916800000.0) {
int equiv = EquivalentYear(YearFromTime(local));
double day = MakeDay(equiv, MonthFromTime(t), DateFromTime(t));
t = MakeDate(day, TimeWithinDay(t));
}
result.append(" (");
java.util.Date date = new Date((long) t);
synchronized (timeZoneFormatter) {
result.append(timeZoneFormatter.format(date));
}
result.append(')');
}
return result.toString();
} | 8 |
protected JPanel createDaysGUI() {
JPanel daysGrid = new JPanel(true);
daysGrid.setLayout(new GridLayout(0, dayName.length));
// What day is today in case we need to highlight it
Calendar today = Calendar.getInstance();
int todayMonth = today.get(Calendar.MONTH);
int todayYear = today.get(Calendar.YEAR);
int todayDay = today.get(Calendar.DAY_OF_MONTH);
// The start of the month
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Use this to go through all the days of the month
Calendar iterator = (Calendar) calendar.clone();
iterator.add(Calendar.DAY_OF_MONTH,
-(iterator.get(Calendar.DAY_OF_WEEK) - 1));
// The end of the month, so we don't display more than we should
Calendar maximum = (Calendar) calendar.clone();
maximum.add(Calendar.MONTH, +1);
// Add the weekdays to the calendar
for (int i = 0; i < dayName.length; i++) {
JPanel dPanel = new JPanel(true);
JLabel date = new JLabel(dayName[i]);
dPanel.add(date);
daysGrid.add(dPanel);
}
int count = 0;
int limit = dayName.length * 6;
// Create and add all buttons of the dates to the calendar
while (iterator.getTimeInMillis() < maximum.getTimeInMillis()) {
int lMonth = iterator.get(Calendar.MONTH);
int lYear = iterator.get(Calendar.YEAR);
JPanel dPanel = new JPanel(true);
JButton dayLabel = new JButton();
dayLabel.setForeground(Color.BLACK);
dayLabel.setContentAreaFilled(false);
dayLabel.setBorderPainted(false);
Listeners l = new Listeners();
dayLabel.addActionListener(l);
if ((lMonth == month) && (lYear == year)) {
int lDay = iterator.get(Calendar.DAY_OF_MONTH);
dayLabel.setText(Integer.toString(lDay));
dayLabel.setActionCommand(Integer.toString(lYear) + " " + Integer.toString(lMonth) + " " + Integer.toString(lDay));
if ((todayMonth == month) && (todayYear == year) && (todayDay == lDay)) {
dPanel.setBackground(Color.YELLOW);
}
} else {
dayLabel.setText(" ");
}
dPanel.add(dayLabel);
daysGrid.add(dPanel);
iterator.add(Calendar.DAY_OF_YEAR, +1);
count++;
}
// Add blanks where needed
for (int i = count; i < limit; i++) {
JPanel dPanel = new JPanel(true);
JLabel dayLabel = new JLabel();
dayLabel.setText(" ");
dPanel.add(dayLabel);
daysGrid.add(dPanel);
}
return daysGrid;
} | 8 |
@Test
public void WhenUpdatingWithNullHostAndRefmaxLesserThanLevelSize_ExpectReducedLevelSize() throws UnknownHostException {
RoutingTable routingTable = new RoutingTable();
localhost_.setHostPath("0");
routingTable.setLocalhost(localhost_);
PGridHost aHost = new PGridHost("127.0.0.1", 3333);
PGridHost anotherHost = new PGridHost("127.0.0.1", 4444);
routingTable.addReference(0, aHost);
routingTable.addReference(0, anotherHost);
int refMax = routingTable.getLevel(0).size() - 1;
routingTable.updateLevelRandomly(0, null, refMax);
Assert.assertTrue(routingTable.levelNumber() == 1);
Assert.assertTrue(routingTable.getLevel(0).size() == refMax);
Assert.assertTrue(routingTable.getLevel(0).contains(aHost) || routingTable.getLevel(0).contains(anotherHost));
Assert.assertFalse(routingTable.getLevel(0).contains(aHost) && routingTable.getLevel(0).contains(anotherHost));
} | 2 |
public static ArrayList<Word> analyze(String string) {
StringTagger tagger = SenFactory.getStringTagger(null);
List<Token> tokens = new ArrayList<Token>();
ArrayList<Word> arrayList = new ArrayList<Word>();
try {
tagger.analyze(string, tokens);
for (Token token : tokens) {
Word word = new Word();
word.setSurface(token.getSurface());
List<String> readings = token.getMorpheme().getReadings();
if (readings != null && readings.size() > 0) {
word.setReading(readings.get(0));
}
String partOfSpeech = token.getMorpheme().getPartOfSpeech();
if (partOfSpeech != null) {
String[] speechs = partOfSpeech.split("-", 0);
if (speechs.length > 0) {
word.setPos(speechs[0]);
}
}
arrayList.add(word);
}
} catch (IOException e) {
}
return arrayList;
} | 6 |
@Override
public boolean equals(Object obj)
{ if(obj instanceof Pair)
{ Pair that=(Pair)obj;
{ return (this.s.equals(that.s)&&this.t.equals(that.t));}
}
else { return false;}
} | 2 |
@Override
public void kill() {
setRunning(false);
listening = false;
try {
if (serverSocket != null)
serverSocket.close();
for (ClientConnection client : clientConnections) {
if (client.getClientSocket() != null)
client.getClientSocket().close();
}
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public boolean isAutoscrollOnStatus() {
if(frame == null) buildGUI();
return autoscrollStatus.isSelected();
} | 1 |
public void swim(int k) {
/**
* Checking for isLesser makes sure that the >= property of MaxHeap is
* satisfied.
*/
while (k > 1 && isLesser(k / 2, k)) {
swapArrayValues(k / 2, k);
k = k / 2;
this.arrayAccess += 2;
this.comparisions++;
}
} | 2 |
public List<CmisObject> getQueryResults(String queryString) {
List<CmisObject> objList = new ArrayList<CmisObject>();
System.out.println(queryString);
// execute query
ItemIterable<QueryResult> results = session.query(queryString, false);
for (QueryResult qResult : results) {
String objectId = "";
PropertyData<?> propData = qResult.getPropertyById("cmis:objectId"); // Atom
// Pub
// binding
if (propData != null) {
objectId = (String) propData.getFirstValue();
} else {
objectId = qResult.getPropertyValueByQueryName("d.cmis:objectId"); // Web
// Services
// binding
}
CmisObject obj = session.getObject(session.createObjectId(objectId));
objList.add(obj);
}
return objList;
} | 3 |
public MP3Container getClone() {
Vector<MP3> temp1 = new Vector<MP3>();
for (int i = 0; i < size();i++) {
temp1.add(list.get(i));
}
Vector<Integer> temp2 = new Vector<Integer>();
for (int i = 0; i < size();i++) {
temp2.add(i);
}
return new MP3Container(temp1,temp2);
} | 2 |
public static void cashSelected()
{
askForAmount();
String s = sc.nextLine();
BigDecimal cashAmt;
cashAmt = BigDecimal.valueOf(Double.parseDouble(s));
if (payments == null || payments.isEmpty())
{
if (s == null || s.isEmpty())
{
System.out.println("Error: Please enter a valid cash amount.");
cashSelected();
}
if (cashAmt.compareTo(InvoiceDisplay.getTotal()) < 0)
{
payments.add(new CashPayment(cashAmt, "CASH"));
calculateIncompleteTotal(cashAmt);
}
}
else
{
if (s == null || s.isEmpty())
{
System.out.println("Error: Please enter a valid cash amount.");
cashSelected();
}
else if (cashAmt.compareTo(remainingTotal) <= 0)
{
payments.add(new CashPayment(cashAmt, "CASH"));
calculateTotalAndFinish(cashAmt);
}
}
} | 8 |
public synchronized static int getStatus() {
if (serverMainThread == null) {
return DEAD;
} else if (serverMainThread.isAlive()
&& !serverMainThread.isInterrupted()) {
return RUNNING;
} else if (serverListeningThreads == null) {
return DEAD; //when server has been closed
} else {
for (ServerListeningThread slt : serverListeningThreads) {
if (slt != null && slt.isAlive() && !slt.isInterrupted()) {
return PLAYERS_CONNECTED;
}
}
return DEAD;
}
} | 8 |
public Dimension preferredLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = new Dimension(0, 0);
if (eastComponent != null) {
Dimension d = eastComponent.getPreferredSize();
dim.width += d.width + getHgap();
dim.height = Math.max(d.height, dim.height);
}
if (westComponent != null) {
Dimension d = westComponent.getPreferredSize();
dim.width += d.width + getHgap();
dim.height = Math.max(d.height, dim.height);
}
if (centerComponent != null) {
Dimension d = centerComponent.getPreferredSize();
dim.width += d.width;
dim.height = Math.max(d.height, dim.height);
}
if (northComponent != null) {
Dimension d = northComponent.getPreferredSize();
dim.width = Math.max(d.width, dim.width);
if (overlapSide != NORTH) {
dim.height += d.height + (getVgap() < 0 ? 0 : getVgap());
}
else {
dim.height += d.height + getVgap();
}
}
if (southComponent != null) {
Dimension d = southComponent.getPreferredSize();
dim.width = Math.max(d.width, dim.width);
if (overlapSide != SOUTH) {
dim.height += d.height + (getVgap() < 0 ? 0 : getVgap());
}
else {
dim.height += d.height + getVgap();
}
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
} | 9 |
private String parseDependencyFromLine(String line) {
String addedPath = null;
if ((line != null) && line.startsWith("//:include ")) {
addedPath = getNormalPath(line);
} else if ((!isIgnoreRequire()) && (line != null) && (line.startsWith("//= "))) {
addedPath = MiniProcessorHelper.getRequirePath(line) + ".js";
}
return addedPath;
} | 5 |
public int getMaxZCaveSpot() {
int count = caveSpots.size();
int[] caveSpot;
int zMax = 0;
int iMax = -1;
for(int i = 0; i < count; i++) {
caveSpot = (int [])caveSpots.get(i);
if(caveSpot[0] > zMax && caveSpot[2] - caveSpot[1] > 3) {
zMax = caveSpot[0];
iMax = i;
}
}
return iMax;
} | 3 |
public static void main(String[] args) {
// String queryString ="SELECT ?actor ?news WHERE {\n"+
//
// "SERVICE <http://linkedmdb.org/sparql> {" +
// "?film <http://purl.org/dc/terms/title> 'Tarzan' .}\n"+
// "SERVICE <http://linkedmdb.org/sparql> {" +
// "?film <http://data.linkedmdb.org/resource/movie/actor> ?actor .}\n"+
// "SERVICE <http://linkedmdb.org/sparql> {" +
// "?actor <http://www.w3.org/2002/07/owl#sameAs> ?x.\n" +
// "}"+
// "SERVICE <http://nytimes.com/sparql> {" +
// "?y <http://www.w3.org/2002/07/owl#sameAs> ?x .}\n"+
// "SERVICE <http://nytimes.com/sparql> {" +
// "?y <http://data.nytimes.com/elements/topicPage> ?news\n" +
// "}" +
//
// "}" ;
// String queryString ="SELECT ?actor ?news WHERE {\n"+
//
//
// "?film <http://purl.org/dc/terms/title> 'Tarzan' .\n"+
// "?film <http://data.linkedmdb.org/resource/movie/actor> ?actor .\n"+
// "?actor <http://www.w3.org/2002/07/owl#sameAs> ?x.\n" +
//
//
// "?y <http://www.w3.org/2002/07/owl#sameAs> ?x .\n"+
// "?y <http://data.nytimes.com/elements/topicPage> ?news\n" +
//
//
// "}" ;
// String queryString ="SELECT ?president ?party ?page WHERE {\n"+
// "SERVICE <http://dbpedia.org/sparql> {" +
// "?president <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n"+
// "<http://dbpedia.org/ontology/President> .\n" +
//
// "?president <http://dbpedia.org/ontology/nationality>\n"+
// "<http://dbpedia.org/resource/United_States> .\n" +
//
// "?president <http://dbpedia.org/ontology/party> ?party .}\n" +
//====================================FIRST TEST QUERY=============================
// String queryString ="select ?x ?page where {"+
// "SERVICE <http://192.168.145.128:8890/sparql> {"+
// "?x <http://data.nytimes.com/elements/topicPage> ?page .}\n" +
// "SERVICE <http://192.168.145.128:8890/sparql> {"+
// "?x <http://www.w3.org/2002/07/owl#sameAs> ?president .}\n"+
// "SERVICE <http://192.168.145.128:8890/sparql>{"+
// "?x a <http://www.w3.org/2004/02/skos/core#Concept>.}\n"+
// "}" ;
//==================================================================================
// String queryString ="SELECT ?president ?page WHERE {\n"+
// "SERVICE <http://dbpedia.org/sparql> {" +
// "?president <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n"+
// "<http://dbpedia.org/ontology/President> .}\n" +
// "SERVICE <http://dbpedia.org/sparql> {"+
// "?president <http://dbpedia.org/ontology/nationality>\n"+
// "<http://dbpedia.org/resource/United_States> .}\n" +
// "SERVICE <http://dbpedia.org/sparql> {" +
// "?president <http://dbpedia.org/ontology/party> ?party .}\n" +
// "SERVICE <http://192.168.145.128:8890/sparql>" +
// "{?x <http://data.nytimes.com/elements/topicPage> ?page .}" +
// //"SERVICE <http://192.168.145.128:8890/sparql>{"+
// "SERVICE <http://192.168.145.128:8890/sparql>" +
// "{?x <http://www.w3.org/2002/07/owl#sameAs> ?president .}"+
// "}" ;
// String queryString="SELECT ?film ?director ?genre WHERE {\n"+
// "SERVICE <http://dbpedia.org/sparql> {\n"+
// "?film <http://dbpedia.org/ontology/director> ?director .\n"+
// "?director <http://dbpedia.org/ontology/nationality> <http://dbpedia.org/resource/Italy> .\n"+
// "}\n"+
// "SERVICE <http://linkedmdb.org/sparql>\n"+
// "{\n"+
// "?x <http://www.w3.org/2002/07/owl#sameAs> ?film .\n"+
// "?x <http://data.linkedmdb.org/resource/movie/genre> ?genre .\n"+
// "}\n" +
// "}" ;
//==============================LATEST TEST QUERY ==================================
// String queryString ="SELECT ?president ?page WHERE {\n"+
// "SERVICE <http://dbpedia.org/sparql> {" +
// "?president <http://dbpedia.org/ontology/party> ?party ." +
// //"}\n" +
//
// //"SERVICE <http://dbpedia.org/sparql> {" +
// "?president <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n"+
// "<http://dbpedia.org/class/yago/PresidentsOfTheUnitedStates> .\n" +
// "}"+
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://data.nytimes.com/elements/topicPage> ?page. " +
// "}" +
// //"SERVICE <http://192.168.145.128:8890/sparql>{"+
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://www.w3.org/2002/07/owl#sameAs> ?president ." +
// "}"+
//
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://www.w3.org/2002/07/owl#sameAs> ?sameas ." +
//"}"+
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://data.nytimes.com/elements/first_use> ?firstuse ." +
// "}"+
//
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://data.nytimes.com/elements/latest_use> ?lastuse ." +
// "}"+
//
// "SERVICE <http://192.168.145.128:8890/sparql>{" +
// "?x <http://www.w3.org/2003/01/geo/wgs84_pos#lat> ?lat ." +
// "}"+
// "}" ;
//First real test
// String queryString ="PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>\n" +
// "PREFIX dbpedia:<http://dbpedia.org/resource/>\n" +
// "PREFIX linkedMDB:<http://data.linkedmdb.org/resource/movie/>\n" +
//
// "SELECT ?film ?director ?genre WHERE {\n "+
// "SERVICE <http://192.168.1.4:8890/sparql>{\n" +
// "?film dbpedia-owl:director ?director."+
// "?director dbpedia-owl:nationality ?n ."+
// " }\n "+
// "SERVICE <http://192.168.1.2:8890/sparql>{\n " +
// "?x owl:sameAs ?film ."+
// " ?x linkedMDB:genre ?genre "+
// " }\n" +
// "}" ;
//My Query
// String queryString ="PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>"+
// "PREFIX owl:<http://www.w3.org/2002/07/owl#>" +
// "PREFIX drugbank:<http://www4.wiwiss.fu-berlin.de/drugbank/resource/drugbank/>" +
// "PREFIX foaf:<http://xmlns.com/foaf/0.1/>" +
// "PREFIX sider:<http://wifo5-04.informatik.uni-mannheim.de/sider/resource/sider/>" +
// "select ?dbpediadrug " +
// "where" +
// "{" +
// "SERVICE <http://192.168.1.2:8890/sparql>" +
// "{" +
// "?dbpediadrug a dbpedia-owl:Drug. " +
// "?dbpediadrug owl:sameAs ?drugbank." +
// "}" +
// "SERVICE <http://192.168.1.3:8890/sparql>" +
// "{" +
// "?drugbank a drugbank:drugs." +
//
//
// "}" +
//// "SERVICE <http://wifo5-04.informatik.uni-mannheim.de/sider/sparql>" +
//// "{" +
//// "?drug a sider:drugs." +
//// "?drug owl:sameAs ?dbpediadrug." +
////
//// "}" +
//
// "}";
// String queryString ="PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>"+
// "PREFIX owl:<http://www.w3.org/2002/07/owl#>" +
// "prefix nytimes: <http://data.nytimes.com/elements/>" +
// "prefix dc:<http://purl.org/dc/terms/>" +
// "prefix linkedMDB: <http://data.linkedmdb.org/resource/movie/>"+
// "prefix dbpedia: <http://dbpedia.org/resource/>" +
// "prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+
// "SELECT * WHERE \n " +
// "{ \n" +
// "SERVICE <http://192.168.1.2:8890/sparql>\n" +
// "{\n"+
// "?dbfilm a dbpedia-owl:Film.\n"+
// "?dbfilm dbpedia-owl:budget ?budget .\n"+
// "?dbfilm dbpedia-owl:director ?director.\n"+
// "}\n"+
// "SERVICE <http://192.168.1.3:8890/sparql>\n"+
// "{\n"+
// "?film a linkedMDB:film .\n"+
// "?film owl:sameAs ?dbfilm.\n" +
// "?film linkedMDB:genre <http://data.linkedmdb.org/resource/film_genre/4>.\n" +
// "?film linkedMDB:actor ?actor.\n"+
// "}\n"+
// "SERVICE <http://192.168.1.4:8890/sparql>\n"+
// "{\n"+
// "?ydirector owl:sameAs ?director.\n" +
// "?ydirector nytimes:topicPage ?newspage.\n" +
// "}\n"+
//
// "}\n" ;
//
// String queryString="PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>PREFIX owl:<http://www.w3.org/2002/07/owl#>prefix nytimes: <http://data.nytimes.com/elements/>prefix dc:<http://purl.org/dc/terms/>prefix linkedMDB: <http://data.linkedmdb.org/resource/movie/>prefix dbpedia: <http://dbpedia.org/resource/>prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>" +
// "SELECT * WHERE\n"+
// "{\n"+
// "SERVICE <http://192.168.1.3:8890/sparql>\n" +
// "{\n"+
// "?film dc:title ?title .\n" +
// "}\n"+
// "SERVICE <http://192.168.1.3:8890/sparql>\n" +
// "{\n"+
// "?film linkedMDB:actor ?actor .\n" +
// "}\n"+
// "SERVICE <http://192.168.1.3:8890/sparql>\n" +
// "{\n"+
// "?actor owl:sameAs ?x.\n" +
// "}\n"+
// "SERVICE <http://192.168.1.4:8890/sparql>\n" +
// "{\n" +
// "?y owl:sameAs ?x .\n" +
//
//
// "?y nytimes:topicPage ?news.\n" +
// "}\n" +
// "}" ;
// String queryString= "PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>PREFIX owl:<http://www.w3.org/2002/07/owl#>prefix nytimes: <http://data.nytimes.com/elements/>prefix dc:<http://purl.org/dc/terms/>prefix linkedMDB: <http://data.linkedmdb.org/resource/movie/>prefix dbpedia: <http://dbpedia.org/resource/>prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>" +
// "SELECT * WHERE\n"+
// "{ \n" +
// "SERVICE <http://dbpedia.org/sparql>\n" +
// "{\n"+
// "?film dbpedia-owl:director ?director.\n" +
// "}\n" +
// "SERVICE <http://192.168.1.3:8890/sparql>\n" +
// "{\n"+
// "?x owl:sameAs ?film .\n" +
// "?x linkedMDB:genre ?genre.\n" +
// "}\n"+
// "}" ;
// String queryString="PREFIX dbpedia-owl:<http://dbpedia.org/ontology/>"+
// "PREFIX owl:<http://www.w3.org/2002/07/owl#>" +
// "prefix nytimes: <http://data.nytimes.com/elements/>" +
// "prefix dc:<http://purl.org/dc/terms/>" +
// "prefix linkedMDB: <http://data.linkedmdb.org/resource/movie/>"+
// "prefix dbpedia: <http://dbpedia.org/resource/>" +
// "prefix rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>"+
// "SELECT * WHERE { "+
// "{SERVICE <http://dbpedia.org/sparql>\n" +
// "{\n"+
//// "?dbfilm a dbpedia-owl:Film.\n"+
//// "?dbfilm dbpedia-owl:budget ?bd .\n"+
// " dbpedia:Barack_Obama ?predicate ?object."+
// "}}\n"+
// "SERVICE <http://dbpedia.org/sparql>\n" +
// "{\n"+
// "?dbfilm dbpedia-owl:budget ?budget .\n"+
// "}\n"+
// "}";
// "{ dbpedia:Barack_Obama ?predicate ?object }"+
// "UNION"+
// "SERVICE <http://172.16.3.171:8890/sparql>\n" +
// "{\n"+
// "?pres rdf:type dbpedia-owl:President ." +
// "?pres dbpedia-owl:nationality dbpedia:United_States ."+
// "?pres dbpedia-owl:party ?party"+
// "}" +
// "SERVICE <http://172.16.3.171:8890/sparql>\n" +
// "{\n"+
// "?pres rdf:type dbpedia-owl:President ." +
// "?pres dbpedia-owl:nationality dbpedia:United_States ."+
//// "?pres dbpedia-owl:party <http://dbpedia.org/resource/Democratic_Party_(United_States)>"+
// "?pres dbpedia-owl:party ?partyj"+
// "}"+
// "SERVICE <http://172.16.3.171:8890/sparql>\n" +
// "{\n"+
// "?pres rdf:type dbpedia-owl:President ." +
// "?pres dbpedia-owl:nationality dbpedia:United_States ."+
//// "?pres dbpedia-owl:party <http://dbpedia.org/resource/Democratic_Party_(United_States)>"+
// "?pres dbpedia-owl:party ?partyk"+
// "}"+
// "}\n";
// "{ SERVICE <http://dbpedia.org/sparql>{" +
// " ?subject owl:sameAs dbpedia:Barack_Obama ." +
// " ?subject ?predicate ?object } }}" ;
// String queryString ="SELECT * WHERE "+
// "{"+
// "SERVICE <http://172.16.3.171:8890/sparql>\n" +
// "{\n"+
// "?dbfilm <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Film>.\n"+
// "?dbfilm <http://dbpedia.org/ontology/starring> ?dbactor.\n"+
// "\n}"+
// "SERVICE <http://172.16.3.164:8890/sparql>\n" +
// "{\n"+
// "?imdbactor <http://www.w3.org/2002/07/owl#sameAs> ?dbactor."+
// " }"+
// "SERVICE <http://172.16.3.178:8890/sparql>\n" +
// "{\n"+
// "?yactor <http://www.w3.org/2002/07/owl#sameAs> ?dbactor."+
// "?yactor <http://data.nytimes.com/elements/topicPage> ?newspage." +
// " }"+
// " }" ;
String queryString =QueryStrings.myQuery4Service ;
myLogger.queryId="Myquery4" ;
myLogger.queryString=queryString ;
myLogger.systemName="MySystem-Deterministic" ;
myLogger.folderToSave="c:\\ADQUEX Evaluations\\Compare with other systems\\Myqueries\\";
myLogger.timeout=5;
myLogger.logging=false;
try
{
long startTime =System.currentTimeMillis();
TupleExpr tExpr = Parser.parseQueryString(queryString) ;
myLogger.printInfo(tExpr);
//System.out.println(tExpr.toString());
Optimizer.Optimize(tExpr,false) ;
myLogger.printInfo("Optimized Plan:\n");
//System.out.println("Optimized Plan:\n");
myLogger.printInfo(tExpr);
//System.out.println(tExpr);
// Joinprinter jp =new Joinprinter();
// tExpr.visit(jp);
// JoinTableGenerator jt =new JoinTableGenerator() ;
// System.out.println(jt.GenerateJoinTable(tExpr));
// System.out.println("Amin!");
// System.out.println("Amin!");
QueryResultList results = FederatedQueryExecuter.ExecuteTupleExpr(tExpr);
BindingSet bindings ;
int countTuples = 0;
boolean isFirstTuple =true;
while (true)
{
bindings =results.next() ;
if (bindings == null )
break ;
if (isFirstTuple)
{
long firstTuple =System.currentTimeMillis()-startTime ;
myLogger.firstTuple =firstTuple ;
//System.out.println("First Tuple = "+firstTuple);
isFirstTuple=false;
}
myLogger.printInfo(bindings);
//System.out.println(bindings);
//System.out.println(bindings.toString());
countTuples++;
myLogger.printInfo("||||||Count Results ="+countTuples) ;
//System.out.println("||||||Count Results ="+countTuples);
}
long executionTime =System.currentTimeMillis()-startTime;
myLogger.executionTime=executionTime ;
myLogger.numberOfResultTuples =countTuples ;
System.out.println("Execution Time = "+ executionTime);
Thread.sleep(2000) ;
myLogger.saveStatistics();
myLogger.printStatistics() ;
System.exit(0);
}
catch (MalformedQueryException e)
{
System.out.println(e.getMessage());
e.printStackTrace() ;
}
catch (OptimizerException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
public static void main(String[] args) throws Exception {
Runnable server = new Runnable() {
@Override
public void run() {
try {
new SocketServerExample("localhost", 8090).startServer();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Runnable client = new Runnable() {
@Override
public void run() {
try {
new SocketClientExample().startClient();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(server).start();
new Thread(client, "client-A").start();
new Thread(client, "client-B").start();
} | 3 |
public static List<IComponent> getAllChildrenComponents(Entity entity, List<IComponent> componentList) {
Children childrenComponent = entity.getComponent(Children.class);
// Our base test, stop recursion if we no longer have children
if (childrenComponent == null) {
return componentList;
}
for (Entity child : childrenComponent.children) {
// Add to the componentList any of the children's components that we
// are searching for, and then call this function on the child (in
// case that child also has children)
componentList.addAll(child.getAllComponents());
getAllChildrenComponents(child, componentList);
}
return componentList;
} | 2 |
private void deleteFile() {
HashMap<String, FileStructure> currFileList = fileUtil.getAllFiles(rootDirAddress, true);
Iterator iter = currFileList.keySet().iterator();
while(iter.hasNext()) {
String currFileName = (String)iter.next();
// here we have a bug, cannot delete an empty dir!
if(!serverFileSet.contains(currFileName)
&& prevFileList.containsKey(currFileName)
// conflict file will not be deleted!
// if a conflict file is deleted in server side, it would not be deleted in the client side
&& !currFileName.endsWith(DropboxConstants.CONFLICT_MARK)) {
String fullPath = rootDirAddress+fileUtil.getDeletedParentRelativePath(currFileName);
File deletedFile = new File(fullPath);
if(deletedFile.isDirectory()) {
DropboxFileUtil.deleteDirAndSubsidiaries(deletedFile);
System.out.println("delete dir and its subsidiaries:"+ fullPath);
// get the address of the copy file and delete it
/*
rootDirAddress
File deletedFileCopy = new File(rootDirAddress+DropboxConstants.COPYFILE_DIR_MARK+fileUtil.getDeletedParentRelativePath(currFileName));
*/
}
else {
deletedFile.delete();
System.out.println("delete file:"+ fullPath);
}
deletedFileSet.add(fileUtil.getDeletedParentRelativePath(currFileName));
}
}
// So far, the client sides's files hierarchy is almost the same as the server side
// except some empty dirs remain undeleted. So next we need to delete these empty dirs
} | 5 |
protected void addDuplicate(URI uri) {
this.duplicates.add(uri);
} | 0 |
private AFParser recursiveAFNEGenerate(RegularExpresionNode node) {
AFParser result = null;
if(node instanceof ConcatNode){
RegularExpresionNode left = ((ConcatNode)node).leftOperandNode;
RegularExpresionNode right = ((ConcatNode)node).rightOperandNode;
result = this.concatenateAutomatas(this.recursiveAFNEGenerate(left), this.recursiveAFNEGenerate(right));
}else if(node instanceof OrNode){
RegularExpresionNode left = ((OrNode)node).leftOperandNode;
RegularExpresionNode right = ((OrNode)node).rightOperandNode;
result = this.orAutomatas(this.recursiveAFNEGenerate(left), this.recursiveAFNEGenerate(right));
}else if(node instanceof CycleNode){
RegularExpresionNode unique = ((CycleNode)node).OperandNode;
result = this.asteriscAutomata(this.recursiveAFNEGenerate(unique));
}else if(node instanceof SymbolNode){
String value = "" + ((SymbolNode)node).Value;
result = this.generateLeafAutomata(value);
}
return result;
} | 4 |
private static ArrayList<Configuration> sautRecursif(Configuration conf, byte[] triplet, byte typeSauteFirst, boolean noirEnPlayer){
ArrayList<Configuration> listeConf = new ArrayList<Configuration>();
byte caseDebut = triplet[0];
byte typeSaute = triplet[1];
byte caseFin = triplet[2];
byte newTurttle=0;
if (typeSaute == conf.player)
newTurttle = conf.player;// player saute opponent2 : pas de changement
else if (typeSaute == conf.opponent)
newTurttle = typeSaute; // player saute opponent2 : rouge2 se retourne en noir
else if (typeSaute == 3) { // player1 saute noir2 : 2 cas, _noir2 devient player, on fait un appel r�cursif pour traiter ce cas.
// _noir2 devient opponent, on continue la fonction normalement
if (noirEnPlayer) {
newTurttle = conf.player;
}else {
listeConf.addAll(sautRecursif(conf, triplet, typeSauteFirst, true)); //appel r�cursif
newTurttle = conf.opponent;
}
}else System.out.println("ERREUR : dans la fct recursive de IA, typeSaute != 1,2 ou 3");
Configuration c = conf.clone();
c.coupJoue(caseDebut, newTurttle, caseFin);
// typeSauteFirst doit contenir le type de la premiere tortue de couleur rouge ou verte saut� dans un tour de jeu
if (typeSauteFirst == 3){
typeSauteFirst = typeSaute;
}
ArrayList<byte[]> lMovePossible = c.possibleMove(caseFin, typeSauteFirst);
if (lMovePossible.isEmpty()){ // si pas de saut possible apr�s le premier coup
listeConf.add(c); // AJOUT de la nouvelle config
}else {
for (byte[] tripletFils : lMovePossible){
listeConf.addAll(sautRecursif(c, tripletFils, typeSauteFirst, false)); //appel r�cursif
}
}
return listeConf;
} | 7 |
private void setBalance(BigInteger balance) throws IllegalArgumentException {
if (! this.canHaveAsBalance(balance))
throw new IllegalArgumentException();
this.balance = balance;
} | 1 |
private void findRecursive(File folder) {
for(File file : folder.listFiles()) {
if(file.isDirectory()) {
findRecursive(file);
}
if(FilenameUtils.getExtension(file.getName()).equals("java")) {
results.add(file);
}
}
} | 3 |
public void checkImgDir(){
if(xDirection > 0 && pDir != 3){
pDir = 3;
}
if(xDirection < 0 && pDir != 2){
pDir = 2;
}
if(yDirection < 0 && pDir != 1){
pDir = 1;
}
if(yDirection > 0 && pDir != 0){
pDir = 0;
}
} | 8 |
private static boolean validateRGB(String[] rgb) {
if (rgb.length < 3) {
return false;
}
for (String color : rgb) {
if (color.isEmpty() || color.length() > 3) {
return false;
}
short value = Short.parseShort(color);
if (value < 0 || value > 255) {
return false;
}
}
return true;
} | 6 |
public void actionPerformed(ActionEvent e)
{
AbstractButton b = (AbstractButton) e.getSource();
if (b == quoteBtn)
{
getQuote();
} else if (b == orderBtn)
{
placeOrder();
} else if (b == marketBtn)
{
priceText.setText("");
} else if (b == limitBtn)
{
priceText.selectAll();
priceText.requestFocus();
}
} | 4 |
@Override
public void execute(String[] input) {
Properties preferences = laura.getPreferences();
String userName = preferences.getProperty("userName");
if (userName == null) {
laura.print("Hello, my name is LAURA. What's yours?");
userName = laura.getInput();
laura.print("Great to meet you, " + userName + "!");
preferences.setProperty("userName", userName);
} else {
laura.print("Hello " + userName + "!");
}
} | 1 |
public void processMouseReleased(int x, int y)
{
// ARE WE COMPLETE MAKING OUR SHAPE?
if (state == PoseurState.COMPLETE_SHAPE_STATE)
{
// WE HAVE TO USE POSE SPACE COORDINATES
Rectangle2D poseArea = zoomableCanvasState.getPoseArea();
float zoomLevel = zoomableCanvasState.getZoomLevel();
int poseSpaceX = (int)((x - poseArea.getX()) / zoomLevel);
int poseSpaceY = (int)((y - poseArea.getY()) / zoomLevel);
lastMouseDraggedX = x;
lastMouseDraggedY = y;
// IF WE'RE NOT IN THE POSE AREA, WE'RE NOT MAKING A SHAPE
if ( (poseSpaceX < 0) ||
(poseSpaceY < 0) ||
(poseSpaceX > poseArea.getWidth()) ||
(poseSpaceY > poseArea.getHeight()))
{
setState(PoseurState.CREATE_SHAPE_STATE);
shapeInProgress = null;
return;
}
// ASK THE SHAPE TO UPDATE ITSELF BASE ON WHERE ON
// THE POSE THE MOUSE BUTTON WAS RELEASED
if (!shapeInProgress.completesValidShape(poseSpaceX, poseSpaceY))
{
shapeInProgress = null;
setState(PoseurState.CREATE_SHAPE_STATE);
}
else
{
// OUR LITTLE SHAPE HAS GROWN UP
pose.addShape(shapeInProgress);
selectedShape = shapeInProgress;
shapeInProgress = null;
// WE CAN DRAW ANOTHER ONE NOW
setState(PoseurState.CREATE_SHAPE_STATE);
// REPAINT OF COURSE
repaintCanvases();
}
}
else if (state == PoseurState.DRAG_SHAPE_STATE)
{
setState(PoseurState.SHAPE_SELECTED_STATE);
}
} | 7 |
public void insertarFinal(T obj){
// Variable auxiliar
Nodo<T> q = p; //EL nodo auxiliar
Nodo<T> t = new Nodo<>(); //El nuevo nodo a insertar
t.setValor(obj);
t.setLiga(null);
if(p == null){
p = t;
}else{
//ciclo que recorre la lista
while(q.getLiga() != null){
q = q.getLiga();
}
q.setLiga(t);//Asignamos a la liga del ultimo
}
} | 2 |
@Override
public int hashCode() {
int hash = 0;
hash += (idEntrada != null ? idEntrada.hashCode() : 0);
return hash;
} | 1 |
public static Sujet creerSujet(Categorie categorie, String sujet, String message, boolean sticky, Utilisateur auteur, Icone icone)
throws ChampInvalideException, ChampVideException {
if (!categorie.peutCreerSujet(auteur))
throw new InterditException("Vous n'avez pas les droits requis pour créer un sujet");
EntityTransaction transaction = SujetRepo.get().transaction();
Sujet s;
try {
transaction.begin();
s = genererSujet(categorie, sujet, sticky, auteur, icone);
genererReponse(s, message, auteur);
SujetRepo.get().creer(s);
transaction.commit();
}
catch(Exception e) {
if (transaction.isActive())
transaction.rollback();
if (e instanceof ChampVideException)
throw (ChampVideException)e;
else if (e instanceof ChampInvalideException)
throw (ChampInvalideException)e;
else
throw (RuntimeException)e;
}
return s;
} | 5 |
public String toString() {
// only ZeroR model?
if (m_ZeroR != null) {
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
buf.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n\n");
buf.append("Warning: No model could be built, hence ZeroR model is used:\n\n");
buf.append(m_ZeroR.toString());
return buf.toString();
}
if (m_Train == null) {
return "Locally weighted learning: No model built yet.";
}
String result = "Locally weighted learning\n"
+ "===========================\n";
result += "Using classifier: " + m_Classifier.getClass().getName() + "\n";
switch (m_WeightKernel) {
case LINEAR:
result += "Using linear weighting kernels\n";
break;
case EPANECHNIKOV:
result += "Using epanechnikov weighting kernels\n";
break;
case TRICUBE:
result += "Using tricube weighting kernels\n";
break;
case INVERSE:
result += "Using inverse-distance weighting kernels\n";
break;
case GAUSS:
result += "Using gaussian weighting kernels\n";
break;
case CONSTANT:
result += "Using constant weighting kernels\n";
break;
}
result += "Using " + (m_UseAllK ? "all" : "" + m_kNN) + " neighbours";
return result;
} | 9 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof MateriaPK)) {
return false;
}
MateriaPK other = (MateriaPK) object;
if ((this.idpropuesta == null && other.idpropuesta != null) || (this.idpropuesta != null && !this.idpropuesta.equals(other.idpropuesta))) {
return false;
}
if ((this.codigomateria == null && other.codigomateria != null) || (this.codigomateria != null && !this.codigomateria.equals(other.codigomateria))) {
return false;
}
return true;
} | 9 |
protected boolean encodeHeader(int alphabetSize, int[] alphabet, int[] frequencies, int lr)
{
EntropyUtils.encodeAlphabet(this.bitstream, alphabet, alphabetSize);
if (alphabetSize == 0)
return true;
this.bitstream.writeBits(lr-8, 3); // logRange
int inc = (alphabetSize > 64) ? 16 : 8;
int llr = 3;
while (1<<llr <= lr)
llr++;
// Encode all frequencies (but the first one) by chunks of size 'inc'
for (int i=1; i<alphabetSize; i+=inc)
{
int max = 0;
int logMax = 1;
final int endj = (i+inc < alphabetSize) ? i + inc : alphabetSize;
// Search for max frequency log size in next chunk
for (int j=i; j<endj; j++)
{
if (frequencies[alphabet[j]] > max)
max = frequencies[alphabet[j]];
}
while (1<<logMax <= max)
logMax++;
this.bitstream.writeBits(logMax-1, llr);
// Write frequencies
for (int j=i; j<endj; j++)
this.bitstream.writeBits(frequencies[alphabet[j]], logMax);
}
return true;
} | 9 |
private void cores() {
Menu m = new Menu("CORES");
m.inclui("listar", "Todos as cores e modificadores");
m.inclui("incluir", "Adicionar um nova cor");
m.inclui("incluir2", "Adicionar um novo modificador");
m.inclui("remover", "Remover uma cor");
m.inclui("remover2", "Remover um modificador");
m.inclui("sair", "Voltar para menu anterior");
do {
switch (m.opcao()) {
case "listar":
System.out.println("Cores:");
for(String s : rol.todasAsCores())
System.out.println(s);
System.out.println("\nModificadores:");
for(String s2 : rol.todosOsModificadores())
System.out.println(s2);
break;
case "incluir":
System.out.print("/nDigite uma palavra que descreve a cor:\n>> ");
rol.adicionaCor((new java.util.Scanner(System.in)).next());
break;
case "incluir2":
System.out.print("/nDigite uma palavra que descreve o modificador:\n>> ");
rol.adicionaModificador((new java.util.Scanner(System.in)).next());
break;
case "remover":
Menu m2 = new Menu("Remover cor", rol.todasAsCores());
rol.removeCor(m2.opcao());
break;
case "remover2":
Menu m3 = new Menu("Remover modificador", rol.todosOsModificadores());
rol.removeModificador(m3.opcao());
case "sair":
return;
default:
System.out.println("Nao implementado");
}
} while (true);
} | 9 |
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.