text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public void setURI(String value) {
this.uri = value;
}
| 0 |
public void visitEnd() {
if (!subroutineHeads.isEmpty()) {
markSubroutines();
if (LOGGING) {
log(mainSubroutine.toString());
Iterator it = subroutineHeads.values().iterator();
while (it.hasNext()) {
Subroutine sub = (Subroutine) it.next();
log(sub.toString());
}
}
emitCode();
}
// Forward the translate opcodes on if appropriate:
if (mv != null) {
accept(mv);
}
}
| 4 |
public void listTickers(){
List<String> tickers = new ArrayList<String>();
while(true){
this.tUI.printGuide1();
while(true){
String s = this.inputScanner.nextLine();
if(s.isEmpty()){
break;
}
tickers.add(s);
}
if(this.stockSwag.validateTickersList()){
break;
}
this.tUI.printTickerFail();
}
}
| 4 |
protected String checkFolder(String folderPath) {
File dir = new File(folderPath);
if (!dir.exists()) {
return("The music folder '"+folderPath+"' does not exist.");
} else if (!dir.isDirectory()) {
return("The music folder '"+folderPath+"' must be a directory.");
} else if (!dir.canRead()) {
return("The music folder '"+folderPath+"' can't be read. Check directory permissions");
}
return "";
}
| 3 |
public Byte toByteHelper(Bits bits, Node currentNode) {
if(currentNode == null){
//The byte we're looking for isn't in the tree. Return null.
return (Byte) null;
}
// Determine if currentNode has data.
if (currentNode.data != null) {
// If it does, return that data. Yay.
return (Byte) currentNode.data;
} else {
// Otherwise, we gotta go deeper.
return bits.poll() ? toByteHelper(bits, currentNode.right) : toByteHelper(bits, currentNode.left);
}
}
| 3 |
public void createTransitions(State currrentState, Boolean startState) {
HashSet<Transition> outgoing = getOutgoingTransition(currrentState);
State newSrcState = getMatchingState(currrentState);
Block newSrcBlock = StateToBlock.get(currrentState);
this.VisitedBlocks.add(newSrcBlock);
for (Transition trans : outgoing) {
Block newTarBlock = StateToBlock.get(trans.getTarState());
if (newSrcBlock.equals(newTarBlock)) { //falls Start und Zielzustand im gleichen Block leigen
if (trans.isIntern()) { //is the transition uses and internal action
if (startState) { //only draw an internal action from block->equal block if it is outgoing from the first state
if (internInStart(currrentState))
{
State newTarState = getMatchingState(trans.getTarState()); //tarState in new lts
Transition newTrans = new Transition(newSrcState,newTarState, trans.getTransAction());
newTransitions.add(newTrans);
}
//reachedStates.add(newTarState); first state is always reachable
}
}
else { //always create external transitions
State newTarState = getMatchingState(trans.getTarState()); //tarState in new lts
Transition newTrans = new Transition(newSrcState,newTarState, trans.getTransAction());
newTransitions.add(newTrans);
//reachedStates.add(newTarState); muss glaub ich nit hin
}
}
else { //falls verschiedene Blöcke muss ich Aktion auf jeden Fall bauen
State newTarState = getMatchingState(trans.getTarState()); //tarState in new lts
Transition newTrans = new Transition(newSrcState,newTarState, trans.getTransAction());
newTransitions.add(newTrans);
reachedStates.add(newTarState);
if (!this.VisitedBlocks.contains(newTarBlock)) //tar oder source block? ich glaub jo tar
this.createTransitions(trans.getTarState(), false);
}
}
}
| 6 |
private String getDescription() {
String desc = "@BatchUpdate(" + this.getParsedSql().getOriginalExpression() + ")";
if (this.isReturnId()) {
desc = desc + ",@ReturnId()";
}
return desc;
}
| 1 |
public final String getMethodName(int identifier) {
String mname = getReflectiveMethods()[identifier].getName();
int j = ClassMetaobject.methodPrefixLen;
for (;;) {
char c = mname.charAt(j++);
if (c < '0' || '9' < c)
break;
}
return mname.substring(j);
}
| 3 |
public E get(int i) {
if (i >= size || i < 0)
return null;
Stack<Node> stack = new Stack<Node>();
int counter = 0;
Node node = root;
while (true) {
if (node != null) {
stack.push(node);
node = node.left;
} else {
node = stack.pop();
if (counter++ == i)
return node.data;
node = node.right;
}
}
}
| 5 |
public boolean checkGoal(State state) {
for (int k = 0; k < state.getData().size(); k++) {
for(int m = 0; m < state.getData().get(k).size(); m++) {
if (state.getData().get(k).get(m).equals("$") || state.getData().get(k).get(m).equals(".")) {
return false;
}
}
}
endTime = System.nanoTime();
System.out.println("Reached goal state!");
ArrayList<Character> path = new ArrayList<Character>();
getPath(path, state);
System.out.println("path: " + path);
System.out.println("Nodes generated: " + totalNodesGenerated);
System.out.println("nodes containing states that were generated previously: " + nodesGeneratedPreviously);
nodesOnFringe = frontier.size();
System.out.println("Nodes on fringe: " + nodesOnFringe);
nodesOnExploredList = visited.size();
System.out.println("Nodes on explored list: " + nodesOnExploredList);
totalTime = endTime - startTime;
double printTime = totalTime/BILLION; //nanoseconds / 1000000000 = seconds
System.out.println("Run time in seconds: " + printTime);
Collections.reverse(path);
System.out.print("Path: ");
for(int i = 0; i < path.size(); i++) {
System.out.print(path.get(i) + ", ");
}
return true;
}
| 5 |
public int recalculateLevel() {
int addedlevels = 0;
int requiredExp = getExpRequirement(level);
while (exp >= requiredExp) {
exp -= requiredExp;
if (exp < 0) { exp = 0; } // so that experience is never below 0
addedlevels++;
addLevel();
requiredExp = getExpRequirement(level);
}
return addedlevels;
}
| 2 |
private List<Oeuvre> loadOeuvres() {
List<Oeuvre> lu = new ArrayList<Oeuvre>();
try {
// String req = "SELECT * FROM oeuvre";
String req = "SELECT * FROM OEUVRE";
Statement statement = DB.getConnexion().createStatement();
ResultSet rs = statement.executeQuery(req);
while (rs.next()) {
Oeuvre u = new Oeuvre(Integer.parseInt(rs.getString("ID_OEUVRE")), rs.getString("NOM"), rs.getString("AUTEUR"));
lu.add(u);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Usager.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Usager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Usager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Usager.class.getName()).log(Level.SEVERE, null, ex);
}
return lu;
}
| 5 |
public boolean setElement(int index, E element) {
LinkedElement<E> elem = findElement(index);
if (elem != null) {
elem.setObj(element);
return true;
}
return false;
}
| 1 |
private void init(InputStream in) throws IOException {
if (in == null) {
throw new IOException("Couldn't find input source");
}
bitStream = new BufferedInputStream(in);
bitStream.mark(Integer.MAX_VALUE);
}
| 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(HistogramPrototypeUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HistogramPrototypeUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HistogramPrototypeUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HistogramPrototypeUI.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 HistogramPrototypeUI().setVisible(true);
}
});
}
| 6 |
boolean deelverzamelingVan(Verzameling V) {
boolean deelverzameling = false;
for(int i = 0; i < elementen.length; i++) {
for(int j = 0; j < V.elementen.length; j++) {
if(elementen[i] == V.elementen[j]) {
deelverzameling = true;
break;
} else {
deelverzameling = false;
}
}
if(!deelverzameling){
return false;
}
}
return deelverzameling;
}
| 4 |
@Override
public void tick() {
if (strict) {
boolean temp = false;
for (boolean input : inputs) {
if (input && temp) {
output = false;
return;
} else if (input) {
temp = true;
}
}
} else {
byte num = 0;
for (boolean input : inputs) {
if (input) {
num++;
}
}
if (num % 2 == 1) {
output = true;
return;
}
}
}
| 8 |
private String getMnemDataErrorMessage() {
ArrayList<String> rawLines = currentMnemonic.getRawLines();
int noOfLines = rawLines.size();
int maxLineLength = 0;
String msg = "";
for (String str : rawLines) {
str = str.replaceAll("\\s+$", "");
if (str.length() > maxLineLength)
maxLineLength = str.length();
msg += "\n" + str;
}
int lastLineLength = rawLines.get(noOfLines - 1).replaceAll("\\s+$", "").length();
int noOfSpaces = 0;
String whiteSpace = "\t\t\t";
if (lastLineLength == 0)
noOfSpaces = maxLineLength;
else
noOfSpaces = maxLineLength - lastLineLength;
for (; noOfSpaces > 0; noOfSpaces -= 1)
whiteSpace += " ";
msg += whiteSpace + "<---";
return msg;
}
| 4 |
public String[] kapaliMasaIsimleriGetir(){
ArrayList<String> s = new ArrayList<>();
for(int i=0;i<bilgisayarlar.size();i++){
if(bilgisayarlar.get(i).getAcilisSaati()==null){
s.add(bilgisayarlar.get(i).getMasaAdi());
}
}
String [] ss = new String[s.size()];
for(int i=0;i<s.size();i++){
ss[i] = s.get(i);
}
return ss;
}
| 3 |
public void addCategory(Category cat)
{
this.categories.add(cat);
}
| 0 |
public String getChannelsAsToolTipText() {
String text = "";
if (channels.size() > 1) {
text = channels.toString();
text = text.substring(1, text.length() - 1).replace(", ", ",");
text = text.replace(",", "<br>");
text = "<html>" + text + "</html>";
} else if (channels.size() == 1) {
text = channels.get(0);
}
return text;
}
| 2 |
public Color getColor(String id) {
Color color = Color.BLACK;
for(int i=0;i<identity.size();i++) {
if(identity.get(i).equals(id)) {
color = colors.get(i)[0];
}
}
return color;
}
| 2 |
@Override
public String getDesc() {
return "Default";
}
| 0 |
private void debug(int[] query) {
// new SGM().run("Q3.4");
// new TJSGM().run("Q3.1");
// new PRM().run("Q3.1");
System.out.print("How many rounds you want? ");
int round = scanner.nextInt();
TJSGM tjsgm = new TJSGM();
long[][][][] result = new long[1][round][query.length][4];
for (int j = 0; j < round; j++) {
for (int i = 0; i < query.length; i++) {
result[0][j][i] = tjsgm.run(QUERY[query[i]]);
}
}
// print
String[] Q = {"TJSGM" };
for (int i = 0; i < result.length; i++) {// alg
System.out.println("Algorithm:" + Q[i]);
for (int k = 0; k < result[i][0].length; k++) {// query
System.out.print(QUERY[query[k]] + "\t");
}
System.out.println();
for (int j = 0; j < result[i].length; j++) {// round
for (int m = 0; m < 4; m++) {//t
for (long[] q : result[i][j]) {// query
System.out.print(q[m]+"\t");
}
System.out.println();
}
System.out.println();
}
}
}
| 7 |
public void cargarComboHorario(){
Usuario u = new Usuario();
ArrayList<String> listado = u.listarHorarios();
if(listado !=null){
for (int i = 0; i < listado.size(); i++) {
Horario.addItem(listado.get(i));
}
}
}
| 2 |
private void checkInvariants()
{
assert (wordsInUse == 0 || words[wordsInUse - 1] != 0);
assert (wordsInUse >= 0 && wordsInUse <= words.length);
assert (wordsInUse == words.length || words[wordsInUse] == 0);
}
| 3 |
public Prefab(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
if (x2 > x1){
width = x2 - x1;
} else {
width = x1 - x2;
}
if (y2 > y1){
height = y2 - y1;
} else {
height = y1 - y2;
}
height++;
width++;
}
| 2 |
public void update(double dt) {
xPos+=xVel*dt;
yPos+=yVel*dt;
xVel+=xAccel*dt;
yVel+=yAccel*dt;
setAccel(dt);
Ball b=null;
for(int i=0;i<MainClass.balls.size();i++) {
b=MainClass.balls.get(i);
if(b!=null && id<b.id && collides(b)) {
bounce(b,i);
}
}
if(xPos-radius<MainClass.wallThickness/2*MainClass.scale || xPos+radius>MainClass.resolution*MainClass.xWindows/MainClass.yWindows-MainClass.wallThickness/2*MainClass.scale) {
wallBounce(false);
}
if(yPos-radius<MainClass.wallThickness/2*MainClass.scale || yPos+radius>MainClass.resolution-MainClass.wallThickness/2*MainClass.scale) {
wallBounce(true);
}
}
| 8 |
public Magic constructMagic(int i, LivingThing l) {
if (i == 0) {
String name = "Fire Magic 1";
Magic fire1 = new Magic(true, Color.ORANGE, l, 5, 3, 1, name);
Damage fire1Dam = new Damage(5, 0, 0, 0, 0, 0, 0, 0, false, false, false);
fire1.setDamage(fire1Dam);
return fire1;
} else if (i == 1) {
String name = "Fire Magic 2";
Magic fire2 = new Magic(true, Color.ORANGE, l, 10, 8, 1, name);
Damage fire2Dam = new Damage(10, 0, 0, 0, 0, 0, 0, 0, false, false, false);
fire2.setDamage(fire2Dam);
return fire2;
} else if (i == 2) {
String name = "Fire Magic 3";
Magic fire2 = new Magic(true, Color.ORANGE, l, 20, 15, 1, name);
Damage fire2Dam = new Damage(5, 0, 0, 0, 0, 0, 0, 5, false, false, false);
fire2.setDamage(fire2Dam);
return fire2;
} else if (i == 3) {
String name = "Ice Magic 1";
Magic ice1 = new Magic(true, new Color(200, 249, 250), l, 5, 3, 1, name);
Damage ice1Dam = new Damage(5, 0, 0, 0, 5, 0, 0, 0, false, false, false);
ice1.setDamage(ice1Dam);
return ice1;
} else if (i == 4) {
String name = "Ice Magic 2";
Magic ice2 = new Magic(true, new Color(200, 249, 250), l, 10, 8, 1, name);
Damage ice2Dam = new Damage(10, 0, 0, 0, 10, 0, 0, 0, false, false, false);
ice2.setDamage(ice2Dam);
return ice2;
} else if (i == 5) {
String name = "Ice Magic 3";
Magic ice3 = new Magic(true, new Color(200, 249, 250), l, 20, 15, 1, name);
Damage ice3Dam = new Damage(15, 0, 0, 0, 10, 0, 0, 0, false, false, true);
ice3.setDamage(ice3Dam);
return ice3;
} else if (i == 6) {
String name = "Solidify";
Magic solidify = new Magic(true, Color.DARK_GRAY, l, 8, 11, 1, name);
Damage solidifyDamage = new Damage(0, 0, 0, 0, 0, 0, 0, 0, true, false, false);
solidify.setDamage(solidifyDamage);
return solidify;
} else if (i == 7) {
String name = "Gassify";
Magic gassify = new Magic(true, Color.LIGHT_GRAY, l, 8, 11, 1, name);
Damage gassifyDamage = new Damage(0, 0, 0, 0, 0, 0, 0, 0, true, false, false);
gassify.setDamage(gassifyDamage);
return gassify;
} else if (i == 8) {
String name = "Flare";
Magic basicFire = new Magic(true, Color.ORANGE, l, 5, 3, 1, name);
Damage basicFireDam = new Damage(1, 0, 0, 0, 0, 0, 0, 0, false, false, false);
basicFire.setDamage(basicFireDam);
return basicFire;
}
return null;
}
| 9 |
private static boolean hasSubTags(Object obj, Class<?> objClass) throws XMLStreamException {
for (Field field : Introspection.getFieldsWithAnnotation(objClass, XmlTag.class, true)) {
try {
Introspection.makeFieldAccessible(field);
Object content = field.get(obj);
if (content != null) {
if (Collection.class.isAssignableFrom(field.getType())) {
if (!((Collection<?>) content).isEmpty()) {
return true;
}
} else {
return true;
}
}
} catch (Exception exception) {
throw new XMLStreamException(exception);
}
}
return false;
}
| 7 |
public static void main(String[] args) {
Directories.foldervalidator();
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
info.getClassName();
break;
}
}
} catch (ClassNotFoundException classNotFoundException) {
ExceptionLogger.classNotFoundExceptionLogger(LogManager.getLogger(LaunchProjectXplorer.class.getName()), classNotFoundException);
} catch (InstantiationException instantiationException) {
ExceptionLogger.instantiationExceptionLogger(LogManager.getLogger(LaunchProjectXplorer.class.getName()), instantiationException);
} catch (IllegalAccessException illegalAccessException) {
ExceptionLogger.illegalAccessExceptionLogger(LogManager.getLogger(LaunchProjectXplorer.class.getName()), illegalAccessException);
} catch (UnsupportedLookAndFeelException unsupportedLookAndFeelException) {
ExceptionLogger.unsupportedLookAndFeelExceptionLogger(LogManager.getLogger(LaunchProjectXplorer.class.getName()), unsupportedLookAndFeelException);
}
new MainGUI();
}
| 6 |
public int demaLookback( int optInTimePeriod )
{
if( (int)optInTimePeriod == ( Integer.MIN_VALUE ) )
optInTimePeriod = 30;
else if( ((int)optInTimePeriod < 2) || ((int)optInTimePeriod > 100000) )
return -1;
return emaLookback ( optInTimePeriod ) * 2;
}
| 3 |
public void reset()
{
countsValid = false;
for(Class key : counters.keySet()) {
Counter count = counters.get(key);
count.reset();
}
}
| 1 |
private void testValue(DateTimeField fieldA, DateTimeField fieldB,
String method, long millis, long valueA, long valueB) {
if (valueA != valueB) {
failValue(fieldA, fieldB, method, millis, valueA, valueB);
}
}
| 1 |
@Override
public void validate() {
if (getEmail().isEmpty()) {
addActionError("Please Enter Email Address");
}
else if (getPassword().isEmpty()) {
addActionError("Please Enter Password");
}
else{
User user = (User) myDao.getDbsession().get(User.class, email);
if (user != null) {
if (user.getPassword().equals(password)) {
if (user.getUserStatus().equals(userEnum.Suspend.getUserType())) {
addActionError("Your Account Has Been Suspended Temporarily Please Contact Our Customer Services for More Details");
} else {
}
} else {
// addFieldError("password", "Invalid password");
addActionError("Invalid password");
}
} else {
// addFieldError("email", "Invalid Email Address");
addActionError("Invalid Email Address");
}
}
}
| 5 |
public boolean isActivated(SkiPass sp) {
Date currentDate = new Date(System.currentTimeMillis());
return (currentDate.before(sp.getActivationDate()) ? false : true);
}
| 1 |
private static PaymentResponse read(String xml) throws InternalApiException {
try {
Persister persister = new Persister();
return persister.read(PaymentResponse.class, xml);
} catch (Exception e) {
throw new InternalApiException(e);
}
}
| 1 |
public static void makeGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeGrid must use SpringLayout.");
return;
}
Spring xPadSpring = Spring.constant(xPad);
Spring yPadSpring = Spring.constant(yPad);
Spring initialXSpring = Spring.constant(initialX);
Spring initialYSpring = Spring.constant(initialY);
int max = rows * cols;
//Calculate Springs that are the max of the width/height so that all
//cells have the same size.
Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
getWidth();
Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
getHeight();
for (int i = 1; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
}
//Apply the new width/height Spring. This forces all the
//components to have the same size.
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
cons.setWidth(maxWidthSpring);
cons.setHeight(maxHeightSpring);
}
//Then adjust the x/y constraints of all the cells so that they
//are aligned in a grid.
SpringLayout.Constraints lastCons = null;
SpringLayout.Constraints lastRowCons = null;
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
if (i % cols == 0) { //start of new row
lastRowCons = lastCons;
cons.setX(initialXSpring);
} else { //x position depends on previous component
cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
xPadSpring));
}
if (i / cols == 0) { //first row
cons.setY(initialYSpring);
} else { //y position depends on previous row
cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
yPadSpring));
}
lastCons = cons;
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH,
Spring.sum(
Spring.constant(yPad),
lastCons.getConstraint(SpringLayout.SOUTH)));
pCons.setConstraint(SpringLayout.EAST,
Spring.sum(
Spring.constant(xPad),
lastCons.getConstraint(SpringLayout.EAST)));
}
| 6 |
@Override
public void start() throws ConsoleException {
if(isStarted) throw new ConsoleException("Console has already been run");
isStarted = true;
completer.getStrings().clear();
completer.getStrings().addAll(commands.keySet());
String line;
try {
while(isStarted && (line = reader.readLine()) != null) {
List<String> tokens = tokenizer.tokenize(line);
String alias;
if(!tokens.isEmpty() && (alias = tokens.get(0)) != null && commands.containsKey(alias)) {
tokens.remove(0);
commands.get(alias).perform(tokens);
} else {
out.println(usage != null ? usage : "Unknown command, press TAB to list available ones");
}
}
} catch (UserInterruptException e) {
stop();
} catch (IOException e) {
throw new ConsoleException(e);
}
}
| 9 |
public static int getClosestColor(int red, int green, int blue) {
if(red < 0 || red > 255)
throw new IllegalArgumentException("getClosestColor: red is outside of valid range (0-255)");
if(green < 0 || green > 255)
throw new IllegalArgumentException("getClosestColor: green is outside of valid range (0-255)");
if(blue < 0 || blue > 255)
throw new IllegalArgumentException("getClosestColor: blue is outside of valid range (0-255)");
double closestMatch = Double.MAX_VALUE;
int closestIndex = 0;
for(Entry entry : colorEntries) {
double distance = entry.distanceTo(red, green, blue);
if(distance < closestMatch) {
closestIndex = entry.index;
closestMatch = distance;
}
}
return closestIndex;
}
| 8 |
private Map<String, Class<?>> getExtensionClasses() {
Map<String, Class<?>> classes = cachedClasses.get();
if (classes == null) {
synchronized (cachedClasses) {
classes = cachedClasses.get();
if (classes == null) {
classes = loadExtensionClasses();
cachedClasses.set(classes);
}
}
}
return classes;
}
| 4 |
private void save(final JFrame frame) {
final JFileChooser chooser = new JFileChooser(new File(GuiUtils.CURRENT_DIRECTORY));
chooser.setSelectedFile(new File("scsync.config"));
if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(frame)) {
final Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
final String json = gson.toJson(GuiUtils.syncConfig);
try {
FileUtils.write(chooser.getSelectedFile(), json);
JOptionPane.showMessageDialog(frame, "SyncConfig was successfully saved to file " + chooser.getSelectedFile(), "Save Success",
JOptionPane.PLAIN_MESSAGE);
GuiUtils.CURRENT_DIRECTORY = chooser.getSelectedFile().getParent();
} catch (final IOException e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Save Error", JOptionPane.ERROR_MESSAGE);
}
}
}
| 2 |
public void mouseReleased(MouseEvent me)
{
if (this.isEnabled())
{
if (tools.getSelectedDrawingTool() == Toolset.TOOL_SELECTION)
{
undo();
}
if (!this.wasDragged)
{
if (selection.height != 0 && selection.width != 0)
{
addUndo();
flattenSelection();
}
this.selection = new Rectangle();
}
fireChanged();
}
}
| 5 |
public void removeDeadBodies() {
for (int i = rigidBodies.size() - 1; i >= 0; i--) {
RigidBody rigidBody = rigidBodies.get(i);
if (rigidBody.getLifeTime() > 0
&& rigidBody.getAge() > rigidBody.getLifeTime()) {
physicsController.removeRigidBody(rigidBody);
graphicsController.removeRigidBody(rigidBody);
rigidBodies.remove(rigidBody);
}
}
}
| 3 |
public String encode(String plain, String pass){
//initialize plaintext and password
plainText = plain;
password = pass;
//generate P array from password
KeyGenerator kg = new KeyGenerator(password);
pArray = kg.getPArray();
//make sure the whole text is in pieces of 16 bytes or 128 bits (the block size)
byte[] plainBytes = plainText.getBytes();
int missing = 16-(plainBytes.length%16);
byte byt = 0;
byte[] temp = new byte[plainBytes.length+missing];
for(int i=0;i<plainBytes.length;i++)
{
temp[i] = plainBytes[i];
}
for(int i=plainBytes.length;i<plainBytes.length+missing;i++)
{
temp[i] = byt;
}
plainBytes = temp;
//make array of 64bit pieces (8byte) for plaintext
byte[][] plain64Array = new byte[plainBytes.length/8][8];
for(int i=0;i<plainBytes.length/8;i++)
{
byte[] tmp = new byte[8];
for(int b=0;b<8;b++)
{
tmp[b] = plainBytes[b+(8*i)];
}
plain64Array[i] = tmp;
}
//encode 128bit at a time
byte[][] resultArray = new byte[plainBytes.length/8][8];
for(int i=0;i<plain64Array.length/2;i++)//for every 128bit
{
//first 64bit feistel
temp = plain64Array[i*2];
for(int a=0;a<16;a+=2)
{
temp = feistel((byte[])pArray[a],temp);
}
resultArray[i*2] = temp;
//second 64bit feistel
temp = plain64Array[i*2+1];
for(int a=1;a<16;a+=2)
{
temp = feistel((byte[])pArray[a],temp);
}
resultArray[i*2+1] = temp;
}
//put bytes back in one byte array
byte[] cipherBytes = new byte[plainBytes.length];
for(int i=0;i<resultArray.length;i++)
{
for(int b=0;b<8;b++)
{
cipherBytes[b+(i*8)] = resultArray[i][b];
}
}
return DatatypeConverter.printBase64Binary(cipherBytes);
}
| 9 |
public List findByContestId(Object contestId) {
return findByProperty(CONTEST_ID, contestId);
}
| 0 |
public String getNombre() {
return nombre;
}
| 0 |
public void remove(int key) {
HashPrinter.tryRemove(key);
/** Run along the array */
int runner = 0;
int hash = (key % table.length);
while (table[hash] != null && runner < table.length) {
if (table[hash].getKey() == key) {
break;
}
runner++;
hash = ((key + runner * runner) % table.length);
}
if (runner == table.length || table[hash].getKey() != key) {
HashPrinter.notFound(key);
} else if (table[hash].getKey() == key) {
size--;
table[hash] = DeletedNode.getUniqueDeletedNode();
HashPrinter.remotionSuccessful(key, hash);
}
}
| 6 |
public void setVar(List<?> list)
{
for(PVar e : this._var_)
{
e.parent(null);
}
this._var_.clear();
for(Object obj_e : list)
{
PVar e = (PVar) obj_e;
if(e.parent() != null)
{
e.parent().removeChild(e);
}
e.parent(this);
this._var_.add(e);
}
}
| 4 |
public static boolean toggleMute(CommandSender s, Player p, String pName) {
if (p == null) {
if(!PlayerChat.plugin.Mute.contains(pName)) {
Messenger.tell(s, pName + " is offline or does not exist.");
return true;
} else {
PlayerChat.plugin.Mute.remove(pName);
Messenger.tell(s, "You have unmuted " + pName + ".");
return true;
}
} else {
if (PlayerChat.plugin.Mute.contains(pName)) {
PlayerChat.plugin.Mute.remove(pName);
Messenger.tell(s, "You have unmuted " + pName);
Messenger.tell(p, "You have been unmuted!");
return true;
} else {
if (p.hasPermission("playerchat.mute.exempt")) {
Messenger.tell(s, "You may not mute this player.");
return false;
}
PlayerChat.plugin.Mute.add(pName);
Messenger.tell(s, "You have muted " + pName);
Messenger.tell(p, "You have been muted!");
return true;
}
}
}
| 4 |
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode tmpHead = head;
for (int i = 2; i <= 5; ++i){
ListNode tmp = new ListNode(i);
tmpHead.next = tmp;
tmpHead = tmp;
}
Rotate_List rl = new Rotate_List();
ListNode node = rl.rotateRight(head, 7);
rl.printList(node);
}
| 1 |
private static void createFile(String filePathName) throws IOException {
File file = new File(filePathName);
boolean exists = file.exists();
if (!exists) {
file.createNewFile();
}
}
| 1 |
protected void update(CheckedFrequencyTable freq, int symbol) throws IOException {
// State check
if (low >= high || (low & MASK) != low || (high & MASK) != high)
throw new AssertionError("Low or high out of range");
long range = high - low + 1;
if (range < MIN_RANGE || range > MAX_RANGE)
throw new AssertionError("Range out of range");
// Frequency table values check
long total = freq.getTotal();
long symLow = freq.getLow(symbol);
long symHigh = freq.getHigh(symbol);
if (symLow == symHigh)
throw new IllegalArgumentException("Symbol has zero frequency");
if (total > MAX_TOTAL)
throw new IllegalArgumentException("Cannot code symbol because total is too large");
// Update range
long newLow = low + symLow * range / total;
long newHigh = low + symHigh * range / total - 1;
low = newLow;
high = newHigh;
// While the highest bits are equal
while (((low ^ high) & TOP_MASK) == 0) {
shift();
low = (low << 1) & MASK;
high = ((high << 1) & MASK) | 1;
}
// While the second highest bit of low is 1 and the second highest bit of high is 0
while ((low & ~high & SECOND_MASK) != 0) {
underflow();
low = (low << 1) & (MASK >>> 1);
high = ((high << 1) & (MASK >>> 1)) | TOP_MASK | 1;
}
}
| 9 |
public void updateAvaliableTexturePacks()
{
ArrayList arraylist = new ArrayList();
selectedTexturePack = field_77314_a;
arraylist.add(field_77314_a);
Iterator iterator = func_77299_i().iterator();
do
{
if (!iterator.hasNext())
{
break;
}
File file = (File)iterator.next();
String s = func_77302_a(file);
if (s != null)
{
Object obj = (TexturePackBase)field_77308_f.get(s);
if (obj == null)
{
obj = file.isDirectory() ? ((Object)(new TexturePackFolder(s, file))) : ((Object)(new TexturePackCustom(s, file)));
field_77308_f.put(s, obj);
}
if (((TexturePackBase)(obj)).func_77538_c().equals(field_77312_b.gameSettings.skin))
{
selectedTexturePack = ((TexturePackBase)(obj));
}
arraylist.add(obj);
}
}
while (true);
availableTexturePacks.removeAll(arraylist);
TexturePackBase texturepackbase;
for (Iterator iterator1 = availableTexturePacks.iterator(); iterator1.hasNext(); field_77308_f.remove(texturepackbase.func_77536_b()))
{
texturepackbase = (TexturePackBase)iterator1.next();
texturepackbase.func_77533_a(field_77312_b.renderEngine);
}
availableTexturePacks = arraylist;
}
| 7 |
public void StartGame(boolean isGameHost, int slots,
HostGameTask hgt) throws InvalidKeyException, BadPaddingException,
IllegalBlockSizeException, InvalidSubscriptionException,
InterruptedException, IOException, InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException,
NoSuchProviderException {
ArrayList<User> gameUsers = null;
if (isGameHost) {
gameUsers = comServ.startNewGame(slots, hgt);
}
if (gameUsers == null) {
comServ.shutdown();
System.exit(1);
return;
}
System.out.println("\nGame Players:");
for (int i = 0; i < gameUsers.size(); i++) {
System.out.println(gameUsers.get(i).getUsername() + " "
+ gameUsers.get(i).getID());
}
System.out.println("");
if (isGameHost) {
playGameAsHost(gameUsers, hgt);
}
return;
}
| 4 |
public void setAsyncRunner(AsyncRunner asyncRunner) {
this.asyncRunner = asyncRunner;
}
| 0 |
public void setIssuer(String value) {
this.issuer = value;
}
| 0 |
private void actualizarProcesos(){
if (!a.getNivel1().isEmpty()) {
if ((a.getNivel1().get(0).getRafaga()<=a.getQuantum())) {
a.getNivel1().remove(0);
actualizarTabla1();
}else{
a.getNivel1().get(0).setRafaga(a.getNivel1().get(0).getRafaga()-a.getQuantum());
a.getNivel2().add(a.getNivel1().get(0));
a.getNivel1().remove(0);
actualizarTabla1();
actualizarTabla2();
}
}else{
if (!a.getNivel2().isEmpty()) {
if ((a.getNivel2().get(0).getRafaga()<=a.getQuantum())) {
a.getNivel2().remove(0);
actualizarTabla2();
}else{
a.getNivel2().get(0).setRafaga(a.getNivel2().get(0).getRafaga()-a.getQuantum());
a.getNivel3().add(a.getNivel2().get(0));
a.getNivel2().remove(0);
actualizarTabla2();
actualizarTabla3();
}
}else{
if ((a.getNivel3().get(0).getRafaga()<=a.getQuantum())) {
a.getNivel3().remove(0);
actualizarTabla3();
}else{
a.getNivel3().get(0).setRafaga(a.getNivel3().get(0).getRafaga()-a.getQuantum());
actualizarTabla3();
}
}
}
}
| 5 |
private int getLevelValue(String name)
{
while (true)
{
Integer levelValue = (Integer) name2levelMap.get(name);
if (levelValue != null)
return levelValue.intValue();
if (name.length() == 0)
{
break;
}
else
{
int lastDot = name.lastIndexOf('.');
if (lastDot >= 0)
name = name.substring(0, lastDot);
else
name = "";
}
}
//default ROOT level
return LEVEL_INFO;
}
| 4 |
public boolean isMatch2(String s, String p) {
// Start typing your Java solution below
// DO NOT write main() function
if (p == null)
return s == null;
if (s == null)
return false;
if (p.length() == 0)
return s.length() == 0;
if (p.charAt(0) != '*') {
if (s.length() > 0
&& (s.charAt(0) == p.charAt(0) || p.charAt(0) == '?'))
return isMatch(s.substring(1), p.substring(1));
else
return false;
}
int i = 0;
for (; i < s.length(); i++) {
if (isMatch(s.substring(i), p.substring(1)))
return true;
}
return isMatch(s.substring(i), p.substring(1));
}
| 9 |
static double[][] multiply(double[][] A, double[][] B){
double[][] AB = new double[A.length][B[0].length];
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B[i].length; j++){
for(int k = 0; k < B.length ; k++){
AB[i][j] += A[i][k]*B[k][j];
}
}
}
return AB;
}
| 3 |
public Object getValueAt(int row, int col) {
Ingredient i = (Ingredient)(data.get(row));
try {
switch (col) {
case 0 :
return new Boolean(add[row]);
case 1 :
String t = data.get(row).getClass().getName();
return t.substring("ca.strangebrew.".length(),t.length());
case 2 :
return i.getName();
}
} catch (Exception e) {
};
return "";
}
| 4 |
public synchronized List<Long> getNodesIds(int pos) {
if (nodes.size() > pos)
return nodes.get(pos);
else
return null;
}
| 1 |
public void connect(TreeLinkNode root) {
if (root == null || root.getLeft() == null || root.getRight() == null) {
return;
}
if (root.getLeft() != null) {
root.getLeft().setNext(root.getRight());
}
if (root.getRight() != null && root.getNext() != null) {
root.getRight().setNext(root.getNext().getLeft());
}
connect(root.getLeft());
connect(root.getRight());
}
| 6 |
public void run() {
try
{
int count = 0;
String edge_id = null;
while((edge_id == null) && (count < 30))
{
edge_id = ControllerEngine.gdb.getResourceEdgeId(resource_id, inode_id, region, agent);
Thread.sleep(1000);
}
if(edge_id != null)
{
if((ControllerEngine.gdb.setINodeParam(resource_id,inode_id,"status_code","10")) &&
(ControllerEngine.gdb.setINodeParam(resource_id,inode_id,"status_desc","iNode Active.")))
{
//recorded plugin activations
System.out.println("SchedulerEngine : pollAddPlugin : Activated inode_id=" + inode_id);
}
}
else
{
System.out.println("SchedulerEngine : pollAddPlugin : unable to verify iNode activation!");
}
}
catch(Exception v)
{
System.out.println(v);
}
}
| 6 |
public void mergeAddr(FlowBlock succ) {
if (succ.nextByAddr == this || succ.prevByAddr == null) {
/*
* Merge succ with its nextByAddr. Note: succ.nextByAddr != null,
* since this is on the nextByAddr chain.
*/
succ.nextByAddr.addr = succ.addr;
succ.nextByAddr.length += succ.length;
succ.nextByAddr.prevByAddr = succ.prevByAddr;
if (succ.prevByAddr != null)
succ.prevByAddr.nextByAddr = succ.nextByAddr;
} else {
/* Merge succ with its prevByAddr */
succ.prevByAddr.length += succ.length;
succ.prevByAddr.nextByAddr = succ.nextByAddr;
if (succ.nextByAddr != null)
succ.nextByAddr.prevByAddr = succ.prevByAddr;
}
}
| 4 |
public Complex[] getWavefunctionCoeffs(int index, double energy) {
ComplexMatrix mx = getPropagationMatrix(index, energy);
if (index == 1) {
return new Complex[]{Complex.fromDouble(0), mx.getElem(1, 0)};
}
return new Complex[]{mx.getElem(0, 0), mx.getElem(1, 0)};
}
| 1 |
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(FLAVORS[0])) { // RTF
return new ByteArrayInputStream(data==null ? new byte[0] : data);
}
else if (flavor.equals(FLAVORS[1])) { // stringFlavor
return data==null ? "" : RtfToText.getPlainText(data);
}
else if (flavor.equals(FLAVORS[2])) { // plainTextFlavor (deprecated)
String text = ""; // Valid if data==null
if (data!=null) {
text = RtfToText.getPlainText(data);
}
return new StringReader(text);
}
else {
throw new UnsupportedFlavorException(flavor);
}
}
| 6 |
public Manifest getManifest()
{
return _manifest;
}
| 0 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((decodedValue == null) ? 0 : decodedValue.hashCode());
result = prime * result + ((encodedValue == null) ? 0 : encodedValue.hashCode());
result = prime * result + ((symmetricKey == null) ? 0 : symmetricKey.hashCode());
return result;
}
| 3 |
public void checkOneLetterOff(String queueHead)
{
for(int i =0; i<allWords.size(); i++)
{
String currentWrd = allWords.get(i);
//compares length and if greater than one skips the wordaddWords();
if(currentWrd.length() == queueHead.length() )
{
//looks at length of word and compares chars
numDiffLetters = 0;
for(int k =0; k<currentWrd.length(); k++)
{
//checks if characters match
char x = queueHead.charAt(k);
char y = currentWrd.charAt(k);
//System.out.print(x + " " + y + "\n");
if(x != y && numDiffLetters <2)
{
numDiffLetters++;
//System.out.println(numDiffLetters);
}
}
//adds all words one letter diff to queueHead to temp array and removes them from all words to avoid going back
if(numDiffLetters == 1)
{
tmp4.add(currentWrd);
if( allWords.contains(currentWrd))
{
allWords.remove(currentWrd);
}
}
}
}
}
| 7 |
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(RoadList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RoadList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RoadList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RoadList.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 RoadList().setVisible(true);
}
});
}
| 6 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Physical target=this.getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_ANY);
if(target==null)
return false;
if(target instanceof Item)
{
}
else
if(target instanceof MOB)
{
}
else
{
mob.tell(L("This chant won't affect @x1.",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(!success)
{
return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) to <T-NAMESELF>, but fail(s)."));
}
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> chant(s) to <T-NAMESELF>, causing a rust proof film to envelope <T-HIM-HER>!^?"));
if(mob.location().okMessage(mob,msg))
{
dontbother.clear();
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
return success;
}
| 7 |
public Updater(Plugin plugin, int id, File file, UpdateType type, boolean announce) {
this.plugin = plugin;
this.type = type;
this.announce = announce;
this.file = file;
this.id = id;
this.updateFolder = plugin.getServer().getUpdateFolder();
final File pluginFile = plugin.getDataFolder().getParentFile();
final File updaterFile = new File(pluginFile, "Updater");
final File updaterConfigFile = new File(updaterFile, "config.yml");
if (!updaterFile.exists()) {
updaterFile.mkdir();
}
if (!updaterConfigFile.exists()) {
try {
updaterConfigFile.createNewFile();
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not create a configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
this.config = YamlConfiguration.loadConfiguration(updaterConfigFile);
this.config.options().header("This configuration file affects all plugins using the Updater system (version 2+ - http://forums.bukkit.org/threads/96681/ )" + '\n'
+ "If you wish to use your API key, read http://wiki.bukkit.org/ServerMods_API and place it below." + '\n'
+ "Some updating systems will not adhere to the disabled value, but these may be turned off in their plugin's configuration.");
this.config.addDefault("api-key", "PUT_API_KEY_HERE");
this.config.addDefault("disable", false);
if (this.config.get("api-key", null) == null) {
this.config.options().copyDefaults(true);
try {
this.config.save(updaterConfigFile);
} catch (final IOException e) {
plugin.getLogger().severe("The updater could not save the configuration in " + updaterFile.getAbsolutePath());
e.printStackTrace();
}
}
if (this.config.getBoolean("disable")) {
this.result = UpdateResult.DISABLED;
return;
}
String key = this.config.getString("api-key");
if (key.equalsIgnoreCase("PUT_API_KEY_HERE") || key.equals("")) {
key = null;
}
this.apiKey = key;
try {
this.url = new URL(Updater.HOST + Updater.QUERY + id);
} catch (final MalformedURLException e) {
plugin.getLogger().severe("The project ID provided for updating, " + id + " is invalid.");
this.result = UpdateResult.FAIL_BADID;
e.printStackTrace();
}
this.thread = new Thread(new UpdateRunnable());
this.thread.start();
}
| 9 |
public boolean load(String audiofile) {
try {
setFilename(audiofile);
sample = AudioSystem.getAudioInputStream(getURL(filename));
clip.open(sample);
return true;
} catch (IOException e) {
return false;
} catch (UnsupportedAudioFileException e) {
return false;
} catch (LineUnavailableException e) {
return false;
}
}
| 3 |
static public boolean isColliding(math.Supportable lhs, math.Supportable rhs){
List<Vector3f> simplex = new java.util.ArrayList<Vector3f>();
Vector3f support = getSupport(lhs,rhs,Vector3f.UNIT_X);
simplex.add(support);
Vector3f direction = support.negate();
int loopCounter = 0;
// If A is in the same direction as we were heading, then we haven't crossed the origin,
// so that means we can't get to the origin
while((support = getSupport(lhs,rhs,direction)).sameDirection(direction)){
simplex.add(support);
if(loopCounter > MAX_ITTERATIONS)
break;
// If the simplex has enclosed the origin then the two objects are colliding
if(containsOrigin(simplex))
return true;
direction = findSimplex(simplex);
// If our dot product gave us the zero vector, our vectors must be colinear and we contain the origin and further test will break
if (direction.equals(Vector3f.ZERO))
return true;
}
return false;
}
| 4 |
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(ListarMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListarMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListarMarcaGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListarMarcaGui.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 ListarMarcaGui().setVisible(true);
}
});
}
| 6 |
public static void testMap(){
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, String> map1 = new HashMap<String, String>();
HashMap<String, String> map2= new HashMap<String, String>();
HashMap<String, String> map3 = new HashMap<String, String>();
HashMap<String, String> map4 = new HashMap<String, String>();
HashMap<String, String> map5 = new HashMap<String, String>();
HashMap<String, String> map6 = new HashMap<String, String>();
HashMap<String, String> map7 = new HashMap<String, String>();
HashMap<String, String> map9 = new HashMap<String, String>();
HashMap<String, String> map8 = new HashMap<String, String>();
HashMap<String, String> map10 = new HashMap<String, String>();
HashMap<String, String> map11 = new HashMap<String, String>();
HashMap<String, String> map12 = new HashMap<String, String>();
HashMap<String, String> map13 = new HashMap<String, String>();
HashMap<String, String> map14 = new HashMap<String, String>();
HashMap<String, String> map15 = new HashMap<String, String>();
HashMap<String, String> map16 = new HashMap<String, String>();
HashMap<String, String> map17 = new HashMap<String, String>();
HashMap<String, String> map18 = new HashMap<String, String>();
HashMap<String, String> map19 = new HashMap<String, String>();
HashMap<String, String> map20 = new HashMap<String, String>();
for(int i = 0 ; i < 15000000; i++){
map.put(String.valueOf(i), "sdaf");
// map1.put(String.valueOf(i), "11");
// map2.put(String.valueOf(i), "11");
// map3.put(String.valueOf(i), "11");
//
// map4.put(String.valueOf(i), "11");
// map5.put(String.valueOf(i), "11");
//
// map6.put(String.valueOf(i), "11");
// map7.put(String.valueOf(i), "11");
//
// map8.put(String.valueOf(i), "11");
// map9.put(String.valueOf(i), "11");
// map10.put(String.valueOf(i), "11");
//
// map11.put(String.valueOf(i), "11");
// map12.put(String.valueOf(i), "11");
// map13.put(String.valueOf(i), "11");
// map14.put(String.valueOf(i), "11");
// map15.put(String.valueOf(i), "11");
// map16.put(String.valueOf(i), "11");
//
// map17.put(String.valueOf(i), "11");
// map18.put(String.valueOf(i), "11");
// map19.put(String.valueOf(i), "11");
// map20.put(String.valueOf(i), "11");
}
System.out.println("haha");
}
| 1 |
private static CellRangeAddress mergeRegion(Doc doc) {
String attr[][] = doc.getAttr();
Td td = (Td) doc;
CellRangeAddress cra = null;
int rowspan = 0;
int colspan = 0;
for (int x = 0; x < attr.length; x++) {
if ("rowspan".equals(attr[x][0]) && (!"".equals(attr[x][1]))) {
rowspan = Integer.parseInt(attr[x][1]);
} else if ("colspan".equals(attr[x][0]) && (!"".equals(attr[x][1]))) {
colspan = Integer.parseInt(attr[x][1]);
}
}
if (rowspan >= 2 && colspan >= 2) {
cra = new CellRangeAddress(td.getAddress()[0], td.getAddress()[0]
+ rowspan - 1, td.getAddress()[1], td.getAddress()[1]
+ colspan - 1);
} else if (rowspan >= 2) {
cra = new CellRangeAddress(td.getAddress()[0], td.getAddress()[0]
+ rowspan - 1, td.getAddress()[1], td.getAddress()[1]);
} else if (colspan >= 2) {
cra = new CellRangeAddress(td.getAddress()[0], td.getAddress()[0],
td.getAddress()[1], td.getAddress()[1] + colspan - 1);
}
return cra;
}
| 9 |
public void updateCurrentQuiz() {
try {
String statement = new String("UPDATE " + DBTable + " SET "
+ "name=?, url=?, description=?, category=?, userid=?, israndom=?, isonepage=?, opfeedback=?, oppractice=?, raternumber=?, rating=?"
+ " WHERE qid=?");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
stmt.setString(1, name);
stmt.setString(2, quizURL);
stmt.setString(3, description);
stmt.setString(4, category);
stmt.setInt(5, creator.userID);
stmt.setBoolean(6, isRandom);
stmt.setBoolean(7, isOnepage);
stmt.setBoolean(8, opFeedback);
stmt.setBoolean(9, opPractice);
stmt.setInt(10, raterNumber);
stmt.setDouble(11, totalRating);
stmt.setInt(12, quizID);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
| 1 |
protected boolean unsingMe(MOB mob, MOB invoker)
{
if(mob==null)
return false;
final Ability A=mob.fetchEffect(ID());
if((A instanceof Song)
&&((invoker==null)||(A.invoker()==null)||(A.invoker()==invoker)))
{
final Song S=(Song)A;
if(S.timeOut==0)
S.timeOut = System.currentTimeMillis()
+ (CMProps.getTickMillis() * (((invoker()!=null)&&(invoker()!=mob))?super.getXTIMELevel(invoker()):0));
if(System.currentTimeMillis() >= S.timeOut)
{
A.unInvoke();
return false;
}
}
return true;
}
| 9 |
public void testFormatAppend_PrinterParser_Printer_null_null_Parser() {
PeriodPrinter printer = new PeriodFormatterBuilder().appendYears().appendLiteral("-").toPrinter();
PeriodParser parser = new PeriodFormatterBuilder().appendWeeks().appendLiteral("-").toParser();
PeriodFormatterBuilder bld = new PeriodFormatterBuilder().append(printer, null).append(null, parser);
assertNull(bld.toPrinter());
assertNull(bld.toParser());
try {
bld.toFormatter();
fail();
} catch (IllegalStateException ex) {}
}
| 1 |
private String loadKeyOfAction(String value) {
if (actionMap == null) {
actionMap = new HashMap<String, String>();
actionMap.put(propertiesLoader.loadProperty(Action.ADVANCE.getKey()), Action.ADVANCE.getKey());
actionMap.put(propertiesLoader.loadProperty(Action.LEFT.getKey()), Action.LEFT.getKey());
actionMap.put(propertiesLoader.loadProperty(Action.RIGHT.getKey()), Action.RIGHT.getKey());
}
return actionMap.get(value);
}
| 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(Records.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Records.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Records.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Records.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 Records().setVisible(true);
}
});
}
| 6 |
private static void setColor(ColorType c, int newColor) {
switch (c) {
case PLAYER:
currentPlayerColor = newColor;
break;
case WALL:
currentWallColor = newColor;
break;
case SLOW_WALL:
currentSlowWallColor = newColor;
break;
case OBJECT:
break;
case PROJECTILE:
break;
default:
break;
}
}
| 5 |
public static float arrayMax(float[] array){
if(array == null || array.length == 0)
return 0;
float max = 0;
for(int i=0; i<array.length;i++){
if(array[i] > max){
max = array[i];
}
}
return max;
}
| 4 |
private static int initOriginal(final Display display, Composite inComposite) {
final Composite originalCompsite = new Composite(inComposite, SWT.BORDER);
int heightHint = 0;
try {
original = new Image(display, Resource.class.getResourceAsStream(IMAGE_PATH));
if (original.getImageData().depth != 8 && original.getImageData().depth != 24)
throw new RuntimeException("Only support 8 bit images. The current image's depth is "
+ original.getImageData().depth);
} catch (Exception e1) {
throw new RuntimeException(e1);
}
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.grabExcessHorizontalSpace = true;
ImageData imageData = original.getImageData();
heightHint = original.getImageData().height + 20;
gridData.heightHint = heightHint;
originalCompsite.setLayoutData(gridData);
originalHisto = ImageUtils.analyzeHistogram(original.getImageData());
originalCompsite.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent event) {
ImageUtils.paintImage(event.gc, original, originalHisto);
}
});
heightHint = (int) Math.sqrt(imageData.width * imageData.width + imageData.height * imageData.height) + 20;
return heightHint;
}
| 3 |
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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.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 Frame().setVisible(true);
}
});
}
| 6 |
public boolean isFull()
{
boolean full = true;
for (int x=0; x<3; x++)
{
for (int y=0; y<3; y++)
{
int[] pos = { x, y };
Player curr = getPlayerAtPosition(pos);
if(curr==null)
{
// Empty spot
full=false;
break;
}
}
if (!full)
{
break;
}
}
return full;
}
| 4 |
void turboBoost() {
}
| 0 |
public static ProtocolFileData getFileDataInBinary(byte[] fileInBytes,
int length) throws TagFormatException {
byte[] subStart = Arrays.copyOfRange(fileInBytes, 0, 11);
byte[] subEnd = Arrays.copyOfRange(fileInBytes, length - 12, length);
byte[] endOfTransfers = Arrays.copyOfRange(fileInBytes, 0, 16);
byte[] content;
boolean isEnd = false;
if (Arrays.equals(endOfTransfers, endOfTransfer)) {
isEnd = true;
content = null;
} else if (Arrays.equals(subStart, fileDataStart)
&& Arrays.equals(subEnd, fileDataEnd)) {
content = Arrays.copyOfRange(fileInBytes, 11, length - 12);
isEnd = false;
} else {
TagFormatException tfe = new TagFormatException(
"It's not a acknowledgement file protocol");
throw tfe;
}
return new ProtocolFileData(content, isEnd);
}
| 3 |
private int lootArea() {
int lootFound = 0;
for (Survivor currentSurvivor : this.raidSettings.getTeam()) {
final int X = currentSurvivor.getSkills().getScavengingSkill(), MIN = Skills.LEVEL_MIN, MAX = Skills.LEVEL_MAX;
double coeff = 1 + ((X - MIN) / ((double) MAX - MIN));
double rand = BitingDeathGame.getRandomProbability() * coeff;
if (rand > 1) {
rand = 1;
}
if (rand > 0.75)
lootFound += 2;
else if (rand > 0.25)
lootFound++;
}
return lootFound;
}
| 4 |
public static ArrayList<StringSequence> formatToStringSequence(ArrayList<String> input)
{
ArrayList <StringSequence> output = new ArrayList<StringSequence>();
String description= "";
StringBuffer currentSequence = new StringBuffer();
//String sequence="";
for(int i=0;i<input.size();i++)
{
if(input.get(i).contains(">"))
{
description=input.get(i);
while(input.get(i+1).contains(">")==false)
{
i++;
currentSequence.append(input.get(i));
//sequence=sequence.concat(input.get(i)); //= sequence +input.get(i);
if(i%10000==0)
{
System.out.println("Formatierte Zeilen: " +i);
}
if(i==input.size()-1)
{
break;
}
}
StringSequence current = new StringSequence(description,currentSequence.toString());
output.add(current);
description="";
currentSequence.delete(0, currentSequence.capacity());
}
}
System.out.println("Formatieren Abgeschlossen!");
return output;
}
| 5 |
public byte[] getPayload() {
return payload;
}
| 0 |
public boolean rankup(Player p) {
if (!p.hasPermission(PERMISSION_RANKUP)) {
p.sendMessage(translate("rankup.no-permission"));
return false;
}
Rank current = ranks.getCurrentRank(perms, p);
if (current == null) {
p.sendMessage(translate("rankup.no-current-rank"));
return false;
}
Rank next = ranks.getNextRank(current);
if (next == null) {
p.sendMessage(translate("rankup.no-next-rank", current.getName()));
return false;
}
double price = next.getPrice();
EconomyResponse transaction = econ.withdrawPlayer(p.getName(), p.getWorld().getName(), price);
if (!transaction.transactionSuccess()) {
p.sendMessage(translate("rankup.no-money", current.getName(), next.getName(), price));
return false;
}
for (GroupAssignment assignment : current.getGroups()) {
perms.playerRemoveGroup(assignment.getWorld(), p.getName(), assignment.getGroup());
}
for (GroupAssignment assignment : next.getGroups()) {
perms.playerAddGroup(assignment.getWorld(), p.getName(), assignment.getGroup());
}
p.sendMessage(translate("rankup.success", current.getName(), next.getName(), price));
getServer().broadcastMessage(translate("rankup.success-broadcast", p.getName(), p.getDisplayName(), current.getName(), next.getName(), price));
return true;
}
| 6 |
private URL makeUrl(String txt) {
try {
txt = URLEncoder.encode(txt.trim(), "UTF-8");
String url;
url = GOOGLE_URL.replace("%lang%", lang.get());
url = url.replace("%txt%", txt);
return new URL(url);
} catch (MalformedURLException ex) {
System.err.println("Error with GoogleVoice (URL): " + ex.getMessage());
return null;
} catch (UnsupportedEncodingException ex) {
System.err.println("Error with GoogleVoice (TXT)[" + txt + "]: " + ex.getMessage());
return null;
}
}
| 2 |
public T getCurrent() {
if(type == TIMED_SEQUENCE) {
if(elapsed >= delay) {
sequence.pollFirst();
elapsed = 0;
}
return sequence.peekFirst();
}
else if(type == RANDOM_SEQUENCE) {
int r = Application.get().getRNG().nextInt(sequence.size());
T t = (T)sequence.toArray()[r];
sequence.remove(t);
return t;
}
else if(type == MANUAL_SEQUENCE) {
return sequence.peekFirst();
}
return null;
}
| 4 |
public Matrix solve (Matrix B) {
if (B.getRowDimension() != m) {
throw new IllegalArgumentException("Matrix row dimensions must agree.");
}
if (!this.isNonsingular()) {
throw new RuntimeException("Matrix is singular.");
}
// Copy right hand side with pivoting
int nx = B.getColumnDimension();
Matrix Xmat = B.getMatrix(piv,0,nx-1);
double[][] X = Xmat.getArray();
// Solve L*Y = B(piv,:)
for (int k = 0; k < n; k++) {
for (int i = k+1; i < n; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
// Solve U*X = Y;
for (int k = n-1; k >= 0; k--) {
for (int j = 0; j < nx; j++) {
X[k][j] /= LU[k][k];
}
for (int i = 0; i < k; i++) {
for (int j = 0; j < nx; j++) {
X[i][j] -= X[k][j]*LU[i][k];
}
}
}
return Xmat;
}
| 9 |
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + (this.tag_alter_preservation ? 1 : 0);
hash = 37 * hash + (this.file_alter_preservation ? 1 : 0);
hash = 37 * hash + (this.read_only ? 1 : 0);
hash = 37
* hash
+ (this.grouping_identity_byte != null ? this.grouping_identity_byte
.hashCode()
: 0);
hash = 37 * hash + (this.compression ? 1 : 0);
hash = 37
* hash
+ (this.encryption_method != null ? this.encryption_method
.hashCode() : 0);
hash = 37 * hash + (this.useDataLengthIndicator ? 1 : 0);
hash = 37
* hash
+ (this.data_length_indicator != null ? this.data_length_indicator
.hashCode()
: 0);
return hash;
}
| 8 |
public int[] shuffle(int data[], int len) {
if (len <= 1) {
return null;
}
for (int i = 0; i < ROUNDS; i++) {
int mid = (len - 1) / 2;
int[] tmpData = new int[len];
for (int j = 0; j < len; j++) {
if (j <= mid) {
tmpData[2 * j] = data[j];
} else {
tmpData[2 * j - len + 1] = data[j];
}
}
data = tmpData;
int splitPos = new Random().nextInt(len);
tmpData = new int[len];
for (int j = splitPos; j < len; j++) {
tmpData[j - splitPos] = data[j];
}
for (int j = 0; j < splitPos; j++) {
tmpData[len - splitPos + j] = data[j];
}
data = tmpData;
}
return data;
}
| 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.