text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static QuestionGeneration[] general() throws Exception {
int[] categoryID = randomGeneration("categories");
String[] category = new String[10];
DatabaseResult db;
int[] quesID = new int[10];
for (int i = 0; i < 10; i++) {
db = new DatabaseResult("categories");
while (db.getResult().next()) {
if (db.getResult().getInt(1) == categoryID[i]) {
category[i] = db.getResult().getString(2);
}
}
}
for (int i = 0; i < 10; i++) {
quesID[i] = randomInt(category[i]);
}
QuestionGeneration[] questionTemp = new QuestionGeneration[10];
for (int i = 0; i < 10; i++) {
questionTemp[i] = new QuestionGeneration();
}
for (int i = 0; i < 10; i++) {
db = new DatabaseResult(category[i]);
while (db.getResult().next()) {
if (db.getResult().getInt(1) == quesID[i]) {
questionTemp[i].question = db.getResult().getString(2);
questionTemp[i].answer = db.getResult().getString(3);
int j = 4;
for (int k = 0; k < 4; k++) {
questionTemp[i].option[k] = db.getResult().getString(j++);
}
}
}
}
return questionTemp;
} | 9 |
public void keyPressed(KeyEvent e) {
int x = e.getKeyCode();
// Exit if the user hit <ESC>
if (x == KeyEvent.VK_ESCAPE) {
System.exit(0);
}
int prevDir = game.pacman.getDirection();
// Movement controls
if (x == KeyEvent.VK_LEFT) {
game.pacman.setDirection(Directions.LEFT);
} else if (x == KeyEvent.VK_RIGHT) {
game.pacman.setDirection(Directions.RIGHT);
} else if (x == KeyEvent.VK_UP) {
game.pacman.setDirection(Directions.UP);
} else if (x == KeyEvent.VK_DOWN) {
game.pacman.setDirection(Directions.DOWN);
}
//However, if Pacman is now colliding with something, revert it.
if (game.isCollision(game.pacman)) {
game.pacman.setDirection(prevDir);
}
} | 6 |
public static void inv( DenseMatrix64F mat , DenseMatrix64F inv ) {
double max = Math.abs(mat.data[0]);
int N = mat.getNumElements();
for( int i = 1; i < N; i++ ) {
double a = Math.abs(mat.data[i]);
if( a > max ) max = a;
}
if( mat.numRows == 2 ) {
inv2(mat,inv,1.0/max);
} else if( mat.numRows == 3 ) {
inv3(mat,inv,1.0/max);
} else if( mat.numRows == 4 ) {
inv4(mat,inv,1.0/max);
} else if( mat.numRows == 5 ) {
inv5(mat,inv,1.0/max);
} else {
throw new IllegalArgumentException("Not supported");
}
} | 6 |
@Override
public int match(String[] argsToTest) {
for (String testArg : argsToTest) {
if (isCommandArg(testArg)) {
boolean argIsOK = false;
for (String allowedElem : allowed) {
if (testArg.equals(allowedElem)) {
argIsOK = true;
}
}
if (!argIsOK) {
addMismatch(testArg);
}
}
}
if (hasMismatches()) {
return Constants.ERROR;
}
return Constants.OK;
} | 6 |
public static void main(String[] args) {
NullPlumbus nullPlumbus = new NullPlumbus(); // standard null plumbus created as such
IPlumbus nameBrandPlumbus = new NameBrandPlumbus("The Original Plumbus", 5.99); // plumbus interface created as a NameBrandPlumbus
NullPlumbus offBrandPlumbus = new OffBrandPlumbus(); // a null plubmus created as an off brand plumbus
ArrayList<IPlumbus> plumbuses = new ArrayList<IPlumbus>(); // collection of the plumbus interface
// add all plumbuses to the array
plumbuses.add(nullPlumbus);
plumbuses.add(nameBrandPlumbus);
plumbuses.add(offBrandPlumbus);
for (IPlumbus plumbus : plumbuses) {
System.out.println("Plumbus Diagnostic");
System.out.println("**************************");
String name = plumbus.getBrandName() != null ? plumbus.getBrandName() : "<NONE>";
double plumbusRatio = plumbus.getPlumbusRatio();
System.out.printf("Brand name: %s%n", name);
System.out.printf("Price: %.2f%n", plumbus.getPrice());
System.out.printf("Plumbus ratio: %.2f%n", plumbusRatio);
if (plumbusRatio >= 90.00) {
System.out.println("This is a true plumbus");
} else if (plumbus instanceof NullPlumbus) {
System.out.println("We've found a null plumbus");
}
System.out.println("**************************");
System.out.println("");
}
} | 4 |
private int searchrow(int[][] matrix,int target,int b,int e)
{
if (b >= e) return -1;
if (b == e-1 ) return b;
int mid = (b + e) /2;
if (matrix[mid][0] <= target && target <= matrix[mid][matrix[mid].length -1] ) return mid;
if (matrix[mid][0] > target ) return searchrow(matrix,target,b, mid);
return searchrow(matrix,target,mid+1,e);
} | 5 |
@Override
public String toString() {
return "[someStrArray=" + Arrays.deepToString(someStrArray)
+ ", someObjArray=" + Arrays.deepToString(someObjArray)
+ ", someList=" + someList + ", someMap=" + someMap + "]";
} | 0 |
@SuppressWarnings("unchecked")
protected ResourceBag() {
Type t = this.getClass().getGenericSuperclass();
Type param = ((ParameterizedType) t).getActualTypeArguments()[0];
if (!(param instanceof Class)) {
throw new IllegalArgumentException("Field to detect our type!");
}
this.type = (Class<T>) param;
this.resources = new ArrayList<T>();
} | 1 |
public void tallennaOsaamistasonTunniste() {
if (tokaTekstikentta.getText().equals("melkein")){
osaamistasonTunniste = "\tMELKEIN";
} else if (tokaTekstikentta.getText().equals("ei")){
osaamistasonTunniste = "\tEI";
} else {
osaamistasonTunniste = ""; //jos käyttäjä ei ole muokannut kenttää tai on muokannut sitä väärin, kaikki merkit kerrataan
}
} | 2 |
public static void writeToStream(String text, Buffer stream) {
if (text.length() > 80)
text = text.substring(0, 80);
text = text.toLowerCase();
int i = -1;
for (int c = 0; c < text.length(); c++) {
char character = text.charAt(c);
int characterCode = 0;
for (int l = 0; l < validChars.length; l++) {
if (character != validChars[l])
continue;
characterCode = l;
break;
}
if (characterCode > 12)
characterCode += 195;
if (i == -1) {
if (characterCode < 13)
i = characterCode;
else
stream.put(characterCode);
} else if (characterCode < 13) {
stream.put((i << 4) + characterCode);
i = -1;
} else {
stream.put((i << 4) + (characterCode >> 4));
i = characterCode & 0xf;
}
}
if (i != -1)
stream.put(i << 4);
} | 9 |
public boolean checkUserData() {
if (logView.getUsername().equals("")
&& logView.getPassword().equals("")) {
JOptionPane
.showMessageDialog(
logView,
"Bitte korrigieren Sie Ihren Kundennamen und Ihr Kundenpasswort!",
"Kein Kundennamen und Passwort angegeben",
JOptionPane.ERROR_MESSAGE);
} else if (logView.getPassword().equals("")
&& !logView.getUsername().equals("")) {
JOptionPane.showMessageDialog(logView,
"Bitte korrigieren Sie ihr Kundenpasswort!",
"Kein Passwort angegeben", JOptionPane.ERROR_MESSAGE);
} else if (!logView.getPassword().equals("")
&& logView.getUsername().equals("")) {
JOptionPane.showMessageDialog(logView,
"Bitte korrigieren Sie Ihren Kundennamen!",
"Kein Kundenname angegeben", JOptionPane.ERROR_MESSAGE);
}
if (!logView.getUsername().equals("")
&& !logView.getPassword().equals("")) {
return true;
}
return false;
} | 8 |
@EventHandler
public void EndermanSlow(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEndermanConfig().getDouble("Enderman.Slow.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getEndermanConfig().getBoolean("Enderman.Slow.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, plugin.getEndermanConfig().getInt("Enderman.Slow.Time"), plugin.getEndermanConfig().getInt("Enderman.Slow.Power")));
}
} | 6 |
public void forwardSelect(boolean withReplacement, Instances instances,
int metric) throws Exception {
double bestPerformance = -1.0;
int bestIndex = -1;
double tempPredictions[][];
for (int i = 0; i < m_bagSize; ++i) {
// For each model in the bag
if ((m_timesChosen[i] == 0) || withReplacement) {
// If the model has not been chosen, or we're allowing
// replacement
// Get the predictions we would have if we add this model to the
// ensemble
tempPredictions = computePredictions(i, true);
// And find out how the hypothetical ensemble would perform.
double metric_value = evaluatePredictions(instances,
tempPredictions, metric);
if (metric_value > bestPerformance) {
// If it's better than our current best, make it our NEW
// best.
bestIndex = i;
bestPerformance = metric_value;
}
}
}
if (bestIndex == -1) {
// Replacement must be false, with more hillclimb iterations than
// models. Do nothing and return.
if (m_debug) {
System.out.println("Couldn't add model. No action performed.");
}
return;
}
// We picked bestIndex as our best model. Update appropriate info.
m_timesChosen[bestIndex]++;
m_numChosen++;
if (bestPerformance > m_bestPerformance) {
// We find the peak of our performance over all hillclimb
// iterations.
// If this forwardSelect step improved our overall performance,
// update
// our best ensemble info.
updateBestTimesChosen();
m_bestPerformance = bestPerformance;
}
} | 7 |
protected Rectangle getAutomatonBounds() {
Rectangle rect = drawer.getBounds();
if (rect == null)
return new Rectangle(getSize());
return rect;
} | 1 |
public static void main(String[] args) {
ArrayList<WeightedItem<String>> itemList = new ArrayList<WeightedItem<String>>();
itemList.add(new WeightedItem<String>("A", 30));
itemList.add(new WeightedItem<String>("B", 45));
itemList.add(new WeightedItem<String>("C", 5));
itemList.add(new WeightedItem<String>("D", 20));
double totalWeight = 0;
for(int i = 0; i < itemList.size(); i++){
itemList.get(i).setStart(totalWeight);
totalWeight += itemList.get(i).getWeight();
itemList.get(i).setEnd(totalWeight);
}
for(int i = 0; i < 100; i++){
double n = Math.random()*totalWeight%totalWeight;
for(int j = 0; j < itemList.size(); j++){
if(itemList.get(j).getStart() <= n && n < itemList.get(j).getEnd()){
itemList.get(j).increment();
break;
}
}
}
for(int i = 0; i < itemList.size(); i++){
String item = itemList.get(i).getItem();
double weight = itemList.get(i).getWeight();
int count = itemList.get(i).getCount();
System.out.println(item+": "+weight+" "+count);
}
return;
} | 6 |
public int setNeighbourNull(TetrahedronElt3D element, ScalarOperator sop) {
TetrahedronElt3D neighbour = this.getNeighbour(0);
if (neighbour != null && neighbour.isGeometryEquivalent(element, sop)) {
this.eltZero = null;
return 0;
}
neighbour = this.getNeighbour(1);
if (neighbour != null && neighbour.isGeometryEquivalent(element, sop)) {
this.eltOne = null;
return 1;
}
neighbour = this.getNeighbour(2);
if (neighbour != null && neighbour.isGeometryEquivalent(element, sop)) {
this.eltTwo = null;
return 2;
}
neighbour = this.getNeighbour(3);
if (neighbour != null && neighbour.isGeometryEquivalent(element, sop)) {
this.eltThree = null;
return 3;
}
return -1;
} | 8 |
public int getColumnCount() {
return terminals.length + 2;
} | 0 |
public void undo()
{
if (DEBUG) log("Attempting to undo TaskEdit");
if (taskViewsToUpdate != null)
{
if (DEBUG) log("currentState Completed? " + currentState.isCompleted());
if (DEBUG) log("previousState Completed? " + previousState.isCompleted());
if (DEBUG) log("Revert task to previous state");
currentState.updateFrom(previousState);
if (DEBUG) log("currentState completed after revert? " + currentState.isCompleted());
if (DEBUG) log("Update taskViews");
for (TaskView taskView : taskViewsToUpdate)
{
taskView.updateTaskInfo();
}
}
} | 8 |
@EventHandler
public void BlazeInvisibility(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getBlazeConfig().getDouble("Blaze.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getBlazeConfig().getBoolean("Blaze.Invisibility.Enabled", true) && damager instanceof Blaze && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getBlazeConfig().getInt("Blaze.Invisibility.Time"), plugin.getBlazeConfig().getInt("Blaze.Invisibility.Power")));
}
} | 6 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AjoutAcompteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AjoutAcompteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AjoutAcompteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AjoutAcompteEtudiant.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
AjoutAcompteEtudiant dialog = new AjoutAcompteEtudiant(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
} | 6 |
public void load() {
cookieslap.chat.log("Loading map " + this.name + ".");
usable = false;
this.file = new File(cookieslap.getDataFolder(), this.name + ".yml");
try {
if (!this.file.exists())
this.file.createNewFile();
} catch (IOException e) {
}
this.setConfig(YamlConfiguration.loadConfiguration(file));
save();
loadSpawns();
loadFloors();
if (this.spawncount > 0) {
usable = true;
} else {
cookieslap.chat.log("Spawn count is 0");
usable = false;
}
if (this.floorcount > 0) {
usable = true;
} else {
cookieslap.chat.log("No floors are setup.");
usable = false;
}
if (usable) {
cookieslap.chat.log("Map is usable");
} else {
cookieslap.chat.log("--<>-- PLEASE SETUP MAP!! --<>--");
}
cookieslap.chat.log("Load Complete!");
} | 5 |
public void loadTowerTypes(){
int x = 1;
try {
while(true){
InputStream is = Main.class.getResourceAsStream(RES_DIR + "towers/" + x + ".cfg");
if(is==null){break;}
byte[] b = new byte[Main.class.getResource(RES_DIR + "towers/" + x + ".cfg").openConnection().getContentLength()];
is.read(b);
is.close();
String s = new String(b);
TowerType t = new TowerType(m, x);
t.setType(findValue(s,"type"));
t.setAttackSpeed( Double.parseDouble(findValue(s,"attackSpeed")) );
t.setDamage( Double.parseDouble(findValue(s,"damage")) );
t.setProjectileSpeed( Double.parseDouble(findValue(s,"projectileSpeed")) );
t.setProjectileAnimationStandDuration( Integer.parseInt(findValue(s, "projectileAnimationStandDuration")) );
t.setProjectileAnimationDeathDuration( Integer.parseInt(findValue(s, "projectileAnimationDeathDuration")) );
t.setRange( Double.parseDouble(findValue(s, "range")) );
t.setAnimationStandDuration( Integer.parseInt(findValue(s, "animationStandDuration")) );
t.setAnimationPreAttackDuration( Integer.parseInt(findValue(s, "animationPreAttackDuration")) );
t.setAnimationPostAttackDuration( Integer.parseInt(findValue(s, "animationPostAttackDuration")) );
t.setBase( findTowerTypeById(Integer.parseInt(findValue(s, "base"))) );
t.setCost( Integer.parseInt(findValue(s, "cost")) );
t.setDescription( findValue(s, "description") );
t.setShootingAir( Boolean.parseBoolean(findValue(s, "shootingAir")) );
if(t.getType().equals(TowerType.TOWER_TYPE_MULTI_TARGET))
t.addArg("maxTargets", Integer.parseInt(findValue(s, "maxTargets")));
if(t.getType().equals(TowerType.TOWER_TYPE_SIEGE))
t.addArg("splashRadius", Double.parseDouble(findValue(s, "splashRadius")));
if(t.getType().equals(TowerType.TOWER_TYPE_DEBUFFER)){
String s2 = findValue(s, "debuffs");
ArrayList<BuffType> debuffs = new ArrayList<BuffType>();
for(String s3 : s2.split(":")){
if(s3.equals("")) continue;
debuffs.add(findBuffTypeById(Integer.parseInt(s3)));
}
t.addArg("debuffs", debuffs);
}
////////////////////////////////////////////////////////
t.setAnimationStand( ImageIO.read(Main.class.getResourceAsStream(RES_DIR + "towers/" + x + "-stand.png")) );
t.setAnimationPreAttack( ImageIO.read(Main.class.getResourceAsStream(RES_DIR + "towers/" + x + "-preAttack.png")) );
t.setAnimationPostAttack( ImageIO.read(Main.class.getResourceAsStream(RES_DIR + "towers/" + x + "-postAttack.png")) );
t.setProjectileAnimationStand( ImageIO.read(Main.class.getResourceAsStream(RES_DIR + "towers/" + x + "-projectileStand.png")) );
t.setProjectileAnimationDeath( ImageIO.read(Main.class.getResourceAsStream(RES_DIR + "towers/" + x + "-projectileDeath.png")) );
setNewTowerType(t);
x++;
}
}
catch (MalformedURLException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
} | 9 |
private void flipVertical() {
switch(direction)
{
case EAST:
case WEST:
break;
case NORTH:
setDirection(Direction.SOUTH);
break;
case SOUTH:
setDirection(Direction.NORTH);
break;
case NORTHEAST:
setDirection(Direction.SOUTHEAST);
break;
case NORTHWEST:
setDirection(Direction.SOUTHWEST);
break;
case SOUTHEAST:
setDirection(Direction.NORTHEAST);
break;
case SOUTHWEST:
setDirection(Direction.NORTHWEST);
break;
}
} | 8 |
public Frame() {
container = this.getContentPane();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth() / 3;
int screenHeight = (int) dim.getHeight() / 3;
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
logTextArea = new JTextArea();
container.add(BorderLayout.NORTH,logTextArea);
panel = new JPanel();
container.add( BorderLayout.CENTER, panel);
startServer = new JButton("Start Server");
panel.add(startServer);
portLabel = new JLabel("Server Port:");
panel.add(portLabel);
portText = new JTextField(6);
portText.setText("8080");
panel.add(portText);
setLocation(screenWidth, screenHeight);
setSize(screenWidth, screenHeight);
addCloseAction();
} | 0 |
public void addHunterListListener(final HunterListListener listener) {
if (listener != null && !listenersHunter.contains(listener)) {
this.listenersHunter.add(listener);
}
} | 2 |
void updateMyMovement(Player player, Stream outStream) {
synchronized (player) {
if (player.mapRegionChanged) {
sendMapRegion();
}
if (player.playerTeleported) {
outStream.createFrameVarSizeWord(81);
outStream.initBitAccess();
outStream.writeBits(1, 1);
outStream.writeBits(2, 3);
outStream.writeBits(2, player.height);
outStream.writeBits(1, 1);
outStream.writeBits(1, (player.updateRequired) ? 1 : 0);
outStream.writeBits(7, player.curY);
outStream.writeBits(7, player.curX);
return;
}
if (player.primaryDirection == -1) {
outStream.createFrameVarSizeWord(81);
outStream.initBitAccess();
player.isMoving = false;
if (player.updateRequired) {
outStream.writeBits(1, 1);
outStream.writeBits(2, 0);
} else {
outStream.writeBits(1, 0);
}
} else {
outStream.createFrameVarSizeWord(81);
outStream.initBitAccess();
outStream.writeBits(1, 1);
if (player.secondaryDirection == -1) {
player.isMoving = true;
outStream.writeBits(2, 1);
outStream.writeBits(3,
Misc.xlateDirection[player.primaryDirection]);
if (player.updateRequired)
outStream.writeBits(1, 1);
else
outStream.writeBits(1, 0);
} else {
player.isMoving = true;
outStream.writeBits(2, 2);
outStream.writeBits(3,
Misc.xlateDirection[player.primaryDirection]);
outStream.writeBits(3,
Misc.xlateDirection[player.secondaryDirection]);
if (player.updateRequired)
outStream.writeBits(1, 1);
else
outStream.writeBits(1, 0);
}
}
}
} | 8 |
public void print(Object... objects) {
System.out.print(String.format("%-30s: ", this.getClass()
.getSimpleName()));
if (objects != null) {
for (Object obj : objects) {
System.out.print(obj);
System.out.print(" ");
}
System.out.println();
}
} | 2 |
@Around("demo.spring.aop.DemoIntercepter.anyPublicOperation()")
public Object aroundTest(ProceedingJoinPoint target ) {
try {
Object[] args = target.getArgs();
System.out.println("mae[" + array2Str(args) + "]");
Object result = target.proceed(args);
System.out.println("ato[" + result + "]");
return result;
} catch (Throwable e) {
throw new RuntimeException(e);
}
} | 1 |
@Override
public void handleEvent(Event event) {
if (event.getType().equals(StateUpdateEvent.TYPE)) {
handleStateEvent((StateUpdateEvent) event);
}
} | 1 |
public void addCity() {
int max=getPreference(WORLD.map[0][0]);
ArrayList<Point> best=new ArrayList<Point>();
best.add(WORLD.map[0][0]);
for (int y=0;y<WORLD.HEIGHT;y++)
for (int x=0;x<WORLD.WIDTH;x++)
if (WORLD.map[x][y].owner==null)
if (getPreference(WORLD.map[x][y])>max) {
best.clear();
best.add(WORLD.map[x][y]);
max=getPreference(WORLD.map[x][y]);
} else if (getPreference(WORLD.map[x][y])==max)
best.add(WORLD.map[x][y]);
if (max>0) {
City c=new City(this,best.get(rand(best.size()+cities.size())%best.size()),rand(cities.size()+future.size())%populationDensity+1,cities.size()-1,max/4);
future.add(c);
} else {
for (City c:cities) {
c.maxPopulation<<=1;
c.maxSize<<=1;
}
}
} | 7 |
@Override
public CommandResponse executeCommand(RequestType requestType, List<Pair<String,String>> headers, String commandName, Object commandParameters, Class<?> responseCastClass){
CommandResponse result;
if(requestType.name().toLowerCase().equals("get")) {
result = doGet(commandName, headers, commandParameters, responseCastClass);
}
else {
result = doPost(commandName, headers, commandParameters, responseCastClass);
}
return result;
} | 2 |
public Move AlphaBetaSearch(Board board, GamePlay game, int color,
int alpha, int beta, int depthLimit, int depth) {
game.setColor(color);
if ((depthLimit <= depth) || (game.isGameOver())) {
int[] scores = game.getScores();
Move m = new Move(color, false, new Point(0, 0));
m.setScore(scores[2]);
return m;
} // end if
ArrayList<Piece> pieces = new ArrayList<Piece>();
if (color == 0)
pieces = game.getMovableBlackPieces(board);
else if (color == 1)
pieces = game.getMovableWhitePieces(board);
Move m1 = new Move(color, false, new Point(0, 0));
for (int i = 0; i < pieces.size(); i++) {
Point p = pieces.get(i).getPosition();
Piece pc = board.getPiece(p);
ArrayList<String> actions = game.getPieceActions(board, pc);
for (int j = 0; j < actions.size(); j++) {
String action = actions.get(j);
// place stone on the board
game.movePiece(board, p, action);
m1.setDirection(action);
m1.setNextPosition(p);
int c = this.enemyColor(color);
Move m2 = this.AlphaBetaSearch(board, game, c, -beta, -alpha,
depthLimit, depth + 1);
m2.setNextPosition(p);
m2.setScore(-1 * m2.getScore());
int value = m2.getScore();
m1.setScore(value);
if (value > alpha)
alpha = value;
game.undoMove(board);
if (value >= beta) {
m1.setScore(beta);
return m1;
}
} // end for
} // end for
m1.setScore(alpha);
return m1;
} // end AlphaBeta() | 8 |
public Entiteetti luoEntiteetti(EntiteettiTyyppi tyyppi, int x, int y) {
switch (tyyppi) {
case PALLO:
return luoPallo(x, y);
case PELAAJA_MAILA:
return luoPelaajanMaila(x, y);
case TEKOALY_MAILA:
return luoTekoalyMaila(x, y);
case STAATTINEN_ESTE:
return luoStaattinenEste(x, y);
case KIMPOILEVA_ESTE:
return luoKimpoilevaEste(x, y);
}
return null;
} | 5 |
public ChartPanel getChartPanel(){
//створюємо панель для графіка
final ChartPanel chartPanel = new ChartPanel(getChart());
//встановлюємо розмір діаграми (можна також скористатись методами JFreeChart цього)
chartPanel.setPreferredSize(new java.awt.Dimension(380, 350));
//додаємо панель на створений нами фрейм
chartPanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JOptionPane.showMessageDialog(p, "text", "title",JOptionPane.ERROR_MESSAGE);
}
});
// frame.setContentPane(chartPanel);
// //підганяємо розміри фрейму
// frame.pack();
// //робимо усе видимим
return chartPanel;
} | 0 |
public Vasara() {
} | 0 |
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFromTo(BlockFromToEvent e) {
CBlock conBlock = parent.getControllerBlockFor(null, e.getToBlock()
.getLocation(), null, Boolean.valueOf(true));
if (conBlock == null) {
return;
}
if (conBlock.isBeingEdited()) {
if (!parent.blockPhysicsEditCheck) {
return;
}
Player player = getPlayerEditing(conBlock);
parent.log
.debug("Block at "
+ Util.formatLocation(e.getToBlock().getLocation())
+ " was drowned while editing and removed from a controller");
conBlock.delBlock(e.getToBlock());
player.sendMessage("Removing block due to change while editing "
+ Util.formatBlockCount(conBlock));
} else {
BlockProtectMode protect = (BlockProtectMode) parent.getConfigu()
.getOpt(Config.Option.BlockFlowProtectMode);
if (protect.equals(BlockProtectMode.protect)) {
e.setCancelled(true);
} else if (protect.equals(BlockProtectMode.remove)) {
conBlock.delBlock(e.getBlock());
}
}
} | 5 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected)))
{
switch(msg.sourceMinor())
{
case CMMsg.TYP_ADVANCE:
unInvoke();
break;
}
}
else
if((msg.amITarget(affected))
&&(msg.targetMinor()==CMMsg.TYP_SNIFF)
&&(CMLib.flags().canSmell(msg.source())))
msg.source().tell(msg.source(),affected,null,L("<T-NAME> smell(s) nauseatingly stinky!"));
super.executeMsg(myHost,msg);
} | 7 |
public void render(Screen screen){
for(Button b : buttons) b.render(font, screen);
for(TextField tf : textFields) tf.render(screen);
for(Label l : labels) l.render(screen);
if(error != "") font.render(error, 10, 10, 0xffff0000, 1, true, screen);
} | 4 |
@Override
public void visitFieldInsn(final int opcode, final String owner,
final String name, final String desc) {
mv.visitFieldInsn(opcode, owner, name, desc);
if (constructor) {
char c = desc.charAt(0);
boolean longOrDouble = c == 'J' || c == 'D';
switch (opcode) {
case GETSTATIC:
pushValue(OTHER);
if (longOrDouble) {
pushValue(OTHER);
}
break;
case PUTSTATIC:
popValue();
if (longOrDouble) {
popValue();
}
break;
case PUTFIELD:
popValue();
if (longOrDouble) {
popValue();
popValue();
}
break;
// case GETFIELD:
default:
if (longOrDouble) {
pushValue(OTHER);
}
}
}
} | 9 |
public String getOutput()
{
return ((MooreMachine) (to.getAutomaton())).getOutput(to);
} | 0 |
public void open() {
Display display = Display.getDefault();
createContents();
shlNewPolicy.open();
shlNewPolicy.layout();
while (!shlNewPolicy.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} | 2 |
public String getDownloadPath(){
if (prop.getProperty("downloadPath").isEmpty()) return System.getProperty ("user.dir");
return prop.getProperty("downloadPath", System.getProperty ("user.dir"));
} | 1 |
@Override
public void map(LongWritable key, Text value, OutputCollector<UserIdPairWritable, UserRatingPairWritable> output, Reporter reporter) throws IOException {
StringTokenizer tokenizer = new StringTokenizer(value.toString(), ";");
Vector<Integer> vec = new Vector<Integer>();
int i, j, x, y;
// Loop over all users and add their ratings to our vector. We have to use a vector because we don't know how
// many users we have.
while (tokenizer.hasMoreTokens()) vec.add(Integer.valueOf(tokenizer.nextToken()));
// Loop twice over our users to create user pairs for correlation computation in the reduce task.
for (i = 0; i < vec.size(); i++) {
for (j = 0; j < vec.size(); j++) {
// Skip user pairs which we've already computed.
if (j < i) continue;
// Only add this pair if both have a valid rating for this joke. This replaces any intersection methods.
if ((x = vec.get(i)) != 99 && (y = vec.get(j)) != 99) {
output.collect(
new UserIdPairWritable(i, j), // User IDs of our user pair.
new UserRatingPairWritable(x, y) // Ratings for this joke of our user pair.
);
}
}
}
} | 6 |
@Override
public Grid generateGrid() {
playerFactory.generate();
// Give the players some items to start
for (Player player : grid.getAllPlayersOnGrid()) {
final LightGrenade item1 = new LightGrenade(grid);
player.getInventory().add(item1);
final IdentityDisc item2 = new IdentityDisc(grid);
player.getInventory().add(item2);
final ChargedIdentityDisc item3 = new ChargedIdentityDisc(grid);
player.getInventory().add(item3);
final LightGrenade item4 = new LightGrenade(grid);
player.getInventory().add(item4);
}
// add some elements to the grid
final Wall wall1 = new Wall(grid);
final Wall wall2 = new Wall(grid);
for (int i = -1; i < 2; i++) {
Position pos1 = Direction.RIGHT.newPosition(new Position(2 + i, 9));
Position pos2 = Direction.RIGHT.newPosition(new Position(i, 1));
grid.addElementToPosition(wall1, pos1);
grid.addElementToPosition(wall2, pos2);
}
final LightGrenade lightGrenade1 = new LightGrenade(grid);
grid.addElementToPosition(lightGrenade1, new Position(0, 7));
final LightGrenade lightGrenade2 = new LightGrenade(grid);
grid.addElementToPosition(lightGrenade2, new Position(1, 7));
final LightGrenade activeLightGrenade1 = new LightGrenade(grid, true);
grid.addElementToPosition(activeLightGrenade1, new Position(2, 8));
final LightGrenade activeLightGrenade2 = new LightGrenade(grid, true);
grid.addElementToPosition(activeLightGrenade2, new Position(1, 6));
final Teleporter teleport1 = new Teleporter(grid);
final Teleporter teleport2 = new Teleporter(grid);
teleport1.setDestination(teleport2);
teleport2.setDestination(teleport1);
grid.addElementToPosition(teleport1, new Position(0, 5));
grid.addElementToPosition(teleport2, new Position(0, 2));
// add some effects to the grid
final PrimaryPowerFailure powerFailure1 = new PrimaryPowerFailure(grid, 3);
grid.addElementToPosition(powerFailure1, new Position(1, 6));
final PrimaryPowerFailure powerFailure2 = new PrimaryPowerFailure(grid, 3);
grid.addElementToPosition(powerFailure2, new Position(1, 7));
final PrimaryPowerFailure powerFailure3 = new PrimaryPowerFailure(grid, 3);
grid.addElementToPosition(powerFailure3, new Position(1, 8));
return grid;
} | 2 |
public static double effectiveSampleNumberConjugateCalcn(Complex[] ww) {
Complex[] weight = Conv.copy(ww);
if (Stat.weightingOptionS) {
ArrayMaths am = new ArrayMaths(ww);
am = am.pow(2);
am = am.invert();
weight = am.array_as_Complex();
}
int n = weight.length;
double nEff = Double.NaN;
if (Stat.nEffOptionS) {
Complex sumw2 = Complex.zero();
Complex sum2w = Complex.zero();
for (int i = 0; i < n; i++) {
sum2w = sum2w.plus(weight[i]);
sumw2 = sumw2.plus(weight[i].times(weight[i].conjugate()));
}
sum2w = sum2w.times(sum2w.conjugate());
nEff = sum2w.getReal() / sumw2.getReal();
}
return nEff;
} | 3 |
@Override
public boolean isDisconnect() {
return disconnect;
} | 0 |
public ArrayList<Pair<String, Color>> getSectionColors(String section, String pref) {
ArrayList<Pair<String, Color>> buf = new ArrayList<Pair<String, Color>>();
for (String j : map.keySet()) {
String[] val = j.split("\\.");
if (val[0].equals(section)) {
buf.add(new Pair<String, Color>(pref + val[1], Color.decode(map.get(j))));
}
}
return buf;
} | 2 |
@Override
public void draw(Graphics g, int x, int y, int side) {
Graphics2D g2d = (Graphics2D) g;
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .35f));
g.drawImage(ResourceManager.getImage("shadow"), x, y, side, side, null);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
super.draw(g, x, y, side);
if (washealed > 0) {
g.drawImage(ResourceManager.getImage("heal"), x, y, side, side, null);
}
if (!washurt.isEmpty()) {
for (Integer i : washurt) {
int hx = x + (new Random().nextInt((side / 3) * 2));
int hy = y + (new Random().nextInt((side / 7) * 4)) + side / 6;
g.drawImage(ResourceManager.getImage("hurt"), hx, hy, side / 3, side / 3, null);
g.setFont(new Font(Font.MONOSPACED, Font.PLAIN, (side / 3) - 3));
g.setColor(Color.WHITE);
g.drawString(i + "", hx + side / 12, hy + (side / 7) * 2);
}
}
if (maxhp() != hp() || washealed > 0) {
g.setColor(Color.BLACK);
g.fillRect(x + 4, y, side - 8, 4);
g.setColor(Color.RED);
int bl = (int) (((double) (side - 8.0) / (double) maxhp()) * (double) hp());
g.fillRect(x + 4, y + 1, bl, 2);
if (!washurt.isEmpty()) {
int tot = 0;
for (Integer i : washurt) {
tot += i;
}
g.setColor(Color.WHITE);
int bn = (int) (((double) (side - 8.0) / (double) maxhp()) * (double) tot);
g.fillRect(x + 4 + bl, y + 1, bn, 2);
}
if (washealed > 0) {
g.setColor(Color.GREEN);
int bn = (int) (((double) (side - 8.0) / (double) maxhp()) * (double) washealed);
g.fillRect(x + 4 + bl - bn, y + 1, bn, 2);
}
}
washurt.clear();
washealed = -1;
} | 8 |
public boolean write(aos.apib.OutStream out, aos.apib.Base o) {
AuthenticationResult v = (AuthenticationResult)o;
int i = -1;
while ((i = out.nextField(i, this)) >= 0) {
switch (i) {
case 0:
out.putBool(v.authentication, i, __def.authentication, this);
break;
case 1:
out.putOther(v.peerList, i, __def.peerList, this);
break;
case 4:
out.writeBaseClasses(o, this);
break;
default:
if (i >= 0 && i <= 4) break;
out.error("Writer for AuthenticationResult: illegal field number:"+i);
return false;
}
}
return true;
} | 6 |
private void tramsformToHtml(Transformer transformer, File xmlFile) {
if (transformer != null) {
File html = new File("logs/html/" + xmlFile.getName() + ".html");
if (!html.exists()) {
boolean success;
try {
success = html.createNewFile();
if (!success) {
throw new IOException();
}
} catch (IOException e) {
e.printStackTrace();
System.err.println("can not create file: " + html.getAbsolutePath());
}
}
transformer.setParameter("logName", xmlFile.getName());
try {
transformer.transform(new StreamSource(xmlFile), new StreamResult(html));
} catch (TransformerException e) {
e.printStackTrace();
System.err.println("transformer exception: " + e.getMessage());
}
}
} | 5 |
public JTextField getjTextFieldVilleNom() {
return jTextFieldVilleNom;
} | 0 |
public void actionPerformed(ActionEvent e){
//When the upload button is pressed
if (e.getSource()==generateButton) {
treasureModel.clear();
if((Integer) levelSpinner.getValue() > 30 || (Integer) levelSpinner.getValue() < 1){
JOptionPane.showMessageDialog(
RunGenerator.this,
" Selected level must be between 1 and 30.",
"Error: Invalid Level",
JOptionPane.INFORMATION_MESSAGE);
} else {
Random rand;
int coin;
int good;
int item;
List<String> output = new ArrayList<String>();
int level = (Integer) levelSpinner.getValue();
rand = new Random();
CoinGen cg = new CoinGen();
GoodGen gg = new GoodGen();
ItemGen ig = new ItemGen();
coin = (rand.nextInt(100) + 1);
cg.doGenerate(level, coin);
output.add(cg.getCoins());
good = (rand.nextInt(100)+1);
gg.doGenerate(level, good);
for(String x:gg.getGoods()){
output.add(x);
}
item = (rand.nextInt(100)+1);
ig.doGenerate(level, item);
for(String x:ig.getItems()){
output.add(x);
}
for(String x:output){
treasureModel.addElement(x);
}
}
}
} | 6 |
@Override
public void setProgress(int i) {
// Need to sleep since NT4.0 doesn't share so well with threads, and it's likely that this dialog
// is running in a different thread from the process updating things. Note: when setProgress is
// called it is executing in the thread from the process calling the method, not the thread the dialog
// is in. Basically this gives swing time to updated the GUI.
try {
if (sleepCounter == 0) {
Thread.sleep(10);
} else if (sleepCounter == SLEEP_LIMIT) {
sleepCounter = 0;
} else {
sleepCounter++;
}
} catch (Exception e) {}
//System.out.println(getMinimum() + ":" + i + ":" + getMaximum());
if (isVisible()) {
if (i >= getMaximum()) {
setCanceled(true);
close();
}
}
bar.setValue(i);
} | 5 |
public boolean isEqual(LiteralLabel value1, LiteralLabel value2) {
if (value1.getDatatype() instanceof XSDDouble && value2.getDatatype() instanceof XSDDouble) {
Double n1, n2;
n1 = null;
n2 = null;
Object v1 = value1.getLexicalForm();
Object v2 = value2.getLexicalForm();
boolean v1String = false;
boolean v2String = false;
try {
n1 = new Double(Double.parseDouble(v1.toString()));
} catch (NumberFormatException ex) {
v1String = true;
}
try {
n2 = new Double(Double.parseDouble(v2.toString()));
} catch (NumberFormatException ex) {
v2String = true;
}
if(v1String && v2String) {
return v1.equals(v2);
}
else {
if(v1String || v2String) {
return false;
}
else {
return n1.doubleValue() == n2.doubleValue();
}
}
} else {
// At least one arg is not part of the integer hierarchy
return false;
}
} | 8 |
protected void processWindowEvent(
WindowEvent event )
{
if (event.getID() == WindowEvent.WINDOW_CLOSING)
{
actionCancel();
}
super.processWindowEvent(event);
} | 1 |
public List<Ant> placeAnts(AntBrain blackBrain, AntBrain redBrain) {
List<Ant> list = new ArrayList<>();
int id = 0;
for (int[] cell : anthillCells) {
if (getCell(cell).anthill.equalsIgnoreCase("black")) {
Ant black = new Ant(blackBrain, true, id++);
black.setPostition(cell);
getCell(cell).ant = black;
list.add(black);
} else if (getCell(cell).anthill.equalsIgnoreCase("red")) {
Ant red = new Ant(redBrain, false, id++);
red.setPostition(cell);
getCell(cell).ant = red;
list.add(red);
}
}
return list;
} | 3 |
public LED(int port) {
_led = new PWM(port);
} | 0 |
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
// Draws the "You're dead" message on the screen.
g.drawString(dead, 50, 50);
// Draws the name TextField on the screen and instructions.
if (addScore && !added){
g.drawString("Enter your name and hit enter", 50, 360);
// Draws the name text field.
nameTF.render(gc, g);
nameTF.setBackgroundColor(Color.black);
nameTF.setFocus(true);
}
if (noNameSpecified){
g.drawString("You must enter a name.", 50, 345);
}
// Confirms that the score has been added to the table.
if (added){
g.drawString("Your score has been added to the highscores table", 50, 360);
}
} | 4 |
private static void loadExecutionPlansForSQLStatements(List<DeltaSQLStatementSnapshot> sqlStatementsToLoad) {
Connection connection = null;
try {
connection = ConnectionPoolUtils.getConnectionFromPool();
PreparedStatement sqlExecutionPlansStatement = connection
.prepareStatement(SELECT_EXECUTION_PLANS_FOR_100_STATEMENTS);
sqlExecutionPlansStatement.setFetchSize(1000);
int indexPlaceholder = 1;
for (DeltaSQLStatementSnapshot currentStatement : sqlStatementsToLoad) {
sqlExecutionPlansStatement.setString(indexPlaceholder,
currentStatement.getSqlStatement().getSqlId());
indexPlaceholder++;
if (indexPlaceholder > NUMBER_BIND_VARIABLES_SELECT_EXECUTION_PLAN) {
// all place holders are filled - so fetch the execution
// plans from the DB
getExecutionPlansFromDB(sqlStatementsToLoad,
sqlExecutionPlansStatement);
indexPlaceholder = 1;
}
}
if (indexPlaceholder > 1) {
// there are some statements left...
// fill the empty bind variables with invalid addresses
for (int index = indexPlaceholder; index <= NUMBER_BIND_VARIABLES_SELECT_EXECUTION_PLAN; index++) {
sqlExecutionPlansStatement.setString(index, "");
}
getExecutionPlansFromDB(sqlStatementsToLoad,
sqlExecutionPlansStatement);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
} finally {
ConnectionPoolUtils.returnConnectionToPool(connection);
}
} | 5 |
@Override
public void rotationPiece()
{
if(largeur==2 && matrice[0][0]!=null)
{
positionX--;
positionY++;
}
else if(largeur==3 && matrice[0][0]!=null){
positionY--;
}
else if(largeur==3 && matrice[0][0]==null){
positionX++;
}
super.rotationPiece();
} | 6 |
public void load(String fileName){
try{
Scanner input = new Scanner(new File(fileName));
shapeList.clear();
selindex = -1;
int count = Integer.parseInt(input.nextLine());
while(input.hasNext()){
String line = input.nextLine();
String [] params = line.split(":");
int x = Integer.parseInt(params[1]);
int y = Integer.parseInt(params[2]);
int wid = Integer.parseInt(params[3]);
int height = Integer.parseInt(params[4]);
String text = null;
if(params.length>5)
text = params[5];
if(text == null)
text = "";
TextBox t = null;
if(params[0].compareTo("TextRectangle")==0){
t = new TextRectangle(x,y,wid,height);
}else if(params[0].compareTo("TextEllipse")==0){
t = new TextEllipse(x,y,wid,height);
}else if(params[0].compareTo("TextRoundRect")==0){
t = new TextRoundRect(x,y,wid,height);
}
if(t!=null){
t.setText(text);
shapeList.add(t);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
repaint();
} | 8 |
boolean isValidMessage(String identifier) {
return "cantPick".equals(identifier) ||
"cantTraverse".equals(identifier) ||
"cantDo".equals(identifier) ||
"didntUnderstand".equals(identifier) ||
"pickedUp".equals(identifier) ||
"emptyInventory".equals(identifier) ||
"changedLocation".equals(identifier) ||
"currentLocation".equals(identifier);
} | 7 |
public Book createBook(int bookNum) {
Book b = null;
Card d0 = new Card(bookNum, 'h');
Card d1 = new Card(bookNum, 'c');
Card d2 = new Card(bookNum, 's');
Card d3 = new Card(bookNum, 'd');
if (checkBook()) {
b = new Book(bookNum);
Card[] bookCards = b.getCards();
Card c = null;
try {
bookCards[0] = returnAndRemove(d0);
bookCards[1] = returnAndRemove(d1);
bookCards[2] = returnAndRemove(d2);
bookCards[3] = returnAndRemove(d3);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return b;
} | 2 |
public static String readString() {
if (isEmpty()) throw new RuntimeException("Reading from empty input stream");
StringBuilder sb = new StringBuilder();
while (!isEmpty()) {
char c = readChar();
sb.append(c);
}
return sb.toString();
} | 2 |
float getRadius() {
/*
* cloud radius is a function of it's age.
* here's the model...
*
* volume of rising air, dv ~ constant.
* decay ~ surface area.
* dynamic equilibrium, dv = decay, at maturity.
* dv = 0 at old age.
*/
float fn;
if (age <= t_nose) {
fn = (float) Math.sqrt((double) age / t_nose);
} else if (age > t_nose && age <= t_nose + t_mature) {
fn = 1;
} else if (age > t_mature + t_nose && age <= t_mature + t_nose + t_tail) {
fn = (float) Math.sqrt(1 - (double) (age - t_mature - t_nose) / t_tail);
} else {
fn = 0;
}
return fn * maxRadius;
} | 5 |
public boolean isNewer (String onlineVersion, String storedVersion) {
if (storedVersion == null || storedVersion.isEmpty())
return true;
String[] oV = onlineVersion.split("[._-]");
String[] sV = storedVersion.split("[._-]");
Logger.logInfo(onlineVersion + " " + storedVersion);
for (int i = 0; i < oV.length; i++) {
if (sV.length > i) {
if (Integer.parseInt(oV[i]) > Integer.parseInt(sV[i])) {
Logger.logInfo(oV[i] + ">" + sV[i]);
Logger.logInfo("ret true");
return true;
} else if (Integer.parseInt(oV[i]) < Integer.parseInt(sV[i])) {
return false;
//stored would be older in this case
}
}
}
Logger.logInfo("ret False");
return false;
} | 6 |
public void testGetInstantMillisInvalid() {
try {
StringConverter.INSTANCE.getInstantMillis("", (Chronology) null);
fail();
} catch (IllegalArgumentException ex) {}
try {
StringConverter.INSTANCE.getInstantMillis("X", (Chronology) null);
fail();
} catch (IllegalArgumentException ex) {}
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MeetingImpl)) return false;
MeetingImpl meeting = (MeetingImpl) o;
if (meetingID != meeting.meetingID) return false;
if (!meetingAttendees.equals(meeting.meetingAttendees)) return false;
if (!scheduledDate.equals(meeting.scheduledDate)) return false;
return true;
} | 5 |
public void putLabelConfiguration( ConnectionLabelConfiguration name, DefaultConnectionLabelConfiguration config ) {
if( config == null ) {
labelConfigurations.remove( name );
} else {
labelConfigurations.put( name, config );
}
} | 1 |
private void updateScreen(Player player, boolean ifFriendly) {
if (!ifFriendly) {
sendInventory(player);
stake.clear();
stake2.clear();
}
player.getPackets().sendItems(134, false, stake);
player.getPackets().sendItems(134, true, stake2);
player.getPackets().sendItems(94, false,
player.getInventory().getItems());
player.getPackets().sendIComponentText(
ifFriendly ? 637 : 631,
ifFriendly ? 16 : 38,
" "
+ Utils.formatPlayerNameForDisplay(getOther(player)
.getUsername()));
player.getPackets().sendIComponentText(ifFriendly ? 637 : 631,
ifFriendly ? 18 : 40,
"" + (getOther(player).getSkills().getCombatLevel()));
player.getPackets().sendConfig(286, 0);
player.getTemporaryAttributtes().put("firstScreen", true);
player.getInterfaceManager().sendInterface(ifFriendly ? 637 : 631);
} | 6 |
public static void main(String[] paramArrayOfString) {
try {
MyProxyLogon localMyProxyLogon = new MyProxyLogon();
String str = null;
logger.setLevel(Level.ALL);
System.out
.println("Warning: terminal will echo passphrase as you type.");
System.out.print("MyProxy Passphrase: ");
str = readLine(System.in);
if (str == null) {
System.err.println("Error reading passphrase.");
System.exit(1);
}
localMyProxyLogon.setPassphrase(str);
localMyProxyLogon.requestTrustRoots(true);
localMyProxyLogon.getCredentials();
localMyProxyLogon.writeProxyFile();
System.out.println("Credential written successfully.");
X509Certificate[] arrayOfX509Certificate = localMyProxyLogon
.getTrustedCAs();
if (arrayOfX509Certificate != null) {
System.out.println(Integer
.toString(arrayOfX509Certificate.length)
+ " CA certificates received.");
}
X509CRL[] arrayOfX509CRL = localMyProxyLogon.getCRLs();
if (arrayOfX509CRL != null) {
System.out.println(Integer.toString(arrayOfX509CRL.length)
+ " CRLs received.");
}
if (localMyProxyLogon.writeTrustRoots()) {
System.out.println("Wrote trust roots to " + getTrustRootPath()
+ ".");
} else {
System.out
.println("Received no trust roots from MyProxy server.");
}
} catch (Exception localException) {
localException.printStackTrace(System.err);
}
} | 5 |
public void rMayusCentrosLocal(double paramDistancia,double paramRadio)
{
Iterator elemFuente;
Elemento entrada,salida;
Iterator elemDestino = destino.listaElementos();
double sumaDistancias,sumaValores,distancia,ponderacion,rMayor;
double dist[];
int count;
while(elemDestino.hasNext()) //Recorre elementos destino
{
sumaDistancias = sumaValores = 0; // inicializa sumas
salida = (Elemento)((Entry)elemDestino.next()).getValue();
elemFuente = fuente.listaElementos(); //carga fuentes
rMayor = 0;
dist = new double[fuente.numeElementos()];
count = 0;
while(elemFuente.hasNext()) //recorre elementos fuente
{
entrada = (Elemento)((Entry)elemFuente.next()).getValue();
distancia = distanciaCentros(entrada,salida);
dist[count] = distancia;
count ++;
rMayor = (distancia > rMayor && distancia < paramRadio)?distancia:rMayor;
}
elemFuente = fuente.listaElementos();
count = 0;
while(elemFuente.hasNext()) //recorre elementos fuente
{
Elemento e = (Elemento)((Entry)elemFuente.next()).getValue();
if(dist[count] < paramRadio)
{
double pow = Math.pow((rMayor - dist[count])/(rMayor * dist[count]),2);
sumaDistancias += pow;
sumaValores += pow * e.valor();
}
count ++;
}
salida.valor(sumaValores / sumaDistancias);
}
} | 6 |
public static long getDateTime(String buffer) {
if (buffer != null) {
buffer = buffer.trim();
for (int i = DateFormat.FULL; i <= DateFormat.SHORT; i++) {
for (int j = DateFormat.FULL; j <= DateFormat.SHORT; j++) {
try {
return DateFormat.getDateTimeInstance(i, j).parse(buffer).getTime();
} catch (Exception exception) {
// Ignore
}
}
}
}
return System.currentTimeMillis();
} | 4 |
public Boolean close() {
try {
this.con.close();
return true;
} catch (SQLException e) {
log.severe("Couldn't close Connection: ");
LogHandler.writeStackTrace(log, e, Level.SEVERE);
return false;
}
} | 1 |
public void setPlainValue(String value) {
this.plainValue = value;
} | 0 |
@Override
public Event next() {
String input = null;
try {
input = br.readLine();
} catch (IOException e) {
}
if(input == null || input.equals("")){
return new DefaultState(as);
}
else{
return new UserHomeState(as, input);
}
} | 3 |
@Override
public void update(MiniGame game)
{
if (calculateDistanceToTarget() < INTERSECTION_RADIUS)
{
stopMovingToTarget();
if (pathIndex < path.size() - 1 && !movingBackToFirst && currentIntersection.open)
{
Road roadInBetween = ((pathXDataModel)game.getDataModel()).getRoad(currentIntersection, path.get(pathIndex+1));
if (roadInBetween.open)
{
pathIndex++;
movingBackToFirst = pathIndex == path.size() - 1 ? true : false;
}
} else if (pathIndex > 0 && currentIntersection.open)
{
pathIndex--;
movingBackToFirst = pathIndex == 0 ? false : true;
}
updatePath(game);
}
super.update(game);
} | 9 |
public List<Node> getPublicDialogList() {
List<Claim> claimList = claimDao.getClaimList();
List<Claim> counterclaimList = null;
List<Claim> subclaimList = null;
List<Evidence> evidenceList = null;
List<Evidence> counterevidenceList = null;
List<BipolarQuestion> bipolarQuestionList = null;
List<BipolarQuestion> responseToBipolarList = null;
List<Challenge> challengeList = null;
Node node = null;
Claim claim = null, counterclaim = null, subclaim = null;
Evidence evidence = null, counterevidence = null;
BipolarQuestion bipolarQuestion = null, responseToBipolar = null;
Challenge challenge = null;
nodeList.clear();
// Get claims
for (int i = 0; i < claimList.size(); i++) {
claim = claimList.get(i);
node = new Node(claim.getId(), null, claim.getType(),
claim.getTitle(), claim.getTeamType());
nodeList.add(node);
// Get counterclaims
counterclaimList = claimDao.getPublicClaimList(claim.getId(), "counterclaim");
for (int j = 0; j < counterclaimList.size(); j++) {
counterclaim = counterclaimList.get(j);
node = new Node(counterclaim.getId(), counterclaim.getParentClaimId(),
counterclaim.getType(), counterclaim.getTitle(), counterclaim.getTeamType());
nodeList.add(node);
// Get counterevidence
counterevidenceList = evidenceDao.getPublicEvidenceList(counterclaim.getId(), "counterevidence");
for (int k = 0; k < counterevidenceList.size(); k++) {
counterevidence = counterevidenceList.get(k);
node = new Node(counterevidence.getId(), counterevidence.getParentClaimId(),
counterevidence.getType(), counterevidence.getTitle(), counterevidence.getTeamType());
nodeList.add(node);
}
}
// Get Sub Claim
subclaimList = claimDao.getPublicClaimList(claim.getId(), "subclaim");
for (int j = 0; j < subclaimList.size(); j++) {
subclaim = subclaimList.get(j);
node = new Node(subclaim.getId(), subclaim.getParentClaimId(),
subclaim.getType(), subclaim.getTitle(), subclaim.getTeamType());
nodeList.add(node);
}
// Get evidence
evidenceList = evidenceDao.getPublicEvidenceList(claim.getId(), "evidence");
for (int j = 0; j < evidenceList.size(); j++) {
evidence = evidenceList.get(j);
node = new Node(evidence.getId(), evidence.getParentClaimId(),
evidence.getType(), evidence.getTitle(), evidence.getTeamType());
nodeList.add(node);
}
// Get counterEvidence
counterevidenceList = evidenceDao.getPublicEvidenceList(claim.getId(), "counterevidence");
for (int j = 0; j < counterevidenceList.size(); j++) {
counterevidence = counterevidenceList.get(j);
node = new Node(counterevidence.getId(), counterevidence.getParentClaimId(),
counterevidence.getType(), counterevidence.getTitle(), counterevidence.getTeamType());
nodeList.add(node);
}
// Get Bi-polar Question
bipolarQuestionList = bipolarQuestionDao.getPublicBipolarList(claim.getId(), "bipolarQuestion");
for (int j = 0; j < bipolarQuestionList.size(); j++) {
bipolarQuestion = bipolarQuestionList.get(j);
node = new Node(bipolarQuestion.getId(), bipolarQuestion.getParentId(),
bipolarQuestion.getType(), bipolarQuestion.getTitle(), bipolarQuestion.getTeamType());
nodeList.add(node);
// Get response to Bi-polar Question
responseToBipolarList = bipolarQuestionDao.getPublicBipolarList(bipolarQuestion.getId(), "responseToBipolar");
for (int k = 0; k < responseToBipolarList.size(); k++) {
responseToBipolar = responseToBipolarList.get(k);
node = new Node(responseToBipolar.getId(), responseToBipolar.getParentId(),
responseToBipolar.getType(), responseToBipolar.getTitle(), responseToBipolar.getTeamType());
nodeList.add(node);
}
}
// Get Challenge
challengeList = challengeDao.getPublicChallengeList(claim.getId());
for (int j = 0; j < challengeList.size(); j++) {
challenge = challengeList.get(j);
node = new Node(challenge.getId(), challenge.getParentId(),
challenge.getType(), challenge.getTitle(), challenge.getTeamType());
nodeList.add(node);
}
}
return nodeList;
} | 9 |
public void setName(String name)
{
nameLabel.setText(name);
} | 0 |
public void visitTryCatchBlock(final Label start, final Label end,
final Label handler, final String type) {
if (type != null) {
cp.newClass(type);
}
mv.visitTryCatchBlock(start, end, handler, type);
} | 1 |
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected)||msg.amISource(((MOB)affected).amFollowing())||(msg.source()==invoker()))
&&(msg.sourceMinor()==CMMsg.TYP_QUIT))
{
unInvoke();
if(msg.source().playerStats()!=null)
msg.source().playerStats().setLastUpdated(0);
}
} | 7 |
public ComplexMatrix getPropagationMatrix(int index, double energy) {
ComplexMatrix mx = ComplexMatrix.identityMatrix(2);
for (int i = index; i < intervals.size() - 1; i++) {
try {
mx = mx.multiply(getLocalPropagationMatrix(i, energy));
if (VERBOSE) {
System.out.println("> > > In getIntervalWavefunctionCoeffs(...)");
System.out.println("Matrix on index " + index + ", energy " + energy + ", interation " + i);
System.out.println(mx);
System.out.println("Current propagation matrix = " + getLocalPropagationMatrix(i, energy));
}
} catch (NullPointerException e) {
System.out.println("Null received in ComplexMatrix multiplication in getIntervalWavefunctionCoeffs(...)");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Something wrong on ComplexMatrix multiplication in getIntervalWavefunctionCoeffs(...)");
e.printStackTrace();
}
}
return mx;
} | 4 |
public String toStringSummary() {
String result;
String titles;
int resultsetLength;
int i;
int j;
if (m_NonSigWins == null)
return "-summary data not set-";
result = "";
titles = "";
resultsetLength = 1 + Math.max((int)(Math.log(getColCount())/Math.log(10)),
(int)(Math.log(getRowCount())/Math.log(10)));
for (i = 0; i < getColCount(); i++) {
if (getColHidden(i))
continue;
titles += " " + Utils.padLeft("" + getSummaryTitle(i),
resultsetLength * 2 + 3);
}
result += titles + " (No. of datasets where [col] >> [row])\n";
for (i = 0; i < getColCount(); i++) {
if (getColHidden(i))
continue;
for (j = 0; j < getColCount(); j++) {
if (getColHidden(j))
continue;
result += " ";
if (j == i)
result += Utils.padLeft("-", resultsetLength * 2 + 3);
else
result += Utils.padLeft("" + m_NonSigWins[i][j]
+ " (" + m_Wins[i][j] + ")",
resultsetLength * 2 + 3);
}
result += " | " + getSummaryTitle(i) + " = " + getColName(i) + '\n';
}
return result;
} | 8 |
public static void main(String[] args) throws Exception {
Globals.lockManager = new LockManager();
Globals.bufferManager = new BufferManager(Globals.PAGES + 3);
Globals.index = new BPlus(1); // xactionId whatever you want
Globals.threads = new HashMap<Long, Thread>();
Globals.threadResults = new HashMap<Long, StringBuilder>();
System.out.println("Index on start...");
Globals.index.debugPrint(1, System.out);
Globals.lockManager.releaseLocks(1); // Release locks of creation
Globals.lockManager.allClear(1);
DeadlockDetector dd = new DeadlockDetector();
dd.start();
if (!READFROMFILE) {
String clientSentence;
ServerSocket welcomeSocket = new ServerSocket(5678);
int counter = 0;
while (true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println("**" + (++counter) + "Received: "
+ clientSentence);
if (clientSentence.startsWith("END ALL"))
break;
Server s = new Server(clientSentence);
Globals.threads.put(s.getId(), s);
s.start();
}
System.out.println("Waiting threads to terminate...");
int count = 0;
for (Entry<Long, Thread> t : Globals.threads.entrySet()) {
t.getValue().join();
count++;
// System.out.println(count);
}
welcomeSocket.close();
} else {
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream(new File("input_del.txt"));
reader = new BufferedReader(new InputStreamReader(fis));
System.out
.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while (line != null) {
if (line.equals("END ALL"))
break;
Server s = new Server(line);
Globals.threads.put(s.getId(), s);
s.start();
line = reader.readLine();
}
} catch (Exception ex) {
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
}
}
int count = 0;
for (Entry<Long, Thread> t : Globals.threads.entrySet()) {
t.getValue().join();
count++;
}
}
System.out.println("FINISH ");
Globals.index.debugPrint(1, System.out);
// Globals.index.rangeQuery(false, 1, System.out);
Globals.lockManager.releaseLocks(1); // Release locks of creation
dd.interrupt();
} | 9 |
public static void main(String[] args) {
ResourceConsumer consumer0 = new ResourceConsumer();
// usage of consumer0
// ...
consumer0.clean();
consumer0 = null;
ResourceConsumer consumer1 = new ResourceConsumer();
consumer1 = null;
new ResourceConsumer();
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
System.out.flush();
} | 1 |
public float[] center()
{
if (parts.size() <= 0) return null;
float minX = parts.get(0).posX,
maxX = parts.get(0).posX,
minY = parts.get(0).posY,
maxY = parts.get(0).posY,
minZ = parts.get(0).posZ,
maxZ = parts.get(0).posZ;
for (int i = 0; i < parts.size(); i++)
{
if (parts.get(i).posX < minX) minX = parts.get(i).posX;
else if (parts.get(i).posX > maxX) maxX = parts.get(i).posX;
if (parts.get(i).posY < minY) minY = parts.get(i).posY;
else if (parts.get(i).posY > maxY) maxY = parts.get(i).posY;
if (parts.get(i).posZ < minZ) minZ = parts.get(i).posZ;
else if (parts.get(i).posZ > maxZ) maxZ = parts.get(i).posZ;
}
return new float[]{(minX+maxX)/2,(minY+maxY)/2,(minZ+maxZ)/2};
} | 8 |
@Override
public void mouseDragged(MouseEvent e) {
mouseDown = true;
GCThread.increaseGCFlag(5);
if (SwingUtilities.isLeftMouseButton(e) && !e.isShiftDown()) {
x2 = e.getX();
y2 = e.getY();
double newUpperLeftX = upperLeftX-((x2-x1)*(75/factor));
double newUpperLeftY = upperLeftY+((y2-y1)*(75/factor));
if(newUpperLeftX <= 434168)
newUpperLeftX = 434168;
if(newUpperLeftX+utmWidth >= 918958)
newUpperLeftX = upperLeftX;
if(newUpperLeftY-utmHeight <= 6032816) {
newUpperLeftY = upperLeftY;
}
if(newUpperLeftY >= 6412239) {
newUpperLeftY = 6412239;
}
zoom(newUpperLeftX, newUpperLeftY, utmWidth, utmHeight, false, 0, 0, 0, 0);
}
if(e.isShiftDown()) {
x2 = Math.min(e.getX(), x1);
y2 = Math.min(e.getY(), y1);
rectWidth = (int) Math.abs(x1 - e.getX());
rectHeight = (int) Math.abs(y1 - e.getY());
dragging = true;
repaint();
}
} | 7 |
public void COME(int bet) {
if (money > 0 && bet <= money && bet >= 0 && count != 0) {
if (combinedRoll == 7 || combinedRoll == 11) {
player.addMoney(bet);
info.updateMoney();
} else {
player.loseMoney(bet);
info.updateMoney();
}
}
} | 6 |
public Edge getFirstEdgeAtPosition(int x, int y, Node n) {
for(Edge e : n.outgoingConnections) {
if(e.isInside(x, y, pt)) {
Edge opposEdge = e.getOppositeEdge();
if(opposEdge != null){
//find out which one we want to delete.
pt.translateToGUIPosition(e.endNode.getPosition());
Position oneEnd = new Position(pt.guiXDouble, pt.guiYDouble, 0.0);
pt.translateToGUIPosition(opposEdge.endNode.getPosition());
Position otherEnd = new Position(pt.guiXDouble, pt.guiYDouble, 0.0);
Position eventPos = new Position(x, y, 0.0);
if(eventPos.distanceTo(oneEnd) > eventPos.distanceTo(otherEnd)){
return opposEdge;
} else {
return e;
}
} else { // there is no opposite edge, return e
return e;
}
}
}
return null;
} | 4 |
private ArrayList<String> getFilesNamesFromFolderWithJPG(){
ArrayList<String> filesNames = new ArrayList<String>();
File folderWithJPG = new File(this.folderWithJPG);
File[] files = folderWithJPG.listFiles();
for(File f:files){
if(f.isFile()){
filesNames.add(getFileNameWithoutExtension(f));
System.out.println(getFileNameWithoutExtension(f));
}
}
return filesNames;
} | 2 |
public void parseParameters(String paramstring) throws MaltChainedException {
if (paramstring == null) {
return;
}
final String[] argv;
String allowedFlags = "sceB";
try {
argv = paramstring.split("[_\\p{Blank}]");
} catch (PatternSyntaxException e) {
throw new LiblinearException("Could not split the liblinear-parameter string '"+paramstring+"'. ", e);
}
for (int i=0; i < argv.length-1; i++) {
if(argv[i].charAt(0) != '-') {
throw new LiblinearException("The argument flag should start with the following character '-', not with "+argv[i].charAt(0));
}
if(++i>=argv.length) {
throw new LiblinearException("The last argument does not have any value. ");
}
try {
int index = allowedFlags.indexOf(argv[i-1].charAt(1));
if (index != -1) {
liblinearOptions.put(Character.toString(argv[i-1].charAt(1)), argv[i]);
} else {
throw new LiblinearException("Unknown liblinear parameter: '"+argv[i-1]+"' with value '"+argv[i]+"'. ");
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new LiblinearException("The liblinear parameter '"+argv[i-1]+"' could not convert the string value '"+argv[i]+"' into a correct numeric value. ", e);
} catch (NumberFormatException e) {
throw new LiblinearException("The liblinear parameter '"+argv[i-1]+"' could not convert the string value '"+argv[i]+"' into a correct numeric value. ", e);
} catch (NullPointerException e) {
throw new LiblinearException("The liblinear parameter '"+argv[i-1]+"' could not convert the string value '"+argv[i]+"' into a correct numeric value. ", e);
}
}
} | 9 |
private final void method1025
(int[] is, int[] is_404_, int i, int i_405_, int i_406_, float f,
float f_407_, float f_408_, float f_409_, float f_410_, float f_411_,
float f_412_, float f_413_, float f_414_, float f_415_, float f_416_,
float f_417_, float f_418_, float f_419_, float f_420_, float f_421_,
float f_422_, float f_423_, float f_424_, float f_425_) {
int i_426_ = i_406_ - i_405_;
float f_427_ = 1.0F / (float) i_426_;
float f_428_ = (f_407_ - f) * f_427_;
float f_429_ = (f_409_ - f_408_) * f_427_;
float f_430_ = (f_411_ - f_410_) * f_427_;
float f_431_ = (f_413_ - f_412_) * f_427_;
float f_432_ = (f_417_ - f_416_) * f_427_;
float f_433_ = (f_419_ - f_418_) * f_427_;
float f_434_ = (f_421_ - f_420_) * f_427_;
float f_435_ = (f_423_ - f_422_) * f_427_;
float f_436_ = (f_425_ - f_424_) * f_427_;
if (((Class109) this).aBoolean1671) {
if (i_406_ > ((Class109) this).anInt1679)
i_406_ = ((Class109) this).anInt1679;
if (i_405_ < 0) {
f -= f_428_ * (float) i_405_;
f_408_ -= f_429_ * (float) i_405_;
f_410_ -= f_430_ * (float) i_405_;
f_412_ -= f_431_ * (float) i_405_;
f_416_ -= f_432_ * (float) i_405_;
f_418_ -= f_433_ * (float) i_405_;
f_420_ -= f_434_ * (float) i_405_;
f_422_ -= f_435_ * (float) i_405_;
f_424_ -= f_436_ * (float) i_405_;
i_405_ = 0;
}
}
if (i_405_ < i_406_) {
i_426_ = i_406_ - i_405_;
i += i_405_;
while (i_426_-- > 0) {
float f_437_ = 1.0F / f;
if (f_437_ < aFloatArray1677[i]) {
float f_438_ = f_408_ * f_437_;
float f_439_ = f_410_ * f_437_;
int i_440_
= ((int) (f_438_ * (float) anInt1693 * aFloat1681)
& anInt1690);
int i_441_
= ((int) (f_439_ * (float) anInt1693 * aFloat1681)
& anInt1690);
int i_442_ = anIntArray1698[i_441_ * anInt1693 + i_440_];
i_440_ = ((int) (f_438_ * (float) anInt1691 * aFloat1684)
& anInt1686);
i_441_ = ((int) (f_439_ * (float) anInt1691 * aFloat1684)
& anInt1686);
int i_443_ = anIntArray1685[i_441_ * anInt1691 + i_440_];
i_440_ = ((int) (f_438_ * (float) anInt1695 * aFloat1682)
& anInt1688);
i_441_ = ((int) (f_439_ * (float) anInt1695 * aFloat1682)
& anInt1688);
int i_444_ = anIntArray1692[i_441_ * anInt1695 + i_440_];
float f_445_ = 1.0F - (f_422_ + f_424_);
i_442_
= (~0xffffff
| ((int) (f_422_ * (float) (i_442_ >> 16 & 0xff))
<< 16)
| (int) (f_422_ * (float) (i_442_ >> 8 & 0xff)) << 8
| (int) (f_422_ * (float) (i_442_ & 0xff)));
i_443_
= (~0xffffff
| ((int) (f_424_ * (float) (i_443_ >> 16 & 0xff))
<< 16)
| (int) (f_424_ * (float) (i_443_ >> 8 & 0xff)) << 8
| (int) (f_424_ * (float) (i_443_ & 0xff)));
i_444_
= (~0xffffff
| ((int) (f_445_ * (float) (i_444_ >> 16 & 0xff))
<< 16)
| (int) (f_445_ * (float) (i_444_ >> 8 & 0xff)) << 8
| (int) (f_445_ * (float) (i_444_ & 0xff)));
int i_446_ = i_442_ + i_443_ + i_444_;
int i_447_
= (~0xffffff
| ((int) (f_416_ * (float) (i_446_ >> 16 & 0xff))
<< 8) & 0xff0000
| ((int) (f_418_ * (float) (i_446_ >> 8 & 0xff))
& 0xff00)
| (int) (f_420_ * (float) (i_446_ & 0xff)) >> 8);
if (f_412_ != 0.0F) {
int i_448_ = (int) (255.0F - f_412_);
int i_449_ = ((((anInt1696 & 0xff00ff) * (int) f_412_
& ~0xff00ff)
| ((anInt1696 & 0xff00) * (int) f_412_
& 0xff0000))
>>> 8);
i_447_ = (((i_447_ & 0xff00ff) * i_448_ & ~0xff00ff
| (i_447_ & 0xff00) * i_448_ & 0xff0000)
>>> 8) + i_449_;
}
is[i] = i_447_;
aFloatArray1677[i] = f_437_;
}
i++;
f += f_428_;
f_408_ += f_429_;
f_410_ += f_430_;
f_412_ += f_431_;
f_416_ += f_432_;
f_418_ += f_433_;
f_420_ += f_434_;
f_422_ += f_435_;
f_424_ += f_436_;
}
}
} | 7 |
@XmlElement
public void setAge(int age) {
this.age = age;
} | 0 |
public void zoomIn() {
if (tileSize + TILE_SIZE_STEP > TILE_MAX_SIZE)
return;
int oldSize = tileSize;
Container c = GraphicPanel.this.getParent();
int newX, newY;
tileSize += TILE_SIZE_STEP;
revalidateScroll();
if (c instanceof JViewport) {
JViewport jv = (JViewport) c;
Point pos = jv.getViewPosition();
newX = pos.x + ((pos.x / oldSize) * (TILE_SIZE_STEP + 1));
newY = pos.y + ((pos.y / oldSize) * (TILE_SIZE_STEP + 1));
jv.setViewPosition(new Point(newX, newY));
}
repaint();
} | 2 |
public void newNPCDrop(int npcType, int dropType, int Items[], int ItemsN[]) {
// first, search for a free slot
int slot = -1;
for (int i = 0; i < maxNPCDrops; i++) {
if (NpcDrops[i] == null) {
slot = i;
break;
}
}
if(slot == -1) return; // no free slot found
NPCDrops newNPCDrop = new NPCDrops(npcType);
newNPCDrop.DropType = dropType;
newNPCDrop.Items = Items;
newNPCDrop.ItemsN = ItemsN;
NpcDrops[slot] = newNPCDrop;
} | 3 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
result = prime * result + Float.floatToIntBits(z);
return result;
} | 0 |
public void moveClouds(){
// Move the clouds
for(int i=0; i<clouds.size(); i++){
Cloud cld2 = clouds.get(i);
if(cld2.getDone()){
clouds.remove(cld2);
clouds.add(new Cloud());
}
else{
cld2.move();
}
}
} | 2 |
public String toString() {
return "" + id + ", " + firstName + ", " + lastName + ", " + age;
} | 0 |
private void updateAddDragObject(String name) {
CategoryType actCategory = guiBuilder.getDragObjectByName(name)
.getCategory();
if (actCategory == CategoryType.BASS) {
this.animationCountArray[0] += 1;
this.animationArray[0] = true;
} else if (actCategory == CategoryType.BEATS) {
this.animationCountArray[1] += 1;
this.animationArray[1] = true;
} else if (actCategory == CategoryType.HARMONY) {
this.animationCountArray[2] += 1;
this.animationArray[2] = true;
} else if (actCategory == CategoryType.MELODY) {
this.animationCountArray[3] += 1;
this.animationArray[3] = true;
} else if (actCategory == CategoryType.EFFECTS) {
this.animationCountArray[4] += 1;
this.animationArray[4] = true;
}
guiBuilder.getDonkey().setAnimationArray(this.animationArray);
} | 5 |
private boolean kingInCheck(PlayerNum playerNum, int x, int y) {
if (!inBounds(x, y)) {
return false;
}
//Iterates through the board and check each pieces movesets
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (!inBounds(i, j)) {
continue;
}
boolean[][] moves;
//Only check pieces that are opponent pieces
if (board[i][j].getClass() != pieces.King.class
&& board[i][j].getPlayerNum() != PlayerNum.EMPTY
&& board[i][j].getPlayerNum() != currentPlayer
.getPlayerNum()) {
moves = getAvailableMoves(board[i][j].getPlayerNum(), i, j,
true);
//If an opponent piece can move in the king's location, it's in check
if (moves[x][y]) {
return true;
}
}
}
}
return false;
} | 8 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.