text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static Vector<Integer> SLOrestricted(GraphModel g, Vector<Integer> V) {
List<Pair<Integer, Integer>> VertexDegree = new Vector<>();
Vector<Integer> Ordering = new Vector<>();
//Compute N_2-degree for all vertices in V
for (int v : V) {
VertexDegree.add(new Pair<>(v, Neighbors.N_2_restricted(g, v).size()));
}
for (int i = 0; i < V.size(); i++) {
int min = g.getEdgesCount() + 1;
int minInd = g.getEdgesCount() + 1;
for (int j = 0; j < VertexDegree.size(); j++) {
if (min > VertexDegree.get(j).second) {
minInd = j;
min = VertexDegree.get(j).second;
}
}
Pair<Integer, Integer> p = VertexDegree.get(minInd);
p.second = g.getEdgesCount();
VertexDegree.set(i, p);
Ordering.add(p.first);
//decrement degree of D_2-neighbors
Vector<Integer> ns = Neighbors.N_2_restricted(g, p.first);
for (int n2 : ns) {
if (n2 >= V.size()) {
if (VertexDegree.get(n2 - V.size()).second != -1) {
Pair<Integer, Integer> tmp = VertexDegree.get(n2 - V.size());
tmp.second--;
VertexDegree.set(n2 - V.size(), tmp);
}
} else {
if (VertexDegree.get(n2).second != -1) {
Pair<Integer, Integer> tmp = VertexDegree.get(n2);
tmp.second++;
VertexDegree.set(n2, tmp);
}
}
}
if (i % 100 == 0) {
System.out.println("i=" + i);
}
}
Collections.reverse(VertexDegree);
return Ordering;
} | 9 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//ADD SEARCH STUFF HERE
Search searcher = new Search();
String title = titleText.getText();
String crn = crnText.getText();
String professor = professorText.getText();
String attribute = attributeText.getText();
String info;
if(!title.isEmpty())
{
try{
info = (searcher.search("title", title));
resultsArea.setText(info);
}
catch (Exception e) {
System.out.println(e);
}
}
if(!crn.isEmpty())
{
try{
info = (searcher.search("crn", crn));
resultsArea.setText(info);
}
catch (Exception e) {
System.out.println(e);
}
}
if(!professor.isEmpty())
{
try{
info = (searcher.search("instructor", professor));
resultsArea.setText(info);
}
catch (Exception e) {
System.out.println(e);
}
}
if(!attribute.isEmpty())
{
try{
info = (searcher.search("atc", attribute));
resultsArea.setText(info);
}
catch (Exception e) {
System.out.println(e);
}
}
}//GEN-LAST:event_jButton1ActionPerformed | 8 |
@Override
public Object evaluate(ArrayList<Context1> pila_basura) throws Exception {
try{
StringBuilder output = new StringBuilder();
for (Evaluator e : lista) {
if (e != null) {
if (e instanceof ReturnEvaluator) {
return e.evaluate(pila);
}
Object ob;
ob = e.evaluate(pila);
if (ob != null) {
if (ob instanceof Double)
output.append(((Double) ob).toString());
else
output.append(ob.toString());
}
if (e instanceof WhileEvaluator) {
if (((WhileEvaluator) e).getBandera())
return ob;
}
if (e instanceof IfEvaluator) {
if (((IfEvaluator) e).getBandera())
return ob;
}
}
}
return output.toString();
}finally{
//pila.remove(pila.size() - 1);
}
} | 9 |
public void setParent(Node<T> parent) {
this.parent = parent;
if (parent != null) {
for (Node<T> sibling : parent.children) {
if (sibling == this) {
return;
}
}
parent.children.add(this);
}
} | 3 |
public String toString() {
IntFraction f = simp(this);
if (f.d == 0)
return "Error: Denominator is zero.";
else if (f.n == 0)
return "0";
else if (f.d == 1)
return String.valueOf((negative?"-":"") + f.n);
else if (f.n < f.d)
return (negative?"-":"") + f.n + "/" + f.d;
else
return (negative?"-":"") + f.n/f.d + "_" + f.n%f.d + "/" + f.d;
} | 7 |
public AntiAliasingLine(Excel ex1, Excel ex2) {
begin = ex1;
end = ex2;
setColoredExes();
} | 0 |
public CardListPanel() {
final CardTableModel dm = new CardTableModel();
final JTable t = new JTable(dm);
dm.setTable(t);
t.getColumnModel().getColumn(0).setCellRenderer(
new DefaultTableCellRenderer() {
private static final long serialVersionUID = -9109954835956521771L;
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (value instanceof Card) {
Card c = (Card) value;
value = c.getName();
Component comp = super
.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row,
column);
if (!isSelected) {
if (!c.isEnabled()) {
comp.setForeground(Color.GRAY);
} else {
comp.setForeground(Color.BLACK);
}
}
return comp;
} else {
return super.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
}
}
});
this.setLayout(new BorderLayout());
JPanel tools = new JPanel();
tools.setOpaque(false);
tools.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 2, 3, 2);
c.gridx = 0;
/*
* c.gridy=0; tools.add(new JButton("Remove"),c); c.gridx++;
* tools.add(new JButton("Assign to user"),c);
*/
JPanel blank = new JPanel();
blank.setOpaque(false);
c.weightx = 1;
c.gridx++;
tools.add(blank, c);
this.add(tools, BorderLayout.NORTH);
split = new JSplitPane();
JScrollPane comp = new JScrollPane(t);
comp.setMinimumSize(new Dimension(200, 200));
comp.setPreferredSize(new Dimension(200, 200));
split.setLeftComponent(comp);
split.setRightComponent(new JPanel());
this.add(split, BorderLayout.CENTER);
t.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int first = t.getSelectedRow();
if (first >= 0) {
Card c = dm.getCard(first);
if (c != null) {
if (split.getRightComponent() instanceof CardPropertiesPanel) {
CardPropertiesPanel up = (CardPropertiesPanel) split
.getRightComponent();
if (up.getCurrentCard().equals(c)) {
return;
}
}
split
.setRightComponent(new CardPropertiesPanel(
c));
} else {
System.err
.println("ClientListPanel: First index:"
+ first);
}
}
}
}
});
} | 8 |
public void write() {
if (!valid()) {
System.err.println("Not saving invalid map");
return;
}
try {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(filepath()));
output.writeObject(this);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 3 |
public static String protdist(String query, String model, String GammaDistrOfRates,
double CoeffOfVariation, double fracOfInvSites, String oneCatOfSubRates,
int noOfCat, String rateForEachCat, String categoriesFile, String UseWts4Posn, String weightsFile,
String analyzeMultipleDataSets, String DataWeights, int noOfMultipleDataSets, String inputSequencesInterleaved,
double transitionTransversion, String baseFreq, double ProbChangeCat, String geneticCode, String catOfAminoAcids) throws ImproperInputEx
{
GetAbsolutePath pt = new GetAbsolutePath();
String absolutePath = pt.getPath();
String output = "";
if (query.equals(""))
{
throw new ImproperInputEx("Job not Submitted: Query Cannot be Null");
}
try
{
//Are the inputs entered valid
boolean check =
verify(model, GammaDistrOfRates, CoeffOfVariation, fracOfInvSites,
oneCatOfSubRates, noOfCat, rateForEachCat, categoriesFile, UseWts4Posn, weightsFile,
analyzeMultipleDataSets, DataWeights, noOfMultipleDataSets, inputSequencesInterleaved,
transitionTransversion,baseFreq, ProbChangeCat, geneticCode, catOfAminoAcids);
if (check)
{
//Create a new Directory for Current request in tmp folder
String dirName = "PhylipProtdist:" + UUID.randomUUID().toString();
String dirNamePath = absolutePath + dirName;
boolean success = (new File(dirNamePath)).mkdir();
if (success)
{
System.out.println("Directory: " + dirNamePath + " created");
} else
{
System.out.println("Directory: " + dirNamePath + " Could not be created");
}
//to do in esle throw a user defined exception, so that execution haults beyond this point
FileWriter f = new FileWriter(dirNamePath + "/query.txt");
BufferedWriter w = new BufferedWriter(f);
w.write(query);
w.close();
if (categoriesFile.length() > 0)
{
f = new FileWriter(dirNamePath + "/categories");
BufferedWriter w1 = new BufferedWriter(f);
w1.write(categoriesFile);
w1.close();
}
if (weightsFile.length() > 0)
{
f = new FileWriter(dirNamePath + "/weights");
BufferedWriter w2 = new BufferedWriter(f);
w2.write(weightsFile);
w2.close();
}
//Create .sh file in the newly created Dir
String partCode = partCodeG;
partCode +="y\n";
partCode += restCode;
String code = "#!/bin/bash\n"
+ "cd " + dirNamePath + "\n"
+ "phylip protdist >>op.txt <<EOD\n"
+ "query.txt\n"
+ partCode
+ "EOD";
f = new FileWriter(dirNamePath + "/protdist.sh");
BufferedWriter ww = new BufferedWriter(f);
ww.write(code);
ww.close();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("sh " + dirNamePath + "/protdist.sh");
output = dirName;
}//end if
else
{
throw new ImproperInputEx(errorMsg);
}//end else
}
catch (ImproperInputEx ex)
{
throw new ImproperInputEx("Program failed due to : " + ex);
}//catch
catch (Exception e)
{
throw new UnexpectedErrorEx(e.getMessage());
}//catch
finally
{
return output;
}
} | 7 |
public static void changeLendability(MediaCopy mc, boolean lendable) {
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 MediaCopies SET lendable = ? WHERE copy_id = ?");
stmnt.setBoolean(1, lendable);
stmnt.setInt(2, mc.getMediaCopyID());
stmnt.execute();
conn.commit();
conn.setAutoCommit(true);
}catch(SQLException e){
System.out.println("update fail!! - " + e);
}
} | 4 |
public void redo() {
if (patchIndex >= undoPatches.size()) {
return;
}
UndoPatch p = undoPatches.get(patchIndex++);
// Perform patch
int prow;
for (prow = 0; prow < p.oldText.length; prow++) {
if (prow >= p.patchText.length) {
for (int da = p.oldText.length - prow; da > 0; da--) {
code.remove(p.startRow + prow);
}
break;
}
code.set(p.startRow + prow, new Line(p.patchText[prow]));
}
while (prow < p.patchText.length) {
code.add(p.startRow + prow, new Line(p.patchText[prow]));
prow++;
}
p.cafter.replace();
fireLineChange(p.startRow, p.startRow + p.oldText.length);
repaint();
} | 5 |
public PlotWindowView(PlotView view) {
setTitle("Plot");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().add(view);
view.setFocusable(true);
view.requestFocus();
} | 0 |
protected void actionPerformed(GuiButton var1) {
if(var1.id == 0) {
;
}
if(var1.id == 1) {
this.mc.thePlayer.respawnPlayer();
this.mc.displayGuiScreen((GuiScreen)null);
}
if(var1.id == 2) {
this.mc.changeWorld1((World)null);
this.mc.displayGuiScreen(new GuiMainMenu());
}
} | 3 |
private void paintPictures(Graphics g){
for(int i = 0; i <4; i++){
for(int n = 0; n <4; n++){
int j = convertBase4(i, n);
BufferedImage img = imageQueue.get(j);
if(img != null)//img will be null if we are not online.
g.drawImage(img, n*img.getWidth(), i*img.getHeight(), null);
}
}
} | 3 |
@Action
public void deleteItem() {
TreePath selectedPath = jTree1.getSelectionPath();
if (selectedPath == null) {
JOptionPane.showMessageDialog(mainPanel,
"Please select a category or item first",
"You need a category or item",
JOptionPane.WARNING_MESSAGE);
return;
}
DefaultMutableTreeNode selectedNode =
(DefaultMutableTreeNode)selectedPath.getLastPathComponent();
if (selectedNode.getUserObject() instanceof JKeeperItem) {
int result = JOptionPane.showConfirmDialog(mainPanel,
"Are you sure you want to delete the item "
+ ((JKeeperItem) selectedNode.getUserObject()).getName()
+ "?", "Really?", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (selectedNode.getUserObject() instanceof JKeeperCategory) {
int result = JOptionPane.showConfirmDialog(mainPanel,
"Are you sure you want to delete the category "
+ (JKeeperCategory)selectedNode.getUserObject()
+ "?\nALL ITS ITEMS WILL BE DELETED",
"Really?",
JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION || result == JOptionPane.CLOSED_OPTION) {
return;
}
}
jKeeperTreeModel.removeNodeFromParent(selectedNode);
addUnsavedMark();
jTree1.updateUI();
} | 7 |
public static void main(String[] args) {
long start = System.nanoTime();
int sum = 0;
for(int i = 3; i < 1000; i++){
if(i % 3 == 0 || i % 5 == 0){
sum += i;
}
}
System.out.println(sum);
System.out.println("Done in " + (double) (System.nanoTime() - start)
/ 1000000000 + " seconds.");
} | 3 |
public void submitAll(IntervalList intervals) {
//adjust threshold to be bigger if we're dealing with genome-sized files,
//elsewise we may blow the stack
if (intervals.getExtent() > 1e8) {
thresholdExtent = (long) 1e7;
}
if (intervals.getExtent() > 1e9) {
thresholdExtent = (long) 1e8;
}
if (intervals.getExtent() < thresholdExtent) {
//Intervals size is pretty small, just call 'em
IntervalCaller<T> caller;
try {
caller = getIntervalCaller(intervals);
if (caller != null) {
callers.add(caller);
pool.execute(caller);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error processing interval, aborting.");
System.exit(1);
}
}
else {
//Intervals cover a lot of ground, so split them in half and submit each half
IntervalList[] intervalArray = splitter.splitIntervals(intervals);
for(int i=0; i<intervalArray.length; i++) {
submitAll(intervalArray[i]);
}
}
} | 6 |
@Override
public int compare(Announcement announcement1, Announcement announcement2) {
if (announcement1.timestamp.getTime() < announcement2.timestamp.getTime())
return 1;
else if (announcement1.timestamp.getTime() > announcement2.timestamp.getTime())
return -1;
else
return 0;
} | 2 |
@Override
public void run() {
String line = "";
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
line = br.readLine(); //Throw away first two lines of title info
line = br.readLine();
while (br.ready()) {
line = br.readLine();
p = parseLine(line);
if(p.getCoords().inZone(c1, c2))
list.add(p);
}
} catch (IOException e) {
System.err.println("Error reading file " + file.getAbsolutePath());
System.exit(1);
} catch (NumberFormatException e) {
System.err.println("Number format exception on line" + line);
System.exit(1);
} finally {
try {
br.close();
} catch (IOException e) {
System.err.println("Error closing file " + file.getAbsolutePath());
System.exit(1);
}
}
} | 5 |
private String decodePapPassword(byte[] encryptedPass, byte[] sharedSecret)
throws RadiusException {
if (encryptedPass == null || encryptedPass.length < 16) {
// PAP passwords require at least 16 bytes
logger.warn("invalid Radius packet: User-Password attribute with malformed PAP password, length = " +
encryptedPass.length + ", but length must be greater than 15");
throw new RadiusException("malformed User-Password attribute");
}
MessageDigest md5 = getMd5Digest();
byte[] lastBlock = new byte[16];
for (int i = 0; i < encryptedPass.length; i+=16) {
md5.reset();
md5.update(sharedSecret);
md5.update(i == 0 ? getAuthenticator() : lastBlock);
byte bn[] = md5.digest();
System.arraycopy(encryptedPass, i, lastBlock, 0, 16);
// perform the XOR as specified by RFC 2865.
for (int j = 0; j < 16; j++)
encryptedPass[i + j] = (byte)(bn[j] ^ encryptedPass[i + j]);
}
// remove trailing zeros
int len = encryptedPass.length;
while (len > 0 && encryptedPass[len - 1] == 0)
len--;
byte[] passtrunc = new byte[len];
System.arraycopy(encryptedPass, 0, passtrunc, 0, len);
// convert to string
return RadiusUtil.getStringFromUtf8(passtrunc);
} | 7 |
private void vergebeIDs(IOManager manager)
{
manager.readRaeume();
List<Raum> rlist = manager.getRaeume();
Set<Integer> idList = new HashSet<Integer>();
for(Raum r : rlist)
{
idList.add(r.getId());
}
Random rand = new Random();
int newid;
GridButton[][] buttons = _ui.getMap().getButtonArray();
for(int y = 0; y < buttons[0].length; ++y)
{
for(int x = 0; x < buttons.length; ++x)
{
Raum raum = buttons[x][y].getRaum();
if(raum != null && raum.getId() == 0)
{
do
{
newid = rand.nextInt();
} while(newid == 0 || idList.contains(newid));
raum.setId(newid);
idList.add(newid);
}
}
}
} | 7 |
public String GetStringData()
{
return data1;
} | 0 |
private int jjMoveStringLiteralDfa9_0(long old0, long active0, long old1, long active1) {
if (((active0 &= old0) | (active1 &= old1)) == 0L) return jjStartNfa_0(7, old0, old1);
try {
curChar = input_stream.readChar();
} catch (IOException e) {
jjStopStringLiteralDfa_0(8, active0, active1);
return 9;
}
switch (curChar) {
case 101:
if ((active0 & 0x20000000000L) != 0L) return jjStartNfaWithStates_0(9, 41, 25);
return jjMoveStringLiteralDfa10_0(active0, 0x800000L, active1, 0L);
case 110:
return jjMoveStringLiteralDfa10_0(active0, 0L, active1, 0x20000L);
case 111:
return jjMoveStringLiteralDfa10_0(active0, 0x80000L, active1, 0L);
case 117:
return jjMoveStringLiteralDfa10_0(active0, 0x100000L, active1, 0L);
case 121:
return jjMoveStringLiteralDfa10_0(active0, 0x1000000L, active1, 0L);
default :
break;
}
return jjStartNfa_0(8, active0, active1);
} | 8 |
@Override
protected void sort(int[] a) {
int largest = a[0];
for (int n : a)
if (largest < n)
largest = n;
int log = (int) Math.ceil(Math.log(largest) / Math.log(RADIX));
for (int i = 0; i < log; i++) {
for (int n : a)
registers[getDigit(n, i)].offer(n);
//printInfo(i);
int index = 0;
for (Queue register : registers) {
while (!register.isEmpty()) {
set(index++, (Integer) register.poll());
}
}
}
} | 6 |
public void queueLoad(Point p)
{
try {
toLoad.put(p);
} catch (InterruptedException e) {
e.printStackTrace();
}
} | 1 |
public boolean checkCheckmate(Board b,int l,int o ){
aiarr=b.getBoardArray();
for(int x=0;x<8;x++){
for(int y=0;y<8;y++){
Point[] mov=canMove(new Point(x,y));
Piece [][] arr0=new Piece[8][8];
for(int x1=0;x1<8;x1++){
for(int y1=0;y1<8;y1++){
arr0[x1][y1]=aiarr[x1][y1];
}
}
Piece [][] a1=aiarr;
aiarr=arr0;
for(int i=0;i<mov.length;i++){
makeMove(new Point(x,y),new Point(mov[i]));
if(!isThreatened(new Point(l,o))){
return false;
}
aiarr=a1;
}
}
}
System.out.println("CHECKMATE");
return true;
} | 6 |
public void fillUpProductComboBox() {
ArrayList<StockItem> productComboboxList = driver.getStockDB().getStockList();
comboBoxItems.clear();
itemsQuantity.clear();
itemsPrice.clear();
for (StockItem stockItem : productComboboxList) {
String values[] = supplierComboBox.getSelectedItem().toString().split("\\t");
if (stockItem.getProduct().getSupplier().getId()==(
Integer.parseInt(values[1].trim()))) {
comboBoxItems.add(stockItem.getProduct().getProductName());
itemsPrice.add(stockItem.getProduct().getSupplierPrice());
itemsQuantity.add(stockItem.getQuantity());
}
}
productComboBox.setSelectedIndex(comboBoxItems.size() - 1);
revalidate();
repaint();
} | 2 |
@Override
public String getDef() {return def;} | 0 |
public int compareTo(Animatable other) {
if (other instanceof GameOfLife) {
GameOfLife o = (GameOfLife) other;
if (x > o.x)
return 1;
else if (x < o.x)
return -1;
else if (y > o.y)
return 1;
else if (y < o.y)
return -1;
else if (boxSize > o.boxSize)
return 1;
else if (boxSize < o.boxSize)
return -1;
else
return (randIndex > o.randIndex) ? 1 : (randIndex < o.randIndex) ? -1 : 0;
} else {
return getClass().getName().compareTo(other.getClass().getName());
}
} | 9 |
private void close() {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new RuntimeException("Erro ao fechar conexão!");
}
} | 4 |
public void onIncomingFileTransfer(DccFileTransfer transfer) {
int choix =
JOptionPane.showConfirmDialog(null, transfer.getNick() + " veux vous envoyer " + transfer.getFile() + ", voulez vous accepter?", transfer.getNick()
+ " - DCC transfer", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (choix == JOptionPane.OK_OPTION) {
File dir = new File("Download");
if (!dir.exists() && !dir.isDirectory()) {
dir.mkdir();
}
transfer.receive(new File("Download" + File.separator + transfer.getFile().getName()), true);
DarkIRC.currentTransfer = transfer;
} else {
transfer.close();
}
} | 3 |
public GenericDAO<Project> getProjectsDAO()
{
if (_projectsDAO == null)
{
_projectsDAO = new GenericDAO<Project>(Project.class);
}
return _projectsDAO;
} | 1 |
public static void load(String path) {
try {
String vertexFilename = "vertex.txt";
String edgeFilename = "edges.txt";
String streetFilename = "streets.txt";
boolean isDirected = true;
PreProcessingMap preProcessingMap = new PreProcessingMap();
Document doc = preProcessingMap.createXMLDocument(path);
// read the boundary of this graph
Boundary boundary = preProcessingMap.readBoundaryFromOSMFile(doc);
// Read the data of OSM nodes
System.out.println("read OSM nodes...");
List<OSMNode> osmNodes = preProcessingMap.readNodesFromOSMFile(doc);
// Create OSM node hashtable
System.out.println("Create index hashtable for OSM nodes ");
Map<String, OSMNode> nodesMap = new HashMap<String, OSMNode>();
preProcessingMap.createNodesHashtable(osmNodes, nodesMap);
// Read the data of OSM ways
System.out.println("read ways...");
List<OSMWay> osmWays = preProcessingMap.readWaysFromOSMFile(doc);
System.out.println("ways size:" + osmWays.size());
// Create streets, 'true' means to generate a directed graph
List<Street> streets = preProcessingMap.createStreets(
nodesMap, osmWays, isDirected);
// Clean those nodes that is not used in this graph and output
// them into a file.
List<OSMNode> requiredNodes = preProcessingMap.selectNodes(streets);
System.out.println("node size:" + requiredNodes.size());
preProcessingMap.outputNodes(requiredNodes, vertexFilename);
// Output streets into file
preProcessingMap.outputStreets(streets,
streetFilename);
preProcessingMap.outputEdges(requiredNodes.size(), streets,
edgeFilename);
System.out.println("streets size:" + streets.size());
int[] indegrees = new int[requiredNodes.size()];
int[] outdegrees = new int[requiredNodes.size()];
for (int i = 0; i < requiredNodes.size(); i++) {
indegrees[i] = 0;
outdegrees[i] = 0;
}
for (int i = 0; i < streets.size(); i++) {
Street street = streets.get(i);
OSMNode startnode = street.getStartNode();
OSMNode endnode = street.getEndNode();
outdegrees[(int)startnode.getIndex()] += 1;
indegrees[(int)endnode.getIndex()] += 1;
}
int count = 0;
for (int i = 0; i < requiredNodes.size(); i++) {
if (outdegrees[i] == 1 && indegrees[i] == 1) {
count += 1;
}
}
System.out.println("redundant points:" + count);
System.out.println("Building Graph - Done");
} catch (Exception e) {
e.printStackTrace();
}
} | 6 |
public void stopgame() {
if(!running)
return;
running = false;
synchronized(applets) {
applets.remove(p);
}
p.interrupt();
remove(h);
p = null;
h = null;
} | 1 |
private static void initializeGame() {
System.out.println("\n\nTHE Dot.Com GUESSING GAME");
System.out.println("--------------------------------------------------------------------------------");
System.out.println("This is a simple guessing game. There are a few web addresses hidden randomly inside " +
"the board. The players will each take turns to guess where they are hidden. The player " +
"who guesses the most options correctly will win the game.\n");
try {
System.out.print("\nEnter the board size : ");
boardSize = Integer.parseInt(input.readLine());
System.out.print("\nEnter the number of players : ");
playerCount = Integer.parseInt(input.readLine());
if(boardSize <= 0) throw new ArrayIndexOutOfBoundsException();
if(playerCount <= 0) throw new ArrayIndexOutOfBoundsException();
if(playerCount > (boardSize * boardSize)) throw new Exception("To many players for the specified board size...!!!");
game = new GameEngine(boardSize, playerCount);
game.fillBoard(boardSize);
System.out.print("\nDo you wish to set names for the players?.. [Y/N] : ");
if(input.readLine().toUpperCase().equals("Y")){
game.setCustomPlayerNames();
}
} catch (NumberFormatException e) {
System.out.println("\n\nAn error has occurred...\n" +
"Enter a valid number for the board size and number of players.\n" +
"Please restart the game to try again...!!!");
System.exit(0);
//e.printStackTrace();
} catch (IOException e) {
System.out.println("\n\nAn error has occurred... \n" +
"There was an error in the input.\n" +
"Please restart the game to try again...!!!");
System.exit(0);
//e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("\n\nAn error has occurred...\n" +
"The Board size and number of Players cannot be less than one.\n" +
"Please restart the game to try again...!!!");
System.exit(0);
}
catch(Exception e){
System.out.println("\n\n"+ e.getMessage());
System.out.println("\nAn error has occurred... Please restart the game to try again...!!!");
System.exit(0);
}
} | 8 |
private static operation getOperateur(String equation) {
//cette fonction retourne un opérateur et affiche l'équation actuelle
final String menu[] = {"=", "/", "*", "-", "+"};
int choix;
operation op;
choix = JOptionPane.showOptionDialog(
null, "Quelle opéranteur voulez-vous ajouter?\n"+equation, "Calculatrice",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
menu, menu[0]);
switch(choix) {
default:
case 0: op = operation.FIN; break;
case 1: op = operation.DIVISION; break;
case 2: op = operation.MULTIPLICATION; break;
case 3: op = operation.SOUSTRACTION; break;
case 4: op = operation.ADDITION; break;
}
return op;
} | 5 |
private void chooseMovement(){
if (x == 49 && y == 25){
world.removeObject (hpBar);
world.removeObject (dv);
currentHp = 0;
world.mobDie (this, true);
}
else{
if (x == 10 && y == 12 && stage == 0){
stage = 1;
}
else if (x == 39 && y == 12 && stage == 1){
stage = 2;
}
movement();
}
} | 8 |
public boolean isEmpty() {
if (size == 0) {
return true;
}
for (int i = 0; i < taulu.length; i++) {
if (taulu[i] != null) {
return false;
}
}
return true;
} | 3 |
public KeyHandler(String alias) {
this.alias = alias;
keychain = new HashMap<String, KeyNoncePair>();
} | 0 |
public List<Cluster> performClustering(double[][] distances
, String[] clusterNames
, LinkingRule linkingRule
, int k
, Matrix features) {
/* Argument checks */
if (distances == null || distances.length == 0
|| distances[0].length != distances.length) {
throw new IllegalArgumentException("Invalid distance matrix");
}
if (distances.length != clusterNames.length) {
throw new IllegalArgumentException("Invalid cluster name array");
}
if (linkingRule == null) {
throw new IllegalArgumentException("Undefined linkage strategy");
}
/* Setup model */
List<Cluster> clusters = createClusters(clusterNames);
List<ClusterPair> linkages = createLinkages(distances, clusters);
/* Process */
HierarchyBuilder builder =
new HierarchyBuilder(clusters
, linkages
, k);
int counter = 0;
while (!builder.isTreeComplete()) {
builder.agglomerate(linkingRule, counter, features);
counter++;
}
return builder.getRootCluster();
} | 6 |
public String toString()
{
int length = 2 * ((z1[0].toString()).length());
String sidespace = "";
for(int i=0; i<length/2; i++){sidespace += " ";}
String unit = "+";
String horiz = " ";
String verti = " | ";
String lab = "";
String topspace = " ";
for(int i=0; i<length/2; i++){topspace += " ";}
String header = sidespace + " ";
for(Zyg z : z1)
{ header += (z.toString() + topspace); }
for(int i=0; i<length+2; i++){unit+="-";}
for(int i=0; i<z1.length; i++){horiz+=unit;}
horiz += "+";
horiz = sidespace + horiz;
lab += (" " + header);
lab += "\n";
for(int i=0; i<z1.length; i++)
{
lab += (horiz + "\n");
lab += (z2[i].toString());
for(int j=0; j<z2.length; j++)
{ lab+=(verti + board[i][j].toString()); }
lab += " |\n";
}
lab += horiz;
return lab;
} | 7 |
private void displayPRF(String prefixStr, int correct, int guessed, int gold, int exact, int total, PrintWriter pw) {
double precision = (guessed > 0 ? correct / (double) guessed : 1.0);
double recall = (gold > 0 ? correct / (double) gold : 1.0);
double f1 = (precision > 0.0 && recall > 0.0 ? 2.0 / (1.0 / precision + 1.0 / recall) : 0.0);
double exactMatch = exact / (double) total;
String displayStr = " P: " + ((int) (precision * 10000)) / 100.0 + " R: " + ((int) (recall * 10000)) / 100.0 + " F1: " + ((int) (f1 * 10000)) / 100.0 + " EX: "+((int) (exactMatch * 10000)) / 100.0 ;
pw.println(prefixStr+displayStr);
} | 4 |
private void processDeckClick() {
//Can assume did click on the deck.
final Stack<Card> deck = game.getDeck();
if (!deck.isEmpty()) {
activeMove = new DeckClickMove();
String result = activeMove.makeMove(game, this);
processMoveResult(result, activeMove);
}
} | 1 |
public boolean equals(Object x) {
// der Parameter muss vom Typ Object sein wegen der Spezifikation der Klasse Object
// deswegen kann diese Methode nicht generisch genacht werden
if (this == x)
return true;
if (x == null)
return false;
if (getClass() != x.getClass())
return false;
GenericInterval<?> iv = (GenericInterval<?>) x;
return (isEmpty() && iv.isEmpty()) // beide leer
|| (lowerBound.equals(iv.lowerBound) && upperBound.equals(iv.upperBound));
} | 8 |
public static String toString(JSONObject jo) throws JSONException {
boolean b = false;
Iterator keys = jo.keys();
String string;
StringBuffer sb = new StringBuffer();
while (keys.hasNext()) {
string = keys.next().toString();
if (!jo.isNull(string)) {
if (b) {
sb.append(';');
}
sb.append(Cookie.escape(string));
sb.append("=");
sb.append(Cookie.escape(jo.getString(string)));
b = true;
}
}
return sb.toString();
} | 3 |
@Override
public void die() {
tile.getBombers().remove(this);
this.tile = null;
this.cooldown = match.dyingCooldown;
this.points -= match.pointsLostForDying;
} | 0 |
public void resolveJumpMarkings() throws SemanticException {
//scan for positions
int position = 0;
final Map<String, Integer> jumpAddresses = new HashMap<>();
for (final Instruction instruction : instructions) {
if (jumpMarkings.containsKey(instruction)) {
final String aJumpMarking = jumpMarkings.get(instruction);
jumpAddresses.put(aJumpMarking, position);
}
if (instruction.getOperation() != Operation.DAT) {
position++; //for the instruction itself except for DAT
}
if (instruction.getOperandA().hasAdditionalWord()) {
position++; //for operandA
}
if (instruction.getOperation().getParameterCount() == 2) {
if (instruction.getOperandB().hasAdditionalWord()) {
position++; //for operandB
}
}
}
//resolve jump markings
for (final Instruction instruction : instructions) {
resolveJumpMarking(jumpAddresses, instruction.getOperandA());
if (instruction.getOperation().getParameterCount() > 1) {
resolveJumpMarking(jumpAddresses, instruction.getOperandB());
}
}
} | 8 |
@Override
public void execute(FileSearchBean task) throws Exception {
final FileInputStream fileInputStream = new FileInputStream(task.getInputFile());
final BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream, bufferSize);
try {
int j = 0;
int buff;
while ((buff = bufferedInputStream.read()) != -1 && j < patternBytes.length) {
while (j >= 0 && buff != (patternBytes[j] & 0xff)) {
j = kmpNext[j];
}
j++;
if (j >= patternBytes.length) {
resultCollector.push(task);
break;
// j = kmpNext[j];
}
}
} finally {
try {
bufferedInputStream.close();
} catch (IOException ioe) { /* ignore silently */ }
try {
fileInputStream.close();
} catch(IOException ioe) { /* ignore silently */ }
}
} | 7 |
PhysConstantEnum(double value) {
this.value = value;
} | 0 |
public int returnCoorFromXY(int x, int y) {
if (x < 0 || x >= this.squaresX) {
return -1;
}
if (y < 0 || y >= this.squaresY) {
return -1;
}
return (x + (y * this.squaresX));
} | 4 |
@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 Empresa)) {
return false;
}
Empresa other = (Empresa) object;
if ((this.codempresa == null && other.codempresa != null) || (this.codempresa != null && !this.codempresa.equals(other.codempresa))) {
return false;
}
return true;
} | 5 |
public static FiniteStateAutomaton removeMultipleCharacterLabels(
Automaton automaton) {
FiniteStateAutomaton fsa = (FiniteStateAutomaton) automaton.clone();
Transition[] transitions = fsa.getTransitions();
for (int k = 0; k < transitions.length; k++) {
FSATransition transition = (FSATransition) transitions[k];
String label = transition.getLabel();
if (label.length() > 1) {
handleLabel(transition, fsa);
}
}
return fsa;
} | 2 |
public ArrayList<Villager> getPeople() {return this.people;} | 0 |
@Override
public boolean importData(TransferSupport support) {
logger.info("importData");
if (!canImport(support)) {
return false;
}
JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
int row = dl.getRow();
logger.info("Row number {}", row);
try {
String data = (String) support.getTransferable().
getTransferData(DataFlavor.stringFlavor);
String[] itemsAsString = data.split("\n");
int[] items = new int[itemsAsString.length];
for (int i = 0; i < itemsAsString.length; i++) {
items[i] = Integer.parseInt(itemsAsString[i]);
}
GiveItemsAction giveItemsAction = new GiveItemsAction(deliveryPacket.getId(), items);
try {
giveItemsAction.redo();
} catch (RuntimeException ex) {
logger.error("", ex);
}
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
} | 5 |
private int getNumberBySlot(int slot) {
slot--; // skip this parameter (not an outer value)
for (int i = 0; slot >= 0 && i < headCount; i++) {
if (slot == 0)
return i;
slot -= head[i].getType().stackSize();
}
return -1;
} | 3 |
@Override
public void explore(ProcessConfiguration config, ExploringThread thread, Explorable parent) throws ExplorationException {
try {
ZipFile zip = (ZipFile) parent;
File zipFile = zip.getPath();
File tempFolder = getTempFolder(zipFile.getName());
tempFolder.mkdirs();
if (log.isLoggable(Level.FINE)) log.fine("Unzipping " + zipFile + " to " + tempFolder + "... ");
ZipUtility.unzip(zipFile, tempFolder, null);
config.closeOnFinish(new FolderDisposer(tempFolder));
if (log.isLoggable(Level.FINE)) log.fine("Done.");
File[] files = tempFolder.listFiles();
if (files != null && files.length > 0) { // Yes, it can be null under Windows for virtual folders like "My Music"
for (File child : files) {
thread.enqueue(
zip,
child.isDirectory() ? Folder.class.getSimpleName() : SimpleFile.class.getSimpleName(),
child
);
}
}
} catch (Throwable t) {
throw new ExplorationException("Unable to explore the content of the folder '" + parent + "'", t);
}
} | 7 |
private void isGreaterThanEqualsToString(String param, Object value) {
if (value instanceof String) {
if (param.compareTo((String) value) <= 0) {
throw new IllegalStateException("String is not greater than supplied value.");
}
} else {
throw new IllegalArgumentException();
}
} | 2 |
public String getHouseNumber() {
return addressCompany.getHouseNumber();
} | 0 |
public void shutdown() {
super.shutdown();
try {
workers.awaitTermination(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// NOP
} finally {
workers.shutdownNow();
}
} | 1 |
private static void method495(char ac[])
{
int i = 0;
for(int j = 0; j < ac.length; j++)
{
if(method496(ac[j]))
ac[i] = ac[j];
else
ac[i] = ' ';
if(i == 0 || ac[i] != ' ' || ac[i - 1] != ' ')
i++;
}
for(int k = i; k < ac.length; k++)
ac[k] = ' ';
} | 6 |
private static String parseData(String data)
{
if(data == null || data.length() == 0)
return data;
if(data.startsWith(BINARY_KEY))
return data.substring(4);
// return parseHexString(data.substring(4), false);
else if(data.startsWith(DWORD_KEY))
return data.substring(6);
// return parseHexString(data.substring(6), false);
else if(data.startsWith(MULTI_KEY))
return data.substring(7);
// return parseHexString(data.substring(7), true);
else if(data.startsWith(EXPAND_KEY))
return data.substring(7);
// return parseHexString(data.substring(7), true);
else if(data.startsWith("\""))
return data.replaceAll("\"", "");
return data;
} | 7 |
@Test
public void twoCompCircular3() throws Exception {
try {
C3 c = new C3();
fail();
} catch (RuntimeException E) {
// E.printStackTrace();
// assertTrue(E.getMessage().contains("src == dest"));
}
} | 1 |
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case statePackage.STATE__PLAYERS:
return getPlayers();
case statePackage.STATE__COUNTRY_STATE:
if (coreType) return getCountryState();
else return getCountryState().map();
case statePackage.STATE__TURN:
return getTurn();
case statePackage.STATE__PHASE:
return getPhase();
case statePackage.STATE__STATE:
return getState();
case statePackage.STATE__TROOPS_TO_SET:
return getTroopsToSet();
case statePackage.STATE__CONQUERED_COUNTRY:
return isConqueredCountry();
}
return super.eGet(featureID, resolve, coreType);
} | 8 |
@Override
public void run() {
for(Object socket : sockets) {
if(socket instanceof DatagramSocket)
if(((DatagramSocket) socket).isClosed()) {
((DatagramSocket) socket).close();
continue;
}
if(socket instanceof ServerSocket)
if(((ServerSocket) socket).isClosed()) {
try {
((ServerSocket) socket).close();
} catch (IOException e) {
System.err.println("Can't stop tcp server socket");
}
continue;
}
if(socket instanceof Socket)
if(((Socket) socket).isClosed()) {
try {
((Socket) socket).close();
} catch (IOException e) {
System.err.println("Can't stop tcp socket");
}
continue;
}
}
} | 9 |
public void setTree(RootedTree tree, Collection<Node> selectedNodes) {
this.originalTree = tree;
if (!originalTree.hasLengths()) {
transformBranches = true;
}
Painter<?>[] pl = { taxonLabelPainter, nodeLabelPainter, branchLabelPainter };
for( Painter<?> p : pl ) {
if( p instanceof BasicLabelPainter ) {
((BasicLabelPainter)p).setTree(tree);
}
}
selectedTaxa.clear();
if( selectedNodes != this.selectedNodes ) {
this.selectedNodes.clear();
}
if( selectedNodes != null ) {
this.selectedNodes.addAll(selectedNodes);
}
setupTree();
} | 7 |
private void updateAndClose(final String initials) {
if (!closing && getDate() != null) {
closing = true;
try {
Connection conn = MySql.getConnection();
PreparedStatement statement = conn.prepareStatement(MySql.OPENING_COUNT_UPDATE);
final java.sql.Date date = new java.sql.Date(getDate().getTime());
statement.setDate(1, date);
int i = 2;
for (Component comp : moneyPanel.getComponents()) {
if (comp instanceof HighlightingCurrencyField) {
statement.setBigDecimal(i, ((HighlightingCurrencyField) comp).getBigDecimalValue());
i++;
}
}
statement.setString(14, initials);
statement.setDate(15, date);
i = 16;
for (Component comp : moneyPanel.getComponents()) {
if (comp instanceof HighlightingCurrencyField) {
statement.setBigDecimal(i, ((HighlightingCurrencyField) comp).getBigDecimalValue());
i++;
}
}
statement.setString(28, initials);
statement.executeUpdate();
conn.close();
WindowEvent wev = new WindowEvent(ClosingCountWindow.this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
} catch (SQLException e) {
ErrorDialog.show("Error in data", e);
}
closing = false;
}
} | 7 |
public static void main(String[] args) {
// Command line arguments
for (String arg : args) {
System.out.println(arg);
}
String code = "declare a transreal declare b transreal set b 1 set a + b nullity";
EsperCompiler compiler = new EsperCompiler();
compiler.readCommandLineArguments(args);
compiler.compile(code);
System.out.println("Compiled!");
System.out.println("Lexer status: "
+ successOrFailure(compiler.lexerSuccess) + " | Errors: "
+ compiler.lexerErrors);
System.out.println("Parser status: "
+ successOrFailure(compiler.parserSuccess) + " | Errors: "
+ compiler.parserErrors);
} | 1 |
private void initCarTypes() {
this._carTypes = new CarType[4];
this._carTypes[0] = new CarType(UUID.randomUUID(), "硬座车", 1L);
for(int i = 1; i <= 118; i ++)
{
Seat seat = new Seat();
seat.setId(UUID.randomUUID());
seat.setNumber(Integer.toString(i));
seat.setType(1L);
this._carTypes[0].getSeats().add(seat);
}
this._carTypes[1] = new CarType(UUID.randomUUID(), "硬卧车", 4L);
for(int i = 1; i <= 66; i ++)
{
Seat seat = new Seat();
seat.setId(UUID.randomUUID());
seat.setNumber(Integer.toString(i));
seat.setType(4L);
this._carTypes[1].getSeats().add(seat);
}
this._carTypes[2] = new CarType(UUID.randomUUID(), "软座车", 2L);
for(int i = 1; i <= 118; i ++)
{
Seat seat = new Seat();
seat.setId(UUID.randomUUID());
seat.setNumber(Integer.toString(i));
seat.setType(2L);
this._carTypes[2].getSeats().add(seat);
}
this._carTypes[3] = new CarType(UUID.randomUUID(), "二级软卧", 8L);
for(int i = 1; i <= 44; i ++)
{
Seat seat = new Seat();
seat.setId(UUID.randomUUID());
seat.setNumber(Integer.toString(i));
seat.setType(8L);
this._carTypes[3].getSeats().add(seat);
}
} | 4 |
public boolean groupSumClump(int start, int[] nums, int target) {
if (start >= nums.length) return (target == 0);
int sum = nums[start];
for (int i = start; i < nums.length - 1; i++) {
if (nums[i + 1] == nums[start]) {
sum += nums[i];
} else {
break;
}
}
if (sum == nums[start]) {
if (groupSumClump(start + 1, nums, target)) return true;
if (groupSumClump(start + 1, nums, target - nums[start])) return true;
} else {
if (groupSumClump(start + (sum / nums[start]), nums, target - sum)) return true;
if (groupSumClump(start + (sum / nums[start]), nums, target)) return true;
}
return false;
} | 8 |
public masterControl(){
// create main controls
buttons[0] = new JButton("New");
buttons[1] = new JButton("Play/Pause");
buttons[2] = new JButton("Step");
//buttons[3] = new JButton("State Editor");
//buttons[4] = new JButton("Cell Editor");
//buttons[5] = new JButton("Cell Picker");
//buttons[6] = new JButton("Selection Tools");
//buttons[7] = new JButton("Brushes");
//buttons[8] = new JButton("About");
checks[0] = new Checkbox("Boredom(1)");
checks[1] = new Checkbox("Boredom(2)");
checks[2] = new Checkbox("Compass Chaos");
throttle = new JSlider(0,1000);
rtsetter[0] = new JSlider(1,1024);
rtsetter[1] = new JSlider(1,1024);
rtsetter[2] = new JSlider(1,1024);
rtslab[0] = new JLabel("50");
rtslab[1] = new JLabel("50");
rtslab[2] = new JLabel("50");
//dispbox = new controlBox(1);
wrapbox = new controlBox(2);
cidButton = new JButton("Cell info");
winitem[0] = new JMenuItem("State Editor");
winitem[1] = new JMenuItem("Cell Editor");
winitem[2] = new JMenuItem("Cell Picker");
winitem[3] = new JMenuItem("Selection Tools");
winitem[4] = new JMenuItem("Brushes");
winitem[5] = new JMenuItem("Cell Info");
winitem[6] = new JMenuItem("About");
winmen = new JMenu("Window");
disitem[0] = new JMenuItem("Classic");
disitem[1] = new JMenuItem("Multicolor");
disitem[2] = new JMenuItem("State Edit");
disitem[3] = new JMenuItem("Cell Edit");
disitem[4] = new JMenuItem("Gradient");
dismen = new JMenu("Display");
mainbar = new JMenuBar();
magsetter = new JSlider(1,30);
maglab = new JLabel("Magnification");
magvallab = new JLabel("5");
//setPreferredSize(new Dimension(675,165));
// set layout
GroupLayout mclayout = new GroupLayout(this);
mclayout.setAutoCreateGaps(false);
mclayout.setAutoCreateContainerGaps(false);
mclayout.setHorizontalGroup(
mclayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(mainbar)
.addGroup(mclayout.createSequentialGroup()
.addComponent(buttons[0])
.addComponent(buttons[1])
.addComponent(throttle)
.addComponent(buttons[2])
.addComponent(cidButton))
/*.addGroup(mclayout.createSequentialGroup()
.addComponent(buttons[3])
.addComponent(buttons[4])
.addComponent(buttons[5])
.addComponent(buttons[6])
.addComponent(buttons[7]))*/
.addGroup(mclayout.createSequentialGroup()
//.addComponent(buttons[8])
//.addComponent(dispbox)
.addComponent(wrapbox)
.addComponent(maglab)
.addComponent(magsetter)
.addComponent(magvallab))
.addGroup(mclayout.createSequentialGroup()
.addComponent(checks[0])
.addComponent(rtsetter[0])
.addComponent(rtslab[0]))
.addGroup(mclayout.createSequentialGroup()
.addComponent(checks[1])
.addComponent(rtsetter[1])
.addComponent(rtslab[1])
.addComponent(checks[2])
.addComponent(rtsetter[2])
.addComponent(rtslab[2]))
);
mclayout.setVerticalGroup(
mclayout.createSequentialGroup()
.addComponent(mainbar)
.addGroup(mclayout.createParallelGroup()
.addComponent(buttons[0])
.addComponent(buttons[1])
.addComponent(throttle)
.addComponent(buttons[2])
.addComponent(cidButton))
/*.addGroup(mclayout.createParallelGroup()
.addComponent(buttons[3])
.addComponent(buttons[4])
.addComponent(buttons[5])
.addComponent(buttons[6])
.addComponent(buttons[7]))*/
.addGroup(mclayout.createParallelGroup()
//.addComponent(buttons[8])
//.addComponent(dispbox)
.addComponent(wrapbox)
.addComponent(maglab)
.addComponent(magsetter)
.addComponent(magvallab))
.addGroup(mclayout.createParallelGroup()
.addComponent(checks[0])
.addComponent(rtsetter[0])
.addComponent(rtslab[0]))
.addGroup(mclayout.createParallelGroup()
.addComponent(checks[1])
.addComponent(rtsetter[1])
.addComponent(rtslab[1])
.addComponent(checks[2])
.addComponent(rtsetter[2])
.addComponent(rtslab[2]))
);
setLayout( mclayout );
// setup controls
//buttons
for( int c = 0; c < buttons.length; c++){
if(c == 2){ throttle.addChangeListener(this);throttle.setMaximumSize(new Dimension(100,15));
}
buttons[c].addActionListener(this);
}
//checkboxes
for(int a = 0; a < checks.length; a++){
checks[a].addItemListener(this);checks[a].setMaximumSize(new Dimension(100,50));
rtsetter[a].addChangeListener(this); rtsetter[a].setMaximumSize(new Dimension(100,15));
rtslab[a].setText(Integer.toString(rtsetter[a].getValue()));
}
//Misc
rtslab[1].setText(Integer.toString(rtsetter[2].getValue()*2));
// dispbox.adducListener(this);
wrapbox.adducListener(this); wrapbox.setMaximumSize(new Dimension(100,50));
cidButton.addActionListener(this);
magsetter.addChangeListener(this); magsetter.setValue(5);
// menu bar
for(int s = 0; s < winitem.length; s++){
winmen.add(winitem[s]); winitem[s].addActionListener(this);}
dismen.add(disitem[0]); disitem[0].addActionListener(this);
dismen.add(disitem[1]); disitem[1].addActionListener(this);
dismen.add(disitem[4]); disitem[4].addActionListener(this);
dismen.add(disitem[2]); disitem[2].addActionListener(this);
dismen.add(disitem[3]); disitem[3].addActionListener(this);
mainbar.add(winmen);
mainbar.add(dismen);
} | 4 |
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} | 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(InscriClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InscriClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InscriClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InscriClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new InscriClient().setVisible(true);
}
});
} | 6 |
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
state = SENTKNOCKKNOCK;
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (currentJoke == (NUMJOKES - 1))
currentJoke = 0;
else
currentJoke++;
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
} | 8 |
public static Proposition buildMemberOfProposition(Cons tree) {
Logic.verifyNumberOfPropositionArguments(tree, 2);
{ Stella_Object collectionref = tree.rest.rest.value;
{ Surrogate testValue000 = Stella_Object.safePrimaryType(collectionref);
if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate collectionref000 = ((Surrogate)(collectionref));
if (collectionref000.getStellaClass(false) != null) {
return (Logic.buildIsaProposition(tree));
}
}
}
else if (Surrogate.subtypeOfSymbolP(testValue000)) {
{ Symbol collectionref000 = ((Symbol)(collectionref));
if (collectionref000.getStellaClass(false) != null) {
return (Logic.buildIsaProposition(tree));
}
}
}
else if (Surrogate.subtypeOfP(testValue000, Logic.SGT_LOGIC_DESCRIPTION)) {
{ Description collectionref000 = ((Description)(collectionref));
if (Description.namedDescriptionP(collectionref000) &&
NamedDescription.classDescriptionP(((NamedDescription)(collectionref000)))) {
return (Logic.buildIsaProposition(Cons.list$(Cons.cons(Logic.SYM_STELLA_ISA, Cons.cons(tree.rest.value, Cons.cons(Cons.cons(collectionref000.descriptionSurrogate(), Stella.NIL), Stella.NIL))))));
}
}
}
else {
}
}
}
return (Logic.buildPredicateProposition(tree));
} | 7 |
public static void writeOSM(HashMap<Integer, CustomNode> clcMainNodes,
HashMap<Integer, CustomWay> clcMainWays,
HashMap<Integer, CustomRelation> clcMainRelations, String filename) {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer;
FileOutputStream stream;
try {
stream = new FileOutputStream("c:\\osm\\" + filename);
} catch (Exception e) {
System.out.append("nincs file");
return;
}
try {
writer = factory.createXMLStreamWriter(stream);
writer.writeStartDocument("UTF-8", "1.0");
writer.writeStartElement("osm");
writer.writeAttribute("version", "0.6");
writer.writeAttribute("upload", "true");
writer.writeAttribute("generator", "JOSM");
writer.writeCharacters("\r\n");
// nodes
for (CustomNode cn : clcMainNodes.values()) {
writer.writeStartElement("node");
writer.writeAttribute("id", Integer.toString(cn.getNodeId()));
writer.writeAttribute("timestamp", "2010-05-02T23:34:43Z");
writer.writeAttribute("visible", "true");
writer.writeAttribute("lat", Double.toString(cn.getLat()));
writer.writeAttribute("lon", Double.toString(cn.getLon()));
writer.writeEndElement();
writer.writeCharacters("\r\n");
}
// ways
for (CustomWay cw : clcMainWays.values()) {
writer.writeStartElement("way");
writer.writeAttribute("id", Integer.toString(cw.getWayId()));
writer.writeAttribute("timestamp", "2010-05-02T23:34:43Z");
writer.writeAttribute("visible", "true");
writer.writeCharacters("\r\n");
for (int i = 0; i < cw.getMembers().size(); i++) {
writer.writeStartElement("nd");
writer.writeAttribute("ref",
Integer.toString(cw.getMembers().get(i)));
writer.writeEndElement();
writer.writeCharacters("\r\n");
}
writer.writeEndElement();
writer.writeCharacters("\r\n");
}
// relations
for (CustomRelation cr : clcMainRelations.values()) {
writer.writeStartElement("relation");
writer.writeAttribute("id",
Integer.toString(cr.getRelationId()));
writer.writeAttribute("timestamp", "2010-05-02T23:34:43Z");
writer.writeAttribute("visible", "true");
writer.writeCharacters("\r\n");
for (int i = 0; i < cr.getMembers().size(); i++) {
writer.writeStartElement("member");
writer.writeAttribute("ref",
Integer.toString(cr.getMembers().get(i).getRef()));
writer.writeAttribute("type", cr.getMembers().get(i)
.getType());
writer.writeAttribute("role", cr.getMembers().get(i)
.getRole());
writer.writeEndElement();
writer.writeCharacters("\r\n");
}
Iterator<Map.Entry<String, String>> it = cr.getTags()
.entrySet().iterator();
while (it.hasNext()) {
writer.writeStartElement("tag");
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it
.next();
writer.writeAttribute("k", pairs.getKey());
writer.writeAttribute("v", pairs.getValue());
writer.writeEndElement();
writer.writeCharacters("\r\n");
//it.remove(); // avoids a ConcurrentModificationException
}
writer.writeEndElement();
writer.writeCharacters("\r\n");
}
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (Exception e) {
}
} | 8 |
private boolean executeNotRandomMusics(int indexMusic) {
for(int i = indexMusic; i < getMusics().size(); i++){
getMusics().get(i).play();
if(isRamdom) return true;
}
return false;
} | 2 |
private void boardDraw(Graphics2D g2d) {
ChessEngine game = gameThread.getGame();
g2d.drawImage(assets.getBackground(), 0, 0, null);
State state = gameThread.getGameState();
if(state == State.PLAYING) {
for(Piece p : game.getWhitePieces()) {
drawPiece(p, g2d);
}
for(Piece p : game.getBlackPieces()) {
drawPiece(p, g2d);
}
}
if(game != null && game.getActive() != null) {
g2d.drawImage(assets.getActive(), (int)game.getActive().getPixelX(), (int)game.getActive().getPixelY(), null);
if(game.getActive().getPiece() != null && game.getActive().getPiece().getColor() == game.getLocal()) {
List<Square> possibleMoves = game.getActive().getPiece().getPossibleMoves();
for(Square s : possibleMoves) {
g2d.drawImage(assets.getActive(), (int)s.getPixelX(), (int)s.getPixelY(), null);
}
}
}
} | 8 |
public static void Help() {
GUI.log("" +
"Commands:\n" +
"north exit through the northern door.\n" +
"east exit through the eastern door.\n" +
"south exit through the southern door.\n" +
"west exit through the western door.\n" +
"exit go back to the main menu.\n" +
"inspect get more information about an item.\n" +
"pickup pickup an item.\n" +
"look get a list of all of the items in the room.\n" +
"drop drop an item out of your inventory.\n" +
"read read a book in your inventory.\n" +
"dance begin dancing.");
} | 0 |
public RegularExpression getExpression() {
return (RegularExpression) super.getObject();
} | 0 |
private long removeRefRippleServer(long lIndex) {
//
// loop through the elements in the actual container, in order to find the one
// at lIndex. Once it is found, then loop through the reference list and remove
// the corresponding reference for that element.
//
RippleServer refActualElement = GetRippleServer(lIndex);
if (refActualElement == null)
return lIndex; // oh well.
// Loop through the reference list and remove the corresponding reference
// for the specified element.
//
for(int intIndex = 0; intIndex < elementList.size(); intIndex++)
{
Object theObject = elementList.get(intIndex);
if ((theObject == null) || !(theObject instanceof RippleServer))
continue;
RippleServer tempRef = (RippleServer)(theObject);
if ((RippleServer.getCPtr(tempRef) == RippleServer.getCPtr(refActualElement)))
{
elementList.remove(tempRef);
break;
}
}
return lIndex;
} | 5 |
private String getFieldString(Object o, int type) {
if (o == null)
return "null";
switch (type) {
case java.sql.Types.INTEGER:
return ((Integer)o).toString();
case java.sql.Types.BOOLEAN:
return ((Boolean)o).toString();
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
return "'" + (String)o + "'";
case java.sql.Types.FLOAT:
return ((Float)o).toString();
case java.sql.Types.DATE:
return ((Date)o).toString();
case java.sql.Types.DECIMAL:
return ((BigDecimal)o).toString();
case java.sql.Types.TIMESTAMP:
return ((java.sql.Timestamp)o).toString();
default:
logger.error("Undefined Type Number " + type);
return null;
}
} | 9 |
public NChatServer(){
//Try to start connection on server port (Start.port).
System.out.println("Trying to connect to port " + Start.port + "...");
try{
connectionSocket = new ServerSocket(Start.port);
}catch(IOException e){
System.out.println("Error connecting to port " + Start.port + "!");
e.printStackTrace();
System.exit(-1);
}
System.out.println("Server started!");
this.startServer();
//Accept new connections.
while(stopServer==false){
try {
new UserNChatThread(connectionSocket.accept(), this).start();
System.out.println("New user connected!");
} catch (IOException e) {
System.out.println("A user failed to connect.");
e.printStackTrace();
}
}
//Attempt to stop the server.
System.out.println("Stopping server...");
try {
connectionSocket.close();
} catch (IOException e) {
System.out.println("Error closing server port!");
e.printStackTrace();
}
this.stopServer();
} | 4 |
private static void doTest(boolean b, String msg) {
if (b) {
System.out.println("Good.");
} else {
System.err.println(msg);
}
} | 1 |
public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException
{
String st=request.getParameter("ques");
int i=Integer.parseInt(st);
String str=request.getParameter("comments");
String str1=request.getParameter("option1");
String str2=request.getParameter("option2");
String str3=request.getParameter("option3");
String str4=request.getParameter("option4");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Connection conn;
Statement stmt;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/chaitanya","root","");
System.out.println("connection successful");
stmt=conn.createStatement();
stmt.executeUpdate("insert into comment values('"+str+"',"+i+",'"+str1+"','"+str2+"','"+str3+"','"+str4+"')");
}
catch(SQLException e1)
{
}
catch(ClassNotFoundException e1)
{
}
out.println("<html>");
out.println("<head>");
out.println("<img src=\"C:\\Users\\pankaj\\Downloads\\images\\icon1.jpg\">");
out.println("</img>");
out.println("<h2>data added succesfully</h2>");
out.println("</head>");
out.println("<body bgcolor\"skyblue\">");
//out.println("<br>");
out.println("<a href=\"http://localhost:8080/ExaminationSoftware/Questions.html\" >");
out.println("back</a>");
out.println("</body>");
out.println("</html>");
} | 2 |
public static void main(String args[]) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int N=parseInt(in.readLine().trim());
int[][] arr=new int[N][];
for(int i=0;i<N;i++) {
StringTokenizer st=new StringTokenizer(in.readLine());
int a=parseInt(st.nextToken()),b=parseInt(st.nextToken());
arr[i]=new int[]{a,b};
}
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(abs(o1[0])+abs(o1[1])<abs(o2[0])+abs(o2[1]))
return -1;
if(abs(o1[0])+abs(o1[1])<abs(o2[0])+abs(o2[1]))
return 1;
if(o1[0]<o2[0])
return -1;
if(o1[0]>o2[0])
return 1;
return o1[1]<o2[1]?-1:1;
}
});
for(int i=0;i<N;i++) {
f(0,0,arr[i][0],arr[i][1]);
solution.add(new int[]{'2'});
f(arr[i][0],arr[i][1],0,0);
solution.add(new int[]{'3'});
}
sb.append(solution.size()).append("\n");
for(int[] a:solution) {
for(int i=0;i<a.length-1;i++)
sb.append(a[i]).append(" ");
sb.append((char)a[a.length-1]).append("\n");
}
System.out.print(new String(sb));
} | 9 |
private static String valueLine(ArrayList<String> values, int columnSize) {
String line = "|";
for(int i = 0; i < values.size(); i++) {
String cell = " ";
if(values.get(i).length() > columnSize-1) {
cell += values.get(i).substring(0, columnSize-4);
cell += ">> ";
} else {
cell += values.get(i);
while(cell.length() < columnSize) {
cell += ' ';
}
}
line += cell + '|';
}
return line;
} | 3 |
public void setPosLab(String posLab) {
this.posLab = posLab;
} | 0 |
@Override
public boolean equals (Object other){
if(other == null)
return false;
if (!(other instanceof Meld))
return false;
Meld otherMeld = (Meld) other;
if(this.isRun != otherMeld.isRun)
return false;
if(this.getNumTiles() != otherMeld.getNumTiles())
return false;
ArrayList<Tile> myTiles = getTiles();
ArrayList<Tile> otherTiles = otherMeld.getTiles();
for(int i=0; i<myTiles.size(); i++)
if(!myTiles.get(i).equals(otherTiles.get(i)))
return false;
return true;
} | 6 |
public ExtendableClassLoader() {
cache = new Hashtable<String, Class<?>>();
paths = new ArrayList<String>();
} | 1 |
private void loadDictionary() throws IOException, FileNotFoundException{
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(WORDS_FILE));
String word;
while ((word = in.readLine()) != null) {
dictionary.add(word.trim().toLowerCase());
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignore
}
}
}
} | 5 |
private static String TranslateEnumToContentType(ContentType contentType){
switch(contentType){
case RDF:
return "application/rdf+xml";
case TURTLE:
return "application/x-turtle";
case NT:
return "text/plain";
case N3:
return "text/rdf+n3";
default:
return "text/plain";
}
} | 4 |
public static void main(String[] args) {
int port;
if (args.length != 2) {
System.err.println("Usage: java ChatServer <port> <database name>");
return;
}
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
System.err.println("Usage: java ChatServer <port>");
return;
}
try {
ss = new ServerSocket(port);
} catch (IOException ioe) {
System.err.println("Cannot use port number "+port);
return;
}
Database d = null;
try {
d = new Database(args[1]);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
mq = new MultiQueue<Message>();
if (d != null) begin(d);
} | 5 |
public float getI() {
float input = 0f;
for (int j = 0; j < inputs.size(); j++) {
FiringState fired = inputs.get(j).getFired();
//fired == null indicates an External Connection which do not fire)
if (fired == FiringState.DISABLED) {
input += activation(inputs.get(j).getValue() * weights[j]);
} else {
input += inputs.get(j).getFired() == FiringState.FIRED ? weights[j] : 0f;
}
}
if (Float.isNaN(input)) {
return 0f;
} else {
return k * input;
}
} | 4 |
public static Scriptable jsConstructor(Context cx, Object[] args,
Function ctorObj,
boolean inNewExpr) {
Font f = new Font();
String font = cx.toString(args[0]);
if (font.startsWith("data:")) {
URI dataUri = null;
try {
new URI(font);
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] fontBytes = org.apache.commons.codec.binary.Base64.decodeBase64(font.substring(font.indexOf(',')+1));
try {
f.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new ByteArrayInputStream(fontBytes)));
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (font.endsWith(".ttf")) {
// First, we need to get the currenly loaded game, so we can figure
// out where the path of this font is.
Scriptable global = ScriptableObject.getTopLevelScope(ctorObj);
Scriptable sgf = (Scriptable)global.get("SGF", global);
Scriptable game = (Scriptable)sgf.get("Game", sgf);
Game curGame = (Game)game.get("current", game);
URL fontPath = null;
try {
fontPath = new URL(curGame.getRoot(), font);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
if (fontPath != null)
try {
f.setFont(java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, fontPath.openStream()));
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
f.setFont(new java.awt.Font(font, java.awt.Font.PLAIN, 1));
}
return f;
} | 7 |
private int getOffset(TimeZone zone, long millis) {
Date date = new Date(millis);
if (zone.inDaylightTime(date)) {
return zone.getRawOffset() + 3600000;
}
return zone.getRawOffset();
} | 1 |
private void selectAndSpillValue() {
Value spill = null;
int maxEdges = 0;
for(Entry<Value, HashSet<Value>> v : adjacencyList.entrySet()) {
if(v.getValue().size() > maxEdges) {
spill = v.getKey();
maxEdges = v.getValue().size();
}
}
deleteNode(spill);
} | 2 |
private CharSequence getExpectedActionString(InputOutputEventType expectedEventType) {
if (expectedEventType == InputOutputEventType.HALT) {
return new HaltEvent().getExpectedActionDescription();
} else if (expectedEventType == InputOutputEventType.INPUT) {
return new InputEvent().getExpectedActionDescription();
} else if (expectedEventType == InputOutputEventType.OUTPUT) {
return outputWordPredicates.peek().expectedWordString(); //check if peek will cause error from queue being empty.
} else {
throw new AssertionError();
}
} | 3 |
public static String vectorPlaceToHTML(Vector<Place> rs){
if (rs.isEmpty())
return "<p class=\"plusbas\">Il n'y a plus de places disponibles.</p>";
String toReturn = "<TABLE BORDER='1' width=\"1000\">";
toReturn+="<CAPTION>Les places disponibles (#) sont :</CAPTION>";
int i=0;
for (int j=1;j<=10;j++){
toReturn+="<TR><TH class=\"c0\"> Rang n°"+j+" </TH>";
for (int k=1;k<=30;k++){
if (i < rs.size() && rs.elementAt(i).getRang() == j && rs.elementAt(i).getNum() == k){
toReturn+="<TH class=\"c"+rs.elementAt(i).getZone()+"\">"+rs.elementAt(i).getNum()+"</TH>";
i++;
}
else
toReturn+="<TH></TH>";
}
toReturn+="</TR>";
}
toReturn=toReturn.replaceAll("#", i+"");
return toReturn+"</TABLE>";
} | 6 |
public static void main(String[] args) {
if (0 == args.length) {
System.out.println("Invalid input parameter");
return;
}
String param = args[0];
if (param.equals(RECORD)) {
System.out.println("User selected RECORD");
/****** RECORD SOUND *********/
final Record dataRecorder = new Record();
dataRecorder.start();
// register the shutdown hook so we stop recording at some point, and
// then process the data
Runtime.getRuntime().addShutdownHook(new ShutdownThread(dataRecorder));
} else if (param.equals(PLAY)) {
System.out.println("User selected PLAY");
if (2 != args.length || args[1].isEmpty()) {
System.out.println("Must provide a filename for playback option");
return;
}
//play file
String fileName = args[1];
System.out.println("Attempting to play file " + fileName);
audioAssistant.readFromFile(fileName);
} else if (param.equals(TEST)) {
System.out.println("User selected TEST");
System.out.println("Hello World");
} else {
System.out.println("Unknown input parameter");
}
} | 6 |
public static ArrayList<Student> sortMenu(ArrayList<Student> inList){
int choice = 0;
do {
System.out.println("What would you like to do: \n 1) Sort by Last Name \n 2) Sort by GPA \n 3) Sort BY Class \n 4) Return to main menu");
Scanner userinput = new Scanner(System.in);
choice = userinput.nextInt();
if(choice ==1)
{
Collections.sort(inList, new SortByLastName());
AddDelete.printList(inList);
}
else if(choice == 2)
{
Collections.sort(inList, new SortByGPA());
CalcGPA.printClassGpa(inList);
}
else if (choice == 3)
{
Collections.sort(inList, new SortByClass());
ChangeGrade.printClassList(inList);
}
else if(choice == 4)
{
break;
}
else
{
System.out.println("Invalid input");
System.out.println();
}
} while (choice != 3);
return inList;
} | 5 |
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.