method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
a743d177-2d19-42e4-9784-1b3e002d6e43 | 0 | public String getHexPeerId() {
return this.hexPeerId;
} |
7e125687-c115-4e00-b2d9-0e134c4a29b4 | 0 | private HeaderType(String type) {
this.typeOf=type;
} |
45a4ffff-c673-46c7-890f-e8194cfed541 | 5 | String []frequencey(double array[]){ // find mode.
int [][]tools = new int[array.length][2];
String shed[] = new String [2];
double []check = array;
int big = 0;
ArrayList<Integer> counter = new ArrayList<Integer>();
int count = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < check.length; j++) {
if(array[i] == check[j]){
count++;
}
}//counter.add(count); count =0;
tools[i][0] = count;
tools[i][1] = i;
//big = tools[0][0];
if(i > 0){
if(tools[i-1][0]< tools[i][0]){
big = tools[i][0];
shed[1] = Integer.toString(tools[i][1]);
}
}
count =0;
}
// int largest= tools[0][0];
// for (int i = 0; i < tools.length; i++) {
// if(largest< tools[i][0]){
// largest = tools[i][0];
// }
// }
shed[0] = Integer.toString(big);
// for (int i = 0; i < tools.length; i++) {
// if(big== tools[i][0]){
// shed[1] = Integer.toString(tools[i][1]);
// }
// }
shed[1] = Double.toString(array[Integer.parseInt(shed[1])]);
return shed;
} |
74be39bc-490f-4298-ab55-74ad70eb68af | 6 | public void day() {
List<Subject> movedAlready = new ArrayList<Subject>();
for (int i = 0; i < grid.getWidth(); i++) {
for (int j = 0; j < grid.getDepth(); j++) {
if (getSubject(i, j) == null
|| movedAlready.contains(getSubject(i, j))) {
continue;
}
// Changes the state of the subject
getSubject(i, j).changeState();
// The subject is contagious
if (getSubject(i, j).isContagious()) {
List<Point> neighbors = getNeighbors(new Point(i, j));
for (Iterator<Point> it = neighbors.iterator(); it
.hasNext();) {
Point neighbor = (Point) it.next();
getSubject(i, j).contact(
getSubject(neighbor.x, neighbor.y));
}
}
randomMove(new Point(i, j));
movedAlready.add(getSubject(i, j));
}
}
} // day() |
d3fac04b-40f3-4358-a472-a715ae65cced | 7 | public static void main(String[] args) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (String line ; (line = in.readLine())!=null; ) {
StringTokenizer st = new StringTokenizer( line );
int i = Integer.parseInt(st.nextToken());
int j = Integer.parseInt(st.nextToken());
if( i == -1 && j == -1) break;
int n = Integer.MAX_VALUE;
int resta = Math.max(i, j) - Math.min(i, j );
if( resta < n ) n = resta;
int sum = 0;
for (int k = Math.max(i, j); k != Math.min(i, j); k++) {
if( k == 100 ) k = -1;
else sum++;
}
if(sum < n) n = sum;
System.out.println(n);
}
} |
9eadf934-94da-4edd-9b9f-bed819af8a76 | 7 | public Boolean process() {
// Permissions
if(!plugin.permission.isAdmin(player)) {
noPermission();
return true;
}
// Invalid args
if(args.length < 3) {
sendMessage("Usage:");
sendMessage("/casino type add <type>");
sendMessage("/casino type edit <type>");
sendMessage("/casino type remove <type>");
return true;
}
// Add type command
if(args[1].equalsIgnoreCase("add")) {
if(plugin.typeData.isType(args[2])) {
sendMessage("Type " + args[2] +" already exists.");
}
else {
plugin.typeData.newType(args[2]);
sendMessage("Type " + args[2] + " created! Configure it to your needs in config.yml before using it.");
}
}
// Edit type command
else if(args[1].equalsIgnoreCase("edit")) {
sendMessage("Not yet implemented.");
}
// Remove type command
else if(args[1].equalsIgnoreCase("remove")) {
if(plugin.typeData.isType(args[2])) {
plugin.typeData.removeType(args[2]);
sendMessage("Type " + args[2] + " removed. Make sure to update any slot machines using this type.");
}
else {
sendMessage("Invalid type " + args[2]);
}
}
return true;
} |
61ebfcea-7542-4848-bd96-d1c469b9774a | 6 | public void HoldIfNotActive(){
Iterator<Entry<CallFrame, List<String>>> linkBridgeIterator = linkBridgeLines.entrySet().iterator();
while (linkBridgeIterator.hasNext()) {
Entry<CallFrame, List<String>> entry = linkBridgeIterator.next();
List<String> bridgeList = (List<String>) entry.getValue();
String bridgeInitNumber=bridgeList.get(0).substring(0,bridgeList.get(0).indexOf("-"));
String bridgeNumber=bridgeList.get(1).substring(0,bridgeList.get(1).indexOf("-"));
for(int i=0;i<Phone.AllExtensions.size();i++)
{
if(!this.equals((CallFrame) entry.getKey()) && bridgeInitNumber.equals(Phone.AllExtensions.get(i)))
{
MakeCallNotActive(bridgeList.get(1),bridgeList.get(0),bridgeNumber,(CallFrame) entry.getKey());
MakeFrameNotActive((CallFrame) entry.getKey());
}
else if(!this.equals((CallFrame) entry.getKey()) && bridgeNumber.equals(Phone.AllExtensions.get(i)))
{
MakeCallNotActive(bridgeList.get(0),bridgeList.get(1),bridgeInitNumber,(CallFrame) entry.getKey());
MakeFrameNotActive((CallFrame) entry.getKey());
}
}
}
} |
5493b297-d5de-4ad8-8eab-9bfa7f8e1366 | 1 | protected static String pumpString(String s, int i)
{
StringBuffer sb = new StringBuffer();
for(int n = i; n > 0; n--)
sb.append(s);
return sb.toString();
} |
9e73e101-fd42-4b34-a626-48d6b078d22f | 9 | public static Hand findHighestStraight(Set<Card> cardSet) {
CardSetStats stats = new CardSetStats(cardSet);
if (stats.rankList.size() < 5) {
return null;
}
Rank pointerRank = null;
List<Rank> straight = new ArrayList<Rank>();
boolean containsAce = false; // used for wheel straight
for (Rank nextRank : stats.rankList) {
if (nextRank == Rank.Ace) {
containsAce = true;
}
if (pointerRank != null && pointerRank.value - 1 != nextRank.value) {
straight = new ArrayList<Rank>();
}
straight.add(nextRank);
pointerRank = nextRank;
if (straight.size() == 5) {
return Hand.Straight(straight.get(0));
}
// Check for wheel (A,2,3,4,5 straight)
if (straight.size() == 4 && straight.get(0) == Rank.Five && containsAce) {
return Hand.Straight(Rank.Five);
}
}
return null;
} |
0fd8e1bf-e80e-4fed-8b90-fb49cbcafaee | 1 | public static long imageToLong(String name) {
name = name.toUpperCase();
long encoded = 0L;
for (int i = 0; i < name.length(); i++) {
encoded = encoded * 61L + name.charAt(i) - 32L;
encoded = encoded + (encoded >> 56) & 0xffffffffffffffL;
}
return encoded;
} |
1f3f0922-f48f-4c32-8b87-7a3d1ca9edac | 5 | public List<MenuItem> getMenuChoices() throws RuntimeException {
List<MenuItem> items = new ArrayList<MenuItem>();
try {
// Make sure you always open a connection before trying to
// send commands to the database.
db.openConnection(DRIVER, URL, ADMIN, PASSWORD);
List<Map> rawData = db.findRecords(sql, true);
for (Map record : rawData) {
MenuItem item = new MenuItem();
int id = Integer.valueOf(record.get(MENU_ID).toString());
item.setMenuId(id);
String name = String.valueOf(record.get(MENU_ITEM));
item.setMenuItem(name);
Double price = Double.valueOf(record.get(MENU_ITEM_PRICE).toString());
item.setItemPrice(price);
int cat = Integer.valueOf(record.get(CATEGORY).toString());
item.setCategory(cat);
String value = String.valueOf(record.get(MENU_VALUE).toString());
item.setMenuValue(value);
items.add(item);
}
return items;
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex.getMessage(), ex);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(ex.getMessage(), ex);
} catch (SQLException ex) {
throw new RuntimeException(ex.getMessage(), ex);
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
} |
3d76e09e-3990-484e-ae4b-3f9d499e0d68 | 5 | private Calendar promptForDate(BufferedReader keyboard)
throws IOException {
Calendar date = new GregorianCalendar();
boolean valid = true;
do {
// Prompt and read input
System.out
.print("Task date (Format = DD/MM/YYYY, Default = today): ");
String dateString = keyboard.readLine();
// If input is empty, return current date as default
if (!dateString.isEmpty()) {
// Tokenize input by slashes
StringTokenizer dateTokenizer = new StringTokenizer(
dateString, "/");
String[] dateTokens = new String[dateTokenizer
.countTokens()];
int i = 0;
while (dateTokenizer.hasMoreTokens()) {
dateTokens[i] = dateTokenizer.nextToken();
i++;
}
// Check that the input format was correct
if (dateTokens.length == 3) {
valid = true;
// Parse input into a Calenar object
try {
int day = Integer.parseInt(dateTokens[0]);
int month = Integer.parseInt(dateTokens[1]) - 1;
int year = Integer.parseInt(dateTokens[2]);
date = new GregorianCalendar(year, month, day);
} catch (NumberFormatException e) {
valid = false;
System.out.println("Format must be DD/MM/YYYY");
}
} else {
valid = false;
System.out.println("Format must be DD/MM/YYYY");
}
} else {
valid = true;
}
} while (!valid); // Repeat until valid input is received
return date;
} |
44f32408-73ba-4e7f-9c9e-2b1d07c3237e | 3 | private JSONWriter end(char mode, char c) throws JSONException {
if (this.mode != mode) {
throw new JSONException(mode == 'a'
? "Misplaced endArray."
: "Misplaced endObject.");
}
this.pop(mode);
try {
this.writer.write(c);
} catch (IOException e) {
throw new JSONException(e);
}
this.comma = true;
return this;
} |
76741b3e-660b-4254-8819-cf8667e63a12 | 7 | public boolean func_48457_a(EntityPlayer par1EntityPlayer, int par2, int par3, int par4, int par5)
{
if (par5 == 0)
{
--par3;
}
if (par5 == 1)
{
++par3;
}
if (par5 == 2)
{
--par4;
}
if (par5 == 3)
{
++par4;
}
if (par5 == 4)
{
--par2;
}
if (par5 == 5)
{
++par2;
}
if (this.getBlockId(par2, par3, par4) == Block.fire.blockID)
{
this.playAuxSFXAtEntity(par1EntityPlayer, 1004, par2, par3, par4, 0);
this.setBlockWithNotify(par2, par3, par4, 0);
return true;
}
else
{
return false;
}
} |
bc972a8f-8e8a-47ea-a6dd-bec687e148e6 | 0 | @Override
public String toString() {
return getURLString();
} |
3e894692-f505-459c-a22e-da9c76f427ff | 7 | public void renderBackground(SpriteSheets sprite, boolean clouds) {
int pixelIndex;
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
int xAbs = x + cameraXCoord;
int yAbs = y + cameraYCoord;
pixelIndex = (xAbs) + (yAbs) * sprite.getXSheetSize();
if(xAbs > 0 && yAbs > 0 && xAbs < sprite.getXSheetSize() && yAbs < sprite.getYSheetSize()) {
pixels[x + y * width] = sprite.getSpriteSheetsPixels(pixelIndex);
}
}
}
if(clouds) {
renderClouds();
}
} |
3fa7f9f0-f299-4eb8-af7f-01c348d70cee | 5 | private static void assemblyC(ArrayList<Integer> cList){ //"spaja" listy wszystkich cykli w jedną listę ułożoną w kolejności
asmC.addAll(cycles[cList.get(0)].vxList);
cList.remove(0);
do{
for(int i : cList){
if(asmC.get(asmC.size()-1) == cycles[i].vxList.get(0)){ //jeżeli ostatni == prerwszy
asmC.addAll(cycles[i].vxList.subList(1, cycles[i].vxList.size()));
cList.remove((Integer) i);
}else if(asmC.get(asmC.size()-1) == cycles[i].vxList.get(cycles[i].vxList.size()-1)){ //jeżeli ostatni == ostatni
for(int j=cycles[i].vxList.size()-2; j>0; j--){ //dodaje w odwróconej kolejności
asmC.add(cycles[i].vxList.get(j));
}
cList.remove((Integer) i);
}
}
}while(cList.size() > 0);
} |
db21a78b-5f32-49f2-bc62-4a619b2d5d4e | 2 | public boolean inServerDB(Connection con, String file_path) {
boolean result = false;
try {
PreparedStatement ps = con
.prepareStatement("SELECT * FROM db_like_files WHERE path_local = ?");
ps.setString(1, file_path);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
result = true;
} else {
result = false;
}
} catch (SQLException e) {
e.printStackTrace();
result = false;
}
return result;
} |
d01e3090-c50e-4a69-a450-ff79f5d0a829 | 1 | public static void main(String args[]){
System.out.println("Usage of MySQLAccess Object...");
try {
MySQLAccess dbAccess = new MySQLAccess();
dbAccess.register();
dbAccess.connect();
dbAccess.createStatement();
//dbAccess.markerIsTaken(1, "kash098");
//dbAccess.deletePlayer("dice098");
//dbAccess.deletePlayer("dicer");
//dbAccess.deletePlayer("dicey");
//dbAccess.deleteHost("kash098");
//dbAccess.deletePlayer("kash098");
//dbAccess.deleteHost("kashr");
/*
System.out.println("Team is full? " + dbAccess.teamIsFull("a", "kashka"));
System.out.println("All players in match are ready? " + dbAccess.allPlayersAreReady("kashka"));
System.out.println(dbAccess.eachTeamHasOnePlayer("kashka"));
*/
dbAccess.close();
}
catch( Exception e ) {
e.printStackTrace();
e.getMessage();
}
}//end main |
b2cf957c-ae55-4316-8f6e-043af4331473 | 0 | @RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
return new ModelAndView("index");
} |
55ad06ae-83b6-4ef3-b55a-eb54a4071579 | 1 | @Override
public boolean scan(String c) {
if (mapOfProductsList.containsKey(c))
return scanProducts.add(c);
return false;
} |
ccfc9864-5471-4e45-a886-3687b044b38e | 7 | public void doLoad(String path) {
FileInputStream inputStream = null;
ObjectInputStream deserializer = null;
try {
inputStream = new FileInputStream(path);
deserializer = new ObjectInputStream(inputStream);
dictionary = (Map<String, TreeSet<Document>>) deserializer.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// no op
}
}
if (deserializer != null) {
try {
inputStream.close();
} catch (IOException e) {
// no op
}
}
}
} |
8f210a62-9177-4ca1-9234-916f0a7ac941 | 3 | private static void sqlStore(Status status) throws SQLException{
long sql_pid = Settings.pid;
Settings.pid++;
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss, z");
String sqlCreateAt = tempDate.format(new java.util.Date(status.getCreatedAt().getTime()));
double sqlGeoLocationLat = 0;
double sqlGeoLocationLong = 0;
if (status.getGeoLocation()!=null){
sqlGeoLocationLat = status.getGeoLocation().getLatitude();
sqlGeoLocationLong = status.getGeoLocation().getLongitude();
}
String sqlPlace = (status.getPlace()!= null ? status.getPlace().getFullName(): "");
long sqlId = status.getId();
String sqlTweet = status.getText().replace("'", "''");
String sqlSource = status.getSource().replace("'", "''");
sqlSource = sqlSource.replace("\\","\\\\");
String sqlLang = status.getUser().getLang();
String sqlScreenName = status.getUser().getScreenName();
String sqlReplyTo = status.getInReplyToScreenName();
long sqlRtCount = status.getRetweetCount();
HashtagEntity[] hashs = status.getHashtagEntities();
String sqlHashtags = "";
for (HashtagEntity hash: hashs) sqlHashtags+=hash.getText()+" ";
pstm.setLong(1, sql_pid);
pstm.setString(2, sqlCreateAt);
pstm.setDouble(3, sqlGeoLocationLat);
pstm.setDouble(4, sqlGeoLocationLong);
pstm.setString(5, sqlPlace);
pstm.setLong(6, sqlId);
pstm.setString(7, sqlTweet);
pstm.setString(8, sqlSource);
pstm.setString(9, sqlLang);
pstm.setString(10, sqlScreenName);
pstm.setString(11, sqlReplyTo);
pstm.setLong(12, sqlRtCount);
pstm.setString(13, sqlHashtags);
pstm.addBatch();
} |
caa2193d-a55d-4ef4-893f-c15a485169a9 | 0 | @Override
public double access(Balance balance) {
return balance.getBalance();
} |
1db1f606-ec05-4525-9814-779b645d1803 | 1 | public Button(JButton button) {
this.button = button;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (clickHandler != null)
clickHandler.run();
}
});
} |
71585850-77c9-434b-97d8-3aeebc62f19e | 7 | public boolean setTileNoUpdate(int var1, int var2, int var3, int var4) {
if(var1 >= 0 && var2 >= 0 && var3 >= 0 && var1 < this.width && var2 < this.depth && var3 < this.height) {
if(var4 == this.blocks[(var2 * this.height + var3) * this.width + var1]) {
return false;
} else {
this.blocks[(var2 * this.height + var3) * this.width + var1] = (byte)var4;
return true;
}
} else {
return false;
}
} |
b3fcf1e3-07bd-40cf-aa3a-17121cb9a698 | 4 | public int[] bigPower(int pN, int pn){
int[] number = new int[(int) Math.ceil(Math.log10(pN)*pn) + 1];
java.util.Arrays.fill(number,0);
number[0]=pN;
for(int n = 1; n < pn; n++){
for(int i = 0; i < number.length; i++){
number[i] = number[i]*2;
}
for(int j=0;j<number.length;j++){
if(number[j]>=10){
number[j+1]+=(number[j]/10);
number[j]=number[j]%10;
}
}
}
return number;
} |
788f37af-77e1-4494-9263-be883f56aea2 | 1 | public void sendMessage(Message msg){
try{
b.writeObject(msg);
}catch(Exception e){
e.printStackTrace();
}
} |
5745be07-197f-4074-9362-2324a1e2d05a | 3 | protected boolean isVector (double x, double y, double z) {
if(x != 0 && y != 0 && z != 0) {
return true;
}
return false;
} |
dafd4f84-4003-4532-acbd-8254d06a0001 | 5 | public static int getRegimeOfGame(){
Scanner scanner = new Scanner(System.in);
int regimeOfGame = 0;
System.out.println("Please choose regime of game:");
System.out.println("1 - Two players on one computer");
System.out.println("2 - Player vs computer");
System.out.println("3 - Two players using internet");
while (true){
if(scanner.hasNextInt()) {
regimeOfGame = scanner.nextInt();
if(regimeOfGame == Game.getOnePlayerGameRegime() || regimeOfGame == Game.getTwoPlayersGameRegime() || regimeOfGame == Game.getTwoPlayersOnlineGameRegime()){
return regimeOfGame;
} else {
System.out.println("Wrong data, please try again");
}
}
}
} |
5b69ffef-5475-45eb-a72e-4dc6fdde1c93 | 9 | public static void TrieIntTreeDemo() {
TrieTreeAPI<Integer> api = new TrieTreeAPI<Integer>() {
@Override
public Integer[] toArray(Object integer) {
String valueStr = integer.toString();
char[] valueChars = valueStr.toCharArray();
Integer[] value = new Integer[valueChars.length];
for(int i=0;i<value.length;i++) {
value[i] = valueChars[i] - '0';
}
return value;
}
};
while(true) {
System.out.println("Help: <commond> <item>");
System.out.println("Commond: [insert, search, delete]");
Scanner scanner = new Scanner(System.in);
String[] input = scanner.nextLine().trim().split(" ");
if(input.length == 2) {
String commond = input[0].toLowerCase().trim();
Integer value = Integer.parseInt(input[1]);
boolean result = false;
if("insert".equals(commond)) {
result = api.insert(value);
} else if("search".equals(commond)) {
result = api.search(value);
} else if("delete".equals(commond)) {
result = api.delete(value);
}
String resultStr = (result)? "Success" : "Failure";
System.out.println("Result: " + resultStr);
} else if(input.length==1 && "exit".equals(input[0].toLowerCase().trim())) {
break;
} else {
System.out.println("Wrong commond.");
}
}
} |
917785c1-c806-4c8f-9488-487c944313f0 | 5 | public void update() {
if(!stallListen) {
up = Keys[KeyEvent.VK_UP] || Keys[KeyEvent.VK_W];
down = Keys[KeyEvent.VK_DOWN] || Keys[KeyEvent.VK_S];
left = Keys[KeyEvent.VK_LEFT] || Keys[KeyEvent.VK_A];
right = Keys[KeyEvent.VK_RIGHT] || Keys[KeyEvent.VK_D];
}
} |
d8dd9f00-0367-4d1b-b067-fdeb3ae69de4 | 4 | public boolean find(int value) {
System.out.println("happen " + this.value);
if (value == this.value) {
return true;
} else if (value > this.value) {
if (right == null)
return false;
return right.find(value);
} else {
if (left == null)
return false;
return left.find(value);
}
} |
4f4cf409-511b-442a-b9ae-a6f4b56b5cdf | 7 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(anteriorBt)) {
anterior();
} else if (e.getSource().equals(proximoBt)) {
proximo();
} else if (e.getSource().equals(gravarBt)) {
gravar();
} else if (e.getSource().equals(apagarBt)) {
apagar();
} else if (e.getSource().equals(novoBt)) {
novo();
} else if (e.getSource().equals(buscarBt)) {
buscar();
} else if (e.getSource().equals(editarBt)) {
editar();
}
} |
78f777c8-56a4-434c-8817-af1667296e81 | 0 | public String get(String key){
return configproperty.get(key);
} |
dcf81ad9-37f4-4fbe-920f-154cf09f5452 | 6 | private void updateTopBottom(int myRoot, int destRoot) {
if (toTop[myRoot]) {
toTop[destRoot] = true;
} else if (toTop[destRoot]) {
toTop[myRoot] = true;
}
if (toBottom[myRoot]) {
toBottom[destRoot] = true;
} else if (toBottom[destRoot]) {
toBottom[myRoot] = true;
}
if (toTop[myRoot] && toBottom[myRoot]) {
percolates = true;
}
} |
2b5b03d1-7f69-43c6-b2c3-7178d46a04ff | 0 | @Override
public String toString() {
return "{VirtualReplayGain}";
} |
5ee07e97-e66c-4a6c-a7ee-4a99e6fbca4c | 0 | public static void main(String[] args)
{
Grammar g=new ContextFreeGrammar();
Production[] p=new Production[5];
/* p[0]=new Production("S","bAC");
p[1]=new Production("A","C");
p[2]=new Production("A","a");
p[3]=new Production("B","bAE");
p[4]=new Production("C","cC");
p[5]=new Production("C","B");
p[6]=new Production("C","");
p[7]=new Production("E","cE");
p[8]=new Production("D","dFA");
p[9]=new Production("F","e");*/
p[0]=new Production("S","aSb");
p[1]=new Production("S","bB");
p[2]=new Production("B","bbB");
p[3]=new Production("B","");
p[4]=new Production("S","SS");
g.addProductions(p);
ArrayList <Production> result=new ArrayList <Production>();
result.add(new Production("S","AD"));
result.add(new Production("A","a"));
result.add(new Production("D","SC"));
result.add(new Production("S","CS"));
result.add(new Production("C","b"));
result.add(new Production("S","SS"));
result.add(new Production("S","b"));
result.add(new Production("S","b"));
result.add(new Production("C","b"));
/*result.add(new Production("D","c"));
result.add(new Production("C","c"));*/
CYKTracer ct=new CYKTracer(g, result);
ct.traceBack();
} |
4711c939-f9bc-460c-a2a1-600b2b0a2d1e | 5 | @Test
public void deepMiddleTest() {
IntArray arr = IntArray.from(
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26);
for(int i = 8; i >= 6; i--) {
arr = arr.remove(i);
}
for(int i = 15; i >= 9; i--) {
arr = arr.remove(i - 3);
}
assertEquals(
IntArray.from(0, 1, 2, 3, 4, 5, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26), arr);
IntArray arr2 = IntArray.from(
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
for(int i = 4; i >= 0; i--) arr2 = arr2.cons(i);
for(int i = 31; i <= 35; i++) arr2 = arr2.snoc(i);
for(int i = 22; i >= 16; i--) arr2 = arr2.remove(i);
assertEquals(
IntArray.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35),
arr2);
} |
fe434f56-fa3b-4171-884f-da6eb0e6cf2f | 9 | public boolean exists(){
String path = Directory.toString();
//Special case for a directory whose path represents a server name (e.g. "\\192.168.0.1")
if (isWindows && path.startsWith("\\\\")){
if (path.endsWith(PathSeparator)) path = path.substring(0, path.length()-1);
if (!path.substring(2).contains(PathSeparator)){
boolean doNetUse = false;
if (File.loadDLL()){
try{
File.GetSharedDrives(path.substring(2));
return true;
}
catch(Exception e){
if (e.getMessage().trim().equals("53")){
return false;
}
else{
doNetUse = true;
}
}
}
else{
doNetUse = true;
}
if (doNetUse){
javaxt.io.Shell cmd = new javaxt.io.Shell("net view " + path);
cmd.run();
java.util.List errors = cmd.getErrors();
errors.remove(null);
if (errors.isEmpty()){
return true;
}
else{
return false;
}
}
}
}
return Directory.exists();
} |
7dffe130-ccbf-4dad-a912-20e28738193d | 3 | @Override
public double[] get2DData(int px, int pz, int sx, int sz)
{
double[] sa = a.get2DData(px, pz, sx, sz);
double[] sb = b.get2DData(px, pz, sx, sz);
double[] sw = weight.get2DData(px, pz, sx, sz);
int s = sx*sz;
for(int i = 0; i < s; i++)
{
double w = sw[i];
if(w < 0) w = 0;
if(w > 1) w = 1;
double va = sa[i];
double vb = sb[i];
sa[i] = va * w + vb*(1-w);
}
return sa;
} |
e968efb4-82b5-4ffa-8440-915da5779db1 | 7 | public boolean compleixRes(Clausula c, ClausulaNom cn) {
String d = cn.getDia();
Integer h = cn.getHora();
int g = c.getGrup();
if(h !=-1 && dia != null){
if (!CompleixResDiaHora(c.getAssignatura(), g, d, h)) return false;
}
else if(dia!=null){
if (!compleixResDia(c.getAssignatura(), g, d)) return false;
}
else if(h != -1){
if (!compleixResHora(c.getAssignatura(), g, h)) return false;
}
return true;
} |
6d64e679-58a1-482c-9699-abdde7924e2a | 4 | @Override
public Operation simplify() {
Expression L = Simplify.mod(this.L);
Expression R = Simplify.mod(this.R);
if ( "1.0".equals(R.getString()) ){
return L.operation;
} else if ( "0.0".equals(L.getString()) ){
return new Number(0);
} else if ( "x".equals(L.getString()) && "x".equals(R.getString()) ) {
return new Number(1);
}else {
return new Quotient( L, R );
}
} |
53398f37-038c-40e1-a42f-f3d1e1c0c0b8 | 9 | private void setLanguageComboBox(JComboBox comboBox) {
ItemListener[] il = comboBox.getItemListeners();
for (ItemListener i : il)
comboBox.removeItemListener(i);
if (Locale.getDefault().equals(Locale.US))
comboBox.setSelectedIndex(0);
else if (Locale.getDefault().equals(Locale.CHINA))
comboBox.setSelectedIndex(1);
else if (Locale.getDefault().equals(Locale.TAIWAN))
comboBox.setSelectedIndex(2);
else if (Locale.getDefault().equals(new Locale("ru")))
comboBox.setSelectedIndex(3);
else if (Locale.getDefault().equals(new Locale("iw")))
comboBox.setSelectedIndex(4);
else if (Locale.getDefault().equals(new Locale("no")))
comboBox.setSelectedIndex(5);
else if (Locale.getDefault().equals(new Locale("es")))
comboBox.setSelectedIndex(6);
for (ItemListener i : il)
comboBox.addItemListener(i);
} |
d2d96722-1317-43a2-9015-e962af30ca5c | 3 | public static void main(String[] args) {
try {
Configuration configuration = new Configuration();
configuration
.set("header",
"id,tstamp,Queue Time,Hold Time,Talk Time,Agent Skill,Agent Tenure,Case Severity,Answer Within Service Level,Brand,Case Status,Product,Vendor,Location,Customer Satisfaction,Satisfaction with Agent,Brand - Satisfaction,Repurchase Likelihood,Recommend Likelihood,Problem Resolution,First Contact Resolution,Resolved within 2");
Job job = new Job(configuration);
job.setJarByClass(MetaData.class);
job.setJobName("Meata Data for valiables");
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(MetaDataMapper.class);
job.setReducerClass(MetaDataReducer.class);
job.waitForCompletion(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
6d92a493-39bc-4a2a-808b-ab3954b2b868 | 6 | @RequestMapping(value = "/hello2/{names}/{ages}", method = RequestMethod.GET)
@ResponseBody
public String testMatrixVariable(@MatrixVariable(pathVar = "names", required = false, defaultValue = ValueConstants.DEFAULT_NONE) Map<String, List<String>> names, @MatrixVariable(pathVar = "ages", required = false) Map<String, List<String>> ages) {
StringBuilder str = new StringBuilder();
if (null != names) {
Set<Entry<String, List<String>>> iter = names.entrySet();
str.append("name{");
for (Entry<String, List<String>> item : iter) {
str.append(item.getKey() + "==");
for (String subitem : item.getValue()) {
str.append(subitem + ",");
}
str.append(";");
}
}
str.append("}age{");
if (null != ages) {
System.out.println(ages);
Set<Entry<String, List<String>>> iter2 = ages.entrySet();
for (Entry<String, List<String>> item : iter2) {
str.append(item.getKey() + "==");
for (String subitem : item.getValue()) {
str.append(subitem + ",");
}
str.append(";");
}
}
str.append("}");
return str.toString();
} |
286e16dc-c1ae-451f-b10d-a808b6dc994e | 1 | @Override
public void remove(ClienteBean oClienteBean) throws Exception {
try {
oMysql.conexion(enumTipoConexion);
oMysql.removeOne(oClienteBean.getId(), "cliente");
oMysql.desconexion();
} catch (Exception e) {
throw new Exception("ClienteDao.removeCliente: Error: " + e.getMessage());
} finally {
oMysql.desconexion();
}
} |
66abd572-21f0-4cb3-990d-5a9a61b675da | 5 | @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBorderCollision(PlayerMoveEvent event) {
Player player = event.getPlayer();
User user = EdgeCoreAPI.userAPI().getUser(player.getName());
Location location = player.getLocation().clone();
Location spawnLoc = player.getWorld().getHighestBlockAt(player.getWorld().getSpawnLocation()).getLocation();
// Check if user exists and it's level > Architect
if (user != null) {
if (!Level.canUse(user, Level.ARCHITECT)) {
// Get radius and distance to radius
int radius = WorldManager.getInstance().getWorldBorder();
double distance = location.distanceSquared(spawnLoc);
if (distance >= Math.pow(radius, 2)) {
// Check if the player's in a vehicle
Entity vehicle = player.getVehicle();
// Let the player leave the vehicle
if (vehicle != null) {
player.leaveVehicle();
/*
* If the vehicle is an instance of LivingEntity (like horse or pig), teleport it to the from-location
* If not, remove the entity
*/
if (!(vehicle instanceof LivingEntity)) {
vehicle.remove();
} else {
event.setTo(event.getFrom());
player.sendMessage(EdgeCoreAPI.languageAPI().getColoredMessage(user.getLanguage(), "radiusreached"));
}
}
// Finally, after all checks, teleport the player to the location it's coming from and let him know why
Vector playerVec = player.getLocation().toVector().clone();
Vector spawnVec = spawnLoc.toVector().clone();
Vector directionToSpawn = playerVec.clone().subtract(spawnVec).normalize();
Vector nextPos = playerVec.add(directionToSpawn.clone().multiply(3));
event.setTo(new Location(event.getFrom().getWorld(), nextPos.getBlockX(), nextPos.getBlockY(), nextPos.getBlockZ()));
player.sendMessage(EdgeCoreAPI.languageAPI().getColoredMessage(user.getLanguage(), "radiusreached"));
}
}
}
} |
4b87d46b-115e-4509-968a-3db2dc2a85bb | 1 | @Override
public String toString() {
StringBuffer s = new StringBuffer();
int counter = 0;
for (MatterInterval mi : intervals) {
s.append("" + (counter++) + " : ");
s.append(mi.toString() + "\n");
}
return s.toString();
} |
20489396-171d-428a-b671-2accfac3c4f2 | 7 | public Card[] contains(Hand h)
{
Card[] nums = {null, null};
for(int i = 0; i < deck.size(); i++)
if(deck.get(i).getValue() == h.getCard(0).getValue())
for(int j = 0; j < deck.size(); j++)
if(deck.get(j).getValue() == h.getCard(1).getValue() && i != j)
if(h.getCard(0).getSuit() != h.getCard(1).getSuit() || deck.get(j).getSuit() == deck.get(i).getSuit())
{
//System.out.println("Contains: " + deck.get(i).toString() + " " + deck.get(j).toString());
nums[0] = deck.get(i);
nums[1] = deck.get(j);
return nums;
}
return nums;
} |
56ceb03b-82e5-4bf6-9aa1-fd9cd793bdb8 | 5 | public void updateDeletePicturefromAlbum(String filePath){
this.albumDao.deletePicture(filePath);
String albumName = "";
for(PictureObject f: pictureList){
if(f.getPath().equals(filePath))
pictureList.remove(f);
albumName = f.getAlbum().getAlbumName();
}
files.setPictureList(pictureList);
if(albumName.equals("")){
for(AlbumObject f:albumList){
if(f.getAlbumName().equals(albumName))
albumList.remove(f);
}
files.setAlbumList(albumList);
}
} |
2808de86-ea61-49f3-86c3-6be34a0e89b5 | 4 | @SuppressWarnings({ "unchecked", "rawtypes" })
public Generator() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("ASM Generator");
setBounds(100, 100, 500, 351);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Etiquetas");
lblNewLabel.setFont(new Font("Lucida Console", Font.PLAIN, 11));
lblNewLabel.setBounds(10, 26, 74, 14);
contentPane.add(lblNewLabel);
final
JComboBox cbLabel = new JComboBox(Listcombobox);
cbLabel.setBounds(84, 22, 51, 20);
contentPane.add(cbLabel);
JLabel lblOrg = new JLabel("ORG");
lblOrg.setBounds(10, 67, 46, 14);
contentPane.add(lblOrg);
final
JComboBox cbOrg = new JComboBox(ListDir);
cbOrg.setBounds(47, 64, 51, 20);
contentPane.add(cbOrg);
JLabel lblNewLabel_1 = new JLabel("DS");
lblNewLabel_1.setBounds(127, 67, 46, 14);
contentPane.add(lblNewLabel_1);
final
JComboBox cbDS = new JComboBox(ListDir);
cbDS.setBounds(156, 64, 51, 20);
contentPane.add(cbDS);
JLabel lblDc = new JLabel("DC");
lblDc.setBounds(234, 67, 46, 14);
contentPane.add(lblDc);
final
JComboBox cbDC = new JComboBox(ListDir);
cbDC.setBounds(254, 64, 51, 20);
contentPane.add(cbDC);
final
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setMinimum(0);
progressBar.setBounds(159, 284, 146, 19);
contentPane.add(progressBar);
final
JLabel label = new JLabel("");
label.setBounds(317, 284, 130, 19);
contentPane.add(label);
JLabel lblEqu = new JLabel("EQU");
lblEqu.setBounds(332, 67, 46, 14);
contentPane.add(lblEqu);
final
JComboBox cbEQ = new JComboBox(ListDir);
cbEQ.setBounds(360, 64, 51, 20);
contentPane.add(cbEQ);
final
JComboBox cbInh = new JComboBox(Listcombobox);
cbInh.setBounds(47, 112, 51, 20);
contentPane.add(cbInh);
final
JComboBox cbDir = new JComboBox(Listcombobox);
cbDir.setBounds(135, 112, 51, 20);
contentPane.add(cbDir);
final
JComboBox cbExt = new JComboBox(Listcombobox);
cbExt.setBounds(229, 112, 51, 20);
contentPane.add(cbExt);
final
JComboBox cbImm8 = new JComboBox(Listcombobox);
cbImm8.setBounds(327, 112, 51, 20);
contentPane.add(cbImm8);
final
JComboBox cbImm16 = new JComboBox(Listcombobox);
cbImm16.setBounds(431, 112, 51, 20);
contentPane.add(cbImm16);
final
JComboBox cb5 = new JComboBox(Listcombobox);
cb5.setBounds(69, 160, 51, 20);
contentPane.add(cb5);
final
JComboBox cbPre = new JComboBox(Listcombobox);
cbPre.setBounds(229, 160, 51, 20);
contentPane.add(cbPre);
final
JComboBox cbAcum = new JComboBox(Listcombobox);
cbAcum.setBounds(360, 160, 51, 20);
contentPane.add(cbAcum);
final
JComboBox cb9 = new JComboBox(Listcombobox);
cb9.setBounds(69, 194, 51, 20);
contentPane.add(cb9);
final
JComboBox cb16 = new JComboBox(Listcombobox);
cb16.setBounds(201, 194, 51, 20);
contentPane.add(cb16);
final
JComboBox cbIDX2 = new JComboBox(Listcombobox);
cbIDX2.setBounds(314, 194, 51, 20);
contentPane.add(cbIDX2);
final
JComboBox cbDIDX = new JComboBox(Listcombobox);
cbDIDX.setBounds(431, 194, 51, 20);
contentPane.add(cbDIDX);
final
JComboBox cbRel8 = new JComboBox(Listcombobox);
cbRel8.setBounds(47, 242, 51, 20);
contentPane.add(cbRel8);
final
JComboBox cbRel16 = new JComboBox(Listcombobox);
cbRel16.setBounds(214, 242, 51, 20);
contentPane.add(cbRel16);
final
JComboBox cbRel9 = new JComboBox(Listcombobox);
cbRel9.setBounds(360, 242, 51, 20);
contentPane.add(cbRel9);
ReadFile();
//System.out.println(" "+ Inst.elementAt(591)); //We test the Vector!
//########## Button Generate, Where almost all the Magic Stuff is.... #############
final JButton btnGenerate = new JButton("Generate!");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int noInh = (Integer) cbInh.getSelectedItem();
int noDir = (Integer) cbDir.getSelectedItem();
int noExt = (Integer) cbExt.getSelectedItem();
int noImm8 = (Integer) cbImm8.getSelectedItem();
int noImm16 = (Integer) cbImm16.getSelectedItem();
int noIDX5 = (Integer) cb5.getSelectedItem();
int noIDX9 = (Integer) cb9.getSelectedItem();
int noIDX16 = (Integer) cb16.getSelectedItem();
int noIdxPre = (Integer) cbPre.getSelectedItem();
int noIdxAcum = (Integer) cbAcum.getSelectedItem();
int noIDX2 = (Integer) cbIDX2.getSelectedItem();
int noDIDX = (Integer) cbDIDX.getSelectedItem();
int noREL8 = (Integer) cbRel8.getSelectedItem();
int noREL16 = (Integer) cbRel16.getSelectedItem();
int noREL9 = (Integer) cbRel9.getSelectedItem();
Integer noLabls = (Integer) cbLabel.getSelectedItem();
Integer noInst = noInh + noDir + noExt + noImm8 + noImm16 + noIDX5 + noIDX9 + noIDX16 + noIdxPre + noIdxAcum + noIDX2 + noDIDX + noREL8 + noREL16 + noREL9;
Integer noOper = noDir + noExt + noImm8 + noImm16 + noIDX5 + noIDX9 + noIDX16 + noIdxPre + noIdxAcum + noIDX2 + noDIDX + noREL8 + noREL16 + noREL9;
Integer noORG = (Integer) cbOrg.getSelectedItem();
Integer noDS = (Integer) cbDS.getSelectedItem();
Integer noDC = (Integer) cbDC.getSelectedItem();
Integer noEQ = (Integer) cbEQ.getSelectedItem();
/* Let's see what the ComboBox has return?
*
System.out.println(" "+cbOper.getSelectedItem());
System.out.println(" "+cbInst.getSelectedItem());
System.out.println(" "+cbLabel.getSelectedItem());
*/
if(noOper > noInst)
{
JOptionPane.showMessageDialog(null, "Mas Operandos que Instrucciones","ERROR",
JOptionPane.ERROR_MESSAGE);
}
else
if (noLabls > (noInst + noORG + noDS + noDC) )
{
JOptionPane.showMessageDialog(null, "Mas Etiquetas que Instrucciones","ERROR",
JOptionPane.ERROR_MESSAGE);
}
else
{
int getMax = progressBar.getMaximum();
int value = progressBar.getValue();
while(value < getMax)
{
progressBar.setValue(value + 1);
value++;
try {
Thread.sleep(2);
}
catch (InterruptedException ex){}
}
String FileName = WriteFile(noLabls, noInst, noOper, noORG, noDS, noDC, noEQ, noInh, noDir, noExt, noImm8, noImm16, noIDX5, noIDX9, noIDX16, noIdxPre, noIdxAcum, noIDX2, noDIDX, noREL8, noREL16, noREL9 );
label.setText("Name: "+FileName);
btnGenerate.setEnabled(false);
}
}
});
btnGenerate.setBounds(47, 281, 89, 23);
contentPane.add(btnGenerate);
JLabel lblDirectivas = new JLabel("DIRECTIVAS");
lblDirectivas.setBounds(191, 39, 74, 14);
contentPane.add(lblDirectivas);
JLabel lblSimples = new JLabel("SIMPLES");
lblSimples.setBounds(196, 95, 56, 14);
contentPane.add(lblSimples);
JLabel lblInh = new JLabel("INH");
lblInh.setBounds(22, 115, 46, 14);
contentPane.add(lblInh);
JLabel lblDir = new JLabel("DIR");
lblDir.setBounds(113, 115, 46, 14);
contentPane.add(lblDir);
JLabel lblExt = new JLabel("EXT");
lblExt.setBounds(206, 115, 46, 14);
contentPane.add(lblExt);
JLabel lblImm = new JLabel("IMM8");
lblImm.setBounds(292, 115, 46, 14);
contentPane.add(lblImm);
JLabel lblImm_1 = new JLabel("IMM16");
lblImm_1.setBounds(390, 115, 46, 14);
contentPane.add(lblImm_1);
JLabel lblIndexados = new JLabel("INDEXADOS");
lblIndexados.setBounds(191, 143, 74, 14);
contentPane.add(lblIndexados);
JLabel lblIdx = new JLabel("IDX 5Bits");
lblIdx.setBounds(10, 163, 58, 14);
contentPane.add(lblIdx);
JLabel lblIdxPrepost = new JLabel("IDX Pre/Post");
lblIdxPrepost.setBounds(156, 163, 74, 14);
contentPane.add(lblIdxPrepost);
JLabel lblIdxAcum = new JLabel("IDX Acum");
lblIdxAcum.setBounds(304, 163, 74, 14);
contentPane.add(lblIdxAcum);
JLabel lblIdx_1 = new JLabel("IDX1 9Bits");
lblIdx_1.setBounds(10, 197, 62, 14);
contentPane.add(lblIdx_1);
JLabel lblIdxbits = new JLabel("IDX2 16Bits");
lblIdxbits.setBounds(133, 197, 74, 14);
contentPane.add(lblIdxbits);
JLabel lblidx = new JLabel("[IDX2]");
lblidx.setBounds(276, 197, 62, 14);
contentPane.add(lblidx);
JLabel lbldidx = new JLabel("[D,IDX]");
lbldidx.setBounds(385, 197, 62, 14);
contentPane.add(lbldidx);
JLabel lblRelativos = new JLabel("RELATIVOS");
lblRelativos.setBounds(191, 225, 74, 14);
contentPane.add(lblRelativos);
JLabel lblRel = new JLabel("REL8");
lblRel.setBounds(10, 245, 46, 14);
contentPane.add(lblRel);
JLabel lblRel_1 = new JLabel("REL16");
lblRel_1.setBounds(172, 245, 46, 14);
contentPane.add(lblRel_1);
JLabel lblRel_2 = new JLabel("REL9");
lblRel_2.setBounds(317, 245, 46, 14);
contentPane.add(lblRel_2);
JSeparator separator = new JSeparator();
separator.setBounds(10, 92, 472, 2);
contentPane.add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(10, 143, 472, 2);
contentPane.add(separator_1);
JSeparator separator_2 = new JSeparator();
separator_2.setBounds(10, 222, 472, 2);
contentPane.add(separator_2);
} |
0176ba31-8799-499b-8599-be6455fdeb3c | 8 | public Card draw(boolean from_throwpile)
{
synchronized(Rummy.this)
{
if (Rummy.this.getCurrentPlayer() != p.getPlayer())
return null;
}
if ((player_state != PlayerState.EXPECTING_DRAW) && (player_state != PlayerState.DEALING))
return null;
Card c = null;
if (!hand.holdingExtraCards())
{
if (from_throwpile)
c = throw_pile.pop();
else
c = game_deck.draw();
if (from_throwpile)
Rummy.this.sendEventToPlayers(new CardEvent(RummyEvents.DRAW_FROM_PILE, c), Rummy.this.current_player);
else
Rummy.this.sendEventToPlayers(new RummyEvent(RummyEvents.DRAW_FROM_DECK), Rummy.this.current_player);
try {
hand.add(c);
}
catch (Exception e)
{
e.printStackTrace();
}
}
if (player_state != PlayerState.DEALING)
player_state = PlayerState.EXPECTING_DISCARD;
return c;
} |
e6eec4ae-3232-4147-89e6-eb70068371cb | 2 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
String nome = jTextField1.getText();
String descricao = jTextArea1.getText();
int ano = Integer.parseInt(jTextField3.getText());
double valor = Double.parseDouble(jTextField4.getText());
Fachada f = Sistema.getInstance();
if (f.cadastrarModelo(nome, descricao, ano, valor)) {
JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!");
dispose();
} else {
JOptionPane.showMessageDialog(null, "Cadastro não realizado!");
}
} catch (NumberFormatException | HeadlessException e) {
JOptionPane.showMessageDialog(null, "O campo telefone precisa ser número!");
}
}//GEN-LAST:event_jButton1ActionPerformed |
cd164acc-4e79-4870-bec8-bf8a059ecc38 | 8 | private Constant parseMemberLookup(byte refKind, List<Object> args) {
// E.g.: lookup().findStatic(Foo.class, "name", MethodType)
if (args.size() != 4) return null;
int argi = 0;
if (!"lookup".equals(args.get(argi++))) return null;
short cindex, ntindex, nindex, tindex;
Object con;
if (!isConstant(con = args.get(argi++), CONSTANT_Class)) return null;
cindex = (short)((Constant)con).index;
if (!isConstant(con = args.get(argi++), CONSTANT_String)) return null;
nindex = ((Constant)con).itemIndex();
if (isConstant(con = args.get(argi), CONSTANT_MethodType) ||
isConstant(con, CONSTANT_Class)) {
tindex = ((Constant)con).itemIndex();
} else return null;
ntindex = (short) cf.pool.addConstant(CONSTANT_NameAndType,
new Short[]{ nindex, tindex }).index;
byte reftag = CONSTANT_Method;
if (refKind <= REF_putStatic)
reftag = CONSTANT_Field;
else if (refKind == REF_invokeInterface)
reftag = CONSTANT_InterfaceMethod;
Constant ref = cf.pool.addConstant(reftag, new Short[]{ cindex, ntindex });
return cf.pool.addConstant(CONSTANT_MethodHandle, new Object[]{ refKind, (short)ref.index });
} |
63752bd7-8289-4346-b202-e56988c05512 | 3 | public String toString() {
if (this == UNINITIALIZED_VALUE) {
return ".";
} else if (this == RETURNADDRESS_VALUE) {
return "A";
} else if (this == REFERENCE_VALUE) {
return "R";
} else {
return type.getDescriptor();
}
} |
9d4186a4-d921-4feb-b7cf-4a86a7948333 | 8 | @Override
public void run() {
if (SwingUtilities.isEventDispatchThread() == false) {
long WAIT = 1500;
while ((System.currentTimeMillis() - this.myStamp) < WAIT) {
try {
long delay = WAIT - (System.currentTimeMillis() - this.myStamp);
if (delay < 1) {
delay = 1;
}
Thread.sleep(delay);
} catch (Exception e) {
Thread.yield();
}
}
SwingUtilities.invokeLater(this);
return;
}
if (this.myStamp != ColorPicker.this.hexDocListener.lastTimeStamp) {
// another event has come along and trumped this one
return;
}
if (this.text.length() > 6) {
this.text = this.text.substring(0, 6);
}
while (this.text.length() < 6) {
this.text = this.text + "0";
}
if (ColorPicker.this.hexField.getText().equals(this.text)) {
return;
}
int pos = ColorPicker.this.hexField.getCaretPosition();
ColorPicker.this.hexField.setText(this.text);
ColorPicker.this.hexField.setCaretPosition(pos);
} |
3c351c42-e535-4322-a28d-84747add4623 | 5 | public int read( ) throws IOException
{
String bits = "";
int bit;
int decode;
while( true )
{
bit = bin.readBit( );
if( bit == -1 )
throw new IOException( "Unexpected EOF" );
bits += bit;
decode = codeTree.getChar( bits );
if( decode == HuffmanTree.INCOMPLETE_CODE )
continue;
else if( decode == HuffmanTree.ERROR )
throw new IOException( "Decoding error" );
else if( decode == HuffmanTree.END )
return -1;
else
return decode;
}
} |
38678f39-cef8-4337-88d1-87857b2401a4 | 9 | public List<OSMWay> readWaysFromOSMFile(Document doc) {
List<OSMWay> osmWays = new ArrayList<OSMWay>();
NodeList waysList = doc.getElementsByTagName("way");
// NOTICE: don't put this into condition part of a for-loop,
// because getLength() is a O(n) function.
int length = waysList.getLength();
// load all ways from the osm file
for (int i = 0; i < length; i++) {
Node item = waysList.item(i);
NamedNodeMap attrsMap = waysList.item(i).getAttributes();
String wayID = attrsMap.getNamedItem("id").getNodeValue();
// read the 'tags' and 'refs' of this way
Map<String, String> tags = readTagMapFromOSMFile(item);
List<String> refs = readRefsOfWayFromOSMFile(item);
// String highway = tags.get("highway");
// String railway = tags.get("railway");
if (tags.get("highway") == null) continue;
String[] labels = tags.get("highway").split("_");
String highway = labels[0];
int level = 0;
if (highway.equals("motorway")) { level = 1; }
else if (highway.equals("primary")) { level = 2; }
else if (highway.equals("secondary")) { level = 3; }
else if (highway.equals("tertiary")) { level = 4; }
else if (highway.equals("trunk")) { level = 5; }
else if (highway.equals("residential")) { level = 6; }
// if (((highway != null)
// && !highway.equals("footway")
// && !highway.equals("cycleway")
// && !highway.equals("pedestrian")
// // if want to only use primary streets, uncomment this
// // condition.
// // && !highway.equals("residential")
// && !highway.equals("service")
// && !highway.equals("unclassified")
// && !highway.equals("platform")
// && !highway.equals("access_ramp")
// && !highway.equals("steps")
// && !highway.equals("path"))) {
// // || ((railway != null) && !railway.equals("tram"))) {
// osmWays.add(new OSMWay(wayID, refs, tags));
// }
if (level != 0) {
osmWays.add(new OSMWay(wayID, refs, tags, level));
}
}
return osmWays;
} |
256f15ac-26b9-40ad-8d13-d17615f8c886 | 6 | @Override
protected void addNewChildrenToOpen(SearchNode parent)
{
boolean[] percepts = board.getPercepts(parent.location.x, parent.location.y);
int danger = 0;
for(int i = 0; i < 2; i++)
if(percepts[i])
danger++;
Point location = parent.getLocation();
SearchNode node = createSearchNode(location.x, location.y - 1, parent);
if(canAdd(node.toString()))
{
open.add(node);
}
addDanger(node, danger);
node = createSearchNode(location.x + 1, location.y, parent);
if(canAdd(node.toString()))
{
open.add(node);
}
addDanger(node, danger);
node = createSearchNode(location.x, location.y + 1, parent);
if(canAdd(node.toString()))
{
open.add(node);
}
addDanger(node, danger);
node = createSearchNode(location.x - 1, location.y, parent);
if(canAdd(node.toString()))
{
open.add(node);
}
addDanger(node, danger);
} |
f3d07421-86f9-47b7-92c3-0a99af0d1da3 | 5 | private void updateTabla(){
//** pido los datos a la tabla
Object[][] vcta = this.getDatos();
//** se colocan los datos en la tabla
DefaultTableModel datos = new DefaultTableModel();
tabla.setModel(datos);
datos = new DefaultTableModel(vcta,colum_names_tabla);
tabla.setModel(datos);
//ajustamos tamaño de la celda Fecha Alta
/*TableColumn columna = tabla.getColumn("Fecha Alta");
columna.setPreferredWidth(100);
columna.setMinWidth(100);
columna.setMaxWidth(100);*/
if (!field_codigo.getText().equals("")){
posicionarAyuda(field_codigo.getText());
}
else{
if ((fila_ultimo_registro-1 >= 0)&&(fila_ultimo_registro-1 < tabla.getRowCount())){
tabla.setRowSelectionInterval(fila_ultimo_registro-1,fila_ultimo_registro-1);
scrollCellToView(this.tabla,fila_ultimo_registro-1,fila_ultimo_registro-1);
cargar_ValoresPorFila(fila_ultimo_registro-1);
}
else{
if ((fila_ultimo_registro+1 >= 0)&&(fila_ultimo_registro+1 <= tabla.getRowCount())){
tabla.setRowSelectionInterval(fila_ultimo_registro,fila_ultimo_registro);
scrollCellToView(this.tabla,fila_ultimo_registro,fila_ultimo_registro);
cargar_ValoresPorFila(fila_ultimo_registro);
}
}
}
} |
c4d043cb-1ca0-47ab-8a20-8826f3f28dea | 6 | @Override
public void caseAProgram(AProgram node)
{
inAProgram(node);
if(node.getPrograma() != null)
{
node.getPrograma().apply(this);
}
if(node.getId() != null)
{
node.getId().apply(this);
}
if(node.getInicio() != null)
{
node.getInicio().apply(this);
}
if(node.getDeclaracao() != null)
{
node.getDeclaracao().apply(this);
}
if(node.getComando() != null)
{
node.getComando().apply(this);
}
if(node.getFim() != null)
{
node.getFim().apply(this);
}
outAProgram(node);
} |
1efd5ffd-1942-47a5-a05a-a2ab9cc32f39 | 1 | @Override
public Long getLongProp(String key, Long value){
Long result = value;
String propValue = getProperty(key);
if (null != propValue){
result = new Long(propValue);
}
return result;
} |
5851a932-3fd6-49b1-8a85-3bb4e4d07b57 | 0 | public int f() {
return 1;
} |
feb6049d-7a0d-47c7-935a-b0dbe88bd3ca | 1 | public File getFile( String fname ) {
JFileChooser fc = new JFileChooser();
fc.setSelectedFile( new File(fname) );
int result = fc.showSaveDialog(new JFrame());
File recvfile;
if (result == JFileChooser.APPROVE_OPTION) {
recvfile = fc.getSelectedFile();
filename = recvfile.getAbsolutePath();
//System.out.println( filename );
jLabel1.setText("接收" + filename);
jLabel2.setText("已完成 0 bytes / " + filesize + " bytes");
return recvfile;
}
else return null;
} |
34b5b130-6b71-47b3-a6c2-48355f721b06 | 8 | @Override
public final void mouseDragged(MouseEvent me)
{
int sliderIndex = 0;
for (TButton slider : sliders)
{
if (slider.inUse)
if (orientation == VERTICAL)
{
slider.y = me.getY() - 12.5f;
if (slider.y < y)
slider.y = y;
else if (slider.y > y + length - 25)
slider.y = y + length - 25;
sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(sliderIndex), sliderIndex));
}
else if (orientation == HORIZONTAL)
{
slider.x = me.getX() - 12.5f;
if (slider.x < x)
slider.x = x;
else if (slider.x > x + length - 25)
slider.x = x + length - 25;
sendTScrollEvent(new TScrollEvent(this, TScrollEvent.TSCROLLBARSCROLLED, getSliderPercent(sliderIndex), sliderIndex));
}
sliderIndex++;
}
} |
6321df34-c6b7-422f-8f03-1ff7d5e9a9e3 | 5 | private static void bootStrap() throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
// print the classpath
// String classPath = System.getProperty("java.class.path");
// System.out.printf("JVM classpath: %s\n", classPath);
System.setProperty("red5.deployment.type", "bootstrap");
System.setProperty("sun.lang.ClassLoader.allowArraySyntax", "true");
// check system property before forcing out selector
//if (System.getProperty("logback.ContextSelector") == null) {
// set to use our logger
//System.setProperty("logback.ContextSelector", "org.red5.logging.LoggingContextSelector");
//}
String policyFile = System.getProperty("java.security.policy");
if (policyFile == null) {
System.setProperty("java.security.debug", "all");
System.setProperty("java.security.policy", String.format("%s/red5.policy", System.getProperty("red5.config_root")));
}
// set the temp directory if we're vista or later
String os = System.getProperty("os.name").toLowerCase();
// String arch = System.getProperty("os.arch").toLowerCase();
// System.out.printf("OS: %s Arch: %s\n", os, arch);
if (os.contains("vista") || os.contains("windows 7")) {
String dir = System.getProperty("user.home");
// detect base drive (c:\ etc)
if (dir.length() == 3) {
// use default
dir += "Users\\Default\\AppData\\Red5";
// make sure the directory exists
File f = new File(dir);
if (!f.exists()) {
f.mkdir();
}
f = null;
} else {
dir += "\\AppData\\localLow";
}
System.setProperty("java.io.tmpdir", dir);
System.out.printf("Setting temp directory to %s%n", System.getProperty("java.io.tmpdir"));
}
/*
* try { // Enable the security manager SecurityManager sm = new
* SecurityManager(); System.setSecurityManager(sm); } catch
* (SecurityException se) {
* System.err.println("Security manager already set"); }
*/
// get current loader
ClassLoader baseLoader = Thread.currentThread().getContextClassLoader();
// build a ClassLoader
ClassLoader loader = ClassLoaderBuilder.build();
// set new loader as the loader for this thread
Thread.currentThread().setContextClassLoader(loader);
// create a new instance of this class using new classloader
Object boot = Class.forName("org.red5.server.Launcher", true, loader).newInstance();
Method m1 = boot.getClass().getMethod("launch", (Class[]) null);
m1.invoke(boot, (Object[]) null);
// not that it matters, but set it back to the original loader
Thread.currentThread().setContextClassLoader(baseLoader);
} |
f7bc17e7-fe00-4bf0-b5c8-06c92885a400 | 4 | public static String selectAccountType(){
Scanner scan = new Scanner(System.in);
do{
System.out.printf("\n***TIPOS DE CUENTA***\n1-%s\n2-%s\n3-%s\nEscoja uno: ",
PLANILLA, NORMAL, VIP);
int opt = scan.nextInt();
switch(opt){
case 1: return PLANILLA;
case 2: return NORMAL;
case 3: return VIP;
default: System.out.println("\033[31mOpcion Incorrecta!");
}
}while(true);
} |
d8b23e27-98c2-4463-8bff-c297104c644e | 5 | public int spaceFor(Service good) {
switch (upgradeForGood(good)) {
case (-1) : return 0 ;
case ( 0) : return 20 ;
case ( 1) : return 35 ;
case ( 2) : return 45 ;
case ( 3) : return 50 ;
}
return 0 ;
} |
dd08bedd-ca8b-4d5f-abd2-5c4133b081b1 | 0 | protected void transitionChange(AutomataTransitionEvent event) {
invalidate();
} |
962e4129-cd9e-4b10-8d8c-5baf1bda0ade | 9 | public static void loadOptionsFile() {
File file = new File("options.ini");
if (file.exists()) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(file));
String tempString;
try {
while ((tempString = br.readLine()) != null) {
if (!tempString.startsWith("#")) {
String delimiter = "[=]";
String[] tempparsed = tempString.split(delimiter);
if (tempparsed.length == 2) {
if (tempparsed[0].equals("langShort")) {
Options.langShort = tempparsed[1];
Utils.loadLocalisedText();
}
if (tempparsed[0].equals("language")) {
Options.language = tempparsed[1];
Utils.loadLocalisedText();
}
if (tempparsed[0].equals("delayLaunchText")) {
Options.delayLaunchText = Integer.parseInt(tempparsed[1]);
}
}
}
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Options.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Options.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
Localisation.determineLanguage();
}
} |
1d7a3812-c8a5-4404-9fb9-1b99ba3c8f5f | 0 | public void setName(String name) {
Name = name;
} |
1f352d7d-9b6f-4174-9f24-6f05c2aac884 | 7 | public GerirEscolasEquipas(AssociacaoEscolasFutebol a) {
this.a = a;
this.a.addObserver(this);
initComponents();
this.setVisible(true);
for (Escola escola : a.getDAOEscola().values()) {
Escola_ComboBox.addItem(escola.getNome());
}
for (Escola escola : a.getDAOEscola().values()) {
Escola_ComboBox1.addItem(escola.getNome());
}
for (Escola escola : a.getDAOEscola().values()) {
Escola_ComboBox2.addItem(escola.getNome());
}
for (Component component : AdicionarJogador_Panel.getComponents()) {
component.setEnabled(false);
}
AdicionarJogador_Panel.setEnabled(false);
for (Component component : DadosJogador_Panel.getComponents()) {
component.setEnabled(false);
}
DadosJogador_Panel.setEnabled(false);
for (Component component : DadosCampo_Panel.getComponents()) {
component.setEnabled(false);
}
DadosCampo_Panel.setEnabled(false);
for (Component component : MoradaCampo_Panel.getComponents()) {
component.setEnabled(false);
}
MoradaCampo_Panel.setEnabled(false);
} |
e183c3d8-0978-4224-abb8-3e1a855ab7ae | 4 | public static String getPlayerFromUUID(final UUID uuid) {
if (uuid == null)
return null;
final Map<UUID, String> players = getPlayers(Arrays.asList(uuid));
if (players == null)
return null;
if (players.isEmpty())
return null;
if (players.get(uuid) == null) {
throw new NullPointerException("Could not get player from UUID " + uuid + "!");
}
return players.get(uuid);
} |
f08b2bef-cbde-45f4-b663-e7d77e9aa7a7 | 1 | @Override
public void fromMessage(Message message) throws JMSException {
try {
inputStream = ((BlobMessage) message).getInputStream();
} catch (IOException e) {
logger.error("Can't get input stream.", e);
}
} |
6159d968-c013-4606-b218-c04a6f933eb5 | 0 | public void setX(int x) {
this.x = x;
} |
0d0af45a-fac6-42d6-adb9-36cafd37ee57 | 6 | public void addNode (int coefficient, int exponent) {
if (head == null) {
head = new Node(coefficient, exponent);
return;
}
if (head.exponent < exponent) {
Node added = new Node(coefficient, exponent);
added.next = head;
head = added;
return;
} else if (head.exponent == exponent) {
head.coefficient += coefficient;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.exponent > exponent) {
current = current.next;
} else if (current.next.exponent < exponent) {
Node added = new Node(coefficient, exponent);
added.next = current.next;
current.next = added;
return ;
} else {
current.next.coefficient += coefficient;
return ;
}
}
current.next = new Node(coefficient, exponent);
} |
a5fd164e-0c23-4f34-8d48-3e446e719b26 | 0 | public void setPerson(PersonBean person) {
this.person = person;
} |
f607d87f-b227-4cc8-a666-fd7d74a1a909 | 9 | public final void parameters() throws RecognitionException {
try {
// Python.g:99:12: ( LPAREN ( varargslist )? RPAREN )
// Python.g:99:14: LPAREN ( varargslist )? RPAREN
{
match(input,LPAREN,FOLLOW_LPAREN_in_parameters261); if (state.failed) return;
// Python.g:99:21: ( varargslist )?
int alt10=2;
int LA10_0 = input.LA(1);
if ( (LA10_0==DOUBLESTAR||LA10_0==LPAREN||LA10_0==NAME||LA10_0==STAR) ) {
alt10=1;
}
switch (alt10) {
case 1 :
// Python.g:99:22: varargslist
{
pushFollow(FOLLOW_varargslist_in_parameters264);
varargslist();
state._fsp--;
if (state.failed) return;
}
break;
}
match(input,RPAREN,FOLLOW_RPAREN_in_parameters268); if (state.failed) return;
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
}
// $ANTLR end "parameters"
// $ANTLR start "varargslist"
// Python.g:102:1: varargslist : ( defparameter ( options {greedy=true; } |
cc0f207e-4038-45a4-a458-141e43346a52 | 6 | @Override
public void run(int interfaceId, int componentId) {
Master master = (Master) player.getTemporaryAttributtes().get(
"SlayerMaster");
if (stage == -1) {
stage = 0;
sendEntityDialogue(SEND_4_OPTIONS, new String[] {
SEND_DEFAULT_OPTIONS_TITLE,
"How many monsters do I have left?",
"Where are you located in the land of "
+ Settings.SERVER_NAME + "?", "Give me a tip.",
"Nothing, Nevermind." }, IS_PLAYER, player.getIndex(), 9827);
} else if (stage == 0) {
if (componentId == 1) {
SlayerTask task = (SlayerTask) player.getTemporaryAttributtes()
.get("SlayerTask");
if (task != null) {
sendEntityDialogue(
SEND_1_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(master
.getMaster()).name,
"You're current assigned to kill "
+ task.getName().toLowerCase()
+ " only " + task.getAmount()
+ " more to go." }, IS_NPC,
master.getMaster(), 9827);
} else {
sendEntityDialogue(
SEND_1_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(master
.getMaster()).name,
"You currently don't have a task, see me to get one." },
IS_NPC, master.getMaster(), 9827);
}
stage = -1;
} else if (componentId == 2) {
sendEntityDialogue(
SEND_1_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(master
.getMaster()).name,
"" + master.getDialouge() + "." }, IS_NPC,
master.getMaster(), 9827);
stage = -1;
} else if (componentId == 3) {
sendEntityDialogue(
SEND_1_TEXT_CHAT,
new String[] {
NPCDefinitions.getNPCDefinitions(master
.getMaster()).name,
"I currently dont have any tips for you now." },
IS_NPC, master.getMaster(), 9827);
stage = -1;
} else {
end();
}
}
} |
262970fb-23dd-496f-8871-4ee4498c24e3 | 5 | public static boolean handleOption(int option, int longind, String arg) {
if (arg == null)
options ^= 1 << option;
else if ("yes".startsWith(arg) || arg.equals("on"))
options |= 1 << option;
else if ("no".startsWith(arg) || arg.equals("off"))
options &= ~(1 << option);
else {
GlobalOptions.err.println("jode.decompiler.Main: option --"
+ longOptions[longind].getName()
+ " takes one of `yes', `no', `on', `off' as parameter");
return false;
}
return true;
} |
316e25f4-4b5c-4ff8-a326-201adbe02929 | 7 | private void checkObstacleBounds(boolean positiveSide, float delta, float half) {
positionCenter = originalCenter + delta;
if (positiveSide) {
positionCorner = Math.abs(originalCorner + delta);
delta = 0.5f * (positionCenter + positionCorner - half);
if (delta > 0) {
positionCenter -= delta;
positionCorner -= delta;
}
else {
delta = 0.5f * (positionCenter - positionCorner + half);
if (delta < 0) {
positionCenter -= delta;
positionCorner += delta;
}
if (positionCenter < -half) {
positionCorner = 0.5f * Obstacle.MIN_THICKNESS;
positionCenter = positionCorner - half;
}
}
}
else {
positionCorner = Math.abs(originalCorner - delta);
// a negative delta means enlargement in the negative zone
delta = 0.5f * (positionCenter - positionCorner + half);
if (delta < 0) {
positionCenter -= delta;
positionCorner += delta;
}
else {
delta = 0.5f * (positionCenter + positionCorner - half);
if (delta > 0) {
positionCenter -= delta;
positionCorner -= delta;
}
if (positionCenter > half) {
positionCorner = 0.5f * Obstacle.MIN_THICKNESS;
positionCenter = half - positionCorner;
}
}
}
} |
808fa6b2-e533-455b-b88d-69b09455ee93 | 1 | private static void drawHistogram(GC gc, int x, int y, int[] histogram, int MAX, int width, int height) {
int gap = 1;
gc.setForeground(Colors.red);
int thickness = 5;
gc.drawRectangle(x - thickness, y - thickness, 256 * gap + 2 * thickness, height + 2 * thickness);
gc.setForeground(Colors.blue);
gc.setLineWidth(1);
for (int i = 0; i < histogram.length; i++) {
int y2 = y + height;
int y1 = y2 - histogram[i] * height / MAX;
gc.drawLine(x + (i * gap), y1, x + (i * gap), y2);
}
} |
f72e2693-cf3c-4443-b2e1-01ced1d4f06e | 3 | public String toString () {
if (!isDisposed () && (parent.getStyle () & SWT.VIRTUAL) != 0 && !cached) {
return "CTableItem {*virtual*}"; //$NON-NLS-1$
}
return super.toString ();
} |
73d36269-728b-4ea8-88ab-9347d0d3dc96 | 3 | private int calcNumberOfNodes(double serialProb, double pow2Prob, double uLow,
double uMed, double uHi, double uProb) {
double u = random.nextDouble();
if (u <= serialProb) {// serial job
return 1;
}
double par = twoStageUniform(uLow, uMed, uHi, uProb);
if (u <= (serialProb + pow2Prob)) { // power of 2 nodes parallel job
par = (int)(par + 0.5); // par = round(par)
}
int numNodes = (int)(Math.pow(2, par) + 0.5); // round(2^par)
int maxNodes = (int)(Math.pow(2, uHi) + 0.5);
return numNodes <= maxNodes ? numNodes : maxNodes;
} |
b478a933-9e1e-4036-85c0-4d195893dcba | 0 | @Override
public void mouseExited(MouseEvent e) {} |
00bc156b-63de-41b5-a81e-c6f719fc3c84 | 3 | Client1() throws IOException {
String s;
System.out.println(getCurrentTime() + "::" +"Starting Client ..");
clientSocket = new Socket("localhost", 38000);
serverIn=new DataInputStream(clientSocket.getInputStream());
serverOut=new DataOutputStream(clientSocket.getOutputStream());
/*--------Reading file from The location specified--------*/
File file = new File("C:/Users/Devi/Documents/scu/COEN233/project/Project/Demo/March9/AmbikaPreethi/src/ClientServer/test1.txt");
/*---- Creating an input stream to get data from file--------*/
DataInputStream bin = null;
try
{
FileInputStream fin = new FileInputStream(file);
bin = new DataInputStream(fin);
/*---- An input stream to receive Patient Data from server----*/
BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
/*-----An output stream to send out the text file to server------*/
DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
/*---------read file using BufferedInputStream------*/
while( bin.available() > 0 ){
@SuppressWarnings("deprecation")
String toserver = bin.readLine();
System.out.println(toserver);
/*------- Send it out to the Server--------*/
serverOut.writeUTF(toserver + '\n');
}
/*--- Reading data sent by server And displaying the output--------*/
String PatientInfo = serverIn.readUTF();
String UpdatedPatientInfo[] = PatientInfo.split(" ");
String PatientId = UpdatedPatientInfo[1];
String PatientFirstName = UpdatedPatientInfo[3];
String PatientLastName = UpdatedPatientInfo[5];
String PatientAge = UpdatedPatientInfo[7];
System.out.println(Client1.getCurrentTime() + "::" +"Patient ID: " +PatientId);
System.out.println("Pateint First Name: "+PatientFirstName);
System.out.println("Patient Last Name "+PatientLastName);
System.out.println("Patient Age: "+PatientAge);
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file " + ioe);
}
} |
1b207fe6-85b6-4878-bd13-10ec30ef5aa3 | 1 | private void downloadIfNeeded(String videoID) throws Exception {
if ( !cacheContains(videoID) )
downloadParseSave(videoID);
} |
c4670369-1e87-4acd-9713-35d632106053 | 4 | private void process_incoming_soap() {
try {
// Copy output stream to input stream to simulate
// coordinated streams over a network connection.
coordinate_streams();
// Create the "received" SOAP message from the
// input stream.
SOAPMessage msg = create_soap_message(in);
// Inspect the SOAP header for the keyword 'time_request'
// and process the request if the keyword occurs.
Name lookup_name = create_qname(msg);
SOAPHeader header = msg.getSOAPHeader();
Iterator it = header.getChildElements(lookup_name);
Node next = (Node) it.next();
String value = (next == null) ? "Error!" : next.getValue();
// If SOAP message contains request for the time, create a
// new SOAP message with the current time in the body.
if (value.toLowerCase().contains("time_request")) {
// Extract the body and add the current time as an element.
String now = new Date().toString();
SOAPBody body = msg.getSOAPBody();
body.addBodyElement(lookup_name).addTextNode(now);
msg.saveChanges();
// Write to the output stream.
msg.writeTo(out);
trace("The received/processed SOAP message:", msg);
}
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
} |
94a48764-281a-404b-99d2-c6a58379ca9a | 0 | ListeTableModel(ArrayList<Metadonnee> listeMetadonnees) {
this.liste = liste;
} |
05f471b2-584b-4200-bc93-65773839f863 | 7 | public static void main(String[] args) {
String jobName = "";
String jobId = null;
// set command line usage
Arguments.usage = usage;
// get command line arguments
Arguments arguments = new Arguments(args);
jobName = arguments.getOptionalArgument("Default Job Name");
System.out.println("jobName: " + jobName);
try {
actuateControl = new ActuateControl(arguments.getURL());
}catch (javax.xml.rpc.ServiceException e){
e.printStackTrace();
}catch (java.net.MalformedURLException e){
e.printStackTrace();
}
// Login
actuateControl.setUsername(arguments.getUsername());
actuateControl.setPassword(arguments.getPassword());
actuateControl.setTargetVolume(arguments.getTargetVolume());
actuateControl.login();
JobScheduleDetail scheduleDetail = new JobScheduleDetail();
//=====Get jobId
JobScheduleCondition[] jobScheduleConditionArray = new JobScheduleCondition[1];
JobScheduleCondition jobScheduleCondition0 = new JobScheduleCondition();
jobScheduleCondition0.setField(com.actuate.schemas.JobScheduleField.JobName);
jobScheduleCondition0.setMatch(jobName);
jobScheduleConditionArray[0]=jobScheduleCondition0;
ArrayOfJobScheduleCondition arrayOfJobScheduleCondition = new ArrayOfJobScheduleCondition();
arrayOfJobScheduleCondition.setJobScheduleCondition(jobScheduleConditionArray);
JobScheduleSearch jobScheduleSearch = new JobScheduleSearch();
jobScheduleSearch.setConditionArray(arrayOfJobScheduleCondition);
SelectJobSchedules selectJobSchedules = new SelectJobSchedules();
selectJobSchedules.setSearch(jobScheduleSearch);
selectJobSchedules.setResultDef( ActuateControl.newArrayOfString(new String[] {"JobID"} ));
try {
SelectJobSchedulesResponse selectJobSchedulesResponse= actuateControl.proxy.selectJobSchedules(selectJobSchedules);
if (!(selectJobSchedulesResponse.getTotalCount()==0)){
jobId = selectJobSchedulesResponse.getJobs().getJobProperties()[0].getJobId();
} else {
System.out.println("Not Found Scheduled Job jobName=<"+jobName+">");
System.exit(0);
}
}
catch (Exception e)
{
e.printStackTrace();
}
// one day offset
Calendar tomorrow = new java.util.GregorianCalendar();
tomorrow.set(Calendar.DATE, tomorrow.get(Calendar.DATE) + 1);
AbsoluteDate date = new AbsoluteDate();
date.setRunOn(dateFormat.format(tomorrow.getTime()));
date.setOnceADay(timeFormat.format(tomorrow.getTime()));
Daily daily = new Daily();
daily.setFrequencyInDays(1);
daily.setOnceADay(dateFormat.format(tomorrow.getTime()));
scheduleDetail.setAbsoluteDate(date);
scheduleDetail.setScheduleType(JobScheduleDetailScheduleType.AbsoluteDate);
ArrayOfJobScheduleDetail scheduleList = new ArrayOfJobScheduleDetail();
scheduleList.setJobScheduleDetail(new JobScheduleDetail[] {scheduleDetail});
JobSchedule jobSchedule = new JobSchedule();
jobSchedule.setTimeZoneName("Pacific Standard Time"); // check $AC_SERVER_HOME/etc/timezonemap.xml for supported time zone
jobSchedule.setScheduleDetails(scheduleList);
// UpdateJobSchedule
UpdateJobScheduleOperation updateJobScheduleOperation = new UpdateJobScheduleOperation();
updateJobScheduleOperation.setSetSchedules(jobSchedule);
UpdateJobScheduleOperationGroup updateJobScheduleOperationGroup = new UpdateJobScheduleOperationGroup();
updateJobScheduleOperationGroup.setUpdateJobScheduleOperation(new UpdateJobScheduleOperation[] {updateJobScheduleOperation});
com.actuate.schemas.UpdateJobSchedule updateJobSchedule = new com.actuate.schemas.UpdateJobSchedule();
updateJobSchedule.setId(jobId);
updateJobSchedule.setUpdateJobScheduleOperationGroup(updateJobScheduleOperationGroup);
AdminOperation adminOperation = new AdminOperation();
adminOperation.setUpdateJobSchedule(updateJobSchedule);
actuateControl.runAdminOperation(adminOperation);
// GetJobDetails
GetJobDetails getJobDetails = new GetJobDetails();
getJobDetails.setJobId(jobId);
getJobDetails.setResultDef( ActuateControl.newArrayOfString(
new String[] {
"InputDetail",
"NotifyUsers",
"NotifyGroups",
"NotifyChannels",
"DefaultOutputFileACL",
"Status",
"JobAttributes",
"Schedules",
"ReportParameters",
"PrinterOptions"
} ));
try {
GetJobDetailsResponse getJobDetailsResponse =
actuateControl.proxy.getJobDetails(getJobDetails);
ArrayOfJobScheduleDetail arrayOfJobScheduleDetails =
getJobDetailsResponse.getSchedules().getScheduleDetails();
JobScheduleDetail[] jobScheduleDetails =
arrayOfJobScheduleDetails.getJobScheduleDetail();
for (int i=0;i<jobScheduleDetails.length;i++)
{
System.out.println("Schedule");
System.out.println("Type: " + jobScheduleDetails[i].getScheduleType() );
AbsoluteDate absoluteDate = jobScheduleDetails[i].getAbsoluteDate();
if ( null != absoluteDate ) {
System.out.println("RunOn: " + absoluteDate.getRunOn() );
System.out.println("Time : " + absoluteDate.getOnceADay() );
}
}
}catch (java.rmi.RemoteException e){
e.printStackTrace();
}
} |
61d54b42-4a11-4bf9-b300-1a074ba7c3d2 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Square other = (Square) obj;
if (x == null) {
if (other.x != null)
return false;
} else if (!x.equals(other.x))
return false;
if (y == null) {
if (other.y != null)
return false;
} else if (!y.equals(other.y))
return false;
return true;
} |
6306c848-4d35-449d-91a4-17468f5cc6cb | 0 | @Test
public void test_gold(){
assertNotNull(pawn);
assertEquals(gold, pawn.getGold());
} |
918d3b0f-24f3-4ced-8ea6-a9edef7c8434 | 4 | public void update(Activity activity) throws InstanceNotFoundException {
boolean found = false;
Iterator<Activity> iter;
iter = activities.iterator();
while (iter.hasNext() && !found) {
Activity a = iter.next();
if (a.equals(activity)) {
found = true;
a.setPlaces(activity.getPlaces());
a.setPrize(activity.getPrize());
a.setStudents(activity.getStudents());
Persistence.getInstance().save();
}
}
if (!found) {
throw new InstanceNotFoundException(activity, "Activity");
}
} |
79522982-c47c-4d82-a332-867489d929dc | 7 | @Override
public boolean onCommand(CommandSender sender, ItemStackRef itemStackRef, Command command, String label, String[] args) {
// Check the player is holding the item
ItemStack held = itemStackRef.get();
if (held == null || held.getTypeId() == 0) {
sender.sendMessage(plugin.translate(sender, "error-no-item-in-hand", "You must be holding a menu item"));
return true;
}
// Get or create the lore
ItemMeta meta = held.getItemMeta();
List<String> loreStrings;
if (meta.hasLore()) {
loreStrings = meta.getLore();
} else {
loreStrings = new ArrayList<>();
}
// Expecting one or more parameters that make up the command or comment to add
StringBuilder sb = new StringBuilder(args[0]);
for (int i = 1; i < args.length; i++) {
sb.append(" ").append(args[i]);
}
String commandString = sb.toString();
// Append to the lore
if (!commandString.startsWith("/")) {
// Support for colour codes in non-commands
commandString = commandString.replace('&', ChatColor.COLOR_CHAR);
}
// Otherwise append this to the lore
if (loreStrings.size() == 1) {
// Handle first-line special case
String firstLine = loreStrings.get(0);
int lastPartIndex = firstLine.lastIndexOf("\r") + 1;
String lastPart = firstLine.substring(lastPartIndex);
if (lastPart.isEmpty()) {
loreStrings.set(0, firstLine.substring(0, lastPartIndex) + commandString);
} else {
loreStrings.add(commandString);
}
} else {
loreStrings.add(commandString);
}
sender.sendMessage(plugin.translate(sender, "script-appended", "{0} was added to the command list of this menu item", commandString));
// Update the item
meta.setLore(loreStrings);
held.setItemMeta(meta);
return true;
} |
ef66e96e-4661-4a0d-838f-961857a67e9f | 5 | public int getRetainPercentage(Player player) {
if (plugin.getWorldGuardClass().isWorldGuardReady()) {
RegionManager regionManager = wgPlugin.getRegionManager(player
.getWorld());
if (regionManager != null) {
ApplicableRegionSet set = regionManager
.getApplicableRegions(player.getLocation());
if (set != null) {
if (set.getFlag(RETAIN_PERCENTAGE) != null) {
return set.getFlag(RETAIN_PERCENTAGE);
}
}
}
}
String group = plugin.getFiles().getGroup(player);
if (group == null)
return plugin.getConfig().getInt("Default values.retain percentage", 50);
else
return plugin.getConfig().getInt(
"Groups." + group + ".retain percentage");
} |
5fff2688-985b-4fa8-8da0-3b8722530811 | 2 | public static double[][] sub( double[][] mat1, double[][] mat2 )
{
int m = mat1.length;
int n = mat1[0].length;
double[][] matres = new double[m][];
for ( int i = 0; i < m; ++i )
{
matres[i] = new double[n];
for ( int j = 0; j < n; ++j )
matres[i][j] = mat1[i][j] - mat2[i][j];
}
return(matres);
} |
bbec5671-87b2-4bb7-9f59-7bdb625c4fa2 | 2 | private static void initStuIDVec() {
StuIDs.clear();
unAssignedStudents.clear();
for (int i = 0; i < Students.size(); i++) {
Student thisStu = new Student((Student) Students.get(i));
StuIDs.add(thisStu.getID());
unAssignedStudents.add(thisStu.getID());
}
System.out.println("initStuIDVec");
for (int i = 0; i < unAssignedStudents.size(); i++)
System.out.print(unAssignedStudents.get(i) + " ");
} |
2369e1de-6d4e-4983-8cfe-a4a90e309849 | 5 | public static TreeNode commomAncestorWithBinarySearchTree(TreeNode p,TreeNode q,TreeNode root){
if(root==null){
return null;
}
if(root.data > p.data && root.data < q.data){
return root;
}
TreeNode left = commomAncestorWithBinarySearchTree(p,q,root.left);
if(left!=null){
return left;
}
TreeNode right = commomAncestorWithBinarySearchTree(p,q,root.right);
if(right != null){
return right;
}
return null;
} |
7992548d-85f4-45cd-ae34-4e999ecb0696 | 3 | private ArrayList<String> removeHTMLCommands(ArrayList<String> array) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i).contains("<") || array.get(i).contains(">")) {
array.remove(i);
i--;
}
}
return array;
} |
Subsets and Splits