method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
14051e03-dc06-495d-95f9-eef3178fb3d3 | 3 | public ArrayList<String> getItemTypeList(String category, String types) {
ArrayList<String> matchingItems = new ArrayList<String>();
ItemType itemType = null;
for (int i = 0; i < itemTypesList.size(); i++) {
itemType = itemTypesList.get(i);
if(itemType.getCategory().equals(category) && types.contains("|" + itemType.getType() + "|")) {
matchingItems.add(itemType.getName());
}
}
return matchingItems;
} |
35a72dd9-3078-4b41-aef2-016236bac715 | 6 | private static void setLookAndFeel(String lookAndFeel) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (lookAndFeel.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Lobby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Lobby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Lobby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Lobby.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
} |
8afab710-68c2-4937-a8cf-caf3dbcb1ebd | 5 | public void tick(Input input)
{
player1.tick(input);
//player2.tick();
//player3.tick();
//player4.tick();
for(Particle p : particles)
{
p.tick();
if(p.remove)
{
particles.remove(p);
}
}
for(Entity e : entities)
{
if(e.name.equals("Bullet"))
{
Bullet b = (Bullet)e;
b.tick();
}
if(e.remove)
{
entities.remove(e);
}
}
} |
d4f6da9c-2403-4e54-b4ce-0c2b40844ef3 | 2 | private void releaseKey(int code) {
keyDown[code] = false;
if (code < maxKeyCount) {
String keyName = keyNames[code];
if (keyName != null) {
lastKey = keyName;
}
}
} |
9ede2c0d-84c2-4040-9d81-d4f1216ce7d0 | 2 | public void close() {
if (sequencer != null && sequencer.isOpen()) {
sequencer.close();
}
} |
2b40396c-32ed-445d-8382-e94849c32d39 | 1 | public void makeMove(Location loc) {
if (loc == null)
removeSelfFromGrid();
else
moveTo(loc);
} |
de0edaa4-bb51-42de-85f0-e76e641976c3 | 3 | public static ArrayList<Station> getAllStation() {
Statement stat;
ArrayList<Station> stations = new ArrayList<>();
try {
stat = ConnexionDB.getConnection().createStatement();
stat.executeUpdate("use nemovelo");
ResultSet res = stat.executeQuery("select * from station");
Station station;
int id_station;
String serialNumber, etat, latitude, longitude;
while (res.next()) {
id_station = res.getInt("id_station");
serialNumber = res.getString("serialNumber");
etat = res.getString("etat");
latitude = res.getString("latitude");
longitude = res.getString("longitude");
station = new Station(id_station, serialNumber, etat, latitude, longitude);
stations.add(station);
}
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
return stations;
} |
747ba2cd-bbbb-40cf-ac60-e0687b621844 | 5 | @Override
public Future<WebServer> stop() {
FutureTask<WebServer> future = new FutureTask<WebServer>(new Callable<WebServer>() {
@Override
public WebServer call() throws Exception {
if (channel != null) {
channel.close();
}
if (connectionTrackingHandler != null) {
connectionTrackingHandler.closeAllConnections();
connectionTrackingHandler = null;
}
if (bootstrap != null) {
bootstrap.releaseExternalResources();
}
// shut down all services & give them a chance to terminate
for (ExecutorService executorService : executorServices) {
shutdownAndAwaitTermination(executorService);
}
bootstrap = null;
if (channel != null) {
channel.getCloseFuture().await();
}
return NettyWebServer.this;
}
});
// don't use Executor here - it's just another resource we need to manage -
// thread creation on shutdown should be fine
final Thread thread = new Thread(future, "WEBBIT-SHUTDOW-THREAD");
thread.start();
return future;
} |
35a6b712-ddea-4c9f-8749-d4eafec5e0f5 | 4 | public static void UperFirstName(){
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 Members set first_name = CONCAT( UPPER( LEFT( first_name, 1 ) ) , SUBSTRING( first_name, 2 ))");
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
e.printStackTrace();
}
} |
0f80087f-0eb9-45ea-93b4-aee4cfee36a5 | 1 | private void init() {
setLayout(new BorderLayout(0, 5));
setBorder(makeBorder());
Box box = Box.createVerticalBox();
box.add(getTopPanel(), BorderLayout.NORTH);
box.add(testPanel.getMainPanel(), BorderLayout.NORTH);
add(box, BorderLayout.NORTH);
new Thread(new Runnable() {
@Override
public void run() {
if (!JMeterUtils.getPropDefault(Constants.BLAZEMETER_RUNNERGUI_INITIALIZED, false)) {
JMeterUtils.setProperty(Constants.BLAZEMETER_RUNNERGUI_INITIALIZED, "true");
}
}
}).start();
} |
395fce66-8256-414a-b4cb-14603b005941 | 0 | public void setFromDate(String fromDate) {
this.fromDate = fromDate;
} |
d515f49f-1e57-49e5-a6c2-4c6afd92d01f | 6 | private static void trainTransitionParameters(double[] emissions, GaussianMarkovModel mm,
GaussianForwardAlgorithm fa, GaussianBackwardsAlgorithm ba) throws Exception
{
int numStates = mm.getMarkovStates().length;
double[][] A = new double[numStates][numStates] ;
double logPx = fa.getLogFinalPValue();
for( int i=0; i < emissions.length-1; i++)
for( int k=0; k < numStates; k++)
for( int l=0; l < numStates; l++)
{
double newVal =
fa.getLogProbs()[k][i]
+ Math.log(mm.getMarkovStates()[k].getTransitionProbs()[l])
+ GaussianViterbi.getLogEmissionProb(emissions[i+1], mm.getMarkovStates()[l])
+ ba.getLogProbs()[l][i+1] - logPx;
A[k][l] += Math.exp(newVal);
}
for( int k=0; k < numStates; k++)
{
double sum =0;
for( int l=0; l < numStates; l++)
sum += A[k][l];
for( int l=0; l < numStates; l++)
mm.getMarkovStates()[k].getTransitionProbs()[l] =
(A[k][l]) / sum;
}
} |
4ab0059a-6f73-48cc-9bc9-46f29fc1bc34 | 0 | public TreePanel initTreePane() {
final TreePanel tpane = new TreePanel(treeDrawer);
gui.SuperMouseAdapter a = new gui.SuperMouseAdapter() {
public void mouseClicked(MouseEvent event) {
TreeNode n = tpane.nodeAtPoint(event.getPoint());
controller.nodeClicked((MinimizeTreeNode) n, event);
}
public void mousePressed(MouseEvent event) {
TreeNode n = tpane.nodeAtPoint(event.getPoint());
controller.nodeDown((MinimizeTreeNode) n, event);
}
};
tpane.addMouseListener(a);
tpane.addMouseMotionListener(a);
return tpane;
} |
6f4e3330-39fb-46a3-a14c-d0ee6368b15d | 5 | private static void createContext
( String subscriptionClassName, String[] parameterValues, String connectionURL )
throws Exception
{
Class<?> subscriptionClass = Class.forName( subscriptionClassName );
SubscriptionSignature subscriptionSignature = (SubscriptionSignature) subscriptionClass.getAnnotation( SubscriptionSignature.class );
HashMap<String, String> parameterMap = null;
String[] parameterNames = subscriptionSignature.parameters();
if ( parameterValues != null )
{
parameterMap = new HashMap<String, String>();
int count = parameterNames.length;
int actual = parameterValues.length;
if ( count != actual )
{
throw new SQLException( "Expected " + count + " parameters, but saw " + actual );
}
for ( int i = 0; i < count; i++ )
{
parameterMap.put( parameterNames[ i ], parameterValues[ i ] );
}
}
SubscriptionContext newContext = new SubscriptionContext( subscriptionSignature, parameterMap, connectionURL );
SubscriptionContext oldContext = getContext( subscriptionClassName, false );
if ( oldContext != null )
{
throw new SQLException( subscriptionClassName + " already in use. Try again later." );
}
_contexts.put( subscriptionClassName, newContext );
} |
70454083-2126-48f3-90d7-6f814a7f12e7 | 5 | public void processEpsilonValue() {
try {
DataWriters = new ArrayList<DataWriter>();
DataWriters.add(new OpinionDensityDataWriter(Constants.files.get(OpinionDensityDataWriter.id)));
DataWriters.add(new OpinionClusterDataWriter(Constants.files.get(OpinionClusterDataWriter.id)));
DataWriters.add(new RealizationFractionByOCDataWriter(Constants.files.get(RealizationFractionByOCDataWriter.id)));
DataWriters.add(new OCDistDataWriter(Constants.files.get(OCDistDataWriter.id), 0));
DataWriters.add(new OCDistDataWriter(Constants.files.get(OCDistDataWriter.id+1), 1));
DataWriters.add(new GroupSizeDistributionDataWriter("GroupSizeDistribution"));
} catch(IOException e) {
e.printStackTrace();
}
ocNonConsensusRatio /= Constants._trials;
for(int i = 0; i < opAverageSet.length; i++) {
opAverageSet[i] /= Constants._trials;
}
forcePrintToConsole("Finalizing data for independent variable value: " + round(indVar.doubleValue())
+ "\n\t\t" + "Avg number of external neighbors: " + round(avgExternalNeighbors)
//+ "\n\t\t" + ""
);
/*printToConsole("Statistics gathered for epsilon value " + epsilon + ":\n"
+ " opAverageTotal: " + opAverageTotal + "\n"
+ " ocOccurranceByPopulation: " + ocOccurranceByPopulation + "\n"
+ " ocOccurranceByGroup: " + ocOccurranceByGroup + "\n"
+ " ocNonConsensusRatio: " + ocNonConsensusRatio + "\n"
);*/
try {
for(DataWriter dw : DataWriters) {
if(dw.active) dw.addNewRow();
}
} catch(IOException e) {
e.printStackTrace();
}
} |
035653b0-cfe9-4e94-adc6-04fc588c61f3 | 0 | public String getMessage() { return Message; } |
d41d5ce6-f55d-48fb-9b1e-4697800692cc | 1 | private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("FiltradoSesion:DoBeforeProcessing");
}
// Write code here to process the request and/or response before
// the rest of the filter chain is invoked.
// For example, a logging filter might log items on the request object,
// such as the parameters.
/*
for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
StringBuffer buf = new StringBuffer();
buf.append(name);
buf.append("=");
for(int i=0; i < n; i++) {
buf.append(values[i]);
if (i < n-1)
buf.append(",");
}
log(buf.toString());
}
*/
} |
d4aedc72-d6ac-4b8d-9709-d0ff2e33aa50 | 1 | private String getIntegerValue(final Field field, final Object object) {
Object result = getRawValue(field, object);
if (result == null) {
result = "";
}
return result.toString();
} |
036ef972-b6e6-4f0e-ba21-330dc126c760 | 3 | public ZFrame unwrap() {
if (size() == 0)
return null;
ZFrame f = pop();
ZFrame empty = getFirst();
if (empty.hasData() && empty.size() == 0) {
empty = pop();
empty.destroy();
}
return f;
} |
a2bc1531-109a-4d6b-8673-3685beb43ff1 | 8 | public List<Movimentacao> buscaPorContaETipo_Concatenando_LevementeRefatorado(Conta conta, TipoMovimentacao tipo) {
StringBuilder jpql = new StringBuilder(" select m from Movimentacao m ");
List<String> criteria = new ArrayList<String>();
if (conta != null) {
criteria.add("m.conta = :conta");
}
if (tipo != null) {
criteria.add("m.tipoMovimentacao = :tipo");
}
if (criteria.size() > 0) {
jpql.append(" where ");
for (int i = 0; i < criteria.size(); i++) {
if (i > 0) {
jpql.append(" and ");
}
jpql.append(criteria.get(i));
}
}
TypedQuery<Movimentacao> query = entityManager.createQuery(jpql.toString(), Movimentacao.class);
if (criteria.size() > 0) {
if (conta != null) {
query.setParameter("conta", conta);
}
if (tipo != null) {
query.setParameter("tipo", tipo);
}
}
return query.getResultList();
} |
6e88f7e6-8a8d-4637-9494-f5cfcb681985 | 5 | public static FileDescriptor forTuple(Tuple tup) {
if (!tup.isOfTypes(byte[].class, Integer.class, Long.class))
throw new IllegalArgumentException(
"Invalid Tuple passed to FileDescriptor.forTuple()!");
String id = new String((byte[]) tup.getItem(0));
int owner = (int) tup.getItem(1);
long size = -1L;
Object o = tup.getItem(2);
if (o instanceof Long)
size = ((Long) o).longValue();
else if (o instanceof Integer)
size = (long) ((Integer) o).intValue();
else if (o instanceof Short)
size = (long) ((Short) o).shortValue();
else if (o instanceof Byte)
size = (long) ((Byte) o).byteValue();
return new FileDescriptor(id, owner, size);
} |
b222fd1a-0a1e-4206-a371-c7923c47abc9 | 6 | private void broadcastFinalScores(){
String stringScores;
int finalScore[];
System.out.println();
printStatus("[ GAME OVER ] " + GameInfo.indexToPlayerName(turn) + " wins");
stringScores = "";
finalScore = new int[hands.length]; // all elements are set to 0 by default in Java
// Calculate the scores of each player
for(int i=0; i<finalScore.length; i++){
outbox[i].println(game.toString());
if(i != turn){
try {
finalScore[i] = finalScore[i] + Integer.parseInt(inbox[i].readLine()) * -1;
} catch (Exception e) {
printStatus(GameInfo.indexToPlayerName(i) + " has already terminated their connection.");
}
finalScore[turn] = finalScore[turn] + finalScore[i] * -1;
}
}
// Create a string that contains all scores
stringScores = "";
for(int i=0; i<finalScore.length; i++)
stringScores = stringScores + finalScore[i] + ",";
stringScores = stringScores.substring(0,stringScores.lastIndexOf(","));
// Broadcast the scores to all players and display the final results in the server
for(int i=0; i<finalScore.length; i++){
if(i == turn)
printStatus("[ " + GameInfo.indexToPlayerName(i) + " ] : " + finalScore[i]);
else
printStatus(" " + GameInfo.indexToPlayerName(i) + " : " + finalScore[i]);
outbox[i].println(stringScores);
}
} |
866648ab-610d-42fd-acc3-ff813bfa6f0c | 5 | private static boolean meetsFilter(String ticker) {
boolean fits = true;
for (FilterPanel fp : EarningsTest.singleton.filters) {
if (!fp.include.isSelected())
continue;
int id = fp.getId();
boolean checkDividendHistory = DBLabels.labels[id]
.equals("Dividends");
float low = fp.getLow();
float high = fp.getHigh();
float currentDataPoint = Database.DB_ARRAY.lastEntry().getValue()[Database.dbSet
.indexOf(ticker)][id];
if (checkDividendHistory) {
currentDataPoint = calculateDividend(ticker);
}
if (currentDataPoint < low || currentDataPoint > high)
return false;
}
return fits;
} |
5b395204-bdb8-4f63-bd31-7750a19ecc8b | 3 | protected void processKeyEvent(KeyEvent ke) {
int kc = ke.getKeyCode();
if (ke.isShiftDown()) {
speed = HYPER;
rotAmount = Math.PI / 60.0;
} else {
speed = NORMAL;
rotAmount = Math.PI / 120.0;
}
if (ke.isAltDown()) {
altTransform(kc);
} else {
if (ke.isControlDown()) {
controlTransform(kc);
} else {
standardTransform(kc);
}
}
} |
367e98bc-9b01-43f8-922a-2f6977887418 | 5 | private static Region getBestNeighborRegion(Region missingRegion, ExpansionDecisions madeExpansionDecisions,
BotState state, SuperRegion superRegion) {
List<Region> ownedNeighbors = missingRegion.getOwnedNeighbors(state);
int maximumIdleArmies = 0;
// First calculate the maximum amount of armies of an owned neighbor.
for (Region ownedNeighbbor : ownedNeighbors) {
int idleArmies = getOverflowIdleArmies(ownedNeighbbor, madeExpansionDecisions);
if (idleArmies > maximumIdleArmies) {
maximumIdleArmies = idleArmies;
}
}
// Second calculate the owned neighbor having the maximum amount of idle
// armies while having a minimum amount of sill missing neighbors.
int minimumMissingNeighbors = 1000;
Region out = null;
for (Region ownedNeighbor : ownedNeighbors) {
int missingNeighborRegions = getStillMissingNeighborRegions(ownedNeighbor, state, madeExpansionDecisions,
superRegion).size();
if (getOverflowIdleArmies(ownedNeighbor, madeExpansionDecisions) == maximumIdleArmies
&& missingNeighborRegions < minimumMissingNeighbors) {
out = ownedNeighbor;
minimumMissingNeighbors = missingNeighborRegions;
}
}
return out;
} |
1685b866-3b42-4853-8d0a-74c4693e78aa | 5 | private void defineRoomSums()
{//Fills in table
roomSumsFrame = new JFrame();
roomSumsTable = new JTable();
roomSumsTable_header = new String[DataBase.schoolPeriodCount*2+1];
roomSumsTable_data = new String[DataBase.rooms.length][DataBase.schoolPeriodCount*2+1];
roomSumsTable_header[0] = "Room";//First column header
for(int col = 0; col <=DataBase.schoolPeriodCount*2; col++)
{//Sets up headers by period
if(col!= 0)
roomSumsTable_header[col] = "Sem " + (int)((col-1)/DataBase.schoolPeriodCount + 1) + " Prd " +
Integer.toString(((col-1)%DataBase.schoolPeriodCount)+1);
}
for (int row = 0; row < roomSumsTable_data.length; row++) {
for (int col = 0; col < roomSumsTable_data[0].length; col++) {
if(col==0)
{
roomSumsTable_data[row][col] = DataBase.rooms[row].getType();
}
else
{//Fill with status of the room (FreeRoomCount/ExistingRoomCount)
roomSumsTable_data[row][col] = "("+
DataBase.rooms[row].numOfRooms()[(int)((col-1)/DataBase.schoolPeriodCount)][((col-1)%DataBase.schoolPeriodCount)]+
"/"+DataBase.rooms[row].getOriginalNumOfRooms() + ")";
}
}
}
roomSumsTable.setModel(new UneditableTableModel(roomSumsTable_data, roomSumsTable_header));
roomSumsTable.getColumnModel().getColumn(0).setPreferredWidth(150);
roomSumsFrame.setContentPane(new JScrollPane(roomSumsTable));
roomSumsFrame.setTitle("Number of Unused Rooms");
roomSumsFrame.pack();
roomSumsFrame.setBounds(0, 0, 900, 500);
roomSumsFrame.setLocationRelativeTo(null);
} |
6db92c77-711e-47ae-bb19-58fcdb4567ae | 7 | public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (image != null) {
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 1);
g2d.setComposite(alpha);
g2d.drawImage(image, getLocation().x + 5, getLocation().y + 5,
getWidth() - 10, getHeight() - 10, this);
}
if (invisibleConnections > 0) {
String number = String.valueOf(invisibleConnections);
int x = getLocation().x + 1;
int y = getLocation().y + getHeight() - 2;
Rectangle2D stringBouds = g2d.getFontMetrics().getStringBounds(
number, g2d);
g2d.setColor(invisibleCounterBackground);
g2d.fillRect(x, y - (int) stringBouds.getHeight() + 2,
(int) stringBouds.getWidth() + 4, (int) stringBouds
.getHeight());
g2d.setColor(invisibleCounterBorder);
g2d.drawRect(x, y - (int) stringBouds.getHeight() + 2,
(int) stringBouds.getWidth() + 4, (int) stringBouds
.getHeight());
g2d.setColor(invisibleCounterForeground);
g2d.drawString(String.valueOf(invisibleConnections), x + 3, y);
}
if (selected || mouseInside || image == null) {
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.5f);
g2d.setComposite(alpha);
g2d.setColor(iconSelectionColor);
g2d.drawRoundRect(getLocation().x, getLocation().y, getWidth() - 1,
getHeight() - 1, 5, 5);
}
if (selected) {
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.2f);
g2d.setComposite(alpha);
g2d.setColor(iconSelectionColor);
g2d.fillRoundRect(getLocation().x, getLocation().y, getWidth(),
getHeight(), 5, 5);
}
if (mouseInside) {
AlphaComposite alpha = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.1f);
g2d.setComposite(alpha);
g2d.setColor(iconSelectionColor);
g2d.fillRoundRect(getLocation().x, getLocation().y, getWidth(),
getHeight(), 5, 5);
}
} |
3e230c90-a17d-4315-b228-e5a1a135deed | 7 | @Override
public void run() {
while (!stop) {
try {
opcion = canalEntrada.readInt();
} catch (IOException e) {
System.out.println("Error al recibir comando" + e.getMessage());
}
switch (opcion) {
case 1:
break;
case 2:
System.out.println(recibirMensaje());
break;
}
synchronized (this) {
while (pause)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (stop)
break;
}
}
} |
9f9acb85-6ca2-4ff2-a892-40dadfaa460d | 8 | @Override
public boolean equals(Object object) {
if (!(object instanceof KeyedId)) {
return false;
}
KeyedId other = (KeyedId) object;
return !((this.name == null && other.name != null)
|| (this.name != null && !this.name.equals(other.name))
|| (this.uid == null && other.uid != null)
|| (this.uid != null && !this.uid.equals(other.uid)));
} |
798bdaf2-4dd4-49f1-b7f5-7db290cfcecf | 2 | public void recruited()
{
for (int i=0; i<recruits.length; ++i) {
recruits[i].updateRange();
}
for (int i=0; i<buys.length; ++i) {
buys[i].checkActive();
}
units.updateUnits();
updateResources();
} |
a2b3fc46-510b-4611-8d46-6e25cf4a9842 | 2 | public void paint(Graphics g){
super.paint(g);
if(gameover){
gameover(g);
}
else{
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.YELLOW);
g2d.fillRect(apple.getX(), apple.getY(), a_width, a_width);
g2d.setColor(Color.GREEN);
g2d.fillRect(player.getX(), player.getY(), p_width, p_width);
g2d.setColor(Color.BLACK);
for(Moveable e : enemies){
g2d.fillRect(e.getX(), e.getY(), e_width, e_width);
}
String s = "Score: " + score;
Font small = new Font("Helvetica", Font.BOLD, 32);
g2d.setFont(small);
g2d.drawString(s, 10, 30);
Toolkit.getDefaultToolkit().sync();
}
g.dispose(); //is this even necessary?
} |
3445fd0e-b81c-46c4-b817-3b8c73e166e5 | 6 | private final int jjMoveStringLiteralDfa17_0(long old1, long active1, long old2, long active2)
{
if (((active1 &= old1) | (active2 &= old2)) == 0L)
return jjStartNfa_0(15, 0L, old1, old2);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(16, 0L, active1, active2);
return 17;
}
switch(curChar)
{
case 103:
return jjMoveStringLiteralDfa18_0(active1, 0L, active2, 0x10L);
case 104:
return jjMoveStringLiteralDfa18_0(active1, 0x40000000000000L, active2, 0x40L);
case 110:
if ((active2 & 0x4L) != 0L)
return jjStopAtPos(17, 130);
break;
default :
break;
}
return jjStartNfa_0(16, 0L, active1, active2);
} |
d9a7550a-3c9c-4d98-bb72-0a460663053e | 6 | @EventHandler
public void SpiderNightVision(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getSpiderConfig().getDouble("Spider.NightVision.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getSpiderConfig().getBoolean("Spider.NightVision.Enabled", true) && damager instanceof Spider && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, plugin.getSpiderConfig().getInt("Spider.NightVision.Time"), plugin.getSpiderConfig().getInt("Spider.NightVision.Power")));
}
} |
d42f861a-8b09-4214-bfd4-24c30f8fab05 | 9 | public void connect() {
int iPort = 6667;
if (wikimediaBot == null || !wikimediaBot.isConnected()) {
try {
iPort = Integer.parseInt(port);
} catch (Exception e) {
System.out.println("IRC.java, problem parsing integer: "
+ e.getMessage());
}
String[] channels = wikimediaChannels.split(",");
if (wikimediaBot == null)
wikimediaBot = new MediawikiBot(server, iPort, nick, channels, mediawikiEnc, data, listener);
else
wikimediaBot.setValues(server, iPort, nick, channels, mediawikiEnc, data, listener);
wikimediaBot.connect();
}
if ((freenodeBot == null || !freenodeBot.isConnected()) && checkFreenodeBoxes()) {
String freenodeNick = config.getProperty("FreenodeNick");
if (freenodeNick == null || freenodeNick.trim().length() == 0)
freenodeNick = createNick();
freenodeBot = new FreenodeBot("irc.freenode.org", iPort, freenodeNick, freenodeEnc, data, listener);
joinFreenodeChannels();
freenodeBot.connect();
}
} |
77d9123b-4da3-4448-8f3e-8e8c80d48c73 | 1 | public static void filewrt() throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter wfile = new PrintWriter(fnames, "UTF-8");
for (int i=0;i<names.size();i++){
wfile.println(names.get(i));
}
wfile.close();
} |
e42d68d2-1d12-4a53-afc0-51347f34de4a | 1 | public Set equivalent(final Node node) {
Set s = (Set) equiv.get(node);
if (s == null) {
s = new HashSet(1);
s.add(node); // A node is equivalent to itself
equiv.put(node, s);
}
return s;
} |
27ec1679-7f08-4aef-974d-5236fa6ce257 | 3 | public void visitLocalVariable(String name, int index) {
if (index >= ignoreCount && index < ignoreCount + paramCount) {
if (!name.equals("arg" + currentParameter))
debugInfoPresent = true;
result.append(',');
result.append(name);
currentParameter++;
}
} |
4778df3a-d392-455c-be98-21b8d2c188c6 | 2 | void compareHypergeometric(int k, int N, int D, int n, double result) {
double p = Hypergeometric.get().hypergeometric(k, N, D, n);
double abs = Math.abs(p - result);
double diff = abs / Math.min(p, result);
if ((abs > 1E-300) && (diff > 0.00001)) throw new RuntimeException("Difference:" + diff + "\t\t" + p + " != " + result);
} |
e2d76c81-bab7-41a1-8ad1-5fa7b2d08400 | 9 | public static String readline(InputStreamReader in) {
int ch;
StringBuffer line=null;
try {
while (true) {
ch = in.read();
if (ch==-1) {
if (line==null) return null;
return line.toString();
}
if (ch==10 || ch==13) {
// eol if we read other characters, ignore if not
if (line!=null) return line.toString();
} else {
if (line==null) line=new StringBuffer();
line.append((char)ch);
}
}
} catch (IOException e) {
if (line==null) return null;
return line.toString();
}
} |
a72ef927-e75c-4447-b8f6-cf68627594a8 | 9 | public int deleteFile(final String directory, final String name) {
final String path = directory + "/" + name;
int error = 0;
final Integer fileNode = fileTable.containsKey(path) ? fileTable.get(path) : -1;
if( fileNode != null && fileNode != -1 && Utils.range(fileNode, 0, MAX_FILES) ) {
final File file = files.get(fileNode);
boolean delete_ok = true;
// assuming the file isn't null
if( file.isDir ) {
if( file.getContents().length != 0 ){
delete_ok = false;
error = ERR_NONEMPTY_DIR;
}
}
if( delete_ok ) {
fileTable.remove(path);
files.set(fileNode, null);
for(int n = 0; n < files.size(); n++) {
if( files.get(n) == null ) {
firstUnused = n;
break;
}
}
}
}
else {
error = ERR_FILE_DOES_NOT_EXIST;
}
return error;
} |
1d212a51-e307-4f5d-af3c-052f16e54a4e | 1 | public static synchronized TaskQueue getInstance() {
if (instance == null) {
instance = new TaskQueue();
}
return instance;
} |
925a6350-7716-46ba-9151-cc34ce570063 | 9 | public void fixJumping() {
if(!isRightHeld && !isLeftHeld) {
if(currentAnimation() == jumpLeft) {
setAnimation(stillLeft);
this.direction = "left";
}
if(currentAnimation() == jumpRight) {
setAnimation(stillRight);
this.direction = "right";
}
} else {
if(!this.frictionLock) {
if(isRightHeld) {
setAnimation(currRightAnim);
this.direction = "right";
} else if (isLeftHeld) {
setAnimation(currLeftAnim);
this.direction = "left";
}
} else {
//System.out.println("Do I ever get here");
if(isRightHeld) {
setAnimation(changeLeft);
this.direction = "left";
} else if (isLeftHeld) {
setAnimation(changeRight);
this.direction = "right";
}
}
}
} |
211585b8-d55d-4985-9378-94f17a943a33 | 1 | @Override
public void run() {
arr_data = Product.showAll();
data = new Object[arr_data.size()][];
for (int i = 0; i < arr_data.size(); i++) {
data[i] = arr_data.get(i).Array();
}
this.fireTableDataChanged();
} |
d2006da9-1a18-48ec-ad0f-0cf0d4908925 | 9 | @Override
public String toString() {
final StringBuffer a = new StringBuffer();
final StringBuffer b = new StringBuffer();
Element temp = pattern;
while(temp != null) {
if (temp.isSpecial) {
switch(temp.item) {
case '.':
a.append("[:ANY:]");
break;
case 'd':
a.append("[:digit:]");
break;
case 'D':
a.append("[:non-digit:]");
break;
case 's':
a.append("[:whitespace:]");
break;
case 'S':
a.append("[:non-whitespace:]");
break;
case 'w':
a.append("[:word character:]");
break;
case 'W':
a.append("[:non-word character:]");
break;
default:
a.append(temp.item);
}
} else {
a.append(temp.item);
}
b.append(temp.replacement);
temp = temp.next;
}
return "tr/" + a + "/" + b + "/";
} |
70196e05-f128-4edb-8b27-3effef40694b | 1 | @Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + averageStartsCount;
return result;
} |
73575b51-2bc7-4111-978f-6bb7cf04f01a | 0 | public int getEventId() {
return eventId;
} |
5f1282ce-b9b5-4c98-8928-d9be1145b862 | 1 | public synchronized void stageOne() {
try {
//do your work here
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
list1.add(random.nextInt(100));
} |
1f5cc96f-2f37-4c24-8b5c-ea7410eda400 | 7 | private JSONWriter append(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(string);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
704acbc2-4a4a-4da5-82c3-55957a78e67d | 8 | @Override
public int compare(Patient o1, Patient o2) {
//throw new UnsupportedOperationException("Not supported yet.");
if(o1.isPrivatpatient() == true && o2.isPrivatpatient() == false){
return -1;
}
if(o1.isPrivatpatient() == false && o2.isPrivatpatient() == true){
return +1;
}
if(o1.isPrivatpatient() == true && o2.isPrivatpatient() == true){
return 0;
}
if(o1.isPrivatpatient() == false && o2.isPrivatpatient() == false){
return 0;
}else{
return 0;
}
} |
dcd6e1c4-8e31-4c55-b232-c777d099fb10 | 9 | public String[][] getRows(String name, String[] columnNames, SortFilterState sortFilter, int start, int pageSize) {
List<String[]> result = new LinkedList<String[]>();
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
for (int i = 0; i < columnNames.length; ++i) {
sb.append(columnNames[i]);
if (i < columnNames.length - 1) {
sb.append(",");
}
}
sb.append(" FROM ");
sb.append(name);
sb.append(" WHERE 1=1 ");
for (Entry<String, String> filter : sortFilter.getFilter()) {
sb.append("AND ");
sb.append(filter.getKey());
sb.append(" LIKE '%");
sb.append(filter.getValue());
sb.append("%' ");
}
Entry<String, Sort> sort = sortFilter.getSort();
if (sort != null) {
sb.append("ORDER BY " + sort.getKey());
sb.append(sort.getValue() == Sort.ASC ? " ASC" : " DESC");
}
String query = sb.toString();
query = String.format(
"SELECT * FROM (SELECT x0.*, ROWNUM as rnum FROM (%s) x0) WHERE rnum >= %s AND rnum < %s", sb, start, start + pageSize);
Statement st = null;
try {
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String[] row = new String[columnNames.length];
for (int i = 1; i < columnNames.length + 1; ++i) {
row[i - 1] = rs.getString(i);
}
result.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result.toArray(new String[][]{{}});
} |
022d6a65-9a02-408f-bbdd-3b577f0eaf8c | 4 | public void writeKnownAttributes(GrowableConstantPool gcp,
DataOutputStream output) throws IOException {
if (lvt != null) {
output.writeShort(gcp.putUTF8("LocalVariableTable"));
int count = lvt.length;
int length = 2 + 10 * count;
output.writeInt(length);
output.writeShort(count);
for (int i = 0; i < count; i++) {
output.writeShort(lvt[i].start.getAddr());
output.writeShort(lvt[i].end.getAddr() + lvt[i].end.getLength()
- lvt[i].start.getAddr());
output.writeShort(gcp.putUTF8(lvt[i].name));
output.writeShort(gcp.putUTF8(lvt[i].type));
output.writeShort(lvt[i].slot);
}
}
if (lnt != null) {
output.writeShort(gcp.putUTF8("LineNumberTable"));
int count = lnt.length;
int length = 2 + 4 * count;
output.writeInt(length);
output.writeShort(count);
for (int i = 0; i < count; i++) {
output.writeShort(lnt[i].start.getAddr());
output.writeShort(lnt[i].linenr);
}
}
} |
e7dc61d9-de45-461f-a54d-0506b79bccc0 | 7 | private static boolean getIsCreateFromConsole() throws CancelOperationException {
String[] options = { "Create a new queue in the system.", "Delete an existing queue from the system."};
final StringBuilder builder = new StringBuilder("Please enter the number of the option to continue:\n");
// Prints each line in the main menu
for (int i = 0; i < options.length; i++) {
builder.append(String.format(MENU_ITEM_FORMAT_STRING, i + 1, options[i]));
}
System.out.println(builder.toString());
// Get the response
boolean validInput;
int result = -1;
do {
validInput = true;
System.out.print("Selection: ");
try {
String input = in.nextLine();
// Check if the input signifies a return to the main menu
if (isReturnToMainMenu(input)) {
throw new CancelOperationException();
}
result = Integer.parseInt(input);
if (result < 1 || result > options.length) {
throw new NumberFormatException("Input outside of range.");
}
} catch (NumberFormatException ex) {
System.out.println("Invalid entry, please re-enter your selection.");
validInput = false;
}
} while (!validInput);
return result == 1 ? true : false;
} |
469d927c-2a39-40d2-90b1-fa73fc093ea5 | 2 | private void trackListGenerator(Object[] inpista) {
//Recibe un arreglo y crea una lista de pistas vacias y su archivo .gdb
tracksList.clear();
String location = ruta + "\\GameData\\Locations";
for (Object pista : inpista) {
String fileMask = pista.toString();
String fileLocation = Track.findFile(location, fileMask);
if(fileLocation!=null) {
Track track = new Track();
track.setFileLocation(fileLocation);
tracksList.add(track);
}
}
} |
57ae49ee-d604-4814-86c8-bc6e09645dcc | 6 | public void paint(Graphics g2) {
Controls.setTile(getTile());
Graphics2D g = (Graphics2D) g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (map != null) {
g.scale(scale, scale);
g.drawImage(map, mapLoc.x, mapLoc.y, null);
getTile().draw(g, mapLoc, Color.white);
g.scale(1 / scale, 1 / scale);
if (areaSelected) {
g.setColor(Color.white);
g.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.5f));
Polygon area = new Polygon();
if (TILES.size() == 2) {
int x1 = TILES.get(0).getScaledGX(mapLoc, scale);
int y1 = TILES.get(0).getScaledGY(mapLoc, scale);
int x2 = TILES.get(1).getScaledGX(mapLoc, scale);
int y2 = TILES.get(1).getScaledGY(mapLoc, scale);
area.addPoint(x1, y1);
area.addPoint(x2, y1);
area.addPoint(x2, y2);
area.addPoint(x1, y2);
} else {
for (MapTile t : TILES) {
area.addPoint(t.getScaledGX(mapLoc, scale), t.getScaledGY(mapLoc, scale));
}
}
g.fill(area);
g.setColor(Color.black);
g.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 1.0f));
} else {
for (int i = 1; i < TILES.size(); i++) {
MapTile.drawLineBetween(g, mapLoc, scale, TILES.get(i - 1), TILES.get(i));
}
}
for (MapTile t : TILES) {
t.drawInScale(g, mapLoc, Color.red, scale);
}
}
} |
f1f4891b-fa2b-4d85-8223-ed29e7199f15 | 2 | public void copyRegionHFlip(CPRect r, CPLayer source) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(r);
for (int j = rect.top; j < rect.bottom; j++) {
for (int i = rect.left, s = rect.right - 1; i < rect.right; i++, s--) {
data[i + j * width] = source.data[s + j * width];
}
}
} |
4852b8c6-1c7a-461c-8bde-957d75e53317 | 4 | /*Update Username*/public boolean changeUsername(String username, String newUsername){
try{
if(newUsername.length() > 40)return false;
if(username.length() > 40) return false;
select1.setString(1, newUsername);
ResultSet rs = select1.executeQuery();
if(rs.next())return false;
updateUsername.setString(1, newUsername);
updateUsername.setString(2, username);
updateUsername.executeUpdate();
return true;
}catch(Exception e){e.printStackTrace();}
return false;
} |
1ac6f628-b90b-4dd6-8ca6-5f85cd75a680 | 4 | @Override
public void run() {
System.out.println("UserHandler thread started");
String hours = new SimpleDateFormat("HH").format(Calendar.getInstance().getTime());
String minutes = new SimpleDateFormat("mm").format(Calendar.getInstance().getTime());
String seconds = new SimpleDateFormat("ss").format(Calendar.getInstance().getTime());
String millis = new SimpleDateFormat("SSS").format(Calendar.getInstance().getTime());
String curTime = hours + "_" + minutes + "_" + seconds + "_" + millis;
log("Started at: " + curTime);
log("Starting the main loop");
while (!terminated) {
performedOperations++;
//System.out.println("[com.user.UserHandler]: Gonna send some.");
int num = random.nextInt(users.size() + 1);
switch (num) {
case 0: {
if (users.size() < maxUsers) {
createOperations++;
User user = new User("Peter");
users.add(user);
BankRequest bankRequest = new BankRequest(user, BankRequest.OPERATION_CREATE_ACCOUNT, 0);
bank.makeRequest(bankRequest);
}
break;
}
default: {
User user = users.get(num - 1);
BankRequest bankRequest;
if (num % 2 == 0) {
creditOperations++;
bankRequest = new BankRequest(user, BankRequest.OPERATION_CREDIT, (num * 100) % 64);
} else {
depositOperations++;
bankRequest = new BankRequest(user, BankRequest.OPERATION_DEPOSIT, (num * 100) % 64);
}
bank.makeRequest(bankRequest);
break;
}
}
}
hours = new SimpleDateFormat("HH").format(Calendar.getInstance().getTime());
minutes = new SimpleDateFormat("mm").format(Calendar.getInstance().getTime());
seconds = new SimpleDateFormat("ss").format(Calendar.getInstance().getTime());
millis = new SimpleDateFormat("SSS").format(Calendar.getInstance().getTime());
curTime = hours + "_" + minutes + "_" + seconds + "_" + millis;
log("Terminated at: " + curTime);
// Telling the bank that we are done sending requests
//bank.reportRequestsEnded();
// Creating a LopPackage for Main
LogPackage logPackage = new LogPackage(performedOperations, createOperations, creditOperations,
depositOperations);
Main.uhAnalytics = logPackage;
log.nextLine();
log("Analytics:");
log("Performed operations", performedOperations);
log("Create operations", createOperations);
log("Credit operations", creditOperations);
log("Deposit operations", depositOperations);
log.nextLine();
log("Terminating");
/*
System.out.println("[com.user.UserHandler] Performed operations: " + performedOperations);
System.out.println("[com.user.UserHandler] Create operations: " + createOperations);
System.out.println("[com.user.UserHandler] Credit operations: " + creditOperations);
System.out.println("[com.user.UserHandler] Deposit operations: " + depositOperations);
System.out.println("[com.user.UserHandler] Users size: " + users.size());
System.out.println("[com.user.UserHandler]: Terminated");
*/
log.terminate();
System.out.println("UserHandler thread terminated");
} |
390a188c-c05e-4fb0-8178-cfbd454ba160 | 0 | public String getComponentTitle() {
return "Multiple Runs";
} |
cccede0f-120e-43dd-a6db-d66c25b089f2 | 6 | private static String stringify(final InputStream inputStream) {
if (inputStream == null) {
return "";
}
try {
int ichar;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (;;) {
ichar = inputStream.read();
if (ichar < 0) {
break;
}
baos.write(ichar);
}
return baos.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
442f2185-c8c4-4508-9a8a-e8eccfe07ad5 | 5 | public static LocaleCode getByLocale(Locale locale)
{
if (locale == null)
{
return null;
}
// Locale.getLanguage() returns either an empty string or
// a lower-case ISO 639 code.
String language = locale.getLanguage();
// Locale.getCountry() returns either an empty string or
// a upper-case ISO 3166-1 alphe-2 code.
String country = locale.getCountry();
if ((language == null || language.length() == 0) &&
(country == null || country.length() == 0))
{
return LocaleCode.undefined;
}
// 'language' and 'country' are already lower-case and upper-case,
// so true can be given as the third argument.
return getByCode(language, country, true);
} |
fb3814bf-cae2-443f-90b2-e2119aa4417b | 1 | public List<double[]> run(File image) {
if (!image.exists())
return new LinkedList<double[]>();
descriptor.run(ImageProcessorFactory.newProcessor(image));
return descriptor.getFeatures();
} |
baf9a62e-5717-4e7e-b77b-c0bdda9b7de8 | 6 | public final void spawnBlockParticles(Level level, int x, int y, int z, int side,
ParticleManager particleManager) {
float offset = 0.1F;
float var8 = x + random.nextFloat() * (minX - maxX - offset * 2F) + offset + maxX;
float var9 = y + random.nextFloat() * (minY - maxY - offset * 2F) + offset + maxY;
float var10 = z + random.nextFloat() * (minZ - maxZ - offset * 2F) + offset + maxZ;
if (side == 0) {
var9 = y + maxY - offset;
}
if (side == 1) {
var9 = y + minY + offset;
}
if (side == 2) {
var10 = z + maxZ - offset;
}
if (side == 3) {
var10 = z + minZ + offset;
}
if (side == 4) {
var8 = x + maxX - offset;
}
if (side == 5) {
var8 = x + minX + offset;
}
particleManager.spawnParticle(new TerrainParticle(
level, var8, var9, var10, 0F, 0F, 0F, this).setPower(0.2F).scale(0.6F));
} |
1757a1e8-f0ee-4f14-972d-a837cb1b10ae | 9 | @Override
public Subtitles parse(InputStream inputStream, String charset, double fps)
throws UnsupportedSubtitlesFormatException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream,
charset));
Subtitles subtitles = new Subtitles(fps);
String line;
while ((line = reader.readLine()) != null) {
if (line.equals("") || line.matches("\\s*"))
continue;
if (!line.matches("\\[\\d*\\]\\[\\d*\\].*"))
throw new UnsupportedSubtitlesFormatException(line);
ArrayList<String> lines = new ArrayList<String>();
String frameFromString = line.substring(1, line.indexOf("]"));
if (frameFromString.equals(""))
frameFromString = "0";
int frameFrom = Integer.parseInt(frameFromString);
line = line.substring(line.indexOf("]") + 1);
String frameToString = line.substring(1, line.indexOf("]"));
if (frameToString.equals(""))
frameToString = "0";
int frameTo = Integer.parseInt(frameToString);
line = line.substring(line.indexOf("]") + 1);
for (String subline : line.split("\\|"))
lines.add(subline);
subtitles.addSubtitle(new Subtitle(frameFrom * 100,
frameTo * 100, lines));
}
return subtitles;
} catch (FileNotFoundException e) {
Global.getInstance().getLogger().warning(e.toString());
e.printStackTrace();
} catch (IOException e) {
Global.getInstance().getLogger().warning(e.toString());
e.printStackTrace();
}
return null;
} |
67f416ba-d361-40d7-91c5-fda649e92e6c | 5 | private void postPlugin(boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
@SuppressWarnings("deprecation")
int playersOnline = Bukkit.getServer().getOnlinePlayers().length;
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
final StringBuilder data = new StringBuilder();
// The plugin's description file containg all of the plugin data such as name, version, author, etc
data.append(encode("guid")).append('=').append(encode(guid));
encodeDataPair(data, "version", pluginVersion);
encodeDataPair(data, "server", serverVersion);
encodeDataPair(data, "players", Integer.toString(playersOnline));
encodeDataPair(data, "revision", String.valueOf(REVISION));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
encodeDataPair(data, "osname", osname);
encodeDataPair(data, "osarch", osarch);
encodeDataPair(data, "osversion", osversion);
encodeDataPair(data, "cores", Integer.toString(coreCount));
encodeDataPair(data, "online-mode", Boolean.toString(onlineMode));
encodeDataPair(data, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
encodeDataPair(data, "ping", "true");
}
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, encode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
connection.setDoOutput(true);
// Write the data
final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data.toString());
writer.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
final String response = reader.readLine();
// close resources
writer.close();
reader.close();
if (response == null || response.startsWith("ERR")) {
throw new IOException(response); //Throw the exception
}
} |
394a6b3c-54b0-4494-aec6-580d1298e7d8 | 3 | private void validateFileName(String fileName) throws InvalidFileException {
Pattern pattern = Pattern.compile(FILE_NAME_REGEXP);
Matcher matcher = pattern.matcher(fileName);
if (matcher.matches()) {
File file = new File(fileName);
if (!file.exists() || file.isDirectory())
throw new InvalidFileException("File is not exists.");
} else
throw new InvalidFileException("Incorrect file name.");
} |
9b810516-49e5-4a03-9c41-034fce1b0074 | 7 | @EventHandler
public void onPlayerChat(final AsyncPlayerChatEvent e) {
String msg = e.getMessage();
msg = ChatColor.translateAlternateColorCodes('&', msg);
String newMsg = msg;
if (plugin.getConfig().getBoolean("Tagging")) {
if (inCooldown.contains(e.getPlayer())) {
e.getPlayer()
.sendMessage(
ChatColor.RED
+ "Du musst "
+ plugin.getConfig().getInt(
"TagCooldown")
+ " Sekunden warten bevor du wieder taggen darfst!");
e.setCancelled(true);
return;
}
for (Player p : Bukkit.getOnlinePlayers()) {
if (msg.contains("@" + p.getName())) {
inCooldown.add(e.getPlayer());
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
new Runnable() {
@Override
public void run() {
inCooldown.remove(e.getPlayer());
}
}, plugin.getConfig().getInt("TagCooldown") * 20);
String nmsg = msg.replace(
"@" + p.getName(),
plugin.getConfig().getString("TagColor") + "@"
+ p.getName()
+ ChatColor.getLastColors(msg));
nmsg = ChatColor.translateAlternateColorCodes('&', nmsg);
Utilities.playTagSound(p);
newMsg = nmsg;
}
}
}
if (!plugin.getConfig().getBoolean("ReplaceSymbols"))
return;
List<String> symbols = plugin.getConfig().getStringList("Symbols");
for (String str : symbols) {
String toReplace = str.split(",")[0];
String symbol = str.split(",")[1];
symbol = ChatColor.translateAlternateColorCodes('&', symbol);
if (msg.contains(toReplace)) {
newMsg = newMsg.replace(toReplace, symbol);
}
}
e.setMessage(newMsg);
} |
564ce12d-2436-46c1-acec-d7221b510982 | 1 | public NetworkUtils(String address, int port, String message){
try {
this.ipaddress = InetAddress.getByName(address);
this.port = port;
this.message = message;
} catch (UnknownHostException e) {
Bukkit.getLogger().severe("Can not connect to host, did you use the correct address?");
}
} |
3fc5fab8-d4f2-4971-8b02-c11cb6939986 | 5 | private double[][] createEmptyValueGrid(GeoParams geoParams, Operator operator) {
double delta_y = Math.abs(geoParams.geoBoundNW.latitude - geoParams.geoBoundSE.latitude);
double delta_x;
if (geoParams.geoBoundNW.longitude > geoParams.geoBoundSE.longitude) {
//We've wrapped around from 180 to -180,
delta_x = 360-(geoParams.geoBoundNW.longitude+geoParams.geoBoundSE.longitude);
} else {
delta_x = Math.abs(geoParams.geoBoundNW.longitude - geoParams.geoBoundSE.longitude);
}
int x_width = (int) Math.round(delta_x/geoParams.geoResolutionX);
int y_width = (int) Math.round(delta_y/geoParams.geoResolutionY);
double[][] valueGrid = new double[x_width][y_width];
if (operator.equals(Operator.MAX)) {
for (int i=0; i<x_width; i++) {
Arrays.fill(valueGrid[i], Integer.MIN_VALUE);
}
}
if (operator.equals(Operator.MIN)) {
for (int i=0; i<x_width; i++) {
Arrays.fill(valueGrid[i], Integer.MAX_VALUE);
}
}
return valueGrid;
} |
c7dc80e6-5558-4f5d-ba3c-8771950599c3 | 8 | public static SortedDocValues wrap(SortedSetDocValues sortedSet, Type selector) {
if (sortedSet.getValueCount() >= Integer.MAX_VALUE) {
throw new UnsupportedOperationException("fields containing more than " + (Integer.MAX_VALUE-1) + " unique terms are unsupported");
}
SortedDocValues singleton = DocValues.unwrapSingleton(sortedSet);
if (singleton != null) {
// it's actually single-valued in practice, but indexed as multi-valued,
// so just sort on the underlying single-valued dv directly.
// regardless of selector type, this optimization is safe!
return singleton;
} else if (selector == Type.MIN) {
return new MinValue(sortedSet);
} else {
if (sortedSet instanceof RandomAccessOrds == false) {
throw new UnsupportedOperationException("codec does not support random access ordinals, cannot use selector: " + selector + " docValsImpl: " + sortedSet.toString());
}
RandomAccessOrds randomOrds = (RandomAccessOrds) sortedSet;
switch(selector) {
case MAX: return new MaxValue(randomOrds);
case MIDDLE_MIN: return new MiddleMinValue(randomOrds);
case MIDDLE_MAX: return new MiddleMaxValue(randomOrds);
case MIN:
default:
throw new AssertionError();
}
}
} |
f0d80d2c-8422-4fe9-84b8-85745ace3eb9 | 1 | public void addUniform(String uniform){
int uniformLocation = glGetUniformLocation(program,uniform);
if (uniformLocation == 0xFFFFFFFF){
System.err.println("Could not find uniform: " + uniform);
new Exception().printStackTrace();
System.exit(1);
}
uniforms.put(uniform,uniformLocation);
} |
a7bae526-7140-4218-a66b-ffe0220b0557 | 3 | @Override
public void deserialize(Buffer buf) {
cellId = buf.readShort();
if (cellId < 0 || cellId > 559)
throw new RuntimeException("Forbidden value on cellId = " + cellId + ", it doesn't respect the following condition : cellId < 0 || cellId > 559");
objectGID = buf.readShort();
if (objectGID < 0)
throw new RuntimeException("Forbidden value on objectGID = " + objectGID + ", it doesn't respect the following condition : objectGID < 0");
} |
2d8ab1aa-a8e8-467f-8c0c-45292dddcd46 | 2 | public static void main(String[] args) throws Exception {
System.out.println("==== Menu =====");
System.out.println("1. Serveur");
System.out.println("2. Client");
String str = sc.nextLine();
int value = Integer.parseInt(str);
switch (value) {
case 1:
new Serveur().createServeur();
break;
case 2:
new Client().createClient();
break;
default:
throw new Exception("Entree utilisateur invalide");
}
} |
186cb73e-f04e-4bf5-bcc9-8e923ae2660d | 6 | @Override
public boolean eval(Critter c) {
// TODO implement me!
// returns the boolean value of this condition for Critter c
if (op.toString().equals("<"))
return left.eval(c) < right.eval(c);
else if (op.toString().equals("<="))
return left.eval(c) <= right.eval(c);
else if (op.toString().equals("="))
return left.eval(c) == right.eval(c);
else if (op.toString().equals(">"))
return left.eval(c) > right.eval(c);
else if (op.toString().equals(">="))
return left.eval(c) >= right.eval(c);
else if (op.toString().equals("!="))
return left.eval(c) != right.eval(c);
else
System.out.println("Error in Comparison");
return true;
} |
996158d3-1e65-47bc-a0ab-f4ab059879f8 | 8 | @EventHandler
public void receivePluginMessage( PluginMessageEvent event ) throws IOException, SQLException {
if ( event.isCancelled() ) {
return;
}
if ( !( event.getSender() instanceof Server ) )
return;
if ( !event.getTag().equalsIgnoreCase( "BSHomes" ) ) {
return;
}
event.setCancelled( true );
DataInputStream in = new DataInputStream( new ByteArrayInputStream( event.getData() ) );
String task = in.readUTF();
if ( task.equals( "DeleteHome" ) ) {
HomesManager.deleteHome( in.readUTF(), in.readUTF() );
} else if ( task.equals( "SendPlayerHome" ) ) {
HomesManager.sendPlayerToHome( PlayerManager.getPlayer( in.readUTF() ), in.readUTF() );
} else if ( task.equals( "SetPlayersHome" ) ) {
HomesManager.createNewHome( in.readUTF(), in.readInt(), in.readInt(), in.readUTF(), new Location( ( ( Server ) event.getSender() ).getInfo().getName(), in.readUTF(), in.readDouble(), in.readDouble(), in.readDouble(), in.readFloat(), in.readFloat() ) );
} else if ( task.equals( "GetHomesList" ) ) {
HomesManager.listPlayersHomes( PlayerManager.getPlayer( in.readUTF() ) );
} else if ( task.equals( "SendVersion" ) ) {
LoggingManager.log( in.readUTF() );
}
in.close();
} |
ee058dbc-5151-4cc5-b58e-c731853c41d4 | 5 | private boolean isStatement() {
return peekTypeMatches("RETURN") || peekTypeMatches("ID")
|| peekTypeMatches("IF") || peekTypeMatches("WHILE")
|| peekTypeMatches("FOR") || peekTypeMatches("BREAK");
} |
5c71db2b-8832-4315-92fc-2d1fcd9070e3 | 9 | private static boolean isPrimitiveEquivalent(Class<?> primitive, Class<? extends Object> aClass) {
if (primitive == int.class
|| primitive == long.class
|| primitive == float.class
|| primitive == double.class) {
return (aClass == Integer.class
|| aClass == Long.class
|| aClass == Float.class
|| aClass == Double.class);
}
return false;
} |
b55d5c5a-dd54-4c25-8d39-1c2212e1d06d | 0 | @Override
public void rotate(int angle)
{
super.rotate(angle,center);
setColoredExes();
} |
2ed83a5a-b624-4d0e-b431-94d4e7ee4179 | 2 | public static boolean isQualified(){
//if (shopList = 0) return false; //@todo should check the size of shopList
if (isSorted) return true;
if (shopListArr.length <= maxShopListSize) return true;
return false;
} |
cd01069c-ce53-4cad-afbd-32e2c9ed0c1a | 1 | public void setForegroundColor( Color foregroundColor ) {
if( foregroundColor == null ) {
throw new IllegalArgumentException( "foregroundColor must not be null" );
}
this.foregroundColor = foregroundColor;
regraph();
} |
5375c82a-6db7-4a94-a64e-2f3c9b42e13d | 4 | public void count() {
genome = snpEffectPredictor.getGenome();
readLengthSum = 0;
readLengthCount = 0;
// Iterate over all BAM/SAM files
try {
if (verbose) Timer.showStdErr("Reading file '" + fileName + "'");
countReads = new CountByKey<Marker>();
countBases = new CountByKey<Marker>();
countTypes = new CountByType();
coverageByType = new CoverageByType();
countFile(fileName);
} catch (Exception e) {
e.printStackTrace();
}
if (verbose) {
System.err.println("");
Timer.showStdErr("Finished reding file " + fileName + "\n\tTotal reads: " + countTotalReads);
}
if (verbose) Timer.showStdErr("Done.");
} |
e15c7399-0c24-4a9e-a7bf-72850fc8d4d3 | 1 | protected int findColumnStrict(CycVariable col) throws IllegalArgumentException {
if (col == null) {
throw new IllegalArgumentException("Got null column name.");
}
return findColumnStrict(col.toString());
} |
7ff245f9-81e1-435b-aa6e-fed0f3e7546a | 3 | public static List<String> topDown (List<Character> s) {
// trivial case
if ( s.size() == 2 ) {
String s1 = new String(new char[]{s.get(0), s.get(1)});
String s2 = new String(new char[]{s.get(1), s.get(0)});
ArrayList<String> al = new ArrayList<>();
al.add(s1);
al.add(s2);
return al;
}
List<String> ret = new ArrayList<>();
for ( Character c : s ) {
List<Character> dup = new ArrayList<>(s);
dup.remove(c);
List<String> l = topDown( dup );
for ( String str : l) {
ret.add( str + c );
}
}
return ret;
} |
72ad8e66-cdc3-48fc-8df3-2dfb440adf2a | 0 | public File getFile() {
return _file;
} |
2d54a3ae-69b0-470a-b612-2bd1ac764fe4 | 4 | public Othello() {
super(GAME_WIDTH, GAME_HEIGHT);
boolean test = false;
if (test || m_test) {
System.out.println("Othello :: Othello() BEGIN");
}
if (test || m_test) {
System.out.println("Othello :: Othello() END");
}
} |
93ca1fcf-c614-42a2-8b8d-cd50f8dbc36a | 6 | public void quickS(int low, int high) {
int mid = (low + high) / 2;
int left = low;
int right = high;
int pivot = arrA[mid]; // select middle element as pivot
while (left <= right) {
while (arrA[left] < pivot)
left++;// find element which is greater than pivot
while (arrA[right] > pivot)
right--;// //find element which is smaller than pivot
// System.out.println(arrA[left] + " " + pivot + " " + arrA[right]
// );
// if we found the element on the left side which is greater than
// pivot
// and element on the right side which is smaller than pivot
// Swap them, and increase the left and right
if (left <= right) {
int temp = arrA[left];
arrA[left] = arrA[right];
arrA[right] = temp;
left++;
right--;
}
}
// Recursion on left and right of the pivot
if (low < right)
quickS(low, right);
if (left < high)
quickS(left, high);
} |
a8dc771c-ff7d-4152-85af-8f98df03e3f0 | 3 | public void updateObjects(int deltaTime) {
// Draws settings Menu if necessary
if (getIsDrawingSettingsMenu()) {
drawSettingsMenu();
}
// Update ImageButtons
for (ImageButton obj : screenObjects) {
obj.update(deltaTime);
}
// Update LoopMenu if necessary
if (loopMenu != null) {
loopMenu.update(deltaTime);
}
} |
f894c56a-f607-45a4-ba7c-c7c146b10eba | 7 | public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof BiCopiesarticlesId) ) return false;
BiCopiesarticlesId castOther = ( BiCopiesarticlesId ) other;
return (this.getNoArticle()==castOther.getNoArticle())
&& ( (this.getIsbn()==castOther.getIsbn()) || ( this.getIsbn()!=null && castOther.getIsbn()!=null && this.getIsbn().equals(castOther.getIsbn()) ) );
} |
545e783a-0c86-4ff4-90b4-78cff6020cf0 | 1 | public String bitrate_string()
{
if (h_vbr == true)
{
return Integer.toString(bitrate()/1000)+" kb/s";
}
else return bitrate_str[h_version][h_layer - 1][h_bitrate_index];
} |
a2a0dab7-4554-447e-99bf-8b582c7987e8 | 5 | public StorageDatabase() {
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File root = Constants.getRoot();
File databaseLocation = new File(root,"storageDatabase");
String path = null;
try {
path = databaseLocation.getCanonicalPath();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
throw new RuntimeException(e2);
}
try {
databaseConn = DriverManager.getConnection("jdbc:h2:" + path + ";ifexists=true","","");
} catch (SQLException e) {
// Database does not already exist
try {
databaseConn = DriverManager.getConnection("jdbc:h2:" + path,"","");
initializeDatabase();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
try {
addFile = databaseConn.prepareStatement("INSERT INTO FileList VALUES ( ?, ? ,?, ?)");
printAllFiles = databaseConn.prepareStatement("SELECT * FROM FileList");
findFileWithTime = databaseConn.prepareStatement("SELECT * FROM FileList WHERE (? BETWEEN StartTime AND EndTime) OR (? BETWEEN StartTime AND EndTime) OR (StartTime BETWEEN ? AND ?) ");
clearAll = databaseConn.prepareStatement("DELETE FROM FileList");
updateEndTime = databaseConn.prepareStatement("UPDATE FileList SET EndTime = ?, Length = ? WHERE FileName =? ");
getFileInfo = databaseConn.prepareStatement("SELECT * FROM FileList WHERE FileName = ?");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} |
a3ffcdc8-1636-41b7-a70a-a035bb3b969b | 8 | public static void main(String[] args) throws Exception {
if (args.length != 9) {
System.err
.print("Syntax error. Correct syntax:\n"
+ " <trainfile_supervised> <trainfile_semisupervised> "
+ " <testset>"
+ "<supervised_weight> <observation_feature> <state_feature> "
+ "<modelfile> <numiterations> <seed>\n");
System.exit(1);
}
int arg = 0;
String trainFileNameS = args[arg++];
String trainFileNameSS = args[arg++];
String testFileName = args[arg++];
double weightS = Double.parseDouble(args[arg++]);
String observationFeatureLabel = args[arg++];
String stateFeatureLabel = args[arg++];
String modelFileName = args[arg++];
int numIterations = Integer.parseInt(args[arg++]);
int seed = Integer.parseInt(args[arg++]);
System.out.println(String.format(
"Parameters:\n"
+ "\tSupervised train file: %s\n"
+ "\tSemi-supervised train file: %s\n"
+ "\tTest file: %s\n" + "\tSupervised weight: %f\n"
+ "\tObservation feature: %s\n"
+ " State feature: %s\n" + "\tModel file: %s\n"
+ " # iterations: %d\n" + "\tSeed: %d\n",
trainFileNameS, trainFileNameSS, testFileName, weightS,
observationFeatureLabel, stateFeatureLabel, modelFileName,
numIterations, seed));
if (seed > 0)
RandomGenerator.gen.setSeed(seed);
// State labels from the initial model.
String[] stateFeaturesV = { "0", "B-PER", "I-PER", "B-LOC", "I-LOC",
"B-ORG", "I-ORG", "B-MISC", "I-MISC" };
// Load the first trainset (supervised).
Corpus trainsetS = new Corpus(trainFileNameS);
int size1 = trainsetS.getNumberOfExamples();
// Load the second trainset (semi-supervised).
Corpus trainsetSS = new Corpus(trainFileNameSS,
trainsetS.getFeatureValueEncoding());
int size2 = trainsetSS.getNumberOfExamples();
// Join the two datasets.
trainsetS.add(trainsetSS);
trainsetSS = null;
// Create and fill the weight vector.
Vector<Object> weights = new Vector<Object>(size1 + size2);
weights.setSize(size1 + size2);
int idxExample = 0;
for (; idxExample < size1; ++idxExample)
weights.set(idxExample, weightS);
for (; idxExample < size1 + size2; ++idxExample)
weights.set(idxExample, 1.0);
// Supervised train an initial model on the joined dataset.
WeightedHmmTrainer wHmmTrainer = new WeightedHmmTrainer();
wHmmTrainer.setWeights(weights);
HmmModel modelSupervised = wHmmTrainer.train(trainsetS,
observationFeatureLabel, stateFeatureLabel, "0");
// Fill the tagged flag vector.
Vector<Object> flags = new Vector<Object>(size1 + size2);
// All examples in the first dataset are flagged as tagged.
idxExample = 0;
for (; idxExample < size1; ++idxExample)
flags.add(new Boolean(true));
// The tokens tagged different of 0 are flagged as tagged. The rest are
// flagged as untagged.
for (; idxExample < size1 + size2; ++idxExample) {
DatasetExample example = trainsetS.getExample(idxExample);
Vector<Boolean> flagsEx = new Vector<Boolean>(example.size());
for (int token = 0; token < example.size(); ++token) {
if (example.getFeatureValueAsString(token, stateFeatureLabel)
.equals("0"))
flagsEx.add(false);
else
flagsEx.add(true);
}
flags.add(flagsEx);
}
// Test file.
Corpus testset = new Corpus(testFileName,
trainsetS.getFeatureValueEncoding());
// Train an HMM model.
SemiSupervisedHmmTrainer ssHmmTrainer = new SemiSupervisedHmmTrainer();
ssHmmTrainer.setTuningSet(testset);
ssHmmTrainer.setTaggedExampleFlags(flags);
ssHmmTrainer.setWeights(weights);
ssHmmTrainer.setInitialModel(modelSupervised);
HmmModel model = ssHmmTrainer.train(trainsetS, observationFeatureLabel,
stateFeatureLabel, stateFeaturesV, numIterations);
// Save the model.
model.save(modelFileName);
} |
def91104-21b6-47c5-a6dd-2277bd428210 | 7 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IpEntity ipEntity = (IpEntity) o;
if (ip != null ? !ip.equals(ipEntity.ip) : ipEntity.ip != null) return false;
if (urlMap != null ? !urlMap.equals(ipEntity.urlMap) : ipEntity.urlMap != null) return false;
return true;
} |
89dce42d-4802-4734-96d9-78e4c1cc12dc | 5 | @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 Link)) {
return false;
}
Link other = (Link) object;
if ((this.codlink == null && other.codlink != null) || (this.codlink != null && !this.codlink.equals(other.codlink))) {
return false;
}
return true;
} |
ef0ef25c-67e3-4fc8-85cf-19517aee6a4d | 1 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==questionDeleteButton) {
this.setVisible(false);
this.getParent().remove(this);
this.invalidate();
}
} |
0db2c38a-c06d-41e5-870c-1ee8eed21722 | 5 | private void unfilter(byte[] curLine, byte[] prevLine) throws IOException {
switch (curLine[0]) {
case 0: // none
break;
case 1:
unfilterSub(curLine);
break;
case 2:
unfilterUp(curLine, prevLine);
break;
case 3:
unfilterAverage(curLine, prevLine);
break;
case 4:
unfilterPaeth(curLine, prevLine);
break;
default:
throw new IOException("invalide filter type in scanline: " + curLine[0]);
}
} |
99ca8e55-0846-467b-a857-25b9143c25df | 7 | public ArrayList<Boolean> CreateAgendaSlotStatus(){
ArrayList<Boolean> result = new ArrayList<Boolean>();
int hour1,hour2,duration;
boolean overlapTasksExist = false;
for (int i = 0; i < 25; i++) {
result.add(true);
}
for (int i=0; i<currDateTask.size(); i++){
if(Character.isDigit(currDateTask.get(i).charAt(1))){
hour1 = Integer.valueOf(currDateTask.get(i).substring(1, 3));
if (!result.get(hour1)) {
overlapTasksExist = true;
}
if (Character.isDigit(currDateTask.get(i).charAt(6)))
hour2 = Integer.valueOf(currDateTask.get(i).substring(6, 8));
else
hour2 = hour1 + 1;
duration = hour2 - hour1;
for(int j=hour1; j<duration+hour1; j++){
result.set(j,false);
}
}
}
if (overlapTasksExist) {
WarningPopUp.infoBox(OVERLAP_TASKS_AGENDA, WARNING);
GUI.agendaOff();
}
return result;
} |
d400c630-1f00-47d5-bc8e-d535a5d1d7a0 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GraphGenericNode<?> other = (GraphGenericNode<?>) obj;
if (Data == null) {
if (other.Data != null)
return false;
} else if (!Data.equals(other.Data))
return false;
return true;
} |
f7b1d377-a457-48ff-9dbc-650f5ce11d87 | 4 | public synchronized T checkOut() {
long now = System.currentTimeMillis();
T t;
if (unlocked.size() > 0) {
Enumeration<T> e = unlocked.keys();
while (e.hasMoreElements()) {
t = e.nextElement();
if ((now - unlocked.get(t)) > expirationTime) {
// object has expired
unlocked.remove(t);
expire(t);
t = null;
} else {
if (validate(t)) {
unlocked.remove(t);
locked.put(t, now);
return (t);
} else {
// object failed validation
unlocked.remove(t);
expire(t);
t = null;
}
}
}
}
// no objects available, create a new one
t = create();
locked.put(t, now);
return (t);
} |
96eecbb2-6673-438b-93e0-9d86b0d9d342 | 1 | public void send(Message msg) {
System.out.println("Sneding message: \"" + msg.encode() + "\"");
try {
conn.send(msg.encode());
} catch (CouldNotSendPacketException e) {
System.out.println("Could not send message: " + e.getMessage());
}
} |
0e80487f-678d-40cb-b594-0f406adc2758 | 1 | private int score(int[] bowl){
int sum=0;
for(int i=0;i<12;i++){
sum+=pref[i]*bowl[i];
}
return sum;
} |
7fc21a31-a5a1-4b2a-b203-cd8de0477081 | 3 | public static String getExtension(String filename)
{
int i = filename.lastIndexOf('.');
int j = filename.lastIndexOf(File.separatorChar);
return (i > 0 && i > j && i < filename.length() - 1) ? filename
.substring(i + 1).toLowerCase() : "";
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.