text stringlengths 14 410k | label int32 0 9 |
|---|---|
public long asLong()
{
try {
if (isNull()) {
return 0;
} else if (isLong()) {
return ((Long) value).longValue();
} else if (isString()) {
String s = (String) value;
s=s.replaceAll(",","");
return Long.valueOf(s).longValue();
} else if (isShort()) {
return ((Short) value).longValue();
} else if (isInt()) {
return ((Integer) value).longValue();
} else if (isDouble()) {
return ((Double) value).longValue();
} else if (isFloat()) {
return ((Float) value).longValue();
} else if (isBigDecimal()) {
return ((BigDecimal) value).longValue();
} else {
return Integer.valueOf(asString()).longValue();
}
} catch (Exception e) {
throw new SwingObjectRunException( e, ErrorSeverity.SEVERE, FrameFactory.class);
}
} | 9 |
public void setThreadState(int id, boolean state) {
threadStates[id] = state;
} | 0 |
@Test
public final void testIterator() {
Iterator<SpatialTree<Sphere>> it;
SpatialTree<Sphere> tree = new SpatialTree<Sphere>(objects);
int count = 0;
it = tree.leafInterator();
while (it.hasNext()) {
for (Sphere s : it.next()) {
assertTrue(s instanceof Sphere);
count++;
}
}
assertEquals(objects.size(), count);
} | 2 |
private void selectUnit(int x, int y) throws GameFieldException {
if (model.isAvailableUnit(x, y)) {
selectSquare(x, y);
selectedSquares = model.getAccessibleSquares(x, y);
}
} | 1 |
public Sound(String soundFile) {
try {
File file = new File("Sounds\\" + soundFile + ".mid");
soundClip = AudioSystem.getClip();
soundClip.open(AudioSystem.getAudioInputStream(file));
}
catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 3 |
public void extractConfig(final String resource, final boolean replace) {
final File config = new File(this.getDataFolder(), resource);
if (config.exists() && !replace) return;
this.getLogger().log(Level.FINE, "Extracting configuration file {1} {0} as {2}", new Object[] { resource, CustomPlugin.CONFIGURATION_SOURCE.name(), CustomPlugin.CONFIGURATION_TARGET.name() });
config.getParentFile().mkdirs();
final char[] cbuf = new char[1024]; int read;
try {
final Reader in = new BufferedReader(new InputStreamReader(this.getResource(resource), CustomPlugin.CONFIGURATION_SOURCE));
final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(config), CustomPlugin.CONFIGURATION_TARGET));
while((read = in.read(cbuf)) > 0) out.write(cbuf, 0, read);
out.close(); in.close();
} catch (final Exception e) {
throw new IllegalArgumentException("Could not extract configuration file \"" + resource + "\" to " + config.getPath() + "\"", e);
}
} | 4 |
public ActiveTestThread(Server serversim){
this.server = serversim;
} | 0 |
private void processScreenBlt(RdpPacket_Localised data,
ScreenBltOrder screenblt, int present, boolean delta) {
if ((present & 0x01) != 0)
screenblt.setX(setCoordinate(data, screenblt.getX(), delta));
if ((present & 0x02) != 0)
screenblt.setY(setCoordinate(data, screenblt.getY(), delta));
if ((present & 0x04) != 0)
screenblt.setCX(setCoordinate(data, screenblt.getCX(), delta));
if ((present & 0x08) != 0)
screenblt.setCY(setCoordinate(data, screenblt.getCY(), delta));
if ((present & 0x10) != 0)
screenblt.setOpcode(ROP2_S(data.get8()));
if ((present & 0x20) != 0)
screenblt.setSrcX(setCoordinate(data, screenblt.getSrcX(), delta));
if ((present & 0x40) != 0)
screenblt.setSrcY(setCoordinate(data, screenblt.getSrcY(), delta));
// if(//logger.isInfoEnabled())
// //logger.info("opcode="+screenblt.getOpcode());
surface.drawScreenBltOrder(screenblt);
} | 7 |
private String formatHistory(String history) {
String[] lines = history.split("\\r?\\n");
String[] fields;
String result = "<table class=\"history\"><thead>";
for (Integer i=0; i<lines.length; i++) {
String line = lines[i].trim();
if (line.matches("(\\-+[\\s\\t]*\\|?[\\s\\t]*)+")) {
continue;
}
fields = line.split("\\|");
result += "<tr>";
for (Integer j=0; j<fields.length; j++) {
String field = fields[j].trim();
if (field.equals("Date") || field.equals("Author") || field.equals("Version")) {
result += ("<th>"+field+"</th>");
continue;
} else if (field.equals("Remarks")) {
result += ("<th class=\"remarks\">"+field+"</th>");
continue;
}
if (result.endsWith("</th>")) {
result += "</tr></thead><tbody>";
}
result += "<td>"+field+"</td>";
}
result += "</tr>";
}
result += "</tbody></table>";
return result;
} | 8 |
@Override
public void run() {
try
{
pushStatusToTaskTracker();
//called once
reducer.setup();
// Shuffle
int count = 0;
if(lookUpJobTracker()){
MapJobsStatus status;
status = getJobTrackerServiceProvider().reportMapStatus(taskID);
while(!status.equals(MapJobsStatus.SUCCEEDED)){
status = getJobTrackerServiceProvider().reportMapStatus(taskID);
Thread.sleep(1000);
}
} else {
System.out.println("ERROR : Cannot look up the Job tracker.");
this.outputCollector.close();
System.exit(0);
}
System.out.println("All map task have been completed.");
System.out.println("Starting the Shuffle process");
List<String> data = shuffleData();
if(data == null){
System.out.println("Error has been occured while accessing the Data from the Mappers.");
// let the job tracker know??????
this.outputCollector.close();
System.exit(0);
} else {
System.out.println("Got all data from the Mapper.");
}
// Packaging the Data
System.out.println("Combining the data.");
HashMap<String, List<String>> packagedData = packageData(data);
if(packagedData.isEmpty()){
System.out.println("There are errors in packaging the Data.");
this.outputCollector.close();
System.exit(0);
} else {
System.out.println("Data packaged.");
totalEntryNumber = packagedData.size();
}
// Reduce
try {
Iterator iter = packagedData.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, List<String>> entry = (Entry<String, List<String>>) iter.next();
reducer.reduce(entry.getKey(), entry.getValue().iterator(), this.outputCollector);
// This is for tracking the progress
processedEntryNumber++;
}
/* close the files */
this.outputCollector.close();
String name = this.outputCollector.getOutputFileName().substring(SystemConstants.getConfig(SystemConstants.ADFS_DIRECTORY).length() + 1);
this.nameNodeSlaveReference.registerToLocalDataNode(name);
getCreatedFiles().add(name);
}/* if runtime exception happens in user's code, exit jvm */
catch (RuntimeException e) {
e.printStackTrace();
System.exit(0);
}
// Send the file to the Job Client location
sendResultToJobClient();
//clean-up at end
reducer.cleanUp();
//Shows task is Done
this.updateStatusSucceeded();
Thread.sleep(4000);
}
catch(IOException | InterruptedException e)
{
System.exit(0);
}
System.exit(0);
} | 7 |
@Override
public void run(int interfaceId, int componentId) {
if (stage == -1) {
sendEntityDialogue(SEND_2_TEXT_CHAT,
new String[] { player.getDisplayName(), "Hey! ",
"Can you help me out?" }, IS_PLAYER,
player.getIndex(), 9827);
stage = 1;
} else if (stage == 1) {
sendEntityDialogue(SEND_4_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"Sure I can! What are you seaking help in?",
"There are various things I can help you out",
"with, just ask and I'll answer for you ",
"the best I can." }, IS_NPC, npcId, 9827);
stage = 2;
} else if (stage == 2) {
sendDialogue(SEND_4_OPTIONS, new String[] {
player.getDisplayName(), "How do you train Range?",
"What are the differences between bows?", "Who are you?",
"Nevermind, thanks." });
stage = 3;
} else if (stage == 3) {
if (componentId == 1) {
sendEntityDialogue(SEND_4_TEXT_CHAT, new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"Training Range is a simple skill. There are many",
"ways you can train. For beginners I recommend using",
"a regular Short bow and Bronze arrows. Walk South",
"towards Al kharid you can kill ducks in the river." },
IS_NPC, npcId, 9827);
stage = 4;
} else if (componentId == 2) {
sendEntityDialogue(
SEND_4_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"Different bows have different bonuses. Some bows",
"even have a special attack options, which makes you",
"hit higher than bows without them. The higher the level",
"you are the better bows and arrows you earn." },
IS_NPC, npcId, 9827);
stage = 5;
} else if (componentId == 3) {
sendEntityDialogue(SEND_2_TEXT_CHAT, new String[] {
NPCDefinitions.getNPCDefinitions(npcId).name,
"I am the instructor for the ranging skill, I don't",
"do much besides stand here and help new comers." },
IS_NPC, npcId, 9827);
stage = 6;
} else if (componentId == 4) {
sendEntityDialogue(SEND_1_TEXT_CHAT,
new String[] { player.getDisplayName(), "Nevermind." },
IS_PLAYER, player.getIndex(), 9827);
stage = 100;
}
} else if (stage == 100) {
end();
}
} | 9 |
public int compare(String o1, String o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int thisMarker = 0;
int thatMarker = 0;
int s1Length = s1.length();
int s2Length = s2.length();
while (thisMarker < s1Length && thatMarker < s2Length)
{
String thisChunk = getChunk(s1, s1Length, thisMarker);
thisMarker += thisChunk.length();
String thatChunk = getChunk(s2, s2Length, thatMarker);
thatMarker += thatChunk.length();
// If both chunks contain numeric characters, sort them numerically
int result = 0;
if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0)))
{
// Simple chunk comparison by length.
int thisChunkLength = thisChunk.length();
result = thisChunkLength - thatChunk.length();
// If equal, the first different number counts
if (result == 0)
{
for (int i = 0; i < thisChunkLength; i++)
{
result = thisChunk.charAt(i) - thatChunk.charAt(i);
if (result != 0)
{
return result;
}
}
}
} else
{
result = thisChunk.compareTo(thatChunk);
}
if (result != 0)
return result;
}
return s1Length - s2Length;
} | 8 |
private static void writeCleanFile(){
try{
writer = new FileWriter("MegaDictionary.txt");
}
catch(IOException e){
System.err.println("New File Could Not Be Initialised For Writing");
}
for(int i = 0; i<words.size(); i++){
String toWrite = (words.get(i));
char[] write = toWrite.toCharArray();
try{
writer.write(write);
writer.write('\r');
writer.write('\n');
}
catch(IOException e){
System.err.println("Could Not Write To File");
e.printStackTrace();
}
}
System.out.println("New File Written");
} | 3 |
public static float clampFloat(float value, float min, float max)
{
return (value < min) ? min : (value > max) ? max : value;
} | 2 |
public boolean hasNextInt()
{
if(hasNext())
try
{
Integer.parseInt(token);
return true;
}
catch(Exception e)
{
return false;
}
else
return false;
} | 2 |
private boolean crossingInternal(Point2D.Double direction1, Point2D.Double direction2) {
if (angles.size() < 2) {
return false;
}
final double angle1 = convertAngle(getAngle(new Line2D.Double(center, direction1)));
final double angle2 = convertAngle(getAngle(new Line2D.Double(center, direction2)));
Double last = null;
for (Double current : angles) {
if (last != null) {
assert last < current;
if (isBetween(angle1, last, current) && isBetween(angle2, last, current)) {
return false;
}
}
last = current;
}
final double first = angles.first();
if ((angle1 <= first || angle1 >= last) && (angle2 <= first || angle2 >= last)) {
return false;
}
return true;
} | 9 |
public SplashScreen(int d) {
duration = d;
} | 0 |
public void checkFields(LYNXsys system) { // method to check textfields before adding book
if (!(getBookTitle().getTextField().getText().equals("")) && //check if ALL fields are provided
!(getAuthorFirstName().getTextField().getText().equals("")) &&
!(getAuthorLastName().getTextField().getText().equals("")) &&
!(getCategory().getTextField().getText().equals("")) &&
!(getIsbn().getTextField().getText().equals("")) &&
!(getCost().getTextField().getText().equals("")) &&
!(getRating().getTextField().getText().equals(""))) { // end check...
// add a book ...
system.addBook(new Book(getBookTitle().getTextField().getText(), getAuthorFirstName().getTextField().getText(), getAuthorLastName().getTextField().getText(), getIsbn().getTextField().getText(), getCategory().getTextField().getText(), Double.parseDouble(getCost().getTextField().getText()),getRating().getTextField().getText(),"Y"));
}
} | 7 |
public static void keyPressed(String key)
{
switch(key)
{
case "escape":
escape();
break;
case "enter":
enter();
break;
case "space":
space();
break;
}
switch(Main.Screen)
{
case "inGame":
Main.inGameManager.keyPressed(key);
break;
}
} | 4 |
public String getPackageName() {
return this.packageName;
} | 0 |
protected boolean validateHeader(byte[] header){
if(header.length != 16){
System.err.println("Invalid header. Not 16 bytes???");
return false;
}
// Now we validate the Header based on this document: http://nesdev.parodius.com/neshdr20.txt
// Bytes:
// 0 = 0x4E (charcter N)
// 1 = 0x45 (character E)
// 2 = 0x53 (character S)
// 3 = 0x1A (Character Break)
// 4 = number of prg banks
// 5 = number of chr banks
// 6 = Mapper, mirroring, etc..
// 7 = More mapper info
// 8 to 15 all zeroes
if((header[0] != 0x4E) ||
(header[1] != 0x45) ||
(header[2] != 0x53) ||
(header[3] != 0x1A))
{
System.err.println("Not a valid ROM file. Not an iNES header");
return false;
}
int prgBanks = (int)header[4];
int chrBanks = (int)header[5];
int baseMapper = header[6];
int additionalMapper = header[7];
for(int i=8;i<=15;i++){
if(header[i] != 0){
System.err.println("The remaining portion of the header (byte) " + i + " was not zero. Invalid iNES header");
// return false;
}
}
_numPrgBanks = prgBanks;
_numChrBanks = chrBanks;
_baseMapperInfo = baseMapper;
_additionalMapperInfo = additionalMapper;
// System.out.println("Header Information:");
// System.out.println("\tNum PRG Banks:" + _numPrgBanks);
// System.out.println("\tNum CHR Banks:" + _numChrBanks);
int mapperType = _baseMapperInfo / 16;
// int mapperFlags = _baseMapperInfo % 16;
_mapperName = (mapperType < 0 || mapperType > INES_ROM_INFO.MAX_MAPPER) ? "???" : INES_ROM_INFO.MAPPER_STRINGS[mapperType];
// String mapFlag = (mapperFlags < 0 || mapperFlags > INES_ROM_INFO.MAX_MAPPER_FLAGS) ? "???" : INES_ROM_INFO.MAPPER_FLAGS[mapperFlags];
// System.out.println("\tMapper Entry:" + _baseMapperInfo);
// System.out.println("\tMapper:" + mapperType);
// System.out.println("\tType:" + _mapperName);
// System.out.println("\tFlags:" + mapFlag);
// System.out.println("\tExtended:" + _additionalMapperInfo);
_additionalMapperInfo = 0;
return true;
} | 9 |
public com.babyduncan.thrift.model.Book recv_getBook() throws org.apache.thrift.TException
{
getBook_result result = new getBook_result();
receiveBase(result, "getBook");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "getBook failed: unknown result");
} | 1 |
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uri = req.getRequestURI();
if (uri.contains("/resources/")) {
super.doGet(req, res);
} else {
processRequest(req, res);
}
} | 1 |
private boolean processArguments(final String[] args)
throws CommandException
{
log.debug("processing arguments: " + Strings.join(args, ","));
if (args.length == 0)
{
throw new CommandException("Command requires arguments");
}
String sopts = "-:";
LongOpt[] lopts =
{
new LongOpt("noprefix", LongOpt.NO_ARGUMENT, null, 0x1000),
};
Getopt getopt = new Getopt(null, args, sopts, lopts);
getopt.setOpterr(false);
int code;
int argidx = 0;
while ((code = getopt.getopt()) != -1)
{
switch (code)
{
case ':':
throw new CommandException
("Option requires an argument: " + args[getopt.getOptind() - 1]);
case '?':
throw new CommandException
("Invalid (or ambiguous) option: " + args[getopt.getOptind() - 1]);
case 0x1000:
break;
// non-option arguments
case 1:
{
String arg = getopt.getOptarg();
switch (argidx++)
{
case 0:
objectName = createObjectName(arg);
log.debug("mbean name: " + objectName);
break;
default:
log.debug("adding attribute name: " + arg);
attributeNames.add(arg);
break;
}
break;
}
}
}
return true;
} | 7 |
public static int[] createHashes(byte[] data, int hashes) {
int[] result = new int[hashes];
int k = 0;
byte salt = 0;
while (k < hashes) {
byte[] digest;
synchronized (digestFunction) {
digestFunction.update(salt);
salt++;
digest = digestFunction.digest(data);
}
for (int i = 0; i < digest.length/4 && k < hashes; i++) {
int h = 0;
for (int j = (i*4); j < (i*4)+4; j++) {
h <<= 8;
h |= ((int) digest[j]) & 0xFF;
}
result[k] = h;
k++;
}
}
return result;
} | 4 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Delivery delivery = deliveries.get(rowIndex);
Item item = delivery.getItem();
if (columnIndex == NUMBER) {
return item.getNumber();
} else if (columnIndex == TYPE) {
return item.getModel().getModelPK().getType();
} else if (columnIndex == MODEL) {
String modelName = item.getModel().getModelPK().getName();
String vendorName = item.getModel().getModelPK().getVendor();
StringBuilder fullModelName = new StringBuilder();
fullModelName.append(modelName);
fullModelName.append(" (").append(vendorName).append(')');
return fullModelName.toString();
} else if (columnIndex == RETURN_DATE) {
return delivery.isReturn() ? delivery.getReturnDate() : null;
} else {
logger.warn("Попытка получить значение которое не существет из списка выдач. "
+ "Строка: " + rowIndex + ", столбец: " + columnIndex);
return null;
}
} | 5 |
@Override
public void tick(ControlleurObjets controlleur) {
if(++timer >= 3){
frame++;
timer = 0;
}
if(frame >= 4 && exploding == false) {
frame = 0;
}
else if (exploding && frame == 3) {
try {
jeu.gameOver();
} catch (Throwable ex) {
System.out.println(ex.toString());
}
}
// Même vitesse peut importe la direction
if (velX != 0 || velY != 0) {
delta = (float) Math.sqrt(velX * velX + velY * velY);
x += Joueur.V * velX/delta;
y += Joueur.V * velY/delta;
}
gererCollision(controlleur);
} | 8 |
public boolean loadSingleImage(String fnm, String name, float transperancy, short red, short green, short blue) {
if (name.equals("")) {
name = getPrefix(fnm);
}
if (imagesMap.containsKey(name)) {
EIError.debugMsg("Error: " + name + "already used", EIError.ErrorLevel.Error);
return false;
}
BufferedImage bi = loadImage(fnm);
bi = changeTransperancy(bi, transperancy);
if (red > -1 && green > -1 && blue > -1) {
bi = changeColor(bi, red, green, blue);
}
if (bi != null) {
ArrayList imsList = new ArrayList();
imsList.add(bi);
imagesMap.put(name.replace("/Images/", ""), imsList);
String imageName[] = name.split("/");
Game.loadingText = "Loading (" + imageName[imageName.length - 1] + ")";
return true;
} else {
return false;
}
} | 6 |
@EventHandler
public void EnderDragonInvisibility(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.getEnderDragonConfig().getDouble("EnderDragon.Invisibility.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if ( plugin.getEnderDragonConfig().getBoolean("EnderDragon.Invisibility.Enabled", true) && damager instanceof EnderDragon && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, plugin.getEnderDragonConfig().getInt("EnderDragon.Invisibility.Time"), plugin.getEnderDragonConfig().getInt("EnderDragon.Invisibility.Power")));
}
} | 6 |
public Vertex[] pathDFS(Vertex source, Vertex target) {
if (graph.containsKey(source) && graph.containsKey(target)) {
Graph tree = new Graph();
Stack<Vertex> S = new Stack<Vertex>();
S.push(source);
source.setVisited(true);
boolean pathFound = false;
// create a tree until target is reached
while (!S.empty() && !pathFound) {
Vertex v = S.pop();
ArrayList<Edge> E = new ArrayList<Edge>();
// if v has an unvisited neighbour w
for (Edge edge : graph.get(v)) {
Vertex w = edge.getTarget();
if (w.equals(target)) {
w.setVisited(true);
w.setParent(v);
E.add(edge);
tree.addConnectedVertex(v, E);
tree.addVertex(w);
pathFound = true;
break;
}
else if (!w.isVisited()) {
w.setVisited(true);
w.setParent(v);
E.add(edge);
S.push(w);
}
}
tree.addConnectedVertex(v, E);
}
// from target retrieve the source
Stack<Vertex> sPath = new Stack<Vertex>();
sPath.push(target);
while (sPath.peek().parent() != null) {
sPath.push(sPath.peek().parent());
}
Vertex[] path = new Vertex[sPath.size()];
return sPath.toArray(path);
}
else {
throw new NullPointerException("Vertex source " + source + " or Vertex target "
+ target + " does not belong to the graph");
}
} | 8 |
public static ArrayList<bConsulta> getListaProdData(String dt1, String arg_gmp) throws SQLException, ClassNotFoundException {
ArrayList<bConsulta> sts = new ArrayList<bConsulta>();
Connection conPol = conMgr.getConnection("PD");
if (conPol == null) {
throw new SQLException("Numero Maximo de Conexoes Atingida!");
}
try {
Statement stmt = conPol.createStatement();
String strQl;
strQl = "SELECT distinct(tb_registro.cod_prod),tb_produto.str_prod FROM tb_registro,tb_produto "
+ "WHERE tb_registro.cod_prod = tb_produto.cod_prod "
+ "AND date_trunc('month', datah) = TO_timestamp('" + dt1 + "','MM/YYYY') ";
if (!arg_gmp.equals("")) {
strQl += " AND cod_gmp = " + arg_gmp;
}
strQl += " ORDER BY cod_prod;";
ResultSet rs = stmt.executeQuery(strQl);
while (rs.next()) {
bConsulta reg = new bConsulta();
reg.setCod_prod(rs.getString("cod_prod"));
reg.setStr_prod(rs.getString("str_prod"));
sts.add(reg);
}
} finally {
if (conPol != null) {
conMgr.freeConnection("PD", conPol);
}
}
return sts;
} | 4 |
public int compareTo( Object obj ) {
if( obj == null ) {
return( 1 );
}
else if( obj instanceof GenKbSecAppByUJEEMountIdxKey ) {
GenKbSecAppByUJEEMountIdxKey rhs = (GenKbSecAppByUJEEMountIdxKey)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredJEEMountName().compareTo( rhs.getRequiredJEEMountName() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else if( obj instanceof GenKbSecAppBuff ) {
GenKbSecAppBuff rhs = (GenKbSecAppBuff)obj;
if( getRequiredClusterId() < rhs.getRequiredClusterId() ) {
return( -1 );
}
else if( getRequiredClusterId() > rhs.getRequiredClusterId() ) {
return( 1 );
}
{
int cmp = getRequiredJEEMountName().compareTo( rhs.getRequiredJEEMountName() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else {
throw CFLib.getDefaultExceptionFactory().newUnsupportedClassException( getClass(),
"compareTo",
"obj",
obj,
null );
}
} | 9 |
public void cutSelection() {
if (selected) {
copySelection();
if (wave.length() - (selectEnd - selectStart + 1) <= 0) {
wave = null;
selectNone();
observer.waveCanvasEvent (this, NULL);
} else {
double[] s = wave.getWave();
double[] d = new double [wave.length() - (selectEnd - selectStart + 1)];
int i, j;
for (i = 0; i < selectStart; i++)
d[i] = s[i];
for (j = selectEnd + 1; j < s.length; j++, i++)
d[i] = s[j];
wave.setWave (d);
int start, end;
if (selectStart >= wave.length()) start = wave.length() - 1;
else start = selectStart;
select (start, start);
i = viewEnd - viewStart + 1;
if (viewStart >= wave.length())
viewStart = wave.length() - 1;
viewEnd = viewStart + i;
if (viewEnd >= wave.length())
viewEnd = wave.length() - 1;
repaint();
}
}
} | 7 |
public boolean addComponentParts(World par1World, Random par2Random, StructureBoundingBox par3StructureBoundingBox)
{
if (this.averageGroundLevel < 0)
{
this.averageGroundLevel = this.getAverageGroundLevel(par1World, par3StructureBoundingBox);
if (this.averageGroundLevel < 0)
{
return true;
}
this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 6 - 1, 0);
}
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 1, 3, 5, 4, 0, 0, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 0, 0, 3, 0, 4, Block.cobblestone.blockID, Block.cobblestone.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 0, 1, 2, 0, 3, Block.dirt.blockID, Block.dirt.blockID, false);
if (this.isTallHouse)
{
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 4, 1, 2, 4, 3, Block.wood.blockID, Block.wood.blockID, false);
}
else
{
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 5, 1, 2, 5, 3, Block.wood.blockID, Block.wood.blockID, false);
}
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 1, 4, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 2, 4, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 1, 4, 4, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 2, 4, 4, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 1, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 2, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 0, 4, 3, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 1, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 2, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.wood.blockID, 0, 3, 4, 3, par3StructureBoundingBox);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 0, 0, 3, 0, Block.wood.blockID, Block.wood.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 0, 3, 3, 0, Block.wood.blockID, Block.wood.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 4, 0, 3, 4, Block.wood.blockID, Block.wood.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 4, 3, 3, 4, Block.wood.blockID, Block.wood.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 0, 1, 1, 0, 3, 3, Block.planks.blockID, Block.planks.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 3, 1, 1, 3, 3, 3, Block.planks.blockID, Block.planks.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 0, 2, 3, 0, Block.planks.blockID, Block.planks.blockID, false);
this.fillWithBlocks(par1World, par3StructureBoundingBox, 1, 1, 4, 2, 3, 4, Block.planks.blockID, Block.planks.blockID, false);
this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 0, 2, 2, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.thinGlass.blockID, 0, 3, 2, 2, par3StructureBoundingBox);
if (this.tablePosition > 0)
{
this.placeBlockAtCurrentPosition(par1World, Block.fence.blockID, 0, this.tablePosition, 1, 3, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, Block.pressurePlatePlanks.blockID, 0, this.tablePosition, 2, 3, par3StructureBoundingBox);
}
this.placeBlockAtCurrentPosition(par1World, 0, 0, 1, 1, 0, par3StructureBoundingBox);
this.placeBlockAtCurrentPosition(par1World, 0, 0, 1, 2, 0, par3StructureBoundingBox);
this.placeDoorAtCurrentPosition(par1World, par3StructureBoundingBox, par2Random, 1, 1, 0, this.getMetadataWithOffset(Block.doorWood.blockID, 1));
if (this.getBlockIdAtCurrentPosition(par1World, 1, 0, -1, par3StructureBoundingBox) == 0 && this.getBlockIdAtCurrentPosition(par1World, 1, -1, -1, par3StructureBoundingBox) != 0)
{
this.placeBlockAtCurrentPosition(par1World, Block.stairCompactCobblestone.blockID, this.getMetadataWithOffset(Block.stairCompactCobblestone.blockID, 3), 1, 0, -1, par3StructureBoundingBox);
}
for (int var4 = 0; var4 < 5; ++var4)
{
for (int var5 = 0; var5 < 4; ++var5)
{
this.clearCurrentPositionBlocksUpwards(par1World, var5, 6, var4, par3StructureBoundingBox);
this.fillCurrentPositionBlocksDownwards(par1World, Block.cobblestone.blockID, 0, var5, -1, var4, par3StructureBoundingBox);
}
}
this.spawnVillagers(par1World, par3StructureBoundingBox, 1, 1, 2, 1);
return true;
} | 8 |
private int pickGene() {
double selector = Math.abs(random.nextDouble())%fitnessSum;//random number between 0 and fitnessSum
int j = 0;
double count = fitnesses[j];
while(count < selector && j<fitnesses.length-1){
count += fitnesses[++j];
}
return j;
} | 2 |
@Override
public Combinaison obtenirCombinaison()
{
Pion[] pions = new Pion[Mastermind.NOMBRE_DE_PIONS_A_DECOUVRIR_PAR_DEFAUT] ;
while(!(this.combinaisonValidee))
{
System.out.println("Veuillez validé la combinaison");
}
for(int numeroPion = 0 ; numeroPion < Mastermind.NOMBRE_DE_PIONS_A_DECOUVRIR_PAR_DEFAUT ; numeroPion++)
{
pions[numeroPion] = new Pion(this.grilleCombinaisonJeu.tableauBoutonCouleur[numeroPion].getCouleurButton());
}
this.combinaisonValidee = false ;
return new Combinaison(pions);
} | 2 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CToJavaMessage other = (CToJavaMessage) obj;
if (this.Z != other.Z) {
return false;
}
if (this.I != other.I) {
return false;
}
if (this.G != other.G) {
return false;
}
if (this.bodyLength != other.bodyLength) {
return false;
}
if (this.body != other.body && (this.body == null ||
!Arrays.equals(this.body, other.body))) {
return false;
}
return true;
} | 9 |
public Record parseDiscogRelease(int id) throws IOException
{
URL url = new URL(base.replace("ID", "" + id));
try
{
// System.err.println(url);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.addRequestProperty("Accept-Encoding", "gzip");
uc.addRequestProperty("User-Agent", "67668099b8BrotherLogic");
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DiscogXMLParser handler = new DiscogXMLParser();
parser.parse(new GZIPInputStream(uc.getInputStream()), handler);
return handler.getRecord();
}
catch (SAXException e)
{
throw new IOException(e);
}
catch (ParserConfigurationException e)
{
throw new IOException(e);
}
catch (IOException e)
{
try
{
// Deal with 400 exceptions here (needs discog login)
if (e.getMessage().contains("Not in GZIP format"))
{
System.err.println(url);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.addRequestProperty("Accept-Encoding", "gzip");
uc.addRequestProperty("User-Agent", "67668099b8BrotherLogic");
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DiscogXMLParser handler = new DiscogXMLParser();
parser.parse(uc.getInputStream(), handler);
Record r = handler.getRecord();
r.setDiscogsNum(id);
return r;
}
}
catch (Exception e2)
{
throw new IOException(e2);
}
}
return null;
} | 5 |
public boolean isLambdaTransition(Transition transition)
{
MealyTransition t = (MealyTransition) transition;
if(t.getLabel().equals(LAMBDA))
return true;
else
return false;
} | 1 |
public void activateDialogs() {
if(currentDialogBox == null && dialogQueue.size() > 0)
checkDialogs();
} | 2 |
public void start() {
Timer timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
long duration = System.currentTimeMillis() - startTime;
progress = (double) duration / (double) runTime;
if (progress > 1f) {
progress = 1f;
((Timer) e.getSource()).stop();
}
Rectangle target = calculateProgress(from, to, progress);
panel.setBounds(target);
finised();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
startTime = System.currentTimeMillis();
timer.start();
} | 1 |
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
if (!(msg instanceof Frame)) {
return msg;
} else if (msg instanceof HeartBeatFrame) {
return ChannelBuffers.wrappedBuffer(new byte[] { '\n' });
}
Frame frame = (Frame) msg;
// COMMAND
StringBuilder formatedFrame = new StringBuilder();
String command = frame.getCommand();
if (command != null && command.length() > 0) {
formatedFrame.append(command).append(Frame.EOL_COMMAND);
} else {
throw new IllegalArgumentException("Command can't be empty");
}
// HEADER
Header header = frame.getHeader();
if (header != null) {
if (header.size() > 0) {
List<String> keys = new ArrayList<String>(header.keySet());
Collections.sort(keys);
for (String key : keys) {
formatedFrame.append(escapeHeader(key)) //
.append(Frame.SEPARATOR_HEADER) //
.append(escapeHeader(header.get(key))) //
.append(Frame.EOL_HEADER);
}
}
}
formatedFrame.append(Frame.EOL_HEADERS);
// BODY
String body = frame.getBody();
if (body != null && body.length() > 0) {
formatedFrame.append(body);
}
formatedFrame.append(Frame.EOL_FRAME);
String frameString = formatedFrame.toString();
return ChannelBuffers.copiedBuffer((String) frameString, Charset.forName("UTF-8"));
} | 9 |
public static String removeNonLiteralSpaces(String toRemove) {
char[] chars = toRemove.toCharArray();
toRemove = "";
boolean inQuotes = false;
for(char c : chars) {
if(c == '"') {
inQuotes = !inQuotes;
}
if(!inQuotes) {
if(c != ' ') {
toRemove += c;
}
} else {
toRemove += c;
}
}
return toRemove;
} | 4 |
public void liblinear_predict_with_kbestlist(Model model, FeatureNode[] x, KBestList kBestList) throws MaltChainedException {
int i;
final int nr_class = model.getNrClass();
final double[] dec_values = new double[nr_class];
Linear.predictValues(model, x, dec_values);
final int[] labels = model.getLabels();
int[] predictionList = new int[nr_class];
for(i=0;i<nr_class;i++) {
predictionList[i] = labels[i];
}
double tmpDec;
int tmpObj;
int lagest;
for (i=0;i<nr_class-1;i++) {
lagest = i;
for (int j=i;j<nr_class;j++) {
if (dec_values[j] > dec_values[lagest]) {
lagest = j;
}
}
tmpDec = dec_values[lagest];
dec_values[lagest] = dec_values[i];
dec_values[i] = tmpDec;
tmpObj = predictionList[lagest];
predictionList[lagest] = predictionList[i];
predictionList[i] = tmpObj;
}
int k = nr_class-1;
if (kBestList.getK() != -1) {
k = kBestList.getK() - 1;
}
for (i=0; i<nr_class && k >= 0; i++, k--) {
if (kBestList instanceof ScoredKBestList) {
((ScoredKBestList)kBestList).add(predictionList[i], (float)dec_values[i]);
} else {
kBestList.add(predictionList[i]);
}
}
} | 8 |
public static boolean fileprocess(String downloadpath, String filepath, String sn){
int errorcode=0;// print error code in the final output file;
int errornum = 3;
String result="PASS";
File downloadfile = new File(downloadpath+"\\factory_image_version.txt");
File outputfile = new File(filepath);
double value=0;
String line="";
ArrayList <String> content = new ArrayList<String>();
try {
if (!downloadfile.exists()){
throw new IOException();
}
BufferedReader br = new BufferedReader(new FileReader(downloadfile));
while ((line=br.readLine())!=null){
content.add(line);
}
br.close();
downloadfile.delete();
if (content.size()!=1){
result = "FAILED";
errorcode = 2;
}
else{
value=Double.parseDouble(content.get(0));
}
} catch (IOException e) {
result = "FAILED";
errorcode = 0;
}
catch (NumberFormatException ex){
result = "FAILED";
errorcode = 1;
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile,true));
bw.write("SW_Version="+value+"\r\n");
System.out.println("SW_Version="+value);
bw.write("SW_Version_Result="+result+"\r\n");
System.out.println("SW_Version_Result="+result);
if (result.equals("FAILED")){
NumberFormat nf = NumberFormat.getIntegerInstance();
nf.setMinimumIntegerDigits(2);
bw.write("Error_Code= "+nf.format(errornum)+nf.format(errorcode)+"\r\n");
System.out.println("Error_Code="+nf.format(errornum)+nf.format(errorcode));
}
bw.flush();
bw.close();
}catch (Exception e){
e.printStackTrace();
}
return true;
} | 7 |
public void dump()
{
log.debug( "Dumping out PackageManager structure" );
Enumeration pts = this.getPackageTypes();
while ( pts.hasMoreElements() )
{
//get the current package and print it.
PackageType current = (PackageType) pts.nextElement();
log.debug( current.getName() );
//get the classes under the package and print those too.
Enumeration classes = current.getClassTypes();
while ( classes.hasMoreElements() )
{
ClassType currentClass = (ClassType) classes.nextElement();
log.debug( "\t" + currentClass.getName() );
}
}
} | 2 |
public void inicializar(int i,final Player enemy) {
this.enemy=enemy;
this.posicionesMapa = new JLabel[mNumeroDeFilas][mNumeroDeColumnas];
for( int columna = 0 ; columna < this.mNumeroDeFilas ; columna ++ ) {
for( int fila = 0 ; fila < this.mNumeroDeColumnas ; fila ++ ) {
JLabel temp=new JLabel();
final JLabel temp2=new JLabel();
//temp.setText(fila+","+columna);
Border border = LineBorder.createGrayLineBorder();
temp.setBorder(border);
temp.setName(Integer.toString(fila)+"?0?"+Integer.toString(columna));
temp2.setName(Integer.toString(fila)+"?1?"+Integer.toString(columna));
temp2.setBorder(border);
if(i==1){
temp2.setIcon(new ImageIcon(getClass().getResource("/imagenes/fondo.png")));
temp2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent evt) {
int largoIcon=temp2.getIcon().toString().length();
String nombre=temp2.getIcon().toString().substring(largoIcon-8,largoIcon);
if(nombre.equals("ondo.png"))
temp2.setIcon(new ImageIcon(getClass().getResource("/imagenes/target.gif")));
}
@Override
public void mouseExited(MouseEvent evt) {
int largoIcon=temp2.getIcon().toString().length();
String nombre=temp2.getIcon().toString().substring(largoIcon-8,largoIcon);
if(nombre.equals("rget.gif"))
temp2.setIcon(new ImageIcon(getClass().getResource("/imagenes/fondo.png")));
}
@Override
public void mouseClicked(MouseEvent evt){
int largoIcon=temp2.getIcon().toString().length();
String nombre=temp2.getIcon().toString().substring(largoIcon-8,largoIcon);
if(nombre.equals("ondo.png") || nombre.equals("rget.gif")){
String delimitador="[?]";
String[] datos=temp2.getName().split(delimitador);
int posx=Integer.parseInt(datos[0]);
int posy=Integer.parseInt(datos[2]);
jugar(enemy, temp2, posx, posy);
}
}
});
this.posicionesMapa[fila][columna] = temp2;
this.add(temp2);
}
if(i==0){
temp=this.ubicarBarco(this.shipMap[fila][columna],temp);
this.posicionesMapa[fila][columna] = temp;
this.add(temp);
}
}
}
enemy.enemy.posicionesMapaHome=this.posicionesMapa;
this.acomodar();
} | 8 |
public ArrayList<Test>parse(String testFile){
try{
String path = getClass().getResource ("/" + testFile).getFile();
InputStream is = getClass().getResourceAsStream("/" + testFile);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
File tempfile = new File(testFile);
tempfile.createNewFile();
FileWriter fileWriter = new FileWriter(tempfile.getAbsoluteFile());
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while((line = bufferedReader.readLine())!=null){
bufferedWriter.write(line);
}
bufferedWriter.close();
Test test = new Test();
test.setName(testFile.replace(".xml", ""));
test.setPath(tempfile.getAbsolutePath());
if(System.getProperty("testFile").equalsIgnoreCase("api-test.xml"))
{
test.setModule("Mobile-Apps");
test.setFeature("Apps");
test.setType("MobileApp");
test.setSubfeature("apis");
}
else
{
test.setModule("Mobile-Apps");
test.setFeature("Apps");
test.setType("MobileApp");
test.setSubfeature(System.getProperty("device"));
}
testList.add(test);
} catch (Exception e){
e.printStackTrace();
}
return testList;
} | 3 |
public void createWeapon(Node node) {
Node n = node.getFirstChild();
while(n != null) {
if(n.getNodeType() == Node.ELEMENT_NODE) {
selectWeapon(n.getNodeName());
weapon.createFromXML(n.getChildNodes());
}
n = n.getNextSibling();
}
} | 2 |
private static void sobelFile(String filename, int numIterations,
boolean rle) {
System.out.println("Reading image file " + filename);
PixImage image = ImageUtils.readTIFFPix(filename);
PixImage blurred = image;
if (numIterations > 0) {
System.out.println("Blurring image file.");
blurred = image.boxBlur(numIterations);
String blurname = "blur_" + filename;
System.out.println("Writing blurred image file " + blurname);
TIFFEncoder.writeTIFF(blurred, blurname);
}
System.out.println("Performing Sobel edge detection on image file.");
PixImage sobeled = blurred.sobelEdges();
String edgename = "edge_" + filename;
System.out.println("Writing grayscale-edge image file " + edgename);
TIFFEncoder.writeTIFF(sobeled, edgename);
if (rle) {
String rlename = "rle_" + filename;
System.out.println("Writing run-length encoded grayscale-edge "
+ "image file " + rlename);
TIFFEncoder.writeTIFF(new RunLengthEncoding(sobeled), rlename);
}
if (numIterations > 0) {
System.out.println("Displaying input image, blurred image, and "
+ "grayscale-edge image.");
System.out.println("Close the image to quit.");
ImageUtils.displayTIFFs(new PixImage[] { image, blurred, sobeled });
} else {
System.out
.println("Displaying input image and grayscale-edge image.");
System.out.println("Close the image to quit.");
ImageUtils.displayTIFFs(new PixImage[] { image, sobeled });
}
} | 3 |
@Override
public void startTrade() {
if(presenter.isPlayersTurn()) {
getTradeOverlay().setStateMessage("set the trade you want to make");
getTradeOverlay().setResourceSelectionEnabled(true);
getTradeOverlay().setPlayerSelectionEnabled(false);
getTradeOverlay().setTradeEnabled(false);
Player player = presenter.getClientModel().getServerModel().getPlayerByID(presenter.getPlayerInfo().getID());
this.receiverIndex = -1;
this.availableBrick = player.getBrick();
this.availableOre = player.getOre();
this.availableSheep = player.getSheep();
this.availableWood = player.getWood();
this.availableWheat = player.getWheat();
boolean decrease = true;
getTradeOverlay().setResourceAmountChangeEnabled(ResourceType.BRICK, this.availableBrick > 0, decrease);
getTradeOverlay().setResourceAmountChangeEnabled(ResourceType.ORE, this.availableOre > 0, decrease);
getTradeOverlay().setResourceAmountChangeEnabled(ResourceType.SHEEP, this.availableSheep > 0, decrease);
getTradeOverlay().setResourceAmountChangeEnabled(ResourceType.WOOD, this.availableWood > 0, decrease);
getTradeOverlay().setResourceAmountChangeEnabled(ResourceType.WHEAT, this.availableWheat > 0, decrease);
this.offeredBrick = 0;
this.offeredOre = 0;
this.offeredSheep = 0;
this.offeredWood = 0;
this.offeredWheat = 0;
this.desiredBrick = 0;
this.desiredOre = 0;
this.desiredSheep = 0;
this.desiredWood = 0;
this.desiredWheat = 0;
this.brickState = 0;
this.oreState = 0;
this.sheepState = 0;
this.woodState = 0;
this.wheatState = 0;
send = false;
receive = false;
ArrayList<PlayerDescription> otherPlayersList = new ArrayList<PlayerDescription>();
//PlayerDescription[] gamePlayers = presenter.getPlayerInfoArray();
ArrayList<Player> gamePlayers = (ArrayList<Player>) presenter.getClientModel().getServerModel().getPlayers();
for (Player p : gamePlayers) {
if (p.getPlayerIndex() != presenter.getPlayerInfo().getIndex()) {
PlayerDescription temp = new PlayerDescription(p.getColor(), p.getPlayerID(), p.getName());
temp.setIndex(p.getPlayerIndex());
otherPlayersList.add(temp);
}
}
PlayerDescription[] otherPlayers = new PlayerDescription[3];
otherPlayers = otherPlayersList.toArray(otherPlayers);
getTradeOverlay().setPlayers(otherPlayers);
getTradeOverlay().showModal();
}
else {
getTradeOverlay().setTradeEnabled(false);
getTradeOverlay().setStateMessage("not your turn");
getTradeOverlay().setResourceSelectionEnabled(false);
getTradeOverlay().setPlayerSelectionEnabled(false);
getTradeOverlay().showModal();
}
} | 3 |
public void initFromXML( Element node )
{
NodeList nList = node.getElementsByTagName("replacespace") ;
Element elem = null ;
// a settings entry was found
if (nList != null)
{
if (nList.getLength() > 0)
{
elem = (Element) nList.item(0) ;
Boolean bool = new Boolean( elem.getAttribute("enable") ) ;
this.setReplaceWhitespace( bool.booleanValue() ) ;
this.setReplaceString( elem.getAttribute("string"));
}
}
nList = node.getElementsByTagName("emptykeys") ;
// a settings entry was found
if (nList != null)
{
if (nList.getLength() > 0)
{
elem = (Element) nList.item(0) ;
Boolean bool = new Boolean( elem.getAttribute("enable") ) ;
this.setSaveEmptyKeys( bool.booleanValue() ) ;
}
}
nList = node.getElementsByTagName("saveWYSIWYGmode") ;
// a settings entry was found
if (nList != null)
{
if (nList.getLength() > 0)
{
elem = (Element) nList.item(0) ;
Boolean bool = new Boolean( elem.getAttribute("enable") ) ;
this.setSaveWYSIWYGmode( bool.booleanValue() ) ;
}
}
} | 6 |
public static <T> Collection<T> shuffleCopyOfCollection(Collection<T> original)
{
ArrayList<T> shuffled = new ArrayList<> ();
ArrayList<T> originalCopy = new ArrayList<> (original);
while ( !originalCopy.isEmpty ()) {
int next = Randomiser.randIntBetween (0, originalCopy.size ());
shuffled.add (originalCopy.remove (next));
}
return shuffled;
} | 1 |
public void muestraVariable(String archivo) throws FileNotFoundException, IOException
{
File var = new File(archivo);
RandomAccessFile raf = new RandomAccessFile(archivo, "rw");
String temp = "";
while(raf.length() > raf.getFilePointer())
{
for (int i = 0; i < 15; i++)
{
temp += raf.readChar();
}
System.out.print(temp + "\t");
temp = "";
for (int i = 0; i < 15; i++)
{
temp += raf.readChar();
}
System.out.print(temp + "\t");
temp = "";
System.out.println(raf.readFloat());
}
raf.close();
} | 3 |
public synchronized boolean shot(Position position){
if ((position.getX() <= this.getXLength()) || (position.getY() <= this.getYLength())) return false;
if (field[position.getX()][position.getY()] != null) {
return field[position.getX()][position.getY()].fired();
}
return false;
} | 3 |
public void changePosition(Player player, ArrayList <Monster> monsters)
{
Rectangle newPosition = new Rectangle(
position.x + direction.x,
position.y + direction.y,
WIDTH, HEIGHT);
// If I'm hitting a player, tell him and then get set to die
if (newPosition.intersects(player.getBox()))
{
player.setHit(true);
quadrant = Map.OUT_OF_BOUNDS;
return;
}
// if I hit a monster, tell the monster, then die
for (int i=0; i<monsters.size(); i++)
{
if (newPosition.intersects(monsters.get(i).getBox()))
{
monsters.get(i).setHit(true);
if (isPlayerBullet)
monsters.get(i).setHitByPlayer(true);
quadrant = Map.OUT_OF_BOUNDS;
return;
}
}
// if I hit a wall, set my quadrant to die
for (int i=0; i<walls[quadrant].size(); i++)
{
if (newPosition.intersects(walls[quadrant].get(i)))
{
quadrant = Map.OUT_OF_BOUNDS;
return;
}
}
// finally: move and figure out where I am
position.x += direction.x;
position.y += direction.y;
determineQuadrant();
} | 6 |
public final MapleCharacter killBy(final MapleCharacter killer) {
int totalBaseExp = (int) (Math.min(Integer.MAX_VALUE, (getMobExp() * (killer.getLevel() <= 10 ? 1 : killer.getClient().getChannelServer().getExpRate()))));
AttackerEntry highest = null;
int highdamage = 0;
for (final AttackerEntry attackEntry : attackers) {
if (attackEntry.getDamage() > highdamage) {
highest = attackEntry;
highdamage = attackEntry.getDamage();
}
}
int baseExp;
for (final AttackerEntry attackEntry : attackers) {
baseExp = (int) Math.ceil(totalBaseExp * ((double) attackEntry.getDamage() / getMobMaxHp()));
attackEntry.killedMob(killer.getMap(), baseExp, attackEntry == highest);
}
final MapleCharacter controll = controller.get();
if (controll != null) { // this can/should only happen when a hidden gm attacks the monster
controll.getClient().getSession().write(MobPacket.stopControllingMonster(getObjectId()));
controll.stopControllingMonster(this);
}
spawnRevives(killer.getMap());
if (eventInstance != null) {
eventInstance.unregisterMonster(this);
eventInstance = null;
}
sponge = null;
if (listener != null) {
listener.monsterKilled();
}
final MapleCharacter ret = highestDamageChar;
highestDamageChar = null; // may not keep hard references to chars outside of PlayerStorage or MapleMap
return ret;
} | 7 |
private void initMovementAndBackground() {
maxXMovement = level.getWidth() * level.getTileSize() - GamePanel.WIDTH;
maxYMovement = level.getHeight() * level.getTileSize() - GamePanel.HEIGHT;
xMovement = player.getxPos() - (GamePanel.WIDTH / 2);
yMovement = player.getxPos() - (GamePanel.HEIGHT / 2);
if (xMovement < 0) {
xMovement = 0;
} else if (xMovement > maxXMovement) {
xMovement = maxXMovement;
}
if (yMovement < 0) {
yMovement = 0;
} else if (yMovement > maxYMovement) {
yMovement = maxYMovement;
}
try {
background = ImageIO.read(getClass().getResourceAsStream(chooseBackGround()));
clock = ImageIO.read(getClass().getResourceAsStream("/graphics/entity/Clock.png"));
} catch (IOException e) {
e.printStackTrace();
}
} | 5 |
public void count(Pet pet){
for(java.util.Map.Entry<Class<? extends Pet>, Integer> pair: this.entrySet())
if(pair.getKey().isInstance(pet))
put(pair.getKey(),pair.getValue() + 1);
} | 3 |
@Override
public ResultSet query(String query) {
Statement statement = null;
ResultSet result = null;
try {
connection = this.open();
statement = connection.createStatement();
switch (this.getStatement(query)) {
case SELECT:
result = statement.executeQuery(query);
return result;
default:
statement.executeQuery(query);
return result;
}
} catch (SQLException ex) {
if (ex.getMessage().toLowerCase().contains("locking") || ex.getMessage().toLowerCase().contains("locked")) {
return retry(query);
//this.writeError("",false);
} else if (ex.getMessage().toLowerCase().contains("query does not return resultset")) {
return null;
} else {
this.writeError("Error at SQL Query: " + ex.getMessage(), false);
}
}
return null;
} | 5 |
public String RGBtoHEX(int r, int g, int b) {
final int MIN_LENGTH = 2;
String red = Integer.toHexString(r);
//String.format("%02", red);
if (red.length() < MIN_LENGTH) {
red = "0" + red;
}
String green = Integer.toHexString(g);
//String.format("%02", green);
if (green.length() < MIN_LENGTH) {
green = "0" + green;
}
String blue = Integer.toHexString(b);
//String.format("%02", blue);
if (blue.length() < MIN_LENGTH) {
blue = "0" + blue;
}
String output = "#" + red + blue + green;
return output.toUpperCase();
} | 3 |
public void conecta() throws SerialPortTimeoutException{
String mac = red.obtenerDireccionMac();
String fecha = f.obtenerFecha();
SerialPort serialPort = new SerialPort("/dev/ttyACM0");
int temp = 1;
try {
System.out.println("Port opened: " + serialPort.openPort());
System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
do{
int[] buffer = serialPort.readIntArray(1);
for(int i=0;i<1;i++)
{
buffer[i] = buffer[i] - 48;
if(buffer[i] == 0 && temp!=0)
{
temp = buffer[i];
video.ReproducirVideo();
proceso.comenzarProceso();
System.out.println("dato para reproducir video: " + temp);
}
else if(buffer[i] == 1)
{
temp = buffer[i];
video.DetenerVideo();
System.out.println("dato para detener video: " + temp);
String tiempo = proceso.finalizaProceso();
System.out.println("Duracion: " + tiempo);
Raspberry dato = new Raspberry(mac, tiempo, fecha);
raspi.guardaRaspi(dato);
}
}
//}while(serialPort.isOpened());
}while(temp != 1);
//System.out.println("Port closed: " + serialPort.closePort());
}
catch (SerialPortException ex){
System.out.println(ex);
}
} | 6 |
public static void makeRandomDouble(Matrix matrix) throws MatrixIndexOutOfBoundsException {
int rows = matrix.getRowsCount();
int cols = matrix.getColsCount();
double temp = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// fill with random values
temp = roundNumber(Math.random() * maxNumber, accuracy).doubleValue();
matrix.setValue(i, j, temp);
}
}
} | 2 |
public TreeElement fillTree(String expression) throws WrongStructure, IncorrectSymbol, ImpossibleAction{
if (isComponent(expression.charAt(counter))) {
counterUp();
TreeElement currentOperation = new Operation(expression.charAt(counter));
counterUp();
if (isComponent(expression.charAt(counter))) {
currentOperation.setLeftSon(fillTree(expression));
counterUp();
} else {
if (isNumber(expression.charAt(counter))) {
int number = Integer.parseInt(String.valueOf(expression.charAt(counter)));
TreeElement currentNum = new Digit(number);
currentOperation.setLeftSon(currentNum);
counterUp();
} else {
if (expression.charAt(counter) == ')') {
counterUp();
} else {
throw new IncorrectSymbol("Wrong symbol!");
}
}
}
if (isComponent(expression.charAt(counter))) {
currentOperation.setRightSon(fillTree(expression));
counterUp();
} else {
if (isNumber(expression.charAt(counter))) {
int number = Integer.parseInt(String.valueOf(expression.charAt(counter)));
TreeElement currentNum = new Digit(number);
currentOperation.setRightSon(currentNum);
counterUp();
} else {
if (expression.charAt(counter) == ')') {
counterUp();
} else {
throw new IncorrectSymbol("Wrong symbol!");
}
}
}
return currentOperation;
}
throw new WrongStructure("Wrong input structure!");
} | 7 |
public static String deviceIdToMac(String deviceId) {
if (deviceId.length() != 20) {
return "";
}
String macStr = deviceId.substring(8, 20);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 12; i++) {
sb.append(macStr.charAt(i));
if (i % 2 == 1) {
sb.append(":");
}
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
} | 3 |
public static int sample(double[] probs, int T) {
// roulette sampling
double []pt = new double[T];
//System.out.print(p[0]);
pt[0] = probs[0];
for (int i = 1; i < T; i++) {
pt[i] = probs[i] + pt[i-1];
// System.out.print(" " + pt[i]);
}
// System.out.println();
// scaled sample because of unnormalized p[]
double rouletter = (double) (Math.random() * pt[T - 1]);
short sample = 0;
for (sample = 0; sample < T; sample++) {
if (pt[sample] > rouletter)
break;
}
// System.out.println(rouletter + "\t" + sample);
if(sample < 0 | sample >= T) {
ComUtil.print(probs, "\t", "\n");
System.out.println("Sampling error!");
System.exit(0);
}
return sample;
} | 4 |
private void anchorNode(Node node) {
if (this.anchors.containsKey(node)) {
String anchor = this.anchors.get(node);
if (null == anchor) {
anchor = generateAnchor();
this.anchors.put(node, anchor);
}
} else {
this.anchors.put(node, null);
switch (node.getNodeId()) {
case sequence:
SequenceNode seqNode = (SequenceNode) node;
List<Node> list = seqNode.getValue();
for (Node item : list) {
anchorNode(item);
}
break;
case mapping:
MappingNode mnode = (MappingNode) node;
List<NodeTuple> map = mnode.getValue();
for (NodeTuple object : map) {
Node key = object.getKeyNode();
Node value = object.getValueNode();
anchorNode(key);
anchorNode(value);
}
break;
}
}
} | 6 |
public void command(CommandSender sender, Player player, String[] cmd){
//
// GETS THE STRING TO REFER TO TO GET THE COMMAND
//
if(cmd[0].equalsIgnoreCase("add")){
// CHECKS IF THE PLAYER IS ALREADY IN THE PROCESS OF ADDING A COMMAND
if(list.containsKey(player)){
sender.sendMessage("§a[§bWarCraft§a] §fYou are already in the process of adding a command.");
sender.sendMessage("§a - §fType '/sc cancel' to cancel the action.");
return;
}
// REBUILDS THE STRING INT STRING FORM AND STORES IN HASHMAP TO REFER TO LATER
StringBuilder sb = new StringBuilder();
for(int i = 1 ; i < cmd.length ; i++){
if(cmd.length-1 == i){
sb.append(cmd[i]);}
else{
sb.append(cmd[i]).append(" ");}
}
list.put(sender,sb.toString()
);
sender.sendMessage("§a[§bWarCraft§a] §fNow enter the command: /sc command <arg> <arg> <arg> etc.");
return;
}
//
// GETS THE COMMAND TO DEFER TO
//
if (cmd[0].equalsIgnoreCase("command")){
// CHECKS TO MAKE SURE THE PLAYER HAS ALREADY STARTED ADDING A COMMAND
if(!list.containsKey(player)){
sender.sendMessage("§a[§bWarCraft§a] §fYou have not properly started the process of adding a command.");
sender.sendMessage("§a - §fType '/sc add [string]' to add a String to reference a command.");
return;
}
// REBUILDS THE COMMAND TO STRING FORM FOR WRITING TO THE FILE
StringBuilder sb = new StringBuilder();
for(int i = 1 ; i < cmd.length ; i++){
if(cmd.length-1 == i){
sb.append(cmd[i]);}
else{
sb.append(cmd[i]).append(" ");}
}
Write(list.get(sender),sb.toString(),player);// SENDS ARGUMENTS TO WRITE METHOD FOR WRITING TO FILE
list.remove(sender);
return;
}
} | 8 |
protected final int shiftKeys(int pos) {
// Shift entries with the same hash.
int last, slot;
for (;;) {
pos = ((last = pos) + 1) & mask;
while (used[pos]) {
slot = (it.unimi.dsi.fastutil.HashCommon
.murmurHash3((key[pos]))) & mask;
if (last <= pos ? last >= slot || slot > pos : last >= slot
&& slot > pos)
break;
pos = (pos + 1) & mask;
}
if (!used[pos])
break;
key[last] = key[pos];
copyValue(last, pos);
}
used[last] = false;
return last;
} | 7 |
private String cipher_digraph(String pl,HashMap<Character,Pair<Integer> > h1, HashMap<Character,Pair<Integer>> h2, HashMap<Character,Pair<Integer>> h3)
{
assert(pl.length()==2);
StringBuilder sb=new StringBuilder();
char c1=pl.charAt(0);
char c2=pl.charAt(1);
if(c1=='J')
{
c1='I';
}
if(c2=='J')
{
c2='I';
}
Pair<Integer> p1=h1.get(Character.valueOf(c1));
Pair<Integer> p2=h2.get(Character.valueOf(c2));
Random r=new Random();
int c1_row=p1.get_first();
int c1_col=p1.get_second();
int c2_row=p2.get_first();
int c2_col=p2.get_second();
int rand=r.nextInt(4)+1;
int rand2=r.nextInt(4)+1;
int ct1_row=(c1_row+rand>4)?c1_row+rand-4:c1_row+rand;
int ct2_col=(c2_col+rand2>4)?c2_col+rand2-4:c2_col+rand2;
sb.append(square1[ct1_row][c1_col]);
sb.append(square3[c1_row][c2_col]);
sb.append(square2[c2_row][ct2_col]);
return sb.toString();
/* if(p1.get_first()==p2.get_first())
{
sb.append(c2);
sb.append(c1);
return sb.toString();
}
else
{
sb.append(square2[p1.get_first()][p2.get_second()]);
sb.append(square1[p2.get_first()][p1.get_second()]);
return sb.toString();
}*/
} | 4 |
protected synchronized void processEvent(Sim_event ev)
{
switch ( ev.get_tag() )
{
case GridSimTags.PKT_FORWARD:
case GridSimTags.JUNK_PKT:
processNetPacket(ev, ev.get_tag());
break;
case GridSimTags.ROUTER_AD:
receiveAd(ev);
break;
case GridSimTags.INSIGNIFICANT:
processInternalEvent(ev);
break;
default:
System.out.println(super.get_name() + ".body(): Unable to " +
"handle request from GridSimTags " +
"with constant number " + ev.get_tag() );
break;
}
} | 4 |
protected boolean isIOLogic(PrimitiveType type) {
return ((type == PrimitiveType.ILOGIC)
|| (type == PrimitiveType.ILOGIC2)
|| (type == PrimitiveType.ILOGICE1)
|| (type == PrimitiveType.ILOGICE2)
|| (type == PrimitiveType.ILOGICE3)
|| (type == PrimitiveType.OLOGIC)
|| (type == PrimitiveType.OLOGIC2)
|| (type == PrimitiveType.OLOGICE1)
|| (type == PrimitiveType.OLOGICE2) || (type == PrimitiveType.OLOGICE3));
} | 9 |
@Override
protected EntityManager getEntityManager() {
return em;
} | 0 |
public void incrementInvalidRxCount() {
invalidRxPackets++;
setChanged();
notifyObservers();
} | 0 |
private void sarsa(int reward, Weights weights, double x_i[], double[] x_ip1)
{
// Set some local variables.
double[] w = weights.getWeights();
double wx = 0.0f;
double sig = 0.0f;
// Compute y_i.
double wxp1 = 0.0f;
for (int j = 0; j < FeatureExplorer.getNumFeatures(); j++) wxp1 += w[j] * x_ip1[j];
double sigp1 = sigmoid(wxp1);
double y_i = reward + gamma * sigp1;
// Print out some debug if needed.
if (PRINT_DEBUG)
{
System.out.println("SARSA Weights:");
weights.printWeights();
}
// For each feature, compute the dot product of w and x.
for (int j = 0; j < FeatureExplorer.getNumFeatures(); j++) wx += w[j] * x_i[j];
if (PRINT_DEBUG)
System.out.println("\twx: " + wx);
// Compute the sigmoid of this.
sig = sigmoid(wx);
if (PRINT_DEBUG)
System.out.println("\tsigmoid(wx): " + sig);
// Weight vector update.
for (int j = 0; j < FeatureExplorer.getNumFeatures(); j++)
w[j] = w[j] + eta * ((y_i - sig) * (sig) * (1 - sig) * x_i[j]);
// Set the new weights.
weights.setWeights(w);
if (PRINT_DEBUG)
{
System.out.println("SARSA New Weights:");
weights.printWeights();
}
} | 7 |
public P2PManager() {
addListener(new ActionListener() {
@Override
protected TaskAction getListenAction() {
return TaskAction.FETCHUSER_PROCESS;
}
@Override
protected void onAction(HashMap<String, String> params) {
if(params != null) {
Set<String> keys = params.keySet();
ClientManager clientManager = ClientManager.getInstance();
Collection<InetAddress> removals = clientManager.getAddressList();
for(String key : keys) {
try {
InetAddress address = InetAddress.getByName(key);
if(clientManager.contains(address)) {
removals.remove(address);
} else {
clientManager.add(address, params.get(key));
P2PManager.this.publishNewRemoteUserTask(params.get(key));
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
for(InetAddress address : removals) {
P2PManager.this.publishLeftRemoteUserTask(clientManager.getUsernameByAddress(address));
clientManager.remove(address);
}
}
}
});
addListener(new ActionListener() {
@Override
protected TaskAction getListenAction() {
return TaskAction.CUSER_NEWMESSAGE;
}
@Override
protected void onAction(HashMap<String, String> params) {
if(params != null) {
if(params.containsKey("username") && params.containsKey("message")) {
String message = String.format("%s: %s\n", params.get("username"), params.get("message"));
ClientManager.getInstance().broadcast(message);
}
}
}
});
addListener(new ActionListener() {
@Override
protected TaskAction getListenAction() {
return TaskAction.QUIT;
}
@Override
protected void onAction(HashMap<String, String> params) {
// stop udp server
if(server != null) {
server.interrupt();
server.close();
}
// stop this manager
interrupt();
}
});
} | 9 |
private void evalCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_evalCancelButtonActionPerformed
if (isRunning == true) {
try {
interactor.cancelLastCommand();
} catch (Exception e) {
}
setGUIToIdleMode();
} else {
setGUIToRunningMode();
new Thread() {
public void run() {
try {
final List result = interactor.submitSubL(inputField.getText());
displayResult(result);
} catch (Exception ex) {
Logger.getLogger(SubLInteractorPanel.class.getName()).log(Level.SEVERE, null, ex);
displayException(ex);
}
}
}.start();
}
}//GEN-LAST:event_evalCancelButtonActionPerformed | 3 |
public String getValue(int place) {
ListElement current = head;
if (place <= count) {
for (int i = 1; i < place; i++) {
current = current.next();
}
return current.getValue();
} else {
return "error";
}
} | 2 |
@Test
public void executeScenario() throws UnknownHostException {
logger_.info("[Repair Scenario 5 Start] Peer on \"1\" repairs subtree on \"0\"");
Injector injector = ScenarioSharedState.getInjector();
localPeerContextInit(injector);
LocalPeerContext context = injector.getInstance(LocalPeerContext.class);
Host[] zeroLevel = context.getLocalRT().getLevelArray(0);
Assert.assertTrue("Something went wrong during test initialization. " +
"Conjugate subtree is overpopulated.", zeroLevel.length == 4);
logger_.info("=====================================================================================");
Host failed = null;
for (Host host : zeroLevel) {
if (host.getHostPath().toString().compareTo("0000") == 0) {
failed = host;
}
}
logger_.info("Repairing host {}:{} [path: {}]",
new Object[]{
failed.getAddress(),
failed.getPort(),
failed.getHostPath()});
RepairService repairService = injector.getInstance(RepairService.class);
repairService.fixNode(failed);
logger_.info("Localhost instance: {}:{} [path: {}]",
new Object[]{
context.getLocalRT().getLocalhost().getAddress(),
context.getLocalRT().getLocalhost().getPort(),
context.getLocalRT().getLocalhost().getHostPath()});
logger_.info("[Repair Scenario 5 End]");
Assert.assertTrue(context.getLocalRT().getLocalhost().getAddress().getHostAddress().compareTo(localIP_) == 0);
Assert.assertTrue(context.getLocalRT().getLocalhost().getPort() == localPort_);
Assert.assertTrue(context.getLocalRT().getLocalhost().getHostPath().toString().compareTo(expectedFinalPath_) == 0);
Assert.assertTrue(context.getLocalRT().levelNumber() == expectedLevelNumber_);
} | 2 |
private void goalieBehaviour(){
final int REACTION_DISTANCE = 20;
final int HOME_DISTANCE = 5;
//the first state has the goalie wait in goal but constantly look for the ball
if(playerState == 0){
turnTowardBall();
//the goalie state changes when the ball moves to a certain distance from the goalie
if(canSeeBall && distanceBall < REACTION_DISTANCE) playerState = 1;
}
//in this state the goalie is actively running towards the ball attempting to intercept it and
//kick it away if possible
if(playerState == 1){
canSeeBallAction();
//the goalie state changes when the ball leaves a certain range
if(distanceOwnGoal >= REACTION_DISTANCE) playerState = 2;
}
//in this state the goalie moves back to the goal
if(playerState == 2){
//the goalie needs to be able to see his/her own goal to move back to it
if(!canSeeOwnGoal){
turnTowardOwnGoal();
}else{
//the goalie moves back towards the goal
canSeeOwnGoalAction();
//the goalie state changes back to the first state of looking for the ball and
//watching it when it returns to the goal
if(distanceOwnGoal < HOME_DISTANCE) playerState = 0;
}
}
} | 8 |
public static void initconfigration()
{
if(driver == null){
if(Constants.browser.equals("firefox")){
driver = new FirefoxDriver();
}
else if(Constants.browser.equals("ie")){
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
driver = new InternetExplorerDriver();
}else if(Constants.browser.equals("chrome")){
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
}
driver.get(Constants.testsite);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(25L, TimeUnit.SECONDS);
topmenu = PageFactory.initElements(driver, TopNavigation.class);
mail = PageFactory.initElements(driver, monitoringMail.class);
Report = PageFactory.initElements(driver, HTMLReport.class);
}
} | 4 |
public void run() {
if (player.getLocation().getBlockX() != pX || player.getLocation().getBlockY() != pY || player.getLocation().getBlockZ() != pZ) {
plugin.sendMessage(player,GRAY+F("recallingToLifestone", GREEN + Config.recallDelay + GRAY));
//plugin.sendMessage(player, GRAY+L("movedTooFarAttunementFailed"));
return;
}
Attunement attunement = Attunements.get(player);
player.teleport(attunement.loc);
plugin.sendMessage(player, GRAY+L("recalledToLifestone"));
plugin.playerProtections.put(player.getName(), Lifestones.getUnixTime() + Config.protectPlayerAfterRecallDuration);
//protectPlayerAfterRecallDuration
} | 3 |
public static void skip10Lines(){
int count=0;
if(count<10)
skip10Lines();
} | 1 |
private Set<Card> threeFoursWithFlush() {
return convertToCardSet("3D,6D,2D,4S,4D,4C,9D");
} | 0 |
public static LookManager getInstance(){
if(instance == null){
instance = new LookManager();
}
return instance;
} | 1 |
public Set<Map.Entry<Float,Double>> entrySet() {
return new AbstractSet<Map.Entry<Float,Double>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TFloatDoubleMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TFloatDoubleMapDecorator.this.containsKey(k)
&& TFloatDoubleMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Float,Double>> iterator() {
return new Iterator<Map.Entry<Float,Double>>() {
private final TFloatDoubleIterator it = _map.iterator();
public Map.Entry<Float,Double> next() {
it.advance();
float ik = it.key();
final Float key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
double iv = it.value();
final Double v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
return new Map.Entry<Float,Double>() {
private Double val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Float getKey() {
return key;
}
public Double getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Double setValue( Double value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Float,Double> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Float key = ( ( Map.Entry<Float,Double> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Float, Double>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TFloatDoubleMapDecorator.this.clear();
}
};
} | 8 |
public String build(Request request, HttpClient client) throws Exception {
String query = DDG_API_URL + "q=" + this.escape(request.getQuery());
if (request.isStandard()) {
query += ARG_STD;
} else {
query +=(request.isNoHtml()) ? AMP + ARG_NO_HTML : "";
//query += AMP + ((request.isNoRedirect()) ? ARG_NO_REDIRECT : "");
query += (request.isFormatJson()) ? AMP + ARG_FORMAT_JSON : AMP + ARG_FORMAT_XML;
query += (request.isPretty()) ? AMP + ARG_PRETTY : "";
query += (request.isSkipDisambig()) ? AMP + ARG_SKIP_DISAMBIG : "";
query += (request.isSafeOff()) ? AMP + ARG_SAFEOFF : "";
}
return query;
} | 6 |
@Override
public void validate() {
if (platform == null) {
addActionError("Please Select Platorm");
}
if (location == null) {
addActionError("Please Select Location");
}
if (iphone.equals("Please select")) {
addActionError("Please Select Os");
}
if (gender == null) {
addActionError("Please Select Gender");
}
if (age == null) {
addActionError("Please Select Age");
}
} | 5 |
public static MapLoader getInstance(){
if(instance == null){
instance = new MapLoader();
}
return instance;
} | 1 |
public static void main(String[] args)
{
int[] dims = new int[]{4,40,20};
Object array = Array.newInstance(Integer.TYPE, dims);
Class<?> classType = array.getClass().getComponentType();
System.out.println(classType);
Object arrayObj = Array.get(array, 2);
Class<?> classType1 = arrayObj.getClass().getComponentType();
System.out.println(classType1);
arrayObj = Array.get(arrayObj, 5);
Array.set(arrayObj, 12, 90);
int[] [] [] arrayCast = (int[] [] []) array;
System.out.println(arrayCast[2][5][12]);
System.out.println("-----------------------");
/**
*
* Integer.TYPE返回的是int,而Integer.Class返回的是Integer类所 对应的Class对象
* int
* class java.lang.Integer
*/
System.out.println(Integer.TYPE);
System.out.println(Integer.class);
} | 2 |
public Document braceMatch(String pennTree)
throws ParserConfigurationException {
ArrayList<Integer> contentTree = new ArrayList<Integer>();
ArrayList<Element> nodes = new ArrayList<Element>();
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document d = builder.newDocument();
Element root = d.createElement("root");
d.appendChild(root);
Stack<String> s_content = new Stack<String>();
String[] split = pennTree.split("\\(");
int depth = 0;
Element node;
for (int i = 0; i < split.length; i++) {
char[] tem = split[i].trim().toCharArray();
if (tem.length == 0)
continue;
s_content.push(split[i]);
depth++;
String[] term = s_content.pop().split(" ");
String tag = term[0];
String content = "";
if (term.length > 1){
content = term[1];
content = content.substring(0, content.indexOf(')')).toLowerCase();
}
node = d.createElement("tag");
node.setAttribute("content", content);
node.setAttribute("nodeName", tag);
nodes.add(node);
contentTree.add(depth);
for (int k = 1; k <= tem.length; k++) {
if (tem[tem.length - k] == ')')
depth--;
else
break;
}
}
for (int i = nodes.size() - 1; i >= 0; i--) {
int curDepth;
int j = i - 1;
Element n = nodes.get(i);
curDepth = contentTree.get(i);
while (j >= 0) {
int dep = contentTree.get(j);
if (dep < curDepth) {
nodes.get(j).appendChild(n);
break;
}
j--;
}
if (1 == curDepth) {
root.appendChild(n);
continue;
}
}
return d;
} | 9 |
public static Double transmittance(Double transmittance, Double molarAbsorbtivity, Double cuvetteWidth, Double concentration)
{
boolean[] nulls = new boolean[4];
nulls[0] = (transmittance == null);
nulls[1] = (molarAbsorbtivity == null);
nulls[2] = (cuvetteWidth == null);
nulls[3] = (concentration == null);
int nullCount = 0;
for(int k = 0; k < nulls.length; k++)
{
if(nulls[k])
nullCount++;
}
if(nullCount != 1)
return null;
double result = 0;
if(nulls[0])
{
// transmittance is unknown
result = 1/(pow(10,(molarAbsorbtivity*cuvetteWidth*concentration)));
}
else if(nulls[1])
{
// molarAbsorbtivity is unknown
result = log10(1/transmittance)/(cuvetteWidth*concentration);
}
else if(nulls[2])
{
// cuvetteWidth is unknown
result = log10(1/transmittance)/(molarAbsorbtivity*concentration);
}
else if(nulls[3])
{
// concentration is unknown
result = log10(1/transmittance)/(molarAbsorbtivity*cuvetteWidth);
}
return result;
} | 7 |
public static UUID mint(int ver, String node, String ns)
throws UUIDException, Exception {
/* Create a new UUID based on provided data. */
switch (ver) {
case 0:
case 1:
throw new UUIDException("Unimplemented");
// return new UUID(mintTime(node));
case 2:
// Version 2 is not supported
throw new UUIDException("Version 2 is unsupported.");
case 3:
return new UUID(mintName(MD5, node, ns));
case 4:
throw new UUIDException("Unimplemented");
// UUID(mintRand());
case 5:
return new UUID(mintName(SHA1, node, ns));
default:
throw new UUIDException(
"Selected version is invalid or unsupported.");
}
} | 6 |
public static boolean addStation(ObjectOutputStream toServer, ObjectInputStream fromServer, Scanner scanner) throws IOException, ClassNotFoundException {
log.debug("Start \"addStation\" method");
List<String> listAllStation = PassengerHomePageHelper.listStations(toServer, fromServer);
String stationName;
do {
System.out.println("Station name must be unique!");
System.out.println("Input station name:");
stationName = scanner.next().toLowerCase();
} while (listAllStation.contains(stationName));
AddStationRequestInfo req = new AddStationRequestInfo(stationName);
log.debug("Send AddStationRequestInfo to server");
toServer.writeObject(req);
Object o = fromServer.readObject();
if (o instanceof RespondInfo) {
if (((RespondInfo) o).getStatus() == RespondInfo.SERVER_ERROR_STATUS) {
System.out.println("Server error");
log.debug("Server error");
return false;
} else if (o instanceof AddStationRespondInfo) {
AddStationRespondInfo respond = (AddStationRespondInfo) o;
log.debug("Received AddStationRespondInfo from server");
if (respond.getStatus() == AddStationRespondInfo.OK_STATUS) {
System.out.println("Station added");
log.debug("Station added");
return true;
} else {
System.out.println("Server error");
log.debug("Server error");
return false;
}
}
}
log.error("Unknown object type");
return false;
} | 5 |
protected void parseEndTag() {
// 1. read name (skipping the </ part)
int i;
for (i = position + 2; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isSpaceChar(c) || c == '>') {
break;
}
}
String tagName = text.substring(position + 2, i).toLowerCase();
if (ignoreUntil != null && ignoreUntil.equals(tagName)) {
ignoreUntil = null;
}
if (ignoreUntil == null) {
closeTag(tagName); // advance to end '>'
}
while (i < text.length() && text.charAt(i) != '>') {
i++;
}
position = i;
} | 8 |
void creatingGui() {
m_window = new JFrame("Othello");
m_window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
m_window.setLayout(new GridBagLayout());
m_window.getContentPane().setBackground(Color.GREEN);
GridBagConstraints c = new GridBagConstraints();
m_window.setIconImage(new ImageIcon(this.getClass().getResource(
"Othello.jpeg")).getImage());
if (m_playerOne.getColour().equals("Black")) {
setPlayerLabel(m_playerOne.getName(), "Black",
m_playerTwo.getName(), "White");
} else {
setPlayerLabel(m_playerOne.getName(), "White",
m_playerTwo.getName(), "Black");
}
m_panel.add(getTimerLabel());
m_panel.add(getPlayerLabel());
setPlayerScore(getGame());
m_panel.add(getPlayerScore());
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 8;
c.anchor = GridBagConstraints.NORTH;
m_panel.setBackground(Color.GREEN);
m_window.add(m_panel, c);
GUIHandler handler = new GUIHandler();
m_gridButtons = new JLabel[TOTALWIDTH][TOTALHEIGHT];
for (int y = 0; y < TOTALWIDTH; y++) {
for (int x = 0; x < TOTALHEIGHT; x++) {
m_gridButtons[x][y] = new JLabel("");
m_gridButtons[x][y].setIcon(m_backgroundTile);
m_gridButtons[x][y].addMouseListener(handler);
m_gridButtons[x][y].setPreferredSize(new Dimension(BOARDWIDTH,
BOARDHEIGHT));
c.gridx = x;
c.gridy = y + 1;
c.gridwidth = 1;
m_window.add(m_gridButtons[x][y], c); // adds button to grid
}
}
m_gridButtons[COLUMN_FOUR][COLUMN_FOUR].setIcon(m_whitePiece);
m_gridButtons[COLUMN_FIVE][COLUMN_FIVE].setIcon(m_whitePiece);
m_gridButtons[COLUMN_FOUR][COLUMN_FIVE].setIcon(m_blackPiece);
m_gridButtons[COLUMN_FIVE][COLUMN_FOUR].setIcon(m_blackPiece);
m_window.setJMenuBar(creatingMenu());
m_window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to exit the program?",
"Exit Program Message Box", JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
m_window.dispose();
}
}
});
m_window.getRootPane().setDefaultButton(m_defaultButton);
m_window.pack();
m_window.setVisible(true);
if (!m_playerOne.getPlayerType().equals("Human")) {
int x, y;
if (m_playerOne.getPlayerType().equals("ComputerEasy")) {
Point p = ((OthelloEasyComputerPlayer) m_playerOne)
.makeAIMove(m_board);
x = (int) p.getX();
y = (int) p.getY();
} else {
Point p = ((OthelloHardComputerPlayer) m_playerOne)
.makeAIMove(m_board);
x = (int) p.getX();
y = (int) p.getY();
}
performMove(x, y);
}
} | 6 |
public SmashServer(SmashGame gamer, Map map){
this.game=gamer;
game.init(map, this);
instance = this;
try {
setServer(new ServerSocket(328));
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new Runnable(){
@Override
public void run() {
while(getMAX_PLAYERS()==10)
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
while(players < getMAX_PLAYERS()){
try {
Socket socket = server.accept();
socket.setKeepAlive(true);
clients[players-1] = new SmashClientHost(socket, instance);
sendMap(game.getMap().getPath(), players-1);
players++;
transfer(PLAYER_NUM+" "+players+" "+MAX_PLAYERS);
} catch (IOException e) {
break;
}
if(getMAX_PLAYERS() == 1)
break;
}
if(getMAX_PLAYERS() == 1)
start();
}
},"Smash It Server").start();
} | 7 |
@XmlElementDecl(namespace = "http://www.w3.org/2000/09/xmldsig#", name = "SignatureProperty")
public JAXBElement<SignaturePropertyType> createSignatureProperty(SignaturePropertyType value) {
return new JAXBElement<SignaturePropertyType>(_SignatureProperty_QNAME, SignaturePropertyType.class, null, value);
} | 0 |
private static String DataToStiring(classifiedData Data){
String out = "";
//Add Cedd data
int i = 0;
for(i = 0; i < Data.getCEDDData().length; i++){
out = out + Data.getCEDDData()[i] + ",";
}
// System.out.println("CEDD data added for image " + Data.getImgName() + " is: " + i);
//Add FCTH data
int j = 0;
for(j = 0; j < Data.getFCTHData().length; j++){
out = out + Data.getFCTHData()[j] + ",";
}
// System.out.println("FCTH data added for image " + Data.getImgName() + " is: " + j);
out = out + Data.getClassification();
return out;
} | 2 |
private String showToUser(ArrayList<TaskData> taskToShow) {
String text = "";
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
SimpleDateFormat f = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
int i = 1;
for (TaskData t : taskToShow) {
text += i + ": ";
text += t.getContent();
if (t.getPriority() != null)
text += "\n " + t.getPriority() + " priority ";
if (t.getCategory() != null)
text += "\n #" + t.getCategory() + " ";
if (t.getStartDateTime() != null) {
Date d;
try {
d = formater.parse(t.getStartDateTime() + "");
String s = f.format(d);
text += "\n From: " + s;
} catch (java.text.ParseException e) {
}
}
if (t.getEndDateTime() != null) {
Date d;
try {
d = formater.parse(t.getEndDateTime() + "");
String s = f.format(d);
text += "\n To : " + s;
} catch (java.text.ParseException e) {
}
}
text += "\n";
i++;
}
return text;
} | 7 |
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.