qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
3,922,249
This is a newbie question but I hope I can express my question as clearly as possible. I'm trying to do pattern matching in C++. I've downloaded the Win32 version of PCRE from [here](http://gnuwin32.sourceforge.net/packages/pcre.htm) and I've placed the downloaded pcre3.dll and pcreposix3.dll files into the folder of Dev-CPP's lib folder (I'm using Bloodshed Dev-C++ 4.9.9 IDE). I've also downloaded a pcrecpp.h header file and have it in the same directory I'm writing the following code (not writing actually. I'm coping example code from a PDF tutorial named PCRE- Perl Compatible Regular Express). But I can't get it to work. The code is as follows: ``` #include <iostream> #include <string> #include <pcrecpp.h> using namespace std; int main() { int i; string s; pcrecpp::RE re("(\\w+):(\\d+)"); if (re.error().length() > 0) { cout << "PCRE compilation failed with error: " << re.error() << "\n"; } if (re.PartialMatch("root:1234", &s, &i)) cout << s << " : " << i << "\n"; } ``` When I compile the code, Dev-C++ gives me a lot of errors including: "`pcrecpp' has not been declared" and "RE" undeclared. How should I deal with the downloaded files and fix my problem? Or is there something obvious that I'm missing?
2010/10/13
[ "https://Stackoverflow.com/questions/3922249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183467/" ]
If you specify the file for `#include` with angle brackets (`<>`), then the compiler will only look for that header in the locations for external libraries, in so far as the compiler is aware of them. If you instead use quotation marks (`""`), then the compiler will also look in the locations for the current project, which typically includes the current directory. ~~The quick fix for your current problem is to use~~ ``` #include "pcrecpp.h" ``` The alternative is to tell the compiler where it can find the headers of the PCRE library. You will have to tell the compiler where it can find the headers of the PCRE library. How to do this differs from build system to build system, but if you are using an IDE, then there should be an option somewhere to specify the 'Include directories'. This is where you add the directory of the PCRE headers (with full path). --- As a side-note: When the compiler gives you a large number of errors and warnings, always start with fixing the first one. I would guess that in this case it was something like "unable to find header: pcrecpp.h". It is often the case that, if the compiler tries to continue after encountering a problem, more problems are found that are follow-on problems of the first one. When the first problem is fixed, these also magically disappear.
``` cout << “PCRE compilation failed with error: “ << re.error() << “\n”; ``` I just copied your code and tried to compile it. I got the same error as you reported. The problem is that string you put to cout is not properly started/ended. You should use real " instead of marks which looks like double quotes (") but it is not. If you fix it, your code should compile w/o any error.
46,699,256
I know this is not a coding service where I ask for something and you spit out a result. I am looking for the following help: say I have 2 unique text data that I can assign to a cell (via data validation or typing in each cell) on a row of 7 cells. Now say I want to allow the text to be assigned to only 3 of those 7 cells each . Is this possible? If any text is selected more than 3 times within the 7 cells I return an error or grey out the remaining cells? In other words, once I input the data in a cell, it loops through the 7 cells and counts the number of unique text data found. if more than three of the same text data is found then error, else allow text input.. Any info on this is helpful. Links etc. I am very grateful for any insight. PS I know a bit about data validation and vba macros. Just looking for pointers.
2017/10/11
[ "https://Stackoverflow.com/questions/46699256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8762074/" ]
The valid value, use instead of `QUrl("local.registry")`: ``` QUrl("tcp://192.168.0.3:-1"); ``` The valid value, use instead of `QUrl("local.replica")`: ``` QUrl("tcp://192.168.0.3:9999"); ``` The IP address *192.168.0.3* - used for example (it value valid for my workstation in our office network) in your case IP address can contain other digits.
If Qt is indicating that 'the address is in use' then that is likely the source of the problem, literally the socket at IP:PORT is being used. You may check your development environment to see if you have multiple processes running of the same app - this is often the case and it leads to a collision of address spaces. We see this error in our environment consistently, and the root cause is simply as stated: 'the address is in use'.
7,992,584
when i am print `System.currentTimeMillis()` give me : ``` 11-03 14:47:05.400: INFO/System.out(7579): date is :: 14475410111 ``` What is the correct procedure to get entire date with time.?
2011/11/03
[ "https://Stackoverflow.com/questions/7992584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863257/" ]
To get current date and time in Android, You can use: ``` Calendar c = Calendar.getInstance(); System.out.println("Current time => "+c.getTime()); ``` Output: ------- Current time => Thu Nov 03 15:00:45 GMT+05:30 2011 FYI, once you have this time in 'c' object, you can use [SimpleDateFormat](http://developer.android.com/reference/java/text/SimpleDateFormat.html) class to get date/time in desired format. Final Solution: --------------- ``` SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Sring formattedDate = df.format(c.getTime()); // c is Calendar object System.out.println("========> formatted date => "+formattedDate); ``` **Output:** ========> formatted date => 2011-11-03 15:13:37
``` Date now = new Date(System.currentTimeMillis()); ``` By the way : `currentTimeMillis()` > > Returns the current system time in milliseconds since January 1, 1970 00:00:00 UTC. > > >
64,906,525
I currently have a windows laptop with an intel i5. I am looking to upgrade to an M1 mac. Emulation isn't a problem for me(Virtualization is slower on ARM). Can any early adopter let me know if it is fast enough for basic android development and some Xcode?
2020/11/19
[ "https://Stackoverflow.com/questions/64906525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14623895/" ]
It's definitely okay for *basic* Android development. I've had a few instances where it has randomly frozen on me and I've had to do a force quit. And it doesn't particularly feel like it is quicker than the 2015 MacBook Pro I was running it on before(!) It is, however, very quiet (no fan!) and hopefully now that IntelliJ has been ported we can see a dedicated M1 version of Android Studio soon.
Is anyone else using NDK with the M1? I have two Android apps that I use Android Studio for. I tried both on my new M1 Mac mini. One, relatively simple and Java only, builds fine. The second has Java and C code (uses the NDK). Building it fails with a crash of Android Studio. As a result of this, I'm having to develop on my legacy Intel MacBook Pro.
34,983,475
<http://cplusplus.com/reference/string/basic_string/operator[]> I understand that it's advantageous to have a second version which returns `const` to prevent warnings when a `const` result is required and to mitigate casting but if the function already provides a non-`const` method (method-- not result) then what is the point of declaring the `const`-result method `const`?
2016/01/25
[ "https://Stackoverflow.com/questions/34983475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1762276/" ]
If you have a `const std::basic_string` you cannot call (non-const) `std::basic_string::operator[]`, as it is, well, not marked const.
If there wasn't a `const` version of the function, the function could not be invoked on a `const` instance. For example: ``` void func (const std::string &h) { if (h[0] == "hello") ... } ``` How would this work if there wasn't a `const` version of `operator[]`?
72,244,234
I am importing the data with this command ``` df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices') ``` and this is the result: [![1](https://i.stack.imgur.com/gZmd4.png)](https://i.stack.imgur.com/gZmd4.png) The date is a common column and I want it like this: [![2](https://i.stack.imgur.com/fLrJu.png)](https://i.stack.imgur.com/fLrJu.png)
2022/05/14
[ "https://Stackoverflow.com/questions/72244234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19081887/" ]
I found the answer.Adding `parse_dates=True`, `index_col=0` to the import command like this: ``` df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices', parse_dates=True, index_col=0) ``` The output is this: [![1](https://i.stack.imgur.com/GhA8p.png)](https://i.stack.imgur.com/GhA8p.png)
I found a better way to import them, because when I was trying to calculate the monthly returns it does not work. So I use this new code and the date were perfect. ``` df = pd.read_excel('C:/Users/Me/Data.xlsx', sheet_name='Prices') df.index = pd.to_datetime(df['Date']) df.drop(['Date'], axis = 'columns', inplace=True) df.head() ``` and this is the result: [![1](https://i.stack.imgur.com/oc5yk.png)](https://i.stack.imgur.com/oc5yk.png)
6,204,878
I am trying to check if a file is on the server with the C# code behind of my ASP.NET web page. I know the file does exist as I put it on the server in a piece of code before hand. Can anyone see why it is not finding the file. This is the code: ``` wordDocName = "~/specifications/" + Convert.ToInt32(ViewState["projectSelected"]) + ".doc"; ViewState["wordDocName"] = wordDocName; if (File.Exists(wordDocName)) { btnDownloadWordDoc.Visible = true; } else { btnDownloadWordDoc.Visible = false; } ```
2011/06/01
[ "https://Stackoverflow.com/questions/6204878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/732352/" ]
`File.Exists()` and probably everything else you want to do with the file will need a real Path. Your `wordDocName` is a relative URL. Simply use ``` string fileName = Server.MapPath(wordDocName); ```
this might not work if the directory holding the file is referenced by a junction/symbolic link. I have this case in my own application and if I put the REAL path to the file, File.Exists() returns true. But if I use Server.MapPath but the folder is in fact a junction to the folder, it seems to fail. Anyone experienced the same behaviour?
22,982,741
I have that form ``` <form action="deletprofil.php" id="form_id" method="post"> <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input"> <button type="submit" name="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button> <button type="submit" name="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button> </div> </form> ``` and that Popup from `jQuery Mobile` ``` <div class="ui-popup-container pop in ui-popup-active" id="popupDialog-popup" tabindex="0" style="max-width: 1570px; top: 2239.5px; left: 599px;"> <div data-role="popup" id="popupDialog" data-overlay-theme="b" data-theme="b" data-dismissible="false" style="max-width:400px;" class="ui-popup ui-body-b ui-overlay-shadow ui-corner-all"> <div data-role="header" data-theme="a" role="banner" class="ui-header ui-bar-a"> <h1 class="ui-title" role="heading" aria-level="1">Delete Page?</h1> </div> <div role="main" class="ui-content"> <h3 class="ui-title">Sicher dass Sie das Profil löschen wollen?</h3> <p>Es kann nicht mehr rückgängig gemacht werden.</p> <a href="#" id="NOlink" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b">Abbrechen</a> <a href="#" id="OKlink" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b">OK</a> </div> </div> </div> ``` with my jQuery Code ``` <script language="javascript" type="text/javascript"> $(function(){ $('#form_id').bind('submit', function(evt){ $form = this; evt.preventDefault(); $("#popupDialog").popup('open'); $("#NOlink").bind( "click", function() { $("#popupDialog").popup('close'); }); $("#OKlink").bind( "click", function() { $("#popupDialog").popup('close'); $( "#form_id" ).submit(); }); }); }); </script> ``` The popup shows up but the form submit does not work. Does someone have any ideas?
2014/04/10
[ "https://Stackoverflow.com/questions/22982741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1374234/" ]
***The NUMBER ONE error is having ANYTHING with the reserved word `submit` as `ID` or `NAME` in your form.*** If you plan to call `.submit()` on the form AND the form has `submit` as id or name on any form element, then you need to **rename that form element**, since the form’s submit method/handler is shadowed by the name/id attribute. --- Several other things: As mentioned, you need to submit the form using a simpler event than the jQuery one BUT you also need to cancel the clicks on the links Why, by the way, do you have two buttons? Since you use jQuery to submit the form, you will never know which of the two buttons were clicked unless you set a hidden field on click. ``` <form action="deletprofil.php" id="form_id" method="post"> <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input"> <button type="submit" value="1" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button> <button type="submit" value="2" class="ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button> </div> </form> $(function(){ $("#NOlink, #OKlink").on("click", function(e) { e.preventDefault(); // cancel default action $("#popupDialog").popup('close'); if (this.id=="OKlink") { document.getElementById("form_id").submit(); // or $("#form_id")[0].submit(); } }); $('#form_id').on('submit', function(e){ e.preventDefault(); $("#popupDialog").popup('open'); }); }); ``` Judging from your comments, I think you really want to do this: ``` <form action="deletprofil.php" id="form_id" method="post"> <input type="hidden" id="whichdelete" name="whichdelete" value="" /> <div data-role="controlgroup" data-filter="true" data-input="#filterControlgroup-input"> <button type="button" value="1" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Anlegen</button> <button type="button" value="2" class="delete ui-btn ui-shadow ui-corner-all ui-icon-delete ui-btn-icon-right" data-icon="delete" aria-disabled="false">Bnlegen</button> </div> </form> $(function(){ $("#NOlink, #OKlink").on("click", function(e) { e.preventDefault(); // cancel default action $("#popupDialog").popup('close'); if (this.id=="OKlink") { // trigger the submit event, not the event handler document.getElementById("form_id").submit(); // or $("#form_id")[0].submit(); } }); $(".delete").on("click", function(e) { $("#whichdelete").val(this.value); }); $('#form_id').on('submit', function(e){ e.preventDefault(); $("#popupDialog").popup('open'); }); }); ```
Some time you have to give all the form element into a same div. example:- If you are using ajax submit with modal. So all the elements are in modal body. Some time we put submit button in modal footer.
38,976
The [US Environmental Protection Authority (EPA) has restrictions on "Particulate Matter"](https://www.epa.gov/pm-pollution). [A recent Wall Street Journal op-ed piece](https://www.wsj.com/articles/a-step-toward-scientific-integrity-at-the-epa-1500326062) article claims it is based on a > > scientifically unsupported notion that the fine particles of soot emitted by smokestacks and tailpipes are lethal. The EPA claims that such particles kill hundreds of thousands of Americans annually. > > > It complains that EPA proceeded despite contrary advice from the Clean Air Scientific Advisory Committee: > > But when the agency ran its claims past CASAC in 1996, the board concluded that the scientific evidence did not support the agency’s regulatory conclusion. Ignoring the panel’s advice, the EPA’s leadership chose to regulate fine particles anyway, and resolved to figure out a way to avoid future troublesome opposition from CASAC. > > > It goes on to say that the evidence hasn't turned up since: > > the sci­en­tific case against par­tic­u­late mat­ter hasn’t im­proved since the 1990s > > > Is it true that the EPA's restrictions on particulate matter are not supported by evidence - even today - that particulate matter kills many thousands of Americans per year?
2017/07/18
[ "https://skeptics.stackexchange.com/questions/38976", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/36871/" ]
**It is justified with (recent) evidence.** Selectively quoting from [WP:Pariculates#Health\_problems](https://en.wikipedia.org/wiki/Particulates#Health_problems), emphasis of publication dates mine: > > Inhalation of PM2.5 – PM10 is associated with elevated risk of > adverse pregnancy outcomes, such as low birth weight. > > > Sapkota, Amir; Chelikowsky, Adam P.; Nachman, Keeve E.; Cohen, Aaron J.; Ritz, Beate (**2012**-12-01). ["Exposure to particulate matter and adverse birth outcomes: a comprehensive review and meta-analysis"](https://link.springer.com/article/10.1007/s11869-010-0106-3). Air Quality, Atmosphere & Health. 5 (4): 369–381. ISSN 1873-9318. doi:10.1007/s11869-010-0106-3. > > Increased levels of fine particles in the air as a result of > anthropogenic particulate air pollution "is consistently and > independently related to the most serious effects, including lung > cancer and other cardiopulmonary mortality." > > > "[...] fine particulate air pollution (PM(2.5)), causes about 3% of mortality from cardiopulmonary disease, about 5% of mortality from cancer of the trachea, bronchus, and lung, and about 1% of mortality from acute respiratory infections in children under 5 years, worldwide." > > > Ole Raaschou-Nielsen; et al. (July 10, **2013**). ["Air pollution and lung cancer incidence in 17 European cohorts: prospective analyses from the European Study of Cohorts for Air Pollution Effects (ESCAPE)"](http://www.thelancet.com/journals/lanonc/article/PIIS1470-2045%2813%2970279-1/abstract). The Lancet Oncology. 14 (9): 813–22. PMID 23849838. doi:10.1016/S1470-2045(13)70279-1. Cohen, A. J.; Anderson, Ross H.; Ostro, B; Pandey, K. D.; Krzyzanowski, M; Künzli, N; Gutschmidt, K; Pope, A; Romieu, I; Samet, J. M.; Smith, K (**2005**). "The global burden of disease due to outdoor air pollution". J. Toxicol. Environ. Health Part A. 68 (13–14): 1301–7. PMID 16024504. doi:10.1080/15287390590936166. > > [...] PM2.5 leads to high plaque deposits in arteries, > causing vascular inflammation and atherosclerosis – a hardening of the > arteries that reduces elasticity, which can lead to heart attacks and > other cardiovascular problems. > > > Pope, C Arden; et al. (**2002**). ["Cancer, cardiopulmonary mortality, and long-term exposure to fine particulate air pollution"](http://jama.ama-assn.org/cgi/reprint/287/9/1132). J. Amer. Med. Assoc. 287 (9): 1132–1141. PMC 4037163 Freely accessible. PMID 11879110. doi:10.1001/jama.287.9.1132. > > An increase in estimated annual exposure to PM 2.5 of just 5 µg/m3 was linked with a 13% increased risk of heart attacks. > > > Cesaroni G, Forastiere F, Stafoggia M,; Stafoggia; Andersen; Badaloni; Beelen; Caracciolo; De Faire; Erbel; Eriksen; Fratiglioni; Galassi; Hampel; Heier; Hennig; Hilding; Hoffmann; Houthuijs; Jöckel; Korek; Lanki; Leander; Magnusson; Migliore; Ostenson; Overvad; Pedersen; j; Penell; et al. (**2014**). ["Long term exposure to ambient air pollution and incidence of acute coronary events: prospective cohort study and meta-analysis in 11 European cohorts from the ESCAPE Project"](http://www.bmj.com/content/348/bmj.f7412). BMJ (Clinical research ed.). 348: f7412. PMC 3898420 Freely accessible. PMID 24452269. doi:10.1136/bmj.f7412. > > Particulate matter studies in Bangkok Thailand from 2008 indicated a 1.9% increased risk of dying from cardiovascular disease, and 1.0% risk of all disease for every 10 micrograms per cubic meter. Levels averaged 65 in 1996, 68 in 2002, and 52 in 2004. Decreasing levels may be attributed to conversions of diesel to natural gas combustion as well as improved regulations. > > > [Archived online document, **2008**](https://web.archive.org/web/20081217174016/http://www.baq2008.org/system/files/sw16_Vajanapoom+presentation.pdf) Please check the full article for more studies and references.
Odd. The CASAC also disagreed with the EPA on PM in 2006 - only they felt the restrictions were not protective enough of public health: > > "The CASAC recommended changes in the annual fine-particle standard > because there is clear and convincing scientific evidence that > significant adverse human-health effects occur in response to > short-term and chronic particulate matter exposures at and below 15 > μg/m3, the level of the current annual PM2.5 standard. The CASAC > affirmed this recommended reduction in the annual fine-particle > standard in our letter dated March 21, 2006 concerning the proposed > rule for the PM NAAQS, in which 20 of the 22 members of the CASAC’s > Particulate Matter Review Panel — including all seven members of the > chartered (statutory) Committee — were in complete agreement. While > there is uncertainty associated with the risk assessment for the PM2.5 > standard, this very uncertainty suggests a need for a prudent approach > to providing an adequate margin of safety. It is the CASAC’s consensus > scientific opinion that the decision to retain without change the > annual PM2.5 standard does not provide an “adequate margin of safety … > requisite to protect the public health” (as required by the Clean Air > Act), leaving parts of the population of this country at significant > risk of adverse health effects from exposure to fine PM. > > > Significantly, we wish to point out that the CASAC’s recommendations > were consistent with the mainstream scientific advice that EPA > received from virtually every major medical association and public > health organization that provided their input to the Agency, including > the American Medical Association, the American Thoracic Society, the > American Lung Association, the American Academy of Pediatrics, the > American College of Cardiology, the American Heart Association, the > American Cancer Society, the American Public Health Association, and > the National Association of Local Boards of Health. Indeed, to our > knowledge there is no science, medical or public health group that > disagrees with this very important aspect of the CASAC’s > recommendations. EPA’s recent “expert elicitation” study (Expanded > Expert Judgment Assessment of the Concentration-Response Relationship > Between PM2.5 Exposure and Mortality, September 21, 2006) only lends > additional support to our conclusions concerning the adverse human > health effects of PM2.5. > > > Source: <https://yosemite.epa.gov/sab%5Csabproduct.nsf/1C69E987731CB775852571FC00499A10/$File/casac-ltr-06-003.pdf>
1,788,015
Is this pure coincidence or is this a special case of some well-known number-theoretic result? If the latter is true, is there some notable generalization? EDIT: Thanks to the interesting answers below, a follow-up question is now on MathOverflow: <https://mathoverflow.net/questions/239033/repdigit-numbers-which-are-sum-of-consecutive-squares?noredirect=1#comment591447_239033>
2016/05/16
[ "https://math.stackexchange.com/questions/1788015", "https://math.stackexchange.com", "https://math.stackexchange.com/users/200455/" ]
It is probably coincidence. When considering sums of 16 or less consecutive squares, where the smallest is at most $200^2$, I found only one other such sum: $$71^2+72^2+73^2+74^2+75^2+76^2+77^2+78^2=44444$$
I've heard this kind of thing called a *curio*, or "curiosity." The kind of thing that makes you go, "Huh ... neat!" Piquito's answer is interesting. I wouldn't be so bold as to say it's *the* answer, because there are lots of other ways to dissect and reassemble things. For example: $$1111 = 555 + 555 + 1 = 10 \cdot 111 + 1.$$ The formula for the sum of the squares of six consecutive integers, starting with $n$, is $S(n) = 6n^2 + 30n + 55.$ This will let you probe that space (I didn't see any other examples of repeated-digit numbers, and I looked up to around $n=90000$.) Or, extending a bit, the sum of $m$ consecutive squares, starting with the square of $n$ is $$S'(m,n) = mn^2 + m(m-1)n + \frac{(m-1)m(2m-1)}{6}.$$ For example $$S'(6,11) = 1111$$ Canvassing this space would result in a subset of OEIS sequence [A180436](https://oeis.org/A180436), "Palindromic numbers which are sum of consecutive squares." The next one above $1111$ that has just one digit in its representation is $44444$. I'm resisting the temptation to figure out which squares this one is a sum of. (OK, wythagoras figured it out.) Anyway, if there is a relationship or an underlying rule, it's well-hidden. But it's fun to look!
105,239
I have a valid US visa on my Indian passport. I changed my nationality to HKSAR. Can my US visa be transferred to my HKSAR passport?
2017/11/14
[ "https://travel.stackexchange.com/questions/105239", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/70298/" ]
**No**. A US visa can not be transferred to any other passport. But if an expired passport contains it and there is a new passport the same visa **can be used** after meeting certain conditions listed below. > > **My old passport has already expired. My visa to travel to the United States is still valid but in my expired passport. Do I need to apply for a new visa with my new passport?** > > > No. If your visa is still valid you can travel to the United States with your two passports, as long as the visa is valid, not damaged, and is the appropriate type of visa required for your principal purpose of travel. (Example: tourist visa, when your principal purpose of travel is tourism). **Both passports (the valid and the expired one with the visa) should be from the same country and type (Example: both Uruguayan regular passports, both official passports, etc.)**. When you arrive at the U.S. port-of-entry (POE, generally an airport or land border) the Customs and Border Protection Immigration Officer will check your visa in the old passport and if s/he decides to admit you into the United States they will stamp your new passport with an admission stamp along with the annotation "VIOPP" (visa in other passport). Do not try to remove the visa from your old passport and stick it into the new valid passport. If you do so, your visa will no longer be valid. > > > (The emphasis is mine) Source: **[US Department of State](https://travel.state.gov/content/visas/en/general/frequently-asked-questions/about-visas-the-basics.html)** Your visa on an expired Indian passport **is not valid** on an HKSAR passport (or any other country for that matter).
TL;DR: **you will need to get a new visa** As the other answer points out, you could use both passports if they had been issued by the same country and of the same type. But since you changed nationalities, this is not an option for you and you will need a new visa. Do take note of the passport number of your Indian passport, in case you're asked to surrender it to Indian authorities. It might help your visa application using your HK passport, as I believe you're asked about previously held nationalities and passports in the application form
29,291,113
When I use the command: ``` pyinstaller.exe --icon=test.ico -F --noconsole test.py ``` All icons do not change to test.ico. Some icons remain as the pyinstaller's default icon. Why? All icon change in * windows 7 32bit * windows 7 64bit (make an exe file OS) Some remain default * windows 7 64bit (other PC)
2015/03/27
[ "https://Stackoverflow.com/questions/29291113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3683061/" ]
I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for `--onefile`: ``` pyinstaller.exe --onefile --windowed --icon=app.ico app.py ``` Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else. The information here was found at this site: <https://mborgerson.com/creating-an-executable-from-a-python-script>
The solution for me was refresh the icon cache of the windows explorer for Windows 10: Enter "ie4uinit.exe -show" in Windows run Link: <https://superuser.com/questions/499078/refresh-icon-cache-without-rebooting>
1,458
As an old-school AD&D 2nd Edition player, I like most of the changes in 4e. One thing I can't come to grips with is the loot system. I *hate hate hate* that the treasure drops are tailored to such a high degree. It pushes the game into such a linear progression for equipping your characters. I'm thinking about sitting down and discussing the [50% Loot System](http://www.enworld.org/forum/4e-fan-creations-house-rules/268176-simpler-treasure-system-mostly-random-loot.html) with our DM. I really miss finding random loots in treasure caches, and this system seems like it would bring some of that mystery back. The system in a nutshell: 1. The DM randomizes (most) loot. 2. Items are sold at half price, instead of at 20% of list price. 3. All treasure parcels containing magic items are raised by one level. If you're into mechanics, please read the thread for some nitty gritty details. Apparently the system works quite well. Has anyone tried alternate loot systems? What are your experiences with them?
2010/08/27
[ "https://rpg.stackexchange.com/questions/1458", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/220/" ]
Take a look at the D&D essentials changes to magic items and loot. It takes a lot of steps in the right direction. Before these changes my group had a similar problem but went it a different direction then what you suggest. We: * removed the ability for a player to start with anything other than magic weapons, armors and neck and then only with a basic +, no extra effects. * free up feats like expertise to be more flexable so that players aren't "tied down" to a particular weapon. Once we started doing these things, we found that we became excited about anything magical that we found. Sure a fire resist cloak wasn't as good of an item for the fighter as a cloak of the walking wounded would have been, but its a heck of a lot more exciting than the +1 cloak he was wearing.
In my original Caldera setting, I'm basically getting rid of magic item "drops" and just letting characters purchase magic items. It's a saberpunk (high fantasy inspired by cyberpunk tropes) campaign, so magic replaces technology in this world. A PC can go buy just about any magic item he or she wants off the black market. *Finding* the magic items they want can be a source of adventure (and skill challenges). I can even let them buy certain items as magical tattoos! "This guy says he can give you a shoulder tattoo that will make you fight at a +1 with a sword it's attuned to." Yes, this is a lot like tailoring magic items to the party, but it doesn't strain credulity the same way. If you're just going to pick items off the party's wish list anyway, why not let them buy what they want? Then you (the DM) give out more coin treasure (or goods that can be sold) and let them buy off their own wish list.
60,246,333
I am trying to join these two URIs ``` from urllib.parse import urljoin # baskslash is not a mistake r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq") print(r) ``` I am getting ``` https:///videofaq ``` How can I get ``` https:/\\corrlinks.blob.core.windows.net/videofaq ``` This one would be Ok too: ``` https://corrlinks.blob.core.windows.net/videofaq ``` Note. Browsers handle the link above just fine.
2020/02/16
[ "https://Stackoverflow.com/questions/60246333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352611/" ]
I have ended up with ``` url = url.replace("\\" , "/").replace("///", "//") ```
python treats backslash(\) as an escape character. using r'string' goes handy many times. r just means raw string. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character. In this case ``` from urllib.parse import urljoin r = urljoin(r"https://corrlinks.blob.core.windows.net", "videofaq") print(r) # returns https://corrlinks.blob.core.windows.net/videofaq ``` This should do the work.
17,633,614
Look at the following code: <http://jsfiddle.net/B2wFZ/> If your resolution is 1366x768 you will see the input in line with the text, try zooming out, the input is no longer in line with the text. How to make sure that the div widens if necessary with min-width? Now if I replace: ``` width: 350px; ``` with ``` min-width: 350px; ``` the width becomes 100%. How to fix it?
2013/07/13
[ "https://Stackoverflow.com/questions/17633614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2579059/" ]
`:=` is used in a *short variable declaration*; it both declares the variables on the left-hand-side, and assigns to them. (This is explained in [the "Short variable declarations" section of *The Go Programming Language Specification*](http://golang.org/ref/spec#Short_variable_declarations).) `=`, by contrast, merely performs assignments. In your example, the second line uses `=` because the variables have already been declared (by the first line), so `:=` is not needed. (In fact, it will give an error message: `:=` is only allowed when at least one of the variables is "new", i.e., not already declared.)
`:=` is for convenience. The important difference is that the `:=` does type inference, so as it declares and assigns the variable all one line, the variables type is inferred from the return value's type of the function. This makes your program easier to read in most cases but does mean someone will have to look up in the docs the function's return value type to figure out the variable's type. You'll want to use `=` when you're re-assiging to an existing variable or when assigning to a global/package variable from within a function, otherwise, you'll be creating a new local variable.
165,146
I recently became enamored with the excellent app in Ubuntu GNU screen. I was really happy to see it installed on my Mac as well, but I can't split vertically... I guess I need to update it somehow. I tried mac ports, and brew, but I couldn't find anything. Has anyone done this successfully?
2010/07/19
[ "https://superuser.com/questions/165146", "https://superuser.com", "https://superuser.com/users/43256/" ]
Patch by Evan Meagher: <http://old.evanmeagher.net/2010/12/patching-screen-with-vertical-split-in-os> Using these instructions and patch to compile screen I now have screen with vertical splitting capability in Mac OS X
AFAIK you need at least screen-4.01. You can get it from their git repositories over at [gnus's savannah](http://savannah.gnu.org/git/?group=screen). One of the newer dowloads [here](http://ftp.gnu.org/gnu/screen/) might also work, but I haven't tried.
63,117
I have two very right-skewed datasets which I must study for difference in means. Given the skewness, I transformed using log 10 scale after adding 1 to be able to take the log. In other words: `xx = log10(x+1)`. `xx` is nicely normally distributed, which is good, but I have a neat spike at 0 (`x` is quite sparsed). Since the $t$-test is very robust about normality, can I apply a inference test against means anyway? I don't think I can remove the zeroes as normality since the spike is quite high (around .2 times the expected value). Have I to consider these values as outliers?
2013/07/02
[ "https://stats.stackexchange.com/questions/63117", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/27020/" ]
Let me try restating your situation. 1. You have very right skewed variables of interest, mostly positive but with marked spikes at zero, generically $x$. 2. To make the distributions easier to handle, you used the transformation log ($x + 1$). (The base of the logs, 10 or e or anything else, is immaterial here.) I would not describe #1 as lognormal or #2 as normal. What's more, your reporting that a distribution is normal, except for a spike, would widely be considered contradictory, or at least puzzling. Many distributions could be described as normal, except in so far as they are not. What to do about your "outliers" of 0 depends on the science of your problem. You must not discard them just because they are awkward for any method. Your main question can be restated as whether you have moved sufficiently closer to normality to justify use of the $t$-test. It is difficult to give precise advice, but here are some questions: 1. Why you are focusing on the means? Are there scientific reasons for being interested in the means of log ($x + 1$)? Or in the means of $x$? (Sometimes means make sense regardless of the distribution, because totals make sense.) If you are really interested in comparing the means of $x$, comparing the means of log ($x + 1$) is not the same question. 2. Sometimes people do $t$-tests as a matter of habit or ritual, but the real question is whether the distributions are the same. If that is so, a quantile-quantile plot is a better choice. 3. Much depends on your sample size. With a large sample size, normality assumptions bite less and in any case it may be that any test would yield a respectably low $P$-value. One strategy is that you could try various different tests, on the untransformed and on the transformed values. They are not asking the same question, but if they gave loosely similar $P$-values you would have some basis for reporting means to be different, regardless of how means are defined. If they give very different results, you have some hard thinking to do.
Nick Cox already gave some very good advice. I'll just make one additional comment: There is no need to guess whether or not the $t$-test is robust enough for your data. If you change the data such that the means are the same but otherwise the distribution of the variable remains unchanged, then you can just use the bootstrap to simulate. The $p$-value should follow a continuous standard uniform distribution. In the example below (using Stata), with a fairly small sample size and fairly skewed variable, the $p$-values still seem to perform OK. This is obviously no guarantee that the $t$-test will also work for your data, and that is not the intention of this example. It is there to give you some code so that you can try it out on your data to see if the $t$-test works well enough for your data. You can also use this simulation to compute a bootstrap estimate of the $p$-value and the associated Monte Carlo confidence interval. ``` . // some data preparation . sysuse auto, clear (1978 Automobile Data) . keep mpg foreign . keep if !missing(mpg,foreign) (0 observations deleted) . . tempname omean tobs . tempfile bsauto2 . . // compute the t-test on the data . ttest mpg, by(foreign) unequal Two-sample t test with unequal variances ------------------------------------------------------------------------------ Group | Obs Mean Std. Err. Std. Dev. [95% Conf. Interval] ---------+-------------------------------------------------------------------- Domestic | 52 19.82692 .657777 4.743297 18.50638 21.14747 Foreign | 22 24.77273 1.40951 6.611187 21.84149 27.70396 ---------+-------------------------------------------------------------------- combined | 74 21.2973 .6725511 5.785503 19.9569 22.63769 ---------+-------------------------------------------------------------------- diff | -4.945804 1.555438 -8.120053 -1.771556 ------------------------------------------------------------------------------ diff = mean(Domestic) - mean(Foreign) t = -3.1797 Ho: diff = 0 Satterthwaite's degrees of freedom = 30.5463 Ha: diff < 0 Ha: diff != 0 Ha: diff > 0 Pr(T < t) = 0.0017 Pr(|T| > |t|) = 0.0034 Pr(T > t) = 0.9983 . scalar `tobs' = r(t) . . // create a "population" in which H0 is true but is . // otherwise as similar as possible to the data . summarize mpg, meanonly . scalar `omean' = r(mean) . summarize mpg if foreign==0, meanonly . replace mpg = mpg - r(mean) + `omean' if foreign==0 mpg was int now float (52 real changes made) . summarize mpg if foreign==1, meanonly . replace mpg = mpg - r(mean) + `omean' if foreign==1 (22 real changes made) . . // compute the t-test on draws from the "population" . // in which H0 is true and store the results . set seed 1 . bootstrap p=r(p) t=r(t), rep(20000) strata(foreign) saving(`bsauto2') nodots: /// > ttest mpg, by(foreign) unequal Warning: Because ttest is not an estimation command or does not set e(sample), bootstrap has no way to determine which observations are used in calculating the statistics and so assumes that all observations are used. This means that no observations will be excluded from the resampling because of missing values or other reasons. If the assumption is not true, press Break, save the data, and drop the observations that are to be excluded. Be sure that the dataset in memory contains only the relevant data. Bootstrap results Number of strata = 2 Number of obs = 74 Replications = 20000 command: ttest mpg, by(foreign) unequal p: r(p) t: r(t) ------------------------------------------------------------------------------ | Observed Bootstrap Normal-based | Coef. Std. Err. z P>|z| [95% Conf. Interval] -------------+---------------------------------------------------------------- p | .9999999 .2887153 3.46 0.001 .4341284 1.565871 t | 1.75e-07 1.03631 0.00 1.000 -2.031129 2.03113 ------------------------------------------------------------------------------ . . use `bsauto2', clear (bootstrap: ttest) . . // compute the bootstrap estimate of the p-value . qui count if abs(t) >= abs(`tobs') . di as txt "bootstrap estimate of the p-value: " /// > as result %6.4f (r(N) + 1) / (_N + 1) bootstrap estimate of the p-value: 0.0041 . . // there is randomness involved in the way I computed . // the p-value, so I would like to see a confidence interval . local a = r(N) + 1 . local b = _N + 1 - r(N) . . di as txt "95% MC CI: [" /// > as result %6.4f invibeta(`a', `b', .025) as txt ", " /// > as result %6.4f invibetatail(`a', `b', .025) as txt "]" 95% MC CI: [0.0033, 0.0050] . . // see if the p-value behave as they should . simpplot p, overall reps(20000) ``` ![enter image description here](https://i.stack.imgur.com/5OKQd.png)
24,043,706
I have this menu, that (when you hover over an icon) makes the icon bigger. What I tried to achieve is, to have it display correctly from both sizes, which doesn't quite work. It only works from the left side, because of the unordered list, but is there a way to make it work from both sides? (basically so the icon covers the one to the right and the one to the left without pushing it). I have this: HTML: ``` <!-- START OF THE MENU !--> <div class="menu-outer" style="font-family: 'Open Sans', sans-serif;;"> <div class="menu-icon"> <div class="bar"></div> <div class="bar"></div> <div class="bar"></div> </div> <nav> <ul class="menu"> <center> <a href="goolag_games.html"><img class="icon" src="games.png"></a> <a href="index.html"><img class="icon" src="home.png"></a> <a href="contact.html"><img class="icon" src="contact.png"></a> <a href="wai.html"><img class="icon" src="wai.png"></a> <a href="wita.html"><img class="icon" src="wita.png"></a> </center> </ul> </nav> </div> <a class="menu-close" onClick="return true"> <div class="menu-icon"> <div class="bar"></div> <div class="bar"></div> </div> </a> <!-- END OF THE MENU!--> ``` CSS: ``` .icon{ display: inline-block; margin-right: -5; } .icon:hover{ width: 155px; margin: -15px -22px -15px -13px; } .menu{ z-index: 10; } ``` Thanks for all the help. If anything, it's all uploaded here (in the right corner menu): <http://goolag.pw/delete2.html>
2014/06/04
[ "https://Stackoverflow.com/questions/24043706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495013/" ]
Add the following to your CSS: ``` .icon{ position: relative; z-index: 10; } .icon:hover{ z-index: 100; } ``` By increasing the `z-index`, the hovered icon is moved up in the DOM-layer, and displayed above the other icons.
You may want to set all the images' `z-index` property to a negative value and when the image hovers, set it to a positive one. I don't know if this is a bug but that's how it behaves, take a look at [this fiddle](http://jsfiddle.net/4BWHs/): ``` #one { width: 100px; height: 40px; background: red; z-index: 10; } #two { width: 100px; height: 40px; background: blue; position: relative; top: -20px; left: 20px; z-index: -1; } ``` If you set the first element's `z-index` to a `>0` value, it won't show over the second one until it's `z-index` is set to something `<0`.
7,451,144
So I know that google places API serves the place information (name, location, website, type ect) with JSON but I was wondering how to grab the data from the JSON? Basically I've got a site where users can use the google maps API Ive set up to search for their retail shops and Id like to store all that information in a table so that way when you go to the user's profile page you can see their google place information on a integrated map. Maybe theres an easier way to do that but Im not sure how.
2011/09/16
[ "https://Stackoverflow.com/questions/7451144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/712486/" ]
You should only use the google places api from the client. Google has a rate limit set pretty low, and it's based on IP address (at least for the google maps api). So if you're making too many requests from your web server, all of a sudden google cuts you off for the day. The way around this is to just do all the calls in javascript, so it's coming from the users IP address. When the user types their address into your form, use the google places api to get the place id, or lat/lng coordinates, then save those along with everything else in your database. Then just use that data to fetch the place json from the google places api when they view the user profile. **Update** According to the [google places docs](https://code.google.com/apis/maps/documentation/javascript/places.html#place_details_requests), it's actually the "`reference` token" you want to store, not the `id`. Since you want users to be able to search for their stores, you need to make 2 queries: 1. First, you need to have lat/lng coordinates to be able to query the places api ([google places api docs](https://code.google.com/apis/maps/documentation/javascript/places.html). You do this by querying [google maps' geocoding api](http://code.google.com/apis/maps/documentation/geocoding/) with, say, the users current location, or some address they filled out when signing up. The response will return, among other attributes, the lat/lng coordinates. Save those to your database tied to the user model. I've done this with [Geocoder](https://github.com/alexreisner/geocoder), but because of google's rate limiting, you quickly run into problems. Keep all the geocoding stuff client side, then save the results with ajax or whatever. 2. Then, on the page where the user searches for their retail stores, you just query the places api with their lat/lng coordinates: [google places api search request example](http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_requests). You'll get a list of results. For each place the user selects, you save the `reference` token. 3. Then when you want to retrieve the details for that place, you make a [google places api 'place details' request](http://code.google.com/apis/maps/documentation/javascript/places.html#place_details_requests) using the reference token.
I thought of doing the same with Geocoder, i think it's worth looking at.http://railscasts.com/episodes/273-geocoder?view=comments
52,967,111
I'm currently trying to use the pg\_trgm operations `%` and `<->`. The GIN Indices on the columns are already available, but I can't find the sqlalchemy equivalent to the previously mentioned operators. What would be the best approach to solve this problem, except writing a pure text query. A simple example query would be: ``` tag = test tag_subq = session.query(sticker_tag.file_id, f'sticker_tag.name <-> {tag}'.label(distance)) \ .filter(f'sticker_tag.name % {tag}')) \ .filter('distance' < 0.3) \ .subquery("tag_subq") ``` The query above is obviously not working, and the select and filter string are just placeholder to visualize what I intend to do.
2018/10/24
[ "https://Stackoverflow.com/questions/52967111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464807/" ]
For people who are using Postgres, it's possible to use `similarity` to do so instead. NOTE: Do remember to install the `pg_trgm` extension in your Postgres first: `CREATE EXTENSION pg_trgm;` Here's an example in using SQLAlchemy: ```py # ... other imports from sqlalchemy import and_, func, or_ def search_store_product(search_string: str) -> Optional[list[Product]]: try: return session.query(Product).filter( or_( func.similarity(Product.name, search_string) > 0.6, func.similarity(Product.brand, search_string) > 0.4, ), and_(Product.updated_on >= datetime.utcnow() - timedelta(days=5)), ).order_by(Product.created_on).limit(20).all() except ProgrammingError as exception: logger.exception(exception) raise finally: session.close() ```
If anyone is interested, I did some tests comparing the `%` method and the `similarity(...) > x` method and there is a significant speed up using `%`. Over 10x in some cases. ``` SELECT * FROM X WHERE name % 'foo'; ``` is way faster than ``` SELECT name FROM x WHERE similarity(name, 'foo') > 0.7; ``` So I recommend only using the `similarity(..)` function in the `SELECT` statement if it's relevant to your query. Like this: ``` SELECT name, similarity(name, 'foo') FROM X WHERE name % 'foo'; ``` But you need to set `pg_trgm.similarity_threshold` before using `%` because the default is 0.3 which in my opinion is way too fuzzy and slow for most applications. So r-m-n's answer is preferable, **just remember** to set `similarity_threshold` every session! **In SQL Alchemy that'll be something like this**: ``` db.session.execute('SET pg_trgm.similarity_threshold = 0.7;') items = Model.query.filter(Model.name.op("%")(name)).all() ```
16,966,714
I have an xml file which I'm trying to minimise using a bash script. After removing any indentation, some part of the file looks like this: ``` <layer name ="dotted_line" align ="topleft" edge ="topleft" handcursor ="false" keep ="true" url ="%SWFPATH%/include/info_btn/dotted_line.png" zorder ="15" /> ``` I'd like to remove any empty spaces before and after the equal sign, so it'd look like: ``` <layer name="dotted_line" align="topleft" edge="topleft" handcursor="false" keep="true" url="%SWFPATH%/include/info_btn/dotted_line.png" zorder="15" /> ``` Any ideas how can achieve this? Thanks
2013/06/06
[ "https://Stackoverflow.com/questions/16966714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187707/" ]
`sed -i s/\ *=\ */=/g filename` Regards
You should first try to see if xmllint --format isn't already doing everything you need: ``` xmllint --format OLDFILE.xml > NEWFILE.xml ``` The big advantage of this approach: * it will strip down every "cosmetic" things (extra spaces, etc). Ie it will not only replace `name = value` with `name=value` but will get rid of many other extra spaces, and indent "neatly" and tersely. * it knows XML, and therefore is much safer to use than any thing based on regular expressions (you CAN'T parse every xml files with regular expressions! It will work for basic xml structures, but is far from encomassing every thing an XML file can contain) another way, if you are SURE that the name ="value" are each alone on their own line: ``` export _tab_="$(printf '\011')" sed -e "s/^[ ${_tab_}]*[a-zA-Z0-9_-]\([a-zA-Z0-9_-]*\)[ ${_tab_}][ ${_tab_}]*=[ ${_tab_}][ ${_tab_}]*/\1=/" OLDFILE.xml > NEWFILE.xml ```
90,425
someone formulated this argument: 1. Iff there's space, then God is omnipresent. 2. Iff there's universe, then there's space. 3. There was a state of affairs when there's no universe (There was a state of affairs in which God existed with no universe. [Creatio ex nihilo]), 4. There was a state of affairs when there's no space (There was a state of affairs in which God existed with no space.). [From 2,3] 5. There was a state of affairs in which God wasn't omnipresent. [From 1,4] 6. But God is omnipresent. 7. If there was a state of affairs in which God wasn't omnipresent and now God is omnipresent, then God changes. 8. Therefore God changes. [From 5,6,7] 9. If God changes, then God is neither immutable nor timeless. 10. God is neither immutable nor timeless [From 8,9] What do you think about this argument against classical theism? I think the three O's of the conception of the Abrahamic god is a weak one. The three O's being omnipotent, omniscient, and omnibenevolent. I think the best way to challenge classical theism is to go beyond classical theism. Any descriptor on God is necessarily limiting for a supposedly limitless being. I think this was by design of the church, more the Christian faith that came out of judaism than judaism itself. You see developments in Christianity like dualism which are rejected in the Hebrew Bible (see Isaiah 45:7). Psalms 139:7-8 doesn't necessarily mean that God is only present in if all spaces but in places where there is no space. I believe the initial conception of YHWH is that the LORD is infinite. "I am what I am," "YHWH" and "I am" in Exodus 13-15 suggests that the ancient Hebrews saw God as a constant. I think these aforementioned limiting O's necessitate God's limited presence and being but this isn't what God was initially conceived as. The spacial-temporal realm would be fine to define the universe as but I don't think that discounts something beyond the universe that perhaps we can't conceive as humans, but God exists there too. I suppose I'm taking the panentheist route of challenging the same thing you're challenging because I feel it's easier to argue using the language and ideas the ancient Hebrews used to challenge the Christian conception of God which has its foundations on that same language and those same concepts.
2022/04/07
[ "https://philosophy.stackexchange.com/questions/90425", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/56931/" ]
What does 'omnipresent' mean? If you mean, "X is everywhere in space", that can be restated as "for every (piece of) space S, X is in S". Then when there is no space, (i.e. "space" is "empty"...), the universal quantifier is fulfilled, and X *is* omnipresent. For any X, in fact.
Imagine the following: a computer programmer creates a simulated universe, within which self-aware programs live. They might think, if there is RAM (computer memory, or however they name it, maybe they call it "space", because they have no conception about what the computer really is), then their creator is omnipresent inside it. But there was a state of affairs when there wasn't any RAM, so it means the creator couldn't have been omnipresent in their world. How could they understand, that although their creator is omnipresent in their world (the programmer could pause the processor at any moment and modify anything anywhere), so is inside their world, but exists at the same time outside of it too?
53,622,292
I need to display HTML code to all user roles except "subscriber" in wordpress. Here is code that I can't get working. ``` <?php $current_user = wp_get_current_user(); ?> <?php if ( $current_user->role == 'subscriber' ) : ?> <span>here is my html</span> <?php endif; ?> ``` PS I'm not that good with php as you can tell.
2018/12/04
[ "https://Stackoverflow.com/questions/53622292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3915892/" ]
Try a package called pandas-dedupe. Uses fuzzy matching and machine learning. <https://pypi.org/project/pandas-dedupe/> I know your question is very old, but the above package may still be of assistance. Did you find a solution in the end?
I agree with @SCool. pandas-dedupe is a very good library that can do exactly this. Here is an example: ``` import pandas as pd import pandas_dedupe df = pd.DataFrame({'name': ['Franc', 'Frank', 'John', 'Michelle', 'Charlotte', 'Carlotte', 'Jonh', 'Filipp', 'Charles', 'Diana', 'Robert', 'Carles', 'Michele']}) dd = pandas_dedupe.dedupe_dataframe( df, field_properties = ['name'], canonicalize=True ) ``` pandas-dedupe will ask to label some examples as distinct or duplicates. Once done, it will take care of deduplication by returning the old name, canonicalised name as well as the confidence in the results. I know that the question is old, but I hope that an example can help people find a solution to their problem quicker.
9,294
I have a Nikon D7000 and I see there are a couple remote release options from Nikon: the (wired) MC-DC2 and the (wireless) ML-L3 which is also about 40% cheaper than the wired remote. Are there any good reasons one would choose the wired remote instead of the wireless, especially given the price difference?
2011/02/28
[ "https://photo.stackexchange.com/questions/9294", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/89/" ]
Infrared triggers can lose their minds when in the presence of sunlight or a strong IR source. The sun puts out *SO* much IR the receiver can't see the signal unless its window is in shade or very close to the transmitter. They do work really well indoors or at night though, and cost less than the radio triggers. And, just as a FYI, a toilet-paper tube taped over the window can help the receiver pick up the transmitter's IR burst when there is a lot of IR noise as it helps the receiver's "eye" see the right IR source. For that matter though, even PocketWizards can get confused when in the presence of lots of radio noise or certain transmitters. I had a shoot where I had receivers on both sides of me lock-up multiple times. I'd used them in the same location several times before with no problems, and the only difference was the announcer was using a wireless microphone. I'd have loved to have wired up sync lines and turned off the wireless that night.
I have a wireless RF remote for my camera and now that I have wireless I would not do wired. The main reason is that there is less chance of tripping over the cable or having to worry about being tangled in it. Or if you are doing pictures with you in them you do not have to worry about hiding the cable. Having said that I would recommend RF (radio frequency) over infrared. The biggest reason is that you do not need to have line of sight to the camera using RF. In addition from previous experience not everything IR works outdoors in the sunlight. I use a Phottix Plato <http://www.phottix.com/en/wireless-remotes/phottix-plato.html> as my wireless remote. It has worked very well for me. I will be the first to admit that I do not have much experience with photographic releases but it has met all of my needs and is a lower price than some of the manufacturer's units.
43,309,869
I want to convert a string to time using the parse method which is going to be inserted to database later. But I get: Incompatible Types: Java.util.date cannot be converted to Java.sql.Date. Any Solution? ``` String s = time.getText(); DateFormat sdf = new SimpleDateFormat("hh:mm:ss"); Date d = sdf.parse(s); ```
2017/04/09
[ "https://Stackoverflow.com/questions/43309869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7549737/" ]
You can use `Array.map` to transform your objects based on whether their `code` is in the `obj2` array: ```js var obj1 = [ { "code": "in_today", "text": "Today" }, { "code": "in_week", "text": "This week" }, { "code": "in_month", "text": "This month" }, { "code": "normal", "text": "Other" } ] var obj2 = ["in_today", "in_week", "normal"] var newObject = obj1.map(function(obj) { if (obj2.indexOf(obj.code) > -1) { obj.selected = true; } else { obj.selected = false; } return obj; }) console.log(newObject) ``` Or a bit simpler if ES6 is available: ``` const newObject = obj1.map((obj) => { obj.selected = obj2.includes(obj.code); return obj; }) ```
You'll want to do something like this: ``` for (var i = 0; i < obj1.length; ++i) { if (obj2.indexOf(obj1[i].code) == -1) { obj1[i].selected = false; } else { obj1[i].selected = true; } } ``` Essentially, you just loop over obj1, then check if the value of `obj1.code` is present in obj2, then set `selected` accordingly.
2,529,490
I'm trying to get the result of a COUNT as a column in my view. Please see the below query for a demo of the kind of thing I want (this is just for demo purposes) ``` SELECT ProductID, Name, Description, Price, (SELECT COUNT(*) FROM ord WHERE ord.ProductID = prod.ProductID) AS TotalNumberOfOrders FROM tblProducts prod LEFT JOIN tblOrders ord ON prod.ProductID = ord.ProductID ``` This obviously isn't working... but I was wondering what the correct way of doing this would be? I am using SQL Server
2010/03/27
[ "https://Stackoverflow.com/questions/2529490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131809/" ]
If you are only interested in the products that have been ordered, you could simply substitute the LEFT OUTER JOIN operation with an INNER JOIN: ``` SELECT prod.ProductID, prod.Name, prod.Description, prod. Price, COUNT(*) AS TotalNumberOfOrders FROM tblProducts prod INNER JOIN tblOrders ord ON prod.ProductID = ord.ProductID ```
This will work: ``` SELECT ProductID, Name, Description, Price, COUNT(ord.ProductId) AS TotalNumberOfOrders FROM tblProducts prod LEFT JOIN tblOrders ord ON prod.ProductID = ord.ProductID GROUP BY ProductID, Name, Description, Price ``` The "COUNT(ord.ProductId)" clause ensures that if no orders are found, TotalNumberOfOrders will be equal to zero. [Later edit: I forgot the GROUP BY clause. Doh!]
111,838
Assume someone received some service (for example, had his hair cut) and had made the payment using his credit card. What if this transaction was declined later? Does he still owe the money that he was supposed to pay? From the shop's point of view, how can the shop charge this customer then, after he has left?
2019/07/25
[ "https://money.stackexchange.com/questions/111838", "https://money.stackexchange.com", "https://money.stackexchange.com/users/88476/" ]
If the service was provided, you must pay for it. A declined credit card is like a bounced check in this regard: the service provider is still owed payment. From the shop's point of view, they are probably out of luck. The amount is likely too small to bother to pursue in small claims court, and their only recourse is to dispute the chargeback with the credit card company. I'm not sure if you represent the shop or the customer, but the right thing to do (regardless of jurisdiction and law) is to pay for the haircut! If you're the shop owner, I'd recommend figuring out how the charge was declined after the fact and look for ways to avoid similar situations in the future. If you're the customer, please realize that you need to pay and make it right. Just because you can get away with something doesn't mean you should.
The purpose of running the card through the reader is to get authorization from the network. If the transaction is later denied, then that is a dispute that the business owner has to make with the network. This has to be a very rare situation, or the business owner would never accept a credit card/debit card. The fee that is charged by the network is to cover the risk that the network has in addition to their costs. A few years ago in the US as we were changing to using cards with chips, the carrot that the networks used was how the risk of a fraudulent transaction would be assigned if the store didn't install the new readers. No new reader meant that if there was some kinds of fraud, then the store would cover the loss. But if they installed the new readers, then the network covered the risk. For some businesses they can contact the individual because they have more information about the customer, but in some cases the transaction is essentially anonymous. In those cases the only info they have is related to the info on the card that was ultimately denied. Ultimately the customer is responsible, so the denied transaction doesn't absolve them of the debt.
35,775,564
Currently I have set up my storyboard that is optimised for landscape mode. At first I figured I would only allow landscape orientation. However along the way I decided it would be better to allow both options. What I've done now is created a new storyboard that holds the layout for the portrait orientation. I did it this way because the views will be completely set up differently. Is there a way to switch between storyboards during runtime based on orientation or is what I'm doing really bad practice and would it be advised to go a different direction. I figured using xib files would cause duplicated code, I might be completely wrong so. I would love to know if it's possible to switch storyboards based on orientation and if so how to achieve this. And if this would be good practice at all. The way I've set it up now the storyboards both use the same view controllers so they all use the same methods/outlets ***Edit based on Haroldo Gondim's awnser*** I put this in my `didFinishLaunchingWithOptions` in the AppDelegate. ``` NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil) ``` then I have this function in the app delegate class as well ``` func rotated(){ if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) { storyboard = UIStoryboard.init(name: "Main", bundle: nil) } if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) { storyboard = UIStoryboard.init(name: "portrait", bundle: nil) } //self.window?.rootViewController = storyboard?.instantiateInitialViewController() storyboard?.instantiateViewControllerWithIdentifier("ViewController") //self.window?.makeKeyAndVisible() } ``` I also tried this with `instantiateInitialViewController` but whatever I try it won't change the storyboard. It does go into the if statement the way it should
2016/03/03
[ "https://Stackoverflow.com/questions/35775564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025852/" ]
The built-in size classes allows you to build completely different UI on the same storyboard. The runtime will select the appropriate scene / controls for the current device/orientation (size class) and will layout automatically (leveraging AutoLayout). Review the size classes feature in your local Xcode help as it is quite easy to use. Essentially, Layout entire scene in all sizes and then change size class (to reference new orientation) before laying out new scene (with all new UI if you like)... Link up the new UI and you're done. *Q: Wouldn't you get a lot of code copy?* Response -------- > > If you are rearranging UI elements using size classes, then you do > **not** use multiple VCs. If you are creating new UI elements then you would need to add IBOutlets and view manipulation code like any new > control one would normally add to an existing ViewController. Using > auto layout and size classes one can rearrange existing views without > any code adjustments at all. The layout changes are hidden inside of > the Storyboard file as xml. If you right-click on a storyboard file > you can open as source code and see that. To revert right-click and > open as interface builder. > > >
`Autolayout` can allow you to rearrange the view for different orientation. For different functionalitys and elements, you should use `Size Class`, Follow the tutorial @Blakusl linked, is very good.
4,200,025
Let $h$ be a continuous function on $\mathbb{R}$ such that $h(x) = o(|x|^{-\alpha})$ at $\infty$ for some $\alpha > 1$. Let also $(b\_k)\_{k\in\mathbb{Z}}$ an increasing sequence such that, $$\lim\_{k\to\infty} b\_k - b\_{k-1} > 0.$$ I consider the function $f$ on $\mathbb{R}$ defined as, $$\forall~ u\in\mathbb{R}, ~f(u) = \sum\_{k=0}^{+\infty} h(u - b\_k).$$ For any $u\in\mathbb{R}$ it is clear that $f(u) < \infty$. But how to prove that $f$ is bounded? Put differently, $\displaystyle \lim\_{u\to\infty} f(u) < \infty$? For example, the proof is straightforward if $(b\_k)$ is an arithmetic sequence: $b\_k = a\_0k$, where $a\_0 > 0$. One can prove that $f$ is modulo $a\_0$: $f(u + a\_0) = f(u).$ This implies that $f$ is necessarily bounded.
2021/07/16
[ "https://math.stackexchange.com/questions/4200025", "https://math.stackexchange.com", "https://math.stackexchange.com/users/473729/" ]
Without loss of generality, I redefine $f$ as, $$f(u) = \sum\_{r=0}^{\infty}h(u-a\_r),$$ where $(a\_r)\_r$ is positive on $\mathbb{N}$. I will prove that $f$ is bounded (this proof can be generalized when $f$ is defined as in initial post). $h(x) =o\left(|x|^{-\alpha}\right) \implies h(x) =o\left((|x|+1)^{-\alpha}\right) \implies |h(x)| =o\left((|x|+1)^{-\alpha}\right)$. Thus, $\exists~x\_0\in\mathbb{R}\_+~/~\forall~x<-x\_0 \text{ or } x>x\_0,~|h(x)| < \left(|x| + 1\right)^{-\alpha} $. In addition, $\exists~M\geq1~/~\forall ~x\in\mathbb{R},~|h(x)| \leq M\left(|x| + 1\right)^{-\alpha} $. For example, one can choose any $\displaystyle M \geq \max\left\{1, \left(\max\_{x\in[-x\_0,x\_0]}h(x)\right)\left(|x\_0| + 1\right)^{\alpha}\right\}$. It follows that, $\forall ~u\in\mathbb{R}$, $r\in\mathbb{N}$, \begin{equation}|h(u-a\_r)| \leq M\left(|u-a\_r|+1\right)^{-\alpha}. \end{equation} Let $f^\*$ be the real-valued function defined as $\displaystyle f^\*(u) = \sum\_{r = 0}^{\infty} \left(|u-a\_r|+1\right)^{-\alpha}, ~\forall ~u\in\mathbb{R}$. $\displaystyle \lim\_{r\to\infty} a\_{r+1} - a\_{r} > 0 \implies \exists~r\_u \in \mathbb{N} \text{ and } a > 0$ such that $\forall~r\geq r\_u$, $a\_{r+1}-a\_r \geq a$. As $(a\_r)\_r$ grows to $\infty$, $\forall~u\in\mathbb{R}$, it is possible to choose $r\_u$ sufficiently large such that $a\_{r\_u} > u$. It follows that, $\forall~r\geq r\_u$, \begin{align\*} &a\_r \geq (r-r\_u)a + a\_{r\_u},\\ &|u-a\_r| = a\_r-u+1 \geq (r-r\_u)a + a\_{r\_u} - u \geq 0, \\ &\left(|u-a\_r| + 1\right)^{-\alpha} \leq \left((r-r\_u)a + a\_{r\_u} - u\right)^{-\alpha}. \end{align\*} Therefore, $\displaystyle f^\*(u) < \infty$, for any $u\in\mathbb{R}$. To prove that $f$ is bounded, it is sufficient to prove that $f^\*$ is also bounded. As $f^\*$ is a continuous function, it is also sufficient to prove that $\displaystyle \lim\_{u\to -\infty} f^\*(u) < \infty$ and $\displaystyle \lim\_{u\to +\infty} f^\*(u) < \infty$. If $\displaystyle u\leq0$, then $\left(|u-a\_r|+1\right)^{-\alpha} = \left(a\_r - u +1\right)^{-\alpha} \leq \left(a\_r +1\right)^{-\alpha}.$ Thus $\forall ~u\leq 0, ~f^\*(u) \leq f^\*(0)$. As $f^\*$ is a positive function, then $\displaystyle \lim\_{u\to -\infty} f^\*(u) < \infty$. Let $k\_0\in\mathbb{N}^\*$ such that $\forall~r\geq k\_0$, $a\_{r+1}-a\_r \geq a$, for some $a > 0$. For $u$ sufficiently large, $\exists ~k\_u\in\mathbb{N}$, where $k\_u > k\_0$ and $\forall~r \leq k\_u - 1$, $u > a\_r$, and $\forall~r \geq k\_u$, $u \leq a\_r$. For $u$ sufficiently large $f^\*(u)$ can be decomposed as, \begin{align\*} f^\*(u) &= \sum\_{r = 0}^{k\_0 - 1}\left(|u-a\_r|+1\right)^{-\alpha} + \sum\_{r = k\_0}^{k\_u - 1}\left(|u-a\_r|+1\right)^{-\alpha} + \sum\_{r = k\_u}^{\infty}\left(|u-a\_r|+1\right)^{-\alpha}\\ f^\*(u) &\leq k\_0 + \sum\_{r = k\_0}^{k\_u - 1}\left(u-a\_r+1\right)^{-\alpha} + \sum\_{r = k\_u}^{\infty}\left(a\_r-u+1\right)^{-\alpha}\\ f^\*(u) &\leq k\_0 + \sum\_{r = k\_0}^{k\_u - 1}\left(a\_{k\_u - 1}-a\_r+1\right)^{-\alpha} + \sum\_{r = k\_u}^{\infty}\left(a\_r-a\_{k\_u}+1\right)^{-\alpha} \end{align\*} If $k\_0 \leq r \leq k\_u -1$, then $a\_{k\_u - 1} - a\_r \geq a(k\_u - 1 - r)$, because $a\_{r+1}-a\_r \geq a$. Thus, $(a\_{k\_u - 1} - a\_r + 1)^{-\alpha} \leq \left(a(k\_u - 1 - r) + 1\right)^{-\alpha}.$ Analogously, if $k\_u \leq r$, then $a\_{r} - a\_{k\_u} \geq a(r - k\_u)$. Thus, $(a\_{r} - a\_{k\_u} + 1)^{-\alpha} \leq \left(a(r - k\_u) + 1\right)^{-\alpha}.$ For $u$ sufficiently large, \begin{align\*} f^\*(u) &\leq k\_0 + \sum\_{r = k\_0}^{k\_u - 1}\left(a(k\_u - 1 - r) + 1\right)^{-\alpha} + \sum\_{r = k\_u}^{\infty}\left(a(r - k\_u) + 1\right)^{-\alpha}\\ f^\*(u) &\leq k\_0 + \sum\_{r = 0}^{k\_u - k\_0 - 1}\left(ar + 1\right)^{-\alpha} + \sum\_{r = 0}^{\infty}\left(ar + 1\right)^{-\alpha}\\ f^\*(u) &\leq k\_0 + 2\sum\_{r = 0}^{\infty}\left(ar + 1\right)^{-\alpha} \end{align\*} The quantity $\displaystyle k\_0 + 2\sum\_{r = 0}^{\infty}\left(ar + 1\right)^{-\alpha}$ does not depend on $u$ and is finite. Hence, $\displaystyle \lim\_{u\to +\infty} f^\*(u) < \infty$. As a result $f$ is bounded.
Your way to use periodicity to prove boundedness is smart, but I couldn't generalize. My idea is to bound the series by the improper integral $\int\_{-\infty}^{+\infty}|h(\alpha x)|dx$. Let $\alpha:=\liminf\_{k\to \infty} b\_k-b\_{k-1} $ be $>0$. Suppose for one moment that we have $b\_k-b\_{k-1} \ge \alpha$ for all $k\in \mathbb{Z}$, then I claim: $$\sum\_{k=1}^\infty |h(u-b\_k)|\le\int\_{-\infty}^{+\infty}|h(\alpha x)|dx$$ so you can bound $f$ by $2\int\_{-\infty}^{+\infty}|h(\alpha x)|dx+M$ where $M:=\sup h$. If $b\_k-b\_{k-1} \ge \alpha$ is true only for $k\ge k\_0$ then you can bound the first terms by $M\cdot k\_0$ and repeat the previous step.
63,446,295
Given a string in C++ containing ranges and single numbers of the kind: ``` "2,3,4,7-9" ``` I want to parse it into a vector of the form: ``` 2,3,4,7,8,9 ``` If the numbers are separated by a `-` then I want to push all of the numbers in the range. Otherwise I want to push a single number. I tried using this piece of code: ```cpp const char *NumX = "2,3,4-7"; std::vector<int> inputs; std::istringstream in( NumX ); std::copy( std::istream_iterator<int>( in ), std::istream_iterator<int>(), std::back_inserter( inputs ) ); ``` The problem was that it did not work for the ranges. It only took the numbers in the string, not all of the numbers in the range.
2020/08/17
[ "https://Stackoverflow.com/questions/63446295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7179370/" ]
Your problem consists of two separate problems: 1. splitting the string into multiple strings at `,` 2. adding either numbers or ranges of numbers to a vector when parsing each string If you first split the whole string at a comma, you won't have to worry about splitting it at a hyphen at the same time. This is what you would call a *Divide-and-Conquer* approach. ### Splitting at `,` [This question](https://stackoverflow.com/questions/5607589/right-way-to-split-an-stdstring-into-a-vectorstring) should tell you how you can split the string at a comma. ### Parsing and Adding to `std::vector<int>` Once you have the split the string at a comma, you just need to turn ranges into individual numbers by calling this function for each string: ```cpp #include <vector> #include <string> void push_range_or_number(const std::string &str, std::vector<int> &out) { size_t hyphen_index; // stoi will store the index of the first non-digit in hyphen_index. int first = std::stoi(str, &hyphen_index); out.push_back(first); // If the hyphen_index is the equal to the length of the string, // there is no other number. // Otherwise, we parse the second number here: if (hyphen_index != str.size()) { int second = std::stoi(str.substr(hyphen_index + 1), &hyphen_index); for (int i = first + 1; i <= second; ++i) { out.push_back(i); } } } ``` Note that splitting at a hyphen is much simpler because we know there can be at most one hyphen in the string. [`std::string::substr`](https://en.cppreference.com/w/cpp/string/basic_string/substr) is the easiest way of doing it in this case. Be aware that [`std::stoi`](https://en.cppreference.com/w/cpp/string/basic_string/stol) can throw an exception if the integer is too large to fit into an `int`.
All very nice solutions so far. Using modern C++ and regex, you can do an all-in-one solution with only very few lines of code. How? First, we define a regex that either matches an integer OR an integer range. It will look like this ``` ((\d+)-(\d+))|(\d+) ``` Really very simple. First the range. So, some digits, followed by a hyphen and some more digits. Then the plain integer: Some digits. All digits are put in groups. (braces). The hyphen is not in a matching group. This is all so easy that no further explanation is needed. Then we call `std::regex_search` in a loop, until all matches are found. For each match, we check, if there are sub-matches, meaning a range. If we have sub-matches, a range, then we add the values between the sub-matches (inclusive) to the resulting `std::vector`. If we have just a plain integer, then we add only this value. All this gives a very simple and easy to understand program: ``` #include <iostream> #include <string> #include <vector> #include <regex> const std::string test{ "2,3,4,7-9" }; const std::regex re{ R"(((\d+)-(\d+))|(\d+))" }; std::smatch sm{}; int main() { // Here we will store the resulting data std::vector<int> data{}; // Search all occureences of integers OR ranges for (std::string s{ test }; std::regex_search(s, sm, re); s = sm.suffix()) { // We found something. Was it a range? if (sm[1].str().length()) // Yes, range, add all values within to the vector for (int i{ std::stoi(sm[2]) }; i <= std::stoi(sm[3]); ++i) data.push_back(i); else // No, no range, just a plain integer value. Add it to the vector data.push_back(std::stoi(sm[0])); } // Show result for (const int i : data) std::cout << i << '\n'; return 0; } ``` If you should have more questions, I am happy to answer. --- Language: C++ 17 Compiled and tested with MS Visual Studio 19 Community Edition
41,330,736
My 4 fragments in **ViewPager** have one common button from parent activity that opens a dialog and should refresh **ListViews** in these 4 fragments. I tried using static adapters but that didn't work. Now I'm trying to use broadcast but still I won't see my adapter from outer **broadcast receiver**. Please help.
2016/12/26
[ "https://Stackoverflow.com/questions/41330736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5857576/" ]
I had same requirement i did following :- 1. Extend pagerAdapter with FragmentStatePagerAdapter 2. Implement below in your pagerAdapter class ``` @Override public int getItemPosition(Object object) { return POSITION_NONE; } ``` 3. then when ever you refresh just call - > > notifyDataSetChanged(); > > > on adapter. you can get your adapter from your viewpager as below: > > viewPager.getAdapter().notifyDataSetChanged(); > > > here viewpager is reference of my viewpager.
add your 4 lists to a map with separate key(1,2,3,4). ``` if (viewPager.getCurrentItem() == 0){ // show list items with key 1 }else if(viewPager.getCurrentItem() == 1){ //show list items with key 2 }else if(....) ``` now put a listener and call it on button click.
16,465
The line for **Queen's Indian Defence** goes like this - ``` [FEN ""] 1. d4 Nf6 2. c4 e6 3. Nf3 b6 ``` Now, the most popular choice for white in this position is **g3** preparing to fianchetto its light squared Bishop. After this, if Black wants to develop its light squared Bishop, the two choices are either **Ba6**(modern main line) or **Bb7**(old min line). Suppose Bb7 is played by Black. Now white can also fianchetto its Bishop and the play can go on. But here is my question - Given that Black plays b6, why does white go on with g3 ? Given that white's main light squares defender around the king (after white castles king side) is its Bishop on g2 which at some point in the game can be exchanged with Black's bishop on b7, isn't this line a bit more riskier? However, this line has been played at top level a very large number of times. Like yesterday in Tata steel 2017 masters, Aronian played this opening and won a wonderful game. So what is the justification behind white's fianchettoing its light squared Bishop given Black has already done that?
2017/01/26
[ "https://chess.stackexchange.com/questions/16465", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/9620/" ]
There are 3 reasons why White fianchettos the light square bishop: 1. White's plan is to play e4 to gain space. The bishop on g2 supports this 2. Building from point 1), white could play e3, Bd3 then e4, but that is an extra tempo spent to play e4 3. White has latent pressure on the queen-side, and may be able to play discovery or pinning tactics with a bishop on g2
> > Given that white's main light squares defender around the king (after white castles king side) is its Bishop on g2 which at some point in the game can be exchanged with Black's bishop on b7, isn't this line a bit more riskier? > > > If they get exchanged black will also lose his light squared bishop which could have taken advantage of the weakened light squares around the white king. For white it would be much worse to exchange the bishop on g2 for a black knight which could make that bishop on b7 very strong. In any case there is nothing wrong having such opposing bishops. Many other factors play a role here as well and the white bishop on g2 does put some pressure on the center and is not threatened to be immediately exchanged. You really need to look at the whole position not at one element only. Otherwise you could argue that any opening where you fianchetto the bishop and castle to the same side (King's Indian, Grünfeld, ....) is bad as the opponent could always fianchetto himself to oppose your bishop.
27,048,302
I am building an app in Rails 4 and am using asset pipeline. For my workflow, I've split my css into 10+ separate sheets. Should I combine them for deployment or does it not matter as long as they're minified? I'm wondering how much performance will be affected with separate stylesheets.
2014/11/20
[ "https://Stackoverflow.com/questions/27048302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3689085/" ]
Another one: ``` var times = 1; $(function(){ $("#test").on('click',function(){ console.log(times); if(times >= 3 || times == 0){ times = -1 } times += 1; }); }); ``` ### Working fiddle: <http://jsfiddle.net/robertrozas/q1ywowm1/1/>
```js var times = 0, n; $('button').on('click',function(){ n = times++; if(times > 4){ n = 0; } $(this).text(n); console.log(n); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>increment</button> ```
59,786,659
I am finishing new version of swift application and I notice that loading from core data become very slow. Same code in last version of app works great but in new it's very slow. Code is below and it's 100% same like in last version but now I must wait for cache 5-6 seconds and cache data are also same when testing old and new version! I already lost few days for this, waiting to resolve so I can publish updated app. I printed index just to see how much it take time to print about all 600 index, and in last version it's max 1 sec, in new version same code about 5-6 sec! I just find that ObjectTMP.init(... take time in newest version and it doesn't in last version. I will investigate it a little bit more Any help with this. ``` DispatchQueue.global(qos: .userInitiated).async { if #available(iOS 10.0, *) { // load //We need to create a context from this container let managedContext = self.appDelegate.persistentContainer.newBackgroundContext() //Prepare the request of type NSFetchRequest for the entity let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Cache") do { let result = try managedContext.fetch(fetchRequest) var j = 0 for data in result as! [NSManagedObject] { ... hash[String(Int(data.value(forKey: "id") as! String)] = ObjectTMP.init( ... ```
2020/01/17
[ "https://Stackoverflow.com/questions/59786659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187965/" ]
The main issue about the code you posted seems to be that you haven't put your functions in a namespace, that is required for user-defined functions; with some clean up to use type declarations (`as="sequence-type"`) and to use `xsl:sequence` to return strings and not text nodes your code becomes ``` <xsl:param name="RightPadding" select="' '"/> <xsl:param name="LeftPadding" select="' '"/> <!-- Function to left-pad (right justify) --> <xsl:function name="mf:PadLeft" as="xs:string"> <xsl:param name="string" as="xs:string"/> <xsl:param name="length" as="xs:integer"/> <xsl:variable name="leftPad" select="substring($LeftPadding,1,$length - string-length($string))"/> <xsl:sequence select="concat($leftPad, $string)"/> </xsl:function> <!-- Function to right-pad (left justify) --> <xsl:function name="mf:PadRight" as="xs:string"> <xsl:param name="string" as="xs:string"/> <xsl:param name="length" as="xs:integer"/> <xsl:sequence select="substring(concat($string,$RightPadding),1,$length)"/> </xsl:function> ``` That way at <https://xsltfiddle.liberty-development.net/jz1Q1xW> it seems to do the job.
The simplest way to pad to width 8 on the right is ``` substring(concat(X, ' '), 1, 8) ``` and on the left: ``` substring(concat(' ', X), 8 - string-length(X)) ```
724,607
[![enter image description here](https://i.stack.imgur.com/SjJSE.png)](https://i.stack.imgur.com/SjJSE.png) In Michelson Interferometer, the mirror that lies in the middle (half-silvered mirror), can reflect and let through light. But the light after being reflected by the half-silvered mirror, only let light through.(they don't show the blue line that I draw) Also, the orange line do not pass through. I want to know how the mirror works and why the reflected light only pass through the mirror.
2022/08/24
[ "https://physics.stackexchange.com/questions/724607", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/343348/" ]
If you want to avoid being lost in Newtonian mechanics, follow these steps: * Define clearly your system. In your example, you have the choice between A, B, and (A+B) * Identify all the **external** forces applied to your system. * Check if the mass of the system is constant. You cannot directly apply Newton's second law if it is not the case. * Check if your system is a rigid body. If it is not the case, you must calculate the position of its center of mass. * Apply Newton's laws:$$ \sum\_i \overrightarrow{ F\_{i} } =m. \overrightarrow{ a } \_{cm}$$ $$ \sum\_i \tau \_{i} =I \frac{d \omega }{dt} $$ Identify the unknowns: $$ \overrightarrow{a} , \omega , \overrightarrow{ F }\_{contact}$$ The contact forces like the normal force, the friction forces, etc... are never known before hand. One must eliminate them from the equations (by combination), solve for the acceleration and then calculate them once we know the acceleration. To come back to your problem: **Before the collision:** * **System: A** * External applied force: F * Newton's second law: $ a= \frac{F}{m}=3 m/s^{2}$ * **System B:** * F=0, a=0 **During the collision:** A new contact force must be taken into account. B exerts the force $ F\_{B/A}$ onto A and A exerts the force $ F\_{A/B}$ onto B. * **System: A** * External applied force: $ F\_{B/A}$, $F$ * Newton's second law: $ F-F\_{B/A}=m\_{A}.a\_{A}$ * **System: B** * External applied force: $ F\_{A/B}$ * Newton's second law: $ F\_{A/B}=m\_{B}.a\_{B}$ Newton's third law allows us to simplify a little bit the problem by eliminating one of the contact forces. $$ F\_{A/B}=-F\_{B/A}=f$$ But we still have two equations with three unknowns: $ a\_{A}, a\_{B}, f $. $$\begin{cases}F-f=m\_{A}.a\_{A}\\f=m\_{B}.a\_{B}\end{cases} $$ Let's see if we can find a new equation by considering the system A+B. * **System: A+B** * External forces: F.$ ( F\_{A/B}$ and $F\_{B/A}$ )are internal forces. * Rigid body: no. The position of the center of mass of the system is changing. It is given by:$$\begin{cases} x\_{cm}= \frac{m\_{A}x\_{A}+m\_{A}x\_{B}}{m\_{A}+m\_{B}} \\v\_{cm}= \frac{m\_{A}V\_{A}+m\_{A}V\_{B}}{m\_{A}+m\_{B}}\\a\_{cm}= \frac{m\_{A}a\_{A}+m\_{A}a\_{B}}{m\_{A}+m\_{B}}\end{cases} $$ * Newton's second law: $ F= \big(m\_{A}+m\_{B}\big) a\_{cm}$ You may think, you have enough equations to solve the problem. Unfortunately, it is not the case, the equation: $ F= \big(m\_{A}+m\_{B}\big) a\_{cm}$ is not independent of: $$\begin{cases}F-f=m\_{A}.a\_{A}\\f=m\_{B}.a\_{B}\end{cases} $$ Indeed by adding member wise, we get: $$ 0=F-f+f=m\_{A}.a\_{A}+m\_{B}.a\_{B}=\big(m\_{A}+m\_{B}\big) a\_{cm}$$ At this point, you can already answer your question. During the collision, the force applied to B is different from the force applied to A. $$F\_{/A}=F-f$$ and $$F\_{/B}=f$$ Even if the external force F is null during the collision, you cannot use the acceleration prior to the collision to calculate the force on B. $F\_{/B}=f=-m\_{A}.a\_{A}$ **where $a\_{A}$ is the acceleration during the collision (not $ a= 3 m/s^{2}$).** At last, the acceleration of B after the collision is null. As soon as the contact between A and B breaks off, the force f disappears. But can we solve the problem and calculate the motion of A and B after the collision. We still have two equations and three unknowns, so we can't. To go any further, one needs more information about the collision process. In introductory mechanics courses, one generally assumes the collision to be elastic (e=1) or inelastic with a coefficient (e<1). That is enough to calculate the velocities of A and B after the collision. But to calculate the force of interaction one further needs the duration$ \triangle t$ of the collision. The force acting onto B during the collision is then given by: $$ f \approx m\_{B}\frac{ \triangle V\_{B}}{ \triangle t} $$
If the two bodies remain in contact they have a mass of 3kg with a 3N force applied. The joint system will therefore accelerate at 1m/s^2. The block A will experience the original force of 3N and an opposite reaction force of 2N from block B. The net force is therefore 1N and it will accelerate at 1 m/s^2 Block B will experience a force of 2N from A and will therefore accelerate at 1 m/s^2
30,555,832
``` <div data-id="123">123</div> <div data-id="120" data-parent="123">120</div> <div data-id="115" data-parent="123">115</div> <div data-id="240">240</div> <div data-id="245" data-parent="240">245</div> <div data-id="246" data-parent="240">246</div> <div data-id="247" data-parent="240">247</div> <div data-id="255" data-parent="245">255</div> <div data-id="256" data-parent="245">256</div> ``` We have above a tree presented by using two attributes : 1. `data-id` 2. `data-parent` Thus, the terminology of child-parent is not got via `$().parent()` or `$().children()` However , ``` $.fn.treeChildren=function(){ return $('div[data-parent='+$(this).attr('data-id')+']'); } ``` Then : ``` $('[data-id=240]').treeChildren() // [245,246,247] ``` Issue : ------- > > this plugin retrieves only the children , not children , children of >children , ... so on. > > > How to get all **Grandchildren** where the expected result of `$('[data-id=240]').treeChildren()` is `[245,246,247,255,256]` not only `[245,246,247]` Known that the following algo didn't work : ``` $.fn.treeGrChildren=function(){ if($('div[data-parent='+$(this).attr('data-id')+']').treeChildren().length){ return $('div[data-parent='+$(this).attr('data-id')+']').treeGrChildren(); }else{ return $('div[data-parent='+$(this).attr('data-id')+']'); } } ``` [FIDDLE](http://jsfiddle.net/abdennour/xabgazk3/) =================================================
2015/05/31
[ "https://Stackoverflow.com/questions/30555832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747579/" ]
To elaborate on Omar's answer, The Android design support library introduced NavigationDrawer that is used together with DrawerLayout to provide means of implementing navigation etc. See here: [Android Design Support Library](http://android-developers.blogspot.com/2015/05/android-design-support-library.html) The NavigationDrawer extends ScrimInsetsFrameLayout which was brought into the library. The error in the question occurs because the insetForeground attribute was defined twice. Once is the context of the library and once when a copy of ScrimInsetsFrameLayout was brought into the project. Options: 1. Rename the property defined in the project (as suggested by Omar) while continuing using the local copy of ScrimInsetsFrameLayout. 2. Remove the local copy of ScrimInsetsFrameLayout and use the one in the library instead. 3. Remove the local copy of ScrimInsetsFrameLayout and use NavigationDrawer instead.
Or else you can rename **insetForeground** in your **values/attr.xml** to **insetForeground2** or something
11,363,969
Can one create an array of calendar objects? If yes, how does one do so? This code surely gives error ``` Calendar cal[length]; //loop for initialising all the objects in cal[] array ``` If no, what other way is there for getting "n" number of calendar objects? I need this for a repeating alarm, set at different times.
2012/07/06
[ "https://Stackoverflow.com/questions/11363969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965830/" ]
You can always do `Calendar[] cal = new Calendar[length];` You can use an ArrayList, too, such as: `List<Calendar> list = new ArrayList<Calendar>();` Then there's a lot of convenience methods, such as `add(Calendar calendar);` Then: You can use `for (int x = 0; x < list.size(); x++)` or `for (Calendar cal : list)` This is valid for the array, too. Inside the for you use `getCalendar()` or `new GregorianCalendar()` or whatever `Calendar` you need.
The proper syntax for creating an array in Java is: Calendar[] cal = new Calander[length]; Then you can initialze the individual elements.
141,924
Are there any methods to store spells of 9th level at a location, preferably in a manner that can be triggered in a manner similar to *glyph of warding*? Magic items could be accepted as the answer as well. It needs to be a method that doesn’t require two 9th-level spell slots; using *glyph of warding* would require you to cast *glyph of warding* at 9th level, then the other spell at 9th level as well.
2019/02/25
[ "https://rpg.stackexchange.com/questions/141924", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/49319/" ]
The [*Tome of the Stilled Tongue*](https://www.dndbeyond.com/magic-items/tome-of-the-stilled-tongue) (DMG, p. 208) allows this if you're a wizard attuned to it and use it as a spellbook. Once per day, you can cast any spell written in it as a bonus action: > > If you can attune to this item, you can use it as a spellbook and an arcane focus. In addition, while holding the tome, you can use a bonus action to cast a spell you have written in this tome, without expending a spell slot or using any verbal or somatic components. Once used, this property of the tome can't be used again until the next dawn. > > >
Timing ====== If you start casting *Glyph of Warding* one half hour before you end a long rest, [you'll use up your 9th level spell slot immediately.](https://rpg.stackexchange.com/a/141304) Then, once you finish your long rest, you'll regain the spell slot you need. Then, once you finish casting the spell, you'll inscribe the magic glyph and cast the stored spell into it with your replenished 9th level slot. 16ish hours later, you can start the process again.
1,319,057
I am trying to define an algebric type: ``` data MyType t = MyType t ``` And make it an instance of Show: ``` instance Show (MyType t) where show (MyType x) = "MyType: " ++ (show x) ``` GHC complains becasue it cannot deduce that type 't' in 'Show (MyType t)' is actually an instance of Show, which is needed for (show x). I have no idea where and how do I declare 't' to be an instance of Show?
2009/08/23
[ "https://Stackoverflow.com/questions/1319057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Add a type constraint on the type of `t`: ``` instance Show t => Show (MyType t) where show (MyType x) = "MyType: " ++ (show x) ```
You could also just: ``` data MyType t = MyType t deriving Show ``` if you want a regular show format.
25,761,405
I am developing a PHP application where I need to fetch 5 random email addresses from a CSV file and send to user. I already worked with CSV file many times but don't know how to fetch randomly in limit. ``` NOTE: CSV file have more than 200k emails. ``` Any one have a idea or suggestion then please send me.
2014/09/10
[ "https://Stackoverflow.com/questions/25761405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1498579/" ]
If CSV is too big and won't be saved in a DB -------------------------------------------- You'll have to loop through all of the rows in the CSV once to count them. You'll have to call a random-number generator function (`rand`, `mt_rand`, others...) and parametrize it to output numbers from `0` to `$count`, and call it 5 times (to get 5 numbers). You'll have to loop through all of the rows in the CSV again and only copy the necessary information for the rows whose number matches the randomly generated values. Nota bene: don't use `file_get_contents` with `str_getcsv`. Instead use `fopen` with `fgetcsv`. The first approach loads the entire file to memory which we don't want to do. The second approach only read the file line-by-line. If the CSV is too big and will be saved in a DB ----------------------------------------------- Loop through the CSV rows and insert each record into the DB. Use a select query with `LIMIT 5` and `ORDER BY RAND()`. If the CSV is small enough to fit into memory --------------------------------------------- Loop through the CSV rows and create an array holding all of them. You'll have to call a random-number generator function (`rand`, `mt_rand`, others...) and parametrize it to output numbers from `0` to array count, and call it 5 times (to get 5 numbers). Then retrieve the rows from the big array by their index number -- using the randomly generated numbers as indexes.
``` <?php $handle = fopen('test.csv', 'r'); $csv = fgetcsv($handle); function randomMail($key) { global $csv; $randomMail = $csv[$key]; return $randomMail; } $randomKey = array_rand($csv, 5); print_r(array_map('randomMail', $randomKey)); ``` This is small utility to achieve the thing you expect and change the declaration of `randomMail` function as you desired.
54,981
In Mail, when I've selected a message, I would like to have a shortcut to copy the message\_id (see [my previous question](https://apple.stackexchange.com/a/54971/769)) to the clipboard. How do I manage that? Applescript, I presume?
2012/06/28
[ "https://apple.stackexchange.com/questions/54981", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/769/" ]
That's doable as well. Paste the text below into AppleScript Editor (find it simply with Spotlight by typing "`⌘``Space` AppleScriptEditor" and hitting the enter key when it's highlighted). ``` tell application "Mail" set theSelection to selection set theMessage to first item of theSelection set theUrl to "message://<" & message id of theMessage & ">" set the clipboard to theUrl end tell ``` You can test this by pressing the run button in the editor (with a message selected in Mail). Once you're satisfied, save the script as "Copy Message URL to Clipboard" under either: > > /Users/yourusername/Library/Scripts > > > or even better > > /Library/Scripts/Mail Scripts > > > To save it to the Mail Scripts folder, first save it to your Desktop. Then open a Finder window and do `⇧``⌘``G`, type the path to the Mail Scripts Folder and hit enter to view that folder. Now drag your newly created script to that folder. While you're in the AppleScript Editor, you probably want to go ahead and enable the AppleScript Menu for the toolbar so that you can find and run the script easily. To do this, open AppleScript-> Preferences (`⌘``,`) and check the box labeled "Show Script menu in menu bar". Now you'll be able to access the script easily from > > Scripts menu -> Mail Scripts->Copy Message URL to Clipboard > > > Reference: Some of the AppleScript displayed above was snipped from a portion of [this AskDifferent answer](https://apple.stackexchange.com/questions/22103/mail-app-in-lion-is-there-a-way-to-create-tasks-from-email/22109#22109)
The correct script is: ``` tell application "Mail" set theSelection to selection set theMessage to first item of theSelection set theUrl to "message:%3C" & message id of theMessage & "%3E" set the clipboard to theUrl end tell ```
8,982,420
In a java class I have a method that sometimes takes a long time for execution. Maybe it hangs in that method flow. What I want is if the method doesn't complete in specific time, the program should exit from that method and continue with the rest of flow. Please let me know is there any way to handle this situation.
2012/01/24
[ "https://Stackoverflow.com/questions/8982420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1121031/" ]
You must use threads in order to achieve this. Threads are not harmful :) Example below run a piece of code for 10 seconds and then ends it. ``` public class Test { public static void main(String args[]) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { System.out.println("0"); method(); } }); thread.start(); long endTimeMillis = System.currentTimeMillis() + 10000; while (thread.isAlive()) { if (System.currentTimeMillis() > endTimeMillis) { System.out.println("1"); break; } try { System.out.println("2"); Thread.sleep(500); } catch (InterruptedException t) {} } } static void method() { long endTimeMillis = System.currentTimeMillis() + 10000; while (true) { // method logic System.out.println("3"); if (System.currentTimeMillis() > endTimeMillis) { // do some clean-up System.out.println("4"); return; } } } } ```
Execute the method in a different thread, you can end a thread at anytime.
41,602,452
I am working on a proof-of-concept where I have a few custom views in a TableLayout. When one of the Views is clicked I want to animate the view expanding into a new Activity. The effect I want to achieve is similar to what is seen [here](https://medium.com/@bherbst/fragment-transitions-with-shared-elements-7c7d71d31cbb#.ezalojbw4). From my research, it seems the way to do this is with [shared element Transitions](https://developer.android.com/training/material/animations.html). However, I can't get it to work correctly and I am wondering if it is because I am using my own custom View. Specifically, the fades are happening, but the scaling and translating motions are not. Check the GIF below to see where I am. In the example I click the upper left circle, which I want to transform to the full circle in the new activity. The issue can also be seen when the back button is pressed. [![enter image description here](https://i.stack.imgur.com/c42l8.gif)](https://i.stack.imgur.com/c42l8.gif) I believe it is incorrect because the View must be drawn, but is there a way to customize my View further to make this work? All of the examples I have found of this type of transition have consisted of ImageViews, Buttons, and TextViews. Below is the relevant source. My custom view is large and doesn't contain any special code, just overrides onDraw() and onMeasure(). MainActivity.java ``` package com.rscottcarson.circleschedulertest; import android.app.Activity; import android.app.ActivityOptions; import android.content.Intent; import android.support.v4.app.ActivityOptionsCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Toast; public class MainActivity extends Activity { private View view1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view1 = findViewById(R.id.circle1); view1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, DetailActivity.class); // create the transition animation - the images in the layouts // of both activities are defined with android:transitionName="profile" ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation(MainActivity.this, view1, "profile"); // start the new activity startActivity(intent, options.toBundle()); } }); } } ``` DetailActivity.java ``` package com.rscottcarson.circleschedulertest; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class DetailActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); } } ``` change\_image\_trans.xml ``` <?xml version="1.0" encoding="utf-8"?> <transitionSet xmlns:android="http://schemas.android.com/apk/res/android"> <changeTransform /> </transitionSet> ``` styles.xml ``` <resources> <!-- Base application theme. --> <style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar"> <item name="android:windowActivityTransitions">true</item> <item name="android:windowContentTransitions">true</item> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!-- specify shared element transitions --> <item name="android:windowSharedElementEnterTransition"> @transition/change_image_trans</item> <!-- specify shared element transitions --> <item name="android:windowSharedElementExitTransition"> @transition/change_image_trans</item> </style> </resources> ```
2017/01/11
[ "https://Stackoverflow.com/questions/41602452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056488/" ]
Just try with `postponeEnterTransition()` and `startPostponedEnterTransition()` in your `DetailActivity` `postponeEnterTransition()` used to temporarily delay the transition until the shared elements have been properly measured and laid out. `startPostponedEnterTransition()` Schedules the shared element transition to be started immediately after the shared element has been measured and laid out within the activity's view hierarchy. `DetailActivity.java` ``` @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); postponeEnterTransition(); } private void scheduleStartPostponedTransition(final View sharedElement) { sharedElement.getViewTreeObserver().addOnPreDrawListener( new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { sharedElement.getViewTreeObserver().removeOnPreDrawListener(this); startPostponedEnterTransition(); return true; } }); } ```
I don't think that your problem is that you have a custom view... I always make those transitions with my custom views and they work ok. I can see that this code: ``` ActivityOptions options = ActivityOptions .makeSceneTransitionAnimation(MainActivity.this, view1, "profile"); // start the new activity startActivity(intent, options.toBundle()); ``` Does't do what you want. Here is what you need to do: **First**, create your xml with the transition: First Activity ``` <YouCustomView android:id="@+id/someId" android:layout_width="match_parent" android:layout_height="wrap_content" android:transitionName="@string/someTransition"> ``` Second Activity: ``` <YouCustomView android:id="@+id/someOtherId" android:layout_width="match_parent" android:layout_height="wrap_content" android:transitionName="@string/someTransition"> ``` **Second**, when you you start your second activity, do it like this: ``` ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation( this, new Pair<>(findViewById(R.id.someId), getString(R.string.someTransition)) startActivity(intent, activityOptions.toBundle()); ``` You forgot to add the Pair with the View and the name of the transition. Add that and your transition will work just fine. The fact that your View is a custom view doesn't change the animation. Happy coding!
688,432
> > Prove that $$1<\dfrac{1}{1001}+\dfrac{1}{1002}+\dfrac{1}{1003}+\dots+\dfrac{1}{3001}<\dfrac43 \, .$$ > > > My work: $$\begin{eqnarray\*} S&=&\bigg(\dfrac{1}{1001}+\dfrac{1}{3001}\bigg)+\bigg(\dfrac{1}{1002}+\dfrac{1}{3000}\bigg)+\ldots+\dfrac{1}{2001}\\ S&=&\dfrac{1}{4002}\bigg\{\bigg(\dfrac{1001+3001}{1001}+\dfrac{1001+3001}{3001}\bigg)+\ldots\bigg\}+\dfrac{1}{2001}\\ S&\ge& \dfrac{1}{4002}4\cdot1000+\dfrac{1}{2001}=1 \end{eqnarray\*}$$ I could derive the left hand inequality with a $\ge$ sign though but could not do anything about the right hand inequality. Please help. EDIT: I do not need to use the equality sign, I can rather use only strict inequality because there exist terms which are not equal so, the AM-HM inequality is actually a strict inequality here. $$S> \dfrac{1}{4002}4\cdot1000+\dfrac{1}{2001}=1$$ Though I got the solution but I am looking for some non-calculus solutions too.
2014/02/24
[ "https://math.stackexchange.com/questions/688432", "https://math.stackexchange.com", "https://math.stackexchange.com/users/105577/" ]
Let $k$ be a fixed integer greater than $0$. It holds that $\frac{1}{1000+k}\leq \frac{1}{1000+x}$for any $x \in [k-1,k]$. Integrating for fixed $k \in [1,2001]$ yields $$\frac{1}{1000+k}\leq \int\_{k-1}^{k}\frac{1}{1000+x}dx$$ Hence $$\frac{1}{1001}+\frac{1}{1002}+\frac{1}{1003}+\ldots+\frac{1}{3001} \leq \int\_{0}^{2001}\frac{1}{1000+x}dx=\ln\left(\frac{3001}{1000}\right)$$ And $$\ln\left(\frac{3001}{1000}\right)\sim 1.1 < \frac{4}{3}$$
For $k=0,1 \cdots 2000$ we have $$ \frac{1}{1001+k} < \frac{1}{1000}\left(1 - \frac{k}{3000}\right)$$ Explanation: let the left side be $f(k)$ and the right side $g(k)$. Then $f(0)=1/1001$, $g(0) = 1/1000$; while $f(2000)=1/3001$ and $g(2000) =1/3000$. Hence $f < g$ in the extreme points - and because $f$ is convex, it must also be below $g$ in the intermediate values, because $g$ is linear. Then $$\sum\_{k=0}^{2000} \frac{1}{1001+k} < \frac{1333}{1000} <\frac{4}{3}$$
2,731,712
I am really trying to follow the DRY principle. I have a sub that looks like this? ``` Private Sub DoSupplyModel OutputLine("ITEM SUMMARIES") Dim ItemSumms As New SupplyModel.ItemSummaries(_currentSupplyModel, _excelRows) ItemSumms.FillRows() OutputLine("") OutputLine("NUMBERED INVENTORIES") Dim numInvs As New SupplyModel.NumberedInventories(_currentSupplyModel, _excelRows) numInvs.FillRows() OutputLine("") End Sub ``` I would like to collapse these into a single method using generics. For the record, ItemSummaries and NumberedInventories are both derived from the same base class DataBuilderBase. I can't figure out the syntax that will allow me to do ItemSumms.FillRows and numInvs.FillRows in the method. FillRows is declared as `Public Overridable Sub FillRows` in the base class. Thanks in advance. **EDIT** Here is my end result ``` Private Sub DoSupplyModels() DoSupplyModelType("ITEM SUMMARIES",New DataBlocks(_currentSupplyModel,_excelRows) DoSupplyModelType("DATA BLOCKS",New DataBlocks(_currentSupplyModel,_excelRows) End Sub Private Sub DoSupplyModelType(ByVal outputDescription As String, ByVal type As DataBuilderBase) OutputLine(outputDescription) type.FillRows() OutputLine("") End Sub ``` But to answer my own question...I could have done this... ``` Private Sub DoSupplyModels() DoSupplyModelType(Of Projections)("ITEM SUMMARIES") DoSupplyModelType(Of DataBlocks)("DATA BLOCKS") End Sub Private Sub DoSupplyModelType(Of T as DataBuilderBase)(ByVal outputDescription As String, ByVal type As T) OutputLine(outputDescription) Dim type as New DataBuilderBase (_currentSupplyModel,_excelRows) type.FillRows() OutputLine("") End Sub ``` Is that right? Seth
2010/04/28
[ "https://Stackoverflow.com/questions/2731712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39478/" ]
you can refactor to take advantage of the fact that the share a common base and use polymorphism: (VB a bit rusty, you should get the idea) you could have a method: ``` Private Sub FillAndOutput(textToOutput as String, filler as DataBuilderBase) OutputLine(string) filler.FillRows() OutputLine("") end sub ``` which you could call: ``` Private Sub DoSupplyModel FillAndOutput("ITEM SUMMARIES",New SupplyModel.ItemSummaries(_currentSupplyModel, _excelRows)) FillAndOutput("NUMBERED INVENTORIES",New SupplyModel.NumberedInventories(_currentSupplyModel, _excelRows)) End Sub ```
In this case I don't think that refactoring to a generic function is justifiable, even at the expense of repeating yourself. You would have two options: 1. Refactor your code so that it allows for parameterless constructors and create a function at a higher level of inheritance that allows you to specify the arguments currently being passed to the constructor. 2. Use explicit reflection to instantiate the generic type and pass those arguments to the constructor. Either of those options involves a non-trivial amount of work with very little gain (you're translating three lines of code into one). However, to answer your question, VB.NET uses the `of` keyword to specify generic type arguments ``` Public Sub Foo(Of T)(argument as T) ... End Sub ```
10,370,143
My homepage has links to pages a.html and b.html. In the same directory with these 2 pages, I have pages **c.html** and **d.html** which **are not linked to by any other pages**. My question is **Do webcrawlers also index c.html and d.html** just because they are in the directory? Or do they only follow the links starting from the home page and index only the homepage plus pages a and b? Thanks.
2012/04/29
[ "https://Stackoverflow.com/questions/10370143", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210654/" ]
Sending this mDNS packet seems to work for my application which has a Raspberry Pi. I think the IP/ports are specific to ZeroConf/Bonjour, which seems to be widely used so it may work for those cameras. ``` public void sendDiscoveryQuery(string local_dhcp_ip_address) { // multicast UDP-based mDNS-packet for discovering IP addresses System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Parse(local_dhcp_ip_address), 52634)); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("224.0.0.251"), 5353); List<byte> bytes = new List<byte>(); bytes.AddRange(new byte[] { 0x0, 0x0 }); // transaction id (ignored) bytes.AddRange(new byte[] { 0x1, 0x0 }); // standard query bytes.AddRange(new byte[] { 0x0, 0x1 }); // questions bytes.AddRange(new byte[] { 0x0, 0x0 }); // answer RRs bytes.AddRange(new byte[] { 0x0, 0x0 }); // authority RRs bytes.AddRange(new byte[] { 0x0, 0x0 }); // additional RRs bytes.AddRange(new byte[] { 0x05, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01 }); // _http._tcp.local: type PTR, class IN, "QM" question socket.SendTo(bytes.ToArray(), endpoint); } ``` The 'local\_dhcp\_ip\_address' is the ip address of your computer's nic. Below is a wireshark trace for this interaction. The device responds directly to your computer. [![enter image description here](https://i.stack.imgur.com/LqpNR.png)](https://i.stack.imgur.com/LqpNR.png) At this point ARP -a should work. You can also use [GetIpNetTable](https://stackoverflow.com/a/1148861/1750408).
On some devices the MAC-Address is printed on a lable, maybe on the backside. As far as my understandig goes, they need to be in the arp cache at least once. But this cache only stores 5 (?) entries, so you may have to refresh it, or clear it before you connect the devices or run the config tool.
444,383
I am curious why can't we switch to a user's home director with either ``` $ cd ~"$USER" ``` or ``` $ cd ~${USER} ```
2018/05/17
[ "https://unix.stackexchange.com/questions/444383", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/286001/" ]
That very much depends on the shell and the order the expansions are done in those shells. `~$user` expands to the home directory of the user whose name is stored in `$user` in csh (where that `~user` feature comes from), AT&T ksh, zsh, fish. Note however these variations: ``` $ u=daemon/xxx csh -c 'echo ~$u' /usr/sbin/xxx # same in zsh/fish $ u=daemon/xxx ksh93 -c 'echo ~$u' ~daemon/xxx $ u=daemon/xxx csh -c 'echo ~"$u"' Unknown user: daemon/xxx. $ u=daemon/xxx zsh -c 'echo ~"$u"' /usr/sbin/x # same in fish $ u=" daemon" csh -c 'echo ~$u' /home/stephane daemon $ u=" daemon" zsh -c 'echo ~$u' ~ daemon # same in ksh/fish $ u="/daemon" csh -c 'echo ~$u' /home/stephane/daemon # same in zsh $ u="/daemon" fish -c 'echo ~$u' ~/daemon # same in ksh ``` It expands to the home directory of the user named literally `$user` in `bash` (provided that user exists, which is very unlikely of course). And to neither in `pdksh`, `dash`, `yash`, presumably because they don't consider `$user` to be a valid user name.
Tilde expansion is a separate step in the processing of the command line. It happens just *before* variable expansion. If the tilde is followed by something other than a slash, it will expand to the home directory of the user whose name is following the tilde, as in, for example, `~otheruser`. Since `$USER` is not expanded at that point and since it's unlikely to correspond to a valid username, the tilde is left unexpanded. `$USER` is likely to be the username of the current user, so your expression could probably be replaced by just `~`.
65,634,447
I'm trying to get values from JSON that looks like this: ``` { "id": 371, "city": "London", "name": "London Station", "trains": [ { "id": 375, "number": "1023", "numberOfCarriages": "21" } ] } ``` I want to get values from trains, like number and numberOfCarriages. I'm trying to get those values in React. My React code: ``` class ViewTrainsComponent extends Component { constructor(props) { super(props) this.state = { id: this.props.match.params.id, station: [] } } render() { return ( <div> <div className="row"> {/* <div>{this.state.station[0].trains[0].number}</div> */} </div> </div> ); } } ``` Am I doing it right? How can I get those values in render function? EDIT. Here is the response from API [![enter image description here](https://i.stack.imgur.com/SxH49.png)](https://i.stack.imgur.com/SxH49.png)
2021/01/08
[ "https://Stackoverflow.com/questions/65634447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14782668/" ]
Jazzy requires a build from the command line to generate the documentation. So you need a command similar to: ```sh jazzy --build-tool-arguments -workspace,ios.xcworkspace,-scheme,iosapp ``` From <https://github.com/realm/jazzy> > > *...try passing extra arguments to xcodebuild, for example `jazzy --build-tool-arguments -scheme,MyScheme,-target,MyTarget`* > > > --- How to find your schemes and targets to pass into `xcodebuild` from Jazzy Be sure to `cd` to the directory where your Xcode Workspace or Xcode Project is: `cd path/to/ios.xcworkspace` ```sh xcodebuild -version # online help man xcodebuild # List schemes & targets xcodebuild -list ``` Results for a sample Xcode Workspace, ``` Information about project "ios": Targets: iosapp bench dynamic static bundle test integration Integration Test Harness Build Configurations: Debug Release RelWithDebInfo If no build configuration is specified and -scheme is not passed then "RelWithDebInfo" is used. Schemes: bench bundle CI dynamic dynamic+static Integration Test Harness iosapp static ```
You can review the content of ``` log file: /var/folders/nd/t1rlxsp94kgbll0v834jnc0h0000gp/T/xcodebuild-84D58051-E84E-40D8-A4E7-E080B83D7117.log ``` for to obtain details the error
4,581
Using 8.1 I would like to implement some personalization on the top banner of a page. So, if the user matches Pattern Card A, they see banner A, if they match Pattern Card B, they see banner B, and so on. My problem is that if the match Pattern Card A first, they can never get to Pattern Card B because in the hierarchy of the rules, once they match A, the always match A and can never change to B because their values still match A. I'm not sure if I am misunderstanding how pattern card matching is working? Or not setting up my rules correctly? **UPDATE** On my banner, I have the following Rules: Condition 1. where the current contact matches **Exercises** in the **MyCustomPersona** profile : Show the Exercise banner Condition 2. where the current contact matches **Swimming** in the **MyCustomPersona** profile : Show the Swimming banner Default Condition. Of none of the other conditions are true, the default condition is used. MyCustomPersona is a Profile, with several Profile Keys: Exercise, Swimming, etc... My profile cards are all or nothing, meaning the profile card for Exercise is Exercise = 100, my profile card for swimming is Swimming = 100 And what is happening is that once a user meets the Exercise = 100 threshold, I only ever see the Exercise banner, no matter what else I do on the site. AND, this seems to be the case when my rules are based on **Visitor**. If I use rules based on **Visit** I seem to be OK. But I really want historical data. Meaning if I browse on the site one day and meet the Exercise threshold, I should be able to come back to the site and it still be personalized for Exercise.
2017/02/23
[ "https://sitecore.stackexchange.com/questions/4581", "https://sitecore.stackexchange.com", "https://sitecore.stackexchange.com/users/341/" ]
The user can still be matched in Pattern Card A or B. Let us take the following scenario: Pattern Card A is assigned to users who are more involved in reading articles that concerns Exercises. Pattern Card B is assigned to users who are more involved in reading articles that concerns Swimming. So, if your user is tag with the Pattern Card A, this means that the user has a preference for exercises articles. For the user to be tag with the Pattern Card B, you need to make him/her to read Swimming articles. To do so, you will require to make use of Goals and Engagement Values which will drive the user to start reading articles about swimming. As long as the user keeps reading Exercises articles, he/she will stay in the Pattern Card A. It all depends on how you set the rules and what you want your users to do on the site. **Update** Sitecore Rules evaluation is like this: Once a condition is met, it will return the action. So, if there are other rules below, they will not be executed. The issue here is that both Exercises and Swimming are 100 and if Exercises Rule is above the Swimming Rule, it will always return Exercises. So, you will need to either rethink on how to set the points or modify the rule to add a certain time limit of displaying the Banner or how to tag your content with the pattern cards. If I am not mistaken, you may tag a content with more than 1 profile card. I would suggest to work on the points because personalization is mostly based on what the user wants. Also, it is Sitecore in its core who calculates in which pattern it will place the user. It all depends which profile cards have been used to tag content and base of each profile card weightage, Sitecore determines in which pattern the user falls.
I would suggest ordering the rules for personalization from most specific to least specific. In your example I would do this like: 1. Exercise and Swimming 2. Exercise only 3. Swimming only 4. Default The thresholds for Exercise and Swimming could also be something less than 100, so you can build upon the points in each facet in a more granular way to determine their level of interest more specifically. This will give you more options for evaluating the rules and determine the content to show. i.e.: Exercise and some Swimming and Swimming and some Exercise, etc.
159,534
If I right click and get "properties" on an [RSS](http://en.wikipedia.org/wiki/RSS) item in Outlook 2007 after I've created it, there doesn't seem any place that shows me the RSS feed [URL](http://en.wikipedia.org/wiki/Uniform_Resource_Locator) that it is using. How do I find it out? ![Enter image description here](https://i.stack.imgur.com/kVms3.png)
2010/07/02
[ "https://superuser.com/questions/159534", "https://superuser.com", "https://superuser.com/users/1501/" ]
It's under menu **Tools** -> **Account Settings** -> **RSS Feeds**. Under the one you want, choose it and then click the **Change** button. The RSS URL is the **Location**.
It's annoying that you can't get to this in the properties. The easiest way to get to the URL would probably be to export the RSS feeds to an OPML file and you can find them all in there. I'm using 2010, but I think in 2007 you start from File > Import and Export (in 2010 it is now in File > Options > Advanced > Export). One of the export options is to export your RSS feeds to an OPML file. You can do this for all at once (which is handy for transferring to another machine, or backing up), or just the specific ones you are interested in. Choose a filename and location you can remember. Open the OPML file from a text editor such as Notepad and you can see the URL for the feed XML
17,886,074
The following button provides the exact functionality I require, but it must be done programmatically as I will be making more than one based on some variables, but the latter I can figure out if I can just create the button below as a starter: ``` <asp:Button runat="server" OnCommand="Load_Items" CommandArgument="1" text="Submit" /> ``` More information on what I've been doing [here](https://stackoverflow.com/questions/17884044/method-being-triggered-on-page-load-but-not-via-asp-button/). Edit: I have looked at questions [like this](https://stackoverflow.com/questions/188007/creating-an-aspbutton-programatically), but don't see where to go from `Button btnSave = new Button();` to seeing a button on the page. Also, most questions I've found seem to go about using C# to handle clicking, but I want to have an OnCommand property to handle it. If I do the following and search using the developer tools for "btn", I get no results. ``` Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; btnSave.CssClass = "btn"; ```
2013/07/26
[ "https://Stackoverflow.com/questions/17886074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/835099/" ]
Here is how you create a Button with Command event. Once it is created, you need to find a way of displaying it. The following example uses `PlaceHolder`; you can also substitute with `Panel` if you want. ASPX ---- ``` <asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder> ``` Code Behind ----------- ``` protected void Page_Load(object sender, EventArgs e) { for (int i = 0; i < 5; i++) { var button = new Button { ID = "Button" + i, CommandArgument = i.ToString(), Text = "Submit" + i }; button.Command += Load_Items; PlaceHolder1.Controls.Add(button); } } private void Load_Items(object sender, CommandEventArgs e) { int id = Convert.ToInt32(e.CommandArgument); // Do something with id } ```
You need a container control on your page. Try an asp panel for example. Then in your codebehind you do panel.controls.add(btnSave); And don't forget to do it on every site load. <http://support.microsoft.com/kb/317515/en-us>
46,820,625
I'm using Kali dist so I have already installed Python 2.7, 3.5 and 3.6. Commands 'python' and 'pip' are associated with Python 2.7. But the 'python3' uses Python 3.6 while pip3 is installing packages for Python 3.5. When I tried to create an venv: ``` pip3 -p python3.6 virtualenv myenv ``` I've got an error: ``` no such option: -p ``` How can I associate pip3 with Python 3.6 instead of Python 3.5?
2017/10/18
[ "https://Stackoverflow.com/questions/46820625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can explicitly run the `pip3` script with a particular Python version, by prefixing it with the appropriate `python3.`*x* command: ``` ldo@theon:~> pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) ldo@theon:~> python3.5 $(which pip3) --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.5) ```
To install a package in the same version location that's associated with the version associated with python3, use the following: ``` python3 -m pip install [package] ``` to pick a specific version that you'd like your package to be associated with (so you're not guessing with the above): ``` python3.5 -m pip install [package] python3.7 -m pip install [package] ``` Also, be careful because pip3 can point to different locations and may not necessarily match the location of the python3 binary. I just found that out when I did a pip3 install and it failed to import when running python3. You can also explicitly call pip3.5, pip3.7, etc, but honestly I prefer using the `python[version] -m pip install [package]` method because I know that it will install the package in the location associated with whatever python3.x binary I'm using.
180,435
Is there an open source alternative (similar to ultraedit) to handle files with filesize >200 MBytes?
2008/10/07
[ "https://Stackoverflow.com/questions/180435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11723/" ]
Duplicate of [Best Free Text Editor Supporting *More Than* 4G Files?](https://stackoverflow.com/questions/102829/best-free-text-editor-supporting-more-than-4g-files "Best Free Text Editor Supporting *More Than* 4G Files?") and even [Editor to open big text files (XML export files)](https://stackoverflow.com/questions/159521/editor-to-open-big-text-files-xml-export-files "Editor to open big text files (XML export files)"), even if you added "open source" (most are).
[textpad](http://www.textpad.com) will probably swallow it oops, just clocked the "open source" requirement. Typing before thinking.
40,423,753
I am new to c# and trying to insert a number from a textbox and I have adding a button to submit the number. I then want it to be added to the array and outputted onto the listbox. However, I am having the whole array outputted onto Thanksthe listbox instead. How do I only show the number being entered? ``` for (int i = 0; i <= MAX_ITEMS; i++) { if (i < index) lstHoldValue.Items.Add(numArray[i]); } ```
2016/11/04
[ "https://Stackoverflow.com/questions/40423753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5826303/" ]
You are not clearing your listbox first. The code below should do the job: ``` lstHoldValue.Items.Clear(); for (int i = 0; i <= MAX_ITEMS; i++) { if (i < index) lstHoldValue.Items.Add(numArray[i]);//show array in a listbox } ```
You can add : ``` lstHoldValue.Items.clear(); ``` before the loop to remove the elements of the List or juste replace the loop by : ``` listBox1.Items.Add(txtInitialise.Text); txtInitialise.Text = ""; ``` to add the elements one by one
3,171,467
I have drawn a rectangle. It is undreneath a horizontal scroll bar on screen. Now i want to zoom the rectangle. On zooming the height of rectangle increases, the location shifts up and horizontal scroll bar moves up. How to do this? I am writing this piece of code: ``` rect = new Rectangle(rect.Location.X, this.Height - rect.Height,rect.Width, Convert.ToInt32(rect.Size.Height * zoom)); g.FillRectangle(brush, rect); ``` This works for the location of the rectangle that is the rectangle shifts up but the height doesn't increase. Help!
2010/07/03
[ "https://Stackoverflow.com/questions/3171467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/378805/" ]
If you simply want to scale the rectangle around the center of the rectangle then you need to increase the width and height of the rectangle and subtract half the increase from the location. This is not tested, but should give you the general idea ``` double newHeight = oldHeight * scale; double deltaY = (newHeight - oldHeight) * 0.5; rect = new Rectangle( rect.Location.X, (int)(rect.Location.Y - deltaY), rect.Width, (int)newHeight); ``` Possibly a better alternative would be to look at using [Graphics.ScaleTransform](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.scaletransform.aspx).
Just add a txtZoom to your form: ``` using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.txtZoom.Text = "1"; this.txtZoom.KeyDown += new KeyEventHandler(txtZoom_KeyDown); this.txtZoom_KeyDown(txtZoom, new KeyEventArgs(Keys.Enter)); } void txtZoom_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { this.Zoom = int.Parse(txtZoom.Text); this.Invalidate(); } } public int Zoom { get; set; } protected override void OnPaint(PaintEventArgs e) { GraphicsPath path = new GraphicsPath(); path.AddRectangle(new Rectangle(10, 10, 100, 100)); Matrix m = new Matrix(); m.Scale(Zoom, Zoom); path.Transform(m); this.AutoScrollMinSize = Size.Round(path.GetBounds().Size); e.Graphics.FillPath(Brushes.Black, path); } } } ```
9,387,269
I'm using "acts\_as\_tree" plugin for my user messaging thread feature on my website. I have a method that makes deleting selected messages possible. The messages don't actually get deleted. Their sender\_status or recipient\_status columns get set to 1 depending on what user is the sender or recipient of the message. Anyway if both users have those status's set to one then that last line makes sure the message row is completely moved from the database. Now this is fine as long as it's not the parent message being deleted. If the parent message deleted then the children that haven't been selected for deletion won't be accessible anymore. Here is the method: ``` def delete_all_users_selected_messages(message_ids, user_id, parent_id) Message.where(:id => message_ids, :sender_id => user_id).update_all(:sender_status => 1) Message.where(:id => message_ids, :recipient_id => user_id).update_all(:recipient_status => 1) Message.delete_all(:sender_status => 1, :recipient_status => 1, :parent_id => parent_id).where("id != ?", parent_id) end ``` It's quite obvious what I'm trying to do. I need to have the parent ignored. So where the primary key is equal to the parent\_id means that row is a parent (normally the parent\_id is nil but I needed it set to the primary keys value for some other reason, long story and not important). Anyway is there an SQL statement I can add on to the end of the last line in tat method? To make sure it only deletes messages where the id of the row is not equal to the parent\_id? I can arrange for the parent\_id row to never be permitted for deletion unless the actual thread (MessageThreads table that references the messages tables conversations) is deleted. Any way how can I make it so this parent row is ignored when that delete\_all method is run? Kind regards
2012/02/22
[ "https://Stackoverflow.com/questions/9387269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439688/" ]
Nowadays in Rails 4, you can do: ``` Model.where.not(attr: "something").delete_all ``` and ``` Model.where.not(attr: "something").destroy_all ``` And don't forget about difference: * destroy\_all: The associated objects are destroyed alongside this object by calling their `destroy` method. Instantiates all the records and destroys them one at a time, so with a large dataset, this could be slow * delete\_all: All associated objects are destroyed immediately without calling their `destroy` method. Callbacks are not called.
This worked for me in the end. ``` Message.where('id != ? AND parent_id = ?', parent_id, parent_id).where(:sender_status => 1, :recipient_status => 1).delete_all ``` Basically returns all messages of that particular conversation except the one where id == parent\_id. Whenever id == parent\_id this means it's a parent message.
11,029,558
This statment is found in the graph api (https://developers.facebook.com/docs/reference/api/) > > Objects with location. The following will return information about > objects that have location information attached. In addition, the > returned objects will be those in which you or your friend have been > tagged, or those objects that were created by you or your friends. > > > But it is not stated how to make this call, has anyone figured it out? In order to get pure checkins the following is used: <https://graph.facebook.com/search?type=checkin>
2012/06/14
[ "https://Stackoverflow.com/questions/11029558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410248/" ]
Well, identifying relationships and "more natural" keys can lower the need for JOINing. For example: ![enter image description here](https://i.stack.imgur.com/CqDEx.png) Since there is `Faxes.ProviderId`, you can directly JOIN `Faxes` and `Providers`. And since [InnoDB tables are clustered](http://www.ovaistariq.net/521/understanding-innodb-clustered-indexes/), you can expect good performance if you ever go in the opposite direction (e.g. "get all faxes of the given provider"). The downside is "fatter" keys and relative unfriendliness towards ORMs. So, I guess this is a matter of compromise, and you are the one who gets to decide which option is better.
What you could do is make the provider-subsequent tables related to each other as [weak entities](http://en.wikipedia.org/wiki/Weak_entity) — where part of the identifying primary key of each table is dependent on another table (via a 1:N *identifying* relationship). You can model this like so: ``` providers ----------------- provider_id [PK] ... addresses ----------------- provider_id [PK] (FK Referencing providers.provider_id) address_id [PK] ... letters ----------------- provider_id [PK] (FK Referencing addresses.provider_id) address_id [PK] (FK Referencing addresses.address_id) letter_id [PK] ... faxes ----------------- provider_id [PK] (FK Referencing letters.provider_id) address_id [PK] (FK Referencing letters.address_id) letter_id [PK] (FK Referencing letters.letter_id) fax_id [PK] ... ``` This way, given a particular fax record where you only need to find out more information about the associated provider, you only need to join one table like so: ``` SELECT subj, content FROM faxes INNER JOIN providers USING (provider_id) WHERE fax_id = <faxid here> ```
24,831,822
I am using asp.net 4 and c#. I have a gridview with a textbox that needs a unique value for the database. This value is to sort the data by precendence with in the database. All my other validators work but they only check the value in the one box. How do I validate that the integers are unique in that column. The only thing I found to do this is "DataKeyNames" but that does not stop it from allowing repeating numbers. Updating the order is done on button click. Thanks for info.
2014/07/18
[ "https://Stackoverflow.com/questions/24831822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3549282/" ]
The problem was: My Mac (I don't know how), changed the files charset when I copy the files to the new server. When I made the same process in a Ubuntu machine, worked very well. Thank's for the answers.
Hey i tested your nginx scenario without wordpress using my local installation and i dont have any issues with the file name. Could you double check the file location? You could try to create a simple setup without wordpress to debug your situation, and did you look at your access.log file? Enclosed is my testsetup. The file Workshop-de-Tricô-e-Crochê-Círculo.png is stored directly in the path /data/nginx-test ``` 1,4M 18 Jul 22:33 Workshop-de-Tricô-e-Crochê-Círculo.png ``` nginx configuration: ``` server { listen 80; listen 443 ssl; server_name test.*; root /data/nginx-test; index index.php; location / { try_files $uri $uri/ /index.php$is_args$args; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_read_timeout 900; } } ``` request/response headers: ``` Remote Address:192.168.33.10:80 Request URL:http://test.vg/Workshop-de-Tric%C3%B4-e-Croch%C3%AA-C%C3%ADrculo.png Request Method:GET Status Code:200 OK Request Headers Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 Cache-Control:no-cache Connection:keep-alive Host:test.vg Pragma:no-cache User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36 Response Headers Accept-Ranges:bytes Connection:keep-alive Content-Length:1486529 Content-Type:image/png Date:Fri, 18 Jul 2014 20:36:54 GMT ETag:"53c98490-16aec1" Last-Modified:Fri, 18 Jul 2014 20:33:20 GMT Server:nginx/1.6.0 ```
6,075,628
![enter image description here](https://i.stack.imgur.com/hE2Xj.jpg) I am using a dual core **XP machine** with 4GB memory installed (but only **2.5GB** reported by the OS due to the 32bit fact). I am actively modifing an old JAVA application for at least a month by using lastest **Eclipse** (edit, build and run) and **Ant** (another way to build and run). In the **Eclipse** run configuration and **build.xml** file, we have the following JVM parameters: `-Xmx1024M -Xms1024M -Xmn384M`. We have been using this configuration for years. I also have a batch file to launch Eclipse with this parameter: `-vmargs -Xmx768M`. This batch file has been with me for years. (now I changed to modify the eclipse.ini to do configuration.) The day before yesterday, I found it was much slower when I used Ant to build and run my application (I build and run it frequently during the modification process). I restarted my machine just before I went home. That night I VPN to my machine to finish some modifications (I am a very good employee.) and found more slower. Next morning, "**could not craete the Java Virtual Machine**" started to happen when I run our application with Ant. I restarted my machine. Then I couldn't start my Eclipse with the same error. I have to change the vmargs to claim only 512MB memory to launch the Eclipse. The build time with Ant increased from about 20 seconds to about 6 minutes. And I have to decrease the max memory for JVM to ``` -Xmx512M -Xms512M ``` in both Eclipse run configuration and Ant build.xml in order to avoid error. Then I uninstall my 1.6u24 jdk/jre and installed the 1.6u25. I reinstalled the Eclipse. Scanned the entire machine with Trend Micro and found nothing. Another machine which I usually connect to do some testing has similar result (slower). All other machines, include my co-worker's machine and my laptop, work fine with the same application and tools. If I use Ant to build and run it, the build process and launch process are extramely slow. I have created two batch files to compile and launch my application . They work as normal. When compile with Eclipse, it works as normal. But I cannot ask JVM to claim **1024MB** for my application in all cases now. All other activities on my machine seem normal. VisualStudio and C# application work as usual. My machine was rebuilt few weeks ago due to hard disk failure. So there are no many useless things to slow my machine down. Anybody can help me figure out why the JVM on my machine changed its behaviour? I hope it is not caused by virus. Do you know anything I can try before I call IT to rebuild my machine? thanks,
2011/05/20
[ "https://Stackoverflow.com/questions/6075628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117039/" ]
Either use the task manager or process explorer from microsoft (http://technet.microsoft.com/en-us/sysinternals/bb896653) and check for memory hogs. If you have to reduce the amount of memory you are using, chances are it is because something else has taken it up. Also, I find the cap at 2.5GB a bit odd, as I thought the cap was more like 3.25GB (mostly because this is what I have on my windows XP with 4gb installed). Also, every time I've seen that error message it is because there isn't enough physical memory available to grab. I've had to close programs in the past in order to run a few things after getting this exception. (I would have put this in a comment, but don't have the rating yet :/ )
Can you see anything odd in the task manager? CPU utilization? The fact that you can't allocate as much memory as you used to sounds odd, but I have seen similar decrease in compilation times after an upgrade of the antivirus on one of my development machines. What happens if you disable antivirus while you do a compilation?
9,619,092
I would like to process a text file (about 400 MB) in order to create a recursive parent-child-structure from the data given in each line. The data have to be prepared for a top down navigation (input: parent, output: all children and sub children). E.g. of lines to be read: (**child**,id1,id2,**parent**,id3) **132142086**;1;2;**132528589**;132528599 **132142087**;1;3;**132528589**;132528599 **132142088**;1;0;**132528589**;132528599 **323442444**;1;0;**132142088**;132528599 **454345434**;1;0;**323442444**;132528599 132528589: is parent of 132142086,132142087,132142088 132142088: is parent of 323442444 323442444: is parent of 454345434 Given: OS windows xp, 32bit, 2GB available Memory and -Xmx1024m Here is the way I prepare the data: ``` HashMap<String,ArrayList<String>> hMap=new HashMap<String,ArrayList<String>>(); while ((myReader = bReader.readLine()) != null) { String [] tmpObj=myReader.split(delimiter); String valuesArrayS=tmpObj[0]+";"+tmpObj[1]+";"+tmpObj[2]+";"+tmpObj[3]+";"+tmpObj[4]; ArrayList<String> valuesArray=new ArrayList<String>(); //case of same key if(hMap.containsKey(tmpObj[3])) { valuesArray=(ArrayList<String>)(hMap.get(tmpObj[3])).clone(); } valuesArray.add(valuesArrayS); hMap.put(tmpObj[3],valuesArray); tmpObj=null; valuesArray=null; } return hMap; ``` After then I use a recursive function: ``` HashMap<String,ArrayList<String>> getChildren(input parent) ``` for creating the data structure needed. The plan is to let the hMap available (read only) for more than one thread using the function getChildren. I tested this program with an input file of 90 MB and it seemed to work properly. However, running it with the real file with more than 380 MB lead to: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space **I need some help in memory resource management**
2012/03/08
[ "https://Stackoverflow.com/questions/9619092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256982/" ]
From the "dirt-simple approach" side of things: Based on your problem statement, you don't need to keep id1, id2, or id3 around. Assuming that's the case, how about replacing your `HashMap<String, ArrayList<String>>` with a `HashMap<Integer, ArrayList<Integer>>`? You can use `Integer.parseInt()` to do the string-to-int conversion, and an Integer should always be smaller than the corresponding String. Other suggestions: replace your `ArrayList` with a `HashSet` if you don't care about duplicates. Per outofBounds' answer, you don't need to clone an `ArrayList` every time you want to add an item to it.
You are really testing the boundaries of what one can doing with 1GB of memory. You could: 1. Increase Heap Space. 32 bit windows will limit you to ~1.5GB, but you still have a little more wiggle room it might be enough to put you over the top. 2. Build some type of pre-processor utility that Pre-partitions the file in sizes you know to work and operates on them one at a time, perhaps hierachically. 3. Try re-structuring your program. It has lots of splitting and concatenating going on. In java strings are immutable and when you split strings and concatenate with `+` operators you are creating new Strings all the time(9 out of 10 cases this doesn't matter, but in your case where you are working with a very limited set of resources it might make a difference) As a side less helpful note. The real issue here is that you just don't have the resources to tackle this task and optimization is only going to take you so far. Its like asking how to better tunnel through a mountain with a garden trowel. The real answer is probably the one you don't want to hear which is throw away the trowel and invest in some industrial equipment On a second more helpful note(and fun if you're like me) - you may try hooking [jVisualVM](http://docs.oracle.com/javase/6/docs/technotes/tools/share/jvisualvm.html) up to your application and trying to understand where you heap is going or use [jhat](http://docs.oracle.com/javase/6/docs/technotes/tools/share/jhat.html) and the `-XX:+HeapDumpOnOutOfMemoryError` jvm flag to see what was happening with the heap at crash time.
60,363
My two friends and I are going to spend quite a bit of time preparing a mega-game. It will be a weekend long gaming session with around 20 players, and the three of us as GMs. We are trying to figure out the best possible use of GM resources given the large number of players. Should we reach out for 'helpers' who aren't quite GMs but do some housekeeping tasks? If that option does not exist, what other methods could be used to keep the game running smoothly? Good answers should pull from experience running large scale games with multiple GMs, and what techniques were used in managing so many players while keeping all of them engaged.
2015/04/29
[ "https://rpg.stackexchange.com/questions/60363", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/21795/" ]
Since you've specified this as system agnostic this is really just a logistics problem that boils down to "How do 3 people manage 20 people?" So we'll focus on minimizing downtime and maximizing engagement with a minimum of effort. As far as background I've run multiple con events that involved 100+ people in rotating tables and recurring multi-day adventures. **Planning and Prep Work** Do as much of the work as possible before the event. I would strongly encourage pre-gen characters. That way you are prepared for all of their powers, spells, etc. On the GM side, have NPC stats, plot outlines, common tables, anything you'll want to reference as you go in a nice handy cheat sheet or binder. Ideally there would be 3 copies, one for each GM. Having pre-made maps, or avoiding the need for maps all together is also very good for these settings. On the note of cheat sheets, if you have newer players, or are using a new system it is extremely helpful to have common rules on a one page sheet to give to every player. **Separate Areas** Trying to have all 20 people be involved in anything that involves regular skill checks, attacks ,etc will be both very hard to manage, and also very boring for the 15-19 people not actively involved in that check. Breaking your players into 3 manageable units will go a long way towards a smooth experience. This could be done by having 3 physical areas the players need to move between, 3 different squads they act in, or anything else that separates their action into smaller groups. It's important to let people flow from one section to the next and back again, so that you're running a mega game, not three games that just happen to be near each other. **Delegation of Tasks** With only three GM's you want to offload many of the normal book keeping tasks of the GM to the players. The biggest things are usually tracking initiative, drawing/using a map, and looking up any rules questions that come up. The less time the GM spends handling the books, the more time he can be driving the narration. There's almost always a player who isn't in the spot light right that second that can look something up or keep track of initiative. **Keep the Rules Simple** This is really a must-do with this many people, and one of the reasons I advocate GM made characters. Stopping a table of 4 players to look up an obscure rule is no fun. Stopping a table of 20 is miserable. It's nearly impossible to get everyone refocused. Ideally no rules issue should take you longer than 30 seconds to arbitrate. If you cannot readily find the rule, make one up from experience. Note, it's important to warn the players about this before hand. Make it clear that your goal is a fluid and exciting event, not a spreadsheet party. **Keep the Action Moving** This is one of the biggest pitfalls of a mega-game. When there are long lulls in the excitement and action people tend to zone out. Getting 20 people refocused and on task is a real pain. The best way of doing this is encouraging Player Empowerment. Encourage them to interact with one another in character without GM arbitration. If the spotlight is on someone else, they can easily be having a small interaction while still focusing on the major events. When you see someone starting to check out mentally, try and give them something to do. **Lastly, Focus on Fun** All of these things are there for one purpose, to ensure that everyone is having a good time. If it seems like a rule or plot point really isn't working for the group, throw it out! TLDR - Prep Work, Sub-Groups, Delegate, Player Empowerment
The answer by Skiptron pretty much hits all the high points. I'd like to add a couple of things to it though. **IRL Time Planning** Knowing that a break is coming will help prevent constant interruptions by players leaving the gaming area. It also gives the GM a chance to take a deep breath, gather their thoughts, and figure out what direction they are going to head next. Make sure you plan on taking a short break every two hours or so. A good 10-15 minutes is enough time to make a critical phone call, use the bathroom, grab a snack, or just stretch. Try to pause on a cliffhanger if possible but don't stress over it. Plan a longer break for food periodically. Depending on the venue it is a good idea to have the meals themselves planned or have a list of nearby options you can give the players. **Character Generation** *Pre-gen Characters* Pros: You can tell part of your story int he character backgrounds. All the characters will fit the world you are running so you will not suffer a massively out of place character concept (I'm looking at you dual wielding drow rangers in sunlight). You can choose to not give the wizard the one spell that will completely bypass a cool encounter you have planned Cons: That is a lot of work you have to do up front, especially for 20 players. You need to make more characters than players if you don't want someone to feel like they got "stuck" with the crappy one. *Player Built Characters* Pros: Get you better buy-in from the players themselves. Takes a lot of front-load work off the GM. Cons: The under-powered, overpowered, and uninteresting character possibilities are endless. If your willing to work closely with the players either one of these can work since you can mitigate the worst of the cons. It does require alot of player communication and time. To help deal with the communication issue during creation I would recommend a google doc for each character. Share it with all the GM's and the associated player. ***Ignore Below*** - Left for reference, not needed by for answer after system tag was added **System Selection** I divide most gaming systems into one of three major categories. Generally speaking the less rules the easier it is to run for a large group of people. I am sure there are tons of examples I don't know about or forgot to list here, please forgive me in advance. *Rules Crunch* These games have alot of specific rules and rely heavily on tactical combat. Tends to require Minis, Maps, Chart Look-ups, Lots of Dice, and/or Lots of Roll Modifiers. Gear tends to be a major factor in these types of games and can get very nit picky in the differences. Character sheets tend to be complicated and require 2+ pages to fix all the information in a well laid out manner. Examples include DnD 3.5e, DnD 4e, Pathfinder, Iron Kingdoms RPG, Almost any 70's or 80's game (like BattleTech) *Rules Lite* These games tend to be able to run mapless. Modifiers are generic in some way (Boost Die in EotE or Aspect in FATE) so they are easier to track. Character sheets tend to be less complicated and can fit on 1-2 pages easily. There is usually some mechanic for the players to drive the story which helps keep the characters involved. Examples include DnD 5e, FATE, Edge of the Empire, Savage Worlds *Rule of Cool* These games are all about the narrative and the rules are just kinda tacked on to give a concrete way of resolving differences. Props are usually just that, props, and not required for game play. Character sheets are generally 1 page affairs and sometimes are only kept as a reference outside of where game play is taking place. Examples include Storyteller System (World of Darkness) and the Dread RPG.
36,917,825
Sorry for weird title. Limited to 150 chars so couldn't use proper sentences. So let's say I've done the following to find out that something went wrong with my file stream: ``` std::ofstream ofs; do_stuff_with(ofs); // streams don't throw on error because C++ [edit: we can make them do so, but the .what()s aren't very user-friendly] // so we have to check for failure manually if(!ofs){ auto fail_code = errno; // threadsafe on Win/Linux // but what goes here? } ``` 1) strerror: Not threadsafe 2) strerror\_s: Not in GCC? Or is it? 3) strerror\_r: Not in Msvc? Or is it? 4) #ifdef/#define/etc: yuck, but may be the only choice I did do some searching but I didn't find a "this will definitely work in a sensible yet slightly platform-dependent way" answer... That said, I feel like this is "obviously a duplicate question", but I can't find the original...
2016/04/28
[ "https://Stackoverflow.com/questions/36917825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5388586/" ]
You can always throw your own exceptions using `std::system_error`: ``` #include <cerrno> #include <fstream> #include <iostream> #include <system_error> int main() { try { std::ofstream foo{"/root/bar.baz"}; foo << "bla" << std::endl; foo.close(); if(!foo) throw std::system_error{errno, std::generic_category()}; } catch(const std::system_error& err) { std::cout << "Error: " << err.code() << " - " << err.what() << std::endl; } return 0; } ``` This returns `Error: generic:13 - Permission denied`.
This is the best I could come up with. It's the "yuck" answer, but at least you can put the "yuck" in a single function and hide it away in some cpp file somewhere. std::ios covers boost streams as well, of course. Requires #ifdefs so it's a cheat. I believe Visual Studio #defines \_WIN32 by default, so at least you don't have to set up that infrastructure per se. ``` void check_stream(std::ios & stream) { if (!stream){ char err[1024] = { 0 }; #ifdef _WIN32 strerror_s(err, errno); #else strerror_r(errno, err, 1024); #endif throw MyException(err); } } ``` My own solution makes me sad so hopefully a better one will come along. But time is finite, so just submit to the Dark Side, use something like this, and get on with your life. :P ``` try{ boost::filesystem::ifstream ifs("testfile"); check_stream(ifs); } catch (std::exception & e){ std::cout << e.what(); // "No such file or directory" } ```
35,488,000
I want to find the way to enter the optgroup label into the inserted search-choice item, when the user select a option. With the format `[optgroup]-[option]`. The problem is that by default there is no a clear way to do it. Any suggestions on how to achieve this behavior? Thank you in advance. This is the default behavior ---------------------------- [![enter image description here](https://i.stack.imgur.com/GBsUI.jpg)](https://i.stack.imgur.com/GBsUI.jpg) This is what I am trying to do ------------------------------ [![Chosen JS](https://i.stack.imgur.com/vGY7d.jpg)](https://i.stack.imgur.com/vGY7d.jpg)
2016/02/18
[ "https://Stackoverflow.com/questions/35488000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2028267/" ]
**[Working fiddle](http://jsfiddle.net/PrHDH/260/)** You can achieve that by receiving a second parameter of `on()` method that contains an object with an attribute `selected` contains a `value` element if it exists or the `text` element (like the current case) : ``` $(".chosen-select").on('change', function (event,el) { ``` Then you can get the closest `optgroup` and concatenate the both then update the option `text` : ``` var selected_value = selected_element.val(); var parent_optgroup = selected_element.closest('optgroup').attr('label'); selected_element.text(parent_optgroup+' - '+selected_value).trigger("chosen:updated"); ``` Check example below, Hope this helps. --- ```js $(".chosen-select").chosen(); $(".chosen-select").on('change', function (event,el) { var selected_element = $(".chosen-select option:contains("+el.selected+")"); var selected_value = selected_element.val(); var parent_optgroup = selected_element.closest('optgroup').attr('label'); selected_element.text(parent_optgroup+' - '+selected_value).trigger("chosen:updated"); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet"/> <script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script> <select multiple data-placeholder="example" style="width:350px;" class="chosen-select" tabindex="5"> <option value=""></option> <optgroup label="NFC EAST"> <option>Dallas Cowboys</option> <option>New York Giants</option> <option>Philadelphia Eagles</option> <option>Washington Redskins</option> </optgroup> <optgroup label="NFC NORTH"> <option>Chicago Bears</option> <option>Detroit Lions</option> <option>Green Bay Packers</option> <option>Minnesota Vikings</option> </optgroup> <optgroup label="NFC SOUTH"> <option>Atlanta Falcons</option> <option>Carolina Panthers</option> <option>New Orleans Saints</option> <option>Tampa Bay Buccaneers</option> </optgroup> <optgroup label="NFC WEST"> <option>Arizona Cardinals</option> <option>St. Louis Rams</option> <option>San Francisco 49ers</option> <option>Seattle Seahawks</option> </optgroup> <optgroup label="AFC EAST"> <option>Buffalo Bills</option> <option>Miami Dolphins</option> <option>New England Patriots</option> <option>New York Jets</option> </optgroup> <optgroup label="AFC NORTH"> <option>Baltimore Ravens</option> <option>Cincinnati Bengals</option> <option>Cleveland Browns</option> <option>Pittsburgh Steelers</option> </optgroup> <optgroup label="AFC SOUTH"> <option>Houston Texans</option> <option>Indianapolis Colts</option> <option>Jacksonville Jaguars</option> <option>Tennessee Titans</option> </optgroup> <optgroup label="AFC WEST"> <option>Denver Broncos</option> <option>Kansas City Chiefs</option> <option>Oakland Raiders</option> <option>San Diego Chargers</option> </optgroup> </select> ```
This code works with multiple selects and also fixes the label when deselecting: ``` $('select').chosen().filter('[multiple]').on('change', function(event, el) { var value = el.selected ? el.selected : el.deselected; var option = $(this).find("option[value=" + value + "]"); var currentText = option.text(); var newText; if (el.selected) { var optgroupLabel = option.closest('optgroup').attr('label'); newText = optgroupLabel + ' - ' + currentText; } else { newText = currentText.split(' - ')[1]; } option.text(newText).trigger("chosen:updated"); }); ```
45,898,366
I am trying to capture the process number from this command ``` ps ax | grep catalina ``` to a variable in tcsh shell. So far, I am able to echo the process number to the screen using this script: ``` set pnum = `ps ax | grep catalina` echo $pnum | cut -d' ' -f1 ``` But when I try this to get the result of both the `grep` and the `cut` ``` set pnum = `ps ax | grep catalina | cut -d' ' -f1` ``` the result is an empty string. And this sequence ``` set pnum = `ps ax | grep catalina` set pnum = `$pnum | cut -d' ' -f1` ``` generates a `1104: Command not found.` error. What am I missing?
2017/08/26
[ "https://Stackoverflow.com/questions/45898366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618171/" ]
You can use lodash's [`_.at()`](https://lodash.com/docs/4.17.4#at) to get an array of the values in the order that you want: ```js var data = { tom: 1, jim: 2, jay: 3 }; var result1 = _.at(data, ['jim', 'tom', 'jay']); var result2 = _.at(data, ['jay', 'tom', 'jim']); console.log("['jim', 'tom', 'jay'] -> ", JSON.stringify(result1)); console.log("['jay', 'tom', 'jim'] -> ", JSON.stringify(result2)); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> ```
``` function SortByKeyArray(obj, key_arr) { return key_arr.map(k => obj[k]); } ``` Or ``` let SortByKeyArray = (obj, keys) => keys.map(k => obj[k]); ``` Which is more friendly to me.
1,123,131
The number of ways in which we can form a 8 letter word from the letters of the word `DAUGHTER` such that all vowels are never occur together is My approach: As they are 5 consonants(DGHTR) and 3 vowels(AUE) we can arrange 5 consonants in `5!` ways. $$\*D\*G\*H\*T\*R\*$$ Now 6 empty slots can be filled with either all vowels separately `(A,U,E)`, which can be done in $\binom{6}{3}\times3!$ ways or 6 empty slots can be filled with a vowel and 2 vowel occurring together `(A,UE or U,AE or E,AU)` which can be done in $\binom{6}{2}\times2!+\binom{6}{2}\times2!+\binom{6}{2}\times2!=3\times\binom{6}{2}\times2!$ Summing up all the possibilities = $5!\times(\binom{6}{3}\times3!+3\times\binom{6}{2}\times2!)=25200$ But answer is given as `36000`, What possibility I missed out.
2015/01/28
[ "https://math.stackexchange.com/questions/1123131", "https://math.stackexchange.com", "https://math.stackexchange.com/users/125258/" ]
You haven't included the possibility of permuting e.g. the `U` and `E` in `UE` when they're together (and the same in the other two cases). When this is included, your method works: $$5! \times \left(\binom{6}{3} \times 3!+3 \times \binom{6}{2} \times 2! \times 2! \right)=36000.$$
You have forgotten to multiply by 2 in the last term because both the vowels that are together can be switched as well as the order of vowel placement. I think the better way to do this (As mentioned by Arthur) is to consider the complement i.e. think of (A,E,U) as a letter. Then the letters are (D,G,H,T,R,AEU) and the total number of ways of arranging them is 6!. Also (A,E,U) can be arranged in 3! ways so the complement is 6!3!. Also the total number of ways of arranging 8 letters is 8! so your answer is 8!-6!3!=36,000.
4,534,370
The time I used to develop applications on iPhone I was converting String to SHA1 with two combination: * Data * Key Now I am developing an Android application and I did not any example for how to calculate SHA1 With key. I am greatly appreciative of any guidance or help. --- *[The code that I currently use]* ``` private void convertStringToSHA1() { String sTimeStamp = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS").format(new java.util.Date()); String sStringToHash = String.format("%1$s\n%2$s", "Username",sTimeStamp); MessageDigest cript = MessageDigest.getInstance("SHA-1"); cript.reset(); cript.update(sStringToHash.getBytes("utf-8")); sStringToHash = new BigInteger(1, cript.digest()).toString(16); } ```
2010/12/26
[ "https://Stackoverflow.com/questions/4534370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488434/" ]
Try something like that: ``` private String sha1(String s, String keyString) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key); byte[] bytes = mac.doFinal(s.getBytes("UTF-8")); return new String( Base64.encodeBase64(bytes)); } ``` [SecretKeySpec](http://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/SecretKeySpec.html) docs.
Another solution would be using apache commons codec library: ``` @Grapes( @Grab(group='commons-codec', module='commons-codec', version='1.10') ) import org.apache.commons.codec.digest.HmacUtils HmacUtils.hmacSha1Hex(key.bytes, message.bytes) ```
22,396
What is the Sanskrit term for a person who is a follower of the Buddha, i.e. a "Buddhist"? Things I tried: I searched online but couldn't find anything. I looked in the only Sanskrit I have access to, which is The Student's Sanskrit English Dictionary by Vaman Shivram Apte. It has a term in it, but the Devanagari is so small, I can't make out the letters. It looks like the term is "buddhupasaka" or "buddhupasakra", and it is defined as "a worshipper of Buddha".
2017/08/30
[ "https://buddhism.stackexchange.com/questions/22396", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/12009/" ]
The Sanskrit term for Buddhist is *bauddha*. This derivation is known as a "secondary derivation" (*taddhita-pratyaya*). An *-a* suffix is added, and the initial vowel is strengthened. It has the general sense of "of or relating to", and here the specific nuance of "one who follows the Buddha". Compare the more familiar word Jaina, which is the name for a follower of the "Jina", i.e. Mahavira. The word *brāhmaṇa* is derived from *brahman* via the same process.
[In pāli canon](http://www.84000.org/tipitaka/pitaka_item/pali_seek.php?text=%CA%D2%C7%A1&book=1&bookZ=45), follower is sāvaka (su+ika=follower to hear dhamma from satthā [saha+attha=philosopher who has philosophy in his mind]). Sāvaka, in pāli, is **śrāvaka**, in sanskrit. This word use in every canon. You can put "buddha" word in font of "sāvaka", buddha-sāvaka, to specify just a buddhist person. <https://www.buddhistdoor.org/tc/dictionary/details/savaka> P.s. use [this tool](http://ballwarapol.github.io/pali-editor/paliThaiRoman.html) to convert between thai and roman of the first reference link.
24,154,917
I'm fairly new to JSON parsing, I'm using the Retrofit library of Square and ran into this problem. I'm trying to parse this JSON reponse: ``` [ { "id": 3, "username": "jezer", "regid": "oiqwueoiwqueoiwqueoiwq", "url": "http:\/\/192.168.63.175:3000\/users\/3.json" }, { "id": 4, "username": "emulator", "regid": "qwoiuewqoiueoiwqueoq", "url": "http:\/\/192.168.63.175:3000\/users\/4.json" }, { "id": 7, "username": "test", "regid": "ksadqowueqiaksj", "url": "http:\/\/192.168.63.175:3000\/users\/7.json" } ] ``` Here are my models: ``` public class Contacts { public List<User> contacts; } ``` ... ``` public class User { String username; String regid; @Override public String toString(){ return(username); } } ``` my Interface: ``` public interface ContactsInterface { @GET("/users.json") void contacts(Callback<Contacts> cb); } ``` my success method: ``` @Override public void success(Contacts c, Response r) { List<String> names = new ArrayList<String>(); for (int i = 0; i < c.contacts.size(); i++) { String name = c.contacts.get(i).toString(); Log.d("Names", "" + name); names.add(name); } ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, names); mSentTo.setAdapter(spinnerAdapter); } ``` When I use it on my success method it throws the error > > Expected BEGIN\_OBJECT but was BEGIN\_ARRAY at line 1 column2 > > > What is wrong here?
2014/06/11
[ "https://Stackoverflow.com/questions/24154917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1426489/" ]
Convert it into a list. Below is the example: ``` BenchmarksListModel_v1[] benchmarksListModel = res.getBody().as(BenchmarksListModel_v1[].class); ```
Using **MPV**, in your Deserializer, put this ``` JsonObject obj = new JsonObject(); obj.add("data", json); JsonArray data = obj.getAsJsonObject().getAsJsonArray("data"); ```
64,494,948
I am trying to get a multimachine network of Hyperledger Fabric running. I encountered some errors. I was able to reproduce the same errors on a single machine in the [Fabcar example](https://hyperledger-fabric.readthedocs.io/en/release-2.1/write_first_app.html) of Fabric v2.1 by changing one line in `fabric-samples/fabcar/javascript/query.js`. I changed the line ``` await gateway.connect(ccp, { wallet, identity: 'appUser', discovery: { enabled: true, asLocalhost: true } }); ``` to the line ``` await gateway.connect(ccp, { wallet, identity: 'appUser', discovery: { enabled: true, asLocalhost: false } }); ``` So I am setting `discovery.asLocalhost` to `false` instead of `true`. When I run `node query.js` in the `fabric-samples/fabcar/javascript/` directory. I get the following errors. ``` Wallet path: /home/userName/my/code/fabric-samples/fabcar/javascript/wallet 2020-10-23T06:09:56.505Z - error: [ServiceEndpoint]: Error: Failed to connect before the deadline on Committer- name: orderer.example.com:7050, url:grpcs://orderer.example.com:7050 2020-10-23T06:09:56.507Z - error: [ServiceEndpoint]: waitForReady - Failed to connect to remote gRPC server orderer.example.com:7050 url:grpcs://orderer.example.com:7050 timeout:3000 2020-10-23T06:09:56.508Z - error: [DiscoveryService]: _buildOrderer[mychannel] - Unable to connect to the discovered orderer orderer.example.com:7050 due to Error: Failed to connect before the deadline on Committer- name: orderer.example.com:7050, url:grpcs://orderer.example.com:7050 2020-10-23T06:09:59.522Z - error: [ServiceEndpoint]: Error: Failed to connect before the deadline on Endorser- name: peer0.org1.example.com:7051, url:grpcs://peer0.org1.example.com:7051 2020-10-23T06:09:59.523Z - error: [ServiceEndpoint]: waitForReady - Failed to connect to remote gRPC server peer0.org1.example.com:7051 url:grpcs://peer0.org1.example.com:7051 timeout:3000 2020-10-23T06:09:59.523Z - error: [DiscoveryService]: _buildPeer[mychannel] - Unable to connect to the discovered peer peer0.org1.example.com:7051 due to Error: Failed to connect before the deadline on Endorser- name: peer0.org1.example.com:7051, url:grpcs://peer0.org1.example.com:7051 2020-10-23T06:10:02.528Z - error: [ServiceEndpoint]: Error: Failed to connect before the deadline on Endorser- name: peer0.org2.example.com:9051, url:grpcs://peer0.org2.example.com:9051 2020-10-23T06:10:02.528Z - error: [ServiceEndpoint]: waitForReady - Failed to connect to remote gRPC server peer0.org2.example.com:9051 url:grpcs://peer0.org2.example.com:9051 timeout:3000 2020-10-23T06:10:02.529Z - error: [DiscoveryService]: _buildPeer[mychannel] - Unable to connect to the discovered peer peer0.org2.example.com:9051 due to Error: Failed to connect before the deadline on Endorser- name: peer0.org2.example.com:9051, url:grpcs://peer0.org2.example.com:9051 2020-10-23T06:10:02.564Z - error: [SingleQueryHandler]: evaluate: message=Query failed. Errors: [], stack=FabricError: Query failed. Errors: [] at SingleQueryHandler.evaluate (/home/sarva/my/code/viacomrepos/temp-fabric-samples/fabric-samples/fabcar/javascript/node_modules/fabric-network/lib/impl/query/singlequeryhandler.js:45:23) at Transaction.evaluate (/home/sarva/my/code/viacomrepos/temp-fabric-samples/fabric-samples/fabcar/javascript/node_modules/fabric-network/lib/transaction.js:287:49) at Contract.evaluateTransaction (/home/sarva/my/code/viacomrepos/temp-fabric-samples/fabric-samples/fabcar/javascript/node_modules/fabric-network/lib/contract.js:115:45) at main (/home/sarva/my/code/viacomrepos/temp-fabric-samples/fabric-samples/fabcar/javascript/query.js:46:39) at processTicksAndRejections (internal/process/task_queues.js:85:5), name=FabricError Failed to evaluate transaction: FabricError: Query failed. Errors: [] ``` I followed the instructions in the [Fabcar tutorial](https://hyperledger-fabric.readthedocs.io/en/release-2.1/write_first_app.html). Here are the steps to reproduce the error. ``` cd fabric-samples/fabcar ./startFabric.sh javascript cd javascript npm install node enrollAdmin.js node registerUser.js [Change the line in query.js] node query.js ``` If I can figure out how/where to specify the grpcs URLs, I think I can get my multimachine network to work. Any help is appreciated. More detailed error logs can be obtained by setting `export GRPC_TRACE=all` and `export GRPC_VERBOSITY=DEBUG` as suggested by [this answer](https://stackoverflow.com/questions/63286790/node-sdk-v2-gateway-cannot-connect-to-peer).
2020/10/23
[ "https://Stackoverflow.com/questions/64494948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1280647/" ]
In the single machine case your client application is running on your local machine but the nodes (peers and orderers) are running in Docker containers on your local machine, and have hostnames like `peer0.org1.example.com`. Within the Docker network the nodes can talk to each other using their hostnames, e.g. `peer0.org1.example.com`. Your client (outside the Docker network) can't talk to `peer0.org1.example.com` because that DNS name does not exist. Instead it needs to connect to localhost on ports mapped (by Docker) to/from specific hosts/ports within the Docker network. Your client application gets node endpoints in two ways: 1. Entries in its local connection profile. 2. Network topology returned by service discovery. You can set appropriate (localhost) endpoint URLs in your connection profile. However, the endpoint URLs returned by discovery will be the ones exposed within the Docker network, e.g. `peer0.org1.example.com`. To facilitate this scenario, the SDK provides the `discovery.asLocalhost` setting which, when enabled, maps all endpoint addresses returned by discovery to the same port at localhost. An alternative approach is to add entries to your local hosts file that map the node names to localhost. You should not have the `discovery.asLocalhost` setting enabled if your nodes are accessible on the real network using their configured hostnames. These hostnames must be resolvable in DNS (so for a real deployment you can't use non-resolvable addresses like `example.com`), and must match your Fabric network configuration (and server certificate details if using TLS).
For setting up the multiMachine network. The changes you have to make is on the config.json and connection.yaml ( basically connection profiles). ``` await gateway.connect(ccp, { wallet, identity: 'appUser', discovery: { enabled: true, asLocalhost: false } }); ``` The localhost Property should be set as "false" as you are going to setup a multi-host Blockchain Network. You can create an overlay network to connect to it. ``` --- name: mychannel.firstnetwork.connectionprofile x-type: "hlfv1" description: "connection profile for 2.1 network" version: "1.0" channels: mychannel: orderers: - orderer.example.com peers: peer0.org1.example.com: endorsingPeer: true chaincodeQuery: true ledgerQuery: true eventSource: true peer0.org2.example.com: endorsingPeer: true chaincodeQuery: true ledgerQuery: true eventSource: true organizations: Org1: mspid: Org1MSP peers: - peer0.org1.example.com certificateAuthorities: - ca.org1.example.com adminPrivateKey: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/8717c2e82c3c4caff76fca964bb70_sk signedCert: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/cert.pem Org2: mspid: Org2MSP peers: - peer0.org2.example.com certificateAuthorities: - ca.org2.example.com adminPrivateKey: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore/9592495c719c2e87fc4a8_sk signedCert: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts/cert.pem orderers: orderer.example.com: url: grpcs://orderer.example.com:7050 grpcOptions: ssl-target-name-override: orderer.example.com tlsCACerts: path: ./caro-blockchain-commonfiles/config/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem peers: peer0.org1.example.com: url: grpcs://peer0.org1.example.com:7051 grpcOptions: ssl-target-name-override: peer0.org1.example.com tlsCACerts: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp/cacerts/localhost-7054-ca-org1.pem peer0.org2.example.com: url: grpcs://peer0.org2.example.com:9051 grpcOptions: ssl-target-name-override: peer0.org2.example.com tlsCACerts: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/msp/cacerts/localhost-8054-ca-org2.pem certificateAuthorities: ca.org1.example.com: url: https://ca.org1.example.com:7054 httpOptions: verify: false tlsCACerts: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org1.example.com/ca/ca.org1.example.com-cert.pem registrar: - enrollId: admin enrollSecret: adminpw caName: ca-org1 ca.org2.example.com: url: https://ca.org2.example.com:8054 httpOptions: verify: false tlsCACerts: path: ./caro-blockchain-commonfiles/config/crypto-config/peerOrganizations/org2.example.com/ca/ca.org2.example.com-cert.pem registrar: - enrollId: admin enrollSecret: adminpw caName: ca-org2 ``` The URLs property here like `grpcs://peer0.org1.example.com:7051` should be changed from hostname to the IP of the other machine to VM ( `grpcs://XX.XX.XX.XX:7051`)where peer container is running.
45,219
I have a PC and a laptop. my laptop is always updated, so for updating the PC I don't want to download the packages again for my PC. What I do is copying rpm files from `/var/cache/yum/i386/17/fedora/updates/packages` to the corresponding directory of the PC. Is there a better/faster way to do this? can I say yum connect with ssh to laptop and get updated packages from there?
2012/08/10
[ "https://unix.stackexchange.com/questions/45219", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/20188/" ]
What you can certainly do is create a Yum repository containing the packages from your laptop and then point your PC to use that repository for getting packages. You can create a repository by installing `createrepo` and then calling `createrepo --database /path/to/local/repository`. See [the RedHat documentation about creating a Yum repository](https://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/sec-Creating_a_Yum_Repository.html "RedHat documentation: Creating a Yum Repository"). Once you've created a repository, you can point your Yum installation to it by creating a new file in `/etc/yum.repos.d`. Unfortunately, Yum only accepts http://, ftp://, or file:// URLs for the `baseurl` argument. So you'll either have to serve the repo over HTTP/FTP, or mount the laptop's filesystem using (for instance) [SSHFS](http://fuse.sourceforge.net/sshfs.html "SSH Filesystem").
Do you really have no Internet access on the computer, or (more likely) do you just wish to avoid downloading packages twice? If the latter, one option is to use [IntelligentMirror](https://fedorahosted.org/intelligentmirror/) for your site. It will keep a copy of packages downloaded the first time, and the other computers will pick them up from your local IntelligentMirror. It hasn't been updated in several years, however it should still work. You can also set up your own [private Fedora mirror](http://fedoraproject.org/wiki/Infrastructure/Mirroring#How_can_someone_make_a_private_mirror.3F), though this requires a bit of work. Unless you're severely bandwidth-constrained (i.e. on dialup, or paying per megabyte) it's probably not worth any of the trouble and you shouldn't bother with any of this.
19,139,066
I have the following code: ``` <html> <head> <style> div { padding:0px; } </style> <body> <div>testing123</div> <iframe src="page2.html"></iframe> </body> </html> ``` Is it possible to apply some js/css to page2.html that will change the `div { padding:0px; }` part of the parent?
2013/10/02
[ "https://Stackoverflow.com/questions/19139066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407943/" ]
you can try to put jquery code into your `Iframe` load: ``` parent.$('body').find('div').css('padding', '10px'); ``` On your html page `page2.html` put code : ``` $(document).ready(function () { parent.$('body').find('div').css('padding', '10px'); }); ```
Yes but you have to add the codes to page2.html even if on the same domain.
3,470,900
I am developing an asp.net website using typed dataset as DAL , everything works fine until today I was about to add some new functionality to my website here is the abstract : get amount from amount\_field from user\_table and calculate something then update user\_table here is my sql query for getting amount\_field in typed dataset : ``` select userId , Amount from [user] WHERE userId=@userid ``` I named this query : getUserCreditByID(@userid) and in my BLL I call this query in such this way : ``` public static int getuseramount(long id) { int amount = 0; userTableAdapters.userTableAdapter usert = new userTableAdapters.userTableAdapter(); user.userDataTable userd = usert.GetUserCreditByID(id); foreach (user.userRow R in userd) { amount = R.Amount; } usert.Dispose(); userd.Dispose(); return amount; } ``` and when I call this function I'll get this error : > > Failed to enable constraints. One or > more rows contain values violating > non-null, unique, or foreign-key > constraints. > > > but when I change the DAL's sql query into this : ``` SELECT userID, username, password, address1, address2, tel1, tel2, cell, active, email, showEmail, last_login, Amount, registerdate, websiteUrl, vote, registerIP, city, firstname, lastname FROM [user] WHERE (userID = @userid) ``` everything works fine I am dazed about this , what is the problem?
2010/08/12
[ "https://Stackoverflow.com/questions/3470900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205463/" ]
Here is my version with async callback in node.js style <https://gist.github.com/4706967> ``` // tinyxhr by Shimon Doodkin - licanse: public doamin - https://gist.github.com/4706967 // // tinyxhr("site.com/ajaxaction",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data) }); // tinyxhr("site.com/ajaxaction",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data) },'POST','value1=1&value2=2'); // tinyxhr("site.com/ajaxaction.json",function (err,data,xhr){ if (err) console.log("goterr ",err,'status='+xhr.status); console.log(data); console.log(JSON.parse(data)) },'POST',JSON.stringify({value:1}),'application/javascript'); // cb - function (err,data,XMLHttpRequestObject){ if (err) throw err; } // function tinyxhr(url,cb,method,post,contenttype) { var requestTimeout,xhr; try{ xhr = new XMLHttpRequest(); }catch(e){ try{ xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ if(console)console.log("tinyxhr: XMLHttpRequest not supported"); return null; } } requestTimeout = setTimeout(function() {xhr.abort(); cb(new Error("tinyxhr: aborted by a timeout"), "",xhr); }, 5000); xhr.onreadystatechange = function() { if (xhr.readyState != 4) return; clearTimeout(requestTimeout); cb(xhr.status != 200?new Error("tinyxhr: server respnse status is "+xhr.status):false, xhr.responseText,xhr); } xhr.open(method?method.toUpperCase():"GET", url, true); //xhr.withCredentials = true; if(!post) xhr.send(); else { xhr.setRequestHeader('Content-type', contenttype?contenttype:'application/x-www-form-urlencoded'); xhr.send(post) } } tinyxhr("/test",function (err,data,xhr){ if (err) console.log("goterr ",err); console.log(data) }); ```
You can probably use omee. Its a single file containing many frequently used javascript functions like ajax request. <https://github.com/agaase/omee/blob/master/src/omee.js> to raise an ajax request you just call omee.raiseAjaxRequest with arguments params- parameters list e.g param1=param1value&param2=param2value url - url to hit the server func- function name which is to be called back connType - GET/POST.
2,237,803
If I have a class like this: ``` public class Whatever { public void aMethod(int aParam); } ``` is there any way to know that `aMethod` uses a parameter named `aParam`, that is of type `int`?
2010/02/10
[ "https://Stackoverflow.com/questions/2237803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
The Paranamer library was created to solve this same problem. It tries to determine method names in a few different ways. If the class was compiled with debugging it can extract the information by reading the bytecode of the class. Another way is for it to inject a private static member into the bytecode of the class after it is compiled, but before it is placed in a jar. It then uses reflection to extract this information from the class at runtime. <https://github.com/paul-hammant/paranamer> I had problems using this library, but I did get it working in the end. I'm hoping to report the problems to the maintainer.
if you use the eclipse, see the bellow image to allow the compiler to store the information about method parameters [![enter image description here](https://i.stack.imgur.com/RSLra.png)](https://i.stack.imgur.com/RSLra.png)
1,372,176
I would like to calculate the following limit: ${\lim \_{n \to \infty }}\sin \left( {2\pi \sqrt {{n^2} + n} } \right)$ I am not sure if this limit exists...
2015/07/24
[ "https://math.stackexchange.com/questions/1372176", "https://math.stackexchange.com", "https://math.stackexchange.com/users/50350/" ]
Hint: Note that $$\sqrt{n^2+n}-\left(n+\frac{1}{2}\right)=\frac{\left(\sqrt{n^2+n}-\left(n+\frac{1}{2}\right)\right)\left(\sqrt{n^2+n}+\left(n+\frac{1}{2}\right)\right)}{\sqrt{n^2+n}+\left(n+\frac{1}{2}\right)}=\frac{-1/4}{\sqrt{n^2+n}+\left(n+\frac{1}{2}\right)}.$$ Thus $$\sin\left(2\pi\sqrt{n^2+n}\right)=\sin\left(2\pi n+\pi - \frac{\pi/2}{\sqrt{n^2+n}+\left(n+\frac{1}{2} \right)}\right).$$
Hint: $2\pi \sqrt {n^2 +n} = 2\pi n\sqrt {1 +1/n}.$
345,762
I have the next circuit: [![enter image description here](https://i.stack.imgur.com/B4f6T.png)](https://i.stack.imgur.com/B4f6T.png) The textbook says that the capacitor is initially charged, but the current directions was selected as in schematic, why? If capacitor is charged and "+" is on upper node then the capacitor must be a voltage source in this circuit and "iC" must go up to node. The textbook solution is: [![enter image description here](https://i.stack.imgur.com/cTDQp.png)](https://i.stack.imgur.com/cTDQp.png) Here an author derivate the result equation. But stop at a second and look. He use hard-coded iC direction. What will be if I try to derivate result myself and select the iC to "up"? The KCL will be: $$ C\*\frac {\partial v\_{C}}{\partial t} = \frac {v}{R} $$. Solving, get: $$v(t) = A\*e^{\frac{t}{R\*C}} $$ And there is no "-" in "e" power. The other current direction give another tau. I know that one task may be solved with different solutions, but anyone can't take in mind not general solutions in mind for every task. I want to see where an error and how to changing directions of currents I can get proper results with method of that textbook. --- For more clarification of my problem I redraw the schematic: [![enter image description here](https://i.stack.imgur.com/gQ1gZ.png)](https://i.stack.imgur.com/gQ1gZ.png) Now I think so: as the capacitor is charged and the external voltage source is turned off then I can think about capacitor as a voltage source with it's own stored charge and the "iC" current begin going through the circuit in one direction with "iR" and the capacitor is discharging through the resistor. The textbook recommends to write KVL with components sign equal to first achieved through loop, in my case it would be: $$ -\frac{1}{C}\*\int {i\_C}{\partial t} + i\_R\*R = 0$$ solving it I get: $$v(t) = A\*e^{\frac{t}{R\*C}} $$ Here ther is no "-" sign in exponent and that equation shows that the voltage on "R" will be increasing and stay on max. values. But it's incorrect! Where is an error? It seems to be I can't interpret a capacitor with stored voltage as an active component.
2017/12/19
[ "https://electronics.stackexchange.com/questions/345762", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/107487/" ]
With the current directions shown, the capacitor equation *must* be set up assuming the capacitor is charging, thus: \$v=\small V\_{C0}+\frac{1}{C}\large \int\small i\_C\:dt\$ ... (1) For the resistor: \$\small v=R\:i\_R \$ and, since \$\small i\_R=-i\_C\$, we may write: \$\small v=-R\:i\_C \$ ... (2) Equating (1) and (2) \$\small V\_{C0}+\frac{1}{C}\large \int\small i\_C\:dt\:=-R\:i\_C\$ Rearranging: \$ \:i\_C+\frac{1}{RC}\large \int\small i\_C\:dt\:=-\large \frac{V\_{C0}}{R}\$ Differentiating: \$\large\frac{di\_C}{dt}+\frac{1}{RC}\small i\_C=0\$ Let \$\small\tau=RC\$ and solve by integrating factor method: \$\small IF= e^{t/\tau}\$ \$i\_C\: e^{t/\tau} =\large\int\small 0\:dt+A \$ \$i\_C=A e^{-t/\tau} \$ Initial condition: at \$\small t=0\$, \$i\_C=-\frac{V\_{C0}}{R}\$, hence \$\small A=-\large\frac{V\_{C0}}{R}\$ Giving: $$i\_C=-\frac{V\_{C0}}{R} e^{-t/\tau} $$ That is, \$i\_C\$ flows in the opposite direction to that assumed.
I am currently facing this same problem (im still holding my pen ), and none of the answers are satisfying to me (maybe im too dumb for those answers) so i tried different approach. I thought it in terms of physical process, i.e., current is going to decrease via resistor so, with below fig. as reference, i is going to decrease, so i = - Cdv/dt ( or i = -v/R ) and there we have it, our missing little fella, "The Negative Sign" ![enter image description here](https://i.stack.imgur.com/LhC4u.jpg)
4,099,432
I see these threads [UNIX socket implementation for Java?](https://stackoverflow.com/questions/170600/unix-socket-implementation-for-java) and <http://forums.sun.com/thread.jspa?threadID=713266>. The second link says that Java already supports UNIX Domain Socket. If that's true what class do I need to implement from Java?. From the first link, it says that Java does not support UNIX Domain Socket. If you need UNIX Domain Socket you must use a 3rd-party library. So, which is it?
2010/11/04
[ "https://Stackoverflow.com/questions/4099432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/195457/" ]
Java cannot create or access Unix Domain Sockets without using a 3rd party (native) library. The last comment on the second link above mentions this. The first link has some good (and correct) information on it.
Netty also supports it since version 4.0.26: <https://github.com/netty/netty/pull/3344>
11,588,377
I'm running a query with joins and conflicting column names. IE: ``` results = TableA.joins(:table_b).select('table_a.id as table_a_id', 'table_b.id as table_b_id') ``` In my result, table\_a\_id and table\_b\_id are both strings. What can I do to make them integers? I feel like theres probably a way to get this to return `results[0]['table_a']['id']` and `results[0]['table_b']['id']` where both have the correct datatype, but I don't know how to do it. My primary concern is making it so I can access both columns without running a second query. Thanks!
2012/07/21
[ "https://Stackoverflow.com/questions/11588377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114855/" ]
Here's a tip: Don't. Use a real label, don't just dump the default text in the textbox. Besides, how does it save space? ``` <input type="text" name="name" value="Name*" /> Name*: <input type="text" name="name" /> ``` Doesn't make sense. --- If you must, just add `|| $name == "Name*"` in there.
As Kolink said, you can add `|| $name == "Name*"` to your `if` statement. Otherwise, this is more of a client side issue. If you are using JQuery, you could do something like this: ``` $('#name').attr("is_focused",0); $('#name').focus(function(){ if($(this).attr("is_focused")==0){ $(this).val(""); $(this).attr("is_focused",1); } }); ``` Then when the user submits the form do this check: ``` if($('#name').attr("is_focused")==0){ alert('You must enter your name'); return; } ```
16,015,656
``` #include <stdio.h> int a[100]; int main(){ printf("%d",a[5]); return 0; } ``` Does the above code always print '0' or is it compiler specific? I'm using gcc compiler and I got the output as '0'.
2013/04/15
[ "https://Stackoverflow.com/questions/16015656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2357362/" ]
"Global variables" are defined at *file scope*, outside any function. All variables that are defined at file scope and all variables that are declared with the keyword `static` have something called *static storage duration*. This means that they will be allocated in a separate part of the memory and exist throughout the whole lifetime of the program. It also means that they are guaranteed to be initialized to zero on any C compiler. From the current C standard C11 6.7.9/10: > > "... If an object that has static or thread storage duration is not initialized > explicitly, then: > > > — if it has pointer type, it is initialized to a null pointer; > > > — if it has arithmetic type, it is initialized to (positive or unsigned) zero;" > > > Practically, this means that if you initialize your global variable to a given value, it will have that value and it will be allocated in a memory segment usually referred to as `.data`. If you don't give it a value, it will be allocated in another segment called `.bss`. Globals will never be allocated on the stack.
File scope objects declared without explicit initializers are initialized by `0` by default (and to `NULL` for pointers). Non-static objects at block scope declared without explicit initializers are left uninitialized.
8,112,529
What's the difference between `NaN` and `Infinity`? When does `NaN` appear? What is it?
2011/11/13
[ "https://Stackoverflow.com/questions/8112529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754487/" ]
Usually happens when you divide 0 by 0. Read more here: <http://msdn.microsoft.com/en-us/library/system.double.nan.aspx>
NaN means "Not a number" and tells you that this variable of type double hasn't any value.
12,088,025
I'm using [EventMachine](https://github.com/eventmachine/eventmachine) and [Monetarily](https://github.com/eatenbyagrue/momentarily) to start e TCP server along with my rails application. This is started from `config/initializers/momentarily.rb`. My problem is that it starts also when I run rake tasks, like `db:migrate`. I only want it to start when when I start the HTTP server. Environments won't help, since both the server start and rake tasks are under Development environment. Is there a way of knowing that the application is running the HTTP server as opposed to anything else? Note that is not only rake tasks, the EM starts also if I run the rails console, which is again something not desirable for my case.
2012/08/23
[ "https://Stackoverflow.com/questions/12088025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105929/" ]
There's not a great way of doing this that I know of. You could copy [newrelic](https://github.com/newrelic/rpm)'s approach (check `discover_dispatcher` in [local\_environment.rb](https://github.com/newrelic/rpm/blob/master/lib/new_relic/local_environment.rb)) which basically has a list of heuristics used to detect if it is running inside passenger, thin, etc. For passenger it checks ``` defined?(::PhusionPassenger) ``` for thin it checks ``` if defined?(::Thin) && defined?(::Thin::Server) ```
``` unless File.basename($0) == "rake" && ARGV.include?("db:migrate") # you are not in rake db:migrate end ```
29,256,154
We have a web service with both WSE 3.0 endpoints and the newer WCF endpoints on .NET Framework 4.5. WCF is using `basicHttpBinding`. The problem is that the new **WCF bindings appear to be significantly slower (~3x)**. Does it use the same mechanism under the hood? I've read a lot about enabling WCF tracing. But when I enable that on production I get way to much information and don't really know how read e.g. the timeline in Microsoft Trace Viewer. I would appreciate any help * Tips for finding causes of the performance difference * Idea from a theoretical standpoint, e.g. are there any **major differences under the hood** in how WCF processes a request? * Any tools that can help to profile WCF server > > Notes: > > > * The issue exists in production; on the test servers everything goes > fine. At first we suspected that the load balancer might be a factor, > but disabling the load balancer does not change the performance at all > * The slowness could be due our application/domain layer of course. > Maybe some thread/connection pool is blocking and messages are getting > queued because of that. > > > In this case does anyone have an idea why the behaviour is so > different from WSE (which runs on the same application pool)? Did any > queue sizes/concurrent processing **default configurations** change > dramatically between WSE3.0 and WCF? > > > Is there a way to find out when this is happening? E.g. some **`perfmon` counters to watch**? In `perfmon` I just get lost choosing between the huge amount of performance counters available > > > Update ------ Here's an anonymized version of our service Web.config: ```xml <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="microsoft.web.services2" type="Microsoft.Web.Services2.Configuration.WebServicesConfiguration, Microsoft.Web.Services2, Version=2.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <system.web> <httpRuntime executionTimeout="900" maxRequestLength="10240" /> <webServices> <!--<wsdlHelpGenerator href="CustomizedWebServicePage.aspx" />--> <protocols> <add name="HttpGet" /> <add name="HttpPost" /> </protocols> <soapExtensionTypes> <add type="Microsoft.Web.Services2.WebServicesExtension, Microsoft.Web.Services2, Version=2.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="1" group="0" /> </soapExtensionTypes> </webServices> <compilation defaultLanguage="cs" debug="true" targetFramework="4.5" /> <customErrors mode="RemoteOnly" /> <!-- dev only - application pool identity is configured on real environment --> <identity impersonate="true" userName="ServiceIdentity" password="********" /> <authentication mode="Windows" /> <authorization> <allow users="*" /> <!-- Allow all users --> </authorization> <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /> <sessionState mode="InProc" cookieless="false" timeout="20" sqlConnectionString="data source=127.0.0.1;user id=someuserid;password=********;port=42424" /> <globalization requestEncoding="utf-8" responseEncoding="utf-8" /> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" /> </system.web> <microsoft.web.services2> <diagnostics> <detailedErrors enabled="true" /> </diagnostics> <policy> <cache name="policyCache.xml" /> </policy> <security> <timeToleranceInSeconds>43200</timeToleranceInSeconds> <defaultTtlInSeconds>43200</defaultTtlInSeconds> <x509 storeLocation="LocalMachine" verifyTrust="false" /> <securityTokenManager type="OurProduct.Business.Authentication.CustomUsernameTokenManager, OurProduct.Business, Version=5.0.2.11517, Culture=neutral" qname="wsse:UsernameToken" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" /> </security> <messaging> <maxRequestLength>10240</maxRequestLength> </messaging> </microsoft.web.services2> <startup> <supportedRuntime version="v2.0.50727" /> </startup> <system.serviceModel> <diagnostics wmiProviderEnabled="true"> <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" /> </diagnostics> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service behaviorConfiguration="OurServiceBehavior" name="OurProduct.Service.OurService"> <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IXXXOurService" bindingNamespace="http://localhost/XXXOurService" contract="OurProduct.ServiceContracts.XXXOurService.IXXXOurService" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="OurServiceBehavior"> <dataContractSerializer maxItemsInObjectGraph="2147483647" /> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="OurProduct.Service.Validation.CustomUserNamePasswordValidator, OurProduct.Service" /> </serviceCredentials> </behavior> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_IXXXOurService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:15:00" sendTimeout="00:15:00" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288000" maxBufferSize="524288000" transferMode="Buffered" maxReceivedMessageSize="524288000" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="524288000" maxStringContentLength="524288000" maxArrayLength="524288000" maxBytesPerRead="524288000" maxNameTableCharCount="524288000" /> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" /> <message clientCredentialType="UserName" /> </security> </binding> </basicHttpBinding> </bindings> </system.serviceModel> <runtime> <gcServer enabled="true" /> <gcConcurrent enabled="true" /> </runtime> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="10485761" /> <!-- 10 megabytes --> </requestFiltering> </security> </system.webServer> </configuration> ```
2015/03/25
[ "https://Stackoverflow.com/questions/29256154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2425482/" ]
Your WCF service configuration file does not appear to have throttling values explicitly set. You may want to use performance monitor to track the WCF resources and/or adjust the default values to make sure you are not hitting the default throttle limit. Service throttling (`serviceThrottling`) allows you to even out the load on your backend WCF servers and to enforce resource allocation. serviceThrottling behavior for backend WCF services is configured by modifying the values for the `maxConcurrentCalls`, `maxConcurrentSessions`, and `maxConcurrentInstances` parameters in the config file for the WCF service. ``` <serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="200" maxConcurrentInstances="200" /> ``` <https://msdn.microsoft.com/en-us/library/ee377061%28v=bts.70%29.aspx>
I would suggest to debug this in the following way: 1. temporarily remove all authentication and security logic from both services and see if the problem remains 2. temporarily disable any business logic and possibly simplify the schema to a single variable 3. when you say performance is slower, do you mean a single user performance or a load test? when you check a single user do you make sure the server is warm? 4. if you time the execution duration of your logic (e.g. from start to end of the your server method implementation) - is it the same? 5. remember to cancel any logging / tracing while benchmarking 6. you can try to revert wcf to [use XmlSerializer](https://msdn.microsoft.com/en-us/library/ms733901%28v=vs.110%29.aspx) instead of DataContract
139,824
Given an integer `n` as input, return a list containing `n`, repeated `n` times. For example, the program would take `5` and turn it into `[5,5,5,5,5]`. The elements need to be integers, not strings. No built-in functions that accomplish the task are allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply.
2017/08/21
[ "https://codegolf.stackexchange.com/questions/139824", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/73598/" ]
TI Basic, 10 [bytes](http://tibasicdev.wikidot.com/one-byte-tokens) =================================================================== This assumes an empty list ``` Ans→dim(L₁:L₁+Ans ``` Here's the hex, along with the code to explain the byte count: ``` 72 04 B5 5D 00 3E 5D 00 70 71 Ans → dim( L₁ : L₁ + Ans ``` How? ---- ``` Ans→dim(L₁:L₁+Ans Ans→dim(L₁ Since the list is empty, this makes L₁ a list on Ans 0's : Separator L₁+Ans Since TI-Basic vectorizes some commands, this adds Ans (basically the input here) to each element in L₁, which results in Ans for each element. ```
[V](https://github.com/DJMcMayhem/V), 5 bytes ============================================= ``` Du@"Ä ``` [Try it online!](https://tio.run/##K/v/36XUQelwy///pgA "V – Try It Online")
29,018,842
I've been using RStudio for years, and this has never happened to me before. For some reason, every time a function throws an error, RStudio goes into debug mode (I don't want it to). Even after using undebug() on a single function. ``` > undebug(http.get) Warning message: In undebug(fun) : argument is not being debugged > x = http.get(country = 'KE') http --timeout=60 get "http://foo@bar.com/observation?country=KE" > freshobs.json </dev/null Error in fromJSON(file = "freshobs.json") : unexpected character 'O' Error in el[["product_name"]] : subscript out of bounds Called from: grepl(el[["product_name"]], pattern = "json:", fixed = T) Browse[1]> Q ``` Any function I use that breaks causes debug mode to start - which is pretty annoying because it opens up a source viewer and takes you away from your code. Anybody know how to stop this functionality? This happens when the 'Use debug mode only when my code contains errors' check box in Preferences is and is not checked. Thanks!
2015/03/12
[ "https://Stackoverflow.com/questions/29018842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521469/" ]
Nothing worked for me: I had a function that when I run kept on debugging. The **solution** for me was (with caution pls): `Debug (menü) -> clear All Breakpoints ...`
I had the same issue in RStudio Cloud. It was solved by choosing a different version of R. I was using R3.6.0 and changed it to R3.5.3 (the option in in the upper right corner). It refreshed the console and the debugging stopped. And then R3.6.0 was again fine. Cheers.
2,007,666
Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code: ``` package pkg; public class LoadTest { public static void main(String[] args) { System.out.println("START"); new Child(); System.out.println("END"); } } class Parent extends Grandparent { // Instance init block { System.out.println("instance - parent"); } // Constructor public Parent() { System.out.println("constructor - parent"); } // Static init block static { System.out.println("static - parent"); } } class Grandparent { // Static init block static { System.out.println("static - grandparent"); } // Instance init block { System.out.println("instance - grandparent"); } // Constructor public Grandparent() { System.out.println("constructor - grandparent"); } } class Child extends Parent { // Constructor public Child() { System.out.println("constructor - child"); } // Static init block static { System.out.println("static - child"); } // Instance init block { System.out.println("instance - child"); } } ``` and got this output: > > START > > static - grandparent > > static - parent > > static - child > > instance - grandparent > > constructor - grandparent > > instance - parent > > constructor - parent > > instance - child > > constructor - child > > END > > > The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy. EDIT: I modified my example code by appending this to LoadTest.java: ``` class IAmAClassThatIsNeverUsed { // Constructor public IAmAClassThatIsNeverUsed() { System.out.println("constructor - IAACTINU"); } // Instance init block { System.out.println("instance - IAACTINU"); } // Static init block static { System.out.println("static - IAACTINU"); } } ``` As implied by the class name, I never referenced the new class anywhere. The new program produced the same output as the old one.
2010/01/05
[ "https://Stackoverflow.com/questions/2007666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122607/" ]
See section 12.4 and 12.5 of the [JLS version 8](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4), they go into gory detail about all of this (12.4 for static and 12.5 for instance variables). For static initialization (section 12.4): A class or interface type T will be initialized immediately before the first occurrence of any one of the following: * T is a class and an instance of T is created. * T is a class and a static method declared by T is invoked. * A static field declared by T is assigned. * A static field declared by T is used and the field is not a constant variable (§4.12.4). * T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed. (and several weasel-word clauses)
``` class A { public A() { // 2 } } class B extends A{ static char x = 'x'; // 0 char y = 'y'; // 3 public B() { // 4 } public static void main(String[] args) { new B(); // 1 } } ``` Numbers in the comment indicate the evaluation order, the smaller, the earlier. As the example showed, 1. static variable 2. main 3. constructor of superclass 4. instance variable 5. constructor
4,132,963
Ok, here is the issue: Recently I hit an problem that I was not able to use Accelerator Keys ( a.k.a [HotKey](http://en.wikipedia.org/wiki/Hotkey)s ) on Buttons inside GroupBox. Just a minute ago I found out why, but now only problem is that this reason makes me even more puzzled than before, which is that Such *button with accelerator cannot be found on Form*. Effect is that when I double click to affected buttons with double-click while in Design-time, I get error "Property and method are not compatible". `MethodName is VKPInputBtnClick`, that is actually declared as function, not as Method in Unit. What makes me puzzled is that I have not assigned `OnClick` event handler for VKPInputBtn to any Method at all! How it is possible that I can compile program and have no run-time problems ... but in Design-time double click on button has such annoying issues .... Any solution? Reinstall of IDE? Any help much appreciated ...
2010/11/09
[ "https://Stackoverflow.com/questions/4132963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132296/" ]
Try deleting the handler from the .pas file from the declaration and the implementation sections (or copy somewhere if they contain code). Then try to recreate the handler for the button. Sometimes the IDE can get out of sync and all that can be done is to reset back to a known state. If that doesnt work see if you can close the form and reopen, or remove the handler from the .dfm file.
The components work differently in design and in runtime. Double clicking on a button in desgintime creates and adds an OnClick handler. That explains why the behavior is different. Hopefully I understand your question correctly. You have a component on your form, and you are not able to assign a correct eventhandler because the automatically created eventhandler is a different type than the expected eventhandler? In that case, create your own eventhandler and assign it. You can even assign it in the OnCreate of the form. If assignment trough the dfm does not succeed.
21,919,815
I am trying to generate C# class using the JSON string from here <http://json2csharp.com/> this works fine. But I can't parse the JSON to the object generated by the website. Here is the JSON string ``` { "searchParameters":{ "key":"**********", "system":"urn:oid:.8" }, "message":" found one Person matching your search criteria.", "_links":{ "self":{ "href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.." } }, "_embedded":{ "person":[ { "details":{ "address":[ { "line":["5554519 testdr"], "city":"testland", "state":"TT", "zip":"12345", "period":{ "start":"2003-10-22T00:00:00Z", "end":"9999-12-31T23:59:59Z" } } ], "name":[ { "use":"usual", "family":["BC"], "given":["TWO"], "period":{ "start":"9999-10-22T00:00:00Z", "end":"9999-12-31T23:59:59Z" } } ], "gender":{ "code":"M", "display":"Male" }, "birthDate":"9999-02-03T00:00:00Z", "identifier":[ { "use":"unspecified", "system":"urn:oid:2.19.8", "key":"", "period":{ "start":"9999-10-22T00:00:00Z", "end":"9999-12-31T23:59:59Z" } } ], "telecom":[ { "system":"email", "value":"test@test.com", "use":"unspecified", "period":{ "start":"9999-10-22T00:00:00Z", "end":"9999-12-31T23:59:59Z" } } ], "photo":[ { "content":{ "contentType":"image/jpeg", "language":"", "data":"", "size":0, "hash":"", "title":"My Picture" } } ] }, "enrolled":true, "enrollmentSummary":{ "dateEnrolled":"9999-02-07T21:39:11.174Z", "enroller":"test Support" }, "_links":{ "self":{ "href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc" }, "unenroll":{ "href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll" }, "personLink":{ "href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink" }, "personMatch":{ "href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId=" } } } ] } } ``` Here is the code I use to convert to the object. ``` JavaScriptSerializer js = new JavaScriptSerializer(); var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM)); ``` Is there any other wat to generate the object and parse?
2014/02/20
[ "https://Stackoverflow.com/questions/21919815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578739/" ]
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters. <http://jsonlint.com/>
The following function will convert JSON into a C# class where T is the class type. ``` public static T Deserialise<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); // return obj; } } ``` You need a reference to the System.Runtime.Serialization.json namespace. The function is called in the following manner; ``` calendarList = Deserialise<GoogleCalendarList>(calendarListString); ``` calendarlist being the C# class and calendarListString the string containing the JSON.
41,307,038
I'd like a function, `is_just_started`, which behaves like the following: ``` >>> def gen(): yield 0; yield 1 >>> a = gen() >>> is_just_started(a) True >>> next(a) 0 >>> is_just_started(a) False >>> next(a) 1 >>> is_just_started(a) False >>> next(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> is_just_started(a) False ``` How can I implement this function? I looked at the `.gi_running` attribute but it appears to be used for something else. If I know the first value that needs to be sent into the generator, I can do something like this: ``` def safe_send(gen, a): try: return gen.send(a) except TypeError as e: if "just-started" in e.args[0]: gen.send(None) return gen.send(a) else: raise ``` However, this seems abhorrent.
2016/12/23
[ "https://Stackoverflow.com/questions/41307038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
This only works in Python 3.2+: ``` >>> def gen(): yield 0; yield 1 ... >>> a = gen() >>> import inspect >>> inspect.getgeneratorstate(a) 'GEN_CREATED' >>> next(a) 0 >>> inspect.getgeneratorstate(a) 'GEN_SUSPENDED' >>> next(a) 1 >>> inspect.getgeneratorstate(a) 'GEN_SUSPENDED' >>> next(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> inspect.getgeneratorstate(a) 'GEN_CLOSED' ``` So, the requested function is: ``` import inspect def is_just_started(gen): return inspect.getgeneratorstate(gen) == inspect.GEN_CREATED: ``` Out of curiosity, I looked into CPython to figure out how it was determining this... Apparently it looks at `generator.gi_frame.f_lasti` which is the "index of last attempted instruction in bytecode". If it's `-1` then it hasn't started yet. Here's a py2 version: ``` def is_just_started(gen): return gen.gi_frame is not None and gen.gi_frame.f_lasti == -1 ```
You may create a iterator and set the flag as the instance property to iterator class as: ``` class gen(object): def __init__(self, n): self.n = n self.num, self.nums = 0, [] self.is_just_started = True # Your flag def __iter__(self): return self # Python 3 compatibility def __next__(self): return self.next() def next(self): self.is_just_started = False # Reset flag with next if self.num < self.n: cur, self.num = self.num, self.num+1 return cur else: raise StopIteration() ``` And your value check function would be like: ``` def is_just_started(my_generator): return my_generator.is_just_started ``` Sample run: ``` >>> a = gen(2) >>> is_just_started(a) True >>> next(a) 0 >>> is_just_started(a) False >>> next(a) 1 >>> is_just_started(a) False >>> next(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 19, in next StopIteration ``` To know the difference between *iterator* and *generator*, check [*Difference between Python's Generators and Iterators*](https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators)
61,348,127
I have functions in my react project that fire a axios call to change a users membershipType to daily, weekly or monthly in the database. They then have to manually be changed back to expired. Is there any way I can have a "timer" function to trigger another axios call to automatically change it back to Expired after a day, week or month? Or is there a better way to go about doing this? This approach seems a little messy
2020/04/21
[ "https://Stackoverflow.com/questions/61348127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12822154/" ]
`selection` is an array of [ImageAsset](https://docs.nativescript.org/api-reference/classes/_image_asset_.imageasset), so `selected.getImage()` is obviously `undefined`. It has only `getImageAsync(...)` but that returns native image data. To create [ImageSource](https://docs.nativescript.org/ns-framework-modules/image-source#save-image-from-image-asset-to-png-file) from asset, you should use `fromAsset` method. `fileUri` is also `undefined`, there is no property as such. I'm not sure where you are picking all these from. I suggest you to refer the documentation for all valid properties and methods.
this will do it ``` function onSelectSingleTap(args) { var context = imagepickerModule.create({ mode: "single" }); if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) { permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage") .then(function () { console.log("Permissions granted!"); startSelection(context); }) .catch(function () { console.log("Uh oh, no permissions - plan B time!"); }); } else { startSelection(context); } } function startSelection(context) { context .authorize() .then(function () { return context.present(); }) .then(function (selection) { selection.forEach(function(selected) { //alert(selected.android.toString()); var file = selected.android.toString(); var url = "https://adekunletestprojects.000webhostapp.com/skog/upload.php"; var name = file.substr(file.lastIndexOf("/") + 1); //alert(name); var bghttp = require("nativescript-background-http"); var session = bghttp.session("image-upload"); var request = { url: url, method: "POST", headers: { "Content-Type": "application/octet-stream", "File-Name": name }, description: "Uploading " + name }; var task = session.uploadFile(file, request); task.on("progress", progressHandler); return task; function progressHandler(e) { var toast = Toast.makeText("uploaded " + e.currentBytes + " / " + e.totalBytes); toast.show(); } }); }).catch(function (e) { console.log(e.eventName); alert(e.message); }); } ```
27,273,853
I'm using List of Map in java but I get a trouble. I use : `Map<String, AttributeValue> item = new HashMap<String, AttributeValue>(); ArrayList<Map<String,AttributeValue>> maps = new ArrayList<Map<String,AttributeValue>>();` I use CSVReader to reading file and store values in ListOfMap ``` CSVReader reader = new CSVReader(new FileReader("data1.csv")); String [] nextLine; while ((nextLine = reader.readNext()) != null) { // nextLine[] is an array of values from the line item.clear(); item.put("Id", new AttributeValue().withN(nextLine[0])); item.put("Name", new AttributeValue().withS(nextLine[1])); System.out.println("Item:"+item); // I try printing item maps.add(item); } ``` And Result is : ``` Item:{Id={N: 0,}, Name={S: goGOv,}} Item:{Id={N: 1,}, Name={S: TBlGD,}} Item:{Id={N: 2,}, Name={S: OtXuw,}} ... Item:{Id={N: 999,}, Name={S: QAMzc,}} Item:{Id={N: 1000,}, Name={S: PumAq,}} ``` But when I print some element from this List ``` System.out.println(" "+maps.get(i)); // I tried i from 0-1000 ``` It always show only 1 ouput ``` {Id={N: 1000,}, Name={S: PumAq,}} ``` So anyone can show me where I'm wrong. Thank you,
2014/12/03
[ "https://Stackoverflow.com/questions/27273853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2845274/" ]
You are using same map to store all elements, but at start of each iteration you are calling `item.clear();` which removes previously stored elements inside map. What you should do is create new, separate map instead of reusing old one, so change ``` item.clear();//don't reuse previously filled map because it still is the same map ``` into ``` item = new HashMap<>();//use separate map ```
You keep using the same Map object. These are persistant objects. You'll have to instantiate a new HashMap() instead of calling clear() on the existing one. Otherwise you'll simply clear the HashMap inside of the List as well, because they refer to the same object.
28,363,467
I'm working with following document ``` { "_id" : 123344223, "firstName" : "gopal", "gopal" : [ { "uuid" : "123", "name" : "sugun", "sudeep" : [ { "uuid" : "add32", "name" : "ssss" }, { "uuid" : "fdg456", "name" : "gfg" } ] }, { "uuid" : "222", "name" : "kiran" } ] } ``` I want to retrieve name from the first document of array sudeep and print it in a table... here is what i have tried ``` Template.table.helpers({ ProductManager: function () { return ProductManager.findOne({_id:123344223},{gopal:{$elemMatch:{uuid:"123"}}}); } }) ``` where ProductManager is my collection and defined in common.js ``` ProductManager = new Meteor.Collection("ProductManager"); ``` Here is my template ``` <template name="table"> <table> <thead> <tr> <th>NAME</th> <th>UUID</th> </tr> </thead> <tbody> {{#each ProductManager.gopal.sudeep}} <tr> <td>{{name}}</td> <td>{{uuid}}</td> </tr> {{/each}} </tbody> </table> ``` when i tried this ``` ProductManager.findOne({_id:123344223},{gopal:{$elemMatch:{uuid:"123"}}}); ``` Iam able get this in mongo shell ``` { "_id" : 123344223, "gopal" : [ { "uuid" : "123", "name" : "sugun", "sudeep" : [ { "uuid" : "add32", "name" : "ssss" }, { "uuid" : "fdg456", "name" : "gfg" } ] } ] } ``` but cant print name and uuid of "sudeep" in the table....... plzz help me to solve this problem... Thanks in advance
2015/02/06
[ "https://Stackoverflow.com/questions/28363467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4148923/" ]
`identity` just calls `eye` so there is no difference in how the arrays are constructed. Here's the code for [`identity`](https://github.com/numpy/numpy/blob/v1.9.1/numpy/core/numeric.py#L2125): ``` def identity(n, dtype=None): from numpy import eye return eye(n, dtype=dtype) ``` As you say, the main difference is that with `eye` the diagonal can may be offset, whereas `identity` only fills the main diagonal. Since the identity matrix is such a common construct in mathematics, it seems the main advantage of using `identity` is for its name alone.
[`np.identity`](https://numpy.org/doc/stable/reference/generated/numpy.identity.html) returns a **square matrix** (special case of a 2D-array) which is an identity matrix with the main diagonal (i.e. 'k=0') as 1's and the other values as 0's. you can't change the diagonal `k` here. [`np.eye`](https://numpy.org/doc/stable/reference/generated/numpy.eye.html) returns a **2D-array**, which fills the diagonal, i.e. 'k' which can be set, with 1's and rest with 0's. So, the main advantage depends on the requirement. If you want an identity matrix, you can go for `identity` right away, or can call the `np.eye` leaving the rest to defaults. But, if you need a 1's and 0's matrix of a particular shape/size or have a control over the diagonal you can go for `eye` method. Just like how a matrix is a special case of an array, `np.identity` is a special case of `np.eye`. Additional references: * [Eye and Identity - HackerRank](https://www.hackerrank.com/challenges/np-eye-and-identity/problem)
49,518,438
There is an idiomatic approach to converting a `Pair` into a `List`: ``` Pair(a, b).toList() ``` No I am searching for the opposite process. My best approach looks like this: ``` Pair(list[0], list[1]) ``` My problem with this is that I need to make a `List` value in code first for this to work. I would love something like this: ``` listOf(a, b).toPair() ```
2018/03/27
[ "https://Stackoverflow.com/questions/49518438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6509751/" ]
You can make this extension for yourself: ``` fun <T> List<T>.toPair(): Pair<T, T> { if (this.size != 2) { throw IllegalArgumentException("List is not of length 2!") } return Pair(this[0], this[1]) } ``` The error handling is up to you, you could also return a `Pair<T, T>?` with `null` being returned in the case where the `List` is not the correct length. You could also only check that it has at least 2 elements, and not require it to have exactly 2. Usage is as you've described: ``` listOf(a, b).toPair() ```
If you're looking for an option that is chainable (for example I came across this when mapping a list of strings that I turned into a pair by splitting), I find this pattern useful: ```kotlin yourList.let{ it[0] to it[1] } // this assumes yourList always has at least 2 values ``` Here it is in context: ```kotlin val pairs: List<Pair<String,String>> = lines.map{ it.split(",").let{ it[0] to it[1] } } ```
33,955,634
I have measured some positions `pos`, e.g.: ``` library(dplyr) set.seed(8) data <- data.frame(id=LETTERS[1:5], pos=c(0,round(runif(4, 1, 10),0))) %>% arrange(pos) > data id pos 1 A 0 2 C 3 3 B 5 4 E 7 5 D 8 ``` How can I expand a data frame like `data` with every possible `pos` (0,1,2,..,n) where n would be max(data$pos) (i.e. 8 in this example). I like to get something as: ``` id pos 1 A 0 2 NA 1 3 NA 2 4 C 3 5 NA 4 6 B 5 7 NA 6 8 E 7 9 D 8 ```
2015/11/27
[ "https://Stackoverflow.com/questions/33955634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3375672/" ]
Probable reason - parent directive shares the same scope, that's why your event is propagated to all child directives. Solution - each directive should define its own scope, which prototypically inherits from parent. (`$root <-- parent <-- child`) ``` <!DOCTYPE html> <html ng-app="app"> <head> <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script> <link rel="stylesheet" href="style.css" /> <script> angular .module('app', []) .directive('parent', function() { return { scope: true, link: function(scope, element) { element.on('click', function() { scope.$broadcast('parent-event'); }); } }; }) .directive('child', function() { return { scope: true, link: function(scope) { scope.$on('parent-event', function() { console.log('child(' + scope.$id + ') caught parent event'); }); } }; }); </script> </head> <body> <div> <div parent> Parent {{ $id }} <div child>Child {{ $id }}</div> </div> <hr /> <div parent> Parent {{ $id }} <div child>Child {{ $id }}</div> </div> </div> </body> </html> ``` [Plunker](http://plnkr.co/edit/IpoiqZa9z0bttAcEoBAI?p=preview)
When you braodcast data you are doing that to all child scopes. Posible solution could be this: ``` $scope.$broadcast('customEvent', { target: ['dir1', 'dir2'], someProp: 'Sending you an Object!' // send whatever you want }); ``` and then in directive one ``` $scope.$on('customEvent', function (event, data) { if(data.target.indexOf('dir1') === -1 ) return; }); ```
17,409,755
So I have the following datasource ("/" represents tab delimited locales), and I want to get it into a JSON format. The data have no headers, and I'd like to be able to insert one for the name, the degree, the area (CEP), the phone number, the email, and the url. Not sure if this will be possible for the first column which contains multiple variables. Any recommendations on how to insert headers and then parse the first column? The csv module has the "has\_header" function, but I want to insert a header. ``` Rxxxx G. Axxxx M.A.T., xxx 561-7x0-xxx rxxxxx@xxxx.com www.txxxx.com Pxxxx D. Axxxx Ed.M. xxxxx D. xxxx Ed.M. 413-xxx-xxxx xxxx@gmail.com www.pxxxxt.com xxxxx xxxx xxxxx M.S. xxx xxx xxxxxx M.S. xxxxxx R. xxxxx M.B.A. xxxxxx xxxxxx M.A.Ed., CEP ``` [This is a similar post](https://stackoverflow.com/questions/12902497/unix-linux-add-a-header-to-a-tab-delimited-file) And I've tried: ``` echo $'name\ phone\ email\ url' | cat - IECA_supplement_output.txt > ieca_supp_output.txt ``` but this doesn't work. It merely gives me 'name\ phone...' at the tope and then the data right beneath. The header is not separated by tab.s
2013/07/01
[ "https://Stackoverflow.com/questions/17409755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849997/" ]
First make sure that delimiter is really what you think. You can check this by opening the file using openoffice or writing a python function to detect the delimiter using regular expressions (re module). Also make sure that lines are ending with "/n" or windows style (additional r). Header is nothing more than the first line. So open the file in python, read all lines. Prepend the header string (separated by **/t for tab delimiter** ) to the first line. Write the lines back to the file. That's it.
There is probably an elegant, programming method to accomplish this, but the method I used was to open the .txt file in excel using 'tab' as the separator. After I opened the file, I just typed in the column headers into the first row. Piece of cake! :)
1,965,030
I have the following bash script, that lists the current number of httpd processes, and if it is over 60, it should email me. This works 80% of the time but for some reason sometimes it emails me anyways when it is not over 60. Any ideas? ``` #!/bin/bash lines=`ps -ef|grep httpd| wc -l` if [ "$lines" -gt "60" ] then mailx -s "Over 60 httpd processes" me@me.com < /dev/null fi ```
2009/12/27
[ "https://Stackoverflow.com/questions/1965030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56952/" ]
This probably doesn't solve your issue but you could simplify things by using `pgrep` instead.
you can do it this way too, reducing the use of grep and wc to just one awk. ``` ps -eo args|awk '!/awk/&&/httpd/{++c} END{ if (c>60){ cmd="mailx -s \047Over 60\047 root" cmd | getline } }' ```
9,529,327
I have two forms on an HTML5 page. Each form has a name and an id. The second form has an h1 element, which also has a name and an id. How do I change the text of this h1 element on the second form using plain JavaScript?
2012/03/02
[ "https://Stackoverflow.com/questions/9529327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1204236/" ]
Try: ``` document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere"; ```
You can do it with regular JavaScript this way: ``` document.getElementById('h1_id').innerHTML = 'h1 content here'; ``` Here is the doc for [getElementById](https://developer.mozilla.org/fr/docs/Web/API/Document/getElementById) and the [innerHTML property](https://developer.mozilla.org/fr/docs/Web/API/Element/innertHTML). The `innerHTML` property description: > > A DOMString containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString. > > >
3,585,755
I just read this question: [Why are different case condition bodies not in different scope?](https://stackoverflow.com/questions/3585073/why-are-different-case-condition-bodies-not-in-different-scope) It's a Java question, but my question applies to both C# and Java (and any other language with this scope reducing feature). In the question, OP talks about how he knows he can manually add in `{}` to refine the scope of each case in the switch. My question is, how does this work? Does it go up the stack as if it were a method call? If so, what does it do so that it still have access to other variables declared before this scope?
2010/08/27
[ "https://Stackoverflow.com/questions/3585755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160527/" ]
All it's doing is defining another scope, it's not translated into a method call. Remember that for locals, the CLR/JVM could decide not to use stack space for them at all, it could choose to utilise processor registers. In some cases, if you'll excuse the pun, it could decide to optimise out some of the locals by virtue of them not being needed. It could even decide that it can use one register, or memory location "on the stack" for multiple variables as they're never going to overlap. Taking the example from the linked question: ``` switch(condition) { case CONDITION_ONE: { int account = 27373; } case CONDITION_TWO: { // account var not needed here } case CONDITION_THREE: { // account var not needed here } case CONDITION_FOUR: { int account = 90384; } } ``` As it stands, that code is functionally identical to: ``` int account; switch(condition) { case CONDITION_ONE: { account = 27373; } case CONDITION_TWO: { // account var not needed here } case CONDITION_THREE: { // account var not needed here } case CONDITION_FOUR: { account = 90384; } } ``` As the `account` variable is never used in multiple cases, which means it's an ideal candidate (in this simplistic example ) for using a register or a single space in memory.
> > My question is, how does this work? Does it go up the stack as if it were a method call? > > > It works just like any other pair of {} used to create a new local scope. There's no difference scopewise between this: ``` void foo() { { int a = 123; } // a is gone here { // different a float a = 12.3f; } } ``` and this: ``` void foo() { switch (123) { case 1: { int a = 123; } // a is gone here break; case 2: { // different a float a = 12.3f; } } } ``` > > If so, what does it do so that it still have access to other variables declared before this scope? > > > Blocks always have access to their outer scopes or this wouldn't work: ``` void foo() { int a = 123; if (true) { a = 345; // accessing a in outer scope } } ```
30,545,372
How can I hide both x and y axis in a bokeh plot ? I've checked and tried based on this : ``` p1= figure (... visible=None) p1.select({"type": "Axis", "visible": 0}) xaxis = Axis(plot=p1, visible = 0) ``` and like <http://docs.bokeh.org/en/latest/docs/user_guide/styling.html#axes>
2015/05/30
[ "https://Stackoverflow.com/questions/30545372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592112/" ]
Create a figure object. So, in your example the figure object is `p1`, then `p1.axis.visible = False` If you want to specify a y or x axis, then use `p1.xaxis.visible = False` or `p1.yaxis.visible = False`
Set the axes parameters in the figure object: `p1 <- figure(xaxes = FALSE, yaxes = FALSE)` or if you also want to hide the grid lines: `p1 <- figure(xgrid = FALSE, ygrid = FALSE, xaxes = FALSE, yaxes = FALSE)` Details are here: <https://hafen.github.io/rbokeh/rd.html#ly_segments>
1,897,355
I have a loop that spawns a lot of threads. These threads contains, among other things, 2 (massive) StringBuilder objects. These threads then run and do their thing. However, I noticed that after a certain amount of threads, I get strange crashes. I know this is because of these StringBuilder, because when I reduce their initial capacity, I can start a lot more threads. Now for these StringBuilders, they are create like this in the constructor of the thread object: StringBuilder a = new StringBuilder(30000); StringBuilder b = new StringBuilder(30000); The point where it generally crashes is around 550 threads, which results in a little bit more than 62MB. Combined with the rest of the program the memory in use is most likely 64MB, which I read online somewhere was the defaulf size of the JVM memory allocation pool. I don't know whether this is true or not. Now, is there something I am doing wrong, that somehow because of the design, I am allocating memory the wrong way? Or is this the only way and should I tell the JVM to increase its memory pool? Or something else entirely? Also, please do not tell me to set a lower capacity, I know these StringBuilders automatically increase their capacity when needed, but I would like to have a solution to this problem.
2009/12/13
[ "https://Stackoverflow.com/questions/1897355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Consider using a `ThreadPoolExecutor`, and set the pool size to the number of CPUs on your machine. Creating more threads than CPUs is just adding overhead. ``` ExecutorService service = Executors.newFixedThreadPool(cpuCount)) ``` Also, you can reduce memory usage by writing your strings to files instead of keeping them in-memory with `StringBuilder`s.
As Gregory said, give the jvm, some options like -Xmx. Also consider using a ThreadPool or Executor to ensure that only a given amount of threads are running simultaneously. That way the amount of memory can be kept limited without slowdown (as your processor is not capable of running 550 threads at the same time anyway). And when you're using an Executor don't create the StringBuilders in the constructor, but in the run method.
17,708,739
I've created app with "`phonegap create`" command. Then I switch to project dir and try to run it with "`phonegap local run android`" and I have next error message: > > Please install Android target 17 <...> > > > Android SDK is placed to C:\dev\sdk My PATH variable contains `C:\dev\sdk; C:\div\sdk\platforms\;C:\dev\sdk\platform-tools` I run "`android`" command from cmd and SDK Manager shows no updates or no missed sdk files. I tried create and run project with cordova cli but had same problem. What can it be?
2013/07/17
[ "https://Stackoverflow.com/questions/17708739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2461168/" ]
It seems that for latest Cordova (3.0.6), ``` cordova platform add android ``` command only recognize Android 4.2.2(API17) SDK. After I install the API17 SDK, the error was gone. Not sure if there is a cordova command option that can specify SDK version.
I had the same problem and the very most simple way to resolve it is changing the target in project.properties to 16 and try.
2,396,529
I need to create a user configurable web spider/crawler, and I'm thinking about using Scrapy. But, I can't hard-code the domains and allowed URL regex:es -- this will instead be configurable in a GUI. How do I (as simple as possible) create a spider or a set of spiders with Scrapy where the domains and allowed URL regex:es are dynamically configurable? E.g. I write the configuration to a file, and the spider reads it somehow.
2010/03/07
[ "https://Stackoverflow.com/questions/2396529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12534/" ]
**WARNING: This answer was for Scrapy v0.7, spider manager api changed a lot since then.** Override default SpiderManager class, load your custom rules from a database or somewhere else and instanciate a custom spider with your own rules/regexes and domain\_name in mybot/settings.py: ``` SPIDER_MANAGER_CLASS = 'mybot.spidermanager.MySpiderManager' ``` in mybot/spidermanager.py: ``` from mybot.spider import MyParametrizedSpider class MySpiderManager(object): loaded = True def fromdomain(self, name): start_urls, extra_domain_names, regexes = self._get_spider_info(name) return MyParametrizedSpider(name, start_urls, extra_domain_names, regexes) def close_spider(self, spider): # Put here code you want to run before spiders is closed pass def _get_spider_info(self, name): # query your backend (maybe a sqldb) using `name` as primary key, # and return start_urls, extra_domains and regexes ... return (start_urls, extra_domains, regexes) ``` and now your custom spider class, in mybot/spider.py: ``` from scrapy.spider import BaseSpider class MyParametrizedSpider(BaseSpider): def __init__(self, name, start_urls, extra_domain_names, regexes): self.domain_name = name self.start_urls = start_urls self.extra_domain_names = extra_domain_names self.regexes = regexes def parse(self, response): ... ``` Notes: * You can extend CrawlSpider too if you want to take advantage of its Rules system * To run a spider use: `./scrapy-ctl.py crawl <name>`, where `name` is passed to SpiderManager.fromdomain and is the key to retreive more spider info from the backend system * As solution overrides default SpiderManager, coding a classic spider (a python module per SPIDER) doesn't works, but, I think this is not an issue for you. More info on default spiders manager [TwistedPluginSpiderManager](http://hg.scrapy.org/scrapy/file/96eabeeccefe/scrapy/contrib/spidermanager.py)
Now it is extremely easy to configure scrapy for these purposes: 1. About the first urls to visit, you can pass it as an attribute on the spider call with `-a`, and use the `start_requests` function to setup how to start the spider 2. You don't need to setup the `allowed_domains` variable for the spiders. If you don't include that class variable, the spider will be able to allow every domain. It should end up to something like: ``` class MySpider(Spider): name = "myspider" def start_requests(self): yield Request(self.start_url, callback=self.parse) def parse(self, response): ... ``` and you should call it with: ``` scrapy crawl myspider -a start_url="http://example.com" ```