text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
@Override
protected void run() {
long startTime = System.currentTimeMillis();
long elapsedTime = 1;
ClonAlg clonAlg = (ClonAlg) algorithms.get("ClonAlg");
int sameCounter = 0;
clonAlg.run();
runBestIndividual = clonAlg.getBestIndividual();
System.out.println();
boolean reset = false;
while (elapsedTime < 86400000) {
if (sameCounter > 7) {
System.out.println("RESETING ALGORITHM");
clonAlg.setInitialIndividual(null);
runBestIndividual = clonAlg.getBestIndividual();
saveBest();
sameCounter = 0;
reset = true;
} else
clonAlg.setInitialIndividual(clonAlg.getBestIndividual());
clonAlg.run();
if (reset) {
runBestIndividual = clonAlg.getBestIndividual();
reset = false;
}
if (clonAlg.getBestIndividual().getActualDuration() < runBestIndividual.getActualDuration()) {
runBestIndividual = clonAlg.getBestIndividual();
saveBest();
System.out.println("NEW BEST " + runBestIndividual);
sameCounter = 0;
} else {
sameCounter++;
}
elapsedTime = System.currentTimeMillis() - startTime;
System.out.println(
String.format("%d h %d min / 24 h",
TimeUnit.MILLISECONDS.toHours(elapsedTime),
TimeUnit.MILLISECONDS.toMinutes(elapsedTime) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(elapsedTime)))
);
System.out.println();
}
}
| 4 |
@Override
public void collideWith(Element e) {
if (isActive() && e instanceof PlayerCTF)
((PlayerCTF) e).dropFlagOnAdjacentPosition(getGrid().getElementPosition(this));
super.collideWith(e);
}
| 2 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final Physical target=getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_UNWORNONLY);
if(target==null)
return false;
if(target==mob)
{
mob.tell(L("@x1 doesn't look dead yet.",target.name(mob)));
return false;
}
if(!(target instanceof DeadBody))
{
mob.tell(L("You can't preserve that."));
return false;
}
final DeadBody body=(DeadBody)target;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> @x1 to preserve <T-NAMESELF>.^?",prayForWord(mob)));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
body.setExpirationDate(0);
CMLib.threads().deleteTick(body,Tickable.TICKID_DEADBODY_DECAY);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> @x1 to preserve <T-NAMESELF>, but fail(s) miserably.",prayForWord(mob)));
// return whether it worked
return success;
}
| 7 |
public void actionPerformed(ActionEvent e) {
if ("hit".equals(e.getActionCommand())) {
this.game.hit(this.hp, 1);
resetScore();
} else if ("stay".equals(e.getActionCommand())) {
stayStuff();
} else if ("reset".equals(e.getActionCommand())) {
resetGame();
} else if ("bet +10".equals(e.getActionCommand())) {
bm10.setEnabled(true);
bp10method();
} else if ("bet -10".equals(e.getActionCommand())) {
bm10method();
} else if ("doubledown".equals(e.getActionCommand())) {
ddMethod();
}
if ("done".equals(e.getActionCommand())) {
setButtons(true);
done.setEnabled(false);
bp10.setEnabled(false);
bm10.setEnabled(false);
game.dealCards(this.dp, this.hp);
drawScorePanel();
validate();
actualGame();
} else if ("done2".equals(e.getActionCommand())) {
this.game.dcindex = 0;
this.game.pcindex = 0;
for (int p = 0; p < 2; p++) {
this.game.players[p].hand = new Hand();
}
game.dealCards(this.dp, this.hp);
resetScore();
setButtons(true);
bm10.setEnabled(false);
bp10.setEnabled(false);
done.setEnabled(false);
actualGame();
}
// if (currentbet == 30.00) {
// bm10.setEnabled(false);
// } else if (currentbet > 30.00) {
// bm10.setEnabled(true);
// }
validate();
}
| 9 |
@Override
public void initialize(Vertex start) {
this.queue = new Queue();
for (int i = 0; i < edges.getSize(); i++) {
edges.get(i).setVisited(false);
}
for (int i = 0; i < vertices.getSize(); i++) {
vertices.get(i).setColor(VertexColor.WHITE);
vertices.get(i).setDistance(Integer.MAX_VALUE);
vertices.get(i).setPath(null);
}
start.setColor(VertexColor.GRAY);
start.setDistance(0);
queue.enqueue(start);
}
| 2 |
public static void maxHeapify(int[] a, int i, int heapSize) {
int left = left(i);
int right = right(i);
int largest = i;
if (left <= heapSize && a[left] > a[i]) {
largest = left;
}
if (right <= heapSize && a[right] > a[largest]) {
largest = right;
}
if (largest != i) {
swap(a, i, largest);
maxHeapify(a, largest, heapSize);
}
}
| 5 |
public static void main(String[] args) {
List<String> maleTeam = new LinkedList<>();
maleTeam.add("John");
maleTeam.add("Tom");
maleTeam.add("Sam");
maleTeam.add("Vijay");
maleTeam.add("Anthony");
System.out.println("Male Team:" + maleTeam);
List<String> femaleTeam = new LinkedList<>();
femaleTeam.add("Catherine");
femaleTeam.add("Mary");
femaleTeam.add("Shilpa");
femaleTeam.add("Jane");
femaleTeam.add("Anita");
System.out.println("Female Team:" + femaleTeam);
ListIterator<String> maleListIterator = maleTeam.listIterator();
Iterator<String> femaleListIterator = femaleTeam.iterator();
while (femaleListIterator.hasNext()) {
if (maleListIterator.hasNext()) {
maleListIterator.next();
}
maleListIterator.add(femaleListIterator.next());
}
System.out.println("Mixed Team: " + maleTeam);
List<String> disqualify = new LinkedList<>();
disqualify.add("Sam");
disqualify.add("Tom");
disqualify.add("Shilpa");
maleTeam.removeAll(disqualify);
System.out.println("Qualified Team:" + maleTeam);
}
| 2 |
public Missile(Player player, Start start, int dir, int heigth, int width,
GameScreen gameScreen, List<BasicZombie> basicZombieList, Boss boss) {
this.player = player;
this.dir = dir;
this.heigth = heigth;
this.width = width;
this.gameScreen = gameScreen;
this.start = start;
this.basicZombieList = basicZombieList;
if (boss != null) {
this.boss = boss;
}
image = Start.art.getMissile(dir);
switch (dir) {
case 0:
x = boss.getX() + 500;
y = boss.getY() + 200;
rec = new Rectangle(x, y, 8, 20);
case 1:
x = boss.getX() + 26;
y = boss.getY() + 16;
rec = new Rectangle(x, y, 20, 8);
break;
case 2:
x = boss.getX() + 4;
y = boss.getY() + 16;
rec = new Rectangle(x, y, 8, 20);
break;
case 3:
x = boss.getX();
y = boss.getY() + 16;
rec = new Rectangle(x, y, 20, 8);
break;
default:
break;
}
}
| 5 |
private boolean onkoNopeusToisestaPois(Pelihahmo h){
double toisenSuunta = normalisoi(hahmojenValinenKulma(h));
double nopeus = normalisoi(nopeudenSuunta(h));
return nopeus < normalisoi(toisenSuunta - Math.PI/2) && nopeus > normalisoi(toisenSuunta + Math.PI/2);
}
| 1 |
@EventHandler
public void createSignEvent(SignChangeEvent event) {
if (event.isCancelled()) return;
Player player = event.getPlayer();
Block block = event.getBlock();
if (event.getLine(0).equalsIgnoreCase("[Teleporter]")) {
if (!player.hasPermission("TeleportManager.sign.create")) {
player.sendMessage(ChatColor.RED + "Keine Rechte!");
event.setCancelled(true);
return;
}
TeleportManagerPlugin.getManager().addSign(block);
player.sendMessage(ChatColor.GREEN + "Teleport Schild erstellt!");
event.setCancelled(true);
}
}
| 3 |
public static byte[] decodeFromFile(String filename)
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if (file.length() > Integer.MAX_VALUE) {
throw new java.io.IOException(
"File is too big for this convenience method ("
+ file.length() + " bytes).");
} // end if: file too big for int index
buffer = new byte[(int) file.length()];
// Open a stream
bis = new Base64.InputStream(new java.io.BufferedInputStream(
new java.io.FileInputStream(file)), Base64.DECODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[length];
System.arraycopy(buffer, 0, decodedData, 0, length);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return decodedData;
} // end decodeFromFile
| 4 |
public String addUser() {
try {
User user = new User();
user.setId(getId());
user.setName(getName());
user.setSurname(getSurname());
userService.addUser(user);
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
| 1 |
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java Registrar [integer]");
System.exit(1);
}
int n = Integer.parseInt(args[0]);
Registrar server = new Registrar(n);
Utils.out(server.pid, String.format("Registrar started; n = %d.",n));
ServerSocket serversocket = null;
boolean done = false;
try {
serversocket = new ServerSocket(Utils.REGISTRAR_PORT, n);
} catch (IOException e) {
System.err.println("Error: failure to launch registrar.");
System.err.println(e.getMessage());
System.exit(1);
}
while (! done) {
Socket clientsocket = null;
try {
clientsocket = serversocket.accept();
} catch (IOException e) {
System.err.println("Error: failure to accept connection at Registrar.");
System.err.println(e.getMessage());
System.exit(1);
}
/* And so it begins... */
server.handle(clientsocket);
}
}
| 4 |
protected void setDecomposition(int[] decomposition)
{
tempDecomposition = decomposition;
}
| 0 |
public static void actWhenMassiveAttackIsPending(Unit unit) {
// If unit is surrounded by other units (doesn't attack alone)
// if (isPartOfClusterOfMinXUnits(unit)) {
// If there is attack target defined, go for it.
if (StrategyManager.isSomethingToAttackDefined()
&& !MapExploration.getEnemyBuildingsDiscovered().isEmpty()) {
// if (UnitManager.unitIsTooFarFromSafePlaceWhenAttackPending(unit))
// {
// return;
// }
if (UnitManager.isHasValidTargetToAttack(unit)) {
return;
}
if (StrategyManager.getTargetPoint() != null && StrategyManager.getTargetUnit() != null) {
if (!UnitManager.isHasValidTargetToAttack(unit)) {
UnitActions.attackTo(unit, StrategyManager.getTargetPoint());
unit.setAiOrder("Forward!");
}
if (UnitManager.isUnitFullyIdle(unit)) {
UnitActions.spreadOutRandomly(unit);
}
} else {
UnitActions.spreadOutRandomly(unit);
}
}
// If no attack target is defined it probably means that the fog
// of war is hiding from us other enemy buildings
else {
UnitActions.spreadOutRandomly(unit);
}
}
| 7 |
public void giveIntervalReward(Player p, int breaks) {
if (intervalRewards == null || intervalRewards.isEmpty()) {
return;
}
for (Reward r : intervalRewards.values()) {
if (breaks % r.getBlocksNeeded() == 0) {
if (r.getCommands() == null || r.getCommands().isEmpty()) {
return;
}
for (String cmd : r.getCommands()) {
String f = cmd.replace("%player%", p.getName()).replace("%blocksbroken%", breaks+"");
if (cmd.startsWith("ezmsg ")) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', f.replace("ezmsg ", "")));
}
else if (cmd.startsWith("ezbroadcast ")) {
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', f.replace("ezbroadcast ", "")));
}
else {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), f);
}
}
}
}
}
| 9 |
public void mouseClicked(MouseEvent event) {
GrammarTable gt = (GrammarTable) event.getSource();
Point at = event.getPoint();
int row = gt.rowAtPoint(at);
if (row == -1)
return;
if (row == gt.getGrammarModel().getRowCount() - 1)
return;
Production p = gt.getGrammarModel().getProduction(row);
Production[] pItems = Operations.getItems(p);
JPopupMenu menu = new JPopupMenu();
ItemMenuListener itemListener = new ItemMenuListener(p);
for (int i = 0; i < pItems.length; i++) {
JMenuItem item = new JMenuItem(pItems[i].toString());
item.setActionCommand(pItems[i].getRHS());
item.addActionListener(itemListener);
menu.add(item);
}
menu.show(gt, at.x, at.y);
}
| 3 |
public static void matrixsum(int x[][]) {
int sumr = 0, sumc[], sumd1 = 0, sumd2 = 0;
sumc = new int[x[0].length];
for (int i = 0; i < x.length; i++) {
sumr = 0;
System.out.print("\n ");
for (int j = 0; j < x[i].length; j++) {
System.out.print(x[i][j] + " ");
sumc[j] = sumc[j] + x[i][j];
sumr = sumr + x[i][j];
if (i == j) {
sumd1 = sumd1 + x[i][j];
}
if (j == (x[0].length - (i + 1))) {
sumd2 = sumd2 + x[i][j];
}
}
System.out.print(sumr);
}
System.out.print("\n" + sumd2 + " ");
for (int i = 0; i < x[0].length; i++) {
System.out.print(sumc[i] + " ");
}
System.out.print(sumd1);
// System.out.println(sumd1 + "\n" + sumd2 + "\n");
}
| 5 |
public void printConfusionMatrix() {
// print header
System.out.println("Confusion Matrix:\n");
System.out.format("%20s", "");
for (String classifier : testInstances.classifiers()) {
System.out.format("%20s | ", classifier);
}
System.out.println("\n");
// get set of classifiers
Set<String> classifiers = testInstances.classifiers();
// print each classifier group
for (String classifierGroup : classifiers) {
// initialize counters
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String classifier : classifiers) {
counts.put(classifier, 0);
}
// compute counts for each classification
for (int i = 0; i < testInstance.size(); i++) {
Instance instance = testInstance.get(i);
if (instance.classifier().equals(classifierGroup)) {
counts.put(predicted.get(i),
counts.get(predicted.get(i)) + 1);
}
}
// print results for classifier group
System.out.format("%20s", classifierGroup);
for (String classifier : classifiers) {
System.out.format("%20s | ", counts.get(classifier));
}
System.out.println("\n");
}
}
| 6 |
private static void findHelp(BoggleBoard board, LexiconInterface lex, int min, int r, int c, AutoPlayerBoardFirst ap, String word, ArrayList<BoardCell> cellList){
cellList.add(new BoardCell (r, c));
if(lex.containsPrefix(word)){
if(lex.contains(word) && word.length() >= min && !ap.myWords.contains(word)){
ap.add(word);
}
for(int row = r-1; row <= r+1; row++){
for(int col = c-1; col <= c+1; col++){
if(board.isInBounds(row,col) && !cellList.contains(new BoardCell(row, col))){
findHelp(board, lex, min, row, col, ap, word + board.getFace(row, col), cellList);
}
}
}
}
cellList.remove(cellList.get(cellList.size() -1));
}
| 8 |
private void addPart(int gridX, int gridY, int dir, int amount) {
Random random = new Random();
amount += 2;
if (gridY < cloudAtlas.length && gridX < cloudAtlas[0].length - 1 && gridX > -1 && gridY > -1) {
//System.out.println("dir: " + dir + " adding cloud: " + gridX + " " + gridY);
cloudAtlas[gridX][gridY] = true;
if (random.nextInt(50) < (200 / amount)) {
switch (dir) {
case 1:
addPart(gridX, gridY + 1, dir, amount);
break;
case 2:
addPart(gridX + 1, gridY, dir, amount);
break;
case 3:
addPart(gridX, gridY - 1, dir, amount);
break;
case 4:
addPart(gridX - 1, gridY, dir, amount);
break;
}
}
}
}
| 9 |
public String getNombre() {
return nombre;
}
| 0 |
static final public NamesValues namesValuesOf(Map map){
if (map == null){
return new NamesValues(new String[0],new Object[0]);
}
Object[] keys = map.keySet().toArray();
String[] names = new String[keys.length];
Object[] vals = new Object[keys.length];
for (int i = 0 ; i < vals.length; i++){
Object key = keys[i];
names[i] = keys[i].toString();
vals[i] = map.get(keys[i]);
}
return new NamesValues(names,vals);
}
| 2 |
@Test
public void testWritePriceForQuantity() throws Exception {
BigDecimal bd1 = BigDecimal.valueOf(150.00);
product.writePriceForQuantity(7, bd1);
assertTrue(product.getPrices().get(7).equals(bd1));
}
| 0 |
private Object unwrapValue(Object value) {
if (value == null)
return null;
if (value instanceof Wrapper) {
return ((Wrapper) value).getHandle();
} else if (value instanceof List) {
throw new IllegalArgumentException("Can only insert a WrappedList.");
} else if (value instanceof Map) {
throw new IllegalArgumentException("Can only insert a WrappedCompound.");
} else {
return createNbtTag(getPrimitiveType(value), value);
}
}
| 4 |
private void addPlanets(Point3 startPoint, Point3 parallSize, int count ){
Random rand = new Random();
int maxLoopEntries = 10000; //чтоб бесконечно не крутился
while(count > 0 && maxLoopEntries>0){
maxLoopEntries--;
Point3 randPoint = new Point3(
rand.nextDouble()*parallSize.x,
rand.nextDouble()*parallSize.y,
rand.nextDouble()*parallSize.z
);
double newRadius = gameParams.smallestPlanetRadius + rand.nextDouble()*(gameParams.rangePlanetRadius);
Point3 newPosition = startPoint.Add(randPoint);
boolean canBeCreatedHere=true;
for(int i = 0; i < planets.size();i++){
if(newPosition.distTo(planets.get(i).position) <= newRadius + planets.get(i).radius)
{
canBeCreatedHere=false;
break;
}
}
if(canBeCreatedHere){
count--;
planets.add(new Planet(newPosition, newRadius
, rand.nextInt(gameParams.planetColorCount)));
}
}
}
| 5 |
public void addKey(int keyEvent, Key key) {
if (keys.containsKey(keyEvent)) {
keys.get(keyEvent).add(key);
}
else {
ArrayList<Key> newKeyList = new ArrayList<Key>();
newKeyList.add(key);
keys.put(keyEvent, newKeyList);
}
}
| 1 |
public double[] columnStandardErrors(){
double[] standardErrors = new double[this.numberOfRows];
for(int i=0; i<this.numberOfColumns; i++){
double[] hold = new double[this.numberOfRows];
for(int j=0; j<this.numberOfRows; j++){
hold[i] = this.matrix[j][i];
}
Stat st = new Stat(hold);
standardErrors[i] = st.standardError();
}
return standardErrors;
}
| 2 |
public ParkingSpot searchBySpotNumber(String number)
{
ParkingSpot spot = null;
for(TreeSet<ParkingSpot> t: garage.values())
for(ParkingSpot p: t)
if(p.getParkingNumber().equalsIgnoreCase(number))
spot = p;
return spot;
}
| 3 |
public void editTask(HabitItem task) {
boolean flag=false;
int i=0;
while(i<this.items.size() && flag!=true) {
if(this.items.get(i).getId().equals(task.getId())) {
flag=true;
} else {
i++;
}
}
if(flag) {
this.items.set(i, task);
}
}
| 4 |
public FieldVisitor visitField(final int access, final String name,
final String desc, final String signature, final Object value) {
buf.setLength(0);
buf.append('\n');
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
buf.append(tab).append("// DEPRECATED\n");
}
buf.append(tab).append("// access flags 0x")
.append(Integer.toHexString(access).toUpperCase()).append('\n');
if (signature != null) {
buf.append(tab);
appendDescriptor(FIELD_SIGNATURE, signature);
TraceSignatureVisitor sv = new TraceSignatureVisitor(0);
SignatureReader r = new SignatureReader(signature);
r.acceptType(sv);
buf.append(tab).append("// declaration: ")
.append(sv.getDeclaration()).append('\n');
}
buf.append(tab);
appendAccess(access);
appendDescriptor(FIELD_DESCRIPTOR, desc);
buf.append(' ').append(name);
if (value != null) {
buf.append(" = ");
if (value instanceof String) {
buf.append('\"').append(value).append('\"');
} else {
buf.append(value);
}
}
buf.append('\n');
text.add(buf.toString());
TraceFieldVisitor tav = createTraceFieldVisitor();
text.add(tav.getText());
if (cv != null) {
tav.fv = cv.visitField(access, name, desc, signature, value);
}
return tav;
}
| 5 |
public static boolean hasNonVowel(String text)
{
int c = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == 'a' || text.charAt(i) == 'e' || text.charAt(i) == 'i' || text.charAt(i) == 'o' || text.charAt(i) == 'u')
c++;
}
if(c > 1)
return true;
else
return false;
}
| 7 |
public TimerunsDataset(String textPath, int step, int count) throws IOException, ParserConfigurationException, SAXException, AnnotationException, XPathExpressionException{
int currIdx = 0;
String fullBody= loadBody(textPath);
for (int i=0; i<count; i++){
//advance of <step> more words
for (int j=0; j<step; j++){
while (currIdx < fullBody.length() && (fullBody.charAt(currIdx) != ' ' && fullBody.charAt(currIdx) != '\n'))
currIdx++;
while (currIdx < fullBody.length() && (fullBody.charAt(currIdx) == ' ' || fullBody.charAt(currIdx) == '\n'))
currIdx++;
if (currIdx == fullBody.length())
throw new AnnotationException("Cannot make "+count+" documents of "+step+ " words each (lower one of these values).");
}
textList.add(fullBody.substring(0, currIdx));
annList.add(new HashSet<Annotation>());
}
System.out.println("Biggest document will be "+currIdx+" chars long.");
}
| 9 |
public void addLocation(String p_Type, int p_X, int p_Y) throws Exception
{
String add = "add_" + p_Type + "(" + appendPos(p_X, p_Y) + ",A,B).";
SolveInfo info = m_Engine.solve(add);
while(info.isSuccess())
{
String x = info.getVarValue("A").toString();
String y = info.getVarValue("B").toString();
if(!info.hasOpenAlternatives())
break;
info = m_Engine.solveNext();
}
}
| 2 |
private void modificarDatos(){
idLabel.setText(Integer.toString(cliente.getIdCliente()));
nombre.setText(cliente.getNombre());
apellidos.setText(cliente.getApellidos());
apodo.setText(cliente.getApodo());
especial.setSelected(cliente.isEspecial());
}
| 0 |
public boolean buscar(T dato){
boolean resultado = false;
Nodo<T> q = p;
while(q != null){
if(q.getValor().equals(dato)){
resultado = true;
}
q = q.getLiga();
}
return resultado;
}
| 2 |
public int compareTo(Vehicle v) {
if (v.getPosition() > this.getPosition()) {
return 1;
} else if (v.getPosition() < this.getPosition() ) {
return -1;
} else {
return 0;
}
}
| 2 |
public void setOptions(String[] options) throws Exception {
String tmpStr;
String[] tmpOptions;
setChecksTurnedOff(Utils.getFlag("no-checks", options));
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() != 0)
setC(Double.parseDouble(tmpStr));
else
setC(1.0);
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0)
setToleranceParameter(Double.parseDouble(tmpStr));
else
setToleranceParameter(1.0e-3);
tmpStr = Utils.getOption('P', options);
if (tmpStr.length() != 0)
setEpsilon(new Double(tmpStr));
else
setEpsilon(1.0e-12);
setMinimax(Utils.getFlag('I', options));
tmpStr = Utils.getOption('N', options);
if (tmpStr.length() != 0)
setFilterType(new SelectedTag(Integer.parseInt(tmpStr), TAGS_FILTER));
else
setFilterType(new SelectedTag(FILTER_NORMALIZE, TAGS_FILTER));
setBuildLogisticModels(Utils.getFlag('M', options));
tmpStr = Utils.getOption('V', options);
if (tmpStr.length() != 0)
m_numFolds = Integer.parseInt(tmpStr);
else
m_numFolds = -1;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() != 0)
setRandomSeed(Integer.parseInt(tmpStr));
else
setRandomSeed(1);
tmpStr = Utils.getOption('K', options);
tmpOptions = Utils.splitOptions(tmpStr);
if (tmpOptions.length != 0) {
tmpStr = tmpOptions[0];
tmpOptions[0] = "";
setKernel(Kernel.forName(tmpStr, tmpOptions));
}
super.setOptions(options);
}
| 7 |
protected static String convertToWikiIndent(String wikiText) {
String[] linesArr = wikiText.split("\\n");
for (int i = 0; i < linesArr.length; i++) {
if (linesArr[i].trim().isEmpty() == false) {
char firstChar = linesArr[i].trim().charAt(0);
if (Character.isDigit(firstChar)) {
linesArr[i] = "#" + linesArr[i].trim().substring(2);
}
}
}
return ArrayUtils.join(linesArr, "\n");
}
| 3 |
public static void pokemonWasSelected(int pokeIndex, Item item)
{
if(item.effect1==Item.Effect.POKEBALL)
{
usePokeBall(item);
}
else if(item.effect1==Item.Effect.ROD)
{
useRod(item);
}
else if(item.effect1==Item.Effect.REPEL)
{
useRepel(item);
}
else if (item.effect1 != Item.Effect.TM && item.effect1 != Item.Effect.HM)
{
Battle.user[pokeIndex] = useItem(Battle.user[pokeIndex],fullInventory.get(getItemId(item)),false);
}
else
{
Battle.user[pokeIndex] = useTMHM(Battle.user[pokeIndex],fullInventory.get(getItemId(item)));
}
if (!itemCancel)
inventoryWindow.itemUsed = true;
else
itemCancel = false;
inventoryWindow.updateSelection();
inventoryWindow.closeInventory();
if (inventoryWindow.state == InventoryWindow.State.BATTLE && inventoryWindow.itemUsed)
Battle.setUserCommand(-1);
}
| 8 |
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(type.toString() + "[" + value + "]");
if (!constraints.isEmpty()) {
sb.append("{");
for (Constraint def : constraints)
sb.append(def);
sb.append("}");
}
return sb.toString();
}
| 2 |
public void updateMembersList(){
listModelMembers.removeAllElements();
for (String i:admin){
listModelMembers.addElement(i+" (Admin)");
}
for (String i:members){
listModelMembers.addElement(i);
}
for (ExternalUser i:externalUsers){
listModelMembers.addElement(i.getName()+" (External)");
}
}
| 3 |
public static double betacf(double a, double b, double x)
{
double MAXIT = 100;
double EPS = 3e-7;
double FPMIN = 1e-30;
int m, m2;
double aa, c, d, del, h, qab, qam, qap;
qab = a+b;
qap = a+1;
qam = a-1;
c = 1;
d = 1-qab*x/qap;
if (Math.abs(d) < FPMIN) d = FPMIN;
d = 1/d;
h = d;
for (m = 1; m <= MAXIT; m++)
{
m2 = 2*m;
aa = m*(b-m)*x/((qam+m2)*(a+m2));
d = 1+aa*d;
if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1+aa/c;
if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1/d;
h *= d*c;
aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
d = 1+aa*d;
if (Math.abs(d) < FPMIN) d = FPMIN;
c = 1+aa/c;
if (Math.abs(c) < FPMIN) c = FPMIN;
d = 1/d;
del = d*c;
h *= del;
if (Math.abs(del-1) < EPS) break;
}
if (m > MAXIT)
{
System.out.println("a or b too big, or MAXIT too small in betacf");
return Double.NaN;
}
else
return h;
}
| 8 |
@Override
public void actionPerformed(GuiButton button)
{
if(button.id == 0)
{
GameStatistics.lives--;
MapGenerator gen = new MapGeneratorSimple();
Remote2D.guiList.pop();
Remote2D.guiList.push(new GuiLoadMap(gen, 40, 40, 1337));
} else if(button.id == 1)
{
while(!(Remote2D.guiList.peek() instanceof GuiMainMenu)) Remote2D.guiList.pop();
}
}
| 3 |
public static void main(String[] args) throws IOException {
readConfigFile();
File file = new File(CONFIG.getEntryFolder());
for (File currentFolder : file.listFiles()) {
for (String currentProject : CONFIG.getProjectsToCheck()) {
if (currentFolder.getAbsolutePath().endsWith(currentProject)) {
if (currentFolder.isDirectory()) {
replaceUnwantedLines(currentFolder);
removeUnwantedLines(currentFolder);
removeEmptyComments(currentFolder);
addHeaderToXMLFiles(currentFolder);
addHeaderToFiles(currentFolder);
removeDoubleLines(currentFolder);
ensureXmlHeaderLineExistsOnlyOneTime(currentFolder);
countTodoAndFixmes(currentFolder);
}
}
}
}
System.out.println("Checked Projects: " + CONFIG.getProjectsToCheck());
System.out.println("Number of changes: " + COUNTER);
System.out.println("Number of TODO's: " + TODOS.size());
if (!TODOS.isEmpty()) {
System.out.println("TODO's found in: " + TODOS);
}
System.out.println("Number of FIXME's: " + FIXMES.size());
if (!FIXMES.isEmpty()) {
System.out.println("FIXME's found in: " + FIXMES);
}
System.out.println("Number of @Deprecateds: " + DEPRECATEDS.size());
if (!DEPRECATEDS.isEmpty()) {
System.out.println("@Deprecateds found in: " + DEPRECATEDS);
}
}
| 7 |
protected void genDoorName(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
if(E instanceof Item)
mob.tell(L("@x1. Exit Direction (or 'null'): '@x2'.",""+showNumber,E.doorName()));
else
mob.tell(L("@x1. Door Name: '@x2'.",""+showNumber,E.doorName()));
if((showFlag!=showNumber)&&(showFlag>-999))
return;
String newName=mob.session().prompt(L("Enter something new\n\r:"),"");
if(newName.length()>0)
{
if((E instanceof Item)&&(newName.equalsIgnoreCase("null")))
newName="";
E.setExitParams(newName,E.closeWord(),E.openWord(),E.closedText());
}
else
mob.tell(L("(no change)"));
}
| 8 |
private int isDPI(String mnemonic)
{
if(mnemonic.length()!=3 && mnemonic.length()!=5 && mnemonic.length()!=6)
{
return -1;
}
String dpiMnemonics[] = {"and","eor","sub","rsb","add","adc","sbc","rsc","tst","teq","cmp","cmn","orr","mov","bic","mvn"};
System.out.println(mnemonic);
for(int i=0;i<dpiMnemonics.length;i++)
{
if(mnemonic.substring(0, 3).equalsIgnoreCase(dpiMnemonics[i]))
{
System.out.println("i="+i);
return i;
}
}
return -1;
}
| 5 |
static public float atan2_fast(float y, float x) {
// From: http://dspguru.com/comp.dsp/tricks/alg/fxdatan2.htm
float abs_y = y < 0 ? -y : y;
float angle;
if (x >= 0)
angle = 0.7853981633974483f - 0.7853981633974483f * (x - abs_y) / (x + abs_y);
else
angle = 2.356194490192345f - 0.7853981633974483f * (x + abs_y) / (abs_y - x);
return y < 0 ? -angle : angle;
}
| 3 |
public void visit_switch(final Instruction inst) {
final Switch sw = (Switch) inst.operand();
final int[] values = sw.values();
final Label[] targets = sw.targets();
if (values.length == 0) {
if (longBranch) {
addOpcode(Opcode.opc_pop); // Pop switch "index" off stack
addOpcode(Opcode.opc_goto_w);
addLongBranch(sw.defaultTarget());
} else {
addOpcode(Opcode.opc_pop); // Pop switch "index" off stack
addOpcode(Opcode.opc_goto);
addBranch(sw.defaultTarget());
}
} else if (sw.hasContiguousValues()) {
addOpcode(Opcode.opc_tableswitch);
addLongBranch(sw.defaultTarget());
addInt(values[0]);
addInt(values[values.length - 1]);
for (int i = 0; i < targets.length; i++) {
addLongBranch(targets[i]);
}
} else {
addOpcode(Opcode.opc_lookupswitch);
addLongBranch(sw.defaultTarget());
addInt(values.length);
for (int i = 0; i < targets.length; i++) {
addInt(values[i]);
addLongBranch(targets[i]);
}
}
stackHeight--;
}
| 5 |
public void destroy(Long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Ausencia ausencia;
try {
ausencia = em.getReference(Ausencia.class, id);
ausencia.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The ausencia with id " + id + " no longer exists.", enfe);
}
em.remove(ausencia);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
| 2 |
public Door(Transform transform, Material material, Vector3f openPosition)
{
this.transform = transform;
this.openPos = openPosition;
this.closedPos = transform.getPosition();
this.material = material;
opening = false;
closing = false;
open = false;
startTime = 0;
openTime = 0;
closeTime = 0;
startCloseTime = 0;
if(door == null)
{
door = new Mesh();
Vertex[] doorVerts = new Vertex[]{new Vertex(new Vector3f(0,0,0), new Vector2f(0.5f,1)),
new Vertex(new Vector3f(0,1,0), new Vector2f(0.5f,0.75f)),
new Vertex(new Vector3f(1,1,0), new Vector2f(0.75f,0.75f)),
new Vertex(new Vector3f(1,0,0), new Vector2f(0.75f,1)),
new Vertex(new Vector3f(0,0,0), new Vector2f(0.73f,1)),
new Vertex(new Vector3f(0,1,0), new Vector2f(0.73f,0.75f)),
new Vertex(new Vector3f(0,1,0.125f), new Vector2f(0.75f,0.75f)),
new Vertex(new Vector3f(0,0,0.125f), new Vector2f(0.75f,1)),
new Vertex(new Vector3f(0,0,0.125f), new Vector2f(0.5f,1)),
new Vertex(new Vector3f(0,1,0.125f), new Vector2f(0.5f,0.75f)),
new Vertex(new Vector3f(1,1,0.125f), new Vector2f(0.75f,0.75f)),
new Vertex(new Vector3f(1,0,0.125f), new Vector2f(0.75f,1)),
new Vertex(new Vector3f(1,0,0), new Vector2f(0.73f,1)),
new Vertex(new Vector3f(1,1,0), new Vector2f(0.73f,0.75f)),
new Vertex(new Vector3f(1,1,0.125f), new Vector2f(0.75f,0.75f)),
new Vertex(new Vector3f(1,0,0.125f), new Vector2f(0.75f,1))};
int[] doorIndices = new int[] {0,1,2,
0,2,3,
6,5,4,
7,6,4,
10,9,8,
11,10,8,
12,13,14,
12,14,15};
door.addVertices(doorVerts, doorIndices);
}
}
| 1 |
public Builder against(final Object value) {
this.value = value;
return this;
}
| 0 |
private void recursivePrint(int i, Node parentNode, int parentPosition, int depthLeft, int depthRight) {
int newLeftPosition = 2 * i + 1;
Pair left = null;
Node nodeLeft = null;
int parentLeftPosition = parentPosition;
if (newLeftPosition < nodes.length) {
left = nodes[newLeftPosition];
parentLeftPosition = getRectNextLeft(parentLeftPosition, heightFromLeft(i));
if (parentNode != null) {
depthLeft++;
nodeLeft = makeNode("<" + left.p + "," + left.v + ">", new Point(parentLeftPosition, getRectNextTop(depthLeft)), Node.COLOR_LEFT, newLeftPosition);
nodeLeft.setParent(parentNode);
}
}
int newRightPosition = 2 * i + 2;
Pair right = null;
Node nodeRight = null;
int parentRightPosition = parentPosition;
if (newRightPosition < nodes.length) {
right = nodes[newRightPosition];
parentRightPosition = getRectNextRight(parentRightPosition, heightFromRight(i));
if (parentNode != null) {
depthRight++;
nodeRight = makeNode("<" + right.p + "," + right.v + ">", new Point(parentRightPosition, getRectNextTop(depthRight)), Node.COLOR_RIGHT, newRightPosition);
nodeRight.setParent(parentNode);
}
}
if (left != null) {
recursivePrint(newLeftPosition, nodeLeft, parentLeftPosition, depthLeft, depthRight);
}
if (right != null) {
recursivePrint(newRightPosition, nodeRight, parentRightPosition, depthLeft, depthRight);
}
}
| 6 |
private boolean handlePlaceBlocked(Player player, Block block, Material type) {
if (WorldRegionsPlugin.getInstanceConfig().ENABLE_BLOCKED_PLACE && WGCommon.willFlagApply(player, WorldRegionsFlags.BLOCKED_PLACE)) {
// Disabled?
if (WGCommon.areRegionsDisabled(player.getWorld())) return true;
// Bypass?
if (!WGCommon.willFlagApply(player, WorldRegionsFlags.BLOCKED_PLACE)) return true;
// Get blocked
Object blocked = RegionUtil.getFlag(WorldRegionsFlags.BLOCKED_PLACE, block.getLocation());
if (blocked == null) return true;
// Check
BlockList list = (BlockList) blocked;
if (type == Material.STATIONARY_WATER) type = Material.WATER;
if (type == Material.STATIONARY_LAVA) type = Material.LAVA;
if (list.contains(type)) { return false; }
return true;
}
return true;
}
| 8 |
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "Lopeta":
System.exit(0);
break;
case "Kirjaudu ulos":
ikkuna.kirjaaUlos();
break;
case "Uusi käyttäjätunnus/oppilas...":
ikkuna.vaihdaPaneeli(new LisaaKayttaja(ikkuna));
break;
case "Uusi ryhmä":
ikkuna.vaihdaPaneeli(new LisaaRyhma(ikkuna));
break;
case "Uusi kurssi":
ikkuna.vaihdaPaneeli(new LisaaKurssi(ikkuna));
break;
case "Hallinnoi oppilaita/käyttäjiä":
ikkuna.vaihdaPaneeli(new EtsiKayttaja(ikkuna));
break;
case "Hallinnoi kursseja":
ikkuna.vaihdaPaneeli(new EtsiKurssi(ikkuna));
break;
case "Hallinnoi ryhmiä":
ikkuna.vaihdaPaneeli(new EtsiRyhma(ikkuna));
break;
case "Hallinnoi lukujärjestyksiä":
ikkuna.vaihdaPaneeli(new EtsiLukkari(ikkuna));
break;
}
}
| 9 |
public Tile getTile (int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height) return Tile.voidTile;
if (tiles[x + y * width] == Tile.col_grass) return Tile.grass;
if (tiles[x + y * width] == Tile.col_floor) return Tile.floor;
if (tiles[x + y * width] == Tile.col_wall_1) return Tile.wall_1;
if (tiles[x + y * width] == Tile.col_wall_2) return Tile.wall_2;
return Tile.voidTile;
}
| 8 |
@Override
public Descriptor compile(SymbolTable symbolTable) {
Descriptor d = null;
if (subject instanceof IdentNode) {
d = symbolTable.descriptorFor(((IdentNode) subject).getIdentName());
}
if (d instanceof IntConstDescriptor) {
write("PUSHI, " + ((IntConstDescriptor) d).value());
} else if (subject instanceof RecordSelectorNode || subject instanceof ArraySelectorNode || d instanceof RecordDescriptor || d instanceof ArrayDescriptor) {
if (d == null) {
d = subject.compile(symbolTable);
} else {
subject.compile(symbolTable);
}
write("CONT, " + d.size());
return d;
} else {
subject.compile(symbolTable);
write("CONT, 1");
}
return null;
}
| 7 |
private void process(Kernel kernel, int[] in, int[] out, int width, int height, boolean alpha, boolean wrap) {
float[] matrix = kernel.getKernelData( null );
int cols = kernel.getWidth();
int cols2 = cols/2;
for (int y = 0; y < height; y++) {
int index = y;
int ioffset = y*width;
for (int x = 0; x < width; x++) {
float r = 0, g = 0, b = 0, a = 0;
int moffset = cols2;
for (int col = -cols2; col <= cols2; col++) {
float f = matrix[moffset+col];
if (f != 0) {
int ix = x+col;
if (ix < 0) {
if (!wrap) ix = 0; else ix = (x+width) % width;
} else if (ix >= width) {
if (!wrap) ix = width-1; else ix = (x+width) % width;
}
int rgb = in[ioffset+ix];
a += f * ((rgb >> 24) & 0xff);
r += f * ((rgb >> 16) & 0xff);
g += f * ((rgb >> 8) & 0xff);
b += f * (rgb & 0xff);
}
}
int ia = alpha ? clamp((int)(a+0.5)) : 0xff;
int ir = clamp((int)(r+0.5));
int ig = clamp((int)(g+0.5));
int ib = clamp((int)(b+0.5));
out[index] = (ia << 24) | (ir << 16) | (ig << 8) | ib;
index += height;
}
}
}
| 9 |
public static void craftRunesOnAltar(Client c, int requiredlvl, int exp, int item, int x2, int x3, int x4) {
int essamount = 0;
if(!hasRequiredLevel(c, 20, requiredlvl, "runecrafting", "craft this runes")) {
return;
}
if (!c.getItems().playerHasItem(1436)) {
c.sendMessage("You need some rune essence to craft runes!");
return;
}
c.gfx100(186);
c.startAnimation(791);
if ((c.playerLevel[20]) >= 0 && (c.playerLevel[20] < x2)) {
essamount = c.getItems().getItemAmount(1436);
}
if (c.playerLevel[20] >= x2 && c.playerLevel[20] < x3) {
essamount = c.getItems().getItemAmount(1436) * 2;
}
if (c.playerLevel[20] >= x4) {
essamount = c.getItems().getItemAmount(1436) * 3;
}
for (int i = 0; i < 29; i++) {
c.getItems().deleteItem(1436, c.getItems().getItemSlot(1436), i);
}
c.getPA().addSkillXP((exp * essamount) * RUNECRAFTING_XP, 20);
c.getItems().addItem(item, essamount);
c.sendMessage("You bind the temple's power into " + essamount + " " + c.getItems().getItemName(item) + "s.");
c.getPA().requestUpdates();
essamount = -1;
}
| 8 |
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
// Memoize call to unscoped.get() under key.
return new Provider<T>() {
public T get() {
ConcurrentMap<Key<T>, Future<T>> futures = futures();
Future<T> f = futures.get(key);
if (f == null) {
FutureTask<T> creator = new FutureTask<T>(new Callable<T>() {
public T call() {
return unscoped.get();
}
});
f = futures.putIfAbsent(key, creator);
if (f == null) {
f = creator;
creator.run();
}
}
try {
return f.get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof Error) {
throw (Error) t;
}
// Can't be a checked exception, so we cast.
throw (RuntimeException) e.getCause();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new ProvisionException("interrupted during provision", e);
}
}
};
}
| 5 |
static private int jjMoveStringLiteralDfa1_0(long active0)
{
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(0, active0);
return 1;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa2_0(active0, 0x20000L);
case 100:
return jjMoveStringLiteralDfa2_0(active0, 0x40000L);
case 101:
return jjMoveStringLiteralDfa2_0(active0, 0x6000L);
case 111:
return jjMoveStringLiteralDfa2_0(active0, 0x80000L);
default :
break;
}
return jjStartNfa_0(0, active0);
}
| 5 |
public static Node nextInorder(Node node) {
if (node == null)
return null;
Node current = node.getRight();
// If current node has right subtree then the next inorder node is
// leftmost node in right subtree
if (current != null) {
while (current.getLeft() != null)
current = current.getLeft();
return current;
}
// If current node does not have right subtree then next inorder node
// will be at upper levels
current = node;
// keep going if current is the right child. Stop only if current
// becomes the left child of a parent
while (current.getParent() != null && current.isRightChild())
current = current.getParent();
if (current.isRoot())
return null;
else if (!current.isRightChild())
return current.getParent();
else
return null;
}
| 7 |
private void removecurrentChartPanel(){
if(this.currentChartPanel != null){
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
TesterMainGUIMode.this.getContentPane().remove(TesterMainGUIMode.this.currentChartPanel);
TesterMainGUIMode.this.getContentPane().repaint();
}
});
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
}
| 2 |
public static void save(String filename) {
File file = new File(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if (suffix.toLowerCase().equals("png")) {
try { ImageIO.write(onscreenImage, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
// need to change from ARGB to RGB for jpeg
// reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
else if (suffix.toLowerCase().equals("jpg")) {
WritableRaster raster = onscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
try { ImageIO.write(rgbBuffer, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
| 4 |
public static int nextValidInt(Scanner s, int lo, int hi){
Integer input = null;
do{
if (s.hasNextInt()){
input = (Integer) s.nextInt();
}
else{ // Case: there is no integer in the next input
System.out.println("Please input a number.");
s.next(); // this prevents build up of empty lines when Scanner receives empty input but does not return anything or move the cursor
// advances past all empty lines to allow searching for a new valid input
continue; // finish iteration of loop
}
if ((int) input < lo || (int) input > hi){ // Checks if input is within desired bounds
System.out.println("Please input a valid number.");
s.nextLine(); // prevents hasNextInt() infinite loop from the same bad input
// advance Scanner cursor to next line to allow searching for next int
}
}while(input == null || (int) input < lo || (int) input > hi); // Case when non-integer input or input not in desired bounds
return input;
}
| 6 |
@Override
public int compareTo(BussinessMessage o) {
if ((getFieldName() == null) && (o.getFieldName() == null)) {
return getMessage().compareTo(o.getMessage());
} else if ((getFieldName() == null) && (o.getFieldName() != null)) {
return 1;
} else if ((getFieldName() != null) && (o.getFieldName() == null)) {
return -1;
} else if ((getFieldName() != null) && (o.getFieldName() != null)) {
if (getFieldName().equals(o.getFieldName())) {
return getMessage().compareTo(o.getMessage());
} else {
return getFieldName().compareTo(o.getFieldName());
}
} else {
throw new RuntimeException("Error de lógica");
}
}
| 9 |
public void UpdateIndicesOnDelete(Persistent obj) throws IllegalArgumentException, IllegalAccessException
{
String globalName = obj.GetIndexGlobalName();
NodeReference node = connection.createNodeReference(globalName);
Field[] fields = obj.getClass().getFields();
for (int i =0; i< fields.length; i++)
{
Field field = fields[i];
Index annotation = field.getAnnotation(Index.class);
if (annotation != null)
node.kill(annotation.IndexName(), ConvertValueForIndexing(field.get(obj).toString()), obj.Id);
}
}
| 2 |
public static boolean hasDivisibilityProperties(String x) {
boolean d234by2, d345by3, d456by5, d567by7, d678by11, d789by13,
d8910by17;
d234by2 = Long.parseLong(x.substring(1, 4)) % 2 == 0;
d345by3 = Long.parseLong(x.substring(2, 5)) % 3 == 0;
d456by5 = Long.parseLong(x.substring(3, 6)) % 5 == 0;
d567by7 = Long.parseLong(x.substring(4, 7)) % 7 == 0;
d678by11 = Long.parseLong(x.substring(5, 8)) % 11 == 0;
d789by13 = Long.parseLong(x.substring(6, 9)) % 13 == 0;
d8910by17 = Long.parseLong(x.substring(7, 10)) % 17 == 0;
if (d234by2 && d345by3 && d456by5 && d567by7 && d678by11 && d789by13 && d8910by17) {
return true;
} else {
return false;
}
}
| 7 |
public Fee(JSONObject json) throws JSONException {
if (json.has("Amount")) {
this.setAmount(json.getString("Amount"));
}
if (json.has("CurrencyCode")) {
this.setCurrencyCode(json.getString("CurrencyCode"));
}
if (json.has("IncludedInEstTotalInd")) {
this.setIncludedInEstTotalInd(json.getString("IncludedInEstTotalInd"));
}
if (json.has("IncludedInRate")) {
this.setIncludedInRate(json.getString("IncludedInRate"));
}
if (json.has("Description")) {
this.setDescription(json.getString("Description"));
}
if (json.has("TaxInclusive")) {
this.setTaxInclusive(json.getString("TaxInclusive"));
}
}
| 6 |
protected void waitForBridgeView(int expected_size, long timeout, long interval, JChannel ... channels) {
long deadline=System.currentTimeMillis() + timeout;
while(System.currentTimeMillis() < deadline) {
boolean views_correct=true;
for(JChannel ch: channels) {
RELAY2 relay=ch.getProtocolStack().findProtocol(RELAY2.class);
View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER);
if(bridge_view == null || bridge_view.size() != expected_size) {
views_correct=false;
break;
}
}
if(views_correct)
break;
Util.sleep(interval);
}
System.out.println("Bridge views:\n");
for(JChannel ch: channels) {
RELAY2 relay=ch.getProtocolStack().findProtocol(RELAY2.class);
View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER);
System.out.println(ch.getAddress() + ": " + bridge_view);
}
for(JChannel ch: channels) {
RELAY2 relay=ch.getProtocolStack().findProtocol(RELAY2.class);
View bridge_view=relay.getBridgeView(BRIDGE_CLUSTER);
assert bridge_view != null && bridge_view.size() == expected_size
: ch.getAddress() + ": bridge view=" + bridge_view + ", expected=" + expected_size;
}
}
| 8 |
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++)
/*
* <T> Future<T> submit(Callable<T> task) Submits a value-returning
* task for execution and returns a Future representing the pending
* results of the task. The Future's get method will return the
* task's result upon successful completion. If you would like to
* immediately block waiting for a task, you can use constructions
* of the form result = exec.submit(aCallable).get();
*
* Note: The Executors class includes a set of methods that can
* convert some other common closure-like objects, for example,
* PrivilegedAction to Callable form so they can be submitted.
*/
results.add(exec.submit(new TaskWithResult(i)));
for (Future<String> fs : results)
try {
// get() blocks until completion:
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
}
| 4 |
private void allFalse() {
for(boolean bool : keyStates)
bool = false;
}
| 1 |
@Override
public List<ValidateException> validate(String parameter) {
final int maxPatronymicLength = 30;
List<ValidateException> validateExceptionList = new LinkedList<>();
if (!ValidateUtils.stringMaxLengthValidation(parameter, maxPatronymicLength)) {
String exMsg = "entered quite long patronymic";
validateExceptionList.add(new ValidateException(String.format("You %s!", exMsg)));
logger.warn("User {}={}. Max patronymic length={}", exMsg, parameter, maxPatronymicLength);
}
return validateExceptionList;
}
| 1 |
@DataProvider(name = DATA_PROVIDER)
public Object[][] parameterIntTestProvider() {
if (USE_REMOTE_BROWSERS) {
return new Object[][] {
{ new DriverGenerator.RemoteFirefox() },
{ new DriverGenerator.RemoteChrome() } };
} else {
if(USE_STORED_PROFILE_FOR_FIREFOX){
return new Object[][] {
{ new DriverGenerator.ProfileFirefox() },
{ new DriverGenerator.Chrome() }
};
}else{
return new Object[][] {
{ new DriverGenerator.Firefox() },
{ new DriverGenerator.Chrome() }
};
}
}
}
| 2 |
@Override
public void hook(Game game) {
String[] statusb = game.getPlayer().toStatus().split("\n");
StringBuilder sb = new StringBuilder();
int cur = 0;
for (String statusb1 : statusb) {
if (statusb1.contains("\r")) {
sb.append(statusb1).append("\n");
} else {
cur += statusb1.length();
if (cur > getWidth() / getColumnWidth()) {
cur = 0;
sb.append("\n");
}
if (cur == 0 && statusb1.length() > 0 && statusb1.charAt(0) == ' ') {
sb.append(statusb1.substring(1));
} else {
sb.append(statusb1);
}
}
}
setText(sb.toString());
}
| 6 |
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0)
throw new IllegalArgumentException("Invalid args");
// Arrays.sort(ratings); // sort
int n = ratings.length;
int num[] = new int[n];
int sum = 0;
for (int i = 0; i < n; i++)
num[i] = 1;
int k = 1;
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
num[i] = Math.max(++k, num[i]);
} else {
k = 1;
}
}
k = 1;
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
num[i] = Math.max(++k, num[i]);
} else {
k = 1;
}
}
for (int i = 0; i < n; i++)
sum += num[i];
return sum;
}
| 8 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Kokus other = (Kokus) obj;
if (this.nbkoku != other.nbkoku) {
return false;
}
return true;
}
| 3 |
private long updateRewrite(Master master, File f, Location accessLoc, int rewriteCount) {
MasterMeta fm = null;
if (master.map.containsKey(f.getId())) {
fm = master.map.get(f.getId());
} else {
fm = new MasterMeta(f);
master.map.put(f.getId(), fm);
}
int cCount = master.clusters.size();
int writes = 0;
long maxDelay = -1;
for (int i = 0; i < cCount && writes < rewriteCount; i++) {
Cluster cluster = master.clusters.get(i);
if (fm.instances.contains(cluster) || !cluster.isHealthy()) {
continue;
}
FileWrite fw = cluster.write(f, NODE_PER_CLUSTER_WRITE_REDUNDANCY);
double distance = accessLoc.distance(cluster.getLocation());
if (fw.time > 0) { // Cluster had sufficient space.
maxDelay = Math.max(maxDelay, fw.time + Util.networkTime(f.getSize(), distance));
fm.instances.add(cluster);
writes++;
} else if (fw.time != Cluster.NO_SPACE_SENTINEL) {
cluster.calibrateSpaceAvailability(NODE_PER_CLUSTER_WRITE_REDUNDANCY);
}
}
if (writes < rewriteCount) {
return -1;
}
return maxDelay;
}
| 8 |
private void findLastUsage_BFS() {
// TODO Auto-generated method stub
List<Unit> first_node = graph.getHeads();
if(first_node.size()>1){
return;
}
queue.add(first_node.get(0));
units_already_seen.add(first_node.get(0));
while(!queue.isEmpty()){
Unit u = queue.remove();
List<Local> vr = sll.getLiveLocalsAfter(u);
Set<Local> dead_keys = getAllDeadKeys(sll.getLiveLocalsAfter(u));
//map_keyset.removeAll(dead_keys);
if(!dead_keys.isEmpty()){
result_map.put(u, dead_keys);
}
//units_already_seen.add(u);
for(Unit succ: graph.getSuccsOf(u)){
if(!units_already_seen.contains(succ)){
units_already_seen.add(succ);
queue.add(succ);
}
}
}
}
| 5 |
private boolean testHypothesis() {
if (hypothesis == Hypothesis.LESS_THAN
&& testStatistic < criticalRegion) {
return true;
}
else if (hypothesis == Hypothesis.GREATER_THAN
&& testStatistic > criticalRegion) {
return true;
}
else if (hypothesis == Hypothesis.NOT_EQUAL
&& (testStatistic < lowerRegion ||
testStatistic > upperRegion)) {
return true;
}
else
conclusion = "Test statistic is NOT within the critical region \n"
+ "Do NOT reject the null hypothesis";
return false;
}
| 7 |
private static String getShortMachineID() throws Exception
{
String MachineID = null;
String localIP=null;
String timestamp=null;
try{
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()){
NetworkInterface current = interfaces.nextElement();
//System.out.println(current);
if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()){
InetAddress current_addr = addresses.nextElement();
if (current_addr.isLoopbackAddress()) continue;
if (current_addr instanceof Inet4Address)
localIP = current_addr.getHostAddress();
}
}
MachineID = localIP;
}
catch (SocketException e)
{
System.out.println("Unable to get Local Host Address");
System.exit(1);
}
return MachineID;
}
| 8 |
void objectParsed(Object what) {
if (logger.isDebugEnabled()) {
logger.debug("objectParsed()");
}
inParams.addElement(what);
}
| 1 |
private GameObject GetRootObject()
{
if(m_root == null)
m_root = new GameObject();
return m_root;
}
| 1 |
public static double getDouble() throws BadInput {
double num;
try {
String str = getString();
num = Double.parseDouble(str);
} catch(NumberFormatException e) {
throw new BadInput();
}
return num;
}
| 1 |
public void restoreBackedUpTiles(){
System.out.println("restoring backed up tiles: " + backUpNum);
//backUpGoBack();
if(backUpMaps.size() > 0){
int[][][] vecArray = backUpMaps.get(backUpNum);
int[][][] temp = new int[vecArray.length][vecArray[0].length][vecArray[0][0].length];
for(int k = 0; k < vecArray.length; k++){
for(int i = 0; i < vecArray[0].length; i++){
temp[k][i] = Arrays.copyOf(vecArray[k][i], vecArray[k][i].length);
}
}
tileID = temp;
revalidate();
}
}
| 3 |
private void insertUserRoles(String email, Role role, Connection conn) throws SQLException {
PreparedStatement st = null;
String q;
try {
switch (role) {
case administrator: {
q = "INSERT INTO user_roles SET email = ?, roles = ?";
st = conn.prepareStatement(q);
st.setString(1, email);
st.setString(2, Role.administrator.toString());
st.executeUpdate();
}
case scout: {
q = "INSERT INTO user_roles SET email = ?, roles = ?";
st = conn.prepareStatement(q);
st.setString(1, email);
st.setString(2, Role.scout.toString());
st.executeUpdate();
}
case team_member: {
q = "INSERT INTO user_roles SET email = ?, roles = ?";
st = conn.prepareStatement(q);
st.setString(1, email);
st.setString(2, Role.team_member.toString());
st.executeUpdate();
}
}
} catch (SQLException e) {
throw e;
} finally {
try {
st.close();
} catch (SQLException e) {
System.out.println("Unable to close statement");
}
}
}
| 5 |
@Override
public void draw(Graphics g)
{
if (acceptingUserInput() && !captured && closeEnough())
{ //illustrate basics
g.setColor(Color.LIGHT_GRAY);
Point pt = getClosestPt();
g.drawLine(getMouseLoc().x, getMouseLoc().y, pt.x, pt.y);
}
if (acceptingUserInput() && captured)
{ //illustrate change
g.setColor(Color.BLUE);
Point pt = getClosestDrawable().getPoint(index);
g.drawLine(pt.x, pt.y, getClosestPt().x, getClosestPt().y);
}
}
| 5 |
public Ellipse2D getShape()
{
return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
}
| 0 |
private DoubleDate handleUntimedTask(String[] words, int indexOfDate1,
int indexOfDate2, int indexOfFrom, int indexOfTo) {
DoubleDate result = null;
boolean noTime = false;
boolean isNext = false;
if (indexOfDate1 != words.length - 1 && indexOfDate1 > -1) {
String toDateFormat = convertToDateFormat(words, indexOfDate1);
String time1 = "";
isNext = isNextDate(words[indexOfDate1]);
if (isNext && indexOfDate1 != words.length - 2) {
time1 = words[indexOfDate1 + 2];
} else {
time1 = words[indexOfDate1 + 1];
}
result = getDoubleDateTime(toDateFormat, null, time1, null);
if (result.getDate1() != null) {
if (isNext) {
int[] toAdd = { indexOfDate1, indexOfDate1 + 1,
indexOfDate1 + 2 };
addToUsedWords(toAdd);
} else {
int[] toAdd = { indexOfDate1, indexOfDate1 + 1 };
addToUsedWords(toAdd);
}
} else {
noTime = true;
}
} else if (indexOfDate1 < 0) {
return new DoubleDate(null, null);
} else {
noTime = true;
}
if (noTime) {
result = handleUntimedDateOnly(words, indexOfDate1, isNext);
}
return result;
}
| 8 |
@Override
public void update(Observable model, Object msg) {
ObserverMessage message = (ObserverMessage) msg;
if (msg instanceof ObserverMessage) {
if (message.getMessage()==ObserverMessage.NEW_LOG_MESSAGE) {
String logmessage = ((AutoDJModel) model).getLogtext();
if (!logmessage.endsWith("\n")) logmessage+="\n";
logPanel.append(logmessage);
logPanel.setCaretPosition(logPanel.getDocument().getLength());
} else if (message.getMessage()==ObserverMessage.LIBRARY_CHANGED) {
// display new content
libraryList.setListData(((AutoDJModel) model).getSongLibrary());
} else if (message.getMessage()==ObserverMessage.PLAYLIST_CHANGED) {
// display new content
playlistList.setListData(((AutoDJModel) model).getPlaylist());
}
}
}
| 5 |
public void connect(String host, int major, int minor, String key) {
this.host = host;
this.major = major;
this.minor = minor;
this.key = key;
try {
socket = new Socket(host, 43594);
input = socket.getInputStream();
output = socket.getOutputStream();
ByteBuffer buffer = ByteBuffer.allocate(11 + 32);
buffer.put((byte) 15); // handshake type
buffer.put((byte) (9 + 32)); // size
buffer.putInt(major); // client's major version
buffer.putInt(minor); // client's minor version?
buffer.put(key.getBytes()); // handshake key?
buffer.put((byte) 0); // nul-byte (c string)
output.write(buffer.array());
output.flush();
state = State.CONNECTING;
} catch (IOException ioex) {
ioex.printStackTrace();
}
}
| 1 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Train train = (Train) o;
if (id != train.id) return false;
if (totalSeats != train.totalSeats) return false;
if (departure != null ? !departure.equals(train.departure) : train.departure != null) return false;
if (name != null ? !name.equals(train.name) : train.name != null) return false;
return true;
}
| 9 |
void setLink() {
final Shell dialog = new Shell(shell, SWT.APPLICATION_MODAL | SWT.SHELL_TRIM);
dialog.setLayout(new GridLayout(2, false));
dialog.setText(getResourceString("SetLink")); //$NON-NLS-1$
Label label = new Label(dialog, SWT.NONE);
label.setText(getResourceString("URL")); //$NON-NLS-1$
final Text text = new Text(dialog, SWT.SINGLE);
text.setLayoutData(new GridData(200, SWT.DEFAULT));
if (link != null) {
text.setText(link);
text.selectAll();
}
final Button okButton = new Button(dialog, SWT.PUSH);
okButton.setText(getResourceString("Ok")); //$NON-NLS-1$
final Button cancelButton = new Button(dialog, SWT.PUSH);
cancelButton.setText(getResourceString("Cancel")); //$NON-NLS-1$
Listener listener = new Listener() {
public void handleEvent(Event event) {
if (event.widget == okButton) {
link = text.getText();
setStyle(UNDERLINE_LINK);
}
dialog.dispose();
}
};
okButton.addListener(SWT.Selection, listener);
cancelButton.addListener(SWT.Selection, listener);
dialog.setDefaultButton(okButton);
dialog.pack();
dialog.open();
while (!dialog.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
| 4 |
@Override
public synchronized void setName(String name) {
this.name = name;
}
| 0 |
private void handleDropItem(Message m, GameSession s) {
Player p = s.getPlayer();
m.readInt();
int slot = m.readLEShortA() & 0xFFFF;
m.readLEShort();
if(slot < 0 || slot >= 28 || p.getInventory().get(slot) == null) {
return;
}
Item item = p.getInventory().get(slot);
World.getSingleton().getGroundItemManager().dropItem(p, item);
p.getInventory().set(slot, null);
p.getInventory().refresh();
}
| 3 |
public void heapify(int indeksi){
int vasen = left(indeksi);
int oikea = right(indeksi);
int pienin;
if(oikea <= heapsize){
if(keko[vasen].getPaino() < keko[oikea].getPaino()){
pienin = vasen;
}
else{
pienin = oikea;
}
if(keko[indeksi].getPaino() > keko[pienin].getPaino()){
vaihdaAlkioidenPaikkaa(indeksi, pienin);
heapify(pienin);
}
else if(vasen == heapsize && keko[indeksi].getPaino() > keko[vasen].getPaino()){
vaihdaAlkioidenPaikkaa(indeksi, vasen);
}
}
}
| 5 |
public void updateCurrentPoints(PlayerCharacter girl) {
double value = 0;
String message = "";
if (challengeNumber == 1) {
value = attributes.get(0).getAttributeValue();
} else if (challengeNumber == 2) {
value = attributes.get(1).getAttributeValue();
} else if (challengeNumber == 3) {
value = attributes.get(2).getAttributeValue();
} else if (challengeNumber == 4) {
value = attributes.get(3).getAttributeValue();
} else if (challengeNumber == 5) {
value = attributes.get(4).getAttributeValue();
}
double tmpV = value;
if (value == 0) {
value = 1;
} else {
value = value/(0.2);
}
/*if (girl.attributes.get(0).getAttributeType().equals(challenge)) {
tmpV*=0.5;
}*/
currentPoints += value;
challenges[challengeNumber] = 1;
if (currentPoints <= 0) currentPoints = 0;
//return "current points are = " +currentPoints+" value = "+value;
}
| 7 |
@EventHandler(priority = EventPriority.HIGH)
public void onBlockDamage(BlockDamageEvent event) {
if (event.isCancelled())
return;
Block bl = event.getBlock();
Location loc = bl.getLocation();
if (bl.getType().equals(Material.ANVIL)) {
if (plugin.anvils.containsKey(loc)) {
ItemStack hand = event.getPlayer().getItemInHand();
ItemMeta meta = hand.getItemMeta();
if (hand.getType().equals(Material.STONE_PICKAXE)
&& meta.getDisplayName().equals(
ChatColor.WHITE + "Hammer")) {
event.setCancelled(true);
}
}
}
}
| 5 |
private final long method714(int i) {
long l = System.nanoTime();
long l2 = 0L;
long l1 = -aLong3105 + l;
aLong3105 = l;
if (0xfffffffed5fa0e00L < l1 && ~l1 > 0xfffffffed5fa0dffL) {
aLongArray3103[anInt3104] = l1;
anInt3104 = (1 + anInt3104) % 10;
if (anInt3106 < 1) {
anInt3106++;
}
}
int j = 1;
if (i != -2) {
return -124L;
}
for (; ~j >= ~anInt3106; j++) {
l2 += aLongArray3103[(-j + (anInt3104 - -10)) % 10];
}
return l2 / (long) anInt3106;
}
| 5 |
private void setPopupMenu(JComponent component) {
//Создаем контекстное меню
final JPopupMenu popup = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Отменить заявку");
popup.add(menuItem);
//Добавляем слушателя на нажатие кнопки меню и на показ контекстного меню
menuItem.addActionListener(new ActionListener() {
//Отмена выбранной заявки
public void actionPerformed(ActionEvent e) {
buttonBackActionPerformed(e);
}
});
//Щелчок правой кнопкой мыши
component.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
//Проверка на вызов контекстного меню
if (event.isPopupTrigger()) {
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
});
//Добавляем контекстное меню в компонент
component.add(popup);
}
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.