method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
02c8d311-34ec-4703-a393-c3440bca32f3 | 0 | public void setBytesRead(long bytesRead)
{
this.bytesRead = bytesRead;
} |
346c14c6-03dc-4d3d-b51a-7684d5b12b92 | 7 | public static void main(String[] args) {
// list (interface) et ArrayList (implementation)
Collection<Integer> integers1 = new ArrayList<>();
integers1.add(1);
integers1.add(2);
integers1.add(3);
for(Integer i : integers1){
System.out.println(i);
}
logger.info("Taille de integers1 "+ integers1.size());
Collection<Integer> integers2 = new ArrayList<>();
integers2.add(4);
integers2.add(2);
integers2.add(5);
integers2.add(1);
for(Integer i : integers2){
logger.info(i);
}
logger.info("Taille de integers2 "+ integers2.size());
Set<Integer> integersSet = new HashSet<>();
integersSet.addAll(integers1);
integersSet.addAll(integers2);
logger.info("Taille de integersSet "+ integersSet.size());
Collection<String> strings = new ArrayList<>();
strings.add("ch1");
strings.add("ch2");
strings.add("ch3");
for(String s : strings){
System.out.println(s);
}
logger.info("Taille de strings : "+ strings.size());
// Set , HashSet
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(2);
set.add(3);
set.add(4);
logger.info("Taille de strings : "+ set.size());
// Map , HashMap
Map<Integer , Collection<String>> villesMap = new HashMap<>();
villesMap.put(75,new ArrayList<String>());
villesMap.get(75).add("Paris");
villesMap.put(69,new ArrayList<String>());
villesMap.get(69).add("Lyon");
villesMap.get(69).add("Givort");
villesMap.put(38,new ArrayList<String>());
villesMap.get(38).add("Grenoble");
villesMap.put(13,new ArrayList<String>());
villesMap.get(13).add("Marseille");
for(Integer cleDepartement : villesMap.keySet()){
Collection<String> villes = villesMap.get(cleDepartement);
logger.info("Departement -> " + cleDepartement);
for(String city : villes){
logger.info("\tVille : "+ city);
}
}
Map<String, Integer> notesMap = new HashMap<>();
notesMap.put("student 1 ", 14);
notesMap.put("student 2 ", 16);
notesMap.put("student 3 ", 18);
Collection<Integer> notes = notesMap.values();
for(Integer note : notes){
logger.info("Note : "+ note);
}
Set<Map.Entry<String , Integer>> entries = notesMap.entrySet();
for(Map.Entry<String, Integer> entry : entries){
logger.info("Entre : " + entry.getValue() + " Note : "+ entry.getValue());
}
// Test des points , equals et hash
Collection<Point> listePoints = new HashSet<>();
listePoints.add(new Point(1,3));
listePoints.add(new Point(2,5));
listePoints.add(new Point(1,5));
listePoints.add(new Point(1,3));
logger.info("ListePoints : "+ listePoints);
logger.info("Taille de la listePoints : "+ listePoints.size());
} |
32d3b682-dbaa-417a-a00d-d0c790770f2a | 4 | public static int getSelectedIndex() {
if (getSelected() == null) {
return -1;
}
RSInterface parent = getInterface();
if (parent.children == null) {
return -1;
}
for (int index = 0; index < parent.children.size(); index++) {
if (parent.children.get(index) == getSelected().id) {
return index;
}
}
return -1;
} |
c4bbf074-14a8-4beb-95fb-409c64b4a499 | 8 | public final boolean equals(final Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Binding)) {
return false;
}
final Binding binding = (Binding) object;
if (!Util.equals(getParameterizedCommand(), binding
.getParameterizedCommand())) {
return false;
}
if (!Util.equals(getContextId(), binding.getContextId())) {
return false;
}
if (!Util.equals(getTriggerSequence(), binding.getTriggerSequence())) {
return false;
}
if (!Util.equals(getLocale(), binding.getLocale())) {
return false;
}
if (!Util.equals(getPlatform(), binding.getPlatform())) {
return false;
}
if (!Util.equals(getSchemeId(), binding.getSchemeId())) {
return false;
}
return (getType() == binding.getType());
} |
b814a9ac-91f2-45ef-8ef9-0251514e60cf | 0 | public String toString(){
return "minus ";
} |
d1f3a6aa-ff34-4f85-8645-7164fcdacb53 | 2 | protected void drawTransitions(Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
super.drawTransitions(g);
Iterator it = selectedTransitions.iterator();
while (it.hasNext()) {
Transition t = (Transition) it.next();
try {
arrowForTransition(t).drawHighlight(g2);
} catch (NullPointerException e) {
// Then this transition isn't in here.
}
}
} |
8ff1ff3e-048a-4d95-b1df-6618d773b2e3 | 5 | public boolean validateTextboxes() {
boolean error = false;
if (txtAname.getText().isEmpty()) {
error = true;
}
if (txtISBNNo.getText().isEmpty()) {
error = true;
}
if (txtName.getText().isEmpty()) {
error = true;
}
if (txtSname.getText().isEmpty()) {
error = true;
}
if (txtTitle.getText().isEmpty()) {
error = true;
}
return error;
} |
e1164601-fe7c-428e-bb61-88249974d1c4 | 9 | public static String removeComments(String code) {
String codeWithoutComments = "";
char command = 0;
// copy whole code without comments
for (int i = 0; i < code.length(); i++) {
command = code.charAt(i);
if (command == '/') {
command = code.charAt(i + 1);
switch (command) {
case '/':
// skip single-line comment
while (code.charAt(i) != '\n' && i < code.length() - 1) i++;
break;
case '*':
// skip multi-line comment
while (!(code.charAt(i) == '*' && code.charAt(i + 1) == '/') && i < code.length() - 2) i++;
i++;
break;
default:
// ignore
codeWithoutComments += '/';
break;
}
} else {
codeWithoutComments += command;
}
}
return codeWithoutComments;
} |
adaea825-530b-4fd2-86e1-d98dfb6f3e30 | 9 | public ProtobufDecoder(String[] classpath, String rootClass,
FieldDefinition[] fields) throws ProtobufDecoderException {
try {
URL[] url = new URL[classpath.length];
for (int i = 0; i < classpath.length; ++i) {
String file = classpath[i];
if (file.startsWith("file://")) {
file = file.substring(7);
}
url[i] = new File(file).toURI().toURL();
}
this.classLoader = new URLClassLoader(url, getClass()
.getClassLoader());
} catch (MalformedURLException e) {
throw new ProtobufDecoderException(e);
}
try {
this.rootClass = classLoader.loadClass(rootClass);
} catch (ClassNotFoundException e) {
throw new ProtobufDecoderException("Can't find root class", e);
}
try {
this.rootParseFromMethod = this.rootClass.getDeclaredMethod(
"parseFrom", new Class<?>[] { byte[].class });
} catch (SecurityException e) {
throw new ProtobufDecoderException(e);
} catch (NoSuchMethodException e) {
throw new ProtobufDecoderException(
"Can't setup Protocol Buffers decoder", e);
}
if (fields != null) {
this.paths = new LinkedHashMap<String, Integer>();
for (int i = 0; i < fields.length; ++i) {
this.paths.put(fields[i].path, Integer.valueOf(i));
}
this.fields = fields;
}
} |
195d8472-a3d6-404a-9d75-695a8f284f2b | 4 | @SuppressWarnings("unchecked")
private void checkPartition(String partitionName, String dn,
HashMap attributes) throws Exception {
LoggerFactory.getLogger(this.getClass()).debug("Adding partition:"+partitionName+dn+attributes.toString());
Partition apachePartition = addPartition(partitionName, dn);
// Index some attributes on the partition
addIndex(apachePartition, "objectClass", "ou", "uid");
// Inject the apache root entry if it does not already exist
try {
directoryService.getAdminSession().lookup(
apachePartition.getSuffixDn());
} catch (LdapNameNotFoundException lnnfe) {
LdapDN dnApache = new LdapDN(dn);
ServerEntry entryApache = directoryService.newEntry(dnApache);
Iterator<String> iter = attributes.keySet().iterator();
while (iter.hasNext()) {
String attributeName = (String) iter.next();
Object value = attributes.get(attributeName);
if (value instanceof String) {
entryApache.add(attributeName, (String) value);
} else {
ArrayList<String> val = (ArrayList<String>) value;
for (String v : val) {
entryApache.add(attributeName, v);
}
}
}
directoryService.getAdminSession().add(entryApache);
}
} |
59470256-f9ab-44ed-93db-5161b216da5a | 4 | public boolean isTranslucencySupported(Translucency translucencyKind, GraphicsDevice gd) {
Object kind = null;
switch(translucencyKind) {
case PERPIXEL_TRANSLUCENT:
kind = PERPIXEL_TRANSLUCENT;
break;
case TRANSLUCENT:
kind = TRANSLUCENT;
break;
case PERPIXEL_TRANSPARENT:
kind = PERPIXEL_TRANSPARENT;
break;
}
try {
return (Boolean) isTranslucencySupported.invoke(gd, kind);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} |
a3951cc9-999b-4914-8ab5-27b324e9843a | 4 | @Override
public void onMoveTick(int x, int y, Game game) {
SinglePlayerGame spg = (SinglePlayerGame) game;
Location loc = spg.getFirstSquareNeighborLocation(x, y, 5, zombie.id);
if (loc == null) {
if (filterByID(spg.getSquareNeighbors(x, y, 2), human.id).isEmpty()) {
loc = Location.idleWander(x, y, 1, 50);
if (loc != null) {
spg.moveEntity(x, y, loc);
}
}
} else {
if (!spg.moveEntity(x, y, Location.towards(x, y, loc, 2))) {
spg.moveEntity(x, y, Location.wander(x, y, 1));
}
}
} |
147171b8-283b-4323-962c-26d753d44d2e | 3 | @Override
public void run() {
long lastTime = System.nanoTime();
double ns = 1000000000.0 / 60.0;
double delta = 0;
long lastTimer = System.currentTimeMillis();
int ticks = 0, frames = 0;
requestFocus();
while (running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while (delta >= 1) {
tick();
ticks++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - lastTimer > 1000) {
lastTimer += 1000;
System.out.println(ticks + " ticks, " + frames + " fps");
frame.setTitle(TITLE + " - " + ticks + " tps, " + frames + " fps");
ticks = 0;
frames = 0;
}
}
stop();
} |
31fa7536-bd18-4f83-9321-058b46337dc5 | 4 | @Override
public void handleEvent() {
LogManager.getLogger(FileAppender.class).info("handle event");
try {
int readed, wrote;
while ((readed = pipe.source().read(dst)) != 0) {
if (readed > 0) {
if (readed < dst.capacity()) {
dst.put(System.lineSeparator().getBytes());
}
dst.flip();
wrote = fileChannel.write(dst);
LogManager.getLogger(FileAppender.class).log(Level.INFO,
"file appender reads {}, wrote {}", readed, wrote);
dst.clear();
} else {
LogManager.getLogger(FileAppender.class).error(
"end of input?");
return;
}
}
} catch (IOException e) {
LogManager.getLogger(FileAppender.class).error("run", e);
}
// if (R.USE_EXECUTORS) {
// try {
// dispatcher.register(FileAppender.this, SelectionKey.OP_READ);
// } catch (ClosedChannelException e) {
// e.printStackTrace();
// }
// }
LogManager.getLogger(FileAppender.class).debug("executed");
} |
e9a542ad-807d-499f-a1a7-1cbab1ff636a | 7 | public void registerEngine(Engine engine) throws EngineException {
final EngineInfo engDep = engine.getClass().getAnnotation(EngineInfo.class);
if (engDep != null) {
String[] depends = engDep.depends();
for (String s : depends) {
if (!isRegistered(s)) {
if (!engineQueue.contains(engine)) {
engineQueue.add(engine);
}
return;
}
}
} else {
throw new EngineException("Unable to find Engine Info.");
}
try {
engine.runStartupChecks();
if (!activeEngines.containsKey(engine.getName())) {
activeEngines.put(engine.getName(), engine);
System.out.println("[FreeForAll] Engine: " + engine.getName() + " has been started.");
if (engineQueue.contains(engine)) {
engineQueue.remove(engine);
}
FreeForAll.getInstance().getServer().getPluginManager().registerEvents(engine, FreeForAll.getInstance());
runEngineQueue();
} else {
throw new EngineException("[FreeForAll] Engine with name: " + engine.getName() + " already is registered.");
}
} catch (EngineException ex) {
System.out.println("[FreeForAll] Unabled to start Engine: " + engine.getName() + " Reason: " + ex.getMessage());
}
} |
86e75eaa-f996-4036-9fed-c9f6f2249dbe | 9 | public void processPacket(String received) {
stringParts = received.split(" ");
try {
// auction- ended- notification
if (stringParts[0].equals("!auction-ended")) {
String describtion = "";
// user is the highest bidder
if (username.equals(stringParts[1].trim())) {
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction '" + describtion +
"' has ended. You won with " + stringParts[2] + "!");
}
else {
// user is the owner- no one bid
if (stringParts[1].equals("none")) { // nobothy bid to this auction
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction '" + describtion + "' has ended. " +
"Nobothy bid.");
}
// user is the woner and someone bid
else {
for (int i = 3; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("The auction ' " + describtion + "' has ended. " +
stringParts[1] + " won with " + stringParts[2] + ".");
}
}
}
// new bid- notification
if (stringParts[0].equals("!new-bid")) {
String describtion = "";
for (int i = 1; i < stringParts.length; i++) {
describtion += stringParts[i] + " ";
}
System.out.println("You have been overbid on '" + describtion + "'.");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: message not correct!");
}
} |
ec0f0bd9-5ba6-4a70-a438-51830c825dcb | 5 | public QuickSort(List liste, int debut, int fin) {
listeComparable = liste;
int gauche = debut - 1;
int droite = fin + 1;
// reset Pivot
pivot = null;
pivot = listeComparable.get(debut);
/* Si le tableau est de longueur nulle, il n'y a rien à faire. */
if (debut >= fin)
return;
while (true) {
do droite--; while (listeComparable.get(droite).compareTo((T) pivot) == BIGGER);
do gauche++; while (listeComparable.get(gauche).compareTo((T) pivot) == SMALLER);
if (gauche < droite)
echanger(listeComparable, gauche, droite);
else break;
}
/* for(int i = 0; i < liste.size(); i++)
{
listeComparable = liste;
System.out.printf("%d ", listToTest.get(i).getPointSource());
}
System.out.println();*/
/*
* Maintenant, tous les éléments inférieurs au pivot sont avant ceux
* supérieurs au pivot. On a donc deux groupes de cases à trier. On
* utilise pour cela... la méthode quickSort elle-même !
*/
new QuickSort(listeComparable, debut, droite);
new QuickSort(listeComparable, droite + 1, fin);
/* profondeur = profondeur- 1;
if (profondeur == 0){
System.out.println("Profondeur = 0!");
liste = listeComparable;
}*/
} |
72784fce-085e-41ee-bbcc-82fd6bc00d85 | 5 | public SemanticsAnalyzer(Node tree) {
SymbolTable.resetAll();
output = new StringBuilder();
this.generativeTree = tree;
Scanner fr = null;
try {
fr = new Scanner(new File("produkcije.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String curr = null;
int index = 0;
productions = new HashMap<String, List<SemanticsAnalyzer.orderedProduction>>();
productionEnum = PPJCProduction.values();
while (fr.hasNextLine()) {
String ln = fr.nextLine();
if (ln.equals("\n"))
continue;
if (ln.startsWith("\t")) {
if (productions.get(curr) == null)
productions.put(curr, new ArrayList<SemanticsAnalyzer.orderedProduction>());
productions.get(curr).add(new orderedProduction(ln.substring(1).split("\\s+"), index));
index++;
} else {
curr = ln;
}
}
fr.close();
} |
d4f948cd-b242-46b4-b8aa-5b3a1ee36350 | 0 | public static void main(String[] args) {
{
int x = 12;
// Only x available
{
int q = 96;
// Both x & q available
}
// Only x available
// q is "out of scope"
}
{
String s = new String("a string");
}
// System.out.println(s); // Error
} |
188e7b2f-c186-403e-ab5b-7a90854b5892 | 7 | public static void impt() throws Exception {
File f = new File(System.getenv("APPDATA")
+ "//.pokechrome/player.sav");
FileInputStream fstream = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(
fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
// Gdx.app.log(ChromeGame.LOG, strLine);
String[] hold = strLine.split(":");
switch (hold[0]) {
case "NAME":
GameFile.playerName = hold[1];
break;
case "MONEY":
GameFile.playerMoney = Float.parseFloat(hold[1]);
break;
case "POS":
String[] pos = hold[1].split(",");
GameFile.playerPosition = new Vector2(
Float.parseFloat(pos[0]),
Float.parseFloat(pos[1]));
break;
case "MAP":
GameFile.currentMap = hold[1];
break;
case "GENDER":
GameFile.playerGender = hold[1];
break;
case "MUSIC":
GameFile.musicName = hold[1];
GameFile.musicPlaying = Gdx.audio
.newMusic(Gdx.files.internal("music/"
+ hold[1] + ".mp3"));
break;
}
}
br.close();
} |
f2453edf-fef3-4791-b17b-90100e27d9bf | 0 | void exportAutomaton() {
Environment e = ((EnvironmentFrame) frame).getEnvironment();
AutomatonPane a = new AutomatonPane(drawer);
e.add(a, "Current FA");
e.setActive(a);
} |
fa785219-9311-45c9-beed-bf4275fec644 | 0 | public static int getCount() {
return phones.size();
} |
43e1500f-54bd-481a-af46-28289d5689ae | 1 | @SuppressWarnings("unchecked")
public static <T extends Object> List<T> addArrayToList(List<T> list, T[] obj) {
for(int i = 0; i < obj.length; ++i) {
list.add(obj[i]);
}
return list;
} |
bdc4029e-8ac7-461d-ab7c-8b4db4a2a010 | 0 | public PadSelection() {} |
c357f1aa-f376-4e83-818f-a8b954be2c19 | 6 | public static BooleanWrapper secondp(Stella_Object number) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(number);
if (Surrogate.subtypeOfIntegerP(testValue000)) {
{ IntegerWrapper number000 = ((IntegerWrapper)(number));
return ((((0 <= number000.wrapperValue) &&
(number000.wrapperValue <= 59)) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER));
}
}
else if (Surrogate.subtypeOfFloatP(testValue000)) {
{ FloatWrapper number000 = ((FloatWrapper)(number));
return ((((0.0 <= number000.wrapperValue) &&
(number000.wrapperValue < 60.0)) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER));
}
}
else {
return (Stella.FALSE_WRAPPER);
}
}
} |
d0b2f558-50ed-4bff-86c1-67eacebfb307 | 9 | private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0;
Token tok = token;
while (tok != null && tok != jj_scanpos) {
i++;
tok = tok.next;
}
if (tok != null)
jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind)
return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos)
throw jj_ls;
return false;
} |
22dcadfc-a380-429e-924f-36f7568da54b | 3 | public String genContent(String httpUrl) {
Object response = null;
for (String key : requests.keySet()) {
if (httpUrl.endsWith(key)) {
response = requests.get(key);
break;
}
}
if (response instanceof String) {
return (String) response;
}
throw (RuntimeException) response;
} |
71fc7ce9-868d-45fe-bfa3-3dc1981ffe58 | 9 | public void zeigeRaeumeAn(String input, ArrayList<Raum> raumListe) {
Analyser ana = new Analyser();
String[] data = ana.splitArguments(input);
int sort = ana.analyseSort(data[0]);
if (sort == 0) {
Collections.sort(raumListe);
} else if (sort == 1) {
Collections.sort(raumListe, Collections.reverseOrder());
}
for (Object o : raumListe) {
if (o instanceof Konferenzraum) {
Konferenzraum showKRaum = (Konferenzraum) o;
System.out.println("Name: " + showKRaum.getName() + " | Groesse: " + showKRaum.getGroesse() + "qm | Status: " + showKRaum.getTextStatus() + " -> ist ein " + showKRaum.getTyp());
} else if (o instanceof Arbeitsraum) {
Arbeitsraum showARaum = (Arbeitsraum) o;
System.out.println("Name: " + showARaum.getName() + " | Groesse: " + showARaum.getGroesse() + "qm | Beamer: " + showARaum.getTextBeamer() + " | Sitze: " + showARaum.getSitze() + " -> ist ein " + showARaum.getTyp());
} else if (o instanceof Kueche) {
Kueche showKueche = (Kueche) o;
System.out.println("Name: " + showKueche.getName() + " | Groesse: " + showKueche.getGroesse() + "qm | Kaffeemaschine: " + showKueche.getTextKaffee() + " | Gedecke: " + showKueche.getGedecke() + " -> ist eine " + showKueche.getTyp());
} else if (o instanceof Toilette) {
Toilette showToi = (Toilette) o;
System.out.println("Name: " + showToi.getName() + " | Groesse: " + showToi.getGroesse() + "qm | Reinigungs-Status: " + showToi.getSauber() + " | Geschlecht: " + showToi.getTextGeschlecht() + " -> ist eine " + showToi.getTyp());
} else if (o == null) {
System.out.println("Keine Raeume vorhanden");
} else {
System.out.println("Keine Raeume vorhanden");
}
}
if (raumListe.isEmpty()) {
System.out.println("Noch keine Raeume vorhanden");
}
} |
ef8702a9-433b-43ed-9996-a071409c94a5 | 2 | public static void remove ( LinkedListNode head ) {
LinkedListNode nd = head;
LinkedListNode pre = null;
HashMap<Integer, Boolean> hm = new HashMap<>();
// travel through the list
while ( nd != null ) {
// 1. check if the data has aldy existed in the HashTable
if ( hm.containsKey(nd.data) ) {
pre.next = nd.next;
nd = nd.next;
}else {
hm.put(nd.data, true);
pre = nd;
nd = nd.next;
}
}
} |
2b4a372e-2517-4242-9205-4eb3155f9f45 | 0 | public String getQueryRes() {
return queryRes;
} |
feb861ff-289b-422a-b7bd-0c97bc4515bd | 2 | public boolean isSelected(int index) {
if (index < 0 || index >= mSize) {
return false;
}
return mSelection.get(index);
} |
4d7dc696-b595-4e37-9d8c-ce5cc2e21c62 | 5 | public boolean shouldExitLoop() {
if (isDebug) {
if (KeyInput.wasKeyPressed('r')) {
I.say("RESET MISSION?") ;
resetScenario() ;
return false ;
}
if (KeyInput.wasKeyPressed('f')) {
I.say("Paused? "+PlayLoop.paused()) ;
PlayLoop.setPaused(! PlayLoop.paused()) ;
}
if (KeyInput.wasKeyPressed('s')) {
I.say("SAVING GAME...") ;
PlayLoop.saveGame(fullSavePath(savesPrefix, CURRENT_SAVE)) ;
return false ;
}
if (KeyInput.wasKeyPressed('l')) {
I.say("LOADING GAME...") ;
PlayLoop.loadGame(fullSavePath(savesPrefix, CURRENT_SAVE), true) ;
return true ;
}
}
return false ;
} |
dfee6ce6-6fa3-4246-b7dd-a39844bda726 | 7 | public int escribir(String nombre, String rutaArchivo) {
InputStream entrada = null;
PreparedStatement pst = null;
int ingresados = 0;
try {
File archivo;
String insert;
z.con.setAutoCommit(false);
insert = "Insert into documentos (nombre, documentos, fecha) values(?,?, NOW())";
pst = (PreparedStatement) z.con.prepareStatement(insert);
archivo = new File(rutaArchivo);
entrada = new FileInputStream(archivo);
pst.setString(1, nombre.toUpperCase());
pst.setBinaryStream(2, entrada, (int) archivo.length());
ingresados = pst.executeUpdate();
z.con.commit();
} catch (FileNotFoundException ex) {
Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (entrada != null) {
entrada.close();
}
} catch (IOException ex) {
Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (pst != null) {
pst.close();
}
} catch (SQLException ex) {
Logger.getLogger(Archivos.class.getName()).log(Level.SEVERE, null, ex);
}
}
return ingresados;
} |
7e45cd57-995c-4aa6-8985-62ea8a5cd5c3 | 8 | public boolean autorizeRemoval (Block block, Player player){
boolean authorized = true; // By default, let it be removed.
if (player != null && plugin.permit(player, "repairchest.destroy")){
authorized = true;
/*
* Basically "do nothing", but this IF block avoids a lot of work for authorized users.
* No need to check block type and blah blah blah if it's just going to be authorized anyway.
*/
}
else if (block.getType().equals(Material.WALL_SIGN)){
if (this.relevantSign(block)){
if (player != null){
player.sendMessage(plugin.cfg().tr("removePermissionDenied"));
}
authorized = false;
}
}
else {
Iterator<BlockFace> faces = checkFaces.iterator();
while (faces.hasNext()){
BlockFace face = faces.next();
if (this.relevantSign(block.getRelative(face))){
authorized = false;
if (player != null){
player.sendMessage(plugin.cfg().tr("cantRemoveProtected"));
}
break;
}
}
}
return authorized;
} |
f2b9b587-cf8b-40ec-9baa-e13df1960299 | 1 | public void visitReturnStmt(final ReturnStmt stmt) {
if (CodeGenerator.DEBUG) {
System.out.println("code for " + stmt);
}
genPostponed(stmt);
stmt.visitChildren(this);
method.addInstruction(Opcode.opcx_return);
// Stack height is zero after return
stackHeight = 0;
} |
e46cb133-5e0f-40cc-b0a3-f102aa5cf9cb | 3 | private void adjustStat(Actor a, int increment){
if(a instanceof Asteroid){
asteroidCount += increment;
} else if(a instanceof Bandit){
banditCount += increment;
} else if(a instanceof BanditBase){
banditBaseCount += increment;
}
} |
407677fc-ad0e-42ae-8c65-f3f649728572 | 8 | @Override
public String getStat(String code)
{
if (CMLib.coffeeMaker().getGenMobCodeNum(code) >= 0)
return CMLib.coffeeMaker().getGenMobStat(this, code);
switch (getCodeNum(code))
{
case 0:
return "" + getWhatIsSoldMask();
case 1:
return prejudiceFactors();
case 2:
return budget();
case 3:
return devalueRate();
case 4:
return "" + invResetRate();
case 5:
return ignoreMask();
case 6:
return CMParms.toListString(itemPricingAdjustments());
default:
return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code);
}
} |
7c613579-504e-4d5e-bcb0-06fc04691ff6 | 0 | public int getSecondID() {
return second_land.getID();
} |
57ccc94e-89d0-4f8c-b865-8e4da8b8c964 | 1 | public int getNumber()
{
int value=0;
if (q.size() > 0)
{
value = (Integer)q.remove();
}
return value;
} |
1c80441b-470c-44da-81fa-5a108f01e6fc | 1 | private static Stock parseStock(String line) {
String[] parts = line.split(",");
if (parts[2].equals("0.00")) {
System.err.println("Stock " + parts[1] + " does not exist!");
return null;
}
Stock s = new Stock(parts[1].replace("\"", ""),
parts[0].replace("\"", ""),
0, Float.parseFloat(parts[2]));
return s;
} |
d69c70c5-cc63-41ed-a093-7685ce4126b2 | 0 | public Integer getSuccessCount() {
return successCount;
} |
4438f235-84e6-4f39-b227-6a355745f307 | 1 | public boolean isReleased() {
if(isDisabled())
return false;
return released;
} |
a6c86ee5-6fc3-40d8-9f93-b650dd2dd79e | 9 | final public SimpleNode Start() throws ParseException {
/*@bgen(jjtree) Start */
SimpleNode jjtn000 = new SimpleNode(JJTSTART);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
try {
expression();
jj_consume_token(21);
jjtree.closeNodeScope(jjtn000, true);
jjtc000 = false;
{if (true) return jjtn000;}
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
}
}
throw new Error("Missing return statement in function");
} |
1d6c6589-fefc-46f6-9b52-b8d1651e610b | 1 | private MyConnection() {
try {
connection = DriverManager.getConnection(url,login,pwd);
} catch (SQLException ex) {
Logger.getLogger(MyConnection.class.getName()).log(Level.SEVERE, null, ex);
}
} |
c9fc09da-f5ef-4dc6-864b-c80afb13d161 | 1 | @Override
public String[][] getListOfGames(Member member) {
List<Game> gameList = data.getListOfGames(member);
String [][] gameArray = new String[gameList.size()][3];
for(int i=0;i<gameList.size();i++){
gameArray[i][0]=gameList.get(i).getDate().toString();
gameArray[i][1]=gameList.get(i).getMemberOne().getFirstname() + " " + gameList.get(i).getMemberOne().getLastname();
gameArray[i][2]=gameList.get(i).getMemberTwo().getFirstname() + " " + gameList.get(i).getMemberTwo().getLastname();
}
return gameArray;
} |
a4c86ade-c422-4f7a-a317-c23096943a9c | 5 | private void loadDataToComboboxHMP(){
this.cmbAulaHMP.removeAllItems();
this.cmbDiaHMP.removeAllItems();
this.cmbMateriaHMP.removeAllItems();
this.cmbHorarioHMP.removeAllItems();
this.cmbGrupoHMP.removeAllItems();
this.cmbUsuarioHMP.removeAllItems();
for(String n: this.hmp.listIdAula){
this.cmbAulaHMP.addItem(n);
}
for(String n: this.hmp.listIdGrupo){
this.cmbGrupoHMP.addItem(n);
}
for(String n: this.hmp.listIdHorario){
this.cmbHorarioHMP.addItem(n);
}
for(String n: this.hmp.listIdMateria){
this.cmbMateriaHMP.addItem(n);
}
for(String n: this.hmp.listIdUsuario){
this.cmbUsuarioHMP.addItem(n);
}
this.cmbDiaHMP.addItem("LUNES");
this.cmbDiaHMP.addItem("MARTES");
this.cmbDiaHMP.addItem("MIERCOLES");
this.cmbDiaHMP.addItem("JUEVES");
this.cmbDiaHMP.addItem("VIERNES");
} |
9c79fcfa-9208-42fd-ac45-f4ea4d52f823 | 8 | protected int getEscapeRoute(int directionToTarget)
{
if(directionToTarget < 0)
return directionToTarget;
Room shipR=CMLib.map().roomLocation(loyalShipItem);
if(shipR!=null)
{
int opDir=Directions.getOpDirectionCode(directionToTarget);
if(isGoodShipDir(shipR,opDir))
return opDir;
final List<Integer> goodDirs = new ArrayList<Integer>();
for(int dir : Directions.CODES())
{
if(isGoodShipDir(shipR,dir))
goodDirs.add(Integer.valueOf(dir));
}
final Integer dirI=Integer.valueOf(directionToTarget);
if(goodDirs.contains(dirI)
&&(goodDirs.size()>1))
goodDirs.remove(dirI);
if(goodDirs.size()>0)
return goodDirs.get(0).intValue();
}
return -1;
} |
c4a8a6c5-46ae-4a87-af26-7d2a6cb27a8e | 1 | private String showAnnonce(int i) {
String res = "";
//////
if (voyages.length > 0) {
sb.append("Destination");
sb.append(voyages[i].getDestination());
sb.append("\n");
sb.append("Date_depart");
sb.append(voyages[i].getDate_depart());
sb.append("\n");
sb.append("Date_retour");
sb.append(voyages[i].getDate_retour());
sb.append("\n");
sb.append("Itineraire");
sb.append(voyages[i].getItineraire());
sb.append("\n");
sb.append("Nb_place");
sb.append(voyages[i].getNb_place());
sb.append("\n");
}
res = sb.toString();
sb = new StringBuffer("");
return res;
} |
c5f1582a-2abc-4252-b508-a51e2a38918b | 5 | public static double FindMax (boolean x, double n, List<Point2D> connection_p)
{
double _n = 0;
for (int i = 0; i < connection_p.size(); i++)
{
if(x)
{
double _x = connection_p.get(i).getX();
if (_x > _n)
{
_n = _x;
}
}
else
{
double _y = connection_p.get(i).getY();
double _x = connection_p.get(i).getX();
if (_y > _n && _x == n)
{
_n = _y;
}
}
}
return _n;
} |
cc202ad4-094f-439e-88da-b0e07f24a3e0 | 1 | public boolean equals(Object o) {
return (o instanceof TreeElement)
&& fullName.equals(((TreeElement) o).fullName);
} |
66f4eafc-c1b4-4cfa-8117-8ee350891503 | 9 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!(affected instanceof MOB))
return super.okMessage(myHost,msg);
final MOB mob=(MOB)affected;
if((msg.amITarget(mob))
&&(CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS))
&&(msg.targetMinor()==CMMsg.TYP_CAST_SPELL)
&&(msg.tool() instanceof Ability)
&&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PRAYER)
&&(invoker!=null)
&&(!mob.amDead())
&&(CMLib.dice().rollPercentage()<35))
{
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("The ward around <S-NAME> inhibits @x1!",msg.tool().name()));
return false;
}
return super.okMessage(myHost,msg);
} |
7cf4f50b-8884-4b53-8883-4cfd3cc526d3 | 3 | public static byte[] getUnsignedBytes(BigInteger number, int length) {
byte[] value = number.toByteArray();
if (value.length > length + 1) {
throw new IllegalArgumentException(
"The given BigInteger does not fit into a byte array with the given length: " + value.length
+ " > " + length);
}
byte[] result = new byte[length];
int i = value.length == length + 1 ? 1 : 0;
for (; i < value.length; i++) {
result[i + length - value.length] = value[i];
}
return result;
} |
a463d6ac-324f-483f-a5f5-88c59e5c3d4d | 4 | private boolean read() {
try {
final URLConnection conn = this.url.openConnection();
conn.setConnectTimeout(5000);
if (this.apiKey != null) {
conn.addRequestProperty("X-API-Key", this.apiKey);
}
conn.addRequestProperty("User-Agent", "Updater (by Gravity)");
conn.setDoOutput(true);
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final String response = reader.readLine();
final JSONArray array = (JSONArray) JSONValue.parse(response);
if (array.size() == 0) {
this.plugin.getLogger().warning("The updater could not find any files for the project id " + this.id);
this.result = UpdateResult.FAIL_BADID;
return false;
}
this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE);
return true;
} catch (final IOException e) {
if (e.getMessage().contains("HTTP response code: 403")) {
this.plugin.getLogger().warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().warning("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().warning("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().warning("If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
this.result = UpdateResult.FAIL_DBO;
}
e.printStackTrace();
return false;
}
} |
3a9c14d6-15ac-49e3-b64c-3ea7dd41c301 | 4 | public InfoNode dealWithPromote(InfoNode infoNode, Node node) {
if(infoNode == null){return null;}
node.add(infoNode.newKey, infoNode.rightChild);
if(node.getSize() <= maxDegree){return null;}
InternalNode sibling = new InternalNode();
int mid = (node.getSize()/2)+1;
int j = 1;
int loopTo = ((InternalNode)node).size;
int promoteKey = ((InternalNode)node).keys[mid];
for(int i = mid+1;i<=loopTo;i++){
sibling.keys[j] = node.getKey(i);
sibling.size++;
j++;
}
j=0;
for(int i = mid; i<=loopTo;i++){
sibling.children[j] = node.getChild(i);
j++;
node.remove(i);
}
return new InfoNode(promoteKey, sibling);
} |
28971e01-99cd-454a-9ad6-29540ca86932 | 8 | protected void setOrientation(int orientation) {
Integer bigTextTopMargin = null;
Integer installButtonTopMargin = null;
Integer peopleTopMargin = null;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
bigTextTopMargin = 8;
installButtonTopMargin = 6;
peopleTopMargin = 9;
} else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
bigTextTopMargin = 19;
installButtonTopMargin = 11;
peopleTopMargin = 12;
}
if (bigTextTopMargin != null && bigText != null) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bigText.getLayoutParams();
params.setMargins(params.leftMargin, Utils.getScaledSize(getContext(), bigTextTopMargin), params.rightMargin, params.bottomMargin);
bigText.setLayoutParams(params);
}
if (installButtonTopMargin != null && installButton != null) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) installButton.getLayoutParams();
params.setMargins(params.leftMargin, Utils.getScaledSize(getContext(), installButtonTopMargin), params.rightMargin, params.bottomMargin);
installButton.setLayoutParams(params);
}
if (peopleTopMargin != null && people != null) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) people.getLayoutParams();
params.setMargins(params.leftMargin, Utils.getScaledSize(getContext(), peopleTopMargin), params.rightMargin, params.bottomMargin);
people.setLayoutParams(params);
}
} |
29dd6e5d-3ba8-4928-bb52-719a8888ebe9 | 2 | private void compare() {
// 第一次执行compare()时,preScan.size() == 0
if (preScan.size() == 0) {
return ;
}
if (!preScan.equals(cruScan)) {
onChange();
}
} |
37aa4f26-0482-4b92-b84d-722f72b71261 | 0 | @Override
public void receive(Map myCustomEvent) {
applicationEventPublisher.publishEvent(new MyCustomEventApplicationEvent(this, myCustomEvent));
} |
1ae11efb-679a-48d1-9c1e-9fbda5acae6b | 2 | private void initArrays() {
if (data == null || picsize != data.length) {
data = new int[picsize];
magnitude = new int[picsize];
xConv = new float[picsize];
yConv = new float[picsize];
xGradient = new float[picsize];
yGradient = new float[picsize];
}
} |
16e43a6d-c7d5-48ff-9df1-e2ff68f0b622 | 0 | public static void ClearCheckedHostmasks(){ CheckedHostmasks.clear(); } |
738f24ef-1073-49df-be43-ee80d9b96e10 | 7 | private void playButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playButtonActionPerformed
// TODO add your handling code here:
int song = -1;
if (repr.isVisible()) {
song = reprList.getSelectedRow();
if (song != -1) {
playFromRepr(song);
}
} else if (music.isVisible()) {
song = musicList.getSelectedRow();
if (song != -1) {
playFromMusic(song);
}
} else if (files.isVisible()) {
song = fileList.getSelectedRow();
if (song != -1) {
play(fileList.getValueAt(song, 0).toString());
}
}
if (song == -1) {
con.next();
}
}//GEN-LAST:event_playButtonActionPerformed |
c28e9ee7-345d-4544-b28d-a5bcf70bb5a6 | 9 | public static void main(String[] args) {
System.out.println("Printing only even numbers (multiples of two)");
for(int i=0; i<=20; i++){
System.out.println(i++);
}
System.out.println("Printing all number from 0 to 20");
for(int i=0; i<=20; i++){
System.out.println(i);
}
System.out.println("Print each word in the array on separate line");
ArrayList<String> array = new ArrayList<String>();
array.add("one");
array.add("two");
array.add("three");
for(String word : array){
System.out.println(word);
}
System.out.println();
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
System.out.println();
for(int i=0; i<10; i++){
if(i == 5){
break;
}
System.out.println(i);
}
System.out.println();
for(int i=0; i<10; i++){
if(i == 5){
continue;
}
System.out.println(i);
}
} |
4202cccd-3103-45bd-abe4-cdc13c727711 | 0 | public Limbs(int upgradeCount, String name) {
super(upgradeCount, UpgradeType.Limbs, name);
} |
78f42967-07cd-4213-baa6-4cc1a8b6c1f2 | 7 | public void runGame(int rolls) {
while (totalRolls < rolls) {
// First, check if the piece is currently on a "Chance Card"
// location...
if (board.getChanceLocations().contains(currentLocation))
drawChanceCard();
else {
// ... or a "Community Chest Card" location
if (board.getComChestLocations().contains(currentLocation))
drawComChestCard();
// ... If not:
else {
// Roll the dice
die1 = rollDie();
die2 = rollDie();
// Increment the number of rolls
totalRolls++;
// Check if doubles rolled and increment numDoubles if true
if (die1 == die2)
numDoubles++;
// Check if three consecutive sets of doubles have been
// rolled and go to jail if true...
if (numDoubles == 3) {
goToJail();
// ...If not, move based on the current location:
} else {
// location is "Go To Jail"
if (currentLocation == 30) {
goToJail();
} else {
// location is "In Jail"
if (inJail == true) {
moveFromJail(die1, die2);
} else {
// all other locations
moveFromNormal(die1, die2);
}
}
}
}
}
}
} |
e1fa0b41-8d8f-4fad-a53d-f2ed26cd967a | 9 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String op = request.getParameter("op");
String userid = "";
String actionUrl = "";
Member user = (Member) session.getAttribute("user");
if(user != null) {
userid = user.getUserid();
}
// op가 없는 경우 무조건 login이라고 인식시킴
if(op == null) {
op = "login";
}
try{
if(op.equals("login")) { // 로그인을 시도하는 경우
actionUrl="login.jsp";
} else if(op.equals("logout")) { // 로그아웃을 시도하는 경우
System.out.println(session.getAttribute("userid") + "님 로그아웃함");
session.invalidate();
} else if(op.equals("signup")) {
request.setAttribute("method", "POST");
request.setAttribute("user", new Member());
actionUrl="signup.jsp";
} else if (op.equals("update")) {
user = MemberDAO.findById(userid);
request.setAttribute("user", user);
request.setAttribute("method", "PUT");
actionUrl = "signup.jsp";
}else { // 로그인도 로그아웃도 아닌 제 3의 상태가 발생했을때..
}
} catch (Exception e) {
// 일단 세션부터 닫고보자
System.out.println("뭔지 모르지만 에러발생하여 세션정리");
session.invalidate();
}
/* 주소창을 이쁘게 보이기 위한 발악... */
if(!op.equals("logout")) {
RequestDispatcher dispatcher = request.getRequestDispatcher(actionUrl);
dispatcher.forward(request, response);
} else if(op.equals("logout")) {
response.sendRedirect(actionUrl);
}
} |
c8e4e702-93c5-41fc-9143-b20ac19d6d7a | 2 | private static final double distanceBase(double[] coord1, double[] coord2, int order)
{
if (coord1.length != coord2.length)
throw new IllegalArgumentException ("Number of dimensions is not equal");
final int NUM_DIMENSIONS = coord1.length;
double distance = 0;
for (int d = 0; d < NUM_DIMENSIONS; d++) {
double absDiff = Math.abs (coord2[d] - coord1[d]);
distance += Math.pow (absDiff, order);
}
distance = Math.pow (distance, (1.0 / order));;
return distance;
} |
15846754-7996-4aea-b1a3-b7f5e3b45e15 | 3 | @Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((classMetadata == null) ? 0 : classMetadata.hashCode());
result = prime * result
+ ((fieldMetadata == null) ? 0 : fieldMetadata.hashCode());
result = prime * result
+ ((qualifiedName == null) ? 0 : qualifiedName.hashCode());
return result;
} |
540f0914-9325-4817-bafd-7d1ed440f92f | 6 | @Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
SnakePiece other = (SnakePiece) obj;
if (type != other.type)
{
return false;
}
if (x != other.x)
{
return false;
}
if (y != other.y)
{
return false;
}
return true;
} |
7abeae4a-96f1-47ae-875c-57f217bd4536 | 6 | public void actionPerformed(ActionEvent ae) {
//
// Process the action command
//
// "new" - Add a price history element
// "delete" - Delete a price history element
// "done" - All done
//
try {
String action = ae.getActionCommand();
if (action.equals("new")) {
PriceHistoryEditDialog.showDialog(this, security, tableModel);
createChartData();
chart.chartModified();
} else if (action.equals("delete")) {
int[] rows = table.getSelectedRows();
if (rows.length == 0) {
JOptionPane.showMessageDialog(this, "You must select an entry to delete",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
for (int row : rows) {
PriceHistory ph = tableModel.getEntryAt(row);
SortedSet<PriceHistory> s = security.getPriceHistory();
s.remove(ph);
}
tableModel.priceHistoryChanged();
createChartData();
chart.chartModified();
Main.dataModified = true;
}
} else if (action.equals("done")) {
setVisible(false);
dispose();
}
} catch (Exception exc) {
Main.logException("Exception while processing action event", exc);
}
} |
3da51c24-6348-4b5d-b5c6-8e2d388e8618 | 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(frmAbout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmAbout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmAbout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmAbout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmAbout().setVisible(true);
}
});
} |
661c9169-4d79-46e3-a208-696624be65ea | 9 | public void giveBonus(MOB mob, Electronics item)
{
if((mob==null)||(item==null))
return;
if((System.currentTimeMillis()-lastCastHelp)<300000)
return;
String experName;
if(CMLib.dice().rollPercentage()>50)
{
final Manufacturer m=item.getFinalManufacturer();
if(m!=null)
{
experName=m.name();
}
else
return;
}
else
{
final Technical.TechType ttype = item.getTechType();
if(ttype!=null)
{
experName=ttype.getDisplayName();
}
else
return;
}
Pair<String,Integer> expertise=mob.fetchExpertise(experName+"%");
final int currentExpertise=(expertise!=null)?expertise.second.intValue():0;
if(((int)Math.round(Math.sqrt((mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)))*34.0*Math.random()))>=currentExpertise)
{
mob.addExpertise(experName+"%"+(currentExpertise+1));
lastCastHelp=System.currentTimeMillis();
AstroEngineering A=(AstroEngineering)mob.fetchAbility(ID());
if(A!=null)
A.lastCastHelp=System.currentTimeMillis();
mob.tell(mob,null,null,L("You gain some new insights about @x1.",CMLib.english().makePlural(experName.toLowerCase())));
}
} |
0129960c-8d9e-4cc0-833f-707da6f62715 | 9 | protected boolean[] datasetIntegrity(
boolean nominalPredictor,
boolean numericPredictor,
boolean stringPredictor,
boolean datePredictor,
boolean relationalPredictor,
boolean multiInstance,
int classType,
boolean predictorMissing,
boolean classMissing) {
print("associator doesn't alter original datasets");
printAttributeSummary(
nominalPredictor, numericPredictor, stringPredictor, datePredictor, relationalPredictor, multiInstance, classType);
print("...");
int numTrain = getNumInstances(),
numClasses = 2, missingLevel = 20;
boolean[] result = new boolean[2];
Instances train = null;
Associator associator = null;
try {
train = makeTestDataset(42, numTrain,
nominalPredictor ? getNumNominal() : 0,
numericPredictor ? getNumNumeric() : 0,
stringPredictor ? getNumString() : 0,
datePredictor ? getNumDate() : 0,
relationalPredictor ? getNumRelational() : 0,
numClasses,
classType,
multiInstance);
if (missingLevel > 0)
addMissing(train, missingLevel, predictorMissing, classMissing);
associator = AbstractAssociator.makeCopies(getAssociator(), 1)[0];
} catch (Exception ex) {
throw new Error("Error setting up for tests: " + ex.getMessage());
}
try {
Instances trainCopy = new Instances(train);
associator.buildAssociations(trainCopy);
compareDatasets(train, trainCopy);
println("yes");
result[0] = true;
} catch (Exception ex) {
println("no");
result[0] = false;
if (m_Debug) {
println("\n=== Full Report ===");
print("Problem during building");
println(": " + ex.getMessage() + "\n");
println("Here is the dataset:\n");
println("=== Train Dataset ===\n"
+ train.toString() + "\n");
}
}
return result;
} |
cd2b291a-8427-4b2e-8faa-c07033134605 | 9 | private int makeRandom() {
int num = random.nextInt(6);
if (num == 1 || num == 2 || num == 3) {
num = random.nextInt(4);
if (num == 1 || num == 2 || num == 3) {
num = random.nextInt(4);
if (num == 1 || num == 2) {
num = random.nextInt(4);
if (num == 2) {
num = random.nextInt(4);
}
}
}
}
return num;
} |
ce469893-9ccd-4026-8e25-2076b67f8bf1 | 4 | @RequestMapping(method = RequestMethod.POST)
public @ResponseBody
JsonResponse uploadAction(@Valid @ModelAttribute(value = "image") Image image,
@RequestParam(value = "captcha_challenge", required=true) String challenge,
@RequestParam(value = "captcha_response", required=true) String response,
BindingResult result,
HttpServletRequest paramHttpServletRequest) {
JsonResponse jsonResponse = new JsonResponse();
String remoteAddr = paramHttpServletRequest.getRemoteAddr();
ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response);
if (!reCaptchaResponse.isValid()) {
jsonResponse.setCaptchaError(context.getMessage("error.bad.captcha", null, Locale.getDefault()));
return jsonResponse;
}
prepareImage(image);
(new ImageValidator()).validate(image, result);
if (!result.hasErrors()) {
try {
image.setBytes(image.getFile().getBytes());
image.setContentType(image.getFile().getContentType());
image = imageService.saveImage(image);
jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId());
} catch (Exception e) {
log.error(e.getMessage());
}
} else {
for (ObjectError error : result.getAllErrors()) {
jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault()));
}
}
return jsonResponse;
} |
4115d747-856a-43b2-8752-0fd16685a9ab | 7 | @Override
public long deriveMudHoursAfter(TimeClock C)
{
long numMudHours=0;
if(C.getYear()>getYear())
return -1;
else
if(C.getYear()==getYear())
{
if(C.getMonth()>getMonth())
return -1;
else
if(C.getMonth()==getMonth())
{
if(C.getDayOfMonth()>getDayOfMonth())
return -1;
else
if(C.getDayOfMonth()==getDayOfMonth())
{
if(C.getHourOfDay()>getHourOfDay())
return -1;
}
}
}
numMudHours+=(getYear()-C.getYear())*(getHoursInDay()*getDaysInMonth()*getMonthsInYear());
numMudHours+=(getMonth()-C.getMonth())*(getHoursInDay()*getDaysInMonth());
numMudHours+=(getDayOfMonth()-C.getDayOfMonth())*getHoursInDay();
numMudHours+=(getHourOfDay()-C.getHourOfDay());
return numMudHours;
} |
e1f0899b-3b43-42e9-910e-604561317fa9 | 0 | public String getAccountName() {
return accountName;
} |
b55bd8d3-95b9-4751-9146-968cb061b0d8 | 3 | public Collection<IrodsFile> listFiles() throws IrodsException {
List<IrodsFile> l = new ArrayList<IrodsFile>();
for (File f : irodsFile.listFiles()) {
if (f instanceof IRODSFile && f.isFile()) {
l.add(new JargonFile(conn, (IRODSFile) f));
}
}
return l;
} |
bbe2c181-4f48-4e90-bea2-15da8ca9ca4c | 9 | @Test
public void testVoterVote()
{
String pollId = null;
Socket socket = null;
try {
socket = connectToServer();
} catch (IOException e) {
e.printStackTrace();
}
// send a connection message indicating email address
this.writer.println(MessageFactory.getConnectMessage("[email protected]"));
// send a createPoll message
this.writer.println(MessageFactory.getCreatePollMessage(0));
// wait for validation
boolean recCreatePollReply = false;
int messagesReceived = 0;
String input = null;
try {
while(!recCreatePollReply && (input=this.reader.readLine()) != null)
{
messagesReceived++;
System.out.println("Client: Received: " + input);
Document doc = MessageFactory.stringToXmlDoc(input);
assertNotNull(doc);
if(doc != null && messagesReceived==2)
{
String messageType = doc.getDocumentElement().getNodeName();
assertEquals(messageType, "createPollReply");
recCreatePollReply = true;
pollId = doc.getElementsByTagName("pollId").item(0).getTextContent();
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
// poll is now created - attempt to vote on it
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (SocketException e1) {
e1.printStackTrace();
}
try {
sendSocket.send(getVoteDatagramPacket(MessageFactory.getVoteMessage(pollId, "a")));
} catch (IOException e1) {
e1.printStackTrace();
}
sendSocket.close();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
} |
1f89af3c-221c-4960-b2fa-d06b5d3436fa | 9 | public void actionPerformed(ActionEvent e) {
if (ModelerUtilities.stopFiring(e))
return;
Object src = e.getSource();
if (!(src instanceof ActivityButton))
return;
ActivityButton ab = (ActivityButton) src;
String pageGroup = ab.getPageNameGroup();
if (pageGroup == null)
return;
if (question()) {
if (!justPrint && Modeler.user.isEmpty()) {
String s = Modeler.getInternationalText("YouAreNotLoggedInYetPleaseTryAgain");
JOptionPane.showMessageDialog(modeler, s != null ? s : "You are not logged in yet. Please try again.",
"Message", JOptionPane.WARNING_MESSAGE);
return;
}
if (png == null)
png = new PageNameGroup();
png.setNameGroup(pageGroup);
Map map = modeler.editor.getPage().prepareReportForPageGroup(png);
if (map != null)
openReportPage(map, png);
}
} |
20bf9e17-21b7-4483-9166-8a23671634be | 8 | public void run() {
this.running = true;
while (this.alive) {
synchronized (this) {
while (this.alive && (!this.running) && (!this.reload)) {
try {
wait();
} catch (InterruptedException e) {
kill();
}
}
}
synchronized (this) {
if (this.alive && this.reload) {
this.running = true;
this.simBkg.setState(this.simCpy);
}
}
if (this.running) {
work();
}
}
} |
3659a4a6-a617-453c-884e-ff3d6a220ef3 | 8 | void selectpanel() {
if(s.gettype().endsWith("bubble")) {
modulepanel.setVisible(false);
carrowpanel.setVisible(false);
dspanel.setVisible(false);
entitypanel.setVisible(false);
bubblepanel.setVisible(true);
arrowpanel.setVisible(false);
}
else if (s.gettype().endsWith("entity")) {
modulepanel.setVisible(false);
carrowpanel.setVisible(false);
dspanel.setVisible(false);
bubblepanel.setVisible(false);
arrowpanel.setVisible(false);
entitypanel.setVisible(true);
}
else if (s.gettype().endsWith("flowarrow")) {
modulepanel.setVisible(false);
carrowpanel.setVisible(false);
dspanel.setVisible(false);
arrowpanel.setVisible(true);
bubblepanel.setVisible(false);
entitypanel.setVisible(false);
}
else if (s.gettype().endsWith("datastore")) {
modulepanel.setVisible(false);
carrowpanel.setVisible(false);
dspanel.setVisible(true);
arrowpanel.setVisible(false);
bubblepanel.setVisible(false);
entitypanel.setVisible(false);
}
else if (s.gettype().endsWith("ctrlarrow")) {
modulepanel.setVisible(false);
carrowpanel.setVisible(true);
dspanel.setVisible(false);
arrowpanel.setVisible(false);
bubblepanel.setVisible(false);
entitypanel.setVisible(false);
}
else if (s.gettype().endsWith("module")) {
modulepanel.setVisible(true);
carrowpanel.setVisible(false);
dspanel.setVisible(false);
arrowpanel.setVisible(false);
bubblepanel.setVisible(false);
entitypanel.setVisible(false);
dfd d = (dfd) Global.n.tabs.getComponentAt(0);
for(int i=0; i<d.shapes.size(); i++) {
if(d.shapes.get(i).gettype().endsWith("bubble")) {
bubbles.addItem(d.shapes.get(i).name);
}
}
}
} |
9e13545c-941a-40b7-9b8f-84cc860e5e82 | 4 | @Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof Item) {
Item i = (Item) obj;
if (! this.getCode().equals(i.getCode()))
return false;
}
return true;
} |
d80cb424-bff7-4131-98f7-a554b2e91a08 | 4 | private void setCurrentAction(Action action) {
currAction = action;
timeSpentCompletingCurrentAction = 0;
switch(action) {
case MOVE:
timeNeededToCompleteCurrentAction = timeNeededToCommitMove;
break;
case MOVE_COMMITTED:
timeNeededToCompleteCurrentAction = timeNeededToCompleteMove;
break;
case MOVE_CANCELED:
timeNeededToCompleteCurrentAction = timeNeededToCancelMove;
break;
case MOVE_CANCELED_RECOVERING:
timeNeededToCompleteCurrentAction = timeNeededToRecoverFromCanceledMove;
break;
default:
timeNeededToCompleteCurrentAction = 0;
break;
}
} |
6cac98eb-6b09-430b-b44b-bf1229bb1147 | 2 | private void checkStmt() throws SQLException {
if(this.stmt == null || this.stmt.isClosed())
throw new SQLException("Statement not ready.");
} |
a3277c29-eece-474f-a1c3-46be8f2dd91e | 4 | public JLabel getPlayer2Name() {
boolean test = false;
if (test || m_test) {
System.out.println("Drawing :: getPlayer2Name() BEGIN");
}
if (test || m_test)
System.out.println("Drawing:: getPlayer2Name() - END");
return m_player2Name;
} |
9d22585a-3d35-4387-a66d-13e9e1aa02db | 8 | @Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
if((mob==null)||(mob.playerStats()==null))
return false;
if(commands.size()<2)
{
final String pageBreak=(mob.playerStats().getPageBreak()!=0)?(""+mob.playerStats().getPageBreak()):"Disabled";
mob.tell(L("Change your page break to what? Your current page break setting is: @x1. Enter a number larger than 0 or 'disable'.",pageBreak));
return false;
}
final String newBreak=CMParms.combine(commands,1);
int newVal=mob.playerStats().getWrap();
if((CMath.isInteger(newBreak))&&(CMath.s_int(newBreak)>0))
newVal=CMath.s_int(newBreak);
else
if("DISABLED".startsWith(newBreak.toUpperCase()))
newVal=0;
else
{
mob.tell(L("'@x1' is not a valid setting. Enter a number larger than 0 or 'disable'.",newBreak));
return false;
}
mob.playerStats().setPageBreak(newVal);
final String pageBreak=(mob.playerStats().getPageBreak()!=0)?(""+mob.playerStats().getPageBreak()):"Disabled";
mob.tell(L("Your new page break setting is: @x1.",pageBreak));
return false;
} |
32178c75-5c79-4dc5-813c-e6cf0ec7a955 | 3 | @Override
public void updateLong() {
super.updateLong();
if(generationTimerEnd == 0) {
resetGenerationTimer();
}
if(generationTimerEnd <= System.currentTimeMillis() && this.isActivated()) {
placeableManager.playerAddItem("Stone", 1);
registry.getIndicatorManager().createImageIndicator(mapX + (width / 2), mapY + height + 32, "Stone");
registry.showMessage("Success", type + " has generated Stone");
resetGenerationTimer();
}
} |
b0fa9c9f-1b60-401f-bbec-34dc01d77922 | 6 | @Override
public void insertUpdate(DocumentEvent e) {
boolean haveNotEncounteredInvis = true;
char lastChar;
String fieldText = null;
Document doc = (Document)e.getDocument();
try {
fieldText =doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
if(fieldText.length() > 1){
lastChar = fieldText.charAt(fieldText.length() - 1);
if(lastChar == '\n'){
int x = fieldText.length()-2;
String enteredText = "";
char currentChar;
while(haveNotEncounteredInvis){
currentChar = fieldText.charAt(x);
if(currentChar == '\n' ){
setEnteredText(enteredText);
haveNotEncounteredInvis = false;
display.setCaretPosition(display.getDocument().getLength());
}
else if(x == 0){
enteredText = currentChar + enteredText;
setEnteredText(enteredText);
haveNotEncounteredInvis = false;
}
else{
enteredText = currentChar + enteredText;
}
x--;
}
}
}
} |
a2679f0f-e546-4500-845c-9dd8b02dfefc | 8 | public void checkPurchase()
{
if(BackerGS.storeVisible)
{
if(CurrencyCounter.currencyCollected < 150)
{
if(Greenfoot.mouseClicked(this))
{
NotEnoughMoney.fade = 200;
boop.play();
}
}
}
if(CurrencyCounter.currencyCollected >= 150)
{
if(PowerUps1.powerUp1 != 0)
{
if(Greenfoot.mouseClicked(this))
{
YouAlreadyHaveThisPotion.yfade = 200;
boop.play();
}
}
if(PowerUps1.powerUp1 == 0)
{
if(Greenfoot.mouseClicked(this))
{
chaChing.play();
CurrencyCounter.currencyCollected = CurrencyCounter.currencyCollected - 150;
PowerUps1.powerUp1 = 3;
}
}
}
} |
4c2f4aa9-3b35-4d12-b922-f65c6988f350 | 1 | public Deck getExpiredDeck()
{
if(crdsToRemove.size() == 0){return null;}
return new Deck(crdsToRemove);
} |
8009cffc-1e39-4b3d-86f8-9c04b2acec99 | 3 | public void initializeDataBase(JList<String> log){
ArrayList<String> alstLog = new ArrayList<>();
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String url = "jdbc:derby:" + DBName + ";create=true";
alstLog.add("Connecting...");
log.setListData(alstLog.toArray(new String[0]));
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
// ###CREATING TABLE USERS###
alstLog.add("Creating Table users...");
log.setListData(alstLog.toArray(new String[0]));
String createUsers = "CREATE TABLE users ("
+ "uid INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "Juser VARCHAR(24) NOT NULL,"
+ "Jpassword VARCHAR(100) NOT NULL,"
+ "Jnick VARCHAR(24),"
+ "level INTEGER DEFAULT 1,"
+ "currentExp INTEGER DEFAULT 0,"
+ "rCoins INTEGER DEFAULT 0,"
+ "vCoins INTEGER DEFAULT 0,"
+ "points INTEGER DEFAULT 0,"
+ "JlastLoggin TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
statement.executeUpdate(createUsers);
alstLog.add("Table users created");
log.setListData(alstLog.toArray(new String[0]));
// INSERT INTO USERS(JUSER, JPASSWORD) VALUES ('root', 'root')
// ###CREATING TABLE USERUSERRELATIONSHIPTYPES###
alstLog.add("Creating Table UserUserRelationshipTypes...");
log.setListData(alstLog.toArray(new String[0]));
String createUserUserRelationshipTypes = "CREATE TABLE UserUserRelationshipTypes ("
+ "uurtid INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "rtype VARCHAR(255))";
statement.executeUpdate(createUserUserRelationshipTypes);
alstLog.add("Table UserUserRelationshipTypes created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE USERUSERRELATIONSHIPTYPES###
alstLog.add("Filling Table UserUserRelationshipTypes...");
log.setListData(alstLog.toArray(new String[0]));
String insertRelationshipTypeFriends = "INSERT INTO UserUserRelationshipTypes (rtype) VALUES ('friends')";
statement.execute(insertRelationshipTypeFriends);
String insertRelationshipTypeBlocked = "INSERT INTO UserUserRelationshipTypes (rtype) VALUES ('blocked')";
statement.execute(insertRelationshipTypeBlocked);
String insertRelationshipTypeRequested = "INSERT INTO UserUserRelationshipTypes (rtype) VALUES ('requested')";
statement.execute(insertRelationshipTypeRequested);
alstLog.add("Table UserUserRelationshipTypes filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE USERUSERRELATIONSHIPS###
alstLog.add("Creating Table UserUserRelationships...");
log.setListData(alstLog.toArray(new String[0]));
String createUserUserRelationships = "CREATE TABLE UserUserRelationships ("
+ "urID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "initialUserID INTEGER REFERENCES USERS (uid),"
+ "destinationUserID INTEGER REFERENCES USERS (uid),"
+ "userUserRelationshipTypesID INTEGER REFERENCES USERUSERRELATIONSHIPTYPES (uurtid))";
statement.executeUpdate(createUserUserRelationships);
alstLog.add("Table UserUserRelationships created");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE CHATCHANNELTYPES###
alstLog.add("Creating Table chatChannelTypes...");
log.setListData(alstLog.toArray(new String[0]));
String createChatChannelTypes = "CREATE TABLE chatChannelTypes("
+ "cctID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
+ "cctype VARCHAR(255))";
statement.executeUpdate(createChatChannelTypes);
alstLog.add("Table chatChannelTypes created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE CHATCHANNELTYPES###
alstLog.add("Filling Table chatChannelTypes");
log.setListData(alstLog.toArray(new String[0]));
String insertChatChannelTypePrivate = "INSERT INTO CHATCHANNELTYPES (cctype) VALUES ('private')";
statement.execute(insertChatChannelTypePrivate);
String insertChatChannelTypePermanent = "INSERT INTO CHATCHANNELTYPES (cctype) VALUES ('permanent')";
statement.execute(insertChatChannelTypePermanent);
String insertChatChannelTypeCustom = "INSERT INTO CHATCHANNELTYPES (cctype) VALUES ('custom')";
statement.execute(insertChatChannelTypeCustom);
alstLog.add("Table chatChannelTypes filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE CHATCHANNELS###
alstLog.add("Creating Table chatChannels...");
log.setListData(alstLog.toArray(new String[0]));
String createChatChannels = "CREATE TABLE chatChannels ("
+ "channelID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
+ "channelType INTEGER REFERENCES CHATCHANNELTYPES(cctID),"
+ "channelName VARCHAR(100))";
statement.executeUpdate(createChatChannels);
alstLog.add("Table chatChannels created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE CHATCHANNELS
alstLog.add("Filling Table chatChannels...");
log.setListData(alstLog.toArray(new String[0]));
String insertChatChannelsHelp = "INSERT INTO CHATCHANNELS (channelType, channelName)" +
"VALUES ((SELECT cctid FROM chatChannelTypes where cctype = 'permanent'), 'Help')";
statement.executeUpdate(insertChatChannelsHelp);
String insertChatChannelsJGame_DEU_1 = "INSERT INTO CHATCHANNELS (channelType, channelName)" +
"VALUES ((SELECT cctid FROM chatChannelTypes where cctype = 'permanent'), 'JGame DEU-1')";
statement.executeUpdate(insertChatChannelsJGame_DEU_1);
alstLog.add("Table chatChannels filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE USERCHANNELRELATIONSHIPTYPES###
alstLog.add("Creating Table userChannelRelationshiptypes...");
log.setListData(alstLog.toArray(new String[0]));
String createUserChannelRelationshiptypes = "CREATE TABLE userChannelRelationshiptypes ("
+ "ucrtID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "rtype VARCHAR(255))";
statement.executeUpdate(createUserChannelRelationshiptypes);
alstLog.add("Table userChannelRelationshiptypes created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE USERCHANNELRELATIONSHIPTYPES###
alstLog.add("Filling Table userChannelRelationshiptypes...");
log.setListData(alstLog.toArray(new String[0]));
String insertRelationshipTypeOnline = "INSERT INTO userChannelRelationshiptypes (rtype) VALUES ('online')";
statement.execute(insertRelationshipTypeOnline);
String insertRelationshipTypeOffline = "INSERT INTO userChannelRelationshiptypes (rtype) VALUES ('offline')";
statement.execute(insertRelationshipTypeOffline);
String insertRelationshipTypeMuted = "INSERT INTO userChannelRelationshiptypes (rtype) VALUES ('muted')";
statement.execute(insertRelationshipTypeMuted);
alstLog.add("Table userChannelRelationshiptypes filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE USERCHATRELATIONS###
alstLog.add("Creating Table userChatRelations...");
log.setListData(alstLog.toArray(new String[0]));
String createUserChatRelations = "CREATE TABLE userChatRelations ("
+ "ucrID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "userID INTEGER REFERENCES USERS (uID),"
+ "channelID INTEGER REFERENCES CHATCHANNELS (channelID),"
+ "relationshipType INTEGER REFERENCES USERCHANNELRELATIONSHIPTYPES (ucrtID))";
statement.executeUpdate(createUserChatRelations);
alstLog.add("Table userChatRelations created");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE CHATMESSAGES###
alstLog.add("Creating Table chatMessages...");
log.setListData(alstLog.toArray(new String[0]));
String createChatMessages = "CREATE TABLE chatmessages ("
+ "messageid INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "user_uid INTEGER REFERENCES USERS (uid),"
+ "channel_cid INTEGER REFERENCES CHATCHANNELS (channelID),"
+ "message VARCHAR(100),"
+ "messagedate TIMESTAMP)";
statement.executeUpdate(createChatMessages);
alstLog.add("Table chatMessages created");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE PLAYMODES###
alstLog.add("Creating Table playmodes...");
log.setListData(alstLog.toArray(new String[0]));
String createPlaymodes = "CREATE TABLE playmodes ("
+ "pmid INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "titel VARCHAR(25),"
+ "desctext VARCHAR(255),"
+ "available boolean)";
statement.executeUpdate(createPlaymodes);
alstLog.add("Table playmodes created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE PLAYMODES###
alstLog.add("Filling Table playmodes...");
log.setListData(alstLog.toArray(new String[0]));
String insertPlaymodesFFA = "INSERT INTO playmodes (titel, desctext, available) VALUES ('FFA', 'Free for all - Up to 8 players fight against each other', true)";
statement.execute(insertPlaymodesFFA);
String insertPlaymodesTEAM = "INSERT INTO playmodes (titel, desctext, available) VALUES ('TEAM', 'Team vs Team - Two teams fight against each other', true)";
statement.execute(insertPlaymodesTEAM);
String insertPlaymodesUNDERDOG = "INSERT INTO playmodes (titel, desctext, available) VALUES ('UNDERDOG', 'The Underdog Challange - A single player competes against a group of player', true)";
statement.execute(insertPlaymodesUNDERDOG);
alstLog.add("Table playmodes filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE PLAYMODETEAMS###
alstLog.add("Creating Table playmodeTeams...");
log.setListData(alstLog.toArray(new String[0]));
String playmodeTeams = "CREATE TABLE playmodeteams ("
+ "pmtID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "pmID INTEGER REFERENCES PLAYMODES (pmID),"
+ "size INTEGER)";
statement.executeUpdate(playmodeTeams);
alstLog.add("Table playmodeTeams created");
log.setListData(alstLog.toArray(new String[0]));
// ###FILLING TABLE PLAYMODETEAMS###
alstLog.add("Filling Table playmodeTeams...");
log.setListData(alstLog.toArray(new String[0]));
for (int i = 0; i < 8; i++) {
String insertPlaymodeTeamsFFA = "INSERT INTO playmodeteams (pmid, size) VALUES ((SELECT pmid FROM playmodes WHERE titel = 'FFA'), 1)";
statement.execute(insertPlaymodeTeamsFFA);
}
for (int i = 0; i < 2; i++) {
String insertPlaymodeTeamsTEAM = "INSERT INTO playmodeteams (pmid, size) VALUES ((SELECT pmid FROM playmodes WHERE titel = 'TEAM'), 3)";
statement.execute(insertPlaymodeTeamsTEAM);
}
String insertPlaymodeTeamsUNDERDOGTeam = "INSERT INTO playmodeteams (pmid, size) VALUES ((SELECT pmid FROM playmodes WHERE titel = 'UNDERDOG'), 3)";
statement.execute(insertPlaymodeTeamsUNDERDOGTeam);
String insertPlaymodeTeamsUNDERDOGSolo = "INSERT INTO playmodeteams (pmid, size) VALUES ((SELECT pmid FROM playmodes WHERE titel = 'UNDERDOG'), 1)";
statement.execute(insertPlaymodeTeamsUNDERDOGSolo);
alstLog.add("Table playmodeTeams filled");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE GAMES###
alstLog.add("Creating Table games...");
log.setListData(alstLog.toArray(new String[0]));
String createGames = "CREATE TABLE games ("
+ "gid INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "pmID INTEGER REFERENCES PLAYMODES (pmID),"
+ "winner INTEGER REFERENCES PLAYMODETEAMS (pmtID),"
+ "gamestart TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
statement.executeUpdate(createGames);
alstLog.add("Table games created");
log.setListData(alstLog.toArray(new String[0]));
// ###CREATING TABLE GAMERUSERLRATIONSHIPS###
alstLog.add("Creating gameUserRelationships games...");
log.setListData(alstLog.toArray(new String[0]));
String createGameUserRelationships = "CREATE TABLE gameUserRelationships ("
+ "gurID INTEGER NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, "
+ "gID INTEGER REFERENCES GAMES (gID),"
+ "uID INTEGER REFERENCES USERS (uID),"
+ "team INTEGER)";
statement.executeUpdate(createGameUserRelationships);
alstLog.add("Table gameUserRelationships created");
log.setListData(alstLog.toArray(new String[0]));
statement.close();
connection.close();
alstLog.add("Connection closed");
log.setListData(alstLog.toArray(new String[0]));
} catch (Exception e) {
new ServerResultFrame(e.getMessage());
}
} |
5d3cbcd1-8e6f-4c60-a666-655971738ab6 | 0 | public boolean isEmpty() {
return heap.isEmpty();
} |
312e1185-3706-4d47-baa3-18366ba2ca2b | 7 | Class163(int i, int i_27_) {
if ((i_27_ ^ 0xffffffff) != (i ^ 0xffffffff)) {
int i_28_ = Class348_Sub1_Sub1.method2726(-21806, i, i_27_);
i /= i_28_;
i_27_ /= i_28_;
anIntArrayArray2163 = new int[i][14];
anInt2159 = i_27_;
anInt2164 = i;
for (int i_29_ = 0; (i ^ 0xffffffff) < (i_29_ ^ 0xffffffff);
i_29_++) {
int[] is = anIntArrayArray2163[i_29_];
double d = (double) i_29_ / (double) i + 6.0;
int i_30_ = (int) Math.floor(1.0 + (-7.0 + d));
if ((i_30_ ^ 0xffffffff) > -1)
i_30_ = 0;
int i_31_ = (int) Math.ceil(d + 7.0);
if ((i_31_ ^ 0xffffffff) < -15)
i_31_ = 14;
double d_32_ = (double) i_27_ / (double) i;
for (/**/; (i_31_ ^ 0xffffffff) < (i_30_ ^ 0xffffffff);
i_30_++) {
double d_33_ = 3.141592653589793 * (-d + (double) i_30_);
double d_34_ = d_32_;
if (d_33_ < -1.0E-4 || d_33_ > 1.0E-4)
d_34_ *= Math.sin(d_33_) / d_33_;
d_34_
*= (Math.cos(0.2243994752564138 * ((double) i_30_ - d))
* 0.46) + 0.54;
is[i_30_] = (int) Math.floor(0.5 + d_34_ * 65536.0);
}
}
}
} |
8a47c65c-303f-4785-bd7c-66c4cb8d9563 | 2 | private MouseListener mouseListener(){
return new MouseAdapter(){
@Override
public void mousePressed( MouseEvent e ) {
mousePressedPoint = e.getPoint();
}
@Override
public void mouseReleased( MouseEvent e ) {
if( moving ){
for( MoveableCapability item : items ){
item.endMoveAt( e.getX(), e.getY() );
}
}
items.clear();
mousePressedPoint = null;
moving = false;
site.listening();
}
};
} |
8f957779-8aa6-465a-8abb-3095373dedbe | 3 | private static boolean isPrime(int n) {
boolean result = true; // assume true and try to prove otherwise
int i=2;
while ((i<n) && (result == true)) {
if ((n%i) == 0) {
result = false;
}
i++;
}
return result;
} |
13bb5227-bc8a-4194-9902-9ae7c1397446 | 5 | private void consumeFutureUninterruptible( Future<?> f ) {
try {
boolean interrupted = false;
while ( true ) {
try {
f.get();
break;
} catch ( InterruptedException e ) {
interrupted = true;
}
}
if( interrupted )
Thread.currentThread().interrupt();
} catch ( ExecutionException e ) {
throw new RuntimeException( e );
}
} |
7b969241-c8ab-4a13-9099-4e434c4ddb83 | 2 | void readCdsFile() {
cdsByTrId = new HashMap<String, String>();
if (cdsFile.endsWith("txt") || cdsFile.endsWith("txt.gz")) readCdsFileTxt();
else readCdsFileFasta();
} |
71a4e3b8-3f82-4f67-8a4d-55e7f6e664d8 | 7 | public Board makeBoard() throws InterruptedException {
int x = -1, y = -1;
topLeft:
for(int h = 50; h < Img.getHeight(); h++){
for(int w= 50; w < Img.getWidth(); w++){
int c = Img.getRGB(w, h);
if(w < 50 || h < 50 || w > Img.getWidth()-50 || h > Img.getHeight()-50) //Ignore Bottom and Top
continue;
if(isTopLeft(c)) {
x = w;
y = h+20;
break topLeft;
}
}
}
cellSize = getCellSize(x, y); //Save Cell size to calculate Move
return new Board(getWidth(x, y)/cellSize, getHeight(x, y)/cellSize, cellSize, this);
} |
65ab4308-e475-4f59-bf5c-8fbdfd051dd8 | 8 | public LineScore alphabeta_max(int currentDepth, int alpha, int beta, Tuple lastMove) {
if (currentDepth >= depth || board.legalMoves.isEmpty()) {
System.out.println("Board state before eval return:\n" + board);
int eval = board.eval(weights);
evals++;
System.out.println("Returning eval: " + eval + " at max.");
if (eval < -1000000 || eval > 1000000)
System.out.println("WIN DETECTED FOR MIN!");
return new LineScore("", eval);
}
Tuple bestMove=null;
String lineTrace=null;
LineScore lS=null;
int a = infHolder.MIN - 1;
LinkedList<Tuple> list = (LinkedList<Tuple>) board.legalMoves.clone();
for (Tuple chosenMove : list) {
board.move(chosenMove);
System.out.println("Now searching move " + chosenMove + ", a=" + alpha + ", b=" + beta + " max");
lS = alphabeta_min(currentDepth+1, alpha, beta, chosenMove.clone());
if (a < lS.score) {
bestMove = chosenMove;
lineTrace = lS.line;
}
a = max(a, lS.score);
if (a >= beta) {
System.out.println("Move " + chosenMove + " better than beta of " + beta + " (" + a + ")");
MoveRecord oldMove = board.takeBack(1);
System.out.println("Took back " + oldMove.move + " at depth " + currentDepth);
return new LineScore(chosenMove + ", " + lS.line, beta);
}
if (a > alpha) {
System.out.println("Move " + chosenMove + " sets alpha to " + a + " (alpha was " + alpha + ")");
alpha = a;
}
MoveRecord oldMove = board.takeBack(1);
System.out.println("Took back " + oldMove.move + " at depth " + currentDepth);
}
return new LineScore(bestMove + ", " + lineTrace, a);
} |
d1ea0757-8a7e-4bfe-a110-39ef31a8bd0c | 4 | public void writeHops() {
// Name,Alpha,Cost,Stock,Units,Descr,Storage,Date,Modified
Debug.print("Write Hops to DB");
try {
PreparedStatement pStatement = conn.prepareStatement("SELECT COUNT(*) FROM hops WHERE name = ?;");
PreparedStatement rStatement = conn.prepareStatement("SELECT COUNT(*) FROM hops WHERE name = ?" +
" AND Alpha=? AND Cost=? AND Stock=? AND " +
"Units=? AND Descr=? AND Storage=? AND Type = ?;");
String sql = "insert into hops (Name,Alpha,Cost,Stock,Units,Descr,Storage,Date, Type) " +
"values(?, ?, ? , ?, ?, ?, ?, ?, ? )";
PreparedStatement insertMisc = conn.prepareStatement(sql);
sql = "UPDATE hops SET Alpha=?,Cost=?,Stock=?," +
"Units=?,Descr=?,Storage=?,Date=?,Type=? " +
"WHERE name = ?";
PreparedStatement updateMisc = conn.prepareStatement(sql);
ResultSet res = null;
int i = 0;
//Sort the list
Collections.sort(hopsDB);
while (i < hopsDB.size()) {
Hop h = hopsDB.get(i);
i++;
pStatement.setString(1, h.getName());
res = pStatement.executeQuery();
res.next();
// Does this hop exist?
if(res.getInt(1) == 0){
insertMisc.setString(1, h.getName());
insertMisc.setString(2, Double.toString(h.getAlpha()));
insertMisc.setString(3, Double.toString(h.getCostPerU()));
insertMisc.setString(4, Double.toString(h.getStock()));
insertMisc.setString(5, h.getUnitsAbrv());
insertMisc.setString(6, h.getDescription());
insertMisc.setString(7, Double.toString(h.getStorage()));
insertMisc.setString(8, h.getDate().toString());
insertMisc.setString(9, h.getType());
insertMisc.executeUpdate();
} else { // check to see if we need to update this hop
rStatement.setString(1, h.getName());
rStatement.setString(2, Double.toString(h.getAlpha()));
rStatement.setString(3, Double.toString(h.getCostPerU()));
rStatement.setString(4, Double.toString(h.getStock()));
rStatement.setString(5, h.getUnitsAbrv());
rStatement.setString(6, h.getDescription());
rStatement.setString(7, Double.toString(h.getStorage()));
rStatement.setString(8, h.getType());
System.out.println(h.getName() + " - " + h.getType());
res = rStatement.executeQuery();
res.next();
if(res.getInt(1) == 0) {
// update required
updateMisc.setString(1, Double.toString(h.getAlpha()));
updateMisc.setString(2, Double.toString(h.getCostPerU()));
updateMisc.setString(3, Double.toString(h.getStock()));
updateMisc.setString(4, h.getUnitsAbrv());
updateMisc.setString(5, h.getDescription());
updateMisc.setString(6, Double.toString(h.getStorage()));
updateMisc.setString(7, h.getDate().toString());
updateMisc.setString(8, h.getType());
// where
updateMisc.setString(9, h.getName());
System.out.println(updateMisc.toString());
updateMisc.executeUpdate();
}
}
}
//clear the list
hopsDB = new ArrayList<Hop>();
stockHopsDB = new ArrayList<Hop>();
readHops(dbPath);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
342fc1fa-6ca1-4bd4-93d8-9b8f1de2b7d9 | 0 | public CheckResultMessage check16(int day) {
return checkReport.check16(day);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.