text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
new Juego().setVisible(true);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Juego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
} | 3 |
public void saveProgress(boolean overwrite) {
//
// In the case of an overwrite, just save under the current file-
if (overwrite) {
PlayLoop.saveGame(fullSavePath(savesPrefix, CURRENT_SAVE)) ;
return ;
}
//
// If necessary, delete the least recent save.
if (timeStamps.size() >= MAX_SAVES) {
final String oldStamp = timeStamps.removeFirst() ;
final File f = new File(fullSavePath(savesPrefix, oldStamp)) ;
if (f.exists()) f.delete() ;
}
//
// Create a new save.
final float time = world.currentTime() / World.STANDARD_DAY_LENGTH ;
String
day = "Day "+(int) time,
hour = ""+(int) (24 * (time % 1)),
minute = ""+(int) (((24 * (time % 1)) % 1) * 60) ;
while (hour.length() < 2) hour = "0"+hour ;
while (minute.length() < 2) minute = "0"+minute ;
final String newStamp = day+", "+hour+minute+" Hours" ;
timeStamps.addLast(newStamp) ;
PlayLoop.saveGame(fullSavePath(savesPrefix, newStamp)) ;
} | 5 |
public void fetchReplicaUsers()
{
LOGGER.info("Fetching Replicas for : " + orgMap.size() + " Orgs");
if(orgMap!=null && orgMap.size()>0)
{
XLSHandler orgXLS = new XLSHandler();
ArrayList<HashMap<String, String>> replicaData = orgXLS.getExcelRows("C:\\temp\\Replicas.xlsx");
//load users in Org from Salesforce.
for(Org o: orgMap.values())
{
o.loadUsersFromSalesforce();
}
LOGGER.info("Setting Replicas : ");
for(HashMap<String, String> liveUserRow: replicaData)
{
String rowUserName = liveUserRow.get("USERNAME");
String rowUserCode = liveUserRow.get("USERCODE");
Org rowOrg = orgMap.get(liveUserRow.get("ORGNAME"));
User rowUser = rowOrg.users.get(liveUserRow.get("USERNAME"));
rowUser.setUserCode(rowUserCode);
LOGGER.info("Replicas for : " + rowUserName + " for " + rowUserCode);
for(HashMap<String, String> row2: replicaData)
{
String rowUserName2 = row2.get("USERNAME");
String rowUserCode2 = row2.get("USERCODE");
Org rowOrg2 = orgMap.get(row2.get("ORGNAME"));
User rowUser2 = rowOrg2.users.get(row2.get("USERNAME"));
String username = "";
if(rowOrg.getOrgName() == rowOrg2.getOrgName())
username = rowUserName2;
else
{
username = rowUser2.getUserId().toLowerCase() + "." + rowOrg2.getOrgId().toLowerCase() + "@" + rowOrg.getOrgId().toLowerCase() + ".dup";
}
if(rowOrg.users.containsKey(username))
{
HashMap<String, User> replicaUsers = rowOrg.replicaUsers.containsKey(rowUser.getUserCode())?rowOrg.replicaUsers.get(rowUser.getUserCode()): new HashMap<String, User>();
replicaUsers.put(rowUserCode2, rowOrg.users.get(username));
rowOrg.replicaUsers.put(rowUser.getUserCode(), replicaUsers);
}
}
}
LOGGER.info("Writting Replicas to Sheet: ");
writeReplicas();
LOGGER.info("Fetching Replicas Complete");
}
} | 8 |
private static void Factor()
{
if( sym == ident )
{
Designator();
if( sym == assign )
{
Scan();
ActPars();
}
else if( sym == lpar )
{
ActPars();
}
}
else if( sym == number ) Scan();
else if( sym == charCon ) Scan();
else if( sym == new_ )
{
Scan();
Check( ident );
if( sym == lbrack )
{
Scan();
Expr(); Check( rbrack );
}
}
else if( sym == lpar )
{
Scan();
Expr(); Check( rpar );
}
else Error( "invalid start of Factor" );
} | 8 |
protected void init() {
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
nameLabel = new JLabel("Name");
phoneLabel = new JLabel("Phone");
nameField = new JTextField(20);
phoneField = new JTextField(20);
addButton = new JButton("Add");
searchButton = new JButton("Search");
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.LINE_END;
constraints.ipadx = 10;
this.add(nameLabel, constraints);
}
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.gridwidth = 3;
constraints.fill = GridBagConstraints.BOTH;
this.add(nameField, constraints);
}
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.anchor = GridBagConstraints.LINE_END;
constraints.ipadx = 10;
this.add(phoneLabel, constraints);
}
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 1;
constraints.gridwidth = 3;
constraints.fill = GridBagConstraints.BOTH;
this.add(phoneField, constraints);
}
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 2;
constraints.gridy = 2;
constraints.anchor = GridBagConstraints.LINE_START;
this.add(addButton, constraints);
}
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 3;
constraints.gridy = 2;
constraints.ipadx = 10;
this.add(searchButton, constraints);
}
//Add Listeners to button events
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String name = nameField.getText().trim();
String number = phoneField.getText().trim();
if(!name.equals("") && !number.equals(""))
{
if(name.length()<120)
{
if(number.length()<120)
parent.addEntry(new Entry(name,number));
else
JOptionPane.showMessageDialog(parent, "Phone number cannot exceed 120 characters.", "Error", JOptionPane.ERROR_MESSAGE);
}
else
JOptionPane.showMessageDialog(parent, "Name cannot exceed 120 characters.", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(parent, "Missing fields", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event)
{
String name = nameField.getText().trim();
String number = phoneField.getText().trim();
if(true/*!name.equals("") || !number.equals("")*/)
{
if(name.length()<120)
{
if(number.length()<120)
parent.dispEntries(new Entry(name,number));
else
JOptionPane.showMessageDialog(parent, "Phone number cannot exceed 120 characters.", "Error", JOptionPane.ERROR_MESSAGE);
}
else
JOptionPane.showMessageDialog(parent, "Name cannot exceed 120 characters.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
//Tool tips for buttons
addButton.setToolTipText("Add a Phone Book Entry");
searchButton.setToolTipText("Search for a Phone Book Entry");
} | 7 |
public static String strip_vt100(String line)
{
int i;
StringBuffer nline = new StringBuffer();
for(i = 0; i < line.length(); i++) {
while(i < line.length() && line.charAt(i) == vt_esc.charAt(0)) { // Got escape sequence
// OK. All VT100 cmds seems to end either with m or H
while(i < line.length() && line.charAt(i) != 'm' && line.charAt(i) != 'H')
i++;
i++; // Skip m or H
}
if(i >= line.length()) // Did we hit the end?
break;
nline.append(line.charAt(i));
}
return nline.toString();
} | 7 |
@Override
protected boolean doSecondPhase(String query, Configuration conf, String outputPath, String[] dimensionTables,
String[] filter_table, int numberOfReducer) {
try {
List<String> AllDimensionTalbes = new ArrayList<String>();
AllDimensionTalbes.add(TABLE_CUSTOMER);
AllDimensionTalbes.add(TABLE_DATE);
AllDimensionTalbes.add(TABLE_PART);
AllDimensionTalbes.add(TABLE_SUPPLIER);
DistributedCache.addCacheFile(new URI(FULL_PATH_COLUMN), conf);
DistributedCache.addCacheFile(new URI(FULL_PATH_JOIN), conf);
for (String t : dimensionTables) {
DistributedCache.addCacheFile(new URI(PATH_BLOOM_FILTER + SYSTEM_SPLIT + AllDimensionTalbes.indexOf(t)),
conf);
}
DistributedCache.addCacheFile(new URI(PATH_OUTPUT_FIRST + SYSTEM_SPLIT + FP_OUTPUT), conf);
conf.setLong(MAPRED_TASK_TIMEOUT, Long.MAX_VALUE);
Job job = new Job(conf, FUNCTION_NAME + " Second Phase " + query);
job.setJarByClass(PRM.class);
job.setMapperClass(PartitionAndReplicationPhaseMapper.class);
job.setNumReduceTasks(numberOfReducer);
job.setReducerClass(PartitionAndReplicationPhaseReducer.class);
job.setOutputKeyClass(QuadTextPair.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(PATH_INPUT + SYSTEM_SPLIT + TABLE_LINEORDER + SYSTEM_SPLIT));// fact
CheckAndDelete.checkAndDelete(outputPath, conf);
FileOutputFormat.setOutputPath(job, new Path(outputPath));
return job.waitForCompletion(true);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return false;
} | 5 |
@Override
public void executeMsg(Environmental host, CMMsg msg)
{
super.executeMsg(host,msg);
if((msg.source()==affected)
&&(msg.targetMinor()==CMMsg.TYP_EAT)
&&(msg.target() instanceof Food)
&&(msg.target() instanceof Item))
{
if(((((Item)msg.target()).material()&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_FLESH)
&&(CMLib.english().containsString(msg.target().Name(),msg.source().charStats().getMyRace().name())))
{
msg.source().curState().adjHunger(+((Food)msg.target()).nourishment(),msg.source().maxState().maxHunger(msg.source().baseWeight()));
msg.source().curState().adjThirst(+((Food)msg.target()).nourishment()*2,msg.source().maxState().maxThirst(msg.source().baseWeight()));
}
else
msg.source().curState().adjHunger(-((Food)msg.target()).nourishment(),msg.source().maxState().maxHunger(msg.source().baseWeight()));
}
else
if((msg.source()==affected)
&&(msg.targetMinor()==CMMsg.TYP_DRINK)
&&(msg.target() instanceof Drink))
msg.source().curState().adjThirst(-((Drink)msg.target()).thirstQuenched(),msg.source().maxState().maxThirst(msg.source().baseWeight()));
} | 9 |
@Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == DELIVERY_PACKET_ID) {
return Integer.class;
} else if (columnIndex == MEMBER_NAME) {
return String.class;
} else if (columnIndex == EVENT) {
return String.class;
} else if (columnIndex == DELIVERY_DATE) {
return Date.class;
} else if (columnIndex == EXPECTED_RETURN_DATE) {
return Date.class;
} else {
return Object.class;
}
} | 6 |
@Override
public Object execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Contexto oContexto = (Contexto) request.getAttribute("contexto");
switch (oContexto.getSearchingFor()) {
case "usuario": {
oContexto.setVista("jsp/usuario/list.jsp");
oContexto.setClase("usuario");
oContexto.setMetodo("list");
oContexto.setFase("1");
oContexto.setSearchingFor("usuario");
oContexto.setClaseRetorno("backlog");
oContexto.setMetodoRetorno("update");
oContexto.setFaseRetorno("1");
oContexto.removeParam("id_usuario");
UsuarioList1 oOperacion = new UsuarioList1();
return oOperacion.execute(request, response);
}
default:
oContexto.setVista("jsp/mensaje.jsp");
BacklogBean oBacklogBean = new BacklogBean();
BacklogDao oBacklogDao= new BacklogDao(oContexto.getEnumTipoConexion());
BacklogParam oBacklogParam = new BacklogParam(request);
oBacklogBean = oBacklogParam.loadId(oBacklogBean);
oBacklogBean = oBacklogDao.get(oBacklogBean);
try {
oBacklogBean = oBacklogParam.load(oBacklogBean);
} catch (NumberFormatException e) {
return "Tipo de dato incorrecto en uno de los campos del formulario";
}
try {
oBacklogDao.set(oBacklogBean);
} catch (Exception e) {
throw new ServletException("BacklogController: Update Error: Phase 2: " + e.getMessage());
}
String strMensaje = "Se ha cambiado la información de backlog con id=" + Integer.toString(oBacklogBean.getId()) + "<br />";
strMensaje += "<a href=\"Controller?class=backlog&method=list&filter=id_usuario&filteroperator=equals&filtervalue=" + oBacklogBean.getUsuario().getId() + "\">Ver Backlogs de este cliente</a><br />";
strMensaje += "<a href=\"Controller?class=backlog&method=view&id=" + oBacklogBean.getId() + "\">Ver BackLog creado en el formulario</a><br />";
return strMensaje;
}
} | 3 |
private static boolean backtrack(int[][] maze, Cell end, int y, int x, Deque<Cell> path) {
// GQ!
//if (end.equals(path.peek())) {
if (end.equals(path.peekLast())) {
return true;
}
final int R = maze.length;
final int C = maze[0].length;
for (int i = 0; i < DELTA_X.length; i++) {
int row = y + DELTA_Y[i];
int col = x + DELTA_X[i];
if (row < 0 || row >= R || col < 0 || col >= C) {
continue;
}
if (maze[row][col] == BLACK || maze[row][col] == DISCOVERED) {
continue;
}
Cell cell = new Cell(row, col);
maze[row][col] = DISCOVERED;
path.addLast(cell);
if (backtrack(maze, end, row, col, path)) {
return true;
}
path.removeLast();
}
return false;
} | 9 |
public boolean canFallthrough() {
return opcode != opc_goto && opcode != opc_goto_w && opcode != opc_ret &&
!(opcode >= opc_ireturn && opcode <= opc_return) && opcode != opc_athrow
&& opcode != opc_jsr && opcode != opc_tableswitch && opcode != opc_lookupswitch;
} | 8 |
public static Filter not( Filter delegate )
{
if ( delegate == null )
{
throw new IllegalArgumentException( "Parameter 'delegate' must be not null" );
}
return new Not( delegate );
} | 1 |
protected void onEntryRemove(Object key, ICacheable data){
} | 0 |
private void maybeShowPopup(MouseEvent e) {
int x = e.getX() / imagemapPanel.zoomFactor;
int y = e.getY() / imagemapPanel.zoomFactor;
if (e.isPopupTrigger()
&& (shapeList.isPointInsideShape(x, y) || shapeList
.isShapePointAt(x, y))) {
menuItem_rempoint.setEnabled(shapeList.getFoundKeyPoint() > 0); // poly
// point
menuItem_convert
.setEnabled(shapeList.getFoundShape().get_type() == ImagemapShape.TYPE_CIRCLE
|| shapeList.getFoundShape().get_type() == ImagemapShape.TYPE_RECT);
selectedShape = shapeList.getFoundShape(); // forrest
popup.show(e.getComponent(), e.getX(), e.getY());
}
} | 4 |
private Grammar readGrammar(File file) {
Grammar g = new UnboundGrammar();
int lineNum = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
lineNum++;
if (line.length() == 0)
continue;
if (line.startsWith("#"))
continue;
String[] elems = line.split("\\s+");
int len = elems.length;
if (len > 3 || len < 2 || !elems[1].equals("->")) {
throw new ParseException("Line " + lineNum
+ " is not formatted properly!");
}
g.addProduction(new Production(elems[0], len == 3 ? elems[2]
: ""));
}
} catch (FileNotFoundException e) {
throw new ParseException("Could not find file " + file.getName()
+ "!");
} catch (IOException e) {
throw new ParseException("Error accessing file to write!");
}
return g;
} | 9 |
@Override
public String print() {
String numberToReturn = "" + number;
if (((number % number) == 0 ) || number == 0)
numberToReturn = "" + (int) number;
if (number < 0)
return "( " + numberToReturn + " )";
return numberToReturn;
} | 3 |
private void joinChan(String user_name, CommandArgsIterator args_it)
throws IOException
{
if (args_it.hasNext()) {
String chan_arg = args_it.next();
if (!args_it.hasNext() && chan_arg.length() >= 2
&& chan_arg.charAt(0) == '#') {
String chan_name = chan_arg.substring(1);
Map<String, Chan> chans = this._server.getChans();
boolean already_joined;
synchronized (chans) {
synchronized (this._chans) {
if (!this._chans.containsKey(chan_name)) {
Chan chan = chans.get(chan_name);
if (chan != null)
chan.joinChan(user_name, this);
else {
new Chan(
this._server, chan_name, user_name, this
);
}
already_joined = false;
} else
already_joined = true;
}
}
if (!already_joined) {
this.traceEvent("Rejoint le salon #" + chan_name);
this.ack();
} else
this.writeCommand(Errors.ChanAlreadyJoined);
} else
this.syntaxError();
} else
this.syntaxError();
} | 7 |
public int maxArea(int[] height) {
if (height.length == 0) {
return 0;
}
int result = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int lh = height[left];
int rh = height[right];
int temp = (right - left) * Math.min(lh, rh);
if (temp > result) {
result = temp;
}
if (lh < rh) {
while (left < right && height[left] <= lh) {
left++;
}
} else {
while (left < right && height[right] <= rh) {
right--;
}
}
}
return result;
} | 8 |
public static void main(String[] args) throws IOException, InterruptedException {
int portNumber = 7777;//Integer.parseInt(args[0]);
ServerSocket serverSocket= new ServerSocket(portNumber);
try {
while (true){
//System.out.println(available.getQueueLength());
Socket clientSocket = serverSocket.accept();
new ServerWorkerThread(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
public boolean merge() throws FileNotFoundException, IOException {
//Select your favourate Jersey No to assign it to the final Index. :)
//Ok we need similarity and we reuse indexreaders for merging so using the same constructor.
int fileNumber = 2;
//Modify here to expand for a distributed index structure.
//Distributed index, would give you the advantage of higher throughput.
File folder = new File(outputDirectory, "FinalIndex");
folder.mkdir();
outputDirectory = folder.getAbsolutePath();
File outputFile = new File(outputDirectory,String.valueOf(fileNumber));
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(outputFile));
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(outputDirectory+"Lexicon")));
int currentFileOffset = 0;
List<Integer> docVector = new LinkedList<Integer>();
List<Integer> freqVector = new LinkedList<Integer>();
//List<Integer> offsetVector = new LinkedList<Integer>();
//List<Integer> contextVector = new LinkedList<Integer>();
// Iterate for all terms discussed in lexicon
for (Integer termID : inputLexicon.keySet()) {
System.out.println("Now Merging for term :"+termID);
List<BlockInfo> list = inputLexicon.get(termID);
PriorityQueue<WrapperIndexEntry> pQueue = new PriorityQueue<WrapperIndexEntry>(
list.size(), new Comparator<WrapperIndexEntry>() {
@Override
public int compare(WrapperIndexEntry o1, WrapperIndexEntry o2) {
if(o1.getDocID(o1.getCurrentPosition())==o2.getDocID(o2.getCurrentPosition()))
return 0;
return( ( (o1.getDocID(o1.getCurrentPosition())-o2.getDocID(o2.getCurrentPosition())) )>0)?1:-1;
}
});
int i=0;
for(BlockInfo blockInfo:list){
WrapperIndexEntry indexEntry = new WrapperIndexEntry(readerMap.get(blockInfo.getFileNumber()).openList(termID));
pQueue.add(indexEntry);
if(pQueue.size()>=2)
pQueue.remove();
i++;
}
while(!pQueue.isEmpty()){
WrapperIndexEntry indexEntry = pQueue.poll();
docVector.add(WrapperIndexEntry.currentDoc(indexEntry));
freqVector.add(WrapperIndexEntry.currentFrequency(indexEntry));
//offsetVector.addAll(WrapperIndexEntry.currentOffsets(indexEntry));
//contextVector.addAll(WrapperIndexEntry.currentContexts(indexEntry));
//If there is another docid in indexentry, we add the the indexentry back into the pQueue
// Notice the fact that now the lastDocChecked has incremented and hence, would the values for docId as well
// This helps us find the lowest docIds from a list of IndexEntries, and then we continue th process till we have pQueue emptied up
if(WrapperIndexEntry.incrIndex(indexEntry))
pQueue.add(indexEntry);
}
//Now we write the vectors to a block and store the info back into the lexicon.
//The merging is complete for a term, now we flush it and update lexicon :)
//System.out.println("Royal Flush *****************"+docVector.size());
currentFileOffset = PostingWriter.writePosting(termID, docVector, freqVector, stream, currentFileOffset, fileNumber, outputLexicon);
}
objectOutputStream.writeObject(outputLexicon);
objectOutputStream.close();
stream.close();
System.gc();
return true;
} | 7 |
public static SolveMethod getSolveMethod(Scanner scan) {
while (true) {
System.out.print("Choose Right, Left, Middle, or Trapazoid: ");
switch (scan.nextLine().toLowerCase().charAt(0)) {
case 'r':
return SolveMethod.RIGHT;
case 'l':
return SolveMethod.LEFT;
case 'm':
return SolveMethod.MIDDLE;
case 't':
return SolveMethod.TRAPAZOID;
default:
System.out.println("No such option! Try again.");
}
}
} | 5 |
public static void main(String[] args) {
SummaryRanges summaryRanges=new SummaryRanges();
summaryRanges.addNum(6);
summaryRanges.addNum(6);
summaryRanges.addNum(0);
summaryRanges.addNum(4);
summaryRanges.addNum(8);
summaryRanges.addNum(7);
summaryRanges.addNum(6);
summaryRanges.addNum(4);
summaryRanges.addNum(7);
summaryRanges.addNum(5);
System.out.println(summaryRanges.getIntervals());
} | 0 |
public List<List<Integer>> levelOrder(TreeNode root){
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<TreeNode> levelNode = new ArrayList<TreeNode>();
if(root == null)
return result;
else
levelNode.add(root);
order(result,levelNode);
return result;
} | 1 |
private Response dequeueMessage(ByteBuffer buffer) {
int receiverId = buffer.getInt();
int senderId = buffer.getInt();
int queueId = buffer.getInt();
int peekFlag = buffer.getInt();
boolean peek = false;
if (peekFlag == 1) {
peek = true;
}
Message m;
long startTime = System.nanoTime();
_manager.startDBConnection();
_manager.startDBTransaction();
try {
m = _manager.getMessageDao().dequeueMessage(receiverId, senderId, queueId, peek);
} catch (MessageDequeueQueueDoesNotExistException e) {
_manager.abortDBTransaction();
return err(ERR_QUEUE_DOES_NOT_EXIST_EXCEPTION);
} catch (MessageDequeueException e) {
_manager.abortDBTransaction();
return err(ERR_MESSAGE_DEQUEUE_EXCEPTION);
} catch (MessageDequeueNotIntendedReceiverException e) {
_manager.abortDBTransaction();
return err(ERR_NO_MESSAGE_EXCEPTION);
} catch (MessageDequeueEmptyQueueException e) {
_manager.abortDBTransaction();
return err(ERR_EMPTY_QUEUE_EXCEPTION);
} finally {
_manager.endDBTransaction();
_manager.endDBConnection();
}
long stopTime = System.nanoTime();
_EVALLOG5.log(startTime + "," + stopTime + ",DB_DEQUEUE_TOTAL");
return ok(m);
} | 5 |
public MainGUI(Player p){
this.p = p;
nextSongButton = new GenericButton("Music On"); //The first button.
nextSongButton.setAnchor(WidgetAnchor.CENTER_CENTER); //We are "sticking" it from the center_center, from there we will be shifting.
nextSongButton.setWidth(90).setHeight(20); //Setting the width and height of the button.
nextSongButton.shiftXPos(-90/2).shiftYPos(-nextSongButton.getHeight()/2+5);
stopMusicButton = new GenericButton("Music Off"); //The second button.
stopMusicButton.setAnchor(WidgetAnchor.CENTER_CENTER);
stopMusicButton.setWidth(90).setHeight(20);
//stopMusicButton.shiftXPos(0).shiftYPos(stopMusicButton.getHeight()/2);
stopMusicButton.shiftXPos(-90/2).shiftYPos((int) (stopMusicButton.getHeight()*1.1));
if (Settings.useBackgroundImage)
addBackground();
currentSongLabel = new GenericLabel("");
currentSongLabel.setAnchor(WidgetAnchor.CENTER_CENTER);
currentSongLabel.setWidth(200).setHeight(10);
currentSongLabel.shiftXPos(-50).shiftYPos(50);
currentSongLabel.setTextColor(new Color(200,200,200));
if (Settings.showCurrentSong) this.attachWidget(AmbientSpout.callback, currentSongLabel);
if (!AmbientSpout.callback.getConfig().getBoolean("Settings.Donation", false))
addCredit();
if (Model.playerMusicEnabled.containsKey(p.getName())){
if (Model.playerMusicEnabled.get(p.getName())){
nextSongButton.setText("Next Song");
updateCurrentSong();
}
else{
stopMusicButton.setVisible(false);
}
}
if (p.hasPermission("ambientspout.admin") || p.isOp()) {
//System.out.println("Adding EffectLoopButton"); //TODO DebugOnly
addEffectLoopButton();
}
this.attachWidget(AmbientSpout.callback, nextSongButton);
this.attachWidget(AmbientSpout.callback, stopMusicButton);
} | 7 |
public boolean addAll(Collection<? extends T> arg0) {
boolean result = false;
for (T object : arg0) {
if (add(object)) {
result = true;
}
}
return result;
} | 3 |
public void addUserToDB() {
try {
String statement = new String("INSERT INTO " + DBTable
+ " (username, password, url, permission, isblocked, isdead, practicenumber, highscorenumber)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement, new String[] {"userid"});
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, homepageURL);
stmt.setInt(4, permission);
stmt.setBoolean(5, isBlocked);
stmt.setBoolean(6, isDead);
stmt.setInt(7, practiceNumber);
stmt.setInt(8, highScoreNumber);
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
userID = rs.getInt("GENERATED_KEY");
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
} | 1 |
public void removePerson(Person P){
Persons.remove(P);
setCantPerson(CantPerson-1);
} | 0 |
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
} | 6 |
public short getId() {
return id;
} | 0 |
public void run() {
int[] route = new int[salesman.n];
minRoute = new int[salesman.n];
minCosts = -1;
count = 0;
route[0] = 0;//first city always zero
for(int i = 1;i < salesman.n;i++){
route[1] = i;
checkRoute(route,2);
}
System.out.println("Brute force results count: "+count+", minimum cost: "+minCosts+", route: ");
salesman.printRoute(minRoute);
} | 1 |
public static int eggOnFloor (int f, int e, int[][] s, int[][] c ) {
if ( s[f][e] != -9999999) {
return s[f][e];
}
if ( f == 0 ) {
return 0;
}
if ( e <= 0) {
return 9999999;
}
int min = 99999999;
for (int i = 1; i <= f; ++i) {
int tmp = Math.max(eggOnFloor(i-1, e-1, s, c),
eggOnFloor(f-i, e, s, c)) + 1;
if ( tmp < min ) {
c[f][e] = i;
min = tmp;
}
}
s[f][e] = min;
System.out.println( String.format("floor: %d, egg: %d => %d", f, e, min));
return min;
} | 5 |
private void init() {
isRunning = true;
gcCallbackProcessor = new Thread(new Runnable() {
@Override
public void run() {
while (isRunning) {
try {
listen();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
private void listen() throws InterruptedException {
final Reference<?> ref = gcCallback.poll();
if (ref != null) {
System.out.println(ref + " is being reclaimed");
refHolder.remove(ref);
System.out.println("Ref holder looks like " + refHolder);
final T newInstance = creator.createNew();
if (objectQueue.offer(newInstance)) {
final Reference<T> newRef = new WeakReference<T>(
newInstance, gcCallback);
refHolder.put(newRef, IS.PRESENT);
}
}
}
}, "Object pool GC reclaim");
gcSpamThread = new Thread(new Runnable() {
@Override
public void run() {
while(isRunning) {
System.gc();
}
}
}, "GC Spam thread");
gcCallbackProcessor.start();
gcSpamThread.start();
} | 6 |
public String getLatestMessage() {
if(history.size()>0) {
return history.get(history.size()-1).getMessageText();
} else {
return null;
}
} | 1 |
private void processCatalogueAddReplicaResult(Sim_event ev)
{
if (ev == null) {
return;
}
Object[] pack = (Object[]) ev.get_data();
if (pack == null) {
return;
}
String filename = (String) pack[0]; // get file name
int msg = ((Integer) pack[1]).intValue(); // get result
int eventSource = findEvent(waitingReplicaAddAck_, filename);
ArrayList list = (ArrayList) catalogueHash_.get(filename);
// if adding replica into top RC is successful
if (msg == DataGridTags.CTLG_ADD_REPLICA_SUCCESSFUL)
{
// create a new entry in the catalogue
if (list == null)
{
list = new ArrayList();
catalogueHash_.put(filename, list);
}
list.add(new Integer(eventSource));
}
// if this is a local RC, we should not send the event back
if (!this.localRC_)
{
sendMessage(filename, DataGridTags.CTLG_ADD_REPLICA_RESULT,
msg, eventSource);
}
} | 5 |
public void stop() {
if(playList != null) {
stopping = true;
GameSong gs = null;
if(currentSongIndex < playList.size()) {
gs = playList.get(currentSongIndex);
currentSongIndex++;
}
if(currentSongIndex > playList.size()) {
currentSongIndex = 0;
}
if(gs != null) {
if(transitionTime > 0.0f) {
gs.fadeOut();
} else {
gs.stop();
if(nextPlayList != null) {
nextPlayList.start();
}
}
}
}
} | 6 |
@Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = ConfigurationManager.getProperty("path.page.createorder");
try {
Criteria criteria = new Criteria();
Order order = (Order) request.getSessionAttribute(JSP_CURRENT_ORDER);
putOrderParams(criteria, order);
User user = (User) request.getSessionAttribute(JSP_USER);
if (user != null) {
criteria.addParam(DAO_USER_LOGIN, user.getLogin());
ClientType type = ClientTypeManager.clientTypeOf(user.getRole().getRoleName());
criteria.addParam(DAO_ROLE_NAME, type);
} else {
criteria.addParam(DAO_ROLE_NAME, request.getSessionAttribute(JSP_ROLE_TYPE));
}
AbstractLogic orderLogic = LogicFactory.getInctance(LogicType.ORDERLOGIC);
Integer resIdOrder = orderLogic.doRedactEntity(criteria);
AbstractLogic userLogic = LogicFactory.getInctance(LogicType.USERLOGIC);
List<User> users = userLogic.doGetEntity(criteria);
if (users != null) {
request.setSessionAttribute(JSP_USER, users.get(0));
}
request.setParameter(JSP_SELECT_ID, resIdOrder.toString());
page = new GoShowUserOrder().execute(request);
} catch (TechnicalException | LogicException ex) {
request.setAttribute("errorReason", ex.getMessage());
request.setAttribute("errorSaveData", "message.errorSaveData");
request.setSessionAttribute(JSP_PAGE, page);
}
return page;
} | 3 |
private int calculateSpeed(Street currentStreet) throws InterruptedException {
int speedLimit = 0;
// Limit by street type
if(!SimulationOption.IGNORE_SPEEDLIMIT.equals(vehicle.getSimulationOption())) {
speedLimit = Math.min(currentStreet.getStreetType().getSpeedLimit(), vehicle.getMaxSpeed());
}else{
speedLimit = vehicle.getMaxSpeed();
}
// Limitation for no-passing streets
if(currentStreet.isNoPassing()) {
for(Vehicle other : currentStreet.getVehicles()) {
int abstand = this.vehicle.getDistToNext() - other.getDistToNext();
if(other == this.vehicle || abstand < 0) {
// Don't check myself and only look forward
continue;
}
if(abstand == Constants.DISTANCE_NO_PASSING) {
// speed of other vehicle
speedLimit = Math.min(currentStreet.getStreetType().getSpeedLimit(), other.getMaxSpeed());
} else if(abstand < Constants.DISTANCE_NO_PASSING) {
// slow a bit down
speedLimit = Math.min(currentStreet.getStreetType().getSpeedLimit(), other.getMaxSpeed()) - 10;
}
}
}
return speedLimit;
} | 7 |
private int numberOfEnemiesToFight(int number){
int res = 0;
for (int i = 0; i < beings.size(); i++){
if (((beings.get(i).isZombie() && beings.get(number).isHuman()) || (beings.get(i).isHuman() && beings.get(number).isZombie())) && getDistance(i, number) < RADIUS_FIGHT){
res++;
}
}
return res;
} | 6 |
public Object getValueAt(int row, int col) {
if (data == null) {
return null;
}
if (row == -1 || col == -1) {
return null;
}
return data[row][col];
} | 3 |
private static void RelationalOperators() {
System.out.println("Start of RelationalOperators");
int a = 1;
int b = 2;
// Check Equality
if (a == b) {
System.out.println("a is equal to b");
} else {
System.out.println("a is not equal to b");
}
// Check Inequality
if (a != b) {
System.out.println("a is not equal to b");
} else {
System.out.println("a is equal to b");
}
// Check Less Than
if (a < b) {
System.out.println("a is less than b");
} else {
System.out.println("a is not less than b");
}
// Check Less EqualTo Than
if (a <= b) {
System.out.println("a is less or equal to b");
} else {
System.out.println("a is not less or equal to b");
}
// Check Greater Than
if (a > b) {
System.out.println("a is greater than b");
} else {
System.out.println("a is not greater than b");
}
// Check Greater Equal to
if (a >= b) {
System.out.println("a is greater than or equal to b");
} else {
System.out.println("a is not greater than or equal to b");
}
System.out.println("End of RelationalOperators");
System.out.println("\n");
} | 6 |
protected TorrentMetaInfo (
TorrentInfoSection info, String announce, List<Set<String>> announceList, DateTime creationDate,
String comment, String createdBy)
{
if (announce == null | info == null)
throw new NullPointerException();
this.announce = announce;
this.creationDate = creationDate;
this.comment = comment == null ? "" : comment;
this.createdBy = createdBy == null ? "" : createdBy;
this.info = info;
if (announceList == null) {
this.announceList = new ArrayList<Set<String>>();
} else {
List<Set<String>> ual = new ArrayList<Set<String>>();
for (Set<String> ls : announceList) {
if (ls != null) {
Set<String> ns = new HashSet<String>(ls);
ns.remove(null);
ual.add(Collections.unmodifiableSet(ns));
}
}
this.announceList = Collections.unmodifiableList(ual);
}
// hashCode
cachedHashCode = announce.hashCode() ^ info.hashCode();
// toString
StringBuilder sb = new StringBuilder(128);
sb.append("TorrentMetaInfo{{ ");
sb
.append("CreationDate(").append(this.creationDate).append("), ").append("Comment(\"").append(this.comment)
.append("\"), ").append("Announce(").append(this.announce).append("), ").append("AnnounceList(").append(
this.announceList).append("), ").append("Info(").append(this.info).append("), ").append(" }}");
chachedToString = sb.toString();
} | 6 |
final void method3287() {
if (secondInt == -1) {
secondInt = 0;
if (aByteArray3899 != null && aByteArray3899.length == 1
&& aByteArray3899[0] == 10)
secondInt = 1;
for (int i_13_ = 0; i_13_ < 5; i_13_++) {
if (options[i_13_] != null) {
secondInt = 1;
break;
}
}
}
if (anInt3855 == -1)
anInt3855 = clipType != 0 ? 1 : 0;
} | 8 |
private void renderPatch(MeshPatch patch, Rendering rendering, float time) {
if (patch == null) return ;
final float alphaVal =
patch.inceptTime == TIME_DONE ? 1 :
((time - patch.inceptTime) / 2f) ;
if (alphaVal >= 1 && patch.previous != null) {
patch.previous = null ;
patch.inceptTime = TIME_DONE ;
}
else renderPatch(patch.previous, rendering, time) ;
final Colour colour = Colour.transparency(alphaVal) ;
for (TerrainMesh mesh : patch.meshes) {
mesh.colour = colour ;
mesh.setAnimTime(time) ;
rendering.addClient(mesh) ;
}
if (patch.roadsMesh != null) {
patch.roadsMesh.colour = colour ;
rendering.addClient(patch.roadsMesh) ;
}
if (patch.dirtMesh != null) {
patch.dirtMesh.colour = colour ;
rendering.addClient(patch.dirtMesh) ;
}
} | 7 |
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(ListaUsr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListaUsr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListaUsr.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListaUsr.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 ListaUsr().setVisible(true);
}
});
} | 6 |
public void testBug4706479() throws Exception {
Random rnd = new Random( 1234 );
TCustomHashMap<byte[], Integer> map =
new TCustomHashMap<byte[], Integer>( new ByteArrayStrategy() );
List<byte[]> list = new ArrayList<byte[]>();
List<Integer> expected = new ArrayList<Integer>();
for ( int i = 0; i < 1000; i++ ) {
byte[] ba = random( 16, rnd );
list.add( ba );
Integer obj = Integer.valueOf( i );
expected.add( obj );
map.put( ba, obj );
}
assertEquals( list.size(), map.size() );
// Make sure all the arrays are found in the map
for( byte[] array : map.keySet() ) {
boolean found_it = false;
for( byte[] test : list ) {
if ( Arrays.equals( test, array ) ) {
found_it = true;
break;
}
}
assertTrue( "Unable to find: " + Arrays.toString( array ), found_it );
}
// Make sure all the Integers are found in the map
for( Integer obj : map.values() ) {
assertTrue( "Unable to find: " + obj, expected.contains( obj ) );
}
for ( int i = 0; i < expected.size(); i++ ) {
assertEquals( expected.get( i ), map.get( list.get( i ) ) );
}
// Remove items
for ( int i = 0; i < list.size(); i++ ) {
assertEquals( expected.get( i ), map.remove( list.get( i ) ) );
}
assertEquals( 0, map.size() );
assertTrue( map.isEmpty() );
for ( byte[] aList : list ) {
assertNull( map.get( aList ) );
}
} | 8 |
public int createGroup( String name, String members ){
int id = dao_id.getID( IDListDao.PARA_GROUP_ID );
if( !handler_group.initialize() ){
System.out.println( "GroupServer : failed to initialize group hander!" );
return 0;
}
if( id == -1 || !handler_group.insertNewGroup( id, name ) ){
handler_group.close();
return 0;
}
if( !handler_group.initGroupMember( id, members.split( "\\|" ) ) ){
handler_group.close();
return 0;
}
handler_group.close();
dao_id.updateID( IDListDao.PARA_GROUP_ID );
return id;
} | 4 |
private int tabulateTrees(TreeReader reader,
Map<String, TreeItem> clades) throws IOException {
int countedTrees = 0;
int examinedTrees =0;
SunFishFrame.getSunFishFrame().setInfoLabelText("Parsing trees file");
progressMonitor.setNote("Counting clades");
progressMonitor.setProgress(0);
DrawableTree tree = reader.getNextTree(); //This is the slow part and we do it for every single tree, regardless of subSampleRate
//We should make a DelayedDrawableTree class that just reads in the string but doesn't do any parsing
//or allocating until necessary.. this would probably be 100x faster
while(tree!=null && countedTrees < maxTrees && (!cancel)) {
examinedTrees++;
//System.out.println("Examining tree #" + examinedTrees );
if (tree!=null && (double)examinedTrees % subsampleRate == 0.0 && examinedTrees > burninTrees) {
//System.out.println("Counting tree #" + examinedTrees + " val : " + (double)examinedTrees/subsampleRate );
if (tree.getRoot().numOffspring()<2) {
System.err.println("Error reading tree, found less than two two tips from root, not tabulating clades...");
}
else {
if (DEBUG)
System.out.println("Counting tree #" + examinedTrees);
countClades(tree, (DrawableNode)tree.getRoot(), clades);
countedTrees++;
}
}
if (examinedTrees%25==0) {
progressMonitor.setProgress((int)Math.round(95.0*(double)examinedTrees/(double)totalTreeEst));
progressMonitor.setNote("Counting tree: " + examinedTrees + "/" + totalTreeEst);
}
tree = reader.getNextTree();
}
//System.out.println("Counted " + countedTrees + " of " + examinedTrees + " trees = " + (double)countedTrees/(double)examinedTrees + "%");
return countedTrees;
} | 9 |
public ArrayList<ArrayList<Course>> getPrereqs(String crn, String term, String year, String subj, String crse) throws Exception {
ArrayList<ArrayList<Course>> prereqs = new ArrayList<ArrayList<Course>>();
// Make url
String courseUrl = COURSE_URL + "?CRN=" + crn + "&TERM=" + term + "&YEAR=" + year +
"&SUBJ=" + subj + "&CRSE=" + crse + "&history=N";
// Go to url
Document courseDoc = Jsoup.connect(courseUrl).userAgent(USER_AGENTS).get();
// Parse document
Elements prereqHtml = courseDoc.select("table.plaintable tr");
Pattern matchCourse = Pattern.compile("[a-zA-Z]{2,4} \\d{4}.*");
for(Element e : prereqHtml) {
if(e.toString().contains("Prerequisites:")) {
String[] prereqLinks = e.getElementsByTag("td").get(1).toString().split(",");
for(String pe : prereqLinks) {
ArrayList<Course> prerecGroup = new ArrayList<>();
if (pe.contains(" or ")) {
String[] orRecList = pe.split("<a h[^>]*>");
for (String opr : orRecList) {
Matcher matcher = matchCourse.matcher(opr);
if (!matcher.matches())
continue;
String[] name = opr.split(" ");
Course temp = new Course(name[0], name[1].substring(0, 4));
prerecGroup.add(temp);
}
} else {
String[] orRecList = pe.split("<a h[^>]*>");
if (orRecList.length > 2) System.out.println("There was more than one element when expecting one prerec. TimeTableScrapper getPrerecs");
String[] name;
if (!matchCourse.matcher(orRecList[0]).matches())
name = orRecList[1].split(" ");
else
name = orRecList[0].split(" ");
Course temp = new Course(name[0], name[1].substring(0, 4));
prerecGroup.add(temp);
}
prereqs.add(prerecGroup);
}
break;
}
}
// Return array
return prereqs;
} | 8 |
@Override
public void run() {
/**
* Monitor para que se ejecute la funcion cada tick de reloj.
*/
synchronized (this) {
while (simulacion) {
try {
wait();
} catch (InterruptedException ex) {
System.out.println("ERROR DURMIENDO CPU");
return;
}
/**
* Se aumenta el tiempo de espera de los procesos no activos del
* CPU
*/
runqueue.aumentarTiempoEnEspera();
/**
* Si aun no ha llegado a los 100 ticks, se van despertando los
* procesos paulatinamente
*/
if (planificador.getReloj().getNumTicks() <= 100) {
agregarProcesosNuevos();
}
/**
* Se actualiza el quantum del proceso actual, si lo hay
*/
if (procesoActual != null) {
planificador.actualizarQuantum(procesoActual);
/**
* Se aumenta el tiempo ocioso del CPU si no tiene proceso
* activo
*/
} else {
tiempoOcioso++;
}
}
}
} | 4 |
private void addItem(String title, String name, ComponentType type, boolean isSimple, JMenuItem classCheckItem) {
if (isSimple && simpleMode) {
simpleMenu.add(classCheckItem);
return;
}
switch (type) {
case ACTIVE:
activeMenu.add(classCheckItem);
break;
case CHIPS:
chipsMenu.add(classCheckItem);
break;
case IO:
ioMenu.add(classCheckItem);
break;
case LOGIC:
logicMenu.add(classCheckItem);
break;
case OTHER:
otherMenu.add(classCheckItem);
break;
case PASSIVE:
passMenu.add(classCheckItem);
break;
case ROOT:
rootMenu.add(classCheckItem);
break;
}
} | 9 |
public static String payXP(Player p, int tier, double basepay, String job) {
double iTimes = tier;
double totalPay = PlayerCache.getEarnedIncome(p.getName());
String pLang = PlayerCache.getLang(p.getName());
String jobName = UpperCaseFirst.toUpperFirst(McJobs.getPlugin().getLanguage().getJobNameInLang(job, pLang).toLowerCase());
job = job.toLowerCase();
double payAmount = basepay * iTimes * Leveler.getMultiplier(PlayerCache.getJobLevel(p.getName(), job));
if(overLimit(payAmount, totalPay, p))
return "";
if((totalPay + payAmount >= _maxPay) && (_maxPay > 0.0D))
payAmount = _maxPay - totalPay + 1.0D;
totalPay += payAmount;
PlayerCache.setEarnedIncome(p.getName(), totalPay);
int xp;
if ((payAmount < 1.0D) && (payAmount >= 0.5D))
xp = 1;
else
xp = (int)payAmount;
manipXP(p, Integer.valueOf(xp));
String str = ChatColor.GREEN + McJobs.getPlugin().getLanguage().getPayment("payxp", pLang).addVariables(jobName, "", _df.format(payAmount));
return str;
} | 5 |
public void levelCheck()
{
boolean found1 = false;
int i = 0;
while(!found1 && i < arraySecondOrdering.length)
{
if (arraySecondOrdering[i].getQualification().charAt(3) > '1')
{
allocatedReferee1 = arraySecondOrdering[i];
found1 = true;
}
i++;
}
boolean found2 = false;
int j = 0;
while(!found2 && j < arraySecondOrdering.length)
{
if (arraySecondOrdering[j] != allocatedReferee1
&& arraySecondOrdering[j].getQualification().charAt(3) > '1')
{
allocatedReferee2 = arraySecondOrdering[j];
found2 = true;
}
j++;
}
if (allocatedReferee1 == null || allocatedReferee2 == null)
throw new IllegalArgumentException();
} | 9 |
private void calculate(int[] aux,int[] prices,int i){
int max=0;
for( int j=i+1;j<aux.length;++j){
int temp=0;
if(prices[j]>prices[i]) temp+=prices[j]-prices[i];
if(j+2<aux.length){
temp+=aux[j+2];
}
if(temp>max) max=temp;
if(aux[j]>max) max=aux[j];
}
aux[i]=max;
} | 5 |
public static void printData(List<?> objects){
for(Object object: objects){
System.out.println(object);
}
} | 2 |
public String getDirection(int tape) {
return (String) direction.get(tape);
} | 0 |
public void writeRefereesOutFile()
{
// create file writer object
FileWriter refereesOutWriter = null;
try
{
try
{
// instantiate file writer object
refereesOutWriter = new FileWriter(refereesOutFile);
// array length for use as iterator limit
int arrayLength = refereeProgram.getrefereeClassArray().length;
// loop over fitnessProgramObject
for (int x = 0; x < arrayLength; x++)
{
RefereeClass refereeClassAtX = refereeProgram.getRefereeClassAtX(x);
// if fitness class at x is not null
if (refereeClassAtX != null)
{
refereesOutWriter.write(String.format("%s %s %s %d %s %s%n",
refereeClassAtX.getRefereeID(), refereeClassAtX.getRefereeName(),
refereeClassAtX.getQualification(), refereeClassAtX.getAllocatedMatches(),
refereeClassAtX.getHomeLocality(), refereeClassAtX.getVisitingLocalities()));
}
}
}
finally
{
// close file writer
if (refereesOutWriter != null) refereesOutWriter.close();
}
}
catch (IOException iox)
{
JOptionPane.showMessageDialog(null, "File could not be created",
"Error", JOptionPane.ERROR_MESSAGE);
}
} | 4 |
private void expand(int[] array, int lay) {
int k = 0;
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < HEIGHT; j++) {
yCbCr[i][j][lay] = array[k++];
}
}
} | 2 |
public static <E> List<E> set2list(Set<E> set) {
ArrayList<E> list = new ArrayList<E>();
for (E e : set) {
list.add(e);
}
return list;
} | 1 |
@Override
public void init() {
log.info("BasicSIRModel - init");
/////////////////////////////////////////////////////////////////
// INITIALISE TRANSITION KERNEL
/////////////////////////////////////////////////////////////////
// an empty kernel for now
kernel = new TransitionKernel();
kernel.clear();
/////////////////////////////////////////////////////////////////
// INITIALISE AMOUNT MANAGER
/////////////////////////////////////////////////////////////////
// set up SIR model
// read in parameters from xml file
int N = this.getParameterValueAsInteger("N");
int initI = this.getParameterValueAsInteger("initI");
double[] rates = new double[2];
rates[0] = this.getParameterValueAsDouble("beta");
rates[1] = this.getParameterValueAsDouble("gamma");
BasicSIR sirModel = new BasicSIR(N, rates);
sirModel.initialiseWithInfected( initI );
// set up amount manager with SIR model and transition kernel
amountManager = new BasicSIRAmountManager( sirModel, kernel );
/////////////////////////////////////////////////////////////////
// INITIALISE SIMULATOR
/////////////////////////////////////////////////////////////////
// read in tau leap parameter from xml file
int tauStep = 0;
try {
tauStep = this.getParameterValueAsInteger("tauStep");
} catch (Exception e) {
}
// set up simulator
// with amount manager and transition kernel
// choose between fixed step tau leap (approximate) or exact gillespie algorithms for stochastic simulation
if (tauStep > 0) {
simulator = new TauLeapingFixedStep(amountManager, kernel, tauStep);
} else {
simulator = new GillespieSimple(amountManager, kernel);
}
// add controller, this stops the simulation after a max time is reached, or no more infecteds, or all recovered
// read in maxTime from xml file
double maxTime = Double.MAX_VALUE;
try {
maxTime = this.getParameterValueAsDouble("maxTime");
} catch (Exception e) {
}
SimulationController controller = new BasicSIRController(maxTime, sirModel);
simulator.setController(controller);
// read in seed from xml file
// if no seed present then generate one
// and re-seed with this (so that you know what it is).
int seed;
try {
seed = this.getParameterValueAsInteger("seed");
simulator.setRngSeed(seed);
//log.info("Seed read in from xml = "+seed);
//log.info("Seed from rng = "+(new RNG()).getSeed());
} catch (Exception e) {
log.info("Seed not set in xml, using own value");
seed = (new RNG()).getInteger(0, 9999999);
simulator.setRngSeed(seed);
}
//////////////////////////////////////////////////////////////////
// INITIALISE OBSERVER
//////////////////////////////////////////////////////////////////
// set up screen and file logging
try {
// if filename in xml then write to file
String outName = this.getParameterValue("filename") + ".txt";
observer = new BasicSIRObserver(simulator, outName);
} catch (Exception e) {
// if no filename present then just output to screen
observer = new BasicSIRObserver(simulator);
((BasicSIRObserver)observer).setPrintToLogInfo(true);
}
try {
// if verbose in xml then set this (log.info to screen)
boolean ans = this.getParameterValueAsBoolean("verbose");
((BasicSIRObserver)observer).setPrintToLogInfo(ans);
((BasicSIRAmountManager)amountManager).setPrintToLogInfo(ans);
} catch (Exception e) {
((BasicSIRAmountManager)amountManager).setPrintToLogInfo(false);
}
// add observer to simulator
simulator.addObserver(observer);
/////////////////////////////////////////////////////////////////////////////////////
// echo parameters that have read in - check that they are set in appropriate objects
//simulation parameters
log.info("seed\t= "+seed);
log.info("maxTime\t= "+((BasicSIRController)simulator.getController()).getMaxTime());
log.info("tauStep\t= "+tauStep);
// model paramters
log.info("N\t= "+((BasicSIRAmountManager)amountManager).getModel().getN());
log.info("initI\t= "+((BasicSIRAmountManager)amountManager).getModel().getNumberI());
log.info("beta\t= "+((BasicSIRAmountManager)amountManager).getModel().stateRates[0]);
log.info("gamma\t= "+((BasicSIRAmountManager)amountManager).getModel().stateRates[1]);
// add first events to kernel
((BasicSIRAmountManager)amountManager).initialiseTransitionKernelWithFirstEvents();
} | 6 |
public static void getOOXML( WorkBookHandle bk, String path ) throws IOException
{
try
{
if( !OOXMLAdapter.hasMacros( bk ) )
{
path = StringTool.replaceExtension( path, ".xlsx" );
}
else // it's a macro-enabled workbook
{
path = StringTool.replaceExtension( path, ".xlsm" );
}
java.io.File fout = new java.io.File( path );
File dirs = fout.getParentFile();
if( (dirs != null) && !dirs.exists() )
{
dirs.mkdirs();
}
OOXMLWriter oe = new OOXMLWriter();
oe.getOOXML( bk, new FileOutputStream( path ) );
}
catch( Exception e )
{
throw new IOException( "Error parsing OOXML file: " + e.toString() );
}
} | 4 |
private String derivationString() {
StringBuffer sb = new StringBuffer();
for (int i = 1; i < STACK.size(); i += 2)
sb.append(STACK.get(i));
sb.append(STRING.substring(P, STRING.length() - 1));
return sb.toString();
} | 1 |
public boolean doMostFavorableMove(Integer[] nextMove) {
Integer[] noMove = nextMove.clone();
Object[] bestCount = getBestLineCount();
String type = bestCount[0].toString();
int i = Integer.parseInt(bestCount[1].toString());
if(type.equals("row")) {
getLineFavorableMove(nextMove, type, i, jTable.getRow(i));
} else if(type.equals("column")) {
getLineFavorableMove(nextMove, type, i, jTable.getColumn(i));
} else if(type.equals("diagonal")) {
getLineFavorableMove(nextMove, type, i, jTable.getDiagonal());
} else if(type.equals("inverse")) {
getLineFavorableMove(nextMove, type, i, jTable.getInverse());
}
return !((noMove[0] == nextMove[0]) || (noMove[1] == nextMove[1]));
} | 5 |
public void onKeyEvent(KeyEvent e) {
if (player == null) return;
switch (e.getKeyCode()) {
// 上
case KeyEvent.VK_UP:
player.moveUp();
break;
case KeyEvent.VK_DOWN:
player.moveDown();
break;
case KeyEvent.VK_LEFT:
player.moveLeft();
break;
case KeyEvent.VK_RIGHT:
player.moveRight();
break;
case KeyEvent.VK_SPACE:
Bullet bullet = player.shoot();
bullets.add(bullet);
break;
}
} | 6 |
public void deleteMethod(final int nameIndex, final int typeIndex) {
final List newMethods = new ArrayList();
boolean foundIt = false;
for (int i = 0; i < this.methods.length; i++) {
final Method method = this.methods[i];
if ((method.nameIndex() == nameIndex)
&& (method.typeIndex() == typeIndex)) {
foundIt = true;
} else {
newMethods.add(method);
}
}
if (!foundIt) {
final String s = "No method with name index " + nameIndex
+ " and type index " + typeIndex + " in " + this.name();
throw new IllegalArgumentException(s);
} else {
this.methods = (Method[]) newMethods.toArray(new Method[0]);
}
} | 4 |
public Atvalinajums() {
} | 0 |
private void annuleer() {
try {
quizWijzigenView.confirmationWindow(
"Ben je zeker dat je de wijzigingen wilt annuleren?",
"Annuleer wijzigingen");
if (quizWijzigenView.isTrueIndicator()) {
for (Quiz q : quizCatalogus.getQuizzen()) {
if (q.getId() == copyQuizOld.getId()) {
q = copyQuizOld;
}
}
quizWijzigenView.closeWindow();
}
} catch (Exception e) {
System.out.println(e);
}
} | 4 |
private String cleanInput(String input) {
if (input == null) {
return null;
}
input = input.trim();
if (input.length() == 0) {
return null;
}
return input.toUpperCase();
} | 2 |
static Subject populate() {
ArrayList<Subject> data = new ArrayList<>();
Subject sun = new Subject(1392e+6);
sun.meta.color = new Color(0xFEE640);
sun.meta.name = "Sun";
sun.meta.type = SubjectType.STAR;
sun.meta.scale = 0.5f;
Subject mercury = new Subject(2439e+3, 87.97 * DAY, new PolarCoordinate(0, 58e+9));
mercury.meta.name = "Mercury";
mercury.meta.type = SubjectType.PLANET;
mercury.meta.period = 115;
mercury.meta.color = new Color(0xFEC07D);
mercury.meta.image = Data.class.getResource("/img/mercury_398x398.png");
sun.add(mercury);
Subject venus = new Subject(6051e+3, 224.7 * DAY, new PolarCoordinate(0, 108e+9));
venus.meta.name = "Venus";
venus.meta.type = SubjectType.PLANET;
venus.meta.period = 224;
venus.meta.color = new Color(0xA7A443);
venus.meta.image = Data.class.getResource("/img/venus_940x940.png");
sun.add(venus);
Subject earth = new Subject(6051e+3, 365.0 * DAY, new PolarCoordinate(0, 149e+9));
earth.meta.name = "Earth";
earth.meta.type = SubjectType.PLANET;
earth.meta.period = 365;
earth.meta.color = new Color(0x15ABFF);
earth.meta.image = Data.class.getResource("/img/earth_512x512.png");
Subject moon = new Subject(1738e+3, 29.5 * DAY, new PolarCoordinate(0, 384e+6));
moon.meta.name = "Moon";
moon.meta.type = SubjectType.MOON;
moon.meta.period = 29;
moon.meta.color = new Color(0xE9E4EA);
earth.add(moon);
sun.add(earth);
Subject mars = new Subject(4439e+3, 779.0 * DAY, new PolarCoordinate(0, 200e+9));
mars.meta.name = "Mars";
mars.meta.type = SubjectType.PLANET;
mars.meta.color = new Color(0xCA7E31);
mars.meta.period = 779;
mars.meta.image = Data.class.getResource("/img/mars_512x512.png");
sun.add(mars);
Subject fobos = new Subject(11.1e+3, 7 * HOUR + 39 * MINUTE + 14, new PolarCoordinate(0, 9.377e+6));
fobos.meta.name = "Fobos";
fobos.meta.type = SubjectType.MOON;
fobos.meta.color = new Color(0x9FACB6);
fobos.meta.scale = 10;
mars.add(fobos);
Subject deimos = new Subject(12e+3, 30 * HOUR + 17 * MINUTE + 55, new PolarCoordinate(0, 23.458e+6));
deimos.meta.name = "Deimos";
deimos.meta.type = SubjectType.MOON;
deimos.meta.color = new Color(0xB1B6AE);
deimos.meta.scale = 10;
mars.add(deimos);
Subject jupiter = new Subject(69_911e+3, 4332.6 * DAY, new PolarCoordinate(0, 770e+9));
jupiter.meta.name = "Jupiter";
jupiter.meta.type = SubjectType.PLANET;
jupiter.meta.period = 4_332;
jupiter.meta.color = new Color(0x826E49);
jupiter.meta.scale = 1;
jupiter.meta.image = Data.class.getResource("/img/jupiter_600x600.png");
sun.add(jupiter);
Subject io = new Subject(1821e+3, 42.5 * DAY, new PolarCoordinate(0, 421e+6));
io.meta.name = "Io";
io.meta.type = SubjectType.MOON;
io.meta.color = new Color(0xD2CE1E);
io.meta.scale = 2;
jupiter.add(io);
Subject europa = new Subject(1560e+3, 3.551 * DAY, new PolarCoordinate(0, 671e+6));
europa.meta.name = "Europa";
europa.meta.type = SubjectType.MOON;
europa.meta.color = new Color(0xDBAEAD);
europa.meta.scale = 2;
jupiter.add(europa);
Subject ganymede = new Subject(2634e+3, 7.1 * DAY, new PolarCoordinate(0, 1070e+6));
ganymede.meta.name = "Ganymede";
ganymede.meta.type = SubjectType.MOON;
ganymede.meta.color = new Color(0xC6B4B3);
ganymede.meta.scale = 2;
jupiter.add(ganymede);
Subject callisto = new Subject(2410e+3, 16.7 * DAY, new PolarCoordinate(0, 1882e+6));
callisto.meta.name = "Callisto";
callisto.meta.type = SubjectType.MOON;
callisto.meta.color = new Color(0xB4A891);
callisto.meta.scale = 2;
jupiter.add(callisto);
// 60 268
Subject saturn = new Subject(60_268e+3, 10_759 * DAY, new PolarCoordinate(0, 1_433e+9));
saturn.meta.name = "Saturn";
saturn.meta.type = SubjectType.PLANET;
saturn.meta.color = new Color(0xDFD864);
saturn.meta.period = 10_759;
saturn.meta.image = Data.class.getResource("/img/saturn_1258x512.png");
sun.add(saturn);
Subject mimas = new Subject(397e+3, 0.942 * DAY, new PolarCoordinate(0, 185.4e+6));
mimas.meta.name = "Mimas";
mimas.meta.type = SubjectType.MOON;
mimas.meta.color = new Color(0xDFD864);
saturn.add(mimas);
Subject enceladus = new Subject(499e+3, 1.37 * DAY, new PolarCoordinate(0, 237.4e+6));
enceladus.meta.name = "Enceladus";
enceladus.meta.type = SubjectType.MOON;
enceladus.meta.color = new Color(0xBAE8EA);
saturn.add(enceladus);
Subject tethys = new Subject(1060e+3, 1.888 * DAY, new PolarCoordinate(0, 294.6e+6));
enceladus.meta.name = "Tethys";
enceladus.meta.type = SubjectType.MOON;
enceladus.meta.color = new Color(0xE3DBE2);
saturn.add(tethys);
Subject dione = new Subject(1118e+3, 2.737 * DAY, new PolarCoordinate(0, 377.4e+6));
dione.meta.name = "Dione";
dione.meta.type = SubjectType.MOON;
dione.meta.color = new Color(0xE3DBE2);
saturn.add(dione);
Subject rhea = new Subject(1528e+3, 4.518 * DAY, new PolarCoordinate(0, 527e+6));
rhea.meta.name = "Rhea";
rhea.meta.type = SubjectType.MOON;
rhea.meta.color = new Color(0xE3DBE2);
saturn.add(rhea);
Subject titan = new Subject(5150e+3, 15.95 * DAY, new PolarCoordinate(0, 1_221e+6));
titan.meta.name = "Titan";
titan.meta.type = SubjectType.MOON;
titan.meta.color = new Color(0xE3D8A1);
saturn.add(titan);
Subject iapetus = new Subject(1436e+3, 79.33 * DAY, new PolarCoordinate(0, 3_560e+6));
iapetus.meta.name = "Iapetus";
iapetus.meta.type = SubjectType.MOON;
iapetus.meta.color = new Color(0xE3E2CF);
saturn.add(iapetus);
Subject uranus = new Subject(25_559e+3, 30_685d * DAY, new PolarCoordinate(0, 2_876e+9));
uranus.meta.name = "Uranus";
uranus.meta.type = SubjectType.PLANET;
uranus.meta.color = new Color(0x93D6DF);
uranus.meta.period = 10_759;
uranus.meta.image = Data.class.getResource("/img/uranus_512x512.png");
sun.add(uranus);
Subject miranda = new Subject(235.8e+3, 1.413 * DAY, new PolarCoordinate(0, 129e+6));
miranda.meta.name = "Miranda";
miranda.meta.type = SubjectType.MOON;
miranda.meta.color = new Color(DEFAULT_COLOR);
uranus.add(miranda);
Subject ariel = new Subject(578.9e+3, 2.520 * DAY, new PolarCoordinate(0, 190e+6));
ariel.meta.name = "Ariel";
ariel.meta.type = SubjectType.MOON;
ariel.meta.color = new Color(DEFAULT_COLOR);
uranus.add(ariel);
Subject umbriel = new Subject(1169.4e+3, 4.144 * DAY, new PolarCoordinate(0, 266e+6));
umbriel.meta.name = "Umbriel";
umbriel.meta.type = SubjectType.MOON;
umbriel.meta.color = new Color(DEFAULT_COLOR);
uranus.add(umbriel);
Subject titania = new Subject(1576.8e+3, 8.706 * DAY, new PolarCoordinate(0, 436e+6));
titania.meta.name = "Titania";
titania.meta.type = SubjectType.MOON;
titania.meta.color = new Color(DEFAULT_COLOR);
uranus.add(titania);
Subject oberon = new Subject(1522.8e+3, 13.46 * DAY, new PolarCoordinate(0, 583e+6));
oberon.meta.name = "Oberon";
oberon.meta.type = SubjectType.MOON;
oberon.meta.color = new Color(DEFAULT_COLOR);
uranus.add(oberon);
Subject neptune = new Subject(24_764e+3, 60_190d * DAY, new PolarCoordinate(0, 4_503e+9));
neptune.meta.name = "Neptune";
neptune.meta.type = SubjectType.PLANET;
neptune.meta.color = new Color(0x335CE9);
neptune.meta.period = 60_190;
neptune.meta.image = Data.class.getResource("/img/neptune_512x512.png");
sun.add(neptune);
Subject triton = new Subject(2706.8e+3, 5.877 * DAY, new PolarCoordinate(0, 354e+6));
triton.meta.name = "Triton";
triton.meta.type = SubjectType.MOON;
triton.meta.color = new Color(DEFAULT_COLOR);
neptune.add(triton);
double size;
double rate;
double radius;
double angle;
PolarCoordinate p;
Subject aster;
//
for (int i = 0; i < 2000; i++) {
size = 2000e+3 * Math.random() * Math.random();
rate = (800 + Math.random() * 100) * 86_400;
radius = 400e9 + Math.random() * Math.random() * 60e9 * (Math.random() - 0.5);
angle = Math.random() * Math.PI * 2;
aster = new Subject(size, rate, new PolarCoordinate(angle, radius));
aster.meta.type = SubjectType.ASTEROID;
sun.add(aster);
}
return sun;
} | 1 |
public int antiFire() {
int toReturn = 0;
if (c.antiFirePot)
toReturn++;
if (c.playerEquipment[c.playerShield] == 1540 || c.prayerActive[12] || c.playerEquipment[c.playerShield] == 11284)
toReturn++;
return toReturn;
} | 4 |
public void saveResult(GameResult result) {
cacheGameResultsMaps(result);
FileOutputStream fo = null;
BufferedWriter bw = null;
try {
fo = new FileOutputStream(new File(this.resultsDataFilePath));
bw = new BufferedWriter(new OutputStreamWriter(fo));
for(Map.Entry<String, List<GameResult>> entry : resultsMappedByGroup.entrySet()){
for(GameResult gameResult : entry.getValue()){
bw.write(gameResult.toString());
bw.newLine();
}
}
bw.flush();
} catch (FileNotFoundException e) {
logger.error("Can't find file :" + this.resultsDataFilePath, e);
} catch (IOException e) {
logger.error("Failed to read content from file :" + this.resultsDataFilePath, e);
} finally {
try {
if (null != fo) {
fo.close();
}
if (null != bw) {
bw.close();
}
} catch (IOException e) {
//e.printStackTrace();
// IGNORE this exception
}
}
} | 7 |
@Override
public void setPrerequisites(String prerequisites) {
if(prerequisites == null || prerequisites.length() == 0) {
JOptionPane.showMessageDialog(null,
"Error: prerequisites cannot be null of empty string");
System.exit(0);
}
this.prerequisites = prerequisites;
} | 2 |
@Override
public Object getValueAt(int i, int i1) {
Tenant t=tenants.get(i); //To change body of generated methods, choose Tools | Templates.
switch(i1){
case 0:
return t.getId();
case 1:
return t.getName();
case 2:
return t.getAddress();
case 3:
return t.getTel();
case 4:
return t.getRoom();
case 5:
return t.getRentDate();
case 6:
return t.getPayStatus();
default:
return null;
}
} | 7 |
@Test
public final void testIntersectCorners() {
SpaceRegion sr1 = new SpaceRegion("sr1");
SpaceRegion sr2 = new SpaceRegion( sr1, "sr1");
Assert.assertTrue( sr1.intersects( sr1 ) );
Assert.assertTrue( sr1.intersects( sr2 ) );
for ( float x = -1.0f; x <= 1.0f; x += 0.1f ) {
sr2.localPosition.x = x;
for ( float y = -1.0f; y <= 1.0f; y += 0.1f ) {
sr2.localPosition.y = y;
for ( float z = -1.0f; z <= 1.0f; z += 0.1f ) {
sr2.localPosition.z = z;
for ( float dx = 1.0f; dx <= 2.0f; dx += 0.1f ) {
sr2.size.x = dx;
for ( float dy = 1.0f; dy <= 2.0f; dy += 0.1f ) {
sr2.size.y = dy;
for ( float dz = 1.0f; dz <= 2.0f; dz += 0.1f ) {
sr2.size.z = dz;
Assert.assertTrue( sr1.intersects( sr2 ) );
}
}
}
}
}
}
sr1.localPosition.set( 0.0f, 0.0f, 0.0f );
sr2.localPosition.set( 0.0f, 0.0f, 0.0f );
sr2.localPosition.set( 0.3f, -1.0f, -1.0f );
sr2.size.set( 0.3f, 2.0f, 2.0f );
Assert.assertTrue( sr1.intersects( sr2 ) );
Assert.assertTrue( sr2.intersects( sr1 ) );
sr2.localPosition.set( -1.0f, 0.3f, -1.0f );
sr2.size.set( 2.0f, 0.3f, 2.0f );
Assert.assertTrue( sr1.intersects( sr2 ) );
Assert.assertTrue( sr2.intersects( sr1 ) );
sr2.localPosition.set( -1.0f, -1.0f, 0.3f );
sr2.size.set( 2.0f, 2.0f, 0.3f );
Assert.assertTrue( sr1.intersects( sr2 ) );
Assert.assertTrue( sr2.intersects( sr1 ) );
sr2.localPosition.set( 0.3f, 0.3f, 0.3f );
sr2.size.set( 0.3f, 0.3f, 0.3f );
Assert.assertTrue( sr1.intersects( sr2 ) );
Assert.assertTrue( sr2.intersects( sr1 ) );
sr2.localPosition.set( 0.3f, -2.0f, 0.3f );
sr2.size.set( 0.3f, 2.0f, 0.3f );
Assert.assertTrue( sr1.intersects( sr2 ) );
Assert.assertFalse( sr1.intersects( null ) );
} | 6 |
private boolean check(EdgeWeightedDigraph G) {
// edge-weighted digraph is cyclic
if (hasCycle()) {
// verify cycle
DirectedEdge first = null, last = null;
for (DirectedEdge e : cycle()) {
if (first == null) first = e;
if (last != null) {
if (last.to() != e.from()) {
System.err.printf("cycle edges %s and %s not incident\n", last, e);
return false;
}
}
last = e;
}
if (last.to() != first.from()) {
System.err.printf("cycle edges %s and %s not incident\n", last, first);
return false;
}
}
return true;
} | 6 |
@Override
//Controls the MainCharacterFigure's movement based on user input from the arrow keys
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
if (dyMC >= -560) {
dyMC -= 4;
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (dyMC <= 0) {
dyMC += 4;
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (dxMC <= 230) {
dxMC += 4;
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (dxMC >= -230) {
dxMC -= 4;
}
repaint();
}
} | 9 |
protected XPathFactory newFactory()
throws XPathFactoryConfigurationException
{
// First try to force the default JRE impl
try
{
return XPathFactory.newInstance(
XPathFactory.DEFAULT_OBJECT_MODEL_URI,
"com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl",
null);
}
catch(XPathFactoryConfigurationException ignore) {}
// If that failed use auto-discovery
return XPathFactory.newInstance();
} | 1 |
public String readLine() throws IOException
{
String s = super.readLine();
if (s.indexOf('\\') >= 0)
{
StringBuffer buffer = new StringBuffer(s.length());
for (int i = 0; i < s.length();)
{
char c = s.charAt(i++);
if (c == '\\')
switch (s.charAt(i++))
{
case '\\':
buffer.append('\\');
break;
case 't':
buffer.append('\t');
break;
case 'n':
buffer.append('\n');
break;
case 'r':
buffer.append('\r');
break;
case 'f':
buffer.append('\f');
break;
case 'u':
buffer.append((char) Integer.parseInt(
s.substring(i, i += 4), 16));
break;
}
else
buffer.append(c);
}
s = buffer.toString();
}
return s;
} | 9 |
public int mergeAdjacentFace (HalfEdge hedgeAdj,
Face[] discarded)
{
Face oppFace = hedgeAdj.oppositeFace();
int numDiscarded = 0;
discarded[numDiscarded++] = oppFace;
oppFace.mark = DELETED;
HalfEdge hedgeOpp = hedgeAdj.getOpposite();
HalfEdge hedgeAdjPrev = hedgeAdj.prev;
HalfEdge hedgeAdjNext = hedgeAdj.next;
HalfEdge hedgeOppPrev = hedgeOpp.prev;
HalfEdge hedgeOppNext = hedgeOpp.next;
while (hedgeAdjPrev.oppositeFace() == oppFace)
{ hedgeAdjPrev = hedgeAdjPrev.prev;
hedgeOppNext = hedgeOppNext.next;
}
while (hedgeAdjNext.oppositeFace() == oppFace)
{ hedgeOppPrev = hedgeOppPrev.prev;
hedgeAdjNext = hedgeAdjNext.next;
}
HalfEdge hedge;
for (hedge=hedgeOppNext; hedge!=hedgeOppPrev.next; hedge=hedge.next)
{ hedge.face = this;
}
if (hedgeAdj == he0)
{ he0 = hedgeAdjNext;
}
// handle the half edges at the head
Face discardedFace;
discardedFace = connectHalfEdges (hedgeOppPrev, hedgeAdjNext);
if (discardedFace != null)
{ discarded[numDiscarded++] = discardedFace;
}
// handle the half edges at the tail
discardedFace = connectHalfEdges (hedgeAdjPrev, hedgeOppNext);
if (discardedFace != null)
{ discarded[numDiscarded++] = discardedFace;
}
computeNormalAndCentroid ();
checkConsistency();
return numDiscarded;
} | 6 |
@Override
public void start()
{
worker = new Thread()
{
@Override
public void run()
{
while (!this.isInterrupted())
{
int currentFrame = Integer.parseInt(pModel.getProperty(PRP_CURRENT_PLAYBACK_FRAME));
if (++currentFrame >= Recorder.getInstance().getFrameCount())
{
currentFrame = 1;
}
pModel.setProperty(PRP_CURRENT_PLAYBACK_FRAME, "" + currentFrame);
try
{
Thread.sleep(deltaTime);
}
catch (InterruptedException e)
{
// may occur, but should not be a problem, we just ignore it
//e.printStackTrace();
// finally we need to set the interrupt flag again, because
// it was rejected by the exception
this.interrupt();
}
}
}
};
worker.start();
} | 3 |
public boolean contains(Coordinate p) {
double res = 0;
for(int i=1; i<this.corners.length; i++)
res += this.corners[i-1].sub(p).angle(this.corners[i].sub(p));
return Math.abs(res) > 6;
} | 1 |
public void mouseClicked(MouseEvent e) {
} | 0 |
public static void main(String[] args) {
logger.info("Trains application started");
TrainGenerator tGenerator = null;
try {
tGenerator = new TrainGenerator( 20 );
PassengerTrain pTrain = tGenerator.buildPassengerTrain();
double commonBaggageWeight = TrainOperations.commonBaggageWeight( pTrain );
int commonPassengersCnt = TrainOperations.commonPassengersCount(pTrain);
pTrain.sort(Collections.reverseOrder(new ComfortComparator()) );
ArrayList<PassengerCar> pCars = TrainOperations.findPassengerCars( pTrain, 40, 80 );
} catch (OutOfRangeException e) {
logger.error( "OutOfRange exception in Main");
}
} | 1 |
public void setStartStop(int value) {
this._startStop = value;
} | 0 |
public static void main(String[] args) throws Exception {
if (args.length > 0 && args[0].equals("-r")) {
remove = true;
String[] nargs = new String[args.length - 1];
System.arraycopy(args, 1, nargs, 0, nargs.length);
args = nargs;
}
new ProcessFiles(new AtUnitRemover(), "class").start(args);
} | 2 |
public Ventana() {
initComponents();
leerProperties();
//PERSONAS
//creo el modelo, sobreescribiendo el método isCellEditable para que
//sólo pueda modificarse el campo persona.
DefaultTableModel modeloPersona = new DefaultTableModel() {
@Override
public boolean isCellEditable(int fila, int columna) {
return columna == Constantes.column_nombre;
}
};
//cargo el modelo
modeloPersona.addColumn("ID");
modeloPersona.addColumn("NOMBRE");
jTable.setModel(modeloPersona);
//COMPRAS
DefaultTableModel modeloCompra = new DefaultTableModel();
//cargo el modelo de las compras
modeloCompra.addColumn("ID");
modeloCompra.addColumn("Cantidad");
modeloCompra.addColumn("Concepto");
jTableCompras.setModel(modeloCompra);
jTable.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent tme) {
//cuando cambia algo en el modelo se modifica en el array en memoria
if (jTable.getSelectedRow() != -1 && !borrando) {
//cambiamos la persona
listaP.replace(
(Integer) jTable.getValueAt(jTable.getSelectedRow(), Constantes.column_id),
new Persona(
Integer.parseInt(jTable.getValueAt(jTable.getSelectedRow(), Constantes.column_id).toString()),
jTable.getValueAt(jTable.getSelectedRow(), Constantes.column_nombre).toString(),
new LinkedHashMap<Integer, Compra>()
)
);
}
}
});
ventanaCompras.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
ventanaCompras.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
UIManager.put("OptionPane.noButtonText", "No, guarda los cambios");
UIManager.put("OptionPane.yesButtonText", "Si, salir sin guardar");
int guardar = JOptionPane.showConfirmDialog(ventanaCompras, "¿Desea salir sin guardar las compras de " + listaP.get(idPersona).getNombre()+"?");
//cancelar=2,No=1, Si=0
if (guardar == 2) {
//no hacmos nada porque es cancelar
} else {
if (guardar == 1) {//No, guarda
// guardamos lo que hay en el modelo en el fichero
LinkedHashMap<Integer, Compra> comprasP;
//de tabla a LinkedHashMap
comprasP = deTablaAMapCompras();
//y guardo a fichero
FicherosDatos fd = new FicherosDatos();
fd.guardarCompraDOM(rutaBD + idPersona + Constantes.archivoCompras, comprasP);
//guardo en la variable del array en memoria
listaP.get(idPersona).setCompras(comprasP);
//y por último salimos de las compras
ventanaCompras.setVisible(false);
} else {//Si salir sin guardar
//No desea guardar, así que salgo sin guardar nada
ventanaCompras.setVisible(false);
}
}
}
@Override
public void windowClosed(WindowEvent e) {
}
@Override
public void windowIconified(WindowEvent e) {
}
@Override
public void windowDeiconified(WindowEvent e) {
}
@Override
public void windowActivated(WindowEvent e) {
}
@Override
public void windowDeactivated(WindowEvent e) {
}
});
} | 4 |
@Override
public void mouseClicked(final MouseEvent e) {
this.e = e;
player.setActivityTimer(1000);
//if(player.getActivityTimer()==0){
new Thread(new Runnable(){
@Override
public void run() {
FlirtOverlay overlay = (FlirtOverlay)((JLabel) e.getSource()).getParent();
overlay.progress.setVisible(true);
overlay.progressText.setVisible(true);
overlay.close.setVisible(false);
while(player.getActivityTimer()>0) {
// System.out.println("Event"+player.getActivityTimer());
switch(player.getActivityTimer()*5/1000) {
case 3:
overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress1.getImage()));
break;
case 2:
overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress2.getImage()));
break;
case 1:
overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress3.getImage()));
break;
case 0:
overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress4.getImage()));
}
try {
Thread.sleep(40);
} catch (InterruptedException e1) {}
}
System.out.println(as.getActivity() + " " + as.getActivityTimer());
DiscoObject.setStatusES(player, action);
((JLabel) e.getSource()).getParent().setVisible(false);
((JLabel) e.getSource()).getParent().setEnabled(false);
disableActions();
player.setActivity(0);
as.setActivity(0);
as.setActivityTimer(0);
System.out.println(player.getActivityTimer());
// bar.openOverlay=false;
// Reset
overlay.progress.setIcon(new ImageIcon(overlay.graphicManager.progress0.getImage()));
overlay.progress.setVisible(false);
overlay.progressText.setVisible(false);
overlay.close.setVisible(true);
((JLabel) e.getSource()).setIcon(i);
}
}).start();;
//}
} | 6 |
public void start(MouseEvent e, mxCellState state)
{
startState = state;
movingCells = getCells(state);
previewStates = (!placeholderPreview) ? getPreviewStates() : null;
if (previewStates == null || previewStates.length >= threshold)
{
placeholder = getPlaceholderBounds(startState).getRectangle();
initialPlaceholder = new Rectangle(placeholder);
graphComponent.getGraphControl().repaint(placeholder);
}
fireEvent(new mxEventObject(mxEvent.START, "event", e, "state",
startState));
} | 3 |
public void upByThrees(int n) {
/*int tracker = 1;
for (int i = 0; i < n; i++) {
System.out.println(tracker);
tracker +=3;
}*/
int tracker = 1;
int i = 0;
while(i < n){
System.out.println(tracker);
tracker=tracker+3;
i++;
}
} | 1 |
public void run(){
while (!stop) {
String randData = Rndm.randString(Rndm.intRandInt(32, 1024));
int port = Rndm.intRandInt(1, 65535);
send(randData, port);
}
} | 1 |
public ProvaDequantizzazione(String fileName) throws Exception {
encoder = new LayerIIIEnc(N_FRAME);
is = getClass().getResourceAsStream(fileName);
bitstream = new BitStream(is);
real_stream = getClass().getResourceAsStream(fileName);
//byte [] b = new byte [100000];
//real_stream.read(b,0,100000);
header = bitstream.readFrame();
decoder = new LayerIIIDecoder(bitstream, header);
mp3_byte_stream = new byte[418 * N_FRAME];
int position = 0;
System.out.print("\n\nE3 = [");
while(cont < N_FRAME){
// System.out.println("\n\n---------------------------------------------(Step 1 - Iteration number: " + cont + ")---------------------------------------------");
if(header.getFramesize() > 0){
decoder.decodeFrame(Constants.DEQUANTIZED_DOMAIN);
float ro [][][] = decoder.get_ro();
FrameData fd = decoder.getFrameInfo();
float [][] energy = {{0.0f, 0.0f}, {0.0f, 0.0f}};
for(int gr = 0; gr < 2; gr++){
for(int ch = 0; ch < 2; ch++){
energy[gr][ch] = 0.0f;
// System.out.println("\n**************************** ch: "+ch+" gr: "+gr+" *************************************");
if(fd.getBlockType(ch, gr) != 2){
for(int b = 0; b < ro[gr][ch].length; b++)
energy[gr][ch] += (float)((ro[gr][ch][b]) * (ro[gr][ch][b]));
energy[gr][ch] /= 576;
}
/* if(fd.getBlockType(ch, gr) == 2){
float energy1 = 0, energy2 = 0, energy3 = 0;
int sb = 0;
for(sb = 0; sb < 192; sb++){
energy1 += (float)((ro[ch][gr][sb]) * (ro[ch][gr][sb]));
}
for(; sb < 384; sb++){
energy2 += (float)((ro[ch][gr][sb]) * (ro[ch][gr][sb]));
}
for(; sb < 576; sb++){
energy3 += (float)((ro[ch][gr][sb]) * (ro[ch][gr][sb]));
}
energy[ch][gr] = energy1 + energy2 +energy3;
energy[ch][gr] /= 192;
}*/
//System.out.println("block flag: " + fd.getMixedBlockFlag(ch, gr));
//System.out.println("subblock gain: " + fd.getSubblockGain(ch, gr));
}
}
// System.out.println("MS stereo: " + fd.getMS_stereo());
//float E = energy[0][0] + energy[0][1] + energy[1][0] + energy[1][1];
float E = energy[0][1] + energy[1][1];
System.out.print(" " + E);
/* System.out.println("energy 0,0: " + energy[0][0]);
System.out.println("energy 1,0: " + energy[1][0]);
System.out.println("energy 0,,: " + energy[0][1]);
System.out.println("energy 1,1: " + energy[1][1]);
System.out.println("en totale: " + E); */
}
header = bitstream.readFrame();
cont++;
}
System.out.print("];\n");
// if(N_FRAME <= 10) Checker.compareStream(mp3_byte_stream, b);
/* for(int i = 0; i < mp3_byte_stream.length; i++) {
System.out.print("byte " + i + ": " + mp3_byte_stream[i]);
System.out.print(" | " + b[i + off]);
if(b[i+off]!= mp3_byte_stream[i])
System.out.print("<-------------------------------------------------- DIVERSO!!!!!!!");
if((i % 418) == 0) System.out.print(" <-- begin of frame " + (i / 418 + 1));
if((i % 418) == 4){
System.out.print(" <-- main_data_beg: ");
int beg = (mp3_byte_stream[i] >= 0) ? ((mp3_byte_stream[i] << 1)+((mp3_byte_stream[i+1]>>> 7) & 1)): (((mp3_byte_stream[i] + 256) << 1)+((mp3_byte_stream[i+1]>>> 7) & 1));
System.out.print(beg);
beg = (b[i+off] >= 0) ? ((b[i+off] << 1)+((b[i+1+off]>>> 7) & 1)): (((b[i+off] + 256) << 1)+((b[off+i+1]>>> 7) & 1));
System.out.print(" | "+beg);
}
if((i % 418) == 36) System.out.print(" <-- begin of data in frame");
System.out.print("\n");
}*/
} | 6 |
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
g.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), this);
g.setColor(Color.red);
if(points != null && !points.isEmpty()){
for(int i = 0; i < points.size(); i++){
g.fillOval(points.get(i).getLocation().x - 4, points.get(i).getLocation().y - 4, 8, 8);
}
}
g.setColor(Color.yellow);
if(hoveredPoint != null) g.fillOval(hoveredPoint.getLocation().x - 4, hoveredPoint.getLocation().y - 4, 8, 8);
g.setColor(Color.red);
if(selectedPoint != null) g.fillOval(selectedPoint.getLocation().x - 6, selectedPoint.getLocation().y - 6, 12, 12);
g.setColor(Color.yellow);
if(selectedPoint != null) g.fillOval(selectedPoint.getLocation().x - 4, selectedPoint.getLocation().y - 4, 8, 8);
g.setColor(Color.BLACK);
for (int i = 0; i < edges.size(); i++)
{
g.drawLine(edges.get(i).a.getLocation().x, edges.get(i).a.getLocation().y, edges.get(i).b.getLocation().x, edges.get(i).b.getLocation().y);
}
if(drawingLine) g.drawLine(selectedPoint.getLocation().x, selectedPoint.getLocation().y, xDragged, yDragged);
} | 8 |
@Test
public void testGetCondVal() {
System.out.println("getCondVal");
Sense instance = new Sense(Sense.senseDir.HERE, 3, 6, Sense.condition.FOE);
Sense.condition expResult = Sense.condition.FOE;
Sense.condition result = instance.getCondVal();
assertEquals(expResult, result);
} | 0 |
private void fatalErrorOccured(String message, Exception ex){
if (ex != null) ex.printStackTrace();
frame.txtrn.setText("Ошибка: " + message);
try {
this.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
} | 2 |
public void registerEvents(Plugin plugin, EventListener listener) {
for (Method method : listener.getClass().getMethods()) {
Annotation annotation = method.getAnnotation(EventHandler.class);
if (annotation == null)
continue;
Class[] params = method.getParameterTypes();
if (params.length != 1)
continue;
Class eventType = params[0];
if (!(eventType.getSuperclass().equals(Event.class)))
continue;
if (!this.handlers.containsKey(plugin))
this.handlers.put(eventType, new ArrayList<EventHandlerInfo>());
this.handlers.get(eventType).add(new EventHandlerInfo(
plugin,
listener,
method
));
}
} | 5 |
public void run(){
while(true){
try {
if(Go==true){
if (vehicleList.size()>0){
printStreet(this);
Vehicle toMove = vehicleList.getFirst();
Street target = toMove.getTargetStreet();
if (target == null) {
vehicleList.removeFirst();
toMove.stopVehicleThread();
}
else if (!target.isMax()) {
vehicleList.removeFirst();
toMove.moveFrontVehicle(); // move Front vehicle
}
printStreet(this);
printStreet(target);
}
//System.out.println("After:");
//printStreet(this);
Thread.sleep(timeDelay);
}
else
//Main.record("Street " + streetName + " is inside false");
Thread.sleep(timeDelay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // wait a bit according to its timeDelay rate
}
// have function that checks if there is an ambulance on alert? ambulance should notify street
} | 6 |
protected AudioDeviceFactory[] getFactoriesPriority()
{
AudioDeviceFactory[] fa = null;
synchronized (factories)
{
int size = factories.size();
if (size!=0)
{
fa = new AudioDeviceFactory[size];
int idx = 0;
Enumeration e = factories.elements();
while (e.hasMoreElements())
{
AudioDeviceFactory factory = (AudioDeviceFactory)e.nextElement();
fa[idx++] = factory;
}
}
}
return fa;
} | 2 |
private void render(Graphics2D graphics2D) {
for (Cell[] cells1 : cells) {
for (Cell cell : cells1) {
cell.render(graphics2D);
}
}
} | 2 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Genre other = (Genre) obj;
if (myName == null) {
if (other.myName != null)
return false;
} else if (!myName.equals(other.myName))
return false;
if (myChildren == null) {
if (other.myChildren != null)
return false;
} else if (!myChildren.equals(other.myChildren))
return false;
return 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.