qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
368
> > * Explaining the plot, character, setting or symbolism of a myth > * Historical or societal context of a myth > * Myth identification > * Translations of and primary sources for a myth > > > Well, it sure isn't explaining, contexting, indentifying, or translations/primary sourcing of. So are they on-topic?
2016/11/16
[ "https://mythology.meta.stackexchange.com/questions/368", "https://mythology.meta.stackexchange.com", "https://mythology.meta.stackexchange.com/users/967/" ]
The recent Thor question is deemed "too broad" but there was a recent question [How do people become immortal as per Taoism?](https://mythology.stackexchange.com/questions/2022/how-do-people-become-immortal-as-per-taoism) that asked **"What are all the ways to become immortal? Also, what is cultivating Tao and yourself?"** That was not deemed too broad, but a very useful question on whether the plot of the Thor movie deviates from the Eddas is deemed unacceptable. I'm sorry, but all I see here is prejudice b/c the Marvel rendition of mythology is considered low-brow and beneath those with scholarly inclinations. We're living in an age when the Classics are no longer part of the basic curriculum, and most people have probably heard about Thor through the comic books. Why not educate these people by actually answering what is a sincere question?
133,406
I know that the effects of a spell don’t combine if it is cast multiple times. Only the most potent effect would be applied. In our last game, this topic came up in regards to the [*Harm*](https://www.dndbeyond.com/spells/harm) spell. *Harm* was cast on an opponent. He failed the save, took a lot of damage and his hit point maximum was reduced drastically. A turn later, he got slammed again with *Harm*. This time, he succeeded on the save and very little necrotic damage was dealt. Then, the discussion started whether his hit point maximum would now be further reduced or if the “more potent” Harm spell takes precedence. Naturally, I argued that his hit point maximum would not be reduced further, because effects of the same spell cast multiple times don’t stack. The counterargument was, that the necrotic damage dealt by the *Harm* spell is clearly an effect of the spell. And no one would argue, that the damage dealt by two consecutive *Harm* spells would only be applied once. So now I ask you: **Can the hit point maximum be reduced repeatedly with multiple *Harm* spells?**
2018/10/11
[ "https://rpg.stackexchange.com/questions/133406", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/40660/" ]
The target's maximum hit points will only be reduced once ========================================================= From [*Harm*](https://www.dndbeyond.com/spells/harm) (PHB, pg. 249): > > If the target fails the saving throw, **its hit point maximum is reduced for 1 hour** by an amount equal to the necrotic damage it took. Any effect that removes a disease allows a creature's hit point maximum to return to normal before that time passes. > > > [Combining Magical Effects](https://www.dndbeyond.com/compendium/rules/basic-rules/spellcasting#CombiningMagicalEffects), from the PHB (pg. 254): > > The effects of different spells add together while the durations of those spells overlap. The effects of the same spell cast multiple times don't combine, however. Instead, **the most potent effect - such as the highest bonus - from those castings applies while their durations overlap**. > > > So multiple castings of the same spell will not stack, but rather the one that dealt the largest amount of damage would take precedence. This rule applies because the hit point reduction has a duration attached to it, unlike, say, a [Wraith's](https://www.dndbeyond.com/monsters/wraith) Life Drain (MM, pg. 302), which is an ongoing affect (albeit with an end condition): > > ... its hit point maximum is reduced by an amount equal to the damage taken. **This reduction lasts until the target finishes a long rest.** > > > Of course, this doesn't stop the target's maximum hit points from being reduced further by something *other* than the *Harm* spell... This is essentially the argument you presented at your table, but I see no reason that this wouldn't apply.
35,548,923
I'm trying to find a way to make it easier to center the content and make the distance between everything the same if the screen gets smaller. If the screen gets less height the content needs to get closer to each other but between every div needs to be the same distance. HTML ``` <div id="our_culture"class="explor_us"> <div class="colums"> <div class="colum1" id="pic1"> <div class="wilpe_logo"> <a href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/SVG_logo.svg/2000px-SVG_logo.svg.png" width="150px" height="100px" alt="" /></a> </div> <div class="text_holder"> <p> Wilpe is an investment group specialized in supporting and developing growing businesses and brands. Wilpe believes in knowledge. <div class="button_two"> <a class="button_text" href="#">Explore</a> </div> </div> </div> <div class="colum1" id="pic1"> <div class="wilpe_logo"> <a href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/SVG_logo.svg/2000px-SVG_logo.svg.png" width="150px" height="100px" alt="" /></a> </div> <div class="text_holder"> <p> Wilpe is an investment group specialized in supporting and developing growing businesses and brands. Wilpe believes in knowledge. <div class="button_two"> <a class="button_text" href="#">Explore</a> </div> </div> </div> <div class="colum1" id="pic1"> <div class="wilpe_logo"> <a href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/SVG_logo.svg/2000px-SVG_logo.svg.png" width="150px" height="100px" alt="" /></a> </div> <div class="text_holder"> <p> Wilpe is an investment group specialized in supporting and developing growing businesses and brands. Wilpe believes in knowledge. <div class="button_two"> <a class="button_text" href="/wilpe_import.html">Explore</a> </div> </div> </div> <div class="colum2" id="pic1"> <div class="wilpe_logo"> <a href="wilpetrade.html"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/SVG_logo.svg/2000px-SVG_logo.svg.png" width="150px" height="100px" alt="" /></a> </div> <div class="text_holder"> <p> Wilpe is an investment group specialized in supporting and developing growing businesses and brands. Wilpe believes in knowledge. <div class="button_two"> <a class="button_text" href="/wilpetrade.html">Explore</a> </div> </div> </div> <div class="colum2"id="pic1"> <div class="wilpe_logo"> <a href="#"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/02/SVG_logo.svg/2000px-SVG_logo.svg.png" width="150px" height="100px" alt="" /></a> </div> <div class="text_holder"> <p> Wilpe is an investment group specialized in supporting and developing growing businesses and brands. Wilpe believes in knowledge. <div class="button_two"> <a class="button_text" href="/wilpe_deal.html">Explore</a> </div> </div> </div> </div> <div class="photo_overlay_filter6"></div> </div> ``` CSS ``` .colum1{ margin-top: -20px; width: 20%; height: 55vh; float: right; } .colum2{ margin-top: -20px; width: 20%; height: 55vh; float: right; } .text_holder{ color: white; padding: 0px; text-align: center; font-size: 16px; width: 80%; margin: auto; margin-top: 18%; z-index: 83; position: relative; } .wilpe_logo{ width: 150px; height: 100px; margin: auto; margin-top: 20px; z-index: 83; position: relative; } #pic1{ background-image:url(http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg); background-size: cover; background-position: center; } ``` <https://jsfiddle.net/u60g7v89/>
2016/02/22
[ "https://Stackoverflow.com/questions/35548923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4554544/" ]
This can now be accomplished with flexbox. This problem is exactly what the flex model was made for. ```css html,body{ width:100%; height:100%; margin:0; padding:0; } .FlexBox{ display:flex; width:100%; height:100%; } .FlexItem{ width:100%; background:#b00; border:5px solid #ddd; flex:1; } ``` ```html <div class="FlexBox"> <div class="FlexItem">1</div> <div class="FlexItem">2</div> <div class="FlexItem">3</div> <div class="FlexItem">4</div> <div class="FlexItem">5</div> </div> ``` To adjust the space between items simply set the width for each item to your desired value, in this case there are 5 elements so I want each to be 15%. (so the total width is less than 100%). Then set `justify-content` property on flex container to either `spacce-around` or `space-between`. ```css html,body{ width:100%; height:100%; margin:0; padding:0; } .FlexBox{ display:flex; width:100%; height:100%; justify-content:space-around; /*(space-between creates equal space with items left aligned)*/ } .FlexItem{ width:15%; /* (total items less than 100%) */ background:#b00; border:5px solid #ddd; } ``` ```html <div class="FlexBox"> <div class="FlexItem">1</div> <div class="FlexItem">2</div> <div class="FlexItem">3</div> <div class="FlexItem">4</div> <div class="FlexItem">5</div> </div> ``` [Support -------](http://caniuse.com/#feat=flexbox) Flex is now supported in all major browsers. *(Some setups can be buggy in i.e, but what's new? Just test before use.)*
25,946,796
I want to get 6 days of the week starting from the given date, but the if clause is not taking the 'SUNDAY'. ``` V DATE :=TO_DATE (&H, 'DDMMYYYY'); V1 DATE:=V+6; V2 VARCHAR(10); BEGIN WHILE V<V1 LOOP V2:=TO_CHAR(V,'DAY'); IF V2='SUNDAY' THEN DBMS_OUTPUT.PUT_LINE('TODAY IS SUNDAY');-- IF IS NOT TAKING THE VALUE END IF; DBMS_OUTPUT.PUT_LINE(V2||V); V:=V+1; END LOOP; END; ``` Output: ``` FRIDAY 19-SEP-14 SATURDAY 20-SEP-14 SUNDAY 21-SEP-14 MONDAY 22-SEP-14 TUESDAY 23-SEP-14 WEDNESDAY24-SEP-14 ```
2014/09/20
[ "https://Stackoverflow.com/questions/25946796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2686661/" ]
The issue is that `TO_CHAR(V,'DAY')` adds spaces after the day, because it pads the day to the longest day name. You can also see this in your output, where all the dates are perfectly aligned underneath each other. The solution: `Trim` the value: ``` IF TRIM(V2) = 'SUNDAY' THEN ``` This issue is also described here: <http://www.orafaq.com/forum/t/45942/0/> Another nice solution is to use `numeric date language` as an NLS setting to get the day number: ``` V3 := TO_CHAR(V, 'DAY', 'NLS_DATE_LANGUAGE=''numeric date language'''); ``` This way, the TO\_CHAR function will return a number (as string) from '1' (Monday) to '7' (Sunday), which is not localized, and is not affected by regional settings when Sunday could be the first day. `numeric date language` is a special 'language' in which day names are numbers. Because it is actually a day name, you need to use `'DAY'` instead of `'D'`, and for that same reason, it is not affected by the territory. It is a hidden feature which I think is used for testing the localization feature of the data functions. The advantage is that it doesn't depend on installed languages, although I guess that English will also be always available.
26,049,171
I have multiple instances of 4096 items. I need to search and find an item on a reocurring basis and i'd like to optimize it. Since not all 4096 items may be used, I thought, an approach to speed things up would be to use a linked list instead of an array. And whenever I have to search an item, once I found it, I'd place it on the head of the list so that next time it comes around, I'd have to do only minimal search (loop) effort. Does this sound right? **EDIT1** I don't think the binary search tree idea is really what I can use as I have ordered data, like an array i.e. every node following the previous one is larger which defeats the purpose, doesn't it? I have attempted to solve my problem with caching and came up with something like this: ``` pending edit ``` But the output I get, suggests that it doesn't work like I'd like it to: any suggestions on how I can improve this?
2014/09/25
[ "https://Stackoverflow.com/questions/26049171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1198201/" ]
When it comes to performance there is only one important rule: measure it! In your case you could for example have two different considerations, a theoretical runtime analysis and what is really going on one the machine. Both are heavily depending on the characteristics of your 4096 items. If your data is sorted you can have a O(log n) search, if it is unsorted it is worst case O(n) etc. Regarding your idea of a linked list you might have more hardware cache misses because the data is not stored together anymore (spatial locality) ending up in having a slower implementation even if your theoretical consideration is right. If you interested in general in such problems I recommend this cool talk from the GoingNative 2013 <http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly>
20,502,369
I'm drawing a pie chart using a CAShapeLayer for each slice of the pie. Even when the end angle of one pie slice is equal to the start angle of the adjacent slice, antialiasing is resulting in the underlying background color appearing between each pice slice if the border between slices is at an angle. [![http://i.stack.imgur.com/Qdu8d.png](https://i.stack.imgur.com/Qdu8d.png)](https://i.stack.imgur.com/Qdu8d.png) I'd like to eliminate the slight gap between slices while still using antialiasing so the resulting pie cart still looks smooth. Conceptually, it seems if there were a way to apply antialiasing to the entire CALayer and it's pie slice sublayers after all the pie slices were drawn, that would do the trick... The pie slices would be antialiased into each other instead of into the background. I've played around with as many CALayer properties as I can think of and am having a hard time finding more information on this. Any ideas? **UPDATE:** See my answer below.
2013/12/10
[ "https://Stackoverflow.com/questions/20502369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3088042/" ]
**UPDATE:** Rob's answer is pretty good, but possibly results in other antialiasing issues. I ended up 'filling' the gaps by drawing 1pt wide radial lines along the end angle of each pie slice, each line being the same color as the adjacent slice. These lines are drawn at a lower z index than the pie slices, so they are underneath. Here's what they look like without the pie slices drawn on top: ![The filler lines with no slices drawn.](https://i.stack.imgur.com/KcW3z.png) And here's the final product: ![Final result with lines underneath and slices on top.](https://i.stack.imgur.com/MD1ij.png)
37,160,929
I am having a dataframe that contains columns named id, country\_name, location and total\_deaths. While doing data cleaning process, I came across a value in a row that has `'\r'` attached. Once I complete cleaning process, I store the resulting dataframe in destination.csv file. Since the above particular row has `\r` attached, it always creates a new row. ``` id 29 location Uttar Pradesh\r country_name India total_deaths 20 ``` I want to remove `\r`. I tried `df.replace({'\r': ''}, regex=True)`. It isn't working for me. Is there any other solution. Can somebody help? ### Edit: In the above process, I am iterating over df to see if `\r` is present. If present, then need to replace. Here `row.replace()` or `row.str.strip()` doesn't seem to be working or I could be doing it in a wrong way. I don't want specify the column name or row number while using `replace()`. Because I can't be certain that only 'location' column will be having `\r`. Please find the code below. ``` count = 0 for row_index, row in df.iterrows(): if re.search(r"\\r", str(row)): print type(row) #Return type is pandas.Series row.replace({r'\\r': ''} , regex=True) print row count += 1 ```
2016/05/11
[ "https://Stackoverflow.com/questions/37160929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1777919/" ]
Another solution is use [`str.strip`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html): ``` df['29'] = df['29'].str.strip(r'\\r') print df id 29 0 location Uttar Pradesh 1 country_name India 2 total_deaths 20 ``` If you want use [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html), add `r` and one `\`: ``` print df.replace({r'\\r': ''}, regex=True) id 29 0 location Uttar Pradesh 1 country_name India 2 total_deaths 20 ``` In `replace` you can define column for replacing like: ``` print df id 29 0 location Uttar Pradesh\r 1 country_name India 2 total_deaths\r 20 print df.replace({'29': {r'\\r': ''}}, regex=True) id 29 0 location Uttar Pradesh 1 country_name India 2 total_deaths\r 20 print df.replace({r'\\r': ''}, regex=True) id 29 0 location Uttar Pradesh 1 country_name India 2 total_deaths 20 ``` EDIT by comment: ``` import pandas as pd df = pd.read_csv('data_source_test.csv') print df id country_name location total_deaths 0 1 India New Delhi 354 1 2 India Tamil Nadu 48 2 3 India Karnataka 0 3 4 India Andra Pradesh 32 4 5 India Assam 679 5 6 India Kerala 128 6 7 India Punjab 0 7 8 India Mumbai, Thane 1 8 9 India Uttar Pradesh\r\n 20 9 10 India Orissa 69 print df.replace({r'\r\n': ''}, regex=True) id country_name location total_deaths 0 1 India New Delhi 354 1 2 India Tamil Nadu 48 2 3 India Karnataka 0 3 4 India Andra Pradesh 32 4 5 India Assam 679 5 6 India Kerala 128 6 7 India Punjab 0 7 8 India Mumbai, Thane 1 8 9 India Uttar Pradesh 20 9 10 India Orissa 69 ``` If need replace only in column `location`: ``` df['location'] = df.location.str.replace(r'\r\n', '') print df id country_name location total_deaths 0 1 India New Delhi 354 1 2 India Tamil Nadu 48 2 3 India Karnataka 0 3 4 India Andra Pradesh 32 4 5 India Assam 679 5 6 India Kerala 128 6 7 India Punjab 0 7 8 India Mumbai, Thane 1 8 9 India Uttar Pradesh 20 9 10 India Orissa 69 ```
2,351,681
Let $X\_1,...,X\_k$ are independent random variables and each $X\_i \thicksim Po(\lambda\_i), \forall i \in\{1,...k\}$ then derive the conditional pdf of $X = (X\_1,...X\_k)$ in case $X\_1 +...+X\_k= n$. --- Since two random variables case, such as $X\_1 \thicksim Po(\lambda\_1)$ and $X\_2\thicksim Po(\lambda\_2)$ which are independent and $X\_1+X\_2 = n $, $P(X\_1=x\_1\mid X\_1+X\_2 =n) = \begin{pmatrix}n\\x\end{pmatrix}\cdot\begin{pmatrix}\dfrac{\lambda\_1}{\lambda\_1+\lambda\_2}\end{pmatrix}^{x\_1}\cdot\begin{pmatrix}\dfrac{\lambda\_2}{\lambda\_1+\lambda\_2}\end{pmatrix}^{x\_2}$, through the analogy of it, $k$ random variables case would be represented as following: $P((X\_1,...,X\_k)=(x\_1,...,x\_k)\mid X\_1+..+X\_k =n)) \\= \begin{pmatrix}n\\x\_1...x\_k\end{pmatrix}\cdot\begin{pmatrix}\dfrac{\lambda\_1}{\lambda\_1+..+\lambda\_k}\end{pmatrix}^{x\_1}\cdot\cdot\cdot\begin{pmatrix}\dfrac{\lambda\_k}{\lambda\_1+..+\lambda\_k}\end{pmatrix}^{x\_k}$ Is this reasoning available and renders right answer?
2017/07/08
[ "https://math.stackexchange.com/questions/2351681", "https://math.stackexchange.com", "https://math.stackexchange.com/users/449209/" ]
Assuming the numbers are given in decimal representation, you actually got sequences $a\_i,b\_i\in\{0,1,2,3,4,5,6,7,8,9\}\;$ of digites, interpreted as the numbers $$a=\sum\_{i=0}^n a\_i10^i, \qquad b=\sum\_{j=0}^m b\_i10^i$$ respectively. When multiplying you will have to pair up all those terms in the following way: $$ab=\sum\_{i=0}^n\sum\_{j=0}^m a\_ib\_j10^{i+j}.$$ When you are looking for the $4$-th digit of $ab$, you just have to include those pairs that have a chance to eventually influence the coefficient $10^3$ of the result. These are the pairs $a\_ib\_j$ with $i+j\leq 3$. Independent of the length of the input numbers, these are at most $10$ pairs. The reason why you can drop all pairs with $i+j\geq 4$ is because they all are multiples of $10^4$, hence have four trailing zeros and do not influence the $4$-th digit of the result. *Side note*: This will be of no big use when dealing with the usual computer integers as used in programming. Extracting the digits from the numbers might be more expensive than the full but hardware supported multiplication. --- **Example** Applying this to your example above, we have \begin{align} 452 &= 4\cdot 10^2+ 5\cdot 10^1+ 2\cdot 10^0,\\ 945 &= 9\cdot 10^2+ 4\cdot 10^1+ 5\cdot 10^0. \end{align} We compute the relevant fragment \begin{align} 10^0\cdot 2\cdot 5 &+ 10^1\cdot(2\cdot4+5\cdot5) \\ &+ 10^2\cdot(2\cdot 9+ 5\cdot4 + 4\cdot 5) \\ &+ 10^3\cdot(5\cdot 9+4\cdot4) \\ &=67140 \end{align} whichs fourth digit is indeed $7$ and it only performed seven of all eight possible multiplications. Of course the gain is small in this case, but significant in the case of two at least four digit factors.
65,536,735
I am trying to test out Azure Purview and connect it to an Azure SQL Server. Since the SQL server is hosted in the cloud I want to use the default AutoResolve Integrated Runtime to get connected but there is not one setup or an option to setup a new one. Has anyone else using Purview been able to setup (or needed to setup) an AutoResolve IR? [![enter image description here](https://i.stack.imgur.com/ptg0x.jpg)](https://i.stack.imgur.com/ptg0x.jpg)
2021/01/02
[ "https://Stackoverflow.com/questions/65536735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14925750/" ]
1.Add the following to edittext in xml: ``` android:autofillHints="smsOTPCode" android:importantForAutofill="yes" ``` 2.Enable the autofill service by navigating to **Settings > Google > Autofill > Sms verification codes > Autofill service**. **Note**: This solution will work on android 8 and above.
7,871,333
Can i have a script running in a Linux environment that tails a log file and then as soon as it sees a certain keyword ( say "EndAPP") it runs another script? If so how ?
2011/10/24
[ "https://Stackoverflow.com/questions/7871333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/692029/" ]
You could use [File::Tail](http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/Tail.pm) ``` use File::Tail; my $file=File::Tail->new("/some/log/file"); while (defined(my $line = $file->read)) { system("/path/to/second/script") if($line =~ /EndApp/) ; } ```
2,506,445
let $f : X \to X $ be an isometry $d((f(x)),f(y)) = d(x,y)$ for all $x,y \in X$. It could easily be shown that $f$ is continuous and injective. Now if we let $X$ to be compact, need to show that it is surjective in this case. The proof proceeds as following: > > Suppose $f(X) \neq X$. Then there exists a $a \in X$ such that $a \not \in f(X)$. The function $f$ is continuous, and since $X$ is compact so is $f(X)$. Notice that $f(X)$ is compact in $X$, being hausdorff $f(X)$ is closed, making $X - f(X)$ open. Then for this $a$, I can find a $\epsilon$ neighbourhood such that $B(a,\epsilon) \subset X - f(X)$. > > > This is ofc, not the whole proof. However I understood the other part easily, only problem I have is here that why $X$ is hausdorff so that $f(X)$ is closed in $X$. I'm not given that it is Hausdorff or anything. Thanks!
2017/11/05
[ "https://math.stackexchange.com/questions/2506445", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
$X$ is a metric space (because you are given a metric to work with). Every metric space is "Hausdorff", which means any two distinct points have neighbourhoods which do not overlap. One can prove that if $H$ is a compact Hausdorff space, and $f$ continuous, then $f(H)$ is compact. However, it's a bit weird that they talk about "Hausdorff", because they could have just said $X$ is a compact metric space, and $f$ is continuous, so $f(X)$ is compact. This an outline for how to show that continuous functions preserve compactness: Let $X, Y$ be metric spaces, $f:X\rightarrow Y$ continuous. Let $K \subset X$ compact. Choose an open cover $\mathcal{U}$ for $f(K)$. Then as the pre-image of open sets is open (by continuity), $\{f^{-1}(U):U\in\mathcal{U}\}$ is an open cover for $K$. Now by compactness you can choose a finite subcover, and then map this back to $Y$ to obtain a finite subcover for $f(K)$.
2,908,884
I'm just about to expand the functionality of our own CMS but was thinking of restructuring the database to make it simpler to add/edit data types and values. Currently, the CMS is quite flat - the CMS requires a field in the database for every type of stored value (manually created). The first option that comes to mind is simply a table which keeps the data types (ie: Address 1, Suburb, Email Address etc) and another table which holds values for each of these data types. Just like how Wordpress keeps values in the 'options' table, PHP serialize would be used to store an array of values. The second option is how Drupal works, the CMS creates tables for every data type. Unlike Wordpress, this can be a bit of an overkill but really useful for SQL queries when ordering and grouping by a particular value. What's everyone's thoughts?
2010/05/25
[ "https://Stackoverflow.com/questions/2908884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167129/" ]
In my opinion, you should avoid serialization where possible. Your relational database should be relational, and thus be structured as such. This would include the 'Drupal Method', e.g. one table per data type. This also keeps your database healthy in a sense that it can be indexed en easily queried upon.
27,799,921
So all I want here to happen is that how can I put all the given output in the answer textbox. UPDATE ``` <html> <body> <script type="text/javascript"> function myFunction() { var x = parseInt(document.f1.n1.value); var y = parseInt(document.f1.n2.value); if(x>=y) { document.write("Invalid"); } while (x<y) { document.write(x) x=x+1; } } </script> <form name=f1 onsubmit="return false"> First no. <input type="text" name="n1"> Second no. <input type="text" name="n2"> Answer: <input type="text" name="ans" disabled> <input type="submit" onClick="myFunction()"> </form> </body> </html> ``` Thank you in advance
2015/01/06
[ "https://Stackoverflow.com/questions/27799921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4424004/" ]
If you can guarantee that the format is exactly as you specified, then a regular expression can capture (denoted by the brackets below) everything from the equals sign upto the pipe symbol, and from the Gene= to the end, and paste them together with a minus sign: ``` sub("mature=([^|]*).*Gene=(.*)", "\\1-\\2", Data[,1]) ```
42,901,284
Just have a couple of questions regarding the usage of Azure Functions with an EventHub in an IoT scenario. * EventHub has partitions. Typically messages from a specific device go to the same partition. How are the instances of an Azure Function distributed across EventHub partitions? Is it based on the performance? In case one instance of an Azure Function manages to process events from all partitions then it is enough otherwise one might end up with one instance of an Azure Function per EventHub partition? * What about the read-offset? Does this binding somehow records where it stopped reading the event stream? I thought the functions are meant to be stateless and here we have some state. Thanks
2017/03/20
[ "https://Stackoverflow.com/questions/42901284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1102175/" ]
Each instance of an Event Hub-Triggered Function is backed by only 1 EventProcessorHost(EPH) instance. Event Hub ensures that only 1 EPH can get a lease on a given partition. **Answer to Question 1:** Let's elaborate on this with a contrived example. Suppose we begin with the following setup and assumptions for an EventHub: 1. 10 partitions. 2. 1000 events distributed evenly across all partitions => 100 messages in each partition. When your Function is first enabled, there is only 1 instance of the Function. Let's call this Function instance *Function\_0*. *Function\_0* will have 1 EPH that manages to get a lease on all 10 partitions. Let this EPH be called *EPH\_0*, and it will start reading events from partitions 0-9. From this point forward, one of the following will happen: 1. **Only 1 Function instance is needed -** *Function\_0* is able to process all 1000 before the Azure Functions' scaling logic kicks in. Hence, all 1000 messages are processed by *Function\_0*. 2. **Add 1 more Function instance -** Azure Functions' scaling logic determines that *Function\_0* seems sluggish, so a new instance *Function\_1* is created, resulting in *EPH\_1*. Event Hub detects that a new EPH instance is trying read messages. Event Hub will start load balancing the partitions across the EPH instances, e.g., partitions 0-4 are assigned to *EPH\_0* and partitions 5-9 are assigned to *EPH\_1*. If all Function execution succeed without errors, both *EPH\_0* and *EPH\_1* checkpoints successfully and all 1000 messages are processed. When check-pointing succeeds, all 1000 messages should never be retrieved again. 3. **Add N more function instances -** Azure Functions' scaling logic determines that both *Function\_0* and *Function\_1* are still sluggish and will repeat workflow 2 again for *Function\_2...N*, where N>9. Event Hub will load balance the partitions across *Function\_0...9* instances. Unique to Azure Functions' current scaling logic is the fact that N is **>(number of partitions)**. This is done to ensure that there are always instances of EPH readily available to quickly get a lock on the partition(s). As a customer, you are only charged for the resources used when your Function instance executes, but you are not charged for this over-provisioning. **Answer to Question 2:** EPH uses a check-pointing mechanism to mark the last known successfully read message. An EventHub-Triggered Function can be setup to process 1 message or a batch of messages at a time. The option you choose needs to consider the following: **1. Speed of message processing -** Processing messages in batches instead of a single message at a time is *one of the factors* that will speed up the ability of your Azure Function workflow to keep up with the incoming messages in your Event Hub. **2. Tolerance for duplicates -** If check-pointing fails due to errors in your Function code/(Updated Aug 24th, 2017) timeout/partition least lost, then the next EPH that gets a lease on that partition will start retrieving messages from the last known checkpoint. Event Hub guarantees **at-least-once** delivery but not **at-most-once** delivery. Azure Functions will not attempt to change that behavior. If not having duplicate messages is a priority, then you will need to mitigate it in your workflow. As such, when check-pointing fails, there are more duplicate messages to manage if your Function is processing messages at batch level.
15,701,385
I am copying data from Amazon S3 to Redshift. During this process, I need to avoid the same files being loaded again. I don't have any unique constraints on my Redshift table. Is there a way to implement this using the copy command? <http://docs.aws.amazon.com/redshift/latest/dg/r_COPY_command_examples.html> I tried adding unique constraint and setting column as primary key with no luck. Redshift does not seem to support unique/primary key constraints.
2013/03/29
[ "https://Stackoverflow.com/questions/15701385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900527/" ]
As user1045047 mentioned, Amazon Redshift doesn't support unique constraints, so I had been looking for the way to delete duplicate records from a table with a delete statement. Finally, I found out a reasonable way. Amazon Redshift supports creating an IDENTITY column that is stored an auto-generated unique number. <http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html> The following sql is for PostgreSQL to delete duplicated records with OID that is unique column, and you can use this sql by replacing OID with the identity column. ``` DELETE FROM duplicated_table WHERE OID > (  SELECT MIN(OID) FROM duplicated_table d2   WHERE column1 = d2.dupl_column1   AND column2 = d2.column2 ); ``` Here is an example that I tested on my Amazon Redshift cluster. ``` create table auto_id_table (auto_id int IDENTITY, name varchar, age int); insert into auto_id_table (name, age) values('John', 18); insert into auto_id_table (name, age) values('John', 18); insert into auto_id_table (name, age) values('John', 18); insert into auto_id_table (name, age) values('John', 18); insert into auto_id_table (name, age) values('John', 18); insert into auto_id_table (name, age) values('Bob', 20); insert into auto_id_table (name, age) values('Bob', 20); insert into auto_id_table (name, age) values('Matt', 24); select * from auto_id_table order by auto_id; auto_id | name | age ---------+------+----- 1 | John | 18 2 | John | 18 3 | John | 18 4 | John | 18 5 | John | 18 6 | Bob | 20 7 | Bob | 20 8 | Matt | 24 (8 rows) delete from auto_id_table where auto_id > ( select min(auto_id) from auto_id_table d where auto_id_table.name = d.name and auto_id_table.age = d.age ); select * from auto_id_table order by auto_id; auto_id | name | age ---------+------+----- 1 | John | 18 6 | Bob | 20 8 | Matt | 24 (3 rows) ``` Also it works with COPY command like this. * auto\_id\_table.csv ``` John,18 Bob,20 Matt,24 ``` * copy sql ``` copy auto_id_table (name, age) from '[s3-path]/auto_id_table.csv' CREDENTIALS 'aws_access_key_id=[your-aws-key-id] ;aws_secret_access_key=[your-aws-secret-key]' delimiter ','; ``` The advantage of this way is that you don't need to run DDL statements. However it doesn't work with existing tables that do not have an identity column because an identity column cannot be added to an existing table. The only way to delete duplicated records with existing tables is migrating all records like this. (same as user1045047's answer) ``` insert into temp_table (select distinct from original_table); drop table original_table; alter table temp_table rename to original_table; ```
61,211
I have found and read a lot of tutorials that speak individually about curves, levels and contrast in post-processing but no luck so far about finding something that compares them. It is my understanding that curves is the most flexible tool, while levels is more simplified and the contrast slider is even more simplified. Is this the case? To put it another way. Am I correct to assume that I can do with curves anything that is possible with levels (and more)? Do I need to bother with the contrast slider at all if I am accustomed to working with curves?
2015/03/22
[ "https://photo.stackexchange.com/questions/61211", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/38534/" ]
Yes, your assumption is correct. A levels control is basically the equivalent of a curves control that can only be adjusted at the end points and one point in the middle, while a contrast slider is (usually) the equivalent of moving both ends at the same time (although some may be more sophisticated). The curves tool gives the most flexibility, but also allows you to create very unnatural-looking results.
33,238,416
How do I detect if the mapview is being tapped on, that isn't an annotation in obj-c?
2015/10/20
[ "https://Stackoverflow.com/questions/33238416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2368378/" ]
Swift 4, I fixed this in our case, by adding tap gestures to both annotation view and map view. add tap gesture to map ``` let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.hideFilterView)) self.mapView.addGestureRecognizer(tapGesture) //override "viewFor annotation:" something like this func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin") if annotationView == nil { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "Pin" annotationView?.canShowCallout = false } else { annotationView?.annotation = annotation } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.didTapPin(onMap:))) annotationView?.addGestureRecognizer(tapGesture) return annotationView } //then don't override func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { } ``` So the all pins selections will be handled using tap gestures. And you can detect map and pins tap separately.
42,873,477
I am currently taking some programming test over at `http://proctor.andela.com/`and my code for the OOP question works fine /correctly in pyCharm and Idle but while 'testing' the code in the provided editor, I keep getting this error > > /bin/sh: 1: python/nose2/bin/nose2: not found > > > Therefore I can't submit my code. I have tried the following: 1. Logged out and back into the curriculum page- No change. 2. Changed my internet to a faster/more reliable one(Saw a post somewhere to make sure the internet connection was stable-I use a 3G connection that is flaky at times)- No change. 3. Re-wrote my code- No change. Further research indicates this is brought about by the unittest used to evaluate the code, Does this mean this is a server issue? I will appreciate any way forward on this matter, as the test are timebound. **EDIT/ADDITIONAL INFO** Moved on to another Lab and still getting same error. Does'nt this point to an environment configuration error, or server side error? My Current setup is: > > Linux Mint 17.3 64 bit. > Taking test through Google Chrome as suggested. Same error comes up when I use Firefox. > > > My code, for reference: ``` class BankAccount(object): def deposit(self): pass def withdraw(self): pass class SavingsAccount(BankAccount): def __init__(self): self.balance = 500 def deposit(self, amount): if amount < 0: return 'Invalid deposit amount' else: self.balance += amount return self.balance def withdraw(self, amount): if amount < 0: return 'Invalid withdraw amount' elif amount > self.balance: return 'Cannot withdraw beyond the current account balance' elif (self.balance - amount < 500): return 'Cannot withdraw beyond the minimum account balance' else: self.balance -= amount return self.balance class CurrentAccount(BankAccount): def __init__(self): self.balance = 0 def deposit(self, amount): if amount < 0: return 'Invalid deposit amount' else: self.balance += amount return self.balance def withdraw(self, amount): if amount < 0: return 'Invalid withdrawal amount' elif amount > self.balance: return 'Cannot withdraw beyond the current account balance' else: self.balance -= amount return self.balance ``` **FINAL EDIT & CLOSE** It was confirmed(by Andela) that indeed the testing platform had serious issues that resulted into it being taken offline for maintenance. I can therefore close this question by confirming that it was a server side issue. Thank you all who replied/commented.
2017/03/18
[ "https://Stackoverflow.com/questions/42873477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6860766/" ]
I'd recommend having a function that processes this instead then. ```js function tr_clicked(event) { var the_class = event.target.className; var the_node = event.target.nodeName; if (the_node !== "INPUT" && the_class !== "checkbox") { alert("I'm going elsewhere"); } } ``` ```css table { width: 100%; } tr:hover { cursor: pointer; } ``` ```html <table border="1"> <tr class="clickable" onclick="tr_clicked(event)"> <td> <div> Lore ipsum </div> </td> <td class="checkbox"> <input type="checkbox" name="check" value="1"> </td> </tr> </table> ``` Using the event trigger, you can see what triggered the event and proceed if necessary. I added a class to the checkbox td just to verify easier and made sure that you didn't click the checkbox.
53,036,908
Still brand new to programming all of a week now. Been writing small programs to help get the basics stuck in my head. When I run this code, it runs correctly if I enter the first question correct, but if I answer it wrong & then it loops back around and I answer it correct again, it keeps looping without continuing to the rest of the code. ``` import java.util.Scanner; public class Parker { public static void main(String []args) { Scanner scan = new Scanner(System.in); System.out.print("How old are you: "); int age = scan.nextInt(); if (age > 6) { System.out.println("You are to old for the program"); } else { System.out.println("Welcome to the program, enjoy!"); System.out.println("What is 5 + 3? "); int num1 = scan.nextInt(); if (num1 == 8) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } while (num1 != 8) { System.out.println("What is 5 + 3? "); int num9 = scan.nextInt(); if (num9 == 8) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } } System.out.println("What is 3 + 11? "); int num2 = scan.nextInt(); if (num2 == 14) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } System.out.println("What is 7 + 6? "); int num3 = scan.nextInt(); if (num3 == 13) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } System.out.println("What is 11 - 5? "); int num4 = scan.nextInt(); if (num4 == 6) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } System.out.println("What is 4 + 9? "); int num5 = scan.nextInt(); if (num5 == 13) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } } } } ```
2018/10/28
[ "https://Stackoverflow.com/questions/53036908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10548080/" ]
``` while (num1 != 8) { System.out.println("What is 5 + 3? "); int num9 = scan.nextInt(); if (num9 == 8) { System.out.println("Correct!"); } else { System.out.println("Wrong! I'm telling your DADDY!"); } } ``` The above condition in your code depends on `num1`, but you never change the value of `num1` within that loop. For that reason, that loop will never terminate.
50,024,939
I am trying to use search and replace in Python 3 with file but when i try my code it only works on the first line and don't go through each and every line and replace it. What i am trying so far ``` f1 = open('test.txt', 'r') f2 = open('test2.txt', 'w') for line in f1: f1.readlines() find = (input('Enter word to find: ')) while find in line: print('Word Found') replace = input('Enter Word to replace with: ') replace_action = (input('Are you sure you want to replace Y or N:')) if replace_action.lower() == 'y': f2.write(line.replace(find.lower(), replace)) else: print('You have cancelled this operation') else: print('Word not found in file') f1.close() f2.close() ``` This code is only reading the first line but doesnot work further.
2018/04/25
[ "https://Stackoverflow.com/questions/50024939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9678942/" ]
This is happening because you are not reading the file properly. ``` for line in f1: f1.readlines() ``` **f1.readlines()** consumes all the file lines returning a list of strings. You just need to remove the f1.readlines() line. Check the documentation if you would like to know the various ways of reading a file in python. <https://docs.python.org/2.7/tutorial/inputoutput.html> <https://docs.python.org/3/tutorial/inputoutput.html>
3,070,774
I'm having difficulties making progress in proving: $$\forall \varepsilon > 0, \ \exists q \in Q \text{ where } 0 < |r - q| < \varepsilon $$ To clarify, $r$ is a real number and $q$ is a rational number. Is there some theorem I should be using? This exercise is presented in the same section/chapter as the Completeness Axiom (each nonempty set has a least upper bound or supremum), the Archimedean Property of Real Numbers ($ \exists n \in Z^{+}$ such that $na>b $ for positive real numbers $a$ and $b$), and a theorem stating there is a rational and irrational number between any two distinct real numbers. I'm just not seeing the connection (if any at all). Any help in the right direction would be much appreciated. Thank you!
2019/01/12
[ "https://math.stackexchange.com/questions/3070774", "https://math.stackexchange.com", "https://math.stackexchange.com/users/560509/" ]
Choose some positive integer $n$ such that $n>\frac{1}{\varepsilon}$. Define $q$ as $\frac{[nr]+1}{n}$. Then, $|r-q|=\frac{1-\{nr\}}{n}\in (0;\varepsilon)$.
44,995,655
My application needs to open a lot of small files, say 1440 files each containing data of 1 minute to read all the data of a certain day. Each file is only a couple of kB big. This is for a GUI application, so I want the user (== me!) to not have to wait too long. It turns out that opening the files is rather slow. After researching, most time is wasted in creating a FileStream (OpenStream = new FileStream) for each file. Example code : ``` // stream en reader aanmaken FileStream OpenStream; BinaryReader bReader; foreach (string file in files) { // bestaat de file? dan inlezen en opslaan if (System.IO.File.Exists(file)) { long Start = sw.ElapsedMilliseconds; // file read only openen, anders kan de applicatie crashen OpenStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Tijden.Add(sw.ElapsedMilliseconds - Start); bReader = new BinaryReader(OpenStream); // alles in één keer inlezen, werkt goed en snel // -bijhouden of appenden nog wel mogelijk is, zonodig niet meer appenden blAppend &= Bestanden.Add(file, bReader.ReadBytes((int)OpenStream.Length), blAppend); // file sluiten bReader.Close(); } } ``` Using the stopwatch timer, I see that most (> 80%) of the time is spent on creating the FileStream for each file. Creating the BinaryReader and actually reading the file (Bestanden.add) takes almost no time. I'm baffled about this and cannot find a way to speed it up. What can I do to speed up the creation of the FileStream? update to the question: * this happens both on windows 7 and windows 10 * the files are local (on a SSD disk) * there are only the 1440 files in a directory * strangely, reading the (same) files again later, creating the FileStreams suddenly cost almost no time at all. Somewhere the OS is remembering the filestreams. * even if I close the application and restart it, opening the files "again" also costs almost no time. This makes it pretty hard to find the performance issue. I had to make a lot of copies of directory to recreate the problem over and over.
2017/07/09
[ "https://Stackoverflow.com/questions/44995655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3582698/" ]
As you have mentioned in the comment to the question `FileStream` reads first 4K to buffer by creating the object. You can change the size of this buffer to reflect better size of your data. (Decrease if your files are smaller than the buffer, for example). If you read file sequentially, you can give OS the hint about this through `FileOptions`. In addition, you can avoid `BinaryReader`, because you read files entirely. ``` // stream en reader aanmaken FileStream OpenStream; foreach (string file in files) { // bestaat de file? dan inlezen en opslaan if (System.IO.File.Exists(file)) { long Start = sw.ElapsedMilliseconds; // file read only openen, anders kan de applicatie crashen OpenStream = new FileStream( file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize: 2048, //2K for example options: FileOptions.SequentialScan); Tijden.Add(sw.ElapsedMilliseconds - Start); var bufferLenght = (int)OpenStream.Length; var buffer = new byte[bufferLenght]; OpenStream.Read(buffer, 0, bufferLenght); // alles in één keer inlezen, werkt goed en snel // -bijhouden of appenden nog wel mogelijk is, zonodig niet meer appenden blAppend &= Bestanden.Add(file, buffer, blAppend); } } ``` I do not know type of `Bestanden` object. But if this object has methods for reading from array you can also reuse buffer for files. ``` //the buffer should be bigger than the biggest file to read var bufferLenght = 8192; var buffer = new byte[bufferLenght]; foreach (string file in files) { //skip ... var fileLenght = (int)OpenStream.Length; OpenStream.Read(buffer, 0, fileLenght); blAppend &= Bestanden.Add(file, /*read bytes from buffer */, blAppend); ``` I hope it helps.
49,933
So I noticed the version numbers had changed from something like `build 5555` to this: `revision: 2010.5.14.1`. Now I understand the first part is today's date, but is the last part how many times they've changed something today? Or is it something else?
2010/05/14
[ "https://meta.stackexchange.com/questions/49933", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/56555/" ]
With [Subversion](http://subversion.tigris.org/), it's easy to [incorporate](https://stackoverflow.com/questions/1349782/creating-an-svn-repository-using-c) [build](http://florent.clairambault.fr/insert-svn-version-and-build-number-in-your-c-assemblyinfo-file) [numbers](http://sharpsvn.open.collab.net/) into your source code. In [April 2010](https://blog.stackoverflow.com/2010/04/stack-overflow-and-dvcs/), Jeff, etc. switched to [Mercurial](http://mercurial.selenic.com/). While it's not impossible to use build numbers, [it is more complicated](https://stackoverflow.com/questions/2386440/embedding-mercurial-revision-information-in-visual-studio-c-projects-automatical). Looking at the number, it is likely they just used the date and number of releases per day (`Release 1, 14th of May, 2010`). (For what it's worth, Jeff has posted a few thoughts [on](http://www.codinghorror.com/blog/2006/08/source-control-anything-but-sourcesafe.html) [source](http://www.codinghorror.com/blog/2007/10/software-branching-and-parallel-universes.html) [control](http://www.codinghorror.com/blog/2008/02/get-your-database-under-version-control.html).)
11,310,731
I put a file inside my Java project file and i want to read it but how can i find the path name with Java. Here i put it in C driver but i just want to find path by just writing the name of file. Is there a function for it? ``` FileInputStream fstream1 = new FileInputStream("C:/en-GB.dic"); ```
2012/07/03
[ "https://Stackoverflow.com/questions/11310731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463542/" ]
If the file is inside the jar file generated for your project (or in the classpath used by your project, generally), under the package `com.foo.bar`, you can load it using ``` SomeClassOfYourProject.class.getResourceAsStream("/com/foo/bar/en-GB.dic"); ``` If it's not in the classpath, and you launch the application (using java.exe) from the directory `c:\baz`, and the file is under `c:\baz\boom\`, the you can load it using ``` new FileInputStream("boom/en-GB.dic"); ```
36,106,722
I am currently running a script (check\_files.sh) that may or may not produce match\* files (eg. match1.txt, match2.txt, etc. I then want to go on to run an R script on the produced match\* files. However, before I run the R script, I have tried a line in my script which checks if the files are present. ``` if [ -s match* ] then for f in match* do Rscript --vanilla format_matches.R ${f} rm match* done else echo "No matches present" fi ``` However, I keep getting an error message (as there are often a lot of match files producted): ``` ./check_files.sh: line 52: [: too many arguments ``` Is there an alternative to [ -s match\* ] which would not throw up the error message? I take it that the error message appears as there are multiple match\* files produced.
2016/03/19
[ "https://Stackoverflow.com/questions/36106722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5631421/" ]
If you expect filenames with spaces, this is a bit ugly but robust: ``` found=0 find -maxdepth 1 -type f -name 'match*' -print0 | while IFS= read -rd $'\0' f do found=1 Rscript --vanilla format_matches.R "$f" rm "$f" done if [ "$found" -eq 0 ]; then >&2 echo "No matches present" fi ```
24,059,358
I want to design login page which is similar to facebook login page. I have tried the below layout view ,if i change the orientation of my screen there is no space at bottom and also fields those i have taken completely changed.Please advice how to fix this problem? ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/RelativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ScrollView android:id="@+id/ScrollView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > <LinearLayout android:id="@+id/LinearLayout1" android:layout_width="fill_parent" android:layout_height="match_parent" android:background="#7CACF5" android:orientation="vertical" android:padding="10dp" android:paddingBottom="30dp" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="70dp" android:layout_marginTop="50dp" android:gravity="center" android:paddingBottom="5dp" android:text="Welcome" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="email or phone" android:inputType="textEmailAddress" android:paddingBottom="5dp" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="password" android:inputType="numberPassword" android:paddingBottom="5dp" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Log In" /> </LinearLayout> </ScrollView> </RelativeLayout> ```
2014/06/05
[ "https://Stackoverflow.com/questions/24059358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909151/" ]
Try this ``` <LinearLayout android:id="@+id/LinearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical|center_horizontal" android:orientation="vertical" android:padding="10dp" android:paddingBottom="30dp" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="50dp" android:gravity="center" android:paddingBottom="5dp" android:text="Welcome" android:textAppearance="?android:attr/textAppearanceLarge" /> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:hint="email or phone" android:inputType="textEmailAddress" android:paddingBottom="5dp" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:ems="10" android:hint="password" android:inputType="numberPassword" android:paddingBottom="5dp" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:text="Log In" /> </LinearLayout> ```
22,196,185
Code first. ``` class A { private A(){} public static A.Builder Builder() { /** * ERROR: * No enclosing instance of type A is accessible. * Must qualify the allocation with an enclosing instance of type A * (e.g. x.new A() where x is an instance of A). */ return new A.Builder(); // Error too //return new Builder(); } public class Builder { private Builder() {} } } ``` Q: How to instance the builder but do not change the static Builder and nested class name ? **EDIT** If the class is static, how to save the date for every builder ? how to chain the build process ? ``` public static class Builder { private Builder() {} public Builder add(int a) { return this;// how to chain the build process ? } public Builder add(float a); public List<Double> Build(); } ``` OK, I should google java builder pattern first.[Here](http://www.javacodegeeks.com/2013/01/the-builder-pattern-in-practice.html) is an example.
2014/03/05
[ "https://Stackoverflow.com/questions/22196185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870054/" ]
**Rule**: If an inner class is used outside of the enclosing class, it must be static. ``` public static class Builder { private Builder() { } } ``` It's by design.
63,744,344
I am a beginner with Laravel and I have a project with multiple tables with the same fields (e.g. id, name). I have about 10 tables with this structure (e.g. country, town, type of users,....) I read it is correct to have for each table a separate Model and Controller. Is this correct? Is there any efficient way to programme like maybe make a single model and controller and extend them maybe? Any suggestions? Thank you.
2020/09/04
[ "https://Stackoverflow.com/questions/63744344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12806791/" ]
it depends on the meaning of those tables. Laravel use the MVC design pattern, it means each concept is represented by a model to persist the data, a controller to manipulate it, and a view to show it. In Laravel you should think by model and not by table. In your case if you want to group your tables in one because they have exactly the same fields then you can, and it will be one model. and then create a model and a controller for it. i advice to separate the concerns, it's always better. then if on of those table need an update, than you don't have to cross everything. You can ask more deep for more details.
14,710,002
I'm trying to upload images in a if/elseif statement. I passed the $\_FILES as a function parameter, since the print\_r outputs array()I think the passing worked. Or is there something wrong in the logic I create? Would anyone please pinpoint it out? Thanks in advance! ``` <?php require_once('../resources/library/admin.class.php'); $obj_admin = new admin(); echo $obj_admin->product_list; echo '<h1>inventory list</h1></br>'; $obj_admin->displayList(); $obj_admin->editData(); $obj_admin->deleteData(); $add[] = '<form name="invent" method="post" action="index.php?res=resources&adm=admin&page=inventory.php" class="ínvent">'; $add[] = '<fieldset>'; $add[] = '<legend>Add products</legend>'; $add[] = "<label for='name'>name</label>"; $add[] = "<input type='text' name='user' value='Grachten' />"; $add[] = '</br>'; $add[] = "<label for='price'>price</label>"; $add[] = "<input type='number' name='price' value='150' />"; $add[] = '</br>'; $add[] = "<label for='description'>description</label>"; $add[] = "<textarea name='description' rows='10' cols= '80'>Its the best!</textarea>"; $add[] = '</br>'; $add[] = "<label for='img'>img</label>"; $add[] = "<input name='image' accept='image/jpeg' type='file' value='files'>"; $add[] = '</br>'; $add[] ="<input type='submit' name='submit'/>"; $add[] = '</fieldset>'; $add[] = '</form>'; echo implode($add); if(isset($_POST['submit'])) { $name = $_POST['user']; $price = $_POST['price']; $description = $_POST['description']; $obj_admin->addData($name, $price, $description, $_FILES); } ``` ``` function addData($name, $price, $description, $files) { if(!empty($name) || !empty($price) || !empty($description)) { if($sql = $this->db->prepare("SELECT * FROM products WHERE name= ? LIMIT 1")) { $sql->bind_param('s', $name); $sql->execute(); $sql->store_result(); $sql->fetch(); $numrows = $sql->num_rows; print_r($numrows); } else { echo "something is wrong"; } if($numrows>0) { echo 'duplicate, go to <a href="index.php?res=resources&adm=admin&page=inventory.php">same page</a>'; } else { if($insert = $this->db->prepare("INSERT INTO products (name, price, description) VALUES(?, ?, ?)")) { $insert->bind_param('sds', $name, $price, $description); $insert->execute(); } //The uploaden image is sent to temp map elseif(isset($files['image']['size'])<=2048000) { if ($files["image"]["error"] > 0) { echo "Return Code: " . $files["image"]["error"] . "<br />"; } else { $uploaddir = "C:/xampp/htdocs/webshop/public/img/content"; $moved = move_uploaded_file($files['image']['tmp_name'], $uploaddir/$files['image']); if($moved) { echo "succes"; } else { echo "failure"; } } //Shows where its stored echo "Stored in: " . "C:/xampp/htdocs/webshop/public/img/content/" . $files["file"]["name"]; } else { echo "didnt inserted the damn thing!"; } } } print_r($files); } ```
2013/02/05
[ "https://Stackoverflow.com/questions/14710002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031928/" ]
Add enctype="multipart/form-data" to the form tag, you could check if that was the issue by var\_dump($\_FILES) which in your case will be empty
26,375,239
So I am trying to implement some inheritance and I am running into an issue. I am coming from java so I am basically trying to convert code. So for example in java you might have this. ``` public class galaxyFactory extends abstractFactory { @Override public galaxy setType() { return new Spiral(); } @Override SolarSystem setType() { return null; } } ``` This will return a new Spiral object if your after a galaxy, and overrides the SolarSystem setType with a simple return null. However when trying to convert this into c# i come up with something like this. Which DOES NOT work, it errors out with "NullReferenceException was unhandled" ``` class GalaxyFactory: AbstractFactory { public override Galaxy CreateProductA() { return new spiral(); } public override SolarSystem CreateProductB() { return null; } } ``` What would I have to change my return null to get the same effect in c#?
2014/10/15
[ "https://Stackoverflow.com/questions/26375239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805779/" ]
This error occures because you trying working with uninitialized object. When you get SolarSystem by using CreateProductB, actually you get null object, and then when you try work with this object obviously it will throw NullReferenceException.
236,860
Using sed how could I replace two patterns within a larger pattern on a single line? Given a single line of text I want to find a pattern (Let's call this the outer pattern) and then within that outer pattern replace two inner patterns. Here's a one line example of the input text: ``` Z:\source\private\main\developer\foo\setenv.sh(25): export 'FONTCONFIG_PATH'="$WINE_SHARED_SUPPORT/X11/etc/fonts" ``` In the example above the outer pattern is `/^.*\([[:digit:]]+\):/` which should equal `Z:\source\private\main\developer\foo\setenv.sh(25):` The two inner patterns are `/^[A-Za-z]:/` and `/\\/`. Another way to phrase my question is: Using sed I know how to perform replacements of a pattern using the `s` command, but how do I limit the range of `s` command so it only works on the portion of the input string up to the `(25):`? The ultimate result I am trying to get is the line of text is transformed into this: ``` /enlistments/source/private/main/developer/foo/setenv.sh(25): export 'FONTCONFIG_PATH'="$WINE_SHARED_SUPPORT/X11/etc/fonts" ```
2011/01/23
[ "https://superuser.com/questions/236860", "https://superuser.com", "https://superuser.com/users/59050/" ]
This command converts your input example to your output example: ``` sed 's|\\|/|g;s|^[^/]*|/enlistments|' ``` If some of your input contains backslashes in the portion after the `/^.*([[:digit:]]+):/` part, then you will have to divide and conquer to prevent those latter backslashes from being replaced. ``` sed 'h;s/^.*([[:digit:]]\+)://;x;s/^\(.*([[:digit:]]\+):\).*/\1/;s|\\|/|g;s|^[^/]*|/enlistments|;G;s/\n//' ``` Explanation (steps marked with an asterisk (**`[*]`**) apply to both commands): * `h` - copy the line to hold space * `s/^.*([[:digit:]]\+)://` - delete the first part of the line from the original in pattern space * `x` - swap pattern space and hold space * `s/^\(.*([[:digit:]]\+):\).*/\1/` - keep the first part of the line from the copy (discard the last part) * `s|\\|/|g` - **[`*`]** change all the backslashes to slashes (in the divide-and-conquer version, only the portion in pattern space - the first part of the line - is affected) * `s|^[^/]*|/enlistments|` - **[`*`]** change whatever appears before the first slash into "/enlistments" - this could be made more selective if needed * `G` - append a newline and the contents of hold space onto the end of pattern space * `s/\n//` - remove the interior newline
30,520,046
Seemingly simple issue here. I have an ng-options select tag that's working funky. Basically my ng-change function does not work properly, as the first parameter, "v", is undefined. Any help? ``` <select ng-model="d.sub_customer" ng ng-options="v.description as v.description for v in subCustomers" ng-change="updateCustomer(v,d.id)"></select> ```
2015/05/29
[ "https://Stackoverflow.com/questions/30520046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3806131/" ]
You cannot access the iteration variable in `ng-options` expression outside (unlike `ng-repeat`). Because ng-options just uses that expression and draws the options for the select in DOM. It really does not create a scope to keep hold off these properties, which is why it is unlike ng-repeat. In your case `d.sub_customer` will be the selected `v.description`,so you could just pass in that in the ng-change, i.e ``` ng-change="updateCustomer(d.description,d.id)" ```
62,763,247
I'm trying to build a python app via docker, but it fails to import numpy even though I've installed the appropriate package via apt. As an example of the dockerfile reduced to only what's important here: ``` FROM python:3 RUN apt-get update \ && apt-get install python3-numpy -y RUN python3 -c "import numpy; print(numpy.__version__)" ``` Attempting to build that dockerfile results in the error `ModuleNotFoundError: No module named 'numpy'`. I am able to get this working if I use pip to install numpy, but I was hoping to get it working with the apt-get package instead. Why isn't this working the way I would expect it to?
2020/07/06
[ "https://Stackoverflow.com/questions/62763247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/541398/" ]
The problem is that you have two Pythons installed: 1. The image comes with `python` in `/usr/local/bin`. 2. When you install `python3-numpy`, that install `python3` package from Debian, which ends up with `/usr/bin/python`. When you run your code at the end you're likely using the version from `/usr/local/bin`, but NumPy was installed for the version in `/usr/bin`. Solution: Install NumPy using `pip`, e.g. `pip install numpy`, instead of using apt. Long version, with other ways you can get import errors: <https://pythonspeed.com/articles/importerror-docker/>
49,805,225
I've got a database structure as follows where item A is in a many to many relationship with B. This is a true many to many, so: Item X (object in table A) relates to Y (object in B) multiple times. Using the laravel `attach()` function easily adds these records. However, I need to update and delete these items. The `detach()` and `sync()` methods seem to not be appropriate. They assume only one pivot table entry between one record and another record. If I `detach()` then ALL items are deleted. That is not what I want. So the main point of my question: If I have the id of the pivot table record, how do I delete/update it... *given that* detach doesn't work as expected. Or put another way: How can I interact with a pivot table object directly?
2018/04/12
[ "https://Stackoverflow.com/questions/49805225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1759381/" ]
We can do this: ``` {-# LANGUAGE PatternSynonyms, ViewPatterns #-} -- at very top of file ^ -- ... -- pick whatever names/operators you want -- synonym signatures are given in GADT-like syntax -- ZCons decomposes a ZipList' a into an a and a ZipList' a -- (assuming it succeeds). This is the syntax even for pattern synonyms that -- can only be used as patterns -- (e.g. pattern Fst :: a -> (a, b); pattern Fst a <- (a, _)). pattern ZCons :: a -> ZipList' a -> ZipList' a -- xs needs to be a ZipList', but it's only a [a], so we uglify this synonym -- by using the newtype wrapper as a view pattern ZCons x xs <- ZipList' (x:(ZipList' -> xs)) -- views aren't in general invertible, so we cannot make this an automatically -- bidirectional synonym (like ZNil is). We can give an explicit version where ZCons x (ZipList' xs) = ZipList' $ x:xs -- simple enough that we can use one definition for both pattern and expression pattern ZNil :: ZipList' a pattern ZNil = ZipList' [] {-# COMPLETE ZNil, ZCons #-} -- ZNil and ZCons cover all ZipLists instance Applicative ZipList' where pure x = ZipList' $ repeat x -- these are bidirectional (ZCons f fs) <*> (ZCons x xs) = ZCons (f x) (fs <*> xs) _ <*> _ = ZNil ```
73,632,386
I have a tab page with `AutomaticKeepAliveClientMixin`, which works well. What I want is, when switch back to this page, I can choose refresh this page or not. As far as I know, `wantKeepAlive` seems work on when widget is displayed. I also checked life cycle of State. Method like `initState`, `activate`. None of them worked. So my question is, Will there be any thing triggered when `AutomaticKeepAliveClientMixin` Widget is back on screen? Or if `AutomaticKeepAliveClientMixin` can't do that, is there any other way to keep page state, and
2022/09/07
[ "https://Stackoverflow.com/questions/73632386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7738260/" ]
You haven't initialized the variable `i`. Also the query selector is not correct. Here's a working codesandbox example: <https://codesandbox.io/s/naughty-frog-bje4jw>
63,859
Consider a self-employed web developer whose work is outsourced from another web development company. That developer could be liable for any mishaps and could be sued by their clients. The web development company are willing to accept liability on the developer's behalf (in the same way that they are liable for their employees), but it's unclear to me if a contract that waives the developer's liability needs to include the end client as a party or if a contract between the developer and the web development company is sufficient. In all but one case, the websites are hosted by the web development company itself. Does the answer differ if the website is hosted and managed by the end client with the web development company (and so also the developer) being granted limited access as needed? All parties are based in England.
2021/04/06
[ "https://law.stackexchange.com/questions/63859", "https://law.stackexchange.com", "https://law.stackexchange.com/users/2828/" ]
Because one is theft and the other is breach of contract -------------------------------------------------------- Theft is taking someone’s property with the intent of permanently depriving them of it. It has always been a crime, in fact, it’s a toss up whether theft or murder was the first crime ever. Not giving someone something you lawfully owe them but that they never possessed is not theft because it lacks the dispossession aspect required of theft. That’s simply failing to pay a debt and that is just breach of contract. Now, there was a time, back in the nineteenth century when not paying your debts would land you in debtors prison but society moved on. Now, there are jurisdictions ([australia](/questions/tagged/australia "show questions tagged 'australia'")) which are considering making wage theft, the deliberate and systemic underpayment of workers a crime. Perhaps society is moving on again?
30,420,355
i made a grid using two javascript for loops, for some reason i have a fixed gap between the lines in the grid. i can't understand what couses the gap. here is what i did. ``` var length = 100; var text = ""; var i; for (i = 0; i < length; i++) { text += '<div>'; for(var x = 0; x < length; x++){ text += '<div class="b"></div>'; } text += '</div>'; } ``` <https://jsfiddle.net/davseveloff/wL3Ljpxo/> I assume the what causes it is that the divs are empty, though they have width and height att... any help would be great. TNX
2015/05/24
[ "https://Stackoverflow.com/questions/30420355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3471458/" ]
This is because the space between the elements and the `<br>` tags get rendered as text, if you set the font size to `0` it will remove the gap while still breaking the line. ([Demo](https://jsfiddle.net/humbleRumble/wL3Ljpxo/1/)) ``` #demo { font-size: 0; } ```
15,463,296
i can get the json in the following format ``` [{"data":{"id":"1","user_name":"StudentA","book":"123","role":"Student"}}, {"data":{"id":"3","user_name":"StudentB","book":"456","role":"Student"}}] ``` how can i use the data to present like the image below, where the first line is username and second line is book ![how can i use the data to present like the image below, where the first line is username and second line is book](https://i.stack.imgur.com/cdgyr.png) ``` <button type="button" id="test">Test 123</button> <ul id="studentList" data-role="listview" data-filter="true"></ul> ``` ``` var serviceURL = "http://mydomain.com/"; var students; $("#test").click(function() { getStudentList(); }); function getStudentList() { $.getJSON(serviceURL + 'getStudents.php', function(data) { $('#studentList li').remove(); students = data.user_name; $.each(students, function(index, student) { $('#studentList').append('<li>' + '<h4>' + student.user_name + ' ' + student.password + '</h4>' + '<p>' + student.user_name + '</p>' + '</li>'); }); $('#studentList').listview('refresh'); }); } ``` may i ask if the codes above correct?
2013/03/17
[ "https://Stackoverflow.com/questions/15463296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005425/" ]
I have figured it out and thought I would share what I found. Thanks to Hudku (<http://blog.hudku.com/2013/02/innocuous-looking-evil-devil.html#elastic-beanstalk.config>) for the excellent article: 1) Create myapp.config 2) enter the following into it ``` packages: yum: dos2unix: [] container_commands: 01-command: command: rm -rf /myapp/ebextensions 02-command: command: mkdir -p /myapp/ebextensions 03-command: command: cp -R .ebextensions/* /myapp/ebextensions/ 04-command: command: dos2unix -k /myapp/ebextensions/mongo.sh 05-command: command: chmod 700 /myapp/ebextensions/mongo.sh 06-command: command: bash /myapp/ebextensions/mongo.sh ``` Then create mongo.sh file and put in it something like: ``` #!/bin/bash if [ ! -f /mongostatus.txt ]; then pecl install mongo echo "mongo extension installed" > /mongostatus.txt apachectl restart fi ``` This will install mongo php extension and restart apache so the install takes affect.
64,582,551
I am trying to create a website with Bootstrap 4 on Apache (Ubuntu Linux), the footer is sticky as expected, but if only have a small amount of information on the page I have to scroll past a lot of white space to see the footer. I don't understand how to get the footer to behave more like the demo on the website, the only difference is that I have a navbar as well as a footer. Advice would be greatly welcomed please, I am pulling my hair out over this. **Minimum working code** ``` <!doctype html> <html lang="en" class='h-100'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" > <style> .footer { margin: 0; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 14px; line-height: 22px; background-color: #13294a; } body { min-height: 75rem; padding-top: 5rem; } </style> <title>Secure Shed Project</title> </head> <body class="d-flex flex-column h-100"> <header role="banner"> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04" aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExample04"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> </ul> </div> </nav> </header> <main role="main" class="flex-shrink-0 pb-2"> <div class="container"> <h1>Website coming soon</h1> </div> </main> <footer class="footer mt-auto"> <div class="container-fluid text-center text-md-left text-white"> <div class="text-center"> <p class="copyright m-0">© 2020 Copyright A.N.Other</p> </div> </div> </footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </body> </html> ```
2020/10/28
[ "https://Stackoverflow.com/questions/64582551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2672227/" ]
The problem in your code is this min-height on the body element. First, you will remove that. Then you will see that your footer is not sticky anymore. There are many solutions for that and I will recommend you this one: Instead of using 75rem, you should use this `min-height: 100vh;`.
60,823,968
I want to create a date with the specific format (2015-03-25), which is the increment of 9 days from the current date for certain requirements. Below is my code, however, when the current date approaches the end of the month such as 23 or 24 it is increasing by 9 and returning 32. which is not acceptable for the date. how to validate and return to next month's appropriate date? I want to do it in plain java-script I want to skip the libraries like moment.js for now. `const date = new Date("2015-03-25"); let currentDate = new Date(); let returnDate = ((currentDate.getDate())>=10)? (currentDate.getDate()+9) : '0' + (currentDate.getDate());`
2020/03/24
[ "https://Stackoverflow.com/questions/60823968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13113282/" ]
> > The HTML element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality. > > > **submit** The button is a submit button (this is default for all browsers, except Internet Explorer) > > > Try ``` <button type="button" className='cancel btn btn-danger ml-2'>Cancel</button> ```
24,434,517
The following 2 lines are my code: ``` $rank_content = file_get_contents('https://www.championsofregnum.com/index.php?l=1&ref=gmg&sec=42&world=2'); $tmp_ = preg_replace("/.+width=.16.> /Uis", "", $rank_content, 1); ``` The second line above causes an infinite loop. In contrary, the following alternatives DO work: ``` $tmp_ = preg_replace("/.+width=.16.> /Ui", "", $rank_content, 1); $tmp_ = preg_replace("/[^§]+width=.16.> /Uis", "", $rank_content, 1); ``` But sadly, they do not give me what I want - both alternatives do not include line breaks within `$rank_content`. Also, if I replaced the `file_get_contents` function with something like ``` $rank_content = "asdfas\nasdfasdfaswidth=m16m> teststring"; ``` There are no problems either, although `\n` represents a line break, too, doesn’t it?! So do I understand it right that RegEx has problems in noticing a String with line breaks in it? How can I filter a substring of `$rank_content` (which has multiple lines in it) by removing some lines until something like `"width="16" "` appears? (Can be seen in the site's source code)
2014/06/26
[ "https://Stackoverflow.com/questions/24434517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3779853/" ]
No need for jQuery when finding the coordinates to set as the `style`: ``` $('.dataCard').on('mousedown touchstart', function(event){ var clickX = (event.clientX || event.originalEvent.clientX), clickY = (event.clientY || event.originalEvent.clientY); $(this).children('.ripple').each(function(){ $(this) .show() .css({ left: clickX - this.offsetParent.offsetLeft, top: clickY - this.offsetParent.offsetTop }); }); }); ``` Updated fiddle from @Gaby aka G. Petrioli: <http://jsfiddle.net/s52u4/1/> In this particular case, using jQuery is like hitting a thumbtack with a sledge hammer.
14,283,325
i am developing web app with ZF2. It is a multilingual website. I would like to use ZF2 Translator for translation. Because, admin can modify the language variables. So, i planned to use the language folder files. I will update the language files while the admin modifying the language variables. Can anyone suggest ideas for this implementation? Thanks.
2013/01/11
[ "https://Stackoverflow.com/questions/14283325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1671284/" ]
Translating based on user input can get a little messy. There is no easy way of doing that right now, as the currently supported formats are all file formats: php files with arrays, a gettext .po file or Tmx/Xliff files. For the easiest access, you would likely store the translations in a database. You therefore need to write your own loader, loading the translations from the database. An alternative is you will write the translations in a php array and export that to a file, but I would not recommend that. For the database loader, you must implement the [`RemoteLoaderInterface`](https://github.com/zendframework/zf2/blob/master/library/Zend/I18n/Translator/Loader/RemoteLoaderInterface.php). In very simple terms: ``` use My\DbTable; use Zend\I18n\Translator\Loader\RemoteLoaderInterface; Zend\I18n\Translator\TextDoamin; class DbLoader implements RemoteLoaderInterface { protected $table; public function __construct(DbTable $table) { $this->table = $table; } public function load($locale, $textDomain) { $data = $this->table->loadFromLocale($locale); // process $data into $messages // $messages is array(key=>value) with key translation key $domain = new TextDomain($messages); return $domain; } } ``` The db table loads the messages in the locale you specify. If you use text domains, pass that on too. Then you need to configure your `Translator` such it uses this loader too to load the message. Everything else should be fine then. In your views, you can create translations like this: ``` <?php echo $this->translate('my original text'); ?> ```
52,668,116
I have this app wherein the home page I load a component that displays a list of movies coming from a local JSON file which I load it in the store in the `App.js` in the `componentDidMount` lifecycle. And I have another route where I display the single movie details. Now I have two options, either I create an action that filters the "all movies" list in the reducer and store the single movie in the "initial state" in the reducer, then fire that action in the "SingleMovie" component in its `componentDidMount` function. Or do I filter all the movies list in the component itself and get the single movie details? Which is better in terms of performance and best practice?
2018/10/05
[ "https://Stackoverflow.com/questions/52668116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1706198/" ]
> > Put your logic inside the component or in somewhere outside of the component? > > > A good practice is always keeping your component as skinny as possible. I mean, the component is the one which responsible for the presentation, not the handling application logic. In your case, you should stick with the option 1: *creating an action that filters the "all movies" list in the reducer and store the single movie in the "initial state" in the reducer, then fire that action in the "SingleMovie" component in its componentDidMount function.*
12,828,190
Assume the following simple POCOs, Country and State: ``` public partial class Country { public Country() { States = new List<State>(); } public virtual int CountryId { get; set; } public virtual string Name { get; set; } public virtual string CountryCode { get; set; } public virtual ICollection<State> States { get; set; } } public partial class State { public virtual int StateId { get; set; } public virtual int CountryId { get; set; } public virtual Country Country { get; set; } public virtual string Name { get; set; } public virtual string Abbreviation { get; set; } } ``` Now assume I have a simple respository that looks something like this: ``` public partial class CountryRepository : IDisposable { protected internal IDatabase _db; public CountryRepository() { _db = new Database(System.Configuration.ConfigurationManager.AppSettings["DbConnName"]); } public IEnumerable<Country> GetAll() { return _db.Query<Country>("SELECT * FROM Countries ORDER BY Name", null); } public Country Get(object id) { return _db.SingleById(id); } public void Add(Country c) { _db.Insert(c); } /* ...And So On... */ } ``` Typically in my UI I do not display all of the children (states), but I do display an aggregate count. So my country list view model might look like this: ``` public partial class CountryListVM { [Key] public int CountryId { get; set; } public string Name { get; set; } public string CountryCode { get; set; } public int StateCount { get; set; } } ``` When I'm using the underlying data provider (Entity Framework, NHibernate, PetaPoco, etc) directly in my UI layer, I can easily do something like this: ``` IList<CountryListVM> list = db.Countries .OrderBy(c => c.Name) .Select(c => new CountryListVM() { CountryId = c.CountryId, Name = c.Name, CountryCode = c.CountryCode, StateCount = c.States.Count }) .ToList(); ``` But when I'm using a repository or service pattern, I abstract away direct access to the data layer. It seems as though my options are to: 1. Return the Country with a populated States collection, then map over in the UI layer. The downside to this approach is that I'm returning a lot more data than is actually needed. -or- 2. Put all my view models into my Common dll library (as opposed to having them in the Models directory in my MVC app) and expand my repository to return specific view models instead of just the domain pocos. The downside to this approach is that I'm leaking UI specific stuff (MVC data validation annotations) into my previously clean POCOs. -or- 3. Are there other options? How are you handling these types of things?
2012/10/10
[ "https://Stackoverflow.com/questions/12828190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139694/" ]
It really depends on the projects architecture for what we do. Usually though.. we have services above the repositories that handle this logic for you. The service decides what repositories to use to load what data. The flow is UI -> Controller -> Service -> Repositories -> DB. The UI and/or Controllers have no knowledge of the repositories or their implementation. Also, `StateCount = c.States.Count` would no doubt populate the States list anyway.. wouldn't it? I'm pretty sure it will in NHibernate (with LazyLoading causing an extra select to be sent to the DB).
1,924
My city, like many, has a recycling program, which I believe is supposed to reduce pollution and create some positive economic activity. But I've heard many people argue that recycling programs are a waste in and of themselves. Essentially that most recycling programs are having the opposite effect than they were intended to have. Not only are they bad for the economy, they are also bad for the environment. [Recycling](http://www.conservapedia.com/Recycling) on Conservapedia contends: > > **Critics dispute the net economic and > environmental benefits of recycling > over its costs**, and suggest that > proponents of recycling often make > matters worse and suffer from > confirmation bias. Specifically, > critics argue that the costs and > energy used in collection and > transportation detract from (and > outweigh) the costs and energy saved > in the production process; > > > Are critics of recycling correct? Do recycling programs usually have a net negative effect on the **environment** and the **economy**? ![](https://i.stack.imgur.com/z8jsw.jpg)
2011/04/08
[ "https://skeptics.stackexchange.com/questions/1924", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/49/" ]
According to [Popular Mechanics](http://www.popularmechanics.com/science/environment/recycling/4291576), who I assume probably did their homework, it's worthwhile recycling newspaper and a couple of types of plastic in addition to aluminum (that aluminum recycling is wise should be utterly uncontroversial--aluminum refining is amazing, but not a low-energy process!). There was an [article in the Economist](http://www.economist.com/node/9249262?story_id=E1_JNQJNGN&CFID=161540127&CFTOKEN=74955032) a few years ago that also supports the idea that recycling (at least of most things) is a net win (it also adds steel to the "good idea" category). Even if you assume that not all factors have been taken into account (e.g. carbon produced by people working at the recycling plant who otherwise could do something else productive), the fraction of energy saved and large amounts of CO2 saved strongly suggest that recycling is a net positive. Whether any individual recycling *program* is worthwhile is harder to judge, but see the article in The Economist for a suggestion of an affirmative answer (actually, an answer of "usually", 83% net positive).
4,534,888
> > Let $\alpha, \beta, \gamma$ be positive real numbers and let $[a,b]$ be an interval. Find numbers $x,y,z\in [a,b]$ so that $E(x,y,z) = \alpha(x-y)^2 + \beta(y-z)^2 + \gamma (z-x)^2$ is maximum. > > > I think we can assume WLOG that $\alpha \leq \beta\leq \gamma.$ > > But how would one justify the above assumption? > > > Also, I think one can assume $x\leq y\leq z$. > > As for the justification, under the assumption that $x\leq y\leq z,$ one can see that $E(x,y,z) \ge E(y,x,z)$ and $E(x,y,z) \ge E(z,y,x).$ But $E(x,y,z) - E(z,y,x) = (\alpha - \beta)((x-y)^2 - (y-z)^2),$ and it's not clear that this value is nonnegative (if one only makes the above two additional assumptions). > > > With the above two assumptions, note that a convex function on a bounded interval attains its maximum at one of the endpoints. It might be useful to define a function like $f\_1(y) = \alpha(y-a)^2 + \beta(y-b)^2,$ which can be used to maximize $E(a,y,b)$ where $y$ ranges over $[a,b]$. But must the maximum value of $E$ be obtained at a point of the form $(a,y,b)$ or $(b,y,a)$?
2022/09/19
[ "https://math.stackexchange.com/questions/4534888", "https://math.stackexchange.com", "https://math.stackexchange.com/users/1087905/" ]
The maximum is attained with two of $x, y, z$ at the endpoints $a, b$. Because if one or both of the endpoints are not used, suppose $x \le y \le z$ (same proof with other orders), then $\alpha (x-y)^2 \le \alpha(a-y)^2$, $\beta (y-z)^2 \le \beta(y-b)^2$, $\gamma(z-x)^2 \lt \gamma(b-a)^2$, so $E(x,y,z) \lt E(a,y,b)$. We assume w.l.o.g. that $\alpha \le \beta \le \gamma$. We compare $E$ of all permutations of $x,y,z$. Note that permuting $(x,y,z)$ is equivalent to permuting $((x-y)^2, (y-z)^2, (z-x)^2)$. It is a known result that the maximum sum of term-by-term product of two finite sequences is when they are ordered the same way ([Proof for two sequences producing the maximum value when sorted](https://math.stackexchange.com/questions/355250/proof-for-two-sequences-producing-the-maximum-value-when-sorted)). So $\alpha \le \beta \le \gamma$ implies $(x-y)^2 \le (y-z)^2 \le (z-x)^2$ for the maximum. As two of $x,y,z$ must be $a,b$, this implies $\{x,z\}=\{a,b\}$. We can choose $x=a, z=b$ as we obtain the same value for $E$ by symmetry: $E(a,y,b)=E(b,a+b-y,a)$. Then to get the optimum value for $y$, study $\frac {\partial E(x,y,z)} {\partial y} = 2\alpha(y-x)+2\beta(y-z) = 2\alpha(y-a)+2\beta(y-b)$. This is null for $y\_0$ such that $\alpha(y\_0-a)=\beta(b-y\_0)$, $y\_0=\frac {\alpha a + \beta b} {\alpha+\beta}$. $\frac {\partial^2 E(x,y,z)} {\partial y^2} = 2\alpha+2\beta > 0$, so $\frac {\partial E(x,y,z)} {\partial y}$ is a strictly increasing function of $y$ that is null on $y\_0$. $E(a,y,b)$ is a decreasing then increasing function of $y$, that reaches a minimum on $y\_0$. There are 2 local maxima, one on $a$ and one on $b$. The largest one is for $y=a$: $E(a,a,b)-E(a,b,b)$ $=\alpha(a-a)^2+\beta(a-b)^2+\gamma(b-a)^2-\alpha(a-b)^2-\beta(b-b)^2-\gamma(b-a)^2$ $=(\beta-\alpha)(a-b)^2 \ge 0$. In summary, maximum is attained at $x=a,y=a,z=b$. (I don't detail the other solutions. There is the symmetric one at $(b,b,a)$; plus some other permutations of $(a,a,b)$ and $(a,b,b)$ when there are some equalities between $\alpha, \beta, \gamma$. Those other solutions have the same maximum value of $E$).
19,127,229
I'm using grep to display all lines that have ONLY 4,5,6,7 and 9 in the zipcode column. How do i display only the lines of the file that contain the numbers 4,5,6,7 and 9 in the zipcode field? A sample row is: 15 m jagger mick 41 4th 95115 Thanks
2013/10/01
[ "https://Stackoverflow.com/questions/19127229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2836730/" ]
I am going to assume you meant "How do I use grep to..." If all of the lines in the file have a 5 digit zip at the end of each line, then: egrep "[45679]{5}$" filename Should give you what you want. If there might be whitespace between the zip and the end of the line, then: egrep "[45679]{5}[[:space:]]\*$" filename would be more robust. If the problem is more general than that, please describe it more accurately.
29,419,688
Here, I want to encode php return in json output.I'm so confused to implement on there. So, how the correct way I have to do. index.html ``` $(function(){ $.ajax({ type: 'GET', url: "profile.php", success: function(resp){ var username = JSON.parse(resp).username; var profile = JSON.parse(resp).profile; $('.test').html(username+profile ); } }); }); ``` profile.php ``` <?php require_once('class.php'); ?> <?php if ($user->is_logged == 1) { $txtuser = ''; if (empty($D->me->firstname)) $txtuser = $D->me->username; else $txtuser = $D->me->firstname; if (empty($D->me->avatar)) $txtavatar = 'default.jpg'; else $txtavatar = $D->me->avatar; } ?> <?php echo json_encode(array('username' => '{$C->SITE_URL.$D->me->username}', 'profile' => '{$txtuser}' )); ?> ```
2015/04/02
[ "https://Stackoverflow.com/questions/29419688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4521365/" ]
You can add a conditional call back on the update of the track ``` class Track < ActiveRecord::Base # ignored associations and stuff after_update :create_track_rank, if: :rank_changed? # ignored methods private def create_track_rank track_ranks.create(data) end end ```
32,083,611
Debugging an application and experimenting a bit I came to a quite strange behaviour that can be reproduced with a following code: ``` #include <iostream> #include <memory> int main() { std::unique_ptr<int> p(new int); *p = 10; int& ref = *p; int* direct_p = &(*p); p.reset(); std::cout << *p << "\n"; // a) SIGSEGV std::cout << ref << "\n"; // b) 0 std::cout << *direct_p << "\n"; // c) 0 return 0; } ``` As I see it, all three variants have to cause undefined behaviour. Keeping that in the mind, I have these questions: 1. Why do `ref` and `direct_p` nevertheless point to zero? (not 10) (I mean, the mechanism of `int`'s destruction seems strange to me, what's the point for compiler to rewrite on unused memory?) 2. Why don't b) and c) fire SIGSEGV? 3. Why does behaviour of a) differ from b) and c)?
2015/08/18
[ "https://Stackoverflow.com/questions/32083611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/539570/" ]
The `StringLength` attribute appears to be overwritting the `FixedLength` attribute. A workaround is to add the length property to your `FixedLength` attribute and set the `HasMaxLength` yourself ``` class FixedLengthAttribute : Attribute { public int Length { get; set; } } public override void Apply(ConventionPrimitivePropertyConfiguration configuration, FixedLengthAttribute attribute) { configuration.IsFixedLength(); configuration.HasMaxLength(attribute.Length); } class MyEntity { [Key, FixedLength(Length=10)] public string MyStringProperty { get; set; } } ```
24,896,927
Does anybody knows while using azure blob storage to store css file , how to handler the image url inside css file like 'background-image: url(../images/test.jpg)' ?
2014/07/22
[ "https://Stackoverflow.com/questions/24896927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772790/" ]
Here is a rather naive rewrite of your code. Instead of tracking which employees you have already processed, let's just group all rows by their employees and process them each separately. ``` var rowsPerEmployee = (from DataRow row in dt.Rows let emp = row["Emp"].ToString().Trim() group row by emp into g select g) .ToDictionary( g => g.Key, g => g.ToArray()); foreach (var current in rowsPerEmployee.Keys) { var empRows = rowsPerEmployee[current]; ... rest of your code here, note that empRows is not all the rows for a single employee ... and not just the lastname or similar } ``` This will first group the entire datatable by the employee and create a dictionary from employee to rows for that employee, and then loop on the employees and get the rows.
24,537,025
I would like to perform a 'cross-difference' as follows: cross\_diff ( [a,b], [c,d] ) = [ [ a - c, a - d], [ b - c, b - d] ] I have a routine to do this in python as follows: ``` def crossdiff(a,b): c = [] for a1 in range(len(a)): for b1 in range(len(b)): c.append (a[a1]-b[b1]) x = numpy.array(c) x.reshape(len(a),len(b)) return x ``` The problem is that I have to create a python array and stuff the results into it, then convert back to a numpy array. I would like to be able to take numpy vectors a and b and get a numpy array c which contains all the differences, as the performance of the code above is poor for large vector sizes. Is there away to perform the above calculation as "pure" numpy operations? EDIT FOR TESTING RESULTS: I ran all four implementations listed in this thread through the Python profiler for comparison. I had to run them on a workstation since the initial implementation uses ~4GB of RAM with 10k elements. ``` import numpy import cProfile def cross_diff(A, B): return A[:,None] - B[None,:] def crossdiff2 (a,b): ap = numpy.tile (a, (numpy.shape(b)[0],1)) bp = numpy.tile (b, (numpy.shape(a)[0],1)) return ap - bp.transpose() def crossdiff(a,b): c = [] for a1 in range(len(a)): for b1 in range(len(b)): c.append (a[a1]-b[b1]) x = numpy.array(c) x.reshape(len(a),len(b)) return x a = numpy.array(range(10000)) b = numpy.array(range(10000)) cProfile.run('crossdiff (a,b)') cProfile.run('crossdiff2 (a,b)') cProfile.run('cross_diff (a,b)') cProfile.run('numpy.subtract.outer (a,b)') ``` Results: Original python is 74.147 seconds, my version is 1.656 seconds, 3rd implementation 0.296 and 4th 0.288.
2014/07/02
[ "https://Stackoverflow.com/questions/24537025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3731094/" ]
Try: ``` import numpy as np np.array([a,b])[:,None] - np.array([c,d,e])[None,:] ``` A bit of explanation: The `None` in the index expands the dimension as much as needed. So, actually the calculation will be: ``` a a a c d e a-c a-d a-e - = b b b c d e b-c b-d b-e ``` Surprisingly useful, the `None` in indexing. One more example: ``` import numpy as np def cross_diff(A, B): return A[:,None] - B[None,:] vec_a = np.array([1,2,3,4]) vec_b = np.array([3,2,1]) print cross_diff(vec_a, vec_b) ```
20,720,375
I've seen two methods of setting a form's action attribute. **#1. An empty action attribute:** ``` action="" ``` **#2. Action attribute with `#`:** ``` action="#" ``` What are the differences between the two?
2013/12/21
[ "https://Stackoverflow.com/questions/20720375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The first one (`""`) resolves to the base URL, and the second one (`#`) resolves to the document URL. The following is perfectly valid: ``` <form action="" method="post"> <p><input type="submit"/></p> </form> ``` Now beware, according to the [HTML4 specification](http://www.w3.org/TR/html4/interact/forms.html#h-17.3), the `action` attribute is mandatory, and it must contain a valid URI. But according to the [URI RFC](http://www.ietf.org/rfc/rfc2396.txt), an empty URI is still a URI: > > A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML's FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request. > > > (extract from [this page](http://www.thefutureoftheweb.com/blog/use-empty-form-action-submit-to-current)) --- Although it is mandatory, most if not all browsers will post back to the originator of the response if no action attribute is specified. And in HTML5, the `action` attribute is not mandatory. From the [specs](http://www.w3.org/html/wg/drafts/html/master/forms.html#action): > > The action and formaction content attributes, **if specified**, must have a value that is a valid non-empty URL potentially surrounded by spaces. > > > Related: * [Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")](https://stackoverflow.com/questions/1131781/is-it-a-good-practice-to-use-an-empty-url-for-a-html-forms-action-attribute-a?rq=1)
34,340,355
I have an ASP MVC app that uses jQuery UI for the datepicker and accordion widgets. When running locally and when deployed to the dev/debug web app on azure the icons for them (buttons to change months, arrow for accordions) show up just fine. However once deployed to the release/production web app, they do not. The widgets still work just fine, but for some reason it refuses to include the jquery ui images associated with the widgets. It does try to load the resource, but it comes back 404. I am deploying to Azure, and the web app configurations are the same for the debug/release web apps on the azure end. I'm not really sure which config files from my project are relevant to the problem, so i'll wait to post those until someone tells me to. I use the minified jquery ui css in my bundle config, and I know it bundles correctly since it actually tries to load the icons in production, but returns 404 on the icons themselves. * Content + images - ui-icons\_222222\_256x240.png + jquery-ui.min.css and in the jquery-ui.min.css it looks for them from the relative path like `background-image:url("images/ui-icons_222222_256x240.png")` So when it gets deployed to the release build it must re arrange where the content directory is relative to the css file or something..
2015/12/17
[ "https://Stackoverflow.com/questions/34340355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3351924/" ]
Assuming your files are marked as content and in a path relative to the ASP App Root, make sure your bundles are genn'ing the same every configuration. Like so: ``` bundles.Add(new StyleBundle("~/Content/cssthemebundle").Include( "~/Content/themes/base/jquery.ui.core.css", "~/Content/themes/base/jquery.ui.accordion.css", "~/Content/themes/base/jquery.ui.tabs.css", "~/Content/themes/base/jquery.ui.datepicker.css", "~/Content/themes/base/jquery.ui.theme.css")); ``` This works in our solution regradless of config. We did have a problem at one point with Release resource paths getting horked, but this bundle pathing works well now. Note: The resource images referenced in the theme css files are relative to the theme folder, not "~/". So the jquery-ui css urls should remain unchanged.
4,335,234
I have textarea where users enter details, I want to extract year from the textarea. The problem is users enter year in different ways. some users input dates as `1999` or `'99` or `september 99`. how can I use a single regex string to extract year.
2010/12/02
[ "https://Stackoverflow.com/questions/4335234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488612/" ]
This should work for extracting the mentioned dates out of text: ``` preg_match_all('/(^|\s+)(\d{4}|\'\d{2}|(january|february|march|april|may|june|july|august|september|october|november|december) \d{2})(\s+|$)/i', $text, $matches); ``` This came to my mind, too (it gives the user a little more freedom): ``` preg_match_all('/(^|\s+)((january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)?(\s|\s?\')(\d{2}|\d{4}))(\s+|$)/i', $text, $matches); ``` All of the above would be easier when parsed with multiple expressions. Why do you need a single one? If you simply want to parse a string that contains nothing else than this, you should use PHP's [`strtotime()`-function](http://php.net/strtotime).
3,115,755
By ASP.NET MVC plugin architecture, [Plug-in architecture for ASP.NET MVC](https://stackoverflow.com/questions/340183/plug-in-architecture-for-asp-net-mvc) I have separated DLL(plugin) which contains the views, css and javascript files in the resources. So my own VirtualPathProvider will load the content out from the DLL if that is for the plugin. It works all fine during development. But It appears not working once I deployed it in IIS. (I mapped the whidcard in IIS 6 and the views are showing) I have registered my VirtualPathProvider in global.asax as ``` protected void Application_Start() { RegisterRoutes(RouteTable.Routes); HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider()); } ``` For example. <http://localhost/Plugin/MyPlugin.dll/Styles.MyStyles.css> This should be loaded from the plugin.dll but IIS returns 404. I guess the static files are all handled by the IIS and not went through asp.net and my VirtualPathProvider ? Is there way to get around this? Please shed some light. Thanks in advance.
2010/06/25
[ "https://Stackoverflow.com/questions/3115755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11413/" ]
If this is IIS 6 you will need a wildcard mapping. See [this blog post](http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx) from Phil Haack.
73,666,818
``` void selectNotification(String? payload) async { print('Selected notification'); Navigator.of(context).push( MaterialPageRoute( builder: (context) => SearchScreen(), ), ); } ``` I am using this method to open a screen when the notification is tapped, I get the print message fine but then the Navigator message shows: ``` The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget. ``` Im just trying to have it so if the notificaiton is tapped from foreground, background where ever the app then just pops open that screen but I cant get it to work
2022/09/09
[ "https://Stackoverflow.com/questions/73666818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18030965/" ]
The problem is that the compiler doesn't know how to do [narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html) on an object property like `IceCreams[item]` where you are indexing with a key whose type isn't known to be a specific [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types). TypeScript is only following the *type* of the index, not the *identity*. And the type of `item` is `string`. If you have `item1` and `item2`, both of type `string`, then checking `IceCreams[item1]` wouldn't let you conclude anything about `IceCreams[item2]`, right? And since TypeScript can't tell the difference between `item1` vs `item2` or `item` vs `item`, it can't narrow. This is a known limitation of TypeScript reported at [microsoft/TypeScript#10530](https://github.com/microsoft/TypeScript/issues/10530). Maybe someday it will be addressed. But for now, there's an easy workaround: Just copy the value into a new variable, so that the problematic indexing occurs only once: ``` iceCreamKeys.forEach(item => { const x = IceCreams[item]; if (x.natural) { console.log(x.naturalComponent) // okay } }) ``` [Playground link to code](https://www.typescriptlang.org/play?#code/FAFwngDgpgBAKgMQDYEMBuB7ArgJxgXhgAoBvYGCmAOxRFxSQC4YQcsoAacymunBgMIYAthAxUoVEMwDOrAJZUA5sAC+AShgAfYmUrVa9JjABmDGZ24UUOEPJPyAxvMEixEqbIXK164KEhYOABJRygBHCgUYQIYACUoRwwcABMAHjkcRSUOeGR0bBwAPn8kqjkYUPDI6JlmELCIqJjCPUohAGsoKqbo5jb9Cl4jZjMkCy5Byhs7B2dXUXFJaRgAck6oVasYVUnKADUUKnkkVH7t-WH+Y1Z2Pamrhfdl5lXD49OUGABRAA9WFCOEBbfS7bYAWSOSgw5ymQ0M12Yt0scIMfCeS08a0hygwMAQbHkwP8oLU-mAZQqTmqzQA0lAwDJYgB5ABGACtEiAAHRdRlEHo1YQyPzAam9YT0xnckzJb6AgAWRCJUBaRRgAxglJAMF+sUFzRkAG0VcIALoAbm29mIv25jyQmk1+kpGCQUG5SAwSiIdodQkWHhAmm2ql85JtAsaQpk3Jx0PtCIYTu2rvdnu9UZptTjUIwifRSADzykmgA9GWYAB1ZIdJkKqCRMlAA)
38,938,349
I am beginner in C++ and have question about these statements. ``` vector<double> vec1; typedef vector<double>::size_type vec_size vec_size size = vec1.size() ``` From question, [C++: "vector<int>::size\_type variable" - what is the point of declaring in this way?](https://stackoverflow.com/questions/24825712/c-vectorintsize-type-variable-what-is-the-point-of-declaring-in-this?noredirect=1), I understand that `size::type` holds largest possible vector size. I am confused what *type* is `size::type` - is it a function, variable, etc.? Using [typedef](https://en.wikipedia.org/wiki/Typedef) `vec_size` is equivalent to `vector<double>::size_type`. So the third line becomes ``` vector<double>::size_type size = vec1.size() ``` This is very confusing to me. What is *type* of variable `size`? It would be really helpful if someone comments in simplified language.
2016/08/14
[ "https://Stackoverflow.com/questions/38938349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707311/" ]
The are really two questions here: > > what is the point of declaring in this way > > > It's to keep your fingers from falling off your hand. If you need to reference this type over and over again, it's easier to just type `vec_size` each time, instead of spelling out `vector<double>::size_type`. Each. and. every. time. Use the `typedef`. Your fingers will thank you for it. Especially the little pinky finger, who doesn't have to hit the `SHIFT` key so often, any more. Not to mention that it makes the resulting code easier on the eyes, too. Now, as far as the second question: > > What is type of variable size? > > > The answer is: you don't know, and you shouldn't care. The only thing you should care about is that this type is sufficient to represent the number of elements in the vector. That's the definition of what this type is. It might be an `unsigned int`, or an `unsigned long`, or even an `unsigned long long`. But don't worry about it. Whatever it is, it will be big enough to express the size of the largest possible vector you have even the slightest hope of declaring and using. This also means that this type would also be the right type for representing an index of any element in the vector. So, if you need to save the index of some particular element in the vector, or iterate over the values in the vector by their index, this is the right type for it. Since it's big enough to represent the size of the vector, it's big enough to represent the index of any particular value in the vector. Of course, for vectors whose size is expected to be quite modest, by today's standards, using a plain `int` will also work. But by using this type, you'll be bragging to all your friends: see, I know a lot about C++. I know how to use this type properly.
108,963
This post actually contains two separate questions but I think grouping them together will give some more context. I have gone through [this question on quotes around variables](https://unix.stackexchange.com/questions/65624/why-do-i-need-to-quote-variable-for-if-but-not-for-echo) but I do not quite understand what *variable expansion* mean in the first place. So my first question is : 1. What is *variable expansion* in unix/linux speak? A second part of my question relates to the following terms : 1. *glob* 2. *split* What do the above mean and how do they affect variable expansion? The answer to the original question mentions the following: > > Think of the absence of quotes (in list contexts) as the split+glob > operator. > > > As if echo $test was echo glob(split("$test")). > > > I couldn't find any answers that directly addresses the concept of *globbing* and *splitting* but rather uses those terms directly in answering other questions like this [recent one](https://unix.stackexchange.com/a/108638/28032).
2014/01/12
[ "https://unix.stackexchange.com/questions/108963", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/28032/" ]
*Variable expansion* (the standard term is *parameter expansion*, and it's also sometimes called *variable substitution*) basically means replacing the variable by its value. More precisely, it means replacing the `$VARIABLE` construct (or `${VARIABLE}` or `${VARIABLE#TEXT}` or other constructs) by some other text which is built from the value of the variable. This other text is the expansion of the variable. The expansion process goes as follows. (I only discuss the common case, some shell settings and extensions modify the behavior.) 1. Take the value of the variable, which is a string. If the variable is not defined, use the empty string. 2. If the construct includes a transformation, apply it. For example, if the construct is `${VARIABLE#TEXT}`, and the value of the variable begins with `TEXT`, remove `TEXT` from the beginning of the value. 3. If the context calls for a single word (for example within double quotes, or in the right-hand side of an assignment, or inside a here document), stop here. Otherwise continue with the next steps. 4. **Split** the value into separate words at each sequence of whitespace. (The variable `IFS` can be changed to split at characters other than whitespace.) The result is thus no longer a string, but a list of strings. This list can be empty if the value contained only whitespace. 5. Treat each element of the list as a file name wildcard pattern, i.e. a **[glob](https://en.wikipedia.org/wiki/Glob_(programming))**. If the pattern matches some files, it is replaces by the list of matching file names, otherwise it is left alone. For example, suppose that the variable `foo` contains `a* b* c*` and the current directory contains the files `bar`, `baz` and `paz`. Then `${foo#??}` is expanded as follows: 1. The value of the variable is the 8-character string `a* b* c*`. 2. `#??` means strip off the first two characters, resulting in the 6-character string `b* c*` (with an initial space). 3. If the expansion is in a list context (i.e. not in double quotes or other similar context), continue. 4. Split the string into whitespace-delimited words, resulting in a list of two-strings: `b*` and `c*`. 5. The string `b*`, interpreted as a pattern, matches two files: `bar` and `baz`. The string `c*` matches no file so it is left alone. The result is a list of three strings: `bar`, `baz`, `c*`. For example `echo ${foo#??}` prints `bar baz c*` (the command `echo` joins its arguments with a space in between). For more details, see: * [Parameter expansion in the POSIX standard](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02), followed by [field splitting](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05) and [pathname expansion](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_06) * [Shell parameter expansion in the bash manual](http://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion), followed by [word splitting](http://www.gnu.org/software/bash/manual/bash.html#Word-Splitting) and [filename expansion](http://www.gnu.org/software/bash/manual/bash.html#Filename-Expansion) * [$VAR vs ${VAR} and to quote or not to quote](https://unix.stackexchange.com/questions/4899/var-vs-var-and-to-quote-or-not-to-quote) * [When is double-quoting necessary?](https://unix.stackexchange.com/questions/68694/when-is-double-quoting-necessary/68748#68748)
27,401,582
I'm pretty new to Angular and having a form like this (about 15 Inputs and Selects): ``` <div id="configForm" data-ng-controller="seutpController"> <form name="configForm" data-ng-submit="update()" novalidate> <input id="id" type="hidden" data-ng-model="config.id" /> <input id="company" type="text" data-ng-model="config.company" data-ng-blur="test()"/> <input id="street" type="text" data-ng-model="config.street" data-ng-blur="test()" /> </form> <input type="submit" /> </div> ``` What's already working: ----------------------- Making an AJAX Call on Submit which updates the Database with all values from the config object. No big Deal. What I'd like to do: -------------------- Making an AJAX Call (on Blur), but I'd like to send only the one key/value pair which was changed by the user like: ``` $http({ url: 'api/setConfig.php', method: 'POST', data: {'company': 'value'} }) ``` Do I have to send $event as function param like ng-blur="test($event)" and get the Elements Id and Value from there? Thanks @ all! Edit ---- Is it a possible option using $watchCollection and watching on the $scope.config object?
2014/12/10
[ "https://Stackoverflow.com/questions/27401582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4323814/" ]
I would say it's probably best to send the $event, since that would be the most extendable solution. I've done something similar in the past: ``` <input name="title" ng-blur="ctrl.onFieldChanged($event)" type="text" ng-model="ctrl.title"/> ``` In my method, I named the input the same name as the ng-model its bound to, just for convenience. In the controller, here's what I do: ``` this.onFieldChanged = function ($event) { var data = {}; data[$event.currentTarget.name] = self[$event.currentTarget.name]; $http({ url: '...', method: 'POST', data: data }); }; ``` Hope this helps.
1,605,378
on my HP notebook I just setup a triple boot system with 2x Windows 10 + Linux Mint partitions (there are reasons why I don't use virtual machines here). In my BIOS I had to enable UEFI custom boot and point it at EFI\ubuntu\grubx64.efi (I had run into [this problem](https://askubuntu.com/questions/1042747/system-bootorder-not-found), found [that solution](https://askubuntu.com/a/1103331/1031178)). Currently the machine boots into a Grub bootloader showing me - among other options - the main Mint entry + an entry for the Windows bootloader. If I select the latter I end up on the Windows bootloader screen (of course) letting me choose between the 2 Windows systems. Questions: 1. is there a way to by-pass the Windows bootloader but instead configure Grub to directly let me choose between the 2 Windows installations? 2. Or as an alternative: could I by-pass Grub and include Mint into the Windows bootloader? What would I have to do to get rid of Grub and make the Windows B/L the prime one? If I had the choice I'd prefer option 1 I've seen many descriptions dealing with older Windows versions, or a mix of Windows 10 with one or two older versions. But none seems to explain what I would like to get. Thanks for your ideas!
2020/11/26
[ "https://superuser.com/questions/1605378", "https://superuser.com", "https://superuser.com/users/555910/" ]
Meanwhile solved it in a different way by just putting the 2 Windows installs onto the internal SSD while installing Linux onto an exernal USB drive. Not quite as fast but much easier to handle
2,859,650
Sorry about the vague title! I have an class with a number of member variables (system, zone, site, ...) ``` public sealed class Cello { public String Company; public String Zone; public String System; public String Site; public String Facility; public String Process; //... } ``` I have an array of objects of this class. ``` private Cello[] m_cellos = null; // ... ``` I need to know whether the array contains objects with the same site but different systems, zones or companies since such a situation would be illegal. I have various other checks to make but they are all along similar lines. The Array class has a number of functions that look promising but I am not very up on defining 'key selector' functions and things like that. Any suggestions or pointers would be greatly appreciated. --- Alistair.
2010/05/18
[ "https://Stackoverflow.com/questions/2859650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41013/" ]
``` bool illegalCellos = m_cellos .Any(c => m_cello .Any(nc => nc.Site == c.Site && (nc.Zone != c.Zone || nc.System != c.System || nc.Company != c.Company))); ```
2,510,024
Given a set $X$ and an indexed family $\{(Y\_i,\mathscr T\_i)\}\_{i\in I}$ of topological spaces with functions $f\_i:Y\_i\to X$. Let $\tau\_{\text{final}}$ be the [final topology](https://en.wikipedia.org/wiki/Final_topology) in $X$ w.r.t. $\{f\_i\}\_{i\in I}$, that is, it's the finest topology such that each $f\_i:(Y\_i,\mathscr T\_i)\to (X,\tau\_{\text{final}})$ is continuous. Now consider a [net](https://en.wikipedia.org/wiki/Net_(mathematics)) $\{x\_\alpha\}\_{\alpha\in A}\subset X$. The question is how to characterize the convergence of the net $\{x\_\alpha\}\_{\alpha\in A}$ in $(X,\tau\_{\text{final}})$? --- It's easy to get the following characterization for net convergence in [initial topology](https://en.wikipedia.org/wiki/Initial_topology): > > Given a family of functions $g\_i:X\to Y\_i$, let $\tau\_{\text{initial}}$ be the initial topology w.r.t. $\{g\_i\}\_{i\in I}$, that is, it's the coarsest topology such that each $g\_i:(X,\tau\_{\text{initial}})\to (Y\_i,\mathscr T\_i)$ is continuous. Then the net $\{x\_\alpha\}\_{\alpha\in A}\to x$ in $(X,\tau\_{\text{initial}})$ if and only if for all $i\in I$, $\{g\_i(x\_\alpha)\}\_{\alpha\in A}\to g\_i(x)$ in $(Y\_i,\mathscr T\_i)$. > > > So is there any analogous characterization for that of final topology? Any comments or hints will be appreciated!
2017/11/08
[ "https://math.stackexchange.com/questions/2510024", "https://math.stackexchange.com", "https://math.stackexchange.com/users/329754/" ]
There is no simple characterization of when a net converges in the final topology. In particular, arguably the simplest case is when your family just consists of a single space $Y$ with a surjective map $f:Y\to X$. In that case the final topology is just the quotient topology, but there is no simple description of when a net converges in the quotient topology in terms of convergence of nets in the original space. For examples of how some naive guesses can go wrong, you may be interested in the post [Lifting a convergent net through a quotient map](https://math.stackexchange.com/questions/2375956/lifting-a-convergent-net-through-a-quotient-map). To give a bit of a broader perspective, convergence of a net in a space $X$ is equivalent to continuity of a certain map $I\to X$ for a certain space $I$ (see [this answer](https://math.stackexchange.com/questions/9825/does-this-property-characterize-a-space-as-hausdorff/1607591#1607591) of mine). The initial topology is a type of limit in the category of topological spaces, and maps into a limit are characterized by a universal property, and so convergence of nets in a limit space has a simple characterization. On the other hand, the final topology is a colimit, and there is no universal property for maps into a colimit (instead the universal property is for maps out of it). So it should not be surprising that there is no nice characterization of convergence of nets in a colimit.
14,456,620
As it stands I'm using a Dictionary to store answers to a question in the following format:- ``` Destination: A1 - Warehouse A2 - Front Office A3 - Developer Office A4 - Admin Office B1 - Support ``` A1, A2 etc are unique identifiers used to select questions elsewhere and the answer is tagged on at the end, the dictionary stores ID and the Answer. This part all works fine. The problem is when inserting the data into a list box/combo box. At the moment I'm using the method below: ``` foreach (KeyValuePair<string, string> oTemp in aoObjectArray) { if (listControl is ComboBox) { ((ComboBox)listControl).Items.Add(string.Format("{0} - {1}", oTemp.Key, oTemp.Value)); } else if (listControl is ListBox) { ((ListBox)listControl).Items.Add(string.Format("{0} - {1}", oTemp.Key, oTemp.Value)); } } ``` This inserts the correct data into the list/combo box but in the following format: ``` Destination: [A1: Warehouse] [A2: Front Office] [A3: Developer Office] [A4: Admin Office] [B1: Support] ``` I've tried a number of other methods to get rid of the squared brackets. Interestingly if I just do ``` ((ComboBox)listControl).Items.Add(string.Format(oTemp.Value)); ``` I still get the data out in the [A1: Warehouse] format. How can I get rid of the squared brackets? EDIT: Been asked to add more code. Here is the full add to list control method: ``` public static void AddDictionaryToListControl(ListControl listControl, Dictionary<string, string> aoObjectArray) { foreach (KeyValuePair<string, string> oTemp in aoObjectArray) { if (listControl is ComboBox) { ((ComboBox)listControl).Items.Add(string.Format(oTemp.Value)); } else if (listControl is ListBox) { ((ListBox)listControl).Items.Add(string.Format(oTemp.Value)); } } } ``` This method is called from: ``` public ComboBox AddQuestionsComboBox(Dictionary<string, string> Items, string Label, string Key, int Order, bool Mandatory) { ComboBox output; output = AddControl<ComboBox>(Label, Key, Order); FormsTools.AddDictionaryToListControl(output, Items); AddTagField(output, Tags.Mandatory, Mandatory); return output; } ``` Which is called using the following line: ``` AddQuestionsComboBox(question.PickList, question.PromptTitle, question.FieldTag, i, offquest.Mandatory); ``` Hope that helps. EDIT: I've tried all the suggestions below and still no improvement - I've checked and rechecked the code and all methods that relate to it for some additional formatting I've missed and found nothing that could cause the formatting to be set correctly at one stage and then binned by the time it gets on screen.
2013/01/22
[ "https://Stackoverflow.com/questions/14456620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1999900/" ]
You will need to [URL encode](http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx) the URLs before posting them in the RSS: ``` var encoded = HttpUtility.UrlEncode(aUrl); ``` Note that the URLs will not be usable directly as `:`, `/` etc will also get encoded. If you want the values of these to be valid XML, use [`SecurityElement.Escape`](http://msdn.microsoft.com/en-us/library/system.security.securityelement.escape.aspx) instead. ``` var escaped = SecurityElement.Escape(aUrl); ```
52,555
so I have some 9 speed campy shifters and a 9 speed shimano wheelset lying around, I'd like to know if they can work with each other so I can save some money as I'm planning on building/ upgrading a bike in the near future with these parts. So in short, is Campagnolo and Shimano in any way compatible with each other?
2018/03/11
[ "https://bicycles.stackexchange.com/questions/52555", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/36880/" ]
Campagnolo has two cable pull numbers for 9 speed, theres 3.0 and 3.2 mm per click. Shimano 9 speed is 2.5mm of cable pull per click, so you're out of luck. --- I'd suggest selling on the campy shifters on ebay and use the proceeds to fund some boring but common shimano ones. Or go the other way and look for a campag rear wheel and derailleurs, but these will likely be more rare and therefore cost more. Reference link: <http://blog.artscyclery.com/science-behind-the-magic/science-behind-the-magic-drivetrain-compatibility/>
6,787,697
I open a apache server on my PC. And I can visit it by <http://localhost>. When I went to cmd and use ipconfig to know my ip and try to visit the site by this ip, it's failed. ``` "Forbidden You don't have permission to access / on this server. Apache/2.2.11 (Win32) PHP/5.2.17 Server at 169.243.***.** Port 80" ``` How can I solve this problem? I want to use my phone to visit it and download some files. btw, my PC and phone were in the same network. Thanks!
2011/07/22
[ "https://Stackoverflow.com/questions/6787697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741395/" ]
Do you have ``` Deny from all Allow from localhost ``` Somewhere in your httpd.conf or your .htaccess?
39,583
Been searching around the web for answers, none found. My guess is that it's uncooked rice (as "unedged" rice doesn't make any sense).
2016/09/30
[ "https://japanese.stackexchange.com/questions/39583", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/11397/" ]
Before cooking rice, many people wash the rice by "grinding" (hence 研ぐ) the individual grains against one another under flowing water until the water runs more or less clear. (In the olden days the purpose of the grinding was to remove the hull (糠【ぬか】).) In the process of this, together with rest of the hulls and dust, minerals and starch are also removed. In any case, お米を研がず means "without washing the rice (rigorous/vigorously)".
23,435
I was intrigued to learn recently of the [Paleocene–Eocene thermal maximum](https://en.wikipedia.org/wiki/Paleocene%E2%80%93Eocene_Thermal_Maximum) from [this blog of John Baez](https://math.ucr.edu/home/baez/week317.html). For those who haven't seen, it's the sharp spike labelled "PETM" in this graph (from Wikipedia) of global temperatures over the past 65 million years: [![Global temps over time](https://i.stack.imgur.com/0uUyO.png)](https://i.stack.imgur.com/0uUyO.png) It immediately struck me that this event is somewhat parallel to modern day climate change–an observation which is also mentioned in the Wikipedia article. Apparently, it is conjectured that the Paleocene–Eocene thermal maximum may have been caused by volcanic eruptions. (In asking the following question, I am not saying that I believe this to be the case (indeed, I find it highly implausible). I ask simply out of scientific curiosity.) **Is there any way we could tell whether the Paleocene–Eocene thermal maximum was caused by an ancient race of intelligent life forms, who caused a period of global warming in similar fashion to what humans are doing currently, and subsequently went extinct?** --- The answer I expect is along the lines of "No, we can't exclude that for sure. But we would expect to see some fossil records from such a civilization, which we don't." But I would be happy to be surprised in either direction by someone more knowledgeable. Some food for thought: * [This answer](https://earthscience.stackexchange.com/a/2873) indicates that there is uncertainty about what actually caused the PETM. * I have heard it said that there are only two things humans have accomplished which will leave a permanent mark on the geological record. The first is climate change. The second is leaded gasoline, which will leave an identifiable stratum around the globe.
2022/01/23
[ "https://earthscience.stackexchange.com/questions/23435", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/26268/" ]
tl;dr: > > No, we can't exclude that for sure. But we would expect to see some > fossil records from such a civilization, which we don't. > > > Yes, pretty much this. --- To elaborate, I would refer to your statement that: > > I have heard it said that there are only two things humans have accomplished which will leave a permanent mark on the geological record. The first is climate change. The second is leaded gasoline, which will leave an identifiable stratum around the globe. > > > This is absolutely incorrect. There are so many signatures that our civilisation is leaving at the moment in the geological record, permanently. Some examples: 1. Mining activities. Assuming your civilisation is extracting resources from the Earth to power their fossil fuel industry, then need to mine the stuff. We are talking about huge holes in the ground. There are no currently known cases of an ore deposit that looks like someone has mined out the valuable stuff millions of years ago, leaving behind a hole (whether currently filled or not) surrounded by lower grade material. What about tailings ponds? Large areas of shallow water (with sediments forming at the bottom), full of stuff that isn't usually found together. This would be very easy to find. 2. Electricity. High voltage power lines. You just don't have very long and thin lines of copper or aluminium forming in nature. Even if they don't remain in their metallic form, copper oxide or carbonate, and aluminium oxide or hydroxide don't form horizontal veins that cut across pretty much everything. 3. Agriculture. The huge amount of fertiliser dumped onto farms, and then washed away in rivers forms very large anomalies of nitrogen and phosphate. Again, something that would stick out like a sore thumb in the geological record. 4. Rare earth elements (lanthanides) and gadolinium. These elements form very distinct concentration distributions in natural rocks and sediments. Humans are using individual elements out of the entire lanthanide group, and this ends up in rivers and then in the ocean. Once the concentration anomalies are out there, they are not going anywhere. We have very sensitive ways to detect even tiny differences of these elements from what they should be in natural systems. 5. Landfills. A whole soup of elements that should not be together. No natural system can form this. They're buried in the ground, and they stay there. 6. Megacities. Tokyo, New York, London, Sydney. Huge amounts of asphalt, concrete, glass, steel, aluminium. Overground and underground. Even if you collapse and erode whatever remains, you will have huge areas covered with former cities, forming rock formation that are otherwise not possible in natural geological processes. 7. Nuclear waste. I reckon there's no need to add anything here - right? Obvious that these things will not form in nature. The list goes on and on. Trust me, if there was a civilisation large enough and advanced enough to destroy itself, we would see that very well in the geological record.
1,055,394
I am unable to delete a VM. Below is the machine type: ``` f1-micro (1 vCPU, 0.6 GB memory) ``` Note:- Delete button is disabled for me. Hence I can't delete it. Below is error that I get from cloud shell: ``` ERROR: (gcloud.compute.instances.delete) Could not fetch resource: - Invalid resource usage: 'Resource cannot be deleted if it's protected against deletion.'. ``` Please help me in resolving this issue.
2021/02/28
[ "https://serverfault.com/questions/1055394", "https://serverfault.com", "https://serverfault.com/users/619618/" ]
Sounds like you have enabled deletion protection in Google Cloud Platform. To check this go to; Computer Engine > [VM instances](https://console.cloud.google.com/compute/instances), and then click on the instance you are having the issue with. Up the top click the edit button > scroll down the page a little bit to Deletion protection, make sure it is unticked: [![enter image description here](https://i.stack.imgur.com/mLTXS.png)](https://i.stack.imgur.com/mLTXS.png) if it is ticked untick it then scroll to the bottom of the page and save. Now try deleting it again.
4,129,580
I need to design a system in a website to display different pages to different users based on multiple rules: 1. If the user's visit is organic, direct hit to the homepage, show /url1 2. If the user's visit is not organic like he was referred from a blog, show /url2 3. If the user wants to shop, but isnt logged in, show /url3 How do I achieve this?!
2010/11/09
[ "https://Stackoverflow.com/questions/4129580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497488/" ]
> > ...they are pretty complex select queries but no joins are involved, they actually select from 2 different views. > > > But are there joins in the views? And do the views have any tables in common? Without seeing the query, and the queries the views stand in for, there's very little anyone can provide that will be of value.
344,253
I have come in a little discussion on a [specific question](https://stackoverflow.com/q/42362726/993547). I wonder if it warrants closing or not. We can't quite agree in the comments so I thought I'd ask here. Given reasons to close: * The duplicate answers the question actually asked; * The question is too broad. Given reasons to reopen it: * The duplicate just gives a very specific answer, and doesn't answer the slightly different requirements; * The duplicate just about finding one item from a list, not a subset of, or strings. Community, what do you think? Does this question needs to be closed or not? To prevent accusations of having a personal interest in the question being reopened, I removed the answer I have posted.
2017/02/21
[ "https://meta.stackoverflow.com/questions/344253", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/993547/" ]
The question is: > > select a random assortment of items [from a collection], the number of which being left up to the user > > > The idiomatic way to do this is to do a proper shuffle of the source collection, then take the first N items. A bad way (in terms of both performance and randomness) to shuffle a list is to order by `Random.Next()` or `Guid.NewGuid()`. Despite the title of the question, what is being asked here is definitely not *"Can the Random class return strings?"*. Answering *that* question is feeding into an XY problem, without showing understanding to the OP's underlying problem, which is explained in their question text. Now as for the actual duplicate, in hindsight (and with the motivation shown above) I agree the question I chose ([Access random item in list](https://stackoverflow.com/questions/2019417/access-random-item-in-list?noredirect=1&lq=1)) was not the best target. The second answer does exactly what the OP asks for, but with an improper implementation. I get trigger-happy with duplicate-votes on questions that show little research effort, and am aware of that. But just as security (*"I can't read the result, so it must be properly encrypted, amirite?"*), random is a poorly understood subject. *"The result isn't ordered like it was at the start, so it must be random, right?"*, so you cannot trust the upvotes on the answers that do contain code. The question [Select N random elements from a List<T> in C#](https://stackoverflow.com/questions/48087/select-n-random-elements-from-a-listt-in-c-sharp) is also a poor duplicate. The first few answers contain theoretical discussions and/or poor implementations, only the seventh answer contains actual, non-broken code. [Given a list of length n select k random elements using C#](https://stackoverflow.com/questions/17763664/given-a-list-of-length-n-select-k-random-elements-using-c-sharp) is a good duplicate. [Randomize a List<T>](https://stackoverflow.com/questions/273313/randomize-a-listt) too, but only answers the question at hand partially.
52,408,830
I got this SQL query and it works (tested on DB and results are as expected) ``` select n.name, s.id, pn.name from structure s join node n on n.id = s.node_id left join structure ps on ps.id = s.parent_id left join node pn on pn.id = ps.node_id ``` How can I re-create this query with the criteria builder API? I cannot figure it out.. Classes are: ``` class node { String id; String name; } class Structure { String id; Node node; String parentId; // Structure id } ``` I can make the Join from Structure to node like ``` Root<Structure> structureRoot = criteriaQuery.from(Structure.class); Join<Structure, Node> firstJoin = structureRoot.join("node"); ``` This takes me from Structure to a Node, how can I use this first join to join in back to parent structure that is on the Structure as a String parentId, not a relation? edit --- When making an relation from structure to structure Classes are updated : ``` class node { String id; String name; } class Structure { String id; @ManyToOne @JoinColumn(name = "node_id") Node node; @ManyToOne @JoinColumn(name = "parent_id") Structure parent; } ``` i got this error: ``` o.h.engine.jdbc.spi.SqlExceptionHelper : Column "STRUCTURE2_.ID" not found; SQL statement: select structure0_.id as col_0_0_, node3_.name as col_1_0_, structure0_.id as id1_2_, structure0_.node_id as node_id3_2_, structure0_.parent_id as parent_i4_2_, structure0_.source_id as source_i2_2_ from structure structure0_ inner join node node4_ on structure0_.node_id=node4_.id and (node1_.id=structure0_.node_id) left outer join structure structure5_ on structure0_.parent_id=structure5_.id and (structure2_.id=structure0_.parent_id) left outer join node node6_ on structure0_.node_id=node6_.id and (node3_.id=structure2_.node_id) cross join node node1_ cross join structure structure2_ cross join node node3_ where lower(node1_.name) like ? order by node1_.name desc limit ? [42122-197] 2018-09-20 12:13:49.447 ERROR 4599 --- [ main] c . .t.assets.service.SortToOrderMapper : org.hibernate.exception.SQLGrammarException: could not prepare statement ``` if i run this query: ``` CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class); Root<Structure> s = criteriaQuery.from(Structure.class); Root<Node> n = criteriaQuery.from(Node.class); Root<Structure> ps = criteriaQuery.from(Structure.class); Root<Node> pn = criteriaQuery.from(Node.class); Join one = s.join("node"); one.on(criteriaBuilder.equal(n.get("id"), s.get("node"))); Join two = ps.join("parent", JoinType.LEFT); two.on(criteriaBuilder.equal(s.get("parent"),ps.get("id"))); Join three = s.join("node",JoinType.LEFT); three.on(criteriaBuilder.equal(pn.get("id"),ps.get("node"))); return criteriaQuery.select(criteriaBuilder.array(s,three.get("name"))).where( criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]))); ```
2018/09/19
[ "https://Stackoverflow.com/questions/52408830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7604893/" ]
Since i added the ``` @ManyToOne @JoinColumn(name = "parent_id") private Structure parent; ``` I do not need to make the joins.. i was doing to much and was doing it at the same time. Cleaned my select clause and removed the joins and it works!
63,753,290
I have made the following example to test my understanding of references: ``` #include <iostream> int test(){ int a = 1; int &b = a; return b; } int main(int argc, const char * argv[]) { std::cout << test() << std::endl; } ``` What I intended to do is to write an example where the referenced variable is destroyed. I originally wrote this thinking that, since the lifetime of `a` in `test` ends when returning `b` in `test`, outputting the return-value of `test` produces gibberish. However, to my big surprise, it actually does output 1! How is this possible? What am I missing here - can `a` somehow continue living in `b`?
2020/09/05
[ "https://Stackoverflow.com/questions/63753290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11074397/" ]
The function does not return a reference to any object. It returns a temporary object of the type int that was copy-initialized by the value referenced by b. ``` int test(){ int a = 1; int &b = a; return b; } ``` In fact the function is equivalent to the following function without using intermediate variables ``` int test(){ return 1; } ``` To return a reference means that the function return type should be a referenced type. Something like ``` int & test() { int a = 1; return a; } ``` In this case the compiler will issue a message that the function returns a reference to a local variable.
40,480,005
``` public static void main(String[] args) { String str1 = "java"; String str2 = str1.intern(); String str3 = new String(str1.intern()); System.out.println("hash1=" + str1.hashCode()); System.out.println("hash2=" + str2.hashCode()); System.out.println("hash3=" + str3.hashCode()); System.out.println("str1==str2==>>" + (str1 == str2)); System.out.println("str1==str3==>>" + (str1 == str3)); } ``` ============================================output===> hash1=3254818 hash2=3254818 hash3=3254818 str1==str2==>>**true** str1==str3==>>**false** ================================= Can anyone explain how == returns **false** even though **s1** and **s3** having **same** hashcode?
2016/11/08
[ "https://Stackoverflow.com/questions/40480005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6813506/" ]
Despite the comments above, I suspect that you already understand that `==` determines if two references point to the same object (or are both null), and that you should use `equals()` if you want to compare two strings for data-equality. Rather, I think what you're missing is that the `hashCode()` method corresponds to the `equals()` method in this respect; it's based on the data in an object, and in fact, it's specified that classes should always implement `hashCode()` in such a way that if `a.equals(b)`, then `a.hashCode() == b.hashCode()`. (Of course, there's nothing in the language that enforces this.) The analogue of `==` that you're looking for is [the `System.identityHashCode()` method](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#identityHashCode-java.lang.Object-). However, even there it should be noted that `System.identityHashCode()` does not *guarantee* that distinct instances will have distinct identity hash codes. (It can't, because it's possible to have more than 232 objects in a JVM at the same time . . . granted, not all JVMs support that; but nothing in the Java language specification forbids it.)
38,166,003
I am hitting a strange issue with score serialization in my game. I have a LevelHighScore class: ``` [System.Serializable] public class LevelHighScores { readonly Dictionary<Level, ModeScores> scores; // clipped out the rest for simplicity } ``` With a enum key, `Level`. I recently added some new levels to my game, but instead of adding the new levels to the end of the enum, I added the new enums in alphabetical order. Now when I load the game my new levels have existing scores associated with them, making me think that the ordinal of the enums are having an effect on the serialization / deserialization. I want to avoid to avoid this issue when adding levels in the future. I also don't want to have to remember to only add levels to the end of the enum. **Is there a way to ensure that enum are deserialized consistently, even when retroactively adding new values?**
2016/07/03
[ "https://Stackoverflow.com/questions/38166003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20774/" ]
Add the `[DataContract]` attribute to the enum and serialize using the [`DataContractSerializer`](https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=vs.110).aspx). Place an `[EnumMember]` attribute on individual values. That will cause the value to be serialized by name, not by numeric value. To be sure I'd test serializing to a file (or a string if it's XML serialization) and see what it's storing to be sure that it works, and to be sure it's not already serializing by the name. Otherwise you won't know for sure if that's the cause.
823,646
How do I configure an xml file as the datasource in iBatis? thanks, R
2009/05/05
[ "https://Stackoverflow.com/questions/823646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you are using Tomcat you can configure the DataSource in config.xml and have the following definition in your iBatis configuration xml where comp/env/jdbc/db is your jndi definition in Tomcat. ``` <bean id="JndiDatasource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/db"/> <property name="resourceRef" value="true" /> </bean> ``` If its a standalone application: ``` <bean id="jdbc.DataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver"/> <property name="initialSize" value="${jdbc.initialSize}"/> <property name="maxActive" value="${jdbc.maxActive}"/> <property name="minIdle" value="${jdbc.minIdle}"/> <property name="password" value="${jdbc.dbpassword}"/> <property name="url" value="${jdbc.dburl}"/> <property name="username" value="${jdbc.dbuser}"/> <property name="accessToUnderlyingConnectionAllowed" value="true"/> </bean> ```
39,584,760
I want to print the list of redditors, who have not posted NOR commented in the last 12 months, for each month of 2010. I'm using the reddit comment/post corpus on BigQuery for this purpose. This is what I am running to get new users in January 2010: ``` SELECT author FROM [fh-bigquery:reddit_comments.2010] WHERE created_utc <= 1264982399 AND author NOT IN (SELECT author FROM [fh-bigquery:reddit_comments.2009]) AND author NOT IN (SELECT author FROM [fh-bigquery:reddit_posts.full_corpus_201512] WHERE created_utc <1420070400) ``` When I run this on BigQuery, I get a "Resources Exceeded" error. If I remove the select statement for [fh-bigquery:reddit\_posts.full\_corpus\_201512], the query runs fine. Therefore, presently, I can only get those users who did not comment in the last 12 months, but they may have posted during that time. I would just like a list of users whose "first" activity on reddit was to comment.
2016/09/20
[ "https://Stackoverflow.com/questions/39584760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6826872/" ]
Based on the example at <https://plot.ly/r/bar-charts/#bar-chart-with-relative-barmode> a separate add\_trace for each category is the way to go. ``` plot_ly(dt_net, x = ~campaign_week, y = ~amount, type = "scatter", mode= "lines+markers", line = list(color = "#00AEFF"), name = "Net Income") %>% add_trace(data = dt[category=="income",] , x = ~campaign_week, y = ~amount, type = "bar", name = "income", marker=list(color = "#00ff00")) %>% add_trace(data = dt[category=="cost",] , x = ~campaign_week, y = ~amount, type = "bar", name = "cost", marker=list(color = "#ff0000")) %>% layout(yaxis = y, barmode = "relative") ``` [![enter image description here](https://i.stack.imgur.com/N9vmY.png)](https://i.stack.imgur.com/N9vmY.png) Note, this gives a warning, because the bar chart traces inherit `mode` and `line` attributes from the scatter chart, but these attributes are not supported for bars. You can either ignore the warnings, or you can call the barchart before the scatter to avoid them... Like this: ``` plot_ly() %>% add_trace(data = dt[category=="income",] , x = ~campaign_week, y = ~amount, type = "bar", name = "income", marker=list(color = "#00ff00")) %>% add_trace(data = dt[category=="cost",] , x = ~campaign_week, y = ~amount, type = "bar", name = "cost", marker=list(color = "#ff0000")) %>% add_trace(data = dt_net, x = ~campaign_week, y = ~amount, type = "scatter", mode= "lines+markers", line = list(color = "#00AEFF"), name = "Net Income") %>% layout(yaxis = y, barmode = "relative") ```
6,037,136
I am trying to learn how to use the ConfigurationSection class. I used to use the IConfigurationSectionHandler but released that it has been depreciated. So being a good lad I am trying the "correct" way. My problem is that it is always returning null. I have a console app and a DLL. ``` class Program { static void Main(string[] args) { StandardConfigSectionHandler section = StandardConfigSectionHandler.GetConfiguration(); string value = section.Value; } } ``` app config: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="ConfigSectionGroup"> <section name="ConfigSection" type="Controller.StandardConfigSectionHandler, Controller" /> </sectionGroup> </configSections> <ConfigSectionGroup> <ConfigSection> <test value="1" /> </ConfigSection> </ConfigSectionGroup> </configuration> ``` section handler in DLL: ``` namespace Controller { public class StandardConfigSectionHandler : ConfigurationSection { private const string ConfigPath = "ConfigSectionGroup/ConfigSection/"; public static StandardConfigSectionHandler GetConfiguration() { object section = ConfigurationManager.GetSection(ConfigPath); return section as StandardWcfConfigSectionHandler; } [ConfigurationProperty("value")] public string Value { get { return (string)this["value"]; } set { this["value"] = value; } } } } ``` What ever values I try for the "ConfigPath" it will return null, or throw an error saying "test" is an unrecognised element. Values I tried: * ConfigSectionGroup * ConfigSectionGroup/ * ConfigSectionGroup/ConfigSection * ConfigSectionGroup/ConfigSection/ * ConfigSectionGroup/ConfigSection/test * ConfigSectionGroup/ConfigSection/test/
2011/05/17
[ "https://Stackoverflow.com/questions/6037136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6486/" ]
There's a couple of things wrong with your code. 1. You're always returning `null` in your `GetConfiguration` method but I'm going to assume that's just in the question and not in your actual code. 2. More importantly, the format of the `ConfigPath` value is incorrect. You have a trailing slash `ConfigSectionGroup/ConfigSection/`, remove the last slash and it'll be able to find the section. 3. Most important, the way you've declared your section the configuration system will expect your "value" be stored in an attribute of your `ConfigSection` element. Like this ``` <ConfigSectionGroup> <ConfigSection value="foo" /> </ConfigSectionGroup> ``` So, putting it all together: ``` public class StandardConfigSectionHandler : ConfigurationSection { private const string ConfigPath = "ConfigSectionGroup/ConfigSection"; public static StandardConfigSectionHandler GetConfiguration() { return (StandardConfigSectionHandler)ConfigurationManager.GetSection(ConfigPath); } [ConfigurationProperty("value")] public string Value { get { return (string)this["value"]; } set { this["value"] = value; } } } ``` To read more about how you configure configuration sections please consult this excellent MSDN documentation: [How to: Create Custom Configuration Sections Using ConfigurationSection](http://msdn.microsoft.com/en-us/library/2tw134k3.aspx). It also contains information about how to store configuration values in sub-elements of (like your test element).
48,331,028
I am trying to achieve the following result. [Expected Result Image](https://i.stack.imgur.com/h3NRa.png) And I am getting the following result. [Actual Result Image](https://i.stack.imgur.com/2Yzq9.png) can anyone guide me to achieve the expected results. I have shared my code below, ``` mLayoutManager = new GridLayoutManager(MyGridActivity.this,3); recyclerView.setLayoutManager(mLayoutManager); adapter = new MyGridAdapterAdapter(MyGridActivity.this,arrayList); recyclerView.setAdapter(adapter); ``` Sharing my item\_layout xml file for grid list. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto"> <android.support.v7.widget.CardView app:cardElevation="3dp" app:cardUseCompatPadding="true" app:cardCornerRadius="10dp" android:layout_margin="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/cardView"> <LinearLayout android:id="@+id/itemLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/iv_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="20dp" android:paddingLeft="10dp" android:paddingRight="10dp" android:scaleType="center" android:src="@mipmap/health_2" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/cardView" android:layout_marginBottom="20dp" android:gravity="center" android:text="Health" /> </LinearLayout> </android.support.v7.widget.CardView> ```
2018/01/18
[ "https://Stackoverflow.com/questions/48331028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7382744/" ]
Your `TextView` length is disturbing GridItems Either give your parent layout a fixed height or give your `TextView` a fixed height try this ... update your `TextView` from ``` <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/cardView" android:layout_marginBottom="20dp" android:gravity="center" android:text="Health" /> ``` to ``` <TextView android:lines="2" android:maxLines="2" android:ellipsize="end" android:id="@+id/tv_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/cardView" android:layout_marginBottom="20dp" android:gravity="center" android:text="Health" /> ``` Result [![Result](https://i.stack.imgur.com/WqV6s.png)](https://i.stack.imgur.com/WqV6s.png)
60,703,883
I-m trying to copy the value from one select to another. One has the value 'A' and the other has the value 'B'. Here's what I'm doing to achieve this: ``` $('#selectTipoInvervencion1').val($('#selectTipoIntervencion0').val()); ``` However, my value is not getting copied. The weird thing is, I'm getting the elements correctly since after executing this line of code I can do: ``` console.log($('#selectTipoIntervencion0').val()); console.log($('#selectTipoIntervencion1').val()); ``` and the output is: ``` A B ``` which is what I expected since the value doesn't appear to be copied in the view but is obviously not what I want. How can I fix this? Update: HTML ``` <select id="selectTipoIntervencion0" name="forms[0].model.intervenciones[0].tipo" class="selectTiposIntervencion"> <option name="A_NAME" value="A" selected="selected">A</option> <option name="B_NAME" value="B">B</option> ... </select> <select id="selectTipoIntervencion1" name="forms[1].model.intervenciones[1].tipo" class="selectTiposIntervencion"> <option name="A_NAME" value="A" selected="selected">A</option> <option name="B_NAME" value="B">B</option> ... </select> ```
2020/03/16
[ "https://Stackoverflow.com/questions/60703883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9289230/" ]
I am guessing you're trying to group identical pairs (e.g. `(a,b)` and `(b,a)`) together. You need to mark one of the rows as the "main" row using the condition `id1 < id2` and check if a match exists: ```sql SELECT * FROM t AS t1 WHERE id1 < id2 AND EXISTS ( SELECT 1 FROM t AS t2 WHERE t2.id1 = t1.id2 AND t2.id2 = t1.id1 ) ```
30,647,798
I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception ``` List<NameValuePair> pair = new ArrayList<>(); pair.add(new BasicNameValuePair("id", String.valueOf(getitemno))); json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair); Log.d("Route Response", json.toString()); int success = 0; try { success = json.getInt(TAG_SUCCESS); Routearrray = new ArrayList<String>(); } catch (JSONException e) { e.printStackTrace(); } try { if (success == 1) { JSONArray jsonarray; json = new JSONObject(JSONParser.Result); JSONArray jArray = json.getJSONArray("data"); for (int i = 0; i <= jArray.length(); i++) { jsonarray = jArray.getJSONArray(i); Stopnames = jsonarray.getString(0); Counter++; if (Counter <=jArray.length()) { //Routearrray.add(Stopnames); Log.d("Stop name:", Stopnames); //Log.d("Route name:", Routearrray.toString()); } else { break; } } ``` JSON URL ``` { "data":[ "Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal", "Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad", "Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU", "Zero Point","Children Hospital","F-8\/4","Ali Hospital" ], "success":1, "status":200, "status_message":"Login Successfull" } ``` Error: at Line ``` jsonarray = jArray.getJSONArray(i); ```
2015/06/04
[ "https://Stackoverflow.com/questions/30647798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4854336/" ]
From your JSON, `jArray` is a array of String and not an array of JSONArray. Replace: ``` jsonarray = jArray.getJSONArray(i); Stopnames = jsonarray.getString(0); ``` with: ``` Stopnames = jArray.getString(i); ```
12,463,046
Below I have a string called line that is coming from a file. The string has commas to separate it, where the first part goes to a string vector, and the second to a float vector. Anything after that is not used. The first part comes out as "text", which is correct. But the second one shows "248", while it's supposed to say "1.234" I need help converting this correctly. Any help would be greatly appreciated, thanks. I'm very new to programming. Sorry for any horrible style. ``` #include <iostream> #include <string> #include <vector> using namespace std; int main () { string line ("test,1.234,4.3245,5.231"); string comma (","); size_t found; size_t found2; string round1; float round2; vector<string> vector1; vector<float> vector2; // Finds locations of first 2 commas found = line.find(comma); if (found!=string::npos) found2 = line.find(comma,found+1); if (found2!=string::npos) //Puts data before first comma to round1 (string type) for (int a = 0; a < found; a++){ round1 = round1 += line[a]; } //Puts data after first comma and before second comma to round2 (float type) for (int b = found+1; b < found2; b++){ round2 = round2 += line[b]; } //Puts data to vectors vector1.push_back(round1); vector2.push_back(round2); cout << vector1[0] << endl << vector2[0] << endl; return 0; } ```
2012/09/17
[ "https://Stackoverflow.com/questions/12463046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1594138/" ]
Your problem is that you're adding chars to a float value, you can't convert it in this way. What you were actually doing is adding up the hex values of the characters that made up your number, if you look in an ASCII table you'll notice 1=49, .=46, 2=50, 3=51, 4=52. If you sum those 5 up you get 248. Also, even though it's wrong in this case: ``` round2 = round2 += line[b]; ``` should be: ``` round2 += line[b]; ``` The reason being that the += operator will is equivalent to: ``` round2 = round2 + line[b]; ``` so it makes no sense to add an extra `round2 =` in front of it. In order to do this properly use stringstreams like so: ``` #include <string> #include <sstream> int main() { float f; std::stringstream floatStream; floatStream << "123.4"; floatStream >> f; return 0; } ```
71,741,551
was trying to install yolox pip install -r requirements.txt and got this Using legacy 'setup.py install' for onnx-simplifier, since package 'wheel' is not installed. Building wheels for collected packages: onnx, pycocotools Building wheel for onnx (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for onnx (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [82 lines of output] C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\dist.py:757: UserWarning: Usage of dash-separated 'license-file' will not be supported in future versions. Please use the underscore name 'license\_file' instead warnings.warn( running bdist\_wheel running build running build\_py running create\_version running cmake\_build -- Building for: NMake Makefiles CMake Error at CMakeLists.txt:17 (project): Generator ``` NMake Makefiles does not support platform specification, but platform x64 was specified. CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage -- Configuring incomplete, errors occurred! See also "C:/Users/ASUS/AppData/Local/Temp/pip-install-9m548hbh/onnx_ad97fc2a0af84a5fa92a29cfbc51c296/.setuptools-cmake-build/CMakeFiles/CMakeOutput.log". Traceback (most recent call last): File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 363, in <module> main() File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 261, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 244, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 229, in _build_with_temp_dir self.run_setup() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 281, in run_setup super(_BuildMetaLegacyBackend, File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\build_meta.py", line 174, in run_setup exec(compile(code, __file__, 'exec'), locals()) File "setup.py", line 321, in <module> setuptools.setup( File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\__init__.py", line 87, in setup return distutils.core.setup(**attrs) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 148, in setup return run_commands(dist) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\core.py", line 163, in run_commands dist.run_commands() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 967, in run_commands self.run_command(cmd) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\dist.py", line 1214, in run_command super().run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command cmd_obj.run() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\wheel\bdist_wheel.py", line 299, in run self.run_command('build') File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\dist.py", line 1214, in run_command super().run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command cmd_obj.run() File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\dist.py", line 1214, in run_command super().run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command cmd_obj.run() File "setup.py", line 217, in run self.run_command('cmake_build') File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\dist.py", line 1214, in run_command super().run_command(command) File "C:\Users\ASUS\AppData\Local\Temp\pip-build-env-du9u4xrx\overlay\Lib\site-packages\setuptools\_distutils\dist.py", line 986, in run_command cmd_obj.run() File "setup.py", line 203, in run subprocess.check_call(cmake_args) File "c:\users\asus\appdata\local\programs\python\python39\lib\subprocess.py", line 373, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['C:\\Users\\ASUS\\anaconda3\\envs\\myenv\\Library\\bin\\cmake.exe', '-DPYTHON_INCLUDE_DIR=c:\\users\\asus\\appdata\\local\\programs\\python\\python39\\include', '-DPYTHON_EXECUTABLE=c:\\users\\asus\\appdata\\local\\programs\\python\\python39\\python.exe', '-DBUILD_ONNX_PYTHON=ON', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-DONNX_NAMESPACE=onnx', '-DPY_EXT_SUFFIX=.cp39-win_amd64.pyd', '-DCMAKE_BUILD_TYPE=Release', '-DPY_VERSION=3.9', '-DONNX_USE_MSVC_STATIC_RUNTIME=ON', '-A', 'x64', '-T', 'host=x64', '-DONNX_ML=1', 'C:\\Users\\ASUS\\AppData\\Local\\Temp\\pip-install-9m548hbh\\onnx_ad97fc2a0af84a5fa92a29cfbc51c296']' returned non-zero exit status 1. [end of output] ``` note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for onnx Building wheel for pycocotools (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for pycocotools (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [14 lines of output] running bdist\_wheel running build running build\_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\pycocotools copying pycocotools\coco.py -> build\lib.win-amd64-3.9\pycocotools copying pycocotools\cocoeval.py -> build\lib.win-amd64-3.9\pycocotools copying pycocotools\mask.py -> build\lib.win-amd64-3.9\pycocotools copying pycocotools\_*init*\_.py -> build\lib.win-amd64-3.9\pycocotools running build\_ext skipping 'pycocotools\_mask.c' Cython extension (up-to-date) building 'pycocotools.\_mask' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": <https://visualstudio.microsoft.com/visual-cpp-build-tools/> [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for pycocotools Failed to build onnx pycocotools ERROR: Could not build wheels for onnx, pycocotools, which is required to install pyproject.toml-based projects (myenv) C:\Users\ASUS\Desktop\YOLOX-main>
2022/04/04
[ "https://Stackoverflow.com/questions/71741551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18624479/" ]
I suggest moving the switch bloc inside a function, like the following: ```js var select = 1; function add(val) { return val + 512 }; function subtract(val) { return val - 300 }; function multiply(val) { return val * 584 }; var value = 290; var string = `this string in ${chooseFunction(select, value)}` console.log(string) function chooseFunction (select, value) { // switch statement // Note that the break statement is optional // if you return a value at the end of a case block switch (select) { case 1: return add(value); case 2: return subtract(value); case 3: return multiply(value); } } ```
46,906,112
I have implemented a function in ANTLR4. Eg. - FUNCTION("A","B") Grammar : ``` parse : block EOF ; block : 'FUNCTION' LPAREN (atom)? COMMA (atom)? RPAREN ; atom : NIL #nilAtom | list #arrayAtom | type=(INT | DOUBLE) #numberAtom | ID #idAtom ; list : BEGL array? ENDL ; array : array_element ( COMMA array_element )* # arrayValues ; array_element : atom # array_element_types ; COMMA : ','; BEGL : '['; LPAREN : '('; RPAREN : ')'; ENDL : ']'; NIL : '' | 'null'; INT : [0-9]+ ; DOUBLE : [0-9]+ '.' [0-9]* | '.' [0-9]+ ; COMMENT : '#' ~[\r\n]* -> skip ; SPACE : [ \t\r\n] -> skip ; OTHER : . ; ``` For input FUNCTION(,"B"), Not able to differentiate between first and second parameter. Getting "B" as first parameter. Thanks for help.
2017/10/24
[ "https://Stackoverflow.com/questions/46906112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5345901/" ]
You should work with the `field` instead: ``` class Address { var address1: String? = null get() = field ?: "" } ``` The problem is, that using `address1` inside its own setter leads to a recursive call sequence. Instead, the `field` qualifier refers to the [backing](https://kotlinlang.org/docs/reference/properties.html#backing-fields) field. The recursive sequence leads to the `StackOverflowError` you encountered. But actually, you should also think about the sense of your property: It's declared as a nullable `String`, but you don't allow `null` since you map it to an empty `String`. Is `""` really accepted for the address? It would be much better to simply do `val address1: String = ""`.
66,080,047
I am using Django framework for project. I am rendering the HTML templet ``` def index(request): print(" --- check fine?") # for print debug trees = Tree.objects.all() print(trees) return render(request, "index.html", {'trees': trees}) ``` ``` --- check fine? <QuerySet [<Tree: Tree object (8)>, <Tree: Tree object (10)>, <Tree: Tree object (11)>, <Tree: Tree object (12)>]> [06/Feb/2021 17:28:44] "GET / HTTP/1.1" 500 145 ``` these are my urls. ``` urlpatterns = [ path("", views.index, name="index"), path('about/', views.about , name='about'), path('contact/', views.contact , name='contact'), path('upload/', views.upload_file , name='upload'), ] ``` `DEBUG = False` I am getting above error. when I set my `DEBUG = True` every thing works fine means show index.html and shows even data too. setting `DEBUG = False` make difficult to find an error. index.html contains below code which fetches data. ``` {% for tree in trees %} <article class="col-lg-3 col-md-4 col-sm-6 col-12 tm-gallery-item"> <figure> <img src="{{tree.image.url}}" alt="Image" class="img-fluid tm-gallery-img" /> <figcaption> <h4 class="tm-gallery-title">{{tree.name}}</h4> <p class="tm-gallery-description">{{tree.desc}}</p> <!-- <p class="tm-gallery-price"></p> --> </figcaption> </figure> </article> {% endfor %} ``` and allowed hosts are. ``` ALLOWED_HOSTS = ['*','127.0.0.1','localhost'] ```
2021/02/06
[ "https://Stackoverflow.com/questions/66080047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12857175/" ]
What i'm seeing is that you may be thinking too much into it. A simple `if` statement should do the trick, try: ``` $creden=Get-Credential -Message "Please enter the server credentials that you want to connect" if(!$creden){break} ```
14,794,158
Having an issue with a small 53x49 image icon being stretched to a giant size. This: <http://imageshack.us/photo/my-images/837/arrowsj.png/> Is supposed to be this size: <http://imageshack.us/photo/my-images/32/resetw.png/> Does anyone know what would cause this to happen? Or what to look for to take out to prevent it? Or what to type in to fix it? Have Tried: Using background image, using a div. Thanks! Image code: ``` <a href='getestimate.php'><img id='fixed' src='css/images/reset.png' alt='Reset' title='Reset'></a> ``` CSS CODE: ``` * { padding:0; margin:0; outline:0; } body { background:#fff; font-family: Arial, sans-serif; font-size:12px; line-height:18px; color:#6d6d6d; } input, textarea, select { font-family: Arial, sans-serif; font-size:12px;color:#6d6d6d; } a img { border:0; display: block;} a { color:#0184c4; text-decoration: underline; cursor:pointer; } a:hover { color:#1c6183; text-decoration: none; } #fixed {width:53px; height:49px;} .notext { font-size:0; line-height:0; text-indent: -4000px; display:block; } .left, .alignleft { float:left; display:inline; } .right, .alignright { float:right; display:inline; } .cl { font-size:0; line-height:0; clear:both; display:block; height:0; } .al { text-align: left; } .ar { text-align: right; } .ac { text-align: center; } h2 { font-size:23px; line-height:26px; color:#0188c9; } h3 { font-size:16px; line-height:20px; color:#000; } h2, h3 { font-family: "Trebuchet MS", Arial, sans-serif;} h1#logo { font-size:0; line-height:0; width:245px; height:74px; float:left; } h1#logo a{ display:block; height:74px; text-indent: -4000px; background:url(images/logo.gif); } .shell { width:980px; margin:0 auto; } #header { height:74px; background:url(images/header.gif);} #navigation { float:right; height:30px;} #navigation ul{ float:left; height:30px; list-style-type:none; padding-top:27px;} #navigation ul li{ float:left; display:inline; margin-left:10px;} #navigation ul li a{ float:left; width:110px; height:30px; text-align: center; background:url(images/nav.gif) no-repeat 0 0; line-height:30px; text-decoration: none; color:#7b7b7b; } #navigation ul li a:hover, #navigation ul li a.active { background-position:right 0; color:#fff;} #slider { height:390px; background:url(images/slider.gif);} .slider-holder { height:390px; position:relative; overflow:hidden; z-index:100} .slides { width:894px; height:315px; position:relative; overflow:hidden; top:59px; left:43px;} .slides .jcarousel-clip{ width:894px; height:315px; position:relative; overflow:hidden; } .slides ul{ width:758px; height:315px; position:relative; overflow:hidden; list-style-type: none;} .slides ul li{ float:left; display:inline; width:758px; height:315px; position:relative; overflow:hidden; margin:0 0 0 136px; left:-68px;} .slide-shadow { position:absolute; bottom:0; height:26px; width:771px; background:url(images/slide-shadow.png); left:-6px;} .slide-bg { width:758px; height:267px; position:relative; overflow:hidden; background:url(images/slide-bg.gif); padding:5px; } .slide-image{ float:left; width:271px; } .slide-info{ float:left; width:440px; padding:30px 0 0 15px; } .slide-info p{ padding:13px 0 20px;} .slider-nav { font-size:0; line-height:0; } .slider-nav a{ width:43px; height:46px; text-indent: -4000px; position:absolute; top:165px; } .slider-nav a.prev{ left:0; background:url(images/prev.gif); } .slider-nav a.next{ left:937px; background:url(images/next.gif); } .learn-button { width:165px; height:37px; background:url(images/learn-button.gif); } #main { width:100%; background:url(images/main.gif) repeat-x 0 0; padding:45px 0 40px 0;} .col { float:left; display:inline; width:280px; margin-right:70px; padding:10px 0;} .col-last { margin-right:0;} .col h3 { padding-bottom:12px; } .col p { padding-bottom:12px; } .three-cols { background:url(images/three-cols.gif) repeat-y center 0; width:100%;} .ico { background-repeat:no-repeat; background-position:0 1px; padding-left:26px; } .ico1 { background-image:url(images/ico1.gif)} .ico2 { background-image:url(images/ico2.gif)} .ico3 { background-image:url(images/ico3.gif)} p.more { font-size:11px; } p.more a{ background:url(images/more.gif) no-repeat 0 center; padding-left:11px;} #footer { height:57px; background:url(images/footer.gif); line-height:56px; white-space:nowrap; color:#5c5c5c;} #footer span{ color:#cfcfcf; padding:0 5px;} #footer a{ color:#5c5c5c; text-decoration: none;} #footer a:hover{ color:#0184c4;} ```
2013/02/10
[ "https://Stackoverflow.com/questions/14794158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2058050/" ]
<http://jsfiddle.net/persianturtle/JhNmp/> - Fixed Use this CSS ID ```css #fixed { width:53px; height:49px; } ``` And include the ID in the html like this: ``` <img id="fixed" etc etc etc> ``` Try this to add specificity: ``` <div id="derp"> <img id="fixed" etc etc etc> </div> ``` and the CSS: ```css #derp #fixed { width:53px; height:49px; } ```
34,298,407
I've coded a wrapper for CryptoPP which would be used by c# app. My issue is that when calling to a specific function in my wrapper using PInvoke, throws an exception "Attempted to read or write protected memory...". Both of them are compiled as x64. Now.. strange part is that **if i compile my wrapper using /MTd or /MDd runtime, the call does not fail and everything works perfectly.** But changing the runtime to /MT or /MD would throw the above exception. I cannot use the /MTd or /MDd option for official use by my customers, as it requires lots of dlls resources to be installed or distributed into the user machine. cpp code: ``` extern "C" __declspec(dllexport) int CryptBlock(bool mode, unsigned char type, unsigned char *inData, unsigned char *outData, int dataLen, unsigned char *key, int keyLen); ``` c# PInvoke: ``` [DllImport("mydll.dll", SetLastError = true, CallingConvention = CallingConvention.Cdecl)] public static extern int CryptBlock(bool mode, byte type, IntPtr inData, IntPtr outData, int dataLen, IntPtr key, int keyLen); ``` I have tried modifying my P/Invoke code in various ways: [In, Out], [Out], ref, ref byte[], byte[] etc... still throwing the exception. Waiting for my savior... Thank you.
2015/12/15
[ "https://Stackoverflow.com/questions/34298407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343866/" ]
You are right that you cannot distribute the debug runtime, but in fact the issue is not quite what you think. The license does not permit redistribution of the debug runtime. The most likely explanation is in fact that your code has a defect. The fact the the defect does not manifest with the debug runtime is simply down to chance. So the correct way to proceed is to track down your defect and fix it.
4,827,871
Are there any and if yes, which ones?
2011/01/28
[ "https://Stackoverflow.com/questions/4827871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473612/" ]
What do you mean by "paradigm shift"? C++0x introduces many new features that will of course change the way you write programs. There are little things that will probably have a big impact on the syntax used, but which won't change the semantics that much. Examples are lambda functions and range-based for-loop: they'll provide a better syntax for what we all are already doing. Then there are big things that will change the way things work. In particular: * Rvalue reference could make you think in a different way about how objects work and how to use them: it'll probably be easier to pass (and return) objects by value. * Explicit conversion operators will let us define conversion operators, while doing this in C++03 was risky.
23,208,838
I have a python function which generates a sympy.Matrix with symbolic entries. It works effectively like: ``` import sympy as sp M = sp.Matrix([[1,0,2],[0,1,2],[1,2,0]]) def make_symbolic_matrix(M): M_sym = sp.zeros(3) syms = ['a0:3'] for i in xrange(3): for j in xrange(3): if M[i,j] == 1: M_sym = syms[i] elif M[i,j] == 2: M_sym = 1 - syms[i] return M_sym ``` This works just fine. I get a matrix out, which I can use for all the symbolical calculations I need. My issue is that now I want to evaluate my matrix at specified parameter-value. Usually I would just use the .subs attribute. However, since the symbols, that are now used as entries in my matrix, were originally defined as temporary elements in a function, I don't know how to call them. It seems as if it should be possible, since I'm able to perform symbolic calculations. What I want to do would look something like (following the code above): ``` M_sym = make_matrix(M) M_eval = M_sym.subs([(a0,.8),(a1,.3),(a2,.5)]) ``` But all I get is "name 'a0' is not defined". I'd be super happy if someone out there got a solution! PS. I'm not just defining the symbols globally, because in the actual problem I don't know how many parameters I have from time to time.
2014/04/22
[ "https://Stackoverflow.com/questions/23208838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3558495/" ]
In the general case, I assume you're looking for an n-by-m matrix of symbolic elements. ``` import sympy def make_symbolic(n, m): rows = [] for i in xrange(n): col = [] for j in xrange(m): col.append(sympy.Symbol('a%d%d' % (i,j))) rows.append(col) return sympy.Matrix(rows) ``` which could be used in the following way: ``` make_symbolic(3, 4) ``` to give: ``` Matrix([ [a00, a01, a02, a03], [a10, a11, a12, a13], [a20, a21, a22, a23]]) ``` once you've got that matrix you can substitute in any values required.
6,494,077
I have now tried to get our webservice to run with debug from within Visual Studio 2008 a long time with no success. This project worked great before and works fine on other computers, I suppose that there is something wrong with the IIS7 settings. The main project in the solution is a WFC service that is used as a simple webservice (svc). All projects in this solution are set to use .NET framework 3.5. When running the service with the built in IIS(VS) it seems to work just fine but as soon as the IIS7 is used a dialog appears and states: > > Unable to start debugging on the web > server. Check for one of the following > > > The following is done in IIS7 : 1. Application created that points to the webservice 2. DefaultAppPool (.NET framework 4 Integrated)(ApplicationPoolIdentity) is used 3. Browsing the service works fine (It shows the WSDL) 4. When changing the DefaultAppPool to .NET framework 2.0 it states somthing about static file problems but I can´t see anything missing from the Webservice > Handler Mappings? 5. Enable 32-bit Application is set to true on the DefaultAppPool. 6. I have runned `aspnet_regiis` from all the .net version in order 7. Set `debug="true"` in the `web.config` 8. I was not at first able to get the webservice starting at all to solve this I hade to comment out a couple of rows in the web.config : ``` <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <!--<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />--> <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <!--<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />--> <!--<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />--> <!--<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />--> <!--<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />--> </sectionGroup> </sectionGroup> </sectionGroup> </configSections> ``` (scriptResourceHandler, jsonSerialization, profileService, authenticationService, roleService) How to get this running with debug?
2011/06/27
[ "https://Stackoverflow.com/questions/6494077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/365624/" ]
If you're running under IIS, you don't "start" but attach to the running process. In the ApplicationPool settings, disable pinging, or IIS will recycle the pool during your debug session.
63,118
I am trying to get the user orders history, used the following query and its working fine. But its returning all the order related fields from table ``` $collection = Mage::getModel("sales/order")->getCollection() ->addAttributeToSelect('*') ->addFieldToFilter('customer_id', 400) ->setOrder('created_at', 'desc'); ``` I want to fetch only particular fields, so in case of **->addAttributeToSelect('\*')** ``` used the following code ->addAttributeToSelect(array('created_at','customer_id','increment_id','updated_at','status','entity_id','state')) ``` But getting error as **"Cannot determine the field name."**
2015/04/09
[ "https://magento.stackexchange.com/questions/63118", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/24169/" ]
Use `addFieldToSelect` incase of addAttributeToSelect **addFieldToSelect** used for flat model **addAttributeToSelect** user for EAV model
15,994,051
i got a piece of html ``` <img style="cursor: pointer; width: auto; height: auto; display: inline;" src="http://www.kidsgen.com/fables_and_fairytales/images/rapunzel.gif" alt="rapunzel" title="rapunzel" align="right"> ``` and even if i set `display: inline;` in its style, when i'm trying to get its css display property like this: ``` alert($('img:first').css('display')) ``` or ``` var el=document.getElementsByTagName('img')[0] alert(document.defaultView.getComputedStyle(el,null)['display']) ``` it always gives me value `block`. what's wrong?
2013/04/13
[ "https://Stackoverflow.com/questions/15994051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2100770/" ]
The `align='right'` property assignment is causing the img element to have its display property set to 'block'. Your code without the `align='right'` propery will alert 'inline' [on jsFiddle.](http://jsfiddle.net/rsGQ9/1/) ``` <body> <img style="cursor: pointer; width: auto; height: auto; display: inline;" src="http://www.kidsgen.com/fables_and_fairytales/images/rapunzel.gif" alt="rapunzel" title="rapunzel" /> </body> alert($('img:first').css('display')); // alerts 'inline' ``` A relevant piece of extra information is img tags are in fact [inline elements by default.](http://www.w3schools.com/html/html_blocks.asp) However, with `align='right'` set inside the img tag, I was unable to set the display property back to inline even by inserting this line of code: ``` $('img:first').css('display', 'inline'); ```
12,682,549
I have the following DIV structure: ----------------------------------- ``` <style> #header{border-bottom:1px solid blue;} #footer{botter-top:1px solid blue;} #header,#footer{height:15%;} #content{height:70%;} #header,#footer,#content{width:100%;} </style> <div id="header"></div> <div id="content"></div> <div id="footer"></div> ``` *What I'm noticing is that in desktop browsers, there is an expected overflow with a 2px+ offset from 100%* **However, in mobile browsers, there does not seem to be any overflow / scrolling.** * Do mobile devices count borders as part of the 100% height/width calculations? If so: ------ * Is there a way to invoke this behavoir through CSS for desktop browsers? * Is there a way to reverse this behavoir through CSS for mobile browsers?
2012/10/01
[ "https://Stackoverflow.com/questions/12682549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113921/" ]
There's the order of fields within the struct, and then there's the order of bytes within a multibyte field. `0x003C` isn't endian at all, it's the hex value for 60. Sure, it's stored in memory with some endianness, but the order you used to write the field and the order you used to read it back out are the same -- both are the native byte order of the Raspberry Pi, and they cancel out. Typically you will want to write: ``` ip->tot_len = htons(60); ``` when storing a 16-bit field into a packet. There's also `htonl` for 32-bit fields, and `ntohs` and `ntohl` for reading fields from network packets.
9,343,105
I want to calculate a point on a line by the distance to the first point. Because I dont have any coordinates of the new point, i can't use the linear interpolation... I thought like this: [**Example Drawing**](http://dl.dropbox.com/u/14970834/mein%20proggen/InterpolationByDistance2.png) (Sorry, I'm a new user and I am not allowed to post images) But actually it doesnt work, so I ask you for help. Here is the actual code in java: ``` public static PointDouble interpolationByDistance(Line l, double d) { double x1 = l.p1.x, x2 = l.p2.x; double y1 = l.p1.y, y2 = l.p2.y; double ratioP = ratioLine_x_To_y(l); double disP = l.p1.distance(l.p2); double ratioDis = d / disP; PointDouble pn = l.p2.getLocation(); pn.multi(ratioDis); System.out.println("dis: " + d); System.out.println("new point dis: " + l.p1.distance(pn)); return pn; } ``` Thank you.
2012/02/18
[ "https://Stackoverflow.com/questions/9343105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218254/" ]
As a programmer you should love changing a problem to a one you have already solved. Find the ratio and then use the linear interpolation: ``` public static PointDouble interpolationByDistance(Line l, double d) { double len = l.p1.distance(l.p2); double ratio = d/len; double x = ratio*l.p2.x + (1.0 - ratio)*l.p1.x; double y = ratio*l.p2.y + (1.0 - ratio)*l.p1.y; System.out.println(x + ", " + y); ... } ```
55,725,507
I'm trying to simply setup an Open Source Greenplum instance and have been hitting the same issue regarding GPFDIST for days! Simply put, I do a full installation from scratch on CentOS 7.6 (can provide further details regarding setup if needed) installing OS GPDB software version 5.18 with GPORCA disabled. Full command for the compile is: ``` ./configure --prefix=/usr/local/gpdb --with-perl --with-python --with-libxml --with-gssapi --with-includes=/usr/local/gpdb/include --with-libs=/usr/local/gpdb/lib --disable-orca ``` This compiles successfully, and the following `make`/`make install` commands too complete without issue. The initialisation of the Greenplum database itself also succeeds, and I can then go into a database and create tables, insert data and run queries like normal. But if I try to select from an external table, such as the following: ``` create external table test_external_table (testing smallint ) location ('gpfdist://mdw:8080/test_data.csv') format 'csv' (header delimiter '|') ; ``` with GPFDIST run as follows: ``` gpfdist -d /home/gpadmin/test/ -p 8080 -l /home/gpadmin/greenplum/logs/gpfdist_log 2>&1 & ``` then I get two errors; one from the external table, and one from GPFDIST. These are as follows: ``` External Table Returns: ERROR: connection with gpfdist failed for gpfdist://mdw:8080/test_data.csv. effective url: http://127.0.0.1:8080/test_data.csv. error code = 104 (Connection reset by peer) (seg0 slice1 127.0.0.1:6000 pid=27962) GPFDIST Returns: [1]+ Segmentation fault gpfdist -d /home/gpadmin/test -p 8080 -l /home/gpadmin/greenplum/logs/gpfdist_log 2>&1 ``` I have removed everything that isn't on the OS GPDB GitHub installation guide (for a 'bare-bones' setup), so I don't think that is causing the issue. I have tried everything to do with the hostname and network firewall, and it's all perfect as far as I can see. I have also downloaded the same version of GPDB (5.18) from Pivotal and installed that version on the same instance simultaneously, and GPFDIST works perfectly fine. I have also tried OS GPDB 5.17, 6 beta and 7 beta, and I get the same issue for all of them. Any ideas at all on what might be causing this is VERY much appreciated, as I'm slowly going insane trying to figure this out now. Thank you very much in advance for any help. -- Edit -- Okay.. Having nearly chewed my own arm off in sheer frustration at trying to install debuginfo stuff on CentOS 7, I've finally generated a core dump with gdb. I then run: ``` gdb -c core_dump.<pid> ``` and get the following output: ``` Core was generated by `gpfdist -d /home/gpadmin/test -p 8080 -l /home/gpadmin/greenplum/logs/gpfdist_log'. Program terminated with signal 11, Segmentation fault. #0 0x00007f4f2c07bdff in ?? () ``` But I have absolutely no idea what that means... Totally honest, I'm a little over my head with this now and really am stuck on how to proceed.
2019/04/17
[ "https://Stackoverflow.com/questions/55725507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11373141/" ]
The connection reset by peer only indicates that the other end of the socket had dropped (...in this case, gpfdist because it crashed out). Setup your gpfdist and try a wget to a hosted file adding: ``` --header='X-GP-PROTO:0' ``` You will need to add the header to avoid having the request rejected. Are you able to retrieve a file there? Or does that also crash out? If that crashes out, it's nothing to do with the database - and you will likely need a core dump to determine what the segfault is about (r/w permissions, memory, ...).
53,968,365
This must have an answer already but I can't find it. My `div`, which I want hidden on page load shows up for a fraction of a second until I explicitly hide it in the document.ready function. ``` $(document).ready(() => $("#myDiv").hide()); ``` Short of not having it and re-creating it (`$.append` / `$.add` ) or making it the same background color as its background to hide it, how do I ensure that it remains hidden on page load?
2018/12/29
[ "https://Stackoverflow.com/questions/53968365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303685/" ]
Some observations for your PDF (the afore mentioned encoding problems are none - just plain ignorance on my behalf): 1. The SansDroid font is not embedded into the PDF. This is fixed by replacing the `F2` font with the newly embedded `F5` font. 2. The `NeedAppearances` flag is set meaning that there is no appearance for the form fields. Any reader must (re)create those. This is not done automatically by PDFBox before flattening so I added this part 3. To not cause any more warnings about missing fonts I removed the F2 font completely. 4. I run the original PDF through preflight and it gave me the following warning: "*The required key /Subtype is missing. Path: ->Pages->Kids->[0]->Annots->[0]->AP->N* " The key does exists however it seems to inicate that there is an error with the appearance of the form field. If I remove the /N dict the error is gone. The stream is "/Tx BMC EMC" - maybe there is some EOL missing? But since the appearance is regenerated anyway the error is gone afterwards. With the following code the DroidSans font is embedded into the PDF: ``` File pdf = new File("Fonts.pdf"); final PDDocument document = PDDocument.load(pdf); FileInputStream fontFile = new FileInputStream(new File("DroidSans.ttf")); PDFont font = PDType0Font.load(document, fontFile, false); //1. embedd and register the font (Catalog dict) PDAcroForm pDAcroForm = document.getDocumentCatalog().getAcroForm(); //create a new font resource PDResources res = pDAcroForm.getDefaultResources(); if (res == null) res = new PDResources(); COSName fontName = res.add(font); pDAcroForm.setDefaultResources(res); //2. Now change the font of form field to the newly added font PDField field = pDAcroForm.getField("text"); //field.setValue("Same font in form text field (updated with PDFBox)"); COSDictionary dict = field.getCOSObject(); COSString defaultAppearance = (COSString) dict.getDictionaryObject(COSName.DA); if (defaultAppearance != null){ String currentValue = dict.getString(COSName.DA); //replace the font - this should be improved with a more general version dict.setString(COSName.DA,currentValue.replace("F2", fontName.getName())); //remove F2 completely COSDictionary resources = res.getCOSObject(); for(Entry<COSName, COSBase> resource : resources.entrySet()) { if(resource.getKey().equals(COSName.FONT)) { COSObject fonts = (COSObject)resource.getValue(); COSDictionary fontDict = (COSDictionary)fonts.getObject(); COSName toBeRemoved=null; for(Entry<COSName, COSBase> item : fontDict.entrySet()) { if(item.getKey().getName().equals("F2")) { toBeRemoved = item.getKey(); } } if(toBeRemoved!=null) { fontDict.removeItem(toBeRemoved); } } } if(pDAcroForm.getNeedAppearances()) { pDAcroForm.refreshAppearances(); pDAcroForm.setNeedAppearances(false); } //Flatten the document pDAcroForm.flatten(); //Save the document document.save("Form-Test-Result.pdf"); document.close(); ``` **Please note that the above code is quite static - Searching and replacing a font called `F2` only works for the supplied PDF in other cases it won't. You have to implement a more generic solution for that...**
33,692,295
I am trying to create a method that will add a new LinearLayout to an existing LinearLayout. I would like to send a parameter to this method telling it whether the new LinearLayout should be VERTICAL or HORIZONTAL. This is what I have so far but 'LinearLayout.Orientation' is not the correct name for this parameter type. ``` private LinearLayout addLinearLayout(View linearLayout, LinearLayout.Orientation orientation) { //Create new horizontal linear layout and add to the specified linear layout LinearLayout newLinearLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); layoutParams.setMargins(20, 10, 0, 10); newLinearLayout.setOrientation(LinearLayout.orientation); ((LinearLayout) linearLayout).addView(newLinearLayout, layoutParams); return newLinearLayout; } ``` Is this possible? If so, what is the type of the parameter I am trying to pass? Thanks for any help.
2015/11/13
[ "https://Stackoverflow.com/questions/33692295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3410340/" ]
Working fiddle: <https://jsfiddle.net/bm576q6j/17/> ``` var elms = document.getElementsByClassName("test"); var n = elms.length; function changeColor(color) { for(var i = 0; i < n; i ++) { elms[i].style.backgroundColor = color; } } for(var i = 0; i < n; i ++) { elms[i].onmouseover = function() { changeColor("gray"); }; } ``` Edit: Sorry for not noticing last part of your question before I answered :)
59,101,193
**SOLVED** --- I know this "error" message is common and there are already posts around this. But did not find a way to fix my issue. I am using the already existing "User", "Group", "UserManager" provided by Django. However, I have a custom authentication backend: ``` class MyAuthentication: # ... # ... def has_perm(self, user_obj, perm, obj=None): permissions = Permission.objects.filter(user=user_obj) if perm in permissions: return True return False ``` My user is an admin NOT a super user. He is part of a group which has all the permissions to view, edit, delete, add my models. **He is able to access them** by using the URL directly. However, when he tries to connect to the admin page `/admin/`, he is getting this error message. `You don't have permission to view or edit anything` I searched for a permission which will give him access to view the lists of models in django documentation, but found nothing. Do I need to add anything to my backend authentication? Add a new perm ? Even advice on where to look at in order to investigate would be very appreciated! EDIT1 ----- After debugging the django code itself, I need to add this method: `def has_module_perms(self, user_obj, perm, obj=None):` So stupid error ...
2019/11/29
[ "https://Stackoverflow.com/questions/59101193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5077188/" ]
I needed to change my has\_perm, because permissions is a QuerySet of Permission... In case anyone needs it, here is my working has\_perm method and fixed code to check both groups perms and user's perms. ``` def has_perm(self, user_obj, perm, obj=None): permissions = Permission.objects.filter(user=user_obj).values() has_specific_perm = False # Check groups permissions the user is member of for group in user_obj.groups.all(): has_specific_perm = self.check_has_permission(perm, group.permissions.all().values()) # Check user's permissions if group was not enough if not has_specific_perm: has_specific_perm = self.check_has_permission(perm, permissions.values()) if user_obj.is_active and user_obj.is_staff and has_specific_perm: return True return False def has_module_perms(self, user_obj, perm, obj=None): return True def check_has_permission(self, perm, permissions_to_check): for index in range(len(permissions_to_check)): if perm == permissions_to_check[index]['codename']: return True ```
36,427,139
recently, I've been looking into how to create an Adobe extension. In CC versions, you can build HTML5 extensions which includes knowledge of HTML/CSS/JS only. This sounds really interesting but, the only thing I am not sure how they work and there are not much resources out there. I read [Extensibility Overview](http://www.adobe.com/devnet/creativesuite/articles/extensibility-overview.html). It didn't help much. Basically, what I am trying to do is look at how an extension can communicate with an Adobe product and what are the limitations? A nice example would be Flexi Layouts 3. How does it do what it does? Is it really a Dreamweaver extension?
2016/04/05
[ "https://Stackoverflow.com/questions/36427139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1887854/" ]
Okay. I fixed my problem by adding that scrollable panel to another panel and setting dock property to fill over that panel. Everything works fine!
22,334,171
Let's say I have a domain object, Here is the pseudocode ``` public class SampleClass { id title ... a lot of other fields from database public boolean equals(AnotherObj) { return this.id.equals(AnotherObj.id); } } ``` The equals method is based on the id, which works for most scenarios. But in one scenario, the two objects shall be considered equal if the titles are the same. **The objects are put in list and list.contains(obj) and list.indexOf(obj) is heavily invoked for business logic, which depends on the equals method.** How to override the equals method at runtime? The sampleClass object could contain complicated tree childrens and I don't want to copy it in the memory. I want to create a wrapper for the existing object. The wrapper only contains the specific equals method, all other method call should still be passed to the existing object. I looked into cglib but it has to generate the target object by itself, it cannot wrap an existing object. Any easy way?
2014/03/11
[ "https://Stackoverflow.com/questions/22334171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/770493/" ]
You need to prevent the parent from handling the config as follows: ``` @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(null); //TODO: Do nothing when orientation has changed... } ``` As you can see all you need to do is pass null to the super method of onConfigurationChanged, so it will actually prevent from going through all the changes you want to avoid. Regards!
24,677,004
I have a js fiddle where i want a padding between two divs, i have placed a css padding rule on the div that requires padding but it is not being applied: <http://jsfiddle.net/Cnr2V/> css: ``` .gap { display: inline-block; width: 15%; height: 300px; float: left; background-image: url("/images/forward_enabled_hover.png"); background-repeat: no-repeat; background-position: center center; } .feature-addons { background-color: #303030; width: 100%; color: #ffffff; font-size: 15px; padding-top: 5px; padding-bottom: 5px; } .feature-container { display: inline-block; width: 40%; float: left; overflow: hidden; } .feature-item { padding: 5px; height: 50px; display: block; } .feature-options { background-color: #f5f5f5; display: block; width: 100%; height: auto; background-image: url("/images/plus.png"); background-repeat: no-repeat; background-position: center right; } .radio-button { display: none; } ``` html: ``` <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_UpdatePanel_Features"> <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Panel_FeatureOptions"> <div class="call-features-table"> <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Panel_SelectFeatures" class="feature-container"> <div class="feature-addons">Feature add-ons</div> <label for="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_RadioButton_Item" id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Label_FeatureItem"> <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Panel_FeatureItem" class="feature-item"> <div class="feature-options"> <h4>Title</h4> <p>lorum ipsum</p> <p>lorum ipsum</p> <span class="radio-button"><input id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_RadioButton_Item" type="radio" name="ctl00$ContentPlaceHolder_Content_Wraper$ctl01$RadioButton_Item" value="RadioButton_Item" /></span> </div> </div> </label> <label for="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_RadioButton_Item" id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Label1"> <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Panel1" class="feature-item"> <div class="feature-options"> <h4>Title</h4> <p>lorum ipsum</p> <span class="radio-button"><input id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_RadioButton1" type="radio" name="ctl00$ContentPlaceHolder_Content_Wraper$ctl01$RadioButton1" value="RadioButton1" /></span> </div> </div> </label> </div> <div class="gap"></div> <div id="ctl00_ContentPlaceHolder_Content_Wraper_ctl01_Panel_SelectedFeatures" class="feature-container"></div> </div> </div> ``` How can i create the padding required between two **feature-item** divs?
2014/07/10
[ "https://Stackoverflow.com/questions/24677004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3793198/" ]
Remove height from feature-item div. ``` .feature-item { padding: 5px; display: block; } ```