text stringlengths 14 410k | label int32 0 9 |
|---|---|
public int hashCode() {
int h = instanceOrClass.hashCode();
h += method.hashCode();
if (n > 0) {
h += (arg1 == null ? 0 : arg1.hashCode());
if (n > 1) {
h += (arg2 == null ? 0 : arg2.hashCode());
if (n > 2) {
h += (arg3 == null ? 0 : arg3.hashCode());
if (n > 3) {
for (int i = 5; i < n + 2; i++) {
h += (moreThanThree[i] == null ? 0 : moreThanThree[i].hashCode());
}
}
}
}
}
return h;
} | 9 |
public static String getString(String domain, String key, String fallback)
{
if ( !config.containsKey(domain) )
config.put(domain, new HashMap<String,String>());
if ( !config.get(domain).containsKey(key) )
config.get(domain).put(key, fallback);
return config.get(domain).get(key);
} | 2 |
@Override
public void deserialize(Buffer buf) {
super.deserialize(buf);
targetId = buf.readInt();
casterCellId = buf.readShort();
if (casterCellId < -1 || casterCellId > 559)
throw new RuntimeException("Forbidden value on casterCellId = " + casterCellId + ", it doesn't respect the following condition : casterCellId < -1 || casterCellId > 559");
targetCellId = buf.readShort();
if (targetCellId < -1 || targetCellId > 559)
throw new RuntimeException("Forbidden value on targetCellId = " + targetCellId + ", it doesn't respect the following condition : targetCellId < -1 || targetCellId > 559");
} | 4 |
@Override
protected boolean executeGameEvents(Integer[] events) {
if(events == null){
events = new Integer[0];
}
for(Integer event : events){
switch (event) {
case EVENT_START_GAME:{
break;
}
case EVENT_SHOW_COUNTDOWN:{
break;
}
case EVENT_MATCH_OVER:{
endMatch();
break;
}
default:
break;
}
}
return events.length > 0;
} | 5 |
protected List<Node> generateSuccessors(Node node) {
List<Node> ret = new LinkedList<Node>();
int x = node.x;
int y = node.y;
if (y < map.length - 1 && map[y + 1][x] == 1) {
ret.add(new Node(x, y + 1));
}
if (x < map[0].length - 1 && map[y][x + 1] == 1) {
ret.add(new Node(x + 1, y));
}
if (y > 0 && map[y - 1][x] == 1) {
ret.add(new Node(x, y - 1));
}
if (x > 0 && map[y][x - 1] == 1) {
ret.add(new Node(x - 1, y));
}
return ret;
} | 8 |
void syncToDB() {
Map<K, Modification> toMods = mods;
mods = new ConcurrentHashMap<>();
new Thread(() -> {
for (Map.Entry<K, Modification> entry : toMods.entrySet()) {
K k = entry.getKey();
Modification modification = entry.getValue();
if (modification.isPut) {
synchronizer.put(k, modification.value);
} else {
synchronizer.remove(k, modification.value);
}
}
}).start();
} | 2 |
public void actionPerformed(ActionEvent e) {
SelectionDrawer drawer = new SelectionDrawer(automaton);
NondeterminismDetector d = NondeterminismDetectorFactory
.getDetector(automaton);
State[] nd = d.getNondeterministicStates(automaton);
for (int i = 0; i < nd.length; i++)
drawer.addSelected(nd[i]);
AutomatonPane ap = new AutomatonPane(drawer);
NondeterminismPane pane = new NondeterminismPane(ap);
environment.add(pane, "Nondeterminism", new CriticalTag() {
});
environment.setActive(pane);
} | 1 |
public static boolean handleSurvivalExceptions(ArrayList<String[]> clinicalValues){
boolean valid = true;
HashSet<String> vitals = new HashSet<String>();
for (int i=0; i<clinicalValues.size(); i++){
if (clinicalValues.get(i).length<3){
System.err.println("Please enter 3 columns for log rank");
return false;
}
if (clinicalValues.get(i)[1]!=null){
if (!clinicalValues.get(i)[1].isEmpty()){
vitals.add(clinicalValues.get(i)[1]);
}
}
//System.out.println(clinicalValues.get(i)[1]);
if (vitals.size() > 2){
System.err.println("INPUT ERROR: Vital Status must be either DECEASED or ALIVE");
return false;
}
if (clinicalValues.get(i)[2]!=null){
if (!clinicalValues.get(i)[2].equals("NA")){
try{
Double.valueOf(clinicalValues.get(i)[2]);
}
catch (Exception e){
valid = false;
}
}
}
}
if (valid == false){
System.err.println("INPUT ERROR: All days followup entries must be a number");
}
return valid;
} | 9 |
public static String reverseComlement(String str){
char[] dna = str.toCharArray();
char[] dnaReverseComplement = new char[dna.length];
int j = 0;
for (int i = dna.length-1; i >=0 ; i--) {
switch (dna[i]) {
case 'A' : dnaReverseComplement[j] = 'T';break;
case 'T' : dnaReverseComplement[j] = 'A';break;
case 'C' : dnaReverseComplement[j] = 'G';break;
case 'G' : dnaReverseComplement[j] = 'C';break;
}
j++;
}
return new String(dnaReverseComplement);
} | 5 |
public void hyperMutate(int mutations, Random rand) {
int mutationsDone = 0;
while (mutationsDone < mutations) {
int indexA = rand.nextInt(projectSize);
int indexB = rand.nextInt(projectSize);
if (indexA == indexB) {
if (indexB == projectSize-1)
indexB--;
else
indexB++;
}
ArrayList<WorkUnit> personWorkList = personWorkLists.get(
rand.nextInt(projectSize)
);
Collections.swap(personWorkList, indexA, indexB);
if (rand.nextDouble() < 0.4) {
personWorkList = personWorkLists.get(
rand.nextInt(projectSize)
);
int distance = rand.nextInt(projectSize-1);
int positive = 1;
if (rand.nextBoolean())
positive = -1;
Collections.rotate(personWorkList, positive*distance);
}
mutationsDone++;
}
} | 5 |
public void binaryFilter(double cutOff, double value) {
for(int i=0; i < data.length; i++) {
double[] block = data[i];
for(int j=0; j < block.length; j++) {
block[j] = (block[j] >= cutOff ? 1.0 : 0.0) * value;
}
}
} | 3 |
@Override
public void toFtanML(Writer writer) {
try {
//Calculate count of double quotation marks (") and single quotation marks (') in the string
int numberDQuotes = 0;
int numberSQuotes = 0;
for (int i=0;i<value.length();++i) {
switch (value.charAt(i)) {
case '"':
++numberDQuotes;
break;
case '\'':
++numberSQuotes;
break;
}
}
//Use the quotation mark that causes less escaping
char usedQuote = (numberDQuotes<=numberSQuotes)?'"':'\'';
//Output the escaped string
writer.append(usedQuote + escape(value, usedQuote) + usedQuote);
} catch (IOException e) {
throw new IllegalStateException(e);
}
} | 5 |
static LookAndFeel getFactory(CHOICE choice) {
switch (choice) {
case WINDOWS:
lookAndFeel = new WindowsLookAndFeel();
break;
case MOTIF:
lookAndFeel = new MotifLookAndFeel();
break;
}
return lookAndFeel;
} | 2 |
public static void expand() {
boolean bit = false;
while (!BinaryStdIn.isEmpty()) {
int run = BinaryStdIn.readInt(lgR); // read lgR bit
for (int i = 0; i < run; i ++)
BinaryStdOut.write(bit);
bit = !bit;
}
BinaryStdOut.close();
} | 2 |
private static void exerciseList(List<MutableTypes> list, long length, Runnable setSize) {
assertEquals(length, list.size());
gcPrintUsed();
long start = System.currentTimeMillis();
do {
System.out.println("Updating");
long startWrite = System.nanoTime();
setSize.run();
populate(list);
int i;
long timeWrite = System.nanoTime() - startWrite;
System.out.printf("Took %,d ns per object write%n", timeWrite / list.size());
if (list.get(64).getInt() == 64)
assertEquals("MutableTypes{boolean=true, boolean2=true, byte=64, byte2=64, char=@, double=64.0, elementType=TYPE, float=64.0, int=64, long=64, short=64, string=64}"
, list.get(64).toString());
if (list instanceof HugeArrayList)
try {
((HugeArrayList) list).flush();
} catch (IOException e) {
throw new AssertionError(e);
}
System.out.println("Checking");
long startRead = System.nanoTime();
validate(list);
long timeRead = System.nanoTime() - startRead;
System.out.printf("Took %,d ns per object read/check%n", timeRead / list.size());
long scanStart = System.nanoTime();
for (MutableTypes mb : list) {
if (mb.getInt() == list.size() - 1)
break;
}
long scanTime = System.nanoTime() - scanStart;
System.out.printf("Took %,d ns per field to scan%n", scanTime / list.size());
long randomStart = System.nanoTime();
for (int n = list.size() / 100, len = list.size(), p = 0; n > 0; n--) {
p = (p + 101912) % len;
final MutableTypes mt = list.get(p);
validate(mt, (int) (p + length));
if (list instanceof HugeArrayList)
((HugeArrayList) list).recycle(mt);
}
long randomTime = System.nanoTime() - randomStart;
System.out.printf("Took %,d ns per object to access randomly%n", randomTime * 100 / list.size());
System.gc();
} while (System.currentTimeMillis() - start < 10 * 1000);
System.out.println("Finished");
} | 8 |
protected void interrupted() {
end();
} | 0 |
public static JTableRenderer getVertex(Component component)
{
while (component != null)
{
if (component instanceof JTableRenderer)
{
return (JTableRenderer) component;
}
component = component.getParent();
}
return null;
} | 2 |
public static final void exampleContantsManipulations() {
System.out.println("Starting Cyc constant manipulation examples.");
try {
CycConstant cycAdministrator = access.getKnownConstantByName("CycAdministrator");
CycConstant generalCycKE = access.getKnownConstantByName("GeneralCycKE");
access.setCyclist(cycAdministrator); // needed to maintain bookeeping information
access.setKePurpose(generalCycKE); // needed to maintain bookeeping information
// obtaining a constant from its external ID (preferred mechanism for lookup)
CycConstant dog = (CycConstant) DefaultCycObject.fromCompactExternalId("Mx4rvVjaoJwpEbGdrcN5Y29ycA", access);
// obtaining an external id from a CycObject
String externalId = DefaultCycObject.toCompactExternalId(dog, access);
// obtaining a constant from its name
// Note: not preferred, because constant names can change in the KB
// which would require all the code references to be modified to
// maintain correct behavior
CycConstant dog2 = access.getKnownConstantByName("Dog");
// obtain comments for a CycConstant
String comment = access.getComment(dog);
System.out.println("Got comments for constant Dog:\n" + comment);
// creating a constant
CycConstant newTypeOfDog = access.findOrCreate("NewTypeOfDog");
// asserting the isa and genls relations
// every new term should have at least 1 isa assertion made on it
access.assertIsa(newTypeOfDog, CycAccess.collection, CycAccess.baseKB);
// every new collection should have at least 1 genls assertion made on it
access.assertGenls(newTypeOfDog, dog, CycAccess.baseKB);
// verify genls relation
assert access.isSpecOf(newTypeOfDog, dog, CycAccess.baseKB) : "Good grief! Our new type of dog isn't known to be a type of dog.";
// find everything that is a dog
System.out.println("Got instances of Dog: " + access.getAllInstances(dog, CycAccess.baseKB));
// find everything that a dog is a type of
System.out.println("Got generalizations of Dog: " + access.getAllGenls(dog, CycAccess.baseKB));
// find everything that is a type of dog
System.out.println("Got specializations of Dog: " + access.getAllSpecs(dog, CycAccess.baseKB));
// generating NL
String dogNl = access.getGeneratedPhrase(dog);
System.out.println("The concept " + dog.cyclify()
+ " can be referred to in English as '" + dogNl + "'.");
// Killing a constant -- removing a constant and all assertions involving that constant
// Warning: you can potentially do serious harm to the KB if you remove critical information
access.kill(newTypeOfDog);
} catch (UnknownHostException nohost) {
nohost.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} catch (CycApiException cyc_e) {
cyc_e.printStackTrace();
}
System.out.println("Finished.");
} | 3 |
public void run() {
for(int i = 1 ; i < 100 ; i ++)
{
System.out.println("Runnable implements Thread " + i + " !");
}
} | 1 |
public static String camel4underline(String param) {
Pattern p = Pattern.compile("[A-Z]");
if (param == null || param.equals("")) {
return "";
}
StringBuilder builder = new StringBuilder(param);
Matcher mc = p.matcher(param);
int i = 0;
while (mc.find()) {
builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
i++;
}
if ('_' == builder.charAt(0)) {
builder.deleteCharAt(0);
}
return builder.toString();
} | 4 |
public static boolean BookingCollides(int cabin_id, Date from_date, Date to_date) {
Database db = new Database();
ArrayList<Booking> bookings = db.getBooking(cabin_id);
db.close();
for(Booking b : bookings) {
if(to_date.compareTo(b.getDate_To()) <= 0 && to_date.compareTo(b.getDate_From()) >= 0)
return true;
else if(from_date.compareTo(b.getDate_To()) <= 0 && from_date.compareTo(b.getDate_From()) >= 0)
return true;
}
return false;
} | 5 |
public void setParams(Object params) {
this.params = params;
} | 0 |
protected void generateMetaLevel(Instances newData, Random random)
throws Exception {
m_MetaFormat = metaFormat(newData);
Instances [] metaData = new Instances[m_Classifiers.length];
for (int i = 0; i < m_Classifiers.length; i++) {
metaData[i] = metaFormat(newData);
}
for (int j = 0; j < m_NumFolds; j++) {
Instances train = newData.trainCV(m_NumFolds, j, random);
Instances test = newData.testCV(m_NumFolds, j);
// Build base classifiers
for (int i = 0; i < m_Classifiers.length; i++) {
getClassifier(i).buildClassifier(train);
for (int k = 0; k < test.numInstances(); k++) {
metaData[i].add(metaInstance(test.instance(k),i));
}
}
}
// calculate InstPerClass
m_InstPerClass = new double[newData.numClasses()];
for (int i=0; i < newData.numClasses(); i++) m_InstPerClass[i]=0.0;
for (int i=0; i < newData.numInstances(); i++) {
m_InstPerClass[(int)newData.instance(i).classValue()]++;
}
m_MetaClassifiers = Classifier.makeCopies(m_MetaClassifier,
m_Classifiers.length);
for (int i = 0; i < m_Classifiers.length; i++) {
m_MetaClassifiers[i].buildClassifier(metaData[i]);
}
} | 7 |
public static void appendHostAddress(StringBuilder sbuf, InetAddress addr) {
if (addr == null) {
throw new IllegalArgumentException("addr must not be null");
}
if (!(addr instanceof Inet4Address)) {
throw new IllegalArgumentException("addr must be an instance of Inet4Address");
}
byte[] src = addr.getAddress();
sbuf.append(src[0] & 0xFF)
.append('.')
.append(src[1] & 0xFF)
.append('.')
.append(src[2] & 0xFF)
.append('.')
.append(src[3] & 0xFF);
} | 2 |
private void appendDigits(String digits,int digitIndex,List<String> list,StringBuffer letter){
if(digitIndex == digits.length()){
list.add(letter.toString());
return;
}
int index= digits.charAt(digitIndex)-48;
String buttonString = board[index];
System.out.println(buttonString);
for(int i=0;i<buttonString.length();i++){
letter.append(buttonString.charAt(i));
appendDigits(digits,digitIndex+1,list,letter);
}
} | 2 |
protected void initRunnableTask() {
if(taskThread != null) {
new IllegalStateException("The Task Thread has already been created");
}
//Create the Thread but don't start it
if(progressDescriptor.getRunnableTask() != null) {
taskThread = new Thread(progressDescriptor.getRunnableTask());
}
//Add a Listener to start the Thread when the Dialog is Opened
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
//stop spinner
if(progressDescriptor.getIconComp() instanceof BusySpinner) {
((BusySpinner)progressDescriptor.getIconComp()).stop();
}
}
public void windowOpened(WindowEvent e) {
//start spinner
if(progressDescriptor.getIconComp() instanceof BusySpinner) {
((BusySpinner)progressDescriptor.getIconComp()).start();
}
//bail early if no taskThred
if(taskThread == null) return;
if(!taskThread.isAlive()) {
taskThread.start();
//Wait for Completion and then dispose org.xito
if(progressDescriptor.disposeOnComplete()) {
Thread waitThread = new Thread(){
public void run() {
try {
taskThread.join();
}
catch(InterruptedException exp) {
System.out.println("Interrupted Wait Thread!");
}
ProgressDialog.this.dispose();
taskThread = null;
}
};
waitThread.start();
}
}
}
});
} | 8 |
static int entrance() {
int x = 0, y = 0;
for (int i = 0; i < layout.length; ++i)
for (int j = 0; j < layout[i].length; ++j) {
if (layout[i][j] == 2) {
x = i;
y = j;
break;
}
}
leastTime[x][y] = 0;
List<Point> resetPoints = new ArrayList<>(layout.length);
List<Point> endPoint = new ArrayList<>(1);
resetPoints.add(new Point(x, y));
while (!resetPoints.isEmpty()) {
List<Point> nextResetPoints = new ArrayList<>(layout.length);
for(Point point : resetPoints){
babyRun(point.x,point.y,leastTime[point.x][point.y],0,nextResetPoints,endPoint);
}
if(!endPoint.isEmpty()){
Point end=endPoint.get(0);
return leastTime[end.x][end.y];
}
resetPoints=nextResetPoints;
}
return -1;
} | 6 |
public boolean play(Player player) {
System.out.println("Welcome to Sudoku!\nYour goal is to fill your board up with numbers 1-9 while abiding by the following rules: in each row there can be no repeated numbers, in each column there can be no repeated numbers, and in each square (3x3 space alloted) there can be no repeated numbers. Use the numbers you have been given to your advantage, good luck!");
pause(6);
setUp();
System.out.println(this);
while (stillRoom() && _wantPlay) {
round();
if (_roundCnt != 0 && _roundCnt % 6 == 0) {
if (giveUp()) {
System.out.println("Game Over! You lose!");
return false;
}
}
}
System.out.println("Congrats, you win!");
return true;
} | 5 |
public static long inet_pton(String ip) {
if (ip == null) return -1;
long f1, f2, f3, f4;
String tokens[] = ip.split("\\.");
if (tokens.length != 4) return -1;
try {
f1 = Long.parseLong(tokens[0]) << 24;
f2 = Long.parseLong(tokens[1]) << 16;
f3 = Long.parseLong(tokens[2]) << 8;
f4 = Long.parseLong(tokens[3]);
return f1+f2+f3+f4;
} catch (Exception e) {
return -1;
}
} | 3 |
public void startElement(String uri, String localName, String qName, Attributes attributes){
if(qName.equals("objects")){
uiElements = new LinkedList<UIElement>();
}
else if(qName.equals("label")){
element = new Label();
element.setType("label");
}
else if(qName.equals("button")){
button = new Button();
element = button;
element.setType("button");
}
else if(qName.equals("input")){
input = new Input();
button = input;
element = button;
element.setType("input");
}
else {
buffer = new StringBuffer();
}
} | 4 |
public static boolean handlePawnJump(){
boolean shouldCallContinue = false; // Returns whether the while loop should skip the current iteration
if (target == null && chosen.getType().equals("PAWN") && !chosen.hasMoved() && Math.abs(myYCoor - targYCoor) == 2 && chosen.validMovement(myXCoor, myYCoor, targXCoor, targYCoor, board)){
board.set(targXCoor, targYCoor, chosen);
board.set(myXCoor, myYCoor, null);
if (kingCheckedAfterMove()){
board.set(myXCoor,myYCoor,board.set(targXCoor,targYCoor,target)); // Return pieces to original position by swapping
loopRound();
shouldCallContinue = true;
}
else{
System.out.println(clearScreen() + "Successful move: " + chosen + " (" + myXCoor + "," + myYCoor + ") to (" + targXCoor + "," + targYCoor + ").\n");
advanceRound();
((Pawn)chosen).setLastPawnJump(true);
shouldCallContinue = true;
}
}
return shouldCallContinue;
} | 6 |
public void testMonthNames_monthMiddle() {
DateTimeFormatter printer = DateTimeFormat.forPattern("MMMM");
for (int i=0; i<ZONES.length; i++) {
for (int month=1; month<=12; month++) {
DateTime dt = new DateTime(2004, month, 15, 12, 20, 30, 40, ZONES[i]);
String monthText = printer.print(dt);
assertEquals(MONTHS[month], monthText);
}
}
} | 2 |
public void setPrice(int price)
{
this.price = price;
notifyListeners();
} | 0 |
public User authenticate(String login, String password, HttpServletRequest request) throws BusinessException {
// TODO ver um padrõa de projeto para isso tipo fabrica.
User user = null;
user = userDAO.findOneByField("login", "=", login);
try {
// Usuário informou um login valido
if(user != null) {
// Caso a autenticação esteja correta
if(this.applyHash(password, user.getSaltAgent()).equals(user.getPassword())) {
if(!checkStatus(user)) {
this.registerAccess(AccessEntry.TYPE_BLOCKED, login, password, request);
throw new BusinessException(MessageBundleUtils.getInstance().getMessage("login.error.acessDenied.blocked"), FacesMessage.SEVERITY_ERROR);
} else {
this.registerAccess(AccessEntry.TYPE_SUCESSED, login, password, request);
return user;
}
// O usuário errou apenas a senha
} else {
this.registerAccess(AccessEntry.TYPE_DENIED, login, password, request);
if(this.updateLoginAttempt(user)) {
throw new BusinessException(MessageBundleUtils.getInstance().getMessage("login.error.acessDenied.gotBlocked"), FacesMessage.SEVERITY_ERROR);
} else {
// TODO arrumar um jeito de parametrizar mensagens pelo addMensage/
// Ter cuidado com validação de crosside script
throw new BusinessException("Acesso Negado: dados inválidos, restão apenas " + user.getLoginAttempt() + " tentativas", FacesMessage.SEVERITY_ERROR);
}
}
}
} catch (EncryptionException e) {
e.printStackTrace();
throw new BusinessException(MessageBundleUtils.getInstance().getMessage("system.error.generic"), e);
}
// Não existe usuário com o login informado
this.registerAccess(AccessEntry.TYPE_DENIED, login, password, request);
throw new BusinessException(MessageBundleUtils.getInstance().getMessage("login.error.acessDenied"), FacesMessage.SEVERITY_ERROR);
} | 5 |
@Override
public boolean allowSource( ConnectionableCapability item, ConnectionFlavor flavor ) {
return item != this || allowSelfReference( flavor );
} | 1 |
public int getAddiction(String player, Column column) {
String query = "SELECT * FROM nosecandy WHERE playername='" + player + "';";
ResultSet result = null;
result = this.sqlite.query(query);
try {
if (result != null && result.next()) {
String name = result.getString("playername");
int addiction = result.getInt(column.getName());
if (name.equals(player)) {
result.close();
return addiction;
}
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
} | 5 |
public boolean playerIsAffected(Player player) // returns whether or not a player is currently affected by Arctica
{
boolean affected = false;
if((null != player ) &&
(playersToAffect.contains(player.getName())))
{
affected = true;
}
return (affected);
} | 2 |
public final TLParser.andExpr_return andExpr() throws RecognitionException {
TLParser.andExpr_return retval = new TLParser.andExpr_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal112=null;
TLParser.equExpr_return equExpr111 = null;
TLParser.equExpr_return equExpr113 = null;
Object string_literal112_tree=null;
try {
// src/grammar/TL.g:147:3: ( equExpr ( '&&' equExpr )* )
// src/grammar/TL.g:147:6: equExpr ( '&&' equExpr )*
{
root_0 = (Object)adaptor.nil();
pushFollow(FOLLOW_equExpr_in_andExpr1042);
equExpr111=equExpr();
state._fsp--;
adaptor.addChild(root_0, equExpr111.getTree());
// src/grammar/TL.g:147:14: ( '&&' equExpr )*
loop20:
do {
int alt20=2;
int LA20_0 = input.LA(1);
if ( (LA20_0==And) ) {
alt20=1;
}
switch (alt20) {
case 1 :
// src/grammar/TL.g:147:15: '&&' equExpr
{
string_literal112=(Token)match(input,And,FOLLOW_And_in_andExpr1045);
string_literal112_tree = (Object)adaptor.create(string_literal112);
root_0 = (Object)adaptor.becomeRoot(string_literal112_tree, root_0);
pushFollow(FOLLOW_equExpr_in_andExpr1048);
equExpr113=equExpr();
state._fsp--;
adaptor.addChild(root_0, equExpr113.getTree());
}
break;
default :
break loop20;
}
} while (true);
}
retval.stop = input.LT(-1);
retval.tree = (Object)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
}
return retval;
} | 4 |
public boolean isInterleave(String s1, String s2, String s3) {
if (s1.length() + s2.length() != s3.length()) {
return false;
}
boolean[] m = new boolean[s1.length() + 1];
m[0] = true;
for (int i = 1; i <= s1.length(); i++) {
m[i] = m[i - 1] && s3.charAt(i - 1) == s1.charAt(i - 1);
}
for (int i = 1; i <= s2.length(); i++) {
m[0] = m[0] && s3.charAt(i - 1) == s2.charAt(i - 1);
for (int j = 1; j <= s1.length(); j++) {
m[j] = (m[j - 1] && s1.charAt(j - 1) == s3.charAt(i + j - 1))
|| (m[j] && s2.charAt(i - 1) == s3.charAt(i + j - 1));
}
}
return m[s1.length()];
} | 9 |
public void leave(String address) {
for (int i = 0; i < size(); i++) {
if (getNode(i).getAddress().equals(address)) {
notifySuccessor(getSuccessor(getNode(i)), getNode(i).getKeys());
nodeList.remove(i);
}
}
} | 2 |
public void unpackBuild() throws Throwable
{
File configBackupDir = new File("config_backup");
File modsBackupDir = new File("mods_backup");
if (configBackupDir.exists())
FileUtils.deleteDirectory(configBackupDir);
if (modsBackupDir.exists())
FileUtils.deleteDirectory(modsBackupDir);
File configDir = new File("config");
File modsDir = new File("mods");
if (configDir.exists())
configDir.renameTo(new File("config_backup"));
if (modsDir.exists())
modsDir.renameTo(new File("mods_backup"));
ZipFile build = new ZipFile(new File("build.hoppix"));
build.extractAll(".");
File readme = new File("readme.txt");
if (readme.exists())
{
readme.delete();
}
} | 5 |
private void assertMe() {
assert x != 0 || y != 0;
assert x == 0 || x == 1 || x== -1;
assert y == 0 || y == 1 || y == -1;
} | 5 |
public SubsetSum(int[] arr) {
int sum = Comparison.SUM(arr);
System.out.println("Sum "+sum);
int m[][] = new int[arr.length][sum+1];
for(int i=0;i<arr.length;i++)
m[i][arr[i]] = 1;
for(int j = 0;j<=sum;j++){
for(int i=1;i<arr.length;i++){
if(j == arr[i]){
m[i][j]=1;
continue;
}
int sumWithoutThisI = Comparison.MAX(j-arr[i],0);
m[i][j] = Comparison.MAX(m[i-1][j], m[i-1][sumWithoutThisI]);
}
}
Comparison.PRINT(m);
int halfSum = sum/2;
int diff = Integer.MAX_VALUE;
int subSet = 0;
for(int i=0;i<arr.length;i++){
for(int j=halfSum;j>=0;j--){
if(m[i][j]==1){
if((halfSum-j)<diff){
diff = halfSum - j;
subSet = i;
}
break;
}
}
}
System.out.println("Subset: "+subSet);
System.out.println("diff: "+diff);
} | 8 |
private void descargaProcedimiento(String nombre) {
int procACargar = 0;
while (!procedimientos.get(procACargar).getNombre().equals(nombre))
procACargar++;
for (int i = 0; i < procedimientos.get(procACargar).getvariablesEnterasL(); i++) {
contEntLoc.remove(contEntLoc.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesFlotantesL(); i++) {
contFlotLoc.remove(contFlotLoc.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesStringL(); i++) {
contStrLoc.remove(contStrLoc.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesBooleanasL(); i++) {
contBoolLoc.remove(contBoolLoc.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesEnterasT(); i++) {
contEntTmp.remove(contEntTmp.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesFlotantesT(); i++) {
contFlotTmp.remove(contFlotTmp.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesStringT(); i++) {
contStrTmp.remove(contStrTmp.size()-1);
}
for (int i = 0; i < procedimientos.get(procACargar).getvariablesBooleanasT(); i++) {
contBoolTmp.remove(contBoolTmp.size()-1);
}
} | 9 |
public void mostraDialegVictoria( String missatge )
{
boolean te_situacio_inicial = PresentacioCtrl.getInstancia().esPartidaAmbSituacioInicial();
try
{
PresentacioCtrl.getInstancia().finalitzaPartida();
}
catch ( Exception excepcio )
{
VistaDialeg dialeg_error = new VistaDialeg();
String[] botons_error = { "Accepta" };
dialeg_error.setDialeg( "Error", excepcio.getMessage(), botons_error, JOptionPane.WARNING_MESSAGE );
}
VistaDialeg dialeg = new VistaDialeg();
String[] botons;
if ( te_situacio_inicial )
{
botons = new String[] {
"Torna al menú principal",
};
}
else
{
botons = new String[] {
"Torna al menú principal",
"Partida de revenja"
};
}
String opcio = dialeg.setDialeg( "Partida finalitzada", missatge, botons, JOptionPane.INFORMATION_MESSAGE );
try
{
PresentacioCtrl.getInstancia().tancaPartida( opcio.equals( "Partida de revenja" ) );
}
catch ( Exception excepcio )
{
VistaDialeg dialeg_error = new VistaDialeg();
String[] botons_error = { "Accepta" };
dialeg_error.setDialeg( "Error", excepcio.getMessage(), botons_error, JOptionPane.ERROR_MESSAGE );
}
if ( opcio.equals( "Partida de revenja" ) )
{
PresentacioCtrl.getInstancia().regeneraPartidaVista();
}
else
{
PresentacioCtrl.getInstancia().vistaPartidaAMenuPrincipal();
}
} | 4 |
public void printBoard() {
for (int row = 0; row < board.getN(); row++) {
for (int col = 0; col < board.getN(); col++) {
if (board.get(row,col) == PLAYER1_VAL)
System.out.print(PLAYER1_CELL);
else if (board.get(row,col) == PLAYER2_VAL)
System.out.print (PLAYER2_CELL);
else
System.out.print(EMPTY_CELL);
if (col < (board.getN() - 1))
System.out.print(COL_SEPARATOR);
}
System.out.println();
if (row < (board.getN() - 1)) {
for (int i = 0; i < (2*board.getN()-1) ; i++)
System.out.print(ROW_SEPARATOR);
System.out.println();
}
}
System.out.println();
} | 7 |
public Object make(HGPersistentHandle handle,
LazyRef<HGHandle[]> targetSet, IncidenceSetRef incidenceSet)
{
HGPersistentHandle[] layout = graph.getStore().getLink(handle);
Pair<?,?> result = (Pair<?,?>)TypeUtils.getValueFor(graph, handle);
if (result != null)
return result;
Object first = null, second = null;
if (!layout[0].equals(graph.getHandleFactory().nullHandle()))
{
HGAtomType type = graph.getTypeSystem().getType(layout[0]);
first = TypeUtils.makeValue(graph, layout[1], type);
}
if (!layout[2].equals(graph.getHandleFactory().nullHandle()))
{
HGAtomType type = graph.getTypeSystem().getType(layout[2]);
//2012.01.24 hilpold BUGFIX old: first = TypeUtils.makeValue(graph, layout[3], type);
second = TypeUtils.makeValue(graph, layout[3], type);
}
result = new Pair<Object,Object>(first, second);
return result;
} | 7 |
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
//INITIALIZE THE PARAMETERS
initParams();
int listenerPort= 9898;
//ASSIGN MACHINE IDs
String fullMachineID = getFullMachineID();
String shortMachineID = getShortMachineID();
//LOGGER SETUP
try {
LogWriter.setup(shortMachineID, LoggingLevel);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
final Logger LOGGER = Logger.getLogger(runner.class.getName());
//CREATE MEMBERSHIP LIST
MemberList memberList = new MemberList(fullMachineID);
//INITIALIZE HEART
Heart dil = new Heart(HeartRate, memberList, fullMachineID);
//INITIALIZE GOSSIP LISTENER
int lossRate = Integer.parseInt(args[1]);
Gossiper gos_obj = new Gossiper(listenerPort, GossipSendingRate, memberList, fullMachineID, FailureCleanUpRate, FailureTimeOut, lossRate);
gos_obj.gossip_listener();
if(args[0].equalsIgnoreCase("contact"))
gos_obj.gossip();
String[] temp;
boolean firstTimeJoin = true;
LOGGER.info(fullMachineID+" # "+"INITIALIZED");
while(true)
{
System.out.println("\nUSAGE: join [contactIP] | leave | exit");
System.out.print(">");
input = br.readLine();
temp = input.split(" ");
if(temp[0].equals("join"))
{
if(firstTimeJoin)
{
gos_obj.joinRequest(temp[1]);
gos_obj.gossip();
firstTimeJoin = false;
}
else
{
fullMachineID = getFullMachineID();
shortMachineID = getShortMachineID();
try {
LogWriter.setup(shortMachineID, LoggingLevel);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Problems with creating the log files");
}
memberList = new MemberList(fullMachineID);
dil = new Heart(HeartRate, memberList, fullMachineID);
gos_obj = new Gossiper(listenerPort, GossipSendingRate, memberList, fullMachineID, FailureCleanUpRate, FailureTimeOut, lossRate);
gos_obj.gossip_listener();
gos_obj.joinRequest(temp[1]);
gos_obj.gossip();
}
}
else if(temp[0].equals("leave"))
{
LOGGER.info(fullMachineID+" # "+" LEFT");
gos_obj.stopGossip();
gos_obj.stopGossipListener();
dil.stop();
gos_obj.leaveRequest();
}
else if(temp[0].equalsIgnoreCase("quit") | temp[0].equalsIgnoreCase("exit") )
{
LOGGER.info(fullMachineID+" # "+" CRASHED");
System.exit(0);
}
else
{
System.out.println("Invalid Command. Please enter again");
}
}
} | 8 |
public void reportException(IllegalArgumentException e) {
JOptionPane.showMessageDialog(getParent(), "Bad format!\n"
+ e.getMessage(), "Bad Format", JOptionPane.ERROR_MESSAGE);
} | 0 |
public static String removeContraction(String s){
String[] words = s.split("\\s+");
String output = "";
for (int i=0; i<words.length; i++){
String current = words[i];
if (current.contains("'")){
int index = current.indexOf("'");
if (current.charAt(index+1) == 's'){
output += current.substring(0, index) + " is";
} else if (current.charAt(index+1) == 't'){
if (current.equals("won't")){
output += "will not";
} else if(current.equals("can't")){
output += "can not";
} else if (current.equals("don't")){
output += "do not";
} else {
output += current.substring(0, index) + " not";
}
} else {
output += current;
}
} else {
output += current;
}
output += " ";
}
return output;
} | 7 |
public void execute() throws Exception {
int keuze = menu.getMenuKeuze();
quizCatalogus = new QuizCatalogus();
opdrachtCatalogus = new OpdrachtCatalogus();
quizCatalogus.lezen();
//De code die hier stond om enkele opdrachten en quizzen aan te maken staat onderaan buiten de klasse in commentaar
switch (keuze) {
case 1: // openen lessenroosterOverzicht frame
break;
case 2:
quiz = new QuizFrame(this, toevoegenQuizController,
toevoegenOpdrachtController, quizCatalogus,
opdrachtCatalogus);
quiz.setBounds(20, 20, 1100, 600);
quiz.setVisible(true);
// quiz.MAXIMIZED_BOTH;
break;
case 3: // openen lessenroosterOverzicht frame
break;
case 4: // openen opdrachtOverzicht frame
break;
case 5:
// opslaan van de nieuwe objecten in tekstbestanden
break;
case 6:
// opslaan van de nieuwe objecten in tekstbestanden
break;
default:
if (keuze != menu.getStopWaarde()) {
IO.toonStringMetVenster("Je hebt een verkeerde keuze gemaakt!!!");
keuze = menu.getMenuKeuze();
}
}
} | 7 |
@Transactional
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException{
try {
Person p = personModelDao.getPersonByLogin(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new GrantedAuthorityImpl(p.getRole().getName())); // RoleName = "ROLE_ADMIN" or "ROLE_USER"
org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(p.getUsername(), p.getPassword(), enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, grantedAuthorities);
return user;
} catch (NoResultException e) {
throw new UsernameNotFoundException("No such user");
}
} | 1 |
private void parseTranscripts() {
logger.info("Parsing gene model file...");
long tstart = System.currentTimeMillis();
this.transcripts = new ArrayList<TranscriptRecord>();
try {
BufferedReader reader = IOUtils.toBufferedReader(new InputStreamReader(new FileInputStream(geneModelFile), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) continue;
TranscriptRecord record = parser.parseLine(line);
if(record == null) continue;
transcripts.add(record);
}
} catch (IOException e) {
throw new RuntimeException("Failed to read gene modle file", e);
} catch (GTFParseException e) {
throw new RuntimeException("Failed to parse gene model file", e);
}
long tend = System.currentTimeMillis();
double totalTime = ((tend - tstart)/1000);
logger.info("Finished parsing gene model file in: "+totalTime + "s");
if(transcripts.size() == 0) {
throw new RuntimeException("No transcripts found! Can't generate fusions without transcripts!");
}
} | 6 |
private final String decode(final String val) throws SAXException {
StringBuffer sb = new StringBuffer(val.length());
try {
int n = 0;
while (n < val.length()) {
char c = val.charAt(n);
if (c == '\\') {
n++;
c = val.charAt(n);
if (c == '\\') {
sb.append('\\');
} else {
n++; // skip 'u'
sb.append((char) Integer.parseInt(
val.substring(n, n + 4), 16));
n += 3;
}
} else {
sb.append(c);
}
n++;
}
} catch (RuntimeException ex) {
throw new SAXException(ex);
}
return sb.toString();
} | 4 |
public Hand[] deel(int aantalHanden, String algorythm) {
if (aantalHanden * Vars.handGrote > Vars.SET_GROTE)
new IndexOutOfBoundsException("Alle kaarten zijn op! Sorry :( Volgende potje mag je meespelen.");
if(algorythm.equals("fikius")){
Hand[] out = new Hand[aantalHanden];
for(int i = 0; i < out.length; i++){
out[i] = new Hand(new Kaart[Vars.handGrote]);
}
int ronde = 0; //geeft aan op hoeveelste ronde je bent.
int curHand = 0; //geeft aan welk stapeltje je aan het verhogen bent
int i = 0; //verhoogt elke kaart
while(true){
out[curHand].kaarten[ronde] = kaarten[i];
i++;
curHand++;
if(curHand >= aantalHanden){
curHand = 0;
ronde++;
}
if(ronde == Vars.handGrote)
break;
}
return out;
}
if(algorythm.equals("sinius")){
Hand[] out = new Hand[aantalHanden];
for(int i = 0; i < out.length; i++){
out[i] = new Hand(Arrays.copyOfRange(kaarten, i*Vars.handGrote, (i+1)*Vars.handGrote));
}
return out;
}
return null;
} | 8 |
private ArrayList<Profile.Entry> toArrayList(int partId,
double startTime, double finishTime) {
if(partId >= partitions.length || partId < 0) {
throw new IndexOutOfBoundsException("It is not possible to " +
"add a partition with index: " + partId + ".");
}
ArrayList<Entry> subProfile = new ArrayList<Entry>();
startTime = Math.max(startTime, currentTime());
Iterator<ProfileEntry> it = avail.itValuesFromPrec(startTime);
Profile.Entry fe = null;
// get first entry or create one if the profile is empty
if(it.hasNext()) {
PartProfileEntry ent = (PartProfileEntry)it.next();
PERangeList list = ent.getAvailRanges(partId) == null ?
null : ent.getAvailRanges(partId).clone();
double entTime = Math.max(startTime, ent.getTime());
fe = new Profile.Entry(entTime, list);
}
else {
fe = new Profile.Entry(startTime);
}
subProfile.add(fe);
while(it.hasNext()) {
PartProfileEntry entry = (PartProfileEntry)it.next();
if(entry.getTime() > finishTime) {
break;
}
PERangeList list = entry.getAvailRanges(partId) == null ?
null : entry.getAvailRanges(partId).clone();
Profile.Entry newEntry = new Profile.Entry(entry.getTime(), list);
subProfile.add(newEntry);
}
return subProfile;
} | 7 |
public String getKeyName() {
return this.name;
} | 0 |
public Mapper(Board board, int whatGameType, int useZones) {
game = board;
gameType = whatGameType;
if(gameType == 0) tileWidth = 64;
gameZones = useZones;
if(gameZones == NO_ZONES) {
zoneArray = new Tiles[1][1];
zoneCountX = 1;
zoneCountY = 1;
zoneArray[0][0] = new Tiles(game, 64);
}
} | 2 |
public static boolean isSyntax (char c) {
return c == ')' || c == '(' || c == ';' || c == '[' || c == ']';
} | 4 |
public void moveAutomatonStates() {
Object[] vertices = vertices();
for (int i = 0; i < vertices.length; i++) {
State state = (State) vertices[i];
Point2D point = pointForVertex(state);
state.setPoint(new Point((int) point.getX(), (int) point.getY()));
}
} | 1 |
public boolean isSymmetric(){
boolean test = true;
if(this.numberOfRows==this.numberOfColumns){
for(int i=0; i<this.numberOfRows; i++){
for(int j=i+1; j<this.numberOfColumns; j++){
if(this.matrix[i][j]!=this.matrix[j][i])test = false;
}
}
}
else{
test = false;
}
return test;
} | 4 |
private String viewTempDigit(final int td) {
String s = "";
StringBuilder sb = new StringBuilder();
for (int i = 1;i<=td-1;i++) {
sb.append(i).append(" ");
}
sb.append(td);
return sb.toString();
} | 1 |
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(AuthClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AuthClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AuthClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AuthClient.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 AuthClient().setVisible(true);
}
});
} | 6 |
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (obstacleGrid == null || obstacleGrid.length == 0
|| obstacleGrid[0].length == 0)
return 0;
int row = obstacleGrid.length;
int col = obstacleGrid[0].length;
int[] path = new int[col];
if (obstacleGrid[row-1][col-1] == 1)
return 0;
path[col-1] = 1;
for (int i = row-1; i >= 0; i--) {
if (obstacleGrid[i][col-1] == 0 && path[col-1] == 1)
path[col-1] = 1;
else
path[col-1] = 0;
for (int j = col-2; j >= 0; j--) {
if (obstacleGrid[i][j] == 1)
path[j] = 0;
else
path[j] += path[j+1];
}
}
return path[0];
} | 9 |
protected void AdjustBuffSize()
{
if (available == bufsize)
{
if (tokenBegin > 2048)
{
bufpos = 0;
available = tokenBegin;
}
else
ExpandBuff(false);
}
else if (available > tokenBegin)
available = bufsize;
else if ((tokenBegin - available) < 2048)
ExpandBuff(true);
else
available = tokenBegin;
} | 4 |
public static List<String> generateAddress(String[] nums, int position, List<String> addressList, String tmp) {
String[] parts = tmp.split("\\.");
if(parts.length == 5) {
return addressList;
}
if(position == nums.length) {
if(parts.length == 4) {
addressList.add(tmp);
return addressList;
}else {
return addressList;
}
}
String last;
if(parts.length == 0) {
last = tmp;
}else {
last = parts[parts.length-1];
}
if(Integer.valueOf(last+nums[position]) < 256) {
addressList = generateAddress(nums, position+1, addressList, tmp+nums[position]);
}
if(tmp != "") {
addressList = generateAddress(nums, position+1, addressList, tmp+"."+nums[position]);
}
return addressList;
} | 6 |
private void inorderRec(List<Integer> list, TreeNode lastroot) {
if(lastroot.left != null)
inorderRec(list,lastroot.left);
list.add(lastroot.val);
if(lastroot.right != null)
inorderRec(list,lastroot.right);
} | 2 |
private int calcDmg() {
if (leadership > 92) { // For high Leadership commanders
return Math.round(leadership + intelligence * 2 / 10);
} else if (combatPower > 92) { // For high combatPower commanders
return Math.round(combatPower * 8 / 10 + leadership * 4 / 10);
} else if (intelligence > 92) { // For high intelligence commanders
return Math.round(leadership * 8 / 10 + intelligence * 4 / 10);
} else { // For everyone else
return Math.round(leadership * 8 / 10 + combatPower * 4 / 10);
}
} | 3 |
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if ((index % 2) == 0) {
if (!isSelected) {
c.setBackground(this.cellBg1);
}
} else {
if (!isSelected) {
c.setBackground(this.cellBg2);
}
}
return c;
} | 4 |
Set<Position> getDiagNeighbors(Position p) {
Set<Position> neighbors = new HashSet<Position>();
if (p.i+1 < n && p.j+1 < m) neighbors.add(board[p.i+1][p.j+1]);
if (p.i-1 >= 0 && p.j+1 < m) neighbors.add(board[p.i-1][p.j+1]);
if (p.i+1 < n && p.j-1 >= 0) neighbors.add(board[p.i+1][p.j-1]);
if (p.i-1 >=0 && p.j-1 >= 0) neighbors.add(board[p.i-1][p.j-1]);
return neighbors;
} | 8 |
public void RandomizeNodeConnections(int X0, int Y0, int XLoc, int YLoc, int X1, int Y1) {// Sparsely connect a node with its neighbors.
double Azar;
Node ctr = GetNodeFromXY(XLoc, YLoc);// get this from xloc and yloc
ctr.CleanEverything();// clean out all dead neighbor links and routes that refer to them
for (int vcnt = Y0; vcnt <= Y1; vcnt++) {
for (int hcnt = X0; hcnt <= X1; hcnt++) {
if (!((XLoc == hcnt) && (YLoc == vcnt))) {// do not connect to self
Azar = rand.nextDouble();
if (Azar <= RandomChangeRate) {
Node nbr = GetNodeFromXY(hcnt, vcnt);
Azar = rand.nextDouble();
if (ctr.Neighbors.containsKey(nbr)) {
if (Azar > ConnectionDensity) {
Disconnect2Nodes(ctr, nbr);
}
} else {
if (Azar <= ConnectionDensity) {
Connect2Nodes(ctr, nbr);
}
}
}
}
}
}
} | 8 |
protected void drawBase(Graphics2D g2d, int x, int y, int colWidth, int rowHeight, int row, int site, Sequence seq) {
if (translate) {
throw new IllegalStateException("Not sure drawBase is supposed to get called for a translated sequence..?");
}
if (site>=seq.length())
base[0] = ' ';
else
base[0] = seq.at(site);
if (letterMode == NO_LETTERS) {
return;
}
if (letterMode == DIF_LETTERS) {
if (referenceSeq == null)
referenceSeq = currentSG.get(0);
if (seq != referenceSeq && base[0] == referenceSeq.at(site))
base[0] = '.';
}
drawBackground(g2d, x, y, colWidth, rowHeight, row, site, seq);
g2d.setFont(font);
y -= 4;
if (base[0]=='G') {
g2d.setColor(shadowColor);
g2d.drawChars(base, 0, 1, x+1, y+1);
g2d.setColor(Color.black);
g2d.drawChars(base, 0, base.length, x, y);
}
else {
g2d.setColor(shadowColor);
g2d.drawChars(base, 0, 1, x+1, y+1);
g2d.setColor(Color.black);
g2d.drawChars(base, 0, 1, x, y);
}
} | 8 |
public Annotation addAnnotation(Annotation newAnnotation) {
// make sure the page annotations have been initialized.
if (!isInited) {
try {
initPageAnnotations();
} catch (InterruptedException e) {
logger.warning("Annotation Initialization interupted");
}
}
StateManager stateManager = library.getStateManager();
Object annots = library.getObject(entries, ANNOTS_KEY.getName());
boolean isAnnotAReference = library.isReference(entries, ANNOTS_KEY.getName());
// does the page not already have an annotations or if the annots
// dictionary is indirect. If so we have to add the page to the state
// manager
if (!isAnnotAReference && annots != null) {
// get annots array from page
if (annots instanceof Vector) {
// update annots dictionary with new annotations reference,
Vector v = (Vector) annots;
v.add(newAnnotation.getPObjectReference());
// add the page as state change
stateManager.addChange(
new PObject(this, this.getPObjectReference()));
}
} else if (isAnnotAReference && annots != null) {
// get annots array from page
if (annots instanceof Vector) {
// update annots dictionary with new annotations reference,
Vector v = (Vector) annots;
v.add(newAnnotation.getPObjectReference());
// add the annotations reference dictionary as state has changed
stateManager.addChange(
new PObject(annots, library.getObjectReference(
entries, ANNOTS_KEY.getName())));
}
}
// we need to add the a new annots reference
else {
Vector annotsVector = new Vector(4);
annotsVector.add(newAnnotation.getPObjectReference());
// create a new Dictionary of annotaions using an external reference
PObject annotsPObject = new PObject(annotsVector,
stateManager.getNewReferencNumber());
// add the new dictionary to the page
entries.put(ANNOTS_KEY, annotsPObject.getReference());
// add it to the library so we can resolve the reference
library.addObject(annotsVector, annotsPObject.getReference());
// add the page and the new dictionary to the state change
stateManager.addChange(
new PObject(this, this.getPObjectReference()));
stateManager.addChange(annotsPObject);
annotations = new ArrayList<Annotation>();
}
// update parent page reference.
newAnnotation.getEntries().put(Annotation.PARENT_PAGE_KEY,
this.getPObjectReference());
// add the annotations to the parsed annotations list
annotations.add(newAnnotation);
// add the new annotations to the library
library.addObject(newAnnotation, newAnnotation.getPObjectReference());
// finally add the new annotations to the state manager
stateManager.addChange(new PObject(newAnnotation, newAnnotation.getPObjectReference()));
// return to caller for further manipulations.
return newAnnotation;
} | 8 |
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(initWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(initWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(initWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(initWindowUI.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 initWindowUI().setVisible(true);
}
});
} | 6 |
private void finish() {
if (restricted == null) {
JOptionPane.showMessageDialog(parent,
"There is no one right answer in this case.", "Ambiguity",
JOptionPane.ERROR_MESSAGE);
return;
}
HashSet toAdd = new HashSet(restricted);
toAdd.removeAll(alreadyChosen);
Iterator it = toAdd.iterator();
while (it.hasNext())
addItem((Production) it.next());
} | 2 |
public void addContact
(
InetAddress iaIn
, int iPort
, String strName
, int iSysState
, int iState
, String strStatus
)
{
InetAddress iaTmp = this.normalizeAddressIfLocal(iaIn);
if (this.idxContact(iaTmp) == -1)
{
synchronized(this.list)
{
try
{
EzimContact ecTmp = null;
int iIdx = 0;
int iLen = this.getSize();
while(iIdx < iLen)
{
ecTmp = this.getElementAt(iIdx);
if
(
strName.compareToIgnoreCase
(
ecTmp.getName()
) < 0
)
{
break;
}
iIdx ++;
}
this.list.add
(
iIdx
, new EzimContact
(
iaTmp
, iPort
, strName
, iSysState
, iState
, strStatus
)
);
this.fireIntervalAdded(iIdx, iIdx);
if (EzimSound.getInstance() != null)
EzimSound.getInstance().playStateChg();
}
catch(EzimContactException eceTmp)
{
EzimLogger.getInstance().severe
(
eceTmp.getMessage()
, eceTmp
);
}
}
}
} | 5 |
public static void main(String[] args) throws RemoteException {
/*
try {
java.rmi.registry.LocateRegistry.createRegistry(1099);
} catch (RemoteException e) {
e.printStackTrace();
}
*/
if (args.length < 1) {
System.err.println("Please specify the registry of this Scheduler!");
return;
}
// Create GridScheduler processes
final ArrayList<Process> processes = new ArrayList<Process>();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Shutting down GridSchedulers process.");
for (Process p : processes)
p.destroy();
}
});
System.out.println("Creating GS nodes..");
ProcessBuilder pb;
for (int i = 0; i < 5; i++) {
pb = new ProcessBuilder("java", "-jar", "LaunchGridScheduler.jar", i + "", ((i + 1) % 5) + "", ((i - 1 + 5) % 5) + "", args[0]);
pb.redirectErrorStream();
try {
processes.add(pb.start());
} catch (IOException e) {
e.printStackTrace();
}
}
//Process p = processes.get(0);
for (Process p : processes)
{
InputStream inputstream = p.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
final BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
// Start a client.
Thread t = new Thread() {
BufferedReader bf = bufferedreader;
public void run() {
String line;
try {
while((line = bf.readLine()) != null) {
System.out.println(line);
System.out.println("We done here.");
}
} catch (IOException e) {}
}
};
t.start();
}
System.out.println("Waiting for process to end");
Process p = processes.get(0);
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End of gridschedulers process");
return;
// Scanner scan = new Scanner(System.in);
/* scan.nextInt();
pb = new ProcessBuilder("java", "-jar", "LaunchGridScheduler.jar", 1 + "", ((1 + 1) % 3) + "", ((1 - 1 + 3) % 3) + "");
pb.redirectErrorStream();
try {
processes.add(pb.start());
} catch (IOException e) {
e.printStackTrace();
}
Process p1 = processes.get(1);*/
//for (Process p : processes)
//{
/* InputStream inputstream1 = p1.getInputStream();
InputStreamReader inputstreamreader1 = new InputStreamReader(inputstream1);
final BufferedReader bufferedreader1 = new BufferedReader(inputstreamreader1);
// Start a client.
Thread t1 = new Thread() {
BufferedReader bf = bufferedreader1;
public void run() {
String line;
try {
while((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {}
}
};
t1.start();
scan.nextInt();
pb = new ProcessBuilder("java", "-jar", "LaunchGridScheduler.jar", 2 + "", ((2 + 1) % 3) + "", ((2 - 1 + 3) % 3) + "");
pb.redirectErrorStream();
try {
processes.add(pb.start());
} catch (IOException e) {
e.printStackTrace();
}
Process p2 = processes.get(2);
//for (Process p : processes)
//{
InputStream inputstream2 = p2.getInputStream();
InputStreamReader inputstreamreader2 = new InputStreamReader(inputstream2);
final BufferedReader bufferedreader2 = new BufferedReader(inputstreamreader2);
// Start a client.
Thread t2 = new Thread() {
BufferedReader bf = bufferedreader2;
public void run() {
String line;
try {
while((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {}
}
};
t2.start();
*/
//scan.nextInt();
//Process pizza = null;
/*int a = 2;
while (a > 1)
{*/
/* pb = new ProcessBuilder("java", "-jar", "LaunchCluster.jar", 0 + "", 1 + "", 50 + "");
pb.redirectErrorStream();
try {
pizza = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
InputStream inputstream = pizza.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
final BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
// Start a client.
Thread t = new Thread() {
BufferedReader bf = bufferedreader;
public void run() {
String line;
try {
while((line = bf.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {}
}
};
t.start();*/
/* a = scan.nextInt();
pizza.destroy();
}*/
/*scan.nextInt();
pizza.destroy();*/
} | 8 |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} | 0 |
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
} | 6 |
public boolean canPlaceBlockOnSide(World par1World, int par2, int par3, int par4, int par5)
{
if (par5 == 2 && par1World.isBlockNormalCube(par2, par3, par4 + 1))
{
return true;
}
if (par5 == 3 && par1World.isBlockNormalCube(par2, par3, par4 - 1))
{
return true;
}
if (par5 == 4 && par1World.isBlockNormalCube(par2 + 1, par3, par4))
{
return true;
}
return par5 == 5 && par1World.isBlockNormalCube(par2 - 1, par3, par4);
} | 7 |
public Class<?> loadClass(String url, String name) throws ClassNotFoundException {
try {
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
InputStream input = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while (data != -1) {
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
return defineClass(null, classData, 0, classData.length);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
} | 4 |
public AST rBlock() throws SyntaxError {
expect(Tokens.LeftBrace);
AST t = new BlockTree();
while (true) { // get decls
try {
t.addKid(rDecl());
} catch (SyntaxError e) { break; }
}
while (true) { // get statements
try {
t.addKid(rStatement());
} catch (SyntaxError e) { break; }
}
expect(Tokens.RightBrace);
return t;
} | 4 |
public Option<Zipper<A>> deleteRight() {
return left.isEmpty() && right.isEmpty()
? Option.<Zipper<A>>none()
: some(zipper(right.isEmpty() ? left.tail()._1() : left,
right.isEmpty() ? left.head() : right.head(),
right.isEmpty() ? right : right.tail()._1()));
} | 5 |
public boolean copierFichier(ObjectInputStream input, ObjectOutputStream output) throws ClassNotFoundException { //Methode permettant la copie d'un fichier
boolean resultat = false;
File source = null;
File destination = null;
// Declaration des flux
FileInputStream sourceFile=null;
FileOutputStream destinationFile=null;
ArrayList<String> srcAndDst = new ArrayList<String>();
try {
Object object = input.readObject();
srcAndDst = (ArrayList<String>) object;
// Création du fichier :
source = new File(srcAndDst.get(0));
destination = new File(srcAndDst.get(1));
// destination.createNewFile();
// Ouverture des flux
sourceFile = new FileInputStream(source);
destinationFile = new FileOutputStream(destination);
// Lecture par segment de 0.5Mo
byte buffer[]=new byte[524288000];
int nbLecture;
while( (nbLecture = sourceFile.read(buffer)) != -1 ) {
destinationFile.write(buffer, 0, nbLecture);
}
// Copie réussie
resultat = true;
envoiConfirmation(output,resultat,"Le fichier "+source.getName() + " a bien été copié !");
} catch( FileNotFoundException f ) {
System.out.println("fichier non trouvé!");
} catch( IOException e ) {
System.out.println("Problème IO!");
} finally {
// Quoi qu'il arrive, on ferme les flux
try {
sourceFile.close();
} catch(Exception e) { }
try {
destinationFile.close();
} catch(Exception e) { }
}
return( resultat );
} | 5 |
StringBuffer generateCode () {
/* Make sure all information being entered is stored in the table */
resetEditors ();
/* Get names for controls in the layout */
names = new String [children.length];
for (int i = 0; i < children.length; i++) {
TableItem myItem = table.getItem(i);
String name = myItem.getText(0);
if (name.matches("\\d")) {
Control control = children [i];
String controlClass = control.getClass ().toString ();
String controlType = controlClass.substring (controlClass.lastIndexOf ('.') + 1);
names [i] = controlType.toLowerCase () + i;
} else {
names [i] = myItem.getText(0);
}
}
/* Create StringBuffer containing the code */
StringBuffer code = new StringBuffer ();
code.append ("import org.eclipse.swt.*;\n");
code.append ("import org.eclipse.swt.layout.*;\n");
code.append ("import org.eclipse.swt.widgets.*;\n");
if (needsCustom ()) code.append ("import org.eclipse.swt.custom.*;\n");
if (needsGraphics ()) code.append ("import org.eclipse.swt.graphics.*;\n");
code.append ("\n");
code.append ("public class MyLayout {\n");
code.append ("\tpublic static void main (String [] args) {\n");
code.append ("\t\tDisplay display = new Display ();\n");
code.append ("\t\tShell shell = new Shell (display);\n");
/* Get layout specific code */
code.append (generateLayoutCode ());
code.append ("\n\t\tshell.pack ();\n\t\tshell.open ();\n\n");
code.append ("\t\twhile (!shell.isDisposed ()) {\n");
code.append ("\t\t\tif (!display.readAndDispatch ())\n");
code.append ("\t\t\t\tdisplay.sleep ();\n\t\t}\n\t\tdisplay.dispose ();\n\t}\n}");
return code;
} | 4 |
private static byte[] insertGap(byte[] info, int where, int gap) {
int len = info.length;
byte[] newinfo = new byte[len + gap];
for (int i = 0; i < len; i++)
newinfo[i + (i < where ? 0 : gap)] = info[i];
return newinfo;
} | 2 |
public static String extractFileNameFromUrl(String url) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(4, "html,aspx");
map.put(3, "jsp,php");
StringBuilder fileName = null;
StringBuilder builder = new StringBuilder(url);
boolean found = false;
for (int i = builder.lastIndexOf("."); i >= 0; i--) {
char c = builder.charAt(i);
if (c == '.' && (i + 1) != builder.length()) {
int changedIndex = 0;
for (Integer key : map.keySet()) {
changedIndex = key + (i + 1);
if (changedIndex <= builder.length()) {
String dummy = builder.substring(i + 1, changedIndex);
String extAry[] = map.get(key).split(",");
for (String temp : extAry) {
if (temp.equalsIgnoreCase(dummy)) {
int y = i;
String str = builder.substring(0, y);
int lstInd = str.lastIndexOf("/");
fileName = new StringBuilder(str.substring(
lstInd + 1, str.length()));
fileName.append(".");
fileName.append(dummy);
found = true;
break;
}
}
}
if (found) {
i = -1;
break;
}
}
}
}
if (!found) {
fileName = new StringBuilder(String.valueOf(new Date().getTime()));
}
return fileName.toString();
} | 9 |
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
if ((columnIndex == 0) || (columnIndex == 5)) {
return true;
}
return false;
} | 2 |
@Override
public Converter put(String key, Converter value) {
Converter v = super.put(key, value);
if (v != null) {
throw new IllegalArgumentException("Duplicate Converter for "
+ key);
}
return v;
} | 1 |
@Override
public String toString() {
return "Action("+b+" goes to " + p + ")";
} | 0 |
public void deleteMealById(long id) {
Session session = null;
Transaction tx = null;
SimpleMealDaoImpl dao = getSimpleMealDaoImpl();
try {
session = HbUtil.getSession();
//TRANSACTION START
tx = session.beginTransaction();
SimpleMeal mealToDelete = dao.getSimpleMeal(id);
dao.deleteSimpleMeal(mealToDelete);
//delete by Id instead of object?
tx.commit();
//TRANSACTION END
//SESSION CLOSE
} catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
} | 4 |
public static AbstractUIItem createItem(FeatureType t, Panel panel)
{
switch(t) {
case Constant:
return new ConstantUIItem(panel);
case Sink:
return new SinkUIItem(panel);
case Source:
return new SourceUIItem(panel);
case Saddle:
return new SaddleUIItem(panel);
case Center:
return new CenterUIItem(panel);
case Focus:
return new FocusUIItem(panel);
case ConvergingElement:
return new ConvergingElementUIItem(panel);
case DivergingElement:
return new DivergingElementUIItem(panel);
case Generic:
return new GenericUIItem(panel);
}
assert false : "Unhandled type: " + t;
return null;
} | 9 |
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(administrateur_simple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(administrateur_simple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(administrateur_simple.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(administrateur_simple.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 administrateur_simple().setVisible(true);
}
});
} | 6 |
public static void addAbilities(LivingEntity entity, SpawnReason spawnReason)
{
// Fetch the mob config for this entity
MobAbilityConfig ma, rateMa;
rateMa = ma = AbilityConfig.i().getMobConfig(entity.getWorld().getName(), ExtendedEntityType.valueOf(entity), spawnReason);
// If there is not config for the entity there is nothing more to do
if (ma == null)
return;
// Fetch Ability Sets
ValueChance<Ability> abilityChance = ma.attributes.get(AbilityType.ABILITY_SET);
AbilitySet abilitySet = null;
if (abilityChance != null)
{
// Fetch an ability
abilitySet = (AbilitySet) abilityChance.getBonus();
// If it is the 'none' ability we ignore it
if (abilitySet != null && abilitySet.getAbilityConfig() == null)
{
abilitySet = null;
}
}
boolean applyNormalAbilities = true;
// If there is no ability or the 'none' ability set is given
// we allow other abilities to be applied
if (abilitySet != null)
{
// Only apply normal abilities if the ability set allows it
applyNormalAbilities = abilitySet.applyNormalAbilities();
// Make sure rates which are applied are the AbilitySets ones
rateMa = abilitySet.getAbilityConfig();
}
// Apply rates to the mob
rateMa.applyRates(entity);
if (applyNormalAbilities)
{
applyNormalAbilities(entity, ma);
}
if (abilitySet != null)
{
// Add the ability and return to prevent other abilities being applied
abilitySet.addAbility(entity);
}
} | 7 |
public void collision() {
for (int i = 0; i < mobs.size(); i++) {
Mob m = mobs.get(i);
if (m instanceof Projectile) {
for (int c = 0; c < mobs.size(); c++) {
Mob a = mobs.get(c);
if (!(a instanceof Projectile)) {
if (m.getBounds().intersects(a.getBounds())) {
System.out.println("Control.collision()");
if(a instanceof FEnemy) {
removeMob(a);
mobs.remove(m);
Sound.lose.play();
clearMobs();
Game.state = State.END;
}
else if (a instanceof REnemy) {
Sound.win.play();
clearMobs();
Wave.spawnWave(this);
}
}
}
}
}
}
} | 7 |
public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (halfWidth < 0) throw new RuntimeException("half width can't be negative");
if (halfHeight < 0) throw new RuntimeException("half height can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
} | 4 |
private String stringify(final InputStream inputStream) {
if (inputStream == null) {
return "";
}
try {
int ichar;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (;;) {
ichar = inputStream.read();
if (ichar < 0) {
break;
}
baos.write(ichar);
}
return baos.toString("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | 6 |
public Set<Long> getListIDs() {
if (toListIDs == null || toListIDs.length() == 0)
return null;
HashSet<Long> listIDs = new HashSet<Long>();
for (String listID : toListIDs.split(","))
listIDs.add(Long.parseLong(listID));
return listIDs;
} | 3 |
public static void insertAlerts(EventsBean event) {
PreparedStatement pst = null;
Connection conn=null;
String str = "There is an event "+event.getEventName() +" added for category ";
try {
conn=ConnectionPool.getConnectionFromPool();
pst = conn
.prepareStatement("INSERT INTO STUDENT_ALERTS (PERSON_ID, ALERT_DESCRIPTION, VIEWED) "
+ " SELECT DISTINCT id, CONCAT(? ,c.category_name) alert_description, 'N'"
+ " FROM person p, category c, student_category_mapping sc"
+ " WHERE p.id=sc.s_id"
+ " AND c.categoryId=sc.c_id"
+ " AND c.categoryId=?");
pst.setString(1, str);
pst.setInt(2, event.getCategoryId());
pst.execute();
}catch (Exception e) {
System.out.println(e);
} finally {
if(conn!=null){
ConnectionPool.addConnectionBackToPool(conn);
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
} | 4 |
@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 Usuario)) {
return false;
}
Usuario other = (Usuario) object;
if ((this.login == null && other.login != null) || (this.login != null && !this.login.equals(other.login))) {
return false;
}
return true;
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.