qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
40,698,535
Disclaimer: I am not going to use any other ways I have a specific requirement. All I want is to Join from posts table to the posts meta so that I can get the featured image per post. I am able to get the post via where clause post type is post and published but I don't know how to write join for MySql to get the featured image of each post
2016/11/19
[ "https://Stackoverflow.com/questions/40698535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4582545/" ]
You mention " i don't want to mix up js and jQuery on the following code" but you are actually mixing vanilla DOM APIs with jQuery methods. `.parent` and `.addClass` are jQuery functions. You can code: ``` btn.parentNode.classList.add("active"); ```
Also consider `parentElement` as an alternative to `parentNode`: ``` btn.parentElement.classList.add("active"); ```
40,698,535
Disclaimer: I am not going to use any other ways I have a specific requirement. All I want is to Join from posts table to the posts meta so that I can get the featured image per post. I am able to get the post via where clause post type is post and published but I don't know how to write join for MySql to get the featured image of each post
2016/11/19
[ "https://Stackoverflow.com/questions/40698535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4582545/" ]
Also consider `parentElement` as an alternative to `parentNode`: ``` btn.parentElement.classList.add("active"); ```
You need .parentNode on the element. Something like this. ``` var clickedPath = this.getElement(); clickedPath.classList.add("active"); var classes = clickedPath.getAttribute('class').match(/\d+/g) || []; buttons.forEach(function(btn) { var method = classes.indexOf(btn.getAttribute('data-date')) > -1 ? 'add' : 'remove'; btn.classList[method]('active'); btn.parentNode.classList.add("active"); }); ```
2,807
Is it true that when someone uses the word うるさい, it means that there is a feeling of *"discontent"* ? Like for example, we will take this sentence: "It will be noisy in the factory" "It will be noisy in the factory" is neutral. (no nuance of *annoyance* ) But is it true that if we translate that sentence into japanese using うるさい as a replacement for noisy, immediately we will have the nuance that the speaker is "annoyed" at the noisyness?
2011/08/23
[ "https://japanese.stackexchange.com/questions/2807", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/264/" ]
`うるさい` definitely conveys a negative attribute which you could reasonably call "annoyance". This is why in Japanese, the equivalent of "shut up!" is `「うるさい!」`. It's saying the noise you're making is annoying, and *therefor* you should "shut up". So if you say: > > 工場{こうじょう}の中{なか}はうるさい > > > ... you're definitely saying "the inside of the factory is loud" in an uncomfortable way. "Annoying," if you like. If you wanted to say it with a neutral tone: > > 工場{こうじょう}の中{なか}は音{おと}が大{おお}きい。 > > > "There is a great deal of noise inside the factory." --- On a side note, I actually think the English "noisy" is also negative. If I wanted to describe the sound in the factory without a negative connotation I'd say, "It's *loud* in the factory."
Yes. It has negative connotation. I think the English `noisy` has it as well. The neutral way of saying it in Japanese is `音が大きい`, and in English `the sound is loud`.
2,807
Is it true that when someone uses the word うるさい, it means that there is a feeling of *"discontent"* ? Like for example, we will take this sentence: "It will be noisy in the factory" "It will be noisy in the factory" is neutral. (no nuance of *annoyance* ) But is it true that if we translate that sentence into japanese using うるさい as a replacement for noisy, immediately we will have the nuance that the speaker is "annoyed" at the noisyness?
2011/08/23
[ "https://japanese.stackexchange.com/questions/2807", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/264/" ]
`うるさい` definitely conveys a negative attribute which you could reasonably call "annoyance". This is why in Japanese, the equivalent of "shut up!" is `「うるさい!」`. It's saying the noise you're making is annoying, and *therefor* you should "shut up". So if you say: > > 工場{こうじょう}の中{なか}はうるさい > > > ... you're definitely saying "the inside of the factory is loud" in an uncomfortable way. "Annoying," if you like. If you wanted to say it with a neutral tone: > > 工場{こうじょう}の中{なか}は音{おと}が大{おお}きい。 > > > "There is a great deal of noise inside the factory." --- On a side note, I actually think the English "noisy" is also negative. If I wanted to describe the sound in the factory without a negative connotation I'd say, "It's *loud* in the factory."
I think it has a negative nuance. The other day, I was walking next to a laboratory with a lot of computers. It made hell of a noise. I said "うるさいですね" as we passed by, and some people around me told me that I had just done a blatant impoliteness. I still think that it's no more impolite than saying "it's hot" during summer, but eh…
19,862,777
I have a query that takes 20 min to executed... I remember in one project we used /\*+ PARALLEL(T,8) */ or we would use the with clause and /*+ materialize \*/ and it would make the query responds time really fast withing seconds. How can I do this to this query? ``` select count(*) from ( select hdr.ACCESS_IND, hdr.SID, hdr.CLLI, hdr.DA, hdr.TAPER_CODE, hdr.CFG_TYPE as CFG_TYPE, hdr.IP_ADDR, hdr.IOS_VERSION, hdr.ADMIN_STATE, hdr.WIRE_CENTER, substr(hdr.SID_IO_PRI, 1, 8) PRI_IO_CLLI, substr(hdr.SID_IO_SEC, 1, 8) SEC_IO_CLLI, hdr.VHO_CLLI , hdr.CFG_TYPE , -- dtl.MULTIPURPOSE_IND, lkup.code3 as shelf_type from RPT_7330_HDR hdr INNER JOIN RPT_7330_DTL dtl on hdr.EID = dtl.EID INNER JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND where LKUP.CATEGORY='ACCESS_MAPPING' and hdr.DT_MODIFIED = (select DT_MODIFIED from LS_DT_MODIFIED where NAME = 'RPT_7330_HDR')) n; ``` ![Here is the explain plan](https://i.stack.imgur.com/EYm9d.png)
2013/11/08
[ "https://Stackoverflow.com/questions/19862777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2475251/" ]
Try this, might be faster: ``` select count(*) from RPT_7330_HDR hdr JOIN LS_DT_MODIFIED LS ON LS.NAME = 'RPT_7330_HDR' AND hdr.DT_MODIFIED = LS.DT_MODIFIED JOIN RPT_7330_DTL dtl on hdr.EID = dtl.EID JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND AND LKUP.CATEGORY='ACCESS_MAPPING' ``` The SQL engine can optimize JOINS to be parallel if you have the right indexes and such. It is often able to optimize joins when it can't optimize sub-queries.
``` SELECT /*+ PARALLEL */ ... ``` You do *not* want to use a magic number and you do *not* want to list any objects. A degree of parallelism of 8 is probably too high on your laptop, yet too low on your production server. If the query simply specifies `PARALLEL`, Oracle will automatically determine the DOP if it's configured for automatic parallelism. Or it will default to the number of CPUs \* threads per CPU \* number of instances. Judging by all the manuals, features, and whitepapers, Oracle has put a lot of thought into the degree of parallelism. If you're not going to benchmark it you should trust the defaults. In 11gR2, when you don't list any objects you use statement level parallelism instead of object level parallelism. There's not need to try to determine exactly which objects and access paths needs to be parallelized. If you change the query or alias names later there's no chance of the hint not working. Here's a [quick introduction to the parallel hint](http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#SQLRF51122). There's also the [Using Parallel Execution](http://docs.oracle.com/cd/E11882_01/server.112/e25523/parallel.htm#i1009828) chapter of the VLDB and Partitioning Guide.
19,862,777
I have a query that takes 20 min to executed... I remember in one project we used /\*+ PARALLEL(T,8) */ or we would use the with clause and /*+ materialize \*/ and it would make the query responds time really fast withing seconds. How can I do this to this query? ``` select count(*) from ( select hdr.ACCESS_IND, hdr.SID, hdr.CLLI, hdr.DA, hdr.TAPER_CODE, hdr.CFG_TYPE as CFG_TYPE, hdr.IP_ADDR, hdr.IOS_VERSION, hdr.ADMIN_STATE, hdr.WIRE_CENTER, substr(hdr.SID_IO_PRI, 1, 8) PRI_IO_CLLI, substr(hdr.SID_IO_SEC, 1, 8) SEC_IO_CLLI, hdr.VHO_CLLI , hdr.CFG_TYPE , -- dtl.MULTIPURPOSE_IND, lkup.code3 as shelf_type from RPT_7330_HDR hdr INNER JOIN RPT_7330_DTL dtl on hdr.EID = dtl.EID INNER JOIN CODE_LKUP2 lkup ON LKUP.CODE1 = hdr.ACCESS_IND where LKUP.CATEGORY='ACCESS_MAPPING' and hdr.DT_MODIFIED = (select DT_MODIFIED from LS_DT_MODIFIED where NAME = 'RPT_7330_HDR')) n; ``` ![Here is the explain plan](https://i.stack.imgur.com/EYm9d.png)
2013/11/08
[ "https://Stackoverflow.com/questions/19862777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2475251/" ]
If you want data then ``` SELECT /*+ PARALLEL(DTL,4) */ HDR.ACCESS_IND, HDR.SID, HDR.CLLI, HDR.DA, HDR.TAPER_CODE, HDR.CFG_TYPE AS CFG_TYPE, HDR.IP_ADDR, HDR.IOS_VERSION, HDR.ADMIN_STATE, HDR.WIRE_CENTER, SUBSTR ( HDR.SID_IO_PRI, 1, 8 ) PRI_IO_CLLI, SUBSTR ( HDR.SID_IO_SEC, 1, 8 ) SEC_IO_CLLI, HDR.VHO_CLLI, HDR.CFG_TYPE, LKUP.CODE3 AS SHELF_TYPE FROM RPT_7330_HDR HDR INNER JOIN RPT_7330_DTL DTL ON HDR.EID = DTL.EID INNER JOIN CODE_LKUP2 LKUP ON LKUP.CODE1 = HDR.ACCESS_IND INNER JOIN LS_DT_MODIFIED ON HDR.DT_MODIFIED = DT_MODIFIED WHERE LKUP.CATEGORY = 'ACCESS_MAPPING' AND NAME = 'RPT_7330_HDR'; ``` If you want count then ``` SELECT /*+ PARALLEL(DTL,4) */ COUNT (*) FROM RPT_7330_HDR HDR INNER JOIN RPT_7330_DTL DTL ON HDR.EID = DTL.EID INNER JOIN CODE_LKUP2 LKUP ON LKUP.CODE1 = HDR.ACCESS_IND INNER JOIN LS_DT_MODIFIED ON HDR.DT_MODIFIED = DT_MODIFIED WHERE LKUP.CATEGORY = 'ACCESS_MAPPING' AND NAME = 'RPT_7330_HDR'; ``` **Note:** Hint used on DTL table which is taking more cost for FTS. Number 4 means query fired on 8 CPU's parallely. Identify your pain points from query plan and decide on your hints for parallel or any other. You can also use parallel hint on multiple tables `/*+ PARALLEL(table1 4) PARALLEL(table2 4) PARALLEL(table3 4) PARALLEL(table4 4)*/` . Also This works only on Enterprise edition and not on standard edition.
``` SELECT /*+ PARALLEL */ ... ``` You do *not* want to use a magic number and you do *not* want to list any objects. A degree of parallelism of 8 is probably too high on your laptop, yet too low on your production server. If the query simply specifies `PARALLEL`, Oracle will automatically determine the DOP if it's configured for automatic parallelism. Or it will default to the number of CPUs \* threads per CPU \* number of instances. Judging by all the manuals, features, and whitepapers, Oracle has put a lot of thought into the degree of parallelism. If you're not going to benchmark it you should trust the defaults. In 11gR2, when you don't list any objects you use statement level parallelism instead of object level parallelism. There's not need to try to determine exactly which objects and access paths needs to be parallelized. If you change the query or alias names later there's no chance of the hint not working. Here's a [quick introduction to the parallel hint](http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#SQLRF51122). There's also the [Using Parallel Execution](http://docs.oracle.com/cd/E11882_01/server.112/e25523/parallel.htm#i1009828) chapter of the VLDB and Partitioning Guide.
50,685,507
I want to seed R's internal `unif_rand()` in a multithreaded environment. The code below generates a 2-column matrix of uniform random numbers within 2 threads. The results are interesting. ``` struct mtRunif: public RcppParallel::Worker { int Nrow; // number of rows in matrix. double *v; // point to the 0th element of the 0th column. void operator() (std::size_t st, std::size_t end) { // st = 0 in the 0th thread, 1 in the 1st thread. double *vst = v + st * Nrow; for(int i = 0; i < Nrow; ++i) { vst[i] = unif_rand(); } } mtRunif(int Nrow, double *v): Nrow(Nrow), v(v) { RcppParallel::parallelFor(0, 2, *this); } }; // [[Rcpp::export]] NumericMatrix testSeeding(int sampleSize) { NumericMatrix rst(sampleSize, 2); mtRunif(sampleSize, &*rst.begin()); return rst; } /***R N = 100 set.seed(42); tmp = testSeeding(N) set.seed(42); tmp2 = testSeeding(N) # see if sequences are identical range(tmp[, 1] - tmp2[, 1]); range(tmp[, 2] - tmp2[, 2]) # [1] 0 0 # [1] 0 0 N = 1000 set.seed(42); tmp = testSeeding(N) set.seed(42); tmp2 = testSeeding(N) range(tmp[, 1] - tmp2[, 1]); range(tmp[, 2] - tmp2[, 2]) # [1] -0.9655154 0.8989870 # [1] -0.969356 0.963239 */ ``` The results suggest `set.seed()` controls the randomness in all threads for small sample sizes? Initially I expected `set.seed()` would be effective in no more than 1 thread. I do not want to exploit the conclusion because it could be absolutely wrong. On the other hand, is there a seeding function for `unif_rand()` akin to `std::srand()` for `std::rand()`? Thank you!
2018/06/04
[ "https://Stackoverflow.com/questions/50685507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961927/" ]
After advertising [dqrng](https://cran.r-project.org/package=dqrng) in the comments I realized that I had not written any documentation on how to use the RNGs from that package for parallel usage. So I started a [new vignette](https://cran.r-project.org/web/packages/dqrng/vignettes/parallel.html), that will be part of the next release. Here one of the examples, which is quite similar to what you were trying to do: ``` #include <Rcpp.h> // [[Rcpp::depends(dqrng)]] #include <pcg_random.hpp> #include <dqrng_distribution.h> // [[Rcpp::depends(RcppParallel)]] #include <RcppParallel.h> // [[Rcpp::plugins(cpp11)]] struct RandomFill : public RcppParallel::Worker { RcppParallel::RMatrix<double> output; uint64_t seed; dqrng::normal_distribution dist{0.0, 1.0}; RandomFill(Rcpp::NumericMatrix output, const uint64_t seed) : output(output), seed(seed) {}; void operator()(std::size_t begin, std::size_t end) { pcg64 rng(seed, end); // ctor with seed and stream id auto gen = std::bind(dist, rng); std::generate(output.begin() + begin * output.nrow(), output.begin() + end * output.nrow(), std::ref(gen)); } }; // [[Rcpp::export]] Rcpp::NumericMatrix parallel_random_matrix(const int n, const int m, const int ncores) { Rcpp::NumericMatrix res(n, m); RandomFill randomFill(res, 42); RcppParallel::parallelFor(0, m, randomFill, m/ncores + 1); return res; } /*** R res <- parallel_random_matrix(1e6, 8, 4) head(res) */ ``` Result: ``` > res <- parallel_random_matrix(1e6, 8, 4) > head(res) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 0.7114429 -0.19759808 -0.47149983 0.6046378 -0.3709571 -0.8089533 0.8185977 0.49010575 [2,] 0.8721661 -0.47654248 1.10411136 -1.6290995 -1.3276661 -0.2585322 -1.2437521 0.90325167 [3,] -1.4959624 0.61068373 -0.54343828 -0.4623555 -1.1779352 -2.8068283 -0.4341252 1.74490995 [4,] 0.5087201 -0.05175746 0.19007581 -0.7869679 0.9672267 -0.5009787 -0.5283977 1.42487290 [5,] -0.8191448 -0.77348120 -0.03458304 0.7243224 1.0594094 -0.6951184 -0.5456669 0.00894037 [6,] 1.2289518 -2.33539762 0.40222707 -2.3346460 -0.5796549 -0.3092356 2.8961294 0.16773085 ``` BTW, please do not sue `std::rand()`. If you want to use the standard library, then please use something like [`std::mt19937`](http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine) from [`random`](http://en.cppreference.com/w/cpp/numeric/random) with C++11.
In short: you can't do this with R for R-internal reasons, and that has been documented extensively. There are also statistical issues about RNGs and streams. So you most likely want to look into "streaming RNGs" suitable for drawing from multiple threads. There are some on CRAN * [doRNG](https://cran.r-project.org/package=doRNG) * [rstream](https://cran.r-project.org/package=rstream) * [rlecuyer](https://cran.r-project.org/package=rlecuyer) * [sitmo](https://cran.r-project.org/package=sitmo) as well as the older [sprng](https://cloud.r-project.org/web/packages/rsprng/) that is no longer on CRAN.
13,323,370
I'm importing a font with CSS. However, it does not seem to work in IE. I don't know why. Here's my CSS code: ``` @font-face { font-family: 'bello'; src: url('../fonts/bello.eot?'); src: url('../fonts/bello.eot?#iefix') format('embedded-opentype'), url('../fonts/bello.woff') format('woff'), url('../fonts/bello.ttf') format('truetype'), url('../fonts/bello.svg#bello') format('svg'); font-weight: normal; font-style: normal; } .bello { font-family: "bello", Verdana, Tahoma; } ``` I've added .eot, .svg, .woff, .ttf and .otf to the folder fonts. It displays correctly in all browsers except IE. To create the .eot file I used this site: <http://www.kirsle.net/wizards/ttf2eot.cgi>. I have no idea why it's not working. Any help would be great. Thanks!
2012/11/10
[ "https://Stackoverflow.com/questions/13323370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/559962/" ]
solved the problem, it was not problem of the eot file. It seems IE has a problem finding the .eot file if the family name is different as the full name of the font. In my case font name was bello-script and font family was bello. Changed both of them and everything worked fine.
I was experiencing a similar issue. As with the other response it didn't appear to be a problem with the .eot file but rather with the font-family value length. Changing the @font-face and references of: ``` font-family: Titillium Web Extra Light Italic ``` To: ``` font-family: Titillium Web Light Italic ``` Fixed it for me. Always expect IE to fall over for absolutely any reason...
20,647
I am currently programming, but I messed up my code. What is the best way to clean this? buttonUitvoeren\_Click\_1: ``` private void buttonUitvoeren_Click_1(object sender, EventArgs e) { buttonNoodstop.Enabled = true; buttonPauze.Enabled = true; buttonUitvoeren.Enabled = false; // Orderlijst uitvoeren en meteen nieuwe status wegschrijven wanneer order klaar is if (orderLijst.Count > 0) { // tussen orders kijken of er gespoeld moet worden eerste beker for (int t = 0; t < orderLijst.Count; t++) { // kijk naar laatste beker in huidige en eerste in volgende om te kijken of er gespoeld moet worden if (t > 0 && t < orderLijst.Count) { if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur != orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur) { orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true; orderLijst[t + 1].Spoelingen++; orderLijst[t + 1].Tijd += 40; } // refresh listview met nieuwe tijd en spoelingen refreshList(); } // ordernummer setten zodat deze gebruikt kan worden in pauze methode currentorder = orderLijst[t].OrderNummer; // zolang order nog niet klaar is while (orderLijst[t].OrderStatus != "Klaar") { // ga alle bekers in de order af for (int i = 0; i < orderLijst[t].BekerList.Count; i++) { // spoelen van beker if (orderLijst[t].BekerList[i].Spoelen == true && orderLijst[t].BekerList[i].Gespoeld == false) { // nieuwe beker aanmaken met 0 % kleur Beker beker = new Beker(0); thread = new Thread(() => newAanvoerband.Beweeg(new Beker(0))); thread.Start(); while (beker.Klaar == false && thread.IsAlive == true) { // Blijf acties uitvoeren in huidige thread(Form) Application.DoEvents(); // Abort thread wanneer spoelen klaar is of wanneer noodstop actief wordt if (noodstop == true || beker.Klaar == true) { // afhankelijk van welke waar is de label setten thread.Abort(); if (noodstop == true) { // zorgen dat hij uit de loop springt t = orderLijst.Count + 1; i = orderLijst[t].BekerList.Count + 1; addToLogListView("Noodstop is geactiveerd op order:" + orderLijst[t].OrderNummer); } if (beker.Klaar == true) { addToLogListView("Er is succesvol gespoeld"); } } } } // "normale" uitvoer van beker , met mengverhouding etc while (orderLijst[t].BekerList[i].Klaar == false && noodstop == false) { thread = new Thread(() => newAanvoerband.Beweeg(orderLijst[t].BekerList[i])); thread.Start(); while (thread.IsAlive == true && noodstop == false) { // Blijf acties uitvoeren in huidige thread(Form) Application.DoEvents(); // Abort thread wanneer beker klaar is of wanneer noodstop actief wordt if (orderLijst[t].BekerList[i].Klaar == true || noodstop == true) { thread.Abort(); if (noodstop == true) { // zorgen dat hij uit de loop springt t = orderLijst.Count + 1; i = orderLijst[t].BekerList.Count + 1; addToLogListView("Order:" + orderLijst[t].OrderNummer + " is beeindigt"); } else if (orderLijst[t].BekerList[i].Klaar == true) { if (orderLijst[t].BekerList[i].Gespoeld == false && orderLijst[t].BekerList[i].Klaar == true) { addToLogListView("Beker " + i + " is gevult"); } } } else if (pauzestand == true) { addToLogListView("Order:" + orderLijst[t].OrderNummer + " is gepauzeerd"); } else if (pauzestand == false && noodstop == false && orderLijst[t].BekerList[i].Klaar == false) { timer.Tick += new EventHandler(timer_Tick); timer.Start(); } // Zolang de uitvoer nog bezig is en noodstop niet geactiveert is } } } // einde bekerlijst addToLogListView("Order:" + orderLijst[t].OrderNummer + " is met succes afgerond"); orderLijst[t].OrderStatus = "Klaar"; // Als de status klaar is , schrijf nieuwe status naar textfile if (noodstop == false && orderLijst[t].OrderStatus == "Klaar") { // Leeg orders.txt try { File.WriteAllText(filesOrdersOrderstxt, String.Empty); } catch (Exception ex) { addToLogListView("Error while emptying:" + ex.Message); } // Schrijf de orders in orderLijst naar Orders.txt try { StreamWriter sw = File.AppendText(filesOrdersOrderstxt); refreshList(); foreach (ListViewItem writeorder in orderListView.Items) { sw.WriteLine(writeorder.SubItems[0].Text + seperator + writeorder.SubItems[1].Text); } sw.Close(); } catch (Exception ex) { addToLogListView("Error while writing:" + ex.Message); } // Wanneer het programma klaar is met uitvoeren mag er weer uitgevoerd worden buttonUitvoeren.Enabled = true; } } } // einde orderlijst addToLogListView("Alle " + orderLijst.Count.ToString() + " orders zijn klaar."); timer.Stop(); } // Als er geen orders ingevoerd zijn else { buttonNoodstop.Enabled = false; buttonPauze.Enabled = false; buttonUitvoeren.Enabled = true; addToLogListView("Er zijn geen orders ingevoerd"); } } ```
2013/01/17
[ "https://codereview.stackexchange.com/questions/20647", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/21235/" ]
I would start by trying to extract methods from your code. My general rule of thumb is that a method should be small enough to fit on the screen without having to scroll up or down. Here is an example: ``` if (t > 0 && t < orderLijst.Count) { if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur != orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur) { orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true; orderLijst[t + 1].Spoelingen++; orderLijst[t + 1].Tijd += 40; } // refresh listview met nieuwe tijd en spoelingen refreshList(); } ``` Could become: ``` private void ProcessOrderIfInRange(int t) { if (t <= 0 || t >= orderLijst.Count) { return; } if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur != orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur) { orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true; orderLijst[t + 1].Spoelingen++; orderLijst[t + 1].Tijd += 40; } refreshList(); } ``` and in your main method: ``` for (int t = 0; t < orderLijst.Count; t++) { ProcessOrderIfInRange(t); // ... ``` I also find you are using too many comments (from what I can read of them). For example, when I see a method `refreshList()`, I know that is probably going to refresh a list. a comment like `// refresh listview met nieuwe tijd en spoelingen` is unnecessary. One thing though, you might want to rename `refreshList()` to something which explains it a bit better, i.e. `RefreshListViewWithUpdatedData()` I also noticed you are not following C# standards. In C# method names start with a capital: `RefreshList()` (Pascal Case), local variable names start with a low case letter (Camel). I'd suggest you read [Microsoft's Page](http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/f75d6cb4-084f-4f2a-95c0-6d7f1b67c978) on casing. I also find you have WAY to many nested if statements. Things get really confusing when you start trying to figure out the code path. Using the same method extraction I mentioned above, you should be able to totally eliminate the nested ifs by pulling them out. ``` if (a) { if (b) { // Do something } else { // Do something } } else { if (c) { // Do something } else { // Do something } } ``` Should be changed into ``` if (a) { ProcessB(); } else { ProcessC(); } ``` where ``` private void ProcessB() { if (b) { // Do something } else { // Do something } } private void ProcessC() { if (c) { // Do something } else { // Do something } } ``` Of course ProcessB() and ProcessC() could be changed to return something if required. These suggestions are a start, try them out, see what you come up with and repost, your code.
I see a problem in here: ``` for (int t = 0; t < orderLijst.Count; t++) { // kijk naar laatste beker in huidige en eerste in volgende om te kijken of er gespoeld moet worden if (t > 0 && t < orderLijst.Count) { if (orderLijst[t].BekerList[(orderLijst[t].BekerList.Count - 1)].PercentageKleur != orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].PercentageKleur) { orderLijst[t + 1].BekerList[(orderLijst[t + 1].BekerList.Count - 1)].Spoelen = true; orderLijst[t + 1].Spoelingen++; orderLijst[t + 1].Tijd += 40; } // refresh listview met nieuwe tijd en spoelingen refreshList(); } ``` In this for loop you already declare that t will be less than orderLijst.Count so there is no need for checking it in if statement. Also, in this if statement you are using t>0, shich means that you will skip first element of orderLijst, and I suppose that it shouldn't be that way. To sum it up, I would avoid this line: ``` if (t > 0 && t < orderLijst.Count) ``` And if you really need t to have value larger than 0 in this part of code, you can leave only ``` if(t > 0) ``` Hope this helps.
33,326,940
I have a array like ``` var abc = ["mon","Thu","Fri","Tue","Wed","Sun","Sat"] ``` So next I want these days in order like ``` ["mon","Tue","Wed","Thu","Fri","Sat","Sun"] ``` Is there any inbuilt functions or any logic for it?
2015/10/25
[ "https://Stackoverflow.com/questions/33326940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3101792/" ]
The callback function doesn't sort itself. It just needs to compare any two items that are passed to it. So you have to write the logic that translates strings starting with 'translate' come before strings starting with 'rotate'. ```js // Very simple, rudimentary function to translate a type to number. Improve at will. function typeIndex(x) { if (x.indexOf('translate') > -1) return 0; if (x.indexOf('rotate') > -1) return 1; if (x.indexOf('skew') > -1) return 2; if (x.indexOf('scale') > -1) return 3; return 1000; // Unknown } var p = ['skewX', 'rotateY', 'rotateZ', 'translateY', 'scale', 'rotateX', 'ordered skewing']; // Sort array using callback; p.sort(function(a, b){ // First compare the difference based on type. var result = typeIndex(a) - typeIndex(b); // If the difference is 0, they are of the same type. Compare the whole string. if (result == 0) result = a.localeCompare(b); return result; }); console.log(p); ```
The sort function can be based on the words you want to sort on in sequence, provided they have unique sequences of characters: ```js var p = ['skewX', 'translateY', 'scale', 'rotateX']; p.sort(function(a, b) { var order = 'transrotaskewscal'; return order.indexOf(a.slice(0,4)) - order.indexOf(b.slice(0,4)); }); document.write(p); ```
68,955,883
I want to color my ridgeline plot with gradient fill colors depending on the height of the area instead of depending on the X axis. It would be somthing like this: ``` library(ggplot2) library(ggridges) ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`, fill = stat(x))) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01) + scale_fill_viridis_c(name = "Temp. [F]", option = "C") + labs(title = 'Temperatures in Lincoln NE') ``` [![enter image description here](https://i.stack.imgur.com/nzzyX.png)](https://i.stack.imgur.com/nzzyX.png) But here instead of fill the gradient according to the x axis I'm looking to use the same vertical gradient for all the curves so the highest the curve, the darkest the color. So the peaks would have a darker color while near the baseline would be lighter. PD:my plot I use `geom_ridgeline()` instead of `geom_density_ridges_gradient()` but I think this example is more clear to illustrate the problem. And also have negative values. PD2:I know there is a similar question "solved" [here](https://stackoverflow.com/questions/58525699/how-can-i-add-a-vertical-colour-gradient-to-a-ridgeplot-in-ggridges). But is obsolete, since if you check the github from the suggested package there is an [issue](https://github.com/VictimOfMaths/DeathsOfDespair/issues/1) stating that the function needed doesn't work because is based on another deprecated function.
2021/08/27
[ "https://Stackoverflow.com/questions/68955883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768667/" ]
The [linked answer](https://stackoverflow.com/questions/58525699/how-can-i-add-a-vertical-colour-gradient-to-a-ridgeplot-in-ggridges) is still valid, provided you bypass the `encode_pattern_params_as_hex_colour()` function and create the pattern gradient yourself (via `svgpatternsimple::create_pattern_gradient()`): ```r library(tidyverse) devtools::install_github("coolbutuseless/devout") devtools::install_github("coolbutuseless/devoutsvg") devtools::install_github("coolbutuseless/minisvg") devtools::install_github("coolbutuseless/poissoned") devtools::install_github("coolbutuseless/svgpatternsimple") library(svgpatternsimple) library(ggridges) gradient_pattern <- svgpatternsimple::create_pattern_gradient( id = "p1", # HTML/SVG id to assign to this pattern angle = 90, # Direction of the gradient colour1 = viridis::viridis(1, direction = -1), # Starting colour colour2 = viridis::viridis(1) # Final colour ) my_pattern_list <- list( `#000001` = list(fill = gradient_pattern) ) devoutsvg::svgout(filename = "test.svg", pattern_list = my_pattern_list) ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`)) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01, fill = '#000001') + labs(title = 'Temperatures in Lincoln NE') dev.off() ``` [![example_1.png](https://i.stack.imgur.com/IsA7l.png)](https://i.stack.imgur.com/IsA7l.png)
You want to color the ridges according to the `density` of the individual traces, so you have to get access to that statistic. Fortunately, `ggridges` allows that with the `stat='density'` option and the `..density..` input to the asthetic. The code: ``` ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`, fill = ..density.., height=..density..)) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01, stat='density') + scale_fill_viridis_c(name = "Temp. [F]", option = "C") + labs(title = 'Temperatures in Lincoln NE') ``` Yields: [![enter image description here](https://i.stack.imgur.com/9nRwK.png)](https://i.stack.imgur.com/9nRwK.png)
68,955,883
I want to color my ridgeline plot with gradient fill colors depending on the height of the area instead of depending on the X axis. It would be somthing like this: ``` library(ggplot2) library(ggridges) ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`, fill = stat(x))) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01) + scale_fill_viridis_c(name = "Temp. [F]", option = "C") + labs(title = 'Temperatures in Lincoln NE') ``` [![enter image description here](https://i.stack.imgur.com/nzzyX.png)](https://i.stack.imgur.com/nzzyX.png) But here instead of fill the gradient according to the x axis I'm looking to use the same vertical gradient for all the curves so the highest the curve, the darkest the color. So the peaks would have a darker color while near the baseline would be lighter. PD:my plot I use `geom_ridgeline()` instead of `geom_density_ridges_gradient()` but I think this example is more clear to illustrate the problem. And also have negative values. PD2:I know there is a similar question "solved" [here](https://stackoverflow.com/questions/58525699/how-can-i-add-a-vertical-colour-gradient-to-a-ridgeplot-in-ggridges). But is obsolete, since if you check the github from the suggested package there is an [issue](https://github.com/VictimOfMaths/DeathsOfDespair/issues/1) stating that the function needed doesn't work because is based on another deprecated function.
2021/08/27
[ "https://Stackoverflow.com/questions/68955883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768667/" ]
An option often overlooked by people is that you can pretty much draw anything in ggplot2 as long as you can express it in polygons. The downside is that it is a lot more work. The following approach mimics my answer given [here](https://stackoverflow.com/a/64695516/11374827) but adapted a little bit to work more consistently for multiple densities. It abandons the {ggridges} approach completely. The function below can be used to slice up an arbitrary polygon along the y-position. ```r library(ggplot2) library(ggridges) library(polyclip) fade_polygon <- function(x, y, yseq = seq(min(y), max(y), length.out = 100)) { poly <- data.frame(x = x, y = y) # Create bounding-box edges xlim <- range(poly$x) + c(-1, 1) # Pair y-edges grad <- cbind(head(yseq, -1), tail(yseq, -1)) # Add vertical ID grad <- cbind(grad, seq_len(nrow(grad))) # Slice up the polygon grad <- apply(grad, 1, function(range) { # Create bounding box bbox <- data.frame(x = c(xlim, rev(xlim)), y = c(range[1], range[1:2], range[2])) # Do actual slicing slice <- polyclip::polyclip(poly, bbox) # Format as data.frame for (i in seq_along(slice)) { slice[[i]] <- data.frame( x = slice[[i]]$x, y = slice[[i]]$y, value = range[3], id = c(1, rep(0, length(slice[[i]]$x) - 1)) ) } slice <- do.call(rbind, slice) }) # Combine slices grad <- do.call(rbind, grad) # Create IDs grad$id <- cumsum(grad$id) return(grad) } ``` Next, we need to calculate densities manually for every month and apply the function above for each one of those densities. ```r # Split by month and calculate densities densities <- split(lincoln_weather, lincoln_weather$Month) densities <- lapply(densities, function(df) { dens <- density(df$`Mean Temperature [F]`) data.frame(x = dens$x, y = dens$y) }) # Extract x/y positions x <- lapply(densities, `[[`, "x") y <- lapply(densities, `[[`, "y") # Make sequence to max density ymax <- max(unlist(y)) yseq <- seq(0, ymax, length.out = 100) # 100 can be any large enough number # Apply function to all densities polygons <- mapply(fade_polygon, x = x, y = y, yseq = list(yseq), SIMPLIFY = FALSE) ``` Next, we need to add the information about Months back into the data. ```r # Count number of observations in each of the polygons rows <- vapply(polygons, nrow, integer(1)) # Combine all of the polygons polygons <- do.call(rbind, polygons) # Assign month information polygons$month_id <- rep(seq_along(rows), rows) ``` Lastly we plot these polygons with vanilla ggplot2. The `(y / ymax) * scale` does a similar scaling to what ggridges does and adding the `month_id` offsets each month from oneanother. ```r scale <- 3 ggplot(polygons, aes(x, (y / ymax) * scale + month_id, fill = value, group = interaction(month_id, id))) + geom_polygon(aes(colour = after_scale(fill)), size = 0.3) + scale_y_continuous( name = "Month", breaks = seq_along(rows), labels = names(rows) ) + scale_fill_viridis_c() ``` ![](https://i.imgur.com/q5f01os.png) Created on 2021-09-12 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
You want to color the ridges according to the `density` of the individual traces, so you have to get access to that statistic. Fortunately, `ggridges` allows that with the `stat='density'` option and the `..density..` input to the asthetic. The code: ``` ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`, fill = ..density.., height=..density..)) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01, stat='density') + scale_fill_viridis_c(name = "Temp. [F]", option = "C") + labs(title = 'Temperatures in Lincoln NE') ``` Yields: [![enter image description here](https://i.stack.imgur.com/9nRwK.png)](https://i.stack.imgur.com/9nRwK.png)
68,955,883
I want to color my ridgeline plot with gradient fill colors depending on the height of the area instead of depending on the X axis. It would be somthing like this: ``` library(ggplot2) library(ggridges) ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`, fill = stat(x))) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01) + scale_fill_viridis_c(name = "Temp. [F]", option = "C") + labs(title = 'Temperatures in Lincoln NE') ``` [![enter image description here](https://i.stack.imgur.com/nzzyX.png)](https://i.stack.imgur.com/nzzyX.png) But here instead of fill the gradient according to the x axis I'm looking to use the same vertical gradient for all the curves so the highest the curve, the darkest the color. So the peaks would have a darker color while near the baseline would be lighter. PD:my plot I use `geom_ridgeline()` instead of `geom_density_ridges_gradient()` but I think this example is more clear to illustrate the problem. And also have negative values. PD2:I know there is a similar question "solved" [here](https://stackoverflow.com/questions/58525699/how-can-i-add-a-vertical-colour-gradient-to-a-ridgeplot-in-ggridges). But is obsolete, since if you check the github from the suggested package there is an [issue](https://github.com/VictimOfMaths/DeathsOfDespair/issues/1) stating that the function needed doesn't work because is based on another deprecated function.
2021/08/27
[ "https://Stackoverflow.com/questions/68955883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4768667/" ]
An option often overlooked by people is that you can pretty much draw anything in ggplot2 as long as you can express it in polygons. The downside is that it is a lot more work. The following approach mimics my answer given [here](https://stackoverflow.com/a/64695516/11374827) but adapted a little bit to work more consistently for multiple densities. It abandons the {ggridges} approach completely. The function below can be used to slice up an arbitrary polygon along the y-position. ```r library(ggplot2) library(ggridges) library(polyclip) fade_polygon <- function(x, y, yseq = seq(min(y), max(y), length.out = 100)) { poly <- data.frame(x = x, y = y) # Create bounding-box edges xlim <- range(poly$x) + c(-1, 1) # Pair y-edges grad <- cbind(head(yseq, -1), tail(yseq, -1)) # Add vertical ID grad <- cbind(grad, seq_len(nrow(grad))) # Slice up the polygon grad <- apply(grad, 1, function(range) { # Create bounding box bbox <- data.frame(x = c(xlim, rev(xlim)), y = c(range[1], range[1:2], range[2])) # Do actual slicing slice <- polyclip::polyclip(poly, bbox) # Format as data.frame for (i in seq_along(slice)) { slice[[i]] <- data.frame( x = slice[[i]]$x, y = slice[[i]]$y, value = range[3], id = c(1, rep(0, length(slice[[i]]$x) - 1)) ) } slice <- do.call(rbind, slice) }) # Combine slices grad <- do.call(rbind, grad) # Create IDs grad$id <- cumsum(grad$id) return(grad) } ``` Next, we need to calculate densities manually for every month and apply the function above for each one of those densities. ```r # Split by month and calculate densities densities <- split(lincoln_weather, lincoln_weather$Month) densities <- lapply(densities, function(df) { dens <- density(df$`Mean Temperature [F]`) data.frame(x = dens$x, y = dens$y) }) # Extract x/y positions x <- lapply(densities, `[[`, "x") y <- lapply(densities, `[[`, "y") # Make sequence to max density ymax <- max(unlist(y)) yseq <- seq(0, ymax, length.out = 100) # 100 can be any large enough number # Apply function to all densities polygons <- mapply(fade_polygon, x = x, y = y, yseq = list(yseq), SIMPLIFY = FALSE) ``` Next, we need to add the information about Months back into the data. ```r # Count number of observations in each of the polygons rows <- vapply(polygons, nrow, integer(1)) # Combine all of the polygons polygons <- do.call(rbind, polygons) # Assign month information polygons$month_id <- rep(seq_along(rows), rows) ``` Lastly we plot these polygons with vanilla ggplot2. The `(y / ymax) * scale` does a similar scaling to what ggridges does and adding the `month_id` offsets each month from oneanother. ```r scale <- 3 ggplot(polygons, aes(x, (y / ymax) * scale + month_id, fill = value, group = interaction(month_id, id))) + geom_polygon(aes(colour = after_scale(fill)), size = 0.3) + scale_y_continuous( name = "Month", breaks = seq_along(rows), labels = names(rows) ) + scale_fill_viridis_c() ``` ![](https://i.imgur.com/q5f01os.png) Created on 2021-09-12 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
The [linked answer](https://stackoverflow.com/questions/58525699/how-can-i-add-a-vertical-colour-gradient-to-a-ridgeplot-in-ggridges) is still valid, provided you bypass the `encode_pattern_params_as_hex_colour()` function and create the pattern gradient yourself (via `svgpatternsimple::create_pattern_gradient()`): ```r library(tidyverse) devtools::install_github("coolbutuseless/devout") devtools::install_github("coolbutuseless/devoutsvg") devtools::install_github("coolbutuseless/minisvg") devtools::install_github("coolbutuseless/poissoned") devtools::install_github("coolbutuseless/svgpatternsimple") library(svgpatternsimple) library(ggridges) gradient_pattern <- svgpatternsimple::create_pattern_gradient( id = "p1", # HTML/SVG id to assign to this pattern angle = 90, # Direction of the gradient colour1 = viridis::viridis(1, direction = -1), # Starting colour colour2 = viridis::viridis(1) # Final colour ) my_pattern_list <- list( `#000001` = list(fill = gradient_pattern) ) devoutsvg::svgout(filename = "test.svg", pattern_list = my_pattern_list) ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = `Month`)) + geom_density_ridges_gradient(scale = 3, size = 0.3, rel_min_height = 0.01, fill = '#000001') + labs(title = 'Temperatures in Lincoln NE') dev.off() ``` [![example_1.png](https://i.stack.imgur.com/IsA7l.png)](https://i.stack.imgur.com/IsA7l.png)
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
If your app is a server, and you need to test if it's listening, you can use ``` netstat -ltpn ``` The meaning of the switches: * -l for "listening", that is, server sockets only * -t for "tcp only"; note that you may need udp, then use -u * -p for "program": show which process opened which socket * -n for "numeric": IPs are OK, don't spend time on looking up hostnames Run it as root (e.g. with sudo) to get process info on sockets opened by the root's processes. This is for UNIX/Linux. Please specify the system you're using to get more precise answers.
There is a nice util at SysInternals called TCPView.exe <http://live.sysinternals.com/Tcpview.exe> That shows all connections and process IDs
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
If your app is a server, and you need to test if it's listening, you can use ``` netstat -ltpn ``` The meaning of the switches: * -l for "listening", that is, server sockets only * -t for "tcp only"; note that you may need udp, then use -u * -p for "program": show which process opened which socket * -n for "numeric": IPs are OK, don't spend time on looking up hostnames Run it as root (e.g. with sudo) to get process info on sockets opened by the root's processes. This is for UNIX/Linux. Please specify the system you're using to get more precise answers.
Inside a Servlet you can ask the HttpRequest object how it was invoked including the port and hostname. There is no standard API for a servlet interrogating the container.
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That's not a lot of information to go on, but if your app is a general purpose TCP server and you're really not sure whether it's running or not, or on what port, try: ``` netstat -an -p tcp ``` (This is a UNIX/Linux/OS X command... not sure what the Windows equivalent is but it will be similar) This will show you all listening sockets on your machine and the IP address/port on which they are listening. One of them may be your app.
if you're using tcp\ip or udp fport should fit your needs [link text](http://www.foundstone.com/us/resources/proddesc/fport.htm)
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
There is a nice util at SysInternals called TCPView.exe <http://live.sysinternals.com/Tcpview.exe> That shows all connections and process IDs
Inside a Servlet you can ask the HttpRequest object how it was invoked including the port and hostname. There is no standard API for a servlet interrogating the container.
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That's not a lot of information to go on, but if your app is a general purpose TCP server and you're really not sure whether it's running or not, or on what port, try: ``` netstat -an -p tcp ``` (This is a UNIX/Linux/OS X command... not sure what the Windows equivalent is but it will be similar) This will show you all listening sockets on your machine and the IP address/port on which they are listening. One of them may be your app.
If your app is a server, and you need to test if it's listening, you can use ``` netstat -ltpn ``` The meaning of the switches: * -l for "listening", that is, server sockets only * -t for "tcp only"; note that you may need udp, then use -u * -p for "program": show which process opened which socket * -n for "numeric": IPs are OK, don't spend time on looking up hostnames Run it as root (e.g. with sudo) to get process info on sockets opened by the root's processes. This is for UNIX/Linux. Please specify the system you're using to get more precise answers.
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
What port did you *tell* it to run on? (You're going to have to give us more details about exactly what you/your program are/is doing for us to be able to give you a more helpful answer than the above.)
if you're using tcp\ip or udp fport should fit your needs [link text](http://www.foundstone.com/us/resources/proddesc/fport.htm)
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That's not a lot of information to go on, but if your app is a general purpose TCP server and you're really not sure whether it's running or not, or on what port, try: ``` netstat -an -p tcp ``` (This is a UNIX/Linux/OS X command... not sure what the Windows equivalent is but it will be similar) This will show you all listening sockets on your machine and the IP address/port on which they are listening. One of them may be your app.
Inside a Servlet you can ask the HttpRequest object how it was invoked including the port and hostname. There is no standard API for a servlet interrogating the container.
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
That's not a lot of information to go on, but if your app is a general purpose TCP server and you're really not sure whether it's running or not, or on what port, try: ``` netstat -an -p tcp ``` (This is a UNIX/Linux/OS X command... not sure what the Windows equivalent is but it will be similar) This will show you all listening sockets on your machine and the IP address/port on which they are listening. One of them may be your app.
What port did you *tell* it to run on? (You're going to have to give us more details about exactly what you/your program are/is doing for us to be able to give you a more helpful answer than the above.)
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
What port did you *tell* it to run on? (You're going to have to give us more details about exactly what you/your program are/is doing for us to be able to give you a more helpful answer than the above.)
There is a nice util at SysInternals called TCPView.exe <http://live.sysinternals.com/Tcpview.exe> That shows all connections and process IDs
1,700,091
How can I know on which port my application is running?
2009/11/09
[ "https://Stackoverflow.com/questions/1700091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96180/" ]
There is a nice util at SysInternals called TCPView.exe <http://live.sysinternals.com/Tcpview.exe> That shows all connections and process IDs
if you're using tcp\ip or udp fport should fit your needs [link text](http://www.foundstone.com/us/resources/proddesc/fport.htm)
68,902,062
here is my code ``` def computepay(h,r): if h>40.0: OT = 1.5*float(r) p=OT else: ck = float(h)*float(r) p=ck return 'p' hrs = input("Enter Hours:") rate = input("Enter rate:") h = float(hrs) r = float(rate) p = computepay(h,r) print("Pay", p) ``` here are the parameters it needs to fill 4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you can assume the user types numbers properly. Do not name your variable sum or use the sum() function. here is the sample code given ``` def computepay(h, r): return 42.37 hrs = input("Enter Hours:") p = computepay(10, 20) print("Pay", p) ``` i've tried messing with indentation several times also removing else statement entirely can I get some advice?
2021/08/24
[ "https://Stackoverflow.com/questions/68902062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16738393/" ]
Pivot to longer format on model columns and filter only those rows that have value TRUE. Group by model and summarise wanted values. ``` shared %>% pivot_longer( cols = matches("^model[0-9]+$"), names_to = "model" ) %>% filter(value == TRUE) %>% group_by(model) %>% summarise( n_transcripts = n(), n_genes = length(unique(gene)), transcripts = str_c(unique(transcript), collapse = ";"), genes = str_c(unique(gene), collapse = ";"), ) ```
Here is my way of doing this. My approach is to use the package `dplyr` which excels at summarizing data like this. However, it works best when your data is in tidy form, meaning it is perfectly square and each column is a variable. This means that the two columns "model1" and "model2" have to become one, like this: ``` require(dplyr) shared <- shared %>% gather(., key = "model", value = "expr", -c(1:2)) ``` This puts the model1 and model2 rows on top of each other, and their resulting TRUE/FALSE are put into their own variable, which I call `expr` here. Your data does have more rows now, but it is much easier now to summarize, as we can use the `dplyr::group_by()` on the "model" column and sum the rest. First we have to fix some other things. In your data your TRUE/FALSE values are "character" values, and not logical. This means that R understands these values like names and not like yes/no, 0/1 or what ever. As we are going to count these, i change them to values like this: ``` shared[shared == "TRUE"] <- 1 shared[shared == "FALSE"] <- 0 shared$expr <- as.numeric(shared$expr) ``` Forcing the `expr` type to `as.numeric()` as i do here was needed, as it had changed to "character" again. This might be a fluke on my part. Anyways, we are now ready to summarize. If your are unfamiliar to `dplyr`, then the next part might seem confusing: ``` shared <- shared %>% .[.$expr == 1, ] %>% #Remove the rows with FALSE (0) group_by(model) %>% summarize(n_transcripts = sum(expr), #Sum all the TRUE (1) n_genes = length(unique(gene)), #Count unique genes transcripts = paste(unique(transcript), collapse = ";"), genes = paste(unique(gene), collapse = ";")) ``` A lot of things are happening here, and `dplyr` allows us to do all of them in one fell swoop. I'm using the `%>%` (pipe) operator to pass the result of each function to the next. The real meat of the this function/call is the function `summarize()` which will count/paste/tally the data for each unique value in the "model" column which in this case is "model1" and "model2"
10,195,384
I would like to be able to setup my GitHub repo to integrate with my Netbeans project. I'm a super noob at versioning in general, so this may be a pretty easy question. Any help would be appreciated! *My question is*: What do I insert as my Repository URL? Here are the options I'm given when I try to push to remote: ![Netbeans Options](https://i.stack.imgur.com/MvGSc.png)
2012/04/17
[ "https://Stackoverflow.com/questions/10195384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971592/" ]
You first need to initialize a git repository in your existing project then you can push using the ssh protocol and git@github.com:Username/repositoryname.git it should ask you for your private key file select it from .ssh in your user folder
The remote repository location refers to somewhere outside of the local repository that you would like to push to. This can be any of those protocols listed (i.e., you can "push" to a local repository on the disk, or somewhere on the internet). A popular remote repository service for git is [Github](http://github.com). Creating a Github account and using it as the remote allows you to push your changes to their server, and make use of their services associated with git. Using a remote is not necessary, however. If you want to have your source code only on your local machine, then there is no need to add remotes. In that case, use the first radio option. You may need to initialize the git repository if you haven't yet. To do that, visit the directory of your project and run `git init` (assumes you have git installed).
3,325,781
The following image has both the problem and its solution. I have a doubt in the solution, the details of which I have included below the image. [![enter image description here](https://i.stack.imgur.com/39zbP.jpg)](https://i.stack.imgur.com/39zbP.jpg) **(Assume the terms in given series are generated from a polynomial)** Here, the author has assumed $T\_n$ as an arbitrary cubic equation (Step indicated by the RED box). My doubt is, why has he assumed it as a cubic equation and not a quadratic or biquadratic equation or any other degree equation? **Please do not use Newton's forward interpolation rule as I don't know such rules.** **Please explain in simple terms and properties.** Kindly clarify my doubt.
2019/08/17
[ "https://math.stackexchange.com/questions/3325781", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
The author is assuming the original terms of the series are values from a polynomial at increasing integral values. Thus, when a sequence of differences causes all of the terms to be the same at some level $m$, the sequence $T\_n$ represents a polynomial of degree $m$. For more information, see Theorem $1$ in [Difference Tables of Sequences](http://mathonline.wikidot.com/difference-tables-of-sequences). In your case, taking the sequence of the third order differences based on those second order differences causes all of the values to be $6$. This means the original sequence represents a cubic equation. Also, although the author doesn't use this, and the linked page only hints at it, the sequence of constant values are $a\_n(n!)$ where $a\_n$ is the coefficient of the $x^n$ term. Thus, in this case, $6 = a\_3(3!) \implies a\_3 = 1$. The author could have used this to determine that $a = 1$ more directly.
(Assuming the terms in given series are generated from a polynomial) When you take the difference, you reduce the degree by $1$. As an example, for a quadratic $T\_n = n^2$, the first order differences would be in A.P: $$(n+1)^2 - n^2 = 2n+1$$ And for a cubic $T\_n = n^3$, the first order differences gives you a quadratic: $$(n+1)^3-n^3=3n^2+3n+1$$ Now if you take the difference on above quadratic, you get a sequence in A.P.
28,967,618
Is it possible for an Android Library to have its own context? The reason I ask is because I am using an Android Library that is used by multiple applications(APKs) and to store something in the database, it needs a context. If the Android Library can have it's own context, the Android Library can view all the data stored by the different applications. Thanks!
2015/03/10
[ "https://Stackoverflow.com/questions/28967618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270257/" ]
No, it is not possible for android library to have it's own context. As context is runtime property of application, hence application pass it's own context only when it is running.
Yes it is possible like Google play service, But at that time library itself work as another application may be in background process. And use of library will work as communication between two applications.
401,959
Using gzip 1.3.12 / ubuntu 64bit I am getting "No space left on device" yet there appears to be plenty of disk space remaining. ``` gunzip 03-05-2012--22-52-01.tar.gz gzip: 03-05-2012--22-52-01.tar: No space left on device ``` If you run the above gunzip twice in a row the first time it takes a while before showing the error, the second time it happens straight away. On the other hand if I use `tar` it works to start with for a certain number of files before giving errors. After the errors I can see some of the files on disk. ``` tar -zxvf 03-05-2012--22-52-01.tar.gz <snip> tar: root/backups/project_x/03-05-2012--22-52-01/data/contentstore/2012/3/29/10/11: Cannot mkdir: No space left on device tar: Exiting with failure status due to previous errors ``` Diskspace: ``` sudo du -sh /* | sort -gr | head -n 5 752M /usr 424M /var 160K /run 78M /lib 48K /tmp df -i -h Filesystem Inodes IUsed IFree IUse% Mounted on /dev/xvda1 640K 75K 566K 12% / udev 932K 381 932K 1% /dev tmpfs 934K 255 934K 1% /run none 934K 2 934K 1% /run/lock none 934K 1 934K 1% /run/shm /dev/xvdb 27M 11 27M 1% /mnt df -h --total Filesystem Size Used Avail Use% Mounted on /dev/xvda1 9.9G 6.3G 3.1G 68% / udev 3.7G 4.0K 3.7G 1% /dev tmpfs 1.5G 160K 1.5G 1% /run none 5.0M 0 5.0M 0% /run/lock none 3.7G 0 3.7G 0% /run/shm /dev/xvdb 414G 199M 393G 1% /mnt total 432G 6.5G 405G 2% sudo blkid /dev/xvda1: LABEL="cloudimg-rootfs" UUID="46e0a6b7-bb53-4d56-aba0-a2a6202d9787" TYPE="ext4" /dev/xvdb: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" TYPE="ext3" /dev/xvdc: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" SEC_TYPE="ext2" TYPE="ext3" ```
2012/06/25
[ "https://serverfault.com/questions/401959", "https://serverfault.com", "https://serverfault.com/users/4803/" ]
What is the question you are asking exactly? > > “No space left on device” > > > Would indicate that you've run out of disk space. Change the current working directory to another directory mounted on a larger partition and try again ... Also, bear in mind that `du` won't always match `df`. It is possible for files to be deleted but the handles still remain in use by an application, so `df` can show less disk space available than `du` reports.
`"No space left on device"` This error can also indicate permission issues. Check that your are executing the command as the appropriate user. Obviously `/root/` requires root permissions.
401,959
Using gzip 1.3.12 / ubuntu 64bit I am getting "No space left on device" yet there appears to be plenty of disk space remaining. ``` gunzip 03-05-2012--22-52-01.tar.gz gzip: 03-05-2012--22-52-01.tar: No space left on device ``` If you run the above gunzip twice in a row the first time it takes a while before showing the error, the second time it happens straight away. On the other hand if I use `tar` it works to start with for a certain number of files before giving errors. After the errors I can see some of the files on disk. ``` tar -zxvf 03-05-2012--22-52-01.tar.gz <snip> tar: root/backups/project_x/03-05-2012--22-52-01/data/contentstore/2012/3/29/10/11: Cannot mkdir: No space left on device tar: Exiting with failure status due to previous errors ``` Diskspace: ``` sudo du -sh /* | sort -gr | head -n 5 752M /usr 424M /var 160K /run 78M /lib 48K /tmp df -i -h Filesystem Inodes IUsed IFree IUse% Mounted on /dev/xvda1 640K 75K 566K 12% / udev 932K 381 932K 1% /dev tmpfs 934K 255 934K 1% /run none 934K 2 934K 1% /run/lock none 934K 1 934K 1% /run/shm /dev/xvdb 27M 11 27M 1% /mnt df -h --total Filesystem Size Used Avail Use% Mounted on /dev/xvda1 9.9G 6.3G 3.1G 68% / udev 3.7G 4.0K 3.7G 1% /dev tmpfs 1.5G 160K 1.5G 1% /run none 5.0M 0 5.0M 0% /run/lock none 3.7G 0 3.7G 0% /run/shm /dev/xvdb 414G 199M 393G 1% /mnt total 432G 6.5G 405G 2% sudo blkid /dev/xvda1: LABEL="cloudimg-rootfs" UUID="46e0a6b7-bb53-4d56-aba0-a2a6202d9787" TYPE="ext4" /dev/xvdb: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" TYPE="ext3" /dev/xvdc: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" SEC_TYPE="ext2" TYPE="ext3" ```
2012/06/25
[ "https://serverfault.com/questions/401959", "https://serverfault.com", "https://serverfault.com/users/4803/" ]
What is the question you are asking exactly? > > “No space left on device” > > > Would indicate that you've run out of disk space. Change the current working directory to another directory mounted on a larger partition and try again ... Also, bear in mind that `du` won't always match `df`. It is possible for files to be deleted but the handles still remain in use by an application, so `df` can show less disk space available than `du` reports.
It was permissions in my case. Anyone facing this issue must check for the file permissions first and the owner.
401,959
Using gzip 1.3.12 / ubuntu 64bit I am getting "No space left on device" yet there appears to be plenty of disk space remaining. ``` gunzip 03-05-2012--22-52-01.tar.gz gzip: 03-05-2012--22-52-01.tar: No space left on device ``` If you run the above gunzip twice in a row the first time it takes a while before showing the error, the second time it happens straight away. On the other hand if I use `tar` it works to start with for a certain number of files before giving errors. After the errors I can see some of the files on disk. ``` tar -zxvf 03-05-2012--22-52-01.tar.gz <snip> tar: root/backups/project_x/03-05-2012--22-52-01/data/contentstore/2012/3/29/10/11: Cannot mkdir: No space left on device tar: Exiting with failure status due to previous errors ``` Diskspace: ``` sudo du -sh /* | sort -gr | head -n 5 752M /usr 424M /var 160K /run 78M /lib 48K /tmp df -i -h Filesystem Inodes IUsed IFree IUse% Mounted on /dev/xvda1 640K 75K 566K 12% / udev 932K 381 932K 1% /dev tmpfs 934K 255 934K 1% /run none 934K 2 934K 1% /run/lock none 934K 1 934K 1% /run/shm /dev/xvdb 27M 11 27M 1% /mnt df -h --total Filesystem Size Used Avail Use% Mounted on /dev/xvda1 9.9G 6.3G 3.1G 68% / udev 3.7G 4.0K 3.7G 1% /dev tmpfs 1.5G 160K 1.5G 1% /run none 5.0M 0 5.0M 0% /run/lock none 3.7G 0 3.7G 0% /run/shm /dev/xvdb 414G 199M 393G 1% /mnt total 432G 6.5G 405G 2% sudo blkid /dev/xvda1: LABEL="cloudimg-rootfs" UUID="46e0a6b7-bb53-4d56-aba0-a2a6202d9787" TYPE="ext4" /dev/xvdb: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" TYPE="ext3" /dev/xvdc: UUID="a7534fe5-1538-4ebc-b553-7dfc6a37df02" SEC_TYPE="ext2" TYPE="ext3" ```
2012/06/25
[ "https://serverfault.com/questions/401959", "https://serverfault.com", "https://serverfault.com/users/4803/" ]
`"No space left on device"` This error can also indicate permission issues. Check that your are executing the command as the appropriate user. Obviously `/root/` requires root permissions.
It was permissions in my case. Anyone facing this issue must check for the file permissions first and the owner.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
The problem is that all `jest.mock` will be hoisted to the top of actual code block at compile time, which in this case is the top of the file. At this point `VocabularyEntry` is not imported. You could either put the `mock` in a `beforeAll` block in your test or use `jest.mock` like this: ``` import {shallow} from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import {VocabularyEntry} from '../../../src/model/VocabularyEntry' import vocabularyService from '../../../src/services/vocabularyService' jest.mock('../../../src/services/vocabularyService', () => jest.fn()) vocabularyService.mockImplementation(() => ({ vocabulary: [new VocabularyEntry("a", "a1")] })) ``` This will first mock the module with a simple spy and after all stuff is imported it sets the real implementation of the mock.
When implementing a `jest.fn()` in a module, which was mocked with `jest.mock`, make sure you do the following two steps: 1. The variable name should begin with `mock`. 2. If you wrote something like `coolFunction: mockCoolFunction`, make sure to change it to `coolFunction: (...args) => mockCoolFunction(...args)`. This way, Jest doesn’t need to know what `mockCoolFunction` is, as long as you haven’t run the function. For further information, I recommend [this blog post](https://blog.bam.tech/developer-news/fix-jest-mock-cannot-access-before-initialization-error).
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
You need to store your mocked component in a variable with a name prefixed by "mock". This solution is based on the Note at the end of the error message I was getting. > > Note: This is a precaution to guard against uninitialized mock > variables. If it is ensured that the mock is required lazily, variable > names prefixed with `mock` are permitted. > > > ``` import {shallow} from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import {VocabularyEntry} from '../../../src/model/VocabularyEntry' const mockVocabulary = () => new VocabularyEntry("a", "a1"); jest.mock('../../../src/services/vocabularyService', () => ({ default: mockVocabulary })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); ```
When implementing a `jest.fn()` in a module, which was mocked with `jest.mock`, make sure you do the following two steps: 1. The variable name should begin with `mock`. 2. If you wrote something like `coolFunction: mockCoolFunction`, make sure to change it to `coolFunction: (...args) => mockCoolFunction(...args)`. This way, Jest doesn’t need to know what `mockCoolFunction` is, as long as you haven’t run the function. For further information, I recommend [this blog post](https://blog.bam.tech/developer-news/fix-jest-mock-cannot-access-before-initialization-error).
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
If you are getting similar error when upgrading to newer Jest [19 to 21 in my case], you can try changing `jest.mock` to `jest.doMock`. Found this here – <https://github.com/facebook/jest/commit/6a8c7fb874790ded06f4790fdb33d8416a7284c8>
In my case this issue started after I was upgrade my react-native project to v0.61 using react-native-git-upgrade. After I have tried everything I could. I decide to clean the project and all my tests back to work. ``` # react-native-clean-project ``` However watch out when running the react-native-clean-project, it can wipe out all ios and android folder including native code, so just answer N when prompted. In my case I just selected wipe node\_modules folder.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
If you are getting similar error when upgrading to newer Jest [19 to 21 in my case], you can try changing `jest.mock` to `jest.doMock`. Found this here – <https://github.com/facebook/jest/commit/6a8c7fb874790ded06f4790fdb33d8416a7284c8>
```js jest.mock("../../../src/services/vocabularyService", () => { // eslint-disable-next-line global-require const VocabularyEntry = require("../../../src/model/VocabularyEntry"); return { vocabulary: [new VocabularyEntry("a", "a1")] }; }); ``` I think it should work with dynamic imports as well instead of `require` but didn't manage to make it work.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
The problem is that all `jest.mock` will be hoisted to the top of actual code block at compile time, which in this case is the top of the file. At this point `VocabularyEntry` is not imported. You could either put the `mock` in a `beforeAll` block in your test or use `jest.mock` like this: ``` import {shallow} from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import {VocabularyEntry} from '../../../src/model/VocabularyEntry' import vocabularyService from '../../../src/services/vocabularyService' jest.mock('../../../src/services/vocabularyService', () => jest.fn()) vocabularyService.mockImplementation(() => ({ vocabulary: [new VocabularyEntry("a", "a1")] })) ``` This will first mock the module with a simple spy and after all stuff is imported it sets the real implementation of the mock.
If you are getting similar error when upgrading to newer Jest [19 to 21 in my case], you can try changing `jest.mock` to `jest.doMock`. Found this here – <https://github.com/facebook/jest/commit/6a8c7fb874790ded06f4790fdb33d8416a7284c8>
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
If you are getting similar error when upgrading to newer Jest [19 to 21 in my case], you can try changing `jest.mock` to `jest.doMock`. Found this here – <https://github.com/facebook/jest/commit/6a8c7fb874790ded06f4790fdb33d8416a7284c8>
When implementing a `jest.fn()` in a module, which was mocked with `jest.mock`, make sure you do the following two steps: 1. The variable name should begin with `mock`. 2. If you wrote something like `coolFunction: mockCoolFunction`, make sure to change it to `coolFunction: (...args) => mockCoolFunction(...args)`. This way, Jest doesn’t need to know what `mockCoolFunction` is, as long as you haven’t run the function. For further information, I recommend [this blog post](https://blog.bam.tech/developer-news/fix-jest-mock-cannot-access-before-initialization-error).
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
```js jest.mock("../../../src/services/vocabularyService", () => { // eslint-disable-next-line global-require const VocabularyEntry = require("../../../src/model/VocabularyEntry"); return { vocabulary: [new VocabularyEntry("a", "a1")] }; }); ``` I think it should work with dynamic imports as well instead of `require` but didn't manage to make it work.
In my case this issue started after I was upgrade my react-native project to v0.61 using react-native-git-upgrade. After I have tried everything I could. I decide to clean the project and all my tests back to work. ``` # react-native-clean-project ``` However watch out when running the react-native-clean-project, it can wipe out all ios and android folder including native code, so just answer N when prompted. In my case I just selected wipe node\_modules folder.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
You need to store your mocked component in a variable with a name prefixed by "mock". This solution is based on the Note at the end of the error message I was getting. > > Note: This is a precaution to guard against uninitialized mock > variables. If it is ensured that the mock is required lazily, variable > names prefixed with `mock` are permitted. > > > ``` import {shallow} from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import {VocabularyEntry} from '../../../src/model/VocabularyEntry' const mockVocabulary = () => new VocabularyEntry("a", "a1"); jest.mock('../../../src/services/vocabularyService', () => ({ default: mockVocabulary })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); ```
```js jest.mock("../../../src/services/vocabularyService", () => { // eslint-disable-next-line global-require const VocabularyEntry = require("../../../src/model/VocabularyEntry"); return { vocabulary: [new VocabularyEntry("a", "a1")] }; }); ``` I think it should work with dynamic imports as well instead of `require` but didn't manage to make it work.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
When implementing a `jest.fn()` in a module, which was mocked with `jest.mock`, make sure you do the following two steps: 1. The variable name should begin with `mock`. 2. If you wrote something like `coolFunction: mockCoolFunction`, make sure to change it to `coolFunction: (...args) => mockCoolFunction(...args)`. This way, Jest doesn’t need to know what `mockCoolFunction` is, as long as you haven’t run the function. For further information, I recommend [this blog post](https://blog.bam.tech/developer-news/fix-jest-mock-cannot-access-before-initialization-error).
In my case this issue started after I was upgrade my react-native project to v0.61 using react-native-git-upgrade. After I have tried everything I could. I decide to clean the project and all my tests back to work. ``` # react-native-clean-project ``` However watch out when running the react-native-clean-project, it can wipe out all ios and android folder including native code, so just answer N when prompted. In my case I just selected wipe node\_modules folder.
44,649,699
I'm trying to mock a call to a service but I'm struggeling with the following message: **The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables**. I'm using babel with ES6 syntax, jest and enzyme. I have a simple component called `Vocabulary` which gets a list of `VocabularyEntry`-Objects from a `vocabularyService` and renders it. ``` import React from 'react'; import vocabularyService from '../services/vocabularyService'; export default class Vocabulary extends React.Component { render() { let rows = vocabularyService.vocabulary.map((v, i) => <tr key={ i } > <td>{ v.src }</td> <td>{ v.target }</td> </tr>); // render rows } } ``` The `vocabularyServise` ist very simple: ``` import { VocabularyEntry } from '../model/VocabularyEntry'; class VocabularyService { constructor() { this.vocabulary = [new VocabularyEntry("a", "b")]; } } export default new VocabularyService(); ``` Now I want to mock the `vocabularyService` in a test: ``` import { shallow } from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import { VocabularyEntry } from '../../../src/model/VocabularyEntry' jest.mock('../../../src/services/vocabularyService', () => ({ vocabulary: [new VocabularyEntry("a", "a1")] })); describe("Vocabulary tests", () => { test("renders the vocabulary", () => { let $component = shallow(<Vocabulary/>); // expect something }); }); ``` Running the test causes an error: Vocabulary.spec.js: babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables. Invalid variable access: VocabularyEntry. As far as I unterstood, I cannot use the VocabularyEntry because it is not declares (as jest moves the mock definition to the top of the file). Can anyone please explain how I can fix this? I saw solutions which required the references insinde the mock-call but I do not understand how I can do this with a class file.
2017/06/20
[ "https://Stackoverflow.com/questions/44649699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652967/" ]
The problem is that all `jest.mock` will be hoisted to the top of actual code block at compile time, which in this case is the top of the file. At this point `VocabularyEntry` is not imported. You could either put the `mock` in a `beforeAll` block in your test or use `jest.mock` like this: ``` import {shallow} from 'enzyme'; import React from 'react'; import Vocabulary from "../../../src/components/Vocabulary "; import {VocabularyEntry} from '../../../src/model/VocabularyEntry' import vocabularyService from '../../../src/services/vocabularyService' jest.mock('../../../src/services/vocabularyService', () => jest.fn()) vocabularyService.mockImplementation(() => ({ vocabulary: [new VocabularyEntry("a", "a1")] })) ``` This will first mock the module with a simple spy and after all stuff is imported it sets the real implementation of the mock.
In my case this issue started after I was upgrade my react-native project to v0.61 using react-native-git-upgrade. After I have tried everything I could. I decide to clean the project and all my tests back to work. ``` # react-native-clean-project ``` However watch out when running the react-native-clean-project, it can wipe out all ios and android folder including native code, so just answer N when prompted. In my case I just selected wipe node\_modules folder.
72,743,019
I am trying to bind host dir to some dir inside container and expecting changes done inside container should reflect on host. Here is the steps I have followed created /hostdir on host and run ubuntu container in privileged mode ``` [root@nhbdlin03 ~]# mkdir /hostdir [root@nhbdlin03 ~]# docker run -itd --privileged --name ubuntu -v /hostdir:/hostdir:z ubuntu 76aebded33274e95a6f569d0831aee4df27e9f200a8fd0401448239bd6f5bf80 [root@nhbdlin03 ~]# docker exec -it ubuntu bash ``` creating a container\_dir inside container ``` root@76aebded3327:/# mkdir /container_dir ``` binding the two directory (successfull) ``` root@76aebded3327:/# mount --bind /container_dir /hostdir ``` creating a file named hello.txt inside /container\_dir ``` root@76aebded3327:/# cd container_dir/ root@76aebded3327:/container_dir# touch hello.txt ``` its get reflected inside /hostdir as it is bind mount to /container\_dir ``` root@76aebded3327:/container_dir# ls /hostdir/ hello.txt ``` exit container and check on host , is the same reflected ``` root@76aebded3327:/container_dir# exit [root@nhbdlin03 ~]# ls /hostdir/ [root@nhbdlin03 ~]# ls /hostdir/ | wc -l 0 [root@nhbdlin03 ~]# ``` the content are not getting reflected. I am missing something or doing completely wrong, please help me in the right direction.
2022/06/24
[ "https://Stackoverflow.com/questions/72743019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2294755/" ]
Your bind mount made with `mount --bind /container_dir /hostdir` will override volume mount inside the container. You simply bind-mount `/container_dir` over it (same as when you mount e.g. `/boot` partition over `/boot` directory on your root filesystem); so anything you write to `/hostdir` from that point will go only to `/container_dir` inside container. What you probably want to do is to swap `mount --bind` arguments or just make `/container_dir` a symlink to `/hostdir`. Or make `/container_dir` a Docker volume directly and save the hassle.
I am able to achieve above using bind mount type and bind-propagation=shared ``` [root@nhbdlin03 ~]# docker run -itd --name ubuntu --privileged --mount type=bind,source=/hostdir,target=/hostdir,bind-propagation=shared ubuntu 2cb814f600ed261ae5e50fcdaec6b5a5a17f3d41d37be307765e20274d918a25 [root@nhbdlin03 ~]# docker exec -it ubuntu bash root@2cb814f600ed:/# mkdir /container_dir root@2cb814f600ed:/# touch /container_dir/hello root@2cb814f600ed:/# mount --bind --make-shared /container_dir /hostdir root@2cb814f600ed:/# ls /hostdir/ hello root@2cb814f600ed:/# exit exit [root@nhbdlin03 ~]# ls /hostdir/ hello ```
69,213,411
There are many questions about CORS policy in JSON. But I did not find any solution which does not need a server side change. I have no access to the server. My code is: ``` $.getJSON('https://app-prod-ws.meteoswiss-app.ch/v1/forecast?plz=800000&callback=?', function(data){}); ``` Is there any client only workaround?
2021/09/16
[ "https://Stackoverflow.com/questions/69213411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/957052/" ]
So, the purpose of CORS is to prevent a Website from accessing data it's not supposed to see. For example, a malicious Website shouldn't see anything from Facebook. Having said that, there are a few options: 1. The client can use a CORS extension to bypass CORS protection. 2. You can use a CORS proxy (not recommended) 3. You can have your server request the resource on the server side and return it to the Web browser.
The above solutions seemed too complicated to me. I found an easier one via php. I am not sure if this works in all cases but it does for mine. ``` <?php $meteoschweizData = file_get_contents("https://app-prod-ws.meteoswiss-app.ch/v1/forecast?plz=800000"); echo "const meteoschweizJSON = '" . $meteoschweizData . "';"; ?> const meteoschweizData = JSON.parse(meteoschweizJSON); ```
44,866,266
I have an Array of Objects with a structure like this: ``` [ { title: "", imagePoster: "", episodes: "", score: "", genres: ["Comedy", "Drama", ...], description: "" }, ... ] ``` I need to return an Object which contains specific value like `"Comedy"` in the `genres` Array. I've been trying a lot of ways like `for`, `filter`, `map`, `indexOf`... But, I still can't figure it out, unless I search for `["Comedy", "Drama", ...]` (i.e., the whole Array).
2017/07/01
[ "https://Stackoverflow.com/questions/44866266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7700400/" ]
You could use [`Array#find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to find the first element that satisfies the condition: ``` const search = "Comedy"; const found = array.find(obj => obj.genres.includes(search)); ``` This also uses [`Array#includes`](https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) which checks if the argument, the search keyword, exists in the `genres` array of each object. And if you needed IE support, use [`Array#indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) and check if the return value is greater than -1 instead which does exactly the same thing: ``` obj => obj.genres.indexOf(search) > -1 ``` And if you wanted to return *all* objects that have a certain genre, not just the first one, filter the array with [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) which filters the array based on a condition: ``` const search = "Comedy"; const found = array.filter(obj => obj.genres.includes(search)); ``` This will filter the array and only leave the objects that include the search keyword in their `genres` array. Again, you can swap out `includes` for the `indexOf` check, and you can always just access the first element of the filtered array if `find` is not supported on your target browsers (namely IE).
`Array.find` & `Array.includes` are your friends. There are also polyfills for non-browsers :) The most supported way would be to use `Array.filter` & `Array.indexOf` ``` function getMovieByGenre(genre) { return movies.filter(function(movie) { return movies.genres.indexOf(genre) >= 0 })[0]; } var someComedy = getMovieByGenre('Comedy'); if (someComedy) { // movie found } ``` I am using the most supported code, without polyfills and ES6 features
4,630,142
In an attempt to find another issue, my tests came up with the following bit of code. ``` public class TestPersistance { private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties"); public static final PersistenceManager pm = PMF.getPersistenceManager(); static final TestUserDataDB ud = new TestUserDataDB(); public static void main(String args[]) { TestPersistance tp = new TestPersistance(); tp.createData(); } @Test public void createData() { assertTrue("Null machined id at start", ud.machineId != null); pm.currentTransaction().begin(); try { pm.makePersistent(ud); } finally { pm.currentTransaction().commit(); } assertTrue("Null machined id at end", ud.machineId != null); } } ``` where the second assert fails. ie. my object that I am asking to be persisted is being changed by the makePersistent call. The data is being stored in the database. Any ideas? Can any one confirm this. using jdo-api-3.0.jar datanucleus-core-2.2.0-release.jar datanucleus-enhancer-2.1.3.jar datanucleus-rdbms-2.2.0-release.jar mysql-connector-java-5.1.13.jar in eclipse with MySql database. ``` @PersistenceCapable public class TestUserDataDB { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) public Long id; @Persistent public String userid = "test1"; @Persistent public String machineId = "test2"; // local userid @Persistent public long uid = 1L; @Persistent public long systemTime = 123L; public long chk = 1234L; public long createTime = System.currentTimeMillis(); public TestUserDataDB() { } @Override public String toString() { return "TestUserDataDB [chk=" + chk + ", createTime=" + createTime + ", id=" + id + ", machineId=" + machineId + ", systemTime=" + systemTime + ", uid=" + uid + ", userid=" + userid + "]"; } } ``` Properties file is ``` javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.jdo.JDOPersistenceManagerFactory datanucleus.metadata.validate=false javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver javax.jdo.option.ConnectionURL=jdbc:mysql://localhost/test javax.jdo.option.ConnectionUserName=root javax.jdo.option.ConnectionPassword=yeahRight datanucleus.autoCreateSchema=true datanucleus.validateTables=false datanucleus.validateConstraints=false ```
2011/01/07
[ "https://Stackoverflow.com/questions/4630142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468854/" ]
Why are you accessing fields directly ? Is the accessing class declared as PersistenceAware ? Well it isn't so you can't do that - use the getters. What is "ud" object state before persist ? (transient?) what is it after persist ? (hollow?) What does the log say ? Chances are that it is in hollow state and then you access a field directly and it has no value (by definition, as per the spec) ... but since you didn't bother calling the getter it hasn't a chance to retrieve the value. And you likely also don't have "RetainValues" persistent property set Suggest you familiarise yourself with the JDO spec and object lifecycle states
In some cases, it is necessary to access deserialized objects' attributes directly (i.e. if using GSON library for JSON serialization). In that case you can use: ``` MyClass copy = myPersistencyManager.detachCopy(myRetrievedInstance); ```
34,051,162
I'm trying to use EF6.1.3 and Visual Studio 2015 to make some simple CRUD pages, but I keep getting errors whenever I go to "Add Controller" I tried everything from reinstalling Entity Framework to reinstalling Visual Studio completely. I've created a new empty web app and tried to add a controller and I get the same crash. I originally had VS2015 before update 1 and had the same problem. I thought Update 1 would fix it but no luck. There is no error message. VS just shuts down and restarts. There is something in the event log but it doesn't seem to be too helpful: Log Name: Application Source: Application Error Date: 12/2/2015 2:00:17 PM Event ID: 1000 Task Category: (100) Level: Error Keywords: Classic User: N/A Computer: john2015.se.local Description: Faulting application name: devenv.exe, version: 14.0.24720.0, time stamp: 0x564ea97e Faulting module name: MSVCR120\_CLR0400.dll, version: 12.0.52512.0, time stamp: 0x5525ef9d Exception code: 0xc00000fd Fault offset: 0x0007e19c Faulting process id: 0x3360 Faulting application start time: 0x01d12d16201217b1 Faulting application path: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe Faulting module path: C:\WINDOWS\SYSTEM32\MSVCR120\_CLR0400.dll Report Id: 0314ac86-6bbd-49fa-a05c-bbf5724ae101 Faulting package full name: Faulting package-relative application ID: Event Xml: 1000 2 100 0x80000000000000 10130 Application john2015.se.local devenv.exe 14.0.24720.0 564ea97e MSVCR120\_CLR0400.dll 12.0.52512.0 5525ef9d c00000fd 0007e19c 3360 01d12d16201217b1 C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe C:\WINDOWS\SYSTEM32\MSVCR120\_CLR0400.dll 0314ac86-6bbd-49fa-a05c-bbf5724ae101
2015/12/02
[ "https://Stackoverflow.com/questions/34051162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339332/" ]
This helps me: 1. Close Visual Studio. 2. Open administrative cmd in folder `C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE` 3. `devenv.exe /resetsettings` 4. `devenv.exe /resetuserdata` Open Visual Studio.
I had the same issue as you after the October update. Aram's answer is the method I used to solve my issue. However, looking closely at the dump, your issue is in the MSVCR120\_CLR0400.dll basically uninstall this dll and re-install it then follow Aram's list. MSVCR120\_CLR0400.dll is a security update that resolves a vulnerability in the 4.5 and 4.5.1 that could allow elevation of privilege on a server by using a web browser that can run ASP.NET applications. [Microsoft explanation of MSVCR120\_CLR0400.dll](https://support.microsoft.com/en-us/kb/2894854#bookmark-appliestoproducts)
47,346,369
I am using pactNet to test an API which should return an array of a flexible length. If i call "myApi/items/" it should return a list of items where the consumer does not know the exact size of. So the answer should look like this: ``` [ { "id": "1", "description": "foo" }, { "id": "2", "description": "foo2" }, { "id": "3", "description": "foo3" } ] ``` or this: ``` [ { "id": "4", "description": "foo4" }, { "id": "2", "description": "foo2" } ] ``` How do I create the contract for this interaction? In the [documentation](https://docs.pact.io/documentation/matching.html) is an example in Ruby, but I cannot find the equivalent in C#. I am using pactNet version 2.1.1. Edit: Here is an example how it should look like. What I want to know is how do I declare that the body should contain an array of items with a flexible length. ``` [Test] public void GetAllItems() { //Arrange _mockProviderService .Given("There are items") .UponReceiving("A GET request to retrieve the items") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/items/", Headers = new Dictionary<string, object> { { "Accept", "application/json" } } }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary<string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = // array of items with some attributes // (somthing like: {"id": "2", "description": "foo"}) // with flexible length }); var consumer = new ItemApiClient(_mockProviderServiceBaseUri); //Act var result = consumer.GetItems(); //Assert Assert.AreEqual(true, result.Count > 0); _mockProviderService.VerifyInteractions(); data.Dispose(); } ```
2017/11/17
[ "https://Stackoverflow.com/questions/47346369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8956409/" ]
Sounds like you are looking for the MinTypeMatcher. The body part would look something like below: ``` Body = Match.MinType(new { id: "1", description: "foo" }, 1) ```
So, what if I want to Match the type of an object that has a property that is a list or array? if you do a Match.Type(new myType()) and the number of elements in the array or list property is not exactly the same, the test will fail. You will see an error like this: ``` Description of differences -------------------------------------- * Actual array is too long and should not contain a Hash at $.data.itinerary[2] ```
47,346,369
I am using pactNet to test an API which should return an array of a flexible length. If i call "myApi/items/" it should return a list of items where the consumer does not know the exact size of. So the answer should look like this: ``` [ { "id": "1", "description": "foo" }, { "id": "2", "description": "foo2" }, { "id": "3", "description": "foo3" } ] ``` or this: ``` [ { "id": "4", "description": "foo4" }, { "id": "2", "description": "foo2" } ] ``` How do I create the contract for this interaction? In the [documentation](https://docs.pact.io/documentation/matching.html) is an example in Ruby, but I cannot find the equivalent in C#. I am using pactNet version 2.1.1. Edit: Here is an example how it should look like. What I want to know is how do I declare that the body should contain an array of items with a flexible length. ``` [Test] public void GetAllItems() { //Arrange _mockProviderService .Given("There are items") .UponReceiving("A GET request to retrieve the items") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/items/", Headers = new Dictionary<string, object> { { "Accept", "application/json" } } }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary<string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = // array of items with some attributes // (somthing like: {"id": "2", "description": "foo"}) // with flexible length }); var consumer = new ItemApiClient(_mockProviderServiceBaseUri); //Act var result = consumer.GetItems(); //Assert Assert.AreEqual(true, result.Count > 0); _mockProviderService.VerifyInteractions(); data.Dispose(); } ```
2017/11/17
[ "https://Stackoverflow.com/questions/47346369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8956409/" ]
Sounds like you are looking for the MinTypeMatcher. The body part would look something like below: ``` Body = Match.MinType(new { id: "1", description: "foo" }, 1) ```
For a nested array scenario like @SlimSjakie asked, just repeat Match.MinType at the property that has array. For example, the following Person object has Address property as an array. ``` Person = Match.MinType(new { FirstName = Match.Type("string"), LastName = Match.Type("string"), Address = Match.MinType(new { Street = Match.Type("string"), Town = Match.Type("string"), State = Match.Type("string"), Postcode = Match.Type("string"), Country = Match.Type("string") }, 1) }, 1) ```
47,346,369
I am using pactNet to test an API which should return an array of a flexible length. If i call "myApi/items/" it should return a list of items where the consumer does not know the exact size of. So the answer should look like this: ``` [ { "id": "1", "description": "foo" }, { "id": "2", "description": "foo2" }, { "id": "3", "description": "foo3" } ] ``` or this: ``` [ { "id": "4", "description": "foo4" }, { "id": "2", "description": "foo2" } ] ``` How do I create the contract for this interaction? In the [documentation](https://docs.pact.io/documentation/matching.html) is an example in Ruby, but I cannot find the equivalent in C#. I am using pactNet version 2.1.1. Edit: Here is an example how it should look like. What I want to know is how do I declare that the body should contain an array of items with a flexible length. ``` [Test] public void GetAllItems() { //Arrange _mockProviderService .Given("There are items") .UponReceiving("A GET request to retrieve the items") .With(new ProviderServiceRequest { Method = HttpVerb.Get, Path = "/items/", Headers = new Dictionary<string, object> { { "Accept", "application/json" } } }) .WillRespondWith(new ProviderServiceResponse { Status = 200, Headers = new Dictionary<string, object> { { "Content-Type", "application/json; charset=utf-8" } }, Body = // array of items with some attributes // (somthing like: {"id": "2", "description": "foo"}) // with flexible length }); var consumer = new ItemApiClient(_mockProviderServiceBaseUri); //Act var result = consumer.GetItems(); //Assert Assert.AreEqual(true, result.Count > 0); _mockProviderService.VerifyInteractions(); data.Dispose(); } ```
2017/11/17
[ "https://Stackoverflow.com/questions/47346369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8956409/" ]
For a nested array scenario like @SlimSjakie asked, just repeat Match.MinType at the property that has array. For example, the following Person object has Address property as an array. ``` Person = Match.MinType(new { FirstName = Match.Type("string"), LastName = Match.Type("string"), Address = Match.MinType(new { Street = Match.Type("string"), Town = Match.Type("string"), State = Match.Type("string"), Postcode = Match.Type("string"), Country = Match.Type("string") }, 1) }, 1) ```
So, what if I want to Match the type of an object that has a property that is a list or array? if you do a Match.Type(new myType()) and the number of elements in the array or list property is not exactly the same, the test will fail. You will see an error like this: ``` Description of differences -------------------------------------- * Actual array is too long and should not contain a Hash at $.data.itinerary[2] ```
27,039,199
I am attempting to use GDI+ in my C application to take a screenshot and save it as JPEG. I am using GDI+ to convert the BMP to JPEG but apparently when calling the GdiplusStartup function, the return code is 2(invalid parameter) instead of 0: ``` int main() { GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; //if(GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) != 0) // printf("GDI NOT WORKING\n"); printf("%d",GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL)); HDC hdc = GetDC(NULL); // get the desktop device context HDC hDest = CreateCompatibleDC(hdc); // create a device context to use yourself // get the height and width of the screen int height = GetSystemMetrics(SM_CYVIRTUALSCREEN); int width = GetSystemMetrics(SM_CXVIRTUALSCREEN); // create a bitmap HBITMAP hbDesktop = CreateCompatibleBitmap( hdc, width, height); // use the previously created device context with the bitmap SelectObject(hDest, hbDesktop); // copy from the desktop device context to the bitmap device context // call this once per 'frame' BitBlt(hDest, 0,0, width, height, hdc, 0, 0, SRCCOPY); // after the recording is done, release the desktop context you got.. ReleaseDC(NULL, hdc); // ..and delete the context you created DeleteDC(hDest); SaveJpeg(hbDesktop,"a.jpeg",100); GdiplusShutdown(gdiplusToken); return 0; } ``` I am trying to figure out why the GdiplusStartup function is not working. Any thoughts?
2014/11/20
[ "https://Stackoverflow.com/questions/27039199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241337/" ]
Initialize `gdiplusStartupInput` variable with the following values: `GdiplusVersion = 1, DebugEventCallback = NULL, SuppressBackgroundThread = FALSE, SuppressExternalCodecs = FALSE` According to MSDN article `GdiplusStartup function` <http://msdn.microsoft.com/en-us/library/windows/desktop/ms534077%28v=vs.85%29.aspx> `GdiplusStartupInput` structure has default constructor which initializes the structure with these values. Since you call the function from C, constructor is not working and structure remains uninitialized. Provide your own initialization code to solve the problem.
``` // As Global ULONG_PTR gdiplusToken; // In top of main GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&programInfo.gdiplusToken, &gdiplusStartupInput, NULL); ``` works for me.
24,244,620
I have a method to get fields from related tables in my Table1 model: ``` public function getFields() { $sort = new CSort(); $sort->attributes = array('field1','field2'); $criteria = new CDbCriteria(); $criteria->select = "t3.xxx as field1, count(t1.id) as field2"; $criteria->alias = "t1"; $criteria->join = "inner join Table2 t2 ON t1.id_table2=t2.id"; $criteria->join .= " inner join Table3 t3 ON t2.id_table3=t3.id"; $criteria->group = "field1"; $criteria->order = "field2 desc"; $dataProvider = new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>array('pageSize'=>50,), 'sort'=>$sort, )); return $dataProvider; } ``` In the controller: ``` public function actionListfields() { $dataProvider=Table1::model()->getFields(); $this->render('index_listfields',array( 'dataProvider'=>$dataProvider, )); } ``` In the index\_listfields: ``` $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'columns'=>array( 'field1', 'field2', ), )); ``` I am getting the Grid with the right headers and 28 lines, that is the right size of my query. But I am getting no results in the colmuns. If I try to click in the headers to "suposely" order a column, I get an error saying an strange thing: it says my sql is trying to use an alias at the order command inside the sql, like this: ``` SELECT t3.field as field1, count(t1.id) as field2 FROM "Table1" "t1" inner join Table2 t2 ON t1.id_table2=t2.id inner join Table3 t3 ON t2.id_table3=t3.id GROUP BY field1 ORDER BY "t1"."field2" DESC LIMIT 50 ``` I don know why the order clause is getting the t1 prefix, but the app is complaining about it. I also don't know if I am doing the right way what I want. I first tryed to accomplish this by using plain SQL. I could bring the values of the fields, but I could not order them in the gridview. I would like some advice, please! Thanks a lot.
2014/06/16
[ "https://Stackoverflow.com/questions/24244620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3570546/" ]
Change - `$sort->attributes = array('field1', 'field2');` with ``` $sort->attributes = array( 'field1' => array( 'asc'=>'field1 ASC', 'desc'=>'field1 DESC', ), 'field2' => array( 'asc'=>'field2 ASC', 'desc'=>'field2 DESC', ) ); ``` It works.
> > I also don't know if I am doing the right way what I want. I first > tryed to accomplish this by using plain SQL. I could bring the values > of the fields, but I could not order them in the gridview. > > > This is probably because the SQLDataProvider returns an Array instead of an object.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
The derivative $3x^2-1$ has roots $\pm\dfrac{\sqrt 3}3$, and $- \dfrac{\sqrt 3}3$ corresponds to a local *maximum*, which happens to be $- \dfrac{2\sqrt 9}3-1<0$. Hence $f(x)\le-\dfrac{2\sqrt 9}3-1$ for $x\le \dfrac{\sqrt 3}3$, then it is monotonically increasing to $+\infty$. Therefore, it has only one (real) root.
The solutions of $3c^2-1=0$ are $\pm1/\sqrt{3}$ outside $[1,2]$. That gives you a contradiction with the assumption that there are two roots inside $[1,2]$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
We have that $f'(x)=3x^2-1$ so $f$ has critical points at $x\_0=-1/\sqrt3$ and $x\_1=1/\sqrt3$. It's easy to check that these are not roots of $f$, and hence $f$ has no double root. It follows that $f$ has either $1$ real root, or $3$ real roots: one in $(-\infty,x\_0)$, one in $(x\_0,x\_1)$ and one in $(x\_1,+\infty)$. On the other hand, $f'\geq 0$ in $(-\infty, x\_0)$ so it is increasing and $$f(x\_0) = -\frac1{3\sqrt3}-\frac1{\sqrt3}-1<0$$ so $f<0$ in $(-\infty, x\_0)$. It follows that $f$ must have exactly $1$ real root.
The solutions of $3c^2-1=0$ are $\pm1/\sqrt{3}$ outside $[1,2]$. That gives you a contradiction with the assumption that there are two roots inside $[1,2]$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
**Without derivative:** Let $r$ be the root. Then the polynomial factorizes as $$(x-r)(x^2+rx+r^2-1)$$ and there are other real roots iff $$\Delta=r^2-4(r^2-1)\ge0,$$ $$|r|\le\frac2{\sqrt3}.$$ But $f\left(\dfrac2{\sqrt3}\right)<0$ implies $r>\dfrac2{\sqrt3}$, a contradiction.
**HINT** We can observe that * $f(x)$ is continuous and limits for $x\to \pm \infty$ are $\pm \infty$ thus we have at least one real root then consider * $f'(x)=3x^2-1=0\implies x=\pm \frac{\sqrt 3}{3}$ and study max/min then by IVT you'll be able to prove that $f(x)$ has exactly one root.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
The derivative $3x^2-1$ has roots $\pm\dfrac{\sqrt 3}3$, and $- \dfrac{\sqrt 3}3$ corresponds to a local *maximum*, which happens to be $- \dfrac{2\sqrt 9}3-1<0$. Hence $f(x)\le-\dfrac{2\sqrt 9}3-1$ for $x\le \dfrac{\sqrt 3}3$, then it is monotonically increasing to $+\infty$. Therefore, it has only one (real) root.
One can notice, that $f(1)f(2) = -5 < 0$, so there must be root of the equation. Also $f'(x) = 3x^2 - 1$, so it is monotonically increasing in range [1, 2] - there is only one root. Next step is to prove that $x^3 < x + 1 $ for $x<1$. For $0 < x < 1$ we have $x + 1 > x > x^3$. For $-1 < x < 0$ following is met: $x + 1 > 0 > x ^ 3$. Finally for $x < -1$ we have $1 + x > x > x^3$. Last step is to prove, that $x^3 > x + 1$ for x > 2, but this is obvious, since $f(2) = 5 > 0$ and for every $x > 2$ $\frac{dx^3}{dx} = 3x^2 > \frac{d(x + 1)}{dx} = 1$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
**Without derivative:** Let $r$ be the root. Then the polynomial factorizes as $$(x-r)(x^2+rx+r^2-1)$$ and there are other real roots iff $$\Delta=r^2-4(r^2-1)\ge0,$$ $$|r|\le\frac2{\sqrt3}.$$ But $f\left(\dfrac2{\sqrt3}\right)<0$ implies $r>\dfrac2{\sqrt3}$, a contradiction.
The solutions of $3c^2-1=0$ are $\pm1/\sqrt{3}$ outside $[1,2]$. That gives you a contradiction with the assumption that there are two roots inside $[1,2]$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
**Without derivative:** Let $r$ be the root. Then the polynomial factorizes as $$(x-r)(x^2+rx+r^2-1)$$ and there are other real roots iff $$\Delta=r^2-4(r^2-1)\ge0,$$ $$|r|\le\frac2{\sqrt3}.$$ But $f\left(\dfrac2{\sqrt3}\right)<0$ implies $r>\dfrac2{\sqrt3}$, a contradiction.
One can notice, that $f(1)f(2) = -5 < 0$, so there must be root of the equation. Also $f'(x) = 3x^2 - 1$, so it is monotonically increasing in range [1, 2] - there is only one root. Next step is to prove that $x^3 < x + 1 $ for $x<1$. For $0 < x < 1$ we have $x + 1 > x > x^3$. For $-1 < x < 0$ following is met: $x + 1 > 0 > x ^ 3$. Finally for $x < -1$ we have $1 + x > x > x^3$. Last step is to prove, that $x^3 > x + 1$ for x > 2, but this is obvious, since $f(2) = 5 > 0$ and for every $x > 2$ $\frac{dx^3}{dx} = 3x^2 > \frac{d(x + 1)}{dx} = 1$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
The derivative $3x^2-1$ has roots $\pm\dfrac{\sqrt 3}3$, and $- \dfrac{\sqrt 3}3$ corresponds to a local *maximum*, which happens to be $- \dfrac{2\sqrt 9}3-1<0$. Hence $f(x)\le-\dfrac{2\sqrt 9}3-1$ for $x\le \dfrac{\sqrt 3}3$, then it is monotonically increasing to $+\infty$. Therefore, it has only one (real) root.
We have that $f'(x)=3x^2-1$ so $f$ has critical points at $x\_0=-1/\sqrt3$ and $x\_1=1/\sqrt3$. It's easy to check that these are not roots of $f$, and hence $f$ has no double root. It follows that $f$ has either $1$ real root, or $3$ real roots: one in $(-\infty,x\_0)$, one in $(x\_0,x\_1)$ and one in $(x\_1,+\infty)$. On the other hand, $f'\geq 0$ in $(-\infty, x\_0)$ so it is increasing and $$f(x\_0) = -\frac1{3\sqrt3}-\frac1{\sqrt3}-1<0$$ so $f<0$ in $(-\infty, x\_0)$. It follows that $f$ must have exactly $1$ real root.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
The derivative $3x^2-1$ has roots $\pm\dfrac{\sqrt 3}3$, and $- \dfrac{\sqrt 3}3$ corresponds to a local *maximum*, which happens to be $- \dfrac{2\sqrt 9}3-1<0$. Hence $f(x)\le-\dfrac{2\sqrt 9}3-1$ for $x\le \dfrac{\sqrt 3}3$, then it is monotonically increasing to $+\infty$. Therefore, it has only one (real) root.
**HINT** We can observe that * $f(x)$ is continuous and limits for $x\to \pm \infty$ are $\pm \infty$ thus we have at least one real root then consider * $f'(x)=3x^2-1=0\implies x=\pm \frac{\sqrt 3}{3}$ and study max/min then by IVT you'll be able to prove that $f(x)$ has exactly one root.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
One can notice, that $f(1)f(2) = -5 < 0$, so there must be root of the equation. Also $f'(x) = 3x^2 - 1$, so it is monotonically increasing in range [1, 2] - there is only one root. Next step is to prove that $x^3 < x + 1 $ for $x<1$. For $0 < x < 1$ we have $x + 1 > x > x^3$. For $-1 < x < 0$ following is met: $x + 1 > 0 > x ^ 3$. Finally for $x < -1$ we have $1 + x > x > x^3$. Last step is to prove, that $x^3 > x + 1$ for x > 2, but this is obvious, since $f(2) = 5 > 0$ and for every $x > 2$ $\frac{dx^3}{dx} = 3x^2 > \frac{d(x + 1)}{dx} = 1$.
The solutions of $3c^2-1=0$ are $\pm1/\sqrt{3}$ outside $[1,2]$. That gives you a contradiction with the assumption that there are two roots inside $[1,2]$.
2,694,289
I want to prove that the equation $f(x)=x^3-x-1=0$ has only one real root, which is on the intervall $[1,2]$. $$$$ I have done the following: $f(1)=-1<0$ and $f(2)=5>0$ so $f(1)\cdot f(2)<0$ and so from Bolzano's Theorem we have that the function has at least one root on $[1,2]$. We suppose that there are two roots, $a$ and $b$. Then we have that $f(a)=f(b)=0$. The function $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$. So, from Rolle's Theorem there is a $c\in (a,b)$ such that $f'(c)=0 \Rightarrow 3c^2-1=0$. How can we get a contradiction?
2018/03/16
[ "https://math.stackexchange.com/questions/2694289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/80708/" ]
**Without derivative:** Let $r$ be the root. Then the polynomial factorizes as $$(x-r)(x^2+rx+r^2-1)$$ and there are other real roots iff $$\Delta=r^2-4(r^2-1)\ge0,$$ $$|r|\le\frac2{\sqrt3}.$$ But $f\left(\dfrac2{\sqrt3}\right)<0$ implies $r>\dfrac2{\sqrt3}$, a contradiction.
We have that $f'(x)=3x^2-1$ so $f$ has critical points at $x\_0=-1/\sqrt3$ and $x\_1=1/\sqrt3$. It's easy to check that these are not roots of $f$, and hence $f$ has no double root. It follows that $f$ has either $1$ real root, or $3$ real roots: one in $(-\infty,x\_0)$, one in $(x\_0,x\_1)$ and one in $(x\_1,+\infty)$. On the other hand, $f'\geq 0$ in $(-\infty, x\_0)$ so it is increasing and $$f(x\_0) = -\frac1{3\sqrt3}-\frac1{\sqrt3}-1<0$$ so $f<0$ in $(-\infty, x\_0)$. It follows that $f$ must have exactly $1$ real root.
49,352,559
How can I replace a NA value by the average of the previous non-NA and next non-NA values? For example, I want to replace the first NA value by -0.873, and the 4th/5th by the average of -0.497+53.200. Thanks! ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) ``` =================== ADD ON =================== Thank you all for answering the question! Sorry for the late response. This is only a part of a dataframe (10000 \* 91) and I only took out the first 10 rows from the first column in order to simplify the question. I think David and MKR have the result that I am expected to have.
2018/03/18
[ "https://Stackoverflow.com/questions/49352559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9513287/" ]
This function imputes values for `NA` in a vector based on the average of the non-`NA` values in a rolling window from the first element to the next element. ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) roll_impute <- function(x){ n <- length(x) res <- x for (i in seq_along(x)){ if (is.na(x[i])){ res[i] <- mean(rep_len(x, i+1), na.rm = TRUE ) } } if (is.na(x[n])) x[n] <- mean(x, na.rm = TRUE) res } roll_impute(t) # [1] -0.87300 -0.87300 -0.49700 -0.68500 17.27667 53.20000 17.27667 17.27667 19.48250 # [10] 26.10000 ``` `roll_impute()` includes code that corrects the rolling window in the case that the final element is `NA`, so that the vector isn't recycled. This isn't the case in your example, but is needed in order to generalize the function. Any improvements on this function would be welcome :) It does use a for loop, but doesn't grow any vectors. No simple way to avoid the for loop and rely on the structure of the objects jumps to my mind right now.
One `dplyr` and `tidyr` based solution could be: ``` library(dplyr) library(tidyr) t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) data.frame(t) %>% mutate(last_nonNA = ifelse(!is.na(t), t, NA)) %>% mutate(next_nonNA = ifelse(!is.na(t), t, NA)) %>% fill(last_nonNA) %>% fill(next_nonNA, .direction = "up") %>% mutate(t = case_when( !is.na(t) ~ t, !is.na(last_nonNA) & !is.na(next_nonNA) ~ (last_nonNA + next_nonNA)/2, is.na(last_nonNA) ~ next_nonNA, is.na(next_nonNA) ~ last_nonNA ) ) %>% select(t) # t # 1 -0.8730 # 2 -0.8730 # 3 -0.4970 # 4 26.3515 # 5 26.3515 # 6 53.2000 # 7 39.6500 # 8 39.6500 # 9 39.6500 # 10 26.1000 ``` **Note:** It looks a bit complicated but it does the trick. One can achieve same thing via for loop.
49,352,559
How can I replace a NA value by the average of the previous non-NA and next non-NA values? For example, I want to replace the first NA value by -0.873, and the 4th/5th by the average of -0.497+53.200. Thanks! ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) ``` =================== ADD ON =================== Thank you all for answering the question! Sorry for the late response. This is only a part of a dataframe (10000 \* 91) and I only took out the first 10 rows from the first column in order to simplify the question. I think David and MKR have the result that I am expected to have.
2018/03/18
[ "https://Stackoverflow.com/questions/49352559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9513287/" ]
Here's a possible vectorized approach using base R (some steps could be probably improved but I have no time to look into it right now) ``` x <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) # Store a boolean vector of NA locaiotns for firther use na_vals <- is.na(x) # Find the NAs location compaed to the non-NAs start_ind <- findInterval(which(na_vals), which(!na_vals)) # Createa right limit end_ind <- start_ind + 1L # Replace zero locations with NAs start_ind[start_ind == 0L] <- NA_integer_ # Calculate the means and replace the NAs x[na_vals] <- rowMeans(cbind(x[!na_vals][start_ind], x[!na_vals][end_ind]), na.rm = TRUE) x # [1] -0.8730 -0.8730 -0.4970 26.3515 26.3515 53.2000 39.6500 39.6500 39.6500 26.1000 ``` This should work properly for NAs on both sides of the vector.
This function imputes values for `NA` in a vector based on the average of the non-`NA` values in a rolling window from the first element to the next element. ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) roll_impute <- function(x){ n <- length(x) res <- x for (i in seq_along(x)){ if (is.na(x[i])){ res[i] <- mean(rep_len(x, i+1), na.rm = TRUE ) } } if (is.na(x[n])) x[n] <- mean(x, na.rm = TRUE) res } roll_impute(t) # [1] -0.87300 -0.87300 -0.49700 -0.68500 17.27667 53.20000 17.27667 17.27667 19.48250 # [10] 26.10000 ``` `roll_impute()` includes code that corrects the rolling window in the case that the final element is `NA`, so that the vector isn't recycled. This isn't the case in your example, but is needed in order to generalize the function. Any improvements on this function would be welcome :) It does use a for loop, but doesn't grow any vectors. No simple way to avoid the for loop and rely on the structure of the objects jumps to my mind right now.
49,352,559
How can I replace a NA value by the average of the previous non-NA and next non-NA values? For example, I want to replace the first NA value by -0.873, and the 4th/5th by the average of -0.497+53.200. Thanks! ``` t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) ``` =================== ADD ON =================== Thank you all for answering the question! Sorry for the late response. This is only a part of a dataframe (10000 \* 91) and I only took out the first 10 rows from the first column in order to simplify the question. I think David and MKR have the result that I am expected to have.
2018/03/18
[ "https://Stackoverflow.com/questions/49352559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9513287/" ]
Here's a possible vectorized approach using base R (some steps could be probably improved but I have no time to look into it right now) ``` x <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) # Store a boolean vector of NA locaiotns for firther use na_vals <- is.na(x) # Find the NAs location compaed to the non-NAs start_ind <- findInterval(which(na_vals), which(!na_vals)) # Createa right limit end_ind <- start_ind + 1L # Replace zero locations with NAs start_ind[start_ind == 0L] <- NA_integer_ # Calculate the means and replace the NAs x[na_vals] <- rowMeans(cbind(x[!na_vals][start_ind], x[!na_vals][end_ind]), na.rm = TRUE) x # [1] -0.8730 -0.8730 -0.4970 26.3515 26.3515 53.2000 39.6500 39.6500 39.6500 26.1000 ``` This should work properly for NAs on both sides of the vector.
One `dplyr` and `tidyr` based solution could be: ``` library(dplyr) library(tidyr) t <- c(NA, -0.873, -0.497, NA, NA, 53.200, NA, NA, NA, 26.100) data.frame(t) %>% mutate(last_nonNA = ifelse(!is.na(t), t, NA)) %>% mutate(next_nonNA = ifelse(!is.na(t), t, NA)) %>% fill(last_nonNA) %>% fill(next_nonNA, .direction = "up") %>% mutate(t = case_when( !is.na(t) ~ t, !is.na(last_nonNA) & !is.na(next_nonNA) ~ (last_nonNA + next_nonNA)/2, is.na(last_nonNA) ~ next_nonNA, is.na(next_nonNA) ~ last_nonNA ) ) %>% select(t) # t # 1 -0.8730 # 2 -0.8730 # 3 -0.4970 # 4 26.3515 # 5 26.3515 # 6 53.2000 # 7 39.6500 # 8 39.6500 # 9 39.6500 # 10 26.1000 ``` **Note:** It looks a bit complicated but it does the trick. One can achieve same thing via for loop.
3,315,760
I have to use key down event on text box. Code for the event looks like this: ``` Private Sub TextBox1_Keydown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles textBox1.KeyDown If e.KeyCode = keys.Enter Then MessageBox.Show("Hello") End If End Sub ``` But it gives the following error: ``` Handles clause requires a WithEvents variable defined in the containing type or one of its base types. (BC30506) ``` what does it mean? what i have to do for this? Please help me out. Thanks for your kind help.
2010/07/23
[ "https://Stackoverflow.com/questions/3315760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399935/" ]
Function names are not the same in the libs - c++ standard does not define it so both msvc and g++ define them their own way. Check this post. [Qt/mingw32 undefined reference errors... unable to link a .lib](https://stackoverflow.com/questions/1137323/qt-mingw32-undefined-reference-errors-unable-to-link-a-lib) There are some work-arounds like this for instance (dll): <http://www.emmestech.com/moron_guides/moron1.html>
If you are getting an undefined reference error then you haven't linked to the correct library.
3,315,760
I have to use key down event on text box. Code for the event looks like this: ``` Private Sub TextBox1_Keydown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles textBox1.KeyDown If e.KeyCode = keys.Enter Then MessageBox.Show("Hello") End If End Sub ``` But it gives the following error: ``` Handles clause requires a WithEvents variable defined in the containing type or one of its base types. (BC30506) ``` what does it mean? what i have to do for this? Please help me out. Thanks for your kind help.
2010/07/23
[ "https://Stackoverflow.com/questions/3315760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399935/" ]
Function names are not the same in the libs - c++ standard does not define it so both msvc and g++ define them their own way. Check this post. [Qt/mingw32 undefined reference errors... unable to link a .lib](https://stackoverflow.com/questions/1137323/qt-mingw32-undefined-reference-errors-unable-to-link-a-lib) There are some work-arounds like this for instance (dll): <http://www.emmestech.com/moron_guides/moron1.html>
You use Qt Creator? Say you have a lib file named libodbc32.a Then you should add a lib like this: LIBS += -L [path to the libodbc32.a] -L [path to libsystemc.a] -lodbc32 -lsystemc So I think you have linked not in an appropriate way.
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
These is a good overview of RTTI in Delphi 2010 on the web: <http://robstechcorner.blogspot.com/2009/09/so-what-is-rtti-rtti-is-acronym-for-run.html> You can get the enumeration values and back the ordinals using the "OLD" RTTI functions in the unit TypInfo (GetEnumValue, GetEnumName). And clip off the lowercase letters you get the same result as above but it is not as flexible.
I use and array of string in the const section: ``` type TTypeOfData = ( todABC, todDEF, todGHI ); const TypeOfDataText: array[TTypeOfData] of string = ( 'ABC', 'DEF', 'GHI' ); ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
While Barry clearly answered your question regarding the attributes on enum elements, I'll take a stab at another suggestion. From your example, you're prefixing each enum element with 'tod' as is traditional in Delphi because enum elements are global in scope (ie. if you had an identifier todABC in scope in addition to the todABC enum elements, you could get some odd behaviors). Starting in D2007, we introduced the notion of "scoped enums" which, when enabled, require you to qualify the enum element with the identifier of the enum itself. For instance: ``` {$SCOPEDENUMS ON} type TTypeOfData = (ABC,DEF,GHI); ``` Will require you to refer to the ABC element as TTypeOfData.ABC. This allows you to use non-prefixed enum element identifiers and not run the risk of having conflicts since the elements are "scoped" to the enumeration. Any enum declared while {$SCOPEDENUMS} is enabled will behave in this manner. Given that, you can now safely use the RTTI to get the actual enum element names in the format you wish.
These is a good overview of RTTI in Delphi 2010 on the web: <http://robstechcorner.blogspot.com/2009/09/so-what-is-rtti-rtti-is-acronym-for-run.html> You can get the enumeration values and back the ordinals using the "OLD" RTTI functions in the unit TypInfo (GetEnumValue, GetEnumName). And clip off the lowercase letters you get the same result as above but it is not as flexible.
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
These is a good overview of RTTI in Delphi 2010 on the web: <http://robstechcorner.blogspot.com/2009/09/so-what-is-rtti-rtti-is-acronym-for-run.html> You can get the enumeration values and back the ordinals using the "OLD" RTTI functions in the unit TypInfo (GetEnumValue, GetEnumName). And clip off the lowercase letters you get the same result as above but it is not as flexible.
For those who are interrested in a practical solution to that problem, I solved it that way : ``` type TTypeOfData = (todABC, todDEF, todGHI); TMySerializableClass = class private FType: TTypeOfData; public property &Type: TTypeOfData read FType write FType; class function TypeOfDataAsString(&Type: TTypeOfData): String; end; implementation class function TMySerializableClass.TypeOfDataAsString(&Type: TTypeOfData): String; const TYPE_STRING: array[TypeOfDataAsString] of String = ('ABC', 'DEF', 'GHI); begin Result := TYPE_STRING[&Type]; end; ``` And later, in the serialization code, I use RTTI to look for a class function conventionnaly named AsString and call it with the property TValue : ``` procedure Serialize(const V: TValue); var N: String; T: TRttiType; F: TRttiField; M: TRttiMethod; R: TValue; begin case V.TypeInfo^.Kind of tkEnumeration: begin T := Ctx.GetType(TypeInfo(TMySerializableClass)); N := V.TypeInfo.Name + 'AsString'; if N[1] = 'T' then Delete(N, 1, 1); M := T.GetMethod(N); if (M <> nil) and M.IsClassMethod and (M.MethodKind = mkClassFunction) and (M.ReturnType.TypeKind = tkUString) then begin R := M.Invoke(TTicket, [V]); // serialize R.AsString end; end; ... end; ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
Attributes associated with elements in enumerations are not currently stored in Win32 RTTI data in the executable. RTTI is already responsible for a fair increase in the size of executables, so some lines had to be drawn somewhere. Attributes in Delphi Win32 are supported on types, on fields of records, and fields, methods, their parameters, and properties of classes. The attribute declarations don't cause errors because of backward compatibility with Delphi for .NET.
While Barry clearly answered your question regarding the attributes on enum elements, I'll take a stab at another suggestion. From your example, you're prefixing each enum element with 'tod' as is traditional in Delphi because enum elements are global in scope (ie. if you had an identifier todABC in scope in addition to the todABC enum elements, you could get some odd behaviors). Starting in D2007, we introduced the notion of "scoped enums" which, when enabled, require you to qualify the enum element with the identifier of the enum itself. For instance: ``` {$SCOPEDENUMS ON} type TTypeOfData = (ABC,DEF,GHI); ``` Will require you to refer to the ABC element as TTypeOfData.ABC. This allows you to use non-prefixed enum element identifiers and not run the risk of having conflicts since the elements are "scoped" to the enumeration. Any enum declared while {$SCOPEDENUMS} is enabled will behave in this manner. Given that, you can now safely use the RTTI to get the actual enum element names in the format you wish.
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
Attributes associated with elements in enumerations are not currently stored in Win32 RTTI data in the executable. RTTI is already responsible for a fair increase in the size of executables, so some lines had to be drawn somewhere. Attributes in Delphi Win32 are supported on types, on fields of records, and fields, methods, their parameters, and properties of classes. The attribute declarations don't cause errors because of backward compatibility with Delphi for .NET.
These is a good overview of RTTI in Delphi 2010 on the web: <http://robstechcorner.blogspot.com/2009/09/so-what-is-rtti-rtti-is-acronym-for-run.html> You can get the enumeration values and back the ordinals using the "OLD" RTTI functions in the unit TypInfo (GetEnumValue, GetEnumName). And clip off the lowercase letters you get the same result as above but it is not as flexible.
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
Ok I think I have found a better solution. I declare a new attribute type, e.g.: ``` TEnumAttribute = class (TCustomAttribute) private FCaption : string; public constructor Create (const Caption : string); property Caption : string read FCaption write FCaption; end; ``` Now I add attributes to my enumeration: ``` [TEnumAttribute ('Normal')] [TEnumAttribute ('High')] TExampleEnum = (eeNormal,eeHigh); ``` Now it is easy to access the attributes by its ordinal: ``` RttiType := RttiContext.FindType ('ExampleUnit.TExampleEnum'); RttiAttributes := Rttitype.GetAttributes; Test := TEnumAttributes(RttiAttributes[index]).Caption; ```
I use and array of string in the const section: ``` type TTypeOfData = ( todABC, todDEF, todGHI ); const TypeOfDataText: array[TTypeOfData] of string = ( 'ABC', 'DEF', 'GHI' ); ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
Attributes associated with elements in enumerations are not currently stored in Win32 RTTI data in the executable. RTTI is already responsible for a fair increase in the size of executables, so some lines had to be drawn somewhere. Attributes in Delphi Win32 are supported on types, on fields of records, and fields, methods, their parameters, and properties of classes. The attribute declarations don't cause errors because of backward compatibility with Delphi for .NET.
I use and array of string in the const section: ``` type TTypeOfData = ( todABC, todDEF, todGHI ); const TypeOfDataText: array[TTypeOfData] of string = ( 'ABC', 'DEF', 'GHI' ); ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
Ok I think I have found a better solution. I declare a new attribute type, e.g.: ``` TEnumAttribute = class (TCustomAttribute) private FCaption : string; public constructor Create (const Caption : string); property Caption : string read FCaption write FCaption; end; ``` Now I add attributes to my enumeration: ``` [TEnumAttribute ('Normal')] [TEnumAttribute ('High')] TExampleEnum = (eeNormal,eeHigh); ``` Now it is easy to access the attributes by its ordinal: ``` RttiType := RttiContext.FindType ('ExampleUnit.TExampleEnum'); RttiAttributes := Rttitype.GetAttributes; Test := TEnumAttributes(RttiAttributes[index]).Caption; ```
For those who are interrested in a practical solution to that problem, I solved it that way : ``` type TTypeOfData = (todABC, todDEF, todGHI); TMySerializableClass = class private FType: TTypeOfData; public property &Type: TTypeOfData read FType write FType; class function TypeOfDataAsString(&Type: TTypeOfData): String; end; implementation class function TMySerializableClass.TypeOfDataAsString(&Type: TTypeOfData): String; const TYPE_STRING: array[TypeOfDataAsString] of String = ('ABC', 'DEF', 'GHI); begin Result := TYPE_STRING[&Type]; end; ``` And later, in the serialization code, I use RTTI to look for a class function conventionnaly named AsString and call it with the property TValue : ``` procedure Serialize(const V: TValue); var N: String; T: TRttiType; F: TRttiField; M: TRttiMethod; R: TValue; begin case V.TypeInfo^.Kind of tkEnumeration: begin T := Ctx.GetType(TypeInfo(TMySerializableClass)); N := V.TypeInfo.Name + 'AsString'; if N[1] = 'T' then Delete(N, 1, 1); M := T.GetMethod(N); if (M <> nil) and M.IsClassMethod and (M.MethodKind = mkClassFunction) and (M.ReturnType.TypeKind = tkUString) then begin R := M.Invoke(TTicket, [V]); // serialize R.AsString end; end; ... end; ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
While Barry clearly answered your question regarding the attributes on enum elements, I'll take a stab at another suggestion. From your example, you're prefixing each enum element with 'tod' as is traditional in Delphi because enum elements are global in scope (ie. if you had an identifier todABC in scope in addition to the todABC enum elements, you could get some odd behaviors). Starting in D2007, we introduced the notion of "scoped enums" which, when enabled, require you to qualify the enum element with the identifier of the enum itself. For instance: ``` {$SCOPEDENUMS ON} type TTypeOfData = (ABC,DEF,GHI); ``` Will require you to refer to the ABC element as TTypeOfData.ABC. This allows you to use non-prefixed enum element identifiers and not run the risk of having conflicts since the elements are "scoped" to the enumeration. Any enum declared while {$SCOPEDENUMS} is enabled will behave in this manner. Given that, you can now safely use the RTTI to get the actual enum element names in the format you wish.
Ok I think I have found a better solution. I declare a new attribute type, e.g.: ``` TEnumAttribute = class (TCustomAttribute) private FCaption : string; public constructor Create (const Caption : string); property Caption : string read FCaption write FCaption; end; ``` Now I add attributes to my enumeration: ``` [TEnumAttribute ('Normal')] [TEnumAttribute ('High')] TExampleEnum = (eeNormal,eeHigh); ``` Now it is easy to access the attributes by its ordinal: ``` RttiType := RttiContext.FindType ('ExampleUnit.TExampleEnum'); RttiAttributes := Rttitype.GetAttributes; Test := TEnumAttributes(RttiAttributes[index]).Caption; ```
2,134,120
Considering such an enumeration : ``` type TTypeOfData = ( [XmlName('ABC')] todABC, [XmlName('DEF')] todDEF, [XmlName('GHI')] todGHI ); ``` Where XmlName is a custom attribute used to define the serialization string for members of this enumeration. How can I explore the attributes attached to each member of this enumeration ?
2010/01/25
[ "https://Stackoverflow.com/questions/2134120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258622/" ]
For those who are interrested in a practical solution to that problem, I solved it that way : ``` type TTypeOfData = (todABC, todDEF, todGHI); TMySerializableClass = class private FType: TTypeOfData; public property &Type: TTypeOfData read FType write FType; class function TypeOfDataAsString(&Type: TTypeOfData): String; end; implementation class function TMySerializableClass.TypeOfDataAsString(&Type: TTypeOfData): String; const TYPE_STRING: array[TypeOfDataAsString] of String = ('ABC', 'DEF', 'GHI); begin Result := TYPE_STRING[&Type]; end; ``` And later, in the serialization code, I use RTTI to look for a class function conventionnaly named AsString and call it with the property TValue : ``` procedure Serialize(const V: TValue); var N: String; T: TRttiType; F: TRttiField; M: TRttiMethod; R: TValue; begin case V.TypeInfo^.Kind of tkEnumeration: begin T := Ctx.GetType(TypeInfo(TMySerializableClass)); N := V.TypeInfo.Name + 'AsString'; if N[1] = 'T' then Delete(N, 1, 1); M := T.GetMethod(N); if (M <> nil) and M.IsClassMethod and (M.MethodKind = mkClassFunction) and (M.ReturnType.TypeKind = tkUString) then begin R := M.Invoke(TTicket, [V]); // serialize R.AsString end; end; ... end; ```
I use and array of string in the const section: ``` type TTypeOfData = ( todABC, todDEF, todGHI ); const TypeOfDataText: array[TTypeOfData] of string = ( 'ABC', 'DEF', 'GHI' ); ```
36,628,862
Can anyone please help to solve the edittext label floating issue, As per my requirement the hint text should be there in editbox itself when error text is displayed. Right now what is happening that whenever I show the error text the label also moving, i don't want to move the labeluntil and unless user start typing The screenshot was taken from google design screen <http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field> [![enter image description here](https://i.stack.imgur.com/93fGO.png)](https://i.stack.imgur.com/93fGO.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36628862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487219/" ]
Say you read a row from a CSV: ``` from StringIO import StringIO import csv infile = StringIO('hello,"foo, bar"') reader = csv.reader(infile) row = reader.next() # row is ['hello', 'foo, bar'] ``` The second value in the row is `foo, bar` instead of `"foo, bar"`. This isn't some Python oddity, it's a reasonable interpretation of CSV syntax. The quotes probably weren't placed there to be part of a value, but rather to show that `foo, bar` is one value and shouldn't be split into `foo` and `bar` based on the comma (`,`). An alternative solution would be to escape the comma when creating the CSV file, so the line would look like: ``` hello,foo \,bar ``` So it's quite a strange request to want to keep those quotes. If we know more about your use case and the bigger picture we can help you better. What are you trying to achieve? Where does the input file come from? Is it really a CSV or is it some other syntax that looks similar? For example if you know that every line consists of two values separated by a comma, and the first value never contains a comma, then you can just split on the first comma: ``` print 'hello,"foo, bar"'.split(',', 1) # => ['hello', '"foo, bar"'] ``` But I doubt the input has such restrictions which is why things like quotes are needed to resolve ambiguities. If you're trying to write to a CSV again, then the quotes will be recreated as you're doing so. They don't have to be there in the intermediate list: ``` outfile = StringIO() writer = csv.writer(outfile) writer.writerow(row) print outfile.getvalue() ``` This will print ``` hello,"foo, bar" ``` You can customise the exact CSV output by setting a new dialect. If you want to grab the individual values in the row with the appropriate quoting rules applied to them, it's possible, but it's a bit of a hack: ``` # We're going to write individual strings, so we don't want a line terminator csv.register_dialect('no_line_terminator', lineterminator='') def maybe_quote_string(s): out = StringIO() # writerow iterates over its argument, so don't give it a plain string # or it'll break it up into characters csv.writer(out, 'no_line_terminator').writerow([s]) return out.getvalue() print maybe_quote_string('foo, bar') print map(maybe_quote_string, row) ``` The output is: ``` "foo, bar" ['hello', '"foo, bar"'] ``` This is the closest I can come to answering your question. It's not really *keeping* the double quotes, rather it's removing them and adding them back with likely the same rules that put them there in the first place. I'll say it again, you're probably headed down the wrong path with this question. Others will probably agree. That's why you're struggling to get good answers. What is the bigger problem that you're trying to solve? We can help you better to achieve that.
Alright so this took a long time to get a solution and it is in no way pretty, but: ``` >>> import re >>> s = 'hello,"foo, bar"' >>> >>> replacements = {} >>> m = re.search("\".*\"", s) >>> while m: ... key = 'unique_phrase_' + str(len(replacements)) ... replacements[key] = s[m.span()[0]:m.span()[1]] ... s = re.sub("\".*\"", key, s, count=1) ... m = re.search("\".*\"", s) ... >>> list_from_string = s.split(",") >>> final_list = [] >>> for element in list_from_string: ... for key in replacements.keys(): ... if re.match(key, element): ... final_list.append(re.sub(key, replacements[key], element)) ... else: ... final_list.append(element) ... >>> >>> print final_list ['hello', '"foo, bar"'] ``` Looks ugly to me but couldn't find any clear ways to make it more pythonic.
36,628,862
Can anyone please help to solve the edittext label floating issue, As per my requirement the hint text should be there in editbox itself when error text is displayed. Right now what is happening that whenever I show the error text the label also moving, i don't want to move the labeluntil and unless user start typing The screenshot was taken from google design screen <http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field> [![enter image description here](https://i.stack.imgur.com/93fGO.png)](https://i.stack.imgur.com/93fGO.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36628862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487219/" ]
Kinda depends upon you Use Case. If the only "s are there for values containing commas (e.g. "foo,bar"), then you can use CSV writer to put them back in. ``` import io import csv infile = io.StringIO('hello,"foo, bar"') outfile = io.StringIO() reader = csv.reader(infile) for row in reader: inList = row break print(inList) # As an output string writer = csv.writer(outfile) writer.writerow(inList) outList = outfile.getvalue().strip() print(outList) # As a List outList = [] for i in range(len(inList)): outfile = io.StringIO() writer = csv.writer(outfile) writer.writerow([inList[i]]) outList.append(outfile.getvalue().strip()) print(outList) ``` Output ``` ['hello', 'foo, bar'] hello,"foo, bar" ['hello', '"foo, bar"'] ``` However, if you have other, unnecessary "s that you want to preserve (e.g. '"hello","foo,bar",humbug') and all fields containing , will be correctly wrapped in "s then you could split the line on the , and look for 'broken' fields (start with " but don't end with ") ``` line = '"hello","foo, bar",humbug' fields = line.split(',') print(fields) values = [] i = 0 while i < len(fields): # If a field doesn't start with a ", or starts and ends with "s if (fields[i][0] != '"') or (fields[i][-1] == '"'): values.append(fields[i]) # It's a stand alone value i += 1 continue value = fields[i] # A value that has been split i += 1 while i < len(fields): value += ',' + fields[i] i += 1 if value[-1] == '"': # The last part would have ended in a " break values.append(value) print(values) ``` Output ``` ['"hello"', '"foo', ' bar"', 'humbug'] ['"hello"', '"foo, bar"', 'humbug'] ```
Alright so this took a long time to get a solution and it is in no way pretty, but: ``` >>> import re >>> s = 'hello,"foo, bar"' >>> >>> replacements = {} >>> m = re.search("\".*\"", s) >>> while m: ... key = 'unique_phrase_' + str(len(replacements)) ... replacements[key] = s[m.span()[0]:m.span()[1]] ... s = re.sub("\".*\"", key, s, count=1) ... m = re.search("\".*\"", s) ... >>> list_from_string = s.split(",") >>> final_list = [] >>> for element in list_from_string: ... for key in replacements.keys(): ... if re.match(key, element): ... final_list.append(re.sub(key, replacements[key], element)) ... else: ... final_list.append(element) ... >>> >>> print final_list ['hello', '"foo, bar"'] ``` Looks ugly to me but couldn't find any clear ways to make it more pythonic.
36,628,862
Can anyone please help to solve the edittext label floating issue, As per my requirement the hint text should be there in editbox itself when error text is displayed. Right now what is happening that whenever I show the error text the label also moving, i don't want to move the labeluntil and unless user start typing The screenshot was taken from google design screen <http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field> [![enter image description here](https://i.stack.imgur.com/93fGO.png)](https://i.stack.imgur.com/93fGO.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36628862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487219/" ]
Say you read a row from a CSV: ``` from StringIO import StringIO import csv infile = StringIO('hello,"foo, bar"') reader = csv.reader(infile) row = reader.next() # row is ['hello', 'foo, bar'] ``` The second value in the row is `foo, bar` instead of `"foo, bar"`. This isn't some Python oddity, it's a reasonable interpretation of CSV syntax. The quotes probably weren't placed there to be part of a value, but rather to show that `foo, bar` is one value and shouldn't be split into `foo` and `bar` based on the comma (`,`). An alternative solution would be to escape the comma when creating the CSV file, so the line would look like: ``` hello,foo \,bar ``` So it's quite a strange request to want to keep those quotes. If we know more about your use case and the bigger picture we can help you better. What are you trying to achieve? Where does the input file come from? Is it really a CSV or is it some other syntax that looks similar? For example if you know that every line consists of two values separated by a comma, and the first value never contains a comma, then you can just split on the first comma: ``` print 'hello,"foo, bar"'.split(',', 1) # => ['hello', '"foo, bar"'] ``` But I doubt the input has such restrictions which is why things like quotes are needed to resolve ambiguities. If you're trying to write to a CSV again, then the quotes will be recreated as you're doing so. They don't have to be there in the intermediate list: ``` outfile = StringIO() writer = csv.writer(outfile) writer.writerow(row) print outfile.getvalue() ``` This will print ``` hello,"foo, bar" ``` You can customise the exact CSV output by setting a new dialect. If you want to grab the individual values in the row with the appropriate quoting rules applied to them, it's possible, but it's a bit of a hack: ``` # We're going to write individual strings, so we don't want a line terminator csv.register_dialect('no_line_terminator', lineterminator='') def maybe_quote_string(s): out = StringIO() # writerow iterates over its argument, so don't give it a plain string # or it'll break it up into characters csv.writer(out, 'no_line_terminator').writerow([s]) return out.getvalue() print maybe_quote_string('foo, bar') print map(maybe_quote_string, row) ``` The output is: ``` "foo, bar" ['hello', '"foo, bar"'] ``` This is the closest I can come to answering your question. It's not really *keeping* the double quotes, rather it's removing them and adding them back with likely the same rules that put them there in the first place. I'll say it again, you're probably headed down the wrong path with this question. Others will probably agree. That's why you're struggling to get good answers. What is the bigger problem that you're trying to solve? We can help you better to achieve that.
A little late to the party but in the CSV library there's [quoting](https://docs.python.org/2/library/csv.html#csv.Dialect.quoting) which should do what you want (set to QUOTE\_NONE)
36,628,862
Can anyone please help to solve the edittext label floating issue, As per my requirement the hint text should be there in editbox itself when error text is displayed. Right now what is happening that whenever I show the error text the label also moving, i don't want to move the labeluntil and unless user start typing The screenshot was taken from google design screen <http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field> [![enter image description here](https://i.stack.imgur.com/93fGO.png)](https://i.stack.imgur.com/93fGO.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36628862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487219/" ]
Kinda depends upon you Use Case. If the only "s are there for values containing commas (e.g. "foo,bar"), then you can use CSV writer to put them back in. ``` import io import csv infile = io.StringIO('hello,"foo, bar"') outfile = io.StringIO() reader = csv.reader(infile) for row in reader: inList = row break print(inList) # As an output string writer = csv.writer(outfile) writer.writerow(inList) outList = outfile.getvalue().strip() print(outList) # As a List outList = [] for i in range(len(inList)): outfile = io.StringIO() writer = csv.writer(outfile) writer.writerow([inList[i]]) outList.append(outfile.getvalue().strip()) print(outList) ``` Output ``` ['hello', 'foo, bar'] hello,"foo, bar" ['hello', '"foo, bar"'] ``` However, if you have other, unnecessary "s that you want to preserve (e.g. '"hello","foo,bar",humbug') and all fields containing , will be correctly wrapped in "s then you could split the line on the , and look for 'broken' fields (start with " but don't end with ") ``` line = '"hello","foo, bar",humbug' fields = line.split(',') print(fields) values = [] i = 0 while i < len(fields): # If a field doesn't start with a ", or starts and ends with "s if (fields[i][0] != '"') or (fields[i][-1] == '"'): values.append(fields[i]) # It's a stand alone value i += 1 continue value = fields[i] # A value that has been split i += 1 while i < len(fields): value += ',' + fields[i] i += 1 if value[-1] == '"': # The last part would have ended in a " break values.append(value) print(values) ``` Output ``` ['"hello"', '"foo', ' bar"', 'humbug'] ['"hello"', '"foo, bar"', 'humbug'] ```
A little late to the party but in the CSV library there's [quoting](https://docs.python.org/2/library/csv.html#csv.Dialect.quoting) which should do what you want (set to QUOTE\_NONE)
36,628,862
Can anyone please help to solve the edittext label floating issue, As per my requirement the hint text should be there in editbox itself when error text is displayed. Right now what is happening that whenever I show the error text the label also moving, i don't want to move the labeluntil and unless user start typing The screenshot was taken from google design screen <http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field> [![enter image description here](https://i.stack.imgur.com/93fGO.png)](https://i.stack.imgur.com/93fGO.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36628862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/487219/" ]
Say you read a row from a CSV: ``` from StringIO import StringIO import csv infile = StringIO('hello,"foo, bar"') reader = csv.reader(infile) row = reader.next() # row is ['hello', 'foo, bar'] ``` The second value in the row is `foo, bar` instead of `"foo, bar"`. This isn't some Python oddity, it's a reasonable interpretation of CSV syntax. The quotes probably weren't placed there to be part of a value, but rather to show that `foo, bar` is one value and shouldn't be split into `foo` and `bar` based on the comma (`,`). An alternative solution would be to escape the comma when creating the CSV file, so the line would look like: ``` hello,foo \,bar ``` So it's quite a strange request to want to keep those quotes. If we know more about your use case and the bigger picture we can help you better. What are you trying to achieve? Where does the input file come from? Is it really a CSV or is it some other syntax that looks similar? For example if you know that every line consists of two values separated by a comma, and the first value never contains a comma, then you can just split on the first comma: ``` print 'hello,"foo, bar"'.split(',', 1) # => ['hello', '"foo, bar"'] ``` But I doubt the input has such restrictions which is why things like quotes are needed to resolve ambiguities. If you're trying to write to a CSV again, then the quotes will be recreated as you're doing so. They don't have to be there in the intermediate list: ``` outfile = StringIO() writer = csv.writer(outfile) writer.writerow(row) print outfile.getvalue() ``` This will print ``` hello,"foo, bar" ``` You can customise the exact CSV output by setting a new dialect. If you want to grab the individual values in the row with the appropriate quoting rules applied to them, it's possible, but it's a bit of a hack: ``` # We're going to write individual strings, so we don't want a line terminator csv.register_dialect('no_line_terminator', lineterminator='') def maybe_quote_string(s): out = StringIO() # writerow iterates over its argument, so don't give it a plain string # or it'll break it up into characters csv.writer(out, 'no_line_terminator').writerow([s]) return out.getvalue() print maybe_quote_string('foo, bar') print map(maybe_quote_string, row) ``` The output is: ``` "foo, bar" ['hello', '"foo, bar"'] ``` This is the closest I can come to answering your question. It's not really *keeping* the double quotes, rather it's removing them and adding them back with likely the same rules that put them there in the first place. I'll say it again, you're probably headed down the wrong path with this question. Others will probably agree. That's why you're struggling to get good answers. What is the bigger problem that you're trying to solve? We can help you better to achieve that.
Kinda depends upon you Use Case. If the only "s are there for values containing commas (e.g. "foo,bar"), then you can use CSV writer to put them back in. ``` import io import csv infile = io.StringIO('hello,"foo, bar"') outfile = io.StringIO() reader = csv.reader(infile) for row in reader: inList = row break print(inList) # As an output string writer = csv.writer(outfile) writer.writerow(inList) outList = outfile.getvalue().strip() print(outList) # As a List outList = [] for i in range(len(inList)): outfile = io.StringIO() writer = csv.writer(outfile) writer.writerow([inList[i]]) outList.append(outfile.getvalue().strip()) print(outList) ``` Output ``` ['hello', 'foo, bar'] hello,"foo, bar" ['hello', '"foo, bar"'] ``` However, if you have other, unnecessary "s that you want to preserve (e.g. '"hello","foo,bar",humbug') and all fields containing , will be correctly wrapped in "s then you could split the line on the , and look for 'broken' fields (start with " but don't end with ") ``` line = '"hello","foo, bar",humbug' fields = line.split(',') print(fields) values = [] i = 0 while i < len(fields): # If a field doesn't start with a ", or starts and ends with "s if (fields[i][0] != '"') or (fields[i][-1] == '"'): values.append(fields[i]) # It's a stand alone value i += 1 continue value = fields[i] # A value that has been split i += 1 while i < len(fields): value += ',' + fields[i] i += 1 if value[-1] == '"': # The last part would have ended in a " break values.append(value) print(values) ``` Output ``` ['"hello"', '"foo', ' bar"', 'humbug'] ['"hello"', '"foo, bar"', 'humbug'] ```
39,658,219
I have a query which is pretty that contains `LEFT JOIN` subquery. It takes 20 minutes to load completely. Here is my query: ``` UPDATE orders AS o LEFT JOIN ( SELECT obe_order_master_id, COUNT(id) AS count_files, id, added FROM customer_instalments GROUP BY obe_order_master_id ) AS oci ON oci.obe_order_master_id = SUBSTRING(o.order_id, 4) SET o.final_customer_file_id = oci.id, o.client_work_delivered = oci.added WHERE oci.count_files = 1 ``` Is there any way that I can make this query runs faster?
2016/09/23
[ "https://Stackoverflow.com/questions/39658219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1626398/" ]
Move `Where` condition in Temp Table and replace `WHERE` with `HAVING` Clause, this will eliminate unnecessary rows from temp table so reduce the filtering and may help to improve performance ``` UPDATE orders AS o LEFT JOIN ( SELECT obe_order_master_id, id, added FROM customer_instalments GROUP BY obe_order_master_id HAVING COUNT(id) = 1 ) AS oci ON oci.obe_order_master_id = SUBSTRING(o.order_id, 4) SET o.final_customer_file_id = oci.id, o.client_work_delivered = oci.added ```
I would suggest to create separate column for Order\_id substring and make index on it. Then use this column in WHERE.
12,841,925
When I test a perl script under linux and use `time sh -c` to measure the time spent, I got a weird result: ``` real 14m11.903s user 34m39.319s sys 16m54.074s ``` which means the real time spent is even less than user time. And visually counting the time by myself, the script didn't spent as much as 34 minutes, and real time is closer to what I see. Has anyone have any clue about this? Thanks.
2012/10/11
[ "https://Stackoverflow.com/questions/12841925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354285/" ]
The script could have used more than 1 core.
The user line is showing the total CPU time that the process used directly. If your process has more than one thread and your cpu has more than one core then you may use more CPU time than wall clock time.
27,630,975
I need help in displaying the output of a rails helper method inside the script tags in the application.html.erb layout file. I put the following code just before the closing html tag: ``` <script> App.ready = function() { App.initApp(jQuery.parseJSON("<%= current_user_json %>")); } </script> ``` This current\_user\_json is a helper method that is in the application controller file. The output the above code produces in the browser(view page source) is: ``` <script> App.ready = function() { App.initApp(jQuery.parseJSON("{&quot;id&quot;:3,&quot;email&quot;:&quot;user5@user.com&quot;,&quot;username&quot;:null}")); } </script> ``` The proper output should be: ``` <script> App.ready = function() { App.initApp(jQuery.parseJSON('{"id":3,"email":"user5@user.com","username":null}')) } </script> ``` If someone could help me out, I will really be relieved of this problem I am trying to resolve for the past couple of days.
2014/12/24
[ "https://Stackoverflow.com/questions/27630975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3746444/" ]
If the filename is `BX-Book-Ratings.csv` then you need to use that instead of `BX-Book-Ratings:` in the command line. This is not a `sed` error, it's a problem from your shell.
Why do you use so many pipes? What about such approach: ``` sed 's/\&amp\;/\&/g;1d;s/;/$$$/g;s/"$$$"/";"/g;s/"//g' BX-Book-Ratings.csv > corrected_rating ``` Or if you want to store the result to a variable do it like this: ``` var=$(sed 's/\&amp\;/\&/g;1d;s/;/$$$/g;s/"$$$"/";"/g;s/"//g' BX-Book-Ratings.csv) ```
72,429,276
I am trying to create a form in vuejs, where a group of inputs can be append onclick. It works fine, but the problem is, All inputs return the same value. I am sharing an image here : [![enter image description here](https://i.stack.imgur.com/bmv1Y.png)](https://i.stack.imgur.com/bmv1Y.png) I am sharing my code from template : ``` <div class="form-group" v-for="(input,k) in data.invoice_product" :key="k"> <div class="row mb-2"> <div class="col-md-3"> <select class="form-control" v-model="data.invoice_product.product_id" @change="getProductCost"> <option v-for="(product, i) in products" :key="i" :value="product.id">{{ product.product_name }}</option> </select> </div> <div class="col-md-3"> <input type="text" class="form-control" placeholder="Quantity" v- model="data.invoice_product.quantity" @keyup="getProductCost"> </div> <div class="col-md-3"> <input type="text" class="form-control" placeholder="Total" v- model="data.invoice_product.total"> </div> <div class="col-md-3"> <span> <i class="fa fa-minus-circle" @click="removeElement(k)" v-show="k || ( !k && data.invoice_product.length > 1)">Remove</i> <i class="fa fa-plus-circle" @click="addElement(k)" v-show="k == data.invoice_product.length-1">Add fields</i> </span> </div> </div> </div> ``` from my script (I am excluding irrelevant code segments) : ``` export default { data() { return { data : { customer_id : '', vat : '' }, inputs: [{ product_id : '', quantity : '', total : '' }], input: { product_id : '', quantity : '', total : '' }, products : [] } }, methods : { getProductCost() { axios.get('/api/product-cost? product_id='+this.item.product_id+'&&quantity='+this.item.quantity, this.data).then(response => { this.input.total = response.data }) }, addElement() { this.data.invoice_product.push({ product_id : '', quantity : '', total : '' }) }, removeElement (index) { this.data.invoice_product.splice(index, 1) }, } ``` Input returns null if I use "input" instead : [![enter image description here](https://i.stack.imgur.com/orl1A.png)](https://i.stack.imgur.com/orl1A.png)
2022/05/30
[ "https://Stackoverflow.com/questions/72429276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13754248/" ]
It's incorrect, you can't use single name for same columns, ``` 'e.code as branch_code', 'e.id as branch_code', ``` change to ``` 'e.code as branch_code', 'e.id as branch_id', ```
go to config/database.php strict set false
236,157
Lean is a theorem prover and programming language. It's also as of writing the [Language of the Month](https://codegolf.meta.stackexchange.com/q/23916/56656)! What tips do people have for golfing in Lean? As always, tips should be specific to to Lean (e.g. "Remove comments" is not an answer), and stick to a single tip per answer.
2021/10/08
[ "https://codegolf.stackexchange.com/questions/236157", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/56656/" ]
Introductions ============= If you've just finished the natural number game you may be familiar with the `intro` tactic, this can be used to create implications / functions. However this tactic is rarely the golfiest. If your intro is the first part of your proof then an implicit forall is probably better. Compare: ```lean def q:list ℕ→ℕ:=by{intro x,induction x,exact 0,exact x_hd+x_ih} ``` with ```lean def q(x:list ℕ):ℕ:=by{induction x,exact 0,exact x_hd+x_ih} ``` This is frequently always your best option. However if the type of your function can be inferred you have other options. ``` def f:ℕ→ℕ:=by{intro x,exact x+3} def f(x:ℕ):ℕ:=by{exact x+3} def f:=λx,by{exact x+3} def f(x):=by{exact x+3} ``` These are ordered by length so implicit forall (the last option is still implicit forall) is the shortest. But the lambda can expression can have the `def f:=` removed if the function is your submission, making it the shortest in that case.
Use `by` instead of `begin ... end` ----------------------------------- `by` can be shorter than `begin` and `end`. ``` def foo(m:ℕ):m=m:=begin refl,end ``` is longer than ``` def bar(m:ℕ):m=m :=by refl ``` You can also use it for multiple tactics, though you'll need to encase the tactics in braces, as Wheat Wizard pointed out. For example, `by{rw add_assoc,refl}` is shorter than `begin rw add_assoc,refl end`.
236,157
Lean is a theorem prover and programming language. It's also as of writing the [Language of the Month](https://codegolf.meta.stackexchange.com/q/23916/56656)! What tips do people have for golfing in Lean? As always, tips should be specific to to Lean (e.g. "Remove comments" is not an answer), and stick to a single tip per answer.
2021/10/08
[ "https://codegolf.stackexchange.com/questions/236157", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/56656/" ]
Introductions ============= If you've just finished the natural number game you may be familiar with the `intro` tactic, this can be used to create implications / functions. However this tactic is rarely the golfiest. If your intro is the first part of your proof then an implicit forall is probably better. Compare: ```lean def q:list ℕ→ℕ:=by{intro x,induction x,exact 0,exact x_hd+x_ih} ``` with ```lean def q(x:list ℕ):ℕ:=by{induction x,exact 0,exact x_hd+x_ih} ``` This is frequently always your best option. However if the type of your function can be inferred you have other options. ``` def f:ℕ→ℕ:=by{intro x,exact x+3} def f(x:ℕ):ℕ:=by{exact x+3} def f:=λx,by{exact x+3} def f(x):=by{exact x+3} ``` These are ordered by length so implicit forall (the last option is still implicit forall) is the shortest. But the lambda can expression can have the `def f:=` removed if the function is your submission, making it the shortest in that case.
The `;` and `<|>` combinators. ------------------------------ `;` makes it so that all subgoals created by the last tactic have the next tactic applied; for example, `lemma asda (n : ℕ) : n = n := by { induction n; refl }` is a valid proof. As a bonus, it also allows you to not use the braces (e.g. `def k(n:ℕ):n=n:=by induction n;refl`). The `<|>` is a bit more niche, but still useful; it allows you to do one tactic, and if it fails, the other instead. It also allows for no braces (although this is longer than `,`, so not as useful). For example: ``` example(x):0+x=x:=by induction x;refl<|>rw nat.zero_add ```
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
u-substitution! Let $u=(x+5)^{1/2}$ so that $du=\frac{1}{2\sqrt{x+5}}dx$, or $2udu=dx$. Then your integral is given by \begin{align\*} I&=3\int (u^2-5)u2udu\\ &=6\int u^4-5u^2du\\ &=\frac{6}{5}u^5-10u^2+C\\ &=\frac{6}{5}(x+5)^{\frac{5}{2}}-10(x+5)^\frac{3}{2}+C \end{align\*}
**Hint**: rationalize by taking $u = \sqrt{x+5}$. Alternatively, and perhaps even simpler: $$x\sqrt{x+5} = \left(x+5-5\right)\sqrt{x+5} = \left(x+5\right)^{3/2}-5\left(x+5\right)^{1/2}$$ So: $$\int x\sqrt{x+5} \,\mbox{d}x = \int \left(x+5\right)^{3/2} \,\mbox{d}x -5\int \left(x+5\right)^{1/2} \,\mbox{d}x = \ldots$$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Set $u=x+5$, so the integrand becomes $3(u-5)\sqrt{u} = 3u^{3/2}-15u^{1/2}.$ (And here $dx=du$.) In general, square roots and addition don't get along well together, so when you see $\sqrt{a\pm b}$, you can make the difficulty go away by substituting $u=a \pm b.$
**Hint**: rationalize by taking $u = \sqrt{x+5}$. Alternatively, and perhaps even simpler: $$x\sqrt{x+5} = \left(x+5-5\right)\sqrt{x+5} = \left(x+5\right)^{3/2}-5\left(x+5\right)^{1/2}$$ So: $$\int x\sqrt{x+5} \,\mbox{d}x = \int \left(x+5\right)^{3/2} \,\mbox{d}x -5\int \left(x+5\right)^{1/2} \,\mbox{d}x = \ldots$$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
u-substitution! Let $u=(x+5)^{1/2}$ so that $du=\frac{1}{2\sqrt{x+5}}dx$, or $2udu=dx$. Then your integral is given by \begin{align\*} I&=3\int (u^2-5)u2udu\\ &=6\int u^4-5u^2du\\ &=\frac{6}{5}u^5-10u^2+C\\ &=\frac{6}{5}(x+5)^{\frac{5}{2}}-10(x+5)^\frac{3}{2}+C \end{align\*}
Hint : Take $x+5=t^2$. Then the integral reduces to $$3\int (t^2-5)t 2t dt=6\int t^4-5t^2 $$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Set $u=x+5$, so the integrand becomes $3(u-5)\sqrt{u} = 3u^{3/2}-15u^{1/2}.$ (And here $dx=du$.) In general, square roots and addition don't get along well together, so when you see $\sqrt{a\pm b}$, you can make the difficulty go away by substituting $u=a \pm b.$
Hint : Take $x+5=t^2$. Then the integral reduces to $$3\int (t^2-5)t 2t dt=6\int t^4-5t^2 $$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
u-substitution! Let $u=(x+5)^{1/2}$ so that $du=\frac{1}{2\sqrt{x+5}}dx$, or $2udu=dx$. Then your integral is given by \begin{align\*} I&=3\int (u^2-5)u2udu\\ &=6\int u^4-5u^2du\\ &=\frac{6}{5}u^5-10u^2+C\\ &=\frac{6}{5}(x+5)^{\frac{5}{2}}-10(x+5)^\frac{3}{2}+C \end{align\*}
Set $u=x+5$, so the integrand becomes $3(u-5)\sqrt{u} = 3u^{3/2}-15u^{1/2}.$ (And here $dx=du$.) In general, square roots and addition don't get along well together, so when you see $\sqrt{a\pm b}$, you can make the difficulty go away by substituting $u=a \pm b.$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
u-substitution! Let $u=(x+5)^{1/2}$ so that $du=\frac{1}{2\sqrt{x+5}}dx$, or $2udu=dx$. Then your integral is given by \begin{align\*} I&=3\int (u^2-5)u2udu\\ &=6\int u^4-5u^2du\\ &=\frac{6}{5}u^5-10u^2+C\\ &=\frac{6}{5}(x+5)^{\frac{5}{2}}-10(x+5)^\frac{3}{2}+C \end{align\*}
Or it can be used the integration by parts: $u = x, dv=\sqrt{x+5}dx \Rightarrow du=dx,v=\frac{2}{3}(x+5)^{\frac{3}{2}}.$ $\int 3x\sqrt{x+5}dx=3\left[x\cdot\frac{2}{3}(x+5)^{\frac{3}{2}}-\int\frac{2}{3}(x+5)^{\frac{3}{2}}dx \right]=2x(x+5)^{\frac{3}{2}}-\frac{4}{5}(x+5)^{\frac{5}{2}}+C=\frac{2}{5}(x+5)^{\frac{3}{2}}(5x-2(x+5))+C=\frac{2}{5}(x+5)^{\frac{3}{2}}(3x-10)+C$
2,219,216
The question is: > > Find the vector equation of the line with Cartesian equation: > > > $$5x + 1 = -10y - 4 = 2z$$ > > > I know the vector equation of a line is $\textbf{r} × \textbf{v} = \textbf{a} × \textbf{v}$, where $\textbf{r}$ is the position vector of a point on the line, $\textbf{a}$ is a fixed point on the line, and $\textbf{v}$ is a direction vector for $\textit{L}$. What I don't get is how the Cartesian equation can give me what I need. If someone could please explain the process of converting Cartesian into vector form and highlight the link between Cartesian and vector equations of lines that would be great.
2017/04/05
[ "https://math.stackexchange.com/questions/2219216", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Set $u=x+5$, so the integrand becomes $3(u-5)\sqrt{u} = 3u^{3/2}-15u^{1/2}.$ (And here $dx=du$.) In general, square roots and addition don't get along well together, so when you see $\sqrt{a\pm b}$, you can make the difficulty go away by substituting $u=a \pm b.$
Or it can be used the integration by parts: $u = x, dv=\sqrt{x+5}dx \Rightarrow du=dx,v=\frac{2}{3}(x+5)^{\frac{3}{2}}.$ $\int 3x\sqrt{x+5}dx=3\left[x\cdot\frac{2}{3}(x+5)^{\frac{3}{2}}-\int\frac{2}{3}(x+5)^{\frac{3}{2}}dx \right]=2x(x+5)^{\frac{3}{2}}-\frac{4}{5}(x+5)^{\frac{5}{2}}+C=\frac{2}{5}(x+5)^{\frac{3}{2}}(5x-2(x+5))+C=\frac{2}{5}(x+5)^{\frac{3}{2}}(3x-10)+C$
3,981,419
Let $f:\mathbb{Z}\_{>0} \rightarrow \mathbb{C}$ be a function. Now require $f$ to satisfy the condition $$ |f(n)|\leq n^{o(1)} $$ where $o(1)$ is any function $g(n)$ satisfy $\frac{g(n)}{1}\rightarrow 0$ as $n\rightarrow\infty$. Can someone give some example of such $f(n)$ besides constant functions?
2021/01/11
[ "https://math.stackexchange.com/questions/3981419", "https://math.stackexchange.com", "https://math.stackexchange.com/users/813593/" ]
It's a Monday afternoon, so let's have some fun: Let's start with the assumption that there is a set $S = \{e, a, b, c\}$ with binary operation $\*$ having Cayley table: $$\begin{array} {|r|r|}\hline \cdot & e & a & b & c \\ \hline e & e & a & b & c \\ \hline a & a & e & c & b \\ \hline b & b & c & e & a \\ \hline c & c & b & a & e \\ \hline \end{array}$$ We're going to use [Light's associativity test](https://en.wikipedia.org/wiki/Light%27s_associativity_test). Because $S$ is generated by $a$ and $b$ (i.e. $e = a \* a$ and $c = a \* b$), it suffices to show that for all $x, y \in S$ we have both $x \* (a \* y) = (x \* a) \* y$, and $x \* (b \* y) = (x \* b) \* y$. Let's check the first of these claims: start by defining binary operations $x \star y = x \* (a \* y)$ and $x \circ y = (x \* a) \* y$. We'll be down when we show that the Cayley tables for $\star$ and $\circ$ agree. There are a few optimizations we can take based on the circumstances: * As the Cayley table is symmetric about the diagonal, we know that $(S, \*)$ is abelian. It follows that $x \star y = y \circ x$ (write it out!). Therefore $x \star x = x \circ x$. Moreover, if $x \star y = x \circ y$ then also $y \star x = y \circ x$ (again, convince yourself!). * We don't need to include the identity element in our table, because if either $x = e$ or $y = e$, then $x \star y = x \circ y$. So now the question is how much of the two Cayley tables do we have to check? Using the above remarks, you get down to something like the below, where "No" means "No, you don't need to check it": $$\begin{array} {|r|r|}\hline \star & e & a & b & c \\ \hline e & No & No & No & No \\ \hline a & No & No & ? & ? \\ \hline b & No & No & No & ? \\ \hline c & No & No & No & No \\ \hline \end{array}$$ When the smoke clears, you see that it suffices to check: $$a \star b = a \circ b,\ a \star c = a \circ c,\ \text{and } b \star c = b \circ c.$$ To check each equation, you need to do 4 multiplications (i.e. Cayley table look-ups). For instance, \begin{align\*} a \star b &= a \* (a \* b) = a \* c = b,\\ a \circ b &= (a \* a) \* b = e \* b = b. \end{align\*} To conclude: to check whether the Klein four-group is associative, for each of its 2 generators, it suffices to check 3 "associativity equations" in $(S, \*)$. I'm curious whether there are further simplifications one can make by using algebraic properties specific to the Klein four-group table, but this is all the mileage I can get out of Light's test alone.
Thank you all for your help! I will post here my final answer: First, we'll write down the Cayley Table: $\begin{array} {|r|r|}\hline \* & e & a & b & c \\ \hline e & e & a & b & c \\ \hline a & a & e & c & b \\ \hline b & b & c & e & a \\ \hline c & c & b & a & e \\ \hline \end{array}$ From the symmetry along the main diagonal of the table, it's immediate that the operation is Abelian. We'll check whether $x,y,z\in P$ satisfy $(x\*y)\*z=x\*(y\*z)$. If any of the elements are $e$, the equality is immediately true. If $x=z$ the equality is immediately true (due to the operation being Abelian). If $y=x\neq z$, the left side of the equation is $(x\*y)\*z=e\*z=z$. For the right side, we'll define $w=y\*z$. So $x\*(y\*z)=y\*w$. By definition, $w$ is the third distinct element so that $w\neq e$. (If $x=y=a$ and $z=c$ then $w=b$). Hence $y\*w=z$. Similarly, it can be proven for $y=z\neq x$. for $x\neq y\neq z$, $(x\*y)\*z=z\*z=e$ and $x\*(y\*z)=x\*x=e$. So the equality is true for any $x,y,z$, the operation is associative.
3,981,419
Let $f:\mathbb{Z}\_{>0} \rightarrow \mathbb{C}$ be a function. Now require $f$ to satisfy the condition $$ |f(n)|\leq n^{o(1)} $$ where $o(1)$ is any function $g(n)$ satisfy $\frac{g(n)}{1}\rightarrow 0$ as $n\rightarrow\infty$. Can someone give some example of such $f(n)$ besides constant functions?
2021/01/11
[ "https://math.stackexchange.com/questions/3981419", "https://math.stackexchange.com", "https://math.stackexchange.com/users/813593/" ]
Using the $K\_4$ properties: : elements are self-inverse : operation is commutative Consider $x,y,z \in K\_4$, not necessarily distinct. We ask if $x\cdot (y \cdot z) = (x\cdot y) \cdot z$. If any of $x,y,z$ is the identity, the equality is immediately true. If $x,y,z$ are distinct, the result is the identity (since inverse is unique): $x\cdot (y \cdot z) = x\cdot x = e$ $(x\cdot y) \cdot z = z\cdot z = e$ For $x=z$, commutativity gives: $(x\cdot y)\cdot x =(y\cdot x)\cdot x =x\cdot (y\cdot x )$ If $y=x\neq z$, $(x\cdot y) \cdot z = e\cdot z = z$ and $x\cdot (y \cdot z) = y\cdot w = z$ where $w$ is the other element, $w\neq (x=y),z$ and similarly if $y=z\neq x$.
Thank you all for your help! I will post here my final answer: First, we'll write down the Cayley Table: $\begin{array} {|r|r|}\hline \* & e & a & b & c \\ \hline e & e & a & b & c \\ \hline a & a & e & c & b \\ \hline b & b & c & e & a \\ \hline c & c & b & a & e \\ \hline \end{array}$ From the symmetry along the main diagonal of the table, it's immediate that the operation is Abelian. We'll check whether $x,y,z\in P$ satisfy $(x\*y)\*z=x\*(y\*z)$. If any of the elements are $e$, the equality is immediately true. If $x=z$ the equality is immediately true (due to the operation being Abelian). If $y=x\neq z$, the left side of the equation is $(x\*y)\*z=e\*z=z$. For the right side, we'll define $w=y\*z$. So $x\*(y\*z)=y\*w$. By definition, $w$ is the third distinct element so that $w\neq e$. (If $x=y=a$ and $z=c$ then $w=b$). Hence $y\*w=z$. Similarly, it can be proven for $y=z\neq x$. for $x\neq y\neq z$, $(x\*y)\*z=z\*z=e$ and $x\*(y\*z)=x\*x=e$. So the equality is true for any $x,y,z$, the operation is associative.
53,345,594
I'm hoping to groupby users and find the first two uploads. I've figured out how to get the first date via minimum, but I'm having trouble getting that second upload date. Then would like to get the average time between the two upload dates for all users. df: ``` Date_Uploaded User_ID Display_Status 2018-10-27 abc123 Cleared 2018-10-28 abc123 Cleared 2018-10-29 abc123 Pending 2018-09-21 abc123 Pending 2018-08-24 efg123 Pending 2018-08-01 efg123 Pending 2018-07-25 efg123 Pending ```
2018/11/16
[ "https://Stackoverflow.com/questions/53345594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9712631/" ]
Using `sort_values` + `head` ``` df.sort_values('Date_Uploaded').groupby('User_ID').head(2) Out[152]: Date_Uploaded User_ID Display_Status 6 2018-07-25 efg123 Pending 5 2018-08-01 efg123 Pending 3 2018-09-21 abc123 Pending 0 2018-10-27 abc123 Cleared ```
`sort`, calculate the difference and then `groupby` + `nth(1)` to get the difference between the first uploads, if it exists (users with 1 date will not show up). ``` import pandas as pd df['Date_Uploaded'] = pd.to_datetime(df.Date_Uploaded) df = df.sort_values(['User_ID', 'Date_Uploaded']) df.Date_Uploaded.diff().groupby(df.User_ID).nth(1) #User_ID #abc123 36 days #efg123 7 days #Name: Date_Uploaded, dtype: timedelta64[ns] ``` --- If you just want the average then average that series: ``` df.Date_Uploaded.diff().groupby(df.User_ID).nth(1).mean() #Timedelta('21 days 12:00:00') ```
53,345,594
I'm hoping to groupby users and find the first two uploads. I've figured out how to get the first date via minimum, but I'm having trouble getting that second upload date. Then would like to get the average time between the two upload dates for all users. df: ``` Date_Uploaded User_ID Display_Status 2018-10-27 abc123 Cleared 2018-10-28 abc123 Cleared 2018-10-29 abc123 Pending 2018-09-21 abc123 Pending 2018-08-24 efg123 Pending 2018-08-01 efg123 Pending 2018-07-25 efg123 Pending ```
2018/11/16
[ "https://Stackoverflow.com/questions/53345594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9712631/" ]
Using `sort_values` + `head` ``` df.sort_values('Date_Uploaded').groupby('User_ID').head(2) Out[152]: Date_Uploaded User_ID Display_Status 6 2018-07-25 efg123 Pending 5 2018-08-01 efg123 Pending 3 2018-09-21 abc123 Pending 0 2018-10-27 abc123 Cleared ```
Since the other answers explain pretty well how to achieve this, I'll give you a one-liner for a change ```  In [1]: df.groupby('User_ID').apply(lambda g: g.sort_values('Date_Uploaded')['Date_Uploaded'][:2].diff()).mean()  Out[1]: Timedelta('21 days 12:00:00') ```
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
For Localhost we don't really need https, please try with <http://localhost:9001/test>
the reason was in an incorrect link. In the controller I have used @RequestMapping(value="/{baseSiteId}/test") And this {baseSiteId} was not what I expected.
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
``` const transporter = nodemailer.createTransport({ host:'smtp.gmail.com', port:587, secure:false, requireTLC:true, auth: { user:'youmail@gmail.com', pass:'youpass' } } ``` Notice that `secure:` is `false`. The error occurs when `secure:` is `true`.
the reason was in an incorrect link. In the controller I have used @RequestMapping(value="/{baseSiteId}/test") And this {baseSiteId} was not what I expected.
61,916,754
During request GET in Postman (<https://localhost:9001/test>) I've received an error: *Error: write EPROTO 8768:error:1408F10B:SSL **routines:ssl3\_get\_record:wrong version number**:c:\users\administrator\buildkite-agent\builds\pm-electron\postman\electron-release\vendor\node\deps\openssl\openssl\ssl\record\ssl3\_record.c:252:* *Warning: This request did not get sent completely and might not have all the required system headers*. Postman Configuration: * SSL certificate verification is disabled; * Proxy configuration - Default Proxy Configuration and Proxy configurations for sending requests are disabled; * Request timeout in ms - 0.
2020/05/20
[ "https://Stackoverflow.com/questions/61916754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730856/" ]
check that you are using the `HTTP` protocol not `HTTPS` to send requests to the server: ### example ```js export const config = { baseUrl: "http://localhost:4000" } ```
the reason was in an incorrect link. In the controller I have used @RequestMapping(value="/{baseSiteId}/test") And this {baseSiteId} was not what I expected.