qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
52,537,188
I am writing code that needs to format a string, and I want to avoid buffer overruns. I know that if `vsnprintf` is available (C99 onwards) we can do: ``` char* formatString(const char *format, ...) { char* result = NULL; va_list ap; va_start(ap, format); /* Get the size of the formatted string by getting vsnprintf return the * number of remaining characters if we ask it to write 0 characters */ int size = vsnprintf(NULL, 0, format, ap); if (size > 0) { /* String formatted just fine */ result = (char *) calloc(size + 1, sizeof(char)); vsnprintf(result, size + 1, format, ap); } va_end(ap); return result; } ``` I can't figure out a way of doing something similar in C90 (without `vsnprintf`). If it turns out to not be possible without writing extremely complex logic I'd be happy to set a maximum length for the result, but I'm not sure how that could be achieved either without risking a buffer overrun.
2018/09/27
[ "https://Stackoverflow.com/questions/52537188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2891462/" ]
Pre-C99 affords no simply solution to format strings with a high degree of safety of preventing buffer overruns. It is those pesky `"%s"`, `"%[]"`, `"%f"` format specifiers that require so much careful consideration with their potential long output. Thus the need for such a function. [@Jonathan Leffler](https://stackoverflow.com/questions/52537188/format-strings-safely-when-vsnprintf-is-not-available#comment92017411_52537188) To do so with those early compilers obliges code to analyze `format` and the arguments to find the required size. At that point, code is nearly there to making you own complete `my_vsnprintf()`. I'd seek existing solutions for that. [@user694733](https://stackoverflow.com/questions/52537188/format-strings-safely-when-vsnprintf-is-not-available#comment92013945_52537188). --- Even with C99, there are environmental limits for `*printf()`. > > The number of characters that can be produced by any single conversion shall be at least 4095. C11dr §7.21.6.1 15 > > > So any code that tries to `char buf[10000]; snprintf(buf, sizeof buf, "%s", long_string);` risks problems even with a sufficient `buf[]` yet with `strlen(long_string) > 4095`. This implies that a quick and dirty code could count the `%` and the format length and make the reasonable assumption that the size needed does not exceed: ``` size_t sz = 4095*percent_count + strlen(format) + 1; ``` Of course further analysis of the specifiers could lead to a more conservative `sz`. Continuing down this [path](https://en.wikipedia.org/wiki/Rabbit_hole) we [end](https://www.youtube.com/watch?v=mBaDcOBoHFk) at writing our own `my_vsnprintf()`. --- Even with your own `my_vsnprintf()` the *safety* is only so good. There is no run-time check that the `format` (which may be dynamic) matches the following arguments. To do so requires a new approach. Cheeky self advertisement for a C99 solution to insure matching specifiers and arguments: [Formatted print without the need to specify type matching specifiers using \_Generic](https://codereview.stackexchange.com/q/115143/29485).
*Transferring [comments](https://stackoverflow.com/questions/52537188/format-strings-safely-when-vsnprintf-is-not-available?noredirect=1#comment92017411_52537188) to answer.* > > The main reason `vsnprintf()` was added to C99 was that it is hard to protect `vsprintf()` or similar. One workaround is to open `/dev/null`, use `vfprintf()` to format the data to it, note how big a result was needed, and then decide whether it is safe to proceed. Icky, especially if you open the device on each call. > > > That means your code might become: ``` #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> extern char *formatString(const char *format, ...); char *formatString(const char *format, ...) { static FILE *fp_null = NULL; if (fp_null == NULL) { fp_null = fopen("/dev/null", "w"); if (fp_null == NULL) return NULL; } va_list ap; va_start(ap, format); int size = vfprintf(fp_null, format, ap); va_end(ap); if (size < 0) return NULL; char *result = (char *) malloc(size + 1); if (result == NULL) return NULL; va_start(ap, format); int check = vsprintf(result, format, ap); va_end(ap); assert(check == size); return result; } int main(void) { char *r1 = formatString("%d Dancing Pigs = %4.2f%% of annual GDP (grandiose dancing pigs!)\n", 34241562, 21.2963); char *r2 = formatString("%s [%-13.10s] %s is %d%% %s\n", "Peripheral", "sub-atomic hyperdrive", "status", 99, "of normality"); if (r1 != NULL) printf("r1 = %s", r1); if (r2 != NULL) printf("r2 = %s", r2); free(r1); free(r2); return 0; } ``` As written with `fp_null` a static variable inside the function, the file stream cannot be closed. If that's a bother, make it a variable inside the file and provide a function to `if (fp_null != NULL) { fclose(fp_null); fp_null = NULL; }`. I'm unapologetically assuming a Unix-like environment with `/dev/null`; you can translate that to `NUL:` if you're working on Windows. Note that the original code in the question did not use `va_start()` and `va_end()` twice (unlike this code); that would lead to disaster. In my opinion, it is a good idea to put the `va_end()` as soon after the `va_start()` as possible — as shown in this code. Clearly, if your function is itself stepping through the `va_list`, then there will be a bigger gap than shown here, but when you're simply relaying the variable arguments to another function as here, there should be just the one line in between. The code compiles cleanly on a Mac running macOS 10.14 Mojave using GCC 8.2.0 (compiled on macOS 10.13 High Sierra) with the command line: ``` $ gcc -O3 -g -std=c90 -Wall -Wextra -Werror -Wmissing-prototypes \ > -Wstrict-prototypes vsnp37.c -o vsnp37 $ ``` When run, it produces: ``` r1 = 34241562 Dancing Pigs = 21.30% of annual GDP (grandiose dancing pigs!) r2 = Peripheral [sub-atomic ] status is 99% of normality ```
45,211,213
We are using Google Charts within an MVC project. We have managed to get the chart implemented however we are having a slight issue. Whenever we slant the text 90 degrees the hAxis labels are repeating (see below). [![enter image description here](https://i.stack.imgur.com/WBHnm.png)](https://i.stack.imgur.com/WBHnm.png) We would like the text to be slanted at 90 degree but only have the label appear once on the hAxis (see below). [![enter image description here](https://i.stack.imgur.com/M1jZO.png)](https://i.stack.imgur.com/M1jZO.png) Things we've tried (that had no effect on the chart): Setting the hAxis grid lines : ``` hAxis: { slantedText: true, slantedTextAngle: 90, gridlines: {count: 7} }, ``` Setting the hAxis minor grid lines: ``` hAxis: { slantedText: true, slantedTextAngle: 90, minorGridlines: { count: 5 } }, ``` Is there a way we can achieve the desired result for the hAxis labels?
2017/07/20
[ "https://Stackoverflow.com/questions/45211213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4608024/" ]
when using a [continuous axis](https://developers.google.com/chart/interactive/docs/customizing_axes#discrete-vs-continuous), provide your own `ticks` to ensure no repeats... `ticks` takes an array of values of the same data type as the axis each tick can be a raw value, such as a date --> `new Date(2017, 3, 2)` or you can use object notation, to provide both the value (`v:`) and the formatted value (`f:`) ``` {v: new Date(2017, 3, 2), f: '2017'} ``` these can be built dynamically, using data table method --> `getColumnRange` which returns an object with the `min` & `max` values for the column ```js google.charts.load('current', { callback: function () { var data = google.visualization.arrayToDataTable([ [{type: 'date'}, {type: 'number'}, {type: 'number'}], [new Date(2008, 2, 5), 10, 2], [new Date(2008, 6, 6), 25, 4], [new Date(2008, 10, 8), 30, 6], [new Date(2009, 3, 2), 50, 7], [new Date(2009, 8, 12), 60, 8], [new Date(2009, 11, 20), 62, 9], [new Date(2010, 2, 5), 64, 10], [new Date(2010, 6, 6), 70, 10], [new Date(2010, 10, 8), 71, 10], [new Date(2011, 3, 2), 100, 12], [new Date(2012, 8, 12), 125, 12], [new Date(2012, 11, 20), 160, 12], [new Date(2013, 10, 8), 71, 10], [new Date(2014, 3, 2), 100, 12], [new Date(2015, 8, 12), 125, 12], [new Date(2016, 9, 20), 160, 12], [new Date(2016, 10, 8), 71, 10], [new Date(2017, 3, 2), 100, 12], [new Date(2017, 5, 12), 125, 12], [new Date(2017, 6, 20), 160, 12] ]); var dateRange = data.getColumnRange(0); var oneYear = (1000 * 60 * 60 * 24 * 365.25); var ticksAxisH = []; for (var i = dateRange.min.getTime(); i <= dateRange.max.getTime(); i = i + oneYear) { var tick = new Date(i); ticksAxisH.push({ v: tick, f: tick.getFullYear().toString() }); } var options = { hAxis: { ticks: ticksAxisH }, legend: 'none' }; var chart = new google.visualization.LineChart($('#chart').get(0)); chart.draw(data, options); }, packages:['corechart'] }); ``` ```html <script src="https://www.gstatic.com/charts/loader.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div id="chart"></div> ``` --- **EDIT** the `ticks` option is only supported by a continuous axis (date, number, etc...) and is unavailable for a discrete axis (string) use a data view to convert the first column to a number... ``` // convert first column to number var view = new google.visualization.DataView(data); view.setColumns([{ calc: function (dt, row) { return parseInt(dt.getValue(row, 0)); }, label: data.getColumnLabel(0), type: 'number' }, 1, 2]); ``` then use data table / view method --> `getDistinctValues(colIndex)` this will return an array of the distinct values in the column, which can be used for the `ticks` see following working snippet... ```js google.charts.load('current', { callback: function () { var data = new google.visualization.DataTable({ "cols": [ {"type": "string" ,"id": "Data" ,"label": "Label" }, {"type": "number" ,"id": "Performance" ,"label": "Performance" }, {"type": "number" ,"id": "Index" ,"label": "Index" } ], "rows": [ {"c" : [{"v": "2008"}, {"v": 0}, {"v": "0"}]}, {"c" : [{"v": "2008"}, {"v": 0.07103609}, {"v": "0.0052939"}]}, {"c" : [{"v": "2008"}, {"v": 0.12668605420031}, {"v": "0.0152939"}]}, {"c" : [{"v": "2009"}, {"v": 0.27103609}, {"v": "0.0252939"}]}, {"c" : [{"v": "2009"}, {"v": 0.32668605420031}, {"v": "0.0352939"}]}, {"c" : [{"v": "2010"}, {"v": 0.37103609}, {"v": "0.0452939"}]}, {"c" : [{"v": "2010"}, {"v": 0.42668605420031}, {"v": "0.0552939"}]}, {"c" : [{"v": "2011"}, {"v": 0.47103609}, {"v": "0.0652939"}]}, {"c" : [{"v": "2011"}, {"v": 0.52668605420031}, {"v": "0.0752939"}]}, {"c" : [{"v": "2012"}, {"v": 0.57103609}, {"v": "0.0852939"}]}, {"c" : [{"v": "2012"}, {"v": 0.62668605420031}, {"v": "0.0952939"}]}, {"c" : [{"v": "2013"}, {"v": 0.67103609}, {"v": "0.1052939"}]}, {"c" : [{"v": "2013"}, {"v": 0.72668605420031}, {"v": "0.2152939"}]} ] }); // convert first column to number var view = new google.visualization.DataView(data); view.setColumns([{ calc: function (dt, row) { return parseInt(dt.getValue(row, 0)); }, label: data.getColumnLabel(0), type: 'number' }, 1, 2]); var options = { hAxis: { format: '0', ticks: view.getDistinctValues(0) }, legend: 'none' }; var chart = new google.visualization.LineChart($('#chart').get(0)); chart.draw(view, options); // <-- use view to draw chart }, packages:['corechart'] }); ``` ```html <script src="https://www.gstatic.com/charts/loader.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div id="chart"></div> ``` --- **EDIT 2** another option would be to leave the axis as discrete (string), and simply remove the duplicate labels from the data this can also be accomplished using a data view... ``` // remove duplicates from first column var view = new google.visualization.DataView(data); view.setColumns([{ calc: function (dt, row) { var xValue = dt.getValue(row, 0); if ((row > 0) && (xValue === dt.getValue(row - 1, 0))) { return null; } else { return xValue; } }, label: data.getColumnLabel(0), type: 'string' }, 1, 2]); ``` see following working snippet... ```js google.charts.load('current', { callback: function () { var data = new google.visualization.DataTable({ "cols": [ {"type": "string" ,"id": "Data" ,"label": "Label" }, {"type": "number" ,"id": "Performance" ,"label": "Performance" }, {"type": "number" ,"id": "Index" ,"label": "Index" } ], "rows": [ {"c" : [{"v": "2008"}, {"v": 0}, {"v": "0"}]}, {"c" : [{"v": "2008"}, {"v": 0.07103609}, {"v": "0.0052939"}]}, {"c" : [{"v": "2008"}, {"v": 0.12668605420031}, {"v": "0.0152939"}]}, {"c" : [{"v": "2009"}, {"v": 0.27103609}, {"v": "0.0252939"}]}, {"c" : [{"v": "2009"}, {"v": 0.32668605420031}, {"v": "0.0352939"}]}, {"c" : [{"v": "2010"}, {"v": 0.37103609}, {"v": "0.0452939"}]}, {"c" : [{"v": "2010"}, {"v": 0.42668605420031}, {"v": "0.0552939"}]}, {"c" : [{"v": "2011"}, {"v": 0.47103609}, {"v": "0.0652939"}]}, {"c" : [{"v": "2011"}, {"v": 0.52668605420031}, {"v": "0.0752939"}]}, {"c" : [{"v": "2012"}, {"v": 0.57103609}, {"v": "0.0852939"}]}, {"c" : [{"v": "2012"}, {"v": 0.62668605420031}, {"v": "0.0952939"}]}, {"c" : [{"v": "2013"}, {"v": 0.67103609}, {"v": "0.1052939"}]}, {"c" : [{"v": "2013"}, {"v": 0.72668605420031}, {"v": "0.2152939"}]} ] }); // remove duplicates from first column var view = new google.visualization.DataView(data); view.setColumns([{ calc: function (dt, row) { var xValue = dt.getValue(row, 0); if ((row > 0) && (xValue === dt.getValue(row - 1, 0))) { return null; } else { return xValue; } }, label: data.getColumnLabel(0), type: 'string' }, 1, 2]); var options = { chartArea: { height: '100%', width: '100%', top: 12, left: 24, bottom: 48, right: 4 }, hAxis: { maxAlternation: 1 }, height: '100%', legend: 'none', width: '100%' }; var chart = new google.visualization.LineChart($('#chart').get(0)); chart.draw(view, options); $(window).resize(function() { chart.draw(view, options); }); }, packages:['corechart'] }); ``` ```html <script src="https://www.gstatic.com/charts/loader.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <div id="chart"></div> ```
VICTORY! So I finally got it working. WhiteHat you're an absolute genius! Thank you! EDIT 2 did the trick, however I added an extra property to the hAxis for it to display all labels (see below). ``` showTextEvery:1 ``` Below is the full implementation for anyone else having this issue. ``` var data = new google.visualization.DataTable(@Html.Raw(Json.Encode(perfData))); var view = new google.visualization.DataView(data); view.setColumns([{ calc: function (dt, row) { var xValue = dt.getValue(row, 0); if ((row > 0) && (xValue === dt.getValue(row-1, 0))) { return null; } else { return xValue; } }, label: data.getColumnLabel(0), type: 'string' }, 1, 2]); var options = { chartArea : { left: 40, top:10}, width:450, height: 300, hAxis: { slantedText: true, slantedTextAngle: 90, showTextEvery:1 }, legend:{position:'bottom'}, vAxis: { format: '#%', gridlines: {count: 7} } }; var chart_div = document.getElementById('returnsChart'); var chart = new google.visualization.LineChart(chart_div); chart.draw(view, options); $(window).resize(function () { chart.draw(view, options); }); ``` below is the final image: [![enter image description here](https://i.stack.imgur.com/T3H8K.png)](https://i.stack.imgur.com/T3H8K.png)
5,487,916
I have a Rails 3 project that uses some java jar files. I'm putting these jars in the vendor/ directory and adding them to the git repo. But these jars can be large (e.g. 22MB), and they are binaries. On the other hand, it's convenient to store them into the repo with the Ruby code since they work closely with the rest of the app. What's the best practice on Java jars, git repositories, and the Rails vendor directory?
2011/03/30
[ "https://Stackoverflow.com/questions/5487916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/232417/" ]
You are opening a big can of worms regarding dependency management. Most projects including some of the [smaller ones](http://code.google.com/p/jaxb-collada/source/browse/#hg/extlib) I work on use the ball of mud, dependencies in a folder approach. As the project gets larger somebody serious comes along and typically does a 'proper' dependency management with [Ant+Ivy](http://ant.apache.org/ivy/) or [Maven](http://maven.apache.org/) for Java projects. Depending on how often your binaries change you may get away with storing them in version control.
In my opinion if your app requires them to run then it makes sense to keep them in the git repo otherwise if you checked out the app on another machine you'd have to mess around sourcing the binaries again. 22MB isn't that huge and they aren't going to be modified, so I don't think this causes any problems.
11,281,401
We have an application that stores some configuration values from C/C++ in MongoDB and has the capability to be restarted (i.e. it runs for a while, someone interrupts the application, changes the configuration, then runs the app again, and it picks up where it left off). This works like a charm for boolean and string configurations. But then we have some integers (in our current C/C++ implementation - 32 bit values). And when I use the MongoDB console to modify those integer values, Mongo always stores them back as Number (which is doulble in the C/C++ implementation). We will change the app to take double values where it expects integers but I was wondering if there is a way to force Mongo to store integers from its JavaScript console. Any suggestions?
2012/07/01
[ "https://Stackoverflow.com/questions/11281401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535201/" ]
In the C/C++ "sense of the word", ints are [not actually guaranteed](https://stackoverflow.com/questions/589575/size-of-int-long-etc?answertab=votes#tab-top) to be 32-bit values. An `int` must be at least 16-bits, but generally matches the platform architecture (eg. 32 or 64bit). As mentioned by @Jasd, JavaScript does only have one numeric type which is a floating point (`double` in C). From the MongoDB shell you should be able to use the functions `NumberInt(..)` to get a [BSON 32-bit integer value](http://bsonspec.org/#/specification) or `NumberLong(..)` to get a BSON 64-bit integer.
MongoDB's shell is powered by a JavaScript Engine. And JavaScript has no type for `integer`. It knows only `Number`, which is a type for floating-point numbers. You can try using the MongoDB type [`NumberLong`](http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell#Overview-TheMongoDBInteractiveShell-Numbers), but it didn't work out for me when i once had the same problem.
11,281,401
We have an application that stores some configuration values from C/C++ in MongoDB and has the capability to be restarted (i.e. it runs for a while, someone interrupts the application, changes the configuration, then runs the app again, and it picks up where it left off). This works like a charm for boolean and string configurations. But then we have some integers (in our current C/C++ implementation - 32 bit values). And when I use the MongoDB console to modify those integer values, Mongo always stores them back as Number (which is doulble in the C/C++ implementation). We will change the app to take double values where it expects integers but I was wondering if there is a way to force Mongo to store integers from its JavaScript console. Any suggestions?
2012/07/01
[ "https://Stackoverflow.com/questions/11281401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535201/" ]
You can fix the types of all values for a certain field on the console with something like: ``` db.Statistic.find({kodoId: {$exists: true}}).forEach(function (x) { x.kodoId = NumberInt(x.kodoId); db.Statistic.save(x); }); ``` This will only load documents that have the `kodoId` field and convert them to int and resave. You could do something like: ``` db.Statistic.find({kodoId: {$exists: true}}, {kodoId: 1}).forEach(function (x) { db.Statistic.update({ _id: x._id }, {$set: { kodoId: NumberInt(x.kodoId) }}); }); ``` with a second param which will *only* load the kodoId value (hopefully from an index). This should be much quicker since it doesn't need to load and resave the entire document - just that one field.
MongoDB's shell is powered by a JavaScript Engine. And JavaScript has no type for `integer`. It knows only `Number`, which is a type for floating-point numbers. You can try using the MongoDB type [`NumberLong`](http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell#Overview-TheMongoDBInteractiveShell-Numbers), but it didn't work out for me when i once had the same problem.
11,281,401
We have an application that stores some configuration values from C/C++ in MongoDB and has the capability to be restarted (i.e. it runs for a while, someone interrupts the application, changes the configuration, then runs the app again, and it picks up where it left off). This works like a charm for boolean and string configurations. But then we have some integers (in our current C/C++ implementation - 32 bit values). And when I use the MongoDB console to modify those integer values, Mongo always stores them back as Number (which is doulble in the C/C++ implementation). We will change the app to take double values where it expects integers but I was wondering if there is a way to force Mongo to store integers from its JavaScript console. Any suggestions?
2012/07/01
[ "https://Stackoverflow.com/questions/11281401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/535201/" ]
In the C/C++ "sense of the word", ints are [not actually guaranteed](https://stackoverflow.com/questions/589575/size-of-int-long-etc?answertab=votes#tab-top) to be 32-bit values. An `int` must be at least 16-bits, but generally matches the platform architecture (eg. 32 or 64bit). As mentioned by @Jasd, JavaScript does only have one numeric type which is a floating point (`double` in C). From the MongoDB shell you should be able to use the functions `NumberInt(..)` to get a [BSON 32-bit integer value](http://bsonspec.org/#/specification) or `NumberLong(..)` to get a BSON 64-bit integer.
You can fix the types of all values for a certain field on the console with something like: ``` db.Statistic.find({kodoId: {$exists: true}}).forEach(function (x) { x.kodoId = NumberInt(x.kodoId); db.Statistic.save(x); }); ``` This will only load documents that have the `kodoId` field and convert them to int and resave. You could do something like: ``` db.Statistic.find({kodoId: {$exists: true}}, {kodoId: 1}).forEach(function (x) { db.Statistic.update({ _id: x._id }, {$set: { kodoId: NumberInt(x.kodoId) }}); }); ``` with a second param which will *only* load the kodoId value (hopefully from an index). This should be much quicker since it doesn't need to load and resave the entire document - just that one field.
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
try this. ``` date('F/j/Y',strtotime($result['postDate'])); ``` as timestamp is required, not formatted date as second parameter. or you can also try ``` SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable ``` instead of `SELECT postDate from myTable` and then have this in your code. ``` date('F/j/Y',$result['postDateInt']); ```
The PHP [date](http://us3.php.net/manual/en/function.date.php) function looks for an `int time()` as the 2nd param. Try using [strtotime()](http://us3.php.net/manual/en/function.strtotime.php) ``` echo date('F/j/Y', strtotime($result['postDate']) ); ```
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
try this. ``` date('F/j/Y',strtotime($result['postDate'])); ``` as timestamp is required, not formatted date as second parameter. or you can also try ``` SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable ``` instead of `SELECT postDate from myTable` and then have this in your code. ``` date('F/j/Y',$result['postDateInt']); ```
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp. You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the `strtotime()` function. At least two other answers have already suggested this. However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL `UNIX_TIMESTAMP()` function, as follows: ``` SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable ``` ..obviously, replacing the field and table names as appropriate. Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the `date()` function as follows: ``` echo date('F/j/Y',$result['mydatefield_timestamp']); ``` Hope that helps.
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
try this. ``` date('F/j/Y',strtotime($result['postDate'])); ``` as timestamp is required, not formatted date as second parameter. or you can also try ``` SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable ``` instead of `SELECT postDate from myTable` and then have this in your code. ``` date('F/j/Y',$result['postDateInt']); ```
Why not format the date as needed in your MySQL query? ``` SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table ```
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
The PHP [date](http://us3.php.net/manual/en/function.date.php) function looks for an `int time()` as the 2nd param. Try using [strtotime()](http://us3.php.net/manual/en/function.strtotime.php) ``` echo date('F/j/Y', strtotime($result['postDate']) ); ```
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp. You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the `strtotime()` function. At least two other answers have already suggested this. However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL `UNIX_TIMESTAMP()` function, as follows: ``` SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable ``` ..obviously, replacing the field and table names as appropriate. Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the `date()` function as follows: ``` echo date('F/j/Y',$result['mydatefield_timestamp']); ``` Hope that helps.
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
The PHP [date](http://us3.php.net/manual/en/function.date.php) function looks for an `int time()` as the 2nd param. Try using [strtotime()](http://us3.php.net/manual/en/function.strtotime.php) ``` echo date('F/j/Y', strtotime($result['postDate']) ); ```
Why not format the date as needed in your MySQL query? ``` SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table ```
5,339,339
i have column named `postDate` defined as timestamp. when i print it directly: ``` echo $result['postDate']; ``` i do get that what is stored(eg. `2011-03-16 16:48:24`) on the other hand when i print it through date function: ``` echo date('F/j/Y',$result['postDate']) ``` i get `December/31/1969` what am i doing wrong? many thanks
2011/03/17
[ "https://Stackoverflow.com/questions/5339339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/653874/" ]
Why not format the date as needed in your MySQL query? ``` SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table ```
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp. You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the `strtotime()` function. At least two other answers have already suggested this. However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL `UNIX_TIMESTAMP()` function, as follows: ``` SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable ``` ..obviously, replacing the field and table names as appropriate. Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the `date()` function as follows: ``` echo date('F/j/Y',$result['mydatefield_timestamp']); ``` Hope that helps.
33,930,758
I'm using a combination of Jquery and Bootstrap. I'm trying to target only visible panels. If I get rid of the first line, of code, the function work, but targets all panels in my HTML, which I don't want. If I keep the first line of code, the function doesn't carry through at all. ``` $(".panel:visible").each(function(){ $("#1star").on("click", function() { $(".5star").show(); $(".4star").show(); $(".3star").show(); $(".2star").show(); $(".1star").show(); }); ``` And yes, I'm sure there's an easier way to do this, but I'm confined to html, css, and jQuery. :::edit:: html requested. ``` div class="panel panel-default pa 5star"> <div class="panel-body"> Pa hotel 5 star </div> </div> <div class="panel panel-default pa 4star"> <div class="panel-body"> pa hotel 4 star </div> </div> <div class="panel panel-default pa 3star"> <div class="panel-body"> pa hotel 3 star </div> </div> <div class="panel panel-default pa 2star"> <div class="panel-body"> pa hotel 2 star </div> </div> <div class="panel panel-default pa 1star"> <div class="panel-body"> pa hotel 1 star </div> </div> ``` ::edit 2::: the reason all the panels are hidden is because 1.They are by default and two this other piece of Jq ``` if (acceptNJ[stateSearch.toLowerCase()]) { $(".nj").fadeIn(2000); $(".pa").hide(); $(".ny").hide(); ```
2015/11/26
[ "https://Stackoverflow.com/questions/33930758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5510690/" ]
Javascript that accesses the DOM must not execute UNTIL the DOM has been loaded. Code that runs in the `<head>` section of the document will execute BEFORE the DOM has been loaded and thus if it tries to operate on the DOM, the DOM will simply be empty. Code that runs in the `<body>` section of the document will execute AFTER any DOM elements that are before that script tag, but BEFORE any DOM elements that are after the script tag. If you put `<script>` tags at the very end of the `<body>` section right before the `</body>` tag, then the whole DOM will be ready when that script executes. `DOMContentLoaded` (which jsFiddle calls `onDomReady`) is an event that fires when the DOM is now loaded and is available for script to access. If you run your code when the DOMContentLoaded event fires, then the DOM will be ready for your code to access at that point. `window.onload` is an event that fires when the DOM is now loaded and any resources specified in the HTML of the page are also done loading (like images). This always fires after the DOMContentLoaded event. You can see further description of this issue here: [pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it](https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the/9899701#9899701) --- If code works when in the `<body>`, but not in the `<head>`, then you are probably running the code too early in the `<head>` tag before the DOM is ready. You can either just leave it near the end of the `<body>` or you can hook it up to one of the load events and then you can put it in the `<head>` tag if you want.
**`<head>`** contains all the information regarding the Page properties, CSS and JavaScript. Though CSS and JavaScript can be included in the body as well. Head will include Page's meta information, Title, base URL etc. **`<body>`** contains the actual content of the body. Which users visiting the website actually see or interact with. **`DOM`** is Document Object Model. It's the basic structure or you can say the skeleton of the Page on which the page stands. **`domready`** is an event which is fired as soon as the DOM has finished loading. For eg: Suppose a page has only one image. It will wait for the image tag to be parsed. As soon as the image tag is received it will be fired. It will NOT wait for whole image to be loaded from the source. **`onload`** is an event which is fired when complete(DOM + content) page is loaded. In the previous example in `donready`, `onload` will wait for the image to be fetched from the source and then will be fired.
2,894,560
I have extra retain counts after calling initWithNib. What could cause this? (There are no referencing outlets in the nib) ``` StepViewController *stepViewController = [[StepViewController alloc] initWithNibName:@"StepViewController" bundle:nil]; [self.navigationController pushViewController:stepViewController animated:YES]; [stepViewController release]; NSLog(@"nextStep stepViewController retain count %i", [stepViewController retainCount]); ``` the above results in a retain count of 3... Thanks for any advice on how to troubleshoot
2010/05/24
[ "https://Stackoverflow.com/questions/2894560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/57254/" ]
What are you troubleshooting? There is nothing wrong here. -retainCount is not your business and tells you almost nothing about the system. Every object that is autoreleased will have an apparent retainCount higher than you think it will be. If internal objects are interested in this object, they will have their own retains that you may or may not expect. Your business is to balance your own retains and releases. The rest of the system is responsible for balancing theirs. You should not second-guess it, and if you do, -retainCount is unlikely to help you much anyway. It is almost always more misleading than helpful. Is there actually a leak going on that you're concerned about?
You would have to look into the source code or API documentation to find out. But it would seem logical that the nvaigation controller has one and the view loaded out of the xib has one, so that's probably another being done by something in the naviation controller would be my guess.
25,225,182
I'm trying to build a searchable database that will allow a user to type in the name of a state and see a small subset of that state's laws (traffic laws, age of consent, conceal and carry laws, etc.). I'm getting confused on how a user submitted string will interact with my Javascript objects. I have seen people submitting questions regarding adding user-submitted integers or concatenating but what I am trying to do is slightly different. I am able to assign the user-submitted text as a variable via the getElementById method but now I'm lost. My question is this: How do I connect that user submitted variable with my objects' key values in Javascript so that when a user types in "Minnesota" and clicks the find button it retrieves and displays my Javascript data (which is information about Minnesota's state laws stored as object keys)? Here is a subset of the **HTML** in question: ``` <div class="formDiv"> <form id="searchbox" action=""> <!--Search field--> <input id="search" type="text" placeholder="Ex: Minnesota"></input> <!--Submit button--> <input id="submit" type="submit" value="Search"></input> </form> </div> <!--Where I want the Javascript object to be displayed--> <div class="answer"><p></p></div> ``` And here is the **Javascript** with just one object for simplicity: ``` var Minnesota = { name: "Minnesota", consent: 18, openBottle: true, deathPen: false, conceal: "Conceal & Carry", txtDriveBan: true, talkDriveBan: false } $(document).ready(function() { $("#submit").on('click', function(){ var State = document.getElementById("#search"); //At this point, what do I write to display Minnesota's information stored in the object?// }); }); ``` Thanks very much for any help!
2014/08/10
[ "https://Stackoverflow.com/questions/25225182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3788480/" ]
here you go I implemented this fiddle for you with how I'd handle what you need. I changed the data structure so that the state names are the keys... <http://jsfiddle.net/yc7w364t/> ``` var stateData = { "minnesota" : { consent: 18, openBottle: true, deathPen: false, conceal: "Conceal & Carry", txtDriveBan: true, talkDriveBan: false } } ```
The keys in your object should be the name of the state. Then you can do this: ``` var states = { "Minnesota": { consent: 18, openBottle: true, deathPen: false, conceal: "Conceal & Carry", txtDriveBan: true, talkDriveBan: false } } $(document).ready(function() { $("#submit").on('click', function(e){ e.preventDefault(); // Don't submit the form. var State = document.getElementById("#search"); var answerString = ''; for (var key in states[State]){ answerString += '<p>' + key + ': ' + states[State][key] + '</p>'; } $('#answer').html(answerString); }); }); ``` Note that you should change the div that will contain the answer to have `id` "answer", not `class` "answer".
25,373,273
First of all, I come from Obj-C and Python, so feel free to edit any faults in my JavaScript teminology. I am looking for an efficient way of joining multiple dictionaries in JavaScript, where each key can exist in more than one dictionary and its values are arrays. For example, I have: ``` {foo: [1,2], bar: [3,4]} {foo: [5,6], baz: [7,8]} ``` And I want to join all the values of the same key, meaning I should return: ``` {foo: [1,2,5,6], bar: [3,4], baz: [7,8]} ``` I started doing something like the following pseudo code, but I feel like there should be a more efficient way of doing it. ``` // Pseudo code return_value = {} for (subset in full_array) for (kv in subset) data = return_value[kv] || [] data.push(subset[kv]) return_value[kv] = data ```
2014/08/18
[ "https://Stackoverflow.com/questions/25373273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1373572/" ]
With [Lo-Dash](http://lodash.com/): ``` var data = [ {foo: [1,2], bar: [3,4]}, {foo: [5,6]}, ]; _.reduce(data, function (result, obj) { _.each(obj, function (array, key) { result[key] = (result[key] || []).concat(array) }) return result }, {}) ``` See this [fiddle](http://jsfiddle.net/80zc2m69/).
This code works: ``` var joinManyObjects = function joinManyObjects (arrayA, arrayB) { var i, j; for(i = 0; i < arrayB.length; i++) { for(j = 0; j < arrayA.length; j++) { var k = Object.keys(arrayB[i]); console.log("Common keys: "+k); if(k in arrayA[j]) { arrayA[j][k] = arrayA[j][k].concat(arrayB[i][k]); } } } } var a = [{foo: [1,2], bar: [3,4]}]; var b = [{foo: [5,6]}]; joinManyObjects(a,b) -> a = [{"foo":[1,2,5,6],"bar":[3,4]}] ``` You can add [remove duplicates](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) or type detection (typeof or Array.isArray).
4,060
Speaking with a large group about Bitcoins lately, I noticed that most people there came to like Bitcoins for different reasons. The shady ppl wanted drugs, the accountants wanted to avoid taxes, the Ron Paul people wanted more personal liberty and to end the Fed, The traders wanted new Forex opportunities, and the computer techies were in love with the elegance of the system... So I'm really starting to wonder here, What are the demographics of the Bitcoin users? Has anyone attempted to do a serious attempt at finding those? Perhaps even a big website poll? Inquiring minds want to know.
2012/06/25
[ "https://bitcoin.stackexchange.com/questions/4060", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/1519/" ]
I can't think of any known data about real demographics. But here are some things you can consider to get an idea: * [BitcoinCharts' currency distribution](http://bitcoincharts.com/charts/volumepie/): Gives you a view on what currencies are traded the most, most currencies are country- or region-specific so this can be a measure. * [BlockChain.info's real-time transaction mapping](https://blockchain.info/unconfirmed-transactions?format=webgl): You can literally see every new transmitted transaction appear on the map. (This is possible because all transactions are public and have an IP bound to them. But note that some users might use Bitcoin with tools like [Tor](http://www.torproject.org) so their location can be wrong.)
A recent survey solicited to BitcoinTalk forum members: * <http://bitcointalk.org/index.php?topic=88927.0>
4,060
Speaking with a large group about Bitcoins lately, I noticed that most people there came to like Bitcoins for different reasons. The shady ppl wanted drugs, the accountants wanted to avoid taxes, the Ron Paul people wanted more personal liberty and to end the Fed, The traders wanted new Forex opportunities, and the computer techies were in love with the elegance of the system... So I'm really starting to wonder here, What are the demographics of the Bitcoin users? Has anyone attempted to do a serious attempt at finding those? Perhaps even a big website poll? Inquiring minds want to know.
2012/06/25
[ "https://bitcoin.stackexchange.com/questions/4060", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/1519/" ]
I can't think of any known data about real demographics. But here are some things you can consider to get an idea: * [BitcoinCharts' currency distribution](http://bitcoincharts.com/charts/volumepie/): Gives you a view on what currencies are traded the most, most currencies are country- or region-specific so this can be a measure. * [BlockChain.info's real-time transaction mapping](https://blockchain.info/unconfirmed-transactions?format=webgl): You can literally see every new transmitted transaction appear on the map. (This is possible because all transactions are public and have an IP bound to them. But note that some users might use Bitcoin with tools like [Tor](http://www.torproject.org) so their location can be wrong.)
There was a Bitcoin survey recently: <https://bitcointalk.org/index.php?topic=88927.0>.
4,060
Speaking with a large group about Bitcoins lately, I noticed that most people there came to like Bitcoins for different reasons. The shady ppl wanted drugs, the accountants wanted to avoid taxes, the Ron Paul people wanted more personal liberty and to end the Fed, The traders wanted new Forex opportunities, and the computer techies were in love with the elegance of the system... So I'm really starting to wonder here, What are the demographics of the Bitcoin users? Has anyone attempted to do a serious attempt at finding those? Perhaps even a big website poll? Inquiring minds want to know.
2012/06/25
[ "https://bitcoin.stackexchange.com/questions/4060", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/1519/" ]
A recent survey solicited to BitcoinTalk forum members: * <http://bitcointalk.org/index.php?topic=88927.0>
There was a Bitcoin survey recently: <https://bitcointalk.org/index.php?topic=88927.0>.
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
Assuming the file is sorted numerically on the first column you can use `awk` for this in the following way ``` awk 'NR==1 {max=$1} {if($1==max){print $0}}' ``` this grabs the first field of the first line and stores that in variable `max` and only the lines that match this number are printed subsequently
You may first retrieve the number of max occurence, and then grep on that file: ``` NB=$(head -n1 error.dat | cut -d ' ' -f 1) egrep ^$NB error.dat ``` Here `egrep` means that `grep` should interpret the pattern as a regex; and `^` represents the beginning of a line
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
Assuming the file is sorted numerically on the first column you can use `awk` for this in the following way ``` awk 'NR==1 {max=$1} {if($1==max){print $0}}' ``` this grabs the first field of the first line and stores that in variable `max` and only the lines that match this number are printed subsequently
You can use this `awk`: ``` awk 'NR==FNR{if ($1>max) max=$1; next} $1==max' file file 19 prob561493 19 prob564972 19 prob561564 ``` In the 1st pass we are getting max value from `$1` stored in variable `max` and in 2nd pass we just print all the records that have first field same as `max`.
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
Assuming the file is sorted numerically on the first column you can use `awk` for this in the following way ``` awk 'NR==1 {max=$1} {if($1==max){print $0}}' ``` this grabs the first field of the first line and stores that in variable `max` and only the lines that match this number are printed subsequently
Use awk to extract the '19' and grep+regex to get the lines that start with `19\b`. Assuming your file-name is "output": ``` grep -E "$(head -n1 output | awk '{print $1}')\b" output ```
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
You asked how to do this in bash. I have to say that awk may provide the clearest method to achieve what you want: ``` awk 'NR==1{n=$1} $1==n{print;next} {exit}' ``` This gets the count from the first field, then prints each line with that first field, and exits when the field doesn't match. It assumes sorted input. But the task can still be handled in bash (or even just shell) alone, without spawning extra commands or subshells. ``` #!/bin/sh n=0 while read count data; do printf "%3d %s\n" "$count" "$data" if [ $n -gt 1 -a "$count" != "$lastcount" ]; then break fi n=$((n+1)) done ``` There are zillions of ways you can achieve this.
Assuming the file is sorted numerically on the first column you can use `awk` for this in the following way ``` awk 'NR==1 {max=$1} {if($1==max){print $0}}' ``` this grabs the first field of the first line and stores that in variable `max` and only the lines that match this number are printed subsequently
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
You asked how to do this in bash. I have to say that awk may provide the clearest method to achieve what you want: ``` awk 'NR==1{n=$1} $1==n{print;next} {exit}' ``` This gets the count from the first field, then prints each line with that first field, and exits when the field doesn't match. It assumes sorted input. But the task can still be handled in bash (or even just shell) alone, without spawning extra commands or subshells. ``` #!/bin/sh n=0 while read count data; do printf "%3d %s\n" "$count" "$data" if [ $n -gt 1 -a "$count" != "$lastcount" ]; then break fi n=$((n+1)) done ``` There are zillions of ways you can achieve this.
You may first retrieve the number of max occurence, and then grep on that file: ``` NB=$(head -n1 error.dat | cut -d ' ' -f 1) egrep ^$NB error.dat ``` Here `egrep` means that `grep` should interpret the pattern as a regex; and `^` represents the beginning of a line
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
You asked how to do this in bash. I have to say that awk may provide the clearest method to achieve what you want: ``` awk 'NR==1{n=$1} $1==n{print;next} {exit}' ``` This gets the count from the first field, then prints each line with that first field, and exits when the field doesn't match. It assumes sorted input. But the task can still be handled in bash (or even just shell) alone, without spawning extra commands or subshells. ``` #!/bin/sh n=0 while read count data; do printf "%3d %s\n" "$count" "$data" if [ $n -gt 1 -a "$count" != "$lastcount" ]; then break fi n=$((n+1)) done ``` There are zillions of ways you can achieve this.
You can use this `awk`: ``` awk 'NR==FNR{if ($1>max) max=$1; next} $1==max' file file 19 prob561493 19 prob564972 19 prob561564 ``` In the 1st pass we are getting max value from `$1` stored in variable `max` and in 2nd pass we just print all the records that have first field same as `max`.
29,614,964
I have an output of the following format in bash, from a script I wrote that returns the number of duplicate file names and the file name itself within a particular directory. ``` 19 prob561493 19 prob564972 19 prob561564 11 prob561965 8 prob562172 7 prob564449 6 prob564155 6 prob562925 6 prob562739 ``` Using `output | head -n1`, I can get the first entry of the above output to get `19 prob561493`. However, I also want to print out other problems that share the same number of max duplicates, so in this case, the final output should look this way: ``` 19 prob561493 19 prob564972 19 prob561564 ``` I tried to do a `cut -d" " | uniq -c` to first get the integer of the output and then only show the unique results, but that returned ALL the duplicate results. How can I print only the duplicated maximum duplication lines?
2015/04/13
[ "https://Stackoverflow.com/questions/29614964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1913389/" ]
You asked how to do this in bash. I have to say that awk may provide the clearest method to achieve what you want: ``` awk 'NR==1{n=$1} $1==n{print;next} {exit}' ``` This gets the count from the first field, then prints each line with that first field, and exits when the field doesn't match. It assumes sorted input. But the task can still be handled in bash (or even just shell) alone, without spawning extra commands or subshells. ``` #!/bin/sh n=0 while read count data; do printf "%3d %s\n" "$count" "$data" if [ $n -gt 1 -a "$count" != "$lastcount" ]; then break fi n=$((n+1)) done ``` There are zillions of ways you can achieve this.
Use awk to extract the '19' and grep+regex to get the lines that start with `19\b`. Assuming your file-name is "output": ``` grep -E "$(head -n1 output | awk '{print $1}')\b" output ```
59,401
Is it because of the inherent limitations of cooling the cylinder walls, only 2 valves per cylinder, relative ease of scaling up instead of dialing up the boost, or some other reason?
2019/01/24
[ "https://aviation.stackexchange.com/questions/59401", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/36532/" ]
I read somewhere once, maybe I can find it again, but it is because of the inherent limitations of cooling the cylinder walls. Air cooling is not as controllable, because the temperature of the air varies with altitude and season. Hence, the temperature of the cylinders in an air cooled engine are not as tightly controlled as a liquid cooled engine. So, the cylinders need to be able to operate over a greater temperature range. Since metal expands with temperature, that means the gap between the cylinders and the bore is typically greater in an air cooled engine than a liquid cooled one. So, this greater gap, even with piston rings means some of the cylinder head pressure after combustion escapes rather than act on the piston. Makes sense to me...
A liquid cooled engine doesn't necessarily expose all its cylinders to the airflow, which reduces drag in comparison to a radial engine. Also, water is a much better medium for distributing heat from an engine so it takes much more heat to have a detrimental effect on LC engines (aka temperature above operating levels). Additionally, the design of a LC engine (inline or V) require the cylinders to be arranged in banks where one camshaft can be used to actuate valves in multiple cylinder heads (thus producing more HP).
7,878,334
i am trying to configure nginx to proxy pass the request to another server, only if the $request\_body variable matches on a specific regular expression. My problem now is, that I don't how to configure this behaviour exactly. I am currently down to this one: ``` server { listen 80 default; server_name test.local; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; if ($request_body ~* ^(.*)\.test) { proxy_pass http://www.google.de; } root /srv/http; } } ``` but the problem here is, that root has always the upperhand. the proxy won't be passed either way. any idea on how I could accomplish this? thanks in advance
2011/10/24
[ "https://Stackoverflow.com/questions/7878334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/671116/" ]
Nginx routing is based on the location directive which matches on the Request URI. The solution is to temporarily modify this in order to forward the request to different endpoints. ``` server { listen 80 default; server_name test.local; if ($request_body ~* ^(.*)\.test) { rewrite ^(.*)$ /istest/$1; } location / { root /srv/http; } location /istest/ { rewrite ^/istest/(.*)$ $1 break; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; proxy_pass http://www.google.de; } } ``` The `if` condition can only safely be used in Nginx with the [rewrite module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) which it is part of. In this example. The `rewrite` prefixes the Request URI with `istest`. The `location` blocks give precedence to the closest match. Anything matching `/istest/` will go to the second block which uses another `rewrite` to remove `/istest/` from the Request URI before forwarding to the upstream proxy.
try this: ``` server { listen 80 default; server_name test.local; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $http_host; if ($request_body ~* ^(.*)\.test) { proxy_pass http://www.google.de; break; } root /srv/http; } } ```
39,947,606
Hi i am trying to build my first project using Android support libraries in order to support material design for all of the devices on market. At the very begining of my journey i create a project from scratch and when i build from graddle using this module configuration: ``` apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "19.1" defaultConfig { applicationId "com.sunshine.org.weather" minSdkVersion 13 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile 'junit:junit:4.12' compile 'com.google.code.gson:gson:2.2.4' compile 'com.android.support:support-v4:24.2.1' compile 'com.android.support:design:24.2.1' compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:support-v13:24.2.1' } ``` i get theese errors -->>> **GRADDLE ERROR:** :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources :app:processDebugManifest UP-TO-DATE :app:processDebugResources invalid resource directory name: C:\Users\weather\app\build\intermediates\res\merged\debug/values-b+sr+Latn FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugResources'. com.android.ide.common.process.ProcessException: Failed to execute aapt * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. **BUILD FAILED** When i deleted the "values-b+sr+Latn" folder containing the coresponding XML file, it always gets recreated by the studio when i build my project. I Tried to clean and build but that did not serve as solution to my problems. I am trying to run the app on ***KitKat(API Level 14)*** and want to have material design down to **HONEYCOMB(API Level 13)** and support application up to ***NOUGAT(API Level 24)*** Could you please point out my mistakes?
2016/10/09
[ "https://Stackoverflow.com/questions/39947606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029631/" ]
Try this in build.gradle ``` aaptOptions { ignoreAssetsPattern "!values-b+sr+Latn" } ```
To expand on powder366's answer, and the comment, since I don't have the rep to comment myself. Inside the Gradle Script called 'build.gradle' for the Project:Name, there is an 'android' section with brackets. Inside those brackets you can add > > aaptOptions { > ignoreAssetsPattern "!values-b+sr+Latn" > } > > > So you'd end up with something like ``` android { aaptOptions { ignoreAssetsPattern "!values-b+sr+Latn" } } ``` That fixed it for me right away, when Rebuilding the project
39,947,606
Hi i am trying to build my first project using Android support libraries in order to support material design for all of the devices on market. At the very begining of my journey i create a project from scratch and when i build from graddle using this module configuration: ``` apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "19.1" defaultConfig { applicationId "com.sunshine.org.weather" minSdkVersion 13 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) testCompile 'junit:junit:4.12' compile 'com.google.code.gson:gson:2.2.4' compile 'com.android.support:support-v4:24.2.1' compile 'com.android.support:design:24.2.1' compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:support-v13:24.2.1' } ``` i get theese errors -->>> **GRADDLE ERROR:** :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources :app:processDebugManifest UP-TO-DATE :app:processDebugResources invalid resource directory name: C:\Users\weather\app\build\intermediates\res\merged\debug/values-b+sr+Latn FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:processDebugResources'. com.android.ide.common.process.ProcessException: Failed to execute aapt * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. **BUILD FAILED** When i deleted the "values-b+sr+Latn" folder containing the coresponding XML file, it always gets recreated by the studio when i build my project. I Tried to clean and build but that did not serve as solution to my problems. I am trying to run the app on ***KitKat(API Level 14)*** and want to have material design down to **HONEYCOMB(API Level 13)** and support application up to ***NOUGAT(API Level 24)*** Could you please point out my mistakes?
2016/10/09
[ "https://Stackoverflow.com/questions/39947606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1029631/" ]
Try this in build.gradle ``` aaptOptions { ignoreAssetsPattern "!values-b+sr+Latn" } ```
### Some background > > Android 7.0 (API level 24) introduced support for BCP 47 language tags, which you can use to qualify language- and region-specific resources. A language tag is composed from a sequence of one or more subtags, each of which refines or narrows the range of language identified by the overall tag. For more information about language tags, see Tags for Identifying Languages. > > > To use a BCP 47 language tag, concatenate b+ and a two-letter ISO 639-1 language code, optionally followed by additional subtags separated by +. > > > Examples: > > > * b+en > * b+en+US > * b+es+419 > > > <https://developer.android.com/guide/topics/resources/providing-resources.html#QualifierRules> ### How to fix this Since this feature was introduced in API 24 I suspect updating build tools to at least 24 would resolve the issue. ``` android { buildToolsVersion "27.0.3" } ``` Latest Android plugin for Gradle will take care of build tools version automatically so you can remove the line altogether.
33,071,718
I have the below code to perform CRUD operations in my MVC program. ``` if (ModelState.IsValid) { CustomerDal dal = new CustomerDal(); dal.Customers.Add(obj); dal.Entry(obj).State = EntityState.Modified;//added this line to resolve issue but still no change dal.SaveChanges(); return View("customer", obj); } else { return View("entercustomer",obj); } ``` and my customerdal class ``` public class CustomerDal : DbContext { public CustomerDal(): base("CustomerDal") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Customer>().ToTable("tbCustomer"); } public DbSet<Customer>Customers { get; set; } } } ``` Customer class ``` public class Customer : DropCreateDatabaseIfModelChanges<CustomerDal> { [Required] [RegularExpression("^[A-Z]{3,3}[0-9]{4,4}$")] [Key] public string CustomerCode { get; set; } [Required] [StringLength(10)] public string CustomerName { get; set; } } ``` I am getting the below error when the program runs. > > Store update, insert, or delete statement affected an unexpected > number of rows (0). Entities may have been modified or deleted since > entities were loaded. See > <http://go.microsoft.com/fwlink/?LinkId=472540> for information on > understanding and handling optimistic concurrency exceptions. > > > There is no record exists in the table. This is a newly created table. when i inspect the element i can see all the items i tried before exist in the context but not updated to database. when i add new item which i didnt try before, the concurrency error will not occur. But the data will not update to database. Note:Im using MVC5
2015/10/12
[ "https://Stackoverflow.com/questions/33071718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/833985/" ]
First off you should fix the issues which Alde has mentioned. Next off what's up with the `while (true)` statement? You should probably replace it with `while (attempts != 0)` and set the: ``` if (attempts == 0) { cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!";//so the user can see the random number at the end of their attempts cout << "\n"; cin.get(); void Again(); } ``` out of the while scope. And about your `int reviewGuess(int, int)` function,are you looking for something like this: ``` int reviewGuess(int randomNumber,int userChoice) { if(randomNumber == userChoice) return 0; if(userChoice > 50) return 1; if(userChoice < 1) return -1; } ```
I see multiple issues: * you are missing a ending '}' at the end of PlayGame and Again functions * in the latter one the return is optional and should have a ';' at the end * you are comparing 'decision' with unitialized variables y, Y, n, and N... I guess you wanted compare its value with the chars 'y', 'Y', 'n', 'N' * the 'else if (decision != y, Y || n, N)' is not a valid syntax and you are already in that case with just an 'else' * you have an extra ';' at the end of 'void Again()' * you are trying to call a function with 'void PlayGame();' * the path the program is taking is not clean and you're doing unwanted recursion, it would be better to return a value instead I would have done something like this: ``` #include <iostream> #include <cstdlib> #include <ctime> using namespace std; void PlayGame() { const int HighestNum = 50; const int LowestNum = 1; int RandomNumber = LowestNum + rand() % HighestNum; cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n"; int attempts = 15; while (attempts > 0) { int guess; cout << "You have " << attempts << " attempt" << (attempts > 1 ? "s" : "") << " remaining\n"; cout << "Enter a number: "; cin >> guess; cout << endl; if (guess < LowestNum || guess > HighestNum) { cout << "Guess must be higher than " << LowestNum << " and be lower than " << HighestNum << ". Try again!\n" << endl; continue; } if (guess == RandomNumber) { cout << "Congratulations, you won!\n\n" << endl; return; } else if (guess < RandomNumber) { cout << "That guess is too low!\n" << endl; } else if (guess > RandomNumber) { cout << "That guess is too high!\n" << endl; } --attempts; } cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!\n\n"; } bool Menu() { cout << "Guess Number Game\n\n"; cout << "Menu\n\n"; cout << "1) Play Game\n"; cout << "2) Exit\n\n"; cout << "Enter your selection: "; int selection = 0; while (true) { cin >> selection; cout << endl; if (selection == 1) return true; else if (selection == 2) return false; else cout << "Try again, choose 1 or 2: "; } } bool Again() { cout << "1) Play Again\n"; cout << "2) Exit\n\n"; cout << "Enter your selection: "; int selection = 0; while (true) { cin >> selection; cout << endl; if (selection == 1) { return true; } else if (selection == 2) { return false; } else { cout << "Try again, choose 1 or 2: "; } } } int main() { srand(time(0)); bool play = Menu(); if (play) while (true) { PlayGame(); if (!Again()) break; } return 0; } ```
25,484,744
I have a quicksort program which executes as shown. But the last element is not getting sorted. Can anyone tell me how to modify the program to obtain the correct result. ``` #include <stdlib.h> #include <stdio.h> static void swap(void *x, void *y, size_t l) { char *a = x, *b = y, c; while(l--) { c = *a; *a++ = *b; *b++ = c; } } static void sort(char *array, size_t size, int (*cmp)(void*,void*), int begin, int end) { if (end > begin) { void *pivot = array + begin; int l = begin + size; int r = end; while(l < r) { if (cmp(array+l,pivot) <= 0) { l += size; } else if ( cmp(array+r, pivot) > 0 ) { r -= size; } else if ( l < r ) { swap(array+l, array+r, size); } } l -= size; swap(array+begin, array+l, size); sort(array, size, cmp, begin, l); sort(array, size, cmp, r, end); } } void qsort(void *array, size_t nitems, size_t size, int (*cmp)(void*,void*)) { sort(array, size, cmp, 0, (nitems-1)*size); } typedef int type; int type_cmp(void *a, void *b){ return (*(type*)a)-(*(type*)b); } int main(void) { /* simple test case for type=int */ int num_list[]={5,4,3,2,1}; int len=sizeof(num_list)/sizeof(type); char *sep=""; int i; qsort(num_list,len,sizeof(type),type_cmp); printf("sorted_num_list={"); for(i=0; i<len; i++){ printf("%s%d",sep,num_list[i]); sep=", "; } printf("};\n"); return 0; } ``` Result: ``` sorted_num_list={2, 3, 4, 5, 1}; ``` Why? I tried doing `(nitems)*size`. But when I try the same for strings, it gives me error
2014/08/25
[ "https://Stackoverflow.com/questions/25484744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3847567/" ]
The problem comes from this line: ``` sort(array, size, cmp, 0, (nitems-1)*size); ``` nitems is your number of items, here 5, you're substracting one so your quick sort will only sort the 4 first elements. Remove the -1 and it will work. ``` sort(array, size, cmp, 0, nitems*size); ```
2 mistakes here... First change `qsort()` function names to `qsort_user()` or any other name then the `qsort()` because `qsort()` is the standard function defined in `stdlib.h` --- Then change this line ``` sort(array, size, cmp, 0, (nitems-1)*size); ``` to ``` sort(array, size, cmp, 0, (nitems)*size); ```
3,329,958
I am a newbie to Android and the Eclipse development environment and would like some advice on best practices for debugging my apps when they throw a Force Close. I have researched ADB, however, I can not get this to interact with my phone even though I have explicitly turned debug mode to true on my test handset. Obviously Android comes with a LOG method which I have seen utilized in many example apps, can someone please explain how to review these logs quickly and how to setup logging appropriately to determine the cause of a Force Close (always occurs when I push the Home button). Any advice on debugging effectively in Eclipse would be much appreciated! Sincerely, Ryan
2010/07/25
[ "https://Stackoverflow.com/questions/3329958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459095/" ]
To debug using your device, you will need to have debug mode turned on (which it sounds like you do), you will then need to have the phone plugged in with the USB connector. From here, you can tell Eclipse to run/debug. Eclipse should ask which device to use (this is done because there should be multiple devices available for running/debugging since your device is plugged in). At this point, you can select your actual device from the list, and you should be up and running. If you are using android.util.Log, then your logs will show up in LogCat. If you do not see LogCat by default in your Eclipse environment, you can add it by doing the following: Go to Window -> Show View -> Other Select Android -> LogCat Cick OK. When running/debugging your device, you should see your Log statments in LogCat.
As I have never been able to get Eclipse to refresh the LogCat when I'm debugging on device, I will add this : You can also debug from command line like this : "adb -d logcat" However, as the windows command line is awfully basic, the line are cut in 2 most of the time. And my asking about your OS does help because the procedure is not the same to set up device debugging if you are on windows or linux or mac. For instance, in the case of windows, you need to install a driver (you can find all the doc [here](http://developer.android.com/sdk/win-usb.html)) before being able to debug on a device.
78,084
I have created a VF page rendered as pdf for QuoteLineItems in which I have added the list inside `<apex:repeat>` tags inside a html table row which again is inside another table.The problem however is that when the list includes more elements than the page can hold, the table borders gets streched and the remaining rows are displayed on the next page. This is my code for rendering the list ``` <table> <tr> <td> <table> <apex:repeat value="{!listQuoteLineItems}" var="product"> <tr style="page-break-inside:avoid;"> <td>{!product.Product2.Name}</td> <td>{!product.Quantity}</td> <td>{!product.TotalPrice}</td> </tr> </apex:repeat> </table> </td> </tr> </table> ``` I know i am supposed to use html `page-break` properties but not sure which and where! I need to display the tables w/o the borders being streched.I hope it is possible to display records partly on both the pages in such case.Please help in any way possible!!
2015/05/31
[ "https://salesforce.stackexchange.com/questions/78084", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/20324/" ]
I found an easy solution for the problem, no need to implement any logic for the same just included the following attribute `-fs-table-paginate: paginate;` in tables style tag and worked like a miracle.
What you want to do typically requires a custom controller. There's an excellent tutorial in the Technical Library titled [Creating Professional PDF Documents with CSS and Visualforce](https://developer.salesforce.com/page/Creating_Professional_PDF_Documents_with_CSS_and_Visualforce) that describes exactly how how to do what you're asking about. It basically involves composing your pages in the controller by counting the lines before they're sent to the page. Since the first is always different than the 2nd because of Company info and other details, the number of lines for the 1st page is less than subsequent pages and handled like below: ``` //controls how many quote line items are displayed on page 1 private static Integer FIRST_BREAK = 10; //controls how many quote line items are displayed on subsequent pages private static Integer SUBSEQ_BREAKS = 20; public List<SFDC_520_QuoteLine__c[]> pageBrokenQuoteLines {get; private set; } ``` Using the above technique, the quote line items are prepared for printing using a controller like below: ``` //splits the quote lines into an approximate number of rows that can be //displayed per page private void prepareQuoteLinesForPrinting() { pageBrokenQuoteLines = new List<SFDC_520_QuoteLine__c[]>(); SFDC_520_QuoteLine__c[] pageOfQuotes = new SFDC_520_QuoteLine__c[]{}; Integer counter = 0; boolean firstBreakFound = false; boolean setSubSeqBreak = false; Integer breakPoint = FIRST_BREAK; for(SFDC_520_QuoteLine__c q&nbsp;: quoteLineItems) { if(counter <= breakPoint) { pageOfQuotes.add(q); counter++; } if(counter == breakPoint) { if (!firstBreakFound) { firstBreakFound = true; setSubSeqBreak = true; } counter = 0; pageBrokenQuoteLines.add(pageOfQuotes); pageOfQuotes.clear(); } if(setSubSeqBreak) { breakPoint = SUBSEQ_BREAKS; setSubSeqBreak = false; } } //if we have finished looping and have some quotes left let's assign them if(!pageOfQuotes.isEmpty()) pageBrokenQuoteLines.add(pageOfQuotes); } ``` `FIRST_BREAK` and `SUBSEQ_BREAKS` are to split the array into smaller arrays which will fit on a page of the PDF quotation using the constructor defined below: ``` // constructor, loads the quote and any opportunity lines void queryQuoteLines(id id) { quote = [ Select s.Opportunity__r.Pricebook2Id, Quote_Amount_rollup__c, (Select Unit_Price__c, Unit_Net_Price__c, ServiceDate__c, Sales_Discount__c, Quote__c, Qty_Ordered__c, Product2__c, Product2__r.Name, Name, Id, Ext_Price__c, Ext_Net_Price__c, Ext_Price_tmp__c, Description__c From Quote_Lines__r order by name ), s.Opportunity__r.HasOpportunityLineItem, s.Opportunity__r.Name, s.Name, s.Opportunity__r.Id, s.Opportunity__c From SFDC_520_Quote__c s where s.id =&nbsp;:id limit 1]; quoteLineItems = quote.Quote_Lines__r; for ( SFDC_520_QuoteLine__c ql&nbsp;: quoteLineItems ) { ql.Ext_Price_tmp__c = ql.Ext_Net_Price__c; if ( ql.Sales_Discount__c == null ) ql.Sales_Discount__c = 0.0; } prepareQuoteLinesForPrinting(); } ``` In code provided for this example, the page is constructed using a datatable, but an html table is actually the preferred way to do this like you're currently using. As such, you can ignore much of the style sheet. The important part of that code is the following: ``` page-break-after:always ``` Unfortunately, the above CSSS line used by itself won't solve your problem without precomposing your pages. You can also number your pages and set the orientation using code like below: ``` @page { /* Landscape orientation */ size:landscape; /* Put page numbers in the top right corner of each page in the pdf document. */ @bottom-right { content: "Page " counter(page) " of " counter(pages); } ``` You'll find more details and a further explanation of how to use this code in the link provided above.
14,772,115
I'm using the Javascript SDK for facebook to login a user with Facebook: Documentation FB.Login: [link](http://developers.facebook.com/docs/reference/javascript/FB.login/) Unfortunatly this dialog is always in English. FB.Dialog will trigger a popup window with url: ``` https://www.facebook.com/login.php?PARAMETERS ``` With the help of another related [question](https://stackoverflow.com/questions/8557509/how-to-change-language-in-facebook-login-page) here I found that I can add locale2 parameter: ``` https://www.facebook.com/login.php?PARAMETERS&locale2=es_ES ``` With this extra parameter the dialog is now shown in Spanish. But I can't find how to pass this language paramter to the FB.Login function so it's also used in the login dialog. Is there any function known that can help me with this issue?
2013/02/08
[ "https://Stackoverflow.com/questions/14772115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681803/" ]
It might be something to do with the SDK source you are using From <http://developers.facebook.com/docs/reference/javascript/> ``` js.src = "//connect.facebook.net/en_US/all.js"; ``` Change **en\_US** to your language locale **es\_ES** and that might fix it.
You can set locale while loading Facebook SDK: ``` // Load the SDK Asynchronously (function (d) { var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) { return; } js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_GB/all.js"; ref.parentNode.insertBefore(js, ref); } (document)); ``` As you can see, in link assigned to `js.src` there is `en_GB` part. If you want to load SDK with current user's locale, you can check the locale before loading SDK and then use this here.
53,816,702
I looked into `stackoverflow`, and found a solution on how to remove animation from the default `bottom navigation.` Now i need to remove the title from bottom navigation. I set empty string in title of bottom navigation xml file, but it does not change the position of images. **I'm working with v27** I need to center the images in `bottom navigation.` once text is removed. This is my code. ``` //OnCreate BottomNavigationViewHelper.removeShiftMode(bottomNavigationView); ``` **Static Class inside MainActivity** ``` public static class BottomNavigationViewHelper { @SuppressLint("RestrictedApi") public static void removeShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); try { Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); shiftingMode.setAccessible(true); shiftingMode.setBoolean(menuView, false); shiftingMode.setAccessible(false); for (int i = 0; i < menuView.getChildCount(); i++) { BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); //noinspection RestrictedApi item.setShiftingMode(false); // set once again checked value, so view will be updated //noinspection RestrictedApi item.setChecked(item.getItemData().isChecked()); } } catch (NoSuchFieldException e) { Log.e("BottomNav", "Unable to get shift mode field", e); } catch (IllegalAccessException e) { Log.e("BottomNav", "Unable to change value of shift mode", e); } } } ```
2018/12/17
[ "https://Stackoverflow.com/questions/53816702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977669/" ]
You could try to add the app:labelVisibilityMode to "unlabeled" ``` <android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:labelVisibilityMode="unlabeled"/> ```
I use variations of the below code to customize the labels of `BottomNavigationView` which are essentially TextViews: ``` private void removeBottomNavigationLabels(BottomNavigationView bottomNavigationView) { for (int i = 0; i < bottomNavigationView.getChildCount(); i++) { View item = bottomNavigationView.getChildAt(i); if (item instanceof BottomNavigationMenuView) { BottomNavigationMenuView menu = (BottomNavigationMenuView) item; for (int j = 0; j < menu.getChildCount(); j++) { View menuItem = menu.getChildAt(j); View small = menuItem.findViewById(android.support.design.R.id.smallLabel); if (small instanceof TextView) { ((TextView) small).setVisibility(View.GONE); } View large = menuItem.findViewById(android.support.design.R.id.largeLabel); if (large instanceof TextView) { ((TextView) large).setVisibility(View.GONE); } } } } BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0); for (int i = 0; i < menuView.getChildCount(); i++) { final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon); iconView.setPadding(0, 40, 0, 0); ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams(); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics); layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics); iconView.setLayoutParams(layoutParams); } } ``` You can call it like this: ``` removeBottomNavigationLabels(yourBottomNavigationView); ``` You could also try similarly to change the visibility, padding or height of the TextViews.
53,816,702
I looked into `stackoverflow`, and found a solution on how to remove animation from the default `bottom navigation.` Now i need to remove the title from bottom navigation. I set empty string in title of bottom navigation xml file, but it does not change the position of images. **I'm working with v27** I need to center the images in `bottom navigation.` once text is removed. This is my code. ``` //OnCreate BottomNavigationViewHelper.removeShiftMode(bottomNavigationView); ``` **Static Class inside MainActivity** ``` public static class BottomNavigationViewHelper { @SuppressLint("RestrictedApi") public static void removeShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); try { Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); shiftingMode.setAccessible(true); shiftingMode.setBoolean(menuView, false); shiftingMode.setAccessible(false); for (int i = 0; i < menuView.getChildCount(); i++) { BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); //noinspection RestrictedApi item.setShiftingMode(false); // set once again checked value, so view will be updated //noinspection RestrictedApi item.setChecked(item.getItemData().isChecked()); } } catch (NoSuchFieldException e) { Log.e("BottomNav", "Unable to get shift mode field", e); } catch (IllegalAccessException e) { Log.e("BottomNav", "Unable to change value of shift mode", e); } } } ```
2018/12/17
[ "https://Stackoverflow.com/questions/53816702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977669/" ]
You could try to add the app:labelVisibilityMode to "unlabeled" ``` <android.support.design.widget.BottomNavigationView android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="wrap_content" app:labelVisibilityMode="unlabeled"/> ```
try using these attributes: ``` showUnselectedLabels: false showSelectedLabels: false ```
53,816,702
I looked into `stackoverflow`, and found a solution on how to remove animation from the default `bottom navigation.` Now i need to remove the title from bottom navigation. I set empty string in title of bottom navigation xml file, but it does not change the position of images. **I'm working with v27** I need to center the images in `bottom navigation.` once text is removed. This is my code. ``` //OnCreate BottomNavigationViewHelper.removeShiftMode(bottomNavigationView); ``` **Static Class inside MainActivity** ``` public static class BottomNavigationViewHelper { @SuppressLint("RestrictedApi") public static void removeShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); try { Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); shiftingMode.setAccessible(true); shiftingMode.setBoolean(menuView, false); shiftingMode.setAccessible(false); for (int i = 0; i < menuView.getChildCount(); i++) { BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); //noinspection RestrictedApi item.setShiftingMode(false); // set once again checked value, so view will be updated //noinspection RestrictedApi item.setChecked(item.getItemData().isChecked()); } } catch (NoSuchFieldException e) { Log.e("BottomNav", "Unable to get shift mode field", e); } catch (IllegalAccessException e) { Log.e("BottomNav", "Unable to change value of shift mode", e); } } } ```
2018/12/17
[ "https://Stackoverflow.com/questions/53816702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977669/" ]
I use variations of the below code to customize the labels of `BottomNavigationView` which are essentially TextViews: ``` private void removeBottomNavigationLabels(BottomNavigationView bottomNavigationView) { for (int i = 0; i < bottomNavigationView.getChildCount(); i++) { View item = bottomNavigationView.getChildAt(i); if (item instanceof BottomNavigationMenuView) { BottomNavigationMenuView menu = (BottomNavigationMenuView) item; for (int j = 0; j < menu.getChildCount(); j++) { View menuItem = menu.getChildAt(j); View small = menuItem.findViewById(android.support.design.R.id.smallLabel); if (small instanceof TextView) { ((TextView) small).setVisibility(View.GONE); } View large = menuItem.findViewById(android.support.design.R.id.largeLabel); if (large instanceof TextView) { ((TextView) large).setVisibility(View.GONE); } } } } BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0); for (int i = 0; i < menuView.getChildCount(); i++) { final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon); iconView.setPadding(0, 40, 0, 0); ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams(); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); layoutParams.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics); layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32, displayMetrics); iconView.setLayoutParams(layoutParams); } } ``` You can call it like this: ``` removeBottomNavigationLabels(yourBottomNavigationView); ``` You could also try similarly to change the visibility, padding or height of the TextViews.
try using these attributes: ``` showUnselectedLabels: false showSelectedLabels: false ```
3,125,692
I have a list of objects, each with a bool ShouldRun() method on them. I am currently iterating over the list of objects, and checking ShouldRun() on each object, and calling Run() on the first one to return true ``` foreach (child in Children) { if (child.ShouldRun()) { child.Run(); break; } } ``` I would like to do this in parallel, because evaluating shouldRun can take a decent amount of time, and it is advantageous to let later elements in the collection start their evaluation early. However, I cannot think of a way to do this that will satisfy these conditions : 1 Only run one item 2 Do not run a later item if an earlier item is true, or has not finished evaluating yet 3 If all "earlier" items have returned false, and a middle item returns true, do not wait on a later item to finish evaluating because you know it can't override anything earlier. I thought of doing a parallel "where" linq query to retrieve all the items that shouldRun() and then sorting, but this will violate condition #3 Ideas? Background info : The system is for a generalized robotics AI system. Some of the higher priority tasks can be triggered by immediately known sensor variables eg : Im falling over, fix it! other tasks might be computationally intensive (do image recognition from the camera, and approach visible objectives) other tasks might be database or remotely driven (look up a list of probable objective locations from a database, and then navigate there to see if you can get into visible range of one of them) Some of the tasks themselves have child tasks, which is essentially going to start this process over recursively at a subset of tasks, and the grandchild task will be passed up through the chain
2010/06/26
[ "https://Stackoverflow.com/questions/3125692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56472/" ]
I'm not a PLINQ genius, but wouldn't this simpler answer suffice? ``` var childToRun = Children.AsParallel().AsOrdered() .Where(x => x.ShouldRun()).FirstOrDefault(); childToRun.Run(); ```
Just a concept of way I would try to do it. Run all `ShouldRun()`'s in parallel. Put the results to the ordered list along with the items and indexes of the items (e.g. ShouldRun() of third item ends with false, the list would contain something like: 2,false,item). In another thread, keep current index starting with 0 and check the ordered list periodically. If the next index on the list equals to current, process the result and advance the current index.
3,125,692
I have a list of objects, each with a bool ShouldRun() method on them. I am currently iterating over the list of objects, and checking ShouldRun() on each object, and calling Run() on the first one to return true ``` foreach (child in Children) { if (child.ShouldRun()) { child.Run(); break; } } ``` I would like to do this in parallel, because evaluating shouldRun can take a decent amount of time, and it is advantageous to let later elements in the collection start their evaluation early. However, I cannot think of a way to do this that will satisfy these conditions : 1 Only run one item 2 Do not run a later item if an earlier item is true, or has not finished evaluating yet 3 If all "earlier" items have returned false, and a middle item returns true, do not wait on a later item to finish evaluating because you know it can't override anything earlier. I thought of doing a parallel "where" linq query to retrieve all the items that shouldRun() and then sorting, but this will violate condition #3 Ideas? Background info : The system is for a generalized robotics AI system. Some of the higher priority tasks can be triggered by immediately known sensor variables eg : Im falling over, fix it! other tasks might be computationally intensive (do image recognition from the camera, and approach visible objectives) other tasks might be database or remotely driven (look up a list of probable objective locations from a database, and then navigate there to see if you can get into visible range of one of them) Some of the tasks themselves have child tasks, which is essentially going to start this process over recursively at a subset of tasks, and the grandchild task will be passed up through the chain
2010/06/26
[ "https://Stackoverflow.com/questions/3125692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56472/" ]
I'm not a PLINQ genius, but wouldn't this simpler answer suffice? ``` var childToRun = Children.AsParallel().AsOrdered() .Where(x => x.ShouldRun()).FirstOrDefault(); childToRun.Run(); ```
You should be able to do a parallel select with the indices attached, then sort the result based on index and pick the first which returned `true`. I don't have an IDE on this machine so this is untested, but something like: ``` var runnables = Children.AsParallel() .Select(child, index => new { Index = index, ShouldRun = child.ShouldRun(), Child = child }) .ToList(); //force evaluation var firstRunner = runnables.OrderBy(r => r.Index) .First(r => r.ShouldRun) //assuming at least one //else use FirstOrDefault and null-check .Child; firstRunner.Run(); ``` edit: better query for the first runner - ``` var firstRunner = runnables.Where(r => r.ShouldRun) // less stuff to sort later .OrderBy(r => r.Index) .First(); // no need for predicate here anymore ``` edit2: this doesn't satisfy your condition #3, though.
3,125,692
I have a list of objects, each with a bool ShouldRun() method on them. I am currently iterating over the list of objects, and checking ShouldRun() on each object, and calling Run() on the first one to return true ``` foreach (child in Children) { if (child.ShouldRun()) { child.Run(); break; } } ``` I would like to do this in parallel, because evaluating shouldRun can take a decent amount of time, and it is advantageous to let later elements in the collection start their evaluation early. However, I cannot think of a way to do this that will satisfy these conditions : 1 Only run one item 2 Do not run a later item if an earlier item is true, or has not finished evaluating yet 3 If all "earlier" items have returned false, and a middle item returns true, do not wait on a later item to finish evaluating because you know it can't override anything earlier. I thought of doing a parallel "where" linq query to retrieve all the items that shouldRun() and then sorting, but this will violate condition #3 Ideas? Background info : The system is for a generalized robotics AI system. Some of the higher priority tasks can be triggered by immediately known sensor variables eg : Im falling over, fix it! other tasks might be computationally intensive (do image recognition from the camera, and approach visible objectives) other tasks might be database or remotely driven (look up a list of probable objective locations from a database, and then navigate there to see if you can get into visible range of one of them) Some of the tasks themselves have child tasks, which is essentially going to start this process over recursively at a subset of tasks, and the grandchild task will be passed up through the chain
2010/06/26
[ "https://Stackoverflow.com/questions/3125692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56472/" ]
I'm not a PLINQ genius, but wouldn't this simpler answer suffice? ``` var childToRun = Children.AsParallel().AsOrdered() .Where(x => x.ShouldRun()).FirstOrDefault(); childToRun.Run(); ```
I'm puzzled as to why you have a "ShouldRun" flag on each child, rather than having earlier placed each child that you would mark as "ShouldRun" into a "RunThese" set. Then you only have to ask if the RunThese set size is zero or not, and if not zero, run them all. [Of course, if you are going to run them, why even mark/set union them? You could just launch them when you discover you should run them. If you think the ShouldRun logic is expensive, then fork it the moment you have the child to decide whether you should run the child.]
34,220,398
I'm attempting to install a custom build on heroku, so I'm using a variety of ways to attempt a third part installing using the buildpacks. In my .buildpacks file I have: ``` https://github.com/ddollar/heroku-buildpack-apt https://github.com/heroku/heroku-buildpack-python.git ``` and in my `Aptfile` I have the following: `libgeoip-dev` which is a pre-requisite for geoip which is installed with the `requirements.txt` (`GeoIP==1.3.2`) Here are my environment variables: ``` remote: C_INCLUDE_PATH is /app/.heroku/vendor/include:/app/.heroku/vendor/include:/app/.heroku/python/include remote: CPATH is /tmp/build_xxxxx/.apt/usr/include: remote: LD_LIBRARY_PATH is /app/.heroku/vendor/lib:/app/.heroku/vendor/lib:/app/.heroku/python/lib ``` The error message I am getting is: ``` remote: building 'GeoIP' extension remote: creating build remote: creating build/temp.linux-x86_64-2.7 remote: gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/app/.heroku/python/include/python2.7 -c py_GeoIP.c -o build/temp.linux-x86_64-2.7/py_GeoIP.o -fno-strict-aliasing remote: creating build/lib.linux-x86_64-2.7 remote: gcc -pthread -shared build/temp.linux-x86_64-2.7/py_GeoIP.o -lGeoIP -o build/lib.linux-x86_64-2.7/GeoIP.so remote: /usr/bin/ld: cannot find -lGeoIP remote: collect2: error: ld returned 1 exit status remote: error: command 'gcc' failed with exit status 1 ``` What is the smartest way to fix this? I.e. I guess I cannot change where the package manager installs. Is there a way around this?
2015/12/11
[ "https://Stackoverflow.com/questions/34220398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673600/" ]
<https://github.com/heroku/heroku-buildpack-python/blob/master/bin/compile#L99-L107> ``` # Prepend proper path buildpack use. export PATH=$BUILD_DIR/.heroku/python/bin:$BUILD_DIR/.heroku/vendor/bin:$PATH export PYTHONUNBUFFERED=1 export LANG=en_US.UTF-8 export C_INCLUDE_PATH=/app/.heroku/vendor/include:$BUILD_DIR/.heroku/vendor/include:/app/.heroku/python/include export CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:$BUILD_DIR/.heroku/vendor/include:/app/.heroku/python/include export LIBRARY_PATH=/app/.heroku/vendor/lib:$BUILD_DIR/.heroku/vendor/lib:/app/.heroku/python/lib export LD_LIBRARY_PATH=/app/.heroku/vendor/lib:$BUILD_DIR/.hero ku/vendor/lib:/app/.heroku/python/lib export PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkg-config:$BUILD_DIR/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config ``` vs. <https://github.com/ddollar/heroku-buildpack-apt/blob/master/bin/compile#L75-L81> ``` export PATH="$BUILD_DIR/.apt/usr/bin:$PATH" export LD_LIBRARY_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu:$BUILD_DIR/.apt/usr/lib:$LD_LIBRARY_PATH" export LIBRARY_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu:$BUILD_DIR/.apt/usr/lib:$LIBRARY_PATH" export INCLUDE_PATH="$BUILD_DIR/.apt/usr/include:$INCLUDE_PATH" export CPATH="$INCLUDE_PATH" export CPPPATH="$INCLUDE_PATH" export PKG_CONFIG_PATH="$BUILD_DIR/.apt/usr/lib/x86_64-linux-gnu/pkgconfig:$BUILD_DIR/.apt/usr/lib/i386-linux-gnu/pkgconfig:$BUILD_DIR/.apt/usr/lib/pkgconfig:$PKG_CONFIG_PATH" ``` The `heroku-buildpack-python` buildpack is not playing nice with `heroku-buildpack-apt` buildpack as it is clobbering important variables for `gcc` to link your python extension with the `geoip` lib. File a bug on the issue tracker. Issue tracker: <https://github.com/heroku/heroku-buildpack-python/issues>
I naively solved a similar problem by modifying heroku-buildpack-python's compile script to not unset LD\_LIBRARY\_PATH and INCLUDE\_PATH, as well as to append the current LD\_LIBRARY\_PATH and INCLUDE\_PATH variables during their export so as to not overwrite them. Here is my fork: <https://github.com/jasrusable/heroku-buildpack-python>
45,336
While playing Phase Ten, is it legal to pick up the top card of the discard pile and then immediately discard that exact card?
2019/02/28
[ "https://boardgames.stackexchange.com/questions/45336", "https://boardgames.stackexchange.com", "https://boardgames.stackexchange.com/users/26637/" ]
Yes. You draw the card, put it into your hand, and then discard **any** card from your hand (which may be the card you just drew).
Yes. You should rather pick up a card from the pile to get a chance to help you. But if you want to do that yes you can.
37,589
Is there any McAfee API [ or command line utility ] that can be integrated with ASP.Net to scan for viruses in uploaded files. **Edit:** I was about to ask the question in stackoverflow but thought since it is related to McAfee only it would be better to put this question in here. ***Edit:*** I don't need a 3rd party tool to connect to the McAfee API.
2009/09/08
[ "https://superuser.com/questions/37589", "https://superuser.com", "https://superuser.com/users/2959/" ]
After doing a little digging for you, it doesn't look like the Mcafee API is commonly available. You need to get in contact directly with them if you want samples, however there are third party tools that can plugin to many other AV scanners such as those available from [Opswat](http://www.opswat.com/) which comes with a very good API for many languages. Edit - Probably not the best way of going around it, but if you need to use Mcafee (a few other AV's actually provide API's out the box) - You could always just install it on the server and disable all the active scan parts and then just call the scanner exe via command line arguments and wait for a response code - the same way as many download managers, IM clients and others hook into third party anti virus scanners.
You could try using the [Microsoft Antivirus API](http://msdn.microsoft.com/en-us/library/ms537365%28VS.85%29.aspx). It is a COM API that can be used to scan files. This is the same API that Internet Explorer and Outlook use to scan downloaded files.
37,589
Is there any McAfee API [ or command line utility ] that can be integrated with ASP.Net to scan for viruses in uploaded files. **Edit:** I was about to ask the question in stackoverflow but thought since it is related to McAfee only it would be better to put this question in here. ***Edit:*** I don't need a 3rd party tool to connect to the McAfee API.
2009/09/08
[ "https://superuser.com/questions/37589", "https://superuser.com", "https://superuser.com/users/2959/" ]
After doing a little digging for you, it doesn't look like the Mcafee API is commonly available. You need to get in contact directly with them if you want samples, however there are third party tools that can plugin to many other AV scanners such as those available from [Opswat](http://www.opswat.com/) which comes with a very good API for many languages. Edit - Probably not the best way of going around it, but if you need to use Mcafee (a few other AV's actually provide API's out the box) - You could always just install it on the server and disable all the active scan parts and then just call the scanner exe via command line arguments and wait for a response code - the same way as many download managers, IM clients and others hook into third party anti virus scanners.
Yes, you can look at [McAfee VirusScan Command Line Reference](https://kc.mcafee.com/resources/sites/MCAFEE/content/live/PRODUCT_DOCUMENTATION/20000/PD20010/en_US/e5200wpg.pdf).
37,589
Is there any McAfee API [ or command line utility ] that can be integrated with ASP.Net to scan for viruses in uploaded files. **Edit:** I was about to ask the question in stackoverflow but thought since it is related to McAfee only it would be better to put this question in here. ***Edit:*** I don't need a 3rd party tool to connect to the McAfee API.
2009/09/08
[ "https://superuser.com/questions/37589", "https://superuser.com", "https://superuser.com/users/2959/" ]
Yes, you can look at [McAfee VirusScan Command Line Reference](https://kc.mcafee.com/resources/sites/MCAFEE/content/live/PRODUCT_DOCUMENTATION/20000/PD20010/en_US/e5200wpg.pdf).
You could try using the [Microsoft Antivirus API](http://msdn.microsoft.com/en-us/library/ms537365%28VS.85%29.aspx). It is a COM API that can be used to scan files. This is the same API that Internet Explorer and Outlook use to scan downloaded files.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
There are a few different ways to attack this - note that the tool instructions will vary a bit, based on what version of Windows CE / Windows Mobile you are using. Some questions to answer: **1. Is your application leaking memory, leading to this low memory condition?** **2. Does your application simply use too much memory at certain stages, leading to this low memory condition?** 1 and 2 can be investigated using the Windows CE AppVerifier tool, which can provide detailed memory logging tools for your product. Other heap wrapping tools can also provide similar information (and may be higher-performance), depending on your product design. <http://msdn.microsoft.com/en-us/library/aa446904.aspx> **3. Are you allocating and freeing memory very frequently in this process?** Windows CE, prior to OS version 6.0 (don't confuse with Windows Mobile 6.x) had a 32MB / process virtual memory limit, which tends to cause lots of fun fragmentation issues. In this case, even if you have sufficient physical memory free, you might be running out of virtual memory. Use of custom block allocators is usually a mitigation for this problem. **4. Are you allocating very large blocks of memory? (> 2MB)** Related to 3, you could just be exhausting the process virtual memory space. There are tricks, somewhat dependent on OS version, to allocate memory in a shared VM space, outside the process space. If you are running out of VM, but not physical RAM, this could help. **5. Are you using large numbers of DLLs?** Also related to 3, Depending on OS version, DLLs may also reduce total available VM very quickly. **Further jumping off points:** Overview of CE memory tools <http://blogs.msdn.com/ce_base/archive/2006/01/11/511883.aspx> Target control window 'mi' tool <http://msdn.microsoft.com/en-us/library/aa450013.aspx>
There are lots of good things in the other answers, but I did think it worth adding that if all the threads get in a similar loop, then the program will be deadlocked. The "correct" answer to this situation is probably to have strict limits for the different parts of the program to ensure that they don't over consume memory. That would probably require rewriting major sections across all parts of the program. The next best solution would be to have some callback where a failed allocation attempt can tell the rest of the program that more memory is needed. Perhaps other parts of the program can release some buffers more aggressively than they normally would, or release memory used to cache search results, or something. This would require new code for other parts of the program. However, this could be done incrementally, rather than requiring a rewrite across the entire program. Another solution would be to have the program protect large (temporary) memory requests with a mutex. It sounds like you are confident that memory will be released soon if you can just try again later. I suggest that you use a mutex for operations that might consume a lot of memory, this will allow the thread to be woken up immediately when another thread has released the memory that is needed. Otherwise your thread will sleep for a tenth of a second even if the memory frees up immediately. You might also try sleep(0), which will simply hand off control to any other thread that is ready to run. This will allow your thread to regain control immediately if all other threads go to sleep, rather than having to wait out its 100 millisecond sentence. But if at least one thread still wants to run, you will still have to wait until it gives up control. This is typically 10 milliseconds on Linux machines, last I checked. I don't know about other platforms. Your thread may also have a lower priority in the scheduler if it has voluntarily gone to sleep.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
A few points: * Embedded programs often allocate all memory at startup or use only static memory to avoid situations like this. * Unless there is something else running on the device that frees memory on a regular basis your solution isn't likely to be effective. * The Viper I have has 64MB RAM, I don't think they come with less than 32MB, how much memory is your application using?
Surely it would depend on whether you have a reasonable expectation of memory becoming available in the 100 (millisecond?) sleep? Certainly, you should limit the number of times it attempts. To me something doesn't smell right here. Hmmm... Embedded systems typically need to be extremely deterministic - perhaps you should review the entire system and head of the potential for this to fail up front; and then just fail hard it it actually happens in practice.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
There are lots of good things in the other answers, but I did think it worth adding that if all the threads get in a similar loop, then the program will be deadlocked. The "correct" answer to this situation is probably to have strict limits for the different parts of the program to ensure that they don't over consume memory. That would probably require rewriting major sections across all parts of the program. The next best solution would be to have some callback where a failed allocation attempt can tell the rest of the program that more memory is needed. Perhaps other parts of the program can release some buffers more aggressively than they normally would, or release memory used to cache search results, or something. This would require new code for other parts of the program. However, this could be done incrementally, rather than requiring a rewrite across the entire program. Another solution would be to have the program protect large (temporary) memory requests with a mutex. It sounds like you are confident that memory will be released soon if you can just try again later. I suggest that you use a mutex for operations that might consume a lot of memory, this will allow the thread to be woken up immediately when another thread has released the memory that is needed. Otherwise your thread will sleep for a tenth of a second even if the memory frees up immediately. You might also try sleep(0), which will simply hand off control to any other thread that is ready to run. This will allow your thread to regain control immediately if all other threads go to sleep, rather than having to wait out its 100 millisecond sentence. But if at least one thread still wants to run, you will still have to wait until it gives up control. This is typically 10 milliseconds on Linux machines, last I checked. I don't know about other platforms. Your thread may also have a lower priority in the scheduler if it has voluntarily gone to sleep.
As others have mentioned, ideally, you would avoid this problem by up-front design and software architecture, but I’m assuming at this point that really isn’t an option. As another post mentions, it would be good to wrap the logic in some utility functions so that you don’t end up writing the out-of-memory code all of the place. To get to the real problem, you try to use a shared resource, memory, but are unable to because that shared resource is being used by another thread in the system. Ideally what you would like to do is wait for one of the other threads in the system to release the resource you need, and then acquire that resource. If you had a way of intercepting all the allocation and free calls you could set-up something so that the allocating thread blocked until memory was available, and the freeing signalled the allocating thread when memory was available. But I’m going to assume that is simply too much work. Given the constraints of not being able to totally re-architect the system, or re-write the memory allocator, then I think your solution is the most practical, as long as you (and the others on your team), understand the limitations, and the problems it will cause down the track. Now to improve your specific approach, you may want to measure the workloads to see how often memory is allocated and freed. This would give you a better ay of calculating what the retry interval should be. Secondly, you way want to try increasing the time-out for each iteration to reduce the load of that thread on the system. Finally, you definitely should have some time of error/panic case if the thread is unable to make progress after some number of iterations. This will let you at least see the potential live-lock case you may encounter if all threads are waiting for another thread in the system to free memory. You could simply pick a number of iterations based on what is empirically shown to work, or you could get smarter about it and keep track of how many threads are stuck waiting for memory, and if that ends up being all threads panic. *Note*: This is obviously not a perfect solution and as the other posters have mentioned a more global view of the application as a whole is needed to solve the problem correctly, but the above is a practical technique that should work in the short-term.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options: * Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, **yes, it is possible to allocate everything statically**. It's just a lot of work, and **every time you change your system's configuration, you have to reconsider the allocations**. * Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They **cooperate so they don't run out of memory**. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a [paper about this approach](http://portal.acm.org/citation.cfm?id=98753). * Each process is aware that memory can become exhausted and can **fail over to a state in which it consumes a minimum amount of memory**. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, **it can lead to thrashing.** **Your proposal above matches none of the scenarios.** Instead, you are hoping **some other process will solve the problem** and the memory you need will eventually appear. You might get lucky. You might not. If you want your system to work reliably, you would do well to **reconsider the design of every process running on the system** in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck!
You use C++. So you can make use of some C++ utilities to make your life easier. For example, why not use new\_handler? ``` void my_new_handler() { // make room for memory, then return, or throw bad_alloc if // nothing can be freed. } int main() { std::set_new_handler(&my_new_handler); // every allocation done will ask my_new_handler if there is // no memory for use anymore. This answer tells you what the // standard allocator function does: // https://stackoverflow.com/questions/377178 } ``` In the new\_handler, you could send all applications a signal so that they know that memory is needed for some application, and then wait a bit to give other applications the time to fulfill the request for memory. Important is that you **do something** and not **silently hope** for available memory. The new operator will call your handler again if still not enough memory is available, so you don't have to worry about whether or not all applications have free'ed the needed memory already. You can also **overload operator new** if you need to know the size of memory that is needed in the new\_handler. See my [other answer](https://stackoverflow.com/questions/365887/how-do-malloc-and-new-work-how-are-they-different-implementation-wise#365891) on how to do that. This way, you have **one central place** to handle memory problems, instead of many places concerned with that.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
I second that the most sensible thing to do is to use static allocation of memory, so you have some idea of what is going on. Dynamic memory allocation is a bad habit from desktop programming that is not suited on restricted-resource machines (unless you spend a fair bit of time and effort creating a good managed and controlled memory management system). Also, check what features the OS in your device (assuming it has one, high-end ARM devices like this one tends to run an OS) has for handling memory.
Surely it would depend on whether you have a reasonable expectation of memory becoming available in the 100 (millisecond?) sleep? Certainly, you should limit the number of times it attempts. To me something doesn't smell right here. Hmmm... Embedded systems typically need to be extremely deterministic - perhaps you should review the entire system and head of the potential for this to fail up front; and then just fail hard it it actually happens in practice.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
Based on your question, I'm assuming that your heap is shared between multiple threads. If it isn't then the code above won't work, because nothing will be freed from the heap while the loop is running. If the heap is shared, then the above would probably work. However, if you have a shared heap, then calling "new" will probably result in either a spin lock ( a similar loop to the one you have, but using CAS instructions), or it will block based on some kernel resources. In both cases, the loop you have will decrease the throughput of your system. This is because you will either incur more context switches then you need to, or will take longer to respond to the "memory is now available" event. I would consider overriding the "new" and "delete" operators. When new fails you can block (or spin lock on a counter variable of some sort) waiting for another thread to free memory, and then delete can either signal the blocked "new" thread or increment the counter variable using CAS. That should give you better throughput and be a bit more efficent
Surely it would depend on whether you have a reasonable expectation of memory becoming available in the 100 (millisecond?) sleep? Certainly, you should limit the number of times it attempts. To me something doesn't smell right here. Hmmm... Embedded systems typically need to be extremely deterministic - perhaps you should review the entire system and head of the potential for this to fail up front; and then just fail hard it it actually happens in practice.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
You use C++. So you can make use of some C++ utilities to make your life easier. For example, why not use new\_handler? ``` void my_new_handler() { // make room for memory, then return, or throw bad_alloc if // nothing can be freed. } int main() { std::set_new_handler(&my_new_handler); // every allocation done will ask my_new_handler if there is // no memory for use anymore. This answer tells you what the // standard allocator function does: // https://stackoverflow.com/questions/377178 } ``` In the new\_handler, you could send all applications a signal so that they know that memory is needed for some application, and then wait a bit to give other applications the time to fulfill the request for memory. Important is that you **do something** and not **silently hope** for available memory. The new operator will call your handler again if still not enough memory is available, so you don't have to worry about whether or not all applications have free'ed the needed memory already. You can also **overload operator new** if you need to know the size of memory that is needed in the new\_handler. See my [other answer](https://stackoverflow.com/questions/365887/how-do-malloc-and-new-work-how-are-they-different-implementation-wise#365891) on how to do that. This way, you have **one central place** to handle memory problems, instead of many places concerned with that.
Surely it would depend on whether you have a reasonable expectation of memory becoming available in the 100 (millisecond?) sleep? Certainly, you should limit the number of times it attempts. To me something doesn't smell right here. Hmmm... Embedded systems typically need to be extremely deterministic - perhaps you should review the entire system and head of the potential for this to fail up front; and then just fail hard it it actually happens in practice.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options: * Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, **yes, it is possible to allocate everything statically**. It's just a lot of work, and **every time you change your system's configuration, you have to reconsider the allocations**. * Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They **cooperate so they don't run out of memory**. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a [paper about this approach](http://portal.acm.org/citation.cfm?id=98753). * Each process is aware that memory can become exhausted and can **fail over to a state in which it consumes a minimum amount of memory**. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, **it can lead to thrashing.** **Your proposal above matches none of the scenarios.** Instead, you are hoping **some other process will solve the problem** and the memory you need will eventually appear. You might get lucky. You might not. If you want your system to work reliably, you would do well to **reconsider the design of every process running on the system** in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck!
As others have mentioned, ideally, you would avoid this problem by up-front design and software architecture, but I’m assuming at this point that really isn’t an option. As another post mentions, it would be good to wrap the logic in some utility functions so that you don’t end up writing the out-of-memory code all of the place. To get to the real problem, you try to use a shared resource, memory, but are unable to because that shared resource is being used by another thread in the system. Ideally what you would like to do is wait for one of the other threads in the system to release the resource you need, and then acquire that resource. If you had a way of intercepting all the allocation and free calls you could set-up something so that the allocating thread blocked until memory was available, and the freeing signalled the allocating thread when memory was available. But I’m going to assume that is simply too much work. Given the constraints of not being able to totally re-architect the system, or re-write the memory allocator, then I think your solution is the most practical, as long as you (and the others on your team), understand the limitations, and the problems it will cause down the track. Now to improve your specific approach, you may want to measure the workloads to see how often memory is allocated and freed. This would give you a better ay of calculating what the retry interval should be. Secondly, you way want to try increasing the time-out for each iteration to reduce the load of that thread on the system. Finally, you definitely should have some time of error/panic case if the thread is unable to make progress after some number of iterations. This will let you at least see the potential live-lock case you may encounter if all threads are waiting for another thread in the system to free memory. You could simply pick a number of iterations based on what is empirically shown to work, or you could get smarter about it and keep track of how many threads are stuck waiting for memory, and if that ends up being all threads panic. *Note*: This is obviously not a perfect solution and as the other posters have mentioned a more global view of the application as a whole is needed to solve the problem correctly, but the above is a practical technique that should work in the short-term.
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options: * Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, **yes, it is possible to allocate everything statically**. It's just a lot of work, and **every time you change your system's configuration, you have to reconsider the allocations**. * Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They **cooperate so they don't run out of memory**. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a [paper about this approach](http://portal.acm.org/citation.cfm?id=98753). * Each process is aware that memory can become exhausted and can **fail over to a state in which it consumes a minimum amount of memory**. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, **it can lead to thrashing.** **Your proposal above matches none of the scenarios.** Instead, you are hoping **some other process will solve the problem** and the memory you need will eventually appear. You might get lucky. You might not. If you want your system to work reliably, you would do well to **reconsider the design of every process running on the system** in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck!
A few points: * Embedded programs often allocate all memory at startup or use only static memory to avoid situations like this. * Unless there is something else running on the device that frees memory on a regular basis your solution isn't likely to be effective. * The Viper I have has 64MB RAM, I don't think they come with less than 32MB, how much memory is your application using?
367,310
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user. Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask. ``` char someArr[]; do{ someArr = new char[10]; Sleep(100); // no justification for choosing 100 ms } while ( someArr == NULL ); ``` Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere? **FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code).
2008/12/15
[ "https://Stackoverflow.com/questions/367310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34910/" ]
You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options: * Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, **yes, it is possible to allocate everything statically**. It's just a lot of work, and **every time you change your system's configuration, you have to reconsider the allocations**. * Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They **cooperate so they don't run out of memory**. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a [paper about this approach](http://portal.acm.org/citation.cfm?id=98753). * Each process is aware that memory can become exhausted and can **fail over to a state in which it consumes a minimum amount of memory**. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, **it can lead to thrashing.** **Your proposal above matches none of the scenarios.** Instead, you are hoping **some other process will solve the problem** and the memory you need will eventually appear. You might get lucky. You might not. If you want your system to work reliably, you would do well to **reconsider the design of every process running on the system** in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck!
I second that the most sensible thing to do is to use static allocation of memory, so you have some idea of what is going on. Dynamic memory allocation is a bad habit from desktop programming that is not suited on restricted-resource machines (unless you spend a fair bit of time and effort creating a good managed and controlled memory management system). Also, check what features the OS in your device (assuming it has one, high-end ARM devices like this one tends to run an OS) has for handling memory.
15,572,947
I want to evaluate an instance of some class in a boolean context. Or to be clearer, i want to define how the object reacts if its used directly in a boolean context. Here an example: ``` class Foo { int state; Foo(): state(1) {} bool checkState() { return (state >= 0); } void doWork() { /*blah with state*/ } }; int main() { Foo obj; //while(obj.checkState()) //this works perfectly, and thats what i indent to do! while(obj) //this is what want to write obj.doWork(); return 0; } ``` Ok, its just a nice to have :-), but is this possible at all? If yes, how? Thanks!
2013/03/22
[ "https://Stackoverflow.com/questions/15572947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2165729/" ]
Use an explicit conversion operator to bool: ``` explicit operator bool() const { return (state >= 0); } ``` This does *exactly* what you want: define what happens when the object is evaluated in a boolean context. If you have an older compiler, you cannot use `explicit`, and that is bad because `operator bool()` (without `explicit`) can end up used unwantingly in non-boolean contexts. In that case, use the [safe bool idiom](http://www.artima.com/cppsource/safebool.html) instead.
You can use `operator bool()`: ``` explicit operator bool() const { return (state >=0) ; } ``` As pointed out you want to use `explicit` to prevent this being used in an integer context. Also [main should return an int](https://stackoverflow.com/questions/204476/what-should-main-return-in-c-c).
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
I think I know this one... Try sending your JSON as JSON by using PHP's [header()](http://php.net/header/) function: ``` /** * Send as JSON */ header("Content-Type: application/json", true); ``` Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header. jQuery used to be fine without the header, but it was changed a few versions back. **ALSO** Be sure that your script is returning valid JSON. Use [Firebug](http://getfirebug.com/) or [Google Chrome's Developer Tools](http://code.google.com/chrome/devtools/) to check the request's response in the console. **UPDATE** You will also want to update your code to sanitize the $\_POST to avoid sql injection attacks. As well as provide some error catching. ``` if (isset($_POST['get_member'])) { $member_id = mysql_real_escape_string ($_POST["get_member"]); $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';"; if ($result = mysql_query( $query )) { $row = mysql_fetch_array($result); $type = $row['type']; $name = $row['name']; $fname = $row['fname']; $lname = $row['lname']; $email = $row['email']; $phone = $row['phone']; $website = $row['website']; $image = $row['image']; /* JSON Row */ $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); } else { /* Your Query Failed, use mysql_error to report why */ $json = array('error' => 'MySQL Query Error'); } /* Send as JSON */ header("Content-Type: application/json", true); /* Return JSON */ echo json_encode($json); /* Stop Execution */ exit; } ```
Well, it might help someone. I was stupid enough to put `var_dump('testing');` in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected `json` response, and with `dataType` set to `json` defined, the request fails.
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
Try using jQuery.parseJSON when you get the data back. ``` type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function(data) { response = jQuery.parseJSON(data); $("input[ name = type ]:eq(" + response.type + " )") .attr("checked", "checked"); $("input[ name = name ]").val( response.name); $("input[ name = fname ]").val( response.fname); $("input[ name = lname ]").val( response.lname); $("input[ name = email ]").val( response.email); $("input[ name = phone ]").val( response.phone); $("input[ name = website ]").val( response.website); $("#admin_member_img") .attr("src", "images/member_images/" + response.image); }, error: function(error) { alert(error); } ```
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code ``` success=function(data){ //something like this jQuery.parseJSON(data) } ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
The `$.ajax` `error` function takes three arguments, not one: ``` error: function(xhr, status, thrown) ``` You need to dump the 2nd and 3rd parameters to find your cause, not the first one.
Well, it might help someone. I was stupid enough to put `var_dump('testing');` in the function I was requesting JSON from to be sure the request was actually received. This obviously also echo's as part for the expected `json` response, and with `dataType` set to `json` defined, the request fails.
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
The `$.ajax` `error` function takes three arguments, not one: ``` error: function(xhr, status, thrown) ``` You need to dump the 2nd and 3rd parameters to find your cause, not the first one.
``` Try this... <script type="text/javascript"> $(document).ready(function(){ $("#find").click(function(){ var username = $("#username").val(); $.ajax({ type: 'POST', dataType: 'json', url: 'includes/find.php', data: 'username='+username, success: function( data ) { //in data you result will be available... response = jQuery.parseJSON(data); //further code.. }, error: function(xhr, status, error) { alert(status); }, dataType: 'text' }); }); }); </script> <form name="Find User" id="userform" class="invoform" method="post" /> <div id ="userdiv"> <p>Name (Lastname, firstname):</p> </label> <input type="text" name="username" id="username" class="inputfield" /> <input type="button" name="find" id="find" class="passwordsubmit" value="find" /> </div> </form> <div id="userinfo"><b>info will be listed here.</b></div> ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
In addition to McHerbie's note, try `json_encode( $json_arr, JSON_FORCE_OBJECT );` if you are on PHP 5.3...
``` Try this... <script type="text/javascript"> $(document).ready(function(){ $("#find").click(function(){ var username = $("#username").val(); $.ajax({ type: 'POST', dataType: 'json', url: 'includes/find.php', data: 'username='+username, success: function( data ) { //in data you result will be available... response = jQuery.parseJSON(data); //further code.. }, error: function(xhr, status, error) { alert(status); }, dataType: 'text' }); }); }); </script> <form name="Find User" id="userform" class="invoform" method="post" /> <div id ="userdiv"> <p>Name (Lastname, firstname):</p> </label> <input type="text" name="username" id="username" class="inputfield" /> <input type="button" name="find" id="find" class="passwordsubmit" value="find" /> </div> </form> <div id="userinfo"><b>info will be listed here.</b></div> ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
Try using jQuery.parseJSON when you get the data back. ``` type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function(data) { response = jQuery.parseJSON(data); $("input[ name = type ]:eq(" + response.type + " )") .attr("checked", "checked"); $("input[ name = name ]").val( response.name); $("input[ name = fname ]").val( response.fname); $("input[ name = lname ]").val( response.lname); $("input[ name = email ]").val( response.email); $("input[ name = phone ]").val( response.phone); $("input[ name = website ]").val( response.website); $("#admin_member_img") .attr("src", "images/member_images/" + response.image); }, error: function(error) { alert(error); } ```
``` Try this... <script type="text/javascript"> $(document).ready(function(){ $("#find").click(function(){ var username = $("#username").val(); $.ajax({ type: 'POST', dataType: 'json', url: 'includes/find.php', data: 'username='+username, success: function( data ) { //in data you result will be available... response = jQuery.parseJSON(data); //further code.. }, error: function(xhr, status, error) { alert(status); }, dataType: 'text' }); }); }); </script> <form name="Find User" id="userform" class="invoform" method="post" /> <div id ="userdiv"> <p>Name (Lastname, firstname):</p> </label> <input type="text" name="username" id="username" class="inputfield" /> <input type="button" name="find" id="find" class="passwordsubmit" value="find" /> </div> </form> <div id="userinfo"><b>info will be listed here.</b></div> ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
The `$.ajax` `error` function takes three arguments, not one: ``` error: function(xhr, status, thrown) ``` You need to dump the 2nd and 3rd parameters to find your cause, not the first one.
In addition to McHerbie's note, try `json_encode( $json_arr, JSON_FORCE_OBJECT );` if you are on PHP 5.3...
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
``` session_start(); include('connection.php'); /* function msg($subjectname,$coursename,$sem) { return '{"subjectname":'.$subjectname.'"coursename":'.$coursename.'"sem":'.$sem.'}'; }*/ $title_id=$_POST['title_id']; $result=mysql_query("SELECT * FROM `video` WHERE id='$title_id'") or die(mysql_error()); $qr=mysql_fetch_array($result); $subject=$qr['subject']; $course=$qr['course']; $resultes=mysql_query("SELECT * FROM course JOIN subject ON course.id='$course' AND subject.id='$subject'"); $qqr=mysql_fetch_array($resultes); $subjectname=$qqr['subjectname']; $coursename=$qqr['coursename']; $sem=$qqr['sem']; $json = array("subjectname" => $subjectname, "coursename" => $coursename, "sem" => $sem,); header("Content-Type: application/json", true); echo json_encode( $json_arr ); $.ajax({type:"POST", dataType: "json", url:'select-title.php', data:$('#studey-form').serialize(), contentType: "application/json; charset=utf-8", beforeSend: function(x) { if(x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success:function(response) { var response=$.parseJSON(response) alert(response.subjectname); $('#course').html("<option>"+response.coursename+"</option>"); $('#subject').html("<option>"+response.subjectname+"</option>"); }, error: function( error,x,y) { alert( x,y ); } }); ```
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code ``` success=function(data){ //something like this jQuery.parseJSON(data) } ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
In addition to McHerbie's note, try `json_encode( $json_arr, JSON_FORCE_OBJECT );` if you are on PHP 5.3...
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code ``` success=function(data){ //something like this jQuery.parseJSON(data) } ```
5,147,522
I've been looking all over for the solution but I cannot find anything that works. I am trying to get a bunch of data from the database and then via AJAX autocomplete input fields in a form. To do this I've decided to use json, because why not, right? Alternatively I've been thinking to just send back a delimited string and then tokenise it, which in hind-sight would've been much easier and spared me the headache... Since I've decided to use json though, I guess I should stick with it and find out what went wrong! What happens is that when the get\_member\_function() is executed, an error pops up in an alert dialogue and reads "[object Object]". I've tried this also using the GET request, and by setting the contentType to ”application/json; charset=utf-8″. Alas, no dice. Can anyone please suggest what I am doing wrong? Take care, Piotr. My javascript/jQuery function is as follows: ``` function get_member_info() { var url = "contents/php_scripts/admin_scripts.php"; var id = $( "select[ name = member ] option:selected" ).val(); $.ajax( { type: "POST", dataType: "json", url: url, data: { get_member: id }, success: function( response ) { $( "input[ name = type ]:eq( " + response.type + " )" ).attr( "checked", "checked" ); $( "input[ name = name ]" ).val( response.name ); $( "input[ name = fname ]" ).val( response.fname ); $( "input[ name = lname ]" ).val( response.lname ); $( "input[ name = email ]" ).val( response.email ); $( "input[ name = phone ]" ).val( response.phone ); $( "input[ name = website ]" ).val( response.website ); $( "#admin_member_img" ).attr( "src", "images/member_images/" + response.image ); }, error: function( error ) { alert( error ); } } ); } ``` and the relevant code in "contents/php\_scripts/admin\_scripts.php" is as follows: ``` if( isset( $_POST[ "get_member" ] ) ) { $member_id = $_POST[ "get_member" ]; $query = "select * from members where id = '$member_id'"; $result = mysql_query( $query ); $row = mysql_fetch_array( $result ); $type = $row[ "type" ]; $name = $row[ "name" ]; $fname = $row[ "fname" ]; $lname = $row[ "lname" ]; $email = $row[ "email" ]; $phone = $row[ "phone" ]; $website = $row[ "website" ]; $image = $row[ "image" ]; $json_arr = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); echo json_encode( $json_arr ); } ```
2011/02/28
[ "https://Stackoverflow.com/questions/5147522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/638369/" ]
I think I know this one... Try sending your JSON as JSON by using PHP's [header()](http://php.net/header/) function: ``` /** * Send as JSON */ header("Content-Type: application/json", true); ``` Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header. jQuery used to be fine without the header, but it was changed a few versions back. **ALSO** Be sure that your script is returning valid JSON. Use [Firebug](http://getfirebug.com/) or [Google Chrome's Developer Tools](http://code.google.com/chrome/devtools/) to check the request's response in the console. **UPDATE** You will also want to update your code to sanitize the $\_POST to avoid sql injection attacks. As well as provide some error catching. ``` if (isset($_POST['get_member'])) { $member_id = mysql_real_escape_string ($_POST["get_member"]); $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';"; if ($result = mysql_query( $query )) { $row = mysql_fetch_array($result); $type = $row['type']; $name = $row['name']; $fname = $row['fname']; $lname = $row['lname']; $email = $row['email']; $phone = $row['phone']; $website = $row['website']; $image = $row['image']; /* JSON Row */ $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image ); } else { /* Your Query Failed, use mysql_error to report why */ $json = array('error' => 'MySQL Query Error'); } /* Send as JSON */ header("Content-Type: application/json", true); /* Return JSON */ echo json_encode($json); /* Stop Execution */ exit; } ```
In addition to McHerbie's note, try `json_encode( $json_arr, JSON_FORCE_OBJECT );` if you are on PHP 5.3...
1,539,915
Why does Swing `JComponent` class implement the interface `Serializable`? The way I've implemented my views, they are stateless, all the state data is stored in a Presentation Model. So I don't need to serialize my views. I've used a `@SuppressWarnings("serial")` annotation to remove the warnings. Are there better ways to remove them?
2009/10/08
[ "https://Stackoverflow.com/questions/1539915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56297/" ]
In the beginning GUI builders were going to save the UI in serialised format. The `applet` tag even has an attribute to load from serialised form (I don't know anyone else who has used that, and I've only used it to be malicious). Unfortunately using the serialisation mechanism for GUIs doesn't really work. Swing only guarantees compatibility in within the same major release (and I'm guessing even that has few tests).
> > Why does Swing JComponent class implement the interface Serializable? > > > Although this allows you to serialize classes and send them to and from the client and the server, this does not seem to be an intuitive scenario. There is a better chance, still slim, that someone might want to serialize components to a file. This will allow for that sort of serialization. > > Are there better ways to remove [the warnings]? > > > You could instantiate the serialVersionUID, but if you do so you will need to maintain it when you class changes. This seems like overkill. Another option, as Laurence Gonsalves points out in his comment, is to suppress the warnings altogether in the Preferences->Java->Compiler->Errors/Warnings->Potential Programming Problems field.
46,377,880
i don't know much about `class` and their `member variables`. What my doubt is, can we declare and initialize a member variable from another member variable in same class? like this ``` class newClass { private $variable1 = 'new1'; private $variable2 = $variable1.'new2'; } ``` If can't, please help me find an solution for this. Pardon me if this is a wrong question to ask.
2017/09/23
[ "https://Stackoverflow.com/questions/46377880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4049258/" ]
Always initialize member variable in constructor. You can assign dynamic value in constructor. Try this code: ``` <?php class newClass { private $variable1 ; private $variable2; function __construct() { $this->variable1 = 'new1'; $this->variable2 = $this->variable1.'new2'; } function get_data() { echo "var1= ".$this->variable1; echo "<br>"; echo "var2= ".$this->variable2; } } $obj = new newClass(); $obj->get_data(); ```
No. You can't do that. What you could do instead is do the initialization in the constructor: ``` class Foo { private $a = 'something'; private $b; public function __construct() { $this->b = $this->a . 'foobar'; } } ``` Buuuut, this would actually be a somewhat questionable practice, since it you should try to avoid doing any computation in the constructors, since you loose the ability to actually test that part of the logic (since constructor is always executed, you have no way to compare the before and after states). A much better way would be to leave this logic in the getter-methods: ``` class Foo { const DEFAULT_VALUE = 'lorem ipsum'; const DEFAULT_PREFIX = '_'; private $bar; public function __construct(string $bar = self::DEFAULT_VALUE) { $this->bar = $bar; } public function getPrefixedBar(string $prefix = self::DEFAULT_PREFIX) { return $prefix . $this->bar; } } ``` With this code you will get: ``` $a = new Foo; echo $a->getPrefixedBar(); // shows: '_lorem ipsum'; echo $a->getPrefixedBar('test '); // shows: 'test lorem ipsum'; $b = new Foo('xx'); echo $b->getPrefixedBar(); // shows: '_xx'; ```
55,821,361
I am trying to put together a useable set of data about glaciers. Our original data comes from an ArcGIS dataset, and latitude/longitude values were stored in a separate file, now detached from the CSV with all of our data. I am attempting to merge the latitude/longitude files with our data set. Heres a preview of what the files look like. This is my main dataset file, **glims** (columns dropped for clarity) ``` | ANLYS_ID | GLAC_ID | AREA | |----------|----------------|-------| | 101215 | G286929E46788S | 2.401 | | 101146 | G286929E46788S | 1.318 | | 101162 | G286929E46788S | 0.061 | ``` This is the latitude-longitude file, **coordinates** ``` | lat | long | glacier_id | |-------|---------|----------------| | 1.187 | -70.166 | G001187E70166S | | 2.050 | -70.629 | G002050E70629S | | 3.299 | -54.407 | G002939E70509S | ``` The problem is, the **coordinates** data frame has one row for each glacier id with latitude longitude, whereas my **glims** data frame has multiple rows for each glacier id with varying data for each entry. I need every single entry in my main data file to have a latitude-longitude value added to it, based on the matching glacier\_id between the two data frames. Heres what I've tried so far. ``` glims = pd.read_csv('glims_clean.csv') coordinates = pd.read_csv('LatLong_GLIMS.csv') df['que'] = np.where((coordinates['glacier_id'] == glims['GLAC_ID'])) ``` error returns: 'int' object is not subscriptable and: ``` glims.merge(coordinates, how='right', on=('glacier_id', 'GLAC_ID')) ``` error returns: int' object has no attribute 'merge' I have no idea how to tackle this big of a merge. I am also afraid of making mistakes because it is nearly impossible to catch them, since the data carries no other identifying factors. Any guidance would be awesome, thank you.
2019/04/24
[ "https://Stackoverflow.com/questions/55821361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5352542/" ]
On the form parent of the input elements (add one if there isnt one already) add this `autocomplete='off'` and then on the inputs add `autocomplete='false'`. And to answer your question, 'can individual fields be disabled without the whole form' Yes. But you would need to add another form onto the child element. Cheers.
autocomplete="off" is the right solution. In your case I think there is some problem with Chrome browser. Update chrome or reinstall. That might solve your problem.
55,821,361
I am trying to put together a useable set of data about glaciers. Our original data comes from an ArcGIS dataset, and latitude/longitude values were stored in a separate file, now detached from the CSV with all of our data. I am attempting to merge the latitude/longitude files with our data set. Heres a preview of what the files look like. This is my main dataset file, **glims** (columns dropped for clarity) ``` | ANLYS_ID | GLAC_ID | AREA | |----------|----------------|-------| | 101215 | G286929E46788S | 2.401 | | 101146 | G286929E46788S | 1.318 | | 101162 | G286929E46788S | 0.061 | ``` This is the latitude-longitude file, **coordinates** ``` | lat | long | glacier_id | |-------|---------|----------------| | 1.187 | -70.166 | G001187E70166S | | 2.050 | -70.629 | G002050E70629S | | 3.299 | -54.407 | G002939E70509S | ``` The problem is, the **coordinates** data frame has one row for each glacier id with latitude longitude, whereas my **glims** data frame has multiple rows for each glacier id with varying data for each entry. I need every single entry in my main data file to have a latitude-longitude value added to it, based on the matching glacier\_id between the two data frames. Heres what I've tried so far. ``` glims = pd.read_csv('glims_clean.csv') coordinates = pd.read_csv('LatLong_GLIMS.csv') df['que'] = np.where((coordinates['glacier_id'] == glims['GLAC_ID'])) ``` error returns: 'int' object is not subscriptable and: ``` glims.merge(coordinates, how='right', on=('glacier_id', 'GLAC_ID')) ``` error returns: int' object has no attribute 'merge' I have no idea how to tackle this big of a merge. I am also afraid of making mistakes because it is nearly impossible to catch them, since the data carries no other identifying factors. Any guidance would be awesome, thank you.
2019/04/24
[ "https://Stackoverflow.com/questions/55821361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5352542/" ]
On the form parent of the input elements (add one if there isnt one already) add this `autocomplete='off'` and then on the inputs add `autocomplete='false'`. And to answer your question, 'can individual fields be disabled without the whole form' Yes. But you would need to add another form onto the child element. Cheers.
You can deactivate the autocomplete with `autocomplete="new-password"` `autocomplete="off"` or `autocomplete="false"` is not working anymore
55,821,361
I am trying to put together a useable set of data about glaciers. Our original data comes from an ArcGIS dataset, and latitude/longitude values were stored in a separate file, now detached from the CSV with all of our data. I am attempting to merge the latitude/longitude files with our data set. Heres a preview of what the files look like. This is my main dataset file, **glims** (columns dropped for clarity) ``` | ANLYS_ID | GLAC_ID | AREA | |----------|----------------|-------| | 101215 | G286929E46788S | 2.401 | | 101146 | G286929E46788S | 1.318 | | 101162 | G286929E46788S | 0.061 | ``` This is the latitude-longitude file, **coordinates** ``` | lat | long | glacier_id | |-------|---------|----------------| | 1.187 | -70.166 | G001187E70166S | | 2.050 | -70.629 | G002050E70629S | | 3.299 | -54.407 | G002939E70509S | ``` The problem is, the **coordinates** data frame has one row for each glacier id with latitude longitude, whereas my **glims** data frame has multiple rows for each glacier id with varying data for each entry. I need every single entry in my main data file to have a latitude-longitude value added to it, based on the matching glacier\_id between the two data frames. Heres what I've tried so far. ``` glims = pd.read_csv('glims_clean.csv') coordinates = pd.read_csv('LatLong_GLIMS.csv') df['que'] = np.where((coordinates['glacier_id'] == glims['GLAC_ID'])) ``` error returns: 'int' object is not subscriptable and: ``` glims.merge(coordinates, how='right', on=('glacier_id', 'GLAC_ID')) ``` error returns: int' object has no attribute 'merge' I have no idea how to tackle this big of a merge. I am also afraid of making mistakes because it is nearly impossible to catch them, since the data carries no other identifying factors. Any guidance would be awesome, thank you.
2019/04/24
[ "https://Stackoverflow.com/questions/55821361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5352542/" ]
You can deactivate the autocomplete with `autocomplete="new-password"` `autocomplete="off"` or `autocomplete="false"` is not working anymore
autocomplete="off" is the right solution. In your case I think there is some problem with Chrome browser. Update chrome or reinstall. That might solve your problem.
4,238,058
When answering general topology questions which ask to show a statement is true, I struggle to be able to formulate a sufficient proof, linking the information I know together. As the title is put, this particular question asks me to 'show that the only dense subset of $\mathbb{Z}$ is $\mathbb{Z}$' and to consider '$\mathbb{Z}$ with discrete topology' as additional information to the question. Below I have provided how I answered the question: My attempt: All subsets are closed and open in the discrete topology. A $\subseteq$ $\mathbb{Z}$ is dense in $\mathbb{Z}$ if ${\overline A}$ = $\mathbb{Z}$. Evidently $\mathbb{Z}$ $\subseteq$ $\mathbb{Z}$ is dense in $\mathbb{Z}$ since $\overline{\mathbb{Z}}$ = $\mathbb{Z}$. Any B $\subseteq$ $\mathbb{Z}$ will not be dense in $\mathbb{Z}$ since for all other B $\subset$ $\mathbb{Z}$ there exists a x in $\mathbb{Z}$ \ B which stops $\overline{B}$ = $\mathbb{Z}$. In this solution, I dont think it is a strong enough proof and I do not know how to apply the fact that all subsets are closed and open. If anyone can tell me where I am going wrong or how to improve, it is appreciated.
2021/09/01
[ "https://math.stackexchange.com/questions/4238058", "https://math.stackexchange.com", "https://math.stackexchange.com/users/962766/" ]
Your proof is incomplete, because it is false that the existence of a $x\in\Bbb Z\setminus B$ is incompatible with the fact that $B$ is dense. It is true in your case, but you did not explain why. But, for instance, $\Bbb Q$ is dense in $\Bbb R$ (with respect to the usual distance), in spite of the fact that $\sqrt2\in\Bbb R\setminus\Bbb Q$. If $B$ is dense, then $\overline B=\Bbb Z$. But $B$ is closed, and therefore $\Bbb Z=\overline B=B$.
Let $A$ dense in $\Bbb Z$, then $\Bbb Z =\bar A = A$
244,957
I want to get a list of products from only pending orders! i have this is code but works only for register customers i need to show product for all orders even for guests and multi store. ``` <?php require_once 'app/Mage.php'; Mage::app(); //Get All Users/Customers $users = mage::getModel('customer/customer')->getCollection() ->addAttributeToSelect('*'); foreach ($users as $user){ $customer_id = $user['entity_id']; //Get the all orders by customer id $order_collection = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id',$customer_id) ->addFieldToFilter('status', array('in' => array('pending'))) ->setOrder('created_at', 'desc'); foreach($order_collection as $orders) { echo $increment_id = $orders['increment_id']."</br>"; $order_id = $orders['entity_id']; //Get all items for the order id $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach($items as $i) { echo $i->getName()."</br>"; } echo "</br>"; } } ?> ```
2018/10/03
[ "https://magento.stackexchange.com/questions/244957", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/65887/" ]
For anyone seeing this error recurring and having to di:compile and rm -rf generated their way out of it repeatedly, check your layout XML files for any blocks using an Abstract class. In my case, I had used: ``` class="Magento\Catalog\Block\Product\View\AbstractView" ``` When it should have just been: ``` class="Magento\Catalog\Block\Product\View" ``` Surprising that it ever worked, to be honest, but making the above change solved it entirely for me.
please replace your consturct code in below file **/home1/dukaania/public\_html/testing2/app/code/Sugarcode/Test/Model/Total/Fee.php** ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` after replacing run command : **rm -rf generated/\* and clear cache and check**
244,957
I want to get a list of products from only pending orders! i have this is code but works only for register customers i need to show product for all orders even for guests and multi store. ``` <?php require_once 'app/Mage.php'; Mage::app(); //Get All Users/Customers $users = mage::getModel('customer/customer')->getCollection() ->addAttributeToSelect('*'); foreach ($users as $user){ $customer_id = $user['entity_id']; //Get the all orders by customer id $order_collection = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id',$customer_id) ->addFieldToFilter('status', array('in' => array('pending'))) ->setOrder('created_at', 'desc'); foreach($order_collection as $orders) { echo $increment_id = $orders['increment_id']."</br>"; $order_id = $orders['entity_id']; //Get all items for the order id $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach($items as $i) { echo $i->getName()."</br>"; } echo "</br>"; } } ?> ```
2018/10/03
[ "https://magento.stackexchange.com/questions/244957", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/65887/" ]
This issue is particularly related to the optional parameter that you are setting in the `public function __construct`. In this particular case the original constructor parameters are like this (which is incorrect and not allowed anymore): ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` The correct way is to include all the optional parameters in the last: ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` Let me know if it helps.
please replace your consturct code in below file **/home1/dukaania/public\_html/testing2/app/code/Sugarcode/Test/Model/Total/Fee.php** ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` after replacing run command : **rm -rf generated/\* and clear cache and check**
244,957
I want to get a list of products from only pending orders! i have this is code but works only for register customers i need to show product for all orders even for guests and multi store. ``` <?php require_once 'app/Mage.php'; Mage::app(); //Get All Users/Customers $users = mage::getModel('customer/customer')->getCollection() ->addAttributeToSelect('*'); foreach ($users as $user){ $customer_id = $user['entity_id']; //Get the all orders by customer id $order_collection = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id',$customer_id) ->addFieldToFilter('status', array('in' => array('pending'))) ->setOrder('created_at', 'desc'); foreach($order_collection as $orders) { echo $increment_id = $orders['increment_id']."</br>"; $order_id = $orders['entity_id']; //Get all items for the order id $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach($items as $i) { echo $i->getName()."</br>"; } echo "</br>"; } } ?> ```
2018/10/03
[ "https://magento.stackexchange.com/questions/244957", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/65887/" ]
For anyone seeing this error recurring and having to di:compile and rm -rf generated their way out of it repeatedly, check your layout XML files for any blocks using an Abstract class. In my case, I had used: ``` class="Magento\Catalog\Block\Product\View\AbstractView" ``` When it should have just been: ``` class="Magento\Catalog\Block\Product\View" ``` Surprising that it ever worked, to be honest, but making the above change solved it entirely for me.
Please replace your this "Sugarcode/Test/Model/Total/Fee.php" model file function \_construct. ``` protected function _construct() { $this->_init('Sugarcode\Test\Model\ResourceModel\Fee'); } ``` and check after that.
244,957
I want to get a list of products from only pending orders! i have this is code but works only for register customers i need to show product for all orders even for guests and multi store. ``` <?php require_once 'app/Mage.php'; Mage::app(); //Get All Users/Customers $users = mage::getModel('customer/customer')->getCollection() ->addAttributeToSelect('*'); foreach ($users as $user){ $customer_id = $user['entity_id']; //Get the all orders by customer id $order_collection = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id',$customer_id) ->addFieldToFilter('status', array('in' => array('pending'))) ->setOrder('created_at', 'desc'); foreach($order_collection as $orders) { echo $increment_id = $orders['increment_id']."</br>"; $order_id = $orders['entity_id']; //Get all items for the order id $order = Mage::getModel('sales/order')->load($order_id); $items = $order->getAllItems(); foreach($items as $i) { echo $i->getName()."</br>"; } echo "</br>"; } } ?> ```
2018/10/03
[ "https://magento.stackexchange.com/questions/244957", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/65887/" ]
This issue is particularly related to the optional parameter that you are setting in the `public function __construct`. In this particular case the original constructor parameters are like this (which is incorrect and not allowed anymore): ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` The correct way is to include all the optional parameters in the last: ``` public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Sugarcode\Test\Model\Total\FeeFactory $feeFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource= null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection= null, array $data = array() ) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_feeFactory = $feeFactory; } ``` Let me know if it helps.
Please replace your this "Sugarcode/Test/Model/Total/Fee.php" model file function \_construct. ``` protected function _construct() { $this->_init('Sugarcode\Test\Model\ResourceModel\Fee'); } ``` and check after that.
5,195,419
I have some xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption>Bla bla bla bla</description> </animal> ``` The xml is being processed and displayed on the screen. I need to provide a longer multi-paragraph description of the dog but I am running into some problems. If I write my xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption> p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla </description> </animal> ``` Then when the xml is printed to the screen it is printed like this: ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` I would like the description to be printed like this (without the leading tabs): ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` Is there a reasonable solution to this problem? I was thinking that one thing I could do would be to put all the text on one line like this: ``` <descirption>p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <NEWLINE/>NEWLINE/>p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<NEWLINE/>NEWLINE/>p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla</description> ``` I am not sure if there is a standard xml new line tag though. I know that you can encode an `&` with & is there something like this for new line? Is there a standard way to deal with this issue?
2011/03/04
[ "https://Stackoverflow.com/questions/5195419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251589/" ]
static can be a little confusing because of its slightly different meaning depending upon where it is used. A static variable, declared globally, will only be visible in that source file. A static variable, declared locally, will keep its value over successive calls to that function (as in netrom's example) A static member variable does not belong to the class. A static function, declared in a class, can be used without declaring an instance of that class.
The static keyword specifies that the life-time of the given the variable, function or class is application-wide. Like having a single instance. This example might illustrate it: ``` #include <iostream> using namespace std; void test() { static int i = 123; if (i == 123) { i = 321; } cout << i << endl; } int main(int arg, char **argv) { test(); test(); return 0; } ``` The output is: 321 321 So "i" is only initialized the first time it is encountered, so to speak. But actually it's allocated at compile time for that function. Afterwards, it's just in the scope of the function test() as a variable, but it is static so changing it changes it in all future calls to test() as well. But I encourage you to read more about it here: <http://www.cprogramming.com/tutorial/statickeyword.html>
5,195,419
I have some xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption>Bla bla bla bla</description> </animal> ``` The xml is being processed and displayed on the screen. I need to provide a longer multi-paragraph description of the dog but I am running into some problems. If I write my xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption> p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla </description> </animal> ``` Then when the xml is printed to the screen it is printed like this: ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` I would like the description to be printed like this (without the leading tabs): ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` Is there a reasonable solution to this problem? I was thinking that one thing I could do would be to put all the text on one line like this: ``` <descirption>p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <NEWLINE/>NEWLINE/>p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<NEWLINE/>NEWLINE/>p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla</description> ``` I am not sure if there is a standard xml new line tag though. I know that you can encode an `&` with & is there something like this for new line? Is there a standard way to deal with this issue?
2011/03/04
[ "https://Stackoverflow.com/questions/5195419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251589/" ]
The static keyword specifies that the life-time of the given the variable, function or class is application-wide. Like having a single instance. This example might illustrate it: ``` #include <iostream> using namespace std; void test() { static int i = 123; if (i == 123) { i = 321; } cout << i << endl; } int main(int arg, char **argv) { test(); test(); return 0; } ``` The output is: 321 321 So "i" is only initialized the first time it is encountered, so to speak. But actually it's allocated at compile time for that function. Afterwards, it's just in the scope of the function test() as a variable, but it is static so changing it changes it in all future calls to test() as well. But I encourage you to read more about it here: <http://www.cprogramming.com/tutorial/statickeyword.html>
> > > > > > why do we have to declare static in class and then assign the value outside the class!!! > > > > > > > > > Because it's merely DECLARED in the class, it is not DEFINED. The class declaration is merely a description of the class, no memory is allocated until of object of that class is defined. If instances of the class can be defined in many modules, and the memory for allocated in many places, where do you put the one instance of the static data members? Remember, the class declaration can & will be included in many source files of the application. C++ has the "ODR" (which I insist should be the "1DR"): The "One Definition Rule". A data item can be DECLARED many times, but must be DEFINED exactly once. When you assign the value outside the class, the assignment part is actually irrelevant, it's the definition of the member that's important: ``` class A { static int MyInt; // Declaration }; int A::MyInt; // Definition ```
5,195,419
I have some xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption>Bla bla bla bla</description> </animal> ``` The xml is being processed and displayed on the screen. I need to provide a longer multi-paragraph description of the dog but I am running into some problems. If I write my xml like this: ``` <animal name="Bow Wow" type="dog"> <birthDate>May 17,2001</birthDate> <descirption> p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla </description> </animal> ``` Then when the xml is printed to the screen it is printed like this: ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` I would like the description to be printed like this (without the leading tabs): ``` p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla ``` Is there a reasonable solution to this problem? I was thinking that one thing I could do would be to put all the text on one line like this: ``` <descirption>p1: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla <NEWLINE/>NEWLINE/>p2: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<NEWLINE/>NEWLINE/>p3: Bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla</description> ``` I am not sure if there is a standard xml new line tag though. I know that you can encode an `&` with & is there something like this for new line? Is there a standard way to deal with this issue?
2011/03/04
[ "https://Stackoverflow.com/questions/5195419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251589/" ]
static can be a little confusing because of its slightly different meaning depending upon where it is used. A static variable, declared globally, will only be visible in that source file. A static variable, declared locally, will keep its value over successive calls to that function (as in netrom's example) A static member variable does not belong to the class. A static function, declared in a class, can be used without declaring an instance of that class.
> > > > > > why do we have to declare static in class and then assign the value outside the class!!! > > > > > > > > > Because it's merely DECLARED in the class, it is not DEFINED. The class declaration is merely a description of the class, no memory is allocated until of object of that class is defined. If instances of the class can be defined in many modules, and the memory for allocated in many places, where do you put the one instance of the static data members? Remember, the class declaration can & will be included in many source files of the application. C++ has the "ODR" (which I insist should be the "1DR"): The "One Definition Rule". A data item can be DECLARED many times, but must be DEFINED exactly once. When you assign the value outside the class, the assignment part is actually irrelevant, it's the definition of the member that's important: ``` class A { static int MyInt; // Declaration }; int A::MyInt; // Definition ```
89,452
Just wondering following from [this](https://scifi.stackexchange.com/questions/31796/do-droids-have-consciousness) and [this](https://scifi.stackexchange.com/questions/71582/are-the-b1-battle-droids-in-star-wars-self-aware?lq=1) question, do we actually ever see (or have evidence of) Jedi successfully (or even attempting) to use their 'mind tricks' on Droids?
2015/05/10
[ "https://scifi.stackexchange.com/questions/89452", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/22917/" ]
In the Star Wars novel *The Truce at Bakura*, Luke Skywalker is able to extract a deadly parasite he was poisoned with with from his lungs using the Force. In the Clone Wars cartoon series, several of the Jedi Masters are able to dismantle droids and use their nuts and bolts to rip through them. A Jedi cannot manipulate an android's *mind* per se, but if you follow the canon of story where they are insanely powerful and able to manipulate things on a small scale using the Force, then it could be reasoned that a Jedi with the knowledge of building and programming droids (e.g. Anakin Skywalker), could reprogram a droid using the Force; effectively altering/controlling its mind.
Droids dont have a conscious mind. I think its common knowledge that robots have computers, not brains. It is shown throught the series that ind tricks only work on the weak MINDED. This is shown when Luke attempts a mind trick on Jabba The Hut. You could see an example prooving this too when Ben Kenobi tricked the Stormtrooper using the old favorite quote: "These are not the droids you are looking for." In summary: Mind tricks only work on weak minded, droids do not have inds therefore a mind trick would be useless against a droid.
89,452
Just wondering following from [this](https://scifi.stackexchange.com/questions/31796/do-droids-have-consciousness) and [this](https://scifi.stackexchange.com/questions/71582/are-the-b1-battle-droids-in-star-wars-self-aware?lq=1) question, do we actually ever see (or have evidence of) Jedi successfully (or even attempting) to use their 'mind tricks' on Droids?
2015/05/10
[ "https://scifi.stackexchange.com/questions/89452", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/22917/" ]
In the Star Wars novel *The Truce at Bakura*, Luke Skywalker is able to extract a deadly parasite he was poisoned with with from his lungs using the Force. In the Clone Wars cartoon series, several of the Jedi Masters are able to dismantle droids and use their nuts and bolts to rip through them. A Jedi cannot manipulate an android's *mind* per se, but if you follow the canon of story where they are insanely powerful and able to manipulate things on a small scale using the Force, then it could be reasoned that a Jedi with the knowledge of building and programming droids (e.g. Anakin Skywalker), could reprogram a droid using the Force; effectively altering/controlling its mind.
Droids can be Jedi as seen in the comic *Skippy the Jedi Droid*, therefore, that makes droids one with the force just as all living things. So I think a Jedi mind trick could work on a droid
89,452
Just wondering following from [this](https://scifi.stackexchange.com/questions/31796/do-droids-have-consciousness) and [this](https://scifi.stackexchange.com/questions/71582/are-the-b1-battle-droids-in-star-wars-self-aware?lq=1) question, do we actually ever see (or have evidence of) Jedi successfully (or even attempting) to use their 'mind tricks' on Droids?
2015/05/10
[ "https://scifi.stackexchange.com/questions/89452", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/22917/" ]
In the Star Wars novel *The Truce at Bakura*, Luke Skywalker is able to extract a deadly parasite he was poisoned with with from his lungs using the Force. In the Clone Wars cartoon series, several of the Jedi Masters are able to dismantle droids and use their nuts and bolts to rip through them. A Jedi cannot manipulate an android's *mind* per se, but if you follow the canon of story where they are insanely powerful and able to manipulate things on a small scale using the Force, then it could be reasoned that a Jedi with the knowledge of building and programming droids (e.g. Anakin Skywalker), could reprogram a droid using the Force; effectively altering/controlling its mind.
Yes. In the (canon) junior novelisation for Return of the Jedi, we see Luke tricking the [TT-8L gate guard droid](https://starwars.fandom.com/wiki/TT-8L/Y7_gatekeeper_droid) with mind powers. > > The way in turns out to be easy enough. An electronic eyeball barely > has time to pop out before Luke has said, “You will open the door.” > > > Yes, this is a Jedi mind trick and it works easily. Inside, the > simpleminded guard who operates the door unthinkingly obeys. > > > [Return of the Jedi: Beware the Power of the Dark Side!](https://starwars.fandom.com/wiki/Return_of_the_Jedi:_Beware_the_Power_of_the_Dark_Side!) > > >
89,452
Just wondering following from [this](https://scifi.stackexchange.com/questions/31796/do-droids-have-consciousness) and [this](https://scifi.stackexchange.com/questions/71582/are-the-b1-battle-droids-in-star-wars-self-aware?lq=1) question, do we actually ever see (or have evidence of) Jedi successfully (or even attempting) to use their 'mind tricks' on Droids?
2015/05/10
[ "https://scifi.stackexchange.com/questions/89452", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/22917/" ]
In the Star Wars novel *The Truce at Bakura*, Luke Skywalker is able to extract a deadly parasite he was poisoned with with from his lungs using the Force. In the Clone Wars cartoon series, several of the Jedi Masters are able to dismantle droids and use their nuts and bolts to rip through them. A Jedi cannot manipulate an android's *mind* per se, but if you follow the canon of story where they are insanely powerful and able to manipulate things on a small scale using the Force, then it could be reasoned that a Jedi with the knowledge of building and programming droids (e.g. Anakin Skywalker), could reprogram a droid using the Force; effectively altering/controlling its mind.
Legends: Yes, by another name ----------------------------- In Legends, a Force ability was known by the name of "[mechu-deru](https://starwars.fandom.com/wiki/Mechu-deru)" that allowed the user to not only influence droids, but to control or reprogram them entirely. From a now-deleted Hyperspace article on starwars.com: > > It is believed that through their bizarre alchemies, the Sith somehow stumbled upon the ability to manipulate mechanicals of complex nature through the Force: ships, computers, and, indeed, even droids. > > > (source: [Droids, Technology and the Force: A Clash of Phenomena](https://www.starwars.com/hyperspace/member/insideronline/81/indexp7.html), via [Wookieepedia](https://starwars.fandom.com/wiki/Mechu-deru#cite_note-DTATF-5)) > > > There seems to be a range of ways that mechu-deru could interface with droids and mechanical objects, from simply allowing the user to understand mechanical systems better (as described in *The Jedi Path*) to turning living beings into cyborgs called "technobeasts" (known as [mechu-deru vitae](https://starwars.fandom.com/wiki/Mechu-deru_vitae)). However, the ability definitely included control over droids: > > Because droids are not organic beings, they were a subject few Jedi bothered to understand. Jedi powers that had a technical influence were usually crude, such as the Force ability *mechu macture*, or, "destroy droid." The Sith went farther than the Jedi ever did, developing the ability *mechu-deru* to allow for Force control over mechanical systems. In true Sith fashion, the power stressed absolute control, turning droids into puppets. > > > (source: *The New Essential Guide to Droids* (2006), page 195) > > >
11,533,613
Halo, the first i want to know the idle time at my android application. after that, i will do something if it is a idle time mode. I follow this link. [Application idle time](https://stackoverflow.com/questions/4075180/application-idle-time) my program work properly, but suddenly the problem show up. I can't move to the other page (for example to the login page) or pop up a message using alertdialog because its in a thread. Do you have any solutions? ``` public class ControlActivity extends Activity { private static final String TAG=ControlActivity.class.getName(); /** * Gets reference to global Application * @return must always be type of ControlApplication! See AndroidManifest.xml */ public ControlApplication getApp() { return (ControlApplication )this.getApplication(); } @Override public void onUserInteraction() { super.onUserInteraction(); getApp().touch(); Log.d(TAG, "User interaction to "+this.toString()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} ``` here is my ControlApplication.java ``` public class ControlApplication extends Application { private static final String TAG=ControlApplication.class.getName(); private Waiter waiter; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "Starting application"+this.toString()); //setContentView(R.layout.activity_main); waiter=new Waiter(5*60*1000); //5 mins waiter.start(); Toast.makeText(ControlApplication.this, "start", Toast.LENGTH_LONG).show(); } public void touch() { waiter.touch(); Toast.makeText(ControlApplication.this, "touch", Toast.LENGTH_LONG).show(); } } ``` here is the Waiter.java ``` public class Waiter extends Thread implements Runnable{ private static final String TAG=Waiter.class.getName(); private long lastUsed; private long period; private boolean stop; Context activity; public Waiter(long period) { this.period=period; stop=false; } @SuppressLint("ParserError") public void run() { long idle=0; this.touch(); do { idle=System.currentTimeMillis()-lastUsed; Log.d(TAG, "Application is idle for "+idle +" ms"); try { Thread.sleep(5000); //check every 5 seconds } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); } if(idle > period) { idle=0; //do something here - e.g. call popup or so //Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show(); stopCounter(); } } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void touch() { lastUsed=System.currentTimeMillis(); } public synchronized void forceInterrupt() { this.interrupt(); } //soft stopping of thread public synchronized void stopCounter() { stop=true; } public synchronized void setPeriod(long period) { this.period=period; }} ``` I tried to create a new class and call a method to intent. Its also fail. tried to pop up a message from that method its also fail. do you guys have any other solutions for idle time? thanks. Regards, Alfred Angkasa
2012/07/18
[ "https://Stackoverflow.com/questions/11533613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533435/" ]
Like this: ``` responseData[0].diccioDatosForm.errorMessage ``` `responseData` itself is an array contains of 2 elements
It is because you are alerting the array that is being returned. To access the field you want, you should do: ``` responseData[0].diccioDatosForm.diccioDatosForm ``` I know that what I will say is not part of your question, but I suggest that you review your JSON structure, because its strange to have an array of two different things. I would use something like this: ``` { "configs": { "segundoNombre": "OK", "encargadoProvincia": "Ingrese un valor", "encargadoLocalidad": "Ingrese un valor" }, "error": { "message": "Verifique los datos invalidos ingresados..." }, "itens": [] // "encargados" list here } ``` Doing this you will have standard to use through yout application. To acess the message error you could do: ``` responseData.error.message ```
11,533,613
Halo, the first i want to know the idle time at my android application. after that, i will do something if it is a idle time mode. I follow this link. [Application idle time](https://stackoverflow.com/questions/4075180/application-idle-time) my program work properly, but suddenly the problem show up. I can't move to the other page (for example to the login page) or pop up a message using alertdialog because its in a thread. Do you have any solutions? ``` public class ControlActivity extends Activity { private static final String TAG=ControlActivity.class.getName(); /** * Gets reference to global Application * @return must always be type of ControlApplication! See AndroidManifest.xml */ public ControlApplication getApp() { return (ControlApplication )this.getApplication(); } @Override public void onUserInteraction() { super.onUserInteraction(); getApp().touch(); Log.d(TAG, "User interaction to "+this.toString()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} ``` here is my ControlApplication.java ``` public class ControlApplication extends Application { private static final String TAG=ControlApplication.class.getName(); private Waiter waiter; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "Starting application"+this.toString()); //setContentView(R.layout.activity_main); waiter=new Waiter(5*60*1000); //5 mins waiter.start(); Toast.makeText(ControlApplication.this, "start", Toast.LENGTH_LONG).show(); } public void touch() { waiter.touch(); Toast.makeText(ControlApplication.this, "touch", Toast.LENGTH_LONG).show(); } } ``` here is the Waiter.java ``` public class Waiter extends Thread implements Runnable{ private static final String TAG=Waiter.class.getName(); private long lastUsed; private long period; private boolean stop; Context activity; public Waiter(long period) { this.period=period; stop=false; } @SuppressLint("ParserError") public void run() { long idle=0; this.touch(); do { idle=System.currentTimeMillis()-lastUsed; Log.d(TAG, "Application is idle for "+idle +" ms"); try { Thread.sleep(5000); //check every 5 seconds } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); } if(idle > period) { idle=0; //do something here - e.g. call popup or so //Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show(); stopCounter(); } } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void touch() { lastUsed=System.currentTimeMillis(); } public synchronized void forceInterrupt() { this.interrupt(); } //soft stopping of thread public synchronized void stopCounter() { stop=true; } public synchronized void setPeriod(long period) { this.period=period; }} ``` I tried to create a new class and call a method to intent. Its also fail. tried to pop up a message from that method its also fail. do you guys have any other solutions for idle time? thanks. Regards, Alfred Angkasa
2012/07/18
[ "https://Stackoverflow.com/questions/11533613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533435/" ]
Like this: ``` responseData[0].diccioDatosForm.errorMessage ``` `responseData` itself is an array contains of 2 elements
It looks like you're trying to find the value of a parameter that's in an object that's the first element of an array in your JSON. In plain Javascript, that means: ``` var data = [{"diccioDatosForm": {"errorMessage": /* ... */] // grab diccioDatosForm from first array element: var diccioDatosForm = data[0].diccioDatosForm; ```
11,533,613
Halo, the first i want to know the idle time at my android application. after that, i will do something if it is a idle time mode. I follow this link. [Application idle time](https://stackoverflow.com/questions/4075180/application-idle-time) my program work properly, but suddenly the problem show up. I can't move to the other page (for example to the login page) or pop up a message using alertdialog because its in a thread. Do you have any solutions? ``` public class ControlActivity extends Activity { private static final String TAG=ControlActivity.class.getName(); /** * Gets reference to global Application * @return must always be type of ControlApplication! See AndroidManifest.xml */ public ControlApplication getApp() { return (ControlApplication )this.getApplication(); } @Override public void onUserInteraction() { super.onUserInteraction(); getApp().touch(); Log.d(TAG, "User interaction to "+this.toString()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} ``` here is my ControlApplication.java ``` public class ControlApplication extends Application { private static final String TAG=ControlApplication.class.getName(); private Waiter waiter; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "Starting application"+this.toString()); //setContentView(R.layout.activity_main); waiter=new Waiter(5*60*1000); //5 mins waiter.start(); Toast.makeText(ControlApplication.this, "start", Toast.LENGTH_LONG).show(); } public void touch() { waiter.touch(); Toast.makeText(ControlApplication.this, "touch", Toast.LENGTH_LONG).show(); } } ``` here is the Waiter.java ``` public class Waiter extends Thread implements Runnable{ private static final String TAG=Waiter.class.getName(); private long lastUsed; private long period; private boolean stop; Context activity; public Waiter(long period) { this.period=period; stop=false; } @SuppressLint("ParserError") public void run() { long idle=0; this.touch(); do { idle=System.currentTimeMillis()-lastUsed; Log.d(TAG, "Application is idle for "+idle +" ms"); try { Thread.sleep(5000); //check every 5 seconds } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); } if(idle > period) { idle=0; //do something here - e.g. call popup or so //Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show(); stopCounter(); } } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void touch() { lastUsed=System.currentTimeMillis(); } public synchronized void forceInterrupt() { this.interrupt(); } //soft stopping of thread public synchronized void stopCounter() { stop=true; } public synchronized void setPeriod(long period) { this.period=period; }} ``` I tried to create a new class and call a method to intent. Its also fail. tried to pop up a message from that method its also fail. do you guys have any other solutions for idle time? thanks. Regards, Alfred Angkasa
2012/07/18
[ "https://Stackoverflow.com/questions/11533613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533435/" ]
Like this: ``` responseData[0].diccioDatosForm.errorMessage ``` `responseData` itself is an array contains of 2 elements
Your `responseData` object is an array with objects within. As a result you must use an index when referencing the internal objects. ``` responseData[0].diccioDatosForm.errorMessage ```
11,533,613
Halo, the first i want to know the idle time at my android application. after that, i will do something if it is a idle time mode. I follow this link. [Application idle time](https://stackoverflow.com/questions/4075180/application-idle-time) my program work properly, but suddenly the problem show up. I can't move to the other page (for example to the login page) or pop up a message using alertdialog because its in a thread. Do you have any solutions? ``` public class ControlActivity extends Activity { private static final String TAG=ControlActivity.class.getName(); /** * Gets reference to global Application * @return must always be type of ControlApplication! See AndroidManifest.xml */ public ControlApplication getApp() { return (ControlApplication )this.getApplication(); } @Override public void onUserInteraction() { super.onUserInteraction(); getApp().touch(); Log.d(TAG, "User interaction to "+this.toString()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} ``` here is my ControlApplication.java ``` public class ControlApplication extends Application { private static final String TAG=ControlApplication.class.getName(); private Waiter waiter; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "Starting application"+this.toString()); //setContentView(R.layout.activity_main); waiter=new Waiter(5*60*1000); //5 mins waiter.start(); Toast.makeText(ControlApplication.this, "start", Toast.LENGTH_LONG).show(); } public void touch() { waiter.touch(); Toast.makeText(ControlApplication.this, "touch", Toast.LENGTH_LONG).show(); } } ``` here is the Waiter.java ``` public class Waiter extends Thread implements Runnable{ private static final String TAG=Waiter.class.getName(); private long lastUsed; private long period; private boolean stop; Context activity; public Waiter(long period) { this.period=period; stop=false; } @SuppressLint("ParserError") public void run() { long idle=0; this.touch(); do { idle=System.currentTimeMillis()-lastUsed; Log.d(TAG, "Application is idle for "+idle +" ms"); try { Thread.sleep(5000); //check every 5 seconds } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); } if(idle > period) { idle=0; //do something here - e.g. call popup or so //Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show(); stopCounter(); } } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void touch() { lastUsed=System.currentTimeMillis(); } public synchronized void forceInterrupt() { this.interrupt(); } //soft stopping of thread public synchronized void stopCounter() { stop=true; } public synchronized void setPeriod(long period) { this.period=period; }} ``` I tried to create a new class and call a method to intent. Its also fail. tried to pop up a message from that method its also fail. do you guys have any other solutions for idle time? thanks. Regards, Alfred Angkasa
2012/07/18
[ "https://Stackoverflow.com/questions/11533613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533435/" ]
Your `responseData` object is an array with objects within. As a result you must use an index when referencing the internal objects. ``` responseData[0].diccioDatosForm.errorMessage ```
It is because you are alerting the array that is being returned. To access the field you want, you should do: ``` responseData[0].diccioDatosForm.diccioDatosForm ``` I know that what I will say is not part of your question, but I suggest that you review your JSON structure, because its strange to have an array of two different things. I would use something like this: ``` { "configs": { "segundoNombre": "OK", "encargadoProvincia": "Ingrese un valor", "encargadoLocalidad": "Ingrese un valor" }, "error": { "message": "Verifique los datos invalidos ingresados..." }, "itens": [] // "encargados" list here } ``` Doing this you will have standard to use through yout application. To acess the message error you could do: ``` responseData.error.message ```
11,533,613
Halo, the first i want to know the idle time at my android application. after that, i will do something if it is a idle time mode. I follow this link. [Application idle time](https://stackoverflow.com/questions/4075180/application-idle-time) my program work properly, but suddenly the problem show up. I can't move to the other page (for example to the login page) or pop up a message using alertdialog because its in a thread. Do you have any solutions? ``` public class ControlActivity extends Activity { private static final String TAG=ControlActivity.class.getName(); /** * Gets reference to global Application * @return must always be type of ControlApplication! See AndroidManifest.xml */ public ControlApplication getApp() { return (ControlApplication )this.getApplication(); } @Override public void onUserInteraction() { super.onUserInteraction(); getApp().touch(); Log.d(TAG, "User interaction to "+this.toString()); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }} ``` here is my ControlApplication.java ``` public class ControlApplication extends Application { private static final String TAG=ControlApplication.class.getName(); private Waiter waiter; @Override public void onCreate() { super.onCreate(); Log.d(TAG, "Starting application"+this.toString()); //setContentView(R.layout.activity_main); waiter=new Waiter(5*60*1000); //5 mins waiter.start(); Toast.makeText(ControlApplication.this, "start", Toast.LENGTH_LONG).show(); } public void touch() { waiter.touch(); Toast.makeText(ControlApplication.this, "touch", Toast.LENGTH_LONG).show(); } } ``` here is the Waiter.java ``` public class Waiter extends Thread implements Runnable{ private static final String TAG=Waiter.class.getName(); private long lastUsed; private long period; private boolean stop; Context activity; public Waiter(long period) { this.period=period; stop=false; } @SuppressLint("ParserError") public void run() { long idle=0; this.touch(); do { idle=System.currentTimeMillis()-lastUsed; Log.d(TAG, "Application is idle for "+idle +" ms"); try { Thread.sleep(5000); //check every 5 seconds } catch (InterruptedException e) { Log.d(TAG, "Waiter interrupted!"); } if(idle > period) { idle=0; //do something here - e.g. call popup or so //Toast.makeText(activity, "Hello", Toast.LENGTH_LONG).show(); stopCounter(); } } while(!stop); Log.d(TAG, "Finishing Waiter thread"); } public synchronized void touch() { lastUsed=System.currentTimeMillis(); } public synchronized void forceInterrupt() { this.interrupt(); } //soft stopping of thread public synchronized void stopCounter() { stop=true; } public synchronized void setPeriod(long period) { this.period=period; }} ``` I tried to create a new class and call a method to intent. Its also fail. tried to pop up a message from that method its also fail. do you guys have any other solutions for idle time? thanks. Regards, Alfred Angkasa
2012/07/18
[ "https://Stackoverflow.com/questions/11533613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1533435/" ]
Your `responseData` object is an array with objects within. As a result you must use an index when referencing the internal objects. ``` responseData[0].diccioDatosForm.errorMessage ```
It looks like you're trying to find the value of a parameter that's in an object that's the first element of an array in your JSON. In plain Javascript, that means: ``` var data = [{"diccioDatosForm": {"errorMessage": /* ... */] // grab diccioDatosForm from first array element: var diccioDatosForm = data[0].diccioDatosForm; ```
69,597,781
So, I'm working in this project with a professor. As of now, it encompasses several own-made packages and modules. I sent him a .rar file with the whole project for revision, which he readily opened up in his pc using Spyder (the same IDE I use). We jointly made some corrections to it over a videocall, after which he sent me the corrected file back (agin, a .rar file). Once I got, I unpacked it and tried to run it again in my pc (the whole folder is configured as a Spyder project folder, so I opened using the spyder "open project" functionality) and all files seemed to execute just fine except for one. I don't know why, but there is a file that won't just execute once I press the "run file" button. It only allows itself to be executed cell-wise by pressing the "run current cell and go to the next one button", after which it runs just fine. But, for some reason, trying to run the whole file raises the following error: ``` File "C:\Users\andre\AppData\Local\Temp/ipykernel_10380/4038856374.py", line 1, in <module> runfile('C:/Users/andre/Desktop/Eafit/8vo Semestre/Monitoría Panel Solar/OptiSurf/Fitness_Function/fit_main.py', wdir='C:/Users/andre/Desktop/Eafit/8vo Semestre/Monitoría Panel Solar/OptiSurf/Fitness_Function') File "C:\Users\andre\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_bundle\pydev_umd.py", line 167, in runfile execfile(filename, namespace) File "C:\Users\andre\anaconda3\lib\site-packages\debugpy\_vendored\pydevd\_pydev_imps\_pydev_execfile.py", line 20, in execfile contents = stream.read() File "C:\Users\andre\anaconda3\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 667: invalid continuation byte ``` I frankly don't know what it is. At the beginning I thought It may had been one of the packages that had been corrupted but commenting THE WHOLE FILE and running it, raises the exact same error (not to mention that the rest of modules I tried, seemed to work just fine). Then I thought that it may have had to do with the fact that I had two projects with the same name (since the uncorrected and unmodified copy of my project started also raising that exact same error in the exact same file), so I tried erasing each one once, but that didn't work. Finally, I tried erasing everything, creating a new spyder project and just pasting the folders in the new project, but no luck there either. In summary, any insight would very much be appreciated.I have the feeling that file itself may have been corrupted? I mean, the error that it raises seems to indicate that file's name can't be decoded or something along those lines. If anyone has any suggestions, I'd love to hear them.
2021/10/16
[ "https://Stackoverflow.com/questions/69597781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16734032/" ]
(*Spyder maintainer here*) I'm sorry for the inconveniences this could have caused you. This was a bug in Spyder and it was fixed in our **5.1.5** version.
First: I saw on Stackoverflow many questions with similar problem and if you would use Google `UnicodeDecodeError: 'utf-8' codec can't decode byte` then you should find them few hours ago and you could resolve this problem few hours ago - without asking question. --- Error shows problem with `0xe9` - if I run `b'\xe9'.decode('utf-8)` then I get error but `b'\xe9'.decode('cp1250')` and `b'\xe9'.decode('latin1')` gives `'é'` - so your file uses `latin1` or `cp1250`. You should find some tool to convert files from `latin1/cp1250` to `utf-8` Or you can use Python for this - like this ``` filename = '...full path to your file...' with open(filename, encoding='latin1', mode='r') as fh: data = fh.read() with open(filename, encoding='utf-8', mode='w') as fh: fh.write(data) ```
23,967,843
This is very tricky for me. Given a very long list, > > [[100,11,1,0,40,1],[100,12,3,1,22,23],[101,11,1,0,45,1],[101,12,3,1,28,30],[102,11,1,0,50,1],[102,12,3,1,50,50],[103,11,1,0,50,1],[103,12,3,1,50,50],[104,11,1,0,50,25],[104,12,3,1,50,50],[105,11,1,0,50,49],[105,12,3,0,30,30],[106,11,1,0,50,49],[106,12,3,0,25,26],[107,11,1,1,33,20],[107,12,3,0,25,26],[108,11,1,1,2,1],[108,12,3,1,20,24],[109,11,1,1,2,1],[109,12,3,1,28,31],[110,11,1,0,40,1],[110,12,3,1,22,23]..] > > > Now igore the first number of each list, if two lists are the same in spite of the first number, for example > > [101,11,1,0,50,1] `alike` [102,11,1,0,50,1] > > > We keep the latter list, until the whole list is all checked. Ideally the result should be like : > > [[102,11,1,0,50,1],[103,12,3,1,50,50]..] > > > My idea is to use map to take the first number away, use nub and \\ to get rid of all repeat results, make it into like > > [[11,1,0,50,1],[12,3,1,50,50],[12,3,1,50,50],[11,1,0,50,49],[12,3,0,25,26],[11,1,1,2,1],[11,1,0,40,1],[12,3,1,22,23],[11,1,0,45,1],[12,3,1,28,30]..] > > > and use Set.isSubsetOf to filter the orignal list out. However, this idea is too complex and difficult to implenment. Since I am a beginner of Haskell, is there a better way to sort this? Or I can use a recursion function instead(still need efforts though)?
2014/05/31
[ "https://Stackoverflow.com/questions/23967843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3689497/" ]
If you need to compact a list by merging all items with same tail, try this code. ``` compactList:: [[Int]] -> [[Int]] compactList list = reverse $ compactList' list [] compactList':: [[Int]] -> [[Int]] -> [[Int]] compactList' [] res = res compactList' (l:ls) res | inList l res = compactList' ls res | otherwise = compactList' ls (l:res) inList :: [Int] -> [[Int]] -> Bool inList [] _ = False inList _ [] = False inList val@(x:xs) ((x':xs'):ls) | xs == xs' = True | otherwise = inList val ls ``` If we need "keep the latter list" (I missed that previously), then just change the place of `reverse` ``` compactList list = reverse $ compactList' list [] ```
You can just find the Euclidian distance between 2 vectors. For example, if you have two lists [a0, a1, ... , an] and [b0, b1, ..., bn], then the square of the Euclidian distance between them would be ``` sum [ (a - b) ^ 2 | (a, b) <- zip as bs ] ``` This can give you an idea of how *close* one list is to another. Ideally you should take the square root, but for what you are doing, I don't know if that is necessary. Edit: Sorry I misunderstood your question. According to your definition, `alike` is defined so: ``` alike as bs = (tail as) == (tail bs) ``` If that is the case, then something like the following should do the trick: ``` xAll [] = [] xAll xa@(x:xaa) = a : xAll b where a = last $ filter (alike x) xa b = filter (\m -> not (alike x m)) xa ``` But not sure if this is what you are looking for ...
23,967,843
This is very tricky for me. Given a very long list, > > [[100,11,1,0,40,1],[100,12,3,1,22,23],[101,11,1,0,45,1],[101,12,3,1,28,30],[102,11,1,0,50,1],[102,12,3,1,50,50],[103,11,1,0,50,1],[103,12,3,1,50,50],[104,11,1,0,50,25],[104,12,3,1,50,50],[105,11,1,0,50,49],[105,12,3,0,30,30],[106,11,1,0,50,49],[106,12,3,0,25,26],[107,11,1,1,33,20],[107,12,3,0,25,26],[108,11,1,1,2,1],[108,12,3,1,20,24],[109,11,1,1,2,1],[109,12,3,1,28,31],[110,11,1,0,40,1],[110,12,3,1,22,23]..] > > > Now igore the first number of each list, if two lists are the same in spite of the first number, for example > > [101,11,1,0,50,1] `alike` [102,11,1,0,50,1] > > > We keep the latter list, until the whole list is all checked. Ideally the result should be like : > > [[102,11,1,0,50,1],[103,12,3,1,50,50]..] > > > My idea is to use map to take the first number away, use nub and \\ to get rid of all repeat results, make it into like > > [[11,1,0,50,1],[12,3,1,50,50],[12,3,1,50,50],[11,1,0,50,49],[12,3,0,25,26],[11,1,1,2,1],[11,1,0,40,1],[12,3,1,22,23],[11,1,0,45,1],[12,3,1,28,30]..] > > > and use Set.isSubsetOf to filter the orignal list out. However, this idea is too complex and difficult to implenment. Since I am a beginner of Haskell, is there a better way to sort this? Or I can use a recursion function instead(still need efforts though)?
2014/05/31
[ "https://Stackoverflow.com/questions/23967843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3689497/" ]
From your description, I take it you want to get a list of the last lists to possess each of the unique tails. You can do it like this: ``` lastUniqueByTail :: Eq a => [[a]] -> [[a]] lastUniqueByTail = reverse . nubBy ((==) `on` tail) . reverse ``` ***Note*** this only works for finite lists of non-empty lists You can find `on` in the `Data.Function` module, and you can find `nubBy` in `Data.List`. So here's an explanation on each part, we'll work from the inside out: * `((==) `on` tail)` This function performs comparisons between two lists, and determines them to be equal if their tails are equal (i.e. it performs an equality check ignoring the first element). The `on` function is what is doing most of the magic here. It has the following type signature: ``` on :: (b -> b -> c) -> (a -> b) -> a -> a -> c ``` And it is essentially defined as `(f `on` g) x y = f (g x) (g y)`, so substituting the functions we provided, we get `((==) `on` tail) x y = (tail x) == (tail y)`. * Then, `nubBy` is like `nub` except that you can provide it a comparator to test equality on. We give it the function we defined above so that it discards elements with the same tail. * But, like `nub`, `nubBy` keeps the *first* element in each equivalence class it finds. (i.e. if it finds two elements that are equal in the list, it always picks the first). We want the last such elements, which is why we must reverse first (so that the last element that would have been equal becomes the first, and so is kept). * Finally, we reverse at the end to get the order back how it was to begin with.
You can just find the Euclidian distance between 2 vectors. For example, if you have two lists [a0, a1, ... , an] and [b0, b1, ..., bn], then the square of the Euclidian distance between them would be ``` sum [ (a - b) ^ 2 | (a, b) <- zip as bs ] ``` This can give you an idea of how *close* one list is to another. Ideally you should take the square root, but for what you are doing, I don't know if that is necessary. Edit: Sorry I misunderstood your question. According to your definition, `alike` is defined so: ``` alike as bs = (tail as) == (tail bs) ``` If that is the case, then something like the following should do the trick: ``` xAll [] = [] xAll xa@(x:xaa) = a : xAll b where a = last $ filter (alike x) xa b = filter (\m -> not (alike x m)) xa ``` But not sure if this is what you are looking for ...
23,967,843
This is very tricky for me. Given a very long list, > > [[100,11,1,0,40,1],[100,12,3,1,22,23],[101,11,1,0,45,1],[101,12,3,1,28,30],[102,11,1,0,50,1],[102,12,3,1,50,50],[103,11,1,0,50,1],[103,12,3,1,50,50],[104,11,1,0,50,25],[104,12,3,1,50,50],[105,11,1,0,50,49],[105,12,3,0,30,30],[106,11,1,0,50,49],[106,12,3,0,25,26],[107,11,1,1,33,20],[107,12,3,0,25,26],[108,11,1,1,2,1],[108,12,3,1,20,24],[109,11,1,1,2,1],[109,12,3,1,28,31],[110,11,1,0,40,1],[110,12,3,1,22,23]..] > > > Now igore the first number of each list, if two lists are the same in spite of the first number, for example > > [101,11,1,0,50,1] `alike` [102,11,1,0,50,1] > > > We keep the latter list, until the whole list is all checked. Ideally the result should be like : > > [[102,11,1,0,50,1],[103,12,3,1,50,50]..] > > > My idea is to use map to take the first number away, use nub and \\ to get rid of all repeat results, make it into like > > [[11,1,0,50,1],[12,3,1,50,50],[12,3,1,50,50],[11,1,0,50,49],[12,3,0,25,26],[11,1,1,2,1],[11,1,0,40,1],[12,3,1,22,23],[11,1,0,45,1],[12,3,1,28,30]..] > > > and use Set.isSubsetOf to filter the orignal list out. However, this idea is too complex and difficult to implenment. Since I am a beginner of Haskell, is there a better way to sort this? Or I can use a recursion function instead(still need efforts though)?
2014/05/31
[ "https://Stackoverflow.com/questions/23967843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3689497/" ]
From your description, I take it you want to get a list of the last lists to possess each of the unique tails. You can do it like this: ``` lastUniqueByTail :: Eq a => [[a]] -> [[a]] lastUniqueByTail = reverse . nubBy ((==) `on` tail) . reverse ``` ***Note*** this only works for finite lists of non-empty lists You can find `on` in the `Data.Function` module, and you can find `nubBy` in `Data.List`. So here's an explanation on each part, we'll work from the inside out: * `((==) `on` tail)` This function performs comparisons between two lists, and determines them to be equal if their tails are equal (i.e. it performs an equality check ignoring the first element). The `on` function is what is doing most of the magic here. It has the following type signature: ``` on :: (b -> b -> c) -> (a -> b) -> a -> a -> c ``` And it is essentially defined as `(f `on` g) x y = f (g x) (g y)`, so substituting the functions we provided, we get `((==) `on` tail) x y = (tail x) == (tail y)`. * Then, `nubBy` is like `nub` except that you can provide it a comparator to test equality on. We give it the function we defined above so that it discards elements with the same tail. * But, like `nub`, `nubBy` keeps the *first* element in each equivalence class it finds. (i.e. if it finds two elements that are equal in the list, it always picks the first). We want the last such elements, which is why we must reverse first (so that the last element that would have been equal becomes the first, and so is kept). * Finally, we reverse at the end to get the order back how it was to begin with.
If you need to compact a list by merging all items with same tail, try this code. ``` compactList:: [[Int]] -> [[Int]] compactList list = reverse $ compactList' list [] compactList':: [[Int]] -> [[Int]] -> [[Int]] compactList' [] res = res compactList' (l:ls) res | inList l res = compactList' ls res | otherwise = compactList' ls (l:res) inList :: [Int] -> [[Int]] -> Bool inList [] _ = False inList _ [] = False inList val@(x:xs) ((x':xs'):ls) | xs == xs' = True | otherwise = inList val ls ``` If we need "keep the latter list" (I missed that previously), then just change the place of `reverse` ``` compactList list = reverse $ compactList' list [] ```
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
Several of the hijackers, including [Mohamed Atta](https://en.wikipedia.org/wiki/Mohamed_Atta), held at least private pilot certificates and had undergone ATP level jet training in DC9 and 737 full motion simulators in December of 2000. Atta himself held a commercial license with instrument and multi engine ratings. They were well versed in aerial navigation techniques and more than capable of navigating the aircraft in question back to New York City and Washington DC after it was hijacked and secured. A basic scenario that any private or commercial pilot could have done: the hijackers knew the flights they were booked on and the rough routes they would take to their destinations. A little basic planning amongst themselves would have produced the approximate position the aircraft would be at at the time it was hijacked. Once seized and the flight crew liquidated, they could quickly determine their positions either from their headings and next waypoints or with a simple VOR fix (any competent private pilot can do this). The autopilots could quickly be disengaged and the airplanes hand flown using basic pilotage (good weather prevailed over the east coast that morning) or radio navaids to return to their targets. The navigation and flying they did that day was relatively simple. As an update, I know these kinds of questions float around with “9/11 truthers” and other conspiracy fanatics as some sort of proof that the official explanation is incorrect. Quite often they cherry pick quotes and ignore any other evidence that won’t fit their narrative. Combine that with the public that’s largely ignorant about aviation, it allows these kinds of ideas to fester very well without challenge.
All of the hijacked flights were going in different directions and had to be piloted to a different destination. The hijacker pilots had different degrees of success in doing this. The flight paths they took are shown in this map [published by the FBI](https://archives.fbi.gov/archives/about-us/ten-years-after-the-fbi-since-9-11/the-flights): [![aircraft flight paths](https://i.stack.imgur.com/yvA15.jpg)](https://i.stack.imgur.com/yvA15.jpg) Mohamed Atta, the ringleader of the effort, was a licensed commercial pilot received significant simulator training for large jets and the Boeing 737 in particular. Marwan al-Shehhi trained with Atta and received similar simulator training for 737s. Even so, al-Shehhi apparently missed Manhatten on his first pass, although he may have just been reconnoitering his approach. The pilot of flight 77, Hani Hanjour, was also a licensed commercial pilot who had knowledge of how to operate and navigate a 737. So, in summary, all of the hijacker pilots were trained in the basic operation of a 737 and knew how to do aeronautical navigation.
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
Several of the hijackers, including [Mohamed Atta](https://en.wikipedia.org/wiki/Mohamed_Atta), held at least private pilot certificates and had undergone ATP level jet training in DC9 and 737 full motion simulators in December of 2000. Atta himself held a commercial license with instrument and multi engine ratings. They were well versed in aerial navigation techniques and more than capable of navigating the aircraft in question back to New York City and Washington DC after it was hijacked and secured. A basic scenario that any private or commercial pilot could have done: the hijackers knew the flights they were booked on and the rough routes they would take to their destinations. A little basic planning amongst themselves would have produced the approximate position the aircraft would be at at the time it was hijacked. Once seized and the flight crew liquidated, they could quickly determine their positions either from their headings and next waypoints or with a simple VOR fix (any competent private pilot can do this). The autopilots could quickly be disengaged and the airplanes hand flown using basic pilotage (good weather prevailed over the east coast that morning) or radio navaids to return to their targets. The navigation and flying they did that day was relatively simple. As an update, I know these kinds of questions float around with “9/11 truthers” and other conspiracy fanatics as some sort of proof that the official explanation is incorrect. Quite often they cherry pick quotes and ignore any other evidence that won’t fit their narrative. Combine that with the public that’s largely ignorant about aviation, it allows these kinds of ideas to fester very well without challenge.
The Hudson River will take you straight to Manhattan. On a clear day, such as September 11 was, you could see the WTC for 100 miles or more (I had seen it from 160 miles away at Montauk Point on clear days, but you had to know where to look). AA77 would have had a problem navigating eastbound with such an amateur as Hani (who most likely never had the certificates reported). Since there aren't any prominent landmarks going east from Falmouth VOR.
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
Several of the hijackers, including [Mohamed Atta](https://en.wikipedia.org/wiki/Mohamed_Atta), held at least private pilot certificates and had undergone ATP level jet training in DC9 and 737 full motion simulators in December of 2000. Atta himself held a commercial license with instrument and multi engine ratings. They were well versed in aerial navigation techniques and more than capable of navigating the aircraft in question back to New York City and Washington DC after it was hijacked and secured. A basic scenario that any private or commercial pilot could have done: the hijackers knew the flights they were booked on and the rough routes they would take to their destinations. A little basic planning amongst themselves would have produced the approximate position the aircraft would be at at the time it was hijacked. Once seized and the flight crew liquidated, they could quickly determine their positions either from their headings and next waypoints or with a simple VOR fix (any competent private pilot can do this). The autopilots could quickly be disengaged and the airplanes hand flown using basic pilotage (good weather prevailed over the east coast that morning) or radio navaids to return to their targets. The navigation and flying they did that day was relatively simple. As an update, I know these kinds of questions float around with “9/11 truthers” and other conspiracy fanatics as some sort of proof that the official explanation is incorrect. Quite often they cherry pick quotes and ignore any other evidence that won’t fit their narrative. Combine that with the public that’s largely ignorant about aviation, it allows these kinds of ideas to fester very well without challenge.
[The 9/11 Commission Report](https://www.9-11commission.gov/report/911Report.pdf) goes into some detail on the hijackers' planning and preparation, including a (not entirely successful) attempt to obtain aviation GPS units: > > Moussaoui also purchased two knives and inquired of two manufacturers of GPS equipment whether their products could be > converted for aeronautical use > > > [...] > > > On August 22, moreover, Jarrah attempted to purchase four GPS units > from a pilot shop in Miami. He was able to buy only one unit, which he > picked up a few days later when he also purchased three aeronautical > charts (page 247-249) > > > The report doesn't detail whether there's any indication that unit was actually used. However, during their flight training, two of the hijackers also took a number of practice flights that would have familiarized themselves with the areas around New York and DC, which could have helped them with visual landmarks: > > Jarrah and Hanjour also received additional training and practice > flights in the early summer.A few days before departing on his > cross-country test flight, Jarrah flew from Fort Lauderdale to > Philadelphia, where he trained at Hortman Aviation and asked to fly > the Hudson Corridor, a low-altitude “hallway” along the Hudson River > that passes New York landmarks like the World Trade Center. Heavy > traffic in the area can make the corridor a dangerous route for an > inexperienced pilot. Because Hortman deemed Jarrah unfit to fly solo, > he could fly this route only with an instructor. > > > Hanjour, too, requested to fly the Hudson Corridor about this same > time, at Air Fleet Training Systems in Teterboro, New Jersey, where he > started receiving ground instruction soon after settling in the area > with Hazmi. Hanjour flew the Hudson Corridor, but his instructor > declined a second request because of what he considered Hanjour’s poor > piloting skills. Shortly thereafter, Hanjour switched to Caldwell > Flight Academy in Fairfield, New Jersey, where he rented small > aircraft on several occasions during June and July. In one such > instance on July 20, Hanjour—likely accompanied by Hazmi—rented > a plane from Caldwell and took a practice flight from Fairfield to > Gaithersburg, Maryland, a route that would have allowed them to fly > near Washington, D.C. (page 242) > > > The report also says that several of the hijackers also had access to flight simulator software and/or simulator time at flight schools, which would have given them further opportunities to practice navigation.
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
All of the hijacked flights were going in different directions and had to be piloted to a different destination. The hijacker pilots had different degrees of success in doing this. The flight paths they took are shown in this map [published by the FBI](https://archives.fbi.gov/archives/about-us/ten-years-after-the-fbi-since-9-11/the-flights): [![aircraft flight paths](https://i.stack.imgur.com/yvA15.jpg)](https://i.stack.imgur.com/yvA15.jpg) Mohamed Atta, the ringleader of the effort, was a licensed commercial pilot received significant simulator training for large jets and the Boeing 737 in particular. Marwan al-Shehhi trained with Atta and received similar simulator training for 737s. Even so, al-Shehhi apparently missed Manhatten on his first pass, although he may have just been reconnoitering his approach. The pilot of flight 77, Hani Hanjour, was also a licensed commercial pilot who had knowledge of how to operate and navigate a 737. So, in summary, all of the hijacker pilots were trained in the basic operation of a 737 and knew how to do aeronautical navigation.
The Hudson River will take you straight to Manhattan. On a clear day, such as September 11 was, you could see the WTC for 100 miles or more (I had seen it from 160 miles away at Montauk Point on clear days, but you had to know where to look). AA77 would have had a problem navigating eastbound with such an amateur as Hani (who most likely never had the certificates reported). Since there aren't any prominent landmarks going east from Falmouth VOR.
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
All of the hijacked flights were going in different directions and had to be piloted to a different destination. The hijacker pilots had different degrees of success in doing this. The flight paths they took are shown in this map [published by the FBI](https://archives.fbi.gov/archives/about-us/ten-years-after-the-fbi-since-9-11/the-flights): [![aircraft flight paths](https://i.stack.imgur.com/yvA15.jpg)](https://i.stack.imgur.com/yvA15.jpg) Mohamed Atta, the ringleader of the effort, was a licensed commercial pilot received significant simulator training for large jets and the Boeing 737 in particular. Marwan al-Shehhi trained with Atta and received similar simulator training for 737s. Even so, al-Shehhi apparently missed Manhatten on his first pass, although he may have just been reconnoitering his approach. The pilot of flight 77, Hani Hanjour, was also a licensed commercial pilot who had knowledge of how to operate and navigate a 737. So, in summary, all of the hijacker pilots were trained in the basic operation of a 737 and knew how to do aeronautical navigation.
[The 9/11 Commission Report](https://www.9-11commission.gov/report/911Report.pdf) goes into some detail on the hijackers' planning and preparation, including a (not entirely successful) attempt to obtain aviation GPS units: > > Moussaoui also purchased two knives and inquired of two manufacturers of GPS equipment whether their products could be > converted for aeronautical use > > > [...] > > > On August 22, moreover, Jarrah attempted to purchase four GPS units > from a pilot shop in Miami. He was able to buy only one unit, which he > picked up a few days later when he also purchased three aeronautical > charts (page 247-249) > > > The report doesn't detail whether there's any indication that unit was actually used. However, during their flight training, two of the hijackers also took a number of practice flights that would have familiarized themselves with the areas around New York and DC, which could have helped them with visual landmarks: > > Jarrah and Hanjour also received additional training and practice > flights in the early summer.A few days before departing on his > cross-country test flight, Jarrah flew from Fort Lauderdale to > Philadelphia, where he trained at Hortman Aviation and asked to fly > the Hudson Corridor, a low-altitude “hallway” along the Hudson River > that passes New York landmarks like the World Trade Center. Heavy > traffic in the area can make the corridor a dangerous route for an > inexperienced pilot. Because Hortman deemed Jarrah unfit to fly solo, > he could fly this route only with an instructor. > > > Hanjour, too, requested to fly the Hudson Corridor about this same > time, at Air Fleet Training Systems in Teterboro, New Jersey, where he > started receiving ground instruction soon after settling in the area > with Hazmi. Hanjour flew the Hudson Corridor, but his instructor > declined a second request because of what he considered Hanjour’s poor > piloting skills. Shortly thereafter, Hanjour switched to Caldwell > Flight Academy in Fairfield, New Jersey, where he rented small > aircraft on several occasions during June and July. In one such > instance on July 20, Hanjour—likely accompanied by Hazmi—rented > a plane from Caldwell and took a practice flight from Fairfield to > Gaithersburg, Maryland, a route that would have allowed them to fly > near Washington, D.C. (page 242) > > > The report also says that several of the hijackers also had access to flight simulator software and/or simulator time at flight schools, which would have given them further opportunities to practice navigation.
55,808
It is quite well known that the airplane hijackers on 9/11 were not professional pilots. So, my question is how some people who didn't have any experience of navigating the airplanes could find their way, for example from Boston to New York City? I read somewhere that some natural signs like the Hudson River (for example) helped them to find their way through New York City. But I'm still looking to find a more convincing answer if it is available.
2018/10/07
[ "https://aviation.stackexchange.com/questions/55808", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/34754/" ]
[The 9/11 Commission Report](https://www.9-11commission.gov/report/911Report.pdf) goes into some detail on the hijackers' planning and preparation, including a (not entirely successful) attempt to obtain aviation GPS units: > > Moussaoui also purchased two knives and inquired of two manufacturers of GPS equipment whether their products could be > converted for aeronautical use > > > [...] > > > On August 22, moreover, Jarrah attempted to purchase four GPS units > from a pilot shop in Miami. He was able to buy only one unit, which he > picked up a few days later when he also purchased three aeronautical > charts (page 247-249) > > > The report doesn't detail whether there's any indication that unit was actually used. However, during their flight training, two of the hijackers also took a number of practice flights that would have familiarized themselves with the areas around New York and DC, which could have helped them with visual landmarks: > > Jarrah and Hanjour also received additional training and practice > flights in the early summer.A few days before departing on his > cross-country test flight, Jarrah flew from Fort Lauderdale to > Philadelphia, where he trained at Hortman Aviation and asked to fly > the Hudson Corridor, a low-altitude “hallway” along the Hudson River > that passes New York landmarks like the World Trade Center. Heavy > traffic in the area can make the corridor a dangerous route for an > inexperienced pilot. Because Hortman deemed Jarrah unfit to fly solo, > he could fly this route only with an instructor. > > > Hanjour, too, requested to fly the Hudson Corridor about this same > time, at Air Fleet Training Systems in Teterboro, New Jersey, where he > started receiving ground instruction soon after settling in the area > with Hazmi. Hanjour flew the Hudson Corridor, but his instructor > declined a second request because of what he considered Hanjour’s poor > piloting skills. Shortly thereafter, Hanjour switched to Caldwell > Flight Academy in Fairfield, New Jersey, where he rented small > aircraft on several occasions during June and July. In one such > instance on July 20, Hanjour—likely accompanied by Hazmi—rented > a plane from Caldwell and took a practice flight from Fairfield to > Gaithersburg, Maryland, a route that would have allowed them to fly > near Washington, D.C. (page 242) > > > The report also says that several of the hijackers also had access to flight simulator software and/or simulator time at flight schools, which would have given them further opportunities to practice navigation.
The Hudson River will take you straight to Manhattan. On a clear day, such as September 11 was, you could see the WTC for 100 miles or more (I had seen it from 160 miles away at Montauk Point on clear days, but you had to know where to look). AA77 would have had a problem navigating eastbound with such an amateur as Hani (who most likely never had the certificates reported). Since there aren't any prominent landmarks going east from Falmouth VOR.
70,417,075
I was creating a war game and I have this dictionary of weapons and the damage they do on another type of troops. also, I have a list which has the keys from the dictionary stored in it. ``` weapon_specs = { 'rifle': {'air': 1, 'ground': 2, 'human': 5}, 'pistol': {'air': 0, 'ground': 1, 'human': 3}, 'rpg': {'air': 5, 'ground': 5, 'human': 3}, 'warhead': {'air': 10, 'ground': 10, 'human': 10}, 'machine gun': {'air': 3, 'ground': 3, 'human': 10} } inv = ['rifle', 'machine gun', 'pistol'] ``` I need to get this output: ``` {'air': 4, 'ground': 6, 'human': 18} ``` I tried this : ``` for i in weapon_specs: for k in inv: if i == k: list.update(weapon_specs[k]) ```
2021/12/20
[ "https://Stackoverflow.com/questions/70417075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17411307/" ]
You can use `collections.Counter`: ``` from collections import Counter count = Counter() for counter in [weapon_specs[weapon] for weapon in inv]: count += counter out = dict(count) ``` If you don't want to use `collections` library, you can also do: ``` out = {} for weapon in inv: for k,v in weapon_specs[weapon].items(): out[k] = out.get(k, 0) + v ``` Output: ``` {'air': 4, 'ground': 6, 'human': 18} ```
Without having to import anything. You can just map the dictionary with two loops. ``` out = {'air': 0, 'ground': 0, 'human': 0} for weapon in inv: for k, v in weapon_specs[weapon].items(): out[k] += v print(out) ``` Output: ``` {'air': 4, 'ground': 6, 'human': 18} ```