text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public void storeFinalGrades(int term){
try {
// Connect
HttpGet finalGet = new HttpGet("https://jweb.kettering.edu/cku1/wbwskogrd.P_ViewGrde?term_in=" + term + "&inam=on&snam=on&sgid=on");
HttpResponse response = this.clientBanner.execute(finalGet);
String html = HTMLParser.parse(response);
// Write to file
PrintWriter printer = new PrintWriter("artifacts/finalgrades.html");
printer.print(html);
printer.close();
System.out.println("Successfully stored \"finalgrades.html\"");
Elements tables = Jsoup.parse(html).getElementsByClass("datadisplaytable");
// Correct amount ?
if (tables.size() == 3 && tables.get(2).getElementsByTag("tbody").size() > 0 && tables.get(2).getElementsByTag("tbody").get(0).children().size() == 5 && tables.get(1).getElementsByTag("tbody").size() > 0){
// Store undergrad summary
this.undergradSummary = new UndergradSummary(tables.get(2).getElementsByTag("tbody").get(0).children());
Elements courses = tables.get(1).getElementsByTag("tbody").get(0).getElementsByTag("tr");
// Titles remove
if (courses.size() > 0) courses.remove(0);
// Add final grades
for(int i = 0; i < courses.size(); i++) if(courses.get(i).getElementsByTag("td").size() == 12) this.finalGrades.add(new FinalGrade(courses.get(i).getElementsByTag("td")));
}
}
catch(Exception e){ e.printStackTrace(); }
}
| 8 |
private Map<Pattern,String> loadPatterns(InputStream is) {
Properties p = new Properties();
try {
p.load(is);
} catch (IOException e) {
throw new RuntimeException("Error loading patterns", e);
}
Map<Pattern,String> pattMap = new HashMap<Pattern,String>();
for (Object k : p.keySet()) {
String key = (String)k;
String repl = p.getProperty(key);
log.finer("load: " + key + "->" + repl);
// If key begins with ${...}, substitute key now
// ("now" == at program start-up).
if (key.charAt(0) == '$') {
String propName = key.substring(2, key.length() - 1);
String newKey = sysProps.getProperty(propName);
log.fine(String.format(
"loadPatterns(): prop %s -> %s", propName, newKey));
key = newKey;
}
log.fine(String.format("loadPatterns() key '%s' value '%s'", key, repl));
Pattern pat = Pattern.compile(key);
pattMap.put(pat, repl);
}
return pattMap;
}
| 3 |
public void initialize() {
setTitle("Manage Teams");
setBounds(100, 100, 464, 362);
getContentPane().setLayout(new BorderLayout());
{
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) {
teamsChanged = true;
setVisible(false);
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
teamsChanged = false;
setVisible(false);
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
{
JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);
getContentPane().add(toolBar, BorderLayout.NORTH);
{
JButton btnAddTeam = toolBar.add(addTeamAction);
btnAddTeam.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
teams.add(new Team("Pavadinimas"));
model.addRow(new Object[] {
teams.get(teams.size()-1).getName(),
teams.get(teams.size()-1).getPoints()
});
}
});
btnAddTeam.setHorizontalAlignment(SwingConstants.LEFT);
btnAddTeam.setHorizontalTextPosition(SwingConstants.TRAILING);
btnAddTeam.setIconTextGap(5);
btnAddTeam.setIcon(new ImageIcon(ManageTeams.class.getResource("/images/Add.png")));
btnAddTeam.setFocusable(false);
btnAddTeam.setMargin(new Insets(0, 10, 0, 5));
btnAddTeam.setToolTipText("Add new team");
btnAddTeam.setText("Add Team");
}
{
JButton btnRemoveTeams = toolBar.add(removeSelectedAction);
btnRemoveTeams.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
removeSelected();
}
});
btnRemoveTeams.setIcon(new ImageIcon(ManageTeams.class.getResource("/images/Delete.png")));
btnRemoveTeams.setIconTextGap(5);
btnRemoveTeams.setHorizontalTextPosition(SwingConstants.TRAILING);
btnRemoveTeams.setHorizontalAlignment(SwingConstants.LEFT);
btnRemoveTeams.setFocusable(false);
btnRemoveTeams.setMargin(new Insets(0, 5, 0, 5));
btnRemoveTeams.setToolTipText("Remove selected teams");
btnRemoveTeams.setText("Remove Selected");
}
}
{
JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
{
if (teams.size() > 0) {
for (int i = 0; i < teams.size(); i++) {
model.addRow(new Object[] {
teams.get(i).getName(),
teams.get(i).getPoints()
});
}
}
model.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if (row >= 0 && column >= 0) {
if (model.getValueAt(row, column) != null) {
switch(column) {
case 0: teams.get(row).setName((String)model.getValueAt(row, column));
break;
case 1: teams.get(row).setPoints((Integer)model.getValueAt(row, column));
break;
default: break;
}
}
}
}
});
table = new JTable();
table.setModel(model);
//table.getColumnModel().getColumn(1).setMaxWidth(75);
scrollPane.setViewportView(table);
}
}
}
| 7 |
private void afficherModifierFormation() {
System.out.println("Code de la formation à modifier ?");
this.modeleApplication.afficherLesFormations();
String code = scan.nextLine();
while(code.isEmpty()) {
System.out.println("Veuillez entrer un code de formation correct.");
System.out.println("Code de la formation : ");
code = scan.nextLine();
}
System.out.println("Nouvean nom de la formation : ");
String nom = scan.nextLine();
while(nom.isEmpty()) {
System.out.println("Veuillez entrer un nom de formation correct.");
System.out.println("Nom de la formation : ");
nom = scan.nextLine();
}
System.out.println("Nouvean nom de la salle CM : ");
String nomSalleCM = scan.nextLine();
while(nomSalleCM.isEmpty()) {
System.out.println("Veuillez entrer un nom de salle correct.");
System.out.println("Nom de la salle CM : ");
nomSalleCM = scan.nextLine();
}
System.out.println("Nouvean nom de la salleTD : ");
String nomSalleTD = scan.nextLine();
while(nomSalleTD.isEmpty()) {
System.out.println("Veuillez entrer un nom de salle correct.");
System.out.println("Nom de la salle TD : ");
nomSalleTD = scan.nextLine();
}
boolean res = this.modeleApplication.modifierFormation(code, nom, nomSalleCM, nomSalleTD);
while (!res) {
this.afficherModifierFormation();
}
System.out.println("Modification enregistrée.");
this.afficherMenuPersonnel();
}
| 5 |
private void jButtonVoteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVoteActionPerformed
SondageReponseDao srd = SondageReponseDao.getInstance();
List<SondageReponse> listReponses = srd.findAll();
SondageReponse sr_vote = new SondageReponse(lastSondage.getId(), lastSondage.getId(), sondageChoix, 1);
for(SondageReponse sr : listReponses){
if(sr_vote.equals(sr)){
sr_vote = sr;
sr_vote.setNombreChoix(sr.getNombreChoix()+1);
srd.update(sr_vote);
break;
}
}
if(sr_vote.getNombreChoix() == 1)
srd.insert(sr_vote);
System.out.println("Vote ajouté " + sr_vote);
}//GEN-LAST:event_jButtonVoteActionPerformed
| 3 |
private final void method3067(byte i) {
int i_5_ = 25 / ((i - -28) / 57);
if ((((Class348_Sub40_Sub8) this).anInt9149 ^ 0xffffffff) < -1) {
aShortArray9162
= new short[((Class348_Sub40_Sub8) this).anInt9150];
aShortArray9159
= new short[((Class348_Sub40_Sub8) this).anInt9150];
for (int i_6_ = 0; ((Class348_Sub40_Sub8) this).anInt9150 > i_6_;
i_6_++) {
aShortArray9159[i_6_]
= (short) (int) ((Math.pow
((double) ((float) ((Class348_Sub40_Sub8)
this).anInt9149
/ 4096.0F),
(double) i_6_))
* 4096.0);
aShortArray9162[i_6_]
= (short) (int) Math.pow(2.0, (double) i_6_);
}
} else if (aShortArray9159 != null
&& (((Class348_Sub40_Sub8) this).anInt9150
== aShortArray9159.length)) {
aShortArray9162
= new short[((Class348_Sub40_Sub8) this).anInt9150];
for (int i_7_ = 0;
((((Class348_Sub40_Sub8) this).anInt9150 ^ 0xffffffff)
< (i_7_ ^ 0xffffffff));
i_7_++)
aShortArray9162[i_7_]
= (short) (int) Math.pow(2.0, (double) i_7_);
}
anInt9151++;
}
| 5 |
public void creationCarte(final int[][] carte)
{
this.carte = new int[carte.length][carte[0].length];
for (int i = 0; i < carte.length; i++) {
for (int j = 0; j < carte[i].length; j++) {
this.carte[i][j] = carte[i][j];
}
}
for (final IleEcouteur ileEcouteur : this.ileEcouteurs.getListeners(IleEcouteur.class)) {
ileEcouteur.creationCarte(this.carte);
}
}
| 3 |
public int getMsgFormat() {
return MsgFormat;
}
| 0 |
public static DayEnum fromValue(String v) {
for (DayEnum c: DayEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
| 2 |
@SuppressWarnings("rawtypes")
public void buildList(JSONObject jo) {
//build from the JSONObejct a arrayList with stops
try{
if(!jo.isEmpty()) {
Set set = jo.entrySet();
Iterator i = set.iterator();
int data = set.size();
int total = 25;
double current = StartUpLoader.getInstance().getProcent();
double stepSize = total/data;
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
String SpBern = (String) me.getKey();
double Latitude = 0;
String TimingPointName = null;
double Longitude = 0;
String TimingPointTown = null;
JSONObject job = (JSONObject) me.getValue();
Set set2 = job.entrySet();
Iterator i2 = set2.iterator();
while(i2.hasNext()) {
Map.Entry me2 = (Map.Entry)i2.next();
if(((String) me2.getKey()).equalsIgnoreCase("TimingPointName")) {
TimingPointName = (String) me2.getValue();
} else if(((String) me2.getKey()).equalsIgnoreCase("TimingPointTown")) {
TimingPointTown = (String) me2.getValue();
} else if(((String) me2.getKey()).equalsIgnoreCase("Latitude")) {
Latitude = (Double) me2.getValue();
} else if(((String) me2.getKey()).equalsIgnoreCase("Longitude")) {
Longitude = (Double) me2.getValue();
}
}
stops.add(new Stop(SpBern, Latitude, TimingPointName, Longitude, TimingPointTown));
current += stepSize;
StartUpLoader.getInstance().setProcent((int) current);
}
} else {
System.out.println("JOSNObject containt no values");
}
} catch(NullPointerException ne) {
System.out.println("JOSNObject is null, maybe connection issue");
}
}
| 8 |
public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
| 7 |
private void writeResultGlobal(ValidateResult[] validateResultsSingle, ValidateResult globalResult, String filepath) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(new File(filepath)));
out.write(ValidateResult.getCaption());
out.newLine();
for (ValidateResult validateResult : validateResultsSingle) {
out.write(validateResult.toString());
out.newLine();
}
out.newLine();
out.write(globalResult.toString());
out.close();
}
| 1 |
public static String findTextInList(List<WebElement> webElements, String ans){
Point sLocation;
int xx, yy, d;
String text;
for(WebElement ss : webElements){
text = ss.getText();
if(text!=null && !text.equals("")){
sLocation = ss.getLocation();
xx = sLocation.getX();
yy = sLocation.getY();
d = Math.abs(yy-y) + Math.abs(xx-x);
if (d < r && yy <= y){
r = d;
ans = text;
}
}
}
return ans;
}
| 5 |
@Override
public double[] computeValue(final char refBase, FastaWindow window, AlignmentColumn col) {
values[ref] = 0.0;
values[alt] = 0.0;
int refCount = 0;
int altCount = 0;
if (col.getDepth() > 0) {
Iterator<MappedRead> it = col.getIterator();
while(it.hasNext()) {
MappedRead read = it.next();
if (read.hasBaseAtReferencePos(col.getCurrentPosition())) {
byte b = read.getBaseAtReferencePos(col.getCurrentPosition());
byte q = read.getQualityAtReferencePos(col.getCurrentPosition());
int index = 0;
if (b == 'N')
continue;
if (b != refBase) {
index = 1;
altCount++;
}
else {
refCount++;
}
values[index] += q;
}
}
}
if (refCount > 0)
values[ref] /= refCount;
if (altCount > 0)
values[alt] /= altCount;
values[ref] = values[ref] / 60.0 * 2.0 -1.0;
values[alt] = values[alt] / 60.0 * 2.0 -1.0;
return values;
}
| 7 |
@Override
public void process(WatchedEvent event) {
try {
final String eventPath = event.getPath();
switch (event.getType()) {
case None:
final Event.KeeperState state = event.getState();
logger.info("new ZK connection state: " + state.toString());
if (state == Event.KeeperState.Expired) {
logger.info("trying to reestablished expired connection");
stop();
start();
return;
}
status.set(state.toString());
propagateToListeners(new ControlMessage(state.toString(), ControlMessage.Type.Z));
break;
case NodeCreated:
//propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.C));
break;
case NodeDeleted:
//propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.D));
break;
case NodeDataChanged:
handleDataChanged(eventPath);
case NodeChildrenChanged:
handleChildrenChanged(eventPath);
break;
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
| 7 |
public void focusGained(FocusEvent e) {
try{
if(e.getSource() == txtAreaTeam1){
if(blnServer){
for(int i = 0; i < player.size(); i++){
tempPlayer = (PlayerConnection)player.get(i);
if(tempPlayer.intID == intID){
tempPlayer.intTeam = 1;
updateTeams();
}
}
}else{
ssm.sendText("SwitchTeam,"+intID+",1");
}
}else if(e.getSource() == txtAreaTeam2){
if(blnServer){
for(int i = 0; i < player.size(); i++){
tempPlayer = (PlayerConnection)player.get(i);
if(tempPlayer.intID == intID){
tempPlayer.intTeam = 2;
updateTeams();
}
}
}else{
ssm.sendText("SwitchTeam,"+intID+",2");
}
}
}catch(Exception ex){
}
}
| 9 |
@SuppressWarnings("unchecked")
public Map<String, Object> getStateForPlayerId(String playerId) {
Map<String, Object> result = Maps.newHashMap();
for (String key : state.keySet()) {
Object visibleToPlayers = visibleTo.get(key);
Object value = null;
if (visibleToPlayers.equals(ALL)
|| ((List<String>) visibleToPlayers).contains(playerId)) {
value = state.get(key);
}
result.put(key, value);
}
return result;
}
| 3 |
public static List<FunctionTrace> extractRelevantSequence(
List<List<FunctionTrace>> llft) {
List<FunctionTrace> relevantSequence = null;
Iterator it = llft.iterator();
List<FunctionTrace> lft = null;
List<FunctionTrace> finalFunctionTrace = new ArrayList<FunctionTrace>();
boolean foundErrorTrace = false;
while (it.hasNext()) {
lft = (List<FunctionTrace>) it.next();
Iterator it_trace = lft.iterator();
while (it_trace.hasNext()) {
FunctionTrace ft = (FunctionTrace) it_trace.next();
int index_from_colons = ft.f_decl.ppt_decl.indexOf(":::");
if (ft.f_decl.ppt_decl.substring(index_from_colons).equals(
":::ERROR")) {
foundErrorTrace = true;
break;
}
}
if (foundErrorTrace) {
break;
}
}
// Return last sequence if no error trace is found
relevantSequence = lft;
if (lft == null) {
System.out.println("Error: Empty list of sequences");
System.exit(-1);
} else if (foundErrorTrace) {
// Remove the "ERROR" trace(s)
Iterator relevantSequence_it = lft.iterator();
while (relevantSequence_it.hasNext()) {
FunctionTrace ft = (FunctionTrace) relevantSequence_it.next();
int index_from_colons = ft.f_decl.ppt_decl.indexOf(":::");
if (ft.f_decl.ppt_decl.substring(index_from_colons).equals(
":::ERROR")) {
break;
} else {
finalFunctionTrace.add(ft);
}
}
} else {
finalFunctionTrace = lft;
}
if (finalFunctionTrace.isEmpty()) {
System.out.println("Error: Empty list of sequences");
System.exit(-1);
}
return finalFunctionTrace;
}
| 9 |
public void cleanUp()
{
try
{
synchronized (this.mutex)
{
while (!pool.isEmpty())
{
pool.get(0).setTaken(true);
Connection c = pool.get(0).getConnection();
c.commit();
//this is a workaround for a bug in some databases that
//won't properly close connections if they're not in autocommit mode
c.setAutoCommit(true);
c.close();
pool.remove(0);
}
this.pool = null;
}
}
catch (Exception e)
{
//We catch all exceptions, there's nothing to be done if we can't close a connection.
LOGGER.log(Level.WARNING, "Exception: ", e);
}
}
| 2 |
void drawSelected(int x, int y, double w, double h) {
if (Main.isBlinked) {
final int border = (int) Math.round(w / 50.0 + 0.5);
g.setColor(SELECTED_COLOR);
g.fillOval(x - border, y - border, (int) w + 2 * border, (int) h + 2 * border);
}
}
| 1 |
@Override
public boolean equals(Object object) {
if (super.equals(object)) {
NBTTagList nbttaglist = (NBTTagList) object;
if (this.type == nbttaglist.type) {
return this.list.equals(nbttaglist.list);
}
}
return false;
}
| 2 |
public void beginRO(String transactionName, long startTime) {
if( transactionMap.containsKey(transactionName) ) {
writeToStreamln("Transaction with same name already"
+ "exists");
return;
}
String output = new StringBuilder("Read only Transaction ")
.append(transactionName).append(" started").toString();
writeToStreamln(output);
//Get a copy of all the variables
Map<String, Integer> variableValuesOld = new HashMap<String, Integer>();
boolean variableFound = false;
for( String variableName : variableSitesMap.keySet() ) {
for( Site site : variableSitesMap.get(variableName) ) {
if( site.isActive() && !siteManager.isVariableDirtyAtSite(variableName, site)) {
variableValuesOld.put(variableName, site.readOld(variableName));
variableFound = true;
break;
}
}
if( !variableFound ) {
//print in output that this read operation will not be possible for this
//variable.
}
}
transactionMap.put(transactionName, new ReadOnlyTransaction
(transactionName, startTime, Transaction.Type.READ_ONlY,
Transaction.State.ACTIVE, variableValuesOld) );
}
| 6 |
@Override
public String toString() {
String desc;
desc = "id3v2TagRestrictions = "+Integer.toBinaryString(getBitmap(null));
return desc;
}
| 0 |
public LayoutStorageAction(String saveString, String restoreString, Automaton a) {
super(saveString, null);
automaton = a;
restoreAction = new AutomatonAction(restoreString, null) {
public void actionPerformed(ActionEvent e) {
graph.moveAutomatonStates();
}
};
restoreAction.setEnabled(false);
}
| 0 |
public String getOldValue(){
return oldValue.getText();
}
| 0 |
public int PrintAge() {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
int age = 0;
birthDate.setTime(this.DOB);
if (birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of
// leap year) then decrement age one year
if ((birthDate.get(Calendar.DAY_OF_YEAR)
- today.get(Calendar.DAY_OF_YEAR) > 3)
|| (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
age--;
// If birth date and todays date are of same month and birth day of
// month is greater than todays day of month then decrement age
} else if ((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH))
&& (birthDate.get(Calendar.DAY_OF_MONTH) > today
.get(Calendar.DAY_OF_MONTH))) {
age--;
}
System.out.println("age is " + age);
return age;
}
| 5 |
public boolean validRay(RayIntersect intersect){
if(intersect == null || Double.isNaN(intersect.getX()) || Double.isNaN(intersect.getZ()) || intersect.getDistance() == 0){
return false;
}
return true;
}
| 4 |
private void displayNext() {
try {
refresh(ekd.next(ek));
} catch (NoNextEmailKontaktFoundException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
e.printStackTrace();
}
}
| 1 |
public ParameterizedTypeImpl(Type ownerType, Type rawType, Type... typeArguments) {
// require an owner type if the raw type needs it
if (rawType instanceof Class<?>) {
Class<?> rawTypeAsClass = (Class<?>) rawType;
boolean isStaticOrTopLevelClass = Modifier.isStatic(rawTypeAsClass.getModifiers())
|| rawTypeAsClass.getEnclosingClass() == null;
checkArgument(ownerType != null || isStaticOrTopLevelClass);
}
this.ownerType = ownerType == null ? null : canonicalize(ownerType);
this.rawType = canonicalize(rawType);
this.typeArguments = typeArguments.clone();
for (int t = 0; t < this.typeArguments.length; t++) {
checkNotNull(this.typeArguments[t]);
checkNotPrimitive(this.typeArguments[t]);
this.typeArguments[t] = canonicalize(this.typeArguments[t]);
}
}
| 8 |
private static void register(Transition transition) {
List<Transition> list = transitions.get();
if (list == null) {
list = new ArrayList<Transition>();
transitions.set(list);
}
list.add(transition);
}
| 1 |
@Override
public boolean equals(Object value) {
if(value instanceof Type){
Type t = (Type) value;
boolean r = true;
r = r && getType().equals(t.getType());
if(getKeyType() !=null){
r = r && getKeyType().equals(t.getKeyType());
}
if(getValueType()!=null){
r = r && getValueType().equals(t.getValueType());
}
return r;
}else if(value instanceof Class){
return equals(this.getType().equals(value));
}
return false;
}
| 7 |
private void dessinerFormesNonTriees(Graphics graphique)
{
Noeud courant = GestionnaireForme.getInstance().getPremierNoeud();
if(courant != null) {
while (courant != null) {
graphique.setColor(courant.getForme().getCouleur());
if (courant.getForme() instanceof Rectangle)
{
Rectangle rect = (Rectangle) courant.getForme();
graphique.fillRect(rect.getX1(), rect.getY1(), rect.getX2() - rect.getX1(), rect.getY2() - rect.getY1());
}
else if (courant.getForme() instanceof Ovale)
{
Ovale ovale = (Ovale) courant.getForme();
graphique.fillOval(ovale.getX1(), ovale.getY1(), ovale.getRayonH()*2, ovale.getRayonV()*2);
}
else if (courant.getForme() instanceof Ligne)
{
Ligne ligne = (Ligne) courant.getForme();
graphique.drawLine(ligne.getX1(), ligne.getY1(), ligne.getX2(), ligne.getY2());
}
courant = courant.getNoeudSuivant();
}
}
}
| 5 |
private void dispatch(String[] commands, PrintWriter writer) {
switch (commands[0]) { //first element of string array must be one of the accepted commands
case AppConstants.ADD:
if (commands.length != 3) {
LOG.warning("Insufficient number of parameters in ADD command");
break;
}
String clientName = commands[1];
String portNumber = commands[2];
int port = 0;
try {
port = Integer.parseInt(portNumber);
boolean status = add(clientName, port);
if (status) {
writer.println(AppConstants.OK);
} else {
writer.println(AppConstants.ERROR);
}
} catch (NumberFormatException nfe) {
LOG.warning("portNumber parameter was not an integer");
}
LOG.log(Level.INFO, "client request serviced: ADD {0} {1}", new Object[]{clientName, portNumber});
break;
case AppConstants.REMOVE:
clientName = commands[1];
remove(clientName);
LOG.log(Level.INFO, "client request serviced: REMOVE {0}", clientName);
break;
case AppConstants.FIND:
clientName = commands[1];
int portNumberResult = find(clientName);
if (portNumberResult == 0) {
writer.println(AppConstants.NOTFOUND);
} else {
writer.println(AppConstants.FOUND + " " + portNumberResult);
}
LOG.log(Level.INFO, "client request serviced: FIND {0}", clientName);
break;
default:
LOG.log(Level.WARNING, "Unknown command: {0}", commands[0]);
}
}
| 7 |
public Entity(EntityType t1,Level l1){
t=t1;
l=l1;
sp = new Sprite(t1);
switch(t){
case BAT:
health=15;
break;
case PLAYER:
health=25;
break;
case SNAKE:
health=25;
break;
case SPIDER:
health=35;
break;
case GOBLIN:
health=75;
break;
case TROLL:
health=150;
break;
case GHOST:
health=190;
break;
case BEHEMOTH:
health=270;
break;
case DRAGON:
health=500;
break;
default:
health=20;
break;
}
maxhealth=health;
spawn();
ai= new AI(this,20);
}
| 9 |
@Override
public List<Event> findEventAll() {
List<Event> list = new ArrayList<Event>();
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
cn = ConnectionHelper.getConnection();
ps = cn.prepareStatement(QTPL_SELECT_ALL);
rs = ps.executeQuery();
while (rs.next()) {
list.add(processResultSet(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { ps.close(); } catch (SQLException e) { e.printStackTrace(); }
try { cn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
return list;
}
| 5 |
private void method289(Object5 class28)
{
for(int j = class28.anInt523; j <= class28.anInt524; j++)
{
for(int k = class28.anInt525; k <= class28.anInt526; k++)
{
Ground class30_sub3 = groundArray[class28.anInt517][j][k];
if(class30_sub3 != null)
{
for(int l = 0; l < class30_sub3.anInt1317; l++)
{
if(class30_sub3.obj5Array[l] != class28)
continue;
class30_sub3.anInt1317--;
for(int i1 = l; i1 < class30_sub3.anInt1317; i1++)
{
class30_sub3.obj5Array[i1] = class30_sub3.obj5Array[i1 + 1];
class30_sub3.anIntArray1319[i1] = class30_sub3.anIntArray1319[i1 + 1];
}
class30_sub3.obj5Array[class30_sub3.anInt1317] = null;
break;
}
class30_sub3.anInt1320 = 0;
for(int j1 = 0; j1 < class30_sub3.anInt1317; j1++)
class30_sub3.anInt1320 |= class30_sub3.anIntArray1319[j1];
}
}
}
}
| 7 |
public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
if (b) {
return true;
}
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
}
| 9 |
private static boolean settNode(int j, int[] noderSett) {
for (int i : noderSett) {
if (i == j) return true;
}
return false;
}
| 2 |
public static void main(String[] args) {
int l=0;int r = 5;int u = 1;int d = 5;
int n=0;
int[][] arr = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int i=0,j=0;
int m = 1;
int num = r*d;
while (n< num){
n++;
switch(m){
case 1:
if(j<r-1){
System.out.println(arr[i][j++]);
}
else{
System.out.println(arr[i++][j]);
r--;
m=2;
}
break;
case 2:
if(i<d-1){
System.out.println(arr[i++][j]);
}
else{
System.out.println(arr[i][j--]);
d--;
m=3;
}
break;
case 3:
if(j>l){
System.out.println(arr[i][j--]);
}
else{
System.out.println(arr[i--][j]);
l++;
m=4;
}
break;
case 4:
if(i>u){
System.out.println(arr[i--][j]);
}
else{
System.out.println(arr[i][j++]);
u++;
m=1;
}
break;
}
}
}
| 9 |
public void selectionInteract(int x, int y)
{
for (Inventory inventory : inventorys) {
if (inventory.getX() >= x && inventory.getY() >= y && inventory.getX() - 20 <= x && inventory.getY() - 20 <= y ) {
if (inventory.getQuantity() > 0) {
holdingItem = !holdingItem;
itemSelection = inventory.getItemCode();
}
}
}
}
| 6 |
@Override
public void open(String name) throws ChannelException {
try {
Socket socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
receiver = new Receiver();
Thread receiverThread = new Thread(receiver);
receiverThread.start();
}
catch (IOException ex) {
throw new ChannelException(ex);
}
}
| 1 |
public void run() {
// get line and buffer from ThreadLocals
SourceDataLine line = (SourceDataLine)localLine.get();
byte[] buffer = (byte[])localBuffer.get();
if (line == null || buffer == null) {
// the line is unavailable
return;
}
// copy data to the line
try {
int numBytesRead = 0;
while (numBytesRead != -1) {
// if paused, wait until unpaused
synchronized (pausedLock) {
if (paused) {
try {
pausedLock.wait();
}
catch (InterruptedException ex) {
return;
}
}
}
// copy data
numBytesRead =
source.read(buffer, 0, buffer.length);
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
| 7 |
protected boolean setEmoteType(String str)
{
str=str.toUpperCase().trim();
if(str.equals("BROADCAST"))
broadcast=true;
else
if(str.equals("NOBROADCAST"))
broadcast=false;
else
if(str.equals("VISUAL")||(str.equals("SIGHT")))
emoteType=EMOTE_TYPE.EMOTE_VISUAL;
else
if(str.equals("AROMA")||(str.equals("SMELL")))
emoteType=EMOTE_TYPE.EMOTE_SMELL;
else
if(str.equals("SOUND")||(str.equals("NOISE")))
emoteType=EMOTE_TYPE.EMOTE_SOUND;
else
if(str.equals("SOCIAL"))
emoteType=EMOTE_TYPE.EMOTE_SOCIAL;
else
return false;
return true;
}
| 9 |
public void jump() {
Cell[][] grid = this.landlord.getGridPanel().getGrid();
// -2 because of fences on the sides
int width = this.landlord.getGridPanel().getW();
int height = this.landlord.getGridPanel().getH();
// +1 because of the fence on the side
int x = (int) (Math.random() * width);
int y = (int) (Math.random() * height);
System.out.println(x);
System.out.println(y);
if (grid[x][y].getOccupant() instanceof Player
|| grid[x][y] instanceof Fence) {
jump(); // keeps trying until random location does not contain
// Player or Fence
} else move(x - getX(), y - getY());
}
| 2 |
*/
private boolean checkSessionLapRawData() {
// Gestion des flashbacks dans le même tour, bug
// FIXME : Not Working
boolean ret = true;
try {
if (this.curRawDataSet != null
&& this.curRawDataSet.size() > 0
&& this.curRawDataSet.last().getLap().equals(this.curRawData.getLap())
&& this.curRawDataSet.last().getLapTime() > this.curRawData.getLapTime()) {
this.slf4j.info("Detection Rollback");
Collection<RawData> toRemove = this.curRawDataSet.tailSet(this.curRawDataSet.floor(this.curRawData));
this.curRawDataSet.removeAll(toRemove);
}
} catch (Exception ex) {
ret = false;
}
return ret;
}
| 5 |
public void sendDebug( String d ) // Temporary Method to send debug
// information to my username.
{
for ( Player p : getServer().getOnlinePlayers() )
{
if ( p.isOp() )
p.sendMessage( ChatColor.DARK_AQUA + "[iNations Debug] " + ChatColor.WHITE + d );
}
}
| 2 |
@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 Servico)) {
return false;
}
Servico other = (Servico) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
| 5 |
private int getMinIndex(char[] arr, int i) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex])
minIndex = j;
}
return minIndex;
}
| 2 |
private Window wdg() {
Widget wdg = UI.instance.getWidget(remote_id);
if (wdg instanceof Window) {
return (Window) wdg;
} else {
return null;
}
}
| 1 |
@Test
public void findDuplicateTypeHand_whenTwoPairsExist_returnsTwoPairPlusHighestKicker() {
Hand hand = findDuplicateTypeHand(twoSixesTwoFoursAceKicker());
assertEquals(HandRank.TwoPair, hand.handRank);
assertEquals(Rank.Six, hand.ranks.get(0));
assertEquals(Rank.Four, hand.ranks.get(1));
assertEquals(Rank.Ace, hand.ranks.get(2));
}
| 0 |
private String getStrFromInputStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String inputLine;
try {
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
} finally {
if(reader != null) {
reader.close();
}
}
return response.toString();
}
| 2 |
public void update()
{
Vector3f playerDistance = transform.getPosition().sub(Transform.getCamera().getPos());
Vector3f orientation = playerDistance.normalized();
float distance = playerDistance.length();
float angle = (float)Math.toDegrees(Math.atan(orientation.getZ()/orientation.getX()));
if(orientation.getX() > 0)
angle = 180 + angle;
transform.setRotation(0,angle + 90,0);
if(distance < PICKUP_THRESHHOLD && Level.getPlayer().getHealth() < 100)
{
Level.getPlayer().damage(-HEAL_AMOUNT);
Level.removeMedkit(this);
AudioUtil.playAudio(pickupNoise, 0);
}
}
| 3 |
public World isAndGetCopyWorld(World world, Player player){
String playerName = "_" + player.getName();
new_name = world.getName();
folderName = "/" + new_name;
if (!(new_name.endsWith(playerName))){
new_name = new_name + playerName;
if (plugin.mainWorlds.contains(world.getName())){
if (playerWorlds(player).size() > 0 && !playerWorlds(player).get(0).endsWith(new_name)){
world = Bukkit.getWorld(plugin.lobbyWorld);
}else{
World world_old = world;
//copy file from inactive if exists
File source = new File("inactive/" + new_name);
if (source.exists()){
adventourmovefolder.main("inactive/" + new_name, new_name);
}
World new_world = Bukkit.getWorld(new_name);
if (new_world == null){
AdvenTourCopyFolder foldercopy = new AdvenTourCopyFolder(plugin);
foldercopy.main(playerName, folderName);
world = WorldCreator.name(new_name).createWorld();
}else{
world = new_world;
}
world.setKeepSpawnInMemory(false);
//Load copy world settings START
world = loadCopyWorldSettings(world_old, world);
//Load copy world settings STOP
}
}
}
return world;
}
| 6 |
@Override
public String toImplementationSyntax(TableModel tableModel, String definition)
{
String newDefinition = definition;
StringTokenizer tokens = new StringTokenizer(newDefinition,
getSyntax().getDelimiters());
String token;
String cellID = null;
String fields = null;
String modelName = model instanceof JeksTableModel ? ((JeksTableModel) model).name : "";
while (tokens.hasMoreTokens())
{
token = tokens.nextToken();
Pattern pattern = Pattern.compile("(([^!]+)!)?([^!]+)!(.+)");
Matcher matcher = pattern.matcher(token);
if(matcher.matches())
{
String match1 = matcher.group(2);
String match2 = matcher.group(3);
String match3 = matcher.group(4);
if(match1 != null && state.getModel(match1) != null)
{
cellID = match1 + "!" + match2;
fields = match3;
}
else if(match1 != null)
{
cellID = match1;
fields = match2 + "!" + match3;
}
else if(state.getModel(match2) == null)
{
cellID = match2;
fields = match3;
}
if(cellID != null)
{
try
{
newDefinition = newDefinition.replace(token, "DEREF(\"" + modelName + "\","
+ cellID + ",\"" + fields + "\")");
} catch (IndexOutOfBoundsException e)
{
// throw new CompilationException();
}
}
}
cellID = null;
fields = null;
}
return newDefinition;
}
| 9 |
public static PathConvexShape findGroundShape(Point3f guyPosition, PathLevel pathLevel) {
List<PathConvexShape> pathConvexShapeList = pathLevel.getPossibleShapes(guyPosition.x, guyPosition.z);
if (pathConvexShapeList == null) {
return null;
}
double highestPossibleY = guyPosition.y;
PathConvexShape closestShape = null;
double smallestYDiff = Double.MAX_VALUE;
for (PathConvexShape curPathConvexShape : pathConvexShapeList) {
if (curPathConvexShape.xzPath.contains(guyPosition.x, guyPosition.z)) {
Point2f guyPoint2f = new Point2f(guyPosition.x, guyPosition.z);
int planeVertexIndex = curPathConvexShape.vertexIndexPointer.get(0);
PathVertex planeVertex = curPathConvexShape.parentMesh.pathVertexList.get(planeVertexIndex);
double yValue = MathUtils.calculatePlaneY(guyPoint2f, planeVertex, curPathConvexShape.planeGradient);
double yDiff = highestPossibleY - yValue;
if (yDiff >= 0 && yDiff < smallestYDiff) {
smallestYDiff = yDiff;
closestShape = curPathConvexShape;
}
}
}
return closestShape;
}
| 5 |
public void progressStart()
{
if (block == 0) {
}
++block;
}
| 1 |
@Override
public void documentRemoved(DocumentRepositoryEvent e) {}
| 0 |
public void renderWorld(){
for(int y = 0; y < worldHeight; y++){
for(int x = 0; x < worldWidth; x++){
Tile tile = Tile.getTileById(mapData.get((y * worldHeight) + x));
tile.render(x * tileSize, y * tileSize);
}
}
renderLights();
renderSides();
renderEntities();
}
| 2 |
public static MultipleChoiceQuestion getMultipleChoiceQuestionByXMLElem(XMLElement root, Quiz quiz, int pos) {
int quizID = quiz.quizID;
int position = pos;
Object question = null;
Object answer = null;
double score = 10;
ArrayList<String> questionList = new ArrayList<String>();
for (int i = 0; i < root.childList.size(); i++) {
XMLElement elem = root.childList.get(i);
if (elem.name.equals("query")) {
questionList.add(elem.content);
} else if (elem.name.equals("option")) {
questionList.add(elem.content);
if (elem.attributeMap.containsKey("answer"))
answer = elem.content;
} else if (elem.name.equals("score")) {
score = Double.parseDouble(elem.content);
} else {
System.out.println("Unexpected field in multiple choice question : " + elem.name);
}
}
question = questionList;
return new MultipleChoiceQuestion(quizID, position, question, answer, score);
}
| 5 |
public Game(World world, BrainParser b1, BrainParser b2){
// ArrayList<Instruction> brain1 = new BrainParser("src/cleverbrain3.brain").parseBrain();
// ArrayList<Instruction> brain2 = new BrainParser("src/cleverbrain4.brain").parseBrain();
ArrayList<Instruction> brain1 = b1.parseBrain();
ArrayList<Instruction> brain2 = b2.parseBrain();
this.world = world;
int antR = 0;
int antB = 0;
for(int x = 0; x<world.getRows(); x++){
for(int y = 0; y<world.getColumns(); y++){
Cell c = world.getCell(x,y);
if(c.getIsRAntHill()){
c.setAnt(new Ant(Colour.RED, antR, brain1));
cellsToUpdateList.add(new Point(x,y));
antR++;
}
else if(c.getIsBAntHill()){
c.setAnt(new Ant(Colour.BLACK, antB, brain2));
cellsToUpdateList.add(new Point(x,y));
antB++;
}
}
}
}
| 4 |
private ArrayList<Action> findPathsFromActionMap(
int goalRowID, int goalColID, int goalDrcID) {
//int startRowID,int startColID,int startDrcID) {
ArrayList<Action> actions = new ArrayList<>();
//Find the action min distance
int rowID = goalRowID;
int colID = goalColID;
int drcID = goalDrcID;
while(preAction[rowID][colID][drcID] != null){
Action currentAction = preAction[rowID][colID][drcID];
actions.add(0, currentAction);
if(currentAction.equals(Action.TURN_LEFT)){
drcID = (drcID + 1) % (OREIT_MAX + 1);
}else if(currentAction.equals(Action.TURN_RIGHT)){
drcID = (drcID + OREIT_MAX) % (OREIT_MAX + 1);
}else{
//currentAction == MOVE_FORWARD
if(drcID == NORTH_INDEX){
rowID++;
}else if(drcID == SOUTH_INDEX){
rowID--;
}else if(drcID == EAST_INDEX){
colID++;
}else{
//RIGHT Orientation
colID--;
}
}
}
// assert(rowID == startRowID && colID == startColID && drcID == startDrcID);
return actions;
}
| 6 |
private ResourceManager()
{
m_textTileMap = new HashMap<Integer, TileResource>();
m_objectsMap = new HashMap<Integer, MovableResource>();
try {
InputStream is = getClass().getResourceAsStream(RESOURCES_FILE);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("TileTexture");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
ResTextureTileBaseFolder = ((Element)(eElement.getParentNode())).getAttribute("dir");
String name = eElement.getAttribute("name");
int id = Integer.valueOf(eElement.getAttribute("id"));
String fileName = eElement.getAttribute("file");
String animatedFlag = eElement.getAttribute("animated");
if(animatedFlag != null)
{
if(animatedFlag.equals("true"))
{
name = name + " (anim\u00E9)";
}
}
TileResource tile = new TileResource(name, id, ResTextureTileBaseFolder, fileName);
m_textTileMap.put(tile.getId(), tile);
}
}
nList = doc.getElementsByTagName("Object");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
ResObjectsBaseFolder = ((Element)(eElement.getParentNode())).getAttribute("dir");
String name = eElement.getAttribute("name");
int id = Integer.valueOf(eElement.getAttribute("id"));
String fileName = eElement.getAttribute("file");
String animatedFlag = eElement.getAttribute("animated");
if(animatedFlag != null)
{
if(animatedFlag.equals("true"))
{
name = name + " (anim\u00E9)";
}
}
MovableResource tile = new MovableResource(name, id, ResObjectsBaseFolder, fileName);
m_objectsMap.put(tile.getId(), tile);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erreur RessourceManager!\n"+e.toString(), "Exception", JOptionPane.ERROR_MESSAGE);
}
}
| 9 |
public List<Vak> getVakkenVanStudent(long studentId) {
List<Vak> vakken = new ArrayList<Vak>();
List<Long> klasIds = new ArrayList<Long>();
List<Long> vakIds = new ArrayList<Long>();
try {
PreparedStatement prepareStatement = manager
.prepareStatement("SELECT klas_id FROM leerling_klas WHERE leerling_id = ?");
prepareStatement.setLong(1, studentId);
ResultSet resultSet = prepareStatement.executeQuery();
while (resultSet.next()) {
klasIds.add(resultSet.getLong(1));
}
PreparedStatement prepareStatement2 = manager
.prepareStatement("SELECT vak_id FROM vak_klas WHERE klas_id = ?");
for (Long klasId : klasIds) {
prepareStatement2.setLong(1, klasId);
ResultSet resultSet2 = prepareStatement2.executeQuery();
while (resultSet2.next()) {
vakIds.add(resultSet2.getLong(1));
}
}
for (Long vakId : vakIds) {
vakken.add(getVak(vakId));
}
return vakken;
} catch (SQLException e) {
e.printStackTrace();
return vakken;
}
}
| 5 |
void updateCacheView() {
TlvCacheInstance cache = cacheModel.getCacheInstance();
TlvCacheState cacheState = (cache == null ? null : cache.getState());
buttonInitCache.setEnabled(cacheState == null || cacheState == TlvCacheState.CREATED || cacheState == TlvCacheState.STOPPED);
buttonStartCache.setEnabled(cacheState == TlvCacheState.CREATED);
buttonStopCache.setEnabled(cacheState == TlvCacheState.STARTING || cacheState == TlvCacheState.WORKING);
buttonShutdownCache.setEnabled(cacheState == TlvCacheState.STARTING || cacheState == TlvCacheState.WORKING || cacheState == TlvCacheState.STOPPING);
buttonPut.setEnabled(cacheState == TlvCacheState.WORKING);
buttonGet.setEnabled(cacheState == TlvCacheState.WORKING);
buttonRemove.setEnabled(cacheState == TlvCacheState.WORKING);
labelCacheState.setText(cacheModel.getCacheStateDesciption());
if (cache != null) {
( (CacheViewTableModel) tableMemoryCache.getModel()).setData(cache.getMemoryCacheContentSnapshot());
( (CacheViewTableModel) tableFsCache.getModel()).setData(cache.getFsCacheContentSnapshot());
}
}
| 7 |
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
| 6 |
public void setDimension(Dimension dim, int size) {
if (dim.getSize() == size) return;
dim.setSize(size);
Set param_set = getParamsForDim(dim);
for (Iterator i = param_set.iterator(); i.hasNext();) {
Parameter param = (Parameter)(i.next());
param.resize();
}
history.add (new ParameterSetHistory (dim, "changed size to " + size));
}
| 2 |
public static void toggleEditableAndClearForSingleNode(Node node, CompoundUndoable undoable) {
toggleEditableForSingleNode(node, undoable);
for (int i = 0, limit = node.numOfChildren(); i < limit; i++) {
clearEditableForSingleNode(node.getChild(i), undoable);
}
}
| 1 |
public static void setPageRanges(PrintRequestAttributeSet set, PageRanges ranges) {
if (ranges != null) {
set.add(ranges);
} else {
set.remove(PageRanges.class);
}
}
| 1 |
public void mousePressed(MouseEvent e) {
if (image !=null && tileset) {
if (e.getX()>=0 && e.getX() <=image.getWidth() && e.getY() >= 0 && e.getY() <= image.getHeight()) {
x0=e.getX()/(8*zoom);
y0=e.getY()/(8*zoom);
}
}
}
| 6 |
public void render(Graphics g) {
if (active) {
if (img != null) {
boolean hover = checkMouse(InputHandler.getInstance().getMouseHoverPoint());
if (hover)
g.drawImage(img, x, y, width, height, Color.darkGray, null);
else
g.drawImage(img, x, y, width, height, null);
}
if (text != null) {
g.setColor(Color.white);
g.drawRect(x, y, width, height);
g.drawString(text, x + 10, y + 15);
}
}
}
| 4 |
public Path getBestPath()
{
if(Ways.isEmpty())
{
return(new Path());
}
float length = Ways.elementAt(0).getDistance();
int p = 0;
//Besten Pfad ausrechnen
for(int i=0; i<Ways.size(); i++)
{
if(Ways.elementAt(i).getDistance() < length)
{
p = i;
}
}
return(Ways.elementAt(p));
}
| 3 |
public static void main(String args[]) throws Exception{
NavigableSet nav = new TreeSet<>();
nav.add("A");
nav.add("B");
nav.add("C");
nav.add("D");
nav.add("E");
// Testing flag inclusive and exclusive
SortedSet tail = (NavigableSet)nav.tailSet("A");
NavigableSet head = nav.headSet("E",true );
NavigableSet sub = nav.subSet("A",false,"E",false);
System.out.print(head.ceiling("B"));
System.out.print(head.higher("B"));
System.out.print(head.floor("B"));
System.out.println(head.lower("B"));
//BCBA
for (Object object : tail) {
System.out.print(object);
}
System.out.println();
for (Object object : head) {
System.out.print(object);
}
System.out.println();
for (Object object : sub) {
System.out.print(object);
}
}
| 3 |
@Override
public void handleModelChangeEvent(ModelChangeEvent e){
displayMessage(e.getMessage());
drawList = e.getDrawable();
for(Drawable2D drawable : drawList) {
if(drawable.getClass().equals(Player2D.class)) {
player = (Player2D)drawable;
}
if(drawable.getClass().equals(Room2D.class)) {
mapArea.setCurrentRoom((Room)drawable);
}
if(drawable.getClass().equals(Item2D.class)){
if(player.collidesWith(drawable)){
collidingWithObject = drawable;
}
}
}
drawArea.updateDrawable(drawList);
}
| 5 |
@Override
public void cycler() {
// Choices
String[] speedModes = { "Easy", "Normal", "Hard" };
// Input System
String speedSelect = (String) JOptionPane.showInputDialog(null,
"Choose Difficulty", "RunBitMan 2", JOptionPane.PLAIN_MESSAGE,
null, speedModes, "Easy");
long speed = 100;
if ((speedSelect != null) && (speedSelect.length() > 0)) {
if (speedSelect.equals("Easy")) {
speed = 45;
}
if (speedSelect.equals("Normal")) {
speed = 30;
}
if (speedSelect.equals("Hard")) {
speed = 20;
}
} else {
System.exit(0);
}
gameRenderObjects();
gameRenderMovement();
gameRenderMobs();
paintScreen();
// Give some time to prepare.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
// While Loop to Repaint the Screen
while (true) {
gameRenderObjects();
gameRenderMovement();
gameRenderMobs();
paintScreen();
gameRenderHitbox(500);
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
}
}
}
| 8 |
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
File outFile = new File("/resources/");
WebSitemapGenerator wsg;
try {
wsg = new WebSitemapGenerator("http://localhost:8080/web/", outFile);
for (int i = 0; i < 60000; i++)
wsg.addUrl("http://localhost:8080/web/doc" + i + ".html");
wsg.write();
wsg.writeSitemapsWithIndex(); // generate the sitemap_index.xml
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "home";
}
| 2 |
public void initialisationFinaleProvince(){
for(Province p : this.hashProvince){
switch(p.getNom()){
case "Chugoku" :
case "Kanto" : p.setTroupe(new Troupes("Samouraï", "Vert"));
break;
case "Chubu" :
case "Kansai" : p.setTroupe(new Troupes("Shinobi", "Noir"));
break;
case "Hokkaido" :
case "Shikoku" : p.setTroupe(new Troupes("Sohei", "Orange"));
break;
case "Kyushu" :
case "Tohoku" : p.setTroupe(new Troupes("Bushi", "Bleu"));
break;
}
}
}
| 9 |
public final void unlinkSub() {
if (previousNode == null) {
} else {
previousNode.nextNode = nextNode;
nextNode.previousNode = previousNode;
nextNode = null;
previousNode = null;
}
}
| 1 |
private void expand1(byte[] src, byte[] dst) {
for(int i=1,n=dst.length ; i<n ; i+=8) {
int val = src[1 + (i >> 3)] & 255;
switch(n-i) {
default: dst[i+7] = (byte)((val ) & 1);
case 7: dst[i+6] = (byte)((val >> 1) & 1);
case 6: dst[i+5] = (byte)((val >> 2) & 1);
case 5: dst[i+4] = (byte)((val >> 3) & 1);
case 4: dst[i+3] = (byte)((val >> 4) & 1);
case 3: dst[i+2] = (byte)((val >> 5) & 1);
case 2: dst[i+1] = (byte)((val >> 6) & 1);
case 1: dst[i ] = (byte)((val >> 7) );
}
}
}
| 8 |
public boolean adisyonEkle(String masaAdi,String urunAdi,int miktar){
Siparis siparis = new Siparis(new Urun().urunBul(urunAdi), miktar);
Bilgisayar b = masaBul(masaAdi);
if(b!=null){
if(mutlakkafe.MutlakKafe.mainCont.getUrunCont().urunSat(siparis.getUrun().getUrunID(), miktar)){
if(b.adisyonEkle(siparis)){
return true;
}
}
}else{
//masa olmadan adisyon kes (yoldan geçene)
}
return false;
}
| 3 |
@Override
public void initializeNorm()
{
checkingNorms();
for ( Action action : getAllActions().values() )
{
if ( action.getNormType() != null ) // Only action linked with deontic concept will goona be setted
{
if ( action.getNormType() == NormType.OBLIGATION )
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.OBLIGATION );
}
else if ( action.getNormType() == NormType.PROHIBITION )
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.PROHIBITION );
}
else
{
if ( getPlayer().containAction( action.getName() ) )
getPlayer().getAction( action.getName() ).setNormType( NormType.PERMISSION );
}
}
}
}
| 7 |
public void start() {
if(!fTimer.isRunning()) {
if(fAnimationTarget == null) {
throw new IllegalStateException("Animation target is not set!");
}
fAnimationStartTime = System.nanoTime() / 1000000;
final Runnable r = new Runnable() {
public void run() {
fAnimationTarget.begin(AnimationTimer.this);
}
};
if(SwingUtilities.isEventDispatchThread()) {
r.run();
} else {
SwingUtilities.invokeLater(r);
}
fTimer.start();
}
}
| 3 |
public void runScript(String configFileName)
{
int lineNum = 0;
try {
BufferedReader in = new BufferedReader(new FileReader(configFileName));
String line;
while ((line = in.readLine())!=null) {
lineNum++;
if (!line.startsWith("#")) {
String command = null;
List args = new ArrayList();
StringTokenizer tok = new StringTokenizer(line);
if (tok.hasMoreTokens()) {
command = tok.nextToken();
}
while (tok.hasMoreTokens()) {
args.add( tok.nextToken() );
}
if (command!=null) {
if (echoCommands) System.out.println("exec: "+line);
execCommand(command,args);
}
}
}
} catch (Exception e) {
System.out.println("Error: "+configFileName+" line "+lineNum+": "+e.toString());
e.printStackTrace();
return;
}
}
| 7 |
public static byte[] compressRow(byte[] b) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte active = b[0];
byte same = (byte) -127;
for (int i = 1; i < b.length; i++) {
if (b[i] == active && same < 127) same += 1;
else {
baos.write(new byte[] { same, active });
same = -127;
active = b[i];
}
}
baos.write(new byte[] { same, active });
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
| 4 |
public boolean checkWin() {
boolean gameWon = false;
boolean gameWonBackDiagonal = false;
boolean gameWonVertical = false;
boolean gameWonForwardDiagonal = false;
boolean gameWonHorizontal = false;
for (int j=0; j<WIDTH ; j++) {
for (int i=0; i<HEIGHT ; i++) {
if (m_Pieces[j][i].getPieceColour() != EMPTY_PIECE) {
gameWonBackDiagonal = checkBackDiagonal(j,i,m_Pieces);
if (gameWonBackDiagonal) {
gameWon = true;
return gameWon;
}
gameWonVertical = checkVertical(j,i,m_Pieces);
if (gameWonVertical) {
gameWon = true;
return gameWon;
}
gameWonForwardDiagonal = checkForwardDiagonal(j,i,m_Pieces);
if (gameWonForwardDiagonal) {
gameWon = true;
return gameWon;
}
gameWonHorizontal = checkHorizontal(j,i,m_Pieces);
if (gameWonHorizontal) {
gameWon = true;
return gameWon;
}
}
}
}
return gameWon;
}
| 7 |
public Object displayCreateActivityPrompt() throws IOException{
Calendar cal = Calendar.getInstance();
Date date = cal.getTime(); //set to today
Date duration = null;
String title = "";
String note = "";
Activity activity = new Activity(userName);
System.out.println("Record an activity"); //initial prompt title
System.out.println("For today? Enter Y or N"); //default to today for usability
String response = scanner.nextLine();
if(response.equals("Y") || response.equals("y") ) //get today's activity's duration
{
title = this.getTextInput("title");
if (title == null) return null;
duration = this.getDuration();
note = this.getTextInput("note");
}
else if (response.equals("N") || response.equals("n")) //get activity's date
{
System.out.println("Enter an activity for...");
System.out.println("(Y)esterday");
System.out.println("A date in MMDDYYYY format");
response = scanner.nextLine();
if (response.equals("Y") || response.equals("y"))
{
cal.add(Calendar.DAY_OF_MONTH, -1);
date = cal.getTime();
title = this.getTextInput("title");
duration = this.getDuration();
note = this.getTextInput("note");
}
}
else
{
this.ungracefulExit();
}
//set activity's user-entered parameters
activity.setTitle(title);
activity.setNote(note);
activity.setDuration(duration);
activity.setDate(date);
//add activity to list
this.activityList.addObject(activity);
//save prompt not working as expected
/*System.out.println("Save this activity now? Y/N");
response = scanner.nextLine();
if(response.equals("Y") || response.equals("y") )
{
this.saveActivities();
}*/
return null;
}
| 7 |
public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE)
|| (object instanceof String && ((String) object)
.equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
}
| 6 |
public static char boardIntToString(boolean[] value) {
// System.out.print("boardToString: " + Integer.toBinaryString(value) +
// " ");
char ret = 'r';
if (Conversions.isWall(value)) {
ret = Constants.S_WALL;
} else if (Conversions.isPlayer(value) && Conversions.isGoal(value)) {
ret = Constants.S_PLAYER_ON_GOAL;
} else if (Conversions.isBox(value) && Conversions.isGoal(value)) {
ret = Constants.S_BOX_ON_GOAL;
} else if (Conversions.isBox(value)) {
ret = Constants.S_BOX;
} else if (Conversions.isPlayer(value)) {
ret = Constants.S_PLAYER;
} else if (Conversions.isGoal(value)) {
ret = Constants.S_GOAL;
} else if (Conversions.isFreeSpace(value)) {
ret = Constants.S_FREE_SPACE;
}
// System.out.println(ret);
return ret;
}
| 9 |
public void setSector(String sector) {
addressCompany.setSector(sector);
}
| 0 |
protected synchronized void executeQuieries() {
if (!m_queries.isEmpty())
{
String query = null;
Statement statement = null;
final Connection connection = getConnection();
try {
if (connection == null) {
Utilities.outputError("Could not connect to database.");
return;
}
statement = connection.createStatement();
Iterator<String> queryItr = m_queries.iterator();
while (queryItr.hasNext()) {
query = queryItr.next();
statement.addBatch(query);
}
statement.executeBatch();
statement.close();
connection.close();
m_queries.clear();
} catch (SQLException e) {
final String errorMessage = e.getMessage().toLowerCase();
if (!(errorMessage.contains("locking") || errorMessage.contains("locked"))) {
Utilities.outputError("Batch Exception: Exception whilst executing");
Utilities.outputError(query);
e.printStackTrace();
m_queries.remove(query);
}
try {
statement.close();
connection.close();
} catch (SQLException ce) {}
}
}
}
| 7 |
private DefaultTreeModel parseTree(String string, Grammar grammar,
LLParseTable table, List nodes) {
int p = 0;
string = string + "$";
Stack stack = new Stack();
MutableTreeNode root = new DefaultMutableTreeNode(grammar
.getStartVariable());
stack.push(root);
nodes.add(root);
DefaultTreeModel tree = new DefaultTreeModel(root);
String read = string.substring(p, p + 1);
p++;
while (!stack.empty()) {
String top = stack.peek().toString();
if (pane.grammar.isTerminal(top)) {
if (top.equals(read)) {
stack.pop();
read = string.substring(p, p + 1);
p++;
} else {
return tree;
}
} else if (pane.grammar.isVariable(top)) {
String entry = get(top, read);
if (entry == null) {
return tree;
} else {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) stack
.pop();
if (entry.length() == 0) {
MutableTreeNode child = new DefaultMutableTreeNode(
Universe.curProfile.getEmptyString());
node.insert(child, 0);
nodes.add(child);
} else {
for (int i = entry.length() - 1; i >= 0; i--) {
MutableTreeNode child = new DefaultMutableTreeNode(
entry.substring(i, i + 1));
node.insert(child, 0);
stack.push(child);
nodes.add(child);
}
}
}
} else {
// This should never happen.
}
}
return tree;
}
| 7 |
public int correSimulacion(Estrategia estr, Datos dato, String id,
int max_time) {
Nodo nodo = null;
time = 0;
if (true) {
estado = new Estado(estr);
for (Sensor x : estr.getSensores())
x.setEstado(estado);
estr.setEstado(estado);
estado.initEstado();
addAleatOponents(MAX_ENEMIGOS);
}
Logger.debug("Comenzando. Quedan:" + estado.presas + " presas libres");
try {
while ((nodo = estado.busca()) != null && estado.presas > 0
&& max_time-- > 0) {
time++;
Logger.debug("Posicion: " + estado.getActual()
+ "\nRestantes: " + estado.presas);
estado.guardaValoresEstado(dato, id, MAX_ENEMIGOS);
estado.updateEstado(nodo);
}
Logger.debug("Simulacion terminada: " + nodo.toString()
+ " Presas capturadas: " + (MAX_ENEMIGOS - estado.salvadas)
+ "\n" + "Presas salvadas: " + estado.salvadas);
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
return (MAX_ENEMIGOS - estado.salvadas);
}
| 6 |
private Node<U, T> buildSubtree(List<T> intervalList, int low, int high) {
U point = intervalList.get((low + high) >>> 1).getLow();
Node<U, T> result = new Node<U, T>(point);
int lowPointer = low;
int highPointer = high;
for (int j = low; j < highPointer; j++) {
T next = intervalList.get(j);
if (next.getHigh().compareTo(point) < 0) {
Collections.swap(intervalList, lowPointer++, j);
} else if (next.getLow().compareTo(point) > 0) {
highPointer = j;
}
}
if (low < lowPointer) {
result.setLeft(buildSubtree(intervalList, low, lowPointer));
}
if (highPointer < high) {
result.setRight(buildSubtree(intervalList, highPointer, high));
}
return result;
}
| 5 |
@Override
public void setMaximum(int i) {bar.setMaximum(i);}
| 0 |
private static String getText(final List<List<Symbol>> board) {
List<WinnerChecker> winnerCheckers = Arrays.asList(new HorizontalChecker(), new VerticalChecker(new Column()),
new VerticalChecker(new DiagonalIncreasing()),
new VerticalChecker(new DiagonalDecreasing()));
// "X won", "O won", "Draw", "Game has not completed"
String text = "Draw";
for (int i = 0; i < board.size(); i++) {
List<Symbol> row = board.get(i);
for (int j = 0; j < row.size(); j++) {
if (row.get(j) == Symbol.EMPTY) {
text = "Game has not completed";
continue;
}
for (WinnerChecker winnerChecker : winnerCheckers) {
if (winnerChecker.isWinner(i, j, board)) {
if (!Arrays.asList(Symbol.O, Symbol.X).contains(winnerChecker.symbol)) {
throw new RuntimeException(String.format("Illegal symbol for winner: %s (%s)",
winnerChecker.symbol, winnerChecker));
}
return winnerChecker.symbol == Symbol.O ? "O won" : "X won";
}
}
}
}
return text;
}
| 7 |
public boolean equalsInContent(Deck d) {
if (this.cardArray.length != d.cardArray.length)
return false;
for (int i = 0; i < cardArray.length; i++) {
if (d.binarySearch(cardArray[i]) == -1) {
return false;
}
}
return true;
}
| 3 |
public James()
{
super("James", 6500, 250, 50, 80, as);
as.setSkill(0, "Work Hard", 100, 20, "James works very hard in class.");
as.setSkill(1, "Wise", 200, 45, "James is exceptionally wise.");
as.setSkill(2, "Program", 500, 100, "James creates a deadly program.");
as.setSkill(3, "High Mark", 4500, 180, "James receives a perfect mark.");
}
| 0 |
private int jjMoveStringLiteralDfa7_1(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return 7;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return 7;
}
switch(curChar)
{
case 69:
case 101:
return jjMoveStringLiteralDfa8_1(active0, 0x1000L);
case 78:
case 110:
if ((active0 & 0x400L) != 0L)
return jjStopAtPos(7, 10);
break;
case 80:
case 112:
return jjMoveStringLiteralDfa8_1(active0, 0x800L);
default :
return 8;
}
return 8;
}
| 9 |
public GUI() {
setTitle("Calculator");
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null); // Center the GUI
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/icon.png"));
this.setIconImage(icon.getImage());
JPanel panel = new JPanel();
panel.setLayout(new GroupLayout(panel));
add(panel);
output = new JTextField("0");
output.setBounds(PADDING, PADDING, WIDTH - PADDING * 2 - FRAME_PADDING, 40);
output.setFont(new Font(Font.DIALOG_INPUT, Font.PLAIN, 20));
output.setHorizontalAlignment(JTextField.RIGHT);
output.setCaretPosition(output.getText().length());
output.addKeyListener(new KeyHandler());
panel.add(output);
solver = new Solver(this);
addButtonSet(panel, functionButtons, 2, PADDING);
addButtonSet(panel, numberButtons, 3, CENTER_PADDING_X);
addButtonSet(panel, operatorButtons, 2, RIGHT_PADDING_X);
}
| 0 |
@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 Funcao)) {
return false;
}
Funcao other = (Funcao) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
| 5 |
@Override
public boolean hesapBilgiGuncelle(String kullaniciAdi, Kisi kisi) {
int sonuc = JOptionPane.showConfirmDialog(null, kullaniciAdi +
" isimli müşteri bilgilerini değiştirmek istediğinize emin misiniz?", "Müşteri Güncelle",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(sonuc == JOptionPane.NO_OPTION)
return false;
if(kullaniciAdi.equals("")){
JOptionPane.showMessageDialog(null, "Kullanici adı boş olamaz!",
"Hata", JOptionPane.ERROR_MESSAGE);
return false;
}
try {
Musteri m = (Musteri) kisi;
if (m.hesapBilgiGuncelle(kullaniciAdi, kisi)) {
JOptionPane.showMessageDialog(null, "Müşteri bilgileri güncellendi!",
"Müşteri Sil", JOptionPane.INFORMATION_MESSAGE);
return true;
}
JOptionPane.showMessageDialog(null, kullaniciAdi + " isimli müşteri bulunamadı!",
"Hata", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Hata oluştu kişi bilgileri güncellenemiyor!", "Hata", JOptionPane.ERROR_MESSAGE);
}
return false;
}
| 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.