qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
84,410
In the second theme of the recapitulation of Beethoven's Pathetique Sonata where the bass line goes into the treble clef and the bass register becomes part of the melody, I see the marking ***ben tenuto il basso***. I tried looking it up last night and couldn't find an answer. Google translate said that this means "well held down", but that wouldn't be the musical definition, I know it wouldn't. From finding out that ben in Italian means well and my knowledge of Italian musical terms, here is the best that I could translate it to: > > Well held in the bass > > > So from that translation, here is what I think Beethoven is trying to get across with that marking: > > Hold the bass notes as though there was a fermata in the bass, in other words, longer than your normal tenuto, while the melody is an accented staccato. > > > **Is that what Beethoven is trying to get across with the marking?** EDIT: Here is what I see in the Schirmer edition, or whenever I look at Sonata Album Book II published by the same people. I use the Schirmer edition, partly because it makes it so easy to see where the recapitulation starts. But here is what I see in that edition: [![enter image description here](https://i.stack.imgur.com/klol4.png)](https://i.stack.imgur.com/klol4.png) As you can see, ***ben tenuto il basso*** is clearly marked here under the same measure that has the poco crescendo marking.
2019/04/30
[ "https://music.stackexchange.com/questions/84410", "https://music.stackexchange.com", "https://music.stackexchange.com/users/9749/" ]
Finding the edition the OP referred to (<https://imslp.org/wiki/Special:ImagefromIndex/11070/torat>) didn't take long. It's the sort of marking that always reminds me of a John Cleese joke in *Fawlty Towers*: "You should be on *Mastermind*. Specialist subject, the bleedin' obvious." Looking through the editors of editions on IMSPL to find somebody full of their own self importance who might write such a thing, my first guess was correct: Godowsky - the guy who rewrote 57 variations on the Chopin Etudes, because he didn't understand *why* the originals were so already so difficult, being unable to see past the mere technical problem of pressing down the piano keys in the right order. So, it means absolutely nothing. As pidgin-Italian, it translates as something like "that bass line should be well held down, man!!" The only logic for it that I can see is that Godowsky (not Beethoven!) decided the four notes in question ought to be slurred in two pairs, but playing the slurs that he invented for no reason is hard, so he decided to add some words saying "yes I really do mean this". Throw that edition away, and look at what *Beethoven* wrote. When *he* adds some textual instructions, they are always both practical and important. While I was writing this the OP posted an picture which confirms the source as the Godowsky edition. Schirmer just republish anything that is out of copyright, without bothering to say where they got it from. Before the internet, Schirmer editions were cheap, but mostly garbage. Now you can get better sources from the internet for free in sites like IMSLP, they are just garbage.
20,834,941
My HTML5 Wordpress `<a href="#">site</a>` is not showing properly in IE, but it works well in Chrome and Firefox. What is the reason for this and how can I resolve it?
2013/12/30
[ "https://Stackoverflow.com/questions/20834941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2910583/" ]
You can see an example of something similar in the Routing guide: <http://guides.rubyonrails.org/routing.html#naming-routes> `get 'exit', to: 'sessions#destroy', as: :logout` You could use: `get 'about_us', to: 'main#about_us'`
3,900,172
> > $\textbf{Problem}$: An athletic facility has $5$ tennis courts. Pairs of players arrive at the > courts and use a court for an exponentially distributed time with mean $40$ minutes. > Suppose a pair of players arrives and finds all courts busy and k other pairs waiting in > queue. What is the expected waiting time to get a court? > > > > > $\textbf{Answer}$: As long as the pair of players are waiting, all five courts are occupied by other players. When all five courts are occupied, the time until a court is freed up is exponentially distributed with mean $40/5=8 $ minutes. For our pair of players to get a court, a court must be freed up $k+1$ times. Thus, the expected waiting time is $8(k + 1)$. > > > The issue that I'm having in understanding is why does "The time until a court is freed up is exponentially distributed with mean $40/5=8$ minutes" rather than simply $40$ minutes. Since every court is independent and using the memoryless property. On the contrary, if I look at $$Z=min(X\_{1}, X\_{2}, X\_{3}, X\_{4}, X\_{5})$$. where $X\_{i}$ is time taken by a pair to play in court $i$ and is exponentially distributed time with mean $40$ minutes. Then $Z$ itself becomes and exponentially distributed with mean $40\*5 = 200$ minutes. I am unable to understand it intuitively. Any help is appreciated.
2020/11/09
[ "https://math.stackexchange.com/questions/3900172", "https://math.stackexchange.com", "https://math.stackexchange.com/users/792588/" ]
Each $X\_i$ has rate $\lambda=\frac1{40}$ (with minutes as the time unit), so $Z$ has $\lambda=\frac5{40}=\frac18$ for a mean of $8$ minutes. You have applied the formula incorrectly: the rates add, not the means.
379,117
I just set up nginx as a http/https reverse proxy and it worked well. After that, I realized that for some domains ftp services are available. I was able to install ftp.proxy and it also works well, although it just handles one single domain. My question is: Is there any possibility to reverse proxy ftp services based on hostnames/domains like I do with nginx for http?
2012/04/13
[ "https://serverfault.com/questions/379117", "https://serverfault.com", "https://serverfault.com/users/81551/" ]
There's a G-WAN [rewrite example here](http://gwan.com/developers#handler) (look at the second handler source code, the first handler example illustrates FLV pseudo-streaming).
46,565,928
I am new to Matlab and i ran into this problem: I have a function that takes 3 doubles as arguments and outputs a single double e.g.: ``` function l = myFunct(a,b,c) l = a^2*b^2 + (2*(c^2 - b) / (a - sqrt(c))) end ``` Now, I need to plot the result of this function for intervals: a = b = [0.1,3], while keeping c = 2. I managed to do this for 2d plot of a single variable, but not for 3d... ``` R = 0:0.01:2; fun = @(x) myFunct(0.2, x, 3); B = arrayfun(fun,R); plot(R, B); ``` Could you please help and explain?
2017/10/04
[ "https://Stackoverflow.com/questions/46565928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8720210/" ]
Add `ml-auto` class to `navbar-nav` along with `mr-auto`
12,739,297
In Global Config in joomla have 2 caching is conservative and progressive, what is difference both ?
2012/10/05
[ "https://Stackoverflow.com/questions/12739297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840461/" ]
> > **Conservative caching** is the standard type of caching. Here’s how it works: > > > * A visitor visits a page on your website. > * Joomla checks if there is a non-expired version of that page in its cache directory. > * If the cached page exists (and it’s not expired), then Joomla will serve it to the visitor – otherwise, a cached version of the page is created, and that cached version will be served to the visitor, and to every other consequent visitor, as long as it’s (by “it” we mean the page) not expired. > > > The above scenario is typical and is how most developers implement > caching. > > > **Progressive caching** works the following way: > > > * A visitor visits a page on your website. > * Joomla checks if a cached version of that page exists for that visitor and it’s not yet expired. > * If that cached page exists, then it’ll be served to the visitor, otherwise, Joomla will create the cached page for that specific visitor and then will serve it to him. > * If another visitor (who has never been on that page) visits that page, then Joomla will not serve the cached page of the previous visitor, instead, it will create a cached version of that page > > specifically for that user, and then serves it to him. > > > As you can see, progressive caching only offers a performance > improvement if the same visitor visits the same page within the > lifetime of the cached version of the page. In most scenarios, > progressive caching results in a huge performance hit that is far > worse than disabling cache, simply because for nearly every visit, > Joomla has to process the request, create the cached version of the > page, and then serve the page to the visitor (instead of just > processing the request and serving the page in the scenario where > cache is disabled). Oh, and don’t forget about all the cache files > generated by Joomla – you can only imagine how many of these files you > will have in your cache folder if you have a high traffic news website > (that has many pages). > > > Now you might wonder, under which circumstances is progressive caching > useful? Well, imagine that you have a video website (similar to > youtube). You want to show each visitor customized pages based on his > location and/or browser settings and/or plugins installed. So, for > every page that the visitors loads, you use this information to > generate a customized version of that page and you cache it. If the > visitor visits that same page again, then Joomla doesn’t need to redo > the work to generate the customized page. > > > Of course, there are many scenarios under which progressive caching is > really useful, but in our opinion, progressive caching should only be > considered if the website receives many visitors and if those visitors > are mostly repeat visitors. Using it in other cases will cause a > significant hit on the website’s performance. > > > Extracted from [here](http://www.itoctopus.com/why-progressive-caching-in-joomla-should-be-avoided-in-most-cases).
16,701,666
Please note this is not the same question as mentioned above since XML escaping to preserve codepoints is possible. I have a UTF-8 XML file which I can send via HTTP to some other system which I have no control over. For whatever crazy reason it decides to convert it to ISO-8859-1 loosing many Unicode characters and replacing them with '?'. This system then sends someone else this converted XML document. How in Java on the sending side can I escape any arbitrary XML with non ASCII codepoints so that they survive this intermediary system and can still be decoded correctly by the endpoint? A --(UTF-8)--> B --(ISO-8859-1)--> C (Decodes to internal Unicode representation). ``` import java.text.Normalizer; import java.text.Normalizer.Form; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.text.translate.CharSequenceTranslator; import org.apache.commons.lang3.text.translate.NumericEntityEscaper; public class Test { private static CharSequenceTranslator translator = StringEscapeUtils.ESCAPE_XML .with(NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE)); public static void main(String[] args) { String s = "<note>\n<to>Tove</to>\n<from>Jani</from>\n<heading>Reminder</heading>\n<body>Don't forget me this weekend!test☠ä</body>\n</note>"; String xmlEscapedS = xmlToRobustXml(s); System.out.println(xmlEscapedS); } /** * @param s * @return */ public static String xmlToRobustXml(String s) { s = Normalizer.normalize(s, Form.NFC); String xmlEscapedS = translator.translate(s); return xmlEscapedS; } } ``` I tried this but it escapes everything. ``` &lt;note&gt; &lt;to&gt;Tove&lt;/to&gt; &lt;from&gt;Jani&lt;/from&gt; &lt;heading&gt;Reminder&lt;/heading&gt; &lt;body&gt;Don&apos;t forget me this weekend!test&#9760;&#228;&lt;/body&gt; &lt;/note&gt; ```
2013/05/22
[ "https://Stackoverflow.com/questions/16701666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1482815/" ]
Here are three standard API methods to produce ISO-8859-1 encoded documents. Using the [StAX API](http://docs.oracle.com/javase/7/docs/api/javax/xml/stream/package-summary.html): ``` // output stream ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // transcode StringReader xml = new StringReader("<x>pi: \u03A0</x>"); XMLEventReader reader = XMLInputFactory.newFactory().createXMLEventReader( xml); XMLEventWriter writer = XMLOutputFactory.newFactory().createXMLEventWriter( buffer, "ISO-8859-1"); try { writer.add(reader); } finally { writer.close(); } // proof String decoded = new String(buffer.toByteArray(), Charset.forName("ISO-8859-1")); System.out.println(decoded); ``` Using the [DOM API](http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/ls/package-frame.html): ``` // output stream ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // create XML DOM InputSource src = new InputSource(new StringReader("<x>pi: \u03A0</x>")); Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(src); // serialize DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation(); LSOutput out = impl.createLSOutput(); out.setEncoding("ISO-8859-1"); out.setByteStream(buffer); impl.createLSSerializer().write(doc, out); // proof String decoded = new String(buffer.toByteArray(), Charset.forName("ISO-8859-1")); System.out.println(decoded); ``` Using the [transform package](http://docs.oracle.com/javase/7/docs/api/javax/xml/transform/package-frame.html): ``` // output stream ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // transformation StreamSource src = new StreamSource(new StringReader("<x>pi: \u03A0</x>")); StreamResult res = new StreamResult(buffer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.transform(src, res); // proof String decoded = new String(buffer.toByteArray(), Charset.forName("ISO-8859-1")); System.out.println(decoded); ``` Which you would use depends on your use case; the StAX API is probably the most efficient. All this sample code will emit documents equivalent to: ``` <?xml version="1.0"?><x>pi: &#x3a0;</x> ```
22,702
*This question continues story of [one ESA vs NASA battle on Mars](https://worldbuilding.stackexchange.com/questions/22573/how-will-my-nerdy-mars-astronauts-do-battle-between-their-colonies). I tried to put everything important into this question. Also, being from Europe, I took ESA side as the one winning:* * **Year:** 2100ish * **Mars:** Two 'surface,' permanent scientific research colonies with a little over 100 scientists and engineers in each with an additional support crew (geologist, psychologist & medical, etc.) to about 150 people each, with the common utilities, agrarian setups, etc. The nerds in Colony ESA have just had it with Colony NASA, about 100km across [Elysium](http://maps.google.com/mars/#lat=0.522717&lon=534.222794&zoom=6) plains, and they went there and did burst their bubble. (Literally) **The question: How will Earth handle this?** It is safe to assume that both colonies are under constant surveillance from ground control. It is also safe to assume that NASA and ESA are still "friends" and the setup of having two colonies instead one is because they got great fundings - so why not build two? It is also safe to assume, that there is some crew rotation (people and material are being exchanged on regular basis) [![Example from Google Image Search](https://i.stack.imgur.com/2L6GD.jpg)](https://i.stack.imgur.com/2L6GD.jpg) The time is Battle + 15 minutes. Ground control of both teams is getting first shocking images of whats happening on Mars. And you know that until they receive first orders, everything will be over... What happens next? **Edit:** Trying to make the question less opinion based: Assume there is only one NASA+ESA joint resupply mission and next one is about to launch, arriving to Mars in half a year. Usually this resuply mission has about 7 months of food + oxygen + water supplies for all the crew + 12 people to go on rotation mission (6 NASA, 6 ESA). The resuply frequency is 6 months. So, lets scope the question like this: Who do I send out in next resupply mission? (profession wise obviously). And how has NASA + ESA proceed is they (obviously) want Mars mission to continue?
2015/08/16
[ "https://worldbuilding.stackexchange.com/questions/22702", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2071/" ]
**NASA/ESA Repsonse** *Surprise* The officials should be shocked. After Houston kept telling the astronauts, for example, to 'just learn to get along,' they will have decided to take things into their own hands and through a series of discussions in 'safe' spaces or on notes of paper, they planned their battles. It wasn't until T minus an-hour-or-so before they departed that NASA/ESA realized their scientists weren't going to take it any more. *(Short-term) Attempt at Cover-up* This is a situation with precedent. Just as whenever there's a situation (riots or whatever), there's a scramble. I don't think it would be an attempt to cover-up permanently, because this will obviously not be successful, but governments and private companies, and even kids who broke a window with a baseball try to keep it a secret until they can think what to do. In this scenario, frantic phone calls are made between agencies internally and among the countries involved. "Hi, Mr. President, we have a situation..." "They what-the-WHAT?" *Damage Control* Heads of agencies, involved companies and government officials are scrambling to figure out what to do. It's hard to punish an employee who is a permanent colonist on a planet 140 million miles away. The press liasons are woken from bed to get onto the case and make sure that the spin is just so: the actions were unprecedented, atypical, and will be handled immediately. *Finger Pointing* This seems inevitable. Everyone wants to assign a cause to a situation, to help understand it, and there will be no end to this. It wouldn't be between the two agencies, rather between sub-sets of organizations and governments. The pressure put on the nerds by a rigorous schedule, or even petty things (the geologists from NASA were not allowed to study an area, because ESA claimed the area with a likelihood for astonishing discovery, for example). The economic and political effects can be complex. However, property destruction and harm to individuals are often immediately measurable and will be assigned. In order to separate government responsibility from the actions of the nerds, I speculate that they would assign this as a 'riot,' and not politically motivated or assigned actions. **Re-route Supplies and Relief Personnel** The relief supplies would have to be enhanced by shifting some of the weight of long-term supplies (soils & plants for future planting, laboratory equipment, etc.) with that of equipment and personnel to either return the remaining scientists or to contain them until they can be returned. This could include mechanisms for locating them (the nerds that won the battle know not to hang around, and have contingency for this), and then disabling their mobility. **Aside: Public Outcry** Phone calls will be made, statements will be made. People who already have disdain for space exploration will use this forever as an argument to defund future space exploration, manned or otherwise. Also, so much for childrens' role models.
13,075,617
I would like to know how to get the current week number from Rails and how do I manipulate it: 1. Translate the week number into date. 2. Make an interval based on week number. Thanks.
2012/10/25
[ "https://Stackoverflow.com/questions/13075617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/788357/" ]
Use [`strftime`](http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-strftime): > > `%U` - Week number of the year. The week starts with Sunday. (00..53) > > `%W` - Week number of the year. The week starts with Monday. (00..53) > > > ``` Time.now.strftime("%U").to_i # 43 # Or... Date.today.strftime("%U").to_i # 43 ``` If you want to *add* 43 weeks (or days,years,minutes, etc...) to a date, you can use [`43.weeks`](http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Numeric/Time.html#M000324), provided by ActiveSupport: ``` irb(main):001:0> 43.weeks => 301 days irb(main):002:0> Date.today + 43.weeks => Thu, 22 Aug 2013 irb(main):003:0> Date.today + 10.days => Sun, 04 Nov 2012 irb(main):004:0> Date.today + 1.years # or 1.year => Fri, 25 Oct 2013 irb(main):005:0> Date.today + 5.months => Mon, 25 Mar 2013 ```
13,659,652
I have found good tutorial to for Handling Screen OFF and Screen ON Intents: <http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/> but i want that after screen is off every 5 minutes wifi is checked if is connected ``` ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); wifi.isConnected() ``` i want to use `alarm manager` <http://developer.android.com/reference/android/app/AlarmManager.html> but i don't know how to check every 5 minutes if is connected or not.
2012/12/01
[ "https://Stackoverflow.com/questions/13659652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267679/" ]
Everything is fine. You just need to take care of little things. In this case `;` is missing after declaring 'pri\_func2'. ``` pri_func2 = function() { //do something }; ``` This should be enough for this error.
70,993
We know through [General Relativity](http://en.wikipedia.org/wiki/General_relativity) (GR) that matter curves spacetime (ST) like a "ball curves a trampoline" but then how energy curves spacetime? Is it just like matter curvature of ST?
2013/07/13
[ "https://physics.stackexchange.com/questions/70993", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/25589/" ]
Theoretical viewpoint: ---------------------- Einstein field equations can be written in the form: $$\color{blue}{G\_{\mu\nu}}=\color{red}{\frac{8\pi G}{c^{4}}} \color{darkgreen}{T\_{\mu\nu}}$$ We can write in simple terms: $$\rm \color{blue}{Space-time \,\,geometry}=\color{red}{const.}\,\,\color{darkgreen}{Material \,\,objects}.$$ And the $T\_{\mu\nu}$ is a mathematical object (a tensor to be precise) which describes material bodies. In that mathematical object, there are some parameters such as the density, the momentum, mass-energy... etc. So it is those parameters that determine 'how much space-time curvature' is around a body. And one of the parameters is of course *energy*. Therefore, *energy* do bend space-time. Experiments that confirm this point: ------------------------------------ First, do photons have mass? The answer is an emphatic **'no'**. The momentum of a photon is $p=\frac{hf}c$, and from special relativity: $$\begin{align}E=\sqrt{(mc^2)^2+(pc)^2}&\iff E^2=(mc^2)^2+(pc)^2\\&\iff E^2-(pc)^2=(mc^2)^2\\ \end{align}.$$ The energy of a photon is: $E=hf$ which is an experimental fact. It can also be expressed as $E=pc$ since $E=hf=\frac{hf}{c}\cdot c=pc.$ Therefore, $E^2=(pc)^2$ and so $E^2-(pc)^2=0$. Putting this in our previous derivation we get: $E^2-(pc)^2=(mc^2)^2=0$. Since $c^2$ is a constant, then $m=0$. Therefore, photons have no rest mass. **Claim:** Photons are not subject to gravitational attraction since they have no rest mass. **Experimental disproof:** [Gravitational lensing](http://en.wikipedia.org/wiki/Gravitational_lens): ![copyright to the author](https://i.stack.imgur.com/exReS.jpg) You could see light being bent due to the presence of a strong gravitational field. **Conclusion:** Even if light has no rest mass, it has energy and momentum. And it is being attracted due to gravity, so the natural conclusion is that energy do curve space-time.
63,514,476
I am attempting to create a regular expression for validating edu emails which may or may not have a sub domain. Some schools have emails like "[email protected]" while other schools have emails like "[email protected]". ``` ([0-9]|[a-z]|[A-Z])+@([0-9]|[a-z]|[A-Z])+([0-9]|[a-z]|[A-Z])\.edu$" ``` This is the current regular expression that I have but I am not well versed in these. I am looking to create an expression that will validate emails with one domain and emails with a subdomain. Any help would be appreciated. Thanks!
2020/08/20
[ "https://Stackoverflow.com/questions/63514476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14140227/" ]
Didn't implement NLP for verb / noun separation, just added a list of good words. They can be extracted and normalized with [spacy](https://spacy.io/) relatively easy. Please note that `walk` occurs in 1,2,5 sentences and forms a triad. ```py import re import networkx as nx import matplotlib.pyplot as plt plt.style.use("ggplot") sentences = [ "I went out for a walk or walking.", "When I was walking, I saw a cat. ", "The cat was injured. ", "My mum's name is Marylin.", "While I was walking, I met John. ", "Nothing has happened.", ] G = nx.Graph() # set of possible good words good_words = {"went", "walk", "cat", "walking"} # remove punctuation and keep only good words inside sentences words = list( map( lambda x: set(re.sub(r"[^\w\s]", "", x).lower().split()).intersection( good_words ), sentences, ) ) # convert sentences to dict for furtehr labeling sentences = {k: v for k, v in enumerate(sentences)} # add nodes for i, sentence in sentences.items(): G.add_node(i) # add edges if two nodes have the same word inside for i in range(len(words)): for j in range(i + 1, len(words)): for edge_label in words[i].intersection(words[j]): G.add_edge(i, j, r=edge_label) # compute layout coords coord = nx.spring_layout(G) plt.figure(figsize=(20, 14)) # set label coords a bit upper the nodes node_label_coords = {} for node, coords in coord.items(): node_label_coords[node] = (coords[0], coords[1] + 0.04) # draw the network nodes = nx.draw_networkx_nodes(G, pos=coord) edges = nx.draw_networkx_edges(G, pos=coord) edge_labels = nx.draw_networkx_edge_labels(G, pos=coord) node_labels = nx.draw_networkx_labels(G, pos=node_label_coords, labels=sentences) plt.title("Sentences network") plt.axis("off") ``` [![enter image description here](https://i.stack.imgur.com/pLbLx.png)](https://i.stack.imgur.com/pLbLx.png) **Update** If you want to measure the similarity between different sentences, you may want to calculate the difference between sentence embedding. This gives you an opportunity to find semantic similarity between sentences with different words like "A soccer game with multiple males playing" and "Some men are playing a sport". Almost SoTA approach using BERT can be found [here](https://keras.io/examples/nlp/semantic_similarity_with_bert/), more simple approaches are [here](https://stackoverflow.com/questions/45869881/finding-similarity-between-2-sentences-using-word2vec-of-sentence-with-python). Since you have similarity measure, just replace add\_edge block to add new edge only if similarity measure is greater than some threshold. Resulting add edges code will look like this: ``` # add edges if two nodes have the same word inside tresold = 0.90 for i in range(len(words)): for j in range(i + 1, len(words)): # suppose you have some similarity function using BERT or PCA similarity = check_similarity(sentences[i], sentences[j]) if similarity > tresold: G.add_edge(i, j, r=similarity) ```
920
It is well-known that we can learn a lot about the structure of the lower crust, mantle, and core by observing the ways in which they refract different kinds of seismic waves. Do we have any *other* ways of imaging the deeper parts of the Earth, though?
2014/05/13
[ "https://earthscience.stackexchange.com/questions/920", "https://earthscience.stackexchange.com", "https://earthscience.stackexchange.com/users/67/" ]
Gravity can be used to investigate the lower crust and upper mantle (see for example [Fullea et al, 2014](http://dx.doi.org/10.1016%2Fj.jag.2014.02.003)). Satellite measurements of gravity could even be used to investigate deeper structures in the mantle, like subducting slabs ([Panet, 2014](http://dx.doi.org/10.1038%2Fngeo2063)). However, I couldn't find any use of gravity data to probe deeper, into the core for example. The [magnetotelluric method](http://en.wikipedia.org/wiki/Magnetotellurics) is sometimes used for deep crustal structure. And features of the geomagnetic field, like [secular variation](http://en.wikipedia.org/wiki/Geomagnetic_secular_variation), can be inverted to investigate as far down as the outer core ([Gubbins, 1996](http://dx.doi.org/10.1016/S0031-9201(96)03187-1)). However, the most common and well developed method to image the lower mantle and core is still through seismic waves.
46,777,671
currently i have two json body : 1. globaljson 2. companyjson globaljson : ``` "dS": { "a": 5, "b": false, "c": 5, "d": false, "e": 1, "f": 5, "g": 33.528, "h": false } ``` company json : ``` "dS": { "a": 90 }, ``` expected output : ``` "dS": { "a": 90, "b": false, "c": 5, "d": false, "e": 1, "f": 5, "g": 33.528, "h": false } ``` i tried to do following : ``` Map<String, Object> map1 = mapper.readValue(companyjson, Map.class); Map<String, Object> map2 = mapper.readValue(globaljson, Map.class); Map<String, Object> merged = new HashMap<String, Object>(map1); merged.putAll(map2); ``` but this returns ``` "dS": { "a": 90 }, ``` im currently using jackson library but couldn't find any method that solves my requirement. i don't want to hard code my keys because key name may change in future.
2017/10/16
[ "https://Stackoverflow.com/questions/46777671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7751734/" ]
Intent is using only for sending some data between activities/services and system. It won't play the music. It don't do anything except saying to some activity what to do. You need the mechanism which will play your multimedia stream. You should use [MediaPlayer](https://developer.android.com/reference/android/media/MediaPlayer.html) class for playing multimedia inside your application. Here's some tutorial, how to play music from stream: <http://programmerguru.com/android-tutorial/android-mediaplayer-example-play-from-internet/>
30,662,784
I am trying to add validation check on this auto complete, however for some reason because its in an `each()` block it's causing me so many problems. Full code: ``` <input type="text" class="productOptionSerialNumber" value="@opt.SerialNumber" data-part-num="@opt.PartNumber" /> ``` ```js $(".productOptionSerialNumber").each(function () { var partNum = $(this).attr("data-part-num"); $(this).autocomplete({ source: "@Url.Action("SerialPartNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val() + "&partnum=" + partNum + "&callnum=" + $("#Form_Call_Num").val(), minlength: 2, delay: 300, }) }); ``` For this .productOptionSerialNumber function i cannot do a validation. i have a working example which has worked before (look below) but with this particular function it doesn't validate, i have tried to add it the same way i did before, but no luck. Working: ``` $(document).ready(function () { //$('input[name="Form.InstallType"]').on('change', function() { var val = $('input[name="Form.InstallType"]:checked').val(); if (val == '1') { var validOptions = "@Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val(); previousValue = ""; $('#abc').autocomplete({ autoFocus: true, source: validOptions, }).change(function(){ var source = validOptions; var found = $('.ui-autocomplete li').text().search(source); console.debug('found:' + found); var val = $('input[name="Form.InstallType"]:checked').val(); if (found < 0 && val === '1') { $(this).val(''); alert("You must select a value from the auto complete list!"); } }); } }); ``` So if I don't choose from auto complete I get an alert. I am trying to implement this to the first part of code but because its in a `.each` and `.attr` it's not liking it this way. Any ideas
2015/06/05
[ "https://Stackoverflow.com/questions/30662784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2519466/" ]
Without additional information I don't know what kind of problems you are experiencing with the each() loop, however what you are trying to accomplish is certainly do-able. Here is an example, hopefully it will help you fill in anything you are missing on your end. HTML ``` <label>productOption aaa:</label> <input type="text" class="productOptionSerialNumber" value="" data-part-num="aaa" /> <br /> <br /> <label>productOption bbb:</label> <input type="text" class="productOptionSerialNumber" value="" data-part-num="bbb" /> <br /> <br /> <label>productOption ccc:</label> <input type="text" class="productOptionSerialNumber" value="" data-part-num="ccc" /> ``` Jquery ``` var dataFromURL = { 'aaa':['What','Is','Up'], 'bbb':['Nothing','Much','Bro man'], 'ccc':['Clown','Question','Bro schmoe'] } $(document).ready(function(){ $(".productOptionSerialNumber").each(function () { var partNum = $(this).attr("data-part-num"); $(this).autocomplete({ source: dataFromURL[partNum], minlength: 2, delay: 300, }).change(function(){ var data = $(this).autocomplete( "option" ).source; var found = data.indexOf($(this).val()); if (found < 0) { alert("You must select a value from the auto complete list!"); $(this).val(''); } }); }); }); ``` [Fiddle Example](http://jsfiddle.net/rkfs540q/)
19,574,593
OK, so I have an Item class that has a many-to-many attribute to User through a 'Roles' class. I am trying to create a django-table for the Items such that out of any of the roles attached to the item, if the current User is attached to that role, the name of the role displays. I hope that makes some sort of sense. Here's what I have so far, which I didn't really expect to work because I don't see how the Table class can know about the request/user. I'm stuck. models.py ``` class Item(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, related_name='Owner') roles = models.ManyToManyField(User, through='Role') class Role(models.Model): role_type = models.ForeignKey(RoleType) user = models.ForeignKey(User) item = models.ForeignKey(Item) ``` tables.py ``` class OwnedTable(tables.Table): roles = tables.Column() user = request.user def render_roles(self): for role in roles: if role.User == user: return role.role_type else: pass class Meta: model = Item attrs = {"class": "paleblue"} fields = ('id', 'name', 'owner', 'roles') ```
2013/10/24
[ "https://Stackoverflow.com/questions/19574593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695507/" ]
You can get the `request` object from `self.context`. So if you only need `request.user`, that's one way to do it. ``` class OwnedTable(tables.Table): roles = tables.Column(empty_values=()) def render_roles(self): user = self.context["request"].user ... ``` Otherwise, @mariodev's solution works.
3,370,823
I am trying to solve this task > > Consider the measure space $([0,1],\mathcal{B}([0,1]),\mu:=2\lambda\_1+3\delta\_{1})$ and the measurable function $f(\omega)=2-\omega$. Find $$\int\_{[0,1]}f\,d\mu$$ > > > My Solution $$\int\_{a}^{b} f(x) d x=\int\_{[a, b]} f d \lambda\_{1}$$ We know Thus $$\int\_{[0,1]} f d \mu=\int\_{[0,1]} 2- x\left(2d \lambda\_{1}+3 d \delta\_{1}\right)=\cdots=6$$
2019/09/26
[ "https://math.stackexchange.com/questions/3370823", "https://math.stackexchange.com", "https://math.stackexchange.com/users/699012/" ]
I pressume that $\delta\_1$ is the Dirac measure and $\lambda\_1$ the Lebesgue measure. If so,then you are correct. Indeed: So $$\int\_0^1f(x)d\mu(x)=2\int\_0^1(2-x)d\lambda\_1(x)+3\int\_0^1f(x)d\delta\_1(x)$$ $$=2\int\_0^1(2-x)dx+3 f(1)=2(2-\frac{1}{2})+3=6$$
30,123,332
I'm trying to test my local storage so I've tried a few examples. this example worked before but now its not. not sure what happened <https://stackoverflow.com/questions/30116818/how-to-use-local-storage-form-with-html-and-javascript?noredirect=1#comment48344527_30116818/> Now I am trying this code and nothing pops up on if else, it just says local storage is ``` function lsTest() { var test = 'test'; try { localStorage.setItem(test, test); localStorage.removeItem(test); return true; } catch(e) { return false; } } var elem = document.getElementById('status'); if (lsTest() === true) { elem.innerHTML += 'available.'; } else { elem.innerHTML += 'unavailable.'; } ``` html ``` <div id="status">Local Storage is </div> ``` full code <http://tny.cz/39896a73>
2015/05/08
[ "https://Stackoverflow.com/questions/30123332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4796973/" ]
You should open your page using a webserver and not your local file system. The browser saves the localstorage data based on the host(domain). This prevents cross site local storage access.
2,059,606
I've got a list with list-style-none which needs to be able to add new items to itself via Ajax and have the background expand appropriately when it does. Adding via Ajax is easy, but every solution I try for the background fails me. I don't know if it's even possible; is it? I'm using a grid like this one: <http://jqueryui.com/demos/sortable/#display-grid> Both WebKit and Firebug are showing me skinny, empty bars when I hover over the enclosing divs and/or the enclosing ul tag. It appears that the minute you set a list loose with list-style-none and float:wherever, you give up control over its background. But that can't be right.
2010/01/13
[ "https://Stackoverflow.com/questions/2059606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/250151/" ]
This is something I've run into a number of times. The problem is that floated elements aren't part of the normal box model, so they don't cause their parent elements to expand **unless** their parent elements are also floated. So if possible, float the ul or containing div. Edit: See [quirksmode](http://www.quirksmode.org/css/clearing.html) for another css-only workaround.
17,011,831
I am trying to googling for passing in acceptable parameters for setting up cronJobs based on a users timeZone. Im using a cronJob module which can be found here. <https://github.com/ncb000gt/node-cron> The problem is I need to pass different timeZones but I can't seem to find the acceptable parameters and format for the different timezones. Can anyone point me in the right direction?
2013/06/09
[ "https://Stackoverflow.com/questions/17011831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382927/" ]
malloc returns a void\*. You need to cast the returned value. ``` HugeInteger *ptr = (HugeInteger*)malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE); ```
50,861,823
i have something like this: ``` DELETE FROM `history` WHERE `date_field` <= now() - INTERVAL 10 DAY ``` but if all records is older than 10 days - this query deletes all! i want to keep last 20 records, even if they too old ! Please help, what and how i need to upd my code, and what will be better use limit+offset of windowed function **OVER()** or need smth another ?
2018/06/14
[ "https://Stackoverflow.com/questions/50861823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5809937/" ]
Join with a subquery that gets the most recent 20 days and excludes them. ``` DELETE h1 FROM history AS h1 LEFT JOIN ( SELECT id FROM history ORDER BY date_field DESC LIMIT 20 ) AS h2 ON h1.id = h2.id WHERE date_field < now() - INTERVAL 10 DAY AND h2.id IS NULL; ```
13,102
I am in the process of building a dining table out of solid walnut. I don't have the skills or equipment to make the tabletop myself, so I got my wood supplier to do it for me. The tabletop is 6/4 walnut, 7' long by 40" wide, and is made up of 6 smaller boards glued together. The shop is reputable and seems to know what they are doing. I received it about a month ago, and since then, it's been standing behind my living room couch leaning against the wall (long side on the floor). It was leaning at maybe a 10 degree angle, with the underside of the piece facing away from the wall. Anyways, now that I've completed the base, I'm paying attention to the tabletop, and I notice that there is some significant cupping. The concave side (the underside) goes in about 3/16" in the middle down from the edges. Unfortunately, I didn't check for cupping when I initially received the piece, so I'm not sure if it came like this or if I caused it myself somehow. Regardless, the damage is done, so what are my options now? I've seen some articles/videos where they dampen the concave side of a cupped board and let it sit overnight to straighten it out, but will that work on my 6/4 tabletop? I tried applying this technique yesterday evening, but this morning I don't measure any difference in the amount of cupping. Any advice would be greatly appreciated. Note: I don't have a table saw, thickness planer, or jointer.
2021/09/18
[ "https://woodworking.stackexchange.com/questions/13102", "https://woodworking.stackexchange.com", "https://woodworking.stackexchange.com/users/2909/" ]
> > Any advice would be greatly appreciated. > > > 3/16” over the length and width of the table isn’t much; if you put the top on the base and leave it unattached, it might flatten out on its own after a week or two. You could encourage it by putting something heavy, like a box of books (or two) in the middle. Whether that helps or not, you can probably also pull it flat with a screw or two through the middle of the base into the bottom of the tabletop. Depending on your design, that might mean that you have to add a piece to the base across the middle.
27,969
In an "alternate universe" where NASA continued to receive a mandate, funding and public support at say peak Apollo levels, could another ten or twenty years have gotten boots on Mars, with astronauts in those boots? Or would there be some clear technical challenge that really needed several more decades of development before this would have been possible? **Ideally:** a bit of math or some supporting links should be presented and not just an opinion or a list. This question is motivated in part by [this thoughtful answer](https://space.stackexchange.com/a/27968/12102).
2018/06/20
[ "https://space.stackexchange.com/questions/27969", "https://space.stackexchange.com", "https://space.stackexchange.com/users/12102/" ]
If you want to get really bummed out for 'what could have been', check out the Wikipedia page for [List of manned Mars mission plans](https://en.wikipedia.org/wiki/List_of_manned_Mars_mission_plans). The earliest plan to get to Mars was [written by von Braun in 1948](http://www.wlym.com/archive/oakland/docs/MarsProject.pdf), with the idea that we would be landing in 1965. With our current knowledge of Mars, it reads like science fiction. Seven passenger ships and three cargo ships would be assembled in Earth orbit using reusable shuttles to launch the materials. They would fly to Mars in the same way we do currently, at the optimal transfer window. They would find a landing site from orbit. A manned glider would be used to make the first landing on Mars, using skis to land on the polar ice cap. The crew would then travel overland using rovers and then build a landing strip. [![Mars 1949](https://i.stack.imgur.com/H5qEQ.png)](https://i.stack.imgur.com/H5qEQ.png)<http://www.astronautix.com/v/vonbraunmarpedition-1952.html> Obviously we now know much of this would be impossible. Mars doesn't have the thickness of atmosphere needed to support landing with gliders, and the radiation of interstellar space was completely unknown at the time. Additionally, the technology and engineering which would be needed to develop reusable shuttles were almost 30 years away, and even then NASA was unable to keep reuse tempos anywhere near what would be necessary for an extended space construction project. Quick budgetary baseline here: Apollo cost about $107 billion in today's dollars. Here are the yearly figures in that-year-dollars from [Wikipedia](https://en.wikipedia.org/wiki/Apollo_program#Costs): [![Apollo budget costs](https://i.stack.imgur.com/AfYtW.png)](https://i.stack.imgur.com/AfYtW.png) The NASA estimates for the space shuttle (which was being costed and developed around the same time Von Braun and Boeing were putting together) was 43 billion in 2011 dollars. This was based on 50 launches per year, which was very unrealistic (lots more to be said here, effectively NASA planned for the Space Shuttle as being the sole launch vehicle for the entirety of the US including commercial and military launches). The actual final total for the space shuttle was 196 billion, so the estimates were way off. Back to the plans. Von Braun updated his plan throughout the Apollo program, and at the very end of his career, proposed his [1969 plan](http://www.astronautix.com/v/vonbraunmarpedition-1969.html). This plan was huge, and would likely have required an amount of investment in excess of what Apollo ran (his estimate was a peak of $8 billion per year, which is more than double what Apollo cost at its peak). The first step of the plan was the space shuttle, albeit a far different shuttle than the one you and I know, mainly because it would use a nuclear rocket for propulsion. This would be followed by an earth space station, and finally the creation of the spacecraft which would take us to Mars. The main lifting vehicle from Earth for this would be a future-state Saturn V, the [Saturn V -25U](http://www.aerospaceprojectsreview.com/blog/?p=1359). This rocket would be a longer version of the Saturn V which took us to the moon, with four solid rocket boosters attached to the bottom, and the upper stages replaced by NERVA, a nuclear rocket engine. This rocket was entirely technically possible at the time, and would have required significant but not impossible engineering and integration work. [![Mars 1969](https://i.stack.imgur.com/9qeu8.png)](https://i.stack.imgur.com/9qeu8.png) <http://www.astronautix.com/v/vonbraunmarpedition-1969.html> The two Mars ships would be assembled in Earth orbit, fly to Mars using a standard trajectory, astronauts would descend using a to-be-designed descent module, stay for 90 days, then swing by Venus on their way back to Earth, docking with the space station and then returning in the reusable shuttle. The big driver for the 1969 plan, as well as for a competing plan from Boeing, was the NERVA rocket. Nuclear Engine for Rocket Vehicle Application (NERVA) was a nuclear-based rocket engine. [![NERVA](https://i.stack.imgur.com/KwDyo.jpg)](https://i.stack.imgur.com/KwDyo.jpg) <https://en.wikipedia.org/wiki/NERVA#/media/File:NERVA.jpg> This rocket engine was (and may still eventually be) the key to interplanetary travel. In a nuclear rocket, you don't need a chemical fuel. Liquid hydrogen is used, and is heated to a very high temperature in a nuclear reactor. As in a conventional rocket engine, the gas then expands and is propelled out the back of the ship. NERVA would have provided basically twice the fuel efficiency of a chemical rocket. I keep saying 'would have', but NERVA was an extensively developed project. Research on nuclear thermal rockets began in 1952, and continued for two decades. Two engines were built and tested. The second, NERVA XE, was basically a complete flight system and tested in a near-vacuum environment. It ran for a total of 115 minutes and was started 28 separate times. [![NERVA Test](https://i.stack.imgur.com/I84aKm.jpg)](https://i.stack.imgur.com/I84aK.jpg) In my opinion (and the opinion of 1960s engineers far far smarter than I), the answer to whether we could have done it technically is yes. The budget would have needed to exceed that of peak apollo, but that would have included far more than just the Mars mission, but also an earth-orbit space station, a reusable shuttle, and a nuclear rocket engine. Whether those estimates were reasonable, given the massive expansion of the space shuttle compared to initial estimates, is debatable. Whether it would have survived the political pressures not only to cut spending in the 70s and 80s, but also the environmental movement which was (and is) diametrically opposed to nuclear rockets is another. But if we'd been willing to double the investment we were making in Apollo, and public support had existed, I absolutely think we could have gotten not only there but to even more distant parts of our solar system.
20,873,246
I've spent far too long messing with this before asking for help. I can't seem to get RSpec and Sorcery to play together nicely. I've read through the docs on [Integration testing with Sorcery](https://github.com/NoamB/sorcery/wiki/Integration-Testing-with-Rspec,-Capybara-and-Fabricator) and can post the login action properly, but my tests still doesn't think the user is logged in. ``` # spec/controllers/user_controller_spec describe 'user access' do let (:user) { create(:user) } before :each do login_user(user[:email], user[:password]) end it "should log in the user" do controller.should be_logged_in end end ``` And my login\_user method ``` # spec/support/sorcery_login module Sorcery module TestHelpers module Rails def login_user email, password page.driver.post(sessions_path, { email: email , password: password, remember_me: false }) end end end end ``` The sessions controller handles the pages properly when I use them on the generated pages just fine. I tried outputting the results of the login\_user method and it appears to properly post the data. How do I persist this logged in user through the tests? Does a before :each block not work for this? I'm just not sure where it could be running wrong and I'm pretty new to testing/RSpec so I may be missing something obvious. I'd appreciate any help. Here's the output of the failed tests: ``` 1) UsersController user access should log in the user Failure/Error: controller.should be_logged_in expected logged_in? to return true, got false ```
2014/01/01
[ "https://Stackoverflow.com/questions/20873246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467579/" ]
I just went through this yesterday. Here's what I did, if it helps. Sorcery provides a test helper `login_user` that relies on a `@controller` object being available. This works great in controller specs, but doesn't work in integration tests. So the workaround in integration tests is to write another method (like the one you have above) to simulate actually logging in via an HTTP request (essentially simulating submitting a form). So my first thought is that you should try renaming your method to `login_user_post` or something else that doesn't collide with the built-in test helper. Another potential gotcha is that it looks to me like the Sorcery helper assumes that your user's password is 'secret'. Here's a link to the built-in helper so you can see what I'm talking about: <https://github.com/NoamB/sorcery/blob/master/lib/sorcery/test_helpers/rails.rb> Good luck - I really like this gem except for this part. It is really only fully explained by patching together SO posts. Here's the code I use: **Integration Helper** ``` module Sorcery module TestHelpers module Rails def login_user_post(user, password) page.driver.post(sessions_url, { username: user, password: password}) end def logout_user_get page.driver.get(logout_url) end end end end ``` **Integration Spec** (where user needs to be logged in to do stuff) ``` before(:each) do @user = create(:user) login_user_post(@user.username, 'secret') end ``` **Controller Spec** (where the regular `login_user` helper works fine) ``` before(:each) do @user = create(:user) login_user end ``` Note that login\_user doesn't need any arguments if you have an `@user` object with the password 'secret'.
68,138,677
I was wondering how I can count the number of unique words that I have in a list from a specific data frame. For example, let's say I have a list = `['John','Bob,'Hannah']` Next, I have a data frame with a column called sentences ``` df = ['sentences'] 0 Bob went to the shop 1 John visited Hannah 2 Hannah ate a burger ``` I want the output to be: ``` John 1 Bob 1 Hannah 2 ``` How can I count the unique names in any given sentence in any row in a dataset?
2021/06/26
[ "https://Stackoverflow.com/questions/68138677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16319156/" ]
You can use `Series.str.contains` and call the `sum` to get the number of occurances of a word in the given column, just iterate over the list for all the substrings and do the same for each word, store the result as dictionary. ```py list1 = ['John','Bob','Hannah'] output = {} for word in list1: output[word] = df['sentences'].str.contains(word).sum() ``` **OUTPUT:** ```py {'John': 1, 'Bob': 1, 'Hannah': 2} ``` You can even use it in a dictionary comprehension: ```py >>> {word: df['sentences'].str.contains(word).sum() for word in list1} {'John': 1, 'Bob': 1, 'Hannah': 2} ``` **PS:** If a word/substring is present multiple time in the same row of the given column, the above method will count those multiple occurrences as 1, if you want to get multiple counts in that case, you can implement the same logic for each cell value
7,737,028
I need help in a Math logic issue. Let say I have an object that can be manipulate (move) by user. After the user moved the object I would like the object to continue moving and decelerate to a stop. Example, when a user move an object from point A to B with a total distance of 100pixel in X axis, after user release a finger, I want to let the object continue moving and decelerate to a stop from point B to point C. So how can I calculate the new distance of point C if I set the time for it to decelerate and stop in 2sec? Thank you!
2011/10/12
[ "https://Stackoverflow.com/questions/7737028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986916/" ]
d = ½at² + vit + d0 d0 is the point at which the user "let go". Calculate vi from the motion before letting go. Set a to something negative; you'll have to fiddle with this to get it to feel right. Increment t from 0 through 2. d is where the object will end up. Remember that a and vi are **vectors** pointing in opposite directions, and that d0 and d are **points**.
797,466
Sorry if this is a noob question (this isn't my normal area) but I need to check something and my Google-fu is failing me. I have a software build machine (not a VM) running Windows Server 2012 R2 Standard that recently started performing very slowly. (A normal build usually completes in under 30 minutes but was now aborting after 5.5 hours. And the server itself would sometimes momentarily disappear off of the network.) Logging in, I noticed in Task Manager that the CPU (Intel Xeon CPU E5-1410 0 @ 2.8GHz) had a constant speed of 0.14GHz while the utilization bounced between 1-5% (memory was at 20% and there was plenty of free space on the C drive). This situation lasted four days and then improved by itself. It now has a constant speed of 1.18GHz while the utilization occasional peaks to 30%. My IT guys are from an outsourced company and say the slow down was due to SQL Server on this machine (even though we only use this instance as part of the build process and we stopped all jobs). They say there is nothing wrong. (a) Does the explanation make sense? (b) Why doesn't Task Manager (on a non-VM) report the speed at 2.8GHz? (c) Should I be worried?
2016/08/17
[ "https://serverfault.com/questions/797466", "https://serverfault.com", "https://serverfault.com/users/371054/" ]
I have Windows 10 and makecert.exe is in "c:\Program Files (x86)\Windows Kits\10\bin\x64" . You can download the SDK from <https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk> .
198,714
Consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. We are interested in computing the exact expected minimum [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between any pair. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. Task ==== Given an input n between 2 and 10, inclusive, consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. Output the exact expected minimum Hamming distance between any pair. Output should be given as a fraction. Your code should run in [TIO](https://tio.run/#) without timing out.
2020/01/31
[ "https://codegolf.stackexchange.com/questions/198714", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
[Pari/GP](http://pari.math.u-bordeaux.fr/), ~~92~~ 90 bytes =========================================================== 2 bytes saved thanks to @Nicolas! ``` n->sum(a=0,n,sum(b=0,n-a,sum(c=0,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*min(a+b,min(a+c,b+c)))))/4^n ``` [Try it online!](https://tio.run/##JcpBCsMwDATAr8Q9KY2EEmiPzlMKksDBh6jGbd/vxokOu8OiIjXTVlqKzWn9/HaQOKNjl3aRnLbLpOiBJbAGtsBwTmRjuO/ZQSbFqw11srEfP17e0ruCxwWfM5aa/Qs@3AZaj0jgx1P7Aw "Pari/GP – Try It Online") $$ f(n) = \frac{1}{4^n} \sum\_{\substack{a+b+c+d=n\\a,b,c,d\geq 0}} \binom{n}{a,b,c,d}\min(a+b,a+c,b+c)$$ A more direct brute force approach may be shorter in some languages, but I'm not sure if that's true for Pari. Anyway, it's a shame that Pari's `min` only accepts two arguments. I can avoid the `min` and be about 6 times faster, but the compensating additional code makes it longer. Maybe in another language this is the shorter way. And maybe it is possible to simplify further and get rid of the innermost sum. ``` n->sum(a=0,n,sum(b=a,n-a,sum(c=b,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*(a+b)*6/(1+(a==b)+(b==c))!)))/4^n ``` [Try it online!](https://tio.run/##HYxBCsMwDAS/EvUkxRZKoO1NeUpBNrjkUNW47ftdJ5dhWHa3Wtv5WXvR7rx9fi80XaLHw5JadLbTs6bDeRDEQBJIBsEz4kwwo4VE811wDeNCE4Wx10wERCTXh/fybui6xtsSa9v9iz5dJt4GCvoo9T8 "Pari/GP – Try It Online")
19,663,048
Hello I have a page where the code was working perfectly that would launch a video when an an element with ".onclick" is assigned. Howvever it only seems to work in Chrome. There was even an instance when one page's video would work (in all browsers) but now neither of them work. This works perfectly fine in Chrome though. I'm figuring I've messed up somewhere in my code and since FF is the most strict of browser's is the reason it won't play (oddly in IE as well). Any help would be appreciated. Thanks.
2013/10/29
[ "https://Stackoverflow.com/questions/19663048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2554449/" ]
Care to share your code because I cannot seem to get it to work in FF. Works great in other browsers though. Here is the code I am using. JS ``` var video = document.getElementById('video'); video.addEventListener('click',function(){ video.play(); },false); ``` HTML ``` <video src="your_video" width="250" height="50" poster="your_image" onclick="this.play();"/></video> ```
40,749,024
Please help me with the query Below are the table and requirement details [![enter image description here](https://i.stack.imgur.com/ux4O6.png)](https://i.stack.imgur.com/ux4O6.png)
2016/11/22
[ "https://Stackoverflow.com/questions/40749024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6874511/" ]
Case statement constructs one variable. For your example you can try this, with one statement of Case : ``` data example; input x $; datalines; A A A B B ; run; proc sql; create table make_two_from_one_2 as select * , case when x = 'A' then 'Result1A,Result2A' when x = 'B' then 'Result1B,Result2B' else 'Error' end as thing0 from example ; quit; data example1(drop=thing0); set make_two_from_one_2; thing1=scan(thing0,1,','); thing2=scan(thing0,2,','); run; ```
16,006
From <http://en.wikipedia.org/wiki/Mutant_%28fictional%29#DC_Comics> > > Mutants play a smaller, but still substantial role in DC Comics > > > However, that particular Wiki article only mentions very few mutants (Captain Comet, and a couple of Batman adversaries), neither of whom strike me as important enough to warrant "**substantial**" role. Was that expression inaccurate? Or are there really mutants who play genuinely substantial role in DC universe?
2012/05/03
[ "https://scifi.stackexchange.com/questions/16006", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/976/" ]
The issue at hand is the DC Universe's definition of mutant. Finishing off your quote: > > DC Comics **does not make a semantic or an abstract distinction between humans (or superheroes/villains) born with mutations making them different from humans mutated by outside sources**. > > > This is to say by DC standards, Spider-man is a mutant, not a mutate. This opens up our definition and the number of applicable characters. > > Also characters who were transformed through radiation or a mutagenic gas are sometimes identified as mutants instead of Marvel's term, 'mutates'. > > > All humans with powers are simply referred to, and treated as, one group collectively known as *metahumans*. The term mutant does still exist for humans born with actual powers instead of attaining them. > > > Here is a handy picture for DC supers: ![enter image description here](https://i.stack.imgur.com/BRAAq.jpg) And for Marvel: ![enter image description here](https://i.stack.imgur.com/jMTta.jpg) So anyone who's been 'mutated' by an external force would be considered a mutant in their lexicon. For instance, *The Flash* might be considered a mutant, as the chemicals he was exposed to mutated him. Because of the huge overlap with metahumans though, and being the more general case, they're often just called meta humans.
20,131,226
I am parsing XML in PHP with SimpleXML and have an XML like this: ``` <xml> <element> textpart1 <subelement>subcontent1</subelement> textpart2 <subelement>subcontent2</subelement> textpart3 </element> </xml> ``` When I do `$xml->element` it naturally gives me the whole element, as in all three textparts. So if I parse this into an array (with a `foreach` for the children) I get: ``` 0 => textpart1textpart2textpart3, 1 => subcontent1, 2 => subcontent2 ``` I need a way to parse the `<element>` node so that each textpart that stops at, or begins after a subelement is treated as its own element. As a result I am looking for an ordered list that could be express in an array like this: ``` 0 => textpart1, 1 => subcontent1, 2 => textpart2, 3 => subcontent2, 4 => textpart3 ``` Is that possible without altering the XML file? Thanks in advance for any hints!
2013/11/21
[ "https://Stackoverflow.com/questions/20131226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1648520/" ]
As others have said, SimpleXML doesn't have any support for accessing individual text nodes as separate entities, so you will need to supplement it with some DOM methods. Thankfully, you can switch between the two at will using [`dom_import_simplexml`](http://php.net/dom_import_simplexml) and [`simplexml_import_dom`](http://php.net/manual/en/function.simplexml-import-dom.php). The key pieces of DOM functionality you need are: * the DOMElement->childNodes member variable for accessing all nodes directly under a particular element as an iterable list * the DOMNode->nodeType variable for determining if a particular child is a text node or an element * the DOMNode->nodeValue variable to get the actual text Given those, you can write a function which returns an array with a mixture of SimpleXML objects for child elements, and strings for child text nodes, something like this: ``` function get_child_elements_and_text_nodes($sx_element) { $return = array(); $dom_element = dom_import_simplexml($sx_element); foreach ( $dom_element->childNodes as $dom_child ) { switch ( $dom_child->nodeType ) { case XML_TEXT_NODE: $return[] = $dom_child->nodeValue; break; case XML_ELEMENT_NODE: $return[] = simplexml_import_dom($dom_child); break; } } return $return; } ``` In your case, you need to recurse down the tree, which makes it a little confusing if you mix DOM and SimpleXML as you go, so you could instead write the recursion entirely in DOM and convert the SimpleXML object before running it: ``` function recursively_find_text_nodes($dom_element) { $return = array(); foreach ( $dom_element->childNodes as $dom_child ) { switch ( $dom_child->nodeType ) { case XML_TEXT_NODE: $return[] = $dom_child->nodeValue; break; case XML_ELEMENT_NODE: $return = array_merge($return, recursively_find_text_nodes($dom_child)); break; } } return $return; } $text_nodes = recursively_find_text_nodes(dom_import_simplexml($simplexml->element)); ``` [Here's a live demo of that last function.](http://codepad.viper-7.com/BrIjY7)
12,013,956
I've got a container div with a bunch of scrollable content (for the record I'm using iScroll - if that changes the solution). When I scroll to the top I want to load content above the current scroll position. If I simply prepend the div using jQuery "prepend();" the contents in my scrollable area shift down. Ideally we'd want to keep the current content in the frame and have the scrollable area grow upwards above the content. Any thoughts? Thanks!
2012/08/17
[ "https://Stackoverflow.com/questions/12013956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1118481/" ]
According to [the iScroll website](http://cubiq.org/iscroll), it has a method called `scrollToElement`: > > **`scrollToElement(el, runtime)`**: scrolls to any element inside the scrolling area. `el` must be a CSS3 selector. Eg: `scrollToElement("#elementID", '400ms')` > > > If you always prepend a fixed amount of `div`s (e.g. always a single `div`), I imagine you could use it to scroll to (e.g.) the second element right after you've prepended the new content: ``` // ... (prepend new content) myScroll.scrollToElement('#scroller :nth-child(2)', '0ms'); ``` I haven't tried this, so please let us know if this works for you.
29,723,423
Today I made a small typo in my program, and was wandering why I wasn't getting any output, although the program compiled fine. Basically it reduces to this: ``` #include <iostream> int main() { std::cout < "test"; // no << but < } ``` I have absolutely no idea what kind of implicit conversion is performed here so the program still compiles (both g++4.9.2 and even g++5). I just realized that clang++ rejects the code. Is there a conversion to `void*` being performed (cannot think of anything else)? I remember seeing something like this, but I thought it was addressed in g++5, but this doesn't seem to be the case. **EDIT:** I was not compiling with `-std=c++11`, so the code was valid in pre-C++11 (due to conversion to `void*` of `ostream`). When compiling with `-std=c++11` g++5 rejects the code, g++4.9 still accepts it.
2015/04/18
[ "https://Stackoverflow.com/questions/29723423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093378/" ]
Yes, the compiler is converting `cout` to a `void*`. If you use the `-S` switch to get the code's disassembly, you'll see something like this: ``` mov edi, OFFSET FLAT:std::cout+8 call std::basic_ios<char, std::char_traits<char> >::operator void*() const cmp rax, OFFSET FLAT:.LC0 setb al test al, al ``` Which makes it clear that `operator void*` is the culprit. Contrary to what Bill Lynch said, I'm able to reproduce it with `—std=c++11` on [Compiler Explorer](http://goo.gl/RgweWS). However, it does appear to be an implementation defect, since C++11 should have replaced `operator void*` with `operator bool` on `basic_ios`.
14,832,221
I have a DF where I want to add a new variable called "B" into the 2nd position. ``` A C D 1 1 5 2 2 3 3 7 3 6 2 3 4 6 4 8 5 1 1 2 ``` Anyone have an idea?
2013/02/12
[ "https://Stackoverflow.com/questions/14832221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2061634/" ]
The easiest way would be to add the columns you want and then reorder them: ``` dat$B <- 1:5 newdat <- dat[, c("A", "B", "C", "D")] ``` Another way: ``` newdat <- cbind(dat[1], B=1:5, dat[,2:3]) ``` If you're concerned about overhead, perhaps a `data.table` solution? (With help from [this answer](https://stackoverflow.com/a/12232123/1465387)): ``` library(data.table) dattable <- data.table(dat) dattable[,B:=1:5] setcolorder(dattable, c("A", "B", "C", "D")) ```
30,072
So far in Dead Island I've noticed white, green, blue, and purple items. These seem to indicate different rarities, similar to the classification system used in Borderlands, but I don't know what these colors actually mean. Is green more rare than blue? What are the different rarity colors?
2011/09/10
[ "https://gaming.stackexchange.com/questions/30072", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/207/" ]
So far, here are all the colors I've found ordered in quality (based on overall stats when compared to one of lesser color and also how often I see weapons of that color): white->green->blue->purple->orange The in game text during loading says that some of the quest rewards gives you unique weapons, and (assuming Gabriel's Sledgehammer is a unique), it is still an orange colored weapon. So I'm going to assume that even unique weapons are orange. I've also found a Master Chef, which was also orange. [This link](http://www.g4tv.com/thefeed/blog/post/716093/dead-island-weaponsmods-location-guide/) seems to back up my answer.
2,436,502
Is it possible, in the `expr` expression of the `with()` function, to access the `data` argument directly? Here's what I mean conceptually: ``` > print(df) result qid f1 f2 f3 1 -1 1 0.0000 0.1253 0.0000 2 -1 1 0.0098 0.0000 0.0000 3 1 1 0.0000 0.0000 0.1941 4 -1 2 0.0000 0.2863 0.0948 5 1 2 0.0000 0.0000 0.0000 6 1 2 0.0000 0.7282 0.9087 > with(df, subset(.data, select=f1:f3)) # Doesn't work ``` Of course the above example is kind of silly, but it would be handy for things like this: ``` with(subset(df, f2>0), foo(qid, vars=subset(.data, select=f1:f3))) ``` I tried to poke around with `environment()` and `parent.frame()` etc., but didn't come up with anything that worked. Maybe this is really a question about `eval()`, since that's how `with.default()` is implemented.
2010/03/12
[ "https://Stackoverflow.com/questions/2436502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169947/" ]
Using `parent.frame()`: ``` # sample data: set.seed(2436502) dfrm <- data.frame(x1 = rnorm(100), x2 = rnorm(100), g1 = sample(letters, 100, TRUE)) # how to use it: with(subset(dfrm, x1<0), { str(parent.frame(2)$data) "Hello!" }) # 'data.frame': 47 obs. of 3 variables: # $ x1: num -0.836 -0.343 -0.341 -1.044 -0.665 ... # $ x2: num 0.362 0.727 0.62 -0.178 -1.538 ... # $ g1: Factor w/ 26 levels "a","b","c","d",..: 11 4 15 19 8 13 22 15 15 23 ... ``` ### How the magic works Using `ls()` you can inspect `parent.frames`: ``` with(subset(dfrm, x1<0), { print(ls()) print(ls(parent.frame(1))) print(ls(parent.frame(2))) print(ls(parent.frame(3))) }) # [1] "g1" "x1" "x2" # [1] "enclos" "envir" "expr" # [1] "data" "expr" # [1] "dfrm" ``` As you can see: * `parent.frame(3)` is base environment (in this case), * `parent.frame(2)` is environment of `subset` function * `parent.frame(1)` is environment of `{` function (see `?Paren`)
4,836,038
I need to decode: ``` file://localhost/G:/test/%E6%B0%97%E3%81%BE%E3%81%90%E3%82%8C%E3%83%AD%E3%83%9E%E3%83%B3%E3%83%86%E3%82%A3%E3%83%83%E3%82%AF.mp3 ``` into ``` file://localhost/G:/test/気まぐれロマンティック.mp3 ``` How to do it in Delphi prior 2009 (I use Delphi 2006) ?
2011/01/29
[ "https://Stackoverflow.com/questions/4836038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193431/" ]
The Indy TIdURI class in IdURI unit contains UrlDecode / UrlEncode functions. You could try it with a recent version (10.5.8) of Indy, which has encoding parameters: ``` class function TIdURI.URLDecode(ASrc: string; AByteEncoding: TIdTextEncoding = nil {$IFDEF STRING_IS_ANSI}; ADestEncoding: TIdTextEncoding = nil{$ENDIF} ): string; ```
38,353,992
So I am currently reading through [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882) and I really like the idea of super small functions that each tell their own "story". I also really like the way he puts how code should be written to be read in terms of "TO paragraphs", which I've decided to kind of rename in my head to "in order to" Anyway I have been refactoring alot of code to include more meaningful names and to make the flow in which it will be read a little better and I have stumbled into something that I am unsure on and maybe some gurus here could give me some solid advice! I know that code-styles is a highly controversial and subjective topic, but hopefully I wont get reamed out by this post. Thanks everyone! PSA: I am a noob, fresh out of College creating a web app using the MEAN stack for an internal project in an internship at the moment. Clean Code refactor ``` //Modal Controller stuff above. vm.task is an instance variable vm.task = vm.data.task; castTaskDataTypesForForm(); function castTaskDataTypesForForm() { castPriorityToInt(); castReminderInHoursToInt(); castDueDateToDate(); getAssigneObjFromAssigneeString(); } function castPriorityToInt() { vm.task.priority = vm.task.priority === undefined ? 0 : parseInt(vm.task.priority); } function castReminderInHoursToInt() { vm.task.reminderInHours = vm.task.reminderInHours === undefined ? 0 : parseInt(vm.task.reminderInHours); } function castDueDateToDate() { vm.task.dueDate = new Date(vm.task.dueDate); } function getAssigneObjFromAssigneeString() { vm.task.assignee = getUserFromId(vm.task.assignee); } ``` Possibly better refactor? / My question ---------------------------- ``` //Modal Controller stuff above. vm.task is an instance variable vm.task = vm.data.task; castTaskDataTypesForForm(); function castTaskDataTypesForForm() { castPriorityToInt(); castReminderInHoursToInt(); castDueDateToDate(); getAssigneObjFromAssigneeString(); function castPriorityToInt() { vm.task.priority = vm.task.priority === undefined ? 0 : parseInt(vm.task.priority); } function castReminderInHoursToInt() { vm.task.reminderInHours = vm.task.reminderInHours === undefined ? 0 : parseInt(vm.task.reminderInHours); } function castDueDateToDate() { vm.task.dueDate = new Date(vm.task.dueDate); } function getAssigneObjFromAssigneeString() { vm.task.assignee = getUserFromId(vm.task.assignee); } } ```
2016/07/13
[ "https://Stackoverflow.com/questions/38353992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370270/" ]
You should define default router for `''` like: ``` const routes: RouterConfig = [ { path: '', component: Home }, { path: 'page2', component: Page2 } ]; ``` Or by using redirect: ``` const routes: RouterConfig = [ { path: '', redirectTo: '/page2', pathMatch: 'full' }, { path: 'page2', component: Page2 } ]; ``` See also the example from angular2 documentation * <https://angular.io/docs/ts/latest/guide/router.html#!#redirect>
855,289
How to find the limit $$\lim\_{x \rightarrow \infty} x^{2/3} -(x^2+1)^{1/3}$$ I've tried: $$\lim x^{2/3} -(x^2+1)^{1/3} = \lim x^{2/3} \cdot \lim \left[1 - \left(1+\frac{1}{x^2}\right)^{1/3} \right] = \infty \cdot 0$$ Any help, please?
2014/07/03
[ "https://math.stackexchange.com/questions/855289", "https://math.stackexchange.com", "https://math.stackexchange.com/users/161448/" ]
Use AM > HM on $\frac{a+b+c}{a+b}, \frac{a+b+c}{b+c}$ and $\frac{a+b+c}{c+a}$.
47,451
In Direct3D 9 effect files you can write a sampler state that specifies a texture variable to use, like ``` Texture2D g_texSkyDome; SamplerState g_samplerSkyDome { Texture = <g_texSkyDome>; // ...other sampler states... }; ``` Using the [ID3DXEffect API](http://msdn.microsoft.com/en-us/library/bb205676.aspx), is it possible to extract the texture variable assigned to a given sampler state variable? I've been searching the docs but can't find anything about this.
2013/01/15
[ "https://gamedev.stackexchange.com/questions/47451", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/9894/" ]
I still haven't found an "official" way to do this via the API. In fact, there is no provision for extracting any of the contents of a SamplerState block - either the texture or any of the state settings. There are some hacky, roundabout ways one could do this: 1. You could give each sampler state an annotation that names the corresponding texture variable, or vice versa. A variant on this approach is to set up a naming convention, e.g. the texture is named `texFoo` and sampler `samplerFoo`. Of course, nothing would prevent these from getting out of sync with the actual texture variable assignments. 2. Scan the HLSL file for `SamplerState` definitions and parse them yourself. You'd probably want to run it through the preprocessor first. The parser doesn't have to be *too* complicated if you make a few simplifying assumptions, e.g. that the word "SamplerState" never occurs anywhere but the definition of a sampler variable. 3. You could create a dummy texture, assign it to a texture variable with `ID3DXBaseEffect::SetTexture`, then run through all the texture units with `IDirect3DDevice9::GetTexture` and see which one ended up with your dummy texture. You could then correlate this with the sampler index obtained by `ID3DXConstantTable::GetSamplerIndex` from each sampler variable in the effect. You could also use `IDirect3DDevice9::GetSamplerState` to get the rest of the sampler state.
2,720,618
I know it's very basic question and hope not so important, but i want to know the answer, please don't suggest only refer links. we all daily face `<input>` type tag and their attributes (`type, class, id, value, name, size, maxlength, tabindex etc..`), I just want to know * is there any specific order required for attributes in `<input>` tag or can we use any order? * if there an order then what is it?
2010/04/27
[ "https://Stackoverflow.com/questions/2720618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155861/" ]
Already been answered, but my full and expanded answer is: * There is no predefined order for the attributes in terms of passing w3c validation... it's completely up to you. However, you should introduce your own standard and stick to it. If there are multiple coders working on the application they should all stick to the same standard. If you are a team leader, web-dev business owner, manager, etc, it is your responsibility to encourage (and enforce) a culture that uses this standard. When doing code reviews the attribute order should be checked, and anything that fails you should make the coder responsible fix it up... they'll only muck it up once or twice if they know they'll have to rewrite their code!!! And why all this fuss and bother over attribute order? * This will increase code development and debugging speed. * It makes code more readable * It encourages the coders (or you) to pay attention to the little details * It helps to fosters an environment of "accountability for your own code" My personal preference is: 1. type (so you can instantly see what it is) 2. id 3. class (I like to keep 2 and 3 together as they are the most common js/jQuery selectors) 4. name 5. value (I like to keep 4 and 5 next to each other so you can quickly reference what input it is and it's value). 6. All others (like checked, max-size, etc) 7. style 8. tabindex (I like 7 and 8 to be at the end as it's "non-relevant", in terms of the actual functionality, they are more styling/usability stuff, keep 'em out of the way!
27,736,680
How can I transform the string "Test(5)" into "Test\(5\)" dynamically? (JQuery or Javascript) I have tried this but with no success ``` var string = "Test(5)"; string = string.replace("(","\("); string = string.replace(")","\)"); console.log(string); ``` <http://jsfiddle.net/mvehkkfe/>
2015/01/02
[ "https://Stackoverflow.com/questions/27736680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3115251/" ]
I assume you meant > > replace the string "Test(5)" into "Test\(5\)" > > > In which case: ``` var string = "Test(5)"; string = string.replace("(","\\("); string = string.replace(")","\\)"); console.log(string); ``` Escape the backslash
58,701,672
The `create_mileage(exclude=None)` function creates a new two-dimensional dictionary with data from the three-dimensional `VEHICLES` dictionary and the default `"unknown"` value. The `exclude` parameter can contain a dictionary with key-value pairs to be excluded from the new dictionary. Unfortunately this does not work like this. Code: ``` VEHICLES = {"car": { "VW Polo": {"power": 75, "color": "blue"}, "BMW 5 series": {"power": 400, "color": "black"}}, "truck": { "MAN TGL": {"power": 200, "color": "red"}, "Mercedes-Benz Actros": {"power": 500, "color": "white"}}, "bus": { "Mercedes-Benz Citaro": {"power": 300, "color": "yellow"}, "Solaris Vacanza 13": {"power": 400, "color": "green"}} } def create_mileage(exclude=None): result = dict() for vehicle_type, vehicle_model in VEHICLES.items(): if {vehicle_type: vehicle_model} not in exclude.items(): # Doesn't work result[vehicle_type] = dict.fromkeys(vehicle_model, "unknown") return result print(create_mileage({"car": "VW Polo", "truck": "Mercedes-Benz Actros"})) ``` The output should be as follows... ``` {'car': {'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}} ``` ...but it is as follows. ``` {'car': {'VW Polo': 'unknown', 'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown', 'Mercedes-Benz Actros': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}} ``` What needs to be changed to make the code work as intended?
2019/11/04
[ "https://Stackoverflow.com/questions/58701672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7481773/" ]
`items()` returns a `tuple`, not a `dict`: ``` def create_mileage(exclude=None): result = dict() eItems = exclude.items() for vehicle_type, vehicle_model in VEHICLES.items(): if (vehicle_type, vehicle_model) not in eItems: result[vehicle_type] = dict.fromkeys(vehicle_model, "unknown") return result print(create_mileage({"car": "VW Polo", "truck": "Mercedes-Benz Actros"})) ``` Result: > > {'car': {'VW Polo': 'unknown', 'BMW 5 series': 'unknown'}, 'truck': {'MAN TGL': 'unknown', 'Mercedes-Benz Actros': 'unknown'}, 'bus': {'Mercedes-Benz Citaro': 'unknown', 'Solaris Vacanza 13': 'unknown'}} > > >
2,602,791
I'm trying to figure out the best way to use agents to consume items from a Message Queue (Amazon SQS). Right now I have a function (process-queue-item) that grabs an items from the queue, and processes it. I want to process these items concurrently, but I can't wrap my head around how to control the agents. Basically I want to keep all of the agents busy as much as possible without pulling to many items from the Queue and developing a backlog (I'll have this running on a couple of machines, so items need to be left in the queue until they are really needed). Can anyone give me some pointers on improving my implementation? ``` (def active-agents (ref 0)) (defn process-queue-item [_] (dosync (alter active-agents inc)) ;retrieve item from Message Queue (Amazon SQS) and process (dosync (alter active-agents dec))) (defn -main [] (def agents (for [x (range 20)] (agent x))) (loop [loop-count 0] (if (< @active-agents 20) (doseq [agent agents] (if (agent-errors agent) (clear-agent-errors agent)) ;should skip this agent until later if it is still busy processing (not sure how) (send-off agent process-queue-item))) ;(apply await-for (* 10 1000) agents) (Thread/sleep 10000) (logging/info (str "ACTIVE AGENTS " @active-agents)) (if (> 10 loop-count) (do (logging/info (str "done, let's cleanup " count)) (doseq [agent agents] (if (agent-errors agent) (clear-agent-errors agent))) (apply await agents) (shutdown-agents)) (recur (inc count))))) ```
2010/04/08
[ "https://Stackoverflow.com/questions/2602791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126617/" ]
``` (let [switch (atom true) ; a switch to stop workers workers (doall (repeatedly 20 ; 20 workers pulling and processing items from SQS #(future (while @switch (retrieve item from Amazon SQS and process)))))] (Thread/sleep 100000) ; arbitrary rule to decide when to stop ;-) (reset! switch false) ; stop ! (doseq [worker workers] @worker)) ; waiting for all workers to be done ```
26,487,801
**What's been done so far:** * I was on Django 1.5 and upgraded to 1.6 (cannot go higher as we are on Python 2.6) and this did not solve the problem. * I have researched this issue to death and cannot seem to find a definite answer. Looking through the Django Project Bug Tracker, I have seen similar issues but none seem to fit my particular case * I have resolved the problem in the past using a raw SQL call to replace for example `affpart.damage_types.all()` with a custom function but this is starting to happen more frequently now and is becoming a real pain. **Description:** I have two Django apps under one project. One of the apps makes use of models in another app using a many-to-many relationship. This has been working smoothly for months, and in fact it works fine on my production machine but fails on my development machine. The scenario lately has been that I am asked to add a new feature and when I start to work on it I get a `FieldError` in related code which I haven't even touched. The offending line of code for this latest issue is: `for dt in affpart.damage_types.all()` The error is: ``` Cannot resolve keyword u'affectedpart' into field. Choices are: cgs_damage_code, description, id, reg_exp, sti ``` The error occurs in the bowels of Django in the `query.py` module. From a high-level, this error occurs when I am trying to use a Many-to-many between models in different Django apps. For example, an affected part can have more than one type of damage and a damage type can be found on different affected parts. The two apps are: `trending` and `sitar` `sitar` was built first and has the models that I want to use from trending. In `trending`, my `models.py` file has an `AffectedPart` model something like this: ``` from sitar.models import (Part, DamageType, Aircraft) # this model is in trendin.models class AffectedPart(models.Model): res = models.ForeignKey(Res, null=True) arising = models.ForeignKey(Arising, null=True) aircraft = models.ForeignKey(Aircraft) # filled out automatically only if part to Damage/Repair type matching done maintenance_phase = models.CharField(max_length=10, choices=MAINTENANCE_PHASE_CHOICES) occurrence_date = models.DateField() partnumber = models.ForeignKey(Part) damage_types = models.ManyToManyField(DamageType, null=True, blank=True) repair_types = models.ManyToManyField(RepairType, null=True, blank=True) def __unicode__(self, ): if self.res: parent = self.res.number else: parent = str(self.arising) return '{0} - {1}'.format(self.partnumber.number, parent) # The following models are in sitar.models class Part(models.Model): ''' This model is used to create pick-lists so the user can associate one or more applicable parts from a pre-defined list to a tracked item. It will also allow for regular CRUD functionality which is implemented by taking advantage of the Django admin interface. ''' # Added to associate a zone with a part zones = models.ManyToManyField("Zone", null=True, blank=True) number = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=100, blank=True) comments = models.TextField(blank=True) material = models.CharField(max_length=100, blank=True) class Meta: ''' Order by part number field (ascending) when presenting data ''' ordering = ['number'] def __unicode__(self): ''' Return unicode description of a part instance ''' if self.description: return '%s -- %s' % (self.number, self.description) else: return self.number def get_encoded_part_number(self): ''' This method will remove any '/' in part numbers and replace them with '~' so that they can be used in URLs. ''' return self.number.replace('/','~') class DamageType(models.Model): description = models.CharField(max_length=50, unique=True) # a regular expression to account for possible spelling mistakes when # querying the database reg_exp = models.CharField(max_length=50, blank=True) # Added to provide damage code for TRENDING cgs_damage_code = models.CharField(max_length=10, blank=True, verbose_name="CGS Damage Code") def __unicode__(self): ''' Return unicode representation of a DamageType instance. ''' return self.description class Meta: ''' Order by description field (ascending) when presenting data ''' ordering = ['description'] def save(self): ''' Override the save method of the DamageType model in order to assign a regexp if one does not exist.''' # if the tracked item does not have a reg_exp just use # the description if not self.reg_exp: self.reg_exp = self.description super(DamageType,self).save() ``` Stack Trace ``` Environment: Request Method: POST Request URL: http://127.0.0.1:8000/trending/trend/ Django Version: 1.6 Python Version: 2.6.7 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'sitar') Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "C:\virtual_env\sitar_env2\lib\site-packages\django\core\handlers\base.py" in get_response 114. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\virtual_env\sitar_env2\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "C:\virtual_env\sitar_env2\cissimp\trending\views.py" in trend 418. list_result = utils.convert_queryset_to_lists(q_results, form) File "C:\virtual_env\sitar_env2\cissimp\trending\utils.py" in convert_queryset_to_lists 918. for dt in affpart.damage_types.all()]), File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\manager.py" in all 133. return self.get_queryset() File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\fields\related.py" in get_queryset 539. return super(ManyRelatedManager, self).get_queryset().using(db)._next_is_sticky().filter(**self.core_filters) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\query.py" in filter 590. return self._filter_or_exclude(False, *args, **kwargs) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 608. clone.query.add_q(Q(*args, **kwargs)) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in add_q 1198. clause = self._add_q(where_part, used_aliases) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in _add_q 1232. current_negated=current_negated) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in build_filter 1100. allow_explicit_fk=True) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in setup_joins 1351. names, opts, allow_many, allow_explicit_fk) File "C:\virtual_env\sitar_env2\lib\site-packages\django\db\models\sql\query.py" in names_to_path 1274. "Choices are: %s" % (name, ", ".join(available))) Exception Type: FieldError at /trending/trend/ Exception Value: Cannot resolve keyword u'affectedpart' into field. Choices are: cgs_damage_code, description, id, reg_exp, sti ``` If anyone has a solution to this or knows of best practices for models in one application having many-to-many relationships with models in another application I would love to hear it. Thanks
2014/10/21
[ "https://Stackoverflow.com/questions/26487801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/898635/" ]
Use [NSSound](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSSound_Class/) instead: Get list of audio devices with `CoreAudio` functions. Then get the devices' unique identifiers: ``` //... address.mSelector = kAudioDevicePropertyDeviceUID; CFStringRef uid = NULL; UInt32 size = sizeof(uid); AudioObjectGetPropertyData(deviceId, &address, 0, NULL, &size, &uid); //... ``` Initialize sound item, set `playbackDeviceIdentifier` property value.
53,783,166
I'm getting an error on iOS only: ``` TypeError: undefined is not an object (evaluating 'this._callListeners.bind') This error is located at: in DrawerLayout (at DrawerView.js:161) ... ``` Project dependencies: ``` "dependencies": { "@babel/runtime": "7.2.0", "@babel/plugin-proposal-async-generator-functions": "7.2.0", "@babel/plugin-proposal-class-properties": "7.2.1", "@babel/plugin-proposal-object-rest-spread": "7.2.0", "babel-preset-expo": "5.0.0", "expo": "31.0.2", "expo-cli": "2.5.0", "native-base": "2.8.1", "react": "16.6.3", "react-native": "0.57.8", "react-redux": "6.0.0", "react-navigation": "3.0.8", "react-native-vector-icons": "6.1.0", "redux": "4.0.1" } ``` This started when I began using react-navigation; but works fine on Android. Here's the code where we're using react-navigation, this is the main app the imports include the Home and Settings screens: ``` //imports... const routes = { Home: Home, Settings: Settings }; const AppNavigator = createDrawerNavigator(routes); const AppContainer = createAppContainer(AppNavigator); export default class App extends React.Component { state = {} render() { if (this.state.isReady) { return ( <AppContainer/> ); } else { return (<Container><Spinner/></Container>); } } componentWillMount() { this._loadAssets(); } async _loadAssets() { await Expo.Font.loadAsync({ Roboto: require("native-base/Fonts/Roboto.ttf"), Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf") }); this.setState({ isReady: true }); } } ```
2018/12/14
[ "https://Stackoverflow.com/questions/53783166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366972/" ]
The [`calloc`](https://en.cppreference.com/w/c/memory/calloc) sets all bytes of the allocated memory to zero. As it happens, that's also the valid [IEEE754](https://en.wikipedia.org/wiki/IEEE_754) (which is the most common format for floating point values on computers) representation for `0.0`. IIRC there's no part of the C specification that requires an implementation to use IEEE754, so to be picky it's not portable. In reality though, it is (and if you're ever going to work on a non-IEEE754 system then you should have gathered enough experience to already know this and how to solve such problems). Also note that this also is valid for pointers. On all systems you're likely to come in contact with, a null pointer should be equal to `0`. But there might be systems where it isn't, but if you work on such systems you should already know about it (and if you use `NULL` then it should not be a problem).
72,523,117
Say I have a dataframe that ***looks*** like this (wasn't sure how to actually rep. this data, given its size): ``` minutes <- seq(0,585, by = 15) salinity <- as.numeric(sample(x = 29:55, size = 40, replace = TRUE)) site <- c(1, 2, 3, ...etc.) year <- c(2020, 2019, ...etc.) season <- c("Dry", "Wet") df <- cbind.data.frame(year, season, site, minutes, salinity) > head(df) year season site minutes salinity 1 2020 DRY 1 0 54 2 2020 DRY 1 15 39 3 2020 DRY 1 30 44 4 2020 DRY 1 45 54 5 2020 DRY 1 60 43 6 2020 DRY 1 75 40 ``` and in reality it has +800k rows of continuously measured data in 15 min. increments for the past couple of years at "n" sites. I'm attempting to make a matrix/table like this in R (that was originally created in Excel). Color is not important, I only hope to re-create the table itself. The values in this plot are the maximum/highest number of minutes where a range of values were consistently measured (ex. For each site, season, and year, create a table that shows the longest lasting run of continuous minutes where the values stayed between 40-50). [![enter image description here](https://i.stack.imgur.com/nXHga.png)](https://i.stack.imgur.com/nXHga.png)
2022/06/06
[ "https://Stackoverflow.com/questions/72523117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16401542/" ]
This error comes from Vue Language Features (Volar). [issue page](https://github.com/johnsoncodehk/volar/issues/1405) Rolling back the volar plug-in to version 0.36.1 can solve this problem.
8,595,332
So my code was working before. I don't know what I did for this to happen and I can't seem to fix it. I've seen people say to reset the ModelState. ( ModelState.Clear(); ) But that didn't help. Also, it doesn't help that I'm still fairly new to MVC. Any help would be appreciated. Thanks. Controller: ``` public ActionResult Create() { ActiveDirectoryModel adm = new ActiveDirectoryModel(); ViewBag.notifyto = adm.FetchContacts(); var model = Populate(); return View(model); } [HttpPost] public ActionResult Create(CreateViewModel model) { if (ModelState.IsValid) { model.leaf.Date = DateTime.Now.Date; model.leaf.Category = model.CategoryId; model.leaf.SubCategory = model.SubCategoryId; model.leaf.AssignedTo = model.AssignedToId; model.leaf.CoAssignedTo = model.CoAssignedToId; model.leaf.Status = model.StatusId; model.leaf.Priority = model.PriorityId; //model.lead.Parent = model.ParentID; db.LeafItems.AddObject(model.leaf); db.SaveChanges(); return RedirectToAction("Index"); } return View(model); } public CreateViewModel Populate() { ActiveDirectoryModel adm = new ActiveDirectoryModel(); var model = new CreateViewModel { AssignedToItems = adm.FetchContacts(), CoAssignedToItems = adm.FetchContacts(), NotifyToItems = adm.FetchContacts(), CategoryItems = from c in new IntraEntities().CategoryItems.ToList() select new SelectListItem { Text = c.Name, Value = c.ID.ToString() }, SubCategoryItems = from sc in new IntraEntities().SubCategoryItems.ToList() select new SelectListItem { Text = sc.Name, Value = sc.ID.ToString() }, StatusItems = from s in new IntraEntities().StatusItems.ToList() where s.IsPriority == false select new SelectListItem { Text = s.Name, Value = s.ID.ToString() }, PriorityItems = from p in new IntraEntities().StatusItems.ToList() where p.IsPriority == true select new SelectListItem { Text = p.Name, Value = p.ID.ToString() } }; return model; } ``` View: ``` <div class="createTopInner"> <div class="editor-label"> @Html.LabelFor(model => model.leaf.Category) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryId, Model.CategoryItems, "") @Html.ValidationMessageFor(model => model.leaf.Category) </div> </div> ``` Model: ``` public int CategoryId { get; set; } public IEnumerable<SelectListItem> CategoryItems { get; set; } ```
2011/12/21
[ "https://Stackoverflow.com/questions/8595332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026288/" ]
If your ModelState is not valid on your POST action, you need to repopulate your SelectList properties: ``` if( ModelState.IsValid ) { // save and redirect // ... } // repopulate your SelectList properties: model.CategoryItems = GetCategories(); return View(model); ``` Do not repopulate the entire model because otherwise you could potentially lose any changes that the user made.
2,067,436
Right now, I'm working on a project which requires sequential text key generation. I need to seed the key generator with an integer corresponding to a certain key, which the constructor converts to a key. My key generator overloads the increment operators so that the string is incremented directly, rather than what I had previously been doing, which is incrementing an index value, then converting the index to a key for every key that I wanted to generate. My problem is that I have a limited character set I want to use when generating keys. I have to find the character in the key that I want to increment, find out where it is in my character set, find the next character in the set, then replace the character in the key with the next character in the set. Here is my code: ``` // Not the full charset std::string charset = "abcdefghijklmnopqrstuvwxyz0123456789"; std::string key; key.push_back(charset[0]); for(unsigned int place = 0; place < key.length(); place++) { if(key[place] == charset[charset.length() - 1]) { // Overflow, reset char at place key[place] = charset[0]; if((key.length() - 1) < (place + 1)) { // Carry, no space, insert char key.insert(key.begin(), charset[0]); break; } else { // Space available, increment next char continue; } } else { // Increment char at place key[place] = charset[charset.find(key[place]) + 1]; break; } } ``` In profiling, I found that the search operation is really slowing things down. Is there any faster way of doing this? I thought of creating a linked list out of the character set, but before I do that, I'd like some input on this.
2010/01/14
[ "https://Stackoverflow.com/questions/2067436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136846/" ]
Rather than doing a find, why don't you have a reverse translation array? The array index would be the character, and the value in the array would be its numeric value (or index into the other array). ``` key[place] = charset[reverse_charset[key[place]] + 1]; ```
11,172,620
I am struggling with linking ALAssetsLibrary in my code. I have googled a lot on this and followed more than one tutorial to the last dot yet I am still where I began. ``` Ld /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator/PickThumb.app/PickThumb normal i386 cd "/Users/vedprakash/Documents/XCode Projects/PickThumb" setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/clang -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.0.sdk -L/Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator -F/Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator -filelist /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Intermediates/PickThumb.build/Debug-iphonesimulator/PickThumb.build/Objects-normal/i386/PickThumb.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -Xlinker -no_implicit_dylibs -D__IPHONE_OS_VERSION_MIN_REQUIRED=50000 -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/vedprakash/Library/Developer/Xcode/DerivedData/PickThumb-gmvprlkgmgexedeojbaoeidbadnw/Build/Products/Debug-iphonesimulator/PickThumb.app/PickThumb Undefined symbols for architecture i386: "_OBJC_CLASS_$_ALAssetsLibrary", referenced from: objc-class-ref in PickThumbViewController.o ld: symbol(s) not found for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) ```
2012/06/23
[ "https://Stackoverflow.com/questions/11172620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477296/" ]
You need to add the `AssetsLibrary` framework to the “Link Binary With Libraries” build phase of your `PickThumb` target. [How to "add existing frameworks" in Xcode 4?](https://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4)
14,763,212
Compare const and non-const pointers. Is the comparison legal? Any special care for such comparison. Thanks.
2013/02/07
[ "https://Stackoverflow.com/questions/14763212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2052376/" ]
A pointer to `T` can be implicitly converted into a const pointer to `T`; similarly, a pointer to `T` can be implicitly converted into a pointer to `const T`. The compiler will do either of those conversions, or both, as needed when you try to compare a pointer to a const pointer. There's nothing there that's any more risky than comparing two non-const pointers or two const pointers.
3,804,875
How would you suggest using `AsEnumerable` on a non-generic `IQueryable`? I cannot use the `Cast<T>` or `OfType<T>` methods to get an `IQueryable<object>` before calling `AsEnumerable`, since these methods have their own explicit translation by the underlying `IQueryProvider` and will break the query translation if I use them with a non-mapped entity (obviously object is not mapped). Right now, I have my own extension method for this (below), but I'm wondering if there's a way built into the framework. ``` public static IEnumerable AsEnumerable(this IQueryable queryable) { foreach (var item in queryable) { yield return item; } } ``` So, with the above extension method, I can now do: ``` IQueryable myQuery = // some query... // this uses the built in AsEnumerable, but breaks the IQueryable's provider because object is not mapped to the underlying datasource (and cannot be) var result = myQuery.Cast<object>().AsEnumerable().Select(x => ....); // this works (and uses the extension method defined above), but I'm wondering if there's a way in the framework to accomplish this var result = myQuery.AsEnumerable().Cast<object>().Select(x => ...); ```
2010/09/27
[ "https://Stackoverflow.com/questions/3804875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326518/" ]
Since the interface `IQueryable` inherits from `IEnumerable` why not: ``` IQueryable queryable; IEnumerable<T> = (queryable as IEnumerable).Cast<T>(); ``` **Edit** There are two `Cast<>` extension methods: ``` public static IQueryable<TResult> Cast<TResult>(this IQueryable source) public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) ``` Which one is called is statically decided by the compiler. So casting an `IQueryable` as an `IEnumerable` will cause the second extension method to be called, where it will be treated as an `IEnumerable`.
8,733,999
I have an rss parser as part of my app code, and it is working fine and loading the rss xml file and populating the tableview fine. The problem is with a refresh/reload button, which does reload the rss data, but it APPENDS the new data to the table and the table just grows and grows in size. What the behaviour should do is to clear the old table data and rebuild the table with the new data - so that the table always shows just ONE set of data and doesn't keep growing every time the reload/refresh is pressed. The table build code is as follows: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1]; cell.textLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"date"]; cell.detailTextLabel.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"]; [cell.textLabel setLineBreakMode:UILineBreakModeWordWrap]; [cell.textLabel setNumberOfLines:0]; [cell.textLabel sizeToFit]; [cell.detailTextLabel setLineBreakMode:UILineBreakModeWordWrap]; [cell.detailTextLabel setNumberOfLines:0]; [cell.detailTextLabel sizeToFit]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } ``` And the reload/refresh button code is: ``` - (void)reloadRss { UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator]; [[self navigationItem] setLeftBarButtonItem:barButton]; [barButton release]; [activityIndicator release]; [activityIndicator startAnimating]; [self performSelector:@selector(parseXMLFileAtURL) withObject:nil afterDelay:0]; [newsTable reloadData]; } ``` I have tried to solve this by adding the line: ``` if (stories) { [stories removeAllObjects]; } ``` to the reload section, which I think should work and does clear the table, but the app then crashes the app with an EXC\_BAD\_ACCESS. Any ideas or suggestions greatly appreciated!
2012/01/04
[ "https://Stackoverflow.com/questions/8733999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076261/" ]
Actually, have now solved this! Was due to "autoreleasing" elements of the array, so after clearing this out, they were invalid. Removing `autorelease` and just releasing these objects in the final dealloc worked.
21,279,393
I have some questions about XMLHttpRequest using $.Post $.Ajax: 1- How the server side verifies if the request was sent from same browser? 2- How the server side verifies if session user who sent the request has been changed on same browser? (ex: user logout and another user login on same browser) 3- Do I need any special settings or PHP code at server side for #1 and #2? Also please give me a link to good documentation about any security issues related to XMLHttpRequest. Thanks
2014/01/22
[ "https://Stackoverflow.com/questions/21279393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2007059/" ]
1. Browsers and servers use cookies to check whether request was sent from same browser. Every request will have cookies attached. 2. The basic idea about the sessions is simple. Whenever you send a request to the server, the session variable (if present) will be sent along with the request to your server. Again, if you modify anything in session or clear the session, the response will contain the modified session. Since both request and response contain sessions, they can operate independently. 3. By using $\_SESSION in PHP, you will be able to retrieve sessions in server. Just use $\_SESSION['userid'] == to check whether it's the same user. I understand you are a PHP person but take a look at node.js request and response objects for a better clarity about sessions. Also you can encrypt session variables in server for security. Code Igniter session library is an excellent example for this.
59,367,740
Please have a look at my website here: <http://35.232.230.0:81> This shows a mat-table in an angular application. I would like to remove the white lines between the rows of the table. How does one do this? Thanks.
2019/12/17
[ "https://Stackoverflow.com/questions/59367740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9334823/" ]
mat-cell and mat-header-cell have the borders. just set border none for those elements. ``` .mat-cell, .mat-header-cell { border: none !important; } ```
222,298
The effect I'm looking for in the end is to have the first line in some paragraphs bolded. These would be the first paragraph of each section in my post. This kind of effect is used on [this](http://www.bloomberg.com/features/2016-how-to-hack-an-election/) Bloomberg.com post. Notice the first paragraph in the post and then also the first paragraph of later sections of the post are bolded. The way they accomplished this was to have a particular class ("section-break" in their post) applied to the paragraphs they wanted this effect on, and then using the ::first-line css pseudo class, applying it to the paragraphs with the "section-break" class. I can set up the css to do that what they did; the only thing I'm struggling with his how I can delineate, while writing my post, which paragraphs would be the beginning of a new section and so would need to have their own "section-break" class. Is there a built in way to do this? And if not how might I be able to hack it in? Thanks!
2016/04/01
[ "https://wordpress.stackexchange.com/questions/222298", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/91575/" ]
I figured this out. Even though Wordpress automatically adds the `<p>` tag and doesn't show it to you in the editor (in either the 'visual' or 'text' editor views), you can type it in anyway in the 'text' editor view, along with a class. So to do this, go to the 'text' editor view, and just type, e.g., `<p class="section-break>Here is the first paragraph of a new section of my document</p>`. And although when you type a regular `<p>` tag yourself (without a class) it will disappear when you switch to the 'visual' editor and back to the 'text' editor view, if instead you type it in with a class, it will stay there available to edit if it has a class attribute (e.g., `<p class="something">stuff</p>`).
47,012,120
I have a dataframe of IDs and addresses. Normally, I would expect each recurring ID to have the same address in all observations, but some of my IDs have different addresses. I want to locate those observations that are duplicated on ID, but have at least 2 different addresses. Then, I want to randomize a new ID for one of them (an ID that didn't exist in the DF before). For example: ``` ID Address 1 X 1 X 1 Y 2 Z 2 Z 3 A 3 B 4 C 4 D 4 E 5 F 5 F 5 F ``` Will return: ``` ID Address 1 X 1 X 6 Y 2 Z 2 Z 3 A 7 B 4 C 8 D 9 E 5 F 5 F 5 F ``` So what happened is the 3rd,7th, 9th and 10th observations got new IDs. I will mention that it is possible for an ID to have even more than 2 different addresses, so the granting of new IDs should happen for each unique address. Edit: I added a code for a longer example of a data frame, with rand column that should be ignored but kept in final output. ``` df <- data.frame(ID = c(1,1,1,2,2,3,3,4,4,4,5,5,5), Address = c("x","x","y","z","z","a","b","c","d","e", "f","f","f"), rand = sample(1:100, 13)) ```
2017/10/30
[ "https://Stackoverflow.com/questions/47012120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4732998/" ]
Here's a solution with `tidyr` and functions `nest` / `unnest` ``` library(tidyr) library(dplyr) df %>% group_by(ID,Address) %>% nest %>% `[<-`(duplicated(.$ID),"ID",max(.$ID, na.rm = TRUE) + 1:sum(duplicated(.$ID))) %>% unnest # # A tibble: 13 x 3 # ID Address rand # <dbl> <fctr> <int> # 1 1 x 58 # 2 1 x 4 # 3 6 y 75 # 4 2 z 5 # 5 2 z 19 # 6 3 a 55 # 7 7 b 34 # 8 4 c 53 # 9 8 d 98 # 10 9 e 97 # 11 5 f 13 # 12 5 f 64 # 13 5 f 80 ``` If you use `magrittr`, replace `[<-` with `inset` if you want prettier code (same output).
42,362,024
I am getting the following crash for a lot of users : ``` Fatal Exception: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set java.util.Map.keySet()' on a null object reference at com.google.android.gms.internal.zzbtn.zza(Unknown Source) at com.google.android.gms.internal.zzbtn.run(Unknown Source) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) ``` I searched through external libraries and found that the source of crash is firebase-config library in the following class zzbtn(see method - zza()). ``` // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.google.android.gms.internal; import android.content.Context; import android.util.Log; import com.google.android.gms.internal.zzbtl; import com.google.android.gms.internal.zzbto; import com.google.android.gms.internal.zzbtr; import com.google.android.gms.internal.zzbxt; import com.google.android.gms.internal.zzbts.zza; import com.google.android.gms.internal.zzbts.zzb; import com.google.android.gms.internal.zzbts.zzc; import com.google.android.gms.internal.zzbts.zzd; import com.google.android.gms.internal.zzbts.zze; import com.google.android.gms.internal.zzbts.zzf; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class zzbtn implements Runnable { public final Context mContext; public final zzbto zzclY; public final zzbto zzclZ; public final zzbto zzcma; public final zzbtr zzclQ; public zzbtn(Context var1, zzbto var2, zzbto var3, zzbto var4, zzbtr var5) { this.mContext = var1; this.zzclY = var2; this.zzclZ = var3; this.zzcma = var4; this.zzclQ = var5; } private zza zza(zzbto var1) { zza var2 = new zza(); if(var1.zzace() != null) { Map var3 = var1.zzace(); ArrayList var4 = new ArrayList(); Iterator var5 = var3.keySet().iterator(); while(var5.hasNext()) { String var6 = (String)var5.next(); ArrayList var7 = new ArrayList(); Map var8 = (Map)var3.get(var6); /* Crash is here when reading keySet() on null map */ Iterator var9 = var8.keySet().iterator(); while(var9.hasNext()) { String var10 = (String)var9.next(); zzb var11 = new zzb(); var11.zzaB = var10; var11.zzcml = (byte[])var8.get(var10); var7.add(var11); } zzd var16 = new zzd(); var16.zzaGP = var6; zzb[] var12 = new zzb[var7.size()]; var16.zzcmq = (zzb[])var7.toArray(var12); var4.add(var16); } zzd[] var15 = new zzd[var4.size()]; var2.zzcmi = (zzd[])var4.toArray(var15); } if(var1.zzzD() != null) { List var13 = var1.zzzD(); byte[][] var14 = new byte[var13.size()][]; var2.zzcmj = (byte[][])var13.toArray(var14); } var2.timestamp = var1.getTimestamp(); return var2; } public void run() { zze var1 = new zze(); if(this.zzclY != null) { var1.zzcmr = this.zza(this.zzclY); } if(this.zzclZ != null) { var1.zzcms = this.zza(this.zzclZ); } if(this.zzcma != null) { var1.zzcmt = this.zza(this.zzcma); } if(this.zzclQ != null) { zzc var2 = new zzc(); var2.zzcmm = this.zzclQ.getLastFetchStatus(); var2.zzcmn = this.zzclQ.isDeveloperModeEnabled(); var2.zzcmo = this.zzclQ.zzacj(); var1.zzcmu = var2; } if(this.zzclQ != null && this.zzclQ.zzach() != null) { ArrayList var8 = new ArrayList(); Map var3 = this.zzclQ.zzach(); Iterator var4 = var3.keySet().iterator(); while(var4.hasNext()) { String var5 = (String)var4.next(); if(var3.get(var5) != null) { zzf var6 = new zzf(); var6.zzaGP = var5; var6.zzcmx = ((zzbtl)var3.get(var5)).zzacd(); var6.resourceId = ((zzbtl)var3.get(var5)).zzacc(); var8.add(var6); } } zzf[] var11 = new zzf[var8.size()]; var1.zzcmv = (zzf[])var8.toArray(var11); } byte[] var9 = zzbxt.zzf(var1); try { FileOutputStream var10 = this.mContext.openFileOutput("persisted_config", 0); var10.write(var9); var10.close(); } catch (IOException var7) { Log.e("AsyncPersisterTask", "Could not persist config.", var7); } } } ``` This class is used in FirebaseRemoteConfig class (see method zzt()) as given below : <https://gist.github.com/anonymous/e6f23c1dc37bf905a9224d8b72ab6cd9> And I am using FirebaseRemoteConfig in my application class as below : ``` public class MyApp extends MultiDexApplication { public static boolean sound = true; private static Context context; private Typeface regularTypeFace; private Typeface boldTypeFace; private final String LOG_TAG = "MyApp"; private FirebaseRemoteConfig remoteConfig = null; @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); context = getApplicationContext(); /* Try catch to handle any runtime exception thrown by firebase API */ try { /* Initialize firebase app : Done to avoid crashes due to IllegalStateException - Default FirebaseApp is not initialized */ FirebaseApp.initializeApp(this); /* Start to fetch Remote config parameters */ startConfigFetch(); } catch (Exception e){ e.printStackTrace(); } } /** * Description : Fetches remote config params from firebase & uses the fetched values */ public void startConfigFetch() { /* try to get the default instance of Firebase Remote config */ /* try-catch : To Resolve Crash #1399 */ try { remoteConfig = FirebaseRemoteConfig.getInstance(); } catch (IllegalStateException e){ e.printStackTrace(); } /* If we don't get an instance of Firebase remote config, then do nothing */ if (remoteConfig == null){ return; } FirebaseRemoteConfigSettings remoteConfigSettings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(BuildConfig.DEBUG) .build(); remoteConfig.setConfigSettings(remoteConfigSettings); remoteConfig.setDefaults(R.xml.remote_config_defaults); /* Time for which cache lives, for now its 0 ms */ long cacheExpiration = 0; OnCompleteListener<Void> onCompleteListener = new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { if (getContext() != null) { onFetchConfigSuccess(); } } else { Log.d(LOG_TAG, "Stories Fetch Fail"); } } }; OnFailureListener onFailListener = new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d(LOG_TAG, "Stories Fetch Fail in remote config"); } }; remoteConfig.fetch(cacheExpiration).addOnCompleteListener(onCompleteListener).addOnFailureListener(onFailListener); } /** * Called when fetch config is success * */ private void onFetchConfigSuccess() { /* Once the config is successfully fetched it must be activated before newly fetched */ /* values are returned (or can be used) */ remoteConfig.activateFetched(); /* Get dynamic stories string */ String dynamicStories = remoteConfig.getString(Common.KEY_DYNAMIC_STORIES_FIREBASE_CONFIG); /* Get bundled stories (these are app-bundled stories & dynamic stories but part of bundled stories) */ String bundledStories = remoteConfig.getString(Common.KEY_BUNDLED_STORIES_FIREBASE_CONFIG); /* Do something with dynamicStories & bundledStories values */ } } ``` And class zzbto is here : <https://gist.github.com/anonymous/e2f3a67e6fd3be51ba4456fe2e847890> Please help to resolve this crash.
2017/02/21
[ "https://Stackoverflow.com/questions/42362024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3904327/" ]
Hint: 1. Produce `[f x1,...,f xn]` first, applying `f` to every member. 2. Then, write a function that takes `[y1,...,yn]` and `w` and produces an interleaving `[y1,w,y2,w,...,yn]`. This can be done by recursion. (There's also a library function for that, but it's not important.) 3. Compose both, to obtain `[f x1, ",", ...]` and then concatenate the result. 4. Add brackets to the resulting string.
48,247,393
I am trying to preload server form in the constructor of client form, in a separate thread. My reason is that server load is time consuming. Here's the client form, you can see in the constructor that I am calling `Preload()`. There's also a button, clicking on it should show the server, which should be fast since the server form is already preloaded: ``` public partial class Form1 : Form { ServerUser server = null; public Form1() { InitializeComponent(); Preload(); } public async void Preload() { await Task.Run(() => { server = new ServerUser(); server.LoadDocument(); server.ShowDialog(); } ); } private void button1_Click(object sender, EventArgs e) { server.Show(); } } ``` Here I try to preload form `ServerUser` in constructor of `Form1` and if I click on button1 Server form show faster And here's the server form: ``` public partial class ServerUser : Form { public ServerUser() { InitializeComponent(); } public void LoadDocument() { ConfigureSource(); } public void ConfigureSource() { InvokeUpdateControls(); } public void InvokeUpdateControls() { UpdateControls(); } private void UpdateControls() { richTextBox1.Rtf = Resource1.ReferatPPC_Bun___Copy; } } ```
2018/01/14
[ "https://Stackoverflow.com/questions/48247393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9018083/" ]
You need to rethink your design. You should create all forms from the main UI thread, and offload the heavy lifting(non UI stuff) to the background threads. Calling UI methods from background threads results in undefined behavior or exceptions. Also, I think you misunderstand what `await` does. You call `Preload()` synchronously even though it is an asynchronous method. This means that by the time `server.Show();` is called, Server might still be running one of these methods: ``` server = new ServerUser(); //you should move this outside of Task.Run() server.LoadDocument(); //implement this method using background threads server.ShowDialog(); //this will actually throw an exception if called via Task.Run(); ``` From your sample I suppose LoadDocument is the expensive operation. You should rewrite that method to run on a background thread and make `ServerUser` show a loading screen untill `LoadDocument()` completes. Make sure that all UI methods from LoadDocument are called via [BeginInvoke](https://msdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.110).aspx) or **proper** async/await.
128,840
We need to do some user documentation for a product we have been working on for the past few sprints. We are now starting a new project in the next sprint and the PO is making the documentation for the product produced previously a User story for this sprint. I am just wondering your opinion on this approach. Personally, I don't agree that documentation is a User Story within Scrum because it doesn't produce any code. EDIT: Thanks for your opinions guys. I had it in the back of my head that a sprint was to implement an increment of working software, but your views have changed my outlook. Thank you for all your answers.
2012/01/06
[ "https://softwareengineering.stackexchange.com/questions/128840", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/40251/" ]
"As a user of X, I need to know how X works" seems like a legitimate user story to me. This could result in written documentation or online help. The point isn't just code--it's meeting the users' requirements.
65,896,559
I have some items inside of my `LinearLayout` and what I want to do is, arrange the items vertically in a way that it would spread evenly with default margin across the items. This is what I have now : [![enter image description here](https://i.stack.imgur.com/SFnCR.png)](https://i.stack.imgur.com/SFnCR.png) So All the FAB's inside of the linear layout doesn't spread evenly, and even if I set a `layout_marginStart` it could cause some problems due to different resolutions across the android models. ``` <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <FrameLayout android:layout_marginTop="25dp" android:layout_width="25dp" android:layout_height="wrap_content" android:layout_gravity="bottom|right"> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:elevation="0dp" app:backgroundTint="@color/gray" app:elevation="0dp" android:src="@android:color/transparent" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:textSize="10sp" android:text="S" android:elevation="16dp" android:textColor="@android:color/white"/> </FrameLayout> ```
2021/01/26
[ "https://Stackoverflow.com/questions/65896559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10881932/" ]
Try this instead of FrameLayout: ``` <RelativeLayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_marginTop="25dp"> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:elevation="0dp" android:src="@android:color/transparent" app:backgroundTint="@color/gray" android:layout_centerInParent="true" app:elevation="0dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:elevation="16dp" android:text="S" android:textColor="@android:color/white" android:textSize="10sp" /> </RelativeLayout> ``` The children of a LinearLayout spread evenly when they have android:layout\_width="0dp" and android:layout\_weight="1"
32,501,002
I'm removing the hash value with `parent.location.hash = ''` but that instantly makes the browser jump to the top of the page - can I just remove the `#!ajax-url-part` from the browser without making it jump to the top of the page? Thank you.
2015/09/10
[ "https://Stackoverflow.com/questions/32501002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2065540/" ]
As OP wants, I put my comment in an answer because is a valid answer: You can read this blog: <http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/> The trick is as easy as this: ``` window.history.pushState(“object or string”, “Title”, “/new-url”); ``` Good luck!
58,178,874
I am trying to make a **checkbox** smaller and change the size of border I have tried playing around with layout in XML and `.width()`or `.height` in Kotlin. Neither does anything to change the size of it. I went to the tutorial that was recommended to others that asked these questions, but I did not understand what he did. Any suggestions? **mycheckbox.xml** ``` xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> ``` ``` android:id="@+id/stSafeCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:button="@drawable/my_checkbox" /> ``` **my\_checkbox.xml** ``` <item android:state_checked="false" android:drawable="@drawable/checkbox_off_background"/> <item android:state_checked="true" android:drawable="@drawable/checkbox_on_background"/> ``` **checkbox\_off\_background** ``` <item> <shape android:shape="rectangle"> <size android:width="25dp" android:height="25dp" /> </shape> </item> <item android:drawable="@android:drawable/checkbox_off_background" /> ``` **checkbox\_on\_background.xml** ``` <item> <shape android:shape="rectangle"> <size android:width="25dp" android:height="25dp" /> </shape> </item> <item android:drawable="@android:drawable/checkbox_on_background" /> ```
2019/10/01
[ "https://Stackoverflow.com/questions/58178874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12146689/" ]
The `break` only breaks the for-loop but then continues with the code below. You probably just say `return` instead or `System.exit(0);`
68,773,352
I have an array of 5 divs ``` `<div id="cap-left2"</div>` `<div id="cap-left1"</div>` `<div id="cap-base"</div>` `<div id="cap-right1"></div>` `<div id="cap-right2"</div>` ``` all these divs have a background . In my javascript I have : ``` let items = [capBase,capLeft1,capLeft2,capRight1,capRight2]; ``` this works : ``` `var tom = items[Math.floor(Math.random()*items.length)] console.log(tom)` ``` and this works ``` `var tom = items[Math.floor(Math.random()*items.length)]` `console.log(tom.style)` ``` but I want the backgroundColor and neither of these work: ``` `var tom = items[Math.floor(Math.random()*items.length)]` `console.log(tom.style.background)` `var tom = items[Math.floor(Math.random()*items.length)]` `console.log(tom.style.backgroundColor)` ``` what I am trying to do is lets say i have 5 swatches represented by 5 elements in an array . i want to be able to have a button that allows me to randomize what colors fill each element any help would be appreciated
2021/08/13
[ "https://Stackoverflow.com/questions/68773352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16028691/" ]
Java has random number generator support via the `java.util.Random` class. This class 'works' by having a seed value, then giving you some random data based on this seed value, which then updates the seed value to something new. This pragmatically means: * 2 instances of j.u.Random with the same seed value will produce the same sequence of values if you invoke the same sequence of calls on it to give you random data. * But, seed values are of type `long` - 64 bits worth of data. * Thus, to do what you want, you need to write an algorithm that turns any String into a `long`. * Given that long, you simply make an instance of `j.u.Random` with that long as seed, using the [`new Random(seedValue)`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#Random-long-) constructor. So that just leaves: How do I turn a string into a long? Easy way -------- The simplest answer is to invoke `hashCode()` on them. But, note, hashcodes only have 32 bits of info (they are `int`, not `long`), so this doesn't cover all possible seed values. This is unlikely to matter unless you're doing this for crypto purposes. If you ARE, then you need to stop what you are doing and do a lot more research, because it is extremely easy to mess up and have working code that seems to test fine, but which is easy to hack. You don't want that. For starters, you'd want `SecureRandom` instead, but that's just the tip of the iceberg. Harder way ---------- Hashing algorithms exist that turn arbitrary data into fixed size hash representations. The hashCode algorithm of string [A] only makes 32-bits worth of hash, and [B] is not cryptographically secure: If you task me to make a string that hashes to a provided value I can trivially do so; a cryptographically secure hash has the property that I can't just cook you up a string that hashes to a desired value. You can search the web for hashing strings or byte arrays (you can turn a string into one with `str.getBytes(StandardCharsets.UTF_8)`). You can 'collapse' a byte array containing a hash into a long also quite easily - just take any 8 bytes in that hash and use them to construct a long. "Turn 8 bytes into a long" also has tons of tutorials if you search the web for it. I assume the easy way is good enough for this exercise, however. Thus: ----- ``` String key = ...; Random rnd = new Random(key.hashCode()); int number1 = rnd.nextInt(10) + 1; int number2 = rnd.nextInt(10) + 1; System.out.println("First number: " + number1); System.out.println("Second number: " + number2); ```
14,686,001
I have some text files in a directory. I would like to read all the files in this directory and if the file has the following line `SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY` move that file with its all contents to another directory. How can I do this?
2013/02/04
[ "https://Stackoverflow.com/questions/14686001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2039457/" ]
Using `find` and `grep`: ``` $ find . -type f -exec \ fgrep -l "SAMPLE 350 AN INTEGER OF TYPE :DECIMAL : CAN BE ASSEMBLED BY" {} \; \ | xargs -i% mv % /path/to/new/dir ```
21,910,653
So i made test code: ``` $fopen = fopen('./mydata.csv',"r"); $data = fgetcsv($fopen, 1000, ","); fclose($fopen); $fp = fopen('mynewdata.csv','a'); fputcsv($fp,$data,','); fclose($fp); ``` Content of mydata.csv file: > > string "some thing", sec string,next string > > > New content of mynewdata.csv file: > > "string ""some thing"""," sec string","next string" > > > My question is: Where this ' " ' comes from. What i do wrong that my output is different than input. Few more obserwations: When i do test like, with enclosure: '' -> empty string: ``` $data = fgetcsv($fopen, 1000,',',''); print_r($data); ``` It print's nothing insted of array with 2 rows, and that's the error i got from logs: " FastCGI sent in stderr: "PHP message: PHP Warning: fgetcsv(): enclosure must be a **character**" So what would be the other option to give as the enclosure an empty string.
2014/02/20
[ "https://Stackoverflow.com/questions/21910653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1847939/" ]
As you can see by the [`fputcsv` documentation](http://dk1.php.net/fputcsv): > > int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] ) > > > The last parameter is the enclosure. Since you haven't defined yours, it defaults to `"`, and then it has to escape your quote by placing a double quote. To get rid of this, simply specify an empty string: ``` $fopen = fopen('./mydata.csv',"r"); $data = fgetcsv($fopen, 1000, ","); fclose($fopen); $fp = fopen('mynewdata.csv','a'); fputcsv($fp,$data,',',''); // ^^ fclose($fp); ``` But *why* does it do this by default?! -------------------------------------- To avoid errors if you have commas in your strings. Imagine the following: ``` $data = array('my string', 'is a great string', 'and it is, very nice'); ``` With an enclosure it would result in the following: ``` "my string","is a great string","and it is, very nice" ``` *Without* an enclosure, it would result in the following: ``` my string,is a great string,and it is, very nice ``` Which would be misinterpreted as 4 values instead of 3.
4,031,666
For creating delegates on the fly, techniques vary from Delegate.CreateDelegate, to Expresion Lambda, DynamicMethod, etc. etc. All of these techniques require that you know the *type* of the delegate. I'm trying to convert closed delegates to open delegates *generically*, and to do to achieve this it seems I need to dynamically create the type of the open delegate before I can actually create the resulting delegate. Consider: ``` pubic class WeakEvent<TDelegate> where TDelegate : class { public WeakEvent(Delegate aDelegate) { var dgt = aDelegate as TDelegate; if(dgt == null) throw new ArgumentException("aDelegate"); MethodInfo method = dgt.Method; var parameters = Enumerable .Repeat(dgt.Target.GetType(),1) .Concat(method.GetParameters().Select(p => p.ParameterType)); Type openDelegateType = // ??? original delegate, with new 1st arg for @this var dm = new DynamicMethod("InnerCode", method.ReturnType, parameters); ... your favourite IL code emmisions go here var openDelegate = dm.CreateDelegate(openDelegateType); } } ``` The purpsoe of the above code is to create a new delegate which is identical to the original delegate, but has a new 1st argument for *this*... i.e. an open version of the previously closed delegate. Is there a simple way to clone & modify an existing delegate type, or is the nearest solution to build out the generic Func<> and Action<> types?
2010/10/27
[ "https://Stackoverflow.com/questions/4031666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64084/" ]
New delegate with different signature is a new type. C# being type-safe it is not possible to do that - other than churning some code and compile on runtime which apart from memory leak is not such an elegant approach. But what you can do is it choose appropriate delegate from the list of already made Action<> or Func<> based on the type of delegate. Alternatively create a lits of your own, based on your expected types, and choose that in runtime.
4,912,154
I have two models: User ``` has_one :email ``` Email ``` belongs_to :user ``` I put the email\_id foreign key (NOT NULL) inside users table. Now I'm trying to save it in the following way: ``` @email = Email.new(params[:email]) @email.user = User.new(params[:user]) @email.save ``` This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email\_id). How can I elegantly solve this or is my data modeling wrong?
2011/02/06
[ "https://Stackoverflow.com/questions/4912154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/130111/" ]
Yes, but only by invoking it: ``` Func<object> func = delegate { return a; }; // or Func<object> func = () => a; object b = func(); ``` And of course, the following is a lot simpler... ``` object b = a; ``` --- In the comments, cross-thread exceptions are mentioned; this can be fixed as follows: If the delegate is the thing we want to run back on the UI thread *from* a BG thread: ``` object o = null; MethodInvoker mi = delegate { o = someControl.Value; // runs on UI }; someControl.Invoke(mi); // now read o ``` Or the other way around (to run the delegate on a BG): ``` object value = someControl.Value; ThreadPool.QueueUserWorkItem(delegate { // can talk safely to "value", but not to someControl }); ```
13,331
I have a 6 months UK Business visa. I need to apply for Schengen Visa to allow other EU countries travel. I will be travelling multiple time to Schengen countries for next 3-4 months and I have travelled to Schengen countries last year as well. Now, till now, only 2 days of Belgium travel is confirmed for next month. Can I apply for 4 months, multiple entries Schengen visas with those 2 days hotel confirmation? And am I eligible for 4 months Schengen multiple entry visa? I am from India and plan to apply Schengen visa in India.
2013/02/07
[ "https://travel.stackexchange.com/questions/13331", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/4339/" ]
The confirmed travel plans for Belgium would for 2 days would be fine though without a longer confirmed stay they might simply issue a [Transit Visa](http://www.immihelp.com/visas/schengenvisa/airport-transit-visa.html) though it's more likely a [Short Term will be issued](http://www.norwayemb.org.in/Embassy/Passports-and-Visas/Visa-Information-/Tourist-Visa/). Generally speaking if you plan to travel multiple times you should not exceed 90 days total duration in any 180 day. And the requirements for the visa you can see on any embassy site for the countries covered by the agreement. I picked [Norway](http://www.norwayemb.org.in/Embassy/Passports-and-Visas/Visa-Information-/Tourist-Visa/). If you need to stay more then 90 days in Europe you may have to pick a country and apply for a long term stay visa instead.
29,308,901
So i have `.cont` that's centered in using position absolute and is height 80% of body. Inside it there are two divs. One is fixed height. And other one needs to expand to rest of parent, `.cont`. So How do i make it expand to parent. One other requirement is that content in both of these needs to be vertically and horizontally centered. ``` body .cont .top .fillRest ``` Here is jsfiddle: <http://jsfiddle.net/24jocwu5/> 1. make .fillRest Expand to rest of .cont. 2. vertically and Horizontally center h1 headings in both divs. Don't Use calc() can use display table, flow, position, and other tricks. ![enter image description here](https://i.stack.imgur.com/k68V6.png)
2015/03/27
[ "https://Stackoverflow.com/questions/29308901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1319799/" ]
Here you go. Absolutely position the white container with a top-padding that equals the height of your fixed-height top div. Then give the top div a z-index so it goes over your white box: Fiddle - <http://jsfiddle.net/24jocwu5/2/> ``` * {margin: 0; padding: 0;} html, body { height: 100%; background-color: #3dd; color: #aaa; font-family: helvetica; } .cont { position: absolute; top: 0; bottom: 0; right: 0; left: 0; background-color: #1af; width: 400px; margin: auto; height: 80%; } .top { height: 100px; background-color: pink; position: relative; z-index: 1; } .fillRest { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding-top: 100px; height: 100%; background-color: #fff; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } h1 { text-align: center; width: 200px; margin: auto; background-color: #eee; } ```
46,316
Pleasures for us is pain & suffering for the animals which are slaughtered. When we are causing suffering & pain to others, we lose moral rights to expect not the same ever happened to us. In case of animal slaughtering, do we also lose the moral rights to mourn if our beloved ones are killed the same way which we, being non Vegetarian, kill other creatures? In other words, Don't we have moral rights to take it as injustice to ourselves if our beloved ones are killed, being Non Vegetarian? **EDIT**: Seems I am unable to express myself clearly, I would like to ask the same question in other words: Do non-vegetarians lose rights to ask GOD if their beloved ones are killed, presuming GOD doesn't want us to kill any creature intentionally for sensual pleasures. (Seems obvious if god is Benevolent & Equal to all the creatures.)?
2017/10/01
[ "https://philosophy.stackexchange.com/questions/46316", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/23084/" ]
> > *moral rights* > > > "Rights" aren't a moral or ethical category. They are a juridical category. > > *to mourn* > > > To "mourn", on the other hand, is psychological, not moral or juridical, phenomenon. So, the "moral right to mourn" is a conflation of disparate concepts, which becomes meaningless at all three - juridical, moral, psychological - levels. Juridically, there is nothing that can be done to prevent people from mourning. If they think that the defeat of their preferred soccer team is something to mourn, more than the death of thousands of people in a war on the other side of the planet, there is nothing to be done about. What would we do? Jail them? Tell them they are going to hell? Dose them some chemical that will make them unable to mourn? Morally, you can condemn whatever you want. It doesn't affect the rights of others. You may think that those who see too much television lose their moral grounds to complain about the moral decadence of society, for television is hugely responsible for such decadence. They will still watch TV and complain about the decaying mores of the commonwealth. Both things are, and should be, legal rights; a society in which either or both were forbidden would be horrible to live in. Psychologically, there is nothing that can be done about mourning or not mourning. One may think that I should mourn the extinction of the pox virus; but the fact is that if I am not, for any reason, psychologically attached to such virus, I won't mourn its extinction, and may be indifferent or happy about it. It's possible, I guess, to shame people into pretending that they are unhappy about a given event, but it is not possible to make them unhappy if they are not. And this - shaming people - is what this idea is probably about. It is not that we should not mourn the passing of our grandmother just because we just ate a barbecue; it is that we should not have eaten the barbecue, for we should think of the poor cow as we think of our grandmother. But as some of the comments above pointed out, the vast majority of human beings do not think a cow is equivalent to a human being, and consequently won't be able to act as if it was. --- Evidently, the idea of an all-encompassing equivalence among all living beings is pragmatically unsustainable. All human beings, vegetarians and animal-rights activists included, are "especiesist" - they do not think killing a vegetal is the same as killing an animal, they do not think killing an insect - or any invertebrate - is the same as killing a mammal, they rarely think that amphibians, fish, or lizards, are on the same standing as birds and mammals, and more often than not discriminate among mammals - who does empathise with a bat or a hyaena as much as with a panda, for instance? --- Talking about empathy, it is often repeated that a psychopath is someone who is devoid of empathy. But empathy is a complicated thing; as someone else put it, if you break your leg, do you want a physician who painfully pulls it into the right position, or a physician who hugs you and cries together? "Empathy" can be paralising in this sence. If no empathy makes one a psychopath, unqualified empathy may turn one *hysteric*. Most of us are by far more empathetic towards our own relatives, friends, neighbours, etc, than towards people we do not know and live far away. And the idea that you should not mourn your grandmother because you didn't properly mourn the victims of a hurricane in Texas or an earthquake in Mexico is somewhat disturbing - at some point, all-encompassing empathy veers dangerously in the direction of no empathy at all.
3,565
This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead. ### Task: Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere. Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like: ``` struct node { void *value; struct node *next; }; int has_loops(struct node *first) { /* write your own loop detection here */ } ``` ### Hints: There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book.
2011/08/26
[ "https://codegolf.stackexchange.com/questions/3565", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/2360/" ]
C, non-golfed ------------- The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though). ``` struct node { void *value; struct node *next; }; int has_loops(struct node *p) { struct node *p1 = p, *p2 = p->next; if (!p2) return 0; while (p1 != p2) { // p1 goes one step p1 = p1->next; if (!p1) return 0; // p2 goes two steps p2 = p2->next; if (!p2) return 0; p2 = p2->next; if (!p2) return 0; } return 1; } ```
1,556,716
I distributed an iPhone application to some testers who are using Windows. On their machines, the application that I built (in the form of an .app bundle) appeared as a directory. That makes sense because a .app bundle **is** actually a directory. What mechanism does Mac OS X use to display these bundles as files within Finder? Is there anyway to get the same kind of abstraction on Windows?
2009/10/12
[ "https://Stackoverflow.com/questions/1556716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105382/" ]
No, but why would you want to? An .app on Mac is not equivalent to an .exe on Windows - if you explore the .app bundle on a Mac (using "Show Package Contents"), you'll see an actual executable program inside. *This* program is more the equivalent of a Windows .exe, and you can liken the entire .app bundle to the Program Files directory for an application on Windows. All the .app serves to do is to concentrate program resources in one directory, much like an install directory does on Windows.
23,783,427
i am a beginner in haskell programming and very often i get the error ``` xxx.hs:30:1: parse error on input `xxx' ``` And often there is a little bit playing with the format the solution. Its the same code and it looks the same, but after playing around, the error is gone. At the moment I've got the error ``` LookupAll.hs:30:1: parse error on input `lookupAll' ``` After that code: ``` lookupOne :: Int -> [(Int,a)] -> [a] lookupOne _ [] = [] lookupOne x list = if fst(head list) == x then snd(head list) : [] lookupOne x (tail list) -- | Given a list of keys and a list of pairs of key and value -- 'lookupAll' looks up the list of associated values for each key -- and concatenates the results. lookupAll :: [Int] -> [(Int,a)] -> [a] lookupAll [] _ = [] lookupAll _ [] = [] lookupAll xs list = lookupOne h list ++ lookupAll t list where h = head xs t = tail xs ``` But I have done everything right in my opinion. There are no tabs or something like that. Always 4 spaces. Is there a general solutoin for this problems? I am using notepad++ at the moment. Thanks!
2014/05/21
[ "https://Stackoverflow.com/questions/23783427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420062/" ]
The problem is not with `lookupAll`, it's actually with the previous two lines of code ``` if fst (head list) == x then snd (head list) : [] lookupOne x (tail list) ``` You haven't included an `else` on this if statement. My guess is that you meant ``` if fst (head list) == x then snd (head list) : [] else lookupOne x (tail list) ``` Which I personally would prefer to format as ``` if fst (head list) == x then snd (head list) : [] else lookupOne x (tail list) ``` but that's a matter of taste. --- If you are wanting to accumulate a list of values that match a condition, there are a few ways. By far the easiest is to use `filter`, but you can also use explicit recursion. To use `filter`, you could write your function as ``` lookupOne x list = map snd -- Return only the values from the assoc list $ filter (\y -> fst y == x) list -- Find each pair whose first element equals x ``` If you wanted to use recursion, you could instead write it as ``` lookupOne _ [] = [] -- The base case pattern lookupOne x (y:ys) = -- Pattern match with (:), don't have to use head and tail if fst y == x -- Check if the key and lookup value match then snd y : lookupOne x ys -- If so, prepend it onto the result of looking up the rest of the list else lookupOne x ys -- Otherwise, just return the result of looking up the rest of the list ``` Both of these are equivalent. In fact, you can implement `filter` as ``` filter cond [] = [] filter cond (x:xs) = if cond x then x : filter cond xs else filter cond xs ``` And `map` as ``` map f [] = [] map f (x:xs) = f x : map f xs ``` Hopefully you can spot the similarities between `filter` and `lookupOne`, and with `map` consider `f == snd`, so you have a merger of the two patterns of `map` and `filter` in the explicit recursive version of `lookupOne`. You could generalize this combined pattern into a higher order function ``` mapFilter :: (a -> b) -> (a -> Bool) -> [a] -> [b] mapFilter f cond [] = [] mapFilter f cond (x:xs) = if cond x then f x : mapFilter f cond xs else : mapFilter f cond xs ``` Which you can use to implement `lookupOne` as ``` lookupOne x list = mapFilter snd (\y -> fst y == x) list ``` Or more simply ``` lookupOne x = mapFilter snd ((== x) . fst) ```
30,633,378
I cannot find a way to change the color of an Excel data bar based on value. Current formatting options only permit different colors based on positive/negative values. I'm currently using Excel 2010. I would like to have the color of a data bar show up as 'red' if the value if between 0-0.3, 'yellow' if the value is between 0.3-0.6, and 'green' if the value if between >0.6. Would really appreciate any info people could share. Thanks, TB
2015/06/04
[ "https://Stackoverflow.com/questions/30633378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4971822/" ]
Data bars only support one color per set. The idea is that the length of the data bar gives you an indication of high, medium or low. Conditional colors can be achieved with color scales. What you describe sounds like a combination of the two, but that does not exist in Excel and I don't see an easy way to hack it. You could use a kind of in-cell "chart" that was popular before sparklines came along. Use a formula to repeat a character (in the screenshot it's the character `g` formatted with Marlett font), and then use conditional formatting to change the font color. ![enter image description here](https://i.stack.imgur.com/Ps5zS.png) For a nicer "bar" feel, use unicode character 2588 with a regular font. ![enter image description here](https://i.stack.imgur.com/qijeW.png) Edit: Not every Unicode character is represented in every font. In this case the the unicode 2588 shows fine with Arial font but not with Excel's default Calibri. Select your fonts accordingly. The Insert > Symbol dialog will help find suitable characters. ![enter image description here](https://i.stack.imgur.com/9yl3K.png)
8,728,033
I used to be able to debug using Visual C# Express 2010 with no problem before. However, since I've opened my project using MonoDevelop (to port it under MacOS), I can't seem to be able to debug anymore. The exact error message is available below: ![The exact error message](https://i.stack.imgur.com/HRONs.png) A lot of people says to go in the configuration manager, which I'm familiar with, however, I can't seem to find it in the Express version.
2012/01/04
[ "https://Stackoverflow.com/questions/8728033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1058466/" ]
Since you didn't have this issue prior to opening in Monodevelop, it more than likely changed something within the solution and/or project files. There are a number of posts on stackoverflow... [stackoverflow: no symbols](https://stackoverflow.com/questions/2155930/fixing-the-breakpoint-will-not-currently-be-hit-no-symbols-have-been-loaded-fo) [stackoverflow: no symbols when crossing module boundries](https://stackoverflow.com/questions/2643659/c-sharp-debugging-issue-no-symbols-are-loaded-for-any-call-stack-frame) (From Răzvan Panda comment on the question) ... that talk about missing symbols. However, based on the information provided about monodevelop, I'd venture to guess that the IDE changed something within the solution and/or project files. If your solution is under source control and you don't see any differences in these files, let me know. Otherwise, you could create a new blank solution/project file (from Visual C# Express 2010) and re-add all your files to it to get the default settings back and see if that resolves your issue. EDIT: Also, keep in mind that there are ".user" files that I guess "might" have an effect on build/debugging configurations. If re-adding your files to blank solution/project files doesn't work make sure all the "extra" files like ".user" are not in the directory. Usually files like "*.csproj.user", and "*.suo". I've never had an issue deleting these they store local configuration changes that are not usually checked into source control.
497,407
We started a TCP/IP introductory course at work today, and learned about the different classes of network addresses: ``` Class A addresses are from 0.0.0.0 thru 127.x.x.x Class B addresses are from 128.0.0.0 thru 191.x.x.x Class C addresses are from 192.0.0.0 thru 223.x.x.x Class D addresses are from 224.0.0.0 thru 239.x.x.x Class E addresses are from 240.0.0.0 thru 255.x.x.x ``` I'm not clear on the possible subnet sizes for the different classes of networks. For example, what is the largest subnet mask possible for a Class C network? Is it 255.255.255.0, or could you also have 255.255.0.0 and 255.0.0.0?
2012/11/01
[ "https://superuser.com/questions/497407", "https://superuser.com", "https://superuser.com/users/115033/" ]
There are no classes, they were deprecated in 1994 (seriously, that was 18 years ago as of writing this). Your teacher should be **fired** for even mentioning them (outside a *history* class) as it will only confuse you when you learn how networks actually work. Networks are subnetted using CIDR (and expressed in CIDR notation). While the old class system maps to particular CIDR subnets, it's a terrible concept. In short, try to forget what you've already learned and dive into [How does IPv4 Subnetting Work?](https://serverfault.com/questions/49765/how-does-ipv4-subnetting-work)
6,127,157
I have a solution with 15+ projects in there While jumping to a class is easy enough in VS2008/2010 with RightClick-Goto definition which jumps to the file containing the definition, but how to locate the project which contains this new class/file ?? I seem to recall it's possible using some "magic" keystrokes/menu but can's seem to locate it
2011/05/25
[ "https://Stackoverflow.com/questions/6127157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135852/" ]
That is one well defined question! There is a question over what is a model. I believe there is a definition floating around as to what constitutes a model in the backbone world, and I'm not sure your strategy is in keeping with that definition. Also you are storing the state in both the url, and the model. You can just store the state in the url, as I will explain. If I was doing this, there would be 2 views. One for your app controls, and nested inside that one for your graph: GraphView, and AppView. The model will be the data your going to plot, not the state of the interface. Use a controller to kick start the app view and also to process any interface state defined in the url. There is a question about levers of state in Backbone. Traditional web applications used a link/url as the primary lever of state but all that is now changing. Here is one possible strategy: ``` Checkbox Change Event -> Update location fragment -> trigger route in controller -> update the view Slider Change Event -> Update location fragment -> trigger route in controller -> update the view ``` The great thing about such a strategy is that it takes care of the case where urls are passed around or bookmarked ``` Url specified in address bar -> trigger route in controller -> update the view ``` I'll take a stab at a pseudo code example. For this, I will make some assumptions on the data: The data is the dog population over time (with a granularity of year), where the slider should have a lower and upper bound, and there volume data is too large to load it all to the client at once. First let's look at the Model to represent the statistical data. For each point on the graph we need something like { population: 27000, year: 2003 } Lets represent this as ``` DogStatModel extends Backbone.Model -> ``` and a collection of this data will be ``` DogStatCollection extends Backbone.Collection -> model: DogStatModel query: null // query sent to server to limit results url: function() { return "/dogStats?"+this.query } ``` Now lets look at the controller. In this strategy I propose, the controller lives up to its name. ``` AppController extends Backbone.Controller -> dogStatCollection: null, appView: null, routes: { "/:query" : "showChart" }, chart: function(query){ // 2dani, you described a nice way in your question // but will be more complicated if selections are not mutually exclusive // countries you could have as countries=sweden;france&fullscreen=true queryMap = parse(query) // if (!this.dogStatCollection) dogStatCollection = new DogStatCollection dogStatCollection.query = queryMap.serverQuery if (!this.appView) { appView = new AppView() appView.collection = dogStatCollection } appView.fullScreen = queryMap.fullScreen dogStatCollection.fetch(success:function(){ appView.render() }) } ```
17,057,338
why i ask this question because i always worried about code like this style ``` def callsomething(x): if x in (3,4,5,6): #do something ``` if the function callsomething was called frequently ,did the (3,4,5,6) waste too much space and time?in some language like C, it might be putted into data segment like constant,but in python,i don't know how it works,so i tended to write code like this ``` checktypes = (3,4,5,6)#cache it def callsomething(x): global checktypes if x in checktypes: #do something ``` but after test i found this way make program slower, in more complicated case, the code would be like this: ``` types = (3,4,5,6) def callsomething(x): global types for t in types: t += x #do something ``` still slower than this ``` def callsomething(x): for t in (3+x,4+x,5+x,6+x): #do something ``` in this case, the program must create (3+x,4+x,5+x,6+x),right?but it still faster than the first version,not head too much though. i know the global var access in python would slow down program but how dose it compare to creating an struct?
2013/06/12
[ "https://Stackoverflow.com/questions/17057338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2003548/" ]
Don't worry, it's stored as a constant (which explains why it's faster than you expected) ``` >>> def callsomething(x): ... if x in (3,4,5,6): pass ... >>> import dis >>> dis.dis(callsomething) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 5 ((3, 4, 5, 6)) 6 COMPARE_OP 6 (in) 9 POP_JUMP_IF_FALSE 15 12 JUMP_FORWARD 0 (to 15) >> 15 LOAD_CONST 0 (None) 18 RETURN_VALUE ``` Looking up `x` in a `set` should be faster, right? But Uh Oh... ``` >>> def callsomething(x): ... if x in {3,4,5,6}: pass ... >>> dis.dis(callsomething) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 1 (3) 6 LOAD_CONST 2 (4) 9 LOAD_CONST 3 (5) 12 LOAD_CONST 4 (6) 15 BUILD_SET 4 18 COMPARE_OP 6 (in) 21 POP_JUMP_IF_FALSE 27 24 JUMP_FORWARD 0 (to 27) >> 27 LOAD_CONST 0 (None) 30 RETURN_VALUE ``` set is mutable, so Python hasn't made this optimization until recently. Python3.3 sees that it's safe to make this into a frozenset ``` Python 3.3.0 (default, Sep 29 2012, 17:17:45) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def callsomething(x): ... if x in {3,4,5,6}: pass ... >>> import dis >>> dis.dis(callsomething) 2 0 LOAD_FAST 0 (x) 3 LOAD_CONST 5 (frozenset({3, 4, 5, 6})) 6 COMPARE_OP 6 (in) 9 POP_JUMP_IF_FALSE 15 12 JUMP_FORWARD 0 (to 15) >> 15 LOAD_CONST 0 (None) 18 RETURN_VALUE >>> ```
401,043
What are some ways of documenting pitfalls and gotchas when working with a codebase with a team of developers? I'm working with a team of developers on a big codebase and there's lots of small little things that cause headaches and frustrations in code, configuration, and testing. It doesn't seem appropriate to put them into the github pages because they could be scattered across repositories and projects - so my question is what are some examples of documenting pitfalls and common gotchas?
2019/11/13
[ "https://softwareengineering.stackexchange.com/questions/401043", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/128090/" ]
Quirks and hacks which are easy to explain could be explained in a form of a **comment**. After all, the purpose of the comments is exactly that—come to a rescue when one cannot or doesn't have enough resources to make unclear code clearer. The goal here is to help a programmer who's reading a given line of code (or series of lines) and asks himself what went so wrong in the past that it resulted in this specific piece of code. Weird architecture decisions (which seemed right when they were taken, then appeared to be wrong, but nobody made the effort to refactor the codebase) should be documented in an **architecture document**. Put it in a location where anybody working on the project would find it easily, and make sure new programmers joining the project would necessarily read it. In both cases, make sure you (and your coworkers) understand that **there is nothing normal in having a source code full of pitfalls and gotchas that need to be documented**. Talk with your product owner to reserve a few hours or days per week for large refactoring tasks (i.e. changes at design or architecture level). If you don't, the project is doomed, as every other project where technical debt was left increasing. Moreover, code-level refactoring should be your constant activity: whenever you work on a piece of code, ensure you follow the boy scout rule: “Leave your code better than you found it.” If a method is unclear because someone used one-letter names for the variables, don't keep it this way: rename them. It doesn't take long, and it will pay out the next time someone won't lose ten minutes trying to figure out how this method works. Most refactoring techniques are pretty simple and quick to implement, and many are very effective.
71,398,009
I have a Python script using Brownie that occasionally triggers a swap on Uniswap by sending a transaction to Optimism Network. It worked well for a few days (did multiple transactions successfully), but now each time it triggers a transaction, I get an error message: > > TransactionError: Tx dropped without known replacement > > > ![Complete error message](https://i.stack.imgur.com/cQQLX.png) However, the transaction goes through and get validated, but the script stops. ```js swap_router = interface.ISwapRouter(router_address) params = ( weth_address, dai_address, 3000, account.address, time.time() + 86400, amount * 10 ** 18, 0, 0, ) amountOut = swap_router.exactInputSingle(params, {"from": account}) ```
2022/03/08
[ "https://Stackoverflow.com/questions/71398009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18410235/" ]
There is a possibility that one of your methods seeks data off-chain and is being called prematurely before the confirmation is received. I had the same problem, and I managed to sort it out by adding time.sleep(60) at the end of the function that seeks for data off-chain
70,900,373
Like in this example, <https://www.duden.de/rechtschreibung/Regen_Niederschlag> , the words are sorted in the following way: "regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbö, Regenbogen..." that is, it is a "more non-case-sensitive" sorting than Collections.Sort() automatically does. Lowercase words come before uppercase ones like "regen, Regen". ``` ArrayList<String> regen = new ArrayList<String>( ); for(String x : new String[]{"regelwidrig", "Regelwidrigkeit", "Regelzeit", "regen", "Regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen"}) { regen.add(x); } ``` Collections.sort(regen) response: `[Regelwidrigkeit, Regelzeit, Regen, Regenabflussrohr, Regenanlage, Regenbogen, Regenbö,` `regelwidrig, regen, regenarm]// lowercase at the end` I can implement a comparator for this, but I'd rather take one-liner of code to get this way of sorting. Such as: Collections.SomeMethod(regen); or Collections.Sort(regen, some\_extra\_parameter); But I haven't found after deep google search, unfortunately.
2022/01/28
[ "https://Stackoverflow.com/questions/70900373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17677104/" ]
* You can use `String.CASE_INSENSITIVE_ORDER` to order strings in case-insensitive way. * If you also at the same time want to farther specify order of elements which current comparator considers as equal (like `String.CASE_INSENSITIVE_ORDER` would do for `"Regen"` and `"regen"`) then you can use [`Comparator#thenComparing`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Comparator.html#thenComparing(java.util.Comparator)) method and pass to it Comparator which would sort those equal elements like you want. + Assuming you would also want to order `"Regen", "regen"` as `"regen", "Regen"` (lower-case before upper-case) you can simply reverse their natural order with `Comparator.reverseOrder()`. So your code can look like: ``` regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder())); ``` Demo: ``` ArrayList<String> regen = new ArrayList<String>( Arrays.asList("regelwidrig", "Regelwidrigkeit", "Regelzeit", "Regen", "regen", "Regenabflussrohr", "Regenanlage", "regenarm", "Regenbö", "Regenbogen") ); regen.sort(String.CASE_INSENSITIVE_ORDER.thenComparing(Comparator.reverseOrder())); System.out.println(regen); ``` Result: `[regelwidrig, Regelwidrigkeit, Regelzeit, regen, Regen, Regenabflussrohr, Regenanlage, regenarm, Regenbogen, Regenbö]` (notice `"Regen"`, `"regen"` ware swapped)
548,798
The exercise is to find the accumulation points of the set $S=\{(\frac {1} {n}, \frac {1} {m}) \space m, n \in \mathbb N\}$ I'm trying to prove that if $A$={accumulation points of the set $S$}, then $A=\{(0,0), (\frac {1} {n},0),(0,\frac {1} {m}) \space n,m \in \mathbb N\}$. I could prove that the set of the right side of the equality is included in $A$. I don't know how to prove the other inclusion, which means that if $x$ is an accumulation point of $S$, then $x$ has to be $(0,0)$, or of the form $(\frac {1} {n},0)$ or $(0,\frac {1} {m})$.
2013/11/02
[ "https://math.stackexchange.com/questions/548798", "https://math.stackexchange.com", "https://math.stackexchange.com/users/100106/" ]
I think you might mean $N\cap Z(G) \neq \{e\}$. In which case, 1. Use the Class equation 2. If $x\in N$, then the conjugacy class $C(x) \subset N$
10,131,208
In my assets, I have a file called `maps.js.erb`, basically with only the following (debugging) content: ``` alert("<%= @map.width %>"); ``` This JS file is loaded through the `show.html.erb` view belonging to maps. ``` <%= javascript_include_tag params[:controller] %> <h1><%= @map.title %></h1> … ``` The HTML file itself shows the map's title, e.g. when browsing to `/maps/1/`, since `@map` is defined in the controller. However, as soon as I include the JS file, I get the following error: > > ### NoMethodError in Maps#show > > > Showing `…/app/views/maps/show.html.erb` where line #1 raised: > > > undefined method 'title' for nil:NilClass > (in `…/app/assets/javascripts/maps.js.erb`) > > > * Why is `@map` not available in the `js.erb` file? * How else can I access this instance variable defined in my controller?
2012/04/12
[ "https://Stackoverflow.com/questions/10131208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/435093/" ]
Ryan Bates did a screencast right on that topic - you might wanna check it out: <http://railscasts.com/episodes/324-passing-data-to-javascript> --- In the `html.erb` file, you can define the variables: ``` <%= javascript_tag do %> window.productsURL = "<%=j products_url %>"; window.products = <%=raw Product.limit(10).to_json %>; <% end %> ```
57,708
I can imagine that finding $p,q,n$ are easy, but my text book also says the $e$ can be found rapidly, so how does modern RSA find this $e$? ![RSA as a Public Key System](https://i.stack.imgur.com/LBR7F.png)
2018/03/22
[ "https://crypto.stackexchange.com/questions/57708", "https://crypto.stackexchange.com", "https://crypto.stackexchange.com/users/-1/" ]
Clarification ------------- > > I'm wondering whether there exists an encoding/hashing/encryption scheme whereby the original string can always be derived in its entirety given the entire encoded/hashed/encrypted string, and nothing else (no key/password). But also, no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string. > > > I am assuming that "no portion of the original string can be derived given any portion of the encoded/hashed/encrypted string" means "no portion of the original string can be derived given anything less than the entire encoded/hashed/encrypted string", otherwise the question would be self-contradictory. Answer ------ It sounds like you are looking for a permutation. A permutation is an invertible transformation on a fixed-size set of blocks. If your input is larger, the/an [All-Or-Nothing Transform](https://en.wikipedia.org/wiki/All-or-nothing_transform) may be useful. The OAEP mentioned by @DannyNiu is an example of an AONT. For example, many block ciphers are built by interleaving applications of a permutation with the addition of secret key material. The permutation provides diffusion, which ensures that if you modify any part of the output then attempt to invert it, you end up back at a completely different input. If you simply strip the key addition portion from a block cipher, it should also do what you're asking. For example, [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) consists of subBytes, mixColumns, shiftRows, and addRoundKey. If you were to omit the addRoundkey operation, you would be left with a fixed permutation that provides the required avalanche effect and some degree of unpredictability. Another example of a permutation is [keccak-f](https://en.wikipedia.org/wiki/Keccak#The_block_permutation), which does the mixing for the [SHA3 algorithm](http://en.wikipedia.org/wiki/Keccak). A key-less permutation does not provide encryption -------------------------------------------------- Note that such a construction with no key is no longer providing *encryption*, as it is not possible to provide confidentiality of the message without some kind of secrecy, which is what the key provides. If anyone who has an input message can compute an output "ciphertext", or anyone who has an output "ciphertext" can invert it to the input message, then clearly confidentiality of the input cannot be achieved. You tagged this question with "encoding", so perhaps confidentiality is not required in your use case. You would need to establish what you need this construction for and whether or not this is an issue.
19,334,041
I moved a database from SQL Server 2012 to Azure. I don't want to use the user `master`, so I created a user `test`. This is what I did for database XXX on Azure: ``` create user test from login test with default_schema=[dbo] exec sp_addrolemember 'db_owner','test' ``` I checked, and the database objects I am interested in are all in the schema `dbo`. The table `Users` is in the schema `dbo`. The connection string in my web project has `test` as the login. It produces the error message: ``` The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo' ``` What does the error message mean and what can I do to let user `test` access the database XXX?
2013/10/12
[ "https://Stackoverflow.com/questions/19334041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/936293/" ]
I think the problem is with the user having **deny privileges**. This error comes when the user which you have created does not have the sufficient privileges to access your tables in the database. Do grant the privilege to the user in order to get what you want. **[GRANT](https://learn.microsoft.com/en-us/sql/t-sql/statements/grant-object-permissions-transact-sql)** the user specific permissions such as SELECT, INSERT, UPDATE and DELETE on tables in that database.
3,533,014
I am having an AIR applicaiton which is supposed to uncompress the file of huge size (>1GB) I tried commonly discussed utilities i.e. FZip nochump and few more I face the same problem with all of them, They tyr to unzip the entire file in the memory (using ByteArray.defalte method) This works well with the files of small size howevre they just hang the applicaiton if the size of the file is big (>1GB) Any suggestions?
2010/08/20
[ "https://Stackoverflow.com/questions/3533014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426556/" ]
Just instantiate a view in the desired size, add a UIImageView with the backround image on it and add your buttons ``` UIView *overlayView = [[UIView alloc] initWithFrame:aRect]; UIImageView *bgView =[[UIImageView alloc] initWithImage:[UIImage imageNamed:thePath]]; [overlayView addSubview:bgView]; [overayView addSubview:aButton]; [aButton release]; [bgView release]; ``` *untested* This code could be executed by a [UILongPressGestureRecognizer](http://developer.apple.com/iphone/library/documentation/uikit/reference/UIGestureRecognizer_Class/Reference/Reference.html)
6,372,248
I have a problem and need some help. My application uses outlook to send email with attachments. Right now i need to find out when the email with attachment has been send out completely by outlook. I tried to follow this [link](http://social.msdn.microsoft.com/forums/en-US/vsto/thread/d891c669-21af-4ce4-b24b-8f6eb2308227) but the ItemEvents\_10\_SendEventHandler does not fulfil my task as outlook will still be attaching the document when this event is fired. I found out that the email takes time to send out due to the attachment and the duration depends on the attachment size. I want my program to be notified if possible or wait until the email has been send out completely. Can someone guide me or tell me the approach on how to get this to work. Any help provided will be greatly appericiated.
2011/06/16
[ "https://Stackoverflow.com/questions/6372248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293240/" ]
Mostly not, modern CPU's are very fast... The most notable improvement is the speed in the download speeds. Strip out any unnecessary comments sent down the wire to the browser, minify CSS, JavaScript files, use CDN's etc.
1,002,429
I used to have a Server 2003 R2 Hyper-V VM instance running on an Server 2012 R2. The performance was very good. THen, I was told that 2003 wasn't being supported anymore by a software package I use, so I upgraded to 2008 R2, and that's when all my SMB shares took a nosedive. When I attempt to navigate to my network drive using SMB2 (verified using wireshark), When I open a folder, it takes almost a minute to list the content of the folder. Using 2003, it was instantaneous. Then, when I move my mouse cursor over a file in the folder, windows explorer locks up for another minute. Wireshark doesn't produce anything other than Keep-Alive messages while I wait for a response from the server. Any ideas as to why this is happening after my upgrade?
2020/02/09
[ "https://serverfault.com/questions/1002429", "https://serverfault.com", "https://serverfault.com/users/559370/" ]
I should have read [the manual](https://www.freedesktop.org/software/systemd/man/systemd.link.html) more carefully. > > The first (in lexical order) of the link files that matches a given device is applied. Note that a default file 99-default.link is shipped by the system. Any user-supplied .link should hence have a lexically earlier name to be considered at all. > > > Renaming `/etc/systemd/network/ens19.link` to `/etc/systemd/network/00-ens19.link` helped. `[MATCH]` should be `[Match]` and `[LINK]` should be `[Link]`. To apply a changed .link file to the link I can reboot or run ``` udevadm test-builtin net_setup_link /sys/class/net/ens19 ``` (Because .link files are processed by udev and not systemd-networkd, restarting systemd-networkd is insufficient.)
385,136
Got a skeptical question about a reverse proxy setup I'm considering. I've currently got a pair of load balanced application servers in the DMZ (S1,S2 in figure below). These accept inbound requests from external clients. They also connections to internal network resources (e.g. DB server, message broker) The DMZ setup is pretty standard: two firewalls -- internal and external facing. The external-facing firewall only allows in external requests to specific server resources on specific ports. The internal-facing firewall only allows the DMZ servers to open specified connections to internal network resources (e.g. DB server, message broker) Now, I have an architectural proposal stating this setup is insecure. The proposal calls for moving the two DMZ servers into the internal network. In the DMZ, they will be replaced by a 'Reverse Proxy' server ('RP' in figure below). The 'RP' will accept inbound requests and proxy them to the S1/S2. The key selling point here is the internal servers *initiate* the network connectivity to the 'reverse proxy' server in the DMZ. So, this: ``` [EXTERNAL] [DMZ] [INTERNAL] Client --> || S1/S2 || --> DB,MQ ``` ...is being replaced by this: ``` [EXTERNAL] [DMZ] [INTERNAL] Client --> || RP || <-- S1/S2 --> DB,MQ ``` RP is essentially a stripped down version of S1/S2 (same technology stack). It conveys the external request to S1/S2 over a persistent connection initiated by S1/S2. **My question:** Given that technology stack for RP is identical to S1/S2 (same tech, less code) -- how does the new setup confer significant additional protection? Won't application attacks get through to S1/S2 unmolested? Specifically, if you compromise RP, you can compromise S1/S2 too. Won't this actually worsen the risk profile (since S1/S2 are now in the internal network)? --- Adding some info and expanding on a point above: 1. The load balancer ('LB') is essentially transparent in this setup (i.e. RP is not a LB). For various reasons, LB cannot terminate inbound requests in any way. 2. Personally, I'm *very* skeptical of the security RP adds. My reasoning: if RP is somehow fully compromised (e.g. buffer overrun/shellcode), its an easy ride over the connection to S1/S2 in the internal network (doesn't matter who initiates the connection - its there), and then a similar exploit on S1/S2 (thanks to similar tech). The problem now is worsened because the compromised S1/S2 are now sited in the soft underbelly (i.e. the intranet), instead of the DMZ.
2012/05/02
[ "https://serverfault.com/questions/385136", "https://serverfault.com", "https://serverfault.com/users/119598/" ]
Silly problem - simple solution once I tracked down the right ference I had selected to perform a custom install of nginx with passenger when doing so it did not add the ``` passenger_root passenger_ruby ``` variables to nginx.conf so passenger was not being initialized hope this helps someone running into the same issue
4,069,054
I cannot seem to find an answer for this anywhere. Superuser *root* has a crontab with a couple of jobs that send the resultant output to *root's* mailbox addressed **from** my non-superuser account *foo*. It is my understanding that the owner of the cron job is supposed to be the sender of the resultant cron job output. Account *foo* does not have a crontab, and in-fact I have even tried explicitly removing *foo's* crontab, but still *root* receives *root's* cron job output from user *foo*. When I edit *root's* crontab, I log into the system as *foo*, and then `su -` to *root*. Does this have anything to do with it? When I `ls -alF /var/spool/cron/crontabs` there is no file for user *foo*. Does anyone know why my non-superuser account *foo*, that does not have a crontab file, seems to be sending mail to superuser *root*? It also seems that for some of *root's* cron jobs, that it executes as *root* **and** as *foo* which both send email to *root's* mailbox. Example: From foo Sat Oct 30 19:01:01 2010 Received: by XXXXXX (8.8.8/1.1.22.3/15Jan03-1152AM) id TAA0000027883; Sat, 30 Oct 2010 19:01:01 -0400 (EDT) Date: Sat, 30 Oct 2010 19:01:01 -0400 (EDT) From: foo Message-Id: <201010302301.TAA0000027883@XXXXXX> *redacted* --- Cron: The previous message is the standard output and standard error of one of your cron commands. From root Sat Oct 30 19:01:01 2010 Received: by XXXXXX (8.8.8/1.1.22.3/15Jan03-1152AM) id TAA0000025999; Sat, 30 Oct 2010 19:01:01 -0400 (EDT) Date: Sat, 30 Oct 2010 19:01:01 -0400 (EDT) From: system privileged account Message-Id: <201010302301.TAA0000025999@XXXXXX> *redacted* --- Cron: The previous message is the standard output and standard error of one of your cron commands.
2010/11/01
[ "https://Stackoverflow.com/questions/4069054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493585/" ]
Copy the form in visual studio solution explorer. Rename it. And **change the class name manually both in .cs and .Designer.cs files**. Do not use VS refactoring feature as it blows away references to the original class.
9,354,945
I'm trying to to resize my image (from URL) to full screen in my iPhone. However, the size 320x480 which is supposed to be full size is not full screen. ``` -(IBAction)changeFullSize{ urlImage.contentMode = UIViewContentModeScaleAspectFit; urlImage.frame = CGRectMake(0,0,320,480); } ``` I'm using a `UIButton` here, so when the user clicks on the opaque button, it changes to a full sized image. However, there is an empty space between the tab bar at the top and the start of the picture. What is the correct size for full screen? Is there a way for it to automatically resize to full screen without me specifying the width and height? Thanks.
2012/02/20
[ "https://Stackoverflow.com/questions/9354945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1210581/" ]
You could try and get it from `self.view.frame.size` but for the entire screen you can use `[[UIScreen mainScreen] bounds]`. Hope this helps.
91,001
I'm an ardent physicalist with a belief in the importance of the partial reduction of theories to physicalism. I have on occasion had discussions with philosophers here who challenge the existence of the natural/supernatural dichotomy, or in some way endorse supernaturalism. My question is directed at those who know something about theology and supernaturalism. Thus, despite ontologically rejecting supernaturalism and magic myself, I'm curious about the metaphysical presuppositions of others that entail belief. EDIT <<< (In response to comments: Naturalism for me is everything conveyed by an athiestic conception of a pluralism of sciences with partial reduction of theory with pragmatic criteria for the distinction of pseudoscience that takes a middle ground between realism and instrumentalism. Supernaturalism is therefore any ontological category outside of this.) <<< **Simply put, for philosophical positions (even of non-Western schools) that accept supernaturalism, does acceptance metaphysically necessitate 'magic' as a category?** My sense is modern theologians accept 'miracles', but reject 'magic' based on my own discussions with those who profess the [Book of Concord](https://en.wikipedia.org/wiki/Book_of_Concord) as a faithful characterization of Christian doctrine. But theology and supernaturalism is much broader than being a confessional Lutheran, so any relevant perspective, including historical philosophy such as the text of [Mauro Allegranza's link](https://en.wikipedia.org/wiki/Renaissance_magic) is of interest.
2022/05/03
[ "https://philosophy.stackexchange.com/questions/91001", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/40730/" ]
The range of supernaturalism is much broader and more general than the religious doctrines contained in the Book of Concord. Taking the definitions from [wikipedia](https://en.wikipedia.org/wiki/Supernatural#Magic) (emphasis J.W.): * The **supernatural** is phenomena or entities that are not subject to the laws of nature. […] The term is attributed to non-physical entities, such as angels, demons, gods, and spirits. It also includes claimed abilities embodied in or provided by such beings, including magic, telekinesis, levitation, precognition, and extrasensory perception. * The philosophy of **naturalism** contends that nothing exists beyond the natural world, and as such approaches supernatural claims with skepticism. * **Magic** or sorcery is the use of rituals, symbols, actions, gestures, or language with the aim of utilizing supernatural forces. Hence Magic presupposes the existence of supernatural entities and forces. From a logical point of view the opposite relation does not hold. Because one may believe in the existence of supernatural entities but assume that we cannot influence them.
45,968,642
I am wondering how to get the width of a `th` and set all of the `td` under this header to be the same width. Next `th` would be a different width and all of the `td` under this `th` would be that appropriate width, different from the first. Essentially trying to line up my `thead` and `tbody` columns relative to eachother. The structure of my table is: ``` <table id="my_table"> <thead> <tr> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> ``` The CSS is as follows for a scroll able table: ``` #my_table thead, #my_table tbody { display: inline-block; overflow: auto; width: 100%; } #my_table thead{ height: 100px; } #my_table tbody{ height: 300px; } ``` The data that goes into th is dynamic and makes the width of the cell different every time. Using jQuery, I am stuck with this not sure how to iterate through each `th` and assign the width to its corresponding `td`: ``` var table = document.getElementById('#my_table'); table.find('th').each(function() { var header_width = this.width(); $table.width(header_width); }); ``` Although this is not working. I feel as if I am using the `each()` function incorrectly. Any ideas?
2017/08/30
[ "https://Stackoverflow.com/questions/45968642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7163580/" ]
Try this, is ugly and is not efficient but should do what you want to do: ``` var table = document.getElementById('#my_table'); table.find('th').each(function(index) { var header_width = this.width(); table.find('tr').each(function() { $(this).find('td:nth-child('+index+')').width(header_width); }); }); ``` Note: I didn't check the syntax, so it may contain a bug.
383,330
How many elements are in the kernel of the homomorphism $f:(\mathbb{Z}/154\mathbb{Z})^\* \to (\mathbb{Z}/154\mathbb{Z})^\* $ where $f(x)=x^5$? The group operation in this case is multiplication with identity element $1 \mod 154$, so the group we are considering is $((\mathbb{Z}/154\mathbb{Z})^\*,\cdot,\overline{1})$. The kernel of a homomorphism is given by: $$\operatorname{Ker}(f):=\{ g\in G|f(g) =e\_G\}$$ There is a theorem that states that for any element in a group, the order of that element is either infinite or it must divide the number of elements in the group. In $(\mathbb{Z}/154 \mathbb{Z})^\*$ there are 154 elements and $5 \nmid 154$. Therefore there are no element of order 5 and because 5 is prime no element other than the identity satisfies $x^5=e$. Therefore the kernel of $f$ contains only the identity element $1 \mod 154$. Is this correct or are there more elements in the kernel? The reason for this question is that I am not sure if this argument alone is enough. Thanks in advance! **EDIT** I realise that I completely forgot to add the $^\*$ to the group $\mathbb(Z)/154\mathbb{Z}$ when I first wrote this question and subsequently in trying to determine the number of elements made a mistake. I realise now that I need to evaluate $\phi(154)$ to find the number of elements and see if $5|\phi(154)$ where $\phi$ is the Euler-Totient function. I am sorry for the confusion.
2013/05/06
[ "https://math.stackexchange.com/questions/383330", "https://math.stackexchange.com", "https://math.stackexchange.com/users/59157/" ]
The problem is that $\mathbb{Z}\_{154}^\star $ [does not](http://en.wikipedia.org/wiki/Multiplicative_group_of_integers_modulo_n), as you've said, have $154$ elements. Note that $\varphi(154)=60$.
143,675
My Windows 7 setup uses around 16GB while Windows XP only needs around 4GB hard disk space. Seems weird. I use Windows only for gaming so I don't need a lot of stuff they have to offer. What is the best way to reduce the size of Windows 7? What can I delete / uninstall and how? I'd also like to reduce the CPU and memory usage as much as possible (as long as it doesnt hurt game performance) - turning off all that fancy stuff and so on. What can I turn off and how?
2010/05/21
[ "https://superuser.com/questions/143675", "https://superuser.com", "https://superuser.com/users/25345/" ]
4GB XP? 16GB Win7? That seems an awful lot. My vanilla win7 install on VirtualBox was around 5GB, and you can certainly get XP down to 700MB or so. Use a visualisation tool such as [WinDirStat](http://windirstat.info/) to find out what's taking up all that disc. Stuff to target, if you don't need it and you really know what you're doing: * unused Windows components (Control Panel -> Add/Remove -> Windows components, or in Vista+, All Control Panel -> Programs and Features -> Turn Windows features on or off) * System Restore * \Windows\System32\dllcache on XP * \Windows\System32\DriverStore\FileRepository on Vista+, if you're sure you're not going to need any more drivers out of it * \Windows\SoftwareDistribution\Download * %TEMP%, the IE cache, the trash * patch rollbacks (hidden $ folders in \Windows on XP) * example shared media and \Windows\Web * disable virtual memory to get rid of the pagefile (assuming you have enough memory to run swapless) * disable hibernation to get read of hiberfil * delete the large Chinese/Japanese/Korean fonts, if you don't use them * all vendor crapware (if an OEM install) must be destroyed as a matter of course For some of these on Win7 you have to take ownership of the files back from SYSTEM before you can delete them.
38,705,614
I have a div that its content is pulled from innerhtml as shown ``` var users = ''; for (var i = 0; i < json.length; i++) { users += '<strong>' + json[i].name + '</strong><br/>'; } users_container.innerHTML = users; } ``` this is the div that the innerhtml replaces its content. The content of the div only displays for some seconds and disappears. ``` <div id="users-container" class="inner-container"> <h3>Active users</h3> </div> ``` Please how can I retain the content of the div as a header while the innerhtml contents is displayed as well. Kindly assist!
2016/08/01
[ "https://Stackoverflow.com/questions/38705614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5220210/" ]
You can use a specific `div` for the `users` content and keep the original content of your `div`. **JavaScript:** ``` var users_div = document.getElementById("users_div"); var users = ''; for (var i = 0; i < json.length; i++) { users += '<strong>' + json[i].name + '</strong><br/>'; } users_div.innerHTML = users; } ``` **HTML:** ``` <div id="users-container" class="inner-container"> <h3>Active users</h3> <div id="users_div"> </div> </div> ```
55,652,352
I have a problem. The concept of Object Oriented Programming in C got homework. I need to use variadic functions. But I get a mistake. I'd appreciate it if you could help me. I'm new to encoding. RastgeleKarakter.h : ``` #ifndef RASTGELEKARAKTER_H #define RASTGELEKARAKTER_H struct RASTGELEKARAKTER{ // code }; RastgeleKarakter SKarakterOlustur(int...); // prototype void Print(const RastgeleKarakter); #endif ``` RastgeleKarakter.c : ``` #include "RastgeleKarakter.h" #include "stdarg.h RastgeleKarakter SKarakterOlustur(int... characters){ //code } ``` Error : ``` make gcc -I ./include/ -o ./lib/test.o -c ./src/Test.c In file included from ./src/Test.c:3:0: ./include/RastgeleKarakter.h:17:38: error: expected ';', ',' or ')' before '...' token RastgeleKarakter SKarakterOlustur(int...); ``` I don't know how many parameters there are. I want to solve this with the variable function.
2019/04/12
[ "https://Stackoverflow.com/questions/55652352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9409166/" ]
So my solution was to simply check if the user was already authenticated in my `[HttpGet]` login controller as opposed to my `[HttpPost]` login controller. ``` [HttpGet] public ActionResult Login() { if (User.Identity.IsAuthenticated) return RedirectToAction("Index", "Dashboard"); return View(); } [HttpPost] public async Task<IActionResult> Login(LoginViewModel req) { return View(req); } ```
15,289,765
I'm searching an userpicker that looks like Gmail, that when you add a "To" address, it becomes a label, or like StackOverflow when you add tags I've found this plugin: <http://htmlpreview.github.com/?https://github.com/ErikNoren/entitypicker/blob/master/entitypickerdemo.html> but I would like to find more plugins to compare... In my case, In my case, I need to convert two values (mail and phone) in one label...How can I do it?? Thank you very much!
2013/03/08
[ "https://Stackoverflow.com/questions/15289765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My current autocomplete plugin of choice is Select2. You can find it here <http://ivaynberg.github.io/select2/>