text stringlengths 14 410k | label int32 0 9 |
|---|---|
private void 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 = "-:dcl";
LongOpt[] lopts =
{
new LongOpt("domain", LongOpt.NO_ARGUMENT, null, 'd'),
new LongOpt("count", LongOpt.NO_ARGUMENT, null, 'c'),
new LongOpt("list", LongOpt.NO_ARGUMENT, null, 'l'),
};
Getopt getopt = new Getopt(null, args, sopts, lopts);
getopt.setOpterr(false);
int code;
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]);
// non-option arguments
case 1:
throw new CommandException("Unused argument: " + getopt.getOptarg());
case 'd':
mode = DEFAULT_DOMAIN;
break;
case 'c':
mode = MBEAN_COUNT;
break;
case 'l':
mode = LIST_NAMES;
break;
}
}
} | 8 |
public void testGuid() {
System.out.println("\n*** testGuid ***");
CycObjectFactory.resetGuidCache();
assertEquals(0, CycObjectFactory.getGuidCacheSize());
String guidString = "bd58c19d-9c29-11b1-9dad-c379636f7270";
Guid guid = CycObjectFactory.makeGuid(guidString);
assertEquals(1, CycObjectFactory.getGuidCacheSize());
assertEquals(guidString, guid.toString());
Guid guid2 = CycObjectFactory.getGuidCache(guidString);
assertEquals(guid, guid2);
Guid guid3 = CycObjectFactory.makeGuid(guidString);
assertEquals(guid, guid3);
assertEquals(1, CycObjectFactory.getGuidCacheSize());
// toXML, toXMLString, unmarshall
XMLStringWriter xmlStringWriter = new XMLStringWriter();
try {
guid.toXML(xmlStringWriter, 0, false);
assertEquals("<guid>bd58c19d-9c29-11b1-9dad-c379636f7270</guid>\n", xmlStringWriter.toString());
assertEquals("<guid>bd58c19d-9c29-11b1-9dad-c379636f7270</guid>\n", guid.toXMLString());
String guidXMLString = guid.toXMLString();
CycObjectFactory.resetGuidCache();
Object object = CycObjectFactory.unmarshall(guidXMLString);
assertTrue(object instanceof Guid);
assertEquals(guid, (Guid) object);
assertTrue(CycObjectFactory.unmarshall(guidXMLString)
== CycObjectFactory.unmarshall(guidXMLString));
} catch (Exception e) {
failWithException(e);
}
System.out.println("*** testGuid OK ***");
} | 1 |
private void getAuthTokenTest(String url, String usr, String pwd)
{
try
{
IAquariusPublishService client = AqWsFactory.newAqPubClient(url);
Assert.assertTrue(client!=null);
String token = client.getAuthToken(TestContext.User, TestContext.Pwd);
Assert.assertTrue(token!=null && token.length()>0);
AqWsFactory.close(client);
}
catch(Exception ex)
{
fail(ex.toString());
}
} | 2 |
public void paint(Graphics2D g2, Node item, Justification justification, Rectangle2D bounds) {
final Font oldFont = g2.getFont();
if (background != null) {
g2.setPaint(background);
g2.fill(bounds);
}
if (borderPaint != null && borderStroke != null) {
g2.setPaint(borderPaint);
g2.setStroke(borderStroke);
g2.draw(bounds);
}
g2.setPaint(foreground);
g2.setFont(taxonLabelFont);
final String label = getLabel(item);
if (label != null) {
Rectangle2D rect = g2.getFontMetrics().getStringBounds(label, g2);
float xOffset = 0;
float y = yOffset + (float) bounds.getY();
switch (justification) {
case CENTER:
//xOffset = (float)(-rect.getWidth()/2.0);
//y = yOffset + (float) rect.getY();
// y = (float)bounds.getHeight()/2;
//xOffset = (float) (bounds.getX() + (bounds.getWidth() - rect.getWidth()) / 2.0);
break;
case FLUSH:
case LEFT:
xOffset = (float) bounds.getX();
break;
case RIGHT:
xOffset = (float) (bounds.getX() + bounds.getWidth() - rect.getWidth());
break;
default:
throw new IllegalArgumentException("Unrecognized alignment enum option");
}
g2.drawString(label, xOffset, y);
//g2.draw(bounds);
}
g2.setFont(oldFont);
} | 8 |
private void setSchedule(int userID)
{
String[] startTimes = new String[7];
String[] endTimes = new String[7];
String startDate = "";
String endDate = "";
int k = 0;
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.connectToDB();
String sql = "SELECT * FROM `TASchedule` WHERE AssistantID = '" + userID + "' order by DayOfWeek asc";
ResultSet rs = db.getResults(conn, sql);
try {
while(rs.next())
{
startTimes[k] = rs.getString("StartTime");
endTimes[k] = rs.getString("EndTime");
startDate = rs.getString("StartDate");
endDate = rs.getString("EndDate");
k++;
}
} catch (SQLException ex) {
Logger.getLogger(ScheduleSelection.class.getName()).log(Level.SEVERE, null, ex);
}
scheduleSelectStartDate.setText(startDate);
scheduleSelectEndDate.setText(endDate);
for(int j = 0; j < 1; j++)
{
for (int i = 1; i < 8; i++)
{
timeTable.setValueAt(startTimes[i-1], j, i);
}
}
for(int j = 1; j < 2; j++)
{
for (int i = 1; i < 8; i++)
{
timeTable.setValueAt(endTimes[i-1], j, i);
}
}
} | 6 |
@Test public void getTopicsRatios() throws Exception {
this.portfolio.openCorpus("MISS");
this.portfolio.openViewpoint("446d798e240d4dee5a552b902ae56c8d");
for (Portfolio.Viewpoint.Topic t : this.portfolio.getTopics()) {
assertTrue(t.getRatio(0)<1);
assertTrue(t.getRatio(1)==0);
}
this.portfolio.toggleTopic(
"446d798e240d4dee5a552b902ae56c8d",
"70551d9a197a874cb76372c789be629e"
);
for (Portfolio.Viewpoint.Topic t : this.portfolio.getTopics()) {
if (
"446d798e240d4dee5a552b902ae56c8d"
.equals(t.getViewpoint().getID())
&& "70551d9a197a874cb76372c789be629e"
.equals(t.getID())
) {
assertTrue(t.getRatio(0)==1);
assertTrue(t.getRatio(1)==1);
}
}
this.portfolio.closeViewpoint("446d798e240d4dee5a552b902ae56c8d");
assertTrue(this.portfolio.getTopics().isEmpty());
} | 4 |
private void applyGravity() {
for (int i = 0; i < planets.size(); i++) {
for (int j = i + 1; j < planets.size(); j++) {
planets.get(i).applyGravitationalAttraction(planets.get(j));
}
planets.get(i).applyGravitationalAttraction(ship);
for (int a = 0; a < spaceJunk.size(); a++) {
planets.get(i).applyGravitationalAttraction(spaceJunk.get(a));
}
for (int b = 0; b < bullets.size(); b++) {
planets.get(i).applyGravitationalAttraction(bullets.get(b));
}
}
for (int a = 0; a < spaceJunk.size(); a++) {
ship.applyGravitationalAttraction(spaceJunk.get(a));
for (int b = 0; b < bullets.size(); b++) {
spaceJunk.get(a).applyGravitationalAttraction(bullets.get(b));
}
}
} | 6 |
public void actualizarSeccion(String seccion, int index){
switch(index){
case 1:
_LblGrupo1.setText(seccion);
break;
case 2:
_LblGrupo2.setText(seccion);
break;
case 3:
_LblGrupo3.setText(seccion);
break;
case 4:
_LblGrupo4.setText(seccion);
}
} | 4 |
private static boolean isNativeMethod(String line) {
line = line.trim();
// what if 'native' appears in a comment
return !(line.startsWith("//") || line.startsWith("*")) && // comments?
line.contains(" native ") && // native qualifier
line.contains(";") && line.contains("(") && line.contains(")") && // necessary for a method declaration
!line.contains("\"");
} | 6 |
public static void LoadSpawn() {
localFile = new File("spawn.dat");
String line;
BufferedReader br;
try {
br = new BufferedReader(new FileReader(localFile));
try {
// Read in spawn coordinates, only 3 numbers separated by spaces
line = br.readLine();
if (line == null) {
Logger.Error("Could not read spawn data coordinate data");
} else {
// Spawn coordinates should now be in field line
Logger.Info("Read in \"" + line + "\"");
SpawnCoords = line;
IsSpawnDefined = true;
}
try {
br.close();
} catch (IOException e) {
Logger.Error("Could not close file??");
e.printStackTrace();
}
} catch (IOException e) {
Logger.Error("Could not read from spawn.dat.");
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Logger.Error("Could not open spawn.dat");
e.printStackTrace();
}
} | 4 |
public int getNumberOfPoints(){
return numberOfPoints;
} | 0 |
public OSCPacket convert(byte[] byteArray, int bytesLength) {
this.bytes = byteArray;
this.bytesLength = bytesLength;
this.streamPosition = 0;
if (isBundle()) {
return convertBundle();
} else {
return convertMessage();
}
} | 1 |
public Integer getNumeroColegiado() {
return numeroColegiado;
} | 0 |
public static void main(final String[] args) throws IOException, ServiceException, InterruptedException {
if (args.length != 3) {
System.err.println("arguments: picasaUser albumName freemapAuthKey");
System.exit(1);
}
final PicasawebService myService = new PicasawebService("freemapPhotoImporter");
final URL feedUrl1 = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album");
final UserFeed myUserFeed = myService.getFeed(feedUrl1, UserFeed.class);
// final URL feedUrl;
final AlbumFeed feed;
// HajskeVodopady
// CergovskeVrchyCergov
// SKHUBorderII
// PloskeToryskaPahorkatina -- ignore
// NizkeTatryDumbier
// NizkeTatryKamienkaChopok
// KoniarskaPlanina
// GolgotaBukovecGolgotaJahodna
// PrielomMurana
// SlanskeVrchyRankovskeSkaly
// ZapadneTatryBystra2248m
// VysokeTatryZbojnickaChata
// TheGulleyOfZadiel
// ZadielskaTiesnava
// SivaBradaChapelOfTheHolyCross
// MalaFatraChleb
// VelkaFatraZvolen
// NizkeTatryKralovaHola
// KosiceErikaNalepkovoStratenaPoprad
found: {
for (final AlbumEntry myAlbum : myUserFeed.getAlbumEntries()) {
// System.out.println(myAlbum.getHtmlLink().getHref());
if (myAlbum.getName().equals(args[1])) {
feed = myAlbum.getFeed("photo");
// feedUrl = new URL(myAlbum.getId());
break found;
}
}
System.err.println("not found");
System.exit(1);
return;
}
// final URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/peter.misovic/albumid/5363100042313820497");
// final AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);
for(final PhotoEntry photo : feed.getPhotoEntries()) {
System.out.println(photo.getId());
if (photo.getGeoLocation() == null) {
System.out.println("no GeoLocation - skipping");
continue;
}
System.out.println(photo.getGeoLocation().getLatitude());
System.out.println(photo.getGeoLocation().getLongitude());
// filename: System.out.println("========> " + photo.getTitle().getPlainText());
System.out.println(photo.getDescription().getPlainText());
System.out.println(((com.google.gdata.data.MediaContent) photo.getContent()).getUri());
final Photo photo1 = new Photo();
photo1.latitude = photo.getGeoLocation().getLatitude();
photo1.longitude = photo.getGeoLocation().getLongitude();
photo1.title = photo.getDescription().getPlainText();
photo1.description = "Picasa Photo ID: " + photo.getId();
photo1.url = ((com.google.gdata.data.MediaContent) photo.getContent()).getUri();
PhotoUploader.upload(args[2], photo1);
}
} | 5 |
private void processMoveToKingPile(MouseEvent e) {
int index = (int) (e.getY() / (CARD_Y_GAP + CARD_HEIGHT));
if (index < 4) {
activeMove.cardReleased(index, CardMoveImpl.MOVE_TYPE_TO.TO_KING_PILES);
String result = activeMove.makeMove(game, this);
processMoveResult(result, activeMove);
}
} | 1 |
public int getY() {
if(this == DOWN) return 1;
if(this == UP) return -1;
return 0;
} | 2 |
@Override
/**
* Fügt dem Baum einen Wert hinzu
*
*/
public void addValue(Integer value) throws BinarySearchTreeException {
if (root == null) {
//Wenn es noch keinen root Knoten gibt, erzeuge diesen mit dem hinzuzufügenen Wert
root = new Node(value);
//Rebalancing muss hier nicht durchgeführt werden, weil der Wert als einziger Knoten daherkommt
} else {
//Der Anfangsknoten zum suchen nach einer Einfügeposition ist immer root
Node n = root;
//Stack für das nachverfolgen des weges über die Nodes
Stack nodeTrace = new Stack();
nodeTrace.add(root);
Node newNode = new Node(value);
//Solange dem Baum folgen, bis ein freier Platz gefunden wird
while (true) {
if (value < n.getValue()) { //Wenn der Wert kleiner als der des aktuellen Knotens ist, suche links nach einem freien Platz
if (n.getLft() == null) {
//Freier Platz gefunden, Knoten einfügen
n.setLft(newNode);
break;
} else {
//Nächste Ebene durchsuchen
n = n.getLft();
//Knoten zum Stack hinzufügen
nodeTrace.add(n);
}
} else if (value > n.getValue()) { //Wenn der Wert größer als der des aktuellen Knotens ist, suche rechts nach einem freien Platz
if (n.getRgt() == null) {
//Freier Platz gefunden, Knoten einfügen
n.setRgt(newNode);
break;
} else {
//Nächste Ebene durchsuchen
n = n.getRgt();
//Knoten zum Stack hinzufügen
nodeTrace.add(n);
}
} else {
//Knoten bereits vorhanden, Exception werfen
throw new BinarySearchTreeException();
}
}
nodeTrace.add(newNode);
//Baum rebalancieren
performRebalance(nodeTrace);
}
} | 6 |
public static void loadFromFile() throws Exception{
String filename = "Girl.bin";
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try{
Object temp = ois.readObject();
if(temp.getClass().getName().equals("Girl")){
head = (Girl) temp;
getTail();
}
}catch(EOFException e){
System.out.println("File loaded");
}
} | 2 |
@Override
public void redo() {
// Insert the Node
parent.insertChild(node, index);
node.getTree().insertNode(node);
node.getTree().addNodeToSelection(node);
} | 0 |
@Override
public FTPResult handleResponse(FTPInterface inter, FTPResponse response) {
if (response.getCode() == 211) {
String[] features = response.getContent().split("\n");
if (features.length > 2) {
int length = features.length - 1;
for (int i = 1; i < length; i++) {
String feature = features[i].trim().toUpperCase();
int index = feature.indexOf(" ");
String tag = feature;
String content = "";
if (index > -1) {
tag = feature.substring(0, index);
content = feature.substring(index + 1);
}
if (tag.equals("EPSV")) inter.setFeatureSupported(Feature.EXTENDED_PASSIVE, true);
if (tag.equals("MDTM")) inter.setFeatureSupported(Feature.MODIFICATION_TIME, true);
if (tag.equals("MLST")) {
inter.setFeatureSupported(Feature.METADATA_LIST, true);
inter.setMetadataParameters(content.split(";"));
}
if (tag.equals("SIZE")) inter.setFeatureSupported(Feature.FILE_SIZE, true);
if (tag.equals("UTF8")) inter.setFeatureSupported(Feature.UTF8, true);
}
}
return FTPResult.SUCCEEDED;
}
return FTPResult.FAILED;
} | 9 |
public void setCost(double value) {
this.cost = value;
} | 0 |
public int similarity(String s1, String s2) {
int[][] d = new int[s1.length()][s2.length()];
for(int i=0;i<s1.length();i++)
{
d[i] = new int[s2.length()];
d[i][0] = i;
for(int j=0;j<s2.length();j++)
{
try
{
d[0][j] = j;
}
catch ( Exception ae){}
}
}
for(int j=0;j<s2.length();j++)
{
for(int i=0;i<s1.length();i++)
{
if ( s1.charAt(i) == s2.charAt(j))
{
try{
d[i][j] = d[i-1][j-1];
}
catch (Exception ae){}
}
else
{
try{
d[i][j] = minimum (d[i-1][j]+1,d[i][j-1],d[i-1][j-1]+1);
}
catch (Exception ae){}
}
}
}
return d[s1.length()-1][s2.length()-1];
} | 8 |
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int start = input.nextInt();
int end = input.nextInt();
for (int i = start; i <= end; i++) {
if (i < 10) {
System.out.print(i + " ");
}
else if (i < 100) {
if ((i / 10) == (i % 10)){
System.out.print(i + " ");
}
}
else {
if ((i / 100) == (i % 10)) {
System.out.print(i + " ");
}
}
}
} | 5 |
public static Map<String, List<String>> prepareArgs(String[] args) {
Map<String, List<String>> preparedArgs = new HashMap<String, List<String>>();
List<String> values = null;
String key = null;
for (String arg : args) {
if (arg.startsWith("--")) {
key = arg.substring(2);
values = new ArrayList<String>();
if (key != null) {
preparedArgs.put(key, values);
}
} else {
if (values != null) {
values.add(arg);
}
}
}
if (!preparedArgs.containsKey("args")) {
preparedArgs.put("args", new ArrayList<String>());
}
return preparedArgs;
} | 5 |
@Override
public void run(CommandSender sender, String maincmd, String[] args)
{
if (sender instanceof Player && !sender.hasPermission("mobmanager.butcher"))
{
sender.sendMessage(ChatColor.DARK_RED + "You do not have permission to use /mm butcher");
return;
}
if (!MMComponent.getLimiter().isEnabled())
{
sender.sendMessage(ChatColor.RED + "This command requires EnableLimiter in main config to be true");
return;
}
if (!super.validArgs(sender, maincmd, args))
return;
ArrayList<Object> toRemove = new ArrayList<Object>(1);
int numMobs = 0;
if (args.length == 1)
{
toRemove.add(MobType.MONSTER);
toRemove.add(MobType.AMBIENT);
toRemove.add(MobType.WATER_ANIMAL);
if (args[0].equalsIgnoreCase("butcherall"))
toRemove.add(MobType.ANIMAL);
}
else if (args.length > 1)
{
for (int i = 1; i < args.length; ++i)
{
if (!addMobType(toRemove, args[i]))
{
sender.sendMessage(ChatColor.RED + "Invalid mob type '" + ChatColor.YELLOW + args[i] + ChatColor.RED + "'");
return;
}
}
}
numMobs = removeMobs(toRemove, args[0].equalsIgnoreCase("butcherall"));
sender.sendMessage(ChatColor.GRAY + "~Removed " + numMobs + " mobs");
} | 9 |
public TruncateHelper setWordDelimeterPattern(Pattern wordDelimeterPattern)
{
Assert.notNull(wordDelimeterPattern);
this._wordDelimeterPattern = wordDelimeterPattern;
return this;
} | 0 |
@Override
public ExpertiseDefinition findDefinition(String ID, boolean exactOnly)
{
ExpertiseDefinition D=getDefinition(ID);
if(D!=null)
return D;
for(final Enumeration<ExpertiseDefinition> e=definitions();e.hasMoreElements();)
{
D=e.nextElement();
if(D.name().equalsIgnoreCase(ID))
return D;
}
if(exactOnly)
return null;
for(final Enumeration<ExpertiseDefinition> e=definitions();e.hasMoreElements();)
{
D=e.nextElement();
if(D.ID().startsWith(ID))
return D;
}
for(final Enumeration<ExpertiseDefinition> e=definitions();e.hasMoreElements();)
{
D=e.nextElement();
if(CMLib.english().containsString(D.name(),ID))
return D;
}
return null;
} | 8 |
public void checkForLoginRequests(List<ServerWorker> w) throws IOException {
ServerWorker wLogin = null;
if (!pendingConnections.isEmpty()) {
Iterator<Entry<NetworkStream, Long>> entrySetIterator = pendingConnections.entrySet().iterator();
while (entrySetIterator.hasNext()) {
Entry<NetworkStream, Long> entry = entrySetIterator.next();
NetworkStream stream = entry.getKey();
SocketAddress address = stream.getChannel().getRemoteAddress();
if (System.currentTimeMillis() - entry.getValue() > connectionTimeout) {
try {
throw new Exception();
} catch (Exception e) {
log.error("No login arrived before timeout from {}", address, e);
}
ditchPendingConnection(entry);
log.debug("Removed pending connection: {}", address);
continue;
}
stream.update();
TCP_Packet packet = stream.available.poll();
if (packet != null) {
if (packet.PacketType == TCP_PacketType.LOGIN) {
if (!stream.available.isEmpty()) {
// Are you trying to inject? NO PACKETS BEFORE
// LOGIN! Son I am disappoint...
ditchPendingConnection(entry);
try {
throw new Exception();
} catch (Exception e) {
log.error("Packet arrived before login was acknowledged", e);
}
}
wLogin = new Login((LoginPacket) packet, stream);
log.debug("Received a login from address: {} with username: {}", address, ((LoginPacket) packet).getUsername());
w.add(wLogin);
pendingConnections.remove(stream);
} else {
ditchPendingConnection(entry);
try {
throw new Exception();
} catch (Exception e) {
log.error("Not a login packet", e);
}
}
}
}
}
} | 9 |
public static Short stoShort(String str){
Short i=0;
if(str!=null){
try{
i = Short.parseShort(str.trim());
}catch(Exception e){
i = null;
}
}else{
i = null;
}
return i;
} | 2 |
public static Cons yieldRelationParametersTree(NamedDescription self, boolean dropfunctionparameterP, boolean typedP) {
{ Cons parameterlist = Stella.NIL;
Stella_Object parameter = null;
{ Symbol pname = null;
Cons iter000 = self.ioVariableNames.theConsList;
Surrogate ptype = null;
Cons iter001 = self.ioVariableTypes.theConsList;
for (;(!(iter000 == Stella.NIL)) &&
(!(iter001 == Stella.NIL)); iter000 = iter000.rest, iter001 = iter001.rest) {
pname = ((Symbol)(iter000.value));
ptype = ((Surrogate)(iter001.value));
parameter = pname;
if (typedP &&
(!(ptype == Logic.SGT_STELLA_THING))) {
parameter = Cons.cons(parameter, Cons.cons(Symbol.internSymbolInModule(ptype.symbolName, ((Module)(ptype.homeContext)), true), Stella.NIL));
}
parameterlist = Cons.cons(parameter, parameterlist);
}
}
if (dropfunctionparameterP &&
NamedDescription.functionDescriptionP(self)) {
parameterlist = parameterlist.rest;
}
return (parameterlist.reverse());
}
} | 6 |
public int[] compile(String[] commandsArray) throws Exception {
int commandNr = 0;
int commandsIntArray[] = new int[MAX_CS_SIZE];
for (int i = 0; i < commandsArray.length; i++) {
if (commandsArray[i].trim().equals("")) {
continue;
} else {
CmdWithVar cmd = recognizeStringCommand(commandsArray[i], i);
if (cmd == null) {
throw new Exception("Komanda neatpažinta. Komanda: "
+ commandsArray[i] + ". Eilute: " + i);
} else {
cmdWithVar[commandNr] = cmd;
String first = this.fixBinaryNumber(cmd.commandOpc, 8);
if ((cmd.command.equals(Command.MOV_AX))
|| (cmd.command.equals(Command.MOV_BX))) {
String second = this.fixBinaryNumber(cmd.variable, 32);
commandsIntArray[commandNr] = Integer
.parseInt(first, 2);
commandsIntArray[commandNr + 1] = Integer.parseInt(
addMinus(second, 32), 2);
commandNr++;
} else {
String second = this.fixBinaryNumber(cmd.variable, 8);
commandsIntArray[commandNr] = Integer.parseInt(first
+ second, 2);
}
commandNr++;
}
}
}
this.setProgramSize(commandNr);
int firstZero = MAX_CS_SIZE;
for (int i = 0; i < commandsIntArray.length; i++) {
if (commandsIntArray[i] == 0) {
firstZero = i;
break;
}
}
return Arrays.copyOf(commandsIntArray, firstZero);
} | 7 |
public int getTEAM() {
return team;
} | 0 |
private String get(String id) {
if (id.equals(UserColumn.ACCOUNT_ID)) {
return account_id;
}
else if (id.equals(UserColumn.ROLE)) {
return role;
}
else if (id.equals(UserColumn.LOGIN_ID)) {
return login_id;
}
else if (id.equals(UserColumn.LOGIN_PW)) {
return login_pw;
}
else if (id.equals(UserColumn.USER_NAME)) {
return user_name;
}
else if (id.equals(UserColumn.USER_PHONE)) {
return user_phone;
}
else if (id.equals(UserColumn.USER_EMAIL)) {
return user_email;
}
return "";
} | 7 |
private void calcTime(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
// Stores the current time.
int secondsPlayedOld = secondsPlayed;
// Increments the time based on delta.
time += delta;
secondsPlayed = time/1000;
// If it's been one second.
if (secondsPlayed - secondsPlayedOld != 0){
timeLeft--;
if(timeLeft == 0 && Settings.level < 7){
// Increments the player number for multiplayer.
if (Settings.currentPlayer < Settings.players){
Settings.currentPlayer++;
}
// Sets the current player back to 1 after everyone has had a turn.
else if (Settings.currentPlayer == Settings.players){
Settings.currentPlayer = 1;
}
// Refresh and enter the level cleared state.
sbg.getState(Game.LEVEL_CLEARED_STATE).init(gc, sbg);
sbg.enterState(Game.LEVEL_CLEARED_STATE);
}
else if (timeLeft == 0 && Settings.level == 7){
sbg.addState(new EndOfGame(Game.END_OF_GAME_STATE));
sbg.getState(Game.END_OF_GAME_STATE).init(gc, sbg);
sbg.enterState(Game.END_OF_GAME_STATE);
}
}
spawner.timedSpawn();
} | 7 |
public ClassInfo getClassInfo() {
if (classType instanceof ClassInterfacesType)
return ((ClassInterfacesType) classType).getClassInfo();
return null;
} | 1 |
public List<ForeignKey> foreignKeys() throws SQLException {
List<ForeignKey> result = new ArrayList<ForeignKey>();
ResultSet rs = statement.executeQuery(getFKStatement);
while (rs.next()) {
ForeignKey foreignKey = new ForeignKey(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4)
);
result.add(foreignKey);
}
return result;
} | 1 |
public String GetPlayedWeek(String profileId) throws Exception {
String gamesString = loadGames(profileId, "games?tab=recent");
List<String> games = parseGamesData(gamesString, "hours");
float total = 0;
for (String str : games) {
try {
total += Float.parseFloat(str);
}
catch(Exception e) {
System.out.println(str);
}
}
return Float.toString(total)+"h";
} | 2 |
private Date getDOB() {
Date DOB;
int dayOfBirth = getDayOfBirth();
int monthOfBirth = getMonthOfBirth();
int yearOfBirth = getYearOfBirth();
String dateToValidate = String.format("%d.%d.%d", dayOfBirth, monthOfBirth, yearOfBirth);
List<ValidateException> validateExceptionList = new DOBValidator().validate(dateToValidate);
if (validateExceptionList.isEmpty()) {
DOB = new GregorianCalendar(yearOfBirth, monthOfBirth - 1, dayOfBirth).getTime();
} else {
view.printValidateExceptionsList(validateExceptionList);
DOB = getDOB();
}
return DOB;
} | 1 |
public Expr Add_Expr() throws ParseException {
Expr e, et;
Token tok;
e = Mul_Expr();
label_24:
while (true) {
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ADD:
case SUB:
break;
default:
jj_la1[55] = jj_gen;
break label_24;
}
switch ((jj_ntk == -1) ? jj_ntk() : jj_ntk) {
case ADD:
tok = jj_consume_token(ADD);
break;
case SUB:
tok = jj_consume_token(SUB);
break;
default:
jj_la1[56] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
et = Mul_Expr();
e = new BinOpExpr(e, tok, et);
}
return e;
} | 7 |
public void send(Object oo){
try {
if(this.running){
out.writeObject(oo);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
} | 2 |
public void randomGrid() {
Random rand = new Random();
/* resetGrid();
int b = rand.nextInt(dim*dim);
barrierPositions = new boolean[dim*dim];
for(int i = 0; i < b; i++) {
barrierPositions[rand.nextInt(barrierPositions.length)] = rand.nextBoolean();
}
repaint();
*/
resetGrid();
nodeMap = new Node[dim*dim];
for(int i = 0; i < dim*dim; i++){
barrierPositions[i] = true;
nodeMap[i] = new Node(i);
}
Node root = new Node(rand.nextInt(dim*dim));
barrierPositions[root.getIndex()] = false;
setStart(root.getIndex());
ArrayList<Node> list = new ArrayList<Node>();
list = addWalls(root, list);
while(!list.isEmpty()){
Node cur = list.remove((int)(Math.random()*list.size()));
Node opposite = getOpposite(cur);
if(opposite != null){
if(barrierPositions[cur.getIndex()] && barrierPositions[opposite.getIndex()]){
barrierPositions[cur.getIndex()] = false;
barrierPositions[cur.getParent().getIndex()] = false;
barrierPositions[opposite.getIndex()] = false;
list = addWalls(opposite, list);
}
}
if(list.isEmpty()){
if(!barrierPositions[opposite.getIndex()]){
setGoal(opposite.getIndex());
} else {
GridModel grid = new GridModel(this);
grid.needToPlaceGoal();
}
}
}
repaint();
} | 7 |
@Override
public String notation() {
return this.from.toString() + "x" + this.to.toString() + " e.p.";
} | 0 |
@Override
public void setReceiveQuery(IReceiveQuery receiveQuery) {
this.receiveQuery = receiveQuery;
} | 0 |
private void initView() {
setGridColor(Color.lightGray);
TableColumn column = getColumnModel().getColumn(0);
// column.setCellRenderer(column.getHeaderRenderer());
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBackground(new Color(200, 200, 200));
column.setCellRenderer(renderer);
} | 0 |
public SSLConnection(CM_Stream chanmon)
{
cm = chanmon;
com.grey.naf.SSLConfig sslcfg = cm.getSSLConfig();
int peerport = (cm.iochan instanceof java.nio.channels.SocketChannel ?
((java.nio.channels.SocketChannel)cm.iochan).socket().getPort()
: 0);
engine = sslcfg.isClient ?
sslcfg.ctx.createSSLEngine(sslcfg.peerCertName, peerport)
: sslcfg.ctx.createSSLEngine();
javax.net.ssl.SSLSession sess = engine.getSession();
int netbufsiz = (BUFSIZ_SSL == 0 ? sess.getPacketBufferSize() : BUFSIZ_SSL);
int appbufsiz = (BUFSIZ_APP == 0 ? sess.getApplicationBufferSize() : BUFSIZ_APP);
sslprotoXmtBuf = com.grey.base.utils.NIOBuffers.create(netbufsiz, com.grey.naf.BufferSpec.directniobufs);
sslprotoRcvBuf = com.grey.base.utils.NIOBuffers.create(netbufsiz, com.grey.naf.BufferSpec.directniobufs);
appdataRcvBuf = com.grey.base.utils.NIOBuffers.create(appbufsiz, com.grey.naf.BufferSpec.directniobufs);
dummyShakeBuf = com.grey.base.utils.NIOBuffers.create(1, false); //could possibly be static?
engine.setUseClientMode(sslcfg.isClient); //must call this in both modes - even if getUseClientMode() already seems correct
if (!sslcfg.isClient) {
if (sslcfg.clientAuth == 1) {
engine.setWantClientAuth(true);
} else if (sslcfg.clientAuth == 2) {
engine.setNeedClientAuth(true);
}
}
lastExpireTime = sess.getCreationTime();
logpfx = "SSL-"+(sslcfg.isClient ? "Client" : "Server")+": ";
} | 8 |
private void movePieceCheck(Piece piece, int x1, int y1, int x2, int y2, Position start, Position end, String command, String startSpot, String endSpot)
{
String currentTurnColor = whitePlayerTurn() ? white : black;
if(board.getChessBoardSquare(x2, y2).getPiece().getPieceColor() != (piece.getPieceColor()))
{
if(otherPieceExistsInPath(x1, y1, x2, y2))
{
if(piece.getPieceColor() == currentTurnColor)
{
movePiece(piece, start, end);
totalTurns++;
System.out.println();
System.out.print("Successfully moved piece " + coordinateToPosition(x1, y1) + " to " + coordinateToPosition(x2, y2));
board.printBoard();
System.out.println();
}
else
{
System.out.println();
System.out.println(command);
System.out.println("Piece at " + startSpot + " is not your piece! Choose from your own color!");
}
}
else
{
System.out.println();
System.out.println(command + " \nYou can't do that! Your path is being blocked!");
}
}
else
{
System.out.println();
System.out.print("There is a an ally piece on the spot you are trying to move to! " + endSpot + " \nMove is not valid!");
}
} | 4 |
public static void refreshMarketOfferList(String serverID, String nymID) {
Map marketList = null;
Map offerList = null;
try {
// DEBUGGING: this is where the next step happens
marketList = Market.loadMarketList(serverID, nymID);
offerList = Market.getNymOfferList(serverID, nymID);
if (marketList != null) {
((MarketTableModel) jTable13.getModel()).setValue(marketList, jTable13);
} else {
System.out.println("refreshMarketOfferList: Market.loadMarketList() returned null!");
}
// ------------------------------------
if (offerList != null) {
((MarketOffersTableModel) jTable14.getModel()).setValue(offerList, jTable14);
} else {
System.out.println("refreshMarketOfferList: Market.getNymOfferList() returned null!");
}
// ------------------------------------
if (marketList != null && marketList.size() > 0) {
jTable13.setRowSelectionInterval(0, 0);
} else {
System.out.println("refreshMarketOfferList: marketList.size() was <= 0");
}
// ------------------------------------
if (offerList != null && offerList.size() > 0) {
jTable14.setRowSelectionInterval(0, 0);
} else {
System.out.println("refreshMarketOfferList: offerList.size() was <= 0");
}
// ------------------------------------
} catch (Exception ex) {
Logger.getLogger(MainPage.class.getName()).log(Level.SEVERE, null, ex);
}
} | 7 |
@Override
public void run(ImageProcessor ip) {
ImageStack stack = imp.getStack();
float[][] slicePixels;
int dimension = ip.getWidth() * ip.getHeight();
int sx = ip.getWidth();
int sy = ip.getHeight();
int sc = imp.getNChannels();
int sz = stack.getSize()/sc;
IJ.log("nChannels = "+sc+"; nSlices = "+sz);
BlendFunc blendFunc =
// new MipFunc();
new LimitedAlphaFunc();
// new AlphaFunc();
ImagePlus blended = NewImage.createImage(
"Blended",
sx, sy, sc,
16,
NewImage.FILL_BLACK);
if (sc > 1) {
blended.setDimensions(sc, 1, 1);
blended = new CompositeImage(blended, CompositeImage.COMPOSITE);
blended.setOpenAsHyperStack(true);
}
FloatProcessor scratch = new FloatProcessor(sx, sy);
// start at back slice, for painters' algorithm
for (int z = sz; z >= 1; --z) { // start at back
// for (int z = 1; z <= sz; ++z) { // start at front
for (int c = 0; c < sc; ++c) {
int i = sc*(z-1) + c;
ImageProcessor srcSlice = stack.getProcessor(i+1);
FloatProcessor srcChannel = srcSlice.toFloat(1, scratch);
blended.setPosition(c+1,1,1); // one-based
ImageProcessor destChannel = blended.getChannelProcessor();
for (int y = 0; y < sy; ++y) {
for (int x = 0; x < sx; ++x) {
boolean debug = true;
if (x != 364) debug = false;
if (y != 153) debug = false;
if (c != 1) debug = false;
float src = srcChannel.getf(x, y);
float dest = destChannel.getf(x, y);
destChannel.setf(x, y, blendFunc.compute(src, dest, debug));
}
}
}
IJ.showProgress(sz-z+1, sz-1+1);
}
blended.show();
// imp.setSlice(stack.getSize());
// stack.addSlice("Blended", mipPixels);
// imp.setSlice(stack.getSize());
} | 8 |
private String calculateStringToSignV2(Map<String, String> parameters,
String httpMethod, String hostHeader, String requestURI) throws SignatureException {
StringBuffer stringToSign = new StringBuffer("");
if (httpMethod == null) throw new SignatureException("HttpMethod cannot be null");
stringToSign.append(httpMethod);
stringToSign.append(NewLine);
// The host header - must eventually convert to lower case
// Host header should not be null, but in Http 1.0, it can be, in that
// case just append empty string ""
if (hostHeader == null) {
stringToSign.append("");
} else {
stringToSign.append(hostHeader.toLowerCase());
}
stringToSign.append(NewLine);
if (requestURI == null || requestURI.length() == 0) {
stringToSign.append(EmptyUriPath);
} else {
stringToSign.append(urlEncode(requestURI, true));
}
stringToSign.append(NewLine);
Map<String, String> sortedParamMap = new TreeMap<String, String>();
sortedParamMap.putAll(parameters);
Iterator<Map.Entry<String, String>> pairs = sortedParamMap.entrySet().iterator();
while (pairs.hasNext()) {
Map.Entry<String, String> pair = pairs.next();
if (pair.getKey().equalsIgnoreCase(SIGNATURE_KEYNAME)) continue;
stringToSign.append(urlEncode(pair.getKey(), false));
stringToSign.append(Equals);
stringToSign.append(urlEncode(pair.getValue(), false));
if (pairs.hasNext()) stringToSign.append(And);
}
return stringToSign.toString();
} | 7 |
public IrcException(String e) {
super(e);
} | 0 |
private void defineStartSaveHistory() {
saveHistory = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
while (revising) {
sleep(10);
}
String text = textLower.getText();
if (!TEXT_HISTORY.contains(text)) {
TEXT_HISTORY.push(textLower.getText());
System.out.println(textLower.getText().replaceAll("\\s"," "));
}
sleep(saveInterval);
}
}
// private long getInverseTime() {
// return Long.MAX_VALUE-System.currentTimeMillis();
// }
private void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
});
saveHistory.start();
} | 4 |
public void die(){
if (actors != null)
actors.remove(this);
if(ParticleSystem.isEnabled())
for(ParticleGenerator<? extends Particle> particleGenerator : particleGenerators)
ParticleSystem.removeGenerator(particleGenerator);
} | 4 |
@Override
public GistUser deserializeUserFromJson(String json) {
JSONObject userJO = null;
try {
userJO = (JSONObject) parser.parse(json);
} catch (ParseException e) {
return null;
}
GistUser user = new GistUser();
Object temp = null;
user.setLogin((String) userJO.get("login"));
user.setUrl((String) userJO.get("url"));
user.setCreatedAt((String) userJO.get("created_at"));
user.setAvatarUrl((String) userJO.get("avatar_url"));
user.setGravatarUrl((String) userJO.get("gravatar_url"));
user.setHtmlUrl((String) userJO.get("html_url"));
user.setName((String) userJO.get("name"));
user.setType((String) userJO.get("type"));
user.setCompany((String) userJO.get("company"));
user.setLocation((String) userJO.get("location"));
user.setBlog((String) userJO.get("blog"));
user.setEmail((String) userJO.get("email"));
user.setBio((String) userJO.get("bio"));
temp = userJO.get("id");
if (temp != null) user.setId((Long) temp);
else user.setId(0L);
temp = userJO.get("hireable");
if (temp != null) user.setHireable((Boolean) temp);
else user.setHireable(false);
temp = userJO.get("followers");
if (temp != null) user.setFollowerCount((Integer) temp);
else user.setFollowerCount(0);
temp = userJO.get("following");
if (temp != null) user.setFollowingCount((Integer) temp);
else user.setFollowingCount(0);
temp = userJO.get("public_repos");
if (temp != null) user.setPublicRepoCount((Integer) temp);
else user.setPublicRepoCount(0);
temp = userJO.get("public_gists");
if (temp != null) user.setPublicGistCount((Integer) temp);
else user.setPublicGistCount(0);
temp = userJO.get("private_gists");
if (temp != null) user.setPrivateGistCount((Integer) temp);
else user.setPrivateGistCount(0);
temp = userJO.get("total_private_repos");
if (temp != null) {
user.setPrivateRepoCount((Integer) temp);
//Got private info, must be authenticated user
user.setIsMe(true);
}
else {
user.setPrivateRepoCount(0);
//No private info, must not be authenticated
user.setIsMe(false);
}
return user;
} | 9 |
public void visitInsn(final int opcode) {
buf.setLength(0);
buf.append(tab2).append(OPCODES[opcode]).append('\n');
text.add(buf.toString());
if (mv != null) {
mv.visitInsn(opcode);
}
} | 1 |
@Override
public Command receive() {
System.out.println("Receive ...");
final byte[] buffer = new byte[K.SIZE];
DatagramPacket data = new DatagramPacket(buffer, buffer.length);
Object o = null;
try {
m_multicastSocket.receive(data);
o = Utils.toObject(data.getData());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
return (Command) o;
} | 2 |
@Override
public void execute() throws ParseException
{
DBManager mng = DBManager.getDBManager();
Schema removeSchema = mng.getSchema(this.tableName);
Table removeTable = mng.getTable(this.tableName);
if (removeSchema == null || removeTable == null) {
throw new ParseException("No table called "+this.tableName);
}
//Check foreign key constraint
for(Schema schema : mng.schemas)
{
if (schema.equals(removeSchema)) {
continue;
}
for(ForeignKey otherForeignKey : schema.foreignKeys)
{
if (removeSchema.attrs.containsKey(otherForeignKey.refAttrName)) {
throw new ParseException("Foreign key constraints violated");
}
}
}
mng.schemas.remove(removeSchema);
mng.tables.remove(removeTable);
System.out.println("Table dropped successfully");
} | 6 |
public Graph(String[] s, int[][] m){
int n = s.length;
if(m.length != n || m[0].length != n){
System.out.println("Dimension does not match, exit!");
System.exit(0);
}
for(int i=0;i<s.length;i++){
vertexList.add(new Vertex(s[i]));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(m[i][j] == 1){
Vertex u = vertexList.get(i);
Vertex v = vertexList.get(j);
u.addEdge(v);
}
}
}
} | 6 |
public void viewExampleOProperties(String filename) {
Document doc = (Document) session.getObjectByPath("/" + filename);
List<Property<?>> properties = doc.getProperties();
for (Property<?> p : properties) {
if (p.getFirstValue()
== null) {
System.out.println(p.getId() + "\t" + p.getLocalName()
+ "=" + p.getFirstValue());
} else {
System.out.println(p.getId()
+ "\t" + p.getLocalName() + "=" + p.getFirstValue());
}
}
} | 4 |
public String buscarClientePorApellidoPaterno(String surname1){
//##########################CARGA_BASE DE DATOS#############
tablaDeClientes();
//##########################INGRESO_VACIO###################
if(surname1.equals("")){
surname1 = "No busque nada";
resultBusqueda = "Debe ingresar datos a buscar";
}
//##########################CONVIRTIENDO A MAYUSCULA################################
cadena = surname1.substring(0,1).toUpperCase() + surname1.substring(1, surname1.length());
int longitud = datos.size();
for(int i = 0; i<longitud;i++){
String PaternoBuscado = datos.get(i).getSurname1();
if (PaternoBuscado.equals(cadena)){
db_Temp.add(datos.get(i));
resultBusqueda = datos.get(i).getSurname1();
}
}
if (db_Temp.size()>0){
for (int j=0; j<db_Temp.size();j++){
System.out.println("SU BÚSQUEDA POR APELLIDO PATERNO MUESTRA LOS SIGUIENTES RESULTADOS\t" + "\n");
mostrar(j);
}
}else{
resultBusqueda = "No se encontraron registros para los filtros ingresados";
}
return resultBusqueda;
} | 5 |
private void addQualifierSchemaNodes(Set<Class<? extends Enum<?>>> qualifiers, ObjectNode props) {
for (Class<? extends Enum<?>> qualifier : qualifiers) {
ObjectNode inner = JsonNodeFactory.instance.objectNode();
// inner.put("type", "string");
props.put(factory.getAttributeName(qualifier), inner);
ArrayNode array = JsonNodeFactory.instance.arrayNode();
inner.put("enum", array);
Object[] vals = qualifier.getEnumConstants();
for (Object val : vals) {
array.add(val.toString());
}
}
} | 6 |
protected short[] union(short[] itemSet1, short[] itemSet2) {
// check for null sets
if (itemSet1 == null) {
if (itemSet2 == null) return(null);
else return(itemSet2);
}
if (itemSet2 == null) return(itemSet1);
// determine size of union and dimension return itemSet
short[] newItemSet = new short[sizeOfUnion(itemSet1,itemSet2)];
// Loop through itemSets
int index1=0, index2=0, index3=0;
while (index1<itemSet1.length) {
// Check for end of itemSet2
if (index2>=itemSet2.length) {
for (int index=index1;index<itemSet1.length;index++,index3++)
newItemSet[index3] = itemSet1[index];
break;
}
// Before
if (itemSet1[index1] < itemSet2[index2]) {
newItemSet[index3] = itemSet1[index1];
index1++;
}
else {
// Equals
if (itemSet1[index1] == itemSet2[index2]) {
newItemSet[index3] = itemSet1[index1];
index1++;
index2++;
}
// After
else {
newItemSet[index3] = itemSet2[index2];
index2++;
}
}
index3++;
}
// add remainder of itemSet2
for (int index=index2;index<itemSet2.length;index++,index3++)
newItemSet[index3] = itemSet2[index];
// Return
return(newItemSet);
} | 9 |
public void setLocaleButtonPosition(Position position) {
if (position == null) {
this.localeBtn_Position = UIPositionInits.LOCALE_BTN.getPosition();
} else {
if (position.equals(Position.NONE)) {
IllegalArgumentException iae = new IllegalArgumentException("Position none is not allowed!");
Main.handleUnhandableProblem(iae);
}
this.localeBtn_Position = position;
}
somethingChanged();
} | 2 |
public void setValueOfOutPut(int pData){
if (_logicaCompuerta == "IN")
_ValorOutPut = pData;
else
System.out.println("Por seguridad solo es permitido cambiar el resultado de logica a las compuertas de InPut");
} | 1 |
public static void dispose() {
Iterator<String> it = resources.keySet().iterator();
while (it.hasNext()) {
Object resource = resources.get(it.next());
if (resource instanceof Font)
((Font) resource).dispose();
else if (resource instanceof Color)
((Color) resource).dispose();
else if (resource instanceof Image)
((Image) resource).dispose();
else if (resource instanceof Cursor)
((Cursor) resource).dispose();
}
resources.clear();
} | 5 |
public static final int encryptMessage(int streamOffset,
int messageDataLength, byte[] streamBuffer, int messageDataOffset,
byte[] messageData) {
int i = 0;
messageDataLength += messageDataOffset;
int i_19_ = streamOffset << 309760323;
for (/**/; messageDataOffset < messageDataLength; messageDataOffset++) {
int i_20_ = 0xff & messageData[messageDataOffset];
int i_21_ = huffmanAlgorithm1[i_20_];
int i_22_ = huffmanAlgorithm2[i_20_];
if (i_22_ == 0)
throw new RuntimeException("No codeword for data value "
+ i_20_);
int i_23_ = i_19_ >> -976077821;
int i_24_ = 0x7 & i_19_;
i &= -i_24_ >> -1041773793;
int i_25_ = (-1 + i_24_ - -i_22_ >> -2003626461) + i_23_;
i_19_ += i_22_;
i_24_ += 24;
streamBuffer[i_23_] = (byte) (i = (i | (i_21_ >>> i_24_)));
if (i_25_ > i_23_) {
i_24_ -= 8;
i_23_++;
streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_);
if ((i_23_ ^ 0xffffffff) > (i_25_ ^ 0xffffffff)) {
i_24_ -= 8;
i_23_++;
streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_);
if ((i_23_ ^ 0xffffffff) > (i_25_ ^ 0xffffffff)) {
i_24_ -= 8;
i_23_++;
streamBuffer[i_23_] = (byte) (i = i_21_ >>> i_24_);
if ((i_25_ ^ 0xffffffff) < (i_23_ ^ 0xffffffff)) {
i_23_++;
i_24_ -= 8;
streamBuffer[i_23_] = (byte) (i = i_21_ << -i_24_);
}
}
}
}
}
return -streamOffset + (7 + i_19_ >> 1737794179);
} | 6 |
Parser(Converter converter) {
if (converter == null) {
throw new RuntimeException("cannot convert.");
}
this.converter = converter;
} | 1 |
private int findMinBinarySearch(int[] num, int start, int end) {
if (start == end) return num[start];
if (end - start == 1) {
return Math.min(num[start], num[end]);
} else { // end - start > 1
int mid = (start + end) / 2;
if (num[mid] < num[start]) {
return findMinBinarySearch(num, start, mid);
} else if (num[mid + 1] > num[end]) {
return findMinBinarySearch(num, mid + 1, end);
} else {
return Math.min(num[start], num[mid + 1]);
}
}
} | 4 |
public MazeMaker() {
try {
newMap = JOptionPane.showConfirmDialog(null, "Do you want to create a new map?", "New Map", JOptionPane.YES_NO_OPTION);
} catch(Exception e) {
System.exit(0);
}
if(newMap == JOptionPane.YES_OPTION) {
try {
borderedMap = JOptionPane.showConfirmDialog(null, "Do you want the new map to have a wall border?", "Border Map", JOptionPane.YES_NO_OPTION);
} catch(Exception e) {
System.exit(0);
}
if(borderedMap == JOptionPane.YES_OPTION) {
border = true;
}
sizeChecker();
chooser();
Map.newMap();
} else {
sizeChecker();
chooser();
}
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setTitle("Maze Maker");
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new Board());
panel.add(new ControlsPanel());
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} | 4 |
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
String userName = txtFieldUserName.getText();
char[] pw = txtFieldPassword.getPassword();
String password = new String(pw);
userName.trim();
password.trim();
if(!userName.isEmpty() && !password.isEmpty()){
if(user == null){
User u = new User();
u.setUsername(userName);
u.setPassword(password, false);
u.setRank((User.Rank)cmbBoxType.getSelectedItem());
if(Controller.Instance().addUser(u)){
JOptionPane.showMessageDialog(this, "User saved");
this.dispose();
}
else{
lblError.setText("UserName already exsists");
}
}
else{
User u = new User();
u.CopyUser(user);
u.setUsername(userName);
u.setPassword(password, false);
u.setRank((User.Rank)cmbBoxType.getSelectedItem());
if(Controller.Instance().ChangeUser(user, u))
{
JOptionPane.showMessageDialog(this, "User saved");
this.dispose();
}
else{
lblError.setText("Change User failed username already exsists");
}
}
}
else{
lblError.setText("Please enter a correct username and or password");
}
}//GEN-LAST:event_btnSaveActionPerformed | 5 |
public void open( boolean readOnly )
throws ReadOnlyException,
IOException {
// Resource cann be double-opened!
if( this.isOpen() )
throw new IOException( "Processable resources cannot be double opened." );
if( !readOnly )
throw new ReadOnlyException( "This BufferedResource implementation only supports read-only access." );
// Read the complete data from the input stream into the byte buffer
ByteArrayOutputStream byteOut = new ByteArrayOutputStream( 1024 ); // add initial buffer size as constructor param?
byte[] buffer = new byte[ 1024 ]; // Use different buffer sizes?
int length;
// Note: InputStream.read(byte[]) returns -1 as soon as EOF is reached.
while( (length = this.in.read(buffer)) > 0 ) {
//for( int i = 0; i < length; i++ )
//System.out.print( (char)buffer[i] );
// Push data into ByteArrayOutputStream
byteOut.write( buffer, 0, length );
}
// Finally 'convert' the ByteOutputStream into a ByteArrayResource
this.byteArrayResource = new ByteArrayResource( this.getHTTPHandler(),
this.getLogger(),
byteOut.toByteArray(),
false // It is not necessary to use fair locks here because this wrapped Resource is private
);
byteOut.close();
// Don't forget the underlying Resource, too!
this.byteArrayResource.open( true ); // Open in readOnly mode (the whole implementation is read-only)
// Done. Do NOT close input stream (that is the task of the instance which opened it!)
} | 3 |
public static String newValue()
{
JOptionPane jp = new JOptionPane("Input");
String value = jp.showInputDialog(null, "Enter value (Type #D (Decimal), #B (Binary), #O (Octal), followed by a value.\n\tDefault base is Hex.");
// If the user does not enter anything, returns "ERROR".
if (value == null) {
return "NULL";
} else if (value.length() == 0) {
return "ERROR";
}
try {
if (value.indexOf("#") == -1) {
value = neg(16, value);
} else {
if (value.substring(1, 2).equalsIgnoreCase("B")) {
value = neg(2, value.substring(2));
} else if (value.substring(1, 2).equalsIgnoreCase("D")) {
value = neg(10, value.substring(2));
} else if (value.substring(1, 2).equalsIgnoreCase("O")) {
value = neg(8, value.substring(2));
} else {
throw new NumberFormatException();
}
}
} catch (NumberFormatException nfe) {
}
return value;
} | 7 |
static public void awaitOn(Condition c) {
MultithreadedTestCase thisTestCase = currentTestCase.get();
if (thisTestCase != null && thisTestCase.failed)
throw new RuntimeException("Test case has failed");
if (skipNextWait.get()) {
skipNextWait.set(false);
return;
}
try {
c.await(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
if (thisTestCase != null && thisTestCase.failed)
throw new RuntimeException("Test case has failed");
throw new AssertionError(e);
}
if (thisTestCase != null && thisTestCase.failed)
throw new RuntimeException("Test case has failed");
} | 8 |
public Color lastStanding()
{
int size, i;
Color last = null;
for (size=0, i=0; i<playersNo; ++i) {
if (players[i].isFinished() == false) {
++size;
last = players[i].getColor();
}
}
if (size == 1) return last;
return null;
} | 3 |
public void startElement(String uri, String localName, String qName,
Attributes attrs) throws SAXException {
String elementName = localName;
if ("".equals(elementName)) {
elementName = qName;
}
System.out.println("element: " + elementName);
if (elementName.equals("booklist")) {
if (bookList == null) {
bookList = new BookList(attrs.getValue(0));
}
else{
bookList.clearBooks();
}
}
//handle book element start
else if (elementName.equals("book")) {
currentBook = new Book(attrs.getValue(0));
}
//handle title element start
else if (elementName.equals("title")) {
currentElement = ProcessingElement.TITLE;
}
//handle filename element start
else if (elementName.equals("filename")) {
currentElement = ProcessingElement.FILENAME;
}
//handle icon filename element start
else if (elementName.equals("icon")) {
currentElement = ProcessingElement.ICON;
}
} | 7 |
public Infix2Postfix(String exp){
String str = "";
infixExp = exp;
stack = new Stack<String>();
for (int i=0;i<infixExp.length();i++){
/*
* If the character is a letter or a digit we append it to the postfix
* expression directly.
*/
str = infixExp.substring(i,i+1);
if(str.matches("[a-zA-Z]|\\d"))
postfixExp += str;
else if (isOperator(str)){
/*
* If the stack is empty we directly push the current char into it.
*/
if (stack.isEmpty()){
stack.push(str);
}
else{
/*
* If the current character is an operator, we need to check the stack
* status then, if the stack top contains an operator with lower
* precedence, we push the current character in the stack else we pop
* the character from the stack and add it to the postfix string. This
* continues till we either find an operator with lower precedence in the
* stack or we find the stack to be empty.
*/
String stackTop = stack.peek();
while (getPrecedence(stackTop,str).equals(stackTop)&& !(stack.isEmpty())){
postfixExp += stack.pop();
if (!(stack.isEmpty()))
stackTop = stack.peek();
}
stack.push(str);
}
}
}
// In the end just append all the operators from the stack to the postfix expression.
while(!(stack.isEmpty()))
postfixExp += stack.pop();
// Print out the postfix expression
//System.out.println("The postfix form of the expression you entered is: " + postfixExp);
returnS=postfixExp;
} | 8 |
public void visitSelector(Selector node, String args){
for (int i =0; i< node.getChain().size(); i++){
if(node.getChain().get(i).getClass().getName().compareTo("ast.IdentSelector")==0){
pp(".");
((IdentSelector) node.getChain().get(i)).getIdent().accept(this, args);
}
else if(node.getChain().get(i).getClass().getName().compareTo("ast.TabSelector")==0){
pp("[");
((TabSelector) node.getChain().get(i)).getExpr().accept(this, args);
pp("]");
}
}
} | 3 |
protected void moveRight() {
if (this.posX < (BattleBotsGUI.instance.xDim-1) && !(this.posY == this.enemyPosY && (this.posX+1) == this.enemyPosX) && !(BattleBotsGUI.instance.obstacles[this.posX+1][this.posY])) {
this.posX++;
}
} | 4 |
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('T', options);
if (tmpStr.length() != 0)
setAttributeType(new SelectedTag(tmpStr, TAGS_TYPE));
else
setAttributeType(new SelectedTag(Attribute.NUMERIC, TAGS_TYPE));
tmpStr = Utils.getOption('C', options);
if (tmpStr.length() == 0)
tmpStr = "last";
setAttributeIndex(tmpStr);
setAttributeName(Utils.unbackQuoteChars(Utils.getOption('N', options)));
if (m_AttributeType == Attribute.NOMINAL) {
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() != 0)
setNominalLabels(tmpStr);
}
else if (m_AttributeType == Attribute.DATE) {
tmpStr = Utils.getOption('F', options);
if (tmpStr.length() != 0)
setDateFormat(tmpStr);
}
if (getInputFormat() != null) {
setInputFormat(getInputFormat());
}
} | 7 |
public void matchSubscriptions(Message message) {
try {
List<Subscription> subscriptions = this.parent.getSubscriptionByTopic(message.getTopic());
for (Subscription subscription : subscriptions) {
try {
System.out.println("Enviando mensaje a: " + subscription.getIpAddress());
Socket newSocket;
newSocket = new Socket(subscription.getIpAddress(), subscription.getPort());
ObjectOutputStream dos = new ObjectOutputStream(newSocket.getOutputStream());
dos.writeObject(message);
newSocket.close();
} catch (IOException ex) {
System.out.println("Failed to deliver message:" + ex);
}
}
} catch (Exception ex) {
System.out.println("machSubscriptions:" + ex);
}
} | 3 |
public List<Organism> GAstep_mutation() throws Exception {
/* mutation */
List<Organism> mutatedOrganisms = new ArrayList<Organism>();
for (int i = 0; i < this.getSpeciesNumber(); i++) {
mutatedOrganisms.addAll(species.get(i).mutation(getGenerationNumber()));
}
/**
* speciate
*/
if (!mutatedOrganisms.isEmpty()) {
speciate(mutatedOrganisms);
}
return mutatedOrganisms;
} | 2 |
private boolean checaTipoVariavelGlobal(String tipoDoRetorno) {
if(!listaVariveisGlobais.isEmpty()){
for(int i = 0; i< listaVariveisGlobais.size();i++){
String tipoVariavel;
String nomeVariavel;
if(listaVariveisGlobais.get(i).split(":")[1].equals("vetor")){
nomeVariavel = listaVariveisGlobais.get(i).split(":")[3];
tipoVariavel = listaVariveisGlobais.get(i).split(":")[2];
}else{
nomeVariavel = listaVariveisGlobais.get(i).split(":")[2];
tipoVariavel = listaVariveisGlobais.get(i).split(":")[1];
}
if(nomeVariavel.equals(tipoDoToken[1])){
if(tipoVariavel.equals(tipoDoRetorno)){
return true;
}
}
}
}
return false;
} | 5 |
private int resolveDayUnit( String unit ) {
if ( unit.equalsIgnoreCase("monday") ) {
return TimeAxisUnit.MONDAY;
}
else if ( unit.equalsIgnoreCase("tuesday") ) {
return TimeAxisUnit.TUESDAY;
}
else if ( unit.equalsIgnoreCase("wednesday") ) {
return TimeAxisUnit.WEDNESDAY;
}
else if ( unit.equalsIgnoreCase("thursday") ) {
return TimeAxisUnit.THURSDAY;
}
else if ( unit.equalsIgnoreCase("friday") ) {
return TimeAxisUnit.FRIDAY;
}
else if ( unit.equalsIgnoreCase("saturday") ) {
return TimeAxisUnit.SATURDAY;
}
else if ( unit.equalsIgnoreCase("sunday") ) {
return TimeAxisUnit.SUNDAY;
}
else {
throw new IllegalArgumentException( "Invalid day unit specified: " + unit );
}
} | 7 |
public boolean isFullFilled() {
boolean isFilled = true;
boolean aId = idActivity >= 0;
boolean sTime = startTime != null;
boolean eTime = endTime != null;
boolean dur = duration >= 0;
if (!aId) isFilled = false;
if (!sTime) isFilled = false;
if (!eTime) isFilled = false;
if (!dur) isFilled = false;
return isFilled;
} | 4 |
public boolean equals( Object other ) {
if ( ! ( other instanceof TObjectIntMap ) ) {
return false;
}
TObjectIntMap that = ( TObjectIntMap ) other;
if ( that.size() != this.size() ) {
return false;
}
try {
TObjectIntIterator iter = this.iterator();
while ( iter.hasNext() ) {
iter.advance();
Object key = iter.key();
int value = iter.value();
if ( value == no_entry_value ) {
if ( !( that.get( key ) == that.getNoEntryValue() &&
that.containsKey( key ) ) ) {
return false;
}
} else {
if ( value != that.get( key ) ) {
return false;
}
}
}
} catch ( ClassCastException ex ) {
// unused.
}
return true;
} | 8 |
static void combine_sort(int l,int m,int h,int num[]) {
int i,j=m+1,k;int temp[]=new int[10];
for(i=l;i<=h;i++) {
temp[i]=num[i];
}
i=l;k=l;
while(i<=m && j<=h) {
if(temp[i]<=temp[j]) {
num[k++]=temp[i++];
}
else {
num[k++]=temp[j++];
}
}
while(i<=m) {
num[k++]=temp[i++];
}
while(j<=h) {
num[k++]=temp[j++];
}
} | 6 |
public static void updateSelectedRow(JTable table, Container controlsContainer) throws Exception {
int selRow = table.getSelectedRow();
DefaultTableModel tableModel = ((DefaultTableModel)table.getModel());
if (selRow > -1) {
int compCount = controlsContainer.getComponentCount();
int column = 0;
Object value = null;
Component comp;
String item;
StringBuffer newItem;
JComboBox comboBox;
for (int i = 0; i < compCount; i++) {
comp = controlsContainer.getComponent(i);
if (!(comp instanceof JLabel)) {
if ((comp instanceof JTextField)) {
value = ((JTextField)comp).getText();
} else if (comp instanceof JToggleButton) {
value = new Boolean(((JToggleButton)comp).isSelected());
} else if (comp instanceof JComboBox) {
comboBox = (JComboBox)comp;
item = (String)comboBox.getSelectedItem();
if (item.indexOf(DELIMETER) > -1) {
//Moves the second value from the table to the combobox.
newItem = new StringBuffer();
newItem.append(tableModel.getValueAt(selRow, 0));
newItem.append(DELIMETER);
newItem.append(tableModel.getValueAt(selRow, 1));
comboBox.addItem(newItem.toString());
//Moves the first value from the combobox to the table.
comboBox.removeItem(item);
tableModel.setValueAt(item.substring(0, item.indexOf(DELIMETER)), selRow, 0);
tableModel.setValueAt(item.substring(item.indexOf(DELIMETER) + DELIMETER.length()), selRow, 1);
return;
} else {
value = item;
}
}
tableModel.setValueAt(value, selRow, column);
column++;
}
}
}
} | 7 |
protected void onSaveKey()
{
File[] fileNames;
FileDialog dlgSave = new FileDialog( this, "Save keystore...", FileDialog.SAVE );
dlgSave.setFile( "*.ks" );
try {
this.readDataToKeyInfo();
this.lblStatus.setText( "Choose file name..." );
dlgSave.setVisible( true );
fileNames = dlgSave.getFiles();
if ( fileNames.length > 0 ) {
File file = fileNames[ 0 ].getCanonicalFile();
KeyManager kg = new KeyManager( file, this.keyInfo );
this.lblStatus.setText( "Generating KeyStore..." );
kg.generate();
this.lblStatus.setText( "KeyStore file generated" );
this.pnlData.setVisible( false );
} else {
this.lblStatus.setText( "Ready" );
}
} catch (RuntimeException
| IOException
| KeyStoreException
| NoSuchAlgorithmException
| CertificateException
| InvalidKeyException
| SignatureException
| NoSuchProviderException ex)
{
this.lblStatus.setText( "Error: " + ex.getLocalizedMessage() );
}
finally {
this.requestFocusInWindow();
}
return;
} | 2 |
@Test
public void testUnion() {
assertThat(uf.connected(0, 1), is(not(true)));
uf.union(0, 1);
uf.union(0, 2);
assertThat(uf.connected(0, 1), is(true));
assertThat(uf.connected(1, 2), is(true));
} | 0 |
@Override
public boolean activate() {
return (!Inventory.isFull()
&& Settings.root.getRoot() == 3
&& !Inventory.contains(Constants.INVENTORY_BURNED_ROOT_ID)
&& !validate(Constants.WAITFOR_WIDGET)
&& !validate(Constants.FLETCH_WIDGET)
);
} | 4 |
public void setPaused(boolean paused) {
if (this.paused != paused && sequencer != null && sequencer.isOpen()) {
this.paused = paused;
if (paused) {
sequencer.stop();
}
else {
sequencer.start();
}
}
} | 4 |
@Override
public boolean onMouseDown(int mX, int mY, int button) {
if(button == 0 && mX > x && mX < x + width && mY > y && mY < y + height) {
Application.get().getHumanView().addScreen(ShopScreenFactory.create());
return true;
}
return false;
} | 5 |
public boolean remove(int value) {
// Knuth, v. 3, 527, Algorithm R.
int i = indexOf(value);
if (_values[i] == ndv) {
return false;
}
--_size;
for (; ;) {
_values[i] = ndv;
int j = i;
int r;
do {
i = (i - 1) & _mask;
if (_values[i] == ndv) {
return true;
}
r = hash(_values[i]);
} while ((i <= r && r < j) || (r < j && j < i) || (j < i && i <= r));
_values[j] = _values[i];
}
} | 9 |
private void form_keyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_form_keyPressed
if (evt.getKeyCode() == KeyEvent.VK_F5)
try {
reload();
} catch (IOException ex) {
logger.log(level.ERROR, "Error while loading devices! Stack trace will be printed to console...");
JOptionPane.showMessageDialog(null, "An error occured while loading currently connected devices.\n"
+ "Please terminate and re-run the erronious step to determine where the error has occurred.", "Error While Loading Devices.", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace(System.err);
}
}//GEN-LAST:event_form_keyPressed | 2 |
private static void estEntourerDeMurs(Labyrinthe l)
throws LabyMalEntoureException {
for (int i = 0; i < l.Xsize(); i++) {
if (l.getContenuCase(i, 0) != ContenuCase.MUR)
throw new LabyMalEntoureException(new Point(i, 0));
if (l.getContenuCase(i, l.Ysize() - 1) != ContenuCase.MUR)
throw new LabyMalEntoureException(new Point(i, l.Ysize() - 1));
}
for (int j = 0; j < l.Ysize(); j++) {
if (l.getContenuCase(0, j) != ContenuCase.MUR)
throw new LabyMalEntoureException(new Point(0, j));
if (l.getContenuCase(l.Xsize() - 1, j) != ContenuCase.MUR)
throw new LabyMalEntoureException(new Point(l.Xsize() - 1, j));
}
} | 6 |
public void update(GameContainer gc, StateBasedGame sbg, GameplayState gs, int delta) throws SlickException {
for (Entry<Long, Tower> entry : this.towers.entrySet()) {
entry.getValue().update(gc, sbg, gs, delta);
}
for (Entry<Long, Bullet> bullet : this.bullets.entrySet()) {
bullet.getValue().update(gc, sbg, gs, delta);
if (bullet.getValue().isDead()) {
this.toBeRemoved.add(bullet.getKey());
}
}
if (!this.toBeRemoved.isEmpty()) {
for (Long bulletId : this.toBeRemoved) {
this.removeBullet(bulletId);
}
this.toBeRemoved.clear();
}
} | 5 |
private int partition() {
int center = (start + end) / 2;
if (array[center] < array[start]) {
swap(center, start);
}
if (array[end] < array[start]) {
swap(start, end);
}
if (array[end] < array[center]) {
swap(center, end);
}
int pivotIndex = center;
swap(pivotIndex, end - 1);
int pivot = array[end - 1];
int left = start;
int right = end - 1;
while (array[++left] < pivot);
while (pivot < array[--right]);
while (left < right) {
swap(left, right);
while (array[++left] < pivot);
while (pivot < array[--right]);
}
pivotIndex = left;
swap(pivotIndex, end - 1);
return pivotIndex;
} | 8 |
@Override
public ArrayList<Short> get(Integer... a) {
ArrayList<Short> r = new ArrayList<Short>();
for (Integer i : a) {
Object[] plain = huff.decode(filter[i/rate]);
int index = i-(i/rate)*rate;
r.add((Short)plain[index]);
}
return r;
} | 1 |
public int length() {
int len = 1;
Node n = this;
while(n.next != null) {
len++;
n = n.next;
}
return len;
} | 1 |
private void addPoint() throws NumberFormatException, IOException {
double[] coordList = new double[dimensionList.length];
for (int count = 0; count < dimensionList.length; count++) {
System.out.println("Enter " + dimensionList[count].toString() + "-coord:");
coordList[count] = Double.parseDouble(Wrapper.getUserInput());
}
Point myPoint = new Point(new Vector(coordList), this);
shapeList.add(shapeList.size(), myPoint);
} | 1 |
@Override
public void renameProductContainer(ProductContainerData renamedContainer, String newName,
int newIndex) {
boolean disabledEvents = disableEvents();
try {
ProductContainerTreeNode renamedNode = _productContainers.get(renamedContainer);
assert renamedNode != null;
if (renamedNode != null) {
ProductContainerTreeNode parentNode =
(ProductContainerTreeNode)renamedNode.getParent();
assert parentNode != null;
if (parentNode != null) {
ProductContainerData parentContainer =
parentNode.getProductContainer();
parentContainer.renameChild(renamedContainer, newName, newIndex);
TreePath renamedPath = new TreePath(renamedNode.getPath());
// remember which descendant nodes were expanded so they
// can be re-expanded after the tree is updated
ArrayList<TreePath> expandedList = null;
Enumeration<TreePath> expandedEnum =
_productContainerTree.getExpandedDescendants(renamedPath);
if (expandedEnum != null) {
expandedList = new ArrayList<TreePath>();
while (expandedEnum.hasMoreElements()) {
TreePath path = expandedEnum.nextElement();
expandedList.add(path);
}
}
// update the tree
_productContainerTreeModel.removeNodeFromParent(renamedNode);
_productContainerTreeModel.insertNodeInto(renamedNode, parentNode, newIndex);
// re-expand descendant nodes that were expanded before the update
if (expandedList != null) {
for (TreePath path : expandedList) {
_productContainerTree.expandPath(path);
}
}
}
}
}
finally {
if (disabledEvents) {
enableEvents();
}
}
} | 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.