text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void setStrategy(Strategy strategy)
{
this.strategy = strategy;
} | 0 |
protected void printParameter(String parentParameterFile,
String childParameterFile, ArrayList<_Doc> docList) {
System.out.println("printing parameter");
try {
System.out.println(parentParameterFile);
System.out.println(childParameterFile);
PrintWriter parentParaOut = new PrintWriter(new File(
parentParameterFile));
PrintWriter childParaOut = new PrintWriter(new File(
childParameterFile));
for (_Doc d : docList) {
if (d instanceof _ParentDoc) {
parentParaOut.print(d.getName() + "\t");
parentParaOut.print("topicProportion\t");
for (int k = 0; k < number_of_topics; k++) {
parentParaOut.print(d.m_topics[k] + "\t");
}
for (_Stn stnObj : d.getSentences()) {
parentParaOut.print("sentence"
+ (stnObj.getIndex() + 1) + "\t");
for (int k = 0; k < number_of_topics; k++) {
parentParaOut.print(stnObj.m_topics[k] + "\t");
}
}
parentParaOut.println();
for (_ChildDoc cDoc : ((_ParentDoc) d).m_childDocs) {
childParaOut.print(cDoc.getName() + "\t");
childParaOut.print("topicProportion\t");
for (int k = 0; k < number_of_topics; k++) {
childParaOut.print(cDoc.m_topics[k] + "\t");
}
childParaOut.println();
}
}
}
parentParaOut.flush();
parentParaOut.close();
childParaOut.flush();
childParaOut.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 8 |
public static void main(String[] args) {
final List ab= new ArrayList();
for(int i=0;i<100;i++){
ab.add(i);
}
ExecutorService ex = Executors.newCachedThreadPool();
for (int i = 0; i < 4; i++) {
final int a = i;
//每一次execute方法,都是向池中放入一个对象
ex.execute(new Runnable() {
public void run() {
while(true){
synchronized (ab) {
if(ab.size()==0) return;
ab.remove(ab.size()-1);
System.err.println("测试"+ab.size()+"...."+a+">"
+Thread.currentThread().getName()+","
+Thread.currentThread().isDaemon());
}
try{
Thread.sleep(2000);
}catch(Exception e){
e.printStackTrace();
}
}
}
});
}
try {
Thread.sleep(1000*60*60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
public TradeProposalPopUp(ArrayList<String[]> tradesProposed, Player proposer) {
final ArrayList<String[]> trades = tradesProposed;
final Player proposingPlayer = proposer;
int cash0 = Integer.parseInt(trades.get(0)[0]);
String[] properties0 = trades.get(1);
int cash1 = Integer.parseInt(trades.get(2)[0]);
String[] properties1 = trades.get(3);
JPanel basePanel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
// Create layouts and buttons
int hGap = 15;
GridLayout baseGridLayout = new GridLayout(3, 1, 0, 0);
GridLayout gridLayout1 = new GridLayout(1, 1, 0, 0);
GridLayout gridLayout2 = new GridLayout(1, 2, 0, 0);
// The pop-up should have enough rows to list each property on one row,
// so we must calculate which set of properties is largest
int maxRows = 0;
if (properties0.length > properties1.length)
maxRows = properties0.length + 2;
else
maxRows = properties1.length + 2;
GridLayout gridLayout3 = new GridLayout(maxRows, 2, hGap, 0);
System.out.println("maxrows: " + maxRows);
basePanel.setLayout(null);
panel1.setLayout(null);
panel2.setLayout(null);
panel3.setLayout(null);
Font labelFont = new Font("arial", Font.PLAIN, 20);
Font buttonFont = new Font("arial", Font.PLAIN, 18);
Font titleFont = new Font("arial", Font.PLAIN, 14);
Font listFont = new Font("arial", Font.PLAIN, 17);
JLabel titleLabel = new JLabel(proposingPlayer.getName() + " would like to trade with you.");
titleLabel.setFont(labelFont);
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel1.setLayout(gridLayout1);
panel1.add(titleLabel);
panel1.setBackground(new Color(236, 234, 166));
JLabel subTitle1 = new JLabel("They will give you:");
subTitle1.setFont(labelFont);
subTitle1.setHorizontalAlignment(SwingConstants.CENTER);
panel3.setLayout(gridLayout3);
panel3.add(subTitle1);
panel3.setBackground(new Color(236, 234, 166));
JLabel subTitle2 = new JLabel("In exchange for:");
subTitle2.setFont(labelFont);
subTitle2.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(subTitle2);
JLabel cashLabel1 = new JLabel("Cash: $" + cash0);
cashLabel1.setFont(listFont);
panel3.add(cashLabel1);
cashLabel1.setHorizontalAlignment(SwingConstants.CENTER);
JLabel cashLabel2 = new JLabel("Cash: $" + cash1);
cashLabel2.setFont(listFont);
cashLabel2.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(cashLabel2);
int i = 0;
int j = 0;
boolean addLeft = true;
while ((i < properties0.length) || (j < properties1.length)) {
JLabel temp;
if (addLeft && (i < properties0.length)) {
temp = new JLabel(properties0[i]);
temp.setFont(listFont);
temp.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(temp);
addLeft = false;
++i;
}
else if (addLeft && (i >= properties0.length)) {
panel3.add(new JLabel(" "));
addLeft = false;
}
else if (!addLeft && (j < properties1.length)) {
temp = new JLabel(properties1[j]);
temp.setFont(listFont);
temp.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(temp);
addLeft = true;
++j;
}
else {
panel3.add(new JLabel(" "));
addLeft = true;
}
}
JButton accept = new JButton("Accept");
accept.setFont(buttonFont);
accept.setVisible(true);
JButton reject = new JButton("Reject");
reject.setFont(buttonFont);
reject.setVisible(true);
panel2.add(accept);
panel2.add(reject);
panel2.setLayout(gridLayout2);
basePanel.setLayout(baseGridLayout);
basePanel.setBackground(new Color(236, 234, 166));
Border blackline = BorderFactory.createLineBorder(Color.black, 2);
TitledBorder title = BorderFactory.createTitledBorder(blackline, "Trade Proposal");
title.setTitleFont(titleFont);
title.setTitleJustification(TitledBorder.LEFT);
basePanel.setBorder(title);
basePanel.add(panel1);
basePanel.add(panel3);
basePanel.add(panel2);
basePanel.setVisible(true);
int xCoord = (int) (DisplayAssembler.getScreenWidth() - basePanel.getPreferredSize().getWidth()) / 2;
int yCoord = (int) (DisplayAssembler.getScreenHeight() - basePanel.getPreferredSize().getHeight()) / 2;
PopupFactory factory = PopupFactory.getSharedInstance();
final Popup popup = factory.getPopup(null, basePanel, xCoord, yCoord);
accept.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
popup.hide();
String proposerName[] = {proposingPlayer.getName()};
trades.add(proposerName);
NotificationManager.getInstance().notifyObservers(Notification.REMOVE_CARD, null);
NotificationManager.getInstance().notifyObservers(Notification.TRADE_ACCEPTED, trades, true);
}
});
reject.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
popup.hide();
NotificationManager.getInstance().notifyObservers(Notification.REMOVE_CARD, null);
// Sends trade decision of "No Trade"
NotificationManager.getInstance().notifyObservers(Notification.TRADE_REJECTED, null, true);
}
});
popup.show();
NotificationManager.getInstance().notifyObservers(Notification.SHOW_CARD, null);
} | 9 |
public boolean isTypedReady(int e){
if(keys[e] && typed[e]){
typed[e]=false;
return true;
}
return false;
} | 2 |
public void die(){
if (sound.Manager.enabled) {
sound.Event effect = new sound.Event(getPosition(), getVelocity(),sound.Library.findByName(DEATH_EFFECT));
effect.gain = EFFECT_VOLUME;
sound.Manager.addEvent(effect);
}
velocity.timesEquals(0);
if(ParticleSystem.isEnabled())
ParticleSystem.addEvent((new Explosion<Fire>(Fire.class,this)).setIntensity(1024));
ParticleSystem.removeGenerator(particleGenerator);
delete();
} | 2 |
public static byte[] decode(String encoded, int length) {
Preconditions.checkArgument(length > 0);
ByteArrayOutputStream os = new ByteArrayOutputStream(length);
int offset = 0, encodedLength = encoded.length(), decodedLength = 0;
while (offset < encodedLength - 1 && decodedLength < length) {
byte first = decodeCharacter(encoded.charAt(offset++));
byte second = decodeCharacter(encoded.charAt(offset++));
if (first == -1 || second == -1) {
break;
}
byte decoded = (byte) (first << 2);
decoded |= (second & 0x30) >> 4;
os.write(decoded);
if (++decodedLength >= length || offset >= encodedLength) {
break;
}
byte next = decodeCharacter(encoded.charAt(offset++));
if (next == -1) {
break;
}
decoded = (byte) ((second & 0x0F) << 4);
decoded |= (next & 0x3c) >> 2;
os.write(decoded);
if (++decodedLength >= length || offset >= encodedLength) {
break;
}
byte last = decodeCharacter(encoded.charAt(offset++));
decoded = (byte) ((next & 0x03) << 6);
decoded |= last;
os.write(decoded);
++decodedLength;
}
return os.toByteArray();
} | 9 |
private boolean filterFile(File file) {
boolean rtnBoolean = false;
if(this.config.getExtensions() != null){
// 파일이 있다면 파일 이름 출력
Set<String> exts = new HashSet<String>();
//해당 확장자만 가져오도록한다.
for(String ext : this.config.getExtensions()){
exts.add("."+ext.toLowerCase().trim());
}
Iterator<String> extList = exts.iterator();
while(extList.hasNext()){
if(file.getName().endsWith(extList.next())){
rtnBoolean = true;
//fileSet.add(file);
}
}
}else{
rtnBoolean = true;
//fileSet.add(file);
}
return rtnBoolean;
} | 4 |
private static Collection<String> moeglicheBefehlsnamen(
List<String> geparsteZeile)
{
ArrayList<String> befehlsnamen = new ArrayList<String>();
if(geparsteZeile.size() == 0)
return befehlsnamen;
for(int i = 0; i < geparsteZeile.size(); i++)
befehlsnamen.add("");
for(int i = 0; i < geparsteZeile.size(); i++)
{
for(int j = i; j < geparsteZeile.size(); j++)
{
String previous = befehlsnamen.get(j);
if(!previous.isEmpty())
previous += " ";
befehlsnamen.set(j, previous + geparsteZeile.get(i));
}
}
Collections.reverse(befehlsnamen);
return befehlsnamen;
} | 5 |
public Player() {
_current = Status.STOP;
_player = null;
_index = -1;
new JFXPanel();
setBackground(Color.WHITE);
SpringLayout layout = new SpringLayout();
setLayout(layout);
//Setting up the list.
_myList = new JList<Song>(new DefaultListModel<Song>());
_myList.setCellRenderer(new PlayerListCellRenderer());
_myList.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
_myList.setDragEnabled(true);
_myList.setDropMode(DropMode.INSERT);
_myList.setTransferHandler(new ListTransferHandler());
_myList.setBorder(null);
_myList.setBackground(Color.WHITE);
JScrollPane scrollPane = new JScrollPane(_myList);
scrollPane.setBorder(new LineBorder(Color.BLACK, 3));
scrollPane.setBackground(Color.WHITE);
add(scrollPane);
try {
//Play
_playEnabled = new BeethovenIcon(getClass().getResource("Icons/play.png").toURI().toURL());
_pauseEnabled = new BeethovenIcon(getClass().getResource("Icons/pause.png").toURI().toURL());
_play = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
play();
}
};
_pause = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pause();
}
};
_playPause = new JButton(_playEnabled);
_playPause.setToolTipText("Play");
_playPause.setBackground(Color.WHITE);
_playPause.setBorder(null);
_playPause.addActionListener(_play);
//Back
_back = new JButton(new BeethovenIcon(getClass().getResource("Icons/previous.png").toURI().toURL()));
_back.setToolTipText("Previous");
_back.setBackground(Color.WHITE);
_back.setBorder(null);
_back.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
back();
}
});
//Stop
_stop = new JButton(new BeethovenIcon(getClass().getResource("Icons/stop.png").toURI().toURL()));
_stop.setToolTipText("Stop");
_stop.setBackground(Color.WHITE);
_stop.setBorder(null);
_stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
stop();
}
});
//Next
_next = new JButton(new BeethovenIcon(getClass().getResource("Icons/next.png").toURI().toURL()));
_next.setToolTipText("Next");
_next.setBackground(Color.WHITE);
_next.setBorder(null);
_next.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
next();
}
});
//Remove
_remove = new JButton(new BeethovenIcon(getClass().getResource("Icons/minus.png").toURI().toURL()));
_remove.setToolTipText("Remove");
_remove.setBackground(Color.WHITE);
_remove.setBorder(null);
_remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
remove();
}
});
//Shuffle
_shuffle = new JButton(new BeethovenIcon(getClass().getResource("Icons/shuffle.png").toURI().toURL()));
_shuffle.setToolTipText("Shuffle");
_shuffle.setBackground(Color.WHITE);
_shuffle.setBorder(null);
_shuffle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shuffle();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
//Seek Bar
_seek = new JProgressBar(0, 100);
_seek.setBackground(Color.WHITE);
_seek.setBorder(new LineBorder(Color.BLACK, 3));
_seek.setToolTipText("Seek");
_seek.setString("00:00/00:00");
_seek.setStringPainted(true);
_seek.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
switch(_current) {
case PLAY:
case PAUSE:
int time = (int)Math.round(((double)e.getX() / (double)_seek.getWidth()) * _seek.getMaximum());
_seek.setValue(time);
_seek.setString(timeToString((int)_player.getCurrentTime().toSeconds()) + "/" +
timeToString(_myList.getModel().getElementAt(_index).getDuration()));
_player.seek(new Duration(time));
break;
default:
break;
}
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
});
Timer t = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_myList.updateUI();
switch(_current) {
case PLAY:
if((int)_player.getCurrentTime().toMillis() > _seek.getMaximum())
_seek.setValue(_seek.getMaximum());
else
_seek.setValue((int) _player.getCurrentTime().toMillis());
_seek.setString(timeToString((int) _player.getCurrentTime().toSeconds()) + "/" +
timeToString(_myList.getModel().getElementAt(_index).getDuration()));
break;
case PAUSE:
break;
case STOP:
_seek.setValue(0);
break;
}
}
});
t.start();
int spacing = 5;
JToolBar toolBar = new JToolBar();
toolBar.setBackground(Color.WHITE);
toolBar.setBorder(null);
toolBar.setFloatable(false);
toolBar.setRollover(true);
toolBar.add(_playPause);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_back);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_stop);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_next);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_remove);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_shuffle);
toolBar.addSeparator(new Dimension(spacing, 0));
toolBar.add(_seek);
add(toolBar);
//Volume Slider
_volume = new JSlider(JSlider.VERTICAL, 0, 10, 5);
_volume.setToolTipText("Volume");
_volume.setBackground(Color.WHITE);
_volume.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(_player != null)
_player.setVolume(((double)((JSlider) e.getSource()).getValue()) / 10);
}
});
add(_volume);
//Positioning
layout.putConstraint(SpringLayout.NORTH, scrollPane, 1, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.EAST, scrollPane, -1, SpringLayout.WEST, _volume);
layout.putConstraint(SpringLayout.SOUTH, scrollPane, -31, SpringLayout.SOUTH, this);
layout.putConstraint(SpringLayout.WEST, scrollPane, 1, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, toolBar, 1, SpringLayout.SOUTH, scrollPane);
layout.putConstraint(SpringLayout.EAST, toolBar, -1, SpringLayout.WEST, _volume);
layout.putConstraint(SpringLayout.WEST, toolBar, 1, SpringLayout.WEST, this);
layout.putConstraint(SpringLayout.NORTH, toolBar, 1, SpringLayout.SOUTH, scrollPane);
layout.putConstraint(SpringLayout.NORTH, _volume, 1, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.EAST, _volume, -1, SpringLayout.EAST, this);
layout.putConstraint(SpringLayout.SOUTH, _volume, -31, SpringLayout.SOUTH, this);
} | 9 |
public static ArrayList<Entry<Integer, String>> getColInfo(String datapath)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(datapath));
HashMap<Integer,String> ctgs = new HashMap<Integer,String>();//每列的类型
String line = br.readLine();
int arrcount = line.split(",").length -1;
int count = 0;
String[] arr;
while(line!=null){
arr = line.split(",");
for(int i=0;i<arr.length-1;i++){//最后一列为label
if(!ctgs.containsKey(i)){
if(!arr[i].trim().equals("")){
String c_ctg;
try {
Double.parseDouble(arr[i]);
c_ctg = "N";
} catch (NumberFormatException e) {
// e.printStackTrace();
c_ctg = "C";
}
ctgs.put(i, c_ctg);//number
count++;
if(count == arrcount){
break;
}
}
}
}
if(count == arrcount){
break;
}
line = br.readLine();
}
br.close();
ArrayList<Entry<Integer, String>> idinfos = new ArrayList<Entry<Integer, String>>(ctgs.entrySet());
//排序
Collections.sort(idinfos, new Comparator<Entry<Integer, String>>() {
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return (o1.getKey() - o2.getKey());
// return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
return idinfos;
} | 7 |
public static HashMap<Integer, String> ReadName(String filename){
HashMap<Integer, String> udict = new HashMap<Integer, String>();
//Read the input file stream
try{
FileInputStream fstream = new FileInputStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
for(String line; (line = br.readLine()) != null;){
String parts[] = line.split("\\t", -1);
udict.put(Integer.parseInt(parts[0]), parts[1]);
}
br.close();
}
catch (Exception e){
System.err.println("FileNotFoundException: " + e.getMessage());
}
return udict;
} | 2 |
public static void main(String[] args) {
SudokuApp sudokuApp = new SudokuApp(0, "800006304000000000040090001309060000000700006021800050002470000400008700000001040");
// SudokuApp sudokuApp = new SudokuApp(0, "002519436596342871314867290"
// + "001738649937654128648921750"
// + "000483967873296510469175380");
// SudokuApp sudokuApp = new SudokuApp(0, "782519436596342871314867295"
// + "251738649937654128648921753"
// + "125483967873296514469175382");
// SudokuApp sudokuApp = new SudokuApp(0, "000009430000000000314867000"
// + "000008640000000000048901703"
// + "025483960000090514469175302");
List<Action> actions = sudokuApp.getActions();
System.out.println("nombre de tests: " + sudokuApp.getNombreTests());
System.out.println("nombre d'actions trouves: " + actions.size());
for(Action action: actions){
for(int i = 0 ; i < 9 ; i++ ){
for(int j = 0 ; j < 9 ; j++ ){
for(int k = 1 ; k <= 9 ; k++){
Action actionCourrent= new DynamicAction(i+""+j+""+k);
if(actionCourrent.equals(action)){
System.out.print(k); }
}
}
}
}
} | 5 |
public int getAge() {
return age;
} | 0 |
public boolean containsMethodAliasDirectly(String methodName,
String paramType, IdentifierMatcher matcher) {
for (Iterator i = methodIdents.iterator(); i.hasNext();) {
Identifier ident = (Identifier) i.next();
if (((Main.stripping & Main.STRIP_UNREACH) == 0 || ident
.isReachable())
&& ident.wasAliased()
&& ident.getAlias().equals(methodName)
&& ident.getType().startsWith(paramType)
&& matcher.matches(ident))
return true;
}
return false;
} | 7 |
public int maxProfit(int[] prices) {
int len = prices.length;
if (len ==0){
return 0;
}
int[] mProL = new int [len];
int[] mProR = new int [len];
for (int i = 0;i<len;i++) {
mProL[i] = mProR[i] = 0;
}
int minL = prices[0],maxR = prices[len-1];
for (int i = 1;i<len;i++){
if(prices[i] >=minL){
mProL[i] = Math.max(prices[i]-minL,mProL[i-1]);
}
else {
mProL[i] = mProL[i-1];
minL = prices[i];
}
if(prices[len-1-i] <=maxR) {
mProR[len-1-i] = Math.max(maxR-prices[len-1-i],mProR[len-i]);
}
else {
mProR[len-1-i] = mProR[len-i];
maxR = prices[len-1-i];
}
}
int result = mProL[len-1];
for (int i = 0;i<len-1;i++) {
if (mProL[i]+mProR[i+1]>result){
result = mProL[i]+mProR[i+1];
}
}
return result;
} | 7 |
public EigenvalueDecomposition (Matrix Arg) {
double[][] A = Arg.getArray();
n = Arg.getColumnDimension();
V = new double[n][n];
d = new double[n];
e = new double[n];
issymmetric = true;
for (int j = 0; (j < n) & issymmetric; j++) {
for (int i = 0; (i < n) & issymmetric; i++) {
issymmetric = (A[i][j] == A[j][i]);
}
}
if (issymmetric) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
V[i][j] = A[i][j];
}
}
// Tridiagonalize.
tred2();
// Diagonalize.
tql2();
} else {
H = new double[n][n];
ort = new double[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
H[i][j] = A[i][j];
}
}
// Reduce to Hessenberg form.
orthes();
// Reduce Hessenberg to real Schur form.
hqr2();
}
} | 7 |
public String toUnicode(char ch){
// check bfChar
if (bfChars != null) {
char[] tmp = bfChars.get((int) ch);
if (tmp != null) {
return String.valueOf(tmp);
}
}
// check bfRange for matches, there may be many ranges to check
if (bfRange != null) {
for (CMapRange aBfRange : bfRange) {
if (aBfRange.inRange(ch)) {
return String.valueOf(aBfRange.getCMapValue(ch));
}
}
}
return String.valueOf(ch);
} | 5 |
private void postExpansionExecute(final ClientServices client, final EventManager em) throws CommandException,
AuthenticationException {
// processExistingModules(client.getLocalPath());
super.execute(client, em);
//
// moved modules code to the end of the other arguments --GAR
//
if (!isRecursive()) {
requests.add(1, new ArgumentRequest("-l")); // NOI18N
}
if (useHeadIfNotFound) {
requests.add(1, new ArgumentRequest("-f")); // NOI18N
}
if ((annotateByDate != null) && (annotateByDate.length() > 0)) {
requests.add(1, new ArgumentRequest("-D")); // NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByDate()));
}
if ((annotateByRevision != null) && (annotateByRevision.length() > 0)) {
requests.add(1, new ArgumentRequest("-r")); // NOI18N
requests.add(2, new ArgumentRequest(getAnnotateByRevision()));
}
for (final String string : modules) {
final String module = string;
requests.add(new ArgumentRequest(module));
}
requests.add(new DirectoryRequest(".", client.getRepository())); // NOI18N
requests.add(CommandRequest.RANNOTATE);
try {
client.processRequests(requests);
requests.clear();
} catch (final CommandException ex) {
throw ex;
} catch (final Exception ex) {
throw new CommandException(ex, ex.getLocalizedMessage());
}
} | 9 |
public ListNode merge2Lists(ListNode list1, ListNode list2) {
if (list1 == null && list2 == null)
return null;
if (list1 == null)
return list2;
if (list2 == null)
return list1;
ListNode head1 = null;
ListNode head2 = null;
if (list1.val <= list2.val) {
head1 = list1;
head2 = list2;
} else {
head1 = list2;
head2 = list1;
}
ListNode p1 = head1;
ListNode p2 = head2;
ListNode pre1 = head1;
p1 = p1.next;
while (p1 != null && p2 != null) {
if (p1.val > p2.val) {
ListNode tmp = p2;
p2 = p2.next;
tmp.next = p1;
pre1.next = tmp;
pre1 = tmp;
} else {
pre1 = p1;
p1 = p1.next;
}
}
if (p1 == null) {
pre1.next = p2;
}
return head1;
} | 9 |
public static void main(String[] args)
{
Algoritmo programa = new Algoritmo();
if (programa.leerFichero(RUTA)){
System.out.println("Se ha cargado correctamente el fichero: "+RUTA);
String solucion = programa.executeDijkstra(origen);
System.out.println("Se ha ejecutado el algoritmo:\n"+solucion);
if (programa.guardarFichero(solucion, SALIDA)) {
System.out.println("Se ha guardado la salida en el fichero: "+SALIDA);
} else {
System.out.println("No ha sido posible ejecutar el algoritmo.");
}
System.out.println("Saliendo de la aplicación...");
} else { // No se ha podido leer el fichero
System.exit(0);
}
} | 2 |
public void start() {
Thread thread = new Thread(this);
try {
thread.start();
System.out.println("Thread Start...");
} catch (Exception error) {
}
} | 1 |
public boolean hasItemAny(int id, int amount) {
for(int i = 0; i < playerItems.length; i++) {
if(playerItems[i] == id+1 && playerItemsN[i] >= amount)
return true;
}
for(int i2 = 0; i2 < playerBankSize; i2++) {
if(bankItems[i2] == id+1 && bankItemsN[i2] >= amount)
return true;
}
return false;
} | 6 |
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction) {
return 5;
} | 0 |
public static String readSqlCmdTemplateVariable(String template, int start, int end, Object [] MV_returnarray) {
{ int cursor = start;
boolean escapedP = false;
if ((cursor >= end) ||
(!(template.charAt(cursor) == '{'))) {
}
else {
loop000 : while (cursor < end) {
{ char c = template.charAt(cursor);
if (c == '\\') {
escapedP = true;
cursor = cursor + 1;
}
else if (c == '}') {
break loop000;
}
else {
}
cursor = cursor + 1;
}
}
if (cursor < end) {
if (escapedP) {
{ String _return_temp = Stella.unescapeTokenString(Native.string_subsequence(template, start + 1, cursor), '\\', false);
MV_returnarray[0] = IntegerWrapper.wrapInteger(cursor + 1);
return (_return_temp);
}
}
else {
{ String _return_temp = Native.string_subsequence(template, start + 1, cursor);
MV_returnarray[0] = IntegerWrapper.wrapInteger(cursor + 1);
return (_return_temp);
}
}
}
}
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
{
stream000.nativeStream.println("Illegal template variable syntax at position `" + cursor + "' in");
stream000.nativeStream.println();
stream000.nativeStream.print(" `" + template + "'");
}
;
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
} | 7 |
private int putTextBlock (Graphics2D g2d, String t, int x, int startY) {
int y = startY;
if ((t == null) || (t.equals(""))) {
return y;
}
TextLayout tl = new TextLayout(t,
MainWindow.setupData.getPrintElementSetupList().getPrintElementSetup (PrintElementSetupList.FONT_SUMMARY_SHEET).getPrintFont(),
g2d.getFontRenderContext());
String[] outputs = t.split("\n");
for(int l=0; l<outputs.length; l++){
g2d.drawString(outputs[l], x, y);
y += tl.getBounds().getHeight()*1.3;
}
return y;
} | 3 |
private synchronized boolean hasReceivedPacketWithSequenceNumber(int sequenceNumber) {
//if the sequence number isn't specified then we can't tell whether we've received it before--assume we haven't
if(sequenceNumber == Packet.SEQUENCE_NUMBER_NOT_APPLICABLE)
return false;
//if we've NEVER received a packet ever before then there's no way we could have received this one
if(lastReceivedPacketSequenceNumber == Packet.SEQUENCE_NUMBER_NOT_APPLICABLE)
return false;
//if we JUST received the packet then obviously we've received it before
if(lastReceivedPacketSequenceNumber == sequenceNumber)
return true;
//if the packet is from the future (possibly the next packet) then we haven't received it before
int delta = Packet.deltaBetweenSequenceNumbers(lastReceivedPacketSequenceNumber, sequenceNumber);
if(delta > 0)
return false;
//if the packet is really old then assume we've received it before
if(delta <= -NUM_RECEIVED_PACKETS_STORED)
return true;
//otherwise find the index of the packet in the receivedPackets array and if it's null we haven't received it before
int index = (lastReceivedPacketIndex + delta);
if(index < 0)
index += PacketRecorder.NUM_RECEIVED_PACKETS_STORED;
return receivedPackets[index] != null;
} | 6 |
private String findLine(String containing, boolean throwException) throws IOException {
String line = reader.readLine();
while (line != null) {
if (line.contains(containing)) {
return line;
}
line = reader.readLine();
}
// We've reached the end of the file
if (throwException) {
throw new IOException("End of file reached looking for: " + containing);
}
return null;
} | 3 |
public double winPossibility(ActionList history, GameInfo gameInfo, int playerHandStrength) {
// find number of raise actions in history
int numRaises = history.opponentActions(gameInfo).numberOfRaises();
// find histogram and adjusted hand strength
int[] histogram = historyToHandStrength.get(numRaises);
int aphs = adjustedHandStrength(playerHandStrength);
// if there is no observed history for this number of raises,
// return a default probability based on adjusted hand strength
if(histogram == null)
return 1.0 - ((double) aphs / 16);
// calculate win% = hands player can defeat / total hands
int handsPlayerWins = 0;
int handsOpponentWins = 0;
int i;
for(i = 0; i < aphs; i++) {
handsOpponentWins += histogram[i];
}
for(; i < histogram.length; i++) {
handsPlayerWins += histogram[i];
}
return (double) handsPlayerWins / (handsPlayerWins + handsOpponentWins);
} | 3 |
public String getHelpMessage() { return this.helpMessage; } | 0 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DefaultPeptideIon that = (DefaultPeptideIon) o;
if (charge != that.charge) return false;
if (Double.compare(that.mass, mass) != 0) return false;
return !(peptide != null ? !peptide.equals(that.peptide) : that.peptide != null);
} | 6 |
public static void tfmsymtri2(double a[][], int n, double d[], double b[], double bb[], double em[]) {
int i, j, r, r1;
double w, x, a1, b0, bb0, machtol, norm;
norm = 0.0;
for (j = 1; j <= n; j++) {
w = 0.0;
for (i = 1; i <= j; i++)
w += Math.abs(a[i][j]);
for (i = j + 1; i <= n; i++)
w += Math.abs(a[j][i]);
if (w > norm)
norm = w;
}
machtol = em[0] * norm;
em[1] = norm;
r = n;
for (r1 = n - 1; r1 >= 1; r1--) {
d[r] = a[r][r];
x = Basic.tammat(1, r - 2, r, r, a, a);
a1 = a[r1][r];
if (Math.sqrt(x) <= machtol) {
b0 = b[r1] = a1;
bb[r1] = b0 * b0;
a[r][r] = 1.0;
}
else {
bb0 = bb[r1] = a1 * a1 + x;
b0 = (a1 > 0.0) ? -Math.sqrt(bb0) : Math.sqrt(bb0);
a1 = a[r1][r] = a1 - b0;
w = a[r][r] = 1.0 / (a1 * b0);
for (j = 1; j <= r1; j++)
b[j] = (Basic.tammat(1, j, j, r, a, a) + Basic.matmat(j + 1, r1, j, r, a, a)) * w;
Basic.elmveccol(1, r1, r, b, a, Basic.tamvec(1, r1, r, a, b) * w * 0.5);
for (j = 1; j <= r1; j++) {
Basic.elmcol(1, j, j, r, a, a, b[j]);
Basic.elmcolvec(1, j, j, a, b, a[j][r]);
}
b[r1] = b0;
}
r = r1;
}
d[1] = a[1][1];
a[1][1] = 1.0;
b[n] = bb[n] = 0.0;
} | 9 |
public ArrayList<BodyPart> getBodypartsByType(UpgradeType type){
ArrayList<BodyPart> bodyparts = new ArrayList<BodyPart>();
switch (type) {
case Head:
for(BodyPart u : allHeads){
bodyparts.add(u);
}
return bodyparts;
case Body:
for(BodyPart u : allBodys){
bodyparts.add(u);
}
return bodyparts;
case Limbs:
for(BodyPart u : allLimbs){
bodyparts.add(u);
}
return bodyparts;
}
return new ArrayList<BodyPart>();
} | 6 |
public void play() {
if (!isLoaded()) {
return;
}
clip.setFramePosition(0);
if (looping) {
clip.loop(Clip.LOOP_CONTINUOUSLY);
} else {
clip.loop(repeat);
}
} | 2 |
private void initRandomLL(int randomNum) {
for (int i = 0; i < randomNum; i++) {
ll.add(ran.nextInt(20));
}
} | 1 |
public void removeValue(Comparable rowKey, Comparable columnKey) {
setValue(null, rowKey, columnKey);
// 1. check whether the row is now empty.
boolean allNull = true;
int rowIndex = getRowIndex(rowKey);
DefaultKeyedValues row = this.rows.get(rowIndex);
for (int item = 0, itemCount = row.getItemCount(); item < itemCount;
item++) {
if (row.getValue(item) != null) {
allNull = false;
break;
}
}
if (allNull) {
this.rowKeys.remove(rowIndex);
this.rows.remove(rowIndex);
}
// 2. check whether the column is now empty.
allNull = true;
//int columnIndex = getColumnIndex(columnKey);
for (DefaultKeyedValues rowItem : this.rows) {
int columnIndex = rowItem.getIndex(columnKey);
if (columnIndex >= 0 && rowItem.getValue(columnIndex) != null) {
allNull = false;
break;
}
}
if (allNull) {
for (DefaultKeyedValues rowItem : this.rows) {
int columnIndex = rowItem.getIndex(columnKey);
if (columnIndex >= 0) {
rowItem.removeValue(columnIndex);
}
}
this.columnKeys.remove(columnKey);
}
} | 9 |
private void setModel(String modelName) {
if (modelName.isEmpty())
modelName = this.getClass().getSimpleName().replace("Controller", "");
modelName += modelName.equals("App")? "Model" : "";
try {
model = (Model) Class.forName("app.models." + modelName).newInstance();
model.setController(this);
}
catch (ClassNotFoundException exception) {
System.out.println("Model '"+ modelName +"' not found!");
System.out.println(exception.getMessage());
}
catch (InstantiationException exception) {
System.out.println("Failed to create an instance!");
System.out.println(exception.getMessage());
}
catch (IllegalAccessException exception) {
System.out.println("Illegal access!");
System.out.println(exception.getMessage());
}
} | 5 |
public static void main(String[] args) {
try {
MoodleCallRestWebService.init("http://localhost:7070/moodle/webservice/rest/server.php", "d65f7f717b69f706873dcae6eef08ac7");
MoodleCourse[] allCourses = MoodleRestCourse.getAllCourses();
for (int i=0; i<allCourses.length; i++, System.out.println("************************************"))
printCourseDetails(allCourses[i]);
long [] courseids = new long[allCourses.length];
for (int i = 0; i < allCourses.length; i++) {
courseids[i] = allCourses[i].getId();
}
System.out.println(courseids);
MoodleRestCourse.deleteCourses(courseids);
} catch (MoodleRestException ex) {
Logger.getLogger(TestDeleteCourses.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TestDeleteCourses.class.getName()).log(Level.SEVERE, null, ex);
}
} | 4 |
public void removeExtras(){
List<Tile> removeList = new ArrayList<Tile>();
for(Tile tile : tileList ) {
if (tile.getStyle() == 0){
removeList.add(tile);
}
}
for(Tile rTile : removeList){
tileList.remove(rTile);
}
} | 3 |
@Override
public void testStarted(Description description) {
resetCurrentFailure();
final String id = getId(description);
logger.info("START Testcase '{}' '{}'.", id, description.getDisplayName());
if (!uri.equals(NULL_URI)) {
logger.info("START Testcase '{}' '{}'.", id,
testLinkUriResolver.fromTestLinkId(TestLinkId.fromDescription(description)));
}
} | 1 |
public Dimension getMinimumSize()
{
Dimension localDimension = super.getSize();
int j;
if (this.HeightPacked)
{
j = (this.HardHeight > -1) && (this.HardHeight < this.ActualHeight) ? this.HardHeight : this.ActualHeight;
} else if (this.HardHeight > -1)
j = this.HardHeight;
else
j = localDimension.height;
int i;
if (this.WidthPacked)
{
i = (this.HardWidth > -1) && (this.HardWidth < this.ActualWidth) ? this.HardWidth : this.ActualWidth;
} else if (this.HardWidth > -1)
i = this.HardWidth;
else {
i = localDimension.width;
}
return new Dimension(i, j);
} | 8 |
public void imprimirTable() {
for (int i = 0; i < this.table_trans.getRowCount(); i++) {
for (int j = 1; j < this.table_trans.getColumnCount(); j++) {
System.out.print(this.table_trans.getValueAt(i, j) + " ");
}
System.out.println("");
}
} | 2 |
private void writeImport() {
ImportGenerator imports = new ImportGenerator( filePath );
if ( date )
imports.addImport( IMPORT_DATE );
sb.append( imports.toString() );
} | 1 |
public int[] computePrefix(String pattern) {
int patternLength = pattern.length(); int longestPrefix = 0;
int[] prefixFunction = new int[patternLength];
prefixFunction[0] = 0;
for(int patternIndex = 1; patternIndex < patternLength; patternIndex++) {
while(longestPrefix > 0 && !this.compareTwoChars(pattern.charAt(longestPrefix) , pattern.charAt(patternIndex)))
longestPrefix = prefixFunction[longestPrefix-1];
if(this.compareTwoChars(pattern.charAt(longestPrefix),pattern.charAt(patternIndex)))
longestPrefix = longestPrefix+1;
prefixFunction[patternIndex] = longestPrefix;
comparisons++;
}
return prefixFunction;
} | 4 |
protected boolean canItselfContain(ContainableSimWo conSimWo)
{
boolean canContain =
conSimWo != this && // a container cannot contain itself
// only a pot can contain a plant. must be in parentheses
(!(conSimWo instanceof Plant) || (this instanceof Pot)) &&
massAfterAdding(conSimWo) <= getMaxMass() &&
volumeAfterAdding(conSimWo) <= getMaxVolume();
/*
System.out.println(getName() + " is finding out whether it itself can contain " + conSimWo.getName());
System.out.println("conSimWo != this: " + (conSimWo != this));
System.out.println("(!(conSimWo instanceof Plant) || (this instanceof Pot)): " +
((!(conSimWo instanceof Plant) || (this instanceof Pot))));
System.out.println("massAfterAdding(conSimWo) <= getMaxMass(): " +
(massAfterAdding(conSimWo) <= getMaxMass()));
System.out.println("volumeAfterAdding(conSimWo) <= getMaxVolume(): " +
(volumeAfterAdding(conSimWo) <= getMaxVolume()));
System.out.println("Conclusion: canItselfContain() == " + canContain + "\n");
*/
return canContain;
} | 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 TypeWork)) {
return false;
}
TypeWork other = (TypeWork) object;
if ((this.idTypeWork == null && other.idTypeWork != null) || (this.idTypeWork != null && !this.idTypeWork.equals(other.idTypeWork))) {
return false;
}
if ((this.nameTypeWork == null && other.nameTypeWork != null) || (this.nameTypeWork != null && !this.nameTypeWork.equals(other.nameTypeWork))) {
return false;
}
return true;
} | 9 |
public String getRandomGeslacht() {
Random rn = new Random();
switch (rn.nextInt(4)) {
case 0:
return "man";
case 1:
return "vrouw";
case 2:
return "onbepaald";
case 3:
return "onbekend";
default:
return "onbekend";
}
} | 4 |
public static void deleteUtilisateur(Utilisateur utilisateur) {
Statement stat;
try {
stat = ConnexionDB.getConnection().createStatement();
stat.executeUpdate("delete from utilisateur where id_utilisateur="+ utilisateur.getId_utilisateur());
} catch (SQLException e) {
while (e != null) {
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e.printStackTrace();
e = e.getNextException();
}
}
} | 2 |
private static void resetOutOfRoi (ImageProcessor ip, int extraX, int extraY) {
int width = ip.getWidth();
int height = ip.getHeight();
Rectangle roiRect = ip.getRoi();
Rectangle temp = (Rectangle)roiRect.clone();
temp.grow(extraX, extraY);
Rectangle outer = temp.intersection(new Rectangle(width, height));
float[] pixels = (float[])ip.getPixels();
float[] snapPixels = (float[])ip.getSnapshotPixels();
for (int y=outer.y, p=y*width+outer.x; y<roiRect.y; y++, p+=width)
System.arraycopy(snapPixels, p, pixels, p, outer.width);
int leftWidth = roiRect.x - outer.x;
int rightWidth = outer.x+outer.width - (roiRect.x+roiRect.width);
for (int y=roiRect.y; y<roiRect.y+roiRect.height; y++) {
if (leftWidth > 0) {
int p = outer.x + y*width;
System.arraycopy(snapPixels, p, pixels, p, leftWidth);
}
if (rightWidth > 0) {
int p = roiRect.x+roiRect.width + y*width;
System.arraycopy(snapPixels, p, pixels, p, rightWidth);
}
}
for (int y=roiRect.y+roiRect.height, p=y*width+outer.x; y<outer.y+outer.height; y++, p+=width)
System.arraycopy(snapPixels, p, pixels, p, outer.width);
} | 5 |
public void inicializarHuertos(int[][] iniciales) throws TamanosInvalidosInicializacionException
{
Huerto hAsignar=null;
Nodo enCreacion=null;
if(iniciales[0].length==CROP_NUMBER*Huerto.NODOS_POR_HUERTO
&& iniciales[1].length==CROP_NUMBER*Huerto.NODOS_POR_HUERTO )
{
for(int i =0; i<CROP_NUMBER*Huerto.NODOS_POR_HUERTO;i++)
{
if(i%Huerto.NODOS_POR_HUERTO==0){
hAsignar=new Huerto(i/2,HARVEST_TIME, FRUIT_NUMBER);
}
enCreacion=new Nodo(iniciales[0][i],iniciales[1][i]);
enCreacion.asignarCultivo(hAsignar);
huertos.add(enCreacion);
}
}else
{
throw new TamanosInvalidosInicializacionException();
}
} | 4 |
public static String removeAllStylenames(String style)
{
StringBuffer buffer = new StringBuffer();
if (style != null)
{
String[] tokens = style.split(";");
for (int i = 0; i < tokens.length; i++)
{
if (tokens[i].indexOf('=') >= 0)
{
buffer.append(tokens[i] + ";");
}
}
}
return (buffer.length() > 1) ? buffer.substring(0, buffer.length() - 1)
: buffer.toString();
} | 4 |
public int getTotalFilhos(ArrayList<Byte> contexto, int nivel){
if(nivel > -1){
if(this.isEsc() || (this.getValor() != contexto.get(nivel))) return -1;
}
if(nivel == contexto.size() - 1) {
if(this.isEsc()) return -1;
return filhos.size();
}
for(Contexto c : filhos){
int res = c.getTotalFilhos(contexto, nivel+1);
if(res != -1){
return res;
}
}
return -1;
} | 7 |
public PlaceHoldRequestDialog(BorrowerSearchPanel parent, final int BID, Controller session) {
setResizable(false);
setTitle("Return Book");
this.parent = parent;
this.mySession = session;
this.BID = BID;
ImageIcon img = new ImageIcon("res/library-icon.png");
this.setIconImage(img.getImage());
setBounds(100, 100, 250, 100);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new FormLayout(new ColumnSpec[] {
FormFactory.RELATED_GAP_COLSPEC,
FormFactory.DEFAULT_COLSPEC,
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(25dlu;default):grow"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("max(19dlu;default)"),
FormFactory.RELATED_GAP_COLSPEC,
ColumnSpec.decode("center:default:grow"),},
new RowSpec[] {
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,
FormFactory.RELATED_GAP_ROWSPEC,
FormFactory.DEFAULT_ROWSPEC,}));
{
txtCallNo = new JTextField();
//txtBidshouldWe.setText("BID (should we autoGenerate?)");
contentPanel.add(txtCallNo, "2, 2, 5, 1, fill, default");
txtCallNo.setColumns(10);
}
{
JLabel lblBid = new JLabel("Call Number");
contentPanel.add(lblBid, "8, 2");
}
{
typeButtonGroup = new ButtonGroup();
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(txtCallNo.getText() == null || txtCallNo.getText().equals("")){
JOptionPane.showMessageDialog(getInstance(), "Please put call number");
}
try{
String message = mySession.placeHoldRequest(txtCallNo.getText(), BID);
// mySession.createNewUser(newUser);
JOptionPane.showMessageDialog(getInstance(), message);
closeDialogBox();
}/*catch(FineAssessedException ue){
JOptionPane.showMessageDialog(getInstance(), ue.getMessage());
closeDialogBox();
}*/
catch(SQLException e1){
JOptionPane.showMessageDialog(getInstance(), e1.getMessage());
}
catch(IllegalArgumentException e3){
JOptionPane.showMessageDialog(getInstance(), "Bad copy number");
}/* catch (UserCreationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BadUserIDException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/ catch (ParseException e1) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(getInstance(), "Unable to place on hold");
}
}
});
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
closeDialogBox();
}
});
buttonPane.add(cancelButton);
}
}
} | 5 |
Base(String path) {
url = asUrl(path);
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
StackTraceElement callee = elements[4];
String className = callee.getClassName();
String methodName = callee.getMethodName();
try {
@SuppressWarnings("unchecked")
Class<? extends API> calleeCls = (Class<? extends API>) Class.forName(className);
for (Method m: calleeCls.getMethods()) {
if (m.getName() == methodName && m.isAnnotationPresent(Volatile.class)) {
LOGGER.log(Level.WARNING, "You are making a request to a non-standard API: " + methodName);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
} | 6 |
protected JComponent initButtons()
{
JPanel q = new JPanel();
q.setLayout(new BoxLayout(q, BoxLayout.Y_AXIS));
myMessage = new JTextArea();
myMessage.setEditable(false);
q.add(myMessage);
JPanel topRow = new JPanel();
JPanel bottomRow = new JPanel();
myAddCase = new JButton("Add");
myAddCase.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addCase();
}
});
myAddCase.setToolTipText("Add the current case to the list");
myAddCase.setEnabled(false);
topRow.add(myAddCase);
myReplace = new JButton("Replace");
myReplace.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
replaceCase(myTable.getSelectedRow());
}
});
myReplace.setToolTipText("Replace the selected case with the current case");
myReplace.setEnabled(false);
topRow.add(myReplace);
myShowAll = new JButton("List");
myShowAll.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
listAll();
}
});
myShowAll.setEnabled(false);
myShowAll.setToolTipText("List all possible cases");
bottomRow.add(myShowAll);
myShowCase = new JButton("Show");
myShowCase.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showCase(myTable.getSelectedRow());
}
});
myShowCase.setEnabled(false);
myShowCase.setToolTipText("Display the selected case");
topRow.add(myShowCase);
myClearCase = new JButton("Delete");
myClearCase.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
clearCase(myTable.getSelectedRow());
}
});
myClearCase.setEnabled(false);
myClearCase.setToolTipText("Delete the selected case");
topRow.add(myClearCase);
myClearAll = new JButton("Clear");
myClearAll.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
clearAll();
}
});
myClearAll.setToolTipText("Clear all cases");
bottomRow.add(myClearAll);
myDone = new JButton("Done?");
myDone.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int numLeft = myLemma.numCasesTotal() - myCases.size();
if(numLeft == 1)
myMessage.setText("1 case left.");
else if(numLeft > 1)
myMessage.setText(numLeft + " cases left.");
else
myMessage.setText("All cases done.");
}
});
myDone.setToolTipText("Check if all cases are done");
bottomRow.add(myDone);
/*
* Enables and disables myShowCase and myClearCase depending on
* whether there is a selection.
*/
myTable.getSelectionModel().addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
if(e.getValueIsAdjusting())
return;
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
if(lsm.isSelectionEmpty())
{
myShowCase.setEnabled(false);
myClearCase.setEnabled(false);
myReplace.setEnabled(false);
}
else
{
myShowCase.setEnabled(true);
myClearCase.setEnabled(true);
myReplace.setEnabled(myAddCase.isEnabled());
}
}
});
q.add(topRow);
q.add(bottomRow);
JScrollPane r = new JScrollPane(q);
return r;
} | 4 |
public Object nextValue() throws JSONException {
char c = this.nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuilder sb = new StringBuilder();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
} | 7 |
public StringBuffer format(final CommandSender target) {
// format all dates with time zone for target
TimeZone timeZone = null;
final Format[] formats = this.getFormatsByArgumentIndex();
for(int i = 0; i < formats.length; i++) {
if (!(formats[i] instanceof DateFormat)) continue;
if (timeZone == null) timeZone = Recipients.getTimeZone(target);
final DateFormat sdf = (DateFormat) formats[i];
sdf.setTimeZone(timeZone);
this.setFormatByArgumentIndex(i, sdf);
}
final StringBuffer formatted = this.format(this.arguments, new StringBuffer(), null);
if (this.suffix != null) formatted.append(this.suffix.format(target));
return formatted;
} | 4 |
public void run() {
while (true) {
if (year!=w.year) {
year=w.year;
this.repaint();
}
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
}
} | 3 |
public void keyPressed(KeyEvent e) {
char keychar = e.getKeyChar();
int keycode = e.getKeyCode();
if (keycode>=0 && keycode < 256) {
keymap[keycode]=true;
lastkey=keycode;
lastkeychar=keychar;
if (wakeup_key==-1 || wakeup_key==keycode) {
if (!eng.isRunning()) {
eng.start();
// key is cleared when it is used as wakeup key
keymap[keycode]=false;
}
}
}
/* shift escape = exit */
if (e.isShiftDown ()
&& e.getKeyCode () == KeyEvent.VK_ESCAPE
&& !eng.isApplet()) {
System.exit(0);
}
//System.out.println(e+" keychar"+e.getKeyChar());
} | 8 |
public int lengthOfLinkedListWithCycle(ListNode head){
if (head == null)
return 0;
ListNode fast = head, slow = head;
int length = 1;
while(true){
if (fast == null || fast.next == null)
break;
slow = slow.next;
head = head.next.next;
if (slow == fast)
break;
}
if (slow == fast){
/* up to meeting point. */
slow = head;
while (slow != head){
slow = slow.next;
head = head.next;
length++;
}
/* get the length of cycle. */
while (fast.next != slow){
fast = fast.next;
length++;
}
length++;
} else {
fast = head;
while (fast != null){
fast = fast.next;
length++;
}
}
return length;
} | 9 |
public static void writeFile(ClassFile cf, String directoryName)
throws CannotCompileException {
try {
writeFile0(cf, directoryName);
}
catch (IOException e) {
throw new CannotCompileException(e);
}
} | 1 |
private void setFrameLocal(final int local, final Object type) {
int l = newLocals.length;
if (local >= l) {
Object[] a = new Object[Math.max(2 * l, local + 1)];
System.arraycopy(newLocals, 0, a, 0, l);
newLocals = a;
}
newLocals[local] = type;
} | 1 |
public void doGet(HttpServletRequest request,
HttpServletResponse res)
throws ServletException, IOException {
// send out the HTML file
res.setContentType("text/html");
PrintWriter out = res.getWriter ();
out.println("<html>");
out.println("<head>");
out.println("<title> Photo List </title>");
out.println("</head>");
out.println("<div style='float: right'><form name=logout method=post action=logout.jsp><input type=submit name=logout value=logout></form>");
out.println("<form name=help method=get action=help.html><input type=submit name=help value=help></form>");
out.println("<form name=logout method=post action=menu.jsp><input type=submit name=menu value=menu></form></div>");
out.println("<body bgcolor=\"#000000\" text=\"#cccccc\" >");
out.println("<center>");
out.println("<h3>The List of Images </h3>");
HttpSession session = request.getSession();
try{
/*
*Retrives a group id from pictureBrowse.jsp and from that the conditional statements get the appropriate pictures
*for the user to see depending on the permissions they chose
*/
String query="";
String userName=(String)session.getAttribute("USERNAME");
String group_id=(String)session.getAttribute("PERMITTED");
if (userName==null){
res.sendRedirect("login.jsp");
userName="";
}
//if name is admin, select all photos
if(userName.equals("admin")){
query = "Select photo_id from images";
//if searching top photos, select all photos that have unique views
if (group_id.equals("top")){
query = "select photo_id from("
+"select distinct(i.photo_id), count(distinct(uv.visitor_id)) as views "
+"from images i, unique_views uv "
+"where i.photo_id = uv.photo_id "
+"group by i.photo_id "
+"order by views desc) "
+"where rownum <=5 ";
}
}
//select private htos
else if (group_id.equals("2")){
query = "Select photo_id from images where permitted='2' and owner_name='"+userName+"'";
}
else if (group_id.equals("all")){
//Sql query that gets all viewable pictures
query = "select photo_id from images where permitted in( select group_id from groups where user_name='"+userName+"' UNION select group_id from group_lists where friend_id='"+userName+"') UNION select photo_id from images where permitted='2' and owner_name='"+userName+"' UNION select photo_id from images where permitted='1'";
}
else if (group_id.equals("top"))
{
query = " select photo_id from ("
+"select distinct(i.photo_id), count(distinct(uv.visitor_id)) as views "
+"from images i, unique_views uv, groups g, group_lists gl "
+"where i.photo_id = uv.photo_id and "
+"((i.permitted = g.group_id and g.user_name = '"+userName+"') "
+"or (i.permitted = gl.group_id and gl.friend_id = '"+userName+"') "
+"or (i.permitted = '1') "
+"or (i.permitted = '2' and owner_name = '"+userName+"')) "
+"group by i.photo_id "
+"order by views desc) "
+"where rownum <=5";
}
else{
query = "Select photo_id from images where permitted='"+group_id+"'";
}
session.removeAttribute("PERMITTED");
Connection conn = getConnected();
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(query);
String p_id = "";
while (rset.next() ) {
p_id = (rset.getObject(1)).toString();
// specify the servlet for the image
out.println("<a href=\"/proj1/GetBigPic?"+p_id+"\">");
// specify the servlet for the themernail
out.println("<img src=\"/proj1/GetOnePic?thumb"+p_id +"\"></a>");
}
stmt.close();
conn.close();
} catch ( Exception ex ){ out.println( ex.toString() );}
out.println("</body>");
out.println("</html>");
} | 8 |
private void logRequest(String uri, String res) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("log.txt", true)));
out.println(uri);
out.println(res);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} | 1 |
@Test
public void determineHighestFlush_ifSevenOfSameSuit_returnsSetOfSevenCards() {
assertFlushOfSize(getAllFlushCards(sevenFlush()), 7);
} | 0 |
public SplitYamlDataHolder(File f) {
folder = f;
userFile = new File(folder, "users.yml");
groupFile = new File(folder, "groups.yml");
worldFile = new File(folder, "worlds.yml");
entityFile = new File(folder, "entities.yml");
specialFile = new File(folder, "specials.yml");
} | 0 |
private void login() {
panel = new LoginPanel(this);
centerWindow();
this.add(panel);
panel.updateUI();
((LoginPanel) panel).getSignInBtn().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String user = ((JTextField)panel.getComponent(1)).getText();
String code = ((JTextField)panel.getComponent(3)).getText();
if(new DBInterface().userExists(user)) {
if(new DBInterface().checkCode(user, code)) {
if(new DBInterface().checkTime(user)) {
showCode(user);
} else {
new WrongLoginWindow(WrongLoginWindow.TIME);
}
} else {
new WrongLoginWindow(WrongLoginWindow.CODE);
}
} else {
new WrongLoginWindow(WrongLoginWindow.USERNAME);
}
}
});
} | 3 |
public Long getAverageStatistical(List<Long> list) {
// parameters check
if (list == null) {
return null;
}
int iterations = list.size();
Long sum = (long) 0;
for (Long result : list) {
sum += result;
}
return sum / iterations;
} | 2 |
private void viewSelectedComment() {
if (table == null)
return;
final int row = table.getSelectedRow();
if (row < 0)
return;
final int id = ((Integer) table.getValueAt(row, 0)).intValue();
URL u = null;
try {
u = new URL(Modeler.getContextRoot() + "comment?client=mw&action=view&primarykey=" + id);
}
catch (MalformedURLException e) {
e.printStackTrace();
return;
}
URLConnection conn = ConnectionManager.getConnection(u);
if (conn == null)
return;
InputStreamReader reader = null;
StringBuffer sb = new StringBuffer();
int c;
try {
reader = new InputStreamReader(conn.getInputStream());
while ((c = reader.read()) != -1)
sb.append((char) c);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException iox) {
}
}
}
viewComment(new String(sb));
} | 8 |
private void abrirLog() {
routeTable.setModel(new MyTableModel());
initColumnSizes(routeTable);
actionStartRouter.setEnabled(true);
actionStartForwarder.setEnabled(true);
actionSendMessage.setEnabled(true);
} | 0 |
public void use(BattleFunction iface, PokeInstance user, PokeInstance target, Move move) {
PokeInstance p;
if (this.target == Target.target) {
p = target;
} else {
p = user;
}
p.battleStatus.flags[flag] = true;
if (text != null) {
text = text.replace("$target", p.getName());
if (p.battleStatus.lastMove != -1)
text = text.replace("$lastMove", p.getMove(p.battleStatus.lastMove).getName());
iface.print(text);
}
} | 3 |
void parseXMPDecl(boolean ignoreEncoding) throws java.lang.Exception
{
String version;
String encodingName = null;
String standalone = null;
// Read the version.
require("version");
parseEq();
version = readLiteral(0);
if (!version.equals("1.0")) {
error("unsupported XML version", version, "1.0");
}
// Try reading an encoding declaration.
skipWhitespace();
if (tryRead("encoding")) {
parseEq();
encodingName = readLiteral(0);
checkEncoding(encodingName, ignoreEncoding);
}
// Try reading a standalone declaration
skipWhitespace();
if (tryRead("standalone")) {
parseEq();
standalone = readLiteral(0);
}
skipWhitespace();
require("?>");
} | 3 |
public static GoalActionSequence findGoalRoute(Level l, Agent agent,
Box box, Field agentFromField, Field agentToField,
Field boxFromField, Field boxToField,
Collection<Field> blockedFields) {
dir boxDir = null;
GoalSequenceNode root = new GoalSequenceNode(boxFromField,
agentFromField, null);
LinkedList<GoalSequenceNode> queue = new LinkedList<GoalSequenceNode>();
// prune looped states (if agent and box ends up in a state already
// explored)
HashMap<Field, ArrayList<Field>> closedSet = new HashMap<Field, ArrayList<Field>>();
// adding initial state to list set of explored states
ArrayList<Field> tempList = new ArrayList<Field>();
tempList.add(boxFromField);
closedSet.put(agentFromField, tempList);
// Add a closed set.
queue.add(root);
GoalSequenceNode currentNode = queue.poll();
while (currentNode != null
&& (currentNode.boxLocation != boxToField || currentNode.agentLocation != agentToField)) {
boxDir = Agent.getBoxDirection(currentNode.agentLocation,
currentNode.boxLocation);
ArrayList<Command> foundCommands = addPossibleBoxCommandsForDirection(
boxDir, currentNode.agentLocation, currentNode.boxLocation,
blockedFields);
for (Command command : foundCommands) {
Field boxLocation = null;
Field agentLocation = null;
if (command.cmd.equals("Push")) {
agentLocation = currentNode.boxLocation;
boxLocation = currentNode.boxLocation.neighbors[command.dir2
.ordinal()];
} else {
boxLocation = currentNode.agentLocation;
agentLocation = currentNode.agentLocation.neighbors[command.dir1
.ordinal()];
}
// Do we already have a way to get to this state?
if (closedSet.containsKey(agentLocation)) {
if (closedSet.get(agentLocation).contains(boxLocation)) {
continue;
} else { // the agent has been here before but without the
// box in same location
closedSet.get(agentLocation).add(boxLocation);
}
} else { // neither the agent or the box has been here before.
// Update DS and create node in BTtree:
ArrayList<Field> tempListe = new ArrayList<Field>();
tempListe.add(boxLocation);
closedSet.put(agentLocation, tempListe);
}
GoalSequenceNode node = new GoalSequenceNode(boxLocation,
agentLocation, command);
node.parent = currentNode;
queue.add(node);
}
if (queue.isEmpty()) { // we have searched to the end without
// finding a solution. Move boxes to get
// access to goals
return null;
}
currentNode = queue.poll();
}
GoalActionSequence returnSequence = new GoalActionSequence();
returnSequence.setAgentLocation(currentNode.agentLocation);
returnSequence.setBoxLocation(currentNode.boxLocation);
ArrayList<Command> commands = new ArrayList<Command>();
while (currentNode.parent != null) {
commands.add(currentNode.action);
currentNode = currentNode.parent;
}
Collections.reverse(commands);
returnSequence.setCommands(commands);
return returnSequence;
} | 9 |
static void initFeature() {
Random rand = new Random();
for(int i = 0; i < DataInfo.userNumber; i++)
for(int j = 0; j < DataInfo.featureNumber; j++)
DataInfo.userFeature[i][j] = 0.01 * rand.nextDouble();
for(int i = 0; i < DataInfo.itemNumber; i++)
for(int j = 0; j < DataInfo.featureNumber; j++)
DataInfo.itemFeature[i][j] = 0.01 * rand.nextDouble();
} | 4 |
private void paintTextBounds(Graphics g) {
Page currentPage = pageViewComponent.getPageLock(this);
// get page transformation
AffineTransform pageTransform = currentPage.getPageTransform(
documentViewModel.getPageBoundary(),
documentViewModel.getViewRotation(),
documentViewModel.getViewZoom());
Graphics2D gg = (Graphics2D) g;
Color oldColor = g.getColor();
g.setColor(Color.red);
PageText pageText = currentPage.getViewText();
ArrayList<LineText> pageLines = pageText.getPageLines();
for (LineText lineText : pageLines) {
for (WordText wordText : lineText.getWords()) {
for (GlyphText glyph : wordText.getGlyphs()) {
g.setColor(Color.black);
GeneralPath glyphSpritePath =
new GeneralPath(glyph.getBounds());
glyphSpritePath.transform(pageTransform);
gg.draw(glyphSpritePath);
}
// if (!wordText.isWhiteSpace()) {
// g.setColor(Color.blue);
// GeneralPath glyphSpritePath =
// new GeneralPath(wordText.getBounds());
// glyphSpritePath.transform(pageTransform);
// gg.draw(glyphSpritePath);
// }
}
g.setColor(Color.red);
GeneralPath glyphSpritePath =
new GeneralPath(lineText.getBounds());
glyphSpritePath.transform(pageTransform);
gg.draw(glyphSpritePath);
}
g.setColor(oldColor);
pageViewComponent.releasePageLock(currentPage, this);
} | 3 |
private void updateParam(List<Instance> instances) {
Map<Integer, Double> update = new HashMap<Integer, Double>();
for (Instance instance : instances) {
double y = Double.parseDouble(instance.getLabel().toString()) ; //yi
double wx = this.innerProduct(instance);
for (Map.Entry<Integer, Double> entry : instance.getFeatureVector().getVector().entrySet()){
int key = entry.getKey(); //j
if (!this.linearParam.containIndex(key)) {
continue;
}
if (!update.containsKey(key)) {
update.put(key, 0.0);
}
double value = entry.getValue(); //xij
double updatedValue = update.get(key) + y * linkFunction(-1 * wx) * value
- (1-y) * linkFunction(wx) * value;
update.put(key, updatedValue);
}
}
for (Map.Entry<Integer, Double> entry : linearParam.getVector().entrySet()) {
entry.setValue(entry.getValue() + gd_eta *update.get(entry.getKey()));
}
} | 5 |
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 7 |
public int getM()
{
return m;
} | 0 |
private void nextMove(int type) {
if (type == 0) {
holdable = true;
generateNextTokens();
} else {
currentType = type;
}
//set currentTokens
switch (currentType) {
case 1:// the I token
setPositionForCase1(currentTokens, 3);
rotater = new RotaterI(tokens);
break;
case 2:// the J token
setPositionForCase2(currentTokens, 3);
rotater = new RotaterJ(tokens);
break;
case 3:// the L token
setPositionForCase3(currentTokens, 3);
rotater = new RotaterL(tokens);
break;
case 4:// the O token
setPositionForCase4(currentTokens, 3);
rotater = new RotaterO(tokens);
break;
case 5:// the S token
setPositionForCase5(currentTokens, 3);
rotater = new RotaterS(tokens);
break;
case 6:// the T token
setPositionForCase6(currentTokens, 3);
rotater = new RotaterT(tokens);
break;
default:// the Z token
setPositionForCase7(currentTokens, 3);
rotater = new RotaterZ(tokens);
}
if (checkIsLose()) {
lose();
return;
}
//set type for the currentToken
setCurrentTokens(currentType);
setDirectingTokens();
rotateCount = 0;
refresh();
} | 8 |
@Override
public void valueChanged(LabelledSpinner source, int value) {
if (source == hpNumerator) {
eventBus.post(new HPNumeratorChanged(value));
} else if (source == hpDenominator) {
eventBus.post(new HPDenominatorChanged(value));
} else if (source == defNumerator) {
eventBus.post(new DefNumeratorChanged(value));
} else if (source == defDenominator) {
eventBus.post(new DefDenominatorChanged(value));
} else if (source == spDefNumerator) {
eventBus.post(new SpDefNumeratorChanged(value));
} else if (source == spDefDenominator) {
eventBus.post(new SpDefDenominatorChanged(value));
}
} | 6 |
@Override
/**
* Encodes a message.
* @param session
* @param message
* @param out
*/
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
try {
Packet p = (Packet) message;
byte[] data = p.getData();
int dataLength = p.getLength();
ByteBuffer buffer;
if (!p.isBare()) {
buffer = ByteBuffer.allocate(dataLength + 3);
int id = p.getId();
buffer.put((byte)id);
if(p.getSize() != Packet.Size.Fixed) {
if(p.getSize() == Packet.Size.VariableByte) {
if(dataLength > 255) //trying to send more data then we can represent with 8 bits!
throw new IllegalArgumentException("Tried to send packet length "+dataLength+" in 8 bits [pid="+p.getId()+"]");
buffer.put((byte)dataLength);
} else if(p.getSize() == Packet.Size.VariableShort) {
if(dataLength > 65535) //trying to send more data then we can represent with 16 bits!
throw new IllegalArgumentException("Tried to send packet length "+dataLength+" in 16 bits [pid="+p.getId()+"]");
buffer.put((byte)(dataLength >> 8));
buffer.put((byte)dataLength);
}
}
} else
buffer = ByteBuffer.allocate(dataLength);
buffer.put(data, 0, dataLength);
buffer.flip();
out.write(buffer);
} catch(Exception err) {
err.printStackTrace();
}
} | 7 |
public static void main(String[] args) throws IOException {
// BufferedReader in = new BufferedReader(new
// InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
String line[];
int times = 1;
while (scan.hasNext()) {
int n = scan.nextInt();// Integer.parseInt(line[0]);
if(n==0)
break;
arr = new int[ n ];
nCartas = n;
dp = new int[ n ][ n ];
dp2 = new int[ n ][ n ];
long tm = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
for (int k = 0; k < n; k++) {
dp[i][k] = Integer.MIN_VALUE;
dp2[i][k] = Integer.MIN_VALUE;
}
}
// System.out.println(System.currentTimeMillis() - tm);
bruteForce(0, 0, 0, 0, arr.length - 1, 0, "");
bruteForce(0, 0, 0, 0, arr.length - 1, 1, "");
//dfs(0, 0, 0, 0, arr.length - 1, 1, "", "");
//dfs2(0, 0, 0, 0, arr.length - 1, 0, "", "");
for (int i = 0; i < n; i++) {
if (dp[i][i] > max)
max = dp[i][i];
if (dp2[i][i] > max)
max = dp2[i][i];
}
//System.out.println(camino);
System.out.println("In game " + times + ", the greedy strategy might lose by as many as " + max + " points.");
max = Integer.MIN_VALUE;
times++;
//System.out.println(System.currentTimeMillis() - tm);
/*
* for (int i = 0; i < n; i++) { for (int k = 0; k < n; k++) { //
* System.out.print((dp[i][k] != Integer.MIN_VALUE ? dp[i][k] :
* "n ")); } System.out.println(); }
*/
}
} | 8 |
@Override
public int hashCode() {
int hash = 0;
hash += (itItemHasEmpleadoPK != null ? itItemHasEmpleadoPK.hashCode() : 0);
return hash;
} | 1 |
public void openFile() throws Exception {
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
DrawInternalFrame internalFrame = new DrawInternalFrame(this);
File file = fileChooser.getSelectedFile();
if (file.getName().endsWith(".png")
|| file.getName().endsWith(".PNG")) {
BufferedImage img;
try {
img = ImageIO.read(file);
ImageIcon icon = new ImageIcon(img);
// internalFrame.getDrawPanel().setIcon();
Dimension imageSize = new Dimension(icon.getIconWidth(),
icon.getIconHeight());
internalFrame.getDrawPanel().setPreferredSize(imageSize);
internalFrame.getDrawPanel().setImage(img);
} catch (IOException e) {
}
internalFrame.setTitle(file.getName());
} else {
JOptionPane.showMessageDialog(this,
"L'extension de l'image doit �tre de type .png.");
throw new Exception("L'extension de l'image est mauvaise.");
}
}
} | 4 |
private boolean isSlavoGermanic(String value) {
return value.indexOf('W') > -1 || value.indexOf('K') > -1 ||
value.indexOf("CZ") > -1 || value.indexOf("WITZ") > -1;
} | 3 |
private boolean isValid() {
if (email.length() > 50 || address.length() > 75)
{
System.err.println("Invalid argument(s) when inserting an availability!");
return false;
}
return true;
} | 2 |
public static void main(String[] args) {
Claire clairette = new Claire();
clairette.play();
} | 0 |
private synchronized ExecutorService getExecutor() {
if (service == null) {
service = Executors.newFixedThreadPool(MAX_NUMBER_OF_ENFORCERS);
}
return service;
} | 1 |
public static void main(String[] args) throws Exception
{
for( int x=1; x < NewRDPParserFileLine.TAXA_ARRAY.length; x++)
{
System.out.println(NewRDPParserFileLine.TAXA_ARRAY[x]);
File inFile = new File(ConfigReader.getAdenomasReleaseDir() + File.separator +
"spreadsheets" + File.separator + "pivoted_" +
NewRDPParserFileLine.TAXA_ARRAY[x] + "LogNormalWithMetadata.txt");
int numSamples = getNumSamples(inFile);
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
ConfigReader.getAdenomasReleaseDir() + File.separator +
"spreadsheets" + File.separator + "pivoted_" +
NewRDPParserFileLine.TAXA_ARRAY[x] + "LogNormalWithMetadata.arff")
));
writer.write("% " + NewRDPParserFileLine.TAXA_ARRAY[x] + "\n");
writer.write("@relation " + NewRDPParserFileLine.TAXA_ARRAY[x] + "_adenomas454\n");
String[] topSplits = reader.readLine().replaceAll("\"","").split("\t");
for( int y=3; y < topSplits.length; y++)
{
writer.write("@attribute " + topSplits[y].replaceAll(" ", "_") + " numeric\n");
}
writer.write("@attribute isCase { true, false }\n");
writer.write("\n\n@data\n");
writer.write("%\n% " + numSamples + " instances\n%\n");
for( String s= reader.readLine(); s != null; s = reader.readLine())
{
s = s.replaceAll("\"", "");
String[] splits = s.split("\t");
if( splits.length != topSplits.length)
throw new Exception("Parsing error!");
for( int y=3; y < splits.length; y++)
{
writer.write( splits[y] + ",");
}
if( splits[1].equals("control") )
writer.write("false\n");
else if( splits[1].equals("case"))
writer.write("true\n");
else throw new Exception("Parsing error\n");
}
writer.flush(); writer.close();
reader.close();
}
} | 7 |
public void deleteElement(String value) {
ListElement index = head;
if (index.value.equals(value)) {
deleteFromBegin();
} else {
while (index.next != null) {
if (index.next.value.equals(value)) {
index.next = index.next.next;
} else {
index = index.next;
}
}
if ((index.next == null) && (index.value.equals(value))) {
deleteFromEnd();
}
}
} | 5 |
public int CantPar(int opcion2) {
if (opcion2 == 5 || opcion2 == 8) {
cp++;
}
//if para reiniciar las partidas jugadas en caso de reiniciar el juego
if (opcion2 == 7) {
cp = 0;
}
return cp;
} | 3 |
private boolean jj_3_1()
{
if (jj_scan_token(LEFTB)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(COMMA)) return true;
return false;
} | 3 |
* @param notes notes to be added about the contact.
* @throws NullPointerException if the name or the notes are null
*/
public void addNewContact(String name, String notes) throws NullPointerException
{
if(name == null)
{
throw new NullPointerException("name should not be null");
}
if(notes == null)
{
throw new NullPointerException("notes should not be null");
}
Contact contact = new ContactImpl(name);
contact.addNotes(notes);
contactList.add(contact);
} | 2 |
final int[][] method3047(int i, int i_3_) {
if (i_3_ != -1564599039)
return null;
anInt9353++;
int[][] is = ((Class348_Sub40) this).aClass322_7033
.method2557(i_3_ + 1564598957, i);
if (((Class322) ((Class348_Sub40) this).aClass322_7033).aBoolean4035) {
int[][] is_4_ = this.method3039((byte) -60, i, 0);
int[] is_5_ = is_4_[0];
int[] is_6_ = is_4_[1];
int[] is_7_ = is_4_[2];
int[] is_8_ = is[0];
int[] is_9_ = is[1];
int[] is_10_ = is[2];
for (int i_11_ = 0; ((Class348_Sub40_Sub6.anInt9139 ^ 0xffffffff)
< (i_11_ ^ 0xffffffff)); i_11_++) {
int i_12_ = is_5_[i_11_];
int i_13_ = is_7_[i_11_];
int i_14_ = is_6_[i_11_];
if (i_13_ != i_12_
|| (i_14_ ^ 0xffffffff) != (i_13_ ^ 0xffffffff)) {
is_8_[i_11_] = anInt9344;
is_9_[i_11_] = anInt9354;
is_10_[i_11_] = anInt9347;
} else {
is_8_[i_11_] = i_12_ * anInt9344 >> -1822350100;
is_9_[i_11_] = anInt9354 * i_13_ >> 1973584748;
is_10_[i_11_] = anInt9347 * i_14_ >> -2011567156;
}
}
}
return is;
} | 5 |
@Test
public void test_solvable_matrix_size_2_solve2() throws
ImpossibleSolutionException,UnsquaredMatrixException,
ElementOutOfRangeException{
int height=2;
int width=2;
float[] result;
try{
test_matrix = new Determinant(height,width);
}catch(UnsquaredMatrixException e){
throw e;
}
try{
test_matrix.setValueAt(0,0, 20.0f);
test_matrix.setValueAt(0,1, 400.0f);
test_matrix.setValueAt(1,0,1700.0f);
test_matrix.setValueAt(1,1, 5.0f);
}catch(ElementOutOfRangeException e){
throw e;
}
try{
result = test_matrix.solve();
}catch(ImpossibleSolutionException e){
throw e;
}
Assert.assertEquals(-679900.00f,result[0],.00001f);
} | 3 |
public static int atoi2(String str) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int result=0;
for(int i=str.length()-1, w=0;i>=0;--i) {
if(str.charAt(i)=='-') return -result;
if(str.charAt(i)=='+') return result;
if(str.charAt(i)!=' ') {
result += ((int)(str.charAt(i))-48)*Math.pow(10,w);
w++;
}
}
return result;
} | 4 |
@Override
public boolean equals(Object o )
{
if(o == null)
return false;
if(o == this)
return true;
if(!(o instanceof FertigungsplanDTO))
return false;
FertigungsplanDTO f = (FertigungsplanDTO)o;
if(f.nr != nr || f.id != id || f.auftragNr != auftragNr || f.produktId != produktId)
return false;
return true;
} | 7 |
public static void main(String[] args) throws Exception {
if (args.length != 4 && args.length != 5) {
System.err.println(USAGE);
System.exit(1);
}
File metadataFile = new File(args[0]);
File outputFile = new File(args[1]);
File pkcs12File = new File(args[2]);
String passwd = args[3];
String email = null;
if (args.length == 5) {
email = args[4];
}
X509Info x509Info = null;
Document doc = null;
try {
KeyStore keyStore = X509Utils.pkcs12ToKeyStore(pkcs12File, passwd);
x509Info = X509Utils.x509FromKeyStore(keyStore, passwd);
} catch (FileNotFoundException e) {
System.err.println("certificate file not found: " + pkcs12File);
System.exit(1);
} catch (Exception e) {
System.err.println("error loading certificate (wrong password?)");
System.exit(1);
}
try {
DocumentBuilder db = XMLUtils.newDocumentBuilder(false);
doc = db.parse(metadataFile);
MetadataUtils.signMetadataEntry(doc, x509Info, email);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
try {
String signedContents = XMLUtils.documentToString(doc);
writeStringToFile(signedContents, outputFile);
} catch (Exception e) {
removeOutputFile(outputFile);
System.err.println(e.getMessage());
System.exit(1);
}
} | 7 |
private void turnAngle(int index, double change){
switch(index){
case 0:
this.angle[0]+=change;
break;
case 1:
this.angle[1]+=change;
break;
case 2:
this.angle[2]+=change;
}
// Keep the angle between -180 and 180
if(this.angle[index]>Math.PI){
this.angle[index]=-Math.PI;
}
if(this.angle[index]<-Math.PI){
this.angle[index]=Math.PI;
}
} | 5 |
public SyncCheckView(final JPanel panel) {
// Top will be button
final JPanel top = new JPanel();
top.setBorder(BorderFactory.createEtchedBorder());
top.setLayout(new BorderLayout());
// Bottom will be text area
final JPanel bottom = new JPanel();
bottom.setBorder(BorderFactory.createEtchedBorder());
bottom.setLayout(new BorderLayout());
// App split so user can mvoe the parts
final JSplitPane pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, top, bottom);
pane.setOneTouchExpandable(true);
pane.setDividerLocation(150);
final Dimension minSize = new Dimension(100, 50);
top.setMinimumSize(minSize);
bottom.setMinimumSize(minSize);
panel.add(pane, BorderLayout.CENTER);
// Build top button
final JButton button = new JButton("Run SyncCheck");
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (final FolderConfig folderConfig : GuiUtils.syncConfig.getConfigs()) {
if (!folderConfig.isSyncOn()) {
System.out.println("Sync is turned off for artist URL " + folderConfig.getArtistUrl()
+ ". Will not run syncCheck for this artist.");
continue;
}
final SyncChecker checker = SCUtilFactory.getSyncChecker(folderConfig.getArtistUrl());
checker.check(folderConfig);
}
JOptionPane
.showMessageDialog(panel, "Finished SyncCheck, make sure to save.", "SyncCheck Success", JOptionPane.PLAIN_MESSAGE);
}
});
thread.start();
}
});
top.add(button);
// Build bottom text area
final JTextArea text = new JTextArea();
final JScrollPane scroll = new JScrollPane(text, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
System.setOut(new PrintStream(new JTextAreaOutputStream(text)));
bottom.add(scroll);
} | 2 |
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.