text stringlengths 14 410k | label int32 0 9 |
|---|---|
public void initialise(World world) throws PatternFormatException
{
String[] cellParts = cells.split(" ");
for (int i=0;i<cellParts.length;i++)
{
char[] currCells = cellParts[i].toCharArray();
for (int j=0;j<currCells.length;j++)
{
if (currCells[j] != '1' && currCells[j] != '0') throw new PatternFormatException("Error: incorrect format of cell description");
if (currCells[j] == '1') world.setCell(j+startCol,i+startRow,true);
}
}
} | 5 |
public static void main(String[] args) {
ArrayList newWordList = new ArrayList();
ArrayList filteredWordList = new ArrayList();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("My Clippings.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Replacing all non-alphanumeric characters with empty strings
strLine = strLine.replaceAll("[^A-Za-z]", " ");
// Replacing multiple spaces with single space
strLine = strLine.replaceAll("( )+", " ");
if (isLetterDigitOrChinese(strLine) && strLine.length()>1 && strLine.length()<41) {
newWordList.add(strLine.trim());
}
else{
filteredWordList.add(strLine.trim());
}
}
// Close the input stream
in.close();
FileOutputStream out = new FileOutputStream("newoutput1.txt");
for (int i = 0; i < newWordList.size(); i++) {
out.write(newWordList.get(i).toString().getBytes());
out.write("\r\n".getBytes());
}
// Close the output stream
out.close();
FileOutputStream fileredOut = new FileOutputStream("fileredOut.txt");
for (int i = 0; i < filteredWordList.size(); i++) {
fileredOut.write(filteredWordList.get(i).toString().getBytes());
fileredOut.write("\r\n".getBytes());
}
fileredOut.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
} | 7 |
public boolean createDirectory(String path) throws IOException {
return fs.mkdirs(new Path(path));
} | 0 |
protected GraphicalRepresentationElement representChildren(PathElement el, Set<PathElement> blackNodes)
{
// FIXME: check casts to VisualizableGraphComponent throughout the method
GraphicalRepresentationElement repr = new GraphicalRepresentationElement(this,
(VisualizableGraphComponent) el.getNode(), Type.NODE);
blackNodes.add(el);
List<PathElement> others = new LinkedList<PathElement>(el.getOtherChildren());
representOthers(others, blackNodes, EdgeType.BACKLINK, el, repr);
boolean first = true;
for(PathElement child : el.getChildren())
{
for(Edge edge : (isBackwards ? theGraph.getInEdges(el.getNode()) : theGraph.getOutEdges(el.getNode())))
if((isBackwards && (edge.getFrom() == child.getNode()))
|| (!isBackwards && (edge.getTo() == child.getNode())))
{
GraphicalRepresentationElement childRepr = representChildren(child, blackNodes);
GraphicalRepresentationElement edgeRepr = new GraphicalRepresentationElement(this,
(VisualizableGraphComponent) edge, Type.EDGE);
edgeRepr.setEdge(EdgeType.CHILDLINK, repr, childRepr);
repr.connected.add(edgeRepr);
((VisualizableGraphComponent) child.getNode()).addRepresentation(childRepr);
((VisualizableGraphComponent) edge).addRepresentation(edgeRepr);
first = false;
}
representOthers(others, blackNodes, first ? EdgeType.FORELINK : EdgeType.SIDELINK, el, repr);
}
representOthers(others, blackNodes, EdgeType.EXTLINK, el, repr);
return repr;
} | 8 |
private static boolean canPushBlock(int par0, World par1World, int par2, int par3, int par4, boolean par5)
{
if (par0 == Block.obsidian.blockID)
{
return false;
}
else
{
if (par0 != Block.pistonBase.blockID && par0 != Block.pistonStickyBase.blockID)
{
if (Block.blocksList[par0].getHardness() == -1.0F)
{
return false;
}
if (Block.blocksList[par0].getMobilityFlag() == 2)
{
return false;
}
if (!par5 && Block.blocksList[par0].getMobilityFlag() == 1)
{
return false;
}
}
else if (isExtended(par1World.getBlockMetadata(par2, par3, par4)))
{
return false;
}
return !(Block.blocksList[par0] != null && Block.blocksList[par0].hasTileEntity(par1World.getBlockMetadata(par2, par3, par4)));
}
} | 9 |
public void run(){
int generation = 0;
calculateFitnesses();
//main loop
while(true){
if(generation % POPULATION_SIZE == 0){
System.out.println("\nGeneration: "+generation+", cost: "+minCost);
System.out.print("\nminimum gene: ");
printGene(genes[fittestGeneIndex]);
initRouteFromGene(genes[fittestGeneIndex]);
System.out.print("\nminimum route: ");
printRoute();
System.out.print("\n");
}
createNewOffspring();
generation++;
}
} | 2 |
private void createDrawHistory(){
DataInstance ddi = new DataInstance(drawNet.inputNodes());
//Rack
ddi.addFeature(rack.getCards(), game.card_count);
//Probabilities
if (USE_PROB_DRAW){
double[][] prob = rack.getProbabilities(false, 0);
ddi.addFeature(prob[0], 1);
ddi.addFeature(prob[1], 1);
}
//Top of discard
int discard = game.deck.peek(true);
ddi.addFeature(discard, game.card_count);
draw_instance = ddi;
} | 1 |
private void findAnnotations(Class clazz) {
if (clazz.getSuperclass() != null) {
findAnnotations(clazz.getSuperclass());
}
for (Method m : clazz.getDeclaredMethods()) {
Command c = null;
m.setAccessible(true);
if ((c = m.getAnnotation(Command.class)) != null) {
String commandName = c.name();
if (commandName.equals(Command.METHOD_NAME)) {
commandName = m.getName();
}
Annotation[][] annArray = m.getParameterAnnotations();
int requiredArguments = 0;
for (int i = 0; i < annArray.length; i++) {
requiredArguments++;
for (int j = 0; j < annArray[i].length; j++) {
if (annArray[i][j] instanceof Argument) {
Argument argument = (Argument) annArray[i][j];
if (argument.optional()) {
requiredArguments--;
}
break;
}
}
}
if (c.help().equals(Command.NO_HELP)) {
this.commands.put(commandName.trim().toLowerCase(), new ShellCommand(commandName, m, requiredArguments));
} else {
this.commands.put(commandName.trim().toLowerCase(), new ShellCommand(commandName, m, requiredArguments, c.help()));
}
}
}
} | 9 |
public void populateFromFolder(final String str_name, final File cl_dir, final boolean b_dir) {
ScriptEngineManager lcl_mgr = new ScriptEngineManager();
for (File lcl_f : cl_dir.listFiles()) {
if (lcl_f.isDirectory()) {
if (b_dir) {
populateFromFolder(str_name, lcl_f, b_dir);
}
} else if (!lcl_f.isHidden()) {
ScriptEngine lcl_engine = lcl_mgr.getEngineByExtension(BTFileUtils.getFileExtension(lcl_f.getName()));
try {
lcl_engine.eval(BTFileUtils.getATextFile(lcl_f));
addScriptFor(str_name, (Invocable) lcl_engine);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} | 5 |
@Override
public boolean equals(Object o) {
if(!(o instanceof MapEntry))
return false;
MapEntry<?, ?> me = (MapEntry<?, ?>)o;
return (key == null ? me.getKey() == null : key.equals(me.getKey()))
&& (value == null ? me.getValue() == null : value.equals(me
.getValue()));
} | 8 |
public void update(WPEngine4 engine) {
if(lightingType.equals(LightingType.SPOT_LIGHT)) {
//setupLighting(lightingType);
for(int i = 0; i < spotList.size(); i++) {
Entity e = spotList.get(i);
int RadiusX = spotRadiusX.get(i);
int RadiusY = spotRadiusY.get(i);
int LeftX = e.getX() - RadiusX;
int LeftY = e.getY() - RadiusY;
int CenterX = e.getX();
int CenterY = e.getY();
for(int x = LeftX; x <= (LeftX + (RadiusX * 2)); x++) {
tiles[(e.getY() * engine.getLevel().getWidth()) + x] = 0; //TILES ARE PIXELS IN LIGHTINGLAYER
}
int FadeLevel = 0;
for(int x = (LeftX - FadeRangeX); x <= LeftX ; x++) {
FadeLevel++;
tiles[(e.getY() * engine.getLevel().getWidth()) + x] = (int)((1.0 * FadeLevel/FadeRangeX) * DarkestPercentage);
}
FadeLevel = 0;
for(int x = (CenterX + RadiusX); x <= (CenterX + RadiusX + FadeRangeX); x++) {
FadeLevel++;
tiles[(e.getY() * engine.getLevel().getWidth()) + x] = (int)((1.0 * FadeLevel/FadeRangeX) * DarkestPercentage);
}
}
}
} | 5 |
public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args)
{
SubCommand subCommand;
if (args.length > 0)
{
subCommand = this.getCommand(args[0]);
}
else
{
subCommand = this.getCommandByName(this.defaultCommand);
args = new String[] {subCommand.getName()};
}
if (subCommand != null)
{
Permission permission = subCommand.getPermission();
if (permission != null && !sender.hasPermission(permission))
{
sender.sendMessage(_("command_permdenied"));
}
else
{
try
{
CommandArgs commandArgs = new CommandArgs(this, label, subCommand, args);
if (!subCommand.execute(sender, commandArgs))
{
sender.sendMessage("/" + label + " " + commandArgs.getLabel() + " " + subCommand.getUsage());
}
return true;
}
catch (CommandException e)
{
sender.sendMessage(e.getLocalizedMessage());
}
catch (Throwable t)
{
sender.sendMessage(_("command_internalerror"));
t.printStackTrace(System.err);
}
}
}
else
{
sender.sendMessage(_("command_notfound"));
}
return true;
} | 7 |
public int GetBus()
{
return bus;
} | 0 |
public void addPhi(final Block block) {
Phi phi = phis[cfg.preOrderIndex(block)];
if (phi == null) {
if (StackPRE.DEBUG) {
System.out.println(" add phi for " + def + " at "
+ block);
}
phi = new Phi(block);
phis[cfg.preOrderIndex(block)] = phi;
}
} | 2 |
private PostParameter getParameterValue(String name,Object value){
if(value instanceof Boolean){
return new PostParameter(name, (Boolean)value?"0":"1");
}else if(value instanceof String){
return new PostParameter(name, value.toString());
}else if(value instanceof Integer){
return new PostParameter(name,Integer.toString((Integer)value));
}else if(value instanceof Long){
return new PostParameter(name,Long.toString((Long)value));
}else if(value instanceof Gender) {
return new PostParameter(name,Gender.valueOf((Gender)value));
}
return null;
} | 6 |
public int claimProvince(String playerName, String worldName, int chunkX, int chunkZ) {
int updateSuccessful = 0;
Connection con = getSQLConnection();
PreparedStatement statement = null;
String SQL = "INSERT INTO `Monarchy_Provinces` (`id`, `player`, `world`, `x`, `z`, `parent`, `invited`, `time`) VALUES (NULL, ?, ?, ?, ?, NULL, NULL, CURRENT_TIMESTAMP);";
try {
statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
statement.setString(2, worldName);
statement.setInt(3, chunkX);
statement.setInt(4, chunkZ);
//statement.setInt(5, Config.defaultProvincePermitFlag);
updateSuccessful = statement.executeUpdate();
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (updateSuccessful > 0)
removeProvinceFromCache(worldName, chunkX, chunkZ);
return updateSuccessful;
} | 2 |
public void deleteApp() throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("Which App do you want to delete? (App Number)");
int ch = in.nextInt();
File x = new File(appDir+ch+".txt");
boolean delete = x.delete();
if(delete)
System.out.println("Deleted!");
else
System.out.println("Cannot Delete");
appMng();
} | 1 |
public Layer setActiveLayer(Layer l, boolean active, ArrayList<Layer> layers) {
if (active) {
for (Layer other : layers) {
other.setActive(false);
}
l.setActive(true);
return l;
} else {
layers.get(1).setActive(true);
l.setActive(false);
return layers.get(1);
}
} | 2 |
public List<Achievement> readAchievements(InputStream stream) throws IOException, JAXBException {
log.trace("Reading achievements XML");
// Need to clean invalid XML and comments before JAXB parsing
BufferedReader in = new BufferedReader(new InputStreamReader(stream, "UTF8"));
StringBuilder sb = new StringBuilder();
String line;
while( (line = in.readLine()) != null ) {
line = line.replaceAll("<!--[^>]*-->", ""); // TODO need a proper Matcher for multiline comments
line = line.replaceAll("<desc>([^<]*)</name>", "<desc>$1</desc>");
sb.append(line).append("\n");
}
in.close();
if ( sb.substring(0, BOM_UTF8.length()).equals(BOM_UTF8) )
sb.replace(0, BOM_UTF8.length(), "");
// XML has multiple root nodes so need to wrap.
sb.insert(0, "<achievements>\n");
sb.append("</achievements>\n");
// Parse cleaned XML
Achievements ach = (Achievements)unmarshalFromSequence( Achievements.class, sb );
return ach.getAchievements();
} | 2 |
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(CadastroTelefone.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastroTelefone.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastroTelefone.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastroTelefone.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() {
CadastroTelefone dialog = new CadastroTelefone(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 static void printAllPercentileLocationHomeDistanceRestByDuration(int percentile, int duration){
try {
Connection con = dbConnect();
PreparedStatement getXY = con.prepareStatement(
"SELECT x,y FROM "+locTbl+" WHERE locationID = ?");
PreparedStatement getDistance = con.prepareStatement(
"SELECT personID,distance FROM "+locHomeDistTbl+" WHERE locationID = ? ORDER BY distance ASC");
for (int location = 1; location <= numLocations; location++){
HashSet<Integer> peopleAtLocLongEnough = getPeopleAtLocationForAtLeastSpecDur(location, duration);
getXY.setInt(1, location);
getDistance.setInt(1, location);
ResultSet getXYQ = getXY.executeQuery();
ResultSet getDistanceQ = getDistance.executeQuery();
getDistanceQ.last();
int numPeople = getDistanceQ.getRow();
if (numPeople > 0) {
getDistanceQ.beforeFirst();
ArrayList<Double> distances = new ArrayList<Double>(numPeople);
while (getDistanceQ.next()) {
double distance = getDistanceQ.getDouble("distance");
Integer personID = new Integer(getDistanceQ.getInt("personID"));
if (peopleAtLocLongEnough.contains(personID))
distances.add(distance);
}
// System.out.println("number of people: "+numPeople);
numPeople = distances.size();
int index = (percentile*numPeople)/100;
// System.out.println("row number: "+person);
if (index > 0 && getXYQ.first()){
System.out.println(getXYQ.getDouble("x")+"\t"+getXYQ.getDouble("y")+
"\t"+distances.get(index));
}
}
}
con.close();
} catch (Exception e){
System.out.println(e);
}
} | 7 |
public void activeHeroChanged(Hero hero)
{
setActiveHero(hero);
System.out.println("active hero changed");
if (WorldMap.getLastInstance() != null) {
System.out.println("pre calculate route");
WorldMap.getLastInstance().calculateRoute(hero);
}
} | 1 |
private TimeSeriesCollection createTimeSeriesData() {
TimeSeriesCollection tsc = new TimeSeriesCollection();
TimeSeries vehTotal = new TimeSeries("Total Vehicles");
TimeSeries carTotal = new TimeSeries("Total Cars");
TimeSeries mcTotal = new TimeSeries("MotorCycles");
//Base time, data set up - the calendar is needed for the time points
Calendar cal = GregorianCalendar.getInstance();
Random rng = new Random(250);
int cars = 0;
int mc = 0;
//Hack loop to make it interesting. Grows for half of it, then declines
for (int i=0; i<=18*60; i++) {
//These lines are important
cal.set(2014,0,1,6,i);
Date timePoint = cal.getTime();
//HACK BEGINS
if (i<9*60) {
if (randomSuccess(0.2,rng)) {
cars++;
}
if (randomSuccess(0.1,rng)) {
mc++;
}
} else if (i < 18*60) {
if (randomSuccess(0.15,rng)) {
cars++;
} else if (randomSuccess(0.4,rng)) {
cars = Math.max(cars-1,0);
}
if (randomSuccess(0.05,rng)) {
mc++;
} else if (randomSuccess(0.2,rng)) {
mc = Math.max(mc-1,0);
}
} else {
cars=0;
mc =0;
}
//HACK ENDS
//This is important - steal it shamelessly
mcTotal.add(new Minute(timePoint),mc);
carTotal.add(new Minute(timePoint),cars);
vehTotal.add(new Minute(timePoint),cars+mc);
}
//Collection
tsc.addSeries(vehTotal);
tsc.addSeries(carTotal);
tsc.addSeries(mcTotal);
return tsc;
} | 9 |
public static void main(String[] args) {
w = new Worker();
} | 0 |
public static ObjectType getTypeFromDataChar(char dataChar) {
switch (dataChar) {
default:
case '0':
return AIR;
case '1':
return STONE;
case '2':
return BRICK;
case '3':
return ICE;
case '4':
return SPIKE;
case '5':
return PORTAL;
case '6':
return KEY;
case '7':
return POTION;
case '8':
return PRESENT;
}
} | 9 |
public static int[] mirror(int[] pixs, int w, int h, int n) {
int[] pix = new int[w * h];
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
if (n == 0) {
int u = w - 1 - i;
int v = j;
pix[v * w + u] = pixs[j * w + i];
} else if (n == 1) {
int u = i;
int v = h - 1 - j;
pix[v * w + u] = pixs[j * w + i];
}
}
}
return pix;
} | 4 |
public BSTNode getNameSearchByName(String name) {
try {
if (Tmproot == null) {
Tmproot = root;
}
String name1 = Tmproot.getName().toString();
if (root == null) {
return null;
} else {
if (name.contentEquals(name1)) {
return Tmproot;
} else if (Tmproot.getLeft() == null) {
Tmproot = Tmproot.getRight();
} else if (Tmproot.getLeft() != null) {
Tmproot = Tmproot.getLeft();
}
getNameSearchByName(name);
}
} catch (Exception ex) {
}
return Tmproot;
} | 6 |
private UselessStatesDetector() {
} | 0 |
private PriceManager()
{
} | 0 |
public static void addEscapeToCloseSupport(final JDialog dialog,
final boolean fadeOnClose) {
LayerUI<Container> layerUI = new LayerUI<Container>() {
/**
*
*/
private static final long serialVersionUID = 2514339457426555702L;
private boolean closing = false;
@Override
public void installUI(JComponent c) {
super.installUI(c);
((JLayer<?>) c).setLayerEventMask(AWTEvent.KEY_EVENT_MASK);
}
@Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
((JLayer<?>) c).setLayerEventMask(0);
}
@Override
public void eventDispatched(AWTEvent e,
JLayer<? extends Container> l) {
if (e instanceof KeyEvent
&& ((KeyEvent) e).getKeyCode() == KeyEvent.VK_ESCAPE) {
if (closing)
return;
closing = true;
if (fadeOnClose)
fadeOut(dialog);
else
dialog.dispose();
}
}
};
JLayer<Container> layer = new JLayer<>(dialog.getContentPane(), layerUI);
dialog.setContentPane(layer);
} | 7 |
@Override
public boolean shouldReact(Message message) {
return message.text.startsWith("stopwatch") && message.text.indexOf(' ') != NOT_FOUND;
} | 1 |
private static void inventoryAdder(Items item){
//push to array
//Items newItem = item;
inventoryHasAtLeastOne = true;
for (int i=0;i<inventory.length;i++){
if (inventory[i] == null){
inventory[i] = item;
item.setObtained(true);
return;
}
}
} | 2 |
public static void haku(Pysakkiverkko2 verkko, String lahto, String maali, int aika) {
PriorityQueue<Tila2> pq = new PriorityQueue<>();
ArrayList<String> loydetyt = new ArrayList<>();
Tila2 maaliTila = null;
boolean loydetty = false;
Tila2 t = new Tila2(lahto, null, lahto, Math.abs(0 - aika), 0, aika, heuristinenArvio(lahto, maali, verkko));
pq.add(t);
while (!pq.isEmpty() && !loydetty) {
t = pq.poll();
loydetyt.add(t.getLinja());
for (String uusi : verkko.getPysakki(t.getLinja()).getNaapurit()) {
if (uusi.equals(maali)) {
// System.out.println("jep");
loydetty = true;
maaliTila = new Tila2(uusi, t, maali, Math.abs(0 - aika), 0, aika, heuristinenArvio(uusi, maali, verkko));
break;
}
if (!sisaltaako(uusi, pq) && !loydetyt.contains(uusi)) {
// System.out.println("lisätty");
pq.add(new Tila2(uusi, t, uusi, 0, 0, t.getNykyinenAika(), heuristinenArvio(uusi, maali, verkko)));
}
}
}
// for (String string : loydetyt) {
// System.out.println(string);
// }
while (maaliTila != null) {
System.out.println("Pysäkki nro: " + maaliTila.getLinja() + " " + verkko.getPysakki(maaliTila.getLinja()).getNimi() + " nykyinen aika: " + maaliTila.getNykyinenAika());
maaliTila = maaliTila.getEdellinen();
}
// System.out.println(maaliTila.getLinja());
} | 7 |
public ActivityTypes getActivityType() {
return activityType;
} | 0 |
public void iniciar() throws Exception {
while (true) {
System.out.println();
System.out.println("Gestión de personas");
System.out.println("1. Agregar");
System.out.println("2. Modificar");
System.out.println("3. Eliminar");
System.out.println("4. Obtener uno");
System.out.println("5. Obtener todos");
System.out.println("6. Salir");
System.out.print("? ");
String opcion = scanner.nextLine();
if (opcion.equals("1"))
guardar(OP_AGREGAR);
else if (opcion.equals("2"))
guardar(OP_MODIFICAR);
else if (opcion.equals("3"))
eliminar();
else if (opcion.equals("4"))
obtener();
else if (opcion.equals("5"))
obtenerTodos();
else if (opcion.equals("6"))
break;
}
} | 7 |
public BufferedImage rotateBufferedImage(BufferedImage bf, int rotateDegree) {
if(rotateDegree % 360 == 0){
return bf;
}
int imageWidth = bf.getWidth();
int imageHeight = bf.getHeight();
double rotationRequired = Math.toRadians(rotateDegree);
double locationX = bf.getWidth() / 2;
double locationY = bf.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
bf = op.filter(bf, null);
if(rotateDegree % 90 != 0){
bf = bf.getSubimage(0,0,imageWidth, imageHeight);
}
return bf;
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Pessoa other = (Pessoa) obj;
if (this.idPessoa != other.idPessoa && (this.idPessoa == null || !this.idPessoa.equals(other.idPessoa))) {
return false;
}
return true;
} | 5 |
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
evaluateRegex();
} else if (e.getKeyCode() == KeyEvent.VK_F3) {
if (!e.isShiftDown()) jumpToNextMatch();
else jumpToPrevMatch();
}
} | 3 |
final void method3924(boolean bool, boolean bool_2_, int i,
Class70 class70, boolean bool_3_) {
try {
anInt9852++;
if (bool_2_ == false) {
OpenGL.glTexEnvi(8960, i + 34176,
Class57.method531((byte) 101, class70));
if (bool)
OpenGL.glTexEnvi(8960, i + 34192, !bool_3_ ? 770 : 771);
else
OpenGL.glTexEnvi(8960, i + 34192, !bool_3_ ? 768 : 769);
}
} catch (RuntimeException runtimeexception) {
throw Class348_Sub17.method2929(runtimeexception,
("bga.DD(" + bool + ',' + bool_2_
+ ',' + i + ','
+ (class70 != null ? "{...}"
: "null")
+ ',' + bool_3_ + ')'));
}
} | 6 |
@Override
public boolean read(DummyObjectList dummyObjects, DummyObject [] dummyTypes,
TileMap tileMap) {
System.out.println("Opening .level file");
try
{
ResFileReader r;
r = new ResFileReader(path);
// load tilemap, post names are map, map2, map3 etc.
r.gotoPost("map", false);
tileMap.setMap(r.readMapArray(), 0);
boolean layersLeft = true;
int mapIndex = 2;
while(layersLeft) {
try {
r.gotoPost("map"+mapIndex, false);
tileMap.addMap(r.readMapArray());
mapIndex ++;
} catch (Exception e) {
layersLeft = false;
}
}
// load objects
r.gotoPost("init",false);
r.nextLine();
int loops = 0;
while (r.getWord().compareTo("end") != 0 && loops < 1000)
{
loops ++;
if (r.getWord().compareTo("new") == 0)
{
System.out.println("Adding dummy...");
String type = r.getNextWord();
int x = r.getNextWordAsInt();
int y = r.getNextWordAsInt();
int w = r.getNextWordAsInt();
int h = r.getNextWordAsInt();
String addData = r.getRestOfLine();
DummyObject dummy ;
boolean found = false;
for (int i = 0; i < dummyTypes.length; i++){
if (dummyTypes[i].name.compareTo(type)==0){
found = true;
dummy = new DummyObject(dummyTypes[i]);
dummy.x = x;
dummy.y = y;
dummy.w = w;
dummy.h = h;
dummy.additionalData = addData;
dummyObjects.newDummy(dummy);
}
}
if (!found){
System.out.println(
"Warning: dummytype "
+type+" not defined in def.file!");
}
}
r.nextLine();
}
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error reading *.level file!");
return false;
}
System.out.println("Init finished");
return true;
} | 9 |
public static void addRingInfo(MaplePacketLittleEndianWriter mplew, MapleCharacter chr) {
mplew.writeShort(0);
mplew.writeShort(chr.getCrushRings().size());
for (MapleRing ring : chr.getCrushRings()) {
mplew.writeInt(ring.getPartnerChrId());
mplew.writeAsciiString(StringUtil.getRightPaddedStr(ring.getPartnerName(), '\0', 13));
mplew.writeInt(ring.getRingId());
mplew.writeInt(0);
mplew.writeInt(ring.getPartnerRingId());
mplew.writeInt(0);
}
mplew.writeShort(chr.getFriendshipRings().size());
for (MapleRing ring : chr.getFriendshipRings()) {
mplew.writeInt(ring.getPartnerChrId());
mplew.writeAsciiString(StringUtil.getRightPaddedStr(ring.getPartnerName(), '\0', 13));
mplew.writeInt(ring.getRingId());
mplew.writeInt(0);
mplew.writeInt(ring.getPartnerRingId());
mplew.writeInt(0);
mplew.writeInt(ring.getItemId());
}
mplew.writeShort(chr.getMarriageRings().size());
int marriageId = 30000;
for (MapleRing ring : chr.getMarriageRings()) {
mplew.writeInt(marriageId);
mplew.writeInt(chr.getGender() == 0 ? chr.getId() : ring.getPartnerChrId());
mplew.writeInt(chr.getGender() == 0 ? ring.getPartnerChrId() : chr.getId());
mplew.writeShort(3);
mplew.writeInt(ring.getItemId());
mplew.writeInt(ring.getItemId());
mplew.writeAsciiString(StringUtil.getRightPaddedStr(chr.getGender() == 0 ? chr.getName() : ring.getPartnerName(), '\0', 13));
mplew.writeAsciiString(StringUtil.getRightPaddedStr(chr.getGender() == 0 ? ring.getPartnerName() : chr.getName(), '\0', 13));
marriageId++;
}
} | 7 |
public static String toEnglish1000(int i) {
String[] f20 = {" zero", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen"};
String[] tens = {"ERR", "ERR", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety"};
if (i >= 1000)
throw new RuntimeException(i + ": not less than 1000");
int hundreds = i/100;
int l2 = i%100;
if (hundreds == 0 && l2 == 0)
return "zero";
StringBuilder desc = new StringBuilder();
if (hundreds > 0)
desc.append(f20[hundreds]);
if (l2 == 0)
desc.append(" hundred");
else {
if (l2 < 20) {
if (l2 < 10 && hundreds > 0) {
desc.append(f20[0]);
}
desc.append(f20[l2]);
} else {
int t = l2/10;
int u = l2%10;
desc.append(tens[t]);
if (u != 0)
desc.append(f20[u]);
}
}
return desc.toString();
} | 9 |
void helper(int need, int complete, List<String> res, StringBuilder tmp, int n) {
if (complete > need) {
tmp.deleteCharAt(tmp.length() - 1);
return;
}
if (need < n && complete < n) {
tmp.append('(');
helper(need + 1, complete, res, tmp, n);
tmp.append(')');
helper(need, complete + 1, res, tmp, n);
} else if (need == n && complete < n) {
tmp.append(')');
helper(need, complete + 1, res, tmp, n);
} else if (need == n && complete == n)
res.add(tmp.toString());
if (tmp.length() != 0)
tmp.deleteCharAt(tmp.length() - 1);
} | 8 |
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
me.setMoveUp(false);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
me.setMoveDown(false);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
me.setMoveLeft(false);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
me.setMoveRight(false);
}
if(e.getKeyCode() == KeyEvent.VK_SPACE){
me.setV(5);
}
} | 5 |
public Wave05PewterGym(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 50; i++){
if(i < 25){
if(i % 2 == 0)
add(m.buildMob(MobID.DIGLETT));
else
add(m.buildMob(MobID.SANDSHREW));
}
else if(i >= 25 && i < 49){
if(i % 2 == 0)
add(m.buildMob(MobID.DIGLETT));
else
add(m.buildMob(MobID.GEODUDE));
}
else
add(m.buildMob(MobID.ONIX));
}
} | 6 |
public int loadProject( File file)
{
int back = -1 ;
TProject dummy = null ;
try
{
dummy = this.readXmlFile( file ) ;
}
catch ( SAXException sxe )
{
// sxe.printStackTrace() ;
back = 1 ;
}
catch ( ParserConfigurationException pce )
{
// pce.printStackTrace() ;
back = 2 ;
}
catch ( IOException ioe )
{
// ioe.printStackTrace() ;
back = 3 ;
}
catch (Exception e)
{
back = 4 ;
}
catch (Error er)
{
back = 5 ;
}
if (dummy != null)
{
dummy.setProjectFile(file);
// all data are up to date
dummy.setUnSaved(false);
this.addProject( dummy ) ;
this.setCurrentProject( dummy ) ;
back = 0 ;
}
return back ;
} | 6 |
public List<Predicate> parsePredicates(String input) throws ParseException {
List<Predicate> predicates = new ArrayList<Predicate>();
int numberOfBrackets = 0;
int start = 0;
for (int end = 0; end < input.length(); ++end) {
char currentChar = input.charAt(end);
switch (currentChar) {
case '(':
numberOfBrackets++;
break;
case ')':
numberOfBrackets--;
break;
case ',':
if (numberOfBrackets == 0) {
String predicate = input.substring(start, end);
predicates.add(parsePredicate(predicate.trim()));
// Skip the current character for the next search (hence the +1)
// and start looking for more predicates from this position
// onwards.
start = end + 1;
}
break;
}
}
String lastPredicate = input.substring(start);
predicates.add(parsePredicate(lastPredicate.trim()));
return predicates;
} | 5 |
public Point tryMove(int quad)
/*
* The quadrant is translated into a tile coordinate, and tested for
* validity. The translation varies depending on if the row position of the
* curent tile (yTile) is even or odd. null is returned if the new position
* is invalid.
*/
{
Point nextPt;
if (quad == NE)
nextPt = (yTile % 2 == 0) ? new Point(xTile, yTile - 1)
: new Point(xTile + 1, yTile - 1);
else if (quad == SE)
nextPt = (yTile % 2 == 0) ? new Point(xTile, yTile + 1)
: new Point(xTile + 1, yTile + 1);
else if (quad == SW)
nextPt = (yTile % 2 == 0) ? new Point(xTile - 1, yTile + 1)
: new Point(xTile, yTile + 1);
else if (quad == NW)
nextPt = (yTile % 2 == 0) ? new Point(xTile - 1, yTile - 1)
: new Point(xTile, yTile - 1);
else
return null;
if (world.validTileLoc(nextPt.x, nextPt.y))
// ask WorldDisplay if the proposed tile is in a valid location
return nextPt;
else
return null;
} // end of tryMove() | 9 |
public int getIndexOfChild(Object parent, Object child)
{
if(!(parent instanceof ObjectNode))
throw new RuntimeException("unexpected object of " + parent.getClass() + " passed");
if(!(child instanceof ObjectNode))
throw new RuntimeException("unexpected object of " + child.getClass() + " passed");
ObjectNode onp = (ObjectNode)parent;
ObjectNode onc = (ObjectNode)child;
ObjectNode[] ch = onp.children();
for(int i = 0; i < ch.length; i++)
{
if(ch[i].equals(child))
return i;
}
return -1;
} | 4 |
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
result = 31 * result + (identityCode != null ? identityCode.hashCode() : 0);
result = 31 * result + (note != null ? note.hashCode() : 0);
result = 31 * result + (created != null ? created.hashCode() : 0);
result = 31 * result + (updated != null ? updated.hashCode() : 0);
result = 31 * result + (createdBy != null ? createdBy.hashCode() : 0);
result = 31 * result + (updatedBy != null ? updatedBy.hashCode() : 0);
result = 31 * result + (birthDate != null ? birthDate.hashCode() : 0);
return result;
} | 9 |
public static void main(String[] args) {
// Declare the JDBC objects.
Connection con = null;
CallableStatement cstmt = null;
ResultSet rs = null;
try {
// Establish the connection.
SQLServerDataSource ds = new SQLServerDataSource();
ds.setIntegratedSecurity(true);
ds.setServerName("localhost");
ds.setPortNumber(1433);
ds.setDatabaseName("AdventureWorks");
con = ds.getConnection();
// Execute a stored procedure that returns some data.
cstmt = con.prepareCall("{call dbo.uspGetEmployeeManagers(?)}");
cstmt.setInt(1, 50);
rs = cstmt.executeQuery();
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println("EMPLOYEE: " + rs.getString("LastName") +
", " + rs.getString("FirstName"));
System.out.println("MANAGER: " + rs.getString("ManagerLastName") +
", " + rs.getString("ManagerFirstName"));
System.out.println();
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (cstmt != null) try { cstmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
} | 8 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TaxonDesignationPK)) {
return false;
}
TaxonDesignationPK other = (TaxonDesignationPK) object;
if ((this.taxonVersionKey == null && other.taxonVersionKey != null) || (this.taxonVersionKey != null && !this.taxonVersionKey.equals(other.taxonVersionKey))) {
return false;
}
if (this.designationID != other.designationID) {
return false;
}
return true;
} | 6 |
public static boolean isLessThan11(int i){
return i < 11;
} | 0 |
@Before
public void setUp()
{
_helper = new TruncateHelper();
} | 0 |
public void setComputerScores(){
computerScores++;
} | 0 |
private void formMouseEvent(java.awt.event.MouseEvent evt) {
int mouseEventId = evt.getID();
int buttonID = evt.getButton();
int xcord = evt.getX();
int ycord = evt.getComponent().getHeight() - evt.getY();
long time = evt.getWhen()/1000;
int modifiers =0;
if((evt.getModifiers() & KeyEvent.SHIFT_MASK) == KeyEvent.SHIFT_MASK)
{
modifiers = 1 + modifiers;
}
if((evt.getModifiers() & KeyEvent.ALT_MASK) == KeyEvent.ALT_MASK )
{
modifiers = 100 + modifiers;
}
if((evt.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK )
{
modifiers = 10 + modifiers ;
}
String modifiersString = Integer.toString(modifiers);
String resultString = mouseEventId+"|"+buttonID+"|"+xcord+"|"+ycord+"|"+time+"|"+modifiers;
//System.out.println(resultString);
if(mouseEventId==501 || mouseEventId==502 || mouseEventId==503 || mouseEventId==506)
{
mouseEventHandler(resultString);
}
} | 7 |
public static boolean isLocation(Location loc1, Location loc2) {
if (loc1.getWorld() == loc2.getWorld() &&
loc1.getBlockX() == loc2.getBlockX() &&
loc1.getBlockY() == loc2.getBlockY() &&
loc1.getBlockZ() == loc2.getBlockZ())
return true;
else
return false;
} | 4 |
public boolean meet(Temporal temporal) {
if (null == temporal) return false;
// if (null == temporal || this == temporal) return false;
if (isTimeInstance()) {
if (temporal.isTimeInstance()) return startTime == temporal.startTime;
else return startTime == temporal.endTime || startTime == temporal.startTime;
} else {
if (temporal.isTimeInstance()) return startTime == temporal.startTime || endTime == temporal.startTime;
}
return startTime == temporal.endTime || endTime == temporal.startTime;
} | 7 |
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int index = -1;
@Override
public boolean hasNext() {
return index < SimpleHashSet.this.size() - 1;
}
@Override
public E next() {
++index;
for(int j = 0; j < SIZE; j++) {
if((start(j) <= index) && (index < end(j))) {
return buckets[j].get(index - start(j));
}
}
return null;
}
@Override
public void remove() {
for(int j = 0; j < SIZE; j++) {
if(start(j) <= index && index < end(j)) {
buckets[j].remove(index - start(j));
}
}
index--;
}
};
} | 6 |
private float coFactor(int c, int r) {
Matrix3 minor = new Matrix3();
int i = 0;
for(int ri = 0;ri < SIZE;ri++) {
if(ri == c) continue;
for(int ci = 0;ci < SIZE;ci++) {
if(ci == r) continue;
minor.m[i++] = m[ri * 4 + ci];
}
}
if((r + c) % 2 == 0) return minor.determinant();
else return -minor.determinant();
} | 5 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AccessRequestType)) {
return false;
}
AccessRequestType other = (AccessRequestType) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
private void displayLists(CommandSender sender, List<Lists> lists) {
for (Lists list : lists) {
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
if (issue.isClosed()) {
sender.sendMessage(main.formatReport(main.displayStrings[1], issue.getId(), issue.getReported(), issue.getReporter(), issue.getIssue(), issue.getTimestamp(), null, null));
}
else {
sender.sendMessage(main.formatReport(main.displayStrings[0], issue.getId(), issue.getReported(), issue.getReporter(), issue.getIssue(), issue.getTimestamp(), null, null));
}
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
sender.sendMessage(main.formatReport(main.displayStrings[4], ban.getId(), ban.getReported(), ban.getReporter(), ban.getReason(), ban.getTimestamp(), null, null));
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
sender.sendMessage(main.formatReport(main.displayStrings[5], unban.getId(), unban.getReported(), unban.getReporter(), unban.getReason(), unban.getTimestamp(), null, null));
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
sender.sendMessage(main.formatReport(main.displayStrings[2], promote.getId(), promote.getReported(), promote.getReporter(), promote.getReason(), promote.getTimestamp(), promote.getPrevRank(), promote.getNewRank()));
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
sender.sendMessage(main.formatReport(main.displayStrings[3], demote.getId(), demote.getReported(), demote.getReporter(), demote.getReason(), demote.getTimestamp(), demote.getPrevRank(), demote.getNewRank()));
break;
default:
sender.sendMessage(ChatColor.DARK_GRAY + "Unspecified action happened");
break;
}
}
} | 8 |
public synchronized final void close() {
if (!open) {
return; // it is not an error to attempt to close a closed Query
}
if (Prolog.thread_self() == -1) {
throw new JPLException("no engine is attached to this thread");
}
if (Prolog.current_engine().value != engine.value) {
throw new JPLException("this Query's engine is not that which is attached to this thread");
}
Query topmost = m.get(new Long(engine.value));
if (topmost != this) {
throw new JPLException("this Query (" + this.hashCode() + ":" + this.toString() + ") is not topmost (" + topmost.hashCode() + ":" + topmost.toString() + ") within its engine["
+ engine.value + "]");
}
Prolog.close_query(qid);
qid = null; // for tidiness
org.jpl7.fli.Prolog.discard_foreign_frame(fid);
fid = null; // for tidiness
m.remove(new Long(engine.value));
if (subQuery == null) { // only Query open in this engine?
if (Prolog.current_engine_is_pool()) { // this (Query's) engine is from the pool?
Prolog.release_pool_engine();
// System.out.println("JPL releasing engine[" + engine.value + "]");
} else {
// System.out.println("JPL leaving engine[" + engine.value + "]");
}
} else {
m.put(new Long(engine.value), subQuery);
// System.out.println("JPL retaining engine[" + engine.value + "] popping subQuery(" + subQuery.hashCode() + ":" + subQuery.toString() + ")");
}
open = false; // this Query is now closed
engine = null; // this Query, being closed, is no longer associated with any Prolog engine
subQuery = null; // this Query, being closed, is not stacked upon any other Query
} | 6 |
void genRandArray(int[] array, int size) {
if (size > array.length)
throw new IllegalArgumentException("Given size " + size
+ " exceeds array length " + array.length);
if (size < N32)
throw new IllegalArgumentException("Size must be at least " + N32
+ ", but is " + size);
if (size % 4 != 0)
throw new IllegalArgumentException("Size must be a multiple of 4: "
+ size);
int i = 0, j = 0, r1I = 4 * (N - 2), r2I = 4 * (N - 1);
int[] r1 = sfmt, r2 = sfmt;
for (; i < 4 * (N - POS1); i += 4) {
doRecursion(array, i, sfmt, i, sfmt, i + 4 * POS1, r1, r1I, r2, r2I);
r1 = r2;
r1I = r2I;
r2 = array;
r2I = i;
}
for (; i < 4 * N; i += 4) {
doRecursion(array, i, sfmt, i, array, i + 4 * (POS1 - N), r1, r1I,
r2, r2I);
assert r1 == r2;
r1I = r2I;
assert r2 == array;
r2I = i;
}
for (; i < size - 4 * N; i += 4) {
doRecursion(array, i, array, i - 4 * N, array, i + 4 * (POS1 - N),
r1, r1I, r2, r2I);
assert r1 == r2;
r1I = r2I;
assert r2 == array;
r2I = i;
}
for (; j < 4 * 2 * N - size; j++)
sfmt[j] = array[j + size - 4 * N];
for (; i < size; i += 4, j += 4) {
doRecursion(array, i, array, i - 4 * N, array, i + 4 * (POS1 - N),
r1, r1I, r2, r2I);
assert r1 == r2;
r1I = r2I;
assert r2 == array;
r2I = i;
sfmt[j] = array[i];
sfmt[j + 1] = array[i + 1];
sfmt[j + 2] = array[i + 2];
sfmt[j + 3] = array[i + 3];
}
} | 8 |
public static Stella_Object accessSubstringPositionIteratorSlotValue(SubstringPositionIterator self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Logic.SYM_LOGIC_SUPER_STRING) {
if (setvalueP) {
self.superString = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.superString);
}
}
else if (slotname == Logic.SYM_LOGIC_SUB_STRING) {
if (setvalueP) {
self.subString = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.subString);
}
}
else if (slotname == Logic.SYM_STELLA_START) {
if (setvalueP) {
self.start = ((IntegerWrapper)(value)).wrapperValue;
}
else {
value = IntegerWrapper.wrapInteger(self.start);
}
}
else if (slotname == Logic.SYM_LOGIC_SUB_LENGTH) {
if (setvalueP) {
self.subLength = ((IntegerWrapper)(value)).wrapperValue;
}
else {
value = IntegerWrapper.wrapInteger(self.subLength);
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
} | 8 |
private HelperGroup better(HelperGroup a, HelperGroup b, int R) {
if (a.totalCapacity >= R && b.totalCapacity < R)
return a;
if (a.totalCapacity < R && b.totalCapacity >= R)
return b;
if (a.totalCapacity < R && b.totalCapacity < R)
return max(a, b);
return min(a, b);
} | 6 |
public boolean userCanSeePatient(String uid, String uunit, Patient patient) {
int type = findType(uid);
if (type == TYPE_GOV) {
return true;
} else if (type == TYPE_DOCTOR || type == TYPE_NURSE) {
ArrayList<JournalEntry> entries = patient.getJournal().getEntries();
for (JournalEntry entry : entries) {
if (entry.getDoctorId().equals(uid) || entry.getUnit().equals(uunit)) {
return true;
}
}
} else if (type == TYPE_PATIENT) {
if (patient.getId().equals(uid)) {
return true;
}
}
return false;
} | 8 |
public static void main(String[] args)
{
ConfigFile f = new ConfigFile("config.txt");
f.ReadFile();
} | 0 |
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(OsobljeN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OsobljeN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OsobljeN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OsobljeN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OsobljeN().setVisible(true);
}
});
} | 6 |
private static Interface getHID (Device dev)
throws IOException
{
Configuration config;
Interface retval = null;
DeviceDescriptor info = dev.getDeviceDescriptor ();
if (info.getDeviceClass () != 0)
throw new IllegalArgumentException ("dev class");
config = dev.getConfiguration ();
for (int i = config.getNumInterfaces (); i-- != 0; ) {
Interface intf = config.getInterface (i, 0);
if (intf.getInterfaceClass () == intf.CLASS_HID) {
if (retval != null)
throw new IllegalArgumentException ("multi-hid");
retval = intf;
}
}
if (retval == null)
throw new IllegalArgumentException ("not hid");
return retval;
} | 5 |
private void touchRotate(final double X, final double Y, final Rotate ROTATE) {
double theta = getTheta(X, Y);
interactiveAngle = (theta + 90) % 360;
double newValue = Double.compare(interactiveAngle, 180) <= 0 ?
(interactiveAngle + 180.0 + getSkinnable().getStartAngle() - 360) / angleStep :
(interactiveAngle - 180.0 + getSkinnable().getStartAngle() - 360) / angleStep;
if (Double.compare(newValue, getSkinnable().getMinValue()) >= 0 && Double.compare(newValue, getSkinnable().getMaxValue()) <= 0) {
ROTATE.setAngle(interactiveAngle);
value.setText(String.format(Locale.US, "%." + getSkinnable().getDecimals() + "f", newValue));
resizeText();
}
} | 3 |
@Override
public String toString(){
return "id= "+this.getId()+", "+this.getName()+"\n"+getTime()+"\n"+"Диаметр: "+this.getHig()+"\n"+"Длин окружности: "+this.getLengh()+"\n"+"Координаты центра: ("+this.getX() +" , "+this.getY()+")"+"\n"+"S=: "+this.getArea()+" V=: "+this.getVolume()+"\n";
} | 0 |
void lookForHbonds(NucleicPolymer other, BitSet bsA, BitSet bsB) {
// Logger.debug("NucleicPolymer.lookForHbonds()");
for (int i = monomerCount; --i >= 0;) {
NucleicMonomer myNucleotide = (NucleicMonomer) monomers[i];
if (!myNucleotide.isPurine())
continue;
Atom myN1 = myNucleotide.getN1();
Atom bestN3 = null;
float minDist2 = 5 * 5;
NucleicMonomer bestNucleotide = null;
for (int j = other.monomerCount; --j >= 0;) {
NucleicMonomer otherNucleotide = (NucleicMonomer) other.monomers[j];
if (!otherNucleotide.isPyrimidine())
continue;
Atom otherN3 = otherNucleotide.getN3();
float dist2 = myN1.distanceSquared(otherN3);
if (dist2 < minDist2) {
bestNucleotide = otherNucleotide;
bestN3 = otherN3;
minDist2 = dist2;
}
}
if (bestN3 != null) {
createHydrogenBond(myN1, bestN3, bsA, bsB);
if (bestNucleotide != null) {
if (myNucleotide.isGuanine()) {
createHydrogenBond(myNucleotide.getN2(), bestNucleotide.getO2(), bsA, bsB);
createHydrogenBond(myNucleotide.getO6(), bestNucleotide.getN4(), bsA, bsB);
}
else {
createHydrogenBond(myNucleotide.getN6(), bestNucleotide.getO4(), bsA, bsB);
}
}
}
}
} | 8 |
public void setUtilityVisible(JButton button) {
String caseString = button.getActionCommand();
switch(caseString) {
case "diceRollerLaunch":
setPanelVisible("dicePanel");
break;
case "calculatorLaunch":
setPanelVisible("calculatorPanel");
break;
case "audioPlayerLaunch":
setPanelVisible("standAloneMusicPlayerPanel");
break;
case "back":
setPanelVisible("none");
default: break;
}
} | 4 |
@Override
public boolean execute(RuleExecutorParam param) {
Rule rule = param.getRule();
List<String> values = Util.getValue(param, rule);
if (values == null || values.isEmpty()) {
return false;
}
boolean retValue = true;
for (String value : values) {
String compareValue = rule.getValue();
if (rule.isIgnoreCase()) {
value = value.toUpperCase();
compareValue = compareValue.toUpperCase();
}
boolean intRetValue = value.contains(compareValue);
if (Operators.DoesNotContains.getValue().equals(rule.getOper())) {
intRetValue = !intRetValue;
}
retValue = retValue && intRetValue;
}
return retValue;
} | 6 |
public void updateImage()
{
//we will update animation when delay counter reaches delay, then reset delay counter
delayCounter++;
if(delayCounter>delay)
{
delayCounter=0;
frameNumber++;//updates frame to next frame
frameNumber%=totalFrame;// if surpass 3rd frame, back to frameNumber 0
//sets image to specific frameNumber by multiplying it with 500, aka width of the image
this.setImage(xLocationSpriteSheet+frameNumber*width+frameNumber, yLocationSpriteSheet, width,height ,newWidth, newHeight);
}
} | 1 |
protected void initialize() {
_setDistance(Robot.vision.getCurrDistance());
super.initialize();
} | 0 |
public void setDumping(boolean b) {
dumping = b;
} | 0 |
private void prepare(){
this.year = Integer.parseInt(split[0]);
this.title = split[1];
this.rating = Float.parseFloat(split[2]);
if(split.length > 3){
if(!split[3].equals("")){
this.genre = split[3].split("\\|");
for (int i = 0; i < this.genre.length; i++) {
RatingData.Cache.add(new RatingData(title, this.genre[i], rating));
}
}
if(split.length > 4){
if(!split[4].equals("")){
this.actors = split[4].split("\\|");
for (int i = 0; i < this.actors.length; i++) {
ActorData actorData = ActorData.Cache.get(this.actors[i]);
if(actorData == null)
{
actorData = new ActorData(this.actors[i], 0);
ActorData.Cache.put(this.actors[i], actorData);
}
actorData.setFilmedIn(actorData.getFilmedIn() + 1);
}
}
}
}
} | 7 |
public void init(int nplayers, int[] pref) {
this.nplayer=nplayers;
this.pref=pref;
this.position=this.getIndex();// position start from 0
this.record = new int[2*nplayer];
if(nplayers-position<=9)
magic=magic_table[nplayers];
else
magic=(int) Math.round(0.369*(nplayers-position) );
} | 1 |
private SaveState computeSaveState(Issue edited, Issue issue) {
try {
// These fields are not editable - so if they differ they are invalid
// and we cannot save.
if (!equal(edited.getId(), issue.getId())) {
return SaveState.INVALID;
}
if (!equal(edited.getProjectName(), issue.getProjectName())) {
return SaveState.INVALID;
}
// If these fields differ, the issue needs saving.
if (!equal(edited.getStatus(), issue.getStatus())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getSynopsis(), issue.getSynopsis())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getDescription(), issue.getDescription())) {
return SaveState.UNSAVED;
}
} catch (Exception x) {
// If there's an exception, some fields are invalid.
return SaveState.INVALID;
}
// No field is invalid, no field needs saving.
return SaveState.UNCHANGED;
} | 6 |
@Override
public int getdir(String path, FuseDirFiller dirFiller) throws FuseException {
Iterable<EntityInfo> iterator;
try {
iterator = fileSystem.listDirectory(path);
if (iterator == null)
System.err.println("Your file system returned null for readDirectory(" + path + ")");
} catch (PathNotFoundException e) {
return Errno.ENOENT;
} catch (AccessDeniedException e) {
return Errno.EACCES;
} catch (NotADirectoryException e) {
return Errno.ENOTDIR;
}
dirFiller.add(".", 0, 0);
dirFiller.add("..", 0, 0);
for (EntityInfo info : iterator)
{
UnixPermissions perms;
try {
perms = fileSystem.getUnixPermissions(info.getFullPath());
} catch (PathNotFoundException e) {
System.err.println("readDirectory and getUnixPermissions inconsistent for " + info.getFullPath());
e.printStackTrace();
continue;
}
int mode = 0;
if (FileInfo.class.isInstance(info))
mode |= FuseFtypeConstants.TYPE_FILE;
if (DirectoryInfo.class.isInstance(info))
mode |= FuseFtypeConstants.TYPE_DIR;
if (SymbolicLinkInfo.class.isInstance(info))
{
// SymbolicLinkInfo sym = (SymbolicLinkInfo)info;
mode |= FuseFtypeConstants.TYPE_SYMLINK;
}
mode |= perms.getPermissions();
dirFiller.add(info.getFileName(), info.hashCode(), mode);
}
return 0;
} | 9 |
public static double getAngle(Vector2D vector) {
double x = vector.x;
double y = vector.y;
if (x > 0) {
return Math.atan(y / x);
}
else if (x < 0) {
return Math.atan(y / x) + Math.PI;
} else if (y > 0) {
return -Math.PI / 2;
} else {
return Math.PI / 2;
}
} | 3 |
@Override public void keyPressed(KeyEvent nappain)
{
switch(nappain.getKeyCode())
{
case KeyEvent.VK_LEFT:
ohjaus.annaKomento(Komento.SIIRTO_VASEMMALLE);
break;
case KeyEvent.VK_RIGHT:
ohjaus.annaKomento(Komento.SIIRTO_OIKEALLE);
break;
case KeyEvent.VK_DOWN:
ohjaus.annaKomento(Komento.PUDOTTAMINEN);
break;
case KeyEvent.VK_UP:
ohjaus.annaKomento(Komento.KAANTAMINEN);
break;
case KeyEvent.VK_P:
ohjaus.annaKomento(Komento.TAUOTTAMINEN);
break;
case KeyEvent.VK_N:
ohjaus.annaKomento(Komento.UUSI_PELI);
break;
}
} | 6 |
public static void handleEvent(int eventId)
{
// Changes focus to Main Ship Shop Menu
if(eventId == 1)
{
System.out.println("Exit Ship Shop Hulls menu to Main Ship Shop Menu selected");
Main.ShipShopHullsMenu.setVisible(false);
Main.ShipShopHullsMenu.setEnabled(false);
Main.ShipShopHullsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopHullsMenu);
Main.mainFrame.add(Main.ShipShopMenu);
Main.ShipShopMenu.setVisible(true);
Main.ShipShopMenu.setEnabled(true);
Main.ShipShopMenu.setFocusable(true);
Main.ShipShopMenu.requestFocusInWindow();
}
// Do nothing because same screen selected
else if(eventId == 2)
{System.out.println("Exit Ship Shop Hulls menu to Engines Ship Shop Menu selected");
Main.ShipShopHullsMenu.setVisible(false);
Main.ShipShopHullsMenu.setEnabled(false);
Main.ShipShopHullsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopHullsMenu);
Main.mainFrame.add(Main.ShipShopEnginesMenu);
Main.ShipShopEnginesMenu.setVisible(true);
Main.ShipShopEnginesMenu.setEnabled(true);
Main.ShipShopEnginesMenu.setFocusable(true);
Main.ShipShopEnginesMenu.requestFocusInWindow();
}
else if(eventId == 3)
{
}
else if(eventId == 4)
{
System.out.println("Exit Ship Shop Hulls menu to Thrusters Ship Shop Menu selected");
Main.ShipShopHullsMenu.setVisible(false);
Main.ShipShopHullsMenu.setEnabled(false);
Main.ShipShopHullsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopHullsMenu);
Main.mainFrame.add(Main.ShipShopThrustersMenu);
Main.ShipShopThrustersMenu.setVisible(true);
Main.ShipShopThrustersMenu.setEnabled(true);
Main.ShipShopThrustersMenu.setFocusable(true);
Main.ShipShopThrustersMenu.requestFocusInWindow();
}
else if(eventId == 5)
{
System.out.println("Exit Ship Shop Hulls menu to Weapons Ship Shop Menu selected");
Main.ShipShopHullsMenu.setVisible(false);
Main.ShipShopHullsMenu.setEnabled(false);
Main.ShipShopHullsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopHullsMenu);
Main.mainFrame.add(Main.ShipShopWeaponsMenu);
Main.ShipShopWeaponsMenu.setVisible(true);
Main.ShipShopWeaponsMenu.setEnabled(true);
Main.ShipShopWeaponsMenu.setFocusable(true);
Main.ShipShopWeaponsMenu.requestFocusInWindow();
}
else if(eventId == 6)
{
}
else if(eventId == 7)
{
}
else if(eventId == 8)
{
System.out.println("Exit Ship Shop Hulls menu to Main Menu selected");
Main.ShipShopHullsMenu.setVisible(false);
Main.ShipShopHullsMenu.setEnabled(false);
Main.ShipShopHullsMenu.setFocusable(false);
Main.mainFrame.remove(Main.ShipShopHullsMenu);
Main.mainFrame.add(Main.mainMenu);
Main.mainMenu.setVisible(true);
Main.mainMenu.setEnabled(true);
Main.mainMenu.setFocusable(true);
Main.mainMenu.requestFocusInWindow();
}
} | 8 |
public ModelProxy<?> getModelProxy() {
return modelProxy;
} | 1 |
public Reference getRef(int i) throws ClassFormatException {
if (i == 0)
return null;
if (tags[i] != FIELDREF && tags[i] != METHODREF
&& tags[i] != INTERFACEMETHODREF)
throw new ClassFormatException("Tag mismatch");
if (constants[i] == null) {
int classIndex = indices1[i];
int nameTypeIndex = indices2[i];
if (tags[nameTypeIndex] != NAMEANDTYPE)
throw new ClassFormatException("Tag mismatch");
String type = getUTF8(indices2[nameTypeIndex]);
try {
if (tags[i] == FIELDREF)
TypeSignature.checkTypeSig(type);
else
TypeSignature.checkMethodTypeSig(type);
} catch (IllegalArgumentException ex) {
throw new ClassFormatException(ex.getMessage());
}
String clName = getClassType(classIndex);
constants[i] = Reference.getReference(clName,
getUTF8(indices1[nameTypeIndex]), type);
}
return (Reference) constants[i];
} | 8 |
@Override
public void run() {
while (!ctx.isShutdown()) {
if (ctx.isPaused()) {
paused = true;
ctx.sleep(1000);
} else {
paused = false;
int delay;
try {
delay = loop();
} catch (Throwable throwable) {
throwable.printStackTrace();
delay = -1;
}
if (delay >= 0) {
ctx.sleep(delay);
} else if (delay == -1) {
break;
}
}
}
} | 5 |
private static void doUpdateTest()
{
try
{
System.out.print("Testing update command ");
// make mvd & load it
String testData = TEST_DATA+File.separator+BLESSED_DAMOZEL;
File testDataFolder = new File( testData );
String mvdName = createTestMVD( testDataFolder );
File mvdFile = new File( mvdName );
MVD mvd = MVDFile.internalise( mvdFile, null );
int numVersions = mvd.numVersions();
Random rand = new Random( System.currentTimeMillis() );
int vId = rand.nextInt(numVersions)+1;
char[] data1 = mvd.getVersion( vId );
// replace every 10th 'b' with 'x'
for ( int bCount=0,i=0;i<data1.length;i++ )
{
if ( data1[i] == 'b' )
{
if ( bCount == 9 )
{
bCount = 0;
data1[i] = 'x';
}
else
bCount++;
}
}
String vIdStr = new Integer(vId).toString();
String tempName = TEST_FOLDER+File.separator+"temp.txt";
File tempFile = new File( tempName );
FileOutputStream fos = new FileOutputStream( tempFile );
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
osw.write( data1 );
osw.close();
String[] args0 = {"-c","update","-m",mvdName,"-v",vIdStr,"-t",
tempName};
MvdTool.run( args0, out );
mvd = MVDFile.internalise( mvdFile, null );
char[] data2 = mvd.getVersion( vId );
compareTwoCharArrays( data1, data2 );
System.out.print(".");
// updated file can't be used for other tests
mvdFile.delete();
testsPassed++;
System.out.println(" test passed.");
}
catch ( Exception e )
{
doTestFailed( e );
}
} | 4 |
public PongView(PongModel model) {
//initialize the View members:
this.model = model;
WIDTH_PXL = 600;
HEIGHT_PXL = WIDTH_PXL*((int)model.getFieldSize().getHeight())/((int)model.getFieldSize().getWidth());
this.ball = new Ball();
this.bars = Collections.unmodifiableMap(new HashMap<BarKey,Bar>() {{
put(BarKey.LEFT, new Bar(0));
put(BarKey.RIGHT, new Bar(WIDTH_PXL));
}});
final Map<BarKey,JLabel> scorelabels = new HashMap<BarKey,JLabel>();
// initialize the graphics stuff:
final JFrame frame = new JFrame("SwingPong");
final JLabel msglabel = new JLabel("Messages");
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
final int MSG_HEIGHT = 30;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JLabel background = new JLabel("");
background.setBackground(Color.BLACK);
background.setOpaque(true);
background.setBorder(BorderFactory.createLineBorder(Color.WHITE));
background.setBounds(0,0,WIDTH_PXL,HEIGHT_PXL);
JLabel centerline = new JLabel("");
final int CENTERLINE_WIDTH = 5;
centerline.setBackground(Color.WHITE);
centerline.setOpaque(true);
centerline.setBounds(WIDTH_PXL/2-CENTERLINE_WIDTH/2,0,
CENTERLINE_WIDTH, HEIGHT_PXL);
msglabel.setPreferredSize(new Dimension(WIDTH_PXL, MSG_HEIGHT));
msglabel.setBounds(1,10, WIDTH_PXL-20, MSG_HEIGHT);
msglabel.setForeground(Color.WHITE);
msglabel.setBackground(Color.BLACK);
msglabel.setOpaque(true);
msglabel.setHorizontalAlignment(SwingConstants.CENTER);
for (BarKey k : BarKey.values()) {
scorelabels.put(k, makeScoreLabel(k));
}
frame.getContentPane().setPreferredSize(new Dimension(WIDTH_PXL, HEIGHT_PXL));
for (Bar bar : bars.values()) {
frame.getContentPane().add(bar.getJComponent());
}
frame.getContentPane().add(ball.getJComponent());
for (JLabel scorelabel : scorelabels.values()) {
frame.getContentPane().add(scorelabel);
}
frame.getContentPane().add(msglabel);
frame.getContentPane().add(centerline);
frame.getContentPane().add(background);
frame.pack();
}
});
} catch (Exception e) {
System.err.println("Couldn't initialize PongView: " + e);
System.exit(1);
}
this.frame = frame;
this.msglabel = msglabel;
this.scorelabels = scorelabels;
} | 4 |
public static void main(String[] args)
{
ListGenericFoo<LinkedList> foo1 = new ListGenericFoo<LinkedList>();
ListGenericFoo<ArrayList> foo2 = new ListGenericFoo<ArrayList>();
LinkedList[] linkedList = new LinkedList[10];
foo1.setFooArray(linkedList);
ArrayList[] arrayList = new ArrayList[10];
foo2.setFooArray(arrayList);
// ListGenericFoo<HashMap> foo3 = new ListGenericFoo<HashMap>();
} | 0 |
public Connection getConnection() {
Context context = null;
try {
context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup(JNDI_NAME);
return dataSource.getConnection();
} catch (NamingException ex) {
throw new DAOException(JNDI_NAME + " niet gevonden", ex);
} catch (SQLException ex) {
throw new DAOException("kan geen connectie krijgen van " + JNDI_NAME, ex);
} finally {
try {
if (context != null) {
context.close();
}
} catch (NamingException ex) {
throw new DAOException("kan " + JNDI_NAME + " niet sluiten",ex);
}
}
} | 4 |
@Override
public Double getScalarValue(Word word) {
for (Word word1:wordList) {
if (word1.getKeyWord().equals(word.getKeyWord())){
if(word1.getSpamLabel().equals(word.getSubkey())){
return word1.getSpamCount();
}else if(word1.getGenuineLabel().equals(word.getSubkey())) {
return word1.getGeuineCount();
}
return word1.getProb();
}
}
return 0.0;
} | 4 |
public void printVector(PrintableStringWriter stream) {
{ FloatVector self = this;
if (self.arraySize == 0) {
stream.print("|i|[]");
}
else {
{ int i = 0;
int limit = 9;
stream.print("|i|[");
{ double element = Stella.NULL_FLOAT;
FloatVector vector000 = self;
int index000 = 0;
int length000 = vector000.arraySize;
loop000 : for (;index000 < length000; index000 = index000 + 1) {
element = ((FloatWrapper)(((FloatWrapper)((vector000.theArray)[index000])))).wrapperValue;
stream.print(element);
i = i + 1;
if (i > limit) {
break loop000;
}
if (i < self.arraySize) {
stream.print(" ");
}
}
}
if ((i <= limit) ||
(i == self.arraySize)) {
stream.print("]");
}
else {
stream.print(" ...]");
}
}
}
}
} | 6 |
public static void mouseMoved(MouseEvent mouseEvent) {
Iterator<PComponent> it = components.iterator();
while(it.hasNext()) {
PComponent comp = it.next();
if(comp == null)
continue;
if (shouldHandleMouse) {
if (comp.shouldHandleMouse())
comp.mouseMoved(mouseEvent);
}
else {
if (comp instanceof PFrame) {
for (PComponent component : ((PFrame) comp).getComponents())
if (component.forceMouse())
component.mouseMoved(mouseEvent);
}
else if (comp.forceMouse())
comp.mouseMoved(mouseEvent);
}
}
} | 8 |
public Object leerObjeto (String path, String nom) /*throws FileNotFoundException, IOException*/ {
Object ob = null;
File f = new File("./Data/Barrios/" + path + nom + ".o");
try{//FileWriter fw = new FileWriter(f);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ob = ois.readObject();
ois.close();
} catch(Exception e){
System.out.println("\nDATA CORRUPTED!!!");
System.out.println(e.getMessage() + "\n");
}
return ob;
} | 1 |
@Test(expected=BadPostfixException.class)
public void evaluatePostfix2() throws DAIndexOutOfBoundsException, DAIllegalArgumentException, NumberFormatException, NotEnoughOperandsException, BadPostfixException
{
try
{
postfix.addLast("5");
String result = calc.evaluatePostfix(postfix);
}
catch (DAIndexOutOfBoundsException e)
{
throw new DAIndexOutOfBoundsException();
}
catch (DAIllegalArgumentException e)
{
throw new DAIllegalArgumentException();
}
catch (NumberFormatException e)
{
throw new NumberFormatException();
}
catch (NotEnoughOperandsException e)
{
throw new NotEnoughOperandsException();
}
catch (BadPostfixException e)
{
throw new BadPostfixException();
}
} | 5 |
@Override
public void repaint(TextGraphics graphics)
{
graphics.applyTheme(graphics.getTheme().getDefinition(style));
graphics = transformAccordingToAlignment(graphics, calculatePreferredSize());
if(textColor != null)
graphics.setForegroundColor(textColor);
if(textBold != null) {
if(textBold)
graphics.setBoldMask(true);
else
graphics.setBoldMask(false);
}
if(text.length == 0)
return;
int leftPosition = 0;
for(int i = 0; i < text.length; i++) {
if(forceWidth > -1) {
if(text[i].length() > forceWidth)
graphics.drawString(leftPosition, i, text[i].substring(0, forceWidth - 3) + "...");
else
graphics.drawString(leftPosition, i, text[i]);
}
else
graphics.drawString(leftPosition, i, text[i]);
}
} | 7 |
public void addOpenHouses() {
nextCheckForhouses = System.currentTimeMillis() + 600000; // 10 minutes
final String json = IOUtil.readString(URL_GET_HOUSES, ctx.useragent);
try {
JsonObject jsonObject = JsonObject.readFrom(json);
final JsonValue open_houses = jsonObject.get("open_houses");
if (open_houses != null && open_houses.isArray()) {
final JsonArray houses = open_houses.asArray();
for (JsonValue house : houses) {
if (house.isString()) {
final String playername = house.asString();
if (!ignoreHouses.contains(playername)) {
final OpenHouse openHouse = new OpenHouse(script, playername);
if (!openHouses.contains(openHouse)) {
openHouses.add(openHouse);
script.log.info("Added house at \"" + playername + "\"");
}
}
//checkedNames.put(playername, true);
//IPlayerValidator.valid(playername);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | 7 |
public static boolean isNumber(String num) throws LexicalException
{
Long lowerBound = -4294967296L;
Long upperBound = 4294967295L;
try {
Long.valueOf(num).longValue();
} catch (NumberFormatException nfe) {
return false;
}
Long temp = Long.valueOf(num).longValue();
if( !(lowerBound<=temp) || !(upperBound>=temp) ){
// TODO: Add exception here
throw new LexicalException("Number out of range");
}
return true;
} | 3 |
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.