INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Program for working with DFA/NFA/PDA? I'm looking for a program or utility to help construct DFA/NFA/PDA etc. and the like. The main reason I'm interested in this, is because I want to be able to move the various states around without breaking their component connections, or having to redraw all the connections to their new place (otherwise I'd be doing this by hand! :P ) Please let me know if there's a better SE site for this.
JFlap is a pretty useful tool. I have also used Grapher which may be downloaded from here: <
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "computer science, automata" }
Rounding up/down to number I have a bunch of integers i need to round up or down, to the closest value which divides by 25. For instance: 417 rounds up to 425 405 rounds down to 400
int roundedValue = (valueToRound + 12) / 25 * 25;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java" }
How to get whole and decimal part of a number? Given, say, 1.25 - how do I get "1" and ."25" parts of this number? I need to check if the decimal part is .0, .25, .5, or .75.
$n = 1.25; $whole = floor($n); // 1 $fraction = $n - $whole; // .25 Then compare against 1/4, 1/2, 3/4, etc. * * * In cases of negative numbers, use this: function NumberBreakdown($number, $returnUnsigned = false) { $negative = 1; if ($number < 0) { $negative = -1; $number *= -1; } if ($returnUnsigned){ return array( floor($number), ($number - floor($number)) ); } return array( floor($number) * $negative, ($number - floor($number)) * $negative ); } The `$returnUnsigned` stops it from making **-1.25** in to **-1** & **-0.25**
stackexchange-stackoverflow
{ "answer_score": 216, "question_score": 123, "tags": "php, math" }
Does every neighborhood of a closed set $F$ in a metric space contain an $\varepsilon$-neighborhood of $F$? Let $(X, d)$ be a metric space, $F$ a closed subset of $X$, and $U$ an open neighborhood of $F$. Define the distance from a point $x \in X$ to $F$ as $$ d(x, F) = \inf_{y \in F} d(x, y), $$ and define the $\varepsilon$-neighborhood of $F$ to be $$ B_d(F, \varepsilon) = \\{ x \in X : d(x, F) < \varepsilon\\}. $$ Is it true that the $\varepsilon$-neighborhood of $F$ is contained in $U$ for some sufficiently small $\varepsilon$?
Nope. Let $(X,d)$ be the real plane with the usual metric, let $F$ be the horizontal axis, and let $U=\\{(x,y):y\lt e^x\\}.$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "real analysis, general topology, analysis, metric spaces, supremum and infimum" }
Iteration of an operator > Let $f_0(x)$ be integrable on $[0,1]$, and $f_0(x)>0$. We define $f_n$ iteratively by $$f_n(x)=\sqrt{\int_0^x f_{n-1}(t)dt}$$ The question is, what is $\lim_{n\to\infty} f_n(x)$? The fix point for operator $\sqrt{\int_0^x\cdot dt}$ is $f(x)=\frac{x}{2}$. But it's a bit hard to prove this result. I have tried approximate $f(x)$ by polynomials, but it's hard to compute $f_n$ when $f_0(x)=x^n$ since the coefficient is quite sophisticated. Thanks!
1) If $f_0(x)\equiv 1$, It is easy to check $f(x)=\frac x2$. 2) If there exists $m,M >0$ such that $m<f_0(x)<M$, then $$\sqrt{mx}=\sqrt{\int_0^xmdt} \leq f_1(x)\leq \sqrt{\int_0^xMdt}=\sqrt{Mx}$$ and $$ \sqrt{\int_0^x\sqrt{mt}dt} \leq f_2(x)\leq \sqrt{\int_0^x\sqrt{Mt}dt} $$ and so on Thanks to 1), it follows that $f(x)=\frac x2$. 3). If $\inf\\{f_0(x)\\}=0$, then Approximation ! choose $\epsilon >0$, think interval $[\epsilon,1]$, begin with $f_1(x)$, not $f_0(x)$ there exists $m,M >0$ such that $m<f_1(x)<M, x\in[\epsilon,1]$, $$\sqrt{m(x-\epsilon)}=\sqrt{\int_\epsilon^xmdt} \leq f_2(x)\leq \sqrt{\int_0^xMdt}=\sqrt{Mx}, x\in [\epsilon,1]$$ and so on, we get that $$\frac{x-\epsilon}2\le f(x)\le\frac x2$$ Let $\epsilon \to 0$, it follows that $f(x)=\frac x2$.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "analysis" }
Issues with circular bit-shift in C++ I'm attempting to implement circular bit-shifting in C++. It kind of works, except after a certain point I get a bunch of zeroes. for (int n=0;n<12;n++) { unsigned char x=0x0f; x=((x<<n)|(x>>(8-n))); //chars are 8 bits cout<<hex<<"0x"<<(int)x<<endl; } My output is: 0xf 0x1e 0x3c 0x78 0xf0 0xe1 0xc3 0x87 0xf 0x0 0x0 0x0 As you can see, I start getting 0x0's instead of the expected 0x1e, 0x3c, etc. If I expand the for loop to iterate 60 times or so, the numbers come back correctly (after a bunch of zeroes.) I'm assuming that a char houses a big space, and the "gaps" of unused data are zeroes. My understanding is a bit limited, so any suggestions would be appreciated. Is there a way to toss out those zeroes?
Shifting by a negative amount is undefined behavior. You loop from `0` to `12`, but you have an `8 - n` in your shifts. So that will go negative. If you want to handle `n > 8`, you'll need to take a modulus by 8. (assuming you want 8-bit circular shift.) * * * for (int n=0; n < 12; n++) { unsigned char x = 0x0f; int shift = n % 8; // Wrap modulus x = ((x << shift) | (x >> (8 - shift))); //chars are 8 bits cout << hex << "0x" << (int)x << endl; }
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "c++, bit manipulation" }
Coaxial CATV to power line adapter When I renovated my apartment and redid my electrical wiring, I missed the chance to set up network and tv cable too. While internet is fortunately solved by Wi-Fi, I am not so lucky about TV. The signal is delivered by the provider via coaxial cables. I noticed there are devices on the market that can pass internet signal over power lines and wondered if there is something similar for TV signal? My searches returned nothing. If this is not possible, is there any other way to pass TV signal without a lot of new wires around the house?
There is not really such a product since power cables are unable to carry the bandwidth needed for broadband signals such as CATV. The best you might be able to do is a remote video sharing device that is hooked to the CATV tuner. These devices take HDMI from your video source, transmit it over WiFi, and then turn it back into HDMI at the receiver. This article offers some options: HDMI over WiFi To quote a section: > The Iogear GW3DHDKIT Wireless HDMI Digital Kit is the best HDMI transmitter for most people. Using WHDI, it delivers the best image from the lengthiest distances, has two HDMI inputs, and can be powered via an included AC adapter or your TV’s USB 3.0 connection (cables not included). It’s also the least expensive dual HDMI unit we tested. I know nothing about this particular unit but it or something like it may do the job.
stackexchange-diy
{ "answer_score": 1, "question_score": 0, "tags": "electrical, television, coaxial cable, catv" }
logarithm in basis $x$ is it always equal to 1? Is the logarithm function $ y = \log_{x} (x) $ always '1' for $x > 0$, this is equal to the implicit function $ x=x^{y} $ so $ y=1$
Almost. Due to the logarithm law $$\log_a b=\frac{\log_cb}{\log_c a}$$ just plug in $a=b$. However, there are two restrictions: $a$, $b$ and $c$ must be positive; and $a$ and $c$ must not be 1 because log to base 1 makes no sense resp. we would divide by 0 in the fraction above. Hence the answer to your question is _" yes, but $x$ must not be 1"_.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "logarithms" }
Calculating differences in a vector for specific elements I want to calculate the differences between elements in a vector, using the function diff. But I only want to do this for the elements that take on a certain value. Let's say I have a vector v <- c(0,1,3,5,0,7,6,0,9,0,7,2) and I only want the differences from the zeros (or any other value). So I would get the result 1,7,9,7. I want to write something like: diff(v for which v == 0) But I dont know how.
Since you want to use `diff` for elements with 0, we can select the elements which are next to 0 because any number subtracted by 0 is the same number. v[which(v == 0) + 1] #[1] 1 7 9 7 * * * If there is any other number apart from 0 we want to use `diff` we can select the next number and subtract it with that number. v[which(v == 0) + 1] - v[which(v == 0)] #[1] 1 7 9 7 With 7 v[which(v == 7) + 1] - v[which(v == 7)] #[1] -1 -5 * * * If we want to use `diff` we can get the indices which are 0 and the number next to it, `split` it based on occurrence of 0 and calculate the difference using `diff`. inds <- which(v == 0) v1 <- v[sort(c(inds, inds + 1))] sapply(split(v1, cumsum(v1 == 0)), diff) #1 2 3 4 #1 7 9 7
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r" }
How to use admin interface if I have no application? I am creating a Django based app and I'd like to put everything under the root in the following structure: /path/to/my/app/ settings.py models.py urls.py admin.py ... One problem that I run into is the admin interface doesn't include whatever models I have that are registerd in admin.py usin admin.site.register(models.MyModel) Usually that's done by using auto discover in urls.py, but now I have no registered "app", the auto discover doesn't work anymore. Is there anyway I can still use the admin interface? Thanks.
Django simply doesn't work without apps. They're the fundamental building block of a Django site. A whole range of things, not just the admin, will fail to work. Why do you want to do this?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "django" }
Fourier transform of the components of bandpass signals I'm referring to a book called _Communication Systems by Simon Haykin, 3rd Ed._ It says that a band-pass signal \$s(t)\$ with mid-band frequency \$f_c\$ and bandwidth \$2W\$ can be represented as follows: $$ s(t) = s_I(t)\cos(2\pi f_c t) - s_Q\sin(2\pi f_c t) $$ where \$s_I(t)\$ is the in-phase component of \$s(t)\$, and \$s_Q(t)\$ is the quadrature-phase component of \$s(t)\$. Following this, it says that the Fourier transform of \$s_I(t)\$ is related to that of \$s(t)\$ by $$ S_I(f) = \left\\{\begin{matrix} S(f-f_c) + S(f+f_c), & -W\leq f\leq W \\\ 0, & \text{elsewhere} \end{matrix}\right. $$ Similarly for \$s_Q(t)\$, $$ S_Q(f) = \left\\{\begin{matrix} j[S(f-f_c) - S(f+f_c)], & -W\leq f\leq W \\\ 0, & \text{elsewhere} \end{matrix}\right. $$ I can't understand how the relations between \$S_I(f)\$ and \$S(f)\$, and \$S_Q(f)\$ and \$S(f)\$ are being derived.
If you multiply \$s(t)\$ with \$2\cos(2\pi f_c t)\$ and with \$-2\sin(2\pi f_c t)\$, respectively (i.e. you are actually demodulating the signal), you get: $$s(t)\cdot2\cos(2\pi f_c t)=2s_I(t)\cos^2(2\pi f_c t)-2s_Q(t)\sin(2\pi f_c t)\cos(2\pi f_c t)=\\\ =s_I(t)+[s_I(t)\cos(2\cdot2\pi f_c t)-s_Q(t)\sin(2\cdot2\pi f_c t)]$$ and $$-s(t)\cdot2\sin(2\pi f_c t)=-2s_I(t)\cos(2\pi f_c t)\sin(2\pi f_c t)+2s_Q(t)\sin^2(2\pi f_c t)=\\\ =s_Q(t)-[s_I(t)\sin(2\cdot2\pi f_c t)+s_Q(t)\cos(2\cdot2\pi f_c t)]$$ Note that the terms in brackets are centered at twice the carrier frequency \$f_c\$. So in the band \$-W<f<W\$ (i.e. by low-pass filtering) we get $$s(t)\cdot2\cos(2\pi f_c t)=s_I(t)\\\ -s(t)\cdot2\sin(2\pi f_c t)=s_Q(t)$$ If you take the Fourier transform of these two equations you obtain the Fourier relations stated in your question.
stackexchange-electronics
{ "answer_score": 1, "question_score": 1, "tags": "signal, communication, modulation" }
Add an associative array to an array - How to? I have an array structure, like this: $families = array ( "Griffin"=>array ( "Father" => "Peter", "Mother" => "Lois", "Child" => "Megan" ), "Brown"=>array ( "Father" => "Cleveland", "Mother" => "Loretta", "Child" => "Junior" ) ); My question is: How do I add another array called "Simpsons" to this structure with "Homer", "Marge" and "Bart" as the data? Thanks guys....
$families['Simpsons'] = array( 'Father' => 'Homer', 'Mother' => 'Marge', 'Child' => 'Bart' );
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "php, arrays" }
How do I display content from another website that requires the user being logged in? Say I have a website that requires a login, hosted somewhere remote. I would like to make a portal that shows this remote site but should always be logged in with the same user name and password on this remote site. If possible the portal should ask for a username and password and then use an iframe ( or something similar now that they are being phased out) to display this remote site where you shoudl be logged in. I would like to know if there is a web-ap for something like this, if not whether this would be possible to create. I do have access to a VPS running centos 64bit and a managed host.
Have you looked into OpenID?
stackexchange-webmasters
{ "answer_score": 1, "question_score": 0, "tags": "web development, web applications, authentication" }
JEditorPane unexpected behavior with new lines I am trying to highlight text in a `JEditorPane` text field and save the index of the selected text. However I keep running into problems when I save the selections. The JEditorPane seems to save new lines in a different way each time. It will write a `"\n"`, a `"\r"` and sometimes even a `"\r\n"` when the user presses the enter key. And sometimes the JEditorPane will even ignore carriage returns which causes wrong selection indices. Is it possible to get a consistent behavior when the user presses the enter key?
Why are you using a JEditorPane. That is for displaying HTML and HTML generally doesn't have line breaks. You use the "br" tag in HTML. For normal text you should be using either a JTextPane or JTextArea. > I am trying to highlight text The text in a string depends on the component you are using and whether you get the text from the Document or the component. In general you should get the text from the Document since the Document only stores the "\n" so you should be able to calculate the offset correctly and highlight the text. When you get the text from the component, the platform new line String is inserted in the text which would cause your offset problems. See Text and New Lines for more information.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, swing, jeditorpane" }
BASH - how to construct a path in an .sh script using external property? I have a property `s3Path=s3a://myBucket` in a file `s3-apps.properties` Currently the path to a `S3` is hardcoded in my bash script: thePath="s3a://myBucket/myApp" I want to get the property from the file instead and concatenate it with `/myApp` So I'm getting path to the file like this: file="/apps/properties/various/s3-apps.properties" But how do I get the property and concatenate it to construct a path? I guess that it should be something like this but it did not work for me: thePath="s3a://{$file.s3Path}/myApp" Non of the answers from the `"Duplicate"` helped me in understanding an solving my question. But the `@cody` answer below was correct and helped.
If you're using GNU grep, the following would work: $ s3path=$(grep -Po '(?<=s3Path=).+$' "$file") $ echo $s3path s3a://myBucket
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bash, shell" }
How can I get the mode (Statistic) in Visual Studio? Basically, in a textbox (txtEl) I'm writing the length of the vector, then add it random numbers (from 1 to 500), showing all of them in a listbox. But I don't know how to get the mode from all those numbers. Random Aleatorio = new Random(); int x = Convert.ToInt16(txtEl.Text); int[] elementos = new int [x]; int moda = 0; for (int i = 0; i < elementos.Length; i++) { elementos[i] = Aleatorio.Next(1, 500); listEl.Items.Add(elementos[i].ToString()); }
You can do something like this Im not real sure what listEl is but you should be able to use it here. If not just add them to a basic list also. var mode = (from item in listEl.Items group item by item into g orderby g.Count() descending select g.Key).First();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, mode" }
For how many years after I file my tax do I need to retain my documents I have copies of t4 and rrsp slips sitting in my tiny condo and eating up valuable storage space since 2009. Can I throw them away? How many years after you file a return are you required to keep your documents in case CRA wants to see them?
CRA suggests keeping them for 6 years : <
stackexchange-money
{ "answer_score": 2, "question_score": 1, "tags": "taxes, canada revenue agency" }
Can mongo handle multiple tailable cursors on the same collection We are using multiple tailable cursor on the same collection, it seems to be having deleterious effect on performance, is this expected? what can be done to improve performance with this setup or must it be changed?
Multiple tailable cursors are fine. Indeed, many of Mongo's internal operations, like replication from a primary to multiple secondaries in a replica set, are implemented with tailable cursors.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mongodb" }
Multiple Interfaces in Java - what's the syntax? I want to implement 3 interfaces in my class. I am not sure whether this is even possible, because as far as I know, a class can only inherit from one other class. Do the interfaces behave different? If they do, how do I implement more then one interface? I have tried this, but it does not work... public class Container implements InterfaceI implements InterfaceII implements InterfaceIII { //... } Thanks for any help. Bene
You have to use a comma, each time you add one interface and use "implements" only one time. So yes, you can implement more interfaces :D So it looks like this: public class Container implements InterfaceI, InterfaceII, InterfaceIII { //... } John
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -4, "tags": "java, interface" }
Roomba s9 -- no communication I connected my Roomba s9+ USB port to my Windows 10 PC, which cannot detect it (nothing under Ports): ![enter image description here]( I messed around a bit and updated drivers, and now Windows 10 detects Roomba as: ![Windows 10 device detection]( I don't know what to do with this. Putty serial connection to this port receives nothing. What should I do to troubleshoot the issue?
Unfortunately, the Roomba S9+ doesn't support the Open Interface spec. So you can't control the robot through the USB port. And neither do any of the other latest generation of Roombas (i.e. the "i", and "j" series) Only certain models of the 500, 600, 700, 800, and maybe "e" series robots have the serial port hardware and code support to make it "hackable". (And the existence of the port doesn't mean that the code supports it). This feature was phased out a while ago. So the older the robot, the more likely it will be to support the OI spec. The proper way to control a Roomba is to use a "Create". i.e. either a Create (antique), Create2 (recently retired), or Create3. _Disclaimer: I work at iRobot where I am developing the next generation of consumer robots. However, my postings on this site are my own and don't necessarily represent iRobot's positions, strategies, or opinions._
stackexchange-robotics
{ "answer_score": 1, "question_score": 0, "tags": "serial, roomba" }
Concept of big endian and little endian In union all elements refer to the same slot of memory. Thus if we consider int as 2 bytes ,then it contains the value in binary as 00000001 00000000(256). Since the size of char is 1 byte, so the first half(1 byte) should be allocated with 00000001 and the second half should be allocated with 00000000. But why does the following code print `256 0 1` rather than `256 1 0`? #include<stdio.h> int main() { union a{ int i; char ch[10]; }; union a u; u.i=256; printf("%d,%d,%d",u.i,u.ch[0],u.ch[1]); return 0; }
You have a little-endian* machine. The bytes of i are laid out with the low byte first. If you had a big-endian machine the expected output would not have been "256 1 0" unless `sizeof(int)` were 2. I don't think you have a 16 bit processor. On the more likely `sizeof(int)` of 4, you would have the output of "256 0 0". Try this program: #include<stdio.h> int main() { union a{ int i; char ch[sizeof(int)]; }; union a u; u.i=256; printf("%d", u.i); for (int b = 0; b < sizeof(int); ++b) printf(",%d", (int)(unsigned char)(u.ch[b])); printf("\n"); return 0; } This will show you all the bytes of `u.i` in order as your processor lays them out. *Assuming you're not on a PDP. You don't want to know about PDP.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, c, storage, unions" }
A contractor I work with for the same client bothers my resources Currently my company is contracted by another company. We work besides another big company where the employees of this companies inquire a lot from us. It has got to the point where we feel like we are spending too much time passing knowledge and time to them that we want it to stop completely. This is because my team also has its work to do. The problem is I do not know whether to report this to the client or not. It might seem like we are just selfish and we do not want to cause conflict since we all work in the same department (client) and office. What is the best way to approach this?
Contact your company liaison and ask them how they want you to handle this problem. Presumably they will not be interested in continuing to enable their competition to exploit your companies knowledge base when they are not being compensated for it. However, it is not your place to make that decision. It could be that your company would rather continue this arrangement rather than risk causing problems with the client. They may wish to convey the issue to the client or address the issue directly with the other company. They may or may not give you direction in how to deal with the issue. But the first step should always be to consult your liaison for any issues you feel could be a problem for your company or contract with the client.
stackexchange-workplace
{ "answer_score": 5, "question_score": 2, "tags": "contractors, knowledge transfer" }
How to do multiple selection on list item? Can I make multiple selection on the given image? I have tried []( but I want tick mark on the multiple selection using Ionic. I am using Ionic framework, Please provide me with the solution in Ionic. `<ion-radio ng-model="filter.yellow" ng-repeat="chat in chats">{{chat.name}}</ion-radio>`
In Ionic projects you would instead use the ion-checkbox feature. You could then apply css to either make it look more like the ion-radio, switch classes around to make it look exactly like the ion-radio or even make it bespoke to you application.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, css, angularjs, ionic framework" }
How to create sliding effects for errors notifications in forms? Is it possible to create sliding effects for errors notifications in yii framework forms ? To explain what I mean please visit for example download.com and select "Join CNET" menu item in the top right corner. Please leave "Join CNET" form empty and press "Join CNET" button at the bottom of the form. As you can see now - all red notifications errors will be elegantly displayed on the screen with really nice "sliding" effect. So my question is - how to create such kind of the sliding effects for errors notifications in the yii framework forms ?
1. OK. A standard Yii (CActiveForm) form looks something like this <div class="row"> <?php echo $form->labelEx($model,'username'); ?> <?php echo $form->textField($model,'username'); ?> <?php echo $form->error($model,'username'); ?> 2. With CSS you make the error disappear with display: none. You accomplish this (relatively) easily with $htmlOptions: **$htmlOptions = array('style' => 'display:none'); echo $form->error($model,'username',$htmlOptions);** 3. Now, if you run your form, the error message will fail to appear. That is good. 4. Lastly, attach some javascript to your submit button. Something that selects the error messages and fades them in: **$(.errorMessage).fadeIn('slow')** Note that Yii already gives the error-messages the class **.errorMessage** That should do it... P.S.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, jquery ui, yii, jquery slide effects" }
To have behavior? Is the following use of _have_ and _behavior_ correct? > All programs have the expected behavior.
Yes. That is reasonable, idiomatic English. One might instead say that the programs 'show' or 'exhibit' the expected behaviour, and you might or might not put the 'u' in behaviour, but the original sentence is very reasonable. It's probably an unrealistic claim — programs don't often all have the expected behaviour — but that's a different discussion.
stackexchange-english
{ "answer_score": 4, "question_score": 1, "tags": "grammaticality, verbs, nouns" }
Resources for understanding Javascript used for Redux and Thunk? I am doing a tutorial on React with Redux and Thunk and am having trouble understanding how some of the props are being sent to the different components. I think I understanding how the Flux Architecture in general is working, but the code itself filled with functions returning other functions and other syntax that is making my head spin. How the dispatcher is working for example is a complete mystery to me. Googling around I have read that this is a very "functional programming" approach to doing things in react. Can anyone point me to some resources to get up to speed with the type of Javascript used for Redux and Thunk? Thanks!
Here are some links, 1. Redux.org 2. React-redux tutorial for beginners 3. Redux-thunk
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, redux, react redux, redux thunk" }
Including a text file in Chrome extension and reading it with Javascript I want to create a Chrome extension that contains a text file with static data (a dictionary of English words) and I want the extension to be able to parse that file. I've only managed to find FileReader class, but it looks like it's made for reading user-selected files, while in my case I always want to read the same exact file included in extension's package. As a workaround, I can convert the file to a Javascript array of strings declared in some .js file included in the manifest, but in that case the whole contents would be loaded into memory at once, while what I need is to read the data line by line. Is there any way to do this?
You can go the `FileReader` route, since you can obtain the Entry of your package directory with `chrome.runtime.getPackageDirectoryEntry()`. However, an easier way is to just make a XHR to your file using `chrome.runtime.getURL()` with a relative path. The first way is useful when you want to list files, though.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "javascript, google chrome, google chrome extension" }
import a file from different directory i'm using python 2.7. I have written a script, i need to import a function from some other file which is there in different folder. my script is in the path C:\python\xyz\xls.py Path of File having function that i need to call is C:\python\abc.py i tried like this from python.abc import * but it is not working. Is there any other way to call the function or i need to move the files into same directory? Please help Thank you
You can dynamically load a module from a file: import imp modl = imp.load_source('modulename', '/path/to/module.py') The imp module docs will give you more details.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 6, "tags": "python, python 2.7" }
I want to realize a function that receive the same parameters of std::bind and then call it, how? What I want to achieve is simple, like is: template<class Fn, class... Args> void ui::addExecutable(Fn&& fn, Args&&... args) { va_list argptr; va_start(argptr, fn); ToBeExecuted.push_back(bind<Fn, Args...>(fn, argptr)); } and when I call it: addExecutable(helloWorld, "ME!"); the compiler said: undefined reference to `void cre::ui::addExecutable<void (&)(char const*), char const (&) [4]>(void (&)(char const*), char const (&) [4])' I am not very familiar with template and did some google but didn't get a clue. So how can I realize the "addExecutable" correctly? Thank you! In case you need, all the source code is here.
You seem to have multiple problems here: 1. You get the linker error because you put the template into your `.cpp` file. Templates must usually be inlined. 2. You mix templates which are the C++ style of handling variable arguments with C style `va_start`/`va_list`. That does not work. In this case, you should stick to the C++ way and remove the first two lines in your function.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++" }
Character encoding of PHP files, only Notepad++ works? I'm uploading changes to a remote server. PHP web pages are configured with the following meta: <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> ... and **I cannot change it** to UTF-8 (it would solve my problems). ### With Notepadd++ When I edit my file with i.e. notepad++ all works fine.I can correctly see accented characters like "é à ò". I correctly upload changes to the server. ### With my IDE (the problem) When I use my favourite IDE (PHPStorm) accented characters are displayed as (in the IDE itself). If I made some changes and upload the file to the server, accented characters are replaced with �. I've to admin I'm not really an expert in file encodings. I just need a way to understand why Notepad++ is working while PHPStorm isn't.
Does it help if you change the file encoding to ISO-8859-1 in PHPStorm settings? Project Settings > File Encodings (< As you've already said, the correct thing to do is to get _everything_ to be UTF-8, but as you can't do that, changing your PHPStorm IDE to default to ISO-8859-1 might get around the issue for now.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, encoding, character encoding, character, notepad++" }
Closing all opened tabs except the first tab/main tab using webdriver Can anyone tell me how to close all opened tabs except the first tab/main tab using webdriver? I tried below, but it is closing all tabs including first tab as well. public static void closeTabs() { String wh1=driver.getWindowHandle(); String cwh=null; while(wh1!=cwh) { new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform(); driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, Keys.TAB); cwh=driver.getWindowHandle(); driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"w"); } } Please help me.
Get all the window handles then iterate through them, switching webdriver to the new handle, then calling the close method. Obviously skip this for the original handle, then switch back to the remaining handle. Something like; String originalHandle = driver.getWindowHandle(); //Do something to open new tabs for(String handle : driver.getWindowHandles()) { if (!handle.equals(originalHandle)) { driver.switchTo().window(handle); driver.close(); } } driver.switchTo().window(originalHandle);
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 12, "tags": "java, selenium, tabs, webdriver, selenium webdriver" }
Multiply element of list with other elements in the same list I want to multiply an element of a list with all other elements. For example: def product(a,b,c): return (a*b, a*c, a*b*c) I have done this def product(*args): list = [] for index,element in enumerate(args): for i in args: if (args[index]*i) not in list: list.append(args[index]*i) return list but this gives me `[a*a, a*b,a*c, b*b]` etc. I don't want the `a*a`, `b*b`, `c*c` bit in there.
you could check for equality if (args[index]*i) not in list and args[index] != i:
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "python, python 2.7" }
Partial Latin squares of even order Can we show that $P$ is a partial latin square that is $n \times n$ where $n$ is even, where the upper quadrant $\frac{n}{2} \times \frac{n}{2}$ is filled and the rest is blank, then $P$ can be completed to a Latin square?
Yes it can always be completed. This is a consequence of an important result in design theory/combinatorics, proved by Ryser in: > Ryser, H. J., A combinatorial theorem with an application to latin rectangles. Proc. Amer. Math. Soc. 2, (1951). 550–552. More generally: an $r \times s$ matrix containing symbols from $\\{1,2,\ldots,n\\}$ can be completed to an $n \times n$ Latin square if and only if the number of copies of the symbol $i$ is at least $r+s-n$, for all $i \in \\{1,2,\ldots,n\\}$. In the specific case of $r=s=n/2$, Ryser's condition is trivially satisfied.
stackexchange-math
{ "answer_score": 5, "question_score": 3, "tags": "combinatorics, latin square" }
Unable to remove duplicates from search results I've got a search method that returns items where the search term is either in the name of the item or in one of the item's tags. Here's that method: def self.search(search) search.blank? ? [] : list = all(:conditions => ['name LIKE ?', "%#{search.strip}%"]) list_two = Illustration.tagged_with('%#{search.strip}%', :any => true) ary = list + list_two return ary.uniq end I've also tried some variations of `list & list_two` with no luck. The list being returned has duplicates. For example, I have 2 items, one named 'Test' and the other 'Test 5'. 'Test 5' has a tag 'test'. When I search 'test', the resulting array is `['Test', 'Test', 'Test 5']` Does anybody see what may be the issue here? Thanks.
try the below: a = ['Test', 'Test', 'Test 5'] p a.uniq!{|i| i.split(" ").first} # >> ["Test"]
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby" }
When declar multiple javascript objects with more than one levels, what is the most elegant way? I currently instantiate objects like this: $scope.vppInfo.contract={}; $scope.vppInfo.contract.companyInfo={}; $scope.vppInfo.contract.companyInfo.custNumber=contract.custNumber; $scope.vppInfo.contract.companyInfo.company=contract.TekOpenAccountClient.company; $scope.vppInfo.contract.contract_type=contract.VPPContractType.id; $scope.vppInfo.contract.action=action; $scope.vppInfo.contract.created_at= contract.created_at; Its getting really ugly. But seems there is no other way I know to improve it... What is the best way to declare objects in this senario that will declare objects in more than one layer (level) attached to one object?
Have you considered: $scope.vppInfo.contract = { companyInfo: { custNumber: contract.custNumber, company: contract.TekOpenAccountClient.company }, contract_type: contract.VPPContractType.id, action: action, created_at: contract.created_at };
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "javascript, angularjs" }
Why doesn't Google Plus pick up link description? When I paste a link into a Google Plus post (using the link option), the title and image appear but there is no description. I've noticed this on many links but some do display a description. I'm not sure what the difference is. The links I'm trying are formatted for OpenGraph and work fine on Facebook. I understand that g+ should pick up this info as well. But it doesn't for description. Any ideas on a fix?
It looks like Google+ stopped including the description when posting I did not find any official place where they confirmed this I tried using schema, open graph and meta description - all failed
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "google plus" }
Múltiples opciones en RegEx Tengo que validar un `input`, el cual contiene un código de Contrato. Los formatos pueden ser: * `AAAXXXX` o `AAAXXXX/XX-XX` o `AAAXXXX/VXXXX` * `AXXXXXX` o `AXXXXXX/VXXXX` (Siendo `A` un caracter alfabético, `X` un dígito y el resto (`/ - V`) literales) * * * La regex que he planteado es esta: /^((\w{3}\d{4}(\/\d{2}-\d{2})?)|(((\w\d{6})|(\w{3}\d{4}))(\/v\d{4})?))$/i Tengo unos casos de pruebas online. Funciona bien para todos los casos menos el último, que lo toma por válido cuando no debería: C123456/30-02 **¿Cómo sería laregex resultante para que cumpla todos los casos?**
Es un error suponer que `\w` coincide sólo con letras, cuando coinciden `a-z`, `A-Z`, `0-9` y `_` (equivale a [`[A-Za-z0-9_]`]( por lo que el emparejamiento se hace con la primera opción encontrada (`AAAXXXX/XX-XX` ya que `A` incluye a `X`). Éste podría ser el patrón correcto: `^(([A-Za-z]{3}\d{4}(\/\d{2}-\d{2})?)|((([A-Za-z]\d{6})|([A-Za-z]{3}\d{4}))(\/v\d{4})?))$` (ver en línea) Si no vas a hacer uso de los datos obtenidos en cada grupo de coincidencia, es mejor usar paréntesis no capturadores (?:x): `^(?:[a-z]{3}\d{4}(?:\/(?:\d{2}-\d{2}|V\d{4}))?|[a-z]\d{6}(?:\/v\d{4})?)$` (ver en línea) Por facilitar la depuración y el mantenimiento de la expresión regular mantengo los grupos tal y como los defines en tus reglas. No impactará al rendimiento ya que el código se ejecutará únicamente a petición del usuario (en el evento de envío del formulario).
stackexchange-es_stackoverflow
{ "answer_score": 14, "question_score": 10, "tags": "javascript, regex" }
Does anyone know how to get maps working inside an activity group? I have used maps many times before, but this is the first time I have ever tried to use it within an ActivityGroup. I have spent hours pulling my hair out trying to figure out why the maps won't show (just showing the grid) and it turns out that it is simply because the Activity is in an ActivityGroup. I googled the problem but all found was people asking how and not getting any answers. Does anyone know if there is a way to get maps working inside an ActivityGroup?
ActivityGroup manages other activities. An activity with a map has to extend MapActivity (which ActivityGroup obviously does not). So you can embed an activity that displays a map, but your activity group can't display the map itself.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "android, android activity, grid, maps, activitygroup" }
What is the use of pickup notes? I was looking through some sheet music, when I noticed quite a few pieces had pickup notes. What is the use of a pickup note? Here is an image: ![Pickup note](
Pickup notes are just a symptom of the fact that many melodies don't start on one of the intuitive downbeats, but between two of them. If the notation bothers you, you can always rewrite such music by inserting a bunch of rests before the pickup note, so that the first bar is a complete bar.
stackexchange-music
{ "answer_score": 4, "question_score": 2, "tags": "sheet music" }
Idling on windows logon screen to allow SSD to recover free space? On this page, the very last paragraph states "For use within windows 7 there is absolutely no maintenance needed apart from allowing the machine to idle at the login screen for a few hours each week, this allows the garbage collection time to recover the drive and free up space TRIM has not been able to deal with. " Is this true? My Windows7 automatically logs me in. My new SSD is an Intel 510 (120G).
No, this is not necessary for your SSD. The link you posted only applies to the relatively old OCZ Vertex SSD, and its specific garbage collector. Your Intel 510 SSD natively supports TRIM, which should be sufficient to prevent performance degradation over time. Intel's SSD Toolbox software has an "optimise SSD" feature, but this should not be needed if you use Windows 7 and the Microsoft AHCI driver (see this PDF for details).
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "windows 7, ssd, trim" }
Display issues (shadowing?) 14.04 This is showed when i open software center, ![enter image description here]( Unreadable letters and description as you see, if i put focus on another program like this: ![enter image description here]( The letters become magically readable... what is happening? I'm a fairly new linux user who was previously a power windows user. This happens with other programs like Firefox, when i load google.com the search textbox becomes 'shadow black' while the page isn't 100% loaded which returns to normal, youtube search box however you can't see what it's typed and the same thing happens on another sites.. (the YT box however doesn't become readable if i focus another window...) Can someone help? I'm running a laptop with Intel Celeron and no dedicated graphics card. (Sorry for the doubled images, i got double monitor setup)
This looks like a theme issue. Try a different theme and see if the same thing happens please.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": -1, "tags": "14.04, gnome" }
Grade Calculator isn't exiting I have a program that is supposed to approximate a letter grade based off of an integer input. I want it to be able to run continuously until the number "-1" is input, then quit. However, whenever I try to run it, the program just keeps telling me my grade over and over again, and it won't do anything else. Here is what I have so far. import easygui grade = int(easygui.enterbox(msg="Enter a grade between 0 and 100: ")) while grade != -1: if grade >= 90 and grade <100: easygui.msgbox ("You got an A") if grade >= 80 and grade <90: easygui.msgbox ("You got a B") if grade >= 70 and grade <80: easygui.msgbox ("You got a C") if grade >= 60 and grade <70: easygui.msgbox ("You got a D") if grade >= 0 and grade <60: easygui.msgbox ("You got an F") else: raise SystemExit
You need to take the inputted grade again in while loop. import easygui grade = int(easygui.enterbox(msg="Enter a grade between 0 and 100: ")) while grade != -1: if grade >= 90 and grade <100: easygui.msgbox ("You got an A") if grade >= 80 and grade <90: easygui.msgbox ("You got a B") if grade >= 70 and grade <80: easygui.msgbox ("You got a C") if grade >= 60 and grade <70: easygui.msgbox ("You got a D") if grade >= 0 and grade <60: easygui.msgbox ("You got an F") grade = int(easygui.enterbox(msg="Enter a grade between 0 and 100: ")) else: raise SystemExit
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, calculator, easygui" }
Redirect to new url after form POST mongo save() This code is incorrect. Redirect only redirects, I don't think you can pass results through it. router.post('/form', function(req, res, next){ var student = new StudentModel({ firstName: req.body.firstName, lastName: req.body.lastName, }); student.save(function (err) { if (err) return handleError(err); db.collection("studentmodels").find().toArray(function(err, result) { if (err) throw err; res.redirect('/submitted', { data: result}); -- what can I do here? }); }); }); Is there a way to redirect and include this information? I would like to use: res.render('submitted', { data: result}) But I can't change the URL path
There are some ways to pass the data to the new route. you can render the submitted template file by passing data if you don't want to change the URI If you want the specific URI you can pass the data as query params into your route you can see the example in the below <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, node.js, mongodb, express" }
Allow user to create and alter table? I have a current mysql user who has `SELECT` privileges for all the table in database `example`. How can give that user privileges to add new tables, and alter/add records to the table it created?
Use the grant keyword combined with the table privileges you seek to give the user. GRANT ALTER, CREATE ON example TO 'someuser'@'somehost'; MySQL Grant MySQL Table Privileges
stackexchange-stackoverflow
{ "answer_score": 28, "question_score": 19, "tags": "mysql" }
Trunk on the outside ASA interface ![enter image description here]( I have a topology as in the picture. It is designed to be a factory network. 2 ASAs in a failover cluster border the whole LAN. And it is pretty much clear how to configure them: outside interface to ISP, inside subinterfaces to different VLANs. But, I need ti have also HA clusters to border Workshops from the rest of the LAN. And I cannot understand, how exactly to configure ASAs. I thought to put them in a transparent mode. But in any case, the interface (Outside) from ASA to switch DSW3-RING need to be trunk, isn't it? I got really confused thinking about it. Thanks in advance for help!!\[topology]2
Assuming you don't route between VLANs, you can create multiple subinterfaces (one for each VLAN) and connect them to the ring as a trunk. The physical interface won't have a name, only the subinterfaces will.
stackexchange-networkengineering
{ "answer_score": 3, "question_score": 2, "tags": "cisco asa, trunk, interface" }
Performance Test - Distributed mode with jtl and smtp listener My test consists of tear down thread that sends the JTL report in the email through SMTP listener. This works fine when I run the tests in non distributed model as the JTL file is in one machine. The issue I am facing is when I run these tests in distributed mode ( for some heavy loads). SMTP listener fails as the file is not found in the slave where the tests are running since JTL file is in the master. is there anyway I can make this work within the JMeter tests or do I need to create a separate script once the test is done to send the final report through email.
The easiest option would be indeed creating a separate test script for sending the results. Alternative option would be 1. kicking off another JMeter Slave instance at the same host with the master 2. Limiting the SMTP Sampler to be executed only on that host via If Controller and __machineName() or __machineIP() functions combination like this: ![enter image description here]( This way you will be able to run SMTP Sampler only on the machine where the .jtl file lives.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jmeter" }
Associations being removed by update_attributes I have two models which are associated through a has and belongs to many association, call them `Foo` and `Bar`. Now say I have a `foo` instance and also have `bar1` and `bar2`. `foo` is already associated with `bar1`. When I try to update the associations and add `bar2` to `foo`, I run in to a problem. foo.update_attributes(bar_ids=>bar2.id) This will first delete the existing association with `bar1` and then add the association with `bar2` so that `foo.bars` will only return `bar2`. I would like the update action to add the second association without deleting the first. I feel like this is a simple solution but I haven't been able to find an answer. Any help would be greatly appreciated thanks!
That's the behavior of the method `bar_ids`, to replace the elements, which is usually what is wanted. If you want to add a new element, you can either add it to the association, like this: foo.bars << bar2 or if you need to use the method `bar_ids`, just first get the value and add it to the array, like this: foo.update(bar_ids: foo.bar_ids | [bar2.id])
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby on rails 4, associations" }
Reading an XML document using pugiXml i have a problem with parsing an xml document using pugiXml, it seems to me that everything is correct but this code doesn't work :( void MainWindow::open() { QString fileName = QFileDialog::getOpenFileName(this,"Open"); xml_document doc; doc.load_file(fileName.toStdString().c_str()); for (pugi::xml_node node : doc.child("Person")) { qDebug(node.child_value("nom")); qDebug(node.child_value("Age")); } } Xml file format : <?xml version="1.0"?> <Persons> <Person> <nom>Med</nom> <Age>12</Age> </Person> <Person> <nom>Nasr</nom> <Age>14</Age> </Person> <Person> <nom>Souad</nom> <Age>52</Age> </Person> </Persons>
The most probable cause is that you should use doc.child("Persons"). Document object in your case has one child Persons, that has several Person children. doc.child("Person") fails to find the node and returns a null handle. Having said that, don't forget to check load_file return value as well.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, qt, pugixml" }
Why calling strcpy() leads to changes of my source string? main() { char a[]="abss"; char c[]=""; strcpy(c,a); printf("%s",a); } Why does the source string `a` change on using `strcpy()` it is checked only when string `c` is greater than or equal to string `a`??
`c` has size `1` but you try to copy 5 characters into it. This causes undefined behaviour. To explain what you are seeing, probably what happens is that `c` and `a` are stored next to each other in memory, so the things you write into `c` overflow and land in `a`.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 0, "tags": "c, strcpy" }
Rocket framework portability to web based applications I am designing a windows form application. I want also to provide a web based front for the same application. I understand that I need to redesign the UI part wholly and I am ready for that. But what I would like to know is that what architecture should I follow during development of the windows form so that the maximum part can be reusable. By maximum part I mean the data access logic, the business logic etc. I am planning to use Rocket Framework < for windows application design. Are any one familiar with it? Please suggest.
After a lot of R&D and extensive study I finally settled here: < It is an MVP architecture written by Christophe Geers. It supports all I needed- Architecture for winform, web portability support, Entity Framework. Really nice and easy to use. **Additional reading:** <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, windows, forms, web applications" }
VSTS Adding Users from Azure Active Directory When attempting to add users to VSTS who exist in the connected Azure Active Directory, I am getting a message stating "You are inviting users from outside your directory". I have checked the setting page and it shows that VSTS is backed by the correct Azure Active Directory. Why would the users in AAD not come up as available users in VSTS? Thanks for your help.
Had to open a ticket with Microsoft to address this issue - even though VSTS was showing that it was linked to the correct AAD, we recently changed our domain for AAD and there are additional changes that MS has to make to ensure the linking is functional.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "azure devops, azure active directory" }
Python regular expression to match a pattern when preceded by either start of line or whitespace I would like to write a regex that matches the word `hello` but only when it either starts a line or is preceded by whitespace. I don't want to match the whitespace if its there...I just need to know it (or the start of line) is there. So I've tried: r = re.compile('hello(?<=\s|^)') but this throws: error: look-behind requires fixed-width pattern For the sake of an example, if my string to be searched is: s = 'hello world hello thello' then I would like my regex to match two times...at the locations in uppercase below: 'HELLO world HELLO thello' where the first would match because it is preceded by the start of the line, while the second match would be because it is preceded by a space. The last 5 characters would not match because they are preceded by a `t`.
`(?:(?<=\s)|^)hello` would be that which you want. The lookbehind needs to be in the beginning of regular expression; and it must indeed be of fixed width - `\s` is 1 character wide, whereas `^` is 0 characters, so you cannot combine them with `|`. In this case we do not need to, we just alternate `(?<=\s)` and `^`. Notice that both of these would still match **hello** oo; if this is not acceptable, you have to add `\b` at the end.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "python, regex" }
jqGrid custom edit form I'm trying to implement a modal popup custom form such as the one shown in < for editing data in a jqGrid such as the one shown in < Anyone skilled for help? Thanks.
If I understand correct the question you try to create a custom form edit in jqGrid using Booostrap. Example of custom form edit can be found in Guriddo Knowledge base here For Bootstrap UI just point the grid to use a Bootstrap as described here
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jqgrid, popup, modal dialog" }
ACCESS 2007, Linked Table, Locking Back End DB for other users when open I have a problem with tables linked to BE database. Opening the table on FE database with linked tables by specific user locks the BE database for others, even for read. An error Run-time 3045 comes when somebody wants to use a linked table. Same as open BE database by msaccess, "Cannot block the file", and open .laccdb - "Permission denied" Every user have same rights.
Solved. Vendor installed on its server the update with prevent data leakage, without information... That update blocks opening files for multiple users.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "ms access, vba, ms access 2007, linked tables" }
Outputs from exec() in windows (PHP)? not seem to getting the outputs from exec() command in PHP, OS: Windows XP here's the code used: exec("echo %username%",$output); using print_r($output) which returns 1;
`echo` is not a program on Windows that you can call. It is a feature provided specifically by the command processor (i.e. `cmd.exe`). If you want the username in this manner don't start up a shell. Use `getenv` instead. (If for some reason you wanted to use `echo` you would need to do `cmd.exe /c echo Whatever`. Also note that checking the return code as well as the output may be useful)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, exec" }
Mock a config file I'm writing tests for an app that refers to a hardcoded filename "classpath:config.properties". It isn't possible to change this name. Is there any way to test this app with different configs? i.e. different tests supply different configs at runtime? This is an odd requirement, but I'd deeply appreciate any inputs
Here is another question that might help you: Dynamically loading properties file using Spring Or you can always overwrite the properties file using the Java IO libraries.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, testing, mocking, easymock" }
Xcode tests - not showing up in the left hand sidebar Adding tests to a test unit in xcode doesn't show them up on the tests inspector (left hand side bar). Does anyone know why this is happening? I have followed the instructions of tutorials to a T. !Screenshot
The test method names need to begin with the word 'test'. i.e. `apiWillLoginWithKnownEmailAndPassword` should be `testApiWillLoginWithKnownEmailAndPassword`
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "ios, xcode, xctest" }
Why is there no @Html.Button in IntelliSense in ASP.NET MVC 3? I see references out there for @Html.Button(), but when I type that, IntelliSense doesn't find such a helper... there's dropdownlist, hidden, editors, et cetera, but no button! Why is that?
I have written my own HTMLButton extension that you can use, instead: public static class HtmlButtonExtension { public static MvcHtmlString Button(this HtmlHelper helper, string innerHtml, object htmlAttributes) { return Button(helper, innerHtml, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) ); } public static MvcHtmlString Button(this HtmlHelper helper, string innerHtml, IDictionary<string, object> htmlAttributes) { var builder = new TagBuilder("button"); builder.InnerHtml = innerHtml; builder.MergeAttributes(htmlAttributes); return MvcHtmlString.Create(builder.ToString()); } }
stackexchange-stackoverflow
{ "answer_score": 69, "question_score": 81, "tags": ".net, asp.net mvc 3, razor, intellisense, html helper" }
Trying to json_agg multiple columns throws an error "No function matches the given name..." Im trying to use json_agg function on postgresql but it keeps throwing error saying > > ERROR: function json_agg(character varying, character varying) does not exist > HINT: No function matches the given name and argument types. You might need to add explicit type casts. > SQL state: 42883" > The problem comes when i am trying to agg multiple columns but not all. i.e SELECT json_agg(users.*) as users FROM users works fine, same with single column query i.e SELECT json_agg(users.id) as users FROM users but if I'm trying to agg multiple columns i.e SELECT json_agg(users.id, users.name, users.address) as users FROM users it throws error shown above, why? Is that not possible or is there some specific syntax required?
`json_agg()` only takes a single parameter, not multiple parameters. If you want to convert the whole row into a JSON and then aggregate that, pass the table reference: SELECT json_agg(users) as users FROM users If you only want some columns, use `json_build_object()` SELECT json_agg(json_build_object('id', users.id, 'name', users.name)) as users FROM users If you want most of the columns and just exclude a few, using `to_jsonb()` and removing the unwanted ones might be easier: SELECT jsonb_agg((to_jsonb(users) - 'password')) as users FROM users
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 3, "tags": "postgresql" }
How to remove all inherited CSS formatting for a table? I have a table which has a certain style due to the CSS file for the page (it has blue borders, etc...). Is there a simple way to remove the CSS for that specific table? I was thinking something along the lines of a command like: style="nostyle" Does anything like this exist?
Try this. From Eric Meyer's Reset CSS table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; }
stackexchange-stackoverflow
{ "answer_score": 41, "question_score": 26, "tags": "css, inheritance, css tables" }
Newer tool to trace memory leak in Android I've researched through several posts trying to find a good tool to trace memory leaks, but I have found posts from 2009 and the tools are already deprecated. What tool I can use (if possible, from the android sdk) to find memory leaks and if possible a simple tutorial might be helpful.
This is still relevant. I used this the other week, and it worked quite nicely. Not sure about whether or not it's "deprecated", as it still works and you aren't exactly building it into an app.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, memory leaks" }
How to prevent ad blockers from restricting sections of my website (non google ads) I have a block towards the header, that is full width, and has some basic HTML with Full HTML Text format. It is getting blocked by my user's ad blocker software. so far it is reported to be blocked with AdBlock and Adguard. I have tested and verified with AdBlock My content isn't "spamy" at all. In fact it is a coupon code so they are missing out :) Here's the content <h2 style="text-align: center; font-weight: 300;">50% OFF entire store. Use code <strong>AWESOMESALE50</strong></h2> The CSS class for the block is **banner-advert** Could it be the inline CSS?
Thanks to No Sssweat's simple suggestion, it is fixed (as far as I can tell). I changed my CSS class for the block from "`banner-advert`" to "`sitewide-promo`". I'm assuming either `banner` or `advert` caused an issue, so I replaced both.
stackexchange-drupal
{ "answer_score": 2, "question_score": 1, "tags": "theming, blocks" }
With Watin, how do I wait until an element gets a certain CSS class? I want to use Watin's `WaitUntil` method to wait until an element gets a certain CSS class (JavaScript adds the class dynamically). How do I do this? var element = browser.Div("my-div"); element.WaitUntil(...); // What to do here??
Try one of these: element.WaitUntil(Find.ByClass("your_class_name")); element.WaitUntil(d => d.ClassName == "your_class_name"); Keep in mind, that element with `class="your_class_name other_class_name"` will probably (I'm not 100% sure) not be found.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "c#, css, watin" }
Letters in a Circle Bob drew 6 letters into a circle. A, B, C, D, E, F. I don't have a graphic, but imagine those letters into a circle, with A at the top. Bob goes clockwise through the circle, writing every third letter, that he hasn't already written down. This results in the sequence A, D, B, F, C, E. Now, Alice mixes up the letters L,M,N,O,P,Q,R,S, randomly, starting with L at the top. Bob does the same thing, and goes through the circle writing every third letter. He ends up with the sequence, L, M, N, O, P, Q, R, S. What is the order that Alice put it in, starting with L at the top. Sorry if this is vague. I read this problem earlier, but I don't know the answer.
The order Alice put the letters, in clockwise order and starting from the top, in is: > L, R, O, M, S, Q, N, P Going in order: > Put $L$ at the top > Go forwards two notches, then write $M$ on the third > Go forwards two notches again, write $N$ on the third > Go forwards two notches, we just passed $L$, so we have to add another notch, write down $O$ on the next notch > Forwards two, we passed $M$, so add another one, we can't write on the next notch because $N$ is there, so add another notch, and write $P$ on that one. > Go forwards two, add one more because we passed $L$, add as many as we need until we find an empty spot, write $Q$ on the next available. > The last two are the next available, and the last remaining. > $R$: We pass an empty spot, go forwards until we find another empty spot, and the third empty spot is going to be the first one we passed by. > $S$: It should be the last spot left.
stackexchange-puzzling
{ "answer_score": 1, "question_score": -1, "tags": "logical deduction, find the order" }
How to access an external drive I plug in a flash drive to my USB port. How can I access it through bash? (`$ cd /` takes me to the directory called `Macintosh HD`, but through Finder, I can go up one more directory called `<myname>'s MacBook Pro`. However, $ cd / $ cd .. doesn't allow me to go to the directory `<myname>'s MacBook Pro`.) How can I get to the files on my flash-drive?
All volumes on internal or external hard disks/thumb drives/DVDs etc. are mounted to the directory /Volumes by default. The boot volume itself is linked as a soft link here. Example: user$ cd /Volumes/ ... dr-xr-xr-x 2 user admin - 12936 23 Nov 16:45 Audio-CD drwxrwx--- 14 user admin - 544 27 Okt 09:43 ExternalDrive lrwxr-xr-x 1 root admin - 1 23 Nov 07:59 MacintoshHD -> / drwx------ 1 user staff - 296 21 Nov 07:56 NetworkShare drwxrwx--- 14 user admin - 544 14 Okt 16:22 ThumbDrive ... To access your thumb drive you have to enter `cd /Volumes/name_of_thumb_drive`.
stackexchange-apple
{ "answer_score": 7, "question_score": 4, "tags": "macos, terminal, bash, folders" }
Handle physical keyboard key event when EditText is not focused state I have an EditText and WebView. I wanna show custom search view when user press `Control + F`. Below codes works when EditText is in focused state. But after I touch WebView (EditText is not focused), it do not work. How can I do? Please help me, thanks. @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode){ case (KeyEvent.KEYCODE_F): if(event.isCtrlPressed()){ //show Custom View } return true; default: return super.onKeyUp(keyCode, event); } }
Problem solved. I disable gaining EditText focus at Activity startup by using this xml code in parent view. android:focusableInTouchMode="true" It works at all.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, keyboard events, keyevent, android keypad" }
Equivalencies and catalytic hydrogenation Can we actually control catalytic hydrogenation by introducing specific molar quantities of hydrogen gas? My prof insists on no. No we cannot use a certain equivalency of hydrogen gas to stop at a desired product. Yet in the book I keep seeing examples of specific molar quantities of hydrogen gas being used ... !enter image description here
Using the equipment that I have and working on the scale that I tend to work on (<1 mol typically), I can't deliver only one equivalent of hydrogen gas. We can measure the amount of hydrogen consumed as the reaction proceeds. The problem you have shown could be interpreted that way, i.e. 1 mol is consumed but more may be present. On industrial scale it may be possible to deliver a more accurate amount of hydrogen. I'll leave it to others that might have more experience on large scale to confirm or deny. There are alternative sources of hydrogen that can more easily be delivered accurately on small scale. Either ammonium formate or cyclohexadiene can be used to generate hydrogen in the presence of palladium. The former liberates ammonia and carbon dioxide as byproducts, while the latter forms benzene as byproduct.
stackexchange-chemistry
{ "answer_score": 3, "question_score": 1, "tags": "organic chemistry, synthesis" }
How to create a nodejs websocket client I'm working on a project where I need to have multiple node clients connect to a node server via websockets. The clients will send files to the server and the server will immediately distribute that file to all connected clients. The problem I'm running into is connecting as a _client_ in node. The built in `ws` module seems to only support server use. I've also tried the npm `websocket` client which allows me to use node as a client but I seem to only be able to send binary data without any other information like the filename, etc. using the `sendBytes` method. Thanks for any suggestions.
Checkout the `delivery` package of `npm`. It provides bi-directional file tranfer for node.js over socket.io. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, node.js" }
Is degreed the same as graduated? I'm translating a sentence > the standards are approved by the customer or degreed metallurgist/equivalent as applicable but I'm not quite sure about 'degreed'. Is it the same as graduated or qualified? I couldn't even find it in the dictionary.
A _degreed metallurgist_ is the same as _someone holding a degree in metallurgy_. Collins lists the word as meaning: > **degreed** ( _adj._ ) [education] having an academic degree Wordnik lists it as well. Essentially, it's about the same as _graduated_ , in that you are awarded a degree when you graduate from an academic program.
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "meaning" }
Is typedef just a string replacement in code or somethings else? I was curious to know how exactly typedef works. typedef struct example identifier; identifier x; In above statement is 'identifier' just replaced (somethings like string replacement) with 'struct example' in code? If no, what does typedef do here? please enlighten!
No, it is not a string replacement - that would be macros. It creates an alias for the type. typedefs are preferred over macros for custom types, in part because they can correctly encode pointer types. typedef char *String_t; #define String_d char * String_t s1, s2; String_d s3, s4; > s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention.
stackexchange-stackoverflow
{ "answer_score": 34, "question_score": 11, "tags": "c++, c, syntax" }
How do I escape HTML elements in C# .NET using JavaScriptSerializer? Consider this code: // Dictionary created. Dictionary<string, string> objDic = new Dictionary<string, string>(); string test = "<>"; objDic.Add("html", test); var Json = new JavaScriptSerializer(); string response = Json.Serialize(return_obj); Output response: [{"html":"\u003c\u003e"}] Expected response: [{"html":"<>"}] How do I get the expected response?
Then you can use Json.NET: var str = JsonConvert.SerializeObject(new {html="<>"}) //returns {"html":"<>"}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, .net, json, serialization, javascriptserializer" }
Setting Alphabets into a double array in C char c; for (c = 'A'; c <= 'Z'; ++c) { for(int i =1; i < newGui->width; i++) { //for (c = 'A'; c <= 'Z'; ++c) newGui->gui[0][i].graphics = c; } } So apparently my code is not setting the Alphabets into the double array properly, I cant figure out wether its the loop thats wrong or the logic that I have used in here. Every-time I run the program it keeps setting all the double arrays with the value of 'Z'. Can someone point me into right direction, thank you. | . || Z || Z || Z || Z || Z | | 1 || 0 || . || . || . || . | | 2 || . || . || 0 || . || . | | 3 || . || . || . || . || . | | 4 || . || . || . || 0 || . |
because the inner `for` set `newGui->gui` at indexes interdependently of the character it is like your replace the external `for` by `c = 'Z';` You want something like that : for(int i = 1; (i < newGui->width) && (i <= 'Z' - 'A' + 1) ; i++) { newGui->gui[0][i].graphics = i + 'A' - 1; } Note that way supposes the code of A, B ... Z are consecutive, which is true in ASCII, to be sure to have the expected behavior in all cases do : for(int i = 1; (i < newGui->width) && (i <= 26) ; i++) { newGui->gui[0][i].graphics = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i-1]; }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "c, arrays" }
Custom Post Type - Get posts by category I am using the following code to return all posts from my custom post type "portfolio". <?php global $wp_query; $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array('post_type' => 'portfolio', 'posts_per_page' => 3, 'paged' => $paged); $wp_query = new WP_Query($args); ?> ... On other pages i would like to return posts by a category of my custom post type, of which i have created a taxonomy for. I am using the following code below but still returning all custom posts. <?php global $wp_query; $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $args = array('post_type' => 'portfolio', 'taxonomy' => 'portfolio_categories', 'category' => '5', 'posts_per_page' => 3, 'paged' => $paged); $wp_query = new WP_Query($args); ?> Any help or direction would be appreciated.
You should use tax_query if you want to list the posts under a category: $args = array( 'posts_per_page' => 3, 'tax_query' => array( array( 'taxonomy' => 'portfolio_categories', 'terms' => '5' ), ), 'post_type' => 'portfolio', 'post_status' => 'publish' );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, arrays, wordpress, custom post type, custom taxonomy" }
Calculating deposit based on interest and required withdrawal in future I am really stuck with example 2-5 and 2-6. I don't really understand example 2-6 and example 2-5 I just can't figure out...I was able to do example 2-4 which was easy... For example 2-4 I did F=P(1+ interest)^n 6500=P(1+0.03)^4 I solved for P and got the deposit value...Example 2-5 or 2-6 are different and don't work the same way so I am not sure what to do here.. !enter image description here
For example 2-5: you want $$ 6500 + Q = P (1.03)^4$$ and $$3000 = Q (1.03)$$ so that $$ = 6500 + \frac{3000}{1.03} = P (1.03)^4$$ Solve for $P$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "finance" }
How can i find out facebook API version I have an app id and secret of a facebook app. But I am not owner, how can I find out its app version? I tried to go through fb graph api document but it did not work.
According to a somewhat relatable FAQ, you can check the `facebook-api-version` header in the response to determine the API version that had been used to process the request. Currently (as of December 26, 2015), the oldest active version is 2.0, so any unversioned calls will use the 2.0 API (until August 2016). The changelog can be found here
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "facebook graph api" }
Send data to TCP Server on local network with PhoneGap / jQuery mobile I want to send this string "ABC" to a TCP Server on local network, and the address and port are available. And I want to do this with phonegap or jquery mobile. Any help? Or, I have to make a proxy with PHP, and this PHP will handle the data send activity? -Ana
jQuery/PhoneGap itself does not support TCP protocol. Using a HTTP proxy for jQuery, or a native plugin for PhoneGap.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, cordova, tcp" }
How can I limit an Artifactory aql query to a specific repository? I have this working aql query: items.find({"@myproperties.fileType":{"$match": "myFile"},"@myproperties.otherType":{"$match": "thisType"}}) It returns all the results I expect. However, this query looks for files containing these properties in every repository. How can I limit the search to a specific repository?
This is the format needed: items.find({"repo":{"$eq":"myrepo"}}, {"$and":[{"@myproperties.fileType":{"$match": "myFile"}},{"@myproperties.otherType":{"$match": "thisType"}}]}) This query language isn't very intuitive, but there it is.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "artifactory, artifactory query lang" }
Except[] with levelspec I am trying to determine all the variables used in list. For This I use: DeleteDuplicates[Cases[l1,_Symbol,-1]] This is great except that `\Pi` etc. are symbols too. I want to add Except to this `Cases` command to discard numeric symbols but I'm not sure where to add it. I tried different combinations, but I either get errors, or it will interpret it differently to what I intended. Alternatively, is there a better way of achieving this?
As an example, let us consider the following expression: expr= Log[ 3 Sin[x] + 2 Exp[Pi+ 4 a b + 1/7]]; This is not a polynomial, so the function `Variables` cannot be used. On level -1 we have the atoms: Cases[expr,_, {-1}] (* {2,E,1/7,4,a,b,\[Pi],3,x} *) Observe that 1/7 is an atom! We restrict ourselves to symbols: Cases[expr,_Symbol, {-1}] (* {E,a,b,\[Pi],x} *) This is not restrictive enough; we only want the symbols that do not have a value. Using Kuba's advice to use function composition: Cases[ expr, _Symbol?(Not @* NumericQ), {-1}] (* {a,b,x} *)
stackexchange-mathematica
{ "answer_score": 4, "question_score": 3, "tags": "pattern matching, conditional" }
Epsilon Delta proof for $\lim_{x\to a} x^{1/3}$ Is this proof for limit $\lim_{x\to a} x^{1/3}$ valid? Lets first find Right Hand limit. $x-a > 0$. Let $x-a < \delta$ so that $x^{1/3}-a^{1/3} < \frac{\delta}{x^{2/3}+x^{1/3}a^{1/3}+a^{2/3}} < \frac{\delta}{a^{2/3}}$ So choosing $\delta = a^{2/3} \varepsilon$, we have $x^{1/3}-a^{1/3} \lt \varepsilon$ whenever $x-a \lt \delta$. Does this complete the proof? Also I have read that we can choose $\delta$ bigger than what I chose. What does this statement mean? And why can we choose it?
If $a=0$, then for any $\epsilon>0$ $$|x^{1/3}-a^{1/3}|=|x^{1/3}|<\epsilon$$ whenever $|x|<\delta=\epsilon^3$. * * * If $a> 0$, we first take $x$ such that $\frac{a}{2}<x<\frac{3a}{2}$. Then, for any $\epsilon>0$ $$\begin{align} |x^{1/3}-a^{1/3}|&=\frac{|x-a|}{|x^{2/3}+a^{1/3}x^{1/3}+a^{2/3}|}\\\\\\\ &<\frac{|x-a|}{a^{2/3}(1+2^{-1/3}+4^{-1/3})}\\\\\\\ &<\epsilon \end{align}$$ whenever $|x-a|<\delta=\min\left(\frac a2,a^{2/3}(1+2^{-1/3}+4^{-1/3})\,\epsilon\right)$. * * * The case $a<0$ is left as an exercise.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "calculus, limits, epsilon delta" }
iPhone CAAnimations playing serially Is it possible to define all CAAnimations at start and play them one after another serially without using delegates, like what we do in CAAnimationGroup, where in animations are played simultaneously. Instead I just want them to play serially.
To run a set of `CAAnimation` animations in sequence, group them in a `CAAnimationGroup` and set the `beginTime` and `duration` of each `CAAnimation` so that they are run one after the other. Most people miss these properties because they're defined in the `CAMediaTiming`, which `CAAnimation` conforms to.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "iphone" }
Achieving pop-up over index with HTML and CSS I have an ideia for my website which consists of making something like this: ![enter image description here]( Basically I want have this little pop-up over the image, which would contain some text content. I already have everything else HTML/CSS wise working. I currently have (using bootstrap) a row and 2 columns, the column with the image is just a div with a background-image and the other col is just some text on a flex-box. How can I achieve what I want using bootstrap or some other CSS features?
Just example, maybe helpful for you. .parent { position: relative; } .content { position: absolute; top: 0; left: 30%; background-color: white; padding: 0 20px; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; } <div class="parent"> <img src=" width="100%"> <div class="content"> <h3>Foobar</h3> <h5>More Beer, more party</h5> </div> </div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, bootstrap 4" }
pgAdmin: Casting null JSONB to JSON returns connection closed I was testing out some basic operations while working on a query to perform operations on a JSON column. When I ran this query: SELECT NULL::jsonb::json I received the following error message: _`Not connected to the server or the connection to the server has been closed.`_ The server is alive and well, any other query works but anything that revolves around this particular type cast seems to be "crashing" the parser/planner/server. Any explanation on why this particular query triggers this behaviour? I am currently running PostgreSQL 9.6.12 and running queries with pgAdmin 4.0 4.6
After testing this in several different ways I have found out that this is actually a bug in pgAdmin 4.6 I have created a bug on their bug tracker and should hopefully be solve with the next version.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "json, postgresql, type conversion, jsonb, pgadmin" }
KeyError when using dango_get_or_create I'm using Factory Boy 2.4.1, Django 1.4.11 and python 2.7 with the following factory: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = auth.models.User django_get_or_create = ('Bob',) username = 'Dan' And every time I try to create a user with the factory I get: KeyError: 'Bob' I've tried putting an existing key into the `django_get_or_create` field with no success. What's going wrong? WHat's going wrong, as the comment says, is that it should read `django_get_or_create = ('username',)` ; I.e. a key of the class, not of the database.
`django_get_or_create = ('username')` as in the docs where `'username'` is a key to the model, not to the database. Changing `'Bob'` to a field in the model is the solution. Thanks to the comments.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django, factory boy" }
Shell script finds file in directory, how to pass into python script I have a shell script that looks through a directory and returns the most recent CVS file; I then want to pass this file into a python script. I'm not very familiar with UNIX, am I supposed to be using arguments for the files in my shell script and how would I go about it? This is the shell code: file = ls -t | $path-n 2 | head -n1 In python: import pandas as pd data = pd.read_excel(file, sep='delimiter',skiprows = 3, header=None, names = colnames)
If your python file is named test.py, it should look like: import sys import pandas as pd data = pd.read_excel(sys.argv[1], sep='delimiter',skiprows = 3, header=None, names = colnames) Then the command would be `./test.py $file` in the shell script. sys.argv[0] is the python file name (ex test.py), and sys.argv[1] is the first argument after the file name.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, unix" }
Demandware site testing We are using Demandware for our eCommerce site so they are giving sandboxes for development and testing. I am automating the site for regression testing. But if I run automation scripts on Testing sandbox, sometimes it is taking longer time to load the page as a result test fails. So what is the best way to do automation testing on Demandware related websites ? Is it possible to deploy site to Cloud ? Is is possible to increase the performance of testing related sandbox ? So tests will not fail? Can you please suggest your thoughts?
Use development instance for these tests, as it is close to production in terms that it uses Akamai CDN, so the loading of pages will be relatively faster. If sandboxes/development instances are performing slow, it may be good idea to look in Pipeline profiler in Demandware Business Manager to get insight as to where the performance bottleneck is lying.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "selenium, selenium webdriver, performance testing" }
iOS Game Center - authentication error on one device On one of my devices (an iPad mini running iOS7), when I attempt to authenticate in Game Center I get the dreaded error: Authentication Error: Error Domain=GKErrorDomain Code=2 "The requested operation has been cancelled or disabled by the user." UserInfo=0x15ef0f00 {NSLocalizedDescription=The requested operation has been cancelled or disabled by the user.} I am clearly logged into Game Center. I have completely wiped the app from the device and even a fresh run from Xcode after deleting the app I still get the error. I can log in with other devices with no problem. I'm signed into the same GC account on different devices. It's just that on this particular device it will not authenticate my app, nor does the app show up in the "Games" list in the Game Center app. Any suggestions?
I was having this same issue with an iPad 3 (retina) running iOS7 - evidently in iOS7 if Game Center is dismissed from your app 3 times the user is NEVER prompted again, and there is no way to reset this by re-logging in to Game Center (as you could in iOS6). The current fix that worked for me is to reset settings - Settings->General->Reset->Reset All Settings. Hopefully Apple fixes this bug in the next release, or at least provides better Game Center documentation for iOS7.
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 11, "tags": "ios, authentication, game center, nserror" }
Setting A Paper on Mathematical Puzzles I need to set a paper for High School Students on Mathematical Puzzles which make the use of logic, simple combinatorics and algebra. Can people provide new and innovative questions. The questions should be preferably easy on calculations and more leaned on puzzles.The level of question can vary from Medium to Advanced, but preferably within Mathematical scope of a Senior Year High School Student (12th Grade).
You might want to visit the _Art of Problem Solving's_ website (AOPS.org) for some great potential problems. For example, see AOPS: Resources for mathematics competitions, which you can explore further for potential problems of interest. You also might want to check out MathForum.org's Math-problems+puzzles link; there, you'll find both problems and links to other sites with problems (including those related logic, algebra, geometry, and elementary combinatorics) of varying level of difficulty, geared for high school students.
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "linear algebra, combinatorics, puzzle" }
C# child form not returning to expected point in program (parent form) I am writing a simple game, this is my first foray into Visual Studio forms and my program is not behaving as expected. I have a main form (game board) that opens a new form allowing the user to select players. When the players are selected and the user clicks OK, the form closes and returns to the main form - except that it does not return to the line after the gp.Show() call. Here is the code that is not behaving as I expect: GetPlayers gp = new GetPlayers(); // Form that allows the user to select players gp.Show(); // Display form Console.WriteLine("Form Closed"); // This is not getting displayed when gp calls this.close() As I mentioned, I am completely new to forms so I may be doing something stupid here. Any help would be appreciated, thanks.
`Show`is non-blocking and does not wait for the form to close. Use `ShowDialog` for that behavior.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, forms" }
Is there a function to return all single letter colors in Matplotlib? I learnt of matplotlib.pyplot.colors that the basic built-in colors can be represented as a single letter. * b: blue * g: green * r: red * c: cyan * m: magenta * y: yellow * k: black * w: white Is there a function in Matplotlib to return those colors?
The built in colors are available via `matplotlib.colors.ColorConverter.colors` >>> print(matplotlib.colors.ColorConverter.colors) {u'b': (0.0, 0.0, 1.0), u'c': (0.0, 0.75, 0.75), u'g': (0.0, 0.5, 0.0), u'k': (0.0, 0.0, 0.0), u'm': (0.75, 0, 0.75), u'r': (1.0, 0.0, 0.0), u'w': (1.0, 1.0, 1.0), u'y': (0.75, 0.75, 0)}
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 6, "tags": "python, matplotlib" }
Add menu itens in Commerce Kickstart administrative toolbar I have worked with default Commerce Kickstart 2 toolbar menu, and I really liked. But now I installed a new module, Commerce Feeds, and I can not access it because there aren't menu entries in toolbar. Is there a way to add menu entries like the one I need in Commerce Kickstart 2 toolbar menu, or I have to back to Drupal 7 administrative toolbar?
You're able to modify the Commerce Kickstart 2 admin menu from this path: /admin/structure/menu/manage/management It's a normal menu created during installation called "Management".
stackexchange-drupal
{ "answer_score": 2, "question_score": 1, "tags": "commerce, toolbar" }
Is there any way to make the train leave the station? I'm trying to get one of the survivalist mastery levels that requires you to shoot birds from a moving train. I found the train sitting idle in one of the stations, but couldn't find any way to make it leave for the next station. The conductor is sitting in the engine, he just won't make it go. I went to the ticket booth, no luck. I sat down on a seat in the train, still nothing. I waited a full day and there it still sits. Am I doing something wrong or missing something?
Trains will normally start back up automatically after a certain amount of time passes. That amount of time differs depending on the reason the train stopped (reaching a station vs. stopping because an animal is in the way). However, there is a documented bug where the train stops and never starts back up: > Occasionally, the red/blue train will stop and then not move again until you restart your console. You can still save your game before you reset as this will not make the bug/glitch permanent. Also an escape to the dashboard can resolve this.
stackexchange-gaming
{ "answer_score": 6, "question_score": 7, "tags": "red dead redemption" }
Where are the az role assignments listed I assigned a Service Principal to a VNET with `az role assignment create --assignee SP_CLIENT_ID --scope VNET_ID --role Contributor` Where can I review the configuration (Azure portal or cli)? Update: I was looking for the subnets roles assignment which are a bit hidden under: vNet > Subnets > Managed users > Role assignments.
> Where can I review the configuration (Azure portal or cli)? 1.Use Azure portal: Navigate to the vnet in the portal -> `Access control (IAM)` -> `Role assignments` -> search for the name of your service principal like below. ![enter image description here]( 2.Use Azure CLI: az role assignment list --assignee SP_CLIENT_ID --scope VNET_ID ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "azure, azure cli" }
Cannot read property in React js In App.js export default function App() { const [data, setData] = useState(null); useEffect(() => { fetch(" .then((response) => response.json()) .then(setData); }, []); return ( <div className="App"> <Card item={data} /> </div> ); } In Card.js function Card(props) { return ( <div><h1>{props.item.name}</h1></div> ); } I'm trying to pass data fetch from API from `app.js` to `card.js` but through > TypeError Cannot read property 'name' of null.
This behavior is because the first time when the `item` is passed then it would be `null` and it doesn't have property `name` on it. So either you can use optional chaining or logical AND **1)** Just use the optional chaining operator in JSX {props.item?.name} **2)** Logical AND <h1>{props.item && props.item.name}</h1> CODE export default function Card(props) { return ( <div> <h1>{props.item?.name}</h1> </div> ); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, react redux" }
How to get rid of shadow that appears on my button? Android I have created a button with a Gradient Drawable. ![enter image description here]( If you look at this button, it has those Extra Grey lines as pointed out by my red arrows. Those don't appear if I create a shape using XML but when i use Gradient Drawable code seen below it shows these lines. How do I get rid of them?? GradientDrawable gd = new GradientDrawable(); gd.setColor(Color.parseColor("#FFFFFFFF")); gd.setCornerRadius(20); gd.setStroke(30, Color.parseColor("#0077CC")); Button.setBackground(gd); These become more apparent if i increase the setCorner Radius
Just add style to your button. `style="?android:attr/borderlessButtonStyle"`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, android layout, android shapedrawable, gradientdrawable" }
Question related to connecting to SQL Server via a subdomain? I asked this question _< on SuperUser but haven't really gotten any bites. I'm curious whether that is the correct Stack Exchange site for that question?
This seems like a question which would be better received on the Pro Webmasters Exchange # ![logo]( > "Pro Webmasters Stack Exchange is a question and answer site for professional and enthusiast webmasters focused on how to operate websites. Questions here are commonly about search engine optimization (SEO), domains, and web-hosting." -Webmaster's topicality
stackexchange-meta
{ "answer_score": 1, "question_score": 2, "tags": "discussion, stack overflow, site recommendation, superuser, serverfault" }
char/varchar - длина в байтах или символах? На какой-то борде прочитал, что `*char` отличается от `*text` тем, что первый измеряет длину _в символах_ , а второй в байтах. То есть, по логике, `char(255)` запишет строку кириллицей в _юникоде_ все 255 знаков, а `text(255)` должен ее обрезать примерно до половины. Так вот вопрос: сколько реально _байт_ будет выделено под хранение фиксированного типа `char(10)` в сравнении `utf8_general_ci`? Где искать правду? _< оффтоп> таблица разрослась до миллионов записей, запросы выполняются неприлично долго, ищу способы увеличения быстродействия. Алсо, узнал, что оказывается, если в таблице есть хотя бы одно поле переменной длины, все поля `char` автоматически преобразуются в `varchar` < /оффтоп>_
Символов. Char, varchar, enum, text и другие ограничены длиной в символах. Но общие лимиты (например, на длину строки в таблице, или размер индекса), могут быть дополнительно сверху ограничены в байтах. Прямым текстом сказано в мануале: > For example, MySQL must reserve 30 bytes for a CHAR(10) CHARACTER SET utf8 column. char(10) в utf8_general_ci займёт 30 байт вне зависимости от записанных данных.
stackexchange-ru_stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "mysql, sql, производительность, char" }
Matlab - How to make a figure current? How to make an axes current? If `f` is the figure handle, I wanted to use `plot3(..)` on it just like I would use `plot(..)`, but this didn't work: >> plot3(f, t, real(Y), imag(Y)) Error using plot3 Vectors must be the same lengths. Then I figured out that the way to do this is to: 1. First make the relevant figure _current_. 2. Then use the `plot3(..)` function. I can find what the current figure is using `gcf`, but how do I make a figure current (via its handle)?
This method has my personal preference: set(0, 'currentfigure', f); %# for figures set(f, 'currentaxes', axs); %# for axes with handle axs on figure f because these commands are their own documentation. I find figure(f) and the like confusing on first read -- do you create a new figure? or merely make an existing one active? -> more reading of the context is required.
stackexchange-stackoverflow
{ "answer_score": 33, "question_score": 14, "tags": "matlab, matlab figure" }
UPDATE and INSERT in the same query when criteria is met What im trying to accomplish is im trying to update a column in a table and insert into a another table if a certain criteria is met. So far i've tried UPDATE raffles r SET active = 3 INNER JOIN (INSERT INTO raffles_notifs VALUES (uid,raf_id,type) VALUES (r.uid,r.id,1) ) WHERE r.end_stamp = '123123123' AND wuid = 0; This throws an error, it was just a blind attempt. I might even get a few down votes on this, but i really am lost so had to ask
Just use two queries. First for update, second for INSERT SELECT: UPDATE raffles AS r SET active = 3 WHERE r.end_stamp = '123123123' AND wuid = 0 ; INSERT INTO raffles_notifs (uid,raf_id,type) SELECT r.uid, r.id, 1 FROM raffles AS r WHERE r.end_stamp = '123123123' AND wuid = 0 ;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, insert, sql update, inner join" }
Is this is a secure use of AES-CTR? Here is a hypothetical application of AES-CTR encryption. Encryption: * Step 1: Generate random key and IV for new object; * Step 2: Use said key and iv to encrypt some data, which is then stored on a content server; * Step 3: Encrypt key and IV using some secret master key, and store the wrapped keys in a database table. **Important** : For each new object that we want to encrypt, a new key and IV are randomly generated. Decryption: * Step 1: Retrieve encrypted key and IV relevant to object that we want to decrypt * Step 2: Decrypt key and IV using master key * Step 3: Use decrypted key and IV to decrypt object I would like to know if this is an acceptable way to proceed with AES-CTR (assuming the master key is handled securely, and we are also hashing content to ensure integrity)? If not, could you please suggest a more secure way to manage key and iv for a given object?
Yes this seems secure. Note that for CTR we use a nonce not an IV but it has similar role. Depending on your operational requirements there may be simpler secure methods. The key question is how the shared secret is managed, of course.
stackexchange-crypto
{ "answer_score": 1, "question_score": 0, "tags": "aes, keys, secure storage" }
what does $o(|x|^2)$ stand for? Statement: Let $ h(n,x): \mathbb{R} \times \mathbb{R^m} \rightarrow \mathbb{R}^m $ be a continuous function and $|h(n,x)| = o(|x|^2)$ near $x = 0,$ where $|h|$ and $|x|$ are the same norm in $ \mathbb{R^m}$. Can somebody explain what does $|h(n,x)| = o(|x|^2)$ mean?
I will put Dan's comment as an answer. Please see * <
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus, real analysis" }