method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
7449cc56-04e7-4edf-a897-d6ce8e2f73d3
| 9
|
@Override
public void run() {
progressBar.setMaximum(gen.getTotal().intValue());
//length is the number of permutations starting with Albany, which are always at the beginning
int length = (gen.getTotal().intValue())/numCities;
int progress = 0;
double shortestDistance = Double.POSITIVE_INFINITY;
for(int i = 0; i<length; i++) {
if(stopRequested) break;
double totalDistance = 0;
City[] route = new City[numCities+1];
int[] perm = gen.getNext();
for(int index : perm) {
if(stopRequested) break;
route[index] = cities.get(perm[index]);
}
route[route.length-1] = cities.get(0); //end up at Albany.
for(int city = 0; city<route.length-1; city++) {
if(stopRequested) break;
City from = route[city];
City to = route[city+1];
totalDistance += from.calculateDistance(to);
progress += 1;
progressBar.setValue(progress);
}
if(totalDistance < shortestDistance) {
shortestDistance = totalDistance;
shortestRoute = route;
}
canvas.repaint();
}
if(!stopRequested) {
message = "Best route:";
for(City city : shortestRoute) {
message += " "+city.getName()+" ";
}
}
field.setText(message);
}
|
b0355822-08a7-4d6e-b795-76439d565b3c
| 3
|
private void durchlaufe(int pStartknoten, int[] pBesucht) {
if (pBesucht[pStartknoten] != 1) {
System.out.println(pStartknoten);
}
pBesucht[pStartknoten] = 1;
int[] lNachbar = this.nachbarKnoten(pStartknoten);
for (int i = 0; i < lNachbar.length; i++) {
if (pBesucht[lNachbar[i]] != 1) {
this.durchlaufe(lNachbar[i], pBesucht);
}
}
}
|
228c6341-c5a6-433d-aa12-181620ed2b08
| 7
|
public void render(GameContainer gc, Graphics gr) throws SlickException {
for (int i = 0; i < entityList.size(); i++) {
if (entityList.get(i) instanceof Skill) {
entityList.get(i).renderSkill(gc, null, gr, ((Skill) entityList.get(i)).isOnCooldown());
if (((Skill) entityList.get(i)).isOnCooldown()) {
ttf.drawString(entityList.get(i).getPosition().x, entityList.get(i).getPosition().y + 14,
String.valueOf(((Skill) entityList.get(i)).getCooldown() / 1000), Color.red);
}
} else if (entityList.get(i) instanceof Player) {
entityList.get(i).renderSkill(gc, null, gr, skillW.isInvincible());
} else {
entityList.get(i).render(gc, null, gr);
}
}
for (int i = 0; i < boardSpawn.getEnemies().size(); i++) {
boardSpawn.getEnemies().get(i).render(gc, null, gr);
}
for (int i = 0; i < birdSpawn.getEnemies().size(); i++) {
birdSpawn.getEnemies().get(i).render(gc, null, gr);
}
for (int i = 0; i < weaponList.size(); i++) {
weaponList.get(i).render(gc, null, gr);
}
ttf.drawString(SCREEN_WIDTH - 200, 30, "Score: " + (int) score, Color.black);
ttf.drawString(100, 30, "Life: " + (int) health, Color.black);
ttfTitle.drawString(440, 15, "The Flying Ninja", Color.black);
}
|
a21da306-ad64-4d7f-80bf-8c7d006c491f
| 3
|
@Override
public void deserialize(Buffer buf) {
elementId = buf.readInt();
if (elementId < 0)
throw new RuntimeException("Forbidden value on elementId = " + elementId + ", it doesn't respect the following condition : elementId < 0");
elementTypeId = buf.readInt();
int limit = buf.readUShort();
enabledSkills = new InteractiveElementSkill[limit];
for (int i = 0; i < limit; i++) {
enabledSkills[i] = ProtocolTypeManager.getInstance().build(buf.readShort());
enabledSkills[i].deserialize(buf);
}
limit = buf.readUShort();
disabledSkills = new InteractiveElementSkill[limit];
for (int i = 0; i < limit; i++) {
disabledSkills[i] = ProtocolTypeManager.getInstance().build(buf.readShort());
disabledSkills[i].deserialize(buf);
}
}
|
a1ab0a83-0c06-4642-81e7-71c4fdb3c332
| 9
|
private void readObject(ObjectInputStream s) throws IOException,
ClassNotFoundException {
s.defaultReadObject();
Vector values = (Vector) s.readObject();
int indexCounter = 0;
int maxCounter = values.size();
if (indexCounter < maxCounter
&& values.elementAt(indexCounter).equals("graphModel")) {
graphModel = (GraphModel) values.elementAt(++indexCounter);
indexCounter++;
}
if (indexCounter < maxCounter
&& values.elementAt(indexCounter).equals("graphLayoutCache")) {
graphLayoutCache = (GraphLayoutCache) values
.elementAt(++indexCounter);
indexCounter++;
}
if (indexCounter < maxCounter
&& values.elementAt(indexCounter).equals("selectionModel")) {
selectionModel = (GraphSelectionModel) values
.elementAt(++indexCounter);
indexCounter++;
}
if (indexCounter < maxCounter
&& values.elementAt(indexCounter).equals("marquee")) {
marquee = (BasicMarqueeHandler) values.elementAt(++indexCounter);
indexCounter++;
}
// Reinstall the redirector.
if (listenerList.getListenerCount(GraphSelectionListener.class) != 0) {
selectionRedirector = new GraphSelectionRedirector();
selectionModel.addGraphSelectionListener(selectionRedirector);
}
}
|
b5f1c169-9291-4c35-8502-b992cdaf070b
| 3
|
public static void doubleHashing() {
System.out.println("START OF DOUBLE HASHING");
statsDouble = new ArrayList<Stats>();
List<Integer> sieve = MakeList.makeEratosthenesSieve();
// System.out.println(sieve);
for (Integer aSieve : sieve) {
for (int j = 0; j < 50; j++) {
List<Integer> list = MakeList.makePermutation(aSieve);
// System.out.println(list + "\n");
DoubleHashing doubleHashing = new DoubleHashing(aSieve);
for (int n = 0; n < list.size(); n++) {
doubleHashing.put(list.get(n), n);
}
// doubleHashing.printTable();
// System.out.println();
}
}
Export.toFile(Export.toSting(statsDouble), "double");
System.out.println("END OF DOUBLE HASHING");
}
|
3c7f8819-26f5-4e3a-a10a-c2d954913745
| 3
|
public synchronized void respond(IRCCommand cmd){
if (cmd == null || cmd == IRCCommand.NONE){
return;
}
if(cmd == IRCCommand.PONG){
String pong = "PONG " + "Dinosaur" + Main.version;
output.write(pong + "\r\n");
//output.flush();
System.out.println(pong);
}
}
|
8cbf3d58-cf35-4148-aadc-d49f406f47b2
| 4
|
public void transport(Checker c) {
if(this.getY() == 0 && c.team == 2) {
c.setLocation(this.getX(), 7);
Greenfoot.playSound("tunnel.wav");
} else if(this.getY() == 8 && c.team == 1) {
c.setLocation(this.getX(), 1);
Greenfoot.playSound("tunnel.wav");
}
}
|
924ff3af-23c6-4e54-ab95-9ee12012000b
| 3
|
public Missile getNearestMissile(){
double nearestDistance = 100000;
Missile nearestMissile = null;
for(Missile missile : missiles){
if(missile != null){
if(settings.screenWidth - missile.posY < nearestDistance){
nearestDistance = settings.screenWidth - missile.posY;
nearestMissile = missile;
}
}
}
return nearestMissile;
}
|
f5b87b93-10ea-499a-9730-740f8e6e46e4
| 8
|
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
final String s=CMParms.combine(commands,1).toLowerCase();
try
{
if(CMath.isInteger(s))
{
int h=CMath.s_int(s);
if(h==0)
h=1;
mob.tell(L("..tick..tock.."));
mob.location().getArea().getTimeObj().tickTock(h);
mob.location().getArea().getTimeObj().save();
}
else
if(s.startsWith("clantick"))
CMLib.clans().tickAllClans();
else
{
for(final Enumeration e=CMLib.libraries();e.hasMoreElements();)
{
final CMLibrary lib=(CMLibrary)e.nextElement();
if((lib.getServiceClient()!=null)&&(s.equalsIgnoreCase(lib.getServiceClient().getName())))
{
if(lib instanceof Runnable)
((Runnable)lib).run();
else
lib.getServiceClient().tickTicker(true);
mob.tell(L("Done."));
return false;
}
}
mob.tell(L("Ticktock what? Enter a number of mud-hours, or clanticks, or thread id."));
}
}
catch(final Exception e)
{
mob.tell(L("Ticktock failed: @x1",e.getMessage()));
}
return false;
}
|
042cfbba-5e8a-41ae-9987-d5449b526a71
| 0
|
public void setMessages(List<String> messages) {
this.messages = messages;
}
|
96a0aae6-3e94-47d4-91de-a88696091f15
| 4
|
public static void checkFainted()
{
System.out.print("Checking for fainted Pokemon...");
for(int i=0; i<userNumOfPokemon; i++)
if(user[i].health<=0)
{
user[i].health=0;
user[i].status=Pokemon.Status.FNT;
}
for(int i=0; i<enemyNumOfPokemon; i++)
if(enemy[i].health<=0)
{
enemy[i].health=0;
enemy[i].status=Pokemon.Status.FNT;
}
System.out.println("Done.");
}
|
881bd9a5-34e9-4b5f-a946-957f23b08b2b
| 9
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(target==mob)
{
mob.tell(L("Um, you could just enter SCORE."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^SYou draw out <T-NAME>s aura, seeing <T-HIM-HER> from the inside out...^?"),verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> draw(s) out your aura.^?"),verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> draws out <T-NAME>s aura.^?"));
if(success)
{
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final StringBuilder str=CMLib.commands().getScore(target);
if(!mob.isMonster())
mob.session().wraplessPrintln(str.toString());
}
}
else
beneficialVisualFizzle(mob,target,L("<S-NAME> examine(s) <T-NAME>, incanting, but the spell fizzles."));
// return whether it worked
return success;
}
|
d8f1ff82-ed9a-4b10-aebf-1ef67985f12b
| 7
|
protected void handleEvent(final Message<JsonObject> event) {
if (event.body().getString("subscribe") != null) {
try {
String destination = event.body().getString("subscribe");
System.err.println("SUBSCRIBE: " + destination);
Session session = this.connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Queue queue = session.createQueue(destination);
MessageConsumer consumer = session.createConsumer(queue);
final Context context = vertx.currentContext();
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(final javax.jms.Message message) {
context.runOnContext(new Handler<Void>() {
@Override
public void handle(Void ignored) {
System.err.println("** handling onContext: " + message);
try {
String address = event.body().getString("address");
System.err.println("sending to: " + address);
vertx.eventBus().send(event.body().getString("address"), ((TextMessage) message).getText(), new Handler<Message<Boolean>>() {
@Override
public void handle(Message<Boolean> event) {
if (event.body()) {
try {
message.acknowledge();
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
} catch (JMSException e) {
e.printStackTrace();
}
}
});
}
});
} catch (JMSException e) {
e.printStackTrace();
event.reply(false);
}
event.reply(true);
} else if (event.body().getString("send") != null) {
String destination = event.body().getString("send");
System.err.println("== SEND: " + destination);
try {
Session session = this.connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(session.createQueue(destination));
producer.send(session.createTextMessage(event.body().getString("body")));
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
181bb001-c3be-44be-a15d-1d1693587fb0
| 0
|
private IautosStatusCode(int code, String desc) {
this.code = code;
this.desc = desc;
}
|
e70c99bf-c764-4479-a1ac-caf4e3578f1e
| 6
|
public static String selectFileExtension(Keyword type) {
{ String extension = null;
{ Cons entry = null;
Cons iter000 = Stella.$TYPE_TO_FILE_EXTENSION_TABLE$;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
entry = ((Cons)(iter000.value));
if (entry.value == type) {
extension = ((StringWrapper)(entry.rest.value)).wrapperValue;
}
}
}
if (type == Stella.KWD_DIRECTORY) {
return (Stella.directorySeparatorString());
}
else if ((type == Stella.KWD_LISP) ||
(type == Stella.KWD_LISP_BINARY)) {
if (Stella.runningAsLispP()) {
return (Keyword.computeCommonLispFileExtension(type));
}
else {
return (Keyword.defaultCommonLispFileExtension(type));
}
}
else {
}
return (extension);
}
}
|
21c2c6b7-912b-49b7-bd48-9e01147e37e2
| 0
|
public Long getId() {
return id;
}
|
8b5cb0d6-c2d9-4dbe-b478-5137174542e2
| 2
|
@Override
public Value get(Key key)
{
for (Node x = first; x != null; x = x.next)
{
// cmp++;
if (key.equals(x.key))
return x.val;
}
return null;
}
|
361c9b9a-aad5-43c5-b4a8-723e83c97503
| 9
|
public static String[] getPhonemeASR(String refWords, String refPhones,
String testWav, String lesson) {
String[] line = new String[3];
int timeout = 0;
int trial = 0;
// if (!Globals.installer){
// testWav = "../../" + testWav.replaceAll("\"", "");
// }
String j_phcmd = "janus -f janus/phonemes/getUttFeat.tcl " + testWav
+ " " + refWords.toLowerCase() + " \"" + refPhones + "\"";
SpeechScorer.janusCommand = j_phcmd;
int i = 0;
LOGGER.debug("Creating speech recognition process to decode given speech file "
+ "using the following command:");
LOGGER.debug(j_phcmd);
try {
do {
if (trial > 0) {
LOGGER.error("Failed to decode speech in trial #" + trial
+ ".\n" + "Trying to decode again.");
timeout = timeout + 10;
}
Runtime r = Runtime.getRuntime();
Process p = r.exec(j_phcmd);
BufferedReader b = new BufferedReader(new InputStreamReader(
p.getInputStream()));
i = 0;
while ((line[i] = b.readLine()) != null) {
if (line[i].equals("*")) {
p.destroy();
}
i++;
}
trial++;
} while (line[0] == null && trial < 3);
} catch (Exception e) {
LOGGER.error(
"Failed to create process for speech recognition engine.",
e);
}
if (line[0] == null) {
LOGGER.error("Failed to recognize sample wav file.");
LOGGER.debug("OUTPUT: null");
} else {
for (i = 0; i < line.length; i++) {
if (line[i] != null)
LOGGER.debug("OUTPUT: " + i + " - " + line[i]);
}
}
return line;
}
|
7f87c974-a7b8-47d4-93f2-bb57aa2544a9
| 1
|
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
System.out.println("New SHAPES:");
shapes[0] = new Square(4);
shapes[1] = new Triangle();
for (Shape shape : shapes) {
System.out.println(shape);
shape.draw();
System.out.println();
}
System.out.println(Arrays.toString(shapes));
Arrays.sort(shapes);
System.out.println(Arrays.toString(shapes));
System.out.println();
System.out.println("New SQUARE:");
Square square = new Square(6);
square.draw();
System.out.println(square.getPerimeter());
}
|
d8c77afa-3e56-4912-b342-7e5d8a766426
| 6
|
public static void initialize() {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
UIManager.setLookAndFeel(info.getClassName());
UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(Settings.progressBarColor)));
UIManager.getLookAndFeelDefaults().put("PopupMenu[Enabled].backgroundPainter", new FillPainter(Color.ORANGE));
UIManager.put("nimbusBlueGrey", (new Color(Settings.ComponentsBackground)));
UIManager.put("nimbusBase", (new Color(Settings.ComponentsPartsColor)));
UIManager.put("nimbusDisabledText", (new Color(Settings.DisabledTextColor)));
UIManager.put("text", (new Color(Settings.ActiveTextColor)));
UIManager.put("nimbusFocus", (new Color(Settings.FocusColor)));
UIManager.put("nimbusBorder", (new Color(Settings.BordersColor)));
UIManager.put("nimbusLightBackground", (new Color(Settings.ComponentsLightBackground)));
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OptionsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OptionsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OptionsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OptionsFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
OptionsFrame = new OptionsFrame();
}
});
}
|
5959f3c8-b7e7-4f49-87bc-45c3612b7701
| 8
|
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc;
ArrayList<String> list = new ArrayList<String>();
int nbAnag;
try{
sc = new Scanner(new File("dictionary.txt"));
while(sc.hasNext())
{
String str = sc.next();
//System.out.print(str+"\n");
list.add(str);
}
}
catch(FileNotFoundException e){System.err.println("Le fichier est introuvable !");}
System.out.println(list.size());
ArrayList<String> anag;
/*for(int i = 0; i < list.size(); i++)*/
while(list.size()>1)
{
anag = new ArrayList<String>();
anag.add(list.get(0));
list.remove(list.get(0));
int s = anag.get(0).length();
nbAnag = 1;
//System.out.println(s);
//System.out.println("oui");
//String sr1 = sortString(s);
ArrayList<String> list2 = null;
list2 = list;
for(int j = 0; j < list2.size(); j++)
{
if(list2.get(j).length() == s)
{
if(Signature.sortString(anag.get(0)).equals(Signature.sortString(list2.get(j))))
{
//System.out.println("egal");
nbAnag++;
anag.add(list2.get(j));
//int j = list.indexOf(s2);
//list.remove(list2.get(j));
}
}
}
//System.out.println(anag.size());
//attention au premier element!
if(nbAnag > 8)
{
System.out.print(nbAnag + " : ");
System.out.print(anag.get(0));
for(int i = 1; i < anag.size(); i++)
{
System.out.print(", " + anag.get(i));
list.remove(anag.get(i));
}
System.out.println("\n");
}
//System.out.println("\n");
}
}
|
ed19f970-9a88-458e-972a-6457a159e143
| 5
|
private void addParticipant() {
lblError.setVisible(false);
Anstalld selAnst = (Anstalld) cbSpecialist.getSelectedItem();
DefaultListModel<Anstalld> dlm = (DefaultListModel<Anstalld>) listParticipantsHolder.getModel();
boolean exists = false; // check if the participant is already added
for (int i = 0; i < dlm.getSize() && !exists; i++) {
if (selAnst.getAid() == dlm.get(i).getAid()) {
exists = true;
}
}
if (!exists) {
try {
String query = "insert into arbetar_i (aid,sid) values(" + selAnst.getAid() + "," + selectedSpelprojekt + ")";
DB.insert(query);
} catch (InfException e) {
e.getMessage();
}
loadParticipants(); //reload if we added someone
} else {
lblError.setText(selAnst.getName() + " är redan tillagd.");
lblError.setVisible(true);
}
}
|
58d96889-b5b2-4707-aab3-c8ba9a61a120
| 7
|
private void initialize() {
bank=new Bank("Accounts.txt");
frmBank = new JFrame();
frmBank.setTitle("Bank");
frmBank.setBounds(100, 100, 457, 325);
frmBank.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnViewAccounts = new JButton("View All Accounts");
btnViewAccounts.setToolTipText("Opens a new Window with all the accounts contained by the bank");
btnViewAccounts.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AccountsFrame frame=new AccountsFrame(bank);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
});
JButton btnAddAccount = new JButton("Add Account");
btnAddAccount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddAccountFrame frame=new AddAccountFrame(bank);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
});
btnAddAccount.setToolTipText("Opens a window to add a new Account");
JButton btnRemoveAccount = new JButton("Remove Account");
btnRemoveAccount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(checkID(txtID1.getText())){
bank.removeAccount(txtID1.getText());
JOptionPane.showMessageDialog(frmBank, "removed","Account info",JOptionPane.INFORMATION_MESSAGE);
}
}
});
btnRemoveAccount.setToolTipText("Removes Account with ID 1 from bank");
txtID1 = new JTextField();
txtID1.setColumns(10);
JButton btnViewAccountLog = new JButton("View Account Log");
btnViewAccountLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(checkID(txtID1.getText()))
JOptionPane.showMessageDialog(frmBank, bank.getAccount(txtID1.getText()).getLog(),"Account info",JOptionPane.INFORMATION_MESSAGE);
}
});
btnViewAccountLog.setToolTipText("Shows the log of Account with ID 1");
JButton btnReadAccount = new JButton("Read Account");
btnReadAccount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(checkID(txtID1.getText()))
JOptionPane.showMessageDialog(frmBank, bank.getAccount(txtID1.getText()).toString(),"Account info",JOptionPane.INFORMATION_MESSAGE);
}
});
btnReadAccount.setToolTipText("Displays info about Account with ID 1");
JButton btnTransfer = new JButton("Transfer");
btnTransfer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(checkID(txtID1.getText()))
if(checkID(txtID2.getText()))
if(toDouble(txtAmount.getText())>0)
{
bank.transfer(txtID2.getText(), txtID1.getText(), toDouble(txtAmount.getText()));
JOptionPane.showMessageDialog(frmBank, toDouble(txtAmount.getText())+"$ transfered","Transfer", JOptionPane.INFORMATION_MESSAGE);
}
}
});
btnTransfer.setToolTipText("Transfers specified amount from Account with ID 1 to Account with ID 2");
JLabel lblAccountId = new JLabel("Account ID 1:");
JLabel lblAccountId_1 = new JLabel("Account ID 2:");
txtID2 = new JTextField();
txtID2.setColumns(10);
JLabel lblAmount = new JLabel("Amount:");
txtAmount = new JTextField();
txtAmount.setColumns(10);
GroupLayout groupLayout = new GroupLayout(frmBank.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addComponent(btnTransfer, GroupLayout.PREFERRED_SIZE, 215, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(lblAmount)
.addGap(18)
.addComponent(txtAmount))
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addComponent(lblAccountId_1)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(txtID2))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblAccountId)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(txtID1, GroupLayout.PREFERRED_SIZE, 328, GroupLayout.PREFERRED_SIZE)))
.addGap(178))
.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(btnViewAccountLog, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnRemoveAccount, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnReadAccount, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnViewAccounts, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAddAccount, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
.addContainerGap())))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblAccountId)
.addComponent(txtID1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblAccountId_1)
.addComponent(txtID2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnViewAccounts)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnAddAccount)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnReadAccount)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnRemoveAccount)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnViewAccountLog)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnTransfer)
.addComponent(txtAmount, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(lblAmount))
.addGap(35))
);
frmBank.getContentPane().setLayout(groupLayout);
JMenuBar menuBar = new JMenuBar();
frmBank.setJMenuBar(menuBar);
JMenu mnMenu = new JMenu("Menu");
mnMenu.setMnemonic('n');
menuBar.add(mnMenu);
JMenuItem mntmSave = new JMenuItem("Save");
mntmSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter("Accounts.txt"));
out.write(bank.toString());
out.close();
} catch (IOException e1) {
JOptionPane.showMessageDialog(null, "ERROR", "ERROR", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
}
});
mntmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
mnMenu.add(mntmSave);
}
|
ffb0decd-d741-4798-a852-8ecf69832629
| 8
|
public static void main(String[] args) throws Throwable {
System.out.println(System.currentTimeMillis());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int n = Integer.parseInt(in.readLine());
for (int tc = 0; tc < n; tc++) {
int nn = Integer.parseInt(in.readLine());
int a = 0;
int p = 0;
int h = 0;
int s = 0;
for (int i = 0; i < nn; i++) {
StringTokenizer st = new StringTokenizer(in.readLine());
st.nextToken();
if(!st.hasMoreTokens()){
a++;
}else{
boolean y = false;
int j = 0;
while(st.hasMoreTokens()){
String li = st.nextToken();
if(li.contains("y") && j==0){
p++;
y=true;
}
else if(li.contains("y")){
h++;
y=true;
}
j++;
}
if(!y) s++;
}
}
sb.append("Roll-call: "+(tc+1)+"\n");
sb.append("Present: "+p+" out of "+nn+"\n");
sb.append("Needs to study at home: "+h+" out of "+nn+"\n");
sb.append("Needs remedial work after school: "+s+" out of "+nn+"\n");
sb.append("Absent: "+a+" out of "+nn+"\n");
}
System.out.print(new String(sb));
}
|
8af185bf-2bf8-4462-b9cb-00428ee54355
| 3
|
public boolean isExecutable() {
return ((status == Watchable.PAUSED || status == Watchable.RUNNING) &&
(gate == null || !gate.stop()));
}
|
88ec5c64-4cc9-4c54-93bb-dd02ae04d95b
| 7
|
protected void checkListeningThreads() {
final List<ListeningThread> threadsForRemoval = new ArrayList<ListeningThread>();
for (final ListeningThread listeningThread : this.listeningThreads) {
threadsForRemoval.add(listeningThread);
}
for (final InetSocketAddress inetSocketAddress : this.listeningAddresses) {
boolean found = false;
for (final ListeningThread listeningThread : this.listeningThreads) {
if (listeningThread.inetSocketAddress.equals(inetSocketAddress)) {
found = true;
threadsForRemoval.remove(listeningThread);
break;
}
}
if (!found) {
try {
final ListeningThread listeningThread = new ListeningThread(
inetSocketAddress);
this.listeningThreads.add(listeningThread);
JSocksProxy.executor.execute(listeningThread);
} catch (final IOException e) {
this.logger
.log(Level.SEVERE,
"Failed to setup listening address for "
+ StringUtils
.formatSocketAddress(inetSocketAddress),
e);
}
}
}
for (final ListeningThread listeningThread : threadsForRemoval) {
listeningThread.shutdown();
this.listeningThreads.remove(listeningThread);
}
}
|
c8d9d234-0185-41d2-8440-8b1ac1907170
| 3
|
public boolean isUsed(Tile t) {
for (int y = 0; y < bounds.height; y++) {
for (int x = 0; x < bounds.width; x++) {
if (map[y][x] == t) {
return true;
}
}
}
return false;
}
|
f5f1cebb-86c9-49fc-9721-70ee975c1061
| 9
|
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(PBDeserializer parser, Type type, Object fieldName) {
Collection array = null;
try
{
if (fieldName != null)
{
byte tmpIsNull = parser.getTheCodedInputStream().readRawByte();
if (tmpIsNull == 1)
{
return null;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
if (type == Set.class || type == HashSet.class) {
array = new HashSet();
} else {
if (type instanceof ParameterizedType) {
Type rawType = ((ParameterizedType) type).getRawType();
if (rawType == Set.class || rawType == HashSet.class) {
array = new HashSet();
}
}
}
if (array == null) {
array = new ArrayList();
}
parseArray(parser, array);
return (T) array;
}
|
cab1ac1f-8562-4042-8900-4c49cc64e0c2
| 5
|
@Override
public int getSamples(byte[] buffer) {
byte[] pwmBuffer = null;
if(pulseWidthCvProvider != null) {
pwmBuffer = new byte[buffer.length];
pulseWidthCvProvider.getSamples(pwmBuffer);
}
int index = 0;
for (int i = 0; i < (buffer.length / 2); i++) {
if(pwmBuffer != null) {
short pwmSample = SampleConverter.toSample(pwmBuffer, index);
double pwmValue = SampleConverter.getSampleValue(pwmSample) * 2;
if(pwmValue < 0.0) {
pwmValue *= -1;
}
if(pulseWidthBaseValue * pwmValue <= 1.0) {
pulseWidth = pulseWidthBaseValue * pwmValue;
}
else {
pulseWidth = 1.0;
}
}
double ds = getSample() * Short.MAX_VALUE;
short ss = (short) Math.round(ds);
buffer[index++] = (byte)(ss >> 8);
buffer[index++] = (byte)(ss & 0xFF);
}
return buffer.length;
}
|
c8f157c9-3975-49ea-bdd0-62195ab46db9
| 9
|
public void display(BufferedImage bi) {
Graphics g = null;
try {
if (bi != null) {
g = bs.getDrawGraphics();
g.drawImage(bi, 0, 0, canvas.getWidth(), canvas.getHeight(), null);
long ct = System.currentTimeMillis();
long lt = ct - FR_SAMPLE_HISTORY;
long t, dt;
long maxdt = 0;
long mindt = FR_SAMPLE_HISTORY;
double ft = 0, fr = 0;
int fc = 1;
Iterator<Long> it = ftimes.iterator();
while (it.hasNext()) {
t = it.next();
if (ct - t > FR_SAMPLE_HISTORY) {
it.remove();
} else {
dt = t - lt;
ft += dt;
fc++;
mindt = dt < mindt ? dt : mindt;
maxdt = dt > maxdt ? dt : maxdt;
}
lt = t;
}
ft += ct - lt;
ft /= fc;
fr = 1000d / ft;
// g.setColor(Color.MAGENTA);
// g.drawString(String.format("%05.1f|%03d|%05.1f|%03d|%d", fr,
// maxdt, ft, mindt, ct - t_lastbad), 5, 15);
setTitle(String.format("%.2f FPS", fr));
if (draw_crosshair) {
g.setColor(Color.WHITE);
int ch_x = canvas.getWidth() / 2 - 10;
int ch_y = canvas.getHeight() / 2 - 10;
g.fillRect(ch_x, ch_y + 9, 20, 2);
g.fillRect(ch_x + 9, ch_y, 2, 20);
}
if (!bs.contentsLost()) {
bs.show();
ct = System.currentTimeMillis();
ftimes.add(ct);
if (ct - lt > 33) {
// System.out.println("Detected frametime = " + (ct -
// lt) + "ms.");
t_lastbad = ct;
}
} else {
System.out.println("Frame dropped: Buffer contents lost.");
}
}
} finally {
if (g != null) {
g.dispose();
}
}
}
|
fceee7f8-46d0-4bb4-9f4b-db195225b972
| 4
|
public void init( Environment<String,BasicType> additionalSettings,
Environment<String,BasicType> optionalReturnValues )
throws InstantiationException {
synchronized( this ) {
// Since version 0.9.9 it is possible to re-use the handler instance ('sharedHandlerInstance' in
// the server config). So yucca might try to initialize the handler multiple times.
// Avoid this here:
if( this.documentRoot != null )
return; // Already initialized
HTTPConfiguration config = new HTTPConfiguration( this, this.getLogger() );
try {
config.applyConfiguration( additionalSettings );
// After all verify the configuration so all essentials are present
if( this.documentRoot == null )
this.initDefaultDocumentRoot();
} catch( IOException e ) {
this.getLogger().log( Level.SEVERE,
getClass().getName() + ".init(...)",
"[IOException] " + e.getMessage() );
throw new InstantiationException( "[IOException] " + e.getMessage() );
} catch( ConfigurationException e ) {
this.getLogger().log( Level.SEVERE,
getClass().getName() + ".init(...)",
"[ConfigurationException] " + e.getMessage() );
throw new InstantiationException( "[ConfigurationException] " + e.getMessage() );
}
} // END synchronized
}
|
551529e0-146a-49f9-99ad-32b4ba686489
| 3
|
public void addObject(int var1, Object var2) {
Integer var3 = (Integer)dataTypes.get(var2.getClass());
if(var3 == null) {
throw new IllegalArgumentException("Unknown data type: " + var2.getClass());
} else if(var1 > 31) {
throw new IllegalArgumentException("Data value id is too big with " + var1 + "! (Max is " + 31 + ")");
} else if(this.watchedObjects.containsKey(Integer.valueOf(var1))) {
throw new IllegalArgumentException("Duplicate id value for " + var1 + "!");
} else {
WatchableObject var4 = new WatchableObject(var3.intValue(), var1, var2);
this.watchedObjects.put(Integer.valueOf(var1), var4);
}
}
|
d33116a3-5648-4669-bbed-f4527381a25b
| 2
|
public void removePush() {
if (stackMap == null)
/* already done or mapping didn't succeed */
return;
stackMap = null;
block.removePush();
Iterator iter = successors.keySet().iterator();
while (iter.hasNext()) {
FlowBlock succ = (FlowBlock) iter.next();
succ.removePush();
}
}
|
541fa203-9a00-4272-92ab-c6d90d53cbf6
| 8
|
static protected int[] case5(int[][] a) {
int[] result = new int[2];
int tmp1, tmp2;
if (a[3][1] <= a[1][1]) {
tmp1 = a[0][0] + a[2][0];
tmp2 = a[1][0] + a[3][0];
} else if (a[3][1] > a[1][1] && a[1][1] + a[0][1] >= a[3][1]) {
tmp1 = a[1][0] + a[3][0];
tmp2 = a[2][0] > a[3][0] ? a[2][0] : a[3][0];
tmp2 += a[0][0];
} else {
tmp1 = a[0][0] > a[1][0] ? a[0][0] : a[1][0];
tmp1 += a[3][0];
tmp2 = a[2][0];
}
result[0] = tmp1 > tmp2 ? tmp1 : tmp2;
tmp1 = a[0][1] + a[1][1];
tmp2 = a[2][1] + a[3][1];
result[1] = tmp1 > tmp2 ? tmp1 : tmp2;
tmp1 = a[1][1] + a[2][1];
result[1] = result[1] > tmp1 ? result[1] : tmp1;
return result;
}
|
4cdceb02-ce6e-494d-bcbd-a880a4442eb0
| 6
|
private static ArrayList<Integer> getPrimesSieve(int n) {
ArrayList<Boolean> integerList = new ArrayList<Boolean>();
ArrayList<Integer> primes = new ArrayList<Integer>();
/* Initialize Arrays:
* (1) Mark all other numbers as prime initially
* (2) 0, 1 not considered primes
*/
integerList.add(false);
integerList.add(false);
for (int i = 2; i < n; i++) {
integerList.add(true);
}
/* Proceed only till sqrt(n) + 1 */
int limit = (int)(Math.pow(n, 0.5) + 1);
/* Cross off non-prime numbers */
for (int i = 2; i < limit; i++) {
/* If the number is a prime, cross off all its multiples */
if (integerList.get(i) == true) {
/* Start at i^2 (e.g. 2^2:4, 3^2: 9, 4^2: 16 */
for (int j = (int)Math.pow(i, 2); j < n; j += i) {
integerList.set(j, false);
}
}
}
/* At the end, those marked as true are true primes */
for (int i = 2; i < n; i++) {
if (integerList.get(i) == true) {
primes.add(i);
}
}
return primes;
}
|
3ceb450d-08c3-4608-b390-b6288d6fcce1
| 3
|
public static void sendPlayerToHome( BSPlayer player, String home ) {
Home h = getSimilarHome( player, home );
if ( h == null ) {
player.sendMessage( Messages.HOME_DOES_NOT_EXIST );
return;
}
Location l = h.loc;
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream( b );
try {
out.writeUTF( "TeleportToLocation" );
out.writeUTF( player.getName() );
out.writeUTF( l.getWorld() );
out.writeDouble( l.getX() );
out.writeDouble( l.getY() );
out.writeDouble( l.getZ() );
out.writeFloat( l.getYaw() );
out.writeFloat( l.getPitch() );
} catch ( IOException e ) {
e.printStackTrace();
}
sendPluginMessageTaskHomes( l.getServer(), b );
if ( !player.getServer().getInfo().equals( l.getServer() ) ) {
player.getProxiedPlayer().connect( l.getServer() );
}
player.sendMessage( Messages.SENT_HOME );
}
|
9953e91c-5ab0-47d9-8cd0-86267babe269
| 3
|
public static IPv4Network getByAddress(String address, int mask) throws NetworkException {
if ((mask < 0) || (mask > 32)) {
throw new InvalidAddressException(String.format("'%d' is not a valid IPv4 mask.", mask));
}
try {
return new IPv4Network(new BigInteger(Inet4Address.getByName(address).getAddress()), BigInteger.valueOf(mask));
} catch (UnknownHostException ex) {
throw new InvalidAddressException(String.format("%s is not a valid address", address));
}
}
|
4505d782-c56a-4c52-93de-5626d19de5ad
| 6
|
public static Element getParentElement(Element element) {
if (element == null) {
return null;
}
Element parentElement = null;
Node parentNode = element.getParentNode();
while (parentNode != null && parentElement == null) {
if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
parentElement = (Element) parentNode;
}
if (parentNode.getNodeType() == Node.DOCUMENT_NODE) {
parentElement = ((Document) parentNode).getDocumentElement();
if (element.isSameNode(parentElement)) {
parentElement = null;
}
}
parentNode = parentNode.getParentNode();
}
return parentElement;
}
|
6f7be275-911c-4e41-88be-919556ded96f
| 9
|
public static void display(String tableName){
Statement stmt = null;
ResultSet rs = null;
String sql;
try{
stmt= conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
if(tableName.toLowerCase().equals("patients")){
sql = "SELECT * FROM PATIENTS";
rs = stmt.executeQuery(sql);
displayPatients(rs);;
}
else if(tableName.toLowerCase().equals("employees")){
sql = "SELECT * FROM EMPLOYEES";
rs = stmt.executeQuery(sql);
displayEmployees(rs);
}
else if(tableName.toLowerCase().equals("drugs")){
sql = "SELECT * FROM DRUGS";
rs = stmt.executeQuery(sql);
displayDrugs(rs);
}
else if(tableName.toLowerCase().equals("prescriptions")){
sql = "SELECT * FROM PRESCRIPTIONS";
rs = stmt.executeQuery(sql);
displayPrescriptions(rs);
}
else if(tableName.toLowerCase().equals("schedules")){
sql = "SELECT * FROM SCHEDULES";
rs = stmt.executeQuery(sql);
displaySchedules(rs);
}
}catch(SQLException e){
System.out.println("sql exception in display()");
System.out.println(e);
}finally{
try{
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
}catch(Exception e){
System.out.println("error closing resource within display()");
}
}
}
|
104c0717-fe2a-40ea-b8f3-04668132ae5d
| 4
|
public String httpPost(String url, String queryString) throws Exception {
String responseData = null;
HttpClient httpClient = new HttpClient();
PostMethod httpPost = new PostMethod(url);
httpPost.addParameter("Content-Type",
"application/x-www-form-urlencoded");
httpPost.getParams().setParameter("http.socket.timeout",
new Integer(CONNECTION_TIMEOUT));
if (queryString != null && !queryString.equals("")) {
httpPost.setRequestEntity(new ByteArrayRequestEntity(queryString
.getBytes()));
}
System.out.println("POST url:"+url);
System.out.println("POST data:"+queryString);
try {
int statusCode = httpClient.executeMethod(httpPost);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("HttpPost Method failed: "
+ httpPost.getStatusLine());
}
responseData = httpPost.getResponseBodyAsString();
} catch (Exception e) {
throw new Exception(e);
} finally {
httpPost.releaseConnection();
httpClient = null;
}
return responseData;
}
|
bc9fad38-dca8-47fa-a704-a11befab6682
| 7
|
private void process(BruteTreeNode node, int level) {
if (this.solutions.size() >= this.getExpectedSolutionCount()) {
return;
}
ValidationResult result = node.validate();
switch(result) {
case RESOLVED:
this.solutions.add(node);
return;
case DEAD:
return;
case PENDING:
Collection<BruteTreeNode> children = node.nextLevel();
if (level < this.multiThreadLevel) {
CountDownLatch countDown = new CountDownLatch(children.size());
processWithThreads(children, level+1, countDown);
try {
countDown.await();
} catch (InterruptedException e) {
// do nothing.
}
} else {
for (BruteTreeNode child: children) {
process(child, level+1);
}
}
return;
}
}
|
9a68e6d0-951d-47f3-9f2c-7c2dfc037635
| 3
|
public List<Message> getUserMessages(String userEmail)
{
initConnection();
String preparedString = null;
PreparedStatement preparedQuery = null;
List<Message> messageList = null;
try
{
//Prepare Statement
preparedString = "SELECT * FROM messages " +
"INNER JOIN users ON users.email = messages.user " +
"WHERE user = ?;";
preparedQuery = (PreparedStatement) connection.prepareStatement(preparedString);
preparedQuery.setString(1, userEmail);
//TODO: Remove debug
System.out.println("Get a user's messages with SQL: [" + preparedQuery.toString() + "] ");
//Execute Statement
ResultSet resultSet = preparedQuery.executeQuery();
messageList = new ArrayList<Message>();
//Extract messages into list of Beans
while (resultSet.next())
{
//Add new message to list for each message from the user
Message newMessage = new Message();
newMessage.setId(resultSet.getInt("id"));
newMessage.setTimeStamp(resultSet.getTimestamp("timestamp"));
newMessage.setContent(resultSet.getString("content"));
//Get author as User object
User author = new User();
author.setEmail(resultSet.getString("user"));
author.setFirstName(resultSet.getString("firstname"));
author.setLastName(resultSet.getString("lastname"));
newMessage.setAuthor(author);
messageList.add(newMessage);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
//Finally close stuff to return connection to pool for reuse
preparedQuery.close();
connection.close();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
return messageList;
}
|
f7791e89-0072-46e1-8c50-15cfbdbfb8bc
| 1
|
public void visit_areturn(final Instruction inst) {
stackHeight -= 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
}
|
f5302ce3-e15f-477b-8e16-4730387c14b6
| 8
|
private boolean check() {
if (N == 0) {
if (first != null) return false;
}
else if (N == 1) {
if (first == null) return false;
if (first.next != null) return false;
}
else {
if (first.next == null) return false;
}
// check internal consistency of instance variable N
int numberOfNodes = 0;
for (Node x = first; x != null; x = x.next) {
numberOfNodes++;
}
if (numberOfNodes != N) return false;
return true;
}
|
4eb024fa-3263-4d42-b020-507afbb85869
| 5
|
private boolean isValidSequence(List<Chemin> listeAvalider){
boolean isOk= true;
boolean tmpBool= false;
List<Chemin> tmpListe = listeAvalider;
//QuickSort<Chemin> qSort = new QuickSort<>(tmpListe, 0 , tmpListe.size());
//Collections.sort(tmpListe, new CheminComparator());
for (int i = 0; i < listeAvalider.size() ; i++) {
for (int j = 1; j <= listeAvalider.size(); j++)
{
//System.out.println(listeAvalider.get(i).getPointArrivee());
if (listeAvalider.get(i).getPointArrivee() == j ) {
tmpBool = true;
} else {
tmpBool = false;
}
}
if (!tmpBool){
for (Chemin chemin : tmpListe)
/* System.out.print(" " + chemin.getPointArrivee()+ " ");
System.out.println("Arrivé");*/
return false;
}
}
// System.out.println();
//System.out.print(" " + chemin.getPointArrivee()+ " ");
System.out.println("Arrivé");
return tmpBool;
}
|
a45d7993-0e16-402b-8e8d-d96443e513ff
| 7
|
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof UsuarioId))
return false;
UsuarioId castOther = (UsuarioId) other;
return (this.getId() == castOther.getId())
&& ((this.getUser() == castOther.getUser()) || (this.getUser() != null
&& castOther.getUser() != null && this.getUser()
.equals(castOther.getUser())));
}
|
a661abc8-f473-4a02-aaae-c6b4a3d882cc
| 5
|
public String viewMember(String firstName, String lastName, String concordiaID){
String foundMember;
DecimalFormat df = new DecimalFormat("#.##");
for(ConcordiaMembers member: concordiaMembers){
if(member!=null){
if(member.getFirstName().equals(firstName) && member.getLastName().equals(lastName) && member.getConcordiaID().equals(concordiaID)){
foundMember= member.viewFullInfo();
return foundMember;
}
}
}
;
return "No one matching that information has been found.\n";
}
|
34ef06af-0e6a-444e-97e7-0a88c3eef182
| 0
|
public DocumentRepository() {}
|
e72dd176-b393-48f5-baad-d5aeac57d308
| 3
|
public List<String> getSchedule_indications() {
List<String> indications = new LinkedList<String>();
for (Indication schedule_indication : schedule_indications) {
if (schedule_indication == null || schedule_indication.getText() == null)
continue;
indications.add(schedule_indication.getText());
}
return indications;
}
|
389177f5-5f03-45dc-8054-f6972ceaebee
| 7
|
public static boolean stringRotation(String str1, String str2) {
if(str1.length() != str2.length())
return false;
String two = str1.substring(0, 2);
int j, i = 2;
if((j = str2.indexOf(two)) != -1)
j += 2;
else if(str2.charAt(str2.length() - 1) == two.charAt(0) && str2.charAt(0) == two.charAt(1))
j = 1;
else
return false;
while(i < str1.length()) {
if(j == str2.length())
j = 0;
if(str1.charAt(i) != str2.charAt(j))
return false;
i++;
j++;
}
return true;
}
|
a32758b8-53bc-4826-810e-5e69a3edf98c
| 0
|
public static void main(String[] args) {
String[] rankArray = {"Ace", "Jack"};
String[] SuitArray = {"Spades", "Diamonds", "Fun"};
Integer[] pointArray = {1, 2};
Deck Bicycle = new Deck(rankArray, SuitArray, pointArray);
Bicycle.shuffle();
System.out.println(Bicycle.deal());
System.out.println(Bicycle.Decksize());
System.out.println(Bicycle.toString());
}
|
806e5d84-05a3-4d36-84fe-6ca9ff156fa4
| 2
|
public int creationpays(int idpays, String nom, String cp) {
retour = 0;
try {
RequetesVille.insertVille(idpays, nom, cp);
} catch (SQLException ex) {
if (ex.getErrorCode() == 1062) {
//error nom de ville deja dans le fichier
retour = 1062;
} else {
Logger.getLogger(RequetesVille.class.getName()).log(Level.SEVERE, null, ex);
retour = 2000;
}
}
return retour;
}
|
22102211-f9f1-42f1-a49d-d4b4e907ee53
| 8
|
public static String ticksToTimeString(long var0)
{
long var2 = var0 / 20L;
long var4 = var2 / 60L;
long var6 = var4 / 60L;
long var8 = var6 / 24L;
String var10 = "";
if (var8 > 0L)
{
var10 = var8 + ":";
}
if (var6 > 0L)
{
var10 = var10 + (var6 % 24L < 10L && var8 > 0L ? "0" : "") + var6 % 24L + ":";
}
if (var4 > 0L)
{
var10 = var10 + (var4 % 60L < 10L && var6 > 0L ? "0" : "") + var4 % 60L + ":";
}
else
{
var10 = var10 + "0:";
}
var10 = var10 + (var2 % 60L < 10L ? "0" : "") + var2 % 60L;
return var10;
}
|
a68fc0e6-3c58-4278-abe3-6020e172e576
| 8
|
public void paint(Graphics g, Shape a) {
RSyntaxDocument document = (RSyntaxDocument)getDocument();
Rectangle alloc = a.getBounds();
tabBase = alloc.x;
host = (RSyntaxTextArea)getContainer();
Rectangle clip = g.getClipBounds();
// An attempt to speed things up for files with long lines. Note that
// this will actually slow things down a tad for the common case of
// regular-length lines, but I don't think it'll make a difference
// visually. We'll see...
clipStart = clip.x;
clipEnd = clipStart + clip.width;
lineHeight = host.getLineHeight();
ascent = host.getMaxAscent();//metrics.getAscent();
int heightAbove = clip.y - alloc.y;
int linesAbove = Math.max(0, heightAbove / lineHeight);
FoldManager fm = host.getFoldManager();
linesAbove += fm.getHiddenLineCountAbove(linesAbove, true);
Rectangle lineArea = lineToRect(a, linesAbove);
int y = lineArea.y + ascent;
int x = lineArea.x;
Element map = getElement();
int lineCount = map.getElementCount();
RSyntaxTextAreaHighlighter h =
(RSyntaxTextAreaHighlighter)host.getHighlighter();
Graphics2D g2d = (Graphics2D)g;
Token token;
//System.err.println("Painting lines: " + linesAbove + " to " + (endLine-1));
int line = linesAbove;
//int count = 0;
while (y<clip.y+clip.height+lineHeight && line<lineCount) {
Fold fold = fm.getFoldForLine(line);
Element lineElement = map.getElement(line);
int startOffset = lineElement.getStartOffset();
//int endOffset = (line==lineCount ? lineElement.getEndOffset()-1 :
// lineElement.getEndOffset()-1);
int endOffset = lineElement.getEndOffset()-1; // Why always "-1"?
h.paintLayeredHighlights(g2d, startOffset, endOffset,
a, host, this);
// Paint a line of text.
token = document.getTokenListForLine(line);
drawLine(token, g2d, x,y);
if (fold!=null && fold.isCollapsed()) {
// Visible indicator of collapsed lines
Color c = RSyntaxUtilities.getFoldedLineBottomColor(host);
if (c!=null) {
g.setColor(c);
g.drawLine(x,y+lineHeight-ascent-1,
alloc.width,y+lineHeight-ascent-1);
}
// Skip to next line to paint, taking extra care for lines with
// block ends and begins together, e.g. "} else {"
do {
int hiddenLineCount = fold.getLineCount();
if (hiddenLineCount==0) {
// Fold parser identified a zero-line fold region.
// This is really a bug, but we'll be graceful here
// and avoid an infinite loop.
break;
}
line += hiddenLineCount;
fold = fm.getFoldForLine(line);
} while (fold!=null && fold.isCollapsed());
}
y += lineHeight;
line++;
//count++;
}
//System.out.println("SyntaxView: lines painted=" + count);
}
|
742355a4-9366-4368-950e-f05bf0e4b54e
| 5
|
public ParamFrame(String title, String textLabel, int _param, int _count, final boolean isSpline){
super(title);
content = getContentPane();
JPanel p = new JPanel();
JLabel paramLabel = new JLabel(textLabel);
final JTextField paramField = new JTextField();
paramField.setText(_param+"");
JLabel countPoints = new JLabel("Points:");
final JTextField countField = new JTextField();
countField.setText(_count+"");
if(!isSpline){
p.setLayout(new GridLayout(2,2));
setSize(230, 90);
}
else{
p.setLayout(new GridLayout(3,2));
setSize(230, 110);
}
JButton okButton = new JButton(new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
param = paramField.getText();
count = countField.getText();
try{
Integer.parseInt(param);
if(isSpline){
int k = Integer.parseInt(count);
if(k<4){
JOptionPane.showMessageDialog(getWindows()[1], "Please, input number more or equals.", "Input error",JOptionPane.ERROR_MESSAGE);
}
else{
dispose();
setVisible(false);
setOkButtonClick(true);
}
}
else{
dispose();
setVisible(false);
setOkButtonClick(true);
}
}
catch (NumberFormatException e) {
// TODO: handle exception
JOptionPane.showMessageDialog(getWindows()[1], "Please, input number.", "Input error",JOptionPane.ERROR_MESSAGE);
}
}
});
okButton.setText("Ok");
JButton cancelButton = new JButton(new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
setOkButtonClick(false);
dispose();
setVisible(false);
}
});
cancelButton.setText("Cancel");
p.add(paramLabel);
p.add(paramField);
if(isSpline){
p.add(countPoints);
p.add(countField);
}
p.add(okButton);
p.add(cancelButton);
content.add(p);
Dimension dim = new Dimension(600, 600);
int w = this.getSize().width;
int h = this.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
setLocation(x, y);
setVisible(true);
}
|
6e9fe3b6-718c-4cbf-896a-a8e1a8f226b7
| 8
|
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
myPointPanel.togglePointType();
if(myPointPanel.getCurrentType()==PointType.BLUE){
clabel.setText("<html>Color: <font color='blue'>blue</font> - space to change</html>");
}
else{
clabel.setText("<html>Color: <font color='red'>red</font> - space to change</html>");
}
}
if (e.getKeyCode() == KeyEvent.VK_N) {
//next step
algBut.doStuff();
}
if (e.getKeyCode() == KeyEvent.VK_A) {
//all steps
allgBut.doStuff();
}
if (e.getKeyCode() == KeyEvent.VK_R) {
//reset
resBut.doStuff();
}
if (e.getKeyCode() == KeyEvent.VK_P) {
//add Points
randBut.doStuff();
}
if (e.getKeyCode() == KeyEvent.VK_S) {
//reset but keep old points
oldresBut.doStuff();
}
if (e.getKeyCode() == KeyEvent.VK_V ) {
//reset zoom
resetz.doStuff();
}
}
|
18b78af5-7584-4f2f-b9ea-2e86bd669aeb
| 0
|
public void mouseEntered(MouseEvent e) {}
|
92bb7726-59ae-4a6a-a732-a6a91893bc1b
| 3
|
public static void blockUntilProcessEnd(Process process, int timeOut) {
int maxCount = timeOut * 5;
for (int i = 0; i < maxCount && checkProcessEnd(process); i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
logger.error(e);
}
}
}
|
1dcd896e-1564-49e0-af2b-fda37db21aa1
| 5
|
@Override
public void mouseReleased (MouseEvent e) {
if (alg.isProcess()) {
return;
}
int i = getRowByMouseX(e.getX());
int j = getColumnByMouseY(e.getY());
draggedCell = null;
alg.reset();
if (e.getButton() == MouseEvent.BUTTON1 && alg.getCell(i, j) instanceof EmptyCell) {
alg.setCell(i, j, new Wall());
} else if (e.getButton() == MouseEvent.BUTTON3 && alg.getCell(i, j) instanceof Wall) {
alg.setCell(i, j, new EmptyCell());
}
}
|
aae70308-452e-4549-bcc8-66a90c1dd126
| 0
|
public void updateFile(File file){
this.file = file;
}
|
f8e58c7c-2677-440d-a1fc-a009119e481f
| 7
|
* @param unit The missionary <code>Unit</code>.
* @param settlement The <code>IndianSettlement</code> to establish at.
* @return An <code>Element</code> encapsulating this action.
*/
public Element establishMission(ServerPlayer serverPlayer, Unit unit,
IndianSettlement settlement) {
ChangeSet cs = new ChangeSet();
csSpeakToChief(serverPlayer, settlement, false, cs);
Unit missionary = settlement.getMissionary();
if (missionary != null) {
ServerPlayer enemy = (ServerPlayer) missionary.getOwner();
enemy.csKillMissionary(settlement, cs);
}
// Result depends on tension wrt this settlement.
// Establish if at least not angry.
switch (settlement.getAlarm(serverPlayer).getLevel()) {
case HATEFUL: case ANGRY:
cs.add(See.perhaps().always(serverPlayer),
(FreeColGameObject) unit.getLocation());
cs.addDispose(See.perhaps().always(serverPlayer),
unit.getLocation(), unit);
break;
case HAPPY: case CONTENT: case DISPLEASED:
cs.add(See.perhaps().always(serverPlayer), unit.getTile());
unit.setLocation(null);
unit.setMovesLeft(0);
cs.add(See.only(serverPlayer), unit);
settlement.changeMissionary(unit);
settlement.setConvertProgress(0);
List<FreeColGameObject> modifiedSettlements
= ((ServerIndianSettlement)settlement).modifyAlarm(serverPlayer,
ALARM_NEW_MISSIONARY);
modifiedSettlements.remove(settlement);
if (!modifiedSettlements.isEmpty()) {
cs.add(See.only(serverPlayer), modifiedSettlements);
}
break;
}
Tile tile = settlement.getTile();
tile.updatePlayerExploredTile(serverPlayer, true);
cs.add(See.perhaps().always(serverPlayer), tile);
String messageId = "indianSettlement.mission."
+ settlement.getAlarm(serverPlayer).getKey();
cs.addMessage(See.only(serverPlayer),
new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY,
messageId, serverPlayer, unit)
.addStringTemplate("%nation%", settlement.getOwner().getNationName()));
// Others can see missionary disappear and settlement acquire
// mission.
sendToOthers(serverPlayer, cs);
return cs.build(serverPlayer);
}
|
ae421201-9f91-4704-86ef-1c34806427a6
| 0
|
public boolean getPassedPoint(int i){
return passedPoint[i];
}
|
0fef88ad-2d46-4240-8957-89ade5d46acc
| 7
|
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
handleLogin((Packet00Login) packet, address, port);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("CLIENT] [" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect) packet).getUsername() + " has left the game...");
game.playerMP = null;
JOptionPane.showMessageDialog(null, ((Packet01Disconnect) packet).getUsername() + " has quit the game", Bootstrap.getTitle(), JOptionPane.ERROR_MESSAGE);
Window.restartApp(true);
break;
case MOVE:
packet = new Packet02Move(data);
handleMove((Packet02Move) packet);
case CLICK:
packet = new Packet03Click(data);
this.handleClick(((Packet03Click) packet));
case START:
packet = new Packet04Start(data);
this.handleStart(((Packet04Start) packet));
case RESPONES:
packet = new Packet05Response(data);
this.handleResponse(((Packet05Response) packet));
}
}
|
cbff35ca-bdf2-4d56-839c-367b60ec91c2
| 7
|
@SuppressWarnings("unchecked")
private static <T extends Object> T getValue(T object, String strFieldName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Class<T> d = (Class<T>)object.getClass();
T e = object;
String[] fieldnames = strFieldName.split("\\.");
for (int i = 0; i < fieldnames.length; i++)
{
String name = fieldnames[i];
StringBuilder newName = new StringBuilder(name.length());
for (int k = 0; k < name.length(); k++)
{
if (k == 0)
{
newName.append(Character.toUpperCase(name.charAt(k)));
}
else
{
newName.append(name.charAt(k));
}
}
Method[] methods = d.getMethods();
Method tobeinvoked = null;
for (int j = 0; j < methods.length; j++)
{
if (("get" + newName.toString()).equals(methods[j].getName()))
{
tobeinvoked = methods[j];
break;
}
}
if (tobeinvoked == null)
{
return null;
}
e = (T)tobeinvoked.invoke(e, new Object[0]);
if (e == null)
{
return null;
}
d = (Class<T>)e.getClass();
}
return e;
}
|
a3a3ba6c-3d84-46bb-a8d8-91d4162dff76
| 0
|
public String getTaxes(String s)
{
String taxValue = "17";
return taxValue;
};
|
719dce52-76eb-4bd4-8431-b85ae9db6d73
| 6
|
public void getTransitionsFromCPN(Document doc, PetriNet pn) {
NodeList transList = doc.getElementsByTagName("trans");
for (int i = 0; i < transList.getLength(); i++) {
Node nNode = transList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
int id = Integer.parseInt(eElement.getAttribute("id").substring(2));
int x, y, width, height;
String name;
x = (int) Double.parseDouble(((Element) eElement.getElementsByTagName("posattr").item(0)).getAttribute("x"));
y = (int) Double.parseDouble(((Element) eElement.getElementsByTagName("posattr").item(0)).getAttribute("y"));
width = (int) Double.parseDouble(((Element) eElement.getElementsByTagName("box").item(0)).getAttribute("w"));
height = (int) Double.parseDouble(((Element) eElement.getElementsByTagName("box").item(0)).getAttribute("h"));
name = eElement.getElementsByTagName("text").item(0).getTextContent();
if (x < minX) {
minX = x;
}
if (y < minY) {
minY = y;
}
if (x > maxX) {
maxX = x;
}
if (y > maxY) {
maxY = y;
}
Transition t = new Transition(name);
t.setX(x);
t.setY(y);
t.setWidth(width);
t.setHeight(height);
t.setColor(new Color(10, 10, 10));
t.setColor2(new Color(255, 255, 255));
t.setFontSize(16);
tranIDs.add(id);
pn.addTransition(t);
}
}
}
|
9583a449-c187-41fb-ae14-54e8d906048c
| 1
|
public void addSegment(Segment s){
if(s.getRoadID() == this.roadID){
segments.add(s);
}
}
|
d0278d50-8705-4cfc-b8f3-d392bc07a8fa
| 0
|
public float getK() {
return this.k;
}
|
74b342e4-db92-4b7d-8d55-2c95de9a0461
| 5
|
public Elevator callDown(Rider r){
int startFloor = r.getFrom();
while(true) {
for(Elevator e : elevators) {
synchronized(e){
if(!e.isGoingUp() && e.getFloor()>startFloor) {
e.addRequest(r);
return e;
}
else if(!e.isInTransit()) {
e.addRequest(r);
return e;
}
}
}
}
}
|
3279e250-ebc3-4508-997a-98670e43ba78
| 3
|
public static TreeSet<Association> mergeArrays(
ArrayList<Association> associations,
ArrayList<Association> fClusterAssociations,
ArrayList<Association> left) {
TreeSet<Association> combine = new TreeSet<Association>();
for (Association a : associations)
combine.add(a);
for (Association a : fClusterAssociations)
combine.add(a);
for (Association a : left)
combine.add(a);
return combine;
}
|
d3371fe9-dd29-4bb2-8791-6aae3ea705bb
| 7
|
public void updatePositions() {
playerAlive = new ArrayList<ChessPiece>();
aiAlive = new ArrayList<ChessPiece>();
for (int i = 0; i < gameState.length; i++) {
for (int j = 0; j < gameState[0].length; j++) {
gameState[i][j].setRow(i);
gameState[i][j].setCol(j);
if (gameState[i][j].getColor() == playerColor) {
playerAlive.add(gameState[i][j]);
}
else if (gameState[i][j].getColor() == aiColor) {
aiAlive.add(gameState[i][j]);
}
}
}
if (DEBUG) {
for (int i = 0; i < gameState.length; i++) {
for (int j = 0; j < gameState[0].length; j++) {
System.out.print(gameState[i][j].getColor() + " ");
}
System.out.println();
}
}
}
|
1e8491b2-044f-45c0-be75-2248a52b1142
| 7
|
@Override
protected void repondreExtension(HttpServletRequest requete, HttpServletResponse reponse, String action, Utilisateur utilisateur) throws ServletException, IOException {
if (utilisateur != null) {
throw new DejaConnecteException();
}
String pseudo = requete.getParameter(Chaine.PSEUDO);
if (pseudo == null) {
requete.setAttribute("erreur", "Aucun pseudo envoyé");
requete.getRequestDispatcher(UrlService.page("site/connexion.jsp")).forward(requete, reponse);
return;
}
pseudo = pseudo.toLowerCase();
Utilisateur u = UtilisateurRepo.get().duPseudo(pseudo);
if (u == null) {
requete.setAttribute("erreur", "Pseudo invalide");
requete.getRequestDispatcher(UrlService.page("site/connexion.jsp")).forward(requete, reponse);
return;
}
String motDePasse = requete.getParameter(Chaine.MOT_DE_PASSE);
if (motDePasse == null || !u.motDePasseValide(motDePasse)) {
requete.setAttribute("erreur", "Mot de passe invalide");
requete.getRequestDispatcher(UrlService.page("site/connexion.jsp")).forward(requete, reponse);
return;
}
if (!u.getCompteActive()) {
requete.setAttribute("erreur", "Le compte n'est pas actif");
requete.getRequestDispatcher(UrlService.page("site/connexion.jsp")).forward(requete, reponse);
return;
}
requete.getSession().setAttribute(Chaine.UTILISATEUR, u);
String pageVoulue = UrlService.pageVoulue(requete);
if (pageVoulue != null)
reponse.sendRedirect(pageVoulue);
else
reponse.sendRedirect("/");
}
|
e88171f4-43bc-4192-bffb-dd0053329954
| 2
|
public void setWindowPadding(int[] padding) {
if ((padding != null) && (padding.length != 4)) {
IllegalArgumentException iae = new IllegalArgumentException("The padding-array must have four elements!");
Main.handleUnhandableProblem(iae);
}
this.window_Padding = padding;
somethingChanged();
}
|
49f112e1-b152-4280-a7d6-bc812e4f24ee
| 4
|
private Particulier createParticulier(HttpServletRequest request) throws Exception{
String email = request.getParameter("email"),
motDePasse = request.getParameter("motdepasse"),
motDePasse2 = request.getParameter("motdepasse2"),
nom = request.getParameter("nom"),
prenom = request.getParameter("prenom"),
titre = request.getParameter("titre"),
rue = request.getParameter("rue"),
ville = request.getParameter("ville"),
province = request.getParameter("province"),
codepostale = request.getParameter("codepostale"),
pays = request.getParameter("pays");
//Verification qu'aucun parametre est a nul.
for (String parametre:
new String[]{
email.trim(),
motDePasse,
motDePasse2,
nom,
prenom,
titre,
rue,
ville,
province,
codepostale,
pays,
}
) if (parametre==null)
throw new Exception("Un parametre obligatoire n'est pas définit.");
if(!motDePasse.equals(motDePasse2))
throw new Exception("Le mot de passe de confirmation est différent du mot de passe.");
String adresse = rue+" "+ville+" "+province+" "+pays+" "+codepostale;
Particulier particulier = new Particulier(email.trim(), motDePasse, nom, prenom, titre, adresse);
ParticulierDAO particulierDAO = new ParticulierDAO();
if(!particulierDAO.create(particulier))
throw new Exception("Une erreur inconnue empeche la création du compte.");
return particulier;
}
|
0cde5921-4b27-49b3-a766-695a4b29f877
| 7
|
public void run() {
//open a socket to the server and send data
try {
//get the user command (put, get, delete)
if(this.commandType.equals("put") || this.commandType.equals("del") || this.commandType.equals("reb")) {
//System.out.println("issuing put to server");
getServerResponse();
}
else if(this.commandType.equals("get")) {
//save the file
FileOutputStream fos = new FileOutputStream("FromDFS/" + this.fileToSaveAs);
fos.write(this.getServerResponse());
fos.close();
}
} catch (ConnectException e) {
//issue connecting to server assume it failed
//e.printStackTrace();
Thread.currentThread().interrupt();
return;
} catch (EOFException e) {
//issue connecting to server assume it failed
//e.printStackTrace();
//if(this.commandType.equals("get")) {
// System.out.println("DFS file not found.");
//}
Thread.currentThread().interrupt();
return;
} catch (IOException e) {
e.printStackTrace();
}
}
|
6f582f6c-c85e-4ba9-b568-b399d3a1945f
| 6
|
public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random)
{
if (!par1World.isRemote)
{
int var6 = par1World.getBlockMetadata(par2, par3, par4);
if ((var6 & 8) != 0)
{
par1World.setBlockMetadataWithNotify(par2, par3, par4, var6 & 7);
par1World.notifyBlocksOfNeighborChange(par2, par3, par4, this.blockID);
int var7 = var6 & 7;
if (var7 == 1)
{
par1World.notifyBlocksOfNeighborChange(par2 - 1, par3, par4, this.blockID);
}
else if (var7 == 2)
{
par1World.notifyBlocksOfNeighborChange(par2 + 1, par3, par4, this.blockID);
}
else if (var7 == 3)
{
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 - 1, this.blockID);
}
else if (var7 == 4)
{
par1World.notifyBlocksOfNeighborChange(par2, par3, par4 + 1, this.blockID);
}
else
{
par1World.notifyBlocksOfNeighborChange(par2, par3 - 1, par4, this.blockID);
}
par1World.playSoundEffect((double)par2 + 0.5D, (double)par3 + 0.5D, (double)par4 + 0.5D, "random.click", 0.3F, 0.5F);
par1World.markBlocksDirty(par2, par3, par4, par2, par3, par4);
}
}
}
|
baf68618-59cc-4be5-8e56-c5e5f00a98d8
| 4
|
public static int editex(String string1, String string2){
char[] str1 = ("#" + string1).toCharArray();
char[] str2 = ("#" + string2).toCharArray();
int length1, length2;
length1 = str1.length;
length2 = str2.length;
int F[][] = new int[length1][length2];
int dStr1[] = new int[length1-1];
int dStr2[] = new int[length2-1];
F[0][0] = 0;
for(int i = 1; i < length1; i++) {
dStr1[i-1] = d(str1[i-1],str1[i]);
F[i][0] = F[i-1][0] + dStr1[i-1];
}
for(int i = 1; i < length2; i++) {
dStr2[i-1] = d(str2[i-1],str2[i]);
F[0][i] = F[0][i-1] + dStr2[i-1];
}
for(int i = 1; i < length1; i++) {
for(int j = 1; j < length2; j++) {
F[i][j] = min3(F[i - 1][j] + dStr1[i - 1],
F[i][j - 1] + dStr2[j - 1],
F[i - 1][j - 1] + r(str1[i], str2[j]));
}
}
return F[length1-1][length2-1];
}
|
fc8fd82b-f8e5-4c88-be64-f9d0fade9b47
| 1
|
public void setComponent(GuiComponent component) {
InputHandler.getInstance().clearAll();
if (activeComponent != null) {
activeComponent.deactivate();
}
component.activate();
activeComponent = component;
}
|
45966c2e-e6a8-4bc6-91e5-45f63a791a08
| 0
|
public void setFesEstado(String fesEstado) {
this.fesEstado = fesEstado;
}
|
9c52675d-aa47-4324-a8fa-fb31c5c2dc36
| 4
|
private void setOthers(ColorFilter filter, String replacing, String test, int testValue, int otherValue, int testGap, int otherGap, int shift) {
boolean set = false;
if (shift == LEFT_SHIFT) {
filter.setShift("left");
} else if (shift == RIGHT_SHIFT) {
filter.setShift("right");
} else {
if (replacing.toLowerCase().equals(labels[2].toLowerCase())) {
filter.setShift("left");
} else {
filter.setShift("right");
}
}
if (replacing.toLowerCase().equals(test)) {
filter.setMeasuresByCamera(testValue);
filter.setKeeping(otherValue);
filter.setGap(testGap);
} else {
filter.setMeasuresByCamera(otherValue);
filter.setKeeping(testValue);
filter.setGap(otherGap);
}
}
|
736d0f88-15c0-43b0-be4c-7fac80794c6c
| 3
|
private static byte[][] InvShiftRows(byte[][] state) {
byte[] t = new byte[4];
for (int r = 1; r < 4; r++) {
for (int c = 0; c < Nb; c++)
t[(c + r)%Nb] = state[r][c];
for (int c = 0; c < Nb; c++)
state[r][c] = t[c];
}
return state;
}
|
c626c730-9707-4dea-8694-841fa7e2052c
| 4
|
@Override
public String execute() {
Polynomial result = new Polynomial();
Multiply mul = new Multiply();
Sum sum = new Sum();
Polynomial minus = new Polynomial();
Polynomial temp;
Term c;
minus.addTerm(-1,1,0);
Term a = divisor.termAt(0);
Term b = dividend.termAt(0);
if(a.getExponent()==0){
dividend.divideWithCoeff(a.getCoefficient());
return dividend.toString();
}
if(a.getExponent()>b.getExponent()){
return "(" + dividend + ")/(" + divisor + ")";
}
while(a.getExponent()<=b.getExponent()){
int div[] = fraction.division(b.getCoefficient()[0], b.getCoefficient()[1], a.getCoefficient()[0], a.getCoefficient()[1]);
c = new Term(div[0],div[1],b.getExponent()-a.getExponent());
result.addTerm(c);
temp=new Polynomial();
temp.addTerm(c);
temp=mul.multiplyTwo(temp,divisor);
temp=mul.multiplyTwo(temp, minus);
dividend=sum.sum(dividend, temp);
b=dividend.termAt(0);
}
if(dividend.toString().equals("0")){
return result.toString();
}else{
dividend.reduce();
return result.toString() + " and the remainder is " + dividend.toString();
}
}
|
b7497c47-3b44-4976-b8d7-85951f9af879
| 3
|
public Dimension getSize() {
Dimension dim = super.getSize();
if (!layingOut) {
if (isAutoPopupWidth) {
popupWidth = getOptimumPopupWidth();
}
if (popupWidth != 0) {
dim.width = popupWidth;
}
}
return dim;
}
|
cbf0dcff-c04a-422e-ac10-cb888df6e572
| 1
|
public boolean opEquals(Operator o) {
return (o instanceof ThisOperator && ((ThisOperator) o).classInfo
.equals(classInfo));
}
|
487cbe59-7c8e-4a6c-b7f6-bbcd3bb67576
| 8
|
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
U = true;
break;
case KeyEvent.VK_W:
U = true;
break;
case KeyEvent.VK_DOWN:
D = true;
break;
case KeyEvent.VK_S:
D = true;
break;
case KeyEvent.VK_LEFT:
L = true;
break;
case KeyEvent.VK_A:
L = true;
break;
case KeyEvent.VK_RIGHT:
R = true;
break;
case KeyEvent.VK_D:
R = true;
break;
}
}
|
fbe1d6a2-fa42-4756-ac69-fd4a90b39123
| 8
|
private void movement() {
if (game.getInput().down.down) {
if (canDown)
game.yOffset += speed;
directionFacing = Down;
}
if (game.getInput().up.down) {
if (canUp)
game.yOffset -= speed;
directionFacing = Up;
}
if (game.getInput().left.down) {
if (canLeft)
game.xOffset -= speed;
directionFacing = Left;
}
if (game.getInput().right.down) {
if (canRight)
game.xOffset += speed;
directionFacing = Right;
}
}
|
a176eeda-516f-416e-9d0b-a1f60dacd215
| 3
|
public ArrayList<Integer> getTransitionStartToGoal( int startID, int goalID ){
ArrayList<Integer> transition = new ArrayList<Integer>();
transition.add( goalID );
while(true){
int to = transition.get(transition.size()-1);
int from = getNode(to).getFromID();
if( from < 0){ //どこからもたどり着かなかった
break;
}
transition.add(from);
if( from == startID ){
break;
}
}
Collections.reverse(transition);
return transition;
}
|
4c95def5-19c4-4241-8c88-f243f028e333
| 0
|
public DriveTrain() {
_leftEncoder.start();
_rightEncoder.start();
LiveWindow.addSensor ("Drive Train", "Gyro", _gyro);
LiveWindow.addSensor ("Drive Train", "Left Encoder", _leftEncoder);
LiveWindow.addSensor ("Drive Train", "Right Encoder", _rightEncoder);
}
|
64b8b9a2-a7dd-40c5-819f-4f469b0d1f51
| 6
|
public void drawGeometry(Graphics g) {
int radius = (int) ((Math.abs(topLeft.distance(bottomRight))));
if ((topLeft.y > bottomRight.y) && (topLeft.x < bottomRight.x)) {
g.drawOval(topLeft.x, bottomRight.y, radius, radius);
} else if ((topLeft.y < bottomRight.y) && (topLeft.x >bottomRight.x)) {
g.drawOval(bottomRight.x, topLeft.y, radius, radius);
} else if (topLeft.y < bottomRight.y) {
g.drawOval(topLeft.x, topLeft.y, radius, radius);
} else if (topLeft.y > bottomRight.y) {
g.drawOval(bottomRight.x, bottomRight.y, radius, radius);
}
}
|
d21275af-64b6-4097-8f4d-a270e571a207
| 1
|
@Override
public List<Pessoa> Buscar(Pessoa obj) {
String consulta = "select l from Pessoa l";
if(obj != null){
consulta = consulta + " where l.nome like '%" + obj.getNome() + "%'";
}
Query q = manager.createQuery(consulta);
return q.getResultList();
}
|
88c64b13-e725-4a7d-8efc-19795ae0ed38
| 1
|
public final void comment(final char[] ch, final int off, final int len)
throws SAXException {
try {
closeElement();
writeIdent();
w.write("<!-- ");
w.write(ch, off, len);
w.write(" -->\n");
} catch (IOException ex) {
throw new SAXException(ex);
}
}
|
76de0827-d853-48e8-b84c-715cb7437f68
| 7
|
public void addNode(Node node) {
if (node instanceof StartEvent) {
if (startEvent != null && startEvent != node) {
throw new ASFModelException("Multiple StartEvent has been found!");
}
this.startEvent = (StartEvent) node;
} else if (node instanceof EndEvent) {
if (endEvent != null && endEvent != node) {
throw new ASFModelException("Multiple EndEvent has been found!");
}
this.endEvent = (EndEvent) node;
}
nodes.put(node.getId(), node);
node.setParent(parentNode);
if (node instanceof AbstractNode) {
((AbstractNode) node).setDefinition(this);
}
}
|
6f4ca593-4a0c-4aeb-a1da-dadc5e5e3861
| 7
|
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((tickID==Tickable.TICKID_TRAP_RESET)&&(getReset()>0))
{
// recage the motherfather
if((tickDown<=1)&&(monsters!=null))
{
for(int i=0;i<monsters.size();i++)
{
final MOB M=monsters.get(i);
if(M.amDead()||(!M.isInCombat()))
M.destroy();
}
monsters=null;
}
}
return super.tick(ticking,tickID);
}
|
f2383f5e-01a4-4b46-bbfe-e4bb0a4e4e04
| 7
|
private String setFPCBindings(String script)
{
Bindings engineBindings = getContext().getBindings(ScriptContext.ENGINE_SCOPE);
Bindings globalBindings = getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
StringBuilder varNames = new StringBuilder();
for (String key : engineBindings.keySet())
{
if (!key.matches("\\w+[\\w\\d_]")) //Not a valid variable name
{
continue;
}
varNames.append(key).append(StringPool.COMA);
}
if (globalBindings != null)
{
for (String key : globalBindings.keySet())
{
if (!key.matches("\\w+[\\w\\d_]")) //Not a valid variable name
{
continue;
}
varNames.append(key).append(StringPool.COMA);
}
}
String vars = varNames.toString();
if (vars.endsWith(StringPool.COMA)) // should be if var is not nul
{
vars = vars.substring(0, vars.length()-1) + ":JLObject;";
}
if (vars.isEmpty())
{
return script;
} else
{
return script.replace("{$binding_vars$}", vars);
}
}
|
8c3d0a96-94d1-4b30-946f-b38ccb4bd8e5
| 9
|
private void printKClosest(int arr[],int x,int k){
//Find the Crossover point to get the left index
int left=findCrossOver(arr,0,arr.length-1,x);
//Find the right index
int right=left+1;
//To Keep track of the elements already counted
int count=0;
//if the element is present in the array then decreement left index
if(arr[left]==x)
left--;
//Print the k elements
while(left>=0 && right<arr.length && count<k){
if(x-arr[left] < arr[right]-x)
System.out.print(arr[left--]+" ");
else
System.out.print(arr[right++]+" ");
count++;
}
while(count<k && left>=0){
System.out.print(arr[left--]+" ");
}
while(count<k && right<arr.length){
System.out.print(arr[right++]+" ");
}
}
|
8bdf0c8e-299c-4b3e-8cc1-dff1855f23a8
| 4
|
public void mouseDown(MouseEvent event) {
if (event.button != 1) return;
getPaintSurface().setStatusMessage(PaintExample.getResourceString(
"session.SegmentedInteractivePaint.message.interactiveMode"));
previousFigure = currentFigure;
if (controlPoints.size() > 0) {
final Point lastPoint = (Point) controlPoints.elementAt(controlPoints.size() - 1);
if (lastPoint.x == event.x || lastPoint.y == event.y) return; // spurious event
}
controlPoints.add(new Point(event.x, event.y));
}
|
b0412f49-5ca9-4d43-95d4-4831c0daaa8f
| 4
|
@Override
protected T readNext() {
try {
if (reader.ready()) {
while ((line = reader.readLine()) != null) { // Read a line (only if needed)
if (!line.trim().isEmpty()) { // Non empty line? Create object
lineNum++;
return createObject(line);
}
}
}
} catch (IOException e) {
return null;
}
return null;
}
|
c472253c-e16a-4648-8890-7fa16ddbc366
| 8
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(!CMLib.flags().isAliveAwakeMobile(mob,false))
return false;
final Ability A=mob.fetchEffect(ID());
if(A!=null)
{
A.unInvoke();
mob.tell(L("You end your all-out defensive posture."));
return true;
}
if(!mob.isInCombat())
{
mob.tell(L("You must be in combat to defend!"));
return false;
}
if((!auto)&&(!(CMLib.flags().isGood(mob))))
{
mob.tell(L("You don't feel worthy of a good defence."));
return false;
}
if(!super.invoke(mob,commands,mob,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_CAST_SOMANTIC_SPELL,L("^S<S-NAME> assume(s) an all-out defensive posture.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
fullRound=false;
beneficialAffect(mob,mob,asLevel,Ability.TICKS_FOREVER);
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> attempt(s) to assume an all-out defensive posture, but fail(s)."));
// return whether it worked
return success;
}
|
598d8db5-88c6-4c24-ad22-a65e30e5b1bf
| 6
|
public double Daf2r(int ideg, int iamin, double asec) throws palError {
/* Preset status */
Status = 0;
double rad = 0.0;
TRACE("Daf2r");
/* Validate arcsec, arcmin, deg */
if ((asec < 0.0) || (asec >= 60.0)) {
Status = 3;
throw new palError(Status, "Daf2r: asec outside range 0-59.999...");
}
if ((iamin < 0) || (iamin > 59)) {
Status = 2;
throw new palError(Status, "Daf2r: iamin outside range 0-59");
}
if ((ideg < 0) || (ideg > 359)) {
Status = 1;
throw new palError(Status, "Daf2r: ideg outside range 0-359");
}
/* Compute angle */
rad = DAS2R * (60.0 * (60.0 * ideg + iamin) + asec);
ENDTRACE("Daf2r");
return rad;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.