method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
93d022ed-3906-4923-954a-92350dd609da | 3 | @Override
protected int getAvgIndex(ChannelType c) {
switch (c) {
case RED:
return 0;
case GREEN:
return 1;
case BLUE:
return 2;
default:
throw new IllegalArgumentException();
}
} |
eab9a69d-f621-41ed-83bb-2dda109008e9 | 0 | public boolean isClosed() {
return isClosed;
} |
7706ca7d-083c-4b6c-95f1-fc27d80de12a | 7 | private final void step6() {
j = k;
if (b[k] == 'e') {
int a = m();
if (a > 1 || a == 1 && !cvc(k - 1))
k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1)
k--;
} |
30d7d612-1edb-451e-8179-dbea34315000 | 8 | public boolean createAccount() {
Scanner sc = new Scanner(System.in);
boolean success = false;
String posUsername, posPassword, firstName, lastName; //Possible username/password.
int attempts = 0;
while (attempts < 3) { //At three attempts, the user is booted back to the main screen.
System.out.print("Enter a username: ");
posUsername = sc.nextLine();
System.out.print("Enter a password: ");
posPassword = sc.nextLine();
System.out.print("Enter your first name: ");
firstName = sc.nextLine();
System.out.print("Enter your last name: ");
lastName = sc.nextLine();
if(posUsername.equals("admin2011")) { //Checks if the user is trying to use the admin username/pw.
System.out.println("Username is in use. Please try again. " +
(2-attempts) + " more attempts.\n");
attempts++;
continue;
}
else if(Usernames.contains(posUsername)) { //Checks to see if the username is in use.
System.out.println("Username is in use. Please try again. " +
(2-attempts) + " more attempts.\n");
attempts++;
continue;
}
else //Checks formatting of possible username and passwords.
{
if(checkUsername(posUsername) == true && checkPassword(posPassword) == true) { //If both the username and password check out to be correct formatting,
setFirstName(firstName); // the program continues back to the main screen.
setLastName(lastName);
setUsername(posUsername);
setPassword(posPassword);
Customers.add(this);
System.out.println("\nYou were successfully added to the system with the following:\n" +
"Username: " + this.username + "\nPassword: " + this.password + "\n");
success = true;
attempts = 3;
break;
}
else if(checkUsername(posUsername) == false && checkUsername(posPassword) == false) {
System.out.println("Both username and password formatting is incorrect. " +
(2-attempts) + " more attempts.\n");
attempts++;
continue;
}
else if(checkUsername(posUsername) == false) {
System.out.println("Incorrect username format. Please try again. " +
(2-attempts) + " more attempts.\n");
attempts++;
continue;
}
else {
System.out.println("Incorrect password format. Please try again. " +
(2-attempts) + " more attempts.\n");
attempts++;
continue;
}
}
}
return success;
} |
da60dcec-7927-4970-bb29-26984837cdab | 8 | private void addResources(int dices)
{
// Liste des tuiles correspondante au nombre des des.
LinkedList<ResourceTile> tiles = new LinkedList<ResourceTile>();
// Pour chaque tuile ressource.
for(int i: resourceIndexes)
{
ResourceTile t = (ResourceTile)grid[i];
if (t.isNumber(dices) && !t.hasThief()) // Si la tuile porte le numero des des et que le voleur n'est pas sur la tuile.
{
tiles.add((ResourceTile) grid[i]); // Ajoute la tuile a la liste.
}
}
// Affecte les ressources aux joueurs possedant une ville autour de la/des tuiles correspondantes.
for (ResourceTile r: tiles) { // Pour chaque tuile avec le numero des des.
for (Town t: r.getNeighbours()) { // Pour chaque ville voisine de la tuile.
for (Player p: players) { // Pour chaque joueur.
if (p.getTowns().contains(t)) { // Si le joueur possede la ville.
p.addResource(r.getResource()); // Incrementer les reserves de la ressource correspondant a la tuile de 1 unite.
if (t.isTown()) p.addResource(r.getResource()); // S'il s'agit d'une ville (et non d'une colonie), incremente les reserves du joueur une seconde fois.
}
}
}
}
} |
658aa42c-9243-4ebe-8d76-6d1924f6cb13 | 9 | public String getAnswer() throws Exception {
String [] input = getResource("problem59.txt").readLine().split(",");
int[] letters = new int[input.length];
int[] key = new int[3];
List<Map<Integer,Integer>> freqAnalysis = new ArrayList<Map<Integer,Integer>>(key.length);
int retVal = 0;
for (int i = 0;i<key.length;i++)
freqAnalysis.add(new HashMap<Integer, Integer>());
for (int i = 0;i<input.length;i++) {
Map<Integer,Integer> set = freqAnalysis.get(i % freqAnalysis.size());
Integer letter = new Integer(input[i]);
letters[i] = letter;
if (set.containsKey(letter))
set.put(letter, set.get(letter) + 1);
else
set.put(letter,1);
}
for (int i = 0;i<key.length;i++) {
int mostFrequent = 0;
int maxFound = 0;
for (Entry<Integer, Integer> frequency : freqAnalysis.get(i).entrySet()) {
if (frequency.getValue() > maxFound) {
mostFrequent = frequency.getKey();
maxFound = frequency.getValue();
}
}
//find character that will make most frequent.
for (int j = 97;i<123;j++) {
//Looking for the most frequent character to be a space. otherwise look for e.
if ((j^mostFrequent) == 32) {
key[i] = j;
break;
}
}
}
for (int i = 0;i<letters.length;i++)
retVal += (letters[i] ^ key[i%key.length]);
return Integer.toString(retVal);
} |
60a516a5-b2ad-4e77-9887-057a939d6493 | 9 | @Override
public void panelResize() {
for (Node current : reachable) {
for (Node to : current.expand()) {
//from is not in cover
if (reachable.contains(to)) {
publish(new HighlightEdge(layer, current, to, Color.RED));
}
}
}
for (Node current : unreachable) {
for (Node to : current.expand()) {
//from is not in cover
if (!cover.contains(to)) {
publish(new HighlightEdge(layer, current, to, Color.RED));
}
}
publish(new HighlightPoint(layer, current, notCovered));
}
for (Node current : cover) {
for (Node to : current.expand()) {
//highlight edge
//both edge's nodes are covered
if (cover.contains(to)) {
publish(new HighlightEdge(layer, current, to, Color.YELLOW));
} else {
publish(new HighlightEdge(layer, current, to, Color.GREEN));
//point
publish(new HighlightPoint(layer, to, reachablePoint));
}
}
publish(new HighlightPoint(layer, current, coveredPoint));
}
} |
90ec8c96-eb28-405b-8107-4bf4d898d138 | 9 | protected int getSquareIndex(int x, int y)
{
int squareIndex = 0;
int offy = resx*y;
int offy1 = resx*(y+1);
if (posDiscrimination == false)
{
if (gridValue[x+offy] < isovalue) squareIndex |= 1;
if (gridValue[x+1+offy] < isovalue) squareIndex |= 2;
if (gridValue[x+1+offy1] < isovalue) squareIndex |= 4;
if (gridValue[x+offy1] < isovalue) squareIndex |= 8;
}
else
{
if (gridValue[x+offy] > isovalue) squareIndex |= 1;
if (gridValue[x+1+offy] > isovalue) squareIndex |= 2;
if (gridValue[x+1+offy1] > isovalue) squareIndex |= 4;
if (gridValue[x+offy1] > isovalue) squareIndex |= 8;
}
return squareIndex;
} |
5f53f39d-a716-4892-9338-6fc07ac6460a | 4 | private void proveedormedicamentoFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_proveedormedicamentoFieldKeyTyped
// TODO add your handling code here:
if (!Character.isLetter(evt.getKeyChar()) && !Character.isISOControl(evt.getKeyChar()) && !Character.isWhitespace(evt.getKeyChar()))
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
}
if(proveedormedicamentoField.getText().length() == 45)
{
Toolkit.getDefaultToolkit().beep();
evt.consume();
JOptionPane.showMessageDialog(this, "Nombre del proveedor demadiado largo.", "ADVERTENCIA", WIDTH);
}
}//GEN-LAST:event_proveedormedicamentoFieldKeyTyped |
64a6ca8e-6ab7-4f69-b9ae-18498759dcd9 | 1 | public static double getSleepFactor() {
double min = getSleepFactorMin();
double diff = getSleepFactorMax() - min;
if (diff == 0) {
return min;
}
return min + (new Random()).nextDouble() * diff;
} |
5d8d37d2-72f1-4192-95f0-1134848457a6 | 7 | private void listForGuessing(){
ArrayList<WordStructure> list = new ArrayList<WordStructure>(GuiBuilder.wordListAll);
try {
FileInputStream fileInputStream = new FileInputStream("settings.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Object rawSettings = objectInputStream.readObject();
mySettings = (Settings)rawSettings;
System.out.println("Разобрался");
System.out.println("GW| mySettings.guessWords: " + mySettings.getNumberOfGuessableWords());
System.out.println("GW| mySettings.kind: " + mySettings.getKindOfTrain());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int cnt = GuiBuilder.numberOfLinesInFile;
switch (mySettings.getKindOfTrain()) {
case 1:
case 2:
listForRepetition = GuiBuilder.wordListAll;
break;
case 3:
for(int i = 0; i < mySettings.getNumberOfGuessableWords(); i++){
Random rnd1 = new Random();
int k = rnd1.nextInt(cnt);
listForRepetition.add(list.get(k));
list.remove(k);
cnt--;
}
break;
default:
System.out.println("In listForGuessing variable kindOfTrain isn't 1,2 or 3!\n" +
"May be you not set some settings");
}
} |
b4e0f8ad-d86d-4bf5-8744-ef8663eca9ad | 2 | @Override
public String getPref(String key) {
for (String _key : preferences.keySet())
if (_key.equals(key))
return String.format("{0}; {1}", key, preferences.get(key));
return null;
} |
70df6513-8518-4698-ab31-7841a8298fac | 1 | @Test
public void testCreatingPhoneNumberWithNullLabelShouldFail() {
try {
new PhoneNumber(null, "12345678");
fail("Was expecting an Exception when no label is provided.");
} catch (IllegalArgumentException iae) {
Assert.assertEquals("Please provide a value for Label as it is a non-nullable field.", iae.getMessage());
}
} |
45c01a37-d4e4-4e5e-86e4-720f915d238f | 2 | public static synchronized void updateCoreVersion(String coreVersion) {
if (Main.coreVersion != null) {
if (!Main.coreVersion.equals(coreVersion)) {
logger.error("You use different Versions of Dynmaps");
System.exit(-1);
}
} else {
Main.coreVersion = coreVersion;
}
} |
a543f0e8-57bb-4549-b98d-a89780efcb9e | 4 | @Override
public void paint(Graphics g) {
super.paint(g);
if (running) {
if (state == 0) {
paintGame(g);
} else if (state == 1) {
paintGame(g);
paintPauseMenu(g);
} else if (state == 2) {
paintGame(g);
paintReconnect(g);
}
}
} |
b140024a-80a7-4346-9841-71e332e1f95e | 8 | public void renderProjectile(int xp, int yp, Projectile p) {
xp -= xOffset;
yp -= yOffset;
for (int y = 0; y < p.getSpriteSize(); y++) {
int ya = y + yp;
for (int x = 0; x < p.getSpriteSize(); x++) {
int xa = x + xp;
if (xa < -p.getSpriteSize() || xa >= width || ya < 0 || ya >= height) break;
if (xa < 0) xa = 0;
int col = p.getSprite().pixels[x+y*p.getSpriteSize()];
if (col != 0xffff00ff) pixels[xa+ya*width] = col;
}
}
} |
f82d7342-9ad6-4b09-a17b-0c071192b27b | 5 | @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 Software)) {
return false;
}
Software other = (Software) object;
if ((this.idSoftware == null && other.idSoftware != null) || (this.idSoftware != null && !this.idSoftware.equals(other.idSoftware))) {
return false;
}
return true;
} |
7038ea0d-faac-48f0-b59c-59039343e4fb | 2 | public static ParticleEffect fromId(int id) {
for (Entry<Integer, ParticleEffect> entry : ID_MAP.entrySet()) {
if (entry.getKey() != id) {
continue;
}
return entry.getValue();
}
return null;
} |
b4a34f2f-71a3-4506-bc66-8d1edd2cfe83 | 7 | static final void method3198(boolean bool, byte i) {
anInt9547++;
if (i != -45)
aShort9555 = (short) -74;
if (bool) {
if ((r.anInt9721 ^ 0xffffffff) != 0)
Class14.method235(r.anInt9721, (byte) -113);
for (Class348_Sub41 class348_sub41
= (Class348_Sub41) Class125.aClass356_4915.method3484(0);
class348_sub41 != null;
class348_sub41 = ((Class348_Sub41)
Class125.aClass356_4915.method3482(0))) {
if (!class348_sub41.method2712((byte) 4)) {
class348_sub41
= ((Class348_Sub41)
Class125.aClass356_4915.method3484(i ^ ~0x2c));
if (class348_sub41 == null)
break;
}
Class127_Sub1.method1118(true, false, class348_sub41, 2533);
}
r.anInt9721 = -1;
Class125.aClass356_4915 = new HashTable(8);
Class99.method882((byte) 11);
r.anInt9721 = Class285.anInt4737;
Class239.method1713(false, 520);
Class354.method3466(100);
ScriptExecutor.method703(r.anInt9721);
}
Class223.aBoolean2895 = false;
Class64_Sub3.playerPassword = Class186.playerUsername = "";
ModernLoadingScreen.method1448(-56);
Class362.anInt4458 = -1;
Class33.method338(i + 45, OndemandFileRequest.anInt10447);
Class132.localPlayer
= new Player();
((Class318_Sub1) Class132.localPlayer).xHash
= 512 * Class367_Sub4.mapSizeX / 2;
((Mob) Class132.localPlayer)
.xList[0]
= Class367_Sub4.mapSizeX / 2;
((Class318_Sub1) Class132.localPlayer).anInt6388
= 512 * Class348_Sub40_Sub3.mapSizeY / 2;
((Mob) Class132.localPlayer)
.yList[0]
= Class348_Sub40_Sub3.mapSizeY / 2;
Class286_Sub4.anInt6246 = Class59_Sub2_Sub2.anInt8685 = 0;
if ((Class348_Sub40_Sub21.anInt9282 ^ 0xffffffff) == -3) {
Class286_Sub4.anInt6246 = Class348_Sub35.anInt6981 << 813833481;
Class59_Sub2_Sub2.anInt8685 = Class275.anInt3550 << 1515187753;
} else
Class348_Sub21.method2954((byte) 62);
Class76.method773(true);
} |
91c78386-d974-49a8-9033-b1d44b994dc0 | 8 | public static String stripNonLongChars(final String value) {
final StringBuilder newString = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
final char c = value.charAt(i);
if (c == '.') {
// stop if we hit a decimal point
break;
} else if (c >= '0' && c <= '9' || c == '-') {
newString.append(c);
}
}
// check to make sure we do not have a single length string with
// just a minus sign
final int sLen = newString.length();
final String s = newString.toString();
if (sLen == 0 || sLen == 1 && "-".equals(s)) {
return "0";
}
return newString.toString();
} |
3833c51c-d36a-4c9f-84f0-ffcb0c6339f3 | 5 | public boolean canJump(int[] A) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
// boolean[] reach = new boolean[A.length];
// for (int i = 0; i < A.length; ++i){
// reach[i] = false;
// }
// reach[0] = true;
// int r = 0;
// if(A.length == 1){
// return true;
// }
// while (reach[r] && r < A.length) {
// for (int j = 1; j <= A[r]; ++j) {
// if (r + j >= A.length - 1) {
// return true;
// }
// reach[r + j] = true;
// }
// ++r;
// }
// return false;
int head = 0;
if(A.length == 1){
return true;
}
for (int i = 0; i < A.length && i <= head; ++i){
head = head > (A[i] + i) ? head : (A[i] + i);
if(head >= A.length - 1){
return true;
}
}
return false;
} |
e45ec78f-ce3e-44b3-a0b8-b01812a6f39e | 7 | @Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Diff other = (Diff) obj;
if (operation != other.operation)
{
return false;
}
if (text == null)
{
if (other.text != null)
{
return false;
}
}
else
if (!text.equals(other.text))
{
return false;
}
return true;
} |
682437cc-af1d-45d9-842b-cd21b76205a1 | 9 | private String getHeaderName(String columnName) {
String headerName = columnName;
if (columnName.equalsIgnoreCase(Buyer.getBuyerColumn())) {
// Buyer name
headerName = Buyer.BUYER_HEADER;
} else if (columnName.equalsIgnoreCase(Buyer.getLocationColumn())) {
// Location
headerName = Buyer.LOCATION_HEADER;
} else if (columnName.equalsIgnoreCase(Transaction.getCostColumn())) {
// Cost
headerName = Transaction.COST_HEADER;
} else if (columnName.equalsIgnoreCase(Transaction.getPriceColumn())) {
// Price
headerName = Transaction.PRICE_HEADER;
} else if (columnName.equalsIgnoreCase(Transaction.getProfitColumn())) {
// Profit
headerName = Transaction.PROFIT_HEADER;
} else if (columnName.equalsIgnoreCase(Transaction.getDateColumn())) {
// Date
headerName = Transaction.DATE_HEADER;
} else if (columnName.equalsIgnoreCase(Transaction.getItemNameColumn())) {
// Item Name
headerName = Transaction.ITEMNAME_HEADER;
} else if (columnName.equalsIgnoreCase(Category.getCategoryNameColumn())) {
// Category
headerName = Category.CATEGORY_HEADER;
} else if (columnName.equalsIgnoreCase(Category.getRateColumn())) {
// Rate
headerName = Category.RATE_HEADER;
}
return headerName;
} |
786fb70e-3a19-4bc5-8d15-76cb2a422f07 | 4 | public static HashMap<String, ClassNode> parseJar(JarFile jar) {
HashMap<String, ClassNode> classes = new HashMap<>();
try {
Enumeration<?> enumeration = jar.entries();
while (enumeration.hasMoreElements()) {
JarEntry entry = (JarEntry) enumeration.nextElement();
if (entry.getName().endsWith(".class")) {
ClassReader cr = new ClassReader(jar.getInputStream(entry));
ClassNode cn = new ClassNode();
cr.accept(cn, ClassReader.SKIP_DEBUG
| ClassReader.SKIP_FRAMES);
classes.put(cn.name, cn);
}
}
jar.close();
} catch (IOException e) {
e.printStackTrace();
}
return classes;
} |
dddd0769-25ab-4954-9bfd-e0d465ff2974 | 2 | public void actionPerformed(ActionEvent event) {
if (event.getActionCommand() == null) {
fadeEffect.start();
this.setTimerDelay();
} else {
switch (event.getActionCommand()) {
case "Effect Complete":
changePin(pinLoader.getRandomPin());
this.setTimerDelay();
break;
}
}
} |
8bc0728d-0747-4ec2-b260-f1ef02ccd558 | 7 | @Override
public Item findDepositInventory(String depositorName, String itemName)
{
final List<PlayerData> V=getRawPDDepositInventory(depositorName);
if(CMath.s_int(itemName)>0)
{
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData PD=V.get(v);
if(PD.xml().startsWith("COINS;"))
return makeItemContainer(PD.xml()).first;
}
}
else
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData PD=V.get(v);
if(PD.xml().lastIndexOf(";CONTAINER=",81)<0)
{
final Pair<Item,String> pair=makeItemContainer(PD.xml());
if(pair!=null)
{
if(CMLib.english().containsString(pair.first.Name(),itemName))
return pair.first;
pair.first.destroy();
}
}
}
return null;
} |
1de9a24e-ba93-4d23-af46-a9b03038974f | 8 | void solve() {
for (int i = 0; i < numberOfPoints; i++) { // zeros wavefunction
phi[i] = 0;
}
for (int i = 0; i < numberOfPoints; i++) {
phi[i] = state[0]; // stores wavefunction
x[i] = state[2];
solver.step(); // steps Schroedinger equation
if (Math.abs(state[0]) > stepThreshold) { // checks for diverging solution
break; // leave the loop
}
if ((state[0] >= 0 && phi[i] < 0)
|| (state[0] < 0 && phi[i] >= 0 && i != 0)) {
nodes++;
}
}
} |
2fafb142-031a-491e-8161-f78bf45881f0 | 6 | private boolean testFilterProperty_Thorough(SpecialFile other) {
List<Byte> one = new ArrayList<Byte>(this.BYTES);
List<Byte> two = new ArrayList<Byte>(other.BYTES);
double matchCount = 0.0d;
double totalCount = 0.0d;
if (one.size() > two.size()) {
double first = two.size();
double second = one.size();
totalCount = first / second;
} else {
double first = one.size();
double second = two.size();
totalCount = first / second;
}
Iterator<Byte> it1 = one.iterator();
Iterator<Byte> it2 = two.iterator();
boolean exitfast = this.filter.getThoroughExitFirstByteMisMatch();
while (it1.hasNext() && it2.hasNext()) {
if (it1.next() == it2.next()) {
matchCount += 1.0d;
continue;
}
if (exitfast)
return false;
}
if (!((matchCount / totalCount) >= this.filter.getPercentMatchThorough()))
return false;
return true;
} |
45f667d4-a250-4379-ba07-0b64b719803b | 8 | protected boolean sting()
{
if (CMLib.flags().isAliveAwakeMobileUnbound(this,true)&&
(CMLib.flags().canHear(this)||CMLib.flags().canSee(this)||CMLib.flags().canSmell(this)))
{
final MOB target = getVictim();
// ===== if it is less than three so roll for it
final int roll = (int)Math.round(Math.random()*99);
// ===== check the result
if (roll<20)
{
// Sting was successful
final CMMsg msg=CMClass.getMsg(this, target, null, CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_POISON, L("^F^<FIGHT^><S-NAME> sting(s) <T-NAMESELF>!^</FIGHT^>^?"));
CMLib.color().fixSourceFightColor(msg);
if(location().okMessage(target,msg))
{
this.location().send(target,msg);
if(msg.value()<=0)
{
final Ability poison = CMClass.getAbility("Poison");
if(poison!=null)
poison.invoke(this, target, true,0);
}
}
}
}
return true;
} |
e4c32454-eeda-4565-9eda-d080599323bc | 0 | @Test
public void compareHands_HighCardHandsHaveSameCardsExceptLastCard_HandsWithHigherFifthCardWins() {
Hand p1 = Hand.HighCard(Rank.King, Rank.Jack, Rank.Nine, Rank.Six, Rank.Five);
Hand p2 = Hand.HighCard(Rank.King, Rank.Jack, Rank.Nine, Rank.Six, Rank.Six);
assertTrue(p1.compareTo(p2) < 0);
} |
12e070ab-f904-474f-a5ab-d10d47d91d8b | 8 | void attributeValueLiteral(String value) {
buf.append('\'');
for (int i = 0, len = value.length(); i < len; i++) {
char c = value.charAt(i);
switch (c) {
case '<':
buf.append("<");
break;
case '&':
buf.append("&");
break;
case '\'':
buf.append("'");
break;
case '"':
buf.append(""");
break;
case '\r':
buf.append("
");
break;
case '\n':
buf.append("
");
break;
case '\t':
buf.append("	");
break;
default:
buf.append(c);
break;
}
}
buf.append('\'');
} |
67bad0e9-6f66-4c52-97a9-2a18865c9057 | 8 | public void configure() {
if (this.mandatory) {
value = true;
} else {
if (Config.getInstance().allno_config()) {
value = false;
} else if (Config.getInstance().allyes_config()) {
if (this.ignore_autoconf) {
value = false;
} else {
value = true;
}
} else if (Config.getInstance().random_config()) {
if (!this.ignore_autoconf) {
value = (Config.getInstance().getRandom(0, 1) == 0) ? false
: true;
} else {
value = false;
}
} else {
String question = "Enable flag ";
if (Config.getInstance().colors()) {
question = new StringBuilder(Color.BLUE).append(question).append(Color.DEFAULT).toString();
}
value = getBoolean(question);
}
}
this.configured = true;
return;
} |
e570e704-41d3-4500-9305-a9e8937d82e4 | 9 | private static void appendTypeAnnotations(TextBuffer buffer, int indent, StructMember mb, int targetType, int index, Set<String> filter) {
for (String name : TYPE_ANNOTATION_ATTRIBUTES) {
StructTypeAnnotationAttribute attribute = (StructTypeAnnotationAttribute)mb.getAttributes().getWithKey(name);
if (attribute != null) {
for (TypeAnnotation annotation : attribute.getAnnotations()) {
if (annotation.isTopLevel() && annotation.getTargetType() == targetType && (index < 0 || annotation.getIndex() == index)) {
String text = annotation.getAnnotation().toJava(indent, BytecodeMappingTracer.DUMMY).toString();
if (!filter.contains(text)) {
buffer.append(text);
if (indent < 0) {
buffer.append(' ');
}
else {
buffer.appendLineSeparator();
}
}
}
}
}
}
} |
fa0e010e-0b25-4b48-a965-c664683a3c7b | 6 | static final AbstractToolkit method958(boolean bool, int i, d var_d, int i_61_,
Canvas canvas, IndexLoader class45) {
try {
if (bool != true)
aClass221_1620 = null;
anInt1610++;
int i_62_ = 0;
int i_63_ = 0;
if (canvas != null) {
Dimension dimension = canvas.getSize();
i_63_ = dimension.height;
i_62_ = dimension.width;
}
return AbstractToolkit.createToolkit(i_61_, i_63_, i_62_, class45, 0, var_d,
canvas, i);
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929
(runtimeexception,
("mha.E(" + bool + ',' + i + ','
+ (var_d != null ? "{...}" : "null") + ',' + i_61_
+ ',' + (canvas != null ? "{...}" : "null") + ','
+ (class45 != null ? "{...}" : "null") + ')'));
}
} |
8f6ff6da-b175-497b-829f-9d9c22cd4696 | 8 | private static String initialise(Token currentToken,
int[][] expectedTokenSequences,
String[] tokenImage) {
String eol = System.getProperty("line.separator", "\n");
StringBuffer expected = new StringBuffer();
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected.append(tokenImage[expectedTokenSequences[i][j]]).append(' ');
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected.append("...");
}
expected.append(eol).append(" ");
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += " " + tokenImage[tok.kind];
retval += " \"";
retval += add_escapes(tok.image);
retval += " \"";
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected.toString();
return retval;
} |
75036a38-5dba-4b1b-b765-ebd06eb24977 | 1 | public static synchronized BusinessObjectDAO getInstance() throws DataException {
if (instance == null) {
instance = new BusinessObjectDAO();
}
return instance;
}//getInstance |
f422bf13-5f2b-40b4-a586-c894e666a519 | 9 | BigInt multiply(BigInt n) {
BigInt result = new BigInt(digits_.length + n.digits_.length);
result.sign_ = sign_ * n.sign_;
int i = 0, j = 0;
for (i = 0; i < n.digits_.length; ++i) {
if (n.digits_[i] != 0) {
int carry = 0;
for (j = 0; j < digits_.length || carry > 0; ++j) {
int n_digit = result.digits_[i + j]
+ (j < digits_.length ? n.digits_[i] * digits_[j] : 0) + carry;
result.digits_[i + j] = (char) (n_digit % 10);
carry = n_digit / 10;
}
}
}
// If one number is 0, the result size should be 0.
if ((digits_.length == 1 && digits_[0] == 0)
|| (n.digits_.length == 1 && n.digits_[0] == 0)) {
result.sign_ = 1;
result.digits_ = Arrays.copyOf(result.digits_, 1);
} else {
result.digits_ = Arrays.copyOf(result.digits_, i + j - 1);
}
return result;
} |
6a86e677-3d13-4e12-adde-d4b55f04587c | 0 | @Override
public void actionPerformed(ActionEvent e) {
exportOutlinerDocument((OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched(), getProtocol());
} |
ad31da22-a466-4a4e-8ac8-ccab940c99e4 | 2 | public List<String> getPasswordUser(){
List<String> res = new ArrayList<String>();
NodeList methodNodes = getDocument().getElementsByTagName("user");
if (methodNodes.getLength() == 0){
System.err.println("Couldn't read XML");
return null;
}else {
for (int i = 0; i < methodNodes.getLength(); i++) {
Node node = methodNodes.item(i);
NamedNodeMap attributes = node.getAttributes();
Node nameAttrib = attributes.getNamedItem("name");
String name = nameAttrib.getNodeValue();
Node passAttrib = attributes.getNamedItem("password");
String password = passAttrib.getNodeValue();
res.add(name+":"+password);
}
}
return res;
} |
beca4b3d-714e-40e5-b64c-fe2b251043f2 | 6 | public void checkForDuplicates(String outputFolder,boolean contentDuplicate, boolean nameDuplicate) throws SQLException, FileNotFoundException, IOException, ProcessingException {
if (!contentDuplicate && !nameDuplicate) {
return;
}
// Set this to true then the method starts.
// The GUI can set this to false via the Cancel button
isRunning = true;
ArrayList<DuplicateMusicObject> fullList = new ArrayList<DuplicateMusicObject>();
// For each of the steps, do a check for running or not.
if (contentDuplicate) {
fullList.addAll(getDuplicateOnContent());
}
if (nameDuplicate) {
fullList.addAll(getDuplicateOnName());
}
if (isRunning) {
Run.addProcessStatus("Writing the report to files in the folder " + outputFolder);
Run.addProcessStatus("Total Potential Duplicate size " + fullList.size());
if (fullList.size() > 0) {
sourceProcessing.writeToExcel(outputFolder, fullList);
}
}
// Set it back to false before leaving successfully
isRunning = false;
} |
8cc9187d-fef7-411d-963f-b16a7e4e05bf | 5 | private OperatingSystem checkUserAgent(String agentString) {
if (this.isInUserAgentString(agentString)) {
if (this.children.size() > 0) {
for (OperatingSystem childOperatingSystem : this.children) {
OperatingSystem match = childOperatingSystem.checkUserAgent(agentString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeToken(agentString)) {
return this;
}
}
return null;
} |
876e9a6f-3188-4bcc-b66d-dab7bba49eff | 0 | public ConcreteFlyweight(String data) {
this.data = data;
} |
e324d98d-2af3-4871-a12e-8ac73b906ae9 | 1 | public void paint(Graphics g)
{
updateLocation();
Graphics2D g2d = (Graphics2D) g;
Line2D l = new Line2D.Double(x1, y1, x2, y2);
g2d.setColor(Color.black);
g2d.draw(l);
if (Math.abs(x1 - x2) > Math.abs(y1 - y2))
g2d.drawString(cardMin + ", " + cardMax, (x1 + x2) / 2,
(y1 + y2 + 25) / 2);
else
g2d.drawString(cardMin + ", " + cardMax, (x1 + x2 + 10) / 2,
(y1 + y2) / 2);
} |
29b6972f-1097-4961-be34-2b0609162b25 | 4 | public Fraction evaluate(Fraction fraction, String inputString) {
// create variables
String operator = "";
Fraction current = fraction;
String item;
// create Scanner
Scanner s1 = new Scanner(inputString);
s1.useDelimiter(" ");
// try doing this : String str = System.console().readLine();
// parse the string and perform calculations
while(s1.hasNext()){
item = s1.next();
// parse numerals
if(Character.isDigit(item.charAt(0))){
switch(operator){
case "+":
current = current.add(parseNumerals(item));
operator = "";
default:
// current = parseNumerals(item);
}
}
else{
switch(item){
case "+": operator = item;
}
}
}
return current;
} |
8d39f82f-468a-476a-a9b1-0c9d58cfffec | 8 | public static double getOctave(Octave octave) {
switch ( octave ) {
case O0:
return 1;
case O1:
return 2;
case O2:
return Math.pow(2, 2);
case O3:
return Math.pow(2, 3);
case O4:
return Math.pow(2, 4);
case O5:
return Math.pow(2, 5);
case O6:
return Math.pow(2, 6);
case O7:
return Math.pow(2, 7);
default:
return 1.;
}
} |
222763e3-d76c-452d-abda-b057088d8920 | 8 | private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes |
f886fd7e-c184-426f-87ab-0ed60ebe23cb | 8 | public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
} |
c083cf24-e353-4dc5-81ab-d12d120ace0b | 3 | public Pointer put(byte[] key, byte[] value, long ttl) throws IOException {
// First try to store in the current active block
Pointer pointer = activeBlock.store(key, value, ttl);
if (pointer != null) {
return pointer;
} else {
// Current active block overflow
activeBlockChangeLock.lock();
try {
// Other thread may change the active block
pointer = activeBlock.store(key, value, ttl);
if (pointer != null) {
return pointer;
} else {
IBlock freeBlock = this.freeBlocks.poll();
if (freeBlock == null) {
freeBlock = createBlock(blockCount.getAndIncrement());
}
pointer = freeBlock.store(key, value, ttl);
this.usedBlocks.add(freeBlock);
this.activeBlock = freeBlock;
return pointer;
}
} finally {
activeBlockChangeLock.unlock();
}
}
} |
e507e265-d39c-4dc9-a303-427aa2c904d0 | 9 | public FailureDetector createFd(String fdName, String className,
Map<String, String> properties) throws Exception {
if (fdName == null) {
throw new IllegalArgumentException(
"No failure detector name was defined.");
}
Class<?> fdClass = null;
if (className != null) {
fdClass = Class.forName(className);
} else {
if (fdName.equals(FIXED_FD_NAME)) {
fdClass = FixedPingFailureDetector.class;
} else if (fdName.equals(CHEN_FD_NAME)) {
fdClass = ChenFailureDetector.class;
} else if (fdName.equals(BERTIER_FD_NAME)) {
fdClass = BertierFailureDetector.class;
} else if (fdName.equals(PHIACCRUAL_FD_NAME)) {
fdClass = PhiAccrualFailureDetector.class;
} else if (fdName.equals(SLICED_FD_NAME)) {
fdClass = SlicedPingFailureDetector.class;
}
}
if (fdClass == null) {
throw new IllegalArgumentException("There is no corresponding " +
"failure detector class for name " + fdName);
}
return (FailureDetector) fdClass.getConstructor(Map.class).newInstance(properties);
} |
2fd214b8-b67f-47c8-b3b2-bfb707baf48b | 8 | public List<Node> calc(int ns, int nt) {
System.out.println(String.format("A*: Started @%s, goal: %s", start, goal));
List<Node> path = null;
int steps = 0;
while (!open.isEmpty() && steps++ < ns) {
// System.out.println(String.format("open list size: %d", open.size()));
Node n = open.remove();
// System.out.println(String.format("Removed Node: %s", n));
if (n.equals(goal)){
System.out.println("A*: Found Goal!");
path = getPath(n);
if (!(path.contains(start))){
System.out.println(String.format("A* path does not contain start node: %s", start));
}
if (!(path.contains(goal))){
System.out.println(String.format("A* path does not contain goal node: %s", goal));
}
return path;
}
closed.add(n);
// System.out.println(String.format("Closed Node: %s", n));
// System.out.println(String.format("closed list size: %d", closed.size()));
List<Node> children = getChildren(n);
// children.removeAll(closed);
// System.out.println(String.format("found %d children", children.size()));
for (Node m : children) {
// if(!closed.contains(m)) { // added check to determine if node closed
m.parent = n;
m.g = n.g + 1;
m.h = heuristic(m);
open.add(m);
// System.out.println(String.format("Opened Node: %s, isclosed?%s", m, closed.contains(m)));
// }
}
}
if (path == null && open.isEmpty()){
System.out.println("A*: Goal not found!");
throw new IllegalStateException("A*: Goal not found!");
}
return path;
} |
9190400b-5df3-4ffe-a4ff-1649c54f2b55 | 9 | public static String getIPAddress() {
if(LCARS.ipAddress == null) {
LCARS.ipAddress = "127.0.0.1";
try {
InetAddress ipAddress = null;
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while(netInterfaces.hasMoreElements()) {
Enumeration<InetAddress> inetAddresses = netInterfaces.nextElement().getInetAddresses();
while(inetAddresses.hasMoreElements()) {
InetAddress ip = inetAddresses.nextElement();
if(ipAddress==null && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":")==-1) {
ipAddress = ip;
}
}
}
if(ipAddress != null) {
LCARS.ipAddress = ipAddress.getHostAddress();
}
else {
throw new UnknownHostException();
}
}
catch(UnknownHostException uhe) {
LOGGER.warning(uhe.getMessage() + " - Couldn't find IP address, returning local loop back address.");
}
catch(SocketException se) {
LOGGER.warning(se.getMessage() + " - Socket exception while trying to get network interfaces.");
}
}
return LCARS.ipAddress;
} |
097ffc28-2dcd-46cb-a8a5-3a77f8a936b7 | 4 | public static PDFPattern getPattern(PDFObject patternObj, Map resources)
throws IOException
{
// see if the pattern is already cached
PDFPattern pattern = (PDFPattern) patternObj.getCache();
if (pattern != null) {
return pattern;
}
// get the pattern type
int type = patternObj.getDictRef("PatternType").getIntValue();
// read the pattern transform matrix
PDFObject matrix = patternObj.getDictRef("Matrix");
AffineTransform xform = null;
if (matrix == null) {
xform = new AffineTransform();
} else {
float elts[]= new float[6];
for (int i = 0; i < elts.length; i++) {
elts[i] = ((PDFObject) matrix.getAt(i)).getFloatValue();
}
xform = new AffineTransform(elts);
}
switch (type) {
case 1:
pattern = new PatternType1();
break;
default:
throw new PDFParseException("Unknown pattern type " + type);
}
// set the transform
pattern.setTransform(xform);
// parse the pattern-specific data
pattern.parse(patternObj, resources);
// set the cache
patternObj.setCache(pattern);
return pattern;
} |
1326ed6a-1c86-4fc7-bdad-79bcdf88ada0 | 8 | private void updateCurrentState() {
if (hitWumpus) {
endGame();
this.currentState = "You aim and fire you weapon of choice. Your trusty bow.\n"
+ "The arrow whistles through the air. Your aim is true.\n"
+ "The beast is dead.\n" + "You return home a hero.";
} else if (hitSelf) {
endGame();
this.currentState = "You aim and fire you weapon of choice. Your trusty bow.\n"
+ "The arrow whistles through the air. Alas your target is not in that direction.\n"
+ "As you are about to turn away a portal appears infront of the arrow. The arrow enters the portal.\n"
+ "You hear a sound behind you. Somehow another portal has opened up behind you. The arrow is flying towards you.\n"
+ "The arrow hits you in the ending your carrer as an explorer. Unable to walk and loosing blood you die alone.";
} else if (getCell(hunterLocation).isGoop()) {
this.currentState = "Eww. You walked onto a reddish green mix of blood and slime. It looks like goop.";
} else if (getCell(hunterLocation).isBlood()) {
this.currentState = "Your feet slip a bit. You look down and see the floor covered in blood.";
} else if (getCell(hunterLocation).isSlime()) {
this.currentState = "Your shoes are now covered in some sort of slime.";
} else if (getCell(hunterLocation).isPit()) {
endGame();
this.currentState = "You loose you footing and fall into a bottemless pit.\n"
+ "GAME OVER";
} else if (getCell(hunterLocation).isWumpus()) {
endGame();
this.currentState = "You walk into the wumpus. Dinner is serverd.\n"
+ "For the wumpus.\n" + "GAME OVER";
} else if (getCell(hunterLocation).isEmpty()) {
this.currentState = "You look around all you see is nothing. The silence is deafaning.";
} else {
this.currentState = "";
}
this.setChanged();
this.notifyObservers();
} |
ddbef165-9cb2-480d-8ae5-d8fb4e5c3775 | 9 | private void persisteInformacoes(List<AvaliacaoDocente> listaAvaliacaoDocente, BeanPopulate beanPopulate) {
System.out.println("Salvando Avaliação..");
avaliacaoDao.salvar(beanPopulate.getAvaliacao());
System.out.println("Avaliação salva.. id: " + beanPopulate.getAvaliacao().getId());
for (AvaliacaoDocente avaliacaoDocente : listaAvaliacaoDocente) {
long matricula = 1;
if (avaliacaoDocente != null && avaliacaoDocente.getDocente() != null) {
avaliacaoDocente.getDocente().setMatricula(matricula);
avaliacaoDocente.getDocente().setRegime("Integral");
avaliacaoDocente.getDocente().setUnidade("INF");
matricula++;
}
if (avaliacaoDocente != null && avaliacaoDocente.getDocente() != null) {
System.out.println("Salvando Docente: " + avaliacaoDocente.getDocente().getNome());
docenteDao.salvar(avaliacaoDocente.getDocente());
System.out.println("Docente salvo.. id:" + avaliacaoDocente.getDocente().getId());
}
if (avaliacaoDocente != null && beanPopulate.getAvaliacao() != null) {
System.out.println("Salvando Avaliação do Docente: ");
avaliacaoDocente.setAvaliacao(beanPopulate.getAvaliacao());
avaliacaoDocenteDao.salvar(avaliacaoDocente);
System.out.println("Avaliação do docente salva... id:" + avaliacaoDocente.getId());
}
if (avaliacaoDocente != null && avaliacaoDocente.getItensAvaliacao() != null) {
System.out.println("Salvando itens avaliacao do professor... Qtd: " + avaliacaoDocente.getItensAvaliacao().size());
itemAvaliacaoDao.salvaEmBloco(avaliacaoDocente.getItensAvaliacao(), avaliacaoDocente.getId());
System.out.println("Itens da avaliacao do professor salvos... ");
}
}
} |
85c020d6-d5af-48ce-ab75-82d1ce96cec4 | 1 | private void configureAbstractButton(AbstractButton button, String resource) {
String title = resources.getString(resource);
int i = title.indexOf('&');
int mnemonic = 0;
if (i >= 0) {
mnemonic = title.charAt(i + 1);
title = title.substring(0, i) + title.substring(i + 1);
button.setText(title);
button.setMnemonic(Character.toUpperCase(mnemonic));
button.setDisplayedMnemonicIndex(i);
} else
button.setText(title);
} |
82c80bb6-4e70-4c22-81c4-515309268cdf | 1 | private static boolean checkIfVampire (int a, int b, int x) {
//cast to strings
char[] charsAB = (a + "" + b).toCharArray();
char[] charsX = ("" + x).toCharArray();
Arrays.sort(charsAB);
Arrays.sort(charsX);
if (Arrays.equals(charsAB,charsX)) return true;
else return false;
} |
ddc74489-dd00-4c4d-8abf-d4d736363967 | 8 | protected void loadParser() throws ClassNotFoundException, NoSuchMethodException,
InstantiationException, IllegalAccessException, InvocationTargetException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if ( !startRuleName.equals(LEXER_START_RULE_NAME) ) {
String parserName = grammarName+"Parser";
parserClass = null;
try {
parserClass = cl.loadClass(parserName).asSubclass(Parser.class);
} catch (ClassNotFoundException cnfe) {
System.err.println("ERROR: Can't load "+parserName+" as a parser");
throw cnfe;
}
try {
Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);
parser = parserCtor.newInstance((TokenStream)null);
} catch (Exception anException) {
System.err.println("ERROR: Could not create a parser for "+parserName);
throw anException;
}
if ( diagnostics ) {
parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
}
if ( printTree ) {
parser.setBuildParseTree(true);
treePrinter = new TreePrinter(primaryIndentStr,
secondaryIndentStr,
indentCyclePeriod,
parser);
}
if ( trace ) {
traceListener = new PrintStreamTraceListener(parser);
parser.addParseListener(traceListener);
}
if ( SLL ) { // overrides diagnostics
parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
}
}
} |
481a119b-3c7b-49a5-be3b-11f80f50cb31 | 8 | public boolean isOppositeOf(Direction direction)
{
switch (this)
{
case UP:
if (direction == Direction.DOWN)
{
return true;
}
break;
case DOWN:
if (direction == Direction.UP)
{
return true;
}
break;
case LEFT:
if (direction == Direction.RIGHT)
{
return true;
}
break;
case RIGHT:
if (direction == Direction.LEFT)
{
return true;
}
break;
}
return false;
} |
b5ebb9dd-b02e-45d2-a7db-f90678d7a0de | 7 | private boolean jj_3R_50()
{
if (jj_scan_token(LET)) return true;
if (jj_3R_17()) return true;
if (jj_scan_token(EQUAL)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(IN)) return true;
if (jj_3R_9()) return true;
if (jj_scan_token(END)) return true;
return false;
} |
69e75d86-4f84-4bca-b0f0-7c7e9e492563 | 3 | public static void sort(Comparable[] a) {
for (int i = 0; i < a.length; i++)
for (int j = 1; j < a.length - i; j++)
if (less(a[j], a[j - 1]))
exch(a, j - 1, j);
} |
e2aa2de4-bb5a-4437-bc85-f5efa3e2263c | 5 | @Override
public void onResultsAvailable(
BiDiInterproceduralCFG<Unit, SootMethod> cfg,
InfoflowResults results) {
// Dump the results
if (results == null) {
print("No results found.");
}
else {
for (SinkInfo sink : results.getResults().keySet()) {
print("Found a flow to sink " + sink + ", from the following sources:");
for (SourceInfo source : results.getResults().get(sink)) {
print("\t- " + source.getSource() + " (in "
+ cfg.getMethodOf(source.getContext()).getSignature() + ")");
if (source.getPath() != null && !source.getPath().isEmpty())
print("\t\ton Path " + source.getPath());
}
}
}
} |
df19747b-244e-40dd-b735-e5d00fb8ae53 | 2 | private void cleanEffects()
{
for(int c = 0; c<effectList.length;c++)
{
if(!effectList[c].isActive())
{
System.out.println(effectList[c].NAME +" wore off.");
effectList[c] = Effect.CLEAR;
effectList[c].duration = -1;
}
}
} |
e81a5ae7-88a8-4cb4-bed1-98a465b82bed | 6 | public boolean isKingInCheck() {
Point kingsLocation = null;
for (Entry<Point, Piece> p : b.entrySet()) {
if (p.getValue() instanceof King
&& isWhitesTurn == p.getValue().getColor()) {
kingsLocation = p.getKey();
}
}
for (Entry<Point, Piece> p : b.entrySet()) {
if ((isWhitesTurn != p.getValue().getColor())
&& validTake(p.getKey(), kingsLocation)) {
return true;
}
}
return false;
} |
1fc044fd-a475-4882-b56e-9d4ef2ff5136 | 7 | public static MoodleCourse[] getAllCourses() throws MoodleRestException, UnsupportedEncodingException {
Vector v=new Vector();
MoodleCourse course=null;
StringBuilder data=new StringBuilder();
String functionCall=MoodleCallRestWebService.isLegacy()?MoodleServices.MOODLE_COURSE_GET_COURSES:MoodleServices.CORE_COURSE_GET_COURSES;
if (MoodleCallRestWebService.getAuth()==null)
throw new MoodleRestCourseException();
else
data.append(MoodleCallRestWebService.getAuth());
data.append("&").append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING)).append("=").append(URLEncoder.encode(functionCall, MoodleServices.ENCODING));
data.append("&").append(URLEncoder.encode("options[ids]", MoodleServices.ENCODING));
NodeList elements=MoodleCallRestWebService.call(data.toString());
course=null;
for (int j=0;j<elements.getLength();j++) {
String content=elements.item(j).getTextContent();
String nodeName=elements.item(j).getParentNode().getAttributes().getNamedItem("name").getNodeValue();
if (nodeName.equals("id")) {
if (course==null)
course=new MoodleCourse(Long.parseLong(content));
else {
v.add(course);
course=new MoodleCourse(Long.parseLong(content));
}
}
course.setMoodleCourseField(nodeName, content);
}
if (course!=null)
v.add(course);
MoodleCourse[] courses=new MoodleCourse[v.size()];
for (int i=0;i<v.size();i++) {
courses[i]=(MoodleCourse)v.get(i);
}
v.removeAllElements();
return courses;
} |
e34ae778-478c-4910-b0b5-738584c01b04 | 1 | public static int executeAndCountSqlFile(String path) throws ClassNotFoundException, SQLException, IOException {
Class.forName("org.postgresql.Driver");
Connection connection = null;
connection = DriverManager.getConnection(
Configuration.getJdbcString(), Configuration.user, Configuration.password);
Statement stmt = connection.createStatement();
String query = readFileUtf8(path);
List<String> sqls = Arrays.asList(query.split(";"));
boolean result = false;
for (String sql : sqls.subList(0, sqls.size() - 1)) {
System.err.println("executing query: " + sql);
result = stmt.execute(sql);
}
System.err.println("Executing count statement: " + sqls.get(sqls.size() - 1));
ResultSet rs = stmt.executeQuery(sqls.get(sqls.size() - 1));
rs.next();
connection.close();
return rs.getInt(1);
} |
17aa9cde-f9da-43ea-9092-3c373866902f | 5 | public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
double n1, n2, result = 0;
String operator;
System.out.print("Please enter first number: ");
n1 = sc.nextDouble();
System.out.print("Please enter second number: ");
n2 = sc.nextDouble();
System.out.print("Please select an operator +, -, * or /: ");
operator = sc.next();
if (operator.equals("+")) {
result = n1+n2;
} else if (operator.equals("-")) {
result = n1-n2;
} else if (operator.equals("*")) {
result = n1*n2;
} else if (operator.equals("/") && n2!=0) {
result = n1/n2;
} else {
System.out.println("invalid operation");
}
System.out.println(result);
} |
a67fbaad-b04b-42c2-aa39-d6592c0407f5 | 2 | public List<String> findSolutions(final LetterGen letGen, final List<String> words) {
final List<String> solutions = new ArrayList<String>();
for (final String word : words) {
if( wordContainsLettersInOrder(letGen, word) ) {
solutions.add(word);
}
}
return solutions;
} |
d68e8e9e-3cbf-4ce2-afef-4724bf32c503 | 2 | public double getDouble(int index) throws JSONException {
Object object = this.get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
} |
df89952b-cf54-43c1-a5cd-37fd9766d3d8 | 5 | public boolean checkDangerFor(Castle castle, Hero dummy)
{
int strength = 0;
if (castle.getGarission() != null) {
strength += castle.getGarission().getStrenght();
}
if (castle.getHero() != null) {
strength += castle.getHero().getStrenght();
}
for (Hero h: p2h.objects()) {
if (h.getStrenght() > strength && h.getMaxMovePoints() < getDistance(dummy.getX(), dummy.getY())) {
return true;
}
}
return false;
} |
71852667-9b24-493c-b509-e53077c4a4e1 | 5 | private void compileAndRun(ICompilationUnit unit) {
Map settings = new HashMap();
settings.put(CompilerOptions.OPTION_LineNumberAttribute,CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute,CompilerOptions.GENERATE);
CompileRequestorImpl requestor = new CompileRequestorImpl();
Compiler compiler = new Compiler(new NameEnvironmentImpl(unit),
DefaultErrorHandlingPolicies.proceedWithAllProblems(),
settings,
requestor,
new DefaultProblemFactory(Locale.getDefault()));
compiler.compile(new ICompilationUnit[] { unit });
List problems = requestor.getProblems();
boolean error = false;
for (Iterator it = problems.iterator(); it.hasNext();) {
IProblem problem = (IProblem)it.next();
StringBuffer buffer = new StringBuffer();
buffer.append(problem.getMessage());
buffer.append(" line: ");
buffer.append(problem.getSourceLineNumber());
String msg = buffer.toString();
if(problem.isError()) {
error = true;
msg = "Error:\n" + msg;
}
else
if(problem.isWarning())
msg = "Warning:\n" + msg;
System.out.println(msg);
}
if (!error) {
try {
ClassLoader loader = new CustomClassLoader(getClass().getClassLoader(),requestor.getResults());
String className = CharOperation.toString(unit.getPackageName()) + "." + new String(unit.getMainTypeName());
Class clazz = loader.loadClass(className);
Method m = clazz.getMethod("main",new Class[] {String[].class});
m.invoke(clazz,new Object[] { new String[0] });
}
catch (Exception e) {
e.printStackTrace();
}
}
} |
4db3343e-8666-4f12-a69e-c13a615856fd | 9 | public void generateTask(Message.TaskInitMessage message){
if(message.getType() == Message.TaskInitMessage.TaskType.BUILDER_TASK){
if(message.getId() != null && message.getDataSourceCount() > 0){
String commId = "LS " + message.getId();
CommClient localSchedulerClient = new CommClient(commId, host, lsPort);
commId = "DH " + message.getId();
CommClient dataHandlerClient = new CommClient(commId, host, dhPort);
commId = "HB " + message.getId();
CommClient heartBeatClient = new CommClient(commId, host, lsPort);
//TODO add ServerConnection for Message Queue
BuilderTask task = new UserBuilderTask();
localSchedulerClient.addInputObserver(task);
dataHandlerClient.addInputObserver(task);
task.init(message.getId(), message.getDataSource(0), localSchedulerClient, dataHandlerClient, heartBeatClient);
new Thread(task).start();
}
} else if(message.getType() == Message.TaskInitMessage.TaskType.COPY_TASK){
if(message.getId() != null && message.getCopyDestination() != null){
String commId = "LS COPY";
CommClient localSchedulerClient = new CommClient(commId, host, lsPort);
commId = "Local DH COPY";
CommClient localDataHandlerClient = new CommClient(commId, host, dhPort);
commId = "Remote DH COPY";
Message.Location destLocation = message.getCopyDestination();
CommClient remoteDataHandlerClient = new CommClient(commId, destLocation.getHost(), destLocation.getPort());
CopyTask task = new CopyTaskImpl();
task.init("Copy Process", localSchedulerClient, localDataHandlerClient, remoteDataHandlerClient, message.getId());
localSchedulerClient.addInputObserver(task);
localDataHandlerClient.addInputObserver(task);
remoteDataHandlerClient.addInputObserver(task);
new Thread(task).start();
}
} else if (message.getType() == Message.TaskInitMessage.TaskType.MERGER_TASK){
if(message.getId() != null && message.getDataSourceCount() > 0){
String commId = "LS " + message.getId();
CommClient localSchedulerClient = new CommClient(commId, host, lsPort);
commId = "DH " + message.getId();
CommClient localDataHandlerClient = new CommClient(commId, host, dhPort);
commId = "DM " + message.getId();
CommClient dataManagerClient = new CommClient(commId, dmHost, dmPort);
commId = "HB " + message.getId();
CommClient heartBeatClient = new CommClient(commId, host, lsPort);
MergeTask task = new UserMergeTask();
localSchedulerClient.addInputObserver(task);
localDataHandlerClient.addInputObserver(task);
dataManagerClient.addInputObserver(task);
task.init(message.getId(), localSchedulerClient, localDataHandlerClient, dataManagerClient, message.getDataSourceList(), heartBeatClient);
new Thread(task).start();
}
}
} |
2128c043-7c0b-49af-9cb2-f8c829b9b253 | 4 | public static int utfSizeOf(String str)
{
int strlen = str.length();
int utflen = 0;
int c = 0;
/* use charAt instead of copying String to char array */
for (int i = 0; i < strlen; i++) {
c = str.charAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
} else if (c > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
return utflen;
} |
ccb5f9ed-f9fc-4008-97f4-bb51dccbdcce | 6 | protected void attackEntity(Entity par1Entity, float par2)
{
float var3 = this.getBrightness(1.0F);
if (var3 > 0.5F && this.rand.nextInt(100) == 0)
{
this.entityToAttack = null;
}
else
{
if (par2 > 2.0F && par2 < 6.0F && this.rand.nextInt(10) == 0)
{
if (this.onGround)
{
double var4 = par1Entity.posX - this.posX;
double var6 = par1Entity.posZ - this.posZ;
float var8 = MathHelper.sqrt_double(var4 * var4 + var6 * var6);
this.motionX = var4 / (double)var8 * 0.5D * 0.800000011920929D + this.motionX * 0.20000000298023224D;
this.motionZ = var6 / (double)var8 * 0.5D * 0.800000011920929D + this.motionZ * 0.20000000298023224D;
this.motionY = 0.4000000059604645D;
}
}
else
{
super.attackEntity(par1Entity, par2);
}
}
} |
eb787d82-b1c2-4f8a-8337-c8427dec9afa | 7 | public void CambiarRealmlistPor(int Seleccion){
try {
String Realmlist = Config.Configuracion(4);
FileReader ArchivoConfiguracion = new FileReader("Configuracion.txt");
BufferedReader _ArchivoConfiguracion = new BufferedReader(ArchivoConfiguracion);
String LineaInformacion = "";
String RealmlistConfiguracion = "";
int Linea = 0;
while((LineaInformacion = _ArchivoConfiguracion.readLine()) != null){
if(Linea == 0){
RealmlistConfiguracion = LineaInformacion;
}
Linea++;
}
ArchivoConfiguracion.close();
_ArchivoConfiguracion.close();
try{
String[] _Realmlist = RealmlistConfiguracion.split(">");
File ArchivoRealmlist = new File(_Realmlist[1].toString());
ArchivoRealmlist.delete();
if(ArchivoRealmlist.createNewFile()){
FileWriter EscribirRealmlist = new FileWriter(_Realmlist[1].toString());
BufferedWriter _EscribirRealmlist = new BufferedWriter(EscribirRealmlist);
FileReader ArchivoRealmlists = new FileReader("Realmlists.txt");
BufferedReader _ArchivoRealmlists = new BufferedReader(ArchivoRealmlists);
String RealmlistSeleccionado = "";
int LineaRealmlist = Seleccion;
int LineaGeneral = 0;
while((LineaInformacion = _ArchivoRealmlists.readLine()) != null){
if(LineaGeneral == LineaRealmlist){
RealmlistSeleccionado = LineaInformacion;
}
LineaGeneral++;
}
_EscribirRealmlist.write(RealmlistSeleccionado);
_EscribirRealmlist.close();
EscribirRealmlist.close();
ArchivoRealmlists.close();
_ArchivoRealmlists.close();
JOptionPane.showMessageDialog(null, "Realmlist cambiado correctamente. El realmlist seleccionado fue: " + RealmlistSeleccionado, "Correcto", JOptionPane.PLAIN_MESSAGE);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "No se encontró el archivo realmlist.wtf", "Error", JOptionPane.PLAIN_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "No se encontró el archivo Configuracion.txt[5]", "Error", JOptionPane.PLAIN_MESSAGE);
}
} |
ce15ceda-3c6b-4a13-8acd-56a1037a24fb | 3 | void out_close(){
try{
if(out!=null && !out_dontclose) out.close();
out=null;
}
catch(Exception ee){}
} |
ef7272d7-180a-4c1e-8db1-ef3267982cc3 | 5 | public int[][] readMap() throws IOException {
int[][] mapTab = new int[nbLine][nbCol];
String lign;
seekFile(1);
for(int i1 = 0; i1 < nbLine; i1++) {
lign = readString(nbCol);
for(int i2 = 0; i2 < nbCol; i2++) {
switch(lign.charAt(i2)) {
case 'o' :
mapTab[i1][i2] = 0;
break;
case 'b' :
mapTab[i1][i2] = 1;
break;
case 'w' :
mapTab[i1][i2] = 2;
break;
}
}
}
return mapTab;
} |
0d4b29de-2dcd-40ab-bbcf-a5c25089ee88 | 9 | public void collsionDetection(){
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
for (GameObject gobj : gameObjects) {
if (getBounds().intersects(gobj.getBounds())) {
switch(gobj.getName()){
case "Crate": changeDirection();break;
case "Container": changeDirection();break;
case "IcePlane": gobj.getIEffectable().playEffect(getCar());break;
case "Spike":
gobj.getIEffectable().playEffect(getCar());
break;
case "Nitro":
gobj.getIEffectable().playEffect(getCar());
break;
case "Gate":
break;
}
}
}
}
}
}).start();
} |
95061f37-54b8-4965-8ead-c579c9663694 | 0 | private Object _getItem(JSONObject obj, String name) {
return obj.get(name);
} |
e3649d1a-b879-4c32-8ded-56252ce968a8 | 6 | private Color translateColor(se.liu.ida.danan391.TDDC69.tetris.Color color) {
switch (color) {
case BLACK:
return Color.BLACK;
case BLUE:
return Color.BLUE;
case GREEN:
return Color.GREEN;
case RED:
return Color.RED;
case YELLOW:
return Color.YELLOW;
case PINK:
return Color.PINK;
default:
return Color.GRAY;
}
} |
c8ce191d-a5c1-4a29-a1d0-8f15f53fbee1 | 3 | public static void readCompressed(File f, byte[] buf, int nbytes) throws FileNotFoundException, IOException {
if (COMPRESSION_ENABLED) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
InflaterInputStream iis = new InflaterInputStream(bis);
int read = 0;
while (read < nbytes) {
read += iis.read(buf, read, nbytes - read);
}
iis.close(); bis.close();
} else {
FileInputStream in = new FileInputStream(f);
int read = 0;
while (read < nbytes) {
read += in.read(buf, read, buf.length - read);
}
in.close();
}
} |
a5a4de0d-7565-47d0-9d5d-3e5bdd576b67 | 6 | public boolean peutCreerCategorie(Utilisateur utilisateur) {
return (
utilisateur != null
&& (
utilisateur.getRole().getValeur() >= Role.Administrateur.getValeur()
|| (
utilisateur.getRole().getValeur() >= Role.Moderateur.getValeur()
&& getCategorieParent() != null
)
|| (getJeuAssocie() != null
&& (
getJeuAssocie().getCreateur().equals(utilisateur)
|| getJeuAssocie().getCollaborateurs().contains(utilisateur)
)
)
)
);
} |
a5f92f7c-d7f2-48ec-973b-f5a71325f9fa | 4 | void update(){
x+=dx;
y+=dy;
if(dx > 0){
dx--;
}else if(dx < 0){
dx++;
}
if(dy < 0){
dy++;
}else if(dy > 0){
dy--;
}
} |
cefb642e-bd87-4839-8fa5-906de6972de7 | 2 | public void setGuid(Guid newGuid) {
if (newGuid == null) {
throw new RuntimeException("Guid must not be null.");
}
if (guid != null) {
throw new RuntimeException("Can only set GUID on a constant with an existing NULL guid.");
}
guid = newGuid;
} |
84198062-b4f9-4909-905f-630bd45543a7 | 7 | public boolean addTypeWorkFrame(){
boolean ret = false;
String name;
JTextField text = new JTextField();
JComponent[] components = new JComponent[]{
new JLabel("Введите название типа работы"),
text
};
do {
boolean result = SMS.dialog(this, "Введите данные о типе работы", components);
if(result){
if(text.getText().trim().length() > 0){
try {
TypeWork type = new TypeWork();
type.setNameTypeWork(text.getText());
int code = type.insertInto();
if(code == -1){
result = SMS.query(this, "Такое значение уже есть\nХотите еще раз ввести данные?");
if(result){
// запускаем занового цикл
continue;
} else {
// значит выходим из цикла
break;
}
} else if( code >= 0 ){
// все прошло успешно
ret = true;
break;
}
} catch (SQLException ex) {
SMS.error(this, ex.toString());
Logger.getLogger(TypeWorkInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
break;
}
} else {
SMS.message(this, "Вы ничего не ввели");
}
} else {
// Пользователь отменил выбор
break;
}
} while (true);
return ret;
} |
dddfca82-f663-479f-bcd7-ef5ac7211a05 | 6 | public void drawSprite2(int i, int j) {
int k = 225;//was parameter
i += anInt1442;
j += anInt1443;
int i1 = i + j * DrawingArea.width;
int j1 = 0;
int k1 = myHeight;
int l1 = myWidth;
int i2 = DrawingArea.width - l1;
int j2 = 0;
if(j < DrawingArea.topY) {
int k2 = DrawingArea.topY - j;
k1 -= k2;
j = DrawingArea.topY;
j1 += k2 * l1;
i1 += k2 * DrawingArea.width;
}
if(j + k1 > DrawingArea.bottomY)
k1 -= (j + k1) - DrawingArea.bottomY;
if(i < DrawingArea.topX) {
int l2 = DrawingArea.topX - i;
l1 -= l2;
i = DrawingArea.topX;
j1 += l2;
i1 += l2;
j2 += l2;
i2 += l2;
}
if(i + l1 > DrawingArea.bottomX) {
int i3 = (i + l1) - DrawingArea.bottomX;
l1 -= i3;
j2 += i3;
i2 += i3;
}
if(!(l1 <= 0 || k1 <= 0)) {
method351(j1, l1, DrawingArea.pixels, myPixels, j2, k1, i2, k, i1);
}
} |
8fd35774-b0c5-455f-86c9-19e24f7a432d | 0 | private void initializeSound (){
new Sound ("music/soundTrack.wav").start();
} |
81a30485-d0cb-43d8-965d-53917c3ee410 | 4 | public Competition(){
super("Competition");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
}
setSize(400, 250);
final JLabel namelabel[] = new JLabel[7];
final JLabel timelabel[] = new JLabel[7];
final JLabel placelabel[] = new JLabel[7];
final SportsmanShortTrack S[]={new SportsmanShortTrack("Vladimir Grigoriev"),new SportsmanShortTrack("Victor An"),
new SportsmanShortTrack("Shinke Knegt"), new SportsmanShortTrack("Dazin U"),
new SportsmanShortTrack("Davun Sin"),new SportsmanShortTrack("Tyanu Han"), new SportsmanShortTrack("Semen Elistratov")};
S[1].SetForces(1.24102);
S[0].SetForces(1.24868);
S[2].SetForces(1.25611);
S[3].SetForces(1.24239);
S[5].SetForces(1.24490);
S[6].SetForces(1.24239);
S[4].SetForces(1.24215);
final Jury J=new Jury("Peter Worte");//final is used inside the inner button listener class
ShortTrack ST=new ShortTrack(1000,"final");
ST.SetWorldRecord(1.25);
for (int i=0; i<S.length; i++){
ST.AddSportsmen(S[i]);
namelabel[i]=new JLabel(S[i].GetName());
/*timelabel[i]=new JLabel(Double.toString(S[i].GetResult()));
placelabel[i]=new JLabel(Integer.toString(S[i].GetPlace()));*/
timelabel[i]=new JLabel(Double.toString(0));
placelabel[i]=new JLabel(Integer.toString(0));
}
J.SetDiscipline(ST);
Container c = getContentPane();
JPanel centerPanel = new JPanel(new GridLayout(1,3));
JPanel panels[]=new JPanel[3];
centerPanel.setBorder(BorderFactory.createEtchedBorder());
c.add(centerPanel, BorderLayout.CENTER);
panels[0]=new JPanel(new GridLayout(7,1));
panels[1]=new JPanel(new GridLayout(7,1));
panels[2]=new JPanel(new GridLayout(7,1));
for (int i=0; i<7; i++){
panels[0].add(placelabel[i]);
panels[1].add(namelabel[i]);
panels[2].add(timelabel[i]);
}
centerPanel.add(panels[0]);
centerPanel.add(panels[1]);
centerPanel.add(panels[2]);
JButton btn = new JButton("start");
c.add(btn, BorderLayout.SOUTH);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
J.StartCompetition();
J.TotalCompetition();
Arrays.sort(S);//necessary
for (int i=0; i<S.length; i++){
namelabel[i].setText(S[i].GetName());
timelabel[i].setText(Double.toString(S[i].GetResult()));
placelabel[i].setText(Integer.toString(S[i].GetPlace()));
}
}
});
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
} |
85b9233b-003e-4dee-a4c6-bddb2cb4bde2 | 2 | public double getInfoFloat(String key) {
if (info == null) parseInfo();
String f = info.get(key);
if (f == null) return Double.NaN;
return Gpr.parseDoubleSafe(f);
} |
daac9700-c04d-4d38-98ea-80a042a8d474 | 3 | public int minMaxLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 30;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return (optInTimePeriod-1);
} |
3a5d941f-7a5c-485a-985c-a4d41313c9aa | 4 | @EventHandler(priority = EventPriority.HIGHEST)
public void onBowHit(EntityDamageByEntityEvent e) {
if (e.getDamager() instanceof Arrow) {
Arrow arrow = (Arrow) e.getDamager();
if (arrow.getShooter() instanceof Player) {
if(parent.isInNation((Player)arrow.getShooter())) {
if(parent.getNationType((Player)arrow.getShooter()).equals(NationType.ENGLAND)) {
// extra 2 hearts damage
e.setDamage(e.getDamage() + 4);
}
}
}
}
} |
c0bea725-3e56-4120-b8b8-cc1e91087529 | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
frmLogin dialog = new frmLogin(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} |
12763d71-9bff-452d-bde2-b5594f4db1ca | 8 | private VarInfo getVar(final String aVarName, final Visibility aVisibility) throws ParsingException {
final VarInfo var = mVariables.get(aVarName);
if (var == null) {
if (mParentScope == null) {
return DUMMY_VAR;
}
final VarInfo closed = mParentScope.getVar(aVarName, aVisibility);
if (closed == DUMMY_VAR) {
return DUMMY_VAR;
}
// globals should not be captured
// TODO: revise this if "updatable" captures are implemented
if (closed.isGlobal()) {
return DUMMY_VAR;
}
if (!(closed.isVar() || closed.isArgument() || closed.isCapture())) {
throw new VariableNotClosable(closed);
}
return addVariable0(aVarName, Visibility.CAPTURE, closed);
}
if (aVisibility != null) {
AssertUtil.runtimeAssert(var.getVisibility() == aVisibility, "Variable not of expected visibility!");
}
return var;
} |
22374f19-4c77-4650-9846-367b2c96e890 | 1 | public int reserve(int x){
int newNum = 0, left =0;
while(x!=0){
left = x%10;
newNum = newNum*10+left;
x = x/10;
}
return newNum;
} |
19e091d1-74ba-4f9f-8040-2a4e933480c3 | 3 | private ArrayList<Cellule> watchBois(){ // Methode qui renvoie ce que regarde le villageois (les cellules adjaçantes à la sienne + la sienne) sans les diagonalles)
ArrayList<Cellule> autour = curent.env.getenv(curent);
for (int i =0 ; i<autour.size() ; i++){
if (autour.get(i) ==null){
autour.remove(i);
i--;
}
else if (!(autour.get(i).objet instanceof Bois )){
autour.remove(i);
i--;
}
}
return autour;
} |
c049d1f4-5e66-4eaf-82e0-a7c88c8c75a1 | 3 | public boolean isPair() {
boolean retBoo = false;
for (int i = 0; i < _cards.size()-1; i++) {
for (int x = (i+1); x < _cards.size(); x++) {
if (_cards.get(i).compareTo(_cards.get(x)) == 0) {
retBoo = true;
break;
}
}
}
return retBoo;
} |
90dfa4f6-7f77-4be6-9215-7b060cb4a825 | 2 | @Test
@Ignore
public void test_RoomListGet()
{
RoomList laRoomList = laClient
.getRoomList("2012-01-01-08.00.00.000000");
System.out.println(laRoomList.getRoomList().size());
if (laRoomList.getRoomList().size() > 0) {
for (Room laRoom : laRoomList.getRoomList()) {
System.out.println(laRoom.toString());
}
}
} |
b8633c7e-0eb8-4320-ae76-95aecd1406c1 | 3 | @Override
public float getCusto() {
// TODO Auto-generated method stub
float cus;
switch (marca) {
case ATI:if(gab.getDescricao().contains("AMD")) cus = 104;else cus = 130; break;
case NVIDIA: cus = 120; break;
default: cus = 0; break;
}
return cus + gab.getCusto();
} |
4f16ccfe-b482-41d8-aab3-ccb7a2b77b32 | 5 | private void addEmptyThings(){
SortedSet<String> keys = new TreeSet<String>(data.keySet());
for (String path : keys) {
while(true){
path = deleteLastLevel(path);
if(path == null || path.equals(""))
break;
if(data.get(path) == null){
data.put(path, " ");
}
}
}
} |
bf110eb0-ba4f-4bbe-82a5-7a84c16d3aad | 7 | public static void pprintOntosaurusObject(Stella_Object self, OutputStream stream) {
{ Object old$LogicDialect$000 = Logic.$LOGIC_DIALECT$.get();
Object old$PprintAtomicObjectRenderer$000 = OntosaurusUtil.$PPRINT_ATOMIC_OBJECT_RENDERER$.get();
try {
Native.setSpecial(Logic.$LOGIC_DIALECT$, OntosaurusUtil.KWD_KIF);
Native.setSpecial(OntosaurusUtil.$PPRINT_ATOMIC_OBJECT_RENDERER$, Native.find_java_method("edu.isi.ontosaurus.OntosaurusUtil", "pprintAtomicObjectForHtml", new java.lang.Class [] {Native.find_java_class("edu.isi.stella.Stella_Object"), Native.find_java_class("org.powerloom.PrintableStringWriter")}));
if (Surrogate.subtypeOfP(Stella_Object.safePrimaryType(self), OntosaurusUtil.SGT_LOGIC_PROPOSITION)) {
{ Proposition self000 = ((Proposition)(self));
{ Keyword testValue000 = self000.kind;
if ((testValue000 == OntosaurusUtil.KWD_ISA) ||
((testValue000 == OntosaurusUtil.KWD_FUNCTION) ||
((testValue000 == OntosaurusUtil.KWD_PREDICATE) ||
((testValue000 == OntosaurusUtil.KWD_NOT) ||
((testValue000 == OntosaurusUtil.KWD_EQUIVALENT) ||
(testValue000 == OntosaurusUtil.KWD_FAIL)))))) {
}
else {
{
stream.nativeStream.print("<PRE>");
OntosaurusUtil.pprintObject(self000, stream.nativeStream);
stream.nativeStream.println("</PRE>");
}
return;
}
}
}
}
else {
}
OntosaurusUtil.pprintObject(self, stream.nativeStream);
} finally {
OntosaurusUtil.$PPRINT_ATOMIC_OBJECT_RENDERER$.set(old$PprintAtomicObjectRenderer$000);
Logic.$LOGIC_DIALECT$.set(old$LogicDialect$000);
}
}
} |
9fd9f924-9339-4cbc-ac68-208707fc2af3 | 6 | public static StorageSlot LOOKUP_ELEMENT_SLOT(XMLObject renamed_Object, Cons elementExpr) {
{ XmlElement tag = ((XmlElement)(elementExpr.value));
Cons general_slots = Stella.NIL;
{ Slot slot = null;
Cons ITER_000 = XMLObject.GET_MAPPED_SLOTS(renamed_Object).theConsList;
for (;!(ITER_000 == Stella.NIL); ITER_000 = ITER_000.rest) {
slot = ((Slot)(ITER_000.value));
if (XmlObjects.ELEMENT_SLOTP(slot)) {
if (XmlObjects.SLOT_REPRESENTS_TAGP(slot, tag, true, false)) {
return (((StorageSlot)(slot)));
}
else if (slot.typeSpecifier() == XmlObjects.SGT_XML_OBJECTS_XMLObject) {
general_slots = Cons.cons(slot, general_slots);
}
else {
}
}
}
}
if (general_slots == Stella.NIL) {
return (null);
}
else if (general_slots.rest == Stella.NIL) {
return (((StorageSlot)(general_slots.value)));
}
else {
return (null);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.