INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
LDR exceeding specified dark resistance I bought the LDR NORPS-12. I tested it in a completely dark room and the resistance keeps increasing after 1 mega ohm. Right now it has reached 5 megaohm. Why is that so?
The datasheet says that it is MINIMUM 1.0 Mohm after 15 seconds after removing the test light. The test procedure isn't laid out explicitly, but it seems that they exposed the unit to a light of a specific intensity (1 foot candela) for 16 hours and then measured the resistance for light. They then shut off the light and measured again after 15 seconds. In those conditions you are guaranteed 1 Mohm. That doesn't mean that the dark resistance can't be higher, just that it won't be lower. * * * Additional tips from Spehro Pefhany's comment: You can limit the maximum dark resistance by putting a resistor in parallel to the LDR. If you want it to top out at 1 Mohm, put a 1 Mohm resistor in parallel to the LDR. The parallel combination then has a combined resistance of just under 1 Mohm in complete darkness, and (assuming the 12 kohm max light resistance from the datasheet) a light resistance of 11.85 kohm.
stackexchange-electronics
{ "answer_score": 11, "question_score": 2, "tags": "ldr" }
Should one write a line in a matrix when solving systems of linear equations? Should one write a line in a matrix when solving systems of linear equations? For example, consider the system consisting of $ax+by=c$ and $dx+ey=f$, should one write $$\left( \begin{array}{ccc} a & b & c \\\ d & e & f \end{array} \right) \quad \mathrm{or} \quad \left( \begin{array}{cc|c} a & b & c \\\ d & e & f \end{array} \right)$$ Which one is perferred?
The comments tell us that * The second notation is generally preferred, * The line informs that it is an augmented matrix.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "linear algebra, matrices, notation, systems of equations" }
Netbeans IDE Open Project(Browse) menu option is not working I am trying to install Netbeans 7.2 in my laptop. After installation "Open Project" menu option is not working, so I am unable to open existing project. I mean "Open Project" option in the menu is not working. And "Browsing for Jar" also not working. Ateast It is not browsing for any project. Just simply "Open Project " menu option not working. So I am unable to open the existing Netbeans projects from my system. the only thing I can do with my Netbeans is I have to create new project from scratch. The menu options which need to browse from computer like open Project are not working. I uninstalled& reinstalled different versions of Netbeans so many times. And formatted C drive and reinstalled OS also, still not working. Could any one please help me...
Got it, Solved problem with help of netbeans.org after reporting bug in netbeans.org < The problem is because of "JDK Version". I had installed beta version of JDK 1.6. Uninstalled JDK from my system, downloaded correct version from oracle website and installed. Finally it is working after so many days of struggle. "But I dont understand why Netbeans cant detect this at the time of installation and warn us." Thank you guys your help and Netbeans.org for support.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, netbeans" }
How to access matched RegExp special expressions? I'm trying to access to special expressions of RegExp patter. Here is my code: var regEx = /\[\[.*?\]\]\[\[.*?\]\]/g; var str = '[[Hello]][[World]]'; I want to get whole `.*?` with their values. So, on this example I should get `Hello` and `World` strings How can I do it?
If you want the values of `.*?` you could use a capturing group `(.*?)`. The values will be in capturing group 1 and 2. \[\[(.*?)]]\[\[(.*?)]] Regex demo const regex = /\[\[(.*?)]]\[\[(.*?)]]/g; const str = `[[Hello]][[World]]`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log(m[1]); console.log(m[2]); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, regex" }
perl regular expression digit match Doing the below regex match to verify whether date is in the YYYY_MM_DD Format. But the regular expression gives an error message if i have a value of 2012_07_7. Date part and month should be exactly 2 digits according to the regex pattern. Not sure why it's not working. if ($cmdParams{RunId} !~ m/^\d{4}_\d{2}_\d{2}$/) { print "Not a valid date in the format YYYY_MM_DD"; }
Your regex specifies exactly 2 digits for the day component, if you want to allow either 1 or 2 digits you should use `{1,2}` rather than `{2}`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "regex, perl, mod perl" }
Product of all elements in finite group **Question:** _If $G$ is a finite group such that the product of its elements (each chosen only once) is always $1$, independent of the ordering in the product, what can we say about $G$?_ I was trying to conclude that $G$ must be abelian (I am not sure about this). I proceed as follows: if $|G|\leq 4$, then obviously, $G$ is abelian. Suppose $|G|>4$. Then consider products of all elements in the order $a^{-1}b^{-1}ab cc^{-1}dd^{-1}....$. This, being identity, implies that $a^{-1}b^{-1}ab=1$, i.e. $G$ is abelian. BUT, the problem is in $a^{-1}b^{-1}ab$, the elements $a$ and $a^{-1}$ should be distinct, and similarly for $b$. Otherwise, the product $a^{-1}b^{-1}ab cc^{-1}dd^{-1}....$ is not in the prescribed form as in question. Also, note that the cyclic group of order $4$ doesn't satisfy that $abcd=1$ where $\\{a,b,c,d\\}\cong \mathbb{Z}_4$.
(as per my earlier comment): let $a$ and $b$ be arbitrary elements of your group and let $P$ be the product of all the other elements, in any order. Then, by assumption, $abP = baP$ so $ab = ba$.
stackexchange-math
{ "answer_score": 38, "question_score": 16, "tags": "group theory, finite groups" }
Minimal polynomial of $1 + 2^{1/3} + 4^{1/3}$ I am attempting to compute the minimal polynomial of $1 + 2^{1/3} + 4^{1/3}$ over $\mathbb Q$. So far, my reasoning is as follows: The Galois conjugates of $2^{1/3}$ are $2^{1/3} e^{2\pi i/3}$ and $2^{1/3} e^{4\pi i /3}$. We have $4^{1/3} = 2^{2/3}$, so the image of $4^{1/3}$ under an automorphism $\sigma$ fixing $\mathbb Q$ is determined by the image of $2^{1/3}$: it must equal the square of $\sigma(2^{1/3})$. Therefore, the Galois conjugates of $1 + 2^{1/3} + 4^{1/3}$ are $1 + 2^{1/3} e^{2\pi i/3} + 4^{1/3} e^{4\pi i/3}$ and $1 + 2^{1/3} e^{4\pi i/3} + 4^{1/3} e^{2\pi i/3}$. Therefore, the minimal polynomial is $(x-a)(x-b)(x-c)$, where $$\begin{align*} a&=1 + 2^{1/3} + 4^{1/3},\\\ b&=1 + 2^{1/3} e^{2\pi i/3} + 4^{1/3} e^{4\pi i/3},\text{ and}\\\ c&=1 + 2^{1/3} e^{4\pi i/3} + 4^{1/3} e^{2\pi i/3}. \end{align*}$$ However, this polynomial does not seem to have coefficients in $\mathbb Q$! What am I doing wrong?
By expanding and using the relation $1+e^{2\pi i/3}+e^{4\pi i/3}=0$ heavily I got that $$ (x-a)(x-b)(x-c)=x^3-3x^2-3x-1. $$ Looks like rational coefficients to me. * * * Another way of seeing this is to compute $$ (a-1)^3=(2^{1/3}+4^{1/3})^3=2+3\cdot 2^{4/3}+3\cdot 2^{5/3}+4=6+6(2^{1/3}+4^{1/3})=6+6(a-1)=6a. $$ Hence $$ 0=a^3-3a^2+3a-1-6a=a^3-3a^2-3a-1. $$
stackexchange-math
{ "answer_score": 9, "question_score": 6, "tags": "abstract algebra, polynomials, field theory" }
Can I have an if($_POST['submit']){} before the <form method='post'> declaration? Can I have an `if($_POST['submit']){}` before the `<form method='post'>` declaration? if($_POST['submit']){ print_r($_POST['submit']); $sql="Delete from db where value=2"; mysqli_query($db,$sql); } echo"<form method='post'><input type='text' name='text' value='hello!'> <input type='submit' name='submit' value='Submit!'></form>"; The problem is, I can not take any sql results when the `if($_POST)` is over the form declaration.
Yes it is valid, but it will throw an error like this `Notice: Undefined index: submit` The better practice is to use `isset()`, to check if the post-variable even exists. Then it woud look like this if(isset($_POST['submit'])){ print_r($_POST['submit']); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, forms, post" }
facebook ios sdk build fails on device, works on simulator I am trying to build an app (with ARC) that uses the facebook_ios_sdk (the latest version on github). As recommended by Facebook, I used the build script to create a static library and then added it to the project. Now when I build the project for an iPhone 5.1 Simulator, it works fine. However, on running it for an actual device (which is running 5.1), it gives the following build error - ld: in ../facebook-ios-sdk/libfacebook_ios_sdk.a, file is universal but does not contain a(n) armv7 slice for architecture armv7 clang: error: linker command failed with exit code 1 (use -v to see invocation) Any suggestions on how to resolve this?
You could modify the build script for static library (which was too complicated for me), or just skip the library approach: * add the Facebook sources from SDK to your project * if using ARC, go to "target->build phases->compile sources" and mark all the Facbook source files with the **\--fno-objc-arc** flag That's it, works for me.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "ios5, facebook ios sdk, arm7" }
merging rows from sql query result What would it be the simplest way to merge a result like this from a sql query to be displayed in an asp.net gridview? NULL Tarde Fer W. Lunes Mañana NULL Fer W. Lunes I need the result to look like this Mañana Tarde Fer W. Lunes
Assuming Table Col1 Col2 Col3 Col4 ------- ------ ------ -------- NULL Tarde Fer W. Lunes Mañana NULL Fer W. Lunes Then SELECT MAX(Col1) AS Col1, MAX(Col2) AS Col2, Col3, Col4 FROM YourTable GROUP BY Col3, Col4
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": ".net, asp.net, sql, sql server 2005, gridview" }
Is there any quick way to print in 3x3 matrix form? User can enter any value & the program will print the final matrix. Here I have used matrix addition to display the matrix in 3x3 form. I want to know is there any short way to still get our matrix in 3x3 form? _Here's my code:_ print('Consider matrix mij with i rows & j colomns:') a=int(input('Enter m11 value: ')) b=int(input('Enter m12 value: ')) c=int(input('Enter m13 value: ')) d=int(input('Enter m21 value: ')) e=int(input('Enter m22 value: ')) f=int(input('Enter m23 value: ')) g=int(input('Enter m31 value: ')) h=int(input('Enter m32 value: ')) i=int(input('Enter m33 value: ')) X=[[a,b,c], [d,e,f], [g,h,i]] Y=[[0,0,0], [0,0,0], [0,0,0]] print('Your matrix is:') for i in range(len(X)): for j in range(len(X[0])): X[i][j]=X[i][j]+Y[i][j] for r in X: print(r)
Indeed, you can use f-strings to achieve this. print(f"[{X[0][0]} {X[0][1]} {X[0][2]}]\n[{X[1][0]} {X[1][1]} {X[1][2]}]\n [{X[2][0]} {X[2][1]} {X[2][2]}]") Take this sample: f"[{X[0][0]} {X[0][1]} {X[0][2]}]\n" Here, the values inside the `{}` are replaced by the expression inside. The `\n` acts as a special character which continues the print on a newline. You can take inputs quicker using this code: X = [[input(f"Enter m{i}{j}: ") for j in range(3)] for i in range(3)] This is called list comprehension and you can extend this to take as many values as you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x, for loop, matrix" }
form validation on codeigniter if the value is empty and below 100 How to validate my form on codeigniter, if the value is empty and below 100. **this is my controller** function aksi_deposit(){ if ((empty($_POST['deposit']))&& (($_POST['deposit'])<100)) { redirect('deposit'); } else { $whc = $this->input->post('deposit'); $money = $whc * 8000; $idUser= 1; $b['data'] = $this->m_user->tampil_invoice($idUser); $b['coin'] = $money; $b['whc'] = $whc; $this->load->view('user/v_invoice',$b); } }
i've found the solution, using "OR" it works 100 %. if ((empty($_POST['deposit']))OR (($_POST['deposit'])<100)) { redirect('deposit'); } else { $whc = $this->input->post('deposit'); $money = $whc * 8000; $idUser= 1; $b['data'] = $this->m_user->tampil_invoice($idUser); $b['coin'] = $money; $b['whc'] = $whc; $this->load->view('user/v_invoice',$b); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, forms, codeigniter, validation" }
How to return integers from a list recursively? Created a function Integers in which a list Num containing integers,float and strings values. Goal: function to return a list from Num that only displays the integers. For example : Num = ([10.4, 134, "134", "Stuff", 4, "5"]) [134, 4] Condition : Using recursion only without any loops.
The problem does not really lend itself to recursion, but you can make it work: def ints(lst, i=0): if i < len(lst): if isinstance(lst[i], int): yield lst[i] yield from ints(lst, i+1) >>> list(ints([10.4, 134, "134", "Stuff", 4, "5"])) [134, 4] This uses a generator function to avoid passing lists around and running index to avoid the more expensive slicing. For code readability, you could go with: def ints(lst): if lst: head, *tail = ints if isinstance(head, int): yield head yield from ints(tail)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "python" }
What does the Betrayer give you? Early on in the game, there is a cut scene where you meet a character called "the Betrayer" In that cut scene he has these lines of dialogue: > I told you all to leave me here. I am where I belong. Saving your people will not bring you peace... only make the burden you carry worse. And now you seek to defy the Khan Maykr herself. It is your people's time to give penance... just as it was mine. Hear me, Slayer - When his heart is laid to rest... then his soul will be at peace. The Betrayer then takes out a small implement (looks a bit like some futuristic vape) and tosses it to the Doom Slayer. What is this small implement?
This seems to be revealed later in the game. It's a special dagger. > "After providing a battery to the Celestial Locator, the Betrayer also gives the Slayer a special dagger to destroy his son's heart that controlled the Icon of Sin in the hopes of giving peace to his son's soul." It's a story item used once again in a cutscene, there's no way for the player to interact with it. source (spoilers)
stackexchange-gaming
{ "answer_score": 5, "question_score": 5, "tags": "doom eternal" }
Iterating through integer by byte in C++ I tried to iterate through an integer using a char pointer. My question is: Why is it stored in memory backwards? When I run the code: #include <iostream> using namespace std; int main(int count, char** args) { unsigned int number = 0xabcdef12; cout << "Number:\t\t" << hex << number << endl; cout << "Iterated:\t"; unsigned char* pointer = (unsigned char*)&number; for(int i=0; i<sizeof(number); i++) cout << hex << (unsigned int)pointer[i]; cout << endl; return 0; } The output is: Number: abcdef12 Iterated: 12efcdab I want to know if there is a way to force C++ to order the bytes, e.g.: Number: abcdef12 Iterated: abcdef12 (Extra info: I want to do this because I want to iterate through a `struct` by byte and write the result to file.)
This is because you're on a "little-endian" system. Some computers, including the x86 ones most of us use, are this way. You can swap the byte order of an int with the standard function `htonl()`; the result will always be in "network byte order" which is the one you were expecting here.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c++, pointers, iteration" }
Using regular expressions in Python I'm struggling with the problem to cut the very first sentence from the string. It wouldn't be such a problem if I there were no abbreviations ended with dot. So my example is: * **string = 'I like cheese, cars, etc. but my the most favorite website is stackoverflow. My new horse is called Randy.'** And the result should be: * **result = 'I like cheese, cars, etc. but my the most favorite website is stackoverflow.'** Normally I would do with: `re.findall(r'^(\s*.*?\s*)(?:\.|$)', event)` but I would like to skip some pre-defined words, like above mentioned _etc._ I came with couple of expression but none of them worked.
You could try NLTK's Punkt sentence tokenizer, which does this kind of thing using a real algorithm to figure out what the abbreviations are instead of your ad-hoc collection of abbreviations. NLTK includes a pre-trained one for English; load it with: nltk.data.load('tokenizers/punkt/english.pickle') From the source code: >>> sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') >>> print '\n-----\n'.join(sent_detector.tokenize(text.strip())) Punkt knows that the periods in Mr. Smith and Johann S. Bach do not mark sentence boundaries. ----- And sometimes sentences can start with non-capitalized words. ----- i is a good variable name.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "python, expression" }
How to acquire DualEELS spectra by DM script? I would like to acquire both low-loss and high-loss EELS spectra simultaneously in DualEELS mode by DM script. However, the command for acquiring an EELS spectrum `EELSAcquireSpectrum()` can obtain only single EELS spectrum. Is there an appropriate scripting commands for DualEELS acquisition? My system is _GMS2.x_ , but please tell me even if such a command is available in only _GMS3.x_.
**GMS 3.2** (Possible also for GMS 2.3) * * * I am not aware of any specific command for DualEELS. As a rought workaround: When you start the acquistions via `EELSInvokeCaptureButton()` or `EELSInvokeViewButton()` the mode you have set on your UI will be followed. You then need to grab the two front-most images per script. This is a rough example script: EELSInvokeCaptureButton() image low,high while ( EELSAcquisitionIsActive() ) { Result(" \n waiting..." ) sleep( 0.1 ) } high := GetImageDocument( 0 ).ImageDocumentGetImage( 0 ) low := GetImageDocument( 1 ).ImageDocumentGetImage( 0 ) low.ImageSetName( low.ImageGetName() + " - l" ) high.ImageSetName( high.ImageGetName() + " - h" )
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "hardware, dm script" }
Average distance between consecutive uniformly distributed values Say I have a list of values $(X_1, X_2, ..., X_n)$ and $X_i$ is a uniform random variable between 0 and 1. Let $(Y_1,Y_2,...,Y_n)$ be the ordered list of those values. How do I find the expected distance between $Y_i$ and $Y_{i+1}$?
You are seeking to find $$\mathbb{E}\left(\vert Y_{i+1} - Y_{i} \vert \right) = \mathbb{E}\left( Y_{i+1} - Y_{i} \right) = \mathbb{E}\left(Y_{i+1}\right) - \mathbb{E}\left(Y_i\right) = \frac{i+1}{n+1} - \frac{i}{n+1} = \frac{1}{n+1}$$ The expectation of $Y_i$ is easy to find, noting that $Y_i \sim \mathrm{Beta}\left(i, n+1-i\right)$: $$ \mathbb{E}\left(Y_i\right) = \frac{a}{a+b} = \frac{i}{n+1} $$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "probability, uniform distribution" }
Why did Yashida fake his own death? In _The Wolverine_ (2013), the aging Yashida wishes to make contact with Logan so that he can try to persuade the mutant to voluntarily relinquish his healing powers to Yashida or, if Logan refuses, to steal those powers. When Logan refuses, Yashida arranges for Logan to be weakened so that his healing factor can be stolen, then fakes his own death and secretly transfers himself to an enormous robot body. Why? In what way was his plan advanced by being thought of as dead?
**mere speculation** I think Yashida "faked" his own death because he could not stay a public figure (head of a big company) while still becoming the Silver Samurai. Since Logan had refused to provide his healing abilities, Yashida might have decided to force it from Logan in the guise of Silver Samurai. It is seen in the final climax that Wolverine vs Silver Samurai is an almost evenly matched fight. Yashida, in his normal persona, could not have obtained Wolverine's healing abilities without resorting to some sort of mercenaries. Also, he himself was old and frail. Hence he _died_ and became the Silver Samurai. This also presented him with an advantage of Logan not knowing who the Silver Samurai is and what he wants. Since Yashida was dead, Logan could not have realized that Viper and others were still trying to take his healing abilities from him. Hence another reason to do so.
stackexchange-movies
{ "answer_score": 9, "question_score": 10, "tags": "plot explanation, x men cinematic universe, the wolverine" }
Self-inductance of a given Setup ![enter image description here]( I am asked to prove that the self inductance of the system is given by ![enter image description here]( I used Ampere's Law to find the magnetic field between the strips: ![enter image description here]( The magnetic field due to the second strip would be the same which would yield a value of |B| = ![enter image description here]( What bugs me is the last step to calculate the inductance, for which I have used two methods(with different answers): ![enter image description here]( ![enter image description here]( Something tells me that the first method is incorrect and I need some conceptual clarity. I am not able to figure out my mistake. Please help.
You just messed up the dimensions a bit and forgot to consider the magnetic field due to the bottom sheet as well. The area through which the magnetic field is passing through is $al$, not $bl$. So, it's $2((muknot)(I)/2b)*al=LI$ which gives us the correct answer.
stackexchange-physics
{ "answer_score": 0, "question_score": 0, "tags": "homework and exercises, electric circuits, electromagnetic induction, inductance" }
Rails method to iterate through hash of photos and return value according to criteria I want to create a method (ruby on rails) to iterate through a hash of photos I am pulling from an API (url, name, date created etc) and return only the dates that are in the correct params the user inputs. Inside of the hash you have `created_time` as one of the keys, and that is what I am interested in. Any suggestions? def pull_time @pictures.map do |picture| if picture.created_time >= @start_date && picture.created_time <= @end_date return @pictures end end end
Use `between`: @pictures.select { |picture| picture.created_time.between?(@start_date, @end_date) }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby on rails, ruby, hash, hashmap, instagram api" }
Set Role to user for login time I want to set Role for some users after login. Note, I don't want to add user to this role permanently and write to db, just set some role after login and then check if this user is in this role. Is it possible ?
I would create your own AppUser class that has AppRoles. You can link up your AppRoles to Membership roles (or not). I do this so I can fake user roles for testing and to contain Membership services code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": ".net, asp.net mvc" }
How do I loop through the application memory? I've written my own C# app that contains a int (`int intfoo = 1234;`) and a string (`string stringfoo = "This is a test string";`). And now I'm working on a memory reader that is supposed to loop through and find those values. How do I loop, what is the starting point and what is the endpoint? I've read somewhere that start is 0x00100000 and other places its 0x00400000. And for my little app that uses 7372 kB, what would the end be? And finally, how do i loop through to find my `intfoo` and `stringfoo`?
If you want to manipulate memory, use an unmanaged language. Managed languages/Frameworks like .NET, Mono and Java are specifically designed that you do not screw around with the memory in any form. The framework manages this completely for you. Therefor it's hard to even access it, though possible. But things are turning really ugly from there. Use a language which is designed to handle memory manipulation of any kind, like C or C++.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#" }
Unhandled Exception: RangeError: Value not in range: 22 I am receiving the following error when the image is not set for the user: "Unhandled Exception: RangeError: Value not in range: 22" when the photo is set, everything comes right My code: Future<Map> getData() async { final prefs = await SharedPreferences.getInstance(); if (prefs != null) { var photo = ((prefs.getString('photo') ?? "")); print('photo'); print(photo); String image = ""; if (image != null && image != "") { image = photo.substring(22); } } else { print('usu error'); } }
As per error, If `photo` is an empty string then using `substring(22)` on `photo` will throw the exception so add another check `photo.length > 22` to verify the lenth before substring as: if (image != null && image != "" && photo.length > 22) { The `image` is always empty as `image` is being declared and initialised right before `if` so you can modify `if` condition as: if (prefs != null) { var photo = ((prefs.getString('photo') ?? "")); print('photo'); print(photo); String image = ""; if (photo.length > 22) { image = photo.substring(22); } } else { print('usu error'); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "flutter, dart" }
Changed properties of application by accident what is default: FireFox I was trying to create a custom shortcut so that I could use multiple profiles with FireFox, however when I created the "link" it was a symbolic link so I edited what I thought was a "shortcut" but was editing the real application launcher. Q: What are the default settings for Firefox? Or How can I reset without losing everything? What happened: I wanted to use multiple profiles so I went to the applications folder and right clicked "Firefox"> "make new link" then I preceded to edit the link thinking it was a shortcut but in fact it was a symbolic link. Now I just need to know what is the default info for firefox or how can I reset without losing everything, because when I open firefox now I get an error that it is already open or a completely different browser opens.
Are you sure you edited the original file? It would have asked you your `sudo` password. **A.** If it did asked you, and you're talking about `/usr/share/applications/firefox.desktop` that was modified, here's a lesson: > _Don't use your sudo password if you're not sure of what you're doing_ **B.** If you never needed `sudo` admin password, then the original file should be accessible (read-only) in `/usr/share/applications/firefox.desktop`, you should copy that file's content in `~/.share/applications/firefox.desktop` **C.** If none of the above is right, you might just make a "default typical" desktop file: > > [Desktop Entry] > Comment=Browse the web > Name=Firefox > Exec=/usr/bin/firefox > Icon=firefox > StartupNotify=false > Categories=Network; > Type=Application > **D.** Ultimately, you could save your profile, purge firefox, and reinstall it clean.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "unity, firefox, shortcut keys, launcher" }
Custom List Not showing up I created a list using a msdn tutorial as given in link below, MSDN Custom List I followed each single step, and deployed the list, and I can see it deployed globally in Sharepoint Central Admin, + I can see it activated in "Site Feature" but when i go to "Site Actions" create a new list, I can't find it there, i used some other tutorials and I can see them custom lists, one more thing is On my servers there isn't Visual Studio so is there any better way to create a custom list, and deploy it on servers, as atm I have to make changes to files generated by Visual Studio if i want to deploy this custom list feature. Thanks
You need to add a Category attribute to the ListTemplate element in ListDefinition.xml. Category - Optional Text. Specifies the category with which to associate lists created through the list definition. Possible values include the following: * Libraries * Communications * Tracking * Custom Lists Regarding how to develop for SharePoint. I'd say you should have a development environment with both SharePoint and VS installed. I'd not use the VS extensions for SharePoint, but prefer to use either WSPBuilder or STSDEV when developing for SharePoint 2007. For SharePoint 2010 you should use VS2010
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "2007, list, development, wss 3.0, custom list" }
Parameters of a GET request are put into the query string of the URL. In a POST request, they are in the request body, so what does the URL look like? For example I may have a HTML form that uses a get method and produces the URL: for the the key-value pairs: Name: Gareth Wylie Age: 24 Formula: a + b == 13%! and for `HelloForm.java` (e.g. using java servlets) If I had the same HTML form, but used the POST request, what would the URL look like?
The URL will be same as `GET` with the query parameters omitted. That is:
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java, http, url, post, servlets" }
What is favicon.ico and why does my server try to make a connection to it? Im very new to web programming. I made a small front end program and decided to use python to host it on my computer. When I ran the python script I got the following messages on my terminal: 127.0.0.1 - - [16/Mar/2019 15:40:45] "GET / HTTP/1.1" 200 - 127.0.0.1 - - [16/Mar/2019 15:40:45] "GET /style.css HTTP/1.1" 200 - 127.0.0.1 - - [16/Mar/2019 15:40:45] "GET /btnEvent.js HTTP/1.1" 200 - 127.0.0.1 - - [16/Mar/2019 15:40:46] "GET /favicon.ico HTTP/1.1" 404 - The first three files belong to my program so thats correct. However, theres a last file favicon.ico and the request apparently failed. Why did that happen?
A favicon.ico is the little icon that browsers display next to a page's title on a browser tab, or in the address bar next to its URL. In practical when you bookmark any page then it shows a logo of website which is nothing but `favicon.ico`. It is default lookup of browsers.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "javascript, python, http, web" }
mime_content_type issue with some extension I try mime_content_type() / finfo_open(). It is ok for .doc but return 'application/zip' for .docx and nothing for .xls what is the problem ? is it a issue with my browser?
This question is basically the same: PHP 5.3.5 fileinfo() MIME Type for MS Office 2007 files - magic.mime updates? And it seems there is no solution. It's not your browser, it's a mime "magic" file that tried to guess, and there is no way to tell the different between docx and a zipfile because docx IS in fact a zipfile!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mime types, file extension" }
Access Stuck Using Security Workgroup My boss fancies himself an IT genius, and has created a number of databases, all secured with Access' user-level security MDW feature. Now for the MDW feature to work, you either have to craft shortcuts that point to the MDW, or you have to configure the workstation to use that MDW as default. He chose the latter. Now, when opening MY unsecured DBs, or even trying to create new blank ones, it wants me to login to his MDW. This cannot stand. How can I reconfigure Access to use the default MDW (I think it is called System.MDW). NB: I cannot run code in the VB window. I cannot open any databases at all. Solutions must likely be external to Access.
Okay, as it turns out, you need to modify the value `HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Access\Access Connectivity Engine\Engines\SystemDB` to "%appdata%\Microsoft\Access\System.mdw" Or, in the case of Office 2010, `HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Access Connectivity Engine\Engines\SystemDB` Not sure why I didn't look in the registry first.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ms access, workgroup, mdw" }
when i click on anchor i need to enable text field I have a anchor tag, with id="click_me". When i click on this i should enable input text (`<input type="text" id="summary" class="summary">`), which is disabled first. even i can do it using javascript function, by calling these javascript function() using onclick in the tag; but in my application i shld not use these. I am newbie to php. please suggest me any alternative solution either using DOM or anything else. Thanks in advance
jQuery: $('#click_me').click(function() { $('select-your-input-element-here').attr('disabled',''); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, javascript, jquery" }
How to create custom attr name with styled component? Can u explain me how to use SC with custom attr name? This code does not work and i dont understand why. I expect to receive like this `<div customAttrName="customAttrName"></div>` export const TagName = styled.div.attrs((props) => { console.log("props", props); return { type: "anyType", size: 25, customAttrName: "customAttrName" }; })` padding: 4px 7px 2px 10px; margin: 5px 6px 5px 0; border-radius: 5px; font-family: "MullerRegular", sans-serif; `; export default function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <TagName>Start editing to see some magic happen!</TagName> </div> ); }
For customs data attributes you need to use the prefix `data-*`: export const TagName = styled.div.attrs((props) => { console.log("props", props); return { type: "anyType", size: 25, data-customAttrName: "customAttrName" }; })` padding: 4px 7px 2px 10px; margin: 5px 6px 5px 0; border-radius: 5px; font-family: "MullerRegular", sans-serif; `; Using data attributes
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "reactjs, styled components" }
Отсутствуют AccountController и папка Account во Views при использовании Identity При создании проекта ASP.NET Core(2.1) Web Application => MVC Не нахожу в архитектуре AccountController и папки Account во Views. Авторизацию сделал, проходит, но внести изменения в оформление и функционал страниц логина не могу, так как не нахожу их в проекте. Подскажите, где их найти, или как вносить изменения?
Начиная с Asp.Net Core 2.1, Identity вынесена в отдельную либу (Razor Class Library), поэтому нет ни контроллеров, ни представлений. Чтобы кастомизировать Identity, нужно использовать Scaffolder - он позволяет выборочно добавлять исходный код нужных компонентов в проект, чтобы его можно было править. Вот, как это сделать: > * From **Solution Explorer** , right-click on the project > **Add** > **New Scaffolded Item** ( _Создать шаблонный элемент_ ). > * From the left pane of the **Add Scaffold dialog** , select **Identity** ( _Удостоверение_ ) > **Add**. > * In the **Add Identity dialog** , select the options you want. > Подробности в документации.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "c#, asp.net mvc, asp.net core, visual studio 2017" }
How to validate integer values to avoid SQL injection? The best way to avoid SQL injection for defined value type such as numbers, is to validate the value; since it is easier to do so comparing with mysqli preparation. In PHP, we can do this by. 1. if(!is_numeric($value)) {$value=0;} 2. $value=floatval($value); 3. $value=intval($value); 4. $value=$value * 1; What is the most reliable one? or a better idea? **UPDATE:** Although I have stated in the original question, most of folks emphasized the usefulness of parameterized queries. Definitely, it is the most efficient way to avoid SQL injection. But when we can simply validate an integer numeric value; IMHO, there is no need to parametrization.
For integers and floats you can use this if you don't want to do a parameterised query. $clean_number = (int)$value; $clean_number = (float)$value; These are actually casting the value as `int` and `float`, this is faster than `intval()` and `floatval()` for example because it does not suffer the function overhead.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "php, mysql, sql, integer, sql injection" }
¿Cómo hacer "sesiones" en golang como en php? Hola a todos les pido ayuda ya que estoy haciendo una sitio web con golang actualmente, y quiero implementar un sistema como las sesiones en php, es decir, tener variables que esten en todas partes del servidor, y que el cliente no tenga acceso a ellas a diferencia de las cookies, pero no se como hacerlo. He intentado buscar alguna forma de hacer algo similar, pero la mayoría de soluciones tenian fallas en varios aspectos, como problemas cuando se usa mas de un servidor o cosas por el estilo. Ahora que expliqué lo que me gustaría hacer, ¿hay algun paquete en golang que haga esto o conocen alguna forma de hacer algo como eso? Desde ahora gracias :D.
Hay muchas formas de hacer lo que dices, pienso que depende mucho de que librería o framework web uses. Por ejemplo si usas echo, este framework tiene middlewares (son como plugins para extender las funcionalidades a tu servidor web) que te permiten tener variables de sesión, aquí un ejemplo de como se implementan sesiones con el framework. Si te interesa, echo también te permite hacer render de templates (algo simiar como php) para tu web. También hay otros frameworks similares a echo como fiber o gin, te permiten hacer casi lo mismo. Si vas a usar net/http para tu web, puedes usar librerías como go-sessions. O también puedes crearlo por tu cuenta, en internet hay algúnos tutoriales para esto, aquí hay uno.
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "go, sesiones" }
Wann wünscht man jemandem eine "gute Zeit"? Wann sagt man zu jemandem > Gute Zeit! und was bedeutet die Aussage genau? Geht man davon aus, dass man sich lange nicht mehr sehen wird und dem anderen für eine unbestimmte Zeit alles Gute wünscht? Kann man es sagen, wenn man weiß, dass man die Person in z.B. einem Monat wiedersehen wird? Das habe ich in unterschiedlichen Kontexten gehört. Z.B. hat es mir eine Kollegin gewünscht, nachdem ich mit meinem Praktikum fertig wurde und mich verabschiedet habe. Gestern habe ich gehört, wie eine ältere Dame es einem älteren Paar auf der Straße gewünscht hat (wahrscheinlich kennen sie sich). Und eine zusätzliche Frage gleich: Wie kann man darauf antworten? Kann man "Gleichfalls" sagen?
Ich nehme an, du hast das in Süddeutschland gehört? > Ich wünsche Dir/Ihnen eine gute Zeit Ist ein typischer finaler Abschiedsgruss im Schwäbischen, wenn man sich von jemandem relativ endgültig verabschiedet, den man mit großer Wahrscheinlichkeit nie wieder oder lange nicht wieder sehen wird (Also eine Art mundartliche Version von "Lebe wohl"). Auch im Schwäbischen ist dieser Abschiedsgruß ein bißchen aus der Mode gekommen und man wird ihn eher von älteren Leuten zu hören bekommen. Die Schwaben, deren Verabschiedungsrepertoire mit "Ade" ein bisschen begrenzt ist, brauchten was, was zu "lebe wohl" passt. Deine Annahme ist also richtig - Für jemanden, den man in einem Monat wiedersehen wird, wird man den Gruß wohl eher nicht verwenden. Dort wo "leb wohl" passt, passt auch "ich wünsch' dir eine gute Zeit". Und lapidar mit "gleichfalls" zu antworten, passt eher nicht. Man würde eher "Ich ihnen/dir auch" antworten.
stackexchange-german
{ "answer_score": 4, "question_score": 5, "tags": "phrase" }
Clean way to bring back background process to foreground in shell script As an example: I have working shell script which starts up weblogic (which will continue to run) and then do deployment At the end I bring background process back to foreground, so that shell script does not exit (Exited with code 0) #!/bin/bash set -m startWebLogic.sh & # create resources in weblogic # deploy war # ... jobs -l fg %1 I had to use `set -m`, to allow job control, but I also found it is not cleaniest way to use it in non-interactive shells. Is there a better way to handle it?
As far as I understand your question you are looking for `wait`: #!/bin/bash startWebLogic.sh & # create resources in weblogic # deploy war # ... wait It does not "bring the process to foreground". But it does wait until weblogic returns. So the shell script does not exit until weblogic exits. Which is the effect you achieved with `fg %1`. from `help wait`: > Waits for each process identified by an ID, which may be a process ID or a job specification, and reports its termination status. If ID is not given, waits for all currently active child processes, and the return status is zero.
stackexchange-unix
{ "answer_score": 6, "question_score": 8, "tags": "shell script, job control, weblogic" }
MacOS path formatting of the dir I have the following paths (they are an example), I would like to be able to get the result below. /Users/nameUser /Users /Users/nameUser/Downloads/nameDir /Users/nameUser/Documents/nameDir /Users/nameUser/Desktop/nameDir/nameProject Result: /Users/nameUser /Users/ ~/Downloads/nameDir ~/Documents/nameDir ~/Desktop/nameDir/nameProject
The `FileManager` can provide the home directory path. So you can then check if a path starts with it, and if so, replace it with a tilde. func pathWithTilde(_ path: String) -> String { let homeDir = FileManager.default.homeDirectoryForCurrentUser.path + "/" if path.starts(with: homeDir) { return "~/" + path[homeDir.endIndex...] } return path } **Update** Turns out this already exists as a method of `NSString` (though it will also convert `/Users/nameUser` to `~`). A little `String` extension help hide the `NSString` specifics. extension String { var abbreviatingWithTildeInPath: String { (self as NSString).abbreviatingWithTildeInPath } } print("/Users/nameUser/Downloads/nameDir".abbreviatingWithTildeInPath)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "swift, macos" }
TPS61240 Boost converter IC is not working at all? I am currently using TPS61240 as a boost converter for my project. As i did not have any sample previously so there was no way I could test it. I ordered the IC and placed it on my final PCB directly. PCB layout and external components are according to the datasheets. I ran continuity and input voltage measurement test. There is no problem in PCB and Input voltage. But I am not getting 5 volts from the IC. I am in great trouble. Any suggestion would be appreciated. Thanks in advance. Here is the PCB layout. !enter image description here and here is the Schematics !enter image description here
I have added a 6.3V 100uf capacitor parallel to the 4.7uf ceramic capacitor at the output of the BOOST converter IC. Now Its working fine, and I am able to get 5.22 voltage from the input 3.3v.
stackexchange-electronics
{ "answer_score": 3, "question_score": 2, "tags": "voltage regulator, pcb design, switch mode power supply, dc dc converter, boost" }
HighCharts: how to update bar color when updating the point value I use the "update" command to refresh the value of a point in my series: mychart.series[0].data[i].update(sigvalue); Now I would like to update the color of this column/point as well. I tried mychart.series[0].data[i].color = "#FF0000"; But that did not work...
Color should be changed by attr() function. < $('#test').click(function() { chart.series[0].data[4].graphic.attr("fill","#ff0000"); }); API **`here`** for your reference.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "highcharts" }
new method declaration in derived interface I lately studied some code and encountered a derived interface that declares `new` method with exactly the same name and signature as a base interface: public interface IBase { Result Process(Settings settings); } public interface IDerived : IBase { new Result Process(Settings settings); } I'm wondering if there could be a reason for this. According to my understanding I can safely remove the latter method declaration and leave `IDerived` empty without possibly breaking any code using it. Am I wrong? P.S. If this matters, these interface declarations also have the following attributes: `ComVisible(true)`, `InterfaceType(ComInterfaceType.InterfaceIsIUnknown)` and `Guid(...)`.
Well, you _may_ be able to get rid of it - but if you get rid of the method in `IDerived`, it's not actually the same, strictly speaking. An implementation can actually provide two different methods to implement the two interface methods differently. For example: using System; public interface IBase { void Process(); } public interface IDerived : IBase { new void Process(); } public class FunkyImpl : IDerived { void IBase.Process() { Console.WriteLine("IBase.Process"); } void IDerived.Process() { Console.WriteLine("IDerived.Process"); } } class Test { static void Main() { var funky = new FunkyImpl(); IBase b = funky; IDerived d = funky; b.Process(); d.Process(); } }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "c#, .net, com interop" }
Azure Devops not listing Scale Set Agent Pools I've created a scale set agent pool. Managed to set everything, but I can't use it withing azure devops pipelines because it's not listed under Agent Pools. I can't create another Scale Set Agent Pool with the same Scale Set as it detects it being used. If I check it from az cli: `az pipelines agent list --pool-id 25 -o table` will show all 3 instances up and online.
Seems like the reason it was not showing was because the location of my organization and the resource group where different. Made another resource group with the same location as my organisation and I got it. Although I have some hard time making the agents work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "azure, azure devops, azure cli, azureportal" }
QGIS Label Expressions I'm trying to create a label that will show the following: MP 23.6 The "23.6" is a double type column in my table, the "MP" is the text I want to add in front of it of the number (milepost). I am new to QGIS. ![enter image description here](
You are trying to perform an addition between a string and a number. Instead, use the `||` evaluator which will concatenate both into a string like so: 'MP' || "Milepost" You could also transform the value of your `Milepost` field to a string in your expression as in this question/answer.
stackexchange-gis
{ "answer_score": 2, "question_score": 1, "tags": "qgis, labeling" }
android:fontFamily requires api level 16, but docs say level 15 is ok? How do I set the font family on API level 15? The docs say API 15 _does_ have the fontFamily attribute. I hoped the docs would say > "This is depcrecated in API level 15. For API level 15 and lower, see [........]" but they don't. How do I set the font in XML (or programmatically) without generating this warning? This is a screenshot from Android Studio on Ubuntu. styles.xml: !enter image description here < !enter image description here
You are wrong what you are seeing is the `class API` not the `attribute` API level: You can look here and said: public static final int fontFamily Added in API level 16 Font families are actually create since android 4.1 not in `4.0.3-4.0.4`
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "android" }
Is there any reason to not run the scheduled job Clean-up Temporary Data and Files every hour? I discovered some problems with Smart Groups that use IN search criteria for custom fields not showing counts. I have the scheduled job Rebuild Smart Group Cache running. However, only after running Administer -> System Settings -> Cleanup Caches and Update Paths, then selecting Update Smart Group Counts, was I able to see updated Smart Group counts. It seems running the scheduled job Clean-up Temporary Data and Files _should_ do the same thing as Cleanup Caches, since it "[r]emoves temporary data and files, and clears old data from cache tables". Is that the case? Currently the scheduled job Cleanup Caches and Update Paths is disabled. So - is there any reason to _not_ run the scheduled job Clean-up Temporary Data and Files every hour? Thanks so much!
Check how long it takes to run on your system. if it doesn't take too long, I don't see any reason not to run it hourly.
stackexchange-civicrm
{ "answer_score": 3, "question_score": 3, "tags": "smartgroups, settings, scheduled job, cache" }
web.xml and relative paths in web.xml i set my welcome file to a jsp within web.xml <welcome-file>WEB-INF/index.jsp</welcome-file> inside index.jsp i then forward on to a servlet <% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %> however the application tries to find the servlet at the following path applicationName/WEB-INF/myServlet the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?
<% response.sendRedirect(response.encodeRedirectURL("/myServlet/")); %>` since the jsp is served from the WEB-INF directory the servlet url is also resolved from that relative path. adding a / before will resolve the url from the context root
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "deployment, tomcat, web.xml, descriptor" }
Coordinates on Button Click javascript Can any one plz tell me where i am wrong.I want to get coordinates of button on click but it give me error **js/main.js (1) :ReferenceError: Can't find variable: $** Button: <input type="button" style="margin-left: 80px;margin-top: 80px;" id="theButton" value="A button" /> J Query var jq = $('#theButton'); var position = jq.offset(); alert('x: ' + position.left + ', y: ' + position.top); it doesn't show me anything
Try this code: $(document).ready(function(){ var jq = $('#theButton'); var position = jq.offset(); alert('x: ' + position.left + ', y: ' + position.top); }); Add any version of `jquery` first in the head sections before adding your `main.js` like: `<script src=" Check fiddle <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html" }
Differences among iOS Simulators I have an app that is intensive computationally but is fairly simple programatically. For example, there are no threads. Everything is straight-line. If I run the app in the iPhone retina 3.5" simulator, I can get exercise the app enough to get it to cause an access violation without much difficulty: {Called from the UIView drawRect method} UIImage *image = [self getImage] ; [image drawAtPoint:point] ; // Crash here-no identifiable pattern when it crashes here. The `getImage` method either returns a pointer to a `UIImage` already loaded or loads the image and returns the pointer. The debugger appears to show a valid `UIImage` after a crash. If I run the app in any of the other simulators, do not encounter a problem. In fact, this is the first access violation I have seen since developing this app. Is there something that is inherently different with the 3.5" simulator or phone?
I discovered what the problem was. Sort of. I noticed that it was always crashing on the same same image. I have 1700 images, whenever it was displaying this one in the 3-1/2" simulator---crash. I loaded the PNG image into photoshop (where it had been created originally). I changed from Indexed color to RGB and no more crash. I have no idea why it only crashed on that one simulator. Preview, Safari, Chrome and Photoshop had no problem with the image.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, ios simulator" }
How to identify a given string is hex color format I'm looking for a regular expression to validate hex colors in ASP.NET C# and am also looking code for validation on server side. For instance: `#CCCCCC`
Note: This is strictly for _validation_ , i.e. accepting a valid hex color. For actual _parsing_ you won't get the individual parts out of this. ^#(?:[0-9a-fA-F]{3}){1,2}$ For ARGB: ^#(?:[0-9a-fA-F]{3,4}){1,2}$ Dissection: ^ anchor for start of string # the literal # ( start of group ?: indicate a non-capturing group that doesn't generate backreferences [0-9a-fA-F] hexadecimal digit {3} three times ) end of group {1,2} repeat either once or twice $ anchor for end of string This will match an arbitrary hexadecimal color value that can be used in CSS, such as `#91bf4a` or `#f13`.
stackexchange-stackoverflow
{ "answer_score": 243, "question_score": 109, "tags": "regex, colors" }
Typescript: Replace string & append HTML tag with id attribute I need to replace the string with an HTML tag & having an id attribute. Here is my code, TS file: let content = "this is a car."; content.replace(new RegExp('car'), match => { return `<span class="highlight-text" id="car"> + match +</span>`; }); <div [innerHTML]="content"></div> In inspecting element it shows only class, <div> <span class="highlight-text">car</span> </div> It doesn't add an ID attribute in the span tag why?
The id field is eliminated by Angular in the process of DOM sanitization. To add the id field in the innerHTML, you will have to explicitly tell Angular, that it's safe to parse this HTML content. You can implement it in the following way: let oldContent = "this is a car."; oldContent.replace(new RegExp('car'), match => { return `<span class="highlight-text" id="car"> + match +</span>`; }); let content = this.sanitizer.bypassSecurityTrustHtml(content) where, sanitizer is an instance of DOMSanitizer, which should be injected in the constructor. constructor(private sanitizer: DomSanitizer) { }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angular, typescript" }
Why is the Finder app always open? First time Mac user. I am confused by the fact that the finder application is always open. For example, when switching apps with `Cmd`+`Tab`, it is always there, even when there are no windows opened for the app. `Cmd`-tabbing to Finder with no windows/tabs opened for it has no effect (it seems to me it would more intuitive to open a new tab when this action is chosen). Furthermore, there is no 'Close app' option when I right click the Finder icon in the dock. Am I misunderstanding something about the Finder app? Is it required for proper functioning of macOS? From what I see, Finder is just a file browser, which by no means should be forced to be open 100% of the time.
The main reason it's always open is that it displays the icons on the desktop. You can check what the finder does by enabling the "Quit" menu feature. To do this, launch the Terminal application and enter the following commands: defaults write com.apple.finder QuitMenuItem -bool YES Hit return. Then restart the Finder by running killall Finder Close the Terminal. Click on the Desktop, choose "Finder" in the top bar, and "Quit Finder". Now you're running without Finder. First thing you'll notice is that all Desktop icons will be gone. To get your desktop icons back, just click on Finder in the Dock. If you want to remove the "Quit Finder" menu item, you can do that with: defaults write com.apple.finder QuitMenuItem -bool NO
stackexchange-apple
{ "answer_score": 59, "question_score": 52, "tags": "finder, macos, application switcher" }
PayPal Business account does not accept payment I've made a buyer account and a seller account. I've generated the button, pasted it into my code and tried it. Then proceed with the transaction and the page for success is showing. After that I log in with the seller account, but there isn't any activity. On the page of the buyer the activity is present, but there is label '... hasn't accepted yet'. How to accept the payment from the seller account? Do I need to register a credit/debit card or bank account? What is missing?
I've did some research and without using your real paypal account and then log in developer.paypal.com you cannot test the functionality. So it is a necessity to have a working PayPal account whose credentials you will use to log into developer.paypal.com and there you will have generated test accounts already. In a few words: You cannot create a sandbox acc directly and use it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "paypal sandbox" }
Visual Studio Tips on getting headers that are used in a given project? I have added all the header files from library in path how to get the headers that are only needed for the project
There's a compiler option that will produce a list of included files for a compilation unit in your Build Output window. In the property page for the compilation unit, under the C/C++ Advanced section, there's an option called "Show Includes". Turn that on and recompile. You can probably do this on the project level as well, but I suggest you do it per compilation unit (.cpp) one by one.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio, visual studio 2008, visual studio 2005" }
Euler's formula for non-planar graph Could anyone please provide an example of non-planar graph, that corresponds to Euler's formula: $$v - e + f = 2$$ or show that there is no such a graph?
In general, Euler's formula can only be used to prove that a graph is non-planar. To prove planarity, one usually either finds an actual plane drawing or shows that the graph contains no $K_5$ or $K_{3,3}$ minors.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "graph theory, planar graphs" }
Is it not possible to construct instances in a loop without a pointer? This code will explode, right? As soon as the loop exits, the original instances will die with all their inner members so if they weren't PODs, any method like `do_stuff` which requires access to members of `B` will throw a segmentation fault, correct? void foo() { std::vector<B> bar; for (int i = 0; i < 7; i++) bar.push_back(B(i, i, i)); bar[3].do_stuff(); } So, is there any way to do this without using a pointer? Or do you have to do this: void foo() { std::vector<B*> bar; for (int i = 0; i < 7; i++) bar.push_back(new B(i, i, i)); bar[3]->do_stuff(); for (int i = 0; i < 7; i++) delete bar[i]; }
The first code is better than the second one. The `B` instances will be **moved** since C++11/ **copied** pre-C++11 into the vector, so they will not fall out of scope after the loop — only after the vector falls out of scope. * * * If you want to get the absolutely optimal performance, then do this: void foo() { std::vector<B> bar; bar.reserve(7); for (int i = 0; i < 7; i++) bar.emplace_back(i, i, i); bar[3].do_stuff(); } This will guarantee only one reallocation, and the elements are constructed directly inside the vector (instead of moving or copying them there) as per Marc Glisse's comments.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 7, "tags": "c++" }
SQLite: no such column error I'm getting the `sqlite3.OperationalError: no such colum: bla` error. I have a sqlite file, which only consists of one table `foo` with column `bar`. connection = lite.connect(db.sqlite) def insertEvent(self, bar): with connection: cur = connection.cursor() cur.execute("INSERT INTO foo(bar) VALUES (bar);") insertEvent("bla") Is my syntax wrong or why am I getting the error? I couldn't find any useful solutions in all the other questions. Just in case: I'm using the sqlite3 library.
Try changing the insert statement to cur.execute("INSERT INTO foo(bar) VALUES (?);", (bar,)) You aren't using the `bar` parameter in the insert statement.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, sqlite" }
Suggest methods for testing changes to "pam.d/common-*" files How do I test the changes to the pam.d configuration files: * Do I need to restart the PAM service to test the changes? * Should I go through _every_ service listed in the `/etc/pam.d/` directory? I'm about to make changes to the `pam.d/common-*` files in an effort to put an Ubuntu box into an active directory controlled network. I'm just learning what to do, so I'm preparing the configuration in a VM, which I plan to deploy in metal in the coming week. It is a clean install of Ubuntu 10.04 Beta 2 server, so other than SSH daemon, all other services are stock.
PAM configuration files are read dynamically. To test, you can authenticate to the appropriate software and view the logs. It is often wise to understand all the configuration files in question if you are attempting to make expansive configuration changes. PAM man page
stackexchange-serverfault
{ "answer_score": 6, "question_score": 8, "tags": "linux, ubuntu, pam, ubuntu 10.04" }
Iframing https site on http sites? I'm about to add an ssl certificate to a rails application hosted on heroku, so I can activate stripe payments. The main function of our app is to let users create embeddable widgets. The widgets are essentially iframes of the views for the objects they're creating in our rails app. The vast majority of our users' sites are using http, and I'm concerned that if we switch our app domain to https, the iframed widgets they've embedded would stop working. Is it possible to have a secured domain name for our app, and let the users embed widgets that iframe parts of the app with source urls using just http?
You could only enforce SSL on certain routes. scope constraints: { protocol: "https" } do # routes you'd like secured end Then, don't enable `force_ssl` for the entire site and the other components should be unsecured.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, iframe, heroku" }
boost multiple calls to class method In boost::thread is it possible to call a class method with out making the class callable and implementing the void operator()() as in just call the class method for(int i=0;i<5;i++) boost::thread worker(myclass.myfunc,i,param2); I get an error `<unresolved overloaded function type>` Actually I would prefer to know the same for zi::thread
`boost::thread` doesn't need anything special, it will work exactly as you want (minus syntax errors): for (int i = 0; i != 5; ++i) boost::thread worker(&myclass::myfunc, myclassPointer, i, param2); From the boost.thread docs: > `template <class F,class A1,class A2,...>` > `thread(F f,A1 a1,A2 a2,...);` > > **Effects:** As if `thread(boost::bind(f, a1, a2, ...))`. Consequently, `f` and each `aN` are copied into internal storage for access by the new thread.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c++, multithreading, boost, callable" }
How to take input from a column and change it to something else and count it From this file < I need to take column 3 which consists of numbers 1-6 and output those numbers to words like 1-sparkling, 2-fine without changing the file. Also these have to be counted so I can output how many of each type there is with the corresponding name. I tried many different kinds of `awk` codes and haven't been able to get it. Currently I have awk -F: '$3==1, ((counter++)) {print counter1}' wine.txt which gives me no output at all.
**`awk`** solution: Assuming the relation map: _(sparkling=1 fine=2 fortified=3 sweet=4 white=5 red=6)_ * * * awk -F':' 'BEGIN{ split("sparkling fine fortified sweet white red", words, " ") } $3 in words{ c[$3]++ } END{ for(i in words) print words[i]"="c[i] }' file * `split("sparkling fine fortified sweet white red", words, " ")` \- split the string containing crucial words into array `words` by separator `" "`(space) so that the array will be indexed with consecutive numbers having words as values (i.e. `words[1]="sparkling" words[2]="fine" ...`) * `$3 in words{ c[$3]++ }` \- check if the 3rd field value (containing a digit) occurs within array `words` indices, if so - count matches with `c[$3]++` * * * The output: sparkling= fine=15 fortified=28 sweet=10 white=23 red=24
stackexchange-unix
{ "answer_score": 1, "question_score": 1, "tags": "linux, text processing, awk" }
Style reset password page? /wp-login.php?action=rp I cannot figure out how to style the reset password page. And I do not mean the page where you request it, I mean the page you are shown when you click the link in the email to set your new password. The URL is `/wp-login.php?action=rp` And looks like this ![]( And the confirmation page: ![]( How do I load my custom styles for these?
You should use login_enqueue_scripts, you can load styles or scripts with it. Example: function login_styles() { wp_enqueue_style( 'loginCSS', '/my-styles.css', false ); } add_action( 'login_enqueue_scripts', 'login_styles', 10 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "customization, wp enqueue style" }
Can I minify JSON-LD without affecting the output in search engines? Can these type of scripts be minified without affecting the output in search engines? Example script: <script type="application/ld+json"> { "@context": "example.com", "@type": "Organization", "url": "example.com", "logo": "example.com/logo.png" } </script>
You can only minify it on the HTML way, with deleting of needless spaces, like: {"@context":"some-domain.com","@type":"Organization","url":"some-domain.com","logo":"some-domain.com/logo.png"} Its functionality remains.
stackexchange-webmasters
{ "answer_score": 3, "question_score": 2, "tags": "rich snippets, json ld" }
How do I enable click on listview? I'm currently working on a code which is written by someone else in my office. I need to enable selection of items in the listview. I know I have to use setOnClickListener. Can someone guide me through this? I've written: Edit: listview.setOnClickListener( (View.OnClickListener) this ); Now what do I do? I need to select an int value and pass it on to another function, which is used to retrieve a certain set of values from a db.
listviewName.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //variable position will give you the required element/object from the array list. } });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, listview" }
Why line declared 'containing no code' in gcov I am trying to analyze code coverage in c++ program using gcov. An output line I got is: //my_header.h.gcov -: 349: TArray<unsigned,1,8> my_var; According to gcov documentation it means that 'line 349 contains no code'. As one can clearly see, this line contains code, namely a declaration. I would really like to understand what happpens there.
Declarations are really just information for the compiler, and no executable code is generated. Therefore, there's nothing in this file to determine coverage for.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, gcc, gcov" }
Javascript: How do I add an HTML code within tags after a given condition is found to be true? I cannot use ng-if because if the condition is false, it would remove the whole tag(will it?), which I don't want. I just want a small code to be added within tags if condition is true, and not-added if it is false. I have something like: <input ***stuff*** ng-if="condition==true" style="text-transform:capitalize"/> If the condition is true, simply add the style in the tag, otherwise, don't add it. I know I can do it by adding a class if the condition is met true and then add the css-part for the class, but, is it possible the way I've mentioned?
Using ng-style you can achieve your result: Here is an example. angular.module("myApp", []).controller("myCtrl", function($scope) { $scope.condition = true; }) <script src=" <html ng-app="myApp"> <body ng-controller="myCtrl"> <input ng-style="condition ? {'text-transform': 'capitalize'} : ''"/> </body> </html>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery, html, css, angularjs" }
CMake External Project Symlinks I am building an external project that generates shared objects with symlinks: i.e. libxml.so -> libxml.so.0.0.0 libxml.so.0 -> libxml.so.0.0.0 libxml.so.0.0.0 I want to copy these 3 files to my library output path. However, if I do: ExternalProject_Add_Step( xml copy2lib COMMAND ${CMAKE_COMMAND} -E copy_directory ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH} DEPENDEES install ) All of the symlinks are destroyed and there are essentially 3 copies of the library. I am aware of the following solution, i.e.: COMMAND ${CMAKE_COMMAND} -E create_symlink ./libxml.so.0.0.0 ./libxml.so WORKING_DIRECTORY ${LIBRARY_OUTPUT_PATH} However, in my case, the external project is generating dozens of libraries that follow this convention. Please tell me I don't have to manually repair every symlink?
CMake has a poor support for file links (symlinks, hardlinks, etc.). Partially, this is because there is **no cross-platform view** of such thing: Windows and Linux have different interpretation of these terms. So, when you want to operate with Linux symlinks in a specific way, use Linux-specific commands. Instead of cross-platform `cmake -E copy_directory` use Linux-specific `cp`: COMMAND cp -Pr ${EXTERNAL_INSTALL_PATH}/xml/lib/ ${LIBRARY_OUTPUT_PATH} * * * Note, that copiing symlink has a sence only for _relative_ symlinks. If symlink contains _absolute_ path, after copy it will refer to original library location, not to the copied one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "cmake" }
Changing Padding of TextView in a ListView I have a listview with an arrayadapter that holds these views <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="wrap_content" > <CheckedTextView android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/list_item" android:gravity="center_vertical" android:minHeight="?android:attr/listPreferredItemHeightSmall" android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" android:paddingStart="?android:attr/listPreferredItemPaddingStart" android:textAppearance="?android:attr/textAppearanceListItemSmall" > </CheckedTextView> </LinearLayout> I want to add X padding to the left of the textview when activated and remove that padding when not selected. The padding will not update. How do I manage this?
Since you have your `CheckedTextView` within a `ListView` you can set an `AdapterView.OnItemClickListener` on the `ListView` using the `setOnItemSelectedListener (AdapterView.OnItemSelectedListener listener)` method and override the `onItemClick(AdapterView<?> parent, View view, int position, long id)` method. Inside that `onItemClick()` method, you check to see which one was the view that was clicked (by comparing the `position` variable that shows the position of the view that was clicked, with your `CheckedTextView`'s actual position to see if they match). Then if your user has indeed click in your `CheckedTextView` you check to see if the `CheckedTextView.isChecked ()` is true. If it is true, change the padding programmatically, else let it be.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, listview" }
How to create instructions and arrows What are the tools used to create the instructions and arrows in such images? Which one is the font? !enter image description here
You can use different programs to do that image. I would use Photoshop, if you have access to it, depends on your OS (mac has great easy soft for this, and Gimp is an excellent program that you can download for free). For Photoshop, put a black layer with 70% opacity for the background, then for the arrows you could use any of these shapes: < And about the font, you could pick your own from here: < * * * In addition to this answer: arrows are not shape,(they can be used as alternative)but you can get same brush from here * * * Make sure all the materials you use have the appropriate licence if you want to distribute your creation.
stackexchange-graphicdesign
{ "answer_score": 3, "question_score": 0, "tags": "adobe photoshop, gimp, shapes" }
HTML tags are not rendered while iterating over an array in ReactJS I am quite new to ReactJS and still playing with the basic concepts, so the answer to my question might look obvious for pros ;) **I have a component as below:** import React from "react"; function NameList(props) { const names = ["Bruce", "Clark", "Diana"]; return ( <div> {names.map((x) => { <h1>{x}</h1>; console.log({ x }); })} </div> ); } export default NameList; Can someone tell me why the h1 tags are not rendered while the values are written in the console?
Just add `return` before the `<h1>` tag based on the syntax which have been used: function NameList(props) { const names = ["Bruce", "Clark", "Diana"]; return ( <div> {names.map((x) => { console.log({ x }); return <h1>{x}</h1>; })} </div> ); } ![Edit relaxed-feather-frdd9](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, reactjs" }
How can I get an empty Builder for a model? Lets say I have a function that returns a builder. In case this builder cannot be returned, I want to return an empty builder - meaning, a builder which doesn't point to any data. One which if you do a get(), you will get empty collection. Any idea?
This is how you do it: $builder = Post::query();
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 19, "tags": "laravel, builder" }
Changing database structure at runtime with Entity Framework? I have to write a solution that uses different databases with different structure from the same code. So, when a user logs to the application I determine to which database he/she is connected to at runtime. The user can create tables and columns at any time and they have to see the change on the fly. The reason that I use one and the same code the information is manipulates the same way for the different databases. How can I accomplish this at runtime? Actually is the Entity Framework a good solution for my problem? Thanks in advance.
You can do this with EF 4 using a code-first model. That said, I tend to avoid changing DB metadata on the fly, with or without EF. Rather, I'd choose a schema which fits the user's changing needs.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "entity framework, schema, runtime" }
No SB_LINEDOWN when scrollbar position is zero Scrollbar isn't giving SB_LINEDOWN or SB_PAGEDOWN events when the current position is at the top. If I drag the thumb down, then events are delivered. What am I missing?
Not expectedly it was a logic problem caused by incorrectly using the pos argument to OnVScroll. (facepalm) Thanks and a +1 to Mark Ransom for taking the time to reply.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, mfc, visual c++ 2008" }
XPath composition in XQuery I two XPaths, `f(x)` and `g(y)`, and some XML `x`. x = <example> <a> <number>1</number> </a> <b> <letter>A</letter> </b> <c> <number>2</number> </c> </example> `f(x) = /example/*` `g(y) = /number|/letter` How do I write `h(x)` in XQuery such that `h(x) = g(f(x))` for any `g(x)`? I don't know `g(x)` ahead of time so I cannot modify it. I can modify `f(x)` if necessary. All of this needs to happen in XQuery because it's part of an Oracle query. `h(x) = g(f(x)) = $data/example/*...`?
I may be confused about the question, but if I have understood it correctly then the answer is let $f := FFFF return $f/(GGGG) where FFFF and GGGG are the expressions corresponding to f(x) and g(y) But I'm assuming that you got your example wrong, and when you wrote g(y) = /number|/letter you meant g(y) = number|letter i.e. a relative selection rather than an absolute selection.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "xpath, xquery" }
How to associate a CLPlacemark to a language (ideally bcp47) I need to know what language(s) is spoken in a given CLPlacemark. Any idea?
I've ended up with the following, 100% automatic solution, and you don't need to collect any ISO code at all. + (NSString*)detectBestLanguageBCP47:(CLPlacemark *)placemark { NSString * countryCode = placemark.ISOcountryCode; for (AVSpeechSynthesisVoice *voice in AVSpeechSynthesisVoice.speechVoices) { NSString *langCode = [voice.language substringWithRange:NSMakeRange(0, 2)]; NSString *cc = [voice.language substringWithRange:NSMakeRange(3, 2)]; int c = [cc compare:countryCode]; if (c==0) { NSString *bcp47 =[ NSString stringWithFormat:@"%@-%@", langCode, cc]; return bcp47; } } return nil; // Not found }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, core location, reverse geocoding" }
Can't compare tokens I made a code to tokenize the data in file using C. I want to print some data if the current token is equal to `SIOL`. My problem is `strcmp` won't work. Can you spot any errors? Here is the code. Thank you for your help int main() { FILE* fp; char line[1024]; char *val1; fp = fopen("sample1.txt" , "r"); while (fgets(line, sizeof(line), fp) != NULL) { val1 = strtok(line, " "); if (strcmp(val1,"SIOL")==0) { printf("Sucess!"); return 0; } else { while(val1) { printf("%s\n", val1); val1=strtok(NULL, " "); } } } } sample1.txt like this: HAHA SIOL Hello World! SIOL 123 4 345 65 756 867 789797 Hello World
The problem in your implementation is that it does not treat `\n` properly. When `fgets` encounters `'\n'` character, it returns it as part of the string. Therefore, both `"SIOL"` strings from your file are returned to your program as `"SIOL\n"` when you tokenize, because they both are at the end of the string. `strcmp` does not consider `"SIOL"` and `"SIOL\n"` equal to each other, so it returns a non-zero value. To fix this, add `'\n'` to the list of delimiters accepted by your program: val1 = strtok(line, " \n"); // change the second call of strtok as well This will make sure that `strtok` eliminates `'\n'` at the end of the token, and passes a clean token back to you.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c, token" }
How do I convert msg.obj into the corresponding object and the compiler does not issue a warning? MutableList use as keyword `when(msg?.what){ MESSAGE_GET_LIST -> { if (msg.obj != null && msg.obj is MutableList<*>){ list = msg.obj as MutableList<BaseIncomeBean> ` when I received a message and want to use it ,I must covert to MutableList use as keyword Finally build my project and appear following warning Warning:(51, 40) Unchecked cast: Any! to MutableList<BaseIncomeBean> How do I fix this warning?
_Kotlin_ has smart casts. But Generics are erased at runtime. Thus you never know the type of list contents. It would work to just cast it to `MutableList<*>`: if (msg.obj is MutableList<*>) list = msg.obj as MutableList<*> But since you set up your project, you know, that the cast should be successful. In this case you could just tell the compiler to ignore the warning: if (msg.obj is MutableList<*>) @Suppress("UNCHECKED_CAST") list = msg.obj as MutableList<BaseIncomeBean>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "android, kotlin" }
Ошибка TypeError: 'int' object is not subscriptable при операции с объектом списка for x in range(0, n): te = d[x] % 2 При смене типа данных на Float выдаёт всё то же. Заранее спасибо за внимание!
а переменная `d` у вас какого типа? очень похоже, что `int`, а не `list` т.е. когда вы пытаетесь обратиться к `int` как к массиву возникает TypeError: 'int' object is not subscriptable простой пример x = 11 print(x[0] % 3)
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
UISwitch too slow when forceRightToLeft My app uses English and Arabic languages. I have this in my AppDelegate: if isArabic { UIView.appearance().semanticContentAttribute = .forceRightToLeft } When `Arabic(forces elements to go right-to-left)`, all UI elements seem to work fine, except `UISwiftch`. It works but it is too slow, it toggles, then after one or two seconds it changes its color depending on `ON/OFF State`. No more code for UISwitch except this: @IBOutlet weak var mySwitch: UISwitch! , so I don't know what causes this weird issue.
Fix I have found: Even if whole app is forced right-to-left on Arabic, I force left-to-right my UISwitch. You can do it in `viewDidLoad` mySwitch.semanticContentAttribute = .forceLeftToRight On is still On, Off is still Off, everything works, the UISwitch is on the left side of the screen because the whole screen is forced to left when Arabic, that is also fine. The only difference now is that the `On` state is active when you swipe toggle left(like in English), not right. But thats almost insensibly and none notices the "hack" :)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "swift, uikit, togglebutton, uiswitch, toggleswitch" }
salesforce Apex class - Http Post json This is kind of new to me - I need to make apex http post call and to set the body as json. My json is constructed in the following way: { "request": "request", "ID": "reqId", "getString": { "StringOne": "12345", "StringTwo": "67891", } } Can you please help me with building this Json inside my apex class ? I'm a bit stuck in the part of the getString - I didn't understand what is the best way to add new object with fields - and set the fields name inside this object. Thanks !! EDIT: This what iv'e done so far .. JSONGenerator gen = JSON.createGenerator(true); gen.writeStartObject(); gen.writeStringField('request', 'request'); gen.writeStringField('ID', 'reqId'); gen.writeEndObject(); String jsonS = gen.getAsString();
Don't use JSONGenerator unless you're porting legacy Java code that already uses it. It's more efficient to just use a Map: String jsonString = JSON.serialize( new Map<String, Object> { 'request' => 'request', 'ID' => 'reqId', 'getString' => new Map<String, Object> { 'StringOne' => '12345', 'StringTwo' => '67891' } } );
stackexchange-salesforce
{ "answer_score": 1, "question_score": 0, "tags": "apex, json, httppost" }
Reinstall Aptana Studio 3 bundles to get my custom snippets back? I'm using Aptana Studio 3 for JavaScript development. Day 1, I tried importing some old favorite Textmate snippets etc. with limited success. Some keys like dot, comma, "d + number" etc. takes precedence over my custom commands and the situation has become almost unbearable ... _(Hmm, no, unbearable situation should be reserved for this:< What should I do next? _I really just want to take back control :)_ 1) How do I make sure my own custom snippets always takes precedence in all scopes? 2) How do I delete all existing (conflicting?) bundles and get some decent ones back?
I believe the majority of those cases were issues with 3.0.4. Can you try updating to 3.0.5 beta to see if that helps?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, aptana, code snippets, textmatebundles, bundles" }
unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) ubuntu I had working selenium with my firefox, but today morning when i ran my test i got the same error. I updated selenium-webdriver for current version ( 2.38 ), but i still have that error. Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) # /home/user/.rvm/gems/ruby-2.0.0-p195@taxand/gems/selenium-webdriver-2.38.0/lib/selenium/webdriver/firefox/launcher.rb:79:in `connect_until_stable' also i checked it in my other project where i have 2.35 version and it also worked yesterday - and there it also doesn't work today ;o So i suppose that is no selenium issue, but my FF can be broken? But i also tried to run it with custom firefox_path to older firefox versions, and the issue is the same :< Any ideas?
I've found the same problem in Mac OS X Mavericks after I updated the Firefox 26. I solved the problem by updating the selenium-webdriver gem In your gemfile, replace your current selenium-webdriver gem line with `gem "selenium-webdriver", "~> 2.38.0"` In your console, `gem update selenium-webdriver`. Then `bundle install`. Try the running the test after.
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 13, "tags": "firefox, selenium" }
Bash: Last Returncode filling variables at bash I can get Returncode of last Command with $?. This does not work by filling a variable as shown: VARIABLE=`echo "My great Text"` Return Code is allways 0. How can I get the Returncode of the Command?
The VARIABLE in your example will get the output of the command > echo $VARIABLE > > My great Text You need to get the result value after that with $? `echo` will always return 0 since no reason it will fail here. In general, you check the status like so: output=`script.sh` retval="$?" echo "Script output is: " $output echo "Script return value is: " $retval < Note, this will read the return value of the script if you used `exit <code>` (I believe it is the case). If the return value is the output of the script, > retval=`script.sh' should be used (but then it is not a return value per se)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "bash, variables, return value" }
useEffect localStorage loop I'm trying to storage a single state and I cannot do that apparently because of a infinite loop. Could you help me? ![enter image description here]( import React, { useState, useEffect } from "react"; const App = () => { const [rows, setRows] = useState("Inicial State"); function init() { const data = localStorage.getItem("my-list"); if (data) { setRows(JSON.parse(data)); } localStorage.setItem("my-list", JSON.stringify(rows)); } useEffect(() => { init(); }); return ( <div> <button onClick={() => setRows("Loaded state!")}>Load!</button> <div>{rows}</div> </div> ); }; export default App;
You call init() every time component re-render. Document how to use `useEffect` here: < You should only call one time like `componentDidMount` in class component by: useEffect(() => { init(); }, []); useEffect(() => { localStorage.setItem("my-list", JSON.stringify(rows)); }, [rows]);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "reactjs, react hooks, state, persistence, use effect" }
Random six letter string in Python Ok, let me rephrase my whole problem. I want to be able to write a Python script that lets me type random letters into Microsoft Word without my keyboard. So for example, I can generate a random string of letters with a code such as the following: import string, random a = string.ascii_uppercase b = random.choice(a) c = random.choice(a) d = random.choice(a) print a + b + c Let's say the code prints out 'HVF'. I want to type this string into Microsoft Word with the same script, which is easy using ctypes. However, that program is only capable of typing only that string 'HVF'. I want a program that will generate any random string of letters, then type that string into Microsoft Word.
From your edited question, looks like you're having trouble looping your program. This is absolute beginner material, so you're clearly jumping light years ahead by diving into `ctypes` to produce a keystroke. Ah well, here we go anyway.... import random, string NUM_CHARS = 6 # how long the string should be textbank = string.ascii_uppercase * NUM_CHARS while True: word = random.sample(textbank,NUM_CHARS) for letter in word: press_key_however_you_do_it(letter) # I have no idea how you're implementing this, but you do press_key_however_you_do_it(" ")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, random, types" }
Copy texture binded to FBO to another OpenGL context I am trying to copy texture from FBO created in one context to another context. I am using Qt 4.8.3 and QGLFramebufferObject class, OpenGL 2.1. i created two contexts with widgets using qt class `QGLWidget` I was trying using blitFramebuffer method to copy full FBO to another context, but not succeeded. How can i copy texture from FBO, or maybe there is another way to transfer visual content from FBO. The FBO is created with such parameters new QGLFramebufferObject(arraySize, arraySize, QGLFramebufferObject::NoAttachment, GL_TEXTURE_2D, GL_ALPHA);
I got two solutions for this problem 1. copy texture attached to the FBO using `glGetTexImage` ` uint * pixels = new uint[FBO_WIDTH * FBO_HEIGHT]; glBindTexture(GL_TEXTURE_2D, someFBO->texture()); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);` 2. share resources as Mateusz Grzejek said: in qt you must put a parameter to the constructor `shareWidget` of `QGLWidget`, read more here QGLWidget e.g. `GLWidget(QWidget *parent = 0, QGLWidget * shareWidget = 0);` and then when you creates two GL widgets use style like this `GLWidget *glWidget = new GLWidget(this); GLWidget *glWidget2 = new GLWidget(this, glWidget);`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, qt, opengl, fbo" }
Equating coefficients explanation for trigonometric identities Equating coefficients for the trigonometric identities does not make sense for me and I will explain why: If I use the example Write $5\cos x - 3 \sin x$ in the form $k\sin(x - \alpha)$, where $0 \le \alpha \le 360$. $=5\cos x - 3\sin x = k\sin(x - \alpha)$ $= k(\sin x\cos \alpha - \cos x\sin \alpha)$ $= k\cos\alpha\sin x - k \sin\alpha\cos x$ -- no idea why x and $\alpha$ switch here $= k \cos \alpha = -3$ I have no idea where $k\cos\alpha = -3$ comes from when in the previous expression, $k\cos\alpha$ is on the left of the minus sign so surely it should be $k\cos\alpha = 5$ Then we have $= k \sin \alpha = -5$ Same as above, $k \sin \alpha$ is on the right hand side of the minus so I have no idea why it is now assigned to -5. It is like I have to do the opposite to get the actual value. Really confused.
It is because $\sin x$ and $\cos x$ are linearly independent -- if you are given $$A\sin x + B\cos x \equiv 0$$ then both $A=B=0$. * * * Proof: If given $A\sin x + B\cos x \equiv 0$, then $$\begin{align*} A\sin x + B\cos x &\equiv 0\\\ A\sin0^\circ + B\cos 0^\circ &= 0 &\iff&&B = 0\\\ A\sin 90^\circ + B\cos 90^\circ &= 0 &\iff &&A=0 \end{align*}$$ * * * So you have made to the point that $$\begin{align*} 5\cos x -3\sin x &\equiv k\cos\alpha\sin x - k\sin\alpha\cos x\\\ 5\cos x+k\sin\alpha\cos x -3\sin x-k\cos\alpha\sin x &\equiv 0\\\ (5+ k\sin\alpha)\cos x + (-3-k\cos\alpha)\sin x &\equiv 0 \end{align*}$$ From the result above, $$\begin{align*} 5+k\sin\alpha &= 0&\iff&&-k\sin\alpha &= 5\\\ -3-k\cos\alpha &= 0 &\iff&&k\cos\alpha &= -3 \end{align*}$$ which is the result of directly matching the coefficients of $\cos x$ and $\sin x$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "trigonometry" }
Can Context Swtich before pause() cause to miss signal? Consider the following code: Process A (At random point in time): void catch(){}; // empty handler. signal(SIGCHLD,&catch); // attach empty handler. doSomthing(); unlock_semaphore(0); pause(); Process B (Currently blocked with semaphore 0) lock_semaphore(0) // Stuck here until process A unlock 0. doSomthing(); kill(Process A, SIGCHLD); And consider this sequence of events: (0)A:doSomthing (1)A:unlock <--------------- Content Switch from A to B. (2)B:lock (3)B:doSomthing (4)B:kill <--------------- The signal is handled here (Doing nothing). (5)A:pause() <--------------- Process A being suspended indefinitely. So, Can the following sequence of event happen and thus missing the signal?
Yes, that can happen. Instead of using `pause` use sigsuspend which atomically unblocks the signal, waits for the signal like pause, and then blocks it again. (This presumes you blocked the signal already because otherwise this scenario can happen at any point in your sequence.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "linux, signals, posix, semaphore" }
Accidentally checked out svn in my user folder and not it is full of php/html/svn files Is there a way to revert checkout of svn repo? I accidentally checked out huge codebase in my user folder, and it will be really pain to delete everything out manually, is there a way to remove it? I'm talking about removing working copy...
`svn ls` will show you the versioned files and folders in the current working directory. To automate removal of versioned files, you can run the following: svn update --set-depth empty This will _set_ the working copy depth to `empty`, meaning that all future update operations will not checkout anything. This also causes all already versioned files not in the given depth (i.e. all of them) to be deleted locally.
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "svn" }
Anchor tag Not working at all {{ apos.singleton(data.page, 'BLPHeroDisclaimerOptionONe', 'apostrophe-rich-text', { addLabel:"Hero Disclaimer", toolbar: ['Bold','Superscript','Italic', 'Subscript', 'Superscript', 'Link', 'Unlink', 'Anchor'], styles: [ { name: 'paragraph', element: 'p' } ] }) }} in the obove code we had Anchor tag and i had enter the id of a div to which i want page to scroll to but its not working at all , Any idea ?
Can you you confirm in your rendered HTML is all looking correct? You are getting both a `<a href="#someId">Jump Link</a>` and a `<div id="someId">Important Content</div>`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "apostrophe, apostrophe cms" }
Is it possible to reduce the number of spaces to only one between words? Is it possible to reduce the number of spaces to only one one between words? For example: "My name Ruby" => "My name Ruby" "this is a good boy" => "this is a good boy"
You can use `squeeze`: "now is the".squeeze(" ") #=> "now is the"
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "ruby" }
How to detect interface of incoming command? I have a dual interface Java card that contains my applet. I want to have two different APDU response for a single command from different interfaces. For example I want to respond to `00 10 00 00` APDU command with "Contact" when the command is received from the contact interface and respond "ContactLess" when this command is received from the contactless interface. So, is there any method in the _Java Card_ APIs or _Global Platform_ APIs to detect the incoming command's interface?
There is a method called `getProtocol()` in the `javacard.framework.APDU` class: > `public static byte getProtocol()` > > Returns the ISO 7816 transport protocol type, T=1 or T=0 in the low nibble and the transport media in the upper nibble in use. The interface is encoded in the upper nibble of the returned byte: final byte transportMedia = (byte) (APDU.getProtocol() & APDU.PROTOCOL_MEDIA_MASK); final boolean isContactless = (transportMedia == APDU.PROTOCOL_MEDIA_CONTACTLESS_TYPE_A) || (transportMedia == APDU.PROTOCOL_MEDIA_CONTACTLESS_TYPE_B);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "javacard, apdu, globalplatform" }
What is Dynamic Optimization in compilers People are talking about dynamic optimization in compilers.What does it mean? Can anyone give me a fair idea about it?
Static optimization is based on the program code itself. Alternatively, dynamic optimization is based on code execution results. For example, having a long switch statement in C/C++, it would be possible to optimize it by changing case operators order. To do this, it is necessary to run the program many times and keep this switch operator statistics. Some modern compilers contain such optimization framework, which allows to run the program and save its runtime statistics. Then the program code is optimized by using this statistics. See, for example, VC++ Profile-Guided Optimizations: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "compiler specific" }
EmberJS - How to update object in an array Interesting, i don't know how to update object in an array. see this jsFiddle i am getting this error. Uncaught TypeError: Object #<Object> has no method 'set' i tried in many ways. target.id = "Degree"; Ember.set('target.id', 'degree'); nothing helps. Code i tried. App.Config = [{id: "Gender"}, {id: "Martial Status"}]; var target = App.Config.findProperty("id", "Gender"); target.set("id", "Degree"); //see error in console.
Your App.Config is just an array of plain javascript objects, not Ember objects, so it doesn't know what `set` is. To fix, we need to create an array of Ember objects: App = Ember.Application.create({}); App.Config = [ Ember.Object.create({id: "Gender"}), Ember.Object.create({id: "Martial Status"}) ]; var target = App.Config.findProperty("id", "Gender"); console.log(target.get('id')); target.set("id", "Degree"); //see updated values in console. console.log(target.get('id')); Working example <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ember.js" }
How to use node-imap and Meteor together? I'm looking for a way to access an IMAP mail account like Gmail and using Meteor. I found node-imap but since it's an NPM module I've had a hard time getting NPM modules to work in Meteor. Is there a good way to access an IMAP account using Meteor?
That's a fun one. I had exactly that as an example, see my repository for it on GitHub In short: Follow this Coderwall tip to install the node-imap module. Then in your meteor code: if (Meteor.isServer) { var require = __meteor_bootstrap__.require; var imap = require('imap'); and put the actual code in the Meteor.startup(function() { ... }); call on the server side.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js, imap, meteor" }
can't find chip define in tensorflow, what templete chip<0>(index) mean? I can't find chip define code in tensorflow, but it is used everywhere. for example, `params.template chip<0>(index)`. What does the number in `<>` mean, it seems that the number can be 0,1,2,3
It is part of the Eigen library that Tensorflow uses. The code is here: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "tensorflow" }
delete files in history to save some space in mercurial ok, when I was young, I put severial big files(like resource file, dll, etc..) in my mercurial repos. and I found the size of it is so big that I cannot easily push it into bitbucket, any way to delete this files history **EASILY**? I put all those files in /res and /dll path. edit: this is a solution, but it will delete part of the history, so maybe there is a better solution. Mercurial Remove History
Your best bet is to use the convert extension, but **warning** you'll end up with a totally different repo. Every hash will be different and every person who cloned will need to delete their clone and re-clone. That said, here's what you do: Create a filemap file named `filemap.txt` containing: exclude res exclude dll and then run this command: hg convert --filemap filemap.txt your-source-repository your-destination-repository For example: hg convert --filemap filemap.txt /home/you/repos/bloatedrepo /home/you/repos/slenderrepo That gets you a whole new repo that has all of your history except the history of any files in /res and /dll, but again it will be a new, unrelated repo as far as mercurial (and bitbucket) are concerned.
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 13, "tags": "mercurial" }
How to make right alignment when using Tikz I use tikz to draw an image, below is part of the image. But the variable name is central alignment, how to make it right alignment? !enter image description here Below is the related code \foreach \i [count=\j from 1] in {5,4,3,2,1} { \pic () at (-0.5,\i) {myarrow}; \node[xshift=-2.5cm] at (-1,\i) {VARIABLE NAME}; }
Is this what you seek? Use of `text width=the longest length and align=left,center, right` of your selections. !enter image description here Code \documentclass[border=10pt]{standalone}%[12pt,twoside,a4paper]{book} \usepackage{graphicx,wrapfig,tikz} \usetikzlibrary{positioning,shapes} \tikzset{myarrow/.pic = { \begin{scope}[rotate=-90,scale=0.5] \draw[fill=black] (-0.5,0) -- (0,0.5)--(0.5,0)--(0.5,1)-- (0,1.5)--(-0.5,1)--(-0.5,0) ; \end{scope}}, } \begin{document} \begin{tikzpicture} \draw (0,0) rectangle (0,6); % draw myarrows on the left side \foreach \i/\k in {5/{FUEL\_LEVEL\_TOT},4/{PBRAKE\_APPLIED\_HIGH}, 3/{FUEL\_VOLUME},2/{FUEL\_LEVEL},1/{FUEL\_CONSUMPTION\_RATE}} { \pic () at (-0.5,\i) {myarrow}; \node[xshift=-6cm,text width=8cm,align=right] at (-1,\i) {RTDB\_{\k}\_E}; } \end{tikzpicture} \end{document}
stackexchange-tex
{ "answer_score": 2, "question_score": 2, "tags": "tikz pgf, graphics, horizontal alignment" }
awk - remove the content of a text file I have two text files with different numbers: File a: 115491 106835 121256 123166 75028 File b: 135991 95770 143987 125900 125899 every file does only contain a number once. File a contains ALL posible numbers, file b contains just a few. I would like to have a file c which contains only the numbers, that are not already included in file b. I would like to have as a result, that if I merge file b and c, I have file a (the order is not important).
for the example you gave, this grep line may help: grep -vFwf fileb filea > filec if you love doing it with awk: awk 'NR==FNR{a[$0]++;next}!a[$0]' fileb filea > filec
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "file, text, awk" }
WAF: recursive find_program() I am very new to WAF. I have configuration function like: def configure(ctx): ######################################################################## # **/myexe does not work too; also abs path in path_list does not work! ctx.find_program('myexe', var='MYEXE', path_list=['mydir/here']) and it does not find `myexe` binary. Only if I pass 'mydir/here/this_dir'! It seems that `find_program()` is not recursive. How to do it in recursive way? Maybe another method?
`find_program` is not recursive, meaning that it doesn't look for subdirectories of the ones you provide. It's for efficiency and security reasons. That the same when your OS look for binaries, it looks in a path list (usually through the PATH environment variable) but not recursively in subdirectories. A hacker can put a modified command in a subdirectory that will be used instead of the real one. That why the current directory is never in PATH :) As waf is python, and if you absolutely want to get that behavior, you can implement it :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, waf" }
Is it possible to return a reference property in an App Engine computed property? I have a model with an attribute that is a reference to another model. The model it references depends on some logic. Is there a way to have a computed property that gives me the same ReferenceProperty niceties (reverse references, dereferencing)? So far I the computed property stores a db.Key, but this is not optimal. Can I have a Computed Reference Property?
To do this you'd have to write your own custom Property subclass. You should be able to do so by examining the code behind `ComputedProperty` and `ReferenceProperty`; in effect you'd be combining the two.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, google app engine, model, reference" }