text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
public void publishInterruptibly(final long sequence, final Sequence cursor)
throws InterruptedException {
int counter = RETRIES;
while (sequence - cursor.get() > pendingPublication.length()) {
if (--counter == 0) {
if(yieldAndCheckInterrupt())
throw new InterruptedException();
counter = RETRIES;
}
}
pendingPublication.set((int) sequence & pendingMask, sequence);
// One of other threads has published this sequence for the current thread
long cursorSequence = cursor.get();
if (cursorSequence >= sequence) {
return;
}
long expectedSequence = Math.max(sequence - 1L, cursorSequence);
long nextSequence = expectedSequence + 1;
while (cursor.compareAndSet(expectedSequence, nextSequence)) {
if(Thread.interrupted())
throw new InterruptedException();
expectedSequence = nextSequence;
nextSequence++;
if (pendingPublication.get((int) nextSequence & pendingMask)
!= nextSequence) {
// if exceeds the capacity of pendingPublication, exit
break;
}
}
} | 7 |
private void combinationSum2Helper(int idx, int[] num, int target,
ArrayList<ArrayList<Integer>> result, int[] times) {
if (target < 0 || (idx == num.length && target != 0))
return;
if (target == 0) {
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int i = 0; i < idx; i++) {
for (int j = 1; j <= times[i]; j++) {
ret.add(num[i]);
}
}
result.add(ret);
return;
}
int time = 0;
int idxCur = idx;
while (idxCur < num.length && num[idxCur] == num[idx]) {
time++;
idxCur++;
}
for (int i = 0; i <= time; i++) {
times[idx] = i;
combinationSum2Helper(idxCur, num, target - num[idx] * i, result, times);
}
} | 9 |
private boolean interfaceIsSelected(RSInterface class9)
{
if(class9.anIntArray245 == null)
return false;
for(int i = 0; i < class9.anIntArray245.length; i++)
{
int j = extractInterfaceValues(class9, i);
int k = class9.anIntArray212[i];
if(class9.anIntArray245[i] == 2)
{
if(j >= k)
return false;
} else
if(class9.anIntArray245[i] == 3)
{
if(j <= k)
return false;
} else
if(class9.anIntArray245[i] == 4)
{
if(j == k)
return false;
} else
if(j != k)
return false;
}
return true;
} | 9 |
public boolean gridHasUserCar(){
if(vehicleMap.containsKey('A')){
return true;
} else {
return false;
}
} | 1 |
private void setResult()
{
if(stressDistribution.size() < 100)
this.result += "Stress distribution = " + stressDistribution + "\n";
else
{
for(Integer value : stressDistribution.values())
{
int i = 10;
Integer key = 1;
while(!(value >= key && value < key * i))
key *= i;
Integer count = stressDistributionRange.get(key);
if (count == null) {
stressDistributionRange.put(key, 1);
}
else {
stressDistributionRange.put(key, count + 1);
}
}
this.result += "Stress distribution range = " + stressDistributionRange + "\n";
}
HashMap<Integer, Integer> temp = new HashMap<Integer, Integer>();
for(Integer key : stressDistribution.values())
{
Integer count = temp.get(key);
if (count == null) {
temp.put(key, 1);
}
else {
temp.put(count, count + 1);
}
}
this.result += "Stress distribution = " + temp + "\n";
this.result += "Node with the max stress distribution = " + Collections.max(stressDistribution.values()) + "\n";
this.result += "Node with the min stress distribution = " + Collections.min(stressDistribution.values()) + "\n";
this.result += "Shortest path length distribution = " + shortestLengthDistribution + "\n";
this.result += "Average path = " + avgPath + "\n";
this.result += "Unconnected pairs of nodes = " + unconnectedNodes + "\n";
this.result += "Connected pairs of nodes = " + connectedNodes + "\n";
this.result += "Network diameter = " + networkDiameter + "\n";
this.result += "Six degrees of separation occurs = " + sixDegreesOfSeparation + "\n";
} | 7 |
@Override
public String[][] loadCells(Settings settings) throws Exception {
SpreadsheetService service = new SpreadsheetService(APP_NAME);
String login = settings.googleLogin;
String password = settings.googlePassword;
if (login == null || login.length() == 0) {
if (System.console() == null) throw new LocalizationException("Can't read google login from console");
System.console().printf("Google account login:\n");
login = System.console().readLine();
}
if (password == null || password.length() == 0) {
if (System.console() == null) throw new LocalizationException("Can't read google password from console");
System.console().printf("Google account password:\n");
password = new String(System.console().readPassword());
}
Settings.checkNotEmpty(login, Settings.PROP_GOOGLE_LOGIN);
Settings.checkNotEmpty(password, Settings.PROP_GOOGLE_PASSWORD);
service.setUserCredentials(login, password);
return loadCells(service, "private", settings);
} | 6 |
public Tape[] getTapes() {
return myTapes;
} | 0 |
private void createAndCompare(){
//Grab each chromosome file.
Sequence_DNA seq;
StringBuffer sb;
//Iterate through each chromosome file, and create all of the transcripts possible from each one
//Code is performed in this order to minize HDD reads.
for(int k = 0; k < 25; k++){
//Ignore the mitochondrian DNA
if(k == 22){
if(!genomeHasMito){
continue;
}//if
}//if
seq = new Sequence_DNA(chrmFile[k]);
sb = new StringBuffer(seq.getNucleotideSequences().get(0).getSequence());
BedFileLine beingTested;
//Check each transcript to determine if it is using the currently open file.
for(int j = 0; j < BEDlist.size(); j++){
//Current BEDlist line being worked on.
beingTested = BEDlist.get(j);
//Ignore lines that do not occur on the chromosome currently being worked on. chromosome
if(beingTested.getChromosomeName() != k + 1){
continue;
}//if
int blockCount = Integer.valueOf(beingTested.getBlockCount());
String dnaSeq = sb.substring(beingTested.getStartLocation(), beingTested.getStopLocation());;
//Handle the situation where there are multiple blocks to string together.
if(blockCount > 1){
String buildingSeq = "";
int blckStart;
int blckSize;
Scanner starts = new Scanner(beingTested.getBlockStart());
Scanner sizes = new Scanner(beingTested.getBlockSize());
starts.useDelimiter(",");
sizes.useDelimiter(",");
for(int p = 0; p < blockCount; p++){
blckStart = (Integer.valueOf(starts.next()));
blckSize = (Integer.valueOf(sizes.next()));
if(beingTested.getStrand() == Definitions.genomicStrandPOSITIVE){
}//if
buildingSeq += dnaSeq.substring(blckStart, blckStart + blckSize);
}//for
dnaSeq = buildingSeq;
}//if
beingTested.setDnaSeq(dnaSeq);
}//inner for
}//outer for
}//Create and compare | 8 |
public static void main(String[] args) {
if(args.length<2){
System.out.println("Please specify train and test file arguments");
System.exit(1);
}
else{
readFile(args[0]);
}
int threshold=50;
if(args.length==3){
threshold=Integer.parseInt(args[2]);
if(threshold%2!=0){
System.out.println("please enter an even number, for equally sized all and aml groups");
System.exit(1);
}
}
chooseGenes(threshold);
readTestFile(args[1]);
double p=0.0;
double wrong=0.0;
double allDiff=0.0;
double amlDiff=0.0;
for(int i=0;i<testData.length;i++){
// expLvls=votingScores(i);
// for(int j=0;j<choiceGenes.length;j++){
// allDiff=Math.abs(expLvls[j]-ALLmeans[(int) weights[j][1]]);
// amlDiff=Math.abs(expLvls[j]-AMLmeans[(int) weights[j][1]]);
// if(allDiff>amlDiff){
// amlVote+=weights[j][0]*weights[j][2];
// }
// else{
// allVote+=weights[j][0]*weights[j][2];
// }
// }
p=Math.abs(allVote-amlVote);
p/=(amlVote+allVote);
//System.out.println("allVote: "+allVote+" amlVote: "+amlVote);
if(amlVote>allVote && p>0.3){
System.out.println("Diagnosis for patient "+i+" is AML");
if(testData[i][0]!=1.0){
System.out.println("(WRONG)");
wrong+=1.0;
}
}
else if(p>0.3){
System.out.println("Diagnosis for patient "+i+" is ALL");
if(testData[i][0]!=0.0){
System.out.println("(WRONG)");
wrong+=1.0;
}
}
else{
System.out.println("patient "+i+" is No-Call. Confidence interval to low.");
}
System.out.println("Prediction strength for patient "+i+" = "+p);
}
System.out.println("The prediction accuracy rate was "+(wrong/testData.length*100)+"%");
System.exit(0);
} | 9 |
public static TreeMap<Integer, Integer> getShiptypesIDOccurrence(
ArrayList<Kill> killBoard, String attribute) {
TreeMap<Integer, Integer> result = new TreeMap<Integer, Integer>();
if (killBoard.isEmpty()) {
return null;
}
for (Kill K : killBoard) {
if (K.getVictim().findAttribute(attribute)) {
Integer shipID = K.getVictim().getShipId();
MapHelpers.incrementValue(result, shipID);
}
ArrayList<ShipAndChar> attackers = K.getAttackers();
for (ShipAndChar SnC : attackers) {
if (SnC.findAttribute(attribute)) {
Integer shipID = SnC.getShipId();
MapHelpers.incrementValue(result, shipID);
}
}
}
return result;
} | 5 |
public static Constructor<?> getConstructor(String inClass, boolean touch) {
// Create a class object from the class matching the table name
Class<?> clazz = null;
Constructor<?> cons = null;
try {
clazz = Class.forName(inClass);
} catch (ClassNotFoundException ex) {
// Logger.getLogger(GTFSParser.class.getName()).log(Level.SEVERE,
// null, ex);
}
try {
if (clazz != null) {
if (touch) {
cons = clazz.getConstructor(String.class);
} else {
cons = clazz.getConstructor(String.class, int.class);
}
}
} catch (NoSuchMethodException | SecurityException ex) {
// Logger.getLogger(GTFSParser.class.getName()).log(Level.SEVERE,
// null, ex);
}
return cons;
} | 7 |
public String doIt(String arg){
System.out.println("called .. demo.service.Service1.doIt(String)");
return arg;
} | 0 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ClientUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ClientUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ClientUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ClientUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientUI().setVisible(true);
}
});
} | 6 |
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("editor_undo")) {
textComponent.undo();
} else if (e.getActionCommand().equals("editor_redo")) {
textComponent.redo();
} else if (e.getActionCommand().equals("editor_cut")) {
textComponent.cut();
} else if (e.getActionCommand().equals("editor_copy")) {
textComponent.copy();
} else if (e.getActionCommand().equals("editor_paste")) {
textComponent.paste();
} else if (e.getActionCommand().equals("editor_delete")) {
int ss = textComponent.getSelectionStart();
int se = textComponent.getSelectionEnd();
try {
textComponent.getDocument().remove(ss, se-ss);
} catch(BadLocationException exc) {
ExceptionHandler.error(exc);
}
} else if (e.getActionCommand().equals("editor_select_all")) {
textComponent.selectAll();
}
} | 8 |
private void insertImmediately(TransObj obj)
{
Connection conn = null;
try {
conn = DBManager.getConnection();
/*PreparedStatement prepStatement = conn.prepareStatement(P_INSERT_STRING);
prepStatement.setInt(1, obj.getSeq());
prepStatement.setLong(2, obj.getInitTime());
prepStatement.setLong(3, System.currentTimeMillis());
prepStatement.setLong(4, (System.currentTimeMillis()-obj.getInitTime()));
prepStatement.addBatch();
prepStatement.executeBatch();*/
String dml = String.format(INSERT_STRING, obj.getSeq(),obj.getInitTime(),System.currentTimeMillis(),(System.currentTimeMillis()-obj.getInitTime()));
Statement stmt = conn.createStatement();
stmt.addBatch(dml);
stmt.executeBatch();
System.out.println("============Insert OK==============");
} catch (SQLException e1) {
e1.printStackTrace();
}finally{
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} | 3 |
private void performSwap(LeftistTreeNode root) {
if (root != null) {
LeftistTreeNode right, left, toBeSwapped;
if (root.parent != null) {
toBeSwapped = root.parent;
right = toBeSwapped.right;
left = toBeSwapped.left;
} else {
toBeSwapped = root;
right = root.right;
left = root.left;
}
String rightValue = right == null ? "" : right.value;
String leftValue = left == null ? "" : left.value;
int rightNpl = right == null ? -1 : npl(right, -1);
int leftNpl = left == null ? -1 : npl(left, -1);
if (rightNpl > leftNpl || (rightNpl == leftNpl && leftValue.compareTo(rightValue) < 0)) { // invert here to change to small priority on top
swap(toBeSwapped);
}
performSwap(root.left);
performSwap(root.right);
}
} | 9 |
public void atualizar(PalavraChave palavrachave) throws Exception
{
String sql = "UPDATE palavrachave SET palavra = ? WHERE id = ?";
try
{
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
stmt.setString(1, palavrachave.getPalavra());
stmt.setLong(2, palavrachave.getId());
stmt.executeUpdate();
}
catch (SQLException e)
{
throw e;
}
} | 1 |
public static void awardBonusExternal() {
class AwardBonus extends RecursiveAction {
public AwardBonus(ArrayList<BankAccount> accounts, int start, int end) {
this.accounts = accounts;
this.start = start;
this.end = end;
}
private ArrayList<BankAccount> accounts;
private final int start, end;
private void awardBonus() {
BigInteger bonusReduction = BigInteger.valueOf(100);
for (int i=start; i<end; i++) {
BankAccount currentAccount = accounts.get(i);
if (currentAccount.getBalance().signum() > 0)
currentAccount.deposit(currentAccount.getBalance().divide(bonusReduction));
}
}
@Override
protected void compute() {
// Better use Runtime.getRuntime().availableProcessors()
if (end-start < 10)
awardBonus();
else {
invokeAll(new AwardBonus(accounts,start,(start+end)/2),
new AwardBonus(accounts,(start+end)/2,end));
}
}
}
ForkJoinPool pool = new ForkJoinPool();
ArrayList<BankAccount> accountsList = new ArrayList<>(christmasBank.getAllAccounts());
pool.invoke(new AwardBonus(accountsList,0,accountsList.size()));
System.out.print("Balances of all accounts (ext): ");
for (BankAccount account: accountsList)
System.out.print(" " + account.getBalance());
System.out.println();
} | 1 |
public FieldVisitor visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
StringBuffer sb = new StringBuffer();
appendAccess(access | ACCESS_FIELD, sb);
AttributesImpl att = new AttributesImpl();
att.addAttribute("", "access", "access", "", sb.toString());
att.addAttribute("", "name", "name", "", name);
att.addAttribute("", "desc", "desc", "", desc);
if (signature != null) {
att.addAttribute("", "signature", "signature", "",
encode(signature));
}
if (value != null) {
att.addAttribute("", "value", "value", "", encode(value.toString()));
}
return new SAXFieldAdapter(getContentHandler(), att);
} | 2 |
private void clearNetsAfterGoalSet() {
Enumeration eNum = CANT23.nets.elements();
while (eNum.hasMoreElements()) {
CANTNet net = (CANTNet)eNum.nextElement();
if ((net.getName().compareTo("VerbInstanceNet") == 0) ||
(net.getName().compareTo("NounAccessNet") == 0) ||
(net.getName().compareTo("VerbAccessNet") == 0) ||
(net.getName().compareTo("NounSemNet") == 0) ||
(net.getName().compareTo("VerbSemNet") == 0) ||
(net.getName().compareTo("GoalSetNet") == 0) ||
(net.getName().compareTo("NounInstanceNet") == 0))
net.clear();
}
} | 8 |
static int KMP(char[] p, char[] t, int start, int end) {
int i = start, j = 0, m = p.length, n = end, max = 0;
while (i < n) {
while (j >= 0 && p[j] != t[i])
j = b[j];
i++;
j++;
if (i == n)
max = Math.max(max, j);
if (j == m)
j = b[j];
}
return max;
} | 5 |
private void computeShortestPath() {
Cell goalCell = map.getGoalCell();
updateKey(goalCell);
// Cell peekedCell = expandedList.peek() == null ? new Cell() {
// {
// key = new Key(Integer.MAX_VALUE, Integer.MAX_VALUE);
// }
// } : expandedList.peek();
while (expandedList.peek() != null && cC.compare(expandedList.peek(), goalCell) < 0
|| goalCell.rhs != goalCell.g) {
Cell topCell = expandedList.poll();
if (topCell.g > topCell.rhs) {
topCell.g = topCell.rhs;
for (Cell c : getCellSuccessors(topCell)) {
updateCell(c);
}
} else {
topCell.g = Integer.MAX_VALUE;
ArrayList<Cell> successors = getCellSuccessors(topCell);
successors.add(topCell);
for (Cell c : successors) {
updateCell(c);
}
}
}
Cell c = goalCell;
LinkedList<Cell> path = new LinkedList<Cell>();
while (c != null) {
path.add(c);
System.out.println(String.format("row:%02d col:%02d", c.row, c.col));
c = c.searchTree;
}
if (!path.isEmpty() && path.getLast() == map.getStartCell()) {
this.shortestPath = path;
}
} | 9 |
public java.awt.Component getTableCellRendererComponent(JTable aTable,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JComponent c = (JComponent) super.getTableCellRendererComponent(
aTable, value, isSelected, hasFocus, row, column);
c.setToolTipText(table.getContentDescription(row, column));
return c;
} | 0 |
public void setHost(String host) {
this.host = host;
} | 0 |
private String cleanText( String text )
{
StringBuilder sb = new StringBuilder();
for ( int i=0;i<text.length();i++ )
{
char token = text.charAt(i);
if ( token == '\n' )
sb.append(" ");
else if ( token == '\t' )
sb.append(" ");
else if ( token == '"' )
sb.append("\\\"");
else
sb.append(token);
}
return sb.toString();
} | 4 |
public Ast compile_text(String text, String type) {
switch (type) {
case "rb":
this._parser = null;//TODO
this._visitor = null;
break;
case "py":
this._parser = null;//TODO
this._visitor = null;
break;
case "c":
this._parser = null;//TODO
this._visitor = null;
break;
case "ob":
this._parser = new OberonParser(console);
this._visitor = new OberonVisitor();
break;
case "java":
this._parser = null;//TODO
this._visitor = null;
break;
}
return (this._ast = this._parser.parse_text(text));
} | 5 |
public QueueSubscriberThread(BlockingQueue<Integer> queue) {
this.queue = queue;
} | 0 |
public TileEncoderImpl(String formatName,
OutputStream output,
TileCodecParameterList param) {
// Cause a IllegalArgumentException to be thrown if formatName, output
// is null
if (formatName == null) {
throw new IllegalArgumentException(
JaiI18N.getString("TileCodecDescriptorImpl0"));
}
if (output == null) {
throw new IllegalArgumentException(
JaiI18N.getString("TileEncoderImpl0"));
}
TileCodecDescriptor tcd =
TileCodecUtils.getTileCodecDescriptor("tileEncoder", formatName);
// If param is null, get the default parameter list.
if (param == null)
param = tcd.getDefaultParameters("tileEncoder");
if (param != null) {
// Check whether the formatName from the param is the same as the
// one supplied to this method.
if (param.getFormatName().equalsIgnoreCase(formatName) == false) {
throw new IllegalArgumentException(
JaiI18N.getString("TileEncoderImpl1"));
}
// Check whether the supplied parameterList supports the
// "tileDecoder" mode.
if (param.isValidForMode("tileEncoder") == false) {
throw new IllegalArgumentException(
JaiI18N.getString("TileEncoderImpl2"));
}
// Check whether the ParameterListDescriptors are the same.
if (param.getParameterListDescriptor().equals(
tcd.getParameterListDescriptor("tileEncoder")) == false)
throw new IllegalArgumentException(JaiI18N.getString("TileCodec0"));
} else {
// If the supplied parameterList is null and the default one is
// null too, then check whether this format supports no parameters
ParameterListDescriptor pld =
tcd.getParameterListDescriptor("tileEncoder");
// If the PLD is not null and says that there are supposed to
// be some parameters (numParameters returns non-zero value)
// throw an IllegalArgumentException
if (pld != null && pld.getNumParameters() != 0) {
throw new IllegalArgumentException(
JaiI18N.getString("TileDecoderImpl6"));
}
}
this.formatName = formatName;
this.outputStream = output;
this.paramList = param;
} | 9 |
public static boolean updateKayttajatunnus(Kayttajatunnus kayttaja) {
Connection con = connect();
try {
con.setAutoCommit(false);
PreparedStatement updateKayttajatunnus = con.prepareStatement("UPDATE kayttajatunnus SET kayttajanimi = ?, salasana = ?, oikeudet = ? WHERE kayttajatunnusID = ?");
updateKayttajatunnus.setString(1, kayttaja.getKayttajanimi());
updateKayttajatunnus.setString(2, kayttaja.getSalasana());
updateKayttajatunnus.setInt(3, kayttaja.getOikeudet());
updateKayttajatunnus.setInt(4, kayttaja.getId());
updateKayttajatunnus.executeUpdate();
if (kayttaja.getOppilas() != null) {
Oppilas oppilas = kayttaja.getOppilas();
PreparedStatement updateOppilas = con.prepareStatement("UPDATE oppilas SET etunimi = ?, sukunimi = ?, ryhma = ? WHERE oppilasID = ?;");
updateOppilas.setString(1, oppilas.getEtunimi());
updateOppilas.setString(2, oppilas.getSukunimi());
updateOppilas.setInt(3, oppilas.getRyhma().getId());
updateOppilas.setInt(4, oppilas.getId());
updateOppilas.executeUpdate();
}
con.commit();
return true;
} catch (SQLException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
try {
con.rollback();
} catch (Exception e) {}
return false;
} finally {
closeConnection(con);
}
} | 3 |
public SoundPoolEntry addSound(String var1, File var2) {
try {
String var3 = var1;
var1 = var1.substring(0, var1.indexOf("."));
if(this.field_1657_b) {
while(Character.isDigit(var1.charAt(var1.length() - 1))) {
var1 = var1.substring(0, var1.length() - 1);
}
}
var1 = var1.replaceAll("/", ".");
if(!this.nameToSoundPoolEntriesMapping.containsKey(var1)) {
this.nameToSoundPoolEntriesMapping.put(var1, new ArrayList());
}
SoundPoolEntry var4 = new SoundPoolEntry(var3, var2.toURI().toURL());
((List)this.nameToSoundPoolEntriesMapping.get(var1)).add(var4);
this.allSoundPoolEntries.add(var4);
++this.numberOfSoundPoolEntries;
return var4;
} catch (MalformedURLException var5) {
var5.printStackTrace();
throw new RuntimeException(var5);
}
} | 4 |
public boolean hasPotentialAvailableSpace(int fileSize) {
if (fileSize <= 0) {
return false;
}
// check if enough space left
if (getAvailableSpace() > fileSize) {
return true;
}
Iterator it = fileList_.iterator();
File file = null;
int deletedFileSize = 0;
// if not enough space, then if want to clear/delete some files
// then check whether it still have space or not
boolean result = false;
while (it.hasNext()) {
file = (File) it.next();
if (!file.isReadOnly()) {
deletedFileSize += file.getSize();
}
if (deletedFileSize > fileSize) {
result = true;
break;
}
}
return result;
} | 5 |
public int calculateScore(DiceManager diceManager, int roundNumber) {
Dice dice1 = diceManager.getFirstDice();
diceManager.nextDice();
Dice dice2 = diceManager.nextDice();
Dice dice3 = diceManager.nextDice();
int score = 0;
nextToPlay = true;
if(dice1.compareTo(dice2) == EQUALS && dice2.compareTo(dice3) == EQUALS && dice1.getActiveFace() == roundNumber)
score = 21;
else if(dice1.compareTo(dice2) == EQUALS && dice2.compareTo(dice3) == EQUALS && dice1.getActiveFace() != roundNumber){
score = 5;
nextToPlay = false;
}
else{
if(dice1.getActiveFace() == roundNumber) {
nextToPlay = false;
score += 1;
}
if(dice2.getActiveFace() == roundNumber) {
nextToPlay = false;
score += 1;
}
if(dice3.getActiveFace() == roundNumber){
nextToPlay = false;
score += 1;
}
}
return score;
} | 9 |
private void mainLoop(String user_name) throws IOException
{
for (;;) {
Command cmd = this._in.readCommand();
char op = cmd.getOperator();
CommandArgsIterator args_it = (CommandArgsIterator) cmd.iterator();
if (op == 'J')
this.joinChan(user_name, args_it);
else if (op == 'Q')
this.quitChan(user_name, args_it);
else if (op == 'M')
this.message(user_name, args_it);
else if (op == 'W')
this.whois(args_it);
else if (op == 'L')
this.listChans(args_it);
else if (op == 'U')
this.listUsers(args_it);
else if (op == 'E')
this.serverExtensions(args_it);
else if (op == 'D')
break;
else
this.syntaxError();
}
} | 9 |
private void horizontalCompactionRight(Digraph<BrandesKoepfNode,Boolean> graph) {
for (BrandesKoepfNode v : graph.vertices()) {
v.sink = v;
v.sink2 = v;
v.shift = Integer.MAX_VALUE;
v.x = Integer.MIN_VALUE; // undefined
}
for (BrandesKoepfNode v : graph.vertices()) {
if (v.root == v) {
placeBlockRight(v);
}
}
for (BrandesKoepfNode v : graph.vertices()) {
if (v.root == v) {
BrandesKoepfNode sink = v.sink;
do {
if (sink.shift < Integer.MAX_VALUE) {
v.x -= sink.shift;
}
sink = sink.sink2;
} while (sink.sink2 != sink);
}
}
for (BrandesKoepfNode v : graph.vertices()) {
v.x = v.root.x;
}
} | 8 |
@SuppressWarnings("unchecked")
public void onAuditEvent(AuditEvent evt){
log.info("Audit Event Arrived:" + evt.getEventId() + ":" );
String ruleID = "";
String severity = "";
String tags = "";
String source = "";
String line = "";
String file = "";
String msgStr = "";
JSONObject json = new JSONObject();
json.put("object", "AuditEvent");
json.put("id", evt.getEventId());
try{
int count = 0;
for(AuditEventMessage msg:evt.getEventMessages()){
msgStr += msg.getRuleMsg();
source += msg.getTxId();
ruleID += msg.getRuleId();
line += msg.getLine();
file += msg.getFile();
severity += msg.getSeverity();
for(String str: msg.getRuleTags()){
tags += str + " | ";
}
count ++;
if(evt.getEventMessages().length-1== count){
msgStr += " | ";
source += " | ";
ruleID += " | ";
line += " | ";
file += " | ";
severity += " | ";
}
}
} catch(Exception e){
log.info("Parsing Message Error : " + e.getMessage());
}
String date =new SimpleDateFormat("dd.MM.yyyy | HH:mm:ss").format(evt.getDate());
json.put("date", date);
json.put("sensor", evt.get(AuditEvent.SENSOR));
json.put("sensorID", evt.get(AuditEvent.SENSOR_ID));
json.put("sensorName", evt.get(AuditEvent.SENSOR_NAME));
json.put("sensorAddr", evt.get(AuditEvent.SENSOR_ADDR));
json.put("sensorType", evt.get(AuditEvent.SENSOR_TYPE));
json.put("site_id", evt.get(AuditEvent.SITE_ID));
json.put("site_name", evt.get(AuditEvent.SITE_NAME));
json.put("webAppID", evt.get(ModSecurity.WEBAPPID));
json.put("serverName", "" + evt.get(ModSecurity.SERVER_NAME));
json.put("serverAddr", "" + evt.get(ModSecurity.SERVER_ADDR));
json.put("serverPort", "" + evt.get(ModSecurity.SERVER_PORT));
json.put("remoteUser", evt.get(ModSecurity.REMOTE_USER ));
json.put("remoteHost", evt.get(ModSecurity.REMOTE_HOST ));
json.put("remoteAddr", evt.get(ModSecurity.REMOTE_ADDR ));
json.put("remotePort", evt.get(ModSecurity.REMOTE_PORT ));
json.put("eventType", evt.getAuditEventType().toString());
json.put("type", evt.getType().toString());
json.put("recieved_at", evt.get(AuditEvent.RECEIVED_AT));
json.put("tx", evt.get(ModSecurity.TX));
json.put("txID", evt.get(ModSecurity.TX_ID));
json.put("ruleID",ruleID);
json.put("file",file);
json.put("line",line);
json.put("source",source);
json.put("tags",tags);
boolean sevCheck = true;
for(Severity sev: Severity.values()){
if(sev.getValue().equals(severity.trim())){
json.put("severity",sev.toString());
sevCheck = false;
}
}
if(sevCheck){
json.put("severity","None");
}
json.put("message",msgStr);
log.info("Sending Message : " + json.toJSONString());
ConnectorService.getMSLogProducer().send(json.toJSONString());
} | 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(KeyBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KeyBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KeyBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KeyBoard.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new KeyBoard().setVisible(true);
}
});
} | 6 |
public void setGaussianKernelRadius(float gaussianKernelRadius) {
if (gaussianKernelRadius < 0.1f)
throw new IllegalArgumentException();
this.gaussianKernelRadius = gaussianKernelRadius;
} | 1 |
@Override
public void fire() {
if(timeSinceLastShot >= timeBetweenShots) {
GameActor a = Application.get().getLogic().getActor(actor);
//WeaponsComponent wc1 = (WeaponsComponent)a.getComponent("WeaponsComponent");
PhysicsComponent pc1 = (PhysicsComponent)a.getComponent("PhysicsComponent");
StatusComponent sc1 = (StatusComponent)a.getComponent("StatusComponent");
GameActor bul = Application.get().getLogic().createActor(bullet);
float weaponDist = pc1.getHeight() / 2 + 10; // barrel of the gun is in front of the weapon
// calculate correct spot with angle of the actor
float bulletY = pc1.getY() - weaponDist * (float)Math.sin(pc1.getAngleRad());
float bulletX = pc1.getX() - weaponDist * (float)Math.cos(pc1.getAngleRad());
bul.move(bulletX, bulletY);
PhysicsComponent pc2 = (PhysicsComponent)bul.getComponent("PhysicsComponent");
StatusComponent sc2 = (StatusComponent)bul.getComponent("StatusComponent");
// the projectile must know who shot it to prevent friendly fire
sc2.setAllegiance(sc1.getAllegiance());
pc2.setDamage(damage);
pc2.setAngleRad(pc1.getAngleRad());
pc2.applyAcceleration(1.0f);
Application.get().getEventManager().queueEvent(new WeaponFiredEvent(actor));
timeSinceLastShot = 0;
}
} | 1 |
private ArrayList<Integer> generateActions(int[][] state) {
ArrayList<Integer> result = new ArrayList<Integer>();
int middle = x/2;
//TODO choose random when x is even
if (state[middle][0] == 0) {
result.add(middle);
}
for (int i=1; i <= x/2; i++){
if(middle + i < x) {
if (state[middle + i][0] == 0) {
result.add(middle + i);
}
}
if(middle - i > -1) {
if (state[middle - i][0] == 0) {
result.add(middle - i);
}
}
}
return result;
} | 6 |
@Override
public void documentAdded(DocumentRepositoryEvent e) {} | 0 |
public static void main(String[] args) {
/** Variablen */
FileInputStream fstream;
String line;
Guitar guitar;
Scanner sc;
final int takt = 22050;
// keys to pluck a string
char[] pluckKeys = { 'm', 'k', 'o', ',', 'l', 'p' };
// keys to press a fret down, only the lower strings can be accessed
char[][] changeFretKeys = { { '<', 'y', 'x', 'c', 'v', 'b' },
{ 'a', 's', 'd', 'f', 'g', 'h' },
{ 'q', 'w', 'e', 'r', 't', 'z' },
{ '2', '3', '4', '5', '6', '7' },
//{ '>', 'Y', 'X', 'C', 'V', 'B' },
//{ 'A', 'S', 'D', 'F', 'G', 'H' },
//{ 'Q', 'W', 'E', 'R', 'T', 'Z' }
};
// Gitarre erzeugen
guitar = new Guitar();
try {
sc = new Scanner(new FileReader(args[0]));
// Buchstaben aus der Datei stueck fuer stueck ab arbeiten
while(sc.hasNextLine()) {
line = sc.nextLine();
for(char key:line.toCharArray()) {
// or change the frequency of a string
// Saite anzupfen
for (int i = 0; i < pluckKeys.length; i++) {
if (key == pluckKeys[i]) {
guitar.pluckString(i);
}
}
for (int i = 0; i < changeFretKeys.length; i++) {
for (int j = 0; j < changeFretKeys[i].length; j++) {
if (key == changeFretKeys[i][j]) {
guitar.pressFretDown(i, j);
}
}
}
for(int i=0; i<takt; i++) { // Simulation um i Takte weiter fueren
guitar.tic();
StdAudio.play(guitar.sample()); // Ton ausgeben
}
}
}
}
catch(Exception ex) {
System.err.println("Fehler beim einlesen der Datei: " + ex.getMessage());
System.exit(1);
}
System.exit(0);
} | 9 |
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} | 8 |
public float getPrice() {
return price;
} | 0 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof UnitPlayer))
return false;
UnitPlayer other = (UnitPlayer) obj;
if (curLocation == null) {
if (other.curLocation != null)
return false;
} else if (!curLocation.equals(other.curLocation))
return false;
if (inventory == null) {
if (other.inventory != null)
return false;
} else if (!inventory.equals(other.inventory))
return false;
return true;
} | 9 |
public ProcessedCell(String name, ImageProcessor origImg, ImageProcessor segmented, int num,
BoundaryBox bb, int area, double mean, Point centroid){
imgName = name;
this.id = num;
this.bb = bb;
this.area = area;
this.mean = mean;
this.centroid = centroid;
origImg.setRoi(this.bb.getX(), this.bb.getY(), this.bb.getWidth(), this.bb.getHeight());
this.origImg = origImg.crop();
origImg.resetRoi();
this.points = new HashSet<Point>();
for(int i = bb.getX(); i < bb.getX() + bb.getWidth(); i++){
for(int j = bb.getY(); j < bb.getY() + bb.getHeight(); j++){
if(segmented.get(i,j) == id){
this.points.add(new Point(i,j));
}
// this.points.add(new Point(i,j));
}
}
} | 3 |
public static void printBoard(int table[][]){
int rows=table.length;
int cols=table[0].length;
msg.print(" ");
for(int i=0;i<cols;i++){
if(i==0){
msg.print("0 ");
}
else{
if(i<10){
msg.print(gen[0].charAt(i-1)+" ");
}
else{
msg.print(gen[0].charAt(i-1)+" ");
}
}
}
msg.print("\n");
for(int i=0;i<rows;i++){
if(i==0){
msg.print("0: ");
}
else{
msg.print(gene.charAt(i-1)+": ");
}
for(int j=0;j<cols;j++){
if(table[i][j]>=0){
msg.print(" ");
}
msg.print(" "+table[i][j]);
if(table[i][j]<10&&table[i][j]>-10){
msg.print(" ");
}
}
msg.println("");
msg.println();
}
} | 9 |
public Route(final String name, final int local_port,
final String remote_address,final File log_dir,
final Properties[] filterConfigs) throws IOException {
this.name = name;
if (remote_address.indexOf(":") == -1) {
throw new Error("port missing in remote address, expected <hostname>:<port>: " + remote_address);
}
this.remote_hostname= remote_address.substring(0, remote_address.indexOf(":"));
this.remote_port= Integer.parseInt(remote_address.substring(remote_address.indexOf(":")+1, remote_address.length()));
this.local_port = local_port;
this.filterConfigs = filterConfigs;
this.log_dir = log_dir;
logger = new ConnectionLoggerImpl(log_dir, name, 0);
logger.enable();
} | 1 |
public void checkBanks() {
try {
File dir = new File("characters");
if(dir.exists()) {
String read;
File files[] = dir.listFiles();
for (int j = 0; j < files.length; j++) {
File loaded = files[j];
if (loaded.getName().endsWith(".txt")) {
Scanner s = new Scanner (loaded);
int cash = 0;
while (s.hasNextLine()) {
read = s.nextLine();
if (read.startsWith("character-item") || read.startsWith("character-bank")) {
String[] temp = read.split("\t");
int token1 = Integer.parseInt(temp[1]);
int token2 = Integer.parseInt(temp[2]);
if (token1 == 996) {
cash += token2;
if (cash > 12500000) {
System.out.println("name: " + loaded.getName());
}
}
}
}
}
}
} else {
System.out.println("FAIL");
}
} catch (Exception e) {
e.printStackTrace();
}
} | 9 |
private static List<String> canonize(String aPath)
throws CommandException
{
final String[] lPieces = aPath.split("/");
final List<String> lResult= new ArrayList<String>(lPieces.length);
for(String lPiece : lPieces)
{
if(".".equals(lPiece))
// Just skip this.
continue;
else if("..".equals(lPiece))
{
// Delete the last part and go back to the previous part.
int lResultSize = lResult.size();
if(lResultSize > 0) lResult.remove(lResultSize - 1);
}
else
{
// Note: Could be done more efficiently using a custom parser.
final Matcher m = PAT_FIELDNAME_BIS.matcher(lPiece);
if(!m.matches())
throw new CommandException(String.format("Illegal path '%s'.", lPiece));
// Fetch the prefix.
final String lName = m.group(1);
if(lName != null) lResult.add(lName);
// Get the indices.
int lStart = m.end(1)<0?0:m.end(1);
final String[] lIndices = lPiece.substring(lStart).split("\\[");
// Skip the first empty string.
for(int i = 1; i < lIndices.length; i++)
{
String lIdx = lIndices[i];
int lClosing = lIdx.lastIndexOf(']');
if(lClosing > 0) lIdx = lIdx.substring(0, lClosing).trim();
lResult.add(lIdx);
}
}
}
return lResult;
} | 9 |
public static int runToAddressL(int limit, Gameboy gbL, Gameboy gbR, int... addresses) {
if (!gbL.onFrameBoundaries) {
int add = dualStepUntilL(gbL, gbR, 0, 0, addresses);
if (add != 0)
return add;
}
int steps = 0;
while (steps < limit) {
int add = dualStepUntilL(gbL, gbR, 0, 0, addresses);
if (add != 0)
return add;
steps++;
}
return 0;
} | 4 |
@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
} | 1 |
public void tryRotate(Block[][] tank) {
int nextRotation = currentRotation < getRotations().length - 1 ? currentRotation + 1 : 0;
Block[][] nextLayout = getRotations()[nextRotation].getLayout();
for (int x = 0; x < nextLayout.length; x++) {
for (int y = 0; y < nextLayout[0].length; y++) {
if (nextLayout[x][y] != null) {
int tankXCoord = coord.getX() + x;
int tankYCoord = coord.getY() + y;
if (tankXCoord >= Model.TANK_WIDTH || tankYCoord >= Model.TANK_HEIGHT - 1 || tank[tankXCoord][tankYCoord] != null) {
return; // Don't rotate as this would lead to escaping the tank or overlapping existings blocks
}
}
}
}
this.currentRotation = nextRotation;
this.layout = getRotations()[currentRotation].getLayout();
this.height = getRotations()[currentRotation].getHeight();
this.width = getRotations()[currentRotation].getWidth();
} | 7 |
public void sendReply_cgibin_latency_cgi(MyHTTPServer socket, List<HTTPRequestData> getData, String cookie) throws Exception
{
try
{
int width = 920;
HTTPRequestData widthData = MyHTTPServer.findRecord(getData, "width");
if (widthData != null && widthData.getData() != null)
width = Integer.valueOf(widthData.getData());
int height = 150;
HTTPRequestData heightData = MyHTTPServer.findRecord(getData, "height");
if (heightData != null && heightData.getData() != null)
height = Integer.valueOf(heightData.getData());
boolean withMetaData = true;
HTTPRequestData withMetaDataData = MyHTTPServer.findRecord(getData, "metadata");
if (withMetaDataData != null && withMetaDataData.getData() != null)
withMetaData = URLDecoder.decode(withMetaDataData.getData(), defaultCharset).equalsIgnoreCase("true");
String header;
if (cookie == null)
header = "HTTP/1.0 200 OK\r\nConnection: close\r\nContent-Type: image/png\r\n\r\n";
else
header = "HTTP/1.0 200 OK\r\nSet-Cookie: " + cookie + "\r\nConnection: close\r\nContent-Type: image/png\r\n\r\n";
socket.getOutputStream().write(header.getBytes());
BufferedImage sparkLine = coffeeSaint.getLatencyGraph(width, height, withMetaData);
ImageIO.write(sparkLine, "png", socket.getOutputStream());
}
catch(Exception e)
{
// really don't care if the transmit failed; browser
// probably closed session
// don't care if we could display the image or not
}
finally
{
socket.close();
}
} | 8 |
static int countLinkageEdges(List<Node> positiveNodeList,
List<Node> negativeNodeList,
int[] positivePartition,
int[] negativePartition) {
int k = 0;
for (int i : positivePartition) {
k = Math.max(k, i);
}
++k;
List<Node>[] positiveMap = new List[k];
List<Node>[] negativeMap = new List[k];
int i = 0;
for (int index : positivePartition) {
if (positiveMap[index] == null) {
positiveMap[index] =
new ArrayList<Node>(positivePartition.length);
}
positiveMap[index].add(positiveNodeList.get(i++));
}
i = 0;
for (int index : negativePartition) {
if (negativeMap[index] == null) {
negativeMap[index] =
new ArrayList<Node>(negativePartition.length);
}
negativeMap[index].add(negativeNodeList.get(i++));
}
Arrays.sort(positiveMap, nodeListEquityComparator);
Arrays.sort(negativeMap, nodeListEquityComparator);
for (i = 0; i < k; ++i) {
if (sumNodeEquities(positiveMap[i])
!= sumNodeEquities(negativeMap[i])) {
return Integer.MAX_VALUE;
}
}
return positiveNodeList.size() + negativeNodeList.size() - k;
} | 7 |
public void getEnabled(boolean isEnabled) {
if (isEnabled == true) {
btn_editor.setEnabled(true);
btn_add.setEnabled(true);
btn_remove.setEnabled(true);
btn_save.setEnabled(true);
}
} | 1 |
public boolean canRobotMove(Direction direction) {
boolean result = true;
/* Each case checks for 2 things: if the robot will move outside of the bounds
* and if there is a rock in the robot's path.
*/
switch(direction) {
case UP:
result &= robot.getLocation().y > 0;
break;
case DOWN:
result &= robot.getLocation().y < currentPlanet.getBOTTOM();
break;
case LEFT:
result &= robot.getLocation().x > 0;
break;
case RIGHT:
result &= robot.getLocation().x < Launcher.getFrameBounds().width - UNIT;
break;
}
result &= !isRockNextToRobot(direction);
result &= robot.getFuelTank().getFuelLevel() > 0;
return result;
} | 4 |
public void addFromFile(String fichier)
{
try{
Scanner input= new Scanner (new File(fichier));
int numberOfEntries= Integer.parseInt(input.next());
System.out.println(numberOfEntries);
NoeudRN found= null;
while (input.hasNext() && numberOfEntries >= 0) {
int a= Integer.parseInt(input.next()), b= Integer.parseInt(input.next());
found= rechercheNoeud(a);
if(found == sentinelle){
System.out.println("Etudiant " + a + " non présent dans le système, a été ajouté.");
insert(a, b);
}
else
addPoints(a, b);
numberOfEntries--;
}
input.close();
}
catch (IOException e){
System.out.println("Erreur : " + e);
}
} | 4 |
@Override
public void trigger(Value v) {
super.trigger(v);
if (parent_ != null && parent_.getMode() == EditorMode.DEBUG) {
for (OVLine l : lines_) {
if (v.getType() == ValueType.VOID
|| v.getType() == ValueType.NONE) {
l.debugDisplay("");
} else {
l.debugDisplay(v.getString());
}
}
}
} | 5 |
public ComputStdMethodLong(long []v){
if (null == v || 0 == v.length){
mean = median = stddev = 0;
min = max = 0;
}else if (1 == v.length){
mean = median = stddev = v[0];
min = max = v[0];
}else{
long sum = v[0],sqSum=0;
min = v[0];
max = v[0];
for (int i=1;i<v.length;i++) {
//Minimum
if (0 == min || v[i] < min)
min = v[i];
//Maximum
if (v[i] > max)
max = v[i];
sum += v[i];
sqSum += (v[i]-v[i-1]) * (v[i]-v[i-1]);
}
mean = sum / (double) v.length;
stddev = Math.sqrt(sqSum/(double)(v.length));
Arrays.sort(v);
if (0 == (v.length % 2))
median = v[(v.length/2) -1];
else{
int mid = (v.length/2) - 1;
median = (v[mid] + v[mid+1])/2;
}
}
} | 8 |
public Ast.AstPredicate parse_restrrPredicate1(Ast.AstPredicate inode, SpecObject specObject, String property)
{
int at = m_current;
if (!ok())
{
return null;
}
if (next(TozeTokenizer.TOKEN_LAND))
{
Ast.AstAndP anode = m_ast.new AstAndP(specObject, property);
anode.m_predicateL = inode;
anode.m_predicateR = parse_rrPredicate1(specObject, property);
if (ok())
{
return anode;
}
}
reset(at);
if (next(TozeTokenizer.TOKEN_LOR))
{
Ast.AstOrP onode = m_ast.new AstOrP(specObject, property);
onode.m_predicateL = inode;
onode.m_predicateR = parse_rrPredicate1(specObject, property);
if (ok())
{
return onode;
}
}
reset(at);
if (next(TozeTokenizer.TOKEN_IMP))
{
Ast.AstImpliesP onode = m_ast.new AstImpliesP(specObject, property);
onode.m_predicateL = inode;
onode.m_predicateR = parse_rrPredicate1(specObject, property);
if (ok())
{
return onode;
}
}
reset(at);
if (next(TozeTokenizer.TOKEN_IFF))
{
Ast.AstBiimpliesP onode = m_ast.new AstBiimpliesP(specObject, property);
onode.m_predicateL = inode;
onode.m_predicateR = parse_rrPredicate1(specObject, property);
if (ok())
{
return onode;
}
}
reset(at);
return inode;
} | 9 |
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(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame1().setVisible(true);
}
});
} | 6 |
public void setYahooAuctionModel(YahooAuctionModel yahooAuctionModel) {
this.yahooAuctionModel = yahooAuctionModel;
} | 0 |
public static String sortByValue(Map<String, ArtistInfo> map) {
List<Map.Entry<String, ArtistInfo>> list = new LinkedList<Map.Entry<String, ArtistInfo>>(
map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, ArtistInfo>>() {
public int compare(Map.Entry<String, ArtistInfo> o1,
Map.Entry<String, ArtistInfo> o2) {
// First, it will evaluate the number of musics of the both
// artists
int nrM = o2.getValue().getNrMusics()
- o1.getValue().getNrMusics();
if (nrM > 0) {
return 1;
} else if (nrM < 0) {
return -1;
} else {
// If this not enough, it will evaluate the longest duration
int sizeP = o2.getValue().getLongestDuration()
- o1.getValue().getLongestDuration();
if (sizeP > 0) {
return 1;
} else if (sizeP < 0) {
return -1;
} else {
// And finally, as last resource, it will compare in
// lexicographic terms the lower artist
return o1.getKey().compareToIgnoreCase(o2.getKey());
}
}
}
});
/*
* Map<String, ArtistInfo> result = new LinkedHashMap<String,
* ArtistInfo>();
*
* for (Map.Entry<String, ArtistInfo> entry : list) { result.put(
* entry.getKey(), entry.getValue() ); }
*/
return list.get(0).getKey();
} | 4 |
public void exec()
{
if (WindowStack.getLastInstance() != null) {
setParent(WindowStack.getLastInstance());
}
move(400, 300);
show();
wait = true;
while (wait) {
QApplication.processEvents();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | 3 |
private boolean define(VirtualMachine virtualMachine) throws Exception {
String memory = virtualMachine
.getProperty(VirtualMachineConstants.MEMORY);
String diskType = virtualMachine
.getProperty(VirtualMachineConstants.DISK_TYPE);
String networkType = virtualMachine
.getProperty(VirtualMachineConstants.NETWORK_TYPE);
String networkAdapterName = virtualMachine
.getProperty(VirtualMachineConstants.NETWORK_ADAPTER_NAME);
String mac = virtualMachine.getProperty(VirtualMachineConstants.MAC);
String bridgedInterface = virtualMachine.getProperty(
VirtualMachineConstants.BRIDGED_INTERFACE);
String paeEnabled = virtualMachine.getProperty(VirtualMachineConstants.PAE_ENABLED);
boolean pae = false;
if (paeEnabled != null) {
pae = Boolean.valueOf(paeEnabled);
}
IMachine machine = this.vbox.findMachine(virtualMachine.getName());
ISession session = getSession(virtualMachine);
machine.lockMachine(session, LockType.Shared);
try {
IMachine mutable = session.getMachine();
mutable.setMemorySize(Long.valueOf(memory));
INetworkAdapter networkAdapter = mutable.getNetworkAdapter(0L);
networkAdapter.setAttachmentType(getNetworkAttachmentType(networkType));
if (networkAdapterName != null) {
networkAdapter.setHostOnlyInterface(networkAdapterName);
}
if (mac != null) {
networkAdapter.setMACAddress(mac);
}
if (bridgedInterface != null) {
networkAdapter.setBridgedInterface(bridgedInterface);
}
try {
mutable.addStorageController(DISK_CONTROLLER_NAME,
getStorageBus(diskType));
} catch (VBoxException e) {
// Do nothing for the controller already exists
}
mutable.setCPUProperty(CPUPropertyType.PAE, pae);
mutable.saveSettings();
} catch (Exception e) {
throw e;
} finally {
unlock(session);
}
return true;
} | 6 |
public static void main(String[] args) {
/*
System.setProperty("sun.java2d.opengl", "true");
System.setProperty("sun.java2d.translaccel", "true");
System.setProperty("sun.java2d.ddforcevram", "true");
*/
Wuuii wuuii = new Wuuii();
wuuii.init();
//TcpBroadcast tcp = new TcpBroadcast();
try {
wuuii.ServerTransmission();
} catch (IOException e) { }
} | 1 |
boolean checkSyntax(){
boolean result = true;
//save the current line to set it to this point at the end again
int initialCurrentLine = this.currentLine;
this.currentLine = 0;
String output = "";
String lastOutput = "";
if(this.lines.length > 0){
lastOutput = this.computeLine();
output = lastOutput;
}
while(this.currentLine < this.lines.length){
lastOutput = this.computeLine();
output = output.concat(System.getProperty("line.separator") + lastOutput);
this.currentLine++;
//if there are errors remember that, change the result and save the error message
if(lastOutput.equals("Error. End of program reached, but HALT is missing.") || lastOutput.equals("No possiblity to compute further. Is the syntax correct?")){
result = false;
if(this.syntaxErrors != ""){
this.syntaxErrors = this.syntaxErrors.concat(System.getProperty("line.separator") + "Line " + this.currentLine + ": " + lastOutput);
}
else{
this.syntaxErrors = this.syntaxErrors.concat("Line " + this.currentLine + ": " + lastOutput);
}
}
}
this.currentLine = initialCurrentLine;
return result;
} | 5 |
public JFreeChart MakeChart() {
DefaultPieDataset chartDataSet = new DefaultPieDataset();
Object[] column1Data = super.getDataset().GetColumnData(super.getAttribute1());
Object[] column2Data = super.getDataset().GetColumnData(super.getAttribute2());
boolean addDataset = true;
String errors = "";
int errorCounter = 0;
for (int i=0; i<super.getDataset().GetNoOfEntrys();i++) {
Comparable<Object> nextValue1;
nextValue1 = (Comparable<Object>) column1Data[i];
Double nextValue2 = null;
boolean addThis = true;
try {
int intNextValue2 = Integer.parseInt(column2Data[i].toString());
nextValue2 = (Double) ((double) intNextValue2);
} catch (NumberFormatException nfe) {
try {
double doubleNextValue2 = Double.parseDouble(column2Data[i].toString());
nextValue2 = (Double) doubleNextValue2;
} catch (NumberFormatException nfe2) {
String strNextValue2 = column2Data[i].toString();
if (strNextValue2.equalsIgnoreCase("True")) {
nextValue2 = TRUE;
} else if (strNextValue2.equalsIgnoreCase("False")) {
nextValue2 = FALSE;
} else {
addThis = false;
}
}
} catch (Exception e) {
addThis = false;
}
if (addThis == true) {
chartDataSet.setValue( nextValue1, nextValue2 );
} else {
addDataset = false;
if (errorCounter < MAX_ERROR_LENGTH) {
errors = errors + "\n"
+ column2Data[i].toString();
errorCounter++;
}
}
}
if (addDataset == false) {
chartDataSet = new DefaultPieDataset(); //Reset
JOptionPane.showMessageDialog(null,
"Your selected y-axis has data in the wrong format" + "\n" +
"The following data needs to be a number in order to be" +
" represented."
+ errors);
}
JFreeChart chart = ChartFactory.createPieChart(
super.getHeader(),
chartDataSet,
true, //include legend
true,
false );
return chart;
} | 9 |
public final INIToken read() throws IOException {
while (true) {
final int symbol = this._reader_.read();
switch (symbol) {
case -1:
return null;
case '[':
final String section = this._readSection_();
return INIToken.fromSection(section);
case ';':
final String comment = this._readComment_();
return INIToken.fromComment(comment);
default:
final String key = this._readKey_(symbol);
final String value = this._readValue_();
return INIToken.fromProperty(key, value);
case '\r':
case '\n': // skip
}
}
} | 6 |
public static void noGui(Settings settings, boolean showNotifications) {
Graph graf = new Graph();
try {
graf.loadFromFile(settings.graphFileName);
} catch (FileNotFoundException ex) {
System.err.println("Błąd pliku grafu!");
System.exit(-1);
}
GraphColoringProblem gcp = new GraphColoringProblem(graf, settings.colors, settings.isDoubleSlicedGenom, settings.isRandomCrossPosition);
final GeneticAlgorithm<Integer> ea = new GeneticAlgorithm<>(gcp, settings.populationSize, settings.parentsSize, settings.crossProbability, settings.mutationProbability, settings.maxIterations);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
saveResult(ea.bestSolution);
}
}));
if (showNotifications) {
new Thread(new Runnable() {
@Override
public void run() {
ea.run();
}
}).start();
do {
try {
Thread.sleep(settings.refreshNotificationTime);
System.out.printf("Iteration: %d Fval: %.6f\n", ea.iterations, ea.bestSolutionCost);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} while (ea.isRunning());
} else {
ea.run();
}
System.out.println("Najlepszy wynik: " + ea.bestSolutionCost + " Liczba iteracji: " + ea.iterations);
Plot2DPanel p = new Plot2DPanel();
GUI.plot(ea.max, ea.avg, ea.min, p, settings.maxPlotVars);
JFrame window = new JFrame("Algorytm Genetyczny");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(p);
window.setSize(600, 600);
window.setVisible(true);
} | 4 |
private static void collectItemData(String itemPath, String split_Sign) throws IOException {
File file = new File(itemPath);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
boolean flag = true;
int tmp = 0 , count = 0;
int[] itemIndex = new int[DataInfo.num_of_item];
int[] item_record = new int[DataInfo.trainNumber];
for(int i = 0; i < DataInfo.num_of_item; i++)
itemIndex[i] = 0;
while(buffRead.ready()) {
String line = buffRead.readLine();
String[] parts = line.split(split_Sign);
int id1 = Integer.parseInt(parts[0]);
int id2 = Integer.parseInt(parts[1]);
int rate = (int)Double.parseDouble(parts[2]);
rate = id2 * 10 + rate;
item_record[count] = rate;
if(flag)
tmp = id1;
else {
if(tmp != id1) {
itemIndex[tmp] = count;
tmp = id1;
}
}
count++;
flag = false;
}
itemIndex[tmp] = count;
buffRead.close();
for(int i = 1; i < DataInfo.num_of_item; i++) {
if(itemIndex[i] < itemIndex[i - 1])
itemIndex[i] = itemIndex[i - 1];
}
for (int i = 0; i != DataInfo.num_of_item; i++) {
int first, last;
if(i == 0)
first = 0;
else {
first = itemIndex[i - 1];
}
last = itemIndex[i];
int number = last - first;
DataInfo.itemlist[i] = new int[number];
int p = 0;
for(int j = first; j < last; j++) {
DataInfo.itemlist[i][p] = item_record[j];
p++;
}
}
} | 9 |
public static ScatterLocation getLocation(Player p) {
for (ScatterLocation sl : locations) {
if (sl.p == p || ScatterManager.score.getPlayerTeam(p) == sl.t) {
return sl;
}
}
return null;
} | 3 |
public String toJSON()
{
Map<String,Object> parameters = new LinkedHashMap<String,Object>();
parameters.put("grant_type",getGrantType());
if (GoCoin.hasValue(getCode()))
{
parameters.put("code",getCode());
}
if (GoCoin.hasValue(getClientId()))
{
parameters.put("client_id",getClientId());
}
if (GoCoin.hasValue(getClientSecret()))
{
parameters.put("client_secret",getClientSecret());
}
if (GoCoin.hasValue(getRedirectUri()))
{
parameters.put("redirect_uri",getRedirectUri());
}
return GoCoin.toJSON(parameters);
} | 4 |
public final TMState createTMStateWithID(Point p, int i){
TMState state = new TMState(i, p, this);
addState(state);
return state;
} | 0 |
public void printList() {
Occurrence temp = head;
while (head != null) {
head.printOcc();
head = head.next;
}
head = temp;
} | 1 |
protected void cancelPurchaseButtonClicked() {
log.info("Purchase cancelled");
try {
domainController.cancelCurrentPurchase();
endSale();
model.getCurrentPurchaseTableModel().clear();
} catch (VerificationFailedException e1) {
log.error(e1.getMessage());
}
} | 1 |
private String getCommand()
{
String command = "";
if (historyIndex>=0 && historyIndex < history.size())
{
command = history.get(historyIndex);
return command;
}
// Get last command from the text area
command = textArea.getText();
int length = command.length();
if (length< lastCommandOffset)
{
command = "";
}
else
{
command = command.substring(lastCommandOffset);
}
lastCommandOffset = length;
command.trim();
return command;
} | 3 |
public void WorkingElevatorEntHist() {
if(WorkingElevator_lastState == RiJNonState)
{
EmergencyStopped_entDef();
}
else
{
WorkingElevator_subState = WorkingElevator_lastState;
switch (WorkingElevator_subState) {
case EmergencyStopped:
{
EmergencyStopped_enter();
}
break;
case EmergencyMoving:
{
EmergencyMoving_enter();
}
break;
case EmergencyBaseLevel:
{
EmergencyBaseLevel_enter();
}
break;
case Stopped:
{
Stopped_enter();
}
break;
case waitingForRequest:
{
waitingForRequest_enter();
}
break;
case Finished:
{
Finished_enter();
}
break;
case Moving:
{
Moving_enter();
}
break;
default:
break;
}
}
} | 8 |
public User getProfileUser(String email)
{
initConnection();
//Check password matches for given email
String preparedString = null;
PreparedStatement preparedQuery = null;
try
{
//Prepare Statement
preparedString = "SELECT email, firstname, lastname FROM users WHERE email = ?;";
preparedQuery = (PreparedStatement) connection.prepareStatement(preparedString);
preparedQuery.setString(1, email);
//Execute Statement
ResultSet resultSet = preparedQuery.executeQuery();
//TODO: Remove debug
System.out.println("Get profile user with [" + preparedQuery.toString() + "] ");
User profileUser = null;
while (resultSet.next())
{
//Package into User bean
profileUser = new User();
profileUser.setEmail(email);
profileUser.setFirstName(resultSet.getString("firstname"));
profileUser.setLastName(resultSet.getString("lastname"));
}
return profileUser;
}
catch(Exception ex)
{
System.out.println("Problem executing SQL Query [" + preparedQuery.toString() + "] in UserService.java");
ex.printStackTrace();
}
finally
{
try
{
//Finally close stuff to return connection to pool for reuse
preparedQuery.close();
connection.close();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
return null;
} | 3 |
public boolean createIndex(String tableName, int atributeIdx, String attributeName) {
for(Record rec: indexesTable) {
if(!tableName.equals((String) rec.getAttributes().get(TABLE_NAME))) {
continue;
}
Integer atrIdx = (Integer) rec.getAttributes().get(ATR_IDX);
if(atrIdx == atributeIdx) {
// Index already exists
return false;
}
}
try {
Table table = loadTable(tableName);
int indexFirstPage = bufferManager.getFreePage();
Object[] indexRecord = {tableName, atributeIdx, indexFirstPage};
indexesTable.insertRecord(indexRecord);
BxTree index = new BxTree(bufferManager, indexFirstPage);
SecondLevelId atrId = new SecondLevelId(tableName, attributeName);
for(Record rec: table) {
Integer val = (Integer)rec.getAttributes().get(atrId);
index.insert(val, rec.getRecordId());
}
tableCache.remove(tableName);
return true;
} catch (UnsupportedEncodingException e) {
// Cannot be
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
} | 6 |
public String GetImage()
{
if (bufpos >= tokenBegin)
return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
else
return new String(buffer, tokenBegin, bufsize - tokenBegin) +
new String(buffer, 0, bufpos + 1);
} | 1 |
@SuppressWarnings("deprecation")
public Client(String playerName, String url, int port) throws RemoteException {
UnicastRemoteObject.exportObject(this, 0);
this.players = new ConcurrentHashMap<>();
this.playerName = playerName;
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
// It *should* be safe to initialize the display at an
// unknow point in the future. As it is an eventQUEUE,
// and I queue all interactions
// with display, I see no Problem.
Client.this.display = new Display();
Client.this.display.setVisible(true);
Client.this.display.client = Client.this;
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
this.server = (IGameServer) Naming.lookup("rmi://" + url + ":" + port + "/" + "Server");
this.server.login(playerName, this);
Object[][] players = this.server.getPlayers();
for (Object[] objects : players) {
if (objects[0] instanceof String && objects[1] instanceof Integer) {
this.players.put((String) objects[0], (Integer) objects[1]);
} else {
throw new IllegalArgumentException("Received invalid connected player, received entry was: Player=" + objects[0] + ", Score=" + objects[1]);
}
}
} catch (Exception e) {
System.out.println("Client failed, caught exception " + e.getMessage());
e.printStackTrace();
}
} | 6 |
public JTable createBookTable() {
// Datenbankverbindung
BookDB myBookDB = new BookDB();
// Bei der erstmaligen Initialisierung des Fensters gibt es noch keine
// Darstellungsprobleme mit der Tabelle. Es werden alle Datensätze
// angezeigt
if (getSearchText().getText().matches("Bitte Suchbegriff eingeben")) {
// alle Datensätze werden angezeigt
bookTable = new JTable(new BookTable(myBookDB.displayAll()));
} else {
// Damit bei Eingabe eines Suchbegriffes die Tabelle neu aufgebaut
// wird, wird sie zunächst einmal aus dem WestPanel entfernt, danach
// wird nach dem entsprechenden Suchbegriff gesucht und am Ende
// werden die Suchergebnisse in einer neu erstellten Tabelle
// angezeigt
this.getContentPane().remove(westPanel);
// Einlesen des Suchkriteriums (Buchtitel, Autor, Kategorie, ISBN)
String searchKey = String.valueOf(this.getSearchCombo()
.getSelectedItem());
bookTable = new JTable(new BookTable(myBookDB.findBook(searchKey,
getSearchText().getText())));
}
// WestPanel wird aufgebaut
this.createteWestTable();
return bookTable;
} | 1 |
public void readString() throws ParseException {
StringBuffer val = new StringBuffer();
while (column < line.length()) {
char c = line.charAt(column++);
if (c == '"') {
value = val.toString();
return;
}
if (c == '\\') {
c = line.charAt(column++);
switch (c) {
case 'n':
val.append('\n');
break;
case 't':
val.append('\t');
break;
case 'r':
val.append('\r');
break;
case 'u':
if (column + 4 <= line.length()) {
try {
char uni = (char) Integer.parseInt(
line.substring(column, column + 4), 16);
column += 4;
val.append(uni);
} catch (NumberFormatException ex) {
throw new ParseException(linenr,
"Invalid unicode escape character");
}
} else
throw new ParseException(linenr,
"Invalid unicode escape character");
break;
default:
val.append(c);
}
} else
val.append(c);
}
throw new ParseException(linenr, "String spans over multiple lines");
} | 9 |
@Override
public void setValue(Object o) {
throw new UnsupportedOperationException("cannot yet set virtual "+this.getNodeProperty().getName());
} | 0 |
@Override
public String toString()
{
StringBuilder builder = new StringBuilder(m_having ? " HAVING " : " WHERE ");
int fieldCnt = 0;
for (WhereInfo whereInfo : m_whereInfo)
{
if (whereInfo.m_startBracket)
{
builder.append('(');
continue;
}
if (whereInfo.m_endBracket)
{
builder.append(')');
continue;
}
if (whereInfo.m_custom != null)
{
builder.append(whereInfo.m_custom);
fieldCnt++;
continue;
}
if (fieldCnt != 0)
{
builder.append(whereInfo.m_orClause ? " OR " : " AND ");
}
fieldCnt++;
builder.append(whereInfo.m_field.toString());
if (whereInfo.m_inCount != 0)
{
builder.append(whereInfo.m_notIn ? " NOT IN (" : " IN (");
QbCommonImp.createPlaceholders(builder, whereInfo.m_inCount);
builder.append(')');
continue;
}
builder.append(' ');
builder.append(whereInfo.m_op.toString());
builder.append(" ?");
}
return builder.toString();
} | 9 |
public void update(Ship ship, int delta) {
Iterator<Invader> it = invaders.iterator();
ArrayList<Invader> invaders_to_remove = new ArrayList<Invader>();
while (it.hasNext()) {
Invader invader = it.next();
if (invader.is_alive()) {
invader.update(delta);
} else {
invaders_to_remove.add(invader);
}
}
invaders.removeAll(invaders_to_remove);
last_shoot += delta;
int taille = invaders.size();
if (last_shoot > 900 && taille > 0) {
invaders.get(r.nextInt(invaders.size())).fire();
last_shoot = 0;
}
} | 4 |
public synchronized void makeCustomRequest (AnalyticsRequestData argData) {
if (!enabled) {
Logger.logInfo("Ignoring tracking request, enabled is false");
return;
}
if (argData == null) {
throw new NullPointerException("Data cannot be null");
}
if (builder == null) {
throw new NullPointerException("Class was not initialized");
}
final String url = builder.buildURL(argData);
switch (mode) {
case MULTI_THREAD:
Thread t = new Thread(asyncThreadGroup, "AnalyticsThread-" + asyncThreadGroup.activeCount()) {
@Override
public void run () {
synchronized (JGoogleAnalyticsTracker.class) {
asyncThreadsRunning++;
}
try {
dispatchRequest(url);
} finally {
synchronized (JGoogleAnalyticsTracker.class) {
asyncThreadsRunning--;
}
}
}
};
t.setDaemon(true);
t.start();
break;
case SYNCHRONOUS:
dispatchRequest(url);
break;
default: // in case it's null, we default to the single-thread
synchronized (fifo) {
fifo.addLast(url);
fifo.notify();
}
if (!backgroundThreadMayRun) {
Logger.logError("A tracker request has been added to the queue but the background thread isn't running." + url);
}
break;
}
} | 6 |
private void initTextField(){
JLabel labelName = new JLabel("Name");
labelName.setBounds(10 , scrollTable.getY()+scrollTable.getHeight()+10, 95, 25 );
textFieldName = new JTextField();
textFieldName.setBounds(labelName.getX()+labelName.getWidth()+10,
scrollTable.getY()+scrollTable.getHeight()+10, 370,25);
JLabel labelFilePath = new JLabel("File name");
labelFilePath.setBounds(10 , textFieldName.getY()+textFieldName.getHeight()+45, 95, 25 );
textFieldFilePath = new JTextField();
textFieldFilePath.setBounds(textFieldName.getX(),
textFieldName.getY()+textFieldName.getHeight()+45, 310,25);
add(labelName);
add(textFieldName);
add(labelFilePath);
add(textFieldFilePath);
} | 0 |
public Class getTypeClass() throws ClassNotFoundException {
switch (typecode) {
case TC_LONG:
return Long.TYPE;
case TC_FLOAT:
return Float.TYPE;
case TC_DOUBLE:
return Double.TYPE;
default:
throw new AssertError("getTypeClass() called on illegal type");
}
} | 3 |
public void saveFile(String filename) {
try {
List<String> sections_list = new ArrayList<String>();
for (String key : map.keySet()) {
String section = key.split("\\.")[0];
if (!sections_list.contains(section)) sections_list.add(section);
}
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
for (String sect : sections_list) {
writer.write("[" + sect + "]\n");
for (String key : map.keySet()) {
String[] keys = key.split("\\.");
if (sect.equals(keys[0])) {
writer.write(keys[1] + "=" + map.get(key) + '\n');
}
}
}
writer.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error while saving ini file: " + filename);
}
} | 6 |
public Texture getTexture() {
if(animation != null) {
return animation.getTexture();
}
return tex;
} | 1 |
@Override
/**
* makes the given little man perform the next action in the sequence of
* little man actions. If the little man completes the final action in the
* list, this action sequence is reset so that the next action to be
* completed is the first action in the sequence.
*
* @param littleMan the little man which is to complete this action's
*
* @return whether the action sequence was successfully completed
*/
public boolean doAction(GenericLittleMan<?> littleMan) {
boolean isComplete = littleManActions.get(currentAction).doAction(littleMan);
if (isComplete) {
incrementAction();
return currentAction == 0;
} else {
return false;
}
} | 2 |
public boolean deleteClaim(Claim c, String actionType) {
Element claimE;
Claim claim;
boolean flag = false;
System.out.println(fileName + "Claim delete: " + actionType);
for (Iterator i = root.elementIterator(actionType); i.hasNext();) {
claimE = (Element)i.next();
System.out.println(fileName + "Claim delete: " + c.getId());
if (claimE.element("id").getText().equals(c.getId())) {
System.out.println("Claim delete: " + c.getId());
claimE.element("isDelete").setText("true");
// Write to xml
try {
XmlUtils.write2Xml(fileName, document);
flag = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
return flag;
} | 3 |
public void sort(Object array[])
{
if (array != null && array.length > 1)
{
int maxLength;
maxLength = array.length;
swapSpace = new Object[maxLength];
toSort = array;
this.mergeSort(0, maxLength - 1);
swapSpace = null;
toSort = null;
}
} | 2 |
private void initObjs(){
//Object Packaging...
jLabelsActvArr = initMyActvJLabelsArray(ACTV_ROW_NUM_MAX);
jTextFieldsArr = initMyJTextFieldsArray(ACTV_ROW_NUM_MAX, DAYS_TO_ROLL_NONE);
//Central Activity Rows
jCheckBoxesCol1 = initMyJCheckBoxesArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_BACK);
jCheckBoxesCol2 = initMyJCheckBoxesArray(ACTV_ROW_NUM_MAX, DAYS_TO_ROLL_TODAY);
jCheckBoxesCol3 = initMyJCheckBoxesArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_FRWR);
jSlidersCol1 = initMyJSlidersArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_BACK);
jSlidersCol2 = initMyJSlidersArray(ACTV_ROW_NUM_MAX, DAYS_TO_ROLL_TODAY);
jSlidersCol3 = initMyJSlidersArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_FRWR);
jTextFieldsCol1 = initMyJTextFieldsArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_BACK);
jTextFieldsCol2 = initMyJTextFieldsArray(ACTV_ROW_NUM_MAX, DAYS_TO_ROLL_TODAY);
jTextFieldsCol3 = initMyJTextFieldsArray(ACTV_ROW_NUM_MAX, ROLL_1_DAY_FRWR);
final MyJTextPane jTextPane1 = new MyJTextPane();
final MyJTextPane jTextPane2 = new MyJTextPane();
final MyJTextPane jTextPane3 = new MyJTextPane();
jTextPanesArr = new MyJTextPane[]{jTextPane1, jTextPane2, jTextPane3};
final javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
final javax.swing.JScrollPane jScrollPane2 = new javax.swing.JScrollPane();
final javax.swing.JScrollPane jScrollPane3 = new javax.swing.JScrollPane();
jScrollPanesArr = new JScrollPane[]{jScrollPane1, jScrollPane2, jScrollPane3};
//Look and Feel
final String LAF = recursosConfig.getString("LAF");
if( !LAF_NONE.equals(LAF) ){
setLookAndFeel( LAF );
}
//Fechas
nowDate = new java.util.Date();
selectedDate = nowDate;
textFiledFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, selectedLocale);
today = textFiledFormat.format( selectedDate );
todayFormat = new SimpleDateFormat(SDF_DAY_PATTERN_1, selectedLocale);
monthFormat = new SimpleDateFormat(SDF_MONTH_PATTERN_1, selectedLocale);
dbPKeyFormat = new SimpleDateFormat(DB_DATE_PKEY_PATTERN, selectedLocale); //"yyyy-MM-dd"
calend = Calendar.getInstance(selectedLocale);
currentTextPaneFontSizeGlobal = 12;
fuente1 = new java.awt.Font("Arial", Font.PLAIN, 12);
fuente1b = new java.awt.Font("Arial", Font.BOLD, 12);
// fuente1i = new java.awt.Font("Arial", Font.ITALIC, 12);
final java.awt.Font fuente2 = new java.awt.Font("Arial", Font.PLAIN, 24);
jFrame1 = new javax.swing.JFrame();
jPanel1 = new javax.swing.JPanel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenuFile = new javax.swing.JMenu();
jMenuTools = new javax.swing.JMenu();
jMenuAbout = new javax.swing.JMenu();
jMenuItemF1 = new javax.swing.JMenuItem();
jMenuItemF2 = new javax.swing.JMenuItem();
jMenuItemF4 = new javax.swing.JMenuItem();
jMenuItemF5 = new javax.swing.JCheckBoxMenuItem();
jMenuItemFExit = new javax.swing.JMenuItem();
jMenuItemA1 = new javax.swing.JMenuItem();
jMenuItemT1 = new javax.swing.JMenuItem();
jMenuItemT2 = new javax.swing.JMenuItem();
jDateBTN = new javax.swing.JButton();
rightBTN = new javax.swing.JButton();
leftBTN = new javax.swing.JButton();
selectedDateTextField = new ObservingTextField();
// final java.awt.Dimension tempDimensions = new java.awt.Dimension();
final java.awt.Insets tempInset = new java.awt.Insets(0, 0, 0, 0);
final java.awt.GridBagConstraints gbc = new GridBagConstraints();
//Frame
jFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jFrame1.setFont(fuente1);
jFrame1.setTitle( recursosTexto.getString("appTitle"));
jPanel1.setLayout(new GridBagLayout());
jPanel1.setOpaque(true);
//Panel Layout
jPanel1.setLayout(new GridBagLayout());
//Basic layout Constraints
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.CENTER;
//Vars locales de despliegue
final int posXBotonFecha = 4;
final int posYBotonFecha = 0;
final int posXFlechas = 4;
final int posYMes = 1;
final int posXLabelsTop = 4;
final int posYLabelsTop = 2;
final int gridWidthLabelsTop = 3;
//Labels actividades
final int posXLabelAct = 0;
final int gridWidthLabelAct = 3;
final int posYLabelActA = 3;
//CheckBoxes
final int posXCheckBoxes = 4;
final int gridWidthCheckBoxes = 3;
final int posYCheckBoxesA = 3;
final int posXTextPanes = 4;
final int posYTextPanes = 12;
final int gridWidthTextPanes = 3;
//Fila 1
gbc.gridy = posYBotonFecha;
gbc.insets = tempInset;
//Texfields
selectedDateTextField.setColumns(TEXTFIELD_COL_SIZE);
selectedDateTextField.setToolTipText(recursosTexto.getString("dateTipL"));
selectedDateTextField.setText(today);
selectedDateTextField.setFocusable(false);
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = posXBotonFecha+7;
gbc.gridwidth = 2;
jPanel1.add(selectedDateTextField, gbc);
//Buttons
//Date button
jDateBTN.setText(recursosTexto.getString("dateBtnL"));
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = posXBotonFecha+9;
gbc.gridwidth = 1;
jPanel1.add(jDateBTN, gbc);
//Next y Prev
tempInset.set(0, 0, INSETS_SEP_A_FULL, 0);
gbc.insets = tempInset;
gbc.gridy = posYLabelsTop;
//Next
// tempDimensions.setSize(DIM_BTN_DEF_X, DIM_BTN_DEF_Y);
rightBTN.setIcon( new javax.swing.ImageIcon(getClass().getResource("/nextmon.gif"), ">") );
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = posXFlechas+8;
jPanel1.add(rightBTN, gbc);
//Prev
leftBTN.setIcon( new javax.swing.ImageIcon(getClass().getResource("/premon.gif"), "<") );
gbc.gridx = posXFlechas+1;
jPanel1.add(leftBTN, gbc);
//Labels
//Mes
tempInset.set(0, 0, 0, INSETS_SEP_A_FULL);
gbc.insets = tempInset;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = 3;
gbc.gridx = posXFlechas+7;
gbc.gridy = posYMes;
jLblMonth.setFont(fuente2);
jLblMonth.setText( monthFormat.format( nowDate ) );
jPanel1.add(jLblMonth, gbc);
//Dias
tempInset.set(0, INSETS_SEP_A_HALF, INSETS_SEP_A_HALF, INSETS_SEP_A_FULL);
gbc.insets = tempInset;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = gridWidthLabelsTop;
gbc.gridy = posYLabelsTop;
//Today
// calend.roll(Calendar.DAY_OF_YEAR, 1);
jLblToday.setText(todayFormat.format( calend.getTime()));
gbc.gridx = posXLabelsTop + (gridWidthTextPanes);
jPanel1.add(jLblToday, gbc);
calend.roll(Calendar.DAY_OF_YEAR, ROLL_1_DAY_FRWR); //Tommorrow
//Special case if has been rolled to first day of year... also roll year
if( calend.get(Calendar.DAY_OF_YEAR) == calend.getActualMinimum(Calendar.DAY_OF_YEAR) ){
calend.roll(Calendar.YEAR, 1); //Forward one day
}
jLblPostDay1.setText(todayFormat.format( calend.getTime()));
gbc.gridx = posXLabelsTop + (gridWidthTextPanes*2);
jPanel1.add(jLblPostDay1, gbc);
//Special case if has been rolled to first day of year... also roll year
if( calend.get(Calendar.DAY_OF_YEAR) == calend.getActualMinimum(Calendar.DAY_OF_YEAR) ){
calend.roll(Calendar.YEAR, -1); //Back one year
}
calend.roll(Calendar.DAY_OF_YEAR, ROLL_1_DAY_BACK-1); //Yesterday
jLblPrevDay1.setText(todayFormat.format( calend.getTime()));
gbc.gridx = posXLabelsTop;
jPanel1.add(jLblPrevDay1, gbc);
//TODO: Programatically add components (i.e.: in a for loop, add new components, to array and then work from the array
//Labels y TextFields Actividades
//Contenidos
tempInset.set(0, 0, 0, 0);
gbc.insets = tempInset;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 0;
gbc.gridwidth = gridWidthLabelAct;
gbc.gridx = posXLabelAct;
gbc.gridy = posYLabelActA;
addActivityRowComponentsColumnWise(jPanel1, jLabelsActvArr, gbc); //Labels
addActivityRowComponentsColumnWise(jPanel1, jTextFieldsArr, gbc); //TextFields
//Checkboxes
tempInset.set(0, 0, 0, INSETS_SEP_A_FULL);
gbc.insets = tempInset;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 0;
gbc.gridwidth = gridWidthCheckBoxes;
gbc.gridy = posYCheckBoxesA;
gbc.gridx = posXCheckBoxes;
addActivityRowComponentsColumnWise(jPanel1, jCheckBoxesCol1, gbc);
addActivityRowComponentsColumnWise(jPanel1, jSlidersCol1, gbc);
addActivityRowComponentsColumnWise(jPanel1, jTextFieldsCol1, gbc);
gbc.gridx = posXCheckBoxes+(gridWidthCheckBoxes);
addActivityRowComponentsColumnWise(jPanel1, jCheckBoxesCol2, gbc);
addActivityRowComponentsColumnWise(jPanel1, jSlidersCol2, gbc);
addActivityRowComponentsColumnWise(jPanel1, jTextFieldsCol2, gbc);
gbc.gridx = posXCheckBoxes+(gridWidthCheckBoxes*2);
addActivityRowComponentsColumnWise(jPanel1, jCheckBoxesCol3, gbc);
addActivityRowComponentsColumnWise(jPanel1, jSlidersCol3, gbc);
addActivityRowComponentsColumnWise(jPanel1, jTextFieldsCol3, gbc);
/* ### TextPanes ### */
//JTextPane Name indicates days to roll from the (middle) actual-selected date....
//Aplica para todos
tempInset.set(INSETS_SEP_A_FULL, 0, 0, INSETS_SEP_A_FULL);
gbc.insets = tempInset;
gbc.gridwidth = gridWidthTextPanes;
//1
jTextPane1.setName(DAYS_TO_ROLL_PREV1_STR);
jTextPane1.setText( recursosTexto.getString("YesterdayTPTxt") );
jScrollPane1.setViewportView(jTextPane1);
gbc.gridx = posXTextPanes;
gbc.gridy = posYTextPanes;
jPanel1.add(jScrollPane1, gbc);
//2
jTextPane2.setName(DAYS_TO_ROLL_TODAY_STR);
jTextPane2.setText( recursosTexto.getString("TodayTPTxt") );
jScrollPane2.setViewportView(jTextPane2);
gbc.gridx = posXTextPanes+(gridWidthTextPanes);
gbc.gridy = posYTextPanes;
jPanel1.add(jScrollPane2, gbc);
//3
jTextPane3.setName(DAYS_TO_ROLL_FRWR1_STR);
jTextPane3.setText( recursosTexto.getString("TomorrowTPTxt") );
jScrollPane3.setViewportView(jTextPane3);
gbc.gridx = posXTextPanes+(gridWidthTextPanes*2);
gbc.gridy = posYTextPanes;
jPanel1.add(jScrollPane3, gbc);
//Menus
//Listeners added in listeners method
//IMPORTANT!!! Menus NOT added in menuVar name order...
jMenuFile.setText( recursosTexto.getString("fileMenu") );
jMenuFile.setFont(fuente1);
jMenuTools.setText( recursosTexto.getString("toolsMenu") );
jMenuTools.setFont(fuente1);
jMenuAbout.setText( recursosTexto.getString("aboutMenu") );
jMenuAbout.setFont(fuente1);
jMenuItemF1.setText(recursosTexto.getString("fileMenuItem1"));
jMenuItemF1.setMnemonic(KeyEvent.VK_N);
jMenuItemF1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
jMenuItemF1.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("fileMenuAccDesc1") );
jMenuItemF2.setText(recursosTexto.getString("fileMenuItem2"));
jMenuItemF2.setMnemonic(KeyEvent.VK_1);
jMenuItemF2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
jMenuItemF2.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("fileMenuAccDesc2") );
jMenuItemF4.setText(recursosTexto.getString("fileMenuItem4"));
jMenuItemF4.setMnemonic(KeyEvent.VK_L);
jMenuItemF4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
jMenuItemF4.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("fileMenuAccDesc4") );
jMenuItemF5.setText(recursosTexto.getString("msgPassEnable"));
jMenuItemF5.setMnemonic(KeyEvent.VK_P);
jMenuItemF5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
jMenuItemF5.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("msgPassEnableDesc") );
jMenuItemFExit.setText(recursosTexto.getString("fileMenuItemExit"));
jMenuItemFExit.setMnemonic(KeyEvent.VK_X);
jMenuItemFExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
jMenuItemFExit.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("fileMenuAccDescExit") );
jMenuItemT1.setText(recursosTexto.getString("toolsMenuItem1"));
jMenuItemT1.setMnemonic(KeyEvent.VK_E);
jMenuItemT1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
jMenuItemT1.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("toolsMenuItem1AccDesc") );
jMenuItemT2.setText(recursosTexto.getString("toolsMenuItem2"));
jMenuItemT2.setMnemonic(KeyEvent.VK_C);
jMenuItemT2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));
jMenuItemT2.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("toolsMenuItem2AccDesc") );
jMenuItemA1.setText(recursosTexto.getString("aboutMenuItem1"));
jMenuItemA1.setMnemonic(KeyEvent.VK_F1);
jMenuItemA1.setAccelerator(KeyStroke.getKeyStroke("F1"));
jMenuItemA1.getAccessibleContext().setAccessibleDescription( recursosTexto.getString("aboutMenuItem1") );
//NOT added in menuVar name order...
jMenuFile.add(jMenuItemF1);
jMenuFile.add(jMenuItemF2);
jMenuFile.add(jMenuItemF4);
jMenuFile.add(jMenuItemF5);
jMenuFile.add(jMenuItemFExit);
jMenuAbout.add(jMenuItemA1);
jMenuTools.add(jMenuItemT1);
jMenuTools.add(jMenuItemT2);
jMenuBar1.add(jMenuFile);
jMenuBar1.add(jMenuTools);
jMenuBar1.add(jMenuAbout);
//Icon Images
// jMenuItemF1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nextmon.gif")));
jFrame1.setJMenuBar(jMenuBar1);
//Size and Position
if( dimPant.width >= APP_SIZE_RECOMMENDED_MIN_WIDTH && dimPant.height >= APP_SIZE_RECOMMENDED_MIN_HEIGHT ){
if( cache.getAppDimensions().getWidth() == APP_SIZE_NOT_INITIALIZED ){
appDimensions.setSize( APP_SIZE_RECOMMENDED_MIN_WIDTH, APP_SIZE_RECOMMENDED_MIN_HEIGHT );
}else{
appDimensions.setSize( cache.getAppDimensions() );
}
jPanel1.setSize(appDimensions);
jPanel1.setPreferredSize(appDimensions);
jFrame1.setSize(appDimensions);
jFrame1.setPreferredSize(appDimensions);
}else{
appDimensions.setSize(APP_SIZE_WIDTH_MIN, APP_SIZE_HEIGHT_MIN);
jFrame1.setMinimumSize( appDimensions );
// jFrame1.setSize(dimPant.width/2, dimPant.height/2);
}
jFrame1.setLocation( (dimPant.width-jFrame1.getWidth())/2, (dimPant.height-jFrame1.getHeight())/2 );
//Focus panel to catch panel key events
jPanel1.setFocusable(true);
//END
jFrame1.add(jPanel1, BorderLayout.CENTER);
jFrame1.setContentPane(jPanel1);
jFrame1.setVisible(false); //Commet to DEBUG
//instance execution lock
if( !Database.createInstanceLock() ){
Database.removeInstanceLock(); //si se va la luz y no se elimina el archivo nunca podra entrar de nuevo...
JOptionPane.showInternalMessageDialog(jPanel1, recursosTexto.getString("msgErrInstanteLockL"), recursosTexto.getString("msgErrorTitle"), JOptionPane.ERROR_MESSAGE);
System.exit(-1);
}
} | 7 |
private PrintWriter fluxSortant() {
if (connecteur != null) {
try {
return new PrintWriter(connecteur.getOutputStream());
} catch (IOException e) {
System.out.println("Problème de récupération du flux sortant du serveur");
}
}
return null;
} | 2 |
public Accounting() {
accountTypes = new AccountTypes();
accounts = new Accounts(accountTypes);
journalTypes = new JournalTypes();
journalTypes.addDefaultType(accountTypes);
journals = new Journals(accounts, journalTypes);
balances = new Balances(accounts, accountTypes);
contacts = new Contacts();
mortgages = new Mortgages(accounts);
projects = new Projects(accounts, accountTypes);
accounts.setName(accounts.getBusinessObjectType());
journals.setName(journals.getBusinessObjectType());
try {
// addBusinessObject((BusinessCollection)accountTypes);
addBusinessObject((BusinessCollection)accounts);
// addBusinessObject((BusinessCollection)journalTypes);
addBusinessObject((BusinessCollection)journals);
addBusinessObject((BusinessCollection)balances);
addBusinessObject((BusinessCollection)contacts);
addBusinessObject((BusinessCollection)mortgages);
addBusinessObject((BusinessCollection)projects);
} catch (EmptyNameException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (DuplicateNameException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
keys = new ArrayList<>();
// keys.add(accountTypes.getBusinessObjectType());
keys.add(accounts.getBusinessObjectType());
// keys.add(journalTypes.getBusinessObjectType());
keys.add(journals.getBusinessObjectType());
keys.add(balances.getBusinessObjectType());
keys.add(contacts.getBusinessObjectType());
keys.add(mortgages.getBusinessObjectType());
keys.add(projects.getBusinessObjectType());
} | 2 |
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeObject(b);
} | 0 |
public void draw(Graphics g){
Color c = g.getColor();
g.setColor(Color.MAGENTA);
g.fillRect(x,y,w,h);
g.setColor(c);
move();
} | 0 |
Subsets and Splits