method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
8ed5858e-96f0-4c44-95a0-69886b3924c1
| 9
|
public SegmentGroup joinSplines() {
long startTime = System.currentTimeMillis();
System.out.println("Sorting and joining Splines...");
SegmentGroup s = new SegmentGroup();
recalculateAllSplines(splines, sGroups, HIGH_RES);
printl(currentID + " curr Id");
for (int i = 0; i < currentID; i++) {
//loops once per each spline.
boolean isGroup = false;
Spline spline = null;
SplineGroup sGroup = null;
for (int j = 0; j < currentID; j++) {
try {
if (splines.get(j).splineID() == i) {
isGroup = false;
spline = splines.get(j);
printl(j + " j");
}
} catch (IndexOutOfBoundsException e) {
}
//if the desired spline is a spline.
try {
if (sGroups.get(j).splineID() == i) {
isGroup = true;
sGroup = sGroups.get(j);
}
} catch (IndexOutOfBoundsException e) {
}
}
if (isGroup) {
ArrayList<Segment> p = sGroup.getSegments().s;
for (int k = 0; k < sGroup.getSegments().s.size(); k++) {
Segment seg = new Segment();
seg.x = p.get(k).x;
seg.y = p.get(k).y;
s.add(seg);
}
} else {
ArrayList<Segment> p = spline.getSegments().s;
System.out.println(spline.getSegments().s.size());
// for (int l = 0; l < spline.getSegments().s.size(); l++) {
//// Segment seg = new Segment();
//// seg.x = p.get(l).x;
//// seg.y = p.get(l).y;
//// s.add(seg);
//// //System.out.println("t");
//// //System.out.println(spline.getSegments().s.size() + " size");
// }
for(int turd = p.size()-1; turd > -1; turd--){
Segment seg = new Segment();
seg.x = p.get(turd).x;
seg.y = p.get(turd).y;
s.add(seg);
}
}
}
System.out.println("Done! In " + (System.currentTimeMillis()-startTime) + " ms.");
return s;
}
|
25e6fd2d-cd12-4592-93a5-5b8e13c6c9f5
| 8
|
public void getInput(Circuit c, boolean is_alice, BufferedReader br) {
String inpline = null;
// Scan through all format objects
for (int i = 0; i < FMT.size(); i++) {
IO io = FMT.elementAt(i);
logger.debug("pulled element from FMT");
// Verify it's an input object of the approriate player (i.e., Alice/Bob).
if ((!io.isInput()) || (is_alice != io.isAlice())) {
continue;
}
System.out.print(io.getPrefix());
System.out.flush();
try {
inpline = br.readLine();
} catch (Exception e) {
logger.error("Formatter: readLine exception " + e.getMessage());
return;
}
StringTokenizer st = new StringTokenizer(inpline);
BigInteger val = BigInteger.ZERO;
String intTokenStr = st.nextToken();
try {
val = MyUtil.parseBigInteger(intTokenStr);
}
catch(NumberFormatException e) {
logger.error("Formatter: " + (is_alice ? "Alice" : "Bob") +
"'s input is not a well formatted integer number: " + intTokenStr);
logger.error("\n" + e.getMessage());
logger.error("\n" + e.getStackTrace());
}
logger.debug("input is: " + val);
// set all specified input bits, one by one
for (int j = 0; j < io.getNLines(); j++) {
// this is the j'th bit value
int b = val.testBit(j) ? 1 : 0;
// this bit should store as input at line_num
int line_num = io.getLinenum(j);
// this is the gate of line_num
Gate g = c.getGate(line_num);
g.setValue(b); // set the input value
logger.debug("input bit " + j + " is: " + b);
}
}
}
|
781ae23f-107c-40d5-befe-8434cba5e470
| 8
|
public void additionalDisplayCombo_actionPerformed (ActionEvent e) {
int selectedIndex = additionalDisplayCombo.getSelectedIndex();
switch (selectedIndex) {
case HackController.SCRIPT_ADDITIONAL_DISPLAY:
if (!scriptMenuItem.isSelected())
scriptMenuItem.setSelected(true);
break;
case HackController.OUTPUT_ADDITIONAL_DISPLAY:
if (!outputMenuItem.isSelected())
outputMenuItem.setSelected(true);
break;
case HackController.COMPARISON_ADDITIONAL_DISPLAY:
if (!compareMenuItem.isSelected())
compareMenuItem.setSelected(true);
break;
case HackController.NO_ADDITIONAL_DISPLAY:
if (!noAdditionalDisplayMenuItem.isSelected())
noAdditionalDisplayMenuItem.setSelected(true);
break;
}
notifyControllerListeners(ControllerEvent.ADDITIONAL_DISPLAY_CHANGE, new Integer(selectedIndex));
}
|
770a2540-2c3d-41fb-86df-8970e76a18cc
| 0
|
public void setPreference(Preference pref) {
this.pref = pref;
}
|
fd109350-5b0e-44b2-b98e-c19c8860fcbf
| 0
|
public int getWidth() {
return width;
}
|
64ee1a04-b400-42cf-b40b-a94b695f5ec8
| 6
|
MatrixFileReader(String fileName) throws IOException {
int ii, jj;
Scanner in = new Scanner(new FileReader(fileName));
if (!in.hasNextInt()) {
in.close();
throw new IOException("Cannot read matrix file.");
}
rows = in.nextInt();
if (!in.hasNextInt()) {
in.close();
throw new IOException("Cannot read matrix file.");
}
cols = in.nextInt();
data = new float[rows][cols];
jj = ii = 0;
while (in.hasNextFloat()) {
float val;
val = in.nextFloat();
data[ii][jj] = val;
jj++;
if (jj == cols) {
jj = 0;
ii++;
}
if (ii == rows && jj == cols) {
break ;
}
}
in.close();
}
|
a338aa30-7906-42ce-b0b4-3b7ea1080226
| 6
|
public int getIndexMin(int start, int end) {
if (this.start == start && this.end == end)
return minIndexVal;
int mid = (this.start + this.end) / 2;
if (mid >= start && mid >= end)
return left.getIndexMin(start, end);
if (mid < start && mid < end)
return right.getIndexMin(start, end);
return minIndexVal(left.getIndexMin(start, mid), right.getIndexMin(mid + 1, end));
}
|
7f4b8593-2b3d-4909-a65d-88574f0993b0
| 0
|
public double mean()
{
//**************************
return this.mean;
//**************************
}
|
fa54ebe7-2c8c-488f-8399-848d66ff40df
| 2
|
private void startFood(){
synchronized(envi.lock_food){
int count = 0;
while(count < 15){
envi.addFood();
food_count++;
count++;
if(food_count == food_needed){
break;
}
}
}
}
|
a17fab4d-4f22-49ba-a8ed-8226aa7dd66f
| 8
|
private int nextCharToProcess() throws IOException, LexerException {
int ich;
if (nextich >= 0) {
ich = nextich;
nextich = -1;
}
else
ich = this.reader.read();
for (; ich != -1; ich = this.reader.read()) {
char ch = (char)ich;
if (Character.isSpaceChar(ch) || Character.isISOControl(ch))
continue;
if (ch == CommentDelimeter) {
for (ich = this.reader.read(); ich != -1 && (char)ich != CommentDelimeter; ich = this.reader.read())
;
if (ich == -1)
throw new LexerException("Unclosed comment");
}
else
return ich;
}
return ich;
}
|
b86168c2-b34f-41ab-a5d4-e32d17e736ef
| 1
|
public static void restoreDefaults() {
for (Entry<String, Fonts> entry : DEFAULTS.entrySet()) {
UIManager.put(entry.getKey(), entry.getValue().mDefaultFont);
}
}
|
8b689335-3609-45b3-a1ed-f0283bea174b
| 9
|
protected double[] computeOptimalPositions(double omega, double[] x_0,
double[] v_p, double[] u_p) {
// -------- initialize all vectors --------
double[] x = x_0;
double[] v = new double[unplacedNets.size()];
double[] u = new double[unplacedNets.size()];
// iterate over nets
for (int l = 0; l < unplacedNets.size(); l++) {
double linearSum = 0;
double quadraticSum = 0;
// iterate over connected instances
for (int i : instancesAtNet.get(l)) {
double x_element = x[i];
linearSum += x_element;
quadraticSum += x_element * x_element;
}
// add constant part of vectors
v[l] = linearSum + v_p[l];
u[l] = quadraticSum + u_p[l];
}
// -------- find optimal x with successive over-relaxation --------
double MAX_ERROR = 1e-6;
double maxMoved; // the highest moved distance of the instances per run
double[] x_last; // the last value of the x vector
double[] xc = new double[unplacedNets.size()]; // the centers of the
// nets
double[] s_inv = new double[unplacedNets.size()]; // the inverted star+
// sizes of the nets
int nrIterations = 0; // to count the number of iterations needed
do {
// save the last step of x
x_last = x;
x = new double[unplacedInstances.size()];
maxMoved = 0;
// iterate over nets
for (int l = 0; l < unplacedNets.size(); l++) {
// calculate the centers of the nets
xc[l] = v[l] / k[l];
// calculate the star+ sizes of the nets
s_inv[l] = 1.0 / Math.sqrt(u[l] - k[l] * xc[l] * xc[l] + 1.0);
}
// iterate over instances
for (int j = 0; j < unplacedInstances.size(); j++) {
double numeratorSum = 0;
double denominatorSum = 0;
// iterate over nets connected to this instance
for (int l : netsAtInstance.get(j)) {
numeratorSum += xc[l] * s_inv[l];
denominatorSum += s_inv[l];
}
// calculate next x values
x[j] = (1.0 - omega) * x_last[j] + omega * numeratorSum
/ denominatorSum;
// calculate differences to old values
double linearDifference = x[j] - x_last[j];
double quadraticDifference = x[j] * x[j] - x_last[j]
* x_last[j];
// iterate over nets connected to this instance to update v and
// u
for (int l : netsAtInstance.get(j)) {
v[l] = v[l] + linearDifference;
u[l] = u[l] + quadraticDifference;
}
// update how far the distance moved
if (linearDifference < 0)
linearDifference = -linearDifference;
if (linearDifference > maxMoved)
maxMoved = linearDifference;
}
// increment counter
nrIterations++;
} while (maxMoved > MAX_ERROR); // stop when no instance has moved more
// than MAX_ERROR
// print number of iterations
MessageGenerator.briefMessage("Number of iterations for solving equations: " + nrIterations);
return x;
}
|
34b3fd95-a484-44c4-a44b-bb9012ed96b1
| 9
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> errors = new HashMap<String, String>();
UserValidation uservalidate = new UserValidation();
User user;
String addressName = request.getParameter("details");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
String state = request.getParameter("statename");
String country = request.getParameter("countryname");
String creditcard = request.getParameter("creditcard");
String postcode = request.getParameter("postcode");
boolean first_Nameresult = uservalidate.validateName(firstname);
boolean last_Nameresult = uservalidate.validateName(lastname);
boolean address_result = uservalidate.validateAddress(addressName);
boolean email_result = uservalidate.validateEmail(email);
boolean state_result = uservalidate.validateState(state);
boolean country_result = uservalidate.validateCountry(country);
boolean postcode_result = uservalidate.validatePost(postcode);
boolean credit_result = uservalidate.validateCredit(creditcard);
if (first_Nameresult)
{
errors.put("fNameError", "Please enter the your first name");
}
if (last_Nameresult){
errors.put("lnameError", "Enter Last name with first letter uppercase");
}
if (email_result){
errors.put("emailError", "Enter email address eg:example@server.com");
}
if(address_result)
errors.put("addressError", "Enter valid address eg: 12 Lane Street");
if(state_result)
errors.put("stateError", "Enter state name");
if(country_result)
errors.put("countryError", "Enter country name");
if(postcode_result)
errors.put("postError", "Enter valid postcode in numbers");
if(credit_result)
errors.put("creditError", "Enter valid credit card in numbers");
if (errors.isEmpty()) {
user = new User("", firstname, lastname, email, addressName, state, country, postcode, creditcard);
HttpSession session = request.getSession();
session.setAttribute("uservalue", user);
request.getRequestDispatcher("confirmpage.jsp").forward(request, response);
} else {
request.setAttribute("errors", errors);
request.getRequestDispatcher("userPage.jsp").forward(request, response);
}
}
|
65989867-9b03-4cf9-9df0-e0f023d6a033
| 5
|
protected void mapChildrenValues(Map<String, Object> output, ConfigurationSection section, boolean deep) {
if (section instanceof MemorySection) {
MemorySection sec = (MemorySection) section;
for (Map.Entry<String, Object> entry : sec.map.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
if (entry.getValue() instanceof ConfigurationSection) {
if (deep) {
mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep);
}
}
}
} else {
Map<String, Object> values = section.getValues(deep);
for (Map.Entry<String, Object> entry : values.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
}
}
}
|
98f793d1-c7a2-4456-a9da-f28ba0481379
| 4
|
public List <String> getAdjacent(String nodeID){
increaseAccess();
Node node = nodeMap.get(nodeID);
List <String> result = new ArrayList<String>();
if (node != null) {
for(Map.Entry<String, Edge> entrySet : this.edgeMap.entrySet()) {
Edge edge = entrySet.getValue();
if (edge.getNode1().equals(node)){
result.add(edge.getNode2().getId());
}else if(edge.getNode2().equals(node)){
result.add(edge.getNode1().getId());
}
}
}
return result;
}
|
30fd03d0-803d-4fa7-ad77-98f89da9268f
| 9
|
public void HashSubtractor(Node Ax)
{
//given another hashTable head A, add to current hashtable
Node Oit = this.mainNode;
while(Oit != null && Ax != null)
{
OverlapType compared = RetOverlap(Oit,Ax,false);
switch(compared)
{
case Equals:
////System.Out.println(ToString());
//good case, do Y ADDER
Oit.Dwn(nami.YSubtractor(Oit.Dwn(),Ax.Dwn())); //merge the Ys of A into Oit
Oit = Oit.Adj();
Ax = Ax.Adj();
break;
case Before:
//If it comes before, no need to subtract it
Ax = Ax.Adj();
break;
case After:
Oit = Oit.Adj();
break;
case Right:
case Left:
_OverlapSplitter(Oit,Ax);
break;
case OEA:
_SubsetSplitter(Ax,Oit);
break;
case AEO:
_SubsetSplitter(Oit,Ax);
break;
}
}
//if A!= null, then there is sitll some A left, since nothing to subtract, a becomes null
Ax = null;
_FinalXMerger(); //remove when fix nami
mainNode = nami.CleanNode(mainNode);
//_NodeDeletor();
}
|
8656c17c-218d-441d-bde7-c2e2e4b532ad
| 6
|
public void atualizarTreeMap(){
List<Integer> listaprovisoria = new ArrayList();
List<Integer> listaprovisoriaexcluir = new ArrayList();
Iterator iterador = lista_de_linhas.keySet().iterator();
while(iterador.hasNext()){
Integer valorAtualizar = (Integer) iterador.next();
int valorAtualizarReal = Math.abs(valorAtualizar);
Iterator iterador2 = lista_de_linhas.get(valorAtualizar).iterator();
while(iterador2.hasNext()){
Integer colunaAtualizar = (Integer) iterador2.next();
int novoTamanho = linhasX.get(colunaAtualizar).getCoberturaValor();
if(novoTamanho < valorAtualizarReal){
listaprovisoriaexcluir.add(valorAtualizar);
listaprovisoriaexcluir.add(colunaAtualizar);
Integer novoTamanhoNeg = Math.negateExact(novoTamanho);
listaprovisoria.add(novoTamanhoNeg);
listaprovisoria.add(colunaAtualizar);
}
}
}
for(int h = 0; h <= (listaprovisoriaexcluir.size()-2); h+=2){
if(lista_de_linhas.remove(listaprovisoriaexcluir.get(h), listaprovisoriaexcluir.get(h+1))){
}
else{
}
}
for(int h = 0; h <= (listaprovisoria.size()-2); h+=2){
lista_de_linhas.put(listaprovisoria.get(h), listaprovisoria.get(h+1));
}
}
|
5c682826-f07f-46f7-b011-89bb7c092e95
| 6
|
private void loopDir(Context ctx, File dir) {
if (dir.isDirectory()) {
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".js")) {
String name = f.getAbsolutePath().substring(f.getAbsolutePath().indexOf(scriptDir.getAbsolutePath()) + scriptDir.getAbsolutePath().length() + 1, f.getAbsolutePath().lastIndexOf(".js")).replace(File.separatorChar, '/');
try {
Script script = ctx.compileReader(new FileReader(f), name, 1, null);
Scriptable scriptObj = (Scriptable) script;
scriptObj.setParentScope(this);
scriptMap.put(name, script);
} catch (IOException e) {
logger.info("Error loading script : " + name);
}
} else if (f.isDirectory()) {
loopDir(ctx, f);
}
}
}
}
|
1c46c83a-2def-4639-887e-bf111e6a57ed
| 4
|
public String next() throws IOException {
int next = skipWhite(getChar());
if (next == -1) {
return null;
} else if (isAlpha(next)) {
return getName(next);
} else if (isNumber(next)) {
return getNumber(next);
} else if (isQuote(next)) {
return getString(next);
} else {
return getSymbol(next);
}
}
|
78edc0ce-4b35-4c89-95e4-fc625f82715f
| 5
|
public void setRequest(Request request) {
// Fail immediately if there are problems in the glue code.
if (request == null) {
throw new IllegalArgumentException("request == null");
}
if (request.getPath() == null) {
throw new RuntimeException("Assertion Failure: request.getPath() == null");
}
if (request.getQuery() == null) {
throw new RuntimeException("Assertion Failure: request.getQuery() == null");
}
if (request.getQuery().get("action") == null) {
throw new RuntimeException("Assertion Failure: request.getAction() == null");
}
if (request.getQuery().get("title") == null) {
throw new RuntimeException("Assertion Failure: request.getTitle() == null");
}
mRequest = request;
}
|
de1ab4a0-d5bd-4c0b-af45-71cd60abda0c
| 2
|
public Register sibling(Width width) {
Register[] family = family();
for(int i=0;i!=family.length;++i) {
Register sibling = family[i];
if(sibling.width() == width) {
// first match
return sibling;
}
}
return null;
}
|
73e5f755-a37e-4b4d-8979-c445265678ee
| 6
|
public boolean open() {
if (isOpen()) {
return true;
}
if (summoned() && select(Option.INTERACT)) {
if (Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return !ctx.chat.select().text("Store").isEmpty();
}
})) {
for (ChatOption option : ctx.chat.first()) {
ctx.sleep(200);
if (option.select(Random.nextBoolean())) {
Condition.wait(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return isOpen();
}
}, Random.nextInt(550, 650), Random.nextInt(4, 12));
}
}
}
}
return isOpen();
}
|
02971fa2-214c-4e9e-a3be-b7aba458aae1
| 6
|
private int jjMoveStringLiteralDfa16_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjMoveNfa_0(0, 15);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return jjMoveNfa_0(0, 15);
}
switch(curChar)
{
case 66:
return jjMoveStringLiteralDfa17_0(active0, 0x7ffe00000000000L);
case 68:
return jjMoveStringLiteralDfa17_0(active0, 0x800000000000000L);
case 98:
return jjMoveStringLiteralDfa17_0(active0, 0x7ffe00000000000L);
case 100:
return jjMoveStringLiteralDfa17_0(active0, 0x800000000000000L);
default :
break;
}
return jjMoveNfa_0(0, 16);
}
|
b27e6c03-6b89-4953-ad3b-745c038f8b25
| 3
|
public void pokemonStats() {// Determines pokemon initial stats and types
if (GameFile.pokemonParty[0].equals("Tykepol")) {// Using Turtwig base
// stats
type = "Fight";
baseHp = 55;
baseAtk = 68;
baseDef = 64;
baseSpAtk = 45;
baseSpDef = 55;
baseSpeed = 31;
} else if (GameFile.pokemonParty[0].equals("Cosmet")) {// Using Treecko
// Hp +5 Def +3
// base stats
type = "Psychic";
baseHp = 45;
baseAtk = 45;
baseDef = 38;
baseSpAtk = 65;
baseSpDef = 55;
baseSpeed = 70;
} else if (GameFile.pokemonParty[0].equals("Embite")) {// Using Torchic
// base stats
type = "Dark";
baseHp = 45;
baseAtk = 60;
baseDef = 40;
baseSpAtk = 70;
baseSpDef = 50;
baseSpeed = 45;
}
}
|
fb47aa1e-2690-4ad5-849f-ed9f3f1b4ecc
| 2
|
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (debug) {
log("LoginFilter:Initializing filter");
}
}
}
|
63483bfc-9e5d-4289-aaec-32ccbbd159b9
| 8
|
void SetColor(int color) {
if (toggling == true)
{
// System.out.println("Warning! Detected Cyle of dependencies in Parents of Marker lists");
return;
}
toggling=true;
for (int i=0;i<NumPoints;i++)
{
GetPoint(i).mycolor=color;
}
if (Parent1List != null)
Parent1List.SetColor(color);
if (Parent2List != null)
Parent2List.SetColor(color);
if (Child1List != null && Child1List.toggling == false)
Child1List.SetColor(color);
if (Child2List != null && Child2List.toggling == false)
Child2List.SetColor(color);
toggling=false;
}
|
6e3ec732-af59-4e74-86d7-8e8be75ef22c
| 6
|
private static void errorMessage(String message, String expecting) { // Report error on input.
if (readingStandardInput && writingStandardOutput) {
// inform user of error and force user to re-enter.
out.println();
out.print(" *** Error in input: " + message + "\n");
out.print(" *** Expecting: " + expecting + "\n");
out.print(" *** Discarding Input: ");
if (lookChar() == '\n')
out.print("(end-of-line)\n\n");
else {
while (lookChar() != '\n') // Discard and echo remaining chars on the current line of input.
out.print(readChar());
out.print("\n\n");
}
out.print("Please re-enter: ");
out.flush();
readChar(); // discard the end-of-line character
inputErrorCount++;
if (inputErrorCount >= 10)
throw new IllegalArgumentException("Too many input consecutive input errors on standard input.");
}
else if (inputFileName != null)
throw new IllegalArgumentException("Error while reading from file \"" + inputFileName + "\":\n"
+ message + "\nExpecting " + expecting);
else
throw new IllegalArgumentException("Error while reading from inptu stream:\n"
+ message + "\nExpecting " + expecting);
}
|
dcd54bae-9b9e-4380-8326-14e9b28225dd
| 7
|
private boolean isIdentifier(String s) {
if (s == null) {
return false;
}
s = s.trim();
if (s.length() > 0) {
if ( !Character.isLetter(s.charAt(0)) ) {
return false;
}
for (int i = 1; i < s.length(); i++) {
final char ch = s.charAt(i);
if ( ch != '_' && ch != '-' && !Character.isLetterOrDigit(ch) ) {
return false;
}
}
}
return false;
}
|
e7ad5705-2cb6-4bfa-931d-952acac68648
| 9
|
@Override
public boolean onFlushDirty(Object entity, Serializable id,
Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types) {
if (!(entity instanceof HibernateTree)) {
return false;
}
HibernateTree<?> tree = (HibernateTree<?>) entity;
for (int i = 0; i < propertyNames.length; i++) {
if (propertyNames[i].equals(tree.getParentName())) {
HibernateTree<?> preParent = (HibernateTree<?>) previousState[i];
HibernateTree<?> currParent = (HibernateTree<?>) currentState[i];
return updateParent(tree, preParent, currParent);
}
}
return false;
}
|
e7e8dece-dc83-4a6d-ae45-93bccbbba98f
| 3
|
@Override
public MedicineDTO getMedicineById(Long id) throws SQLException {
Session session = null;
MedicineDTO medicine = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
medicine = (MedicineDTO) session.load(MedicineDTO.class, id);
}
catch (Exception e) {
System.err.println("Error while getting a medicine!");
}
finally {
if (session != null && session.isOpen())
session.close();
}
return medicine;
}
|
8002a634-3669-40ac-95f1-bde8cb7a4e0b
| 9
|
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target==null)
return false;
if(target.fetchEffect(ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> already <S-HAS-HAVE> the grace of a cat."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<S-NAME> gain(s) the grace of a cat!"):L("^S<S-NAME> chant(s) for the grace of a cat!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s), but nothing more happens."));
// return whether it worked
return success;
}
|
e88c1477-a0f5-4588-9464-c8566b7b1d5c
| 1
|
@Override
public AState breakTie(AState state1, AState state2)
{
if(state1.getH() < state2.getH())
return state1;
else
return state2;
}
|
f0ed4410-42ac-42c1-9c1b-5a9af7322409
| 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.USER_AGENT);
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().severe("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
this.plugin.getLogger().severe("Please double-check your configuration to ensure it is correct.");
this.result = UpdateResult.FAIL_APIKEY;
} else {
this.plugin.getLogger().severe("The updater could not contact dev.bukkit.org for updating.");
this.plugin.getLogger().severe("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;
}
this.plugin.getLogger().log(Level.SEVERE, null, e);
return false;
}
}
|
968f51f4-4b62-493e-9417-d33488294658
| 9
|
private static String formatString(String string){
StringBuilder temp = new StringBuilder(string);
boolean hasBeenGood = true;
for (int i = 0; i < temp.length(); i++){
char curChar = temp.charAt(i);
if ((curChar >= 'a' && curChar <= 'z') ||
(curChar >= 'A' && curChar <= 'Z') ||
(curChar >= '0' && curChar <= '9') ||
curChar == '_')
hasBeenGood = true;
else{
if (hasBeenGood){
temp.setCharAt(i, '_');
hasBeenGood = false;
}
else{
temp.deleteCharAt(i--);
}
}
}
return temp.toString();
}
|
14a93a34-cbca-4d70-89c9-641792a73ff0
| 2
|
private static boolean isStringValid(String str, int size) {
return str != null && !str.isEmpty() && str.length() <= size;
}
|
83c6d68f-6ed7-417c-9ce1-e6565c372e0d
| 8
|
private void setupLevelsEntities(){
resetPlayerPosition();
entities.clear();
view.actions.clear();
view.questionString = currentDepth.question;
view.situationString = currentDepth.exposition;
view.contextualString = null;
if(0 == currentDepth.entrances.size()){
//TODO end game
view.endGameString = "You earned "+playerScore+" on this game";
return;
}
int middle = 400;
int bellowPortal = 150 + Portal.height ;
view.floors.clear();
for(int i = 800; i > bellowPortal; i-=Floor.height){
view.floors.add(new Floor(Floor.FLOOR_TYPE.LIGHT_STONE, new Position(middle,i)));
}
for(int i = padding; i < 800 - padding; i += Floor.width){
view.floors.add(new Floor(Floor.FLOOR_TYPE.LIGHT_STONE, new Position(i,bellowPortal)));
}
//TODO dynamic witdh
int spacer = ((800 - padding * 2) +Portal.width) /*(Portal.width * currentDepth.entrances.size()))*/ / currentDepth.entrances.size();
//TODO there are other ways to do that but I was to lazy to change the whole setup, thus the ugly workaround
class ContextToken {
int index = 0;
int count = currentDepth.entrances.size();
boolean textWanted = false;
}
final ContextToken token = new ContextToken();
for(int i = 0; i < token.count; ++i){
final Entrance entrance = currentDepth.entrances.get(i);
final int xPortal = padding+i* spacer;
final int yPortal = 150;
Position portalPos = new Position(xPortal, yPortal);
entities.add(new Portal(portalPos, Portal.PORTAL_TYPE.IN));
view.floors.add(new Floor(Floor.FLOOR_TYPE.GREY_STONE, portalPos));
view.actions.add(new LoopedActions() {
@Override
public void execute() {
int playerX = view.player.position.x;
int playerY = view.player.position.y;
int xPow = playerX * playerX - 2 * playerX * xPortal + xPortal * xPortal;
int yPow = playerY * playerY - 2 * playerY * yPortal + yPortal * yPortal;
double distanceToPortal = Math.sqrt(xPow + yPow);
//System.out.println("Portal at "+xPortal+","+yPortal+" player at : "+playerX+","+playerY+" distance is : "+distanceToPortal);
if( displayAnswerDistance >= distanceToPortal ){
view.contextualString = entrance.text;
token.textWanted = true;
}
if((Portal.width/2) >= distanceToPortal){
currentDepth = entrance.target;
playerScore += entrance.value;
setupLevelsEntities();
}
if(token.count == ++token.index){
if(!token.textWanted)
view.contextualString = null;
token.textWanted = false;
token.index = 0;
}
}
});
}
//so player is printed over portals
entities.add(view.player);
}
|
52e60913-01e2-45df-b8be-052aa43cc5a2
| 8
|
public static void main(String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner(new File("11grid.txt"));
int[][] a = new int[20][20];
int row = 0, column = 0;
String nextline;
while (sc.hasNextLine())
{
column = 0;
nextline = sc.nextLine();
Scanner sc2 = new Scanner(nextline);
while (sc2.hasNextInt())
{
a[row][column] = sc2.nextInt();
column++;
}
row++;
}
row = 0;
column = 0;
int max = 0;
for (row = 0; row < 17; row++)
{
for (column = 0; column < 17; column++)
{
int temp = a[row][column] * a[row][column+1] * a[row][column+2] * a[row][column+3];
if (temp > max)
{
max = temp;
System.out.printf("%d %d %d 1\n", max, row, column);
}
temp = a[row][column] * a[row+1][column] * a[row+2][column] * a[row+3][column];
if (temp > max)
{
max = temp;
System.out.printf("%d %d %d 2\n", max, row, column);
}
temp = a[row][column] * a[row+1][column+1] * a[row+2][column+2] * a[row+3][column+3];
if (temp > max)
{
max = temp;
System.out.printf("%d %d %d 4\n", max, row, column);
}
temp = a[row + 3][column] * a[row + 2][column+1] * a[row + 1][column +2] * a[row][column +3];
if (temp > max)
{
max = temp;
System.out.printf("%d %d %d 4\n", max, row, column);
}
}
}
System.out.println(max);
}
|
f7670dab-e034-4b8e-9296-8e8a6c6a5d4a
| 5
|
@Override
public void move(GameBoard currentBoard) {
System.out.print(playerName + ", it's your turn. ");
int playerColumnInput = 0;
if (playerColor == Color.BLUE) {
System.out.println("You are player O (blue).");
}
else {
System.out.println("You are player X (red).");
}
currentBoard.draw();
System.out.println("Enter the number of the column where you would like to place a piece (1-7).");
playerColumnInput = sc.nextInt();
if ((playerColumnInput > -1) && (playerColumnInput < 8)) {
for (int i = 5; i >= 0; --i) {
if ((currentBoard.getColor(i,playerColumnInput-1))==Color.EMPTY) {
currentBoard.setColor(i,(playerColumnInput-1),playerColor);
System.out.println(playerName + " placed a piece in " + (i + 1) + ", " + playerColumnInput + ".");
return;
}
}
}
// if column is full
System.out.println("You can't place a piece in that column..");
move(currentBoard);
}
|
656fe830-2f15-4829-a4fd-5115c1cbbc68
| 7
|
public static String editString(String s, GameContainer container) {
Input input = container.getInput();
for (int key : collection) {
if (input.isKeyPressed(key)) {
String keyString = Input.getKeyName(key);
if (keyString.startsWith("NUMPAD")) {
keyString = keyString.substring(keyString.length() - 1);
}
return s + keyString;
}
}
if (input.isKeyPressed(Input.KEY_BACK) && s.length() > 0) {
return s.substring(0, s.length() - 1);
}
if (input.isKeyPressed(Input.KEY_SPACE) && s.length() > 0) {
return s + " ";
}
return s;
}
|
b7f6b592-5463-461c-a61b-54e86d954e0c
| 1
|
@Override
public void init(List<String> argumentList) {
literalValue = Integer.parseInt(argumentList.get(0));
if (argumentList.size() > 1) {
identifier = argumentList.get(1);
}
}
|
8a2a6e6c-d88a-49f0-862a-a555f84fc9cd
| 8
|
protected void updateCapabilitiesFilter(Capabilities filter) {
Instances tempInst;
Capabilities filterClass;
if (filter == null) {
m_AssociatorEditor.setCapabilitiesFilter(new Capabilities(null));
return;
}
if (!ExplorerDefaults.getInitGenericObjectEditorFilter())
tempInst = new Instances(m_Instances, 0);
else
tempInst = new Instances(m_Instances);
tempInst.setClassIndex(-1);
try {
filterClass = Capabilities.forInstances(tempInst);
}
catch (Exception e) {
filterClass = new Capabilities(null);
}
m_AssociatorEditor.setCapabilitiesFilter(filterClass);
m_StartBut.setEnabled(true);
// Check capabilities
Capabilities currentFilter = m_AssociatorEditor.getCapabilitiesFilter();
Associator associator = (Associator) m_AssociatorEditor.getValue();
Capabilities currentSchemeCapabilities = null;
if (associator != null && currentFilter != null &&
(associator instanceof CapabilitiesHandler)) {
currentSchemeCapabilities = ((CapabilitiesHandler)associator).getCapabilities();
if (!currentSchemeCapabilities.supportsMaybe(currentFilter) &&
!currentSchemeCapabilities.supports(currentFilter)) {
m_StartBut.setEnabled(false);
}
}
}
|
e58da536-2de0-42b6-af20-925108b7116f
| 3
|
private void writeLog() {
String correct;
String time;
if(wasCorrect) {
correct = " correctly";
}
else {
correct = " incorrectly";
}
if(duration == 1){
time = " second.";
}
else{
time = " seconds.";
}
try {
logWriter.writeToFile(problemCount + ". The problem " + oneText + " x " + twoText +
" was answered as " + extract(answerField) + correct + " in " + duration + time);
} catch (IOException ex) {
Logger.getLogger(MultiplicationProblems.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
26c76209-4d29-4075-b3a7-b28edd0fd25b
| 2
|
@Test
public void testConstantReadingAndWriting()
{
final LockRef<String> mod = new LockRef<String>("Hello World");
final AtomicInteger finished = new AtomicInteger();
final AtomicBoolean running = new AtomicBoolean(true);
Runnable writer = new Runnable() {
public void run() {
String newValue = null;
for (int i = 0; i < 100; i++) {
mod.lock();
sleep(10);
newValue = "Random:" + Math.random();
mod.unlock(newValue);
assertEquals( newValue, mod.get() );
sleep(40);
assertEquals( newValue, mod.get() );
}
running.set(false);
System.out.println("Writer finished");
}
};
Runnable reader = new Runnable() {
public void run() {
while (running.get()) {
mod.get();
sleep(2);
}
System.out.println("Reader ["+Thread.currentThread().getId()+"] finished");
finished.incrementAndGet();
}
};
GroupTask.initialize(5);
GroupTask.add(reader, 4);
GroupTask.add(writer);
GroupTask.execute();
assertEquals(4, finished.get());
}
|
bc0e7043-f45e-47f0-981b-d541b28d8b46
| 7
|
public final void dotted_attr() throws RecognitionException {
try {
// Python.g:93:5: ( NAME ( DOT NAME )* )
// Python.g:93:7: NAME ( DOT NAME )*
{
match(input,NAME,FOLLOW_NAME_in_dotted_attr213); if (state.failed) return;
// Python.g:93:12: ( DOT NAME )*
loop8:
while (true) {
int alt8=2;
int LA8_0 = input.LA(1);
if ( (LA8_0==DOT) ) {
alt8=1;
}
switch (alt8) {
case 1 :
// Python.g:93:13: DOT NAME
{
match(input,DOT,FOLLOW_DOT_in_dotted_attr216); if (state.failed) return;
match(input,NAME,FOLLOW_NAME_in_dotted_attr218); if (state.failed) return;
}
break;
default :
break loop8;
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
}
|
8d2dd209-4986-472a-b2cd-53de94fd3103
| 3
|
private void refreshChatLogs() {
File dir = new File(ConfigManager.getInstance().chatlogsDir);
if (!dir.exists()) {
dir.mkdir();
}
File[] logs = dir.listFiles();
if (logs.length == 0) {
return;
}
String[] names = new String[logs.length];
for (int i = 0; i < logs.length; i++) {
names[i] = logs[i].getName();
}
lbChatDates.setListData(names);
}
|
c8c28871-61a6-40d4-8ee4-3c06905c5c30
| 5
|
private void initComponents() {
getStyleClass().add("body");
HBox hbox1 = new HBox(10);
GridPane grid1 = new GridPane();
grid1.setHgap(10);
grid1.setVgap(10);
grid1.getStyleClass().add("grid-region");
grid1.setPadding(new Insets(10, 10, 10, 10));
Button nameButton = new Button("Full Name");
nameButton.getStyleClass().add("submit-button");
nameButton.setPrefWidth(AppSettings.getDoubleValue("body.label.width"));
grid1.add(nameButton, 0, 0);
fullNameText = new TextBox();
grid1.add(fullNameText, 1, 0);
LabelBox companyLabel = new LabelBox("Company");
grid1.add(companyLabel, 0, 1);
companyNameText = new TextBox();
grid1.add(companyNameText, 1, 1);
LabelBox jobTitleLabel = new LabelBox("Job Title");
grid1.add(jobTitleLabel, 0, 2);
jobTitleText = new TextBox();
grid1.add(jobTitleText, 1, 2);
LabelBox prefNameLabel = new LabelBox("File As");
grid1.add(prefNameLabel, 0, 3);
prefNameCombo = new ComboBox<>();
prefNameCombo.setPrefWidth(AppSettings
.getDoubleValue("body.input.width"));
grid1.add(prefNameCombo, 1, 3);
StackPane hBoxPhoto = new StackPane();
hBoxPhoto.getStyleClass().add("photo");
File photoFile = new File("resources/images/photo.png");
final ImageView image = new ImageView();
try {
image.setImage(new Image(photoFile.toURI().toURL().toString()));
} catch (Exception ex) {
}
image.setPreserveRatio(true);
image.setFitWidth(AppSettings.getDoubleValue("photo.input.width"));
image.setFitHeight(AppSettings.getDoubleValue("photo.input.height"));
GridPane.setRowSpan(hBoxPhoto, 4);
hBoxPhoto.getChildren().add(image);
grid1.add(hBoxPhoto, 2, 0);
GridPane grid11 = new GridPane();
grid11.setHgap(10);
grid11.setVgap(10);
grid11.getStyleClass().add("grid-region");
grid11.setPadding(new Insets(10, 10, 10, 10));
StackPane vCardStack = new StackPane();
final ImageView vCardImage = new ImageView();
vCardImage.setPreserveRatio(true);
vCardImage.setFitWidth(AppSettings.getDoubleValue("photo.input.width"));
vCardImage.setFitHeight(AppSettings
.getDoubleValue("photo.input.height"));
vCardImage.imageProperty().bind(image.imageProperty());
final Label vCard = new Label();
vCard.setPrefSize(AppSettings.getDoubleValue("body.vcard.width"),
AppSettings.getDoubleValue("body.vcard.height"));
StackPane.setAlignment(vCardImage, Pos.TOP_RIGHT);
vCardStack.getChildren().addAll(vCardImage, vCard);
grid11.add(vCardStack, 0, 0);
HBox hbox2 = new HBox();
GridPane grid2 = new GridPane();
grid2.setHgap(10);
grid2.setVgap(10);
grid2.getStyleClass().add("grid-region");
grid2.setPadding(new Insets(0, 10, 10, 10));
LabelBox emailLabel = new LabelBox("E-mail");
grid2.add(emailLabel, 0, 1);
emailText = new TextBox();
grid2.add(emailText, 1, 1);
LabelBox displayEmailLabel = new LabelBox("Display As");
grid2.add(displayEmailLabel, 0, 2);
displayEmailText = new TextBox();
grid2.add(displayEmailText, 1, 2);
LabelBox webpageAddressLabel = new LabelBox("Web page Address");
grid2.add(webpageAddressLabel, 0, 3);
webpageAddressText = new TextBox();
grid2.add(webpageAddressText, 1, 3);
LabelBox imAddressLabel = new LabelBox("IM Address");
grid2.add(imAddressLabel, 0, 4);
imAddressText = new TextBox();
grid2.add(imAddressText, 1, 4);
HBox hbox3 = new HBox();
ScrollPane phoneScroll = ScrollPaneBuilder
.create()
.minWidth(
AppSettings.getDoubleValue("body.label.width")
+ AppSettings
.getDoubleValue("body.input.width")
+ 40).minHeight(60).styleClass("grid-region")
.vbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED).build();
final GridPane grid3 = new GridPane();
grid3.setHgap(10);
grid3.setVgap(10);
grid3.setPadding(new Insets(10, 10, 10, 10));
Button phoneButton = new Button("Phone Number");
phoneButton.getStyleClass().add("submit-button");
phoneButton
.setPrefWidth(AppSettings.getDoubleValue("body.label.width"));
grid3.add(phoneButton, 0, 0);
phoneNumberText = new TextBox();
grid3.add(phoneNumberText, 1, 0);
final Button addPhoneButton = new Button("Add Phone Number");
addPhoneButton.getStyleClass().add("submit-button");
addPhoneButton.setPrefWidth(AppSettings
.getDoubleValue("body.input.width"));
grid3.add(addPhoneButton, 1, 1);
phoneNumberText = new TextBox();
grid3.add(phoneNumberText, 1, 0);
phoneScroll.setContent(grid3);
HBox hbox4 = new HBox();
ScrollPane addressScroll = ScrollPaneBuilder
.create()
.minWidth(
AppSettings.getDoubleValue("body.label.width")
+ AppSettings
.getDoubleValue("body.input.width")
+ 40).minHeight(60).styleClass("grid-region")
.vbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED).build();
final GridPane grid4 = new GridPane();
grid4.setHgap(10);
grid4.setVgap(10);
grid4.setPadding(new Insets(10, 10, 10, 10));
Button addressButton = new Button("Address");
addressButton.getStyleClass().add("submit-button");
addressButton.setPrefWidth(AppSettings
.getDoubleValue("body.label.width"));
grid4.add(addressButton, 0, 0);
addressText = new TextBox();
grid4.add(addressText, 1, 0);
final Button addAddressButton = new Button("Add Address");
addAddressButton.getStyleClass().add("submit-button");
addAddressButton.setPrefWidth(AppSettings
.getDoubleValue("body.input.width"));
grid4.add(addAddressButton, 1, 1);
addressScroll.setContent(grid4);
hbox1.getChildren().addAll(grid1, grid11);
hbox2.getChildren().addAll(grid2);
hbox3.getChildren().addAll(phoneScroll);
hbox4.getChildren().addAll(addressScroll);
getChildren().addAll(hbox1, hbox2, hbox3, hbox4);
fullNameText.focusedProperty().addListener(
new ChangeListener<Boolean>() {
@Override
public void changed(
ObservableValue<? extends Boolean> observable,
Boolean oldValue, Boolean newValue) {
if (oldValue == true && newValue == false) {
setFullNameFromTextField(fullNameText.getText());
setPrefNames(Name.getInstance()
.getNameCombinations());
vCard.setText(Name.getInstance()
.getNameCombinations().get(0)
+ "\n"
+ Phone.getInstance("Business").getNumber()
+ "\n"
+ Address.getInstance("Business")
.getAddressDetail());
}
}
});
image.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
FileChooser fileChooser = new FileChooser();
ExtensionFilter extFilter1 = new ExtensionFilter(
"Bitmap Image (*.bmp)", "*.bmp");
ExtensionFilter extFilter2 = new ExtensionFilter(
"PNG Image (*.png)", "*.png");
ExtensionFilter extFilter3 = new ExtensionFilter(
"JPG Image (*.jpg)", "*.jpg");
ExtensionFilter extFilter4 = new ExtensionFilter(
"GIF Image (*.gif)", "*.gif");
ExtensionFilter extFilter5 = new ExtensionFilter(
"All files (*.*)", "*.*");
fileChooser.getExtensionFilters().addAll(extFilter1,
extFilter2, extFilter3, extFilter4, extFilter5);
try {
image.setImage(new Image(fileChooser.showOpenDialog(null)
.toURI().toURL().toString()));
} catch (Exception ex) {
}
}
});
addPhoneButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Button phoneButton = new Button("Phone Number");
phoneButton.getStyleClass().add("submit-button");
phoneButton.setPrefWidth(AppSettings
.getDoubleValue("body.label.width"));
grid3.add(phoneButton, 0, Phone.getCount());
phoneNumberText = new TextBox();
grid3.add(phoneNumberText, 1, Phone.getCount());
GridPane.setRowIndex(addPhoneButton, Phone.getCount() + 1);
phoneButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Contacts.getInstance().showPhoneNumberPopup();
}
});
}
});
addAddressButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Button addressButton = new Button("Address");
addressButton.getStyleClass().add("submit-button");
addressButton.setPrefWidth(AppSettings
.getDoubleValue("body.label.width"));
grid4.add(addressButton, 0, Address.getCount());
addressText = new TextBox();
grid4.add(addressText, 1, Address.getCount());
GridPane.setRowIndex(addAddressButton, Phone.getCount() + 1);
addressButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Contacts.getInstance().showAddressPopup();
}
});
}
});
nameButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Contacts.getInstance().showFullNamePopup();
}
});
phoneButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Contacts.getInstance().showPhoneNumberPopup();
}
});
addressButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Contacts.getInstance().showAddressPopup();
}
});
}
|
1543dac2-660d-4d11-ac7b-78b921ae90b5
| 1
|
public String getFile() {
if (file == null) {
throw new RuntimeException("missing file name.");
}
return file;
}
|
b703a990-1a7b-4568-89c7-9690243d3809
| 9
|
Field getFieldWithPos(int position_) {
if (isPrimitive != null) { // if this is a primitive
return null;
//throw new ASNException("Cannot get subfield's position for a Primitive Type");
}
if (position_ != 6) { // Optimization for Tag 6 Object Identifier.
for (int i = 0; i < fields.length; i++) {
if (fields[i].pos == position_) {
return fields[i];
}
}
} else {
int emptyPos = -1;
for (int i = 0; i < fields.length; i++) {
if (fields[i].pos == position_) {
return fields[i];
}
if (fields[i].pos < 0) {
emptyPos = i;
}
}
if (emptyPos != -1) { // We hit an empty Pos
//System.out.println("Here...OBJECT IDENTIFIER");
if (fields[emptyPos].type.name.equals("OBJECT IDENTIFIER")) {
return fields[emptyPos];
}
}
}
return null;
//throw new ASNException("Unable to find subfield's position " + position + " inside ASNClass \"" + this.name + "\"" );
}
|
c0fc696b-b594-4e13-874a-b2f32f7beb4b
| 0
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
|
8b6e73f0-d943-4a9c-bbc1-9a9950da1576
| 1
|
public static void listItem(){
rover = head;
while(rover != null){
System.out.println("" + rover.name + " : " + rover.alt + " : " + rover.img);
rover = rover.next;
}
}
|
d498c0b8-e910-490e-a462-409b34909687
| 2
|
public static TicketRestrictionEnumeration fromValue(String v) {
for (TicketRestrictionEnumeration c: TicketRestrictionEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
|
5ccc9269-c208-4b4c-b696-20f68e1fdf01
| 7
|
public Boolean calcHetero() {
// No genotyping information? => Use number of ALT field
if (genotypeFieldsStr == null) return isMultiallelic();
Boolean isHetero = null;
// No genotype fields => Parse fields (we only parse them if there is only one GT field)
if (genotypeFields == null) {
// Are there more than two tabs? (i.e. more than one format field + one genotype field)
int countFields, fromIndex;
for (countFields = 0, fromIndex = 0; (fromIndex >= 0) && (countFields < 1); countFields++, fromIndex++)
fromIndex = genotypeFieldsStr.indexOf('\t', fromIndex);
// OK only one genotype field => Parse it in order to extract homo info.
if (countFields == 1) parseGenotypes();
}
// OK only one genotype field => calculate if it is heterozygous
if ((genotypeFields != null) && (genotypeFields.length == 1)) isHetero = getVcfGenotype(0).isHeterozygous();
return isHetero;
}
|
b1a87092-8137-4494-9b2d-0e857bae280b
| 3
|
protected static String describe(String name,Class[] params) {
StringBuilder invp=new StringBuilder();
invp.append(name);
invp.append('(');
if (params!=null)
for(int k=0;k<params.length;k++) {
if (k!=0) invp.append(',');
invp.append(params[k].toString());
};
invp.append(')');
return invp.toString();
};
|
075229a5-4e06-4b08-b61b-ab7a09b265fd
| 9
|
public final Method[] getReflectiveMethods() {
if (methods != null)
return methods;
Class baseclass = getJavaClass();
Method[] allmethods = baseclass.getDeclaredMethods();
int n = allmethods.length;
int[] index = new int[n];
int max = 0;
for (int i = 0; i < n; ++i) {
Method m = allmethods[i];
String mname = m.getName();
if (mname.startsWith(methodPrefix)) {
int k = 0;
for (int j = methodPrefixLen;; ++j) {
char c = mname.charAt(j);
if ('0' <= c && c <= '9')
k = k * 10 + c - '0';
else
break;
}
index[i] = ++k;
if (k > max)
max = k;
}
}
methods = new Method[max];
for (int i = 0; i < n; ++i)
if (index[i] > 0)
methods[index[i] - 1] = allmethods[i];
return methods;
}
|
fb6d3b95-9038-41a0-bb38-3b6f86968892
| 6
|
public static String unescape(String string) {
int length = string.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
if (c == '+') {
c = ' ';
} else if (c == '%' && i + 2 < length) {
int d = JSONTokener.dehexchar(string.charAt(i + 1));
int e = JSONTokener.dehexchar(string.charAt(i + 2));
if (d >= 0 && e >= 0) {
c = (char)(d * 16 + e);
i += 2;
}
}
sb.append(c);
}
return sb.toString();
}
|
bd09856e-48ed-4939-b726-911a45d64abf
| 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 SubCategoria)) {
return false;
}
SubCategoria other = (SubCategoria) object;
if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
44152a05-d927-4637-b1c4-eb023dd249a7
| 4
|
private int[][] pasaArregloAMatrizLeft(int[] c0, int[] c1, int[] c2, int[] c3) {
int[][] res = new int[4][4];
for (int i = 0; i < 4; i++)
res[0][i] = c0[i];
for (int j = 0; j < 4; j++)
res[1][j] = c1[j];
for (int k = 0; k < 4; k++)
res[2][k] = c2[k];
for (int m = 0; m < 4; m++)
res[3][m] = c3[m];
return res;
}
|
26f2e39e-7e7e-4962-a8e7-a56c09413e32
| 6
|
protected String constructCookies(String... names){
StringBuilder ret = new StringBuilder();
//syntax:
//name1=value1; name2=value2
if(names != null && names.length != 0){
//put in name + value
boolean start = false;
for(int i=0; i<names.length; i++){
if(start){
ret.append("; ");
}
ret.append(names[i]).append("=").append(cookies.get(names[i]));
start = true;
}
}else{
//put in everything
boolean start = false;
for(Entry<String, String> entry : cookies.entrySet()){
if(start){
ret.append("; ");
}
ret.append(entry.getKey()).append("=").append(entry.getValue());
start = true;
}
}
return ret.toString();
}
|
caee4399-ccfb-47a6-a206-4a240da885a6
| 1
|
private int CountNumberLines()
{
int i;
for(i = 0; scn.hasNextLine(); i++){
scn.nextLine();
}
return i;
}
|
05370394-2a10-438f-aeb7-4419c13469b9
| 9
|
private void createUpperLayout() {
JPanel upper = new JPanel();
upper.setSize(100, 50);
upper.setLayout(new BorderLayout());
JPanel sticks = new JPanel();
sendSticks = new JButton("Send sticks");
sendSticks.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (setSticks) {
if (nbrOfPlayersThatSetSticks == nbrOfPlayers - 1
&& (int) spinner.getValue() + totalSticks == sticksInRound) {
textMessage
.setText("This number of sticks is not allowed!");
revalidate();
return;
}
Thread t = new Thread() {
public void run() {
if (stickThread.isAlive()) {
stickThread.kill();
}
setSticks = false;
System.out.println("count: " + spinner.getValue());
monitor.addNumberOfSticksCommand((int) spinner
.getValue());
textMessage.setText("Waitinng for other players...");
revalidate();
}
};
t.start();
}
}
});
spinner = new JSpinner( new SpinnerNumberModel( 1,0,numberOfRounds,1 ) );
sticks.add(spinner);
sticks.add(sendSticks);
JPanel panelTakenSticks = new JPanel();
panelTakenSticks.setLayout(new GridBagLayout());
panelTakenSticks.setBorder(new EmptyBorder(10, 10, 10, 10));
GridBagConstraints c = new GridBagConstraints();
takenSticks = new JLabel[nbrOfPlayers];
for(int j=0;j<3;j++) {
for(int i = 0;i<nbrOfPlayers;i++) {
if(j==0) {
if(i==0){
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = i;
c.gridy = 0;
panelTakenSticks.add(new JLabel("Taken sticks:"),c);
}
}else if(j==1) {
System.out.println("add player"+i);
c.weightx = 0.5;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = i;
c.gridy = 11;
panelTakenSticks.add(new JLabel("Player " + (i + 1)), c);
} else {
takenSticks[i] = new JLabel("0");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = i;
c.gridy = 22;
panelTakenSticks.add(takenSticks[i], c);
}
}
}
upper.setBackground(backgroundGreen);
sticks.setBackground(backgroundGreen);
panelTakenSticks.setBackground(lightBlue);
panelTakenSticks.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(5, 5, 5, 5),BorderFactory.createLineBorder(Color.BLACK,0,false)));
textMessage.setHorizontalAlignment(SwingConstants.CENTER);
textMessage.setBackground(backgroundGreen);
textMessage.setFont(new Font(textMessage.getFont().getFontName(),Font.PLAIN,20));
textMessage.setForeground(Color.RED);
textMessage.setAlignmentX(CENTER_ALIGNMENT);
textMessage.setBorder(new EmptyBorder(2, 2, 2, 2));
JPanel upperText = new JPanel();
upperText.setLayout(new BoxLayout(upperText,BoxLayout.Y_AXIS));
upperText.add(sticks);
upperText.add(textMessage);
upperText.setBackground(backgroundGreen);
upper.add(upperText,BorderLayout.NORTH);
getContentPane().add(upper,BorderLayout.NORTH);
}
|
1709c855-4941-44df-b921-94f42a20963f
| 6
|
public static int mst(PriorityQueue<Edge> edges, Vertex[] noder) {
ArrayList<Edge> A = new ArrayList<Edge>();
Edge e = null;
while(!edges.isEmpty()) {
e = edges.poll();
Vertex from = noder[e.getFrom()];
Vertex fromsParent = from.getParent();
Vertex to = noder[e.getTo()];
Vertex tosParent = to.getParent();
if(fromsParent != tosParent || fromsParent == null && tosParent == null) {
A.add(e);
if(tosParent == null) {
if(fromsParent == null) {
to.setParent(to);
} else {
to.setParent(fromsParent);
}
}
}
}
return e.getWeight();
}
|
563a49b0-9754-453c-a002-f8676cf10478
| 0
|
private Sundae() {
print("Sundae()");
}
|
d192d0ae-afec-4564-b8cb-af0ea0eb708b
| 9
|
void event(){
//EFF: plays event if there is a trap
Trap trip = curPlayer.curRoom.trap;
Wumpus wump = curPlayer.curRoom.wumpus;
Random ran = new Random();
if(wump != null){
if(players.length==1){
new GameOver(curPlayer.score, "You were eaten by the Wumpus!");
}
else {
String name = Integer.toString(curPlayer.playerNum);
nextPlayer();
int score = curPlayer.score;
players = new Player[1];
curPlayer.playerNum = 1;
players[0] = curPlayer;
//new GameOver(score, "Player " + name + " was eaten by the Wumpus");
}
}
else if(trip !=null){
if(trip instanceof Gold){
int score = curPlayer.score;
int moves = curPlayer.numMoves;
String name = Integer.toString(curPlayer.playerNum);
score = score + ran.nextInt(5000);
if(score<0) score = 0;
new GameOver(score, "Player "+ name +" found the gold!");
}
if(trip instanceof Bats){
curPlayer.curRoom.panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
curPlayer.score -= 100;
int newCol = ran.nextInt(colNum -1);
int newRow = ran.nextInt(rowNum -1);
curPlayer.setRoom(roomMap[newRow][newCol]);
Point point = new Point(newRow, newCol);
if (curPlayer == players[0])
curPlayer.curRoom.panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
else
curPlayer.curRoom.panel.setBorder(BorderFactory.createLineBorder(Color.GREEN));
curPlayer.setLocation(point);
event();
}
if(trip instanceof Pitfall){
if(players.length==1){
new GameOver(curPlayer.score, "You fell into a pit!");
}
else {
String name = Integer.toString(curPlayer.playerNum);
nextPlayer();
players = new Player[1];
curPlayer.playerNum = 1;
players[0] = curPlayer;
//new GameOver(score, "Player " + name + " fell into a pit");
}
}
}
}
|
def4290a-2a8c-4444-82f1-6335a28b3c6f
| 9
|
public void checkFilesExist() {
String currDateString = DateModifier.getCurrDate();
fileName = "archives.txt";
File ArchivesFile = new File(fileName);
if (!ArchivesFile.exists()) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.print(String.format(FILE_HEADING, "", "Archives"));
writer.close();
}
fileName = "general.txt";
File GeneralFile = new File(fileName);
if (!GeneralFile.exists()) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.print(String.format(FILE_HEADING, "", "General"));
writer.close();
}
fileName = "overdue.txt";
File Overdue = new File(fileName);
if (!Overdue.exists()) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
writer.print(String.format(FILE_HEADING, "", "Overdue"));
writer.close();
}
/*
* check the 7 task boxes
*/
for (int i = 1; i < 8; i++) {
fileName = currDateString + ".txt";
File file = new File(fileName);
if (!file.exists()) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
}
String _dayOfWeek = DayModifier.getDayOfWeek(currDateString);
String formattedDate = reformatDate(currDateString);
writer.print(String.format(FILE_HEADING, _dayOfWeek,
formattedDate));
writer.close();
}
currDateString = DateModifier.getNextDate(currDateString);
}
}
|
c9e00281-fd5d-42cf-aed4-ece927bfdefe
| 1
|
public double haeVuosimyynti(int vuosi) throws DAOPoikkeus {
TilastointiDAO tilasto = new TilastointiDAO();
HashMap<Integer, Tilastointi> kktilaukset = tilasto.haeTilaukset(vuosi);
double vuosimyynti = 0;
for (int i = 1; i < 13; i++) {
Tilastointi tilastot = kktilaukset.get(i);
vuosimyynti = vuosimyynti + tilastot.getKkmyynti();
System.out.println(vuosimyynti);
}
return vuosimyynti;
}
|
87b4d857-62e5-4910-aa11-092fe1992d08
| 7
|
@Override
public void spring(MOB target)
{
if(target.location()!=null)
{
if((!invoker().mayIFight(target))
||(isLocalExempt(target))
||(invoker().getGroupMembers(new HashSet<MOB>()).contains(target))
||(target==invoker())
||(doesSaveVsTraps(target)))
target.location().show(target,null,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,L("<S-NAME> avoid(s) the flame burst!"));
else
if(target.location().show(invoker(),target,this,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISE,(affected.name()+" flames all over <T-NAME>!")+CMLib.protocol().msp("fireball.wav",30)))
{
super.spring(target);
CMLib.combat().postDamage(invoker(),target,null,CMLib.dice().roll(trapLevel()+abilityCode(),12,1),CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,L("The flames <DAMAGE> <T-NAME>!"));
}
}
}
|
4f66fcd2-36d3-4906-baef-a5f654912932
| 2
|
public Object get(String name) throws IllegalAccessError {
int index;
if((index = ObjectNames.indexOf(name)) != -1) {
if(ObjectType.get(index) == OBJECT_ARRAY) {
//technically miss used exception I think, but it fits the purpose
throw new IllegalAccessError("You may only access saved Arrays via the getArray function!");
}
return ObjectList.get(index);
}
return null;
}
|
c052cf33-d259-4747-b14f-8f2352b1c6b7
| 0
|
public Date getDate() {
return date;
}
|
f110791a-4d64-403f-899c-0a3a49ee518b
| 4
|
@Override
public Intersection findIntersect(Ray r) throws Exception {
Intersection closest = null;
for (Entity o : entities) {
Intersection p = o.findIntersect(r);
if (p == null) {
continue;
}
if (closest == null) {
closest = p;
continue;
}
if (p.getDistance() < closest.getDistance()) {
closest = p;
}
}
return closest;
}
|
d945ce89-cef5-4a81-8ae4-458470ea37af
| 9
|
public void writeTRJ(String filename, int reldepth, String release) {
File file = new File(filename);
BufferedReader br = null;
String ln = null;
try {
br = new BufferedReader(new FileReader(file));
br.readLine();
ln = br.readLine();
while (ln != null) {
StringTokenizer stk = new StringTokenizer(ln);
if (stk.countTokens() != 10) {
System.out
.println("WARNING: Number of fields must equal 10 (contains "
+ stk.countTokens()
+ "). Skipping "
+ filename + "...");
ps1.clearBatch();
return;
}
ps1.setString(
1,
file.getName().substring(0,
file.getName().lastIndexOf("."))); // Source
ps1.setInt(2, reldepth);
ps1.setInt(3, Integer.parseInt(stk.nextToken())); // Index
Timestamp ts = null;
try {
String s = stk.nextToken() + " " + stk.nextToken();
if (s.contains(":")) {
ts = new Timestamp(df1.parse(s).getTime());
} else {
ts = new Timestamp(df2.parse(s).getTime());
}
} catch (ParseException e) {
System.out
.println("WARNING: Date could not be parsed from "
+ ln + ". Continuing");
ln = br.readLine();
continue;
}
ps1.setTimestamp(4, ts); // Time
ps1.setDouble(5, Double.parseDouble(stk.nextToken())); // Duration
double depth = Double.parseDouble(stk.nextToken());
ps1.setDouble(6, depth); // Depth
double longitude = Double.parseDouble(stk.nextToken());
ps1.setDouble(7, longitude); // Longitude
double latitude = Double.parseDouble(stk.nextToken());
ps1.setDouble(8, latitude); // Latitude
ps1.setDouble(9, Double.parseDouble(stk.nextToken())); // Distance
String status = stk.nextToken();
if (!status.startsWith("\"S")) {
ps1.setString(10, status); // Status
ps1.setString(11, "");
} else {
ps1.setString(10, "S");
ps1.setString(11, status.substring(2, status.length() - 1));
}
ps1.setBoolean(12, Boolean.parseBoolean(stk.nextToken())); // NoData
ps1.setString(13, release);
ps1.setDouble(14, longitude);
ps1.setDouble(15, latitude);
ps1.setDouble(16, depth);
// ps1.execute();
ln = br.readLine();
ps1.addBatch();
}
ps1.executeBatch();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException sq) {
sq.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
}
}
}
// System.out.println(filename + " processing complete");
}
|
65e14816-6f86-433a-b69a-48cade1ad292
| 2
|
protected void processMouseWheelEvent(MouseWheelEvent e) {
if (hasFocus()) {
int code = InputManager.MOUSE_WHEEL_DOWN;
if (e.getWheelRotation() < 0) {
code = InputManager.MOUSE_WHEEL_UP;
}
mapGameAction(code, true);
}
e.consume();
}
|
68630c26-9439-48cb-a290-21c9ab86dea9
| 0
|
public void setQuantita(Integer quantita) {
this.quantita = quantita;
}
|
2713f80e-ccb3-4b46-a9fe-104025962319
| 5
|
@SuppressWarnings ("unchecked")
protected final void delete(final BaseItem item) throws NullPointerException, IllegalArgumentException {
switch (item.state()) {
case Item.APPEND_STATE:
case Item.UPDATE_STATE:
case Item.REMOVE_STATE:
if (!this.equals(item.pool())) throw new IllegalArgumentException();
this.doDelete((GItem)item);
case Item.CREATE_STATE:
return;
default:
throw new IllegalArgumentException();
}
}
|
c44f6944-65bd-4a70-b766-1a44947e638e
| 0
|
public static void main(String[] args) {
SprinklerSystem sprinklers = new SprinklerSystem();
System.out.println(sprinklers);
}
|
74ab9d5c-f316-4f70-a9bf-030a6dfaecce
| 1
|
public void cancel() throws java.io.IOException {
if (!(getStatus() == SubLWorkerStatus.WORKING_STATUS)) { return; }
CycAccess cycAccess = getCycServer();
synchronized (cycAccess) {
cycAccess.getCycConnection().cancelCommunication(this);
}
}
|
2a0e373c-853a-4853-b510-ed53b7eeb5eb
| 0
|
public void grow(float size)
{
this.size += size;
}
|
348718eb-fbf7-44fb-bc8e-17f77cc659b7
| 9
|
public void start() throws IOException {
/* Open DB Connection */
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
ObservableThread userInputThread = new ObservableThread() {
@Override
public void run() {
try {
new BufferedReader(new InputStreamReader(System.in))
.readLine();
} catch (IOException e) {
e.printStackTrace();
this.fireThreadError();
return;
}
this.fireThreadSuccess();
}
};
userInputThread.setDaemon(true);
ThreadStatusObserver threadObserver = new ThreadStatusObserver(
Thread.currentThread(), userInputThread);
/* load initial user screen names */
final String resDirPrefix = "";
List<String> initUserScreenNames = new ArrayList<>();
try {
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "follower_rank.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "retweet_rank.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "twittercounter_following.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#blogger.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#internet.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#kultur.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#marketing.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#medien.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#nachrichten.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#socialmedia.csv"));
initUserScreenNames.addAll(loadUserScreenNames(resDirPrefix
+ "tweet_rank_#twitter.csv"));
} catch (IOException e) {
e.printStackTrace();
}
TwitterAccess twitterAcc = new CachedTwitterAccess("twittercache");
List<User> initUsers;
try {
initUsers = twitterAcc.lookupUsersByScreenName(initUserScreenNames
.toArray(new String[0]));
} catch (TwitterException e) {
e.printStackTrace();
return;
}
/* eliminate duplicate user IDs */
for (int i = 0; i < initUsers.size(); i++) {
followIdsSet.add(initUsers.get(i).getId());
}
LinkedBlockingQueue<String> statusQueue = new LinkedBlockingQueue<>();
MongoConsumer mongoConsumer = new MongoConsumer(mongoClient,
statusQueue);
mongoConsumer.start();
mongoConsumer.registerObserver(threadObserver);
userInputThread.registerObserver(threadObserver);
TwitterStream stream = TwitterStreamFactory.getSingleton();
stream.addListener(new StatusProducer(statusQueue));
stream.addListener(this);
userInputThread.start();
int oldFollowIdsSize = 0;
try {
while (true) {
if (oldFollowIdsSize != followIdsSet.size()) {
/* copy IDs to array */
long[] followIds = new long[followIdsSet.size()];
int followIdsIndex = 0;
for (Long l : followIdsSet) {
followIds[followIdsIndex] = l;
followIdsIndex++;
}
/* build stream filter from user IDs */
oldFollowIdsSize = followIdsSet.size();
FilterQuery filterQuery = new FilterQuery(followIds);
filterQuery.language(new String[] { "en" });
stream.filter(filterQuery);
}
Thread.sleep(30 * 60 * 1000);
// Thread.sleep(20000); // for debugging
}
} catch (InterruptedException e) {
System.out.println("TwitterMonitor exits");
} finally {
stream.shutdown();
mongoConsumer.interrupt();
try {
mongoConsumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Number of omitted statuses due do BSONExceptions: " + mongoConsumer.getBsonExceptionCount());
}
}
|
4607aa03-46b1-4277-b641-52ab358765fc
| 4
|
void doLower() {
if (gameInProgress == false) {
// If the game has ended, it was an error to click "Lower",
// So set up an error message and abort processing.
message = "Apasa \"Joc nou\" pentru a incepe!";
repaint();
return;
}
hand.addCard( deck.dealCard() ); // Deal a card to the hand.
int cardCt = hand.getCardCount();
Card thisCard = hand.getCard( cardCt - 1 ); // Card just dealt.
Card prevCard = hand.getCard( cardCt - 2 ); // The previous card.
if ( thisCard.getValue() > prevCard.getValue() ) {
gameInProgress = false;
message = "Ce pacat! Ai pierdut.";
}
else if ( thisCard.getValue() == prevCard.getValue() ) {
gameInProgress = false;
message = "Ce pacat! Cartile sunt egale.";
}
else if ( cardCt == 4) {
gameInProgress = false;
message = "Ai castigat! Ai ghicit de trei ori consecutiv.";
}
else {
message = "Ai ghicit! Incearca pentru " + cardCt + ".";
}
repaint();
} // end doLower()
|
a7608211-a1a6-49d0-9c8d-d44b39abb593
| 9
|
public void GetInput() {
if (Input.MousePressed(org.newdawn.slick.Input.MOUSE_LEFT_BUTTON)) {
if ((Mouse.getX() >= this.x && Mouse.getX() <= this.x+48) && ((Main.SCREEN_HEIGHT-Mouse.getY()) >= this.y && (Main.SCREEN_HEIGHT-Mouse.getY()) <= this.y+48)) {
clicked = true;
}
}
if ((Mouse.getX() >= this.x && Mouse.getX() <= this.x+48) && ((Main.SCREEN_HEIGHT-Mouse.getY()) >= this.y && (Main.SCREEN_HEIGHT-Mouse.getY()) <= this.y+48)) {
hover = true;
}
else {
hover = false;
}
}
|
a2cf9451-b14e-4e35-a895-a51b15623c38
| 4
|
private static int lcmList(ArrayList<Integer> list) {
if (list.size() == 0)
throw new NullPointerException();
if (list.size() == 1)
return list.get(0);
if (list.size() == 2)
return lcm(list.get(0), list.get(1));
int result = list.get(list.size() - 1);
for (int i = list.size() - 1; i >= 0; i--)
result = lcm(list.get(i), result);
return result;
}
|
97f870db-327a-48de-bf36-1d45af7ba2ad
| 1
|
void draw(Graphics2D g) {
this.g = g;
if (Main.SELECTED_SUBJECT != null) {
reversDrawSubject(Main.SELECTED_SUBJECT, null, GCENTER);
} else {
drawSubject(Main.system, GCENTER);
}
drawRuler(100, 1050, 540);
}
|
4287a8ac-0e63-4fe4-84da-19033856ea9e
| 4
|
private void writeKeywordFile(String[] keywords, boolean black) {
String temp = (black? "": ": ");
for (String s: keywords) { temp += s+", "; }
try {
if(!black){
out = new BufferedWriter(new FileWriter(fileName+"KeywordsList.txt",true));
out.append(fm.format(new Date())+temp+"\n");
}else{
out = new BufferedWriter(new FileWriter(fileName+"BlackList.txt"));
out.append(temp);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
|
a8378e7a-1528-44db-9d05-f36b10320fbc
| 3
|
public void repaintTripleBuffer(Rectangle clip)
{
if (tripleBuffered && tripleBufferGraphics != null)
{
if (clip == null)
{
clip = new Rectangle(tripleBuffer.getWidth(),
tripleBuffer.getHeight());
}
// Clears and repaints the dirty rectangle using the
// graphics canvas of the graph component as a renderer
mxUtils.clearRect(tripleBufferGraphics, clip, null);
tripleBufferGraphics.setClip(clip);
paintGraph(tripleBufferGraphics);
tripleBufferGraphics.setClip(null);
repaintBuffer = false;
repaintClip = null;
}
}
|
f62eb2cf-2b7f-49f7-9cd3-82fea07e1d22
| 9
|
public String getCurrentLightConditions(DemonstratorMain main, String dbName, boolean useJSON, LocalTime currentTime){
String lightConditions = "";
try {
//time since last update of the solar altitude (times for sunrise and sunset)
long diffInHours = Duration.between(lastUpdateSolarAltitude, LocalDateTime.now(Clock.systemUTC())).toHours();
//if times for sunrise and sunset are unknown or "older" than interval-time
if ((sunrise == null || sunset == null) || diffInHours > updateIntervalSolarAltitude) {
String sunriseSunsetJSON = "";
if (DemonstratorMain.mongoDBConnection != null && !useJSON){
sunriseSunsetJSON = DemonstratorMain.mongoDBConnection.getCurrentSunsetSunriseTimes(dbName);
}
else{
sunriseSunsetJSON = main.jsonParser.getJSONMessage("sunTimes.json");
}
if(!sunriseSunsetJSON.isEmpty()){
JSONObject sunriseSunsetJSONObject = (JSONObject) main.jsonParser.myParser.parse(sunriseSunsetJSON);
Utils.printWithDate("Sunrise/Sunset:" + sunriseSunsetJSONObject, Utils.DEBUGLEVEL.DEBUG);
//Date Format: 2014-10-29T06:01:43.823Z
DateTimeFormatter myDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
sunrise = LocalDateTime.parse(main.jsonParser.getDataFromSunTimesJSON(sunriseSunsetJSONObject, "sunriseEnd"), myDateTimeFormat).toLocalTime();
sunset = LocalDateTime.parse(main.jsonParser.getDataFromSunTimesJSON(sunriseSunsetJSONObject, "sunsetStart"), myDateTimeFormat).toLocalTime();
lightConditions = new TimeInterpreter().getCurrentLightConditionsOutdoors(sunrise, sunset, currentTime);
Utils.printWithDate("Current light condition (outdoors): " + lightConditions, Utils.DEBUGLEVEL.GENERAL);
lastUpdateSolarAltitude = LocalDateTime.now(Clock.systemUTC());
}
//no information
else if (sunrise == null || sunset == null){
Utils.printWithDate("No updated times for sunrise and sunset received", Utils.DEBUGLEVEL.DEBUG);
lightConditions = "";
}
//old information
else{
Utils.printWithDate("No updated times for sunrise and sunset received. Use old times.", Utils.DEBUGLEVEL.DEBUG);
lightConditions = new TimeInterpreter().getCurrentLightConditionsOutdoors(sunrise, sunset, currentTime);
Utils.printWithDate("Current light condition (outdoors): " + lightConditions + " (lastUpdate(Sunrise/Sunset) " + diffInHours + " hours ago)", Utils.DEBUGLEVEL.GENERAL);
}
}
else{
lightConditions = new TimeInterpreter().getCurrentLightConditionsOutdoors(sunrise, sunset, currentTime);
Utils.printWithDate("Current light condition at (outdoors): " + lightConditions + " (lastUpdate(Sunrise/Sunset) " + diffInHours + " hours ago)", Utils.DEBUGLEVEL.GENERAL);
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lightConditions;
}
|
49a22de7-ec9c-4f82-800a-f92a20f69bb9
| 1
|
private List<String> parseParameterTypes(String signature) {
int positionOfParameterStart = signature.indexOf("(");
int positionOfParameterEnd = signature.indexOf(")");
String allParams = signature.substring(positionOfParameterStart + 1,
positionOfParameterEnd);
String[] paramsInArray = allParams.split(",");
List<String> parameters = new ArrayList<String>();
for(String parameter : paramsInArray) {
parameters.add(parameter.trim());
}
return parameters;
}
|
b3a182a8-8f22-465e-8a6a-f10cd8f0f147
| 1
|
private ServerSocket createServerSocket() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(this.serverInfo.getPort());
this.log.info("create Server Socket: " + serverSocket.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
serverSocket = null;
this.log.severe("create Server Socket: fail IOException");
}
return serverSocket;
}
|
66769c6d-65d9-44d8-ab6e-a44cd5dd666c
| 4
|
public void keyPressed(KeyEvent event) {
// println("You pressed: " + event.getKeyCode() + ", " + event.getKeyChar());
if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0);
} else if (event.getKeyCode() == KeyEvent.VK_ENTER) {
lab.genNewLab();
render();
} else if (event.getKeyCode() == KeyEvent.VK_P) {
AStar.findPath(1, 1, 38, 28, lab.getWalkways());
render();
} else if (event.getKeyCode() == KeyEvent.VK_R) {
clearPath();
render();
}
}
|
f64779ec-6e9e-4939-8d4c-7b744c3783c0
| 2
|
private Route contrueerRoute(RouteMetaData routemd[][], Knooppunt eind) {
Route korsteRoute = null;
if (routemd[eind.rij][eind.kol] != null) {
korsteRoute = new Route();
Knooppunt huidig = eind;
while (huidig != null) {
korsteRoute.prependKnooppunt(huidig);
huidig = routemd[huidig.rij][huidig.kol].vorigeStap;
}
}
return korsteRoute;
}
|
9a393aea-cffd-45a5-aae6-f0abe97c7520
| 9
|
@Override
public void simpleUpdate(float tpf) {
//For player movement and cam follow
Vector3f camDir = cam.getDirection().clone().multLocal(0.6f);
camDir.y*=0.3f;
camDir.normalize();
Vector3f camLeft = cam.getLeft().clone().multLocal(0.4f);
walkDirection.set(0, 0, 0);
if (left) { walkDirection.addLocal(camLeft); }
if (right) { walkDirection.addLocal(camLeft.negate()); }
if (up) { walkDirection.addLocal(camDir); }
if (down) { walkDirection.addLocal(camDir.negate()); }
playerManager.player_FP.characterControl.setWalkDirection(walkDirection);
cam.setLocation(playerManager.player_FP.characterControl.getPhysicsLocation());
//for 3d audio
listener.setLocation(cam.getLocation());
listener.setRotation(cam.getRotation());
//Calls relevant updates for the various types of targets
for(Spatial s:targetManager.targets){
if(s.getUserData("Animation")!=null){
switch((int)s.getUserData("Target_Type")){
case TARGET_TYPE_GHOST:
s.getControl(GhostControl.class).controlUpdate(tpf);
break;
case TARGET_TYPE_DROPTARGET:
s.getControl(TargetControl.class).controlUpdate(tpf);
break;
case TARGET_TYPE_PLAIN:
s.getControl(TargetControl.class).controlUpdate(tpf);
}
}
}
}// END OF SIMPLE UPDATE
|
3c4b96e3-b6b5-4cb8-9e0d-b5d6eff2a04b
| 7
|
private void processThreePlayerActions(AIConnection currentPlayer){
JSONObject first = currentPlayer.getNextMessage();
JSONObject second = currentPlayer.getNextMessage();
JSONObject third = currentPlayer.getNextMessage();
int validActions = 0;
if(letPlayerPerformAction(first, currentPlayer, 2)){
broadcastAction(first, currentPlayer);
validActions++;
if(Util.wasActionOffensive(first))
return;
}
else {Debug.debug("First action was invalid.");}
if(letPlayerPerformAction(second, currentPlayer, 1)){
broadcastAction(second, currentPlayer);
validActions++;
if(Util.wasActionOffensive(second))
return;
}
else {Debug.debug("Second action was invalid.");}
if(letPlayerPerformAction(third, currentPlayer, 0)){
broadcastAction(third, currentPlayer);
validActions++;
if(Util.wasActionOffensive(third))
return;
}
else {Debug.debug("Third action was invalid.");}
Debug.game("player " + currentPlayer.username + " performed " + validActions + " valid actions");
if(validActions == 0){
currentPlayer.givePenality(10);
}
}
|
19e7e416-31f0-4088-87f4-c9a2e6d3984a
| 2
|
public static void main(String[] args) throws FileNotFoundException {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream("D:\\chapter7_exceptions_test.txt");
System.out.println("File Opened...");
fileInputStream.read();
System.out.println("Read file...");
} catch (FileNotFoundException e) {
System.out.println("File not found exception");
/*
The 'finally' block will execute even if the code in a 'try', or 'catch' block defines a return statement.
There are however, a couple of scenarios where the 'finally' block will not be executed.
* Application termination: The 'try' or 'catch' executes System.exit, which terminates the application.
* Fatal errors: A crash of the JVM or the OS.
*/
return;
} catch (IOException e) {
System.out.println("File closing exception");
} finally {
System.out.println("finally...");
}
MultipleExceptions multipleExceptions = new MultipleExceptions();
System.out.println(multipleExceptions.getInt());
System.out.println(multipleExceptions.getIntModify());
// Rethrowing exceptions
rethrowException();
}
|
385cb53e-d440-46e7-be4d-e2a289b35791
| 3
|
public Config() {
File file = new File("config");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(file);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.getDocumentElement().normalize();
}
|
c684fb47-87db-456f-b996-00afcd521b8a
| 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 Ausencia)) {
return false;
}
Ausencia other = (Ausencia) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
|
c8a3007b-50ce-4520-96c2-d31b4ff46a8b
| 6
|
private <T> String getBeanName(Class<T> registeredClass) {
Class<?>[] interfaces = registeredClass.getInterfaces();
if (interfaces != null && interfaces.length > 0) {
for (Class<?> anInterface : interfaces) {
if (matchInterfaceClassName(registeredClass, anInterface)) {
return anInterface.getSimpleName();
}
}
}
return registeredClass.getSimpleName();
}
|
3d6e2001-5834-4392-908a-80746222e995
| 4
|
public static double jauPap(double a[] , double b[] )
{
double am, au[] = new double[3], bm, st, ct, xa, ya, za, eta[] = new double[3], xi[] = new double[3], a2b[] = new double[3], pa;
/* Modulus and direction of the a vector. */
NormalizedVector nv = jauPn(a );
am = nv.r; au = nv.u;
/* Modulus of the b vector. */
bm = jauPm(b);
/* Deal with the case of a null vector. */
if ((am == 0.0) || (bm == 0.0)) {
st = 0.0;
ct = 1.0;
} else {
/* The "north" axis tangential from a (arbitrary length). */
xa = a[0];
ya = a[1];
za = a[2];
eta[0] = -xa * za;
eta[1] = -ya * za;
eta[2] = xa*xa + ya*ya;
/* The "east" axis tangential from a (same length). */
xi = jauPxp(eta,au);
/* The vector from a to b. */
a2b = jauPmp(b, a);
/* Resolve into components along the north and east axes. */
st = jauPdp(a2b, xi);
ct = jauPdp(a2b, eta);
/* Deal with degenerate cases. */
if ((st == 0.0) && (ct == 0.0)) ct = 1.0;
}
/* Position angle. */
pa = atan2(st, ct);
return pa;
}
|
233b52b6-3c82-4e03-a89d-574a563e72d6
| 1
|
public void refresh(){
try {
questionDAO = new QuestionDAO();
List<SettingQuestion> questions = null;
questions = questionDAO.getAllQuestion();
QuestionTableModel model = new QuestionTableModel(questions);
questionTable.setModel(model);
setTable();
} catch (Exception exc) {
JOptionPane.showMessageDialog(this, "Error: " + exc, "Error", JOptionPane.ERROR_MESSAGE);
}
}
|
5241a7f3-1827-4a72-8845-82e86cb0b94b
| 6
|
public boolean skipField(final int tag) throws IOException {
switch (WireFormat.getTagWireType(tag)) {
case WireFormat.WIRETYPE_VARINT:
readInt32();
return true;
case WireFormat.WIRETYPE_FIXED64:
readRawLittleEndian64();
return true;
case WireFormat.WIRETYPE_LENGTH_DELIMITED:
skipRawBytes(readRawVarint32());
return true;
case WireFormat.WIRETYPE_START_GROUP:
skipMessage();
checkLastTagWas(
WireFormat.makeTag(WireFormat.getTagFieldNumber(tag),
WireFormat.WIRETYPE_END_GROUP));
return true;
case WireFormat.WIRETYPE_END_GROUP:
return false;
case WireFormat.WIRETYPE_FIXED32:
readRawLittleEndian32();
return true;
default:
throw InvalidProtocolBufferException.invalidWireType();
}
}
|
c71adeb0-8cf9-4c96-80e3-70d4b0865e98
| 2
|
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case '[':
controller.setBrushSize(controller.getBrushSize() - 1);
break;
case ']':
controller.setBrushSize(controller.getBrushSize() + 1);
break;
}
}
|
06fb6cca-feb3-44bd-9f61-b1a253257ad8
| 7
|
private void button_add_red_hitboxMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button_add_red_hitboxMousePressed
if(frame_index_selected!=-1)
{
if(current_frame==null)
{
Element new_frame = hitboxes_doc.createElement("Frame");
new_frame.setAttribute("number", ""+(frame_index_selected+1));
if(current_move==null)
{
Element new_move = hitboxes_doc.createElement("Move");
new_move.setAttribute("name", ""+list_moves.getSelectedValue());
hitboxes_doc.getFirstChild().appendChild(new_move);
current_move=new_move;
}
current_move.appendChild(new_frame);
current_frame=new_frame;
}
int i=0;
boolean hitboxes_exist=false;
for(Node hitboxes_node=current_frame.getFirstChild();hitboxes_node!=null;hitboxes_node=hitboxes_node.getNextSibling())//Hitbox loop
{
if(hitboxes_node.getNodeName().equals("Hitboxes"))
{
if(((Element)hitboxes_node).getAttribute("variable").equals("red"))
{
hitboxes_exist=true;
Element new_hitbox = hitboxes_doc.createElement("Hitbox");
new_hitbox.setAttribute("x1", ""+spinner_x1.getValue());
new_hitbox.setAttribute("y1", ""+spinner_y1.getValue());
new_hitbox.setAttribute("x2", ""+spinner_x2.getValue());
new_hitbox.setAttribute("y2", ""+spinner_y2.getValue());
hitboxes_node.appendChild(new_hitbox);
}
}
}
if(!hitboxes_exist)
JOptionPane.showMessageDialog(null, "Create a clean hitboxes list before.", "Be careful", JOptionPane.INFORMATION_MESSAGE);
updateHitboxes(current_frame);
}
else
{
JOptionPane.showMessageDialog(null, "Select a frame first.", "Be careful", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_button_add_red_hitboxMousePressed
|
577d2473-7f63-4474-93e5-5302048fd1ab
| 3
|
public int addSoundtrack(OggAudioHeaders audio) {
if (w == null) {
throw new IllegalStateException("Not in write mode");
}
// If it doesn't have a sid yet, get it one
OggPacketWriter aw = null;
if (audio.getSid() == -1) {
aw = ogg.getPacketWriter();
// TODO How to tell the OggAudioHeaders the new SID?
} else {
aw = ogg.getPacketWriter(audio.getSid());
}
int audioSid = aw.getSid();
// If we have a skeleton, tell it about the new stream
if (skeleton != null) {
SkeletonFisbone bone = skeleton.addBoneForStream(audioSid);
bone.setContentType(audio.getType().mimetype);
// TODO Populate the rest of the bone as best we can
}
// Record the new audio stream
soundtracks.put(audioSid, (OggAudioStreamHeaders)audio);
soundtrackWriters.put((OggAudioStreamHeaders)audio, aw);
// Report the sid
return audioSid;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.