INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
dotted output after skeletonization in matlab I wish to skeletonize this image ![enter image description here]( To do so i am using matlab's `bwmorph` function, Here is the snippet : bw = bwmorph(img_bw,'skel',Inf); However the output is not as expected. Here is the output. ![enter image description here]( Could someone suggest a better way to achieve proper results ? **EDIT:** here is a stripped down relevant code img = imread(name); img = rgb2gray(img*4); img_bw = img > 50; img_bw = medfilt2(img_bw,[10 10]); bw = bwmorph(img_bw,'skel',Inf);
What you see is aliasing, the `imshow` function can not display the full image because it is to large to fit the screen. To fit the screen some rows and columns are skipped, which cause the lines to be disconnected. To display an image at full resolution using a scrollpanel, use `imscrollpanel` hFig = figure('Toolbar','none', 'Menubar','none'); hIm = imshow(bw); hSP = imscrollpanel(hFig,hIm);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "image, matlab, image processing, morphological analysis, mathematical morphology" }
Linking Bootstrap to my VS Code project I am going through VS Code for the first time and doing a bootstrap project. I used the marketplace to add bootstrap 4 and font awesome (install & reloaded) what else do I need to do? As my project folder does not have and bootstrap files, but strangely the intellisense let's me use the bootstrap snippets. I ran the index.html and the page wasn't bootstrap styled. The download didn't add any files to my project. Any suggestions?
You mixed up some things. The extensions that you installed are more for quick coding of Bootstrap and for visualizing it better. However Bootstrap is not installed on your site, which is a totally different process. You can achieve this in many ways. (npm, bower) I would recommend you to read the Bootstrap getting started documentation. (It's for Bootstrap 3 but it's the same principle) Documentation
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "visual studio code, bootstrap 4" }
Why is an ellipse not a self-intersecting curve? For a Hamiltonian which is time-independent, the phase trajectories don't intersect. But the Hamiltonian of a one-dimensional harmonic oscillator with constant energy, for example, has an elliptical phase trajectory. Since the phase space point comes back to the same point of the trajectory, how is an ellipse not a self-intersecting curve?
In case of Hamiltonian mechanics, fixing initial condition (x and p for 2 dimensional system) uniquely fixes the time evolution. The trajectories in phase space can not intersect, because if it does then for same initial condition one can have multiple trajectories. For a periodic trajectory (circle or ellipse) no such problem arises. That is why elliptic trajectories are allowed. Whether you can call it self intersecting or not, I think, is a question of nomenclature.
stackexchange-physics
{ "answer_score": 6, "question_score": 0, "tags": "classical mechanics, terminology, hamiltonian formalism, phase space, non linear systems" }
Lua mySQL update statements and where clauses So I'm trying to run an update with LuaSQL and mySQL, and seem to be stuck in one place. Whenever I try to update, the `WHERE` clause always fails on me, stating that the column doesn't exist. However, the column is correct, and the output gives a different column name. This is the update clause and what comes of it after running it status,errorString = assert(conn:execute[[UPDATE Users SET count=count+1 WHERE userID = user#id50589297]])) lua: test3.lua:16: LuaSQL: error executing query. MySQL: Unknown column 'user' in 'where clause' stack traceback: [C]: in function 'assert' test3.lua:16: in main chunk [C]: in ?
You're missing quotes around your string `user#id50589297`, it's trying to parse it as a column identifier. status, err = assert( conn:execute[[UPDATE Users SET count=count+1 WHERE userID='user#id50589297']]))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, database, lua" }
Passing String Arguments to kill() in C I am looking for a way to pass Arguments as String to the Function kill in C (man 2 kill), because the Signal depends on the OS. So the User puts in what the Programm should send(For Example SIGUSR1,..) and i want to submit it. Through kill(pid,USR_INPUT); My Error Invalid Argument Where I use it: kill(pid,name); Thanks a lot
It's simply not possible. `kill(2)` doesn't accept string (second) argument for the signal. It sounds a bit iffy that you had to handle signals inputted as strings. If you really need to do this, you can convert your string input to an integer form by comparing it with the list of signals you are interested in: if (strcmp(sig_str, "SIGINT") == 0) { sig_num = SIGINT; } else if (sig_str, "SIGTERM") == 0) { sig_num = SIGTERM; } else if ... ... kill(pid, sig_num);
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "c, process, signals, kill" }
Pre-calculus - Deriving position from acceleration Suppose an object is dropped from the tenth floor of a building whose roof is 50 feet above the point of release. Derive the formula for the position of the object _t_ seconds after its release is distance is measured from the _roof_. The positive direction of distance is downward and time is measured from the instant the object is dropped. What is the distance fallen by the object in _t_ seconds? The problem gives you acceleration as being **$a=32$**. I integrate to velocity, getting **$v=32t + C$**. At the time of release, $v=0$, so the equation is **$v=32t$**. Integrate again for position and I get **$$s=16t^2 + C$$** Here is where I get stuck. Do I add 50 to the position function because the height is measured from the roof? What is the next step?
Yes, add $50$ft to the function, because when $t=0$, the object is $50$ft away from the roof.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "calculus, integration, physics" }
How can I get the last row value with MySQL? I have a table called `Live`, and in the table I have `public_id`. In `public_id` are numbers (e.g. 1,2,3,4,5). How can I get the highest number or the last entry's number?
I'd choose SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1; It has already been posted, but i'll add something more: If you perform this query usually you can create an index with inverted ordering. Something like: CREATE INDEX ON Live (public_id DESC) Please Note > DESC PHP + MySQL code: <?php $result = mysql_query('SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;'); if (mysql_num_rows($result) > 0) { $max_public_id = mysql_fetch_row($result); echo $max_public_id[0]; //Here it is } ?>
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 2, "tags": "php, mysql, insert" }
Detach Writer from System.out without closing Some tool I have uses `Writer` as output. I want to write to `System.out`, so I created an `OutputStreamWriter` for `System.out`. My problem is that I want to do other things with the standard output of my program after I completed this task. I did not find any means to detach the writer. Is there any common `Writer` implementation that can do that? Should I write my own `Writer`? Should I call `flush()` on my `OutputStreamWriter` and then leak it?
You can override close and flush instead: PrintWriter w = new PrintWriter(System.out) { @Override public void close() { flush(); } };
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, io" }
Compute $\int_{0}^{+\infty} e^{-y}y^a\mathrm{d} y$ Does the following integral have a finite value? How to compute it? $$\int_{0}^{+\infty} e^{-x^k}\mathrm{d} x$$ where $k$ is given and $0<k<1$. By substituting $x^k=y$ we may obtain an equivalent integral $$\int_{0}^{+\infty} e^{-y}y^a\mathrm{d} y$$ where $a>0$ is given.
I am formalizing the comments: $$\Gamma(a)=\int_0^\infty e^{-y}y^{a-1}\text{ d}y$$ $$\Gamma(a+1)=\int_0^\infty e^{-y}y^a\text{ d}y$$ Convergence: So we know that $\Gamma(x)$ converges (for at least $x\geqslant0$) because it converges significantly faster than $x^{-2}$ for arbitrarily large $x$ values.
stackexchange-math
{ "answer_score": 0, "question_score": 7, "tags": "real analysis, integration" }
Javascript in browser address string - problem with form submit I try to write inline javascript for visa state checking This is my code javascript:document.getElementById("txtRefNO").value="xxxxxxxxxxxxxxxxxxxxx";document.getElementById("txtDat").value="dd";document.getElementById("txtMont").value="mm";document.getElementById("txtYea").value="yyyy";setTimeout('document.getElementById("form1").submit()',5000);void(0); This script fill filds and jast reload page. But when i click on submit button it's ok. What the difference between clicking and submit() calling?
To answer the _What the difference between clicking and submit() calling?_ , in this case when you click the button, the form submits with an extra parameter `cmdSubmit` with the value `Submit` \- this is the submit button and the text you see on it. The server side component for this page may very well be looking for this parameter in order to validate the submitted form (perhaps not the best approach). Try this instead - note that I've changed it from a call to `submit()` on the form to a `click()` on the submit button javascript:document.getElementById("txtRefNO").value="xxxxxxxxxxxxxxxxxxxxx";document.getElementById("txtDat").value="dd";document.getElementById("txtMont").value="mm";document.getElementById("txtYea").value="yyyy";setTimeout('document.getElementById("cmdSubmit").click()',5000);void(0);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, submit" }
How do I automatically fire a (remote) stored procedure in SQL Server when connecting to a remote server? The specific issue is that I want a SQL Server to connect to an Oracle database and the Oracle database has a Virtual Private Database configured. I need to execute a static stored procedure to enable the VPD to see data. How can I configure SQL Server to fire a stored procedure upon connecting to a remote database? I figure if I can fire a local stored procedure, I can put the remote stored procedure call inside of that. The key is, I need the SQL Server to fire this as soon as it is done connecting to the remote database and before it tries to pass any other queries to it. I'm trying to avoid making the applications do it explicitly.
SQL Server does not offer a solution to my problem. However, you can setup the service account to have a logon trigger to execute what is needed. Create Trigger My_User.Logon_Trigger_Name AFTER LOGON ON SCHEMA WHEN (USER = 'MY_USER') BEGIN --Do Stuff Here. NULL; EXCEPTION WHEN OTHERS THEN NULL; --Consume errors so you can still log on. END;
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sql server, oracle" }
Changing style properties inside 'click' events in multiple elements, using if statements I have a simple todo list (`<ul>`). When user clicks `<li>`, the textDecoration property changes to "line-through". I want to be able to "undo" this somehow. Here's my code... const lis = document.querySelectorAll('li'); lis.forEach(li => li.addEventListener('click', taskHandler)); function taskHandler(e) { const li = e.target; if ((li.style.textDecoration = 'none')) { li.style.textDecoration = 'line-through'; console.log(`${li.textContent} is done`); } else { li.style.textDecoration = 'none'; console.log(`${li.textContent} is undone`); } } My question is : **why`else` block doesn't work ? And how do I fix this code ?** Thanks!
You are using a single `=` assignment operator to compare: if ((li.style.textDecoration = 'none')) Replace it with either `==` or `===`: if ((li.style.textDecoration == 'none')) Also, not sure why the double `(())` parenthesis? if (li.style.textDecoration === 'none') Should work fine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, dom, addeventlistener" }
At what moment is memory typically allocated for local variables in C++? I'm debugging a rather weird stack overflow supposedly caused by allocating too large variables on stack and I'd like to clarify the following. Suppose I have the following function: void function() { char buffer[1 * 1024]; if( condition ) { char buffer[1 * 1024]; doSomething( buffer, sizeof( buffer ) ); } else { char buffer[512 * 1024]; doSomething( buffer, sizeof( buffer ) ); } } I understand, that it's compiler-dependent and also depends on what optimizer decides, but what is the **_typical strategy_** for allocating memory for those local variables? Will the worst case (1 + 512 kilobytes) be allocated immediately once function is entered or will 1 kilobyte be allocated first, then depending on condition either 1 or 512 kilobytes be additionally allocated?
Your local (stack) variables are allocated in the same space as stack frames. When the function is called, the stack pointer is changed to "make room" for the stack frame. It's typically done in a single call. If you consume the stack with local variables, you'll encounter a stack overflow. ~512 kbytes is really too large for the stack in any case; you should allocate this on the heap using `std::vector`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 26, "tags": "c++, visual c++, memory management, stack overflow, local variables" }
How to mark JIRA status "Closed" when Current status of JIRA issue is "Resolved" via REST API Current jira status is "Resolved" and trying to close it with "transition":{"id":"2"}, "update":{"comment":""} getting error Can't move (DC-XXXXXX). You might not have permission, or the issue is missing required information. If you keep having this problem, contact your JIRA Administrator." Note: current status of jira is "Resolved" { "transition":{"id":"2"}, "update":{"comment":[{"add":{"body":"Auto close the issue"}}]} }
Resolved by changing the id to 701 Note: Ensure transition from Resolved to Closed required 701 id value. < { "transition":{"id":"701"}, "update":{"comment":[{"add":{"body":"Auto Comment added to close issue"}}]} }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jira, jira rest api" }
How to use second piping with echo and bc commands? I want to use echo|bc commands to calculate big amount of calculation. for example: echo "scale=8; sqrt($NUM)" | bc -l that calculates the square root of NUM to 8 decimal digits accuracy. now suppose I have a file `numbers.txt` that contain lots of numbers, and I want to calculate the square roots of all of them. I tried using grep -ow "^[0-9]*$" numbers.txt | xargs -I '{}' echo "scale=8; sqrt({})" | bc -l grep -ow "^[0-9]*$" numbers.txt | xargs -I '{}' (echo "scale=8; sqrt({})" | bc -l) grep -ow "^[0-9]*$" numbers.txt | xargs -I '{}' $(echo "scale=8; sqrt({})" | bc -l) read num numbers.txt | echo "scale=8; sqrt($num)" | bc -l and few more variations of these, but couldn't find a way to make it works. Any ideas?
Your first line works fine: grep -ow "^[0-9]*$" numbers.txt | xargs -I {} echo "scale=8; sqrt({})" | bc -l
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "bash, macos, shell, pipe" }
symfony 2.7.5 : homepage link does not work when using other controller I'm creating a website with symfony 2.7.5. I have a menu bar that is the same for all pages, so I included it into base.html.twig, than the other views can inherit from it. In this menu bar, I have a link to the home page. And here is the problem : when I open this link from a view contained at the root directory, no problem. But When I open this link from a subfolder view, the link is automatically overwritten with FOLDER NAME/HOMEPAGE link. So how can I have an homepage link working from every place of my website ? Thanks in advance
This is because you are using relative paths. A path function is available in Twig to generate the correct urls. Here is the relative information in the SF2 docs: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "symfony, routes" }
How can I strip the data:image part from a base64 How can I strip data:image part from base64 string? Sometime I have data:text/plain, data:image/jpeg , data:image/png How can I do it one regular expression . Currently I am using the following code. preg_replace('#data:image/[^;]+;base64,#', '', $file) but this is just for image type
Data URI scheme is made of the following format. data:[<media type>][;charset=<character set>][;base64],<data> Based on the above structure, here is a REGEX for the same. Strip out the REGEX match and you've got your data. data:(\w+/[+-.\w]+)?(;charset=([^"'])+)?(;base64)?, !Regular expression visualization Debuggex Demo
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, base64, preg match, php 5.3" }
Pointless Question Edit? So one of my questions has received an edit. < I thought the revision was fairly trivial and wondered why the user even bothered to make the edit. Rather than roll the edit back or re-edit it, thought I'd post here to see if there was anything I've missed. I've looked at the following post: When should I make edits to code? I cannot see why removing 28 characters is really needed? I also like to think I'm polite so the removal of 'Thanks :)' is particularly annoying. Is it considered bad form to put pleasantries like this on questions?
As others have said, greetings and salutations on posts are considered noise and typically are removed - so I understand why that was removed. However, the post is 5 years old and the removal, IMO, was not critical **and** they removed your data from the question - which doesn't seem at all appropriate since it changes your question. I've rollback the edit because it changed your data and subsequently removed the "Thanks" which should have been the only thing removed from the post.
stackexchange-meta_stackoverflow
{ "answer_score": 21, "question_score": 1, "tags": "discussion, edits" }
Does $f(x)=ax$ intersect $g(x)=\sqrt{x}$ It maybe a stupid question but I want to be sure how to explain it formally. Does $f(x)=ax$ intersect $g(x)=\sqrt{x}$, when $x>0$ and $a>0$ (however small it is) I think it does. The derivative of $f(x)$ is constant, positive. And the derivative of $g(x)$ tends to $0$. So there will be some point $x_0$, from which the derivative of $f$ will be greater than derivative of $g$. Therefore $g$ will grow slower than $f$ and both functions finally meet. Am I right? This is enough? Can one formally prove it?
If there is a point of intersection, it will satisfy the equation $$ax = \sqrt x\implies (ax)^2 = x \iff a^2x^2 - x = 0 \iff x(a^2x - 1) = 0\;$$ Indeed, the graphs intersect, when $x = 0$ and when $a^2x-1=0 \iff x = \frac 1{a^2}$. Since we are interested in only $x\gt 0$, the point of intersection you are looking for is $$(x, f(x)) = (x, g(x))=\left(\frac 1{a^2}, g\left(\frac 1{a^2}\right)\right) = \left(\frac 1{a^2}, \frac 1a\right)$$ Note: we know that $a > 0$ and $x>0$. Hence $$g\left(\frac 1{a^2}\right) = \sqrt{\frac 1{a^2}} = \frac 1a$$
stackexchange-math
{ "answer_score": 5, "question_score": 3, "tags": "calculus, functions" }
What's wrong with this piece of code? Scala - tuple as function type What's wrong with the following piece of code ? I'm trying to use a tuple (String, Int) as the type of input to the function `find_host`. The complier doesn't give me any errors but when I run the program I get one. What am I missing here? def find_host ( f : (String, Int) ) = { case ("localhost", 80 ) => println( "Got localhost") case _ => println ("something else") } val hostport = ("localhost", 80) find_host(hostport) missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: ? def find_host ( f : (String, Int) ) = { ^
To do a pattern match (your case statements here), you need to tell the compiler what to match on: def find_host ( f : (String, Int) ) = f match { ... ^^^^^^^
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "scala, runtime error" }
Matrix substraction in Python error or confusion I have this code to help understand the problem hypotesisResult = (hypotesis(dataset, theta_init)) print(dataset.T.shape) print(hypotesisResult.shape) print(y.shape) print((hypotesisResult - y).shape) print(np.subtract(hypotesisResult, y).shape) And the output of this: > (7, 1329) > (1329, 1) > (1329,1) > (1329, 1329) > (1329, 1329) And my question is, why if a have the matrix "hypotesisResult" with a size of (1329, 1), and i substract "y" (1329,1) from it, it results in a matrix of (1329, 1329) ¿What are i'm doing wrong? I want a new matrix of (1329, 1), this like an scalar substraction
I don't trust your displayed shapes. It might be good to rerun this script, and also check dtype. Here's the behavior I expect, involving (n,1) and (n,) or (1,n) arrays: In [605]: x=np.ones((4,1),int); y=np.ones((4,),int) In [606]: x,y Out[606]: (array([[1], [1], [1], [1]]), array([1, 1, 1, 1])) In [607]: x-y Out[607]: array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) In [608]: x-y[None,:] Out[608]: array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) In [609]: x-y[:,None] Out[609]: array([[0], [0], [0], [0]]) In [610]: x.T-y Out[610]: array([[0, 0, 0, 0]]) The two basic broadcasting rules are: * add leading size 1 dimensions if needed to match the number of dimensions * adjust size 1 dimensions to match the other arrays.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, python 3.x, numpy, machine learning" }
How do I detect a reinstall of the app and delete the files I've created on the device's memory beforehand In my app I create some files and I store them on internal storage/sd card. I want to detect reinstall and detele them when a reinstall occurs or better yet, make them in a way that will make them automatically deleted when app is uninstalled. is this possible? EDIT: directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() * this is where I store my files and they do not get deleted
For most Android devices, files put on `getFilesDir()`, `getCacheDir()`, `getDatabaseDir()`, `getExternalFilesDir()`, and `getExternalCacheDir()` will be automatically removed when the app is uninstalled. Support for automatic deletion for the two external ones did not kick until until API Level 9 or so, IIRC.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android" }
Linear search arrays How do I print multiple searches from a linear search in C? for (i=0; i < index; i++) if (array[i] == target) return i; Is it possible to return more then one value, say, if the array has multiple elements that equals the target?
Instead of returning matching elements, you could print out their index values (allowing multiple values to be printed) or insert them into an array and then return that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, linear search" }
Trouble with commas in subscript of chemical formula (using mhchem) I'm writing a thesis on clay materials which have rather unusual chemical formulas with commas in the subscript. For intance I try to write the following chemical formula in LaTeX: \begin{document} \usepackage[version=3]{mhchem} The chemical formula of beidelite is: \ce{Na0,5Al2(Si3,5Al0,5)O10(OH)2.n(H2O)} \end{document} It ignores the commas and gives the following output: !chemical formula of beidelite To be clear, I want the subscript after Na to say 0,5, the subscript after Si say 3,5 and the subscript after Al say 0,5. How do i fix this?
Place the non-integers inside curly bracket groups: \documentclass[border=5pt]{standalone} \usepackage[version=3]{mhchem} \begin{document} The chemical formula of beidelite is: \ce{Na_{0,5}Al2(Si_{3,5}Al_{0,5})O10(OH)2.$n$(H2O)} \end{document} ![Output with <code>version=3</code>](
stackexchange-tex
{ "answer_score": 3, "question_score": 6, "tags": "subscripts, mhchem" }
stop bash script if react build fails I have a couple of deployments that has broken production, since the bash script continues if the build fails. How can I make sure that the script exits should the `npm run build` fail? #!/usr/bin/env bash source .env ENVIRONMENT="$REACT_APP_STAGE" if [ "$ENVIRONMENT" != "production" ]; then echo "improper .env NODE_ENV" exit fi git pull origin master npm i npm run build rm -r /var/www/domain_name.dk/html/* mv /var/www/domain_name.dk/website/build/* /var/www/domain_name.dk/html/
It is surprisingly easy: #!/usr/bin/env bash source .env ENVIRONMENT="$REACT_APP_STAGE" if [ "$ENVIRONMENT" != "production" ]; then echo "improper .env NODE_ENV" >&2 # Errors belong on stderr exit 1 fi git pull origin master npm i npm run build || exit # Exit if npm run build fails ... By using the short-circuiting `||` operator, if `npn run build` fails, then the command on the right side excutes. `exit` returns the exit status of the last executed command, so the script will exit with the same failure code that `npn run build` exited with. If `npm run build` succeeds, then the `exit` is not executed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "reactjs, bash, npm, build" }
Batch script compiler Is there any batch script compiler available? I have a very big batch file and I want to check where my syntax is going wrong. Also using @pause and echo I can check what's going wrong but a compiler would be a better option.
I suppose the best you could find is a syntax checker, not a real compiler, as in batch many constructs could only _compile_ at runtime. Nearly each `%var%` expansion needs to _compile_ in the moment of expansion, as the content could change everything. Also the possibility of self modifying code makes this problem a bit tricky. Perhaps someone, sometimes will write a batch debugger, that should be possible.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "batch file" }
C# Convert List<string> to Dictionary<string, string> LINQ I have a JSON string[] like this : "['518','Incorrect date (it can not be earlier today or later today+1year)']" Which I deserialize using Json.Net library to a List, now I need to convert that list string to a Dictionary which key is the first value and the value is the second item in the list, following on. I have done this using a for loop like this : string Json = "['518','Incorrect CheckIn date (it can not be earlier today or later today+1year)']"; var json = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(Json); var errorList = new ErrorList(); for(int i=1;i<= json.Length;i++) { errorList.ErrorMessages.Add(new ErrorMessage(){ErrorCode = json[i -1], Message = json[i]}); i = i + 1; } I was wondering is there is a way to replace the fro loop with linq. Thanks.
You can try this way : string Json = "['1','value1','2','value2','3','value3']"; var json = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(Json); var result = json.Select((v, i) => new {value = v, index = i}) .Where(o => o.index%2 == 0) .ToDictionary(o => o.value, o => json[o.index + 1]); foreach (var pair in result) { Console.WriteLine("key: {0}, value: {1}", pair.Key, pair.Value); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, json, linq, serialization" }
Loops in SQL to create table I am trying to create a table that looks like the following, I was wondering if there was a quick way to create it rather than use a ton of unions. | Week_No | Day_Of_Week | | 1 | 1 | | 1 | 2 | | 1 | 3 | | 1 | 4 | | 1 | 5 | | 2 | 1 | | 2 | 2 | | 2 | 3 | | 2 | 4 | | 2 | 5 | I need to create it so the week_no goes up to 53, each week has to have 1-5. I am using Sql Server. Regards, Neil
Recursive Common table expressions: WITH CTE_Weeks AS ( SELECT 1 AS Week_No UNION ALL SELECT Week_No + 1 FROM CTE_Weeks WHERE Week_No < 53 ) , CTE_Days AS ( SELECT 1 AS Day_Of_Week UNION ALL SELECT Day_Of_Week + 1 FROM CTE_Days WHERE Day_Of_Week < 5 ) SELECT Week_No, Day_Of_Week FROM CTE_Weeks CROSS JOIN CTE_Days ORDER BY Week_No, Day_Of_Week
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server" }
Why does this class file get created? In Java all classes are loaded into the JVM dynamically, upon the first use of a class. Does it mean if i have class in a my source file and I do not make any reference to it then its `Class` object is not created (i.e. `.class` file is not created)? In the sample code below iam not making a refernce to `test3` class but still its class object gets created. class test1 { static { System.out.println("static block of test1"); } } class test2{ static { System.out.println("static block of test2"); } } class test3 {} class MyExample1 { public static void main(String ...strings ) { new test1(); new test2(); } } Why `test3.class` file gets created?
_.class_ file was created at _compilation_ time. But, it will be loaded from _.class_ file by first usage (probably). From where it should be loaded without _.class_ file?)
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "java, class, javac" }
How to get a string into a where clause in Ruby on Rails 3? I have this class method: def self.default_column "created_at" end How can I rewrite the following function, so that I can make use of my `default_column` method? def next User.where("created_at > ?", created_at).order('created_at ASC').first end I tried things like these... def next User.where("#{default_column} > ?", default_column).order('#{default_column} ASC').first end ... but I must be awfully wrong here because it doesn't work at all. Thanks for any help.
def next default_column = self.class.default_column User .where("#{default_column} > ?", send(default_column)) .order("#{default_column} ASC") .first end
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails, ruby, ruby on rails 3, ruby on rails 3.2" }
pandas use cumsum on a column and create a new boolean column that mark edge case as True I have the following `df`, year_month pct 201903 50 201903 40 201903 5 201903 5 201904 90 201904 5 201904 5 I want to create a boolean column called `non-tail`, which satisfies the following condition, df.sort_values(['pct'], ascending=False).groupby('year_month')['pct'].apply(lambda x: x.cumsum().le(80)) that in `non-tail`, any next value in `pct` that will be added which makes cumsum immediately great than 80 will be mark as `True` as well, so the result will look like year_month pct non-tail 201903 50 True 201903 40 True 201903 5 False 201903 5 False 201904 90 True 201904 5 False 201904 5 False
What I will do df.pct.iloc[::-1].groupby(df['year_month']).cumsum()>20 Out[306]: 6 False 5 False 4 True 3 False 2 False 1 True 0 True Name: pct, dtype: bool
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python 3.x, pandas, dataframe, pandas groupby, cumsum" }
Extract table from image I have the image of a matrix (download it to see it bigger): !a matrix Is there a way to convert this into a Mathematica numerical matrix, using Mathematica?
`TextRecognize` works fine after some tweaks and error corrections: x = Import[" res = TextRecognize[Binarize[ImageResize[x, Scaled[5]], 0.7],"SegmentationMode" -> 6]; m = ToExpression /@ StringSplit[#] & /@ StringSplit[ StringReplace[ res, {"O" | "D" | "U" -> "0", "~" | "\"" -> "-", "I" -> "1"}], "\n"]; m // MatrixForm !enter image description here I have used the undocumented option `"SegmentationMode" -> 6`.
stackexchange-mathematica
{ "answer_score": 10, "question_score": 12, "tags": "image processing, ocr" }
I am not getting the mean of a set when I calculate the mean of its subsets means I am stucked with some python code because I am not getting the mean of my set when I calculate the mean of the means of its subsets. #First I define my mean fucntion: def mean_f(numbers): return float(sum(numbers)) / max(len(numbers), 1) #Then I calculate the mean of my whole dataset directly myset=[28, 36,76,23,34,856,77,90,22,34,12,80,34, 106, 39] mean_f(myset) 103.13333333333334 #Finally, I calculate the mean of my dataset using the means of its subsets: subset1=[28,36,76] subset2=[23,34,856,77,90] subset3=[22,34] subset4=[12,80,34,106,39] mean_f([mean_f(subset1), mean_f(subset2), mean_f(subset3), mean_f(subset4)]) 86.21666666666667 Do you know why am I not getting the same result?
You can't simply average means of subsets _if these subsets have different numbers of elements_. As a simple example, suppose one subset consists of the smallest element alone, and the other subset contains all other elements. If you then average these subsets' means, the smallest element will get the same weight as all other elements _together_. The solution is to take a _weighted_ average of the subset means, where each subset's mean gets a weight that is proportional to the number of elements in the subset.
stackexchange-stats
{ "answer_score": 3, "question_score": 0, "tags": "descriptive statistics" }
cobalt: When StorageManager calling destructor , there is task in last_change_timer_ or change_max_delay_timer_ ,it maybe be discarded I found that StorageManager would call FinishIO and OnDestroy when it call destructor. It will wait sql_message_loop and savegame_thread_ completed in FinishIO, and reset resources include flush_on_last_change_timer_ and flush_on_change_max_delay_timer_. So if there is a task in flush_on_last_change_timer_ or flush_on_change_max_delay_timer_ when iStorageManager calling destructor, it maybe discard this task and lead to last savegame operate miss. Is it a problem or I don`t understand right.
Thanks for pointing this out. I believe that you are correct; it does appear that the last save can fail to occur if the StorageManager is destructed before the timer goes off. This will be fixed in later versions of Cobalt.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "cobalt" }
Open new Tab when button is clicked using wicket I want to open a new tab when a button or link is clicked, how can I achieve it? what I have managed to do is to open it in a pop up like this: PopupSettings popupSettings = new PopupSettings("popuppagemap").setLeft(0).setHeight(500).setWidth(500).setHeight(0); // Popup example final Link<Void> setPopupSettings = new BookmarkablePageLink<Void>("searchBtn", HomePage.class) .setPopupSettings(popupSettings); but this opens it in a new window.
no problem to open a link in a new tab: just add 'target="_blank"' to the link. final Link<Void> link = new BookmarkablePageLink<Void>("link", HomePage.class){ @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); tag.put("target", "_blank"); } }; add(link);
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "wicket, wicket 1.6" }
Adding word to names of multiple images in Linux I have multiple images in a folder and would like to add a word to all of their names. Say I have 3 images in the folder A.jpeg B.jpeg C.jpeg So I would like the final result to be Afoo.jpeg Bfoo.jpeg Cfoo.jpeg The word to be added must be the same and the script must not change the format of the images. Please ask for any details you might need. Thanks. (image names as code because stackoverflow editor though the names were code) **EDIT** All the names are of this format . IF the image NAME has multiple words the they are NOT separated by spaces but are separated by "-" eg- 41. blah-blah.jpeg
Try: for img in *.jpeg; do mv -- "$img" "${img%.*}foo.jpeg" done
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "bash, shell, ubuntu 16.04" }
Passing the id in the controller Rails I have a problem with passing the id in the controller. I have a function of accepting and rejecting a request. @friend = Friend.find(params[:id]) @friend.update(value_params) When it updates it automatically updates the id of which user id created the value I want to be able to the same but this time when it clicks accept or reject I want to get the id of the one who created the value and pass it as a parameter of `:for_id =>` inserting in the request and the updating the friend table so the one who created the request will be the only one to see the request accepted or declined given his or her id I tried using this but it wont insert into the database @friend = Friend.find(params[:id]) @req = Request.new(:for_id => @friend) No error it just doesn't include for_id in the insert clause or statement
> it just doesnt include **for_id** in the insert clause or statement please include this statement from your `server log` also explain us what you are trying to accomplish, because you are not saving `@req` so I don't really see the reason why the server should do some `insert` statement. If you want to have an insert statement 1. in case `friend has_many requests` then you should do: @friend.requests << @req @friend.update(value_params) 2. else to save your `@req` in your db do: @req.save This probably is wrong, but also a chance for you to explain us clearly what you are trying to accomplish
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails" }
how to display the latest records in the db. in Laravel my code to display the latest records in datable in laravel .now it's showing the first in the first. need to display the last data in first if($status == 'pending'){ $datas = Order::where('status','=','pending')->get(); }
if you want to get the last record use `latest()->first()` if($status == 'pending'){ $datas = Order::where('status','=','pending')->latest()->first(); } and if you want to order if($status == 'pending'){ $datas = Order::where('status','=','pending')->orderBy('id', 'DESC')->get(); }
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -2, "tags": "mysql, laravel" }
Custom Membership Provider or Profile Provider in mvc asp.net I'm venturing into the world of asp.net mvc. I have not yet understood whether it makes sense to use a custom Membership Provider or use the Profile provider for the user management?
One, Membership providers and Profile providers serve two different purposes. The Membership provider provides a user list and authentication functionality. The Profile provider provides a way to store application-specific data associated with each user. Whether you need a custom provider depends on what type of datastore you want to use. The two built-in Membership providers allow for using an Active Directory domain (generally only appropriate if you're developing an application for a corporate intranet) or an MS SQL Server Database. The one built-in Profile provider uses MS SQL. If you want to use a different type of datastore, for example a PostgreSQL database, then you'll need a custom provider for that particular datastore.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "asp.net mvc, asp.net membership, profile provider" }
How do i create ranges dynamically in R? > **Possible Duplicate:** > Create categorical variable in R based on range Given a range and number of intervals that are desired how do i create equal intervals in `R`. eg. If the range is between 1 and 100 and i want to create 10 intervals, I should get 1 - 10, 11 - 20, ..., 91 - 100. Only this function should work for any range and any number of intervals. If i have a range of 0 to 1 and number of intervals 30, then it should create the ranges such as 0 - 0.03, ..., 0.97 - 1, and so on. The aim is to use these ranges to obtain values from a data.frame.
If you have minVal<-0 maxVal<-1 numItv<-30 you can use seq(minVal, maxVal, length.out=numItv+1) to get the cutpoints for your intervals.
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 4, "tags": "r, range" }
which type of data structure is best? In my application, we already have Map<String, List<String>> Now we got another use-case where need to find a key which is mapped to a particular string inside the list. I am thinking of writing following: string getKey(Map<String, List<String>> m, String str) { for (Entry<String, List<String>> entry :m.entrySet()) { if(entry.getValue().contains(str)) { retrun entry.getKey(); } } return null; } `Map` can have at max 2000 entries. and each `List` can have at max 500 `String`s. Any suggestions that might be a better fit? I can change the initial data structure (`Map`) also if there is a better way to do it..
I would suggest that you add another map that gives the reverse mapping - from a string to list of keys. This will require a bit more of work to keep in sync with the first map but will give the best performance for your task. Still if you think the frequency of such queries will be relatively low, maybe your solution could be better(although slower, the time you save for keeping both maps in sync will make up for that).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "java, data structures, collections" }
How to get the total spent hour per day I have a column here and I need to get the hour count per day (every succeeding hour +1) ![enter image description here]( Expected Output: Date | HourSpent 2017-12-08 | 6 My Code attempt: SELECT Cast(TransDateTime as Date), DateDIFF(hour,MIN(TransDateTime),MAX(TransDateTime)) as DateTime FROM GuestTransLedger where GuestExtID = '2016-120-5624873' GROUP BY Cast(TransDateTime as Date) ORDER BY 1 DESC
Try this: select convert(date, datetime_column) as Date, count(distinct datepart(hour,datetime_column)) as HourSpent from tbl group by convert(date, datetime_column)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "sql, sql server" }
Is it possible to tell if brake fluid needs to be flushed just by looking at it? I've got spongy brake feel. This situation has me wondering if it is at all possible to tell that brake fluid needs changing just by looking at the fluid in the reservoir, similar to how you can tell if you need an engine oil change if the oil is black. Does moisture ingression affect the appearance of brake fluid?
Yes. When brand new, brake fluid looks clear. Once there is a significant amount of water absorbed, it will turn an amber color. This applies to regular brake fluid (DOT 3, 4, & 5.1) and not synthetic. Here is an image of new and old brake fluid: ![enter image description here]( As you can tell, it gets darker as it gets older.
stackexchange-mechanics
{ "answer_score": 5, "question_score": 4, "tags": "brake fluid" }
Schedule of cricket matches sql query I have a table with list of countries as shown below. Every country will play against all countries in the list. I need a query to display the list of opponent countries in format (country1, country2) for all the possible matches without repetitions. e.g. c1 & c2 will play against each other. Display list should not have c2 & c1 (repetition) CtryName --- c1 c2 c3 c4 c5 It's an interview question. I have no idea how to get expected results. Please help me by a simple query to display expected results.
Try like this: select t1.c teamA, t2.c teamB from test t1, test t2 where t1.c < t2.c order by t1.c, t2.c I named the table as `test` and the country column as `c`. See it here on fiddle: <
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "sql, sql server" }
Definite integral of the cube root of $x \ln (x)$ I was trying to solve the 2016 CSE) question paper for Math Optional $$I = \int_{0}^1 \left (x\log \left (\frac{1}{x}\right)\right)^{\frac{1}{3}} dx$$ In my attempt to find $I$, I tried to substitute $$t = \log \left (\frac{1}{x}\right) \\\\\ dt = \frac{x}{-x^2}$$ Even tried taking $$t = x\log \left (\frac{1}{x}\right)$$ and then tried by parts. But I am unable to make headway. Any idea what might work? How can I tackle these types of problems?
**Hint** : Set $u = \ln \frac{1}{x}$. Assuming my scratchwork is correct, I think you should end up with something like $$\int_0^{\infty} \sqrt[3]{u} e^{-\frac{4}{3} u} du.$$ Then make the substitution $\widetilde{u} : = \frac{4}{3} u$ and the result comes out nicely. Spoiler: Answer is $$\left( \frac{3}{4} \right)^{\frac{4}{3}} \frac{\Gamma(1/3)}{3},$$ where $\Gamma$ denotes the gamma-function.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "calculus, integration, definite integrals" }
Getting CreationTime from PNG I'm coding a winForm application that renames images with the datetime taken. e.g. Original image name => Image_YYYYMMDD_HHMMSS I was using GetPropertyItem(36867) which is the Exif Date/Time Origin. But this only works on JPG, not PNG. As far as I know PNG does not have exif until recent versions and the closest thing in PNG is CreationTime. Also, I've come across a discussion thread about calling exiftool in console. Is it possible to get the date/time without exiftool? Or how can I implement exiftool into my c# GUI program without adding too much complexity?
`File.GetCreationTime(file path)` from the `System.IO` namespace is the best you can (reliably) do. Unfortunately PNG metadata doesn't usually contian a creation date so getting the write date is the best you can do. For more information on how to use this, read: <
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "c#, datetime, png, exif, exiftool" }
Cross domain ajax to diversify requests to API service I want to access data from an API service using a client-side web app. The service is the openFDA's new API: < There is a 1000 request per day limit, 60000 with key. To diversify IP usage, would it be feasible to have the users send the requests to the FDA's service themselves, by making a cross domain ajax request? Are there other considerations that would make this a bad practice? Thanks.
For building something entirely client-side, I would recommend not using a key and instead relying on the IP-based limits. openFDA supports CORS, so the requests will be coming from the visitor's IP address and your app won't be subject to app-specific restrictions. Hope this helps! Sean Herron, openFDA Core Team Member
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ajax, api, cross domain" }
Cannot insert datasheet into form (Access Project) Following the instruction found here: Insert a datasheet into a form I get an error when trying to insert a query as a datasheet in an Access Project (SQL Server 2005 backend) > The form name you entered doesn't follow Microsoft Office Access object-naming rules I selected the view `View.dbo.viewname` from the dropdown in 'Source Object' and the above error occurred as soon as I did that. If I take off `View.dbo.viewname`, it saves, but then I can't see the datasheet data. I want to add the view as it contains subdatasheets. Wrapping it in brackets, e.g. `[View.dbo.viewname]` or `View[.]dbo[.]viewname` (as dots are apparently not allowed, although the link suggests otherwise) doesn't help
Never managed to get it to work. Perhaps due to being an Access Project (ADP) rather than database (MDB). Had to resort to creating forms (with nested subforms) instead of datasheets to get what I wanted. Also, nested forms (two levels down) don't seem to work in Access 2007, but do in 2003, so had to go back to that.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql server, sql server 2005, ms access, ms access 2007" }
Has XOR EAX, EBX another purpose? I have the following line in an assembler code: XOR EAX, EBX So, then I've searched a little bit and found out that XOR represents a "swap algorithm". You can read it here: < But when I look in register window of ollydbg, then I have the following EAX = 00000068 EBX = 0000003B Now, after the line the register window says EAX = 000000053 EBX = 0000003B But from that what I have read in wikipedia article I would expect the following EAX = 0000003B EBX = 00000053 At the end, i can say that a normal XOR operation is performed because: 0111011 =>EAX=0000003B 1101000 =>EBX=00000068 ------- 1010011 =>EAX=00000053 So my question would be why the swap algorithm is not performed. Or in other words: When can I expect the swap algorithm?
As the first answer states, XOR is a bitewise XOR, not an XOR swap. To do the Xor swap that you referenced from wikipedia it takes _3 instructions_ : xor eax, ebx xor ebx, eax xor eax, ebx Since you asked about the _purpose_ of XOR I thought I would include some other concepts for you to read up on, so you might have an idea of what to expect from XORs You can use XOR to clear a register: xor eax,eax Calculate absolute value: cdq xor eax,edx sub eax,edx XORs can be used for Crypto: < XORs are used in the CRC checksum algorithm: < XORs can be used to calculate Gray codes: < This is just the tip of the iceberg. The instruction can be used in a large number of situations.
stackexchange-reverseengineering
{ "answer_score": 13, "question_score": 3, "tags": "assembly" }
Differentiation with respect to radial direction This is a question that I've had since my PDE classes. Let us be in $\mathbb{R}^n$, where $x \in \mathbb{R}^n$ is fixed. Define $$\phi(r) = \int_{\partial B(0,1)} u(x+ry) d \sigma(y) ,$$ where $u: \mathbb{R}^n \to \mathbb{R}$, $d\sigma$ is the surface measure. $r$ is supposed to represent a "radial distance", and I'm not entirely sure what it is. Furthermore, there is this calculation $$\frac{\partial \phi}{\partial r} = \int_{\partial B(0,1)} (\nabla u(x+ry) \cdot y) \, d \sigma(y),$$ that I don't know how to justify. Can anyone help with this? Thanks.
**HINT** : Write $u=u(z)$, where $z=x+ry$; here $x$ is fixed and $y$ varies over the unit sphere. We take the $r$ derivative under the integral sign, obtaining $$\frac{\partial}{\partial r} u(x+ry) = \nabla u(x+ry)\cdot \frac{\partial(x+ry)}{\partial r} = \nabla u(x+ry)\cdot y.$$ If you insist on writing it out in the confusing coordinate notation, write $$\sum\frac{\partial u}{\partial z_i}(x+ry)\frac{\partial z_i}{\partial r} = \sum\frac{\partial u}{\partial z_i}(x+ry)\, y_i,$$ as you were trying to do.
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "multivariable calculus, partial differential equations" }
How do I burn an .img file onto a USB drive? I'm using Windows and trying to burn this Chromium OS nightly onto my USB drive. Could someone recommend a program (freeware) that can "burn" an .img file onto a USB drive?
In Hexxeh's Chromium OS Flow instructions its recommended to use Image Writer which is here: < Theres more info on it here. Its not for exactly the same release, but the image file will most likely be the same format.
stackexchange-superuser
{ "answer_score": 4, "question_score": 10, "tags": "windows 7, usb" }
Does there exist Git commit policies? E.g. when and what to commit? We are going to use Git where I work, and we have some in house programmers, and some external freelance programmers that have never used Source Control Management before. The reason we want to use Git is to be better at communicating with the freelance programmers, and to avoid code from being lost and in general track what they do. So now we need a commit policy. I.e when should users commit, and when should they rebase commits and so on. Does there exist written policies from other projects that I can read? Or does someone know of good practices that we should use?
Git is designed to be as flexible as possible in this regard. However, there are some common deployment models. A good overview can be found in the ProGit Workflow section.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "git" }
Equivalent diag R function in numpy python When I do with R `diag(0.03,2)` I obtain : [,1] [,2] [1,] 0.03 0.00 [2,] 0.00 0.03 How can I have the same result in Python ? I tried `numpy.diag(0.03,2)` but I get an error : `ValueError: Input must be 1- or 2-d`. Same with `numpy.diagonal(0.03,2)` Thanks for any help
Do `numpy.diag([.03]*2)`. `numpy.diag()` takes in a list of the diagonal components, and you can multiply lists in python to repeat elements.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, r, numpy, diagonal" }
Zend Framework - Route: Call action by param $router->addRoute('routeName', new Zend_Controller_Router_Route( 'test/:category/', array( 'module' => 'default', 'controller' => 'test', 'action' => ':category' ) )); That's my code at the moment (see above). How could I call now the action by a given param (via URL)? The url look e.g. like that: `domain.com/test/news/` and now I want to call the action newsAction() in the test controller. With the code above I get the error: `Action "category" does not exist and was not trapped in __call()`
Your statement is useless. The goal you want to achieve is exactly how the standard route works.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "zend framework, zend route, zend router" }
Separar comilla simple en String JS Tengo una cadena así: var cadena = '<form name="name" th:action=" 'ERROR' ">'; Tengo unas comillas simples dentro de la cadena y es lo que limita el inicio y el fin, ¿cómo puedo hacer para incluir los caracteres de escape como parte de la cadena ? Un saludo.
Para escapar tus comillas simples tendrás que escaparlas con `\`. Quedando de la siguiente manera: var cadena = '\'tu contenido\'';
stackexchange-es_stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "javascript, string" }
Error in Ionic project: Uncaught Error: Type Storage does not have 'ɵmod' property" I started a new project in Ionic 6.13.1. So, i added the plugin storage: ionic cordova plugin add cordova-sqlite-storage npm install --save @ionic/storage In _app.module.ts_ i wrote: import { IonicStorageModule } from '@ionic/storage'; but _IonicStorageModule_ was not recognized, only _Storage_ was. When i declare Storage in Imports section and run _ionic serve_ there was an error: "Uncaught Error: Type Storage does not have 'ɵmod' property". I did not wrote any other line in code, only this ones. How can i solve this? Thanks
For Angular-based Ionic apps using Ionic storage, you have to use the storage-angular library. npm install @ionic/storage-angular Here is a link to the Ionic Storage documentation for additional information
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "angular, cordova, ionic framework, plugins" }
Why are Matthew, Mark, and Luke called 'synoptic' gospels? The first three gospels are sometimes known as the "synoptic" gospels. What does this term mean, and how does it differentiate them from the gospel of John?
Matthew, Mark, and Luke are very similar: they record many of the same miracle stories, parables, and sermons. John by contrast has fewer miracles (and most are unique), no parables at all, and is the only Gospel to record Jesus's teaching on the nature of God at the Last Supper (ch. 13-17). Synoptic comes from the Greek for "see together" because they tell Jesus's story in the same way.
stackexchange-christianity
{ "answer_score": 5, "question_score": 5, "tags": "terminology, gospels" }
Minimization over the integers I am nearly sure this question has been asked earlier but I do not find an answer. Is there a way to solve this minimization in Mathematica Minimize[{Abs[1.2 - x] + Abs[3.3 - y] + Abs[1.6 - z] && x + y + z == 5 && x ∈ Integers && y ∈ Integers && z ∈ Integers}, {x, y, z}] When I run the command or change to `NMinimize` or `FindMininimum`, I receive the infamous message NMinimize::nnum: The function value False is not a number at {x,y,z} = {0.673558,0.659492,0.0861047}. But since for this specific value, the absolute value in the 3 cases is positive, I do not understand why Mathematica send this message. Of course this optimization can be transformed in a linear program. For information, this problem is a simplification of an apportionment problem.
Look at the usage of `Minimize`! Minimize[{Abs[1.2 - x] + Abs[33/10 - y] + Abs[16/10 - z], x + y + z == 5 && x ∈ Integers && y ∈ Integers && z ∈ Integers}, {x, y, z}] (* {1.1, {x -> 1, y -> 3, z -> 1}} *)
stackexchange-mathematica
{ "answer_score": 5, "question_score": 2, "tags": "mathematical optimization" }
Converting list of dates from a file to timestamp with bash I'm using bash and I would like to convert list of dates in format "`08-Sep-2020 07:08:49`" to timestamp. I found the way to do it one by one, line by line in a loop but I would like to convert whole file without using loops if possible. I was thinking about one line code like "`cat /tmp/file | <some_command>`" Example file content: 08-Sep-2020 03:07:04 08-Sep-2020 02:20:46 08-Sep-2020 23:25:52 Currently I'm using date -d "09-Sep-2020 06:52:44" +%s I would like to get another file or the same file with: 1599530824 1599528046 1599603952
With GNU awk for mktime(): $ awk -F'[ :-]' '{print mktime($3" "((index("JanFebMarAprMayJunJulAugSepOctNovDec",$2)+2)/3)" "$1" "$4" "$5" "$6)}' file 1599552424 1599549646 1599625552
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bash, awk, sed" }
jQuery show and hide not working as expected Please check example < When I click on button Show Data loader div should be displayed and after couple of seconds hidden. In console log you can clearly see that display property of qloader div get set to block and none, but nothing happens, qloader div never gets displayed. What is wrong?
That's not a good way of sleeping. It eats up the CPU, and you can't even rely on it taking the full 3 seconds on a fast machine. Instead use setTimeout(): setTimeout(function(){ $("#loading").hide(); console.log("qloader display = " + $("#loading").css("display")); }, 3000); That will allow the browser and your website to continue operating while you are waiting for the time to pass.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "jquery, hide, show" }
In bash script, is it possible to assign a value which will be calculated by a background process to a variable? if I have a script like this: #!/bin/bash echo `script2.sh` > temp.txt & (wait for long enough time) a=`cat temp.txt` echo $a a's value will be successfully changed by script2.sh. However, if I do this: #!/bin/bash a=`script2.sh` & (wait for long enough time) echo $a a's value would not be changed by script2.sh. The reason why I want to do this is becasue:(1)I do not want the main process to be blocked by the script2.sh(during waiting,I can do something else) (2)My main program will do a lot of such stuff, so doing a lot of file IOs will give me a big overhead and it's better to directly assign the value to a variable in memory. I have found the file IO in bash script is really very slow. In my program,doing 400 such IOs will take about 10 seconds (when the computer is busy though)! Any suggestion?
You can't assign a shell variable to a value that doesn't exist yet, so your approach simply isn't possible. I don't see a realistic option other than a temp file, but you can speed that option up quite a bit. I'm pretty sure it's not the file I/O that's slow, it's that you're creating a subshell to `echo` the script's output to the file, and a `cat` process to read the file. Process creation is slow, so if you want speed that's important to minimize. You can avoid creating the `echo` subprocess by redirecting the shell's output directly to the file, and replace the `cat` process with a bash's `$(<file)` idiom that reads the file directly in the shell. Here's what I came up with: #!/bin/bash script2.sh >temp.txt & # (wait for long enough time) a=$(<temp.txt) echo "$a"
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "bash, file, io" }
Unexpected behavior of a switch statement in a for loop The code below displays even the case 20, but my `int x` is equal to 10 only. What I want to happen is if `x` = 10, then I should show case 10 only. The problem is that it also shows case 20. public class For_Loop { public static void main(String[] args) { for (int x = 10; x <= 20; x++){ switch (x) { case 10: System.out.println ("Ten"); break; case 20: System.out.println ("Twenty"); break; default: System.out.println ("None"); break; } } } }
condition should be incrementing by 10: `for (int x = 10; x <= 20; x=x+10)`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -5, "tags": "java, for loop, switch statement" }
VBScript to detect today's modified files in a folder (including subfolders inside it) I need to get all the modified files inside a folder including the subfolders inside it, and copy them to another folder. How can it be done using VBScript or any other way to achieve this? Thanks in advance, Bibhu
try this (copy files modified less than 24 hrs ago ) Set objFS = CreateObject("Scripting.FileSystemObject") ''# Directory to scan strFolder = "c:\test" Set objFolder = objFS.GetFolder(strFolder) Go( objFolder) Sub Go(objDIR) If objDIR <> "\System Volume Information" Then For Each eFolder in objDIR.SubFolders Go eFolder Next For Each strFiles In objDIR.Files strFileName = strFiles.Name strFilePath = strFiles.Path If DateDiff("h",strFile.DateLastModified,Now) < 24 Then objFS.CopyFile strFolder&"\"&strFileName,"c:\tmp" End If Next End If End Sub
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "scripting, file, vbscript, directory" }
Turn off customErrors for web service only My ASP.NET 2.0 web app includes a web service, which throws various exceptions along with custom error messages (e.g. "You do not have access to this item" etc.). These are shown on screen, in a ASP.NET AJAX callback handler. The rest of the app is covered by some custom error pages, specified in the usual way in web.config. <customErrors mode="RemoteOnly" defaultRedirect="Error.html"> <error statusCode="404" redirect="NotFound.html" /> <error statusCode="403" redirect="NoAccess.html" /> </customErrors> My problem is if I have customErrors enabled in web.config, I lose my error messages returned from the web service - instead they are replaced with "There was an error processing the request" - which isn't very useful for either me or the users. Is there a way to turn off custom errors for just the web service?
Put your web service into separate directory and put additional web.config file in this directory. Each directory can have it own web.config containing settings of this directory (and directories inside this directory).
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "asp.net, web services, exception" }
How do I change the polygon fill color and border color for SpatialPolygons objects? I have SpatialPolygons or SpatialPolygonsDataFrames which I'd like to plot. How do I change the color using the three plotting systems in R (base graphics, lattice graphics, and ggplot2)? Example data: library(sp) Srs1 = Polygons(list(Polygon(cbind(c(2,4,4,1,2),c(2,3,5,4,2)))), "s1") Srs2 = Polygons(list(Polygon(cbind(c(5,4,2,5),c(2,3,2,2)))), "s2") SpDF <- SpatialPolygonsDataFrame( SpatialPolygons(list(Srs1,Srs2)), data.frame( z=1:2, row.names=c("s1","s2") ) ) spplot(SpDF, zcol="z") !test map
**Base graphics (`plot`)** For base graphics, `col=` sets the fill and `border=` sets the border color. plot(SpDF, col="red",border="green") If you want a choropleth map, set `col=` to a vector of colors, one for each polygon's data value. !base graphics **Lattice graphics (`spplot`)** Unlike base graphics, the `col=` option for lattice graphics controls the border color. For no border, set `col=NA` or `col="transparent"`. spplot(SpDF, zcol="z", col=NA) !no border For the polygon fill, set `col.regions` to a standard R color scheme (`gray`, `rainbow.colors`, `topo.colors`, etc.): spplot(SpDF, zcol="z", col.regions=gray(seq(0,1,.01))) !col.regions **ggplot2** As usual for ggplot2, you specify the levels and it picks the color scheme. You can override the scheme for the whole plot, however. Details to follow at some point.
stackexchange-gis
{ "answer_score": 38, "question_score": 29, "tags": "polygon, r" }
Recovering a broken subversion repository? Due to a failing harddrive on my windows homeserver where my personal subversion repository resided im having some missing repository files (the files in db/revs/n/nnnn), and thus my checkins/checkouts are failing… Is there any hope of recreating those files in any way or am i going to have to hope i got everything recently checked out somewhere and start over loosing the versionlog?
Do you not take backups of the subversion folders (i.e. with a dump or just file backups)? If not, and you're missing certain revisions, your best bet is to start making sure you have backed up copies of your last checkout. This is a far better option than hoping that you can piece together a valid revision from what's left in the repository.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 2, "tags": "svn, data recovery" }
Detecting specific Number Incoming Phone Call In Android I am trying to make an app that notify me when a specific number calls me . in short . the user must save a specific number and when this number call the app show a Toast or any thing. what should i use in the broadcast Receiver
Try this following code to get incoming call using `BroadcastReceiver` public class PhoneStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){ //Here you will incomeing mobile number do your logic here Toast.makeText(context,"Ringing State Number is - " + incomingNumber, Toast.LENGTH_SHORT).show(); } } catch (Exception e){ e.printStackTrace(); } } To get more reference here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "android" }
C/C++ alternative for matlab reshape and permute functions I need to port a piece of code from matlab into C or C++. Matlab implementation of the code extensively use reshape and permute functions to manipulate the layout of multidimensional arrays. Is there any library in c or c++ to get effect of these two matlab routines. Any suggestion would be helpful.
You can use **`OpenCV`** library, which contains similar **`Mat::reshape()`** routines to do transforms and permutations.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, c, matlab" }
Django admin action for photologue gallery change I have a photologue site set up and I really wanted to add an admin action so that when looking at a list of photos in the Django admin I can select a few and mark their respective checkboxes and via an admin action change them to some other gallery. How can something like this be implemented? I already got creating an admin class without having to write the photologue package and adding the action.. but have got no clue on how to send the "gallery" parameter.
Actually I think I got the answer after some more googling in this tutorial here (a bit old but it appears to work) link
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "django, photologue" }
SQL Update a table based on join with anther table I am trying to update a table by joining the values with another table. Here's my query so far. UPDATE LOGIN SET LOGIN.DISABLED_IND = 'N', LOGIN.DREASON = 'Test' FROM CONTACT WHERE CONTACT.CONTACT_ID = LOGIN.CONTACT_ID AND CONTACT.RID ='abc' When i run this, i get this [Error Code: 933, SQL State: 42000] ORA-00933: SQL command not properly ended Thanks
If you expect to update a large fraction of the rows in `LOGIN`, it will likely be more efficient to use an EXISTS UPDATE LOGIN l SET l.DISABLED_IND = 'N', l.DREASON = 'Test' WHERE EXISTS ( SELECT 1 FROM CONTACT c WHERE c.CONTACT_ID = l.CONTACT_ID AND c.RID ='abc' ) If you are updating a relatively small fraction of the rows in `LOGIN`, Yahia's approach of using an IN would likely be more efficient UPDATE LOGIN l SET l.DISABLED_IND = 'N', l.DREASON = 'Test' WHERE l.contact_id IN ( SELECT c.contact_id FROM CONTACT c WHERE c.RID ='abc' )
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "sql, oracle, oracle10g, ora 00933" }
Which is a better option for multitasking in arduino - millis( ) or Scheduler Library? I have an application wherein I want to flash( trigger for a sec) a solenoid every 10 seconds and at the same time receive a serial input to rotate a servo motor. The `delay()` creates conflicts so I have gone through the `millis()` function which is easy to understand.But in the arduino website they have something called the Scheduler library which looks pretty damn easy( haven't tried it though). So which is better and efficient option to consider, is it `millis()` or Scheduler? Thank you,
The Scheduler library uses `millis()` as well to calculate the delay between tasks. To link a function to the sheduler, it needs to have a `void f(void)` prototype. So to be able to add a function that returns something or has parameters, you need to wrap it in another function of `void f(void)` prototype. IMHO, a sheduler library is usefull to organize your code when you have multiple tasks (This library has a maximum of 10 tasks, but you can change it). In your case, you only have two tasks. It may be better to just use your own little sheduler using `millis()`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "arduino, serial port, multitasking" }
Android camera2: java.lang.IllegalStateException: maxImages (1) has already been acquired, call #close before acquiring more Hello having trouble to fix this issue. I already have a imageReader.close called inside the ImageAvailable callback but still having the error: > java.lang.IllegalStateException: maxImages (1) has already been acquired, call #close before acquiring more. Code I have is here: private ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener() { @Override public void onImageAvailable(ImageReader reader) { Image img = mReader.acquireLatestImage(); mReader.close(); } }; ps. I also use the argument reader as well but not seem to solve the problem
Ok I have solved my problem. I need to close the img object not the ImageReader.
stackexchange-stackoverflow
{ "answer_score": 33, "question_score": 18, "tags": "android, image, reader, camera2" }
Will Changing Country Change Language So I am a switching to the Mac guy and I have a query. Once I get my new Mac it seems I am asked to setup my country. **Say if I set the country to be Germany will it change the interface language to be German as well or will it still be English?** Thanks. P.S. : If I purchase the Mac from Germany and set it to my original home country will it create a problem?
If you select German as installation language your OS X installation and UI will be in German. You can always your change your system (UI) and input language or use multiple languages at the same time. It doesn't matter where you buy your Mac. However please note, a German MacBook will include a German keyboard. Some local stores also sell english keyboards as well..
stackexchange-apple
{ "answer_score": 2, "question_score": 0, "tags": "internationalization, language" }
Can I play on on multiple servers without affecting my existing characters from a single account? I regularly game with different groups and while I have played exclusively on the US servers to this point I have some interest in gaming with friends in Europe on the EU server. We've seen that you can use a US activated copy of Diablo to access the EU server and it's clear that I will not be able to access my current characters on the EU server but my question is "If I log into the EU server and start creating characters there, will I in any way harm/affect my current US characters?" IE Does Blizzard require you to commit to a single server?
I have characters on both the EU server and the US one, I can assure you they are completely separate, there is no way to even detect that I have characters on one server when I'm logged in on the other. The auction house is separate as well, so there is no way to share items either. Both servers are completely isolated from each other.
stackexchange-gaming
{ "answer_score": 1, "question_score": 0, "tags": "diablo 3" }
set innerHTML of an iframe In javascript, how can I set the innerHTML of an iframe? I mean: how to set, not get. `window["ifrm_name"].document.innerHTML= "<h1>Hi</h1>"` does not work, and the same for other solutions. Iframe and parent document are on the same domain. I would need to set html of the whole document iframe, not its body. I would need to avoid jquery solution.
A really simple example ... <iframe id="fred" width="200" height="200"></iframe> then the following Javascript is run, either inline, part of an event, etc ... var s = document.getElementById('fred'); s.contentDocument.write("fred rules"); the "contentDocument" is the equivalent of the "document" you get in the main window, so you can make calls against this to set the body, head, any elements inside ... etc. I've only tested this in IE8, Chrome and Firefox ... so you may want to test in IE6/7 if you have copies available.
stackexchange-stackoverflow
{ "answer_score": 32, "question_score": 29, "tags": "javascript, iframe, innerhtml" }
Equivalent to layout_weight for height Is there any equivalent command to the mentioned Iayout-weight to dynamically define the height of more than one View inside a LinearLayout? I want to have a LinearLayout with orientation="vertical" and then split that height to a defined ratio, but I can't find any command for that.
You don't need an equivalent to `layout-weight`, you just use that. Set your width to a value you want, set height to be 0dp and set the weight to be in proportion to what you want.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "android, android linearlayout" }
Is there an English equivalent of the Korean expression: "If the rice cake looks good, then it tastes good"? This Korean saying is essentially the direct opposite of "never judge a book by its cover."
You can probably consider the following in addition to some wonderful suggestions in comments **_What you see is what you get_** > The product you are looking at is exactly what you get if you buy it [Dictionary.com] It is a popular phrase in the computer industry. It is abbreviated to WYSIWYG (pronounced as "wiz-ee-wig"). For instance, if you are printing a document, whatever you see on the computer screen will be exactly printed as it is without any changes whatsoever. For more reading , go here
stackexchange-english
{ "answer_score": 4, "question_score": 2, "tags": "popular refrains" }
Creating unique custom attributes on AWS Cognito I need to create a custom attribute that is unique for each of the users inside my `User Pool`. Is there a way for me to do it with a custom attribute using `AWS Cognito`? I'm integrating the `AWS-SDK` in JavaScript.
Such a setting is not possible for custom attributes. The only attributes that work that way are alias attributes (they will need to be unique). These are email, phone_number, and preferred_username. Email and phone_number would need to be verified to be used that way. The only workaround I can think about is using one of the aliases to emulate this behavior.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "javascript, amazon web services, amazon cognito" }
How to deploy clojure noir website on a 3d party web hosting server? I have built my own website using clojure (noir), but I have no clue on how to deploy the website to a web hosting server. I know how to run it on a virtual port (localhost8080). Is there some sort of way to compile all clojure code into javascript and html so the third party web server will understand it and read it? or am is there another way for all of this? Thank you.
Just like many of the common Clojure web frameworks, noir is build on top of the ring framework. Ring produces Java servlets that are contained in .war files. Hosting providers know how to host war files. In general you use leiningen to produce a war file and give it to your hosting company through some manner of web interface (or by pushing it through git in the case of Heroku) add the `lein-ring` plugin to your project.clj's plugin section <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "web, clojure, hosting, noir" }
Generating Mouse-Keyboard combination events in python I want to be able to do a combination of keypresses and mouseclicks simultaneously, as in for example `Control+LeftClick` At the moment I am able to do Control and then a left click with the following code: import win32com, win32api, win32con def CopyBox( x, y): time.sleep(.2) wsh = win32com.client.Dispatch("WScript.Shell") wsh.SendKeys("^") win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) What this does is press control on the keyboard, then it clicks. I need it to keep the controll pressed longer and return while it's still pressed to continue running the code. Is there a maybe lower level way of saying press the key and then later in the code tell it to lift up the key such as like what the mouse is doing?
to press control: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) to release it: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0) so your code will look like this: import win32api, win32con def CopyBox(x, y): time.sleep(.2) win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0) win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, mouseevent, combinations, keyboard hook" }
Styled components not applying styles I have this 2 styled components export const Icon = styled.svg` width: 8px; height: 8px; background: black; ` export const Dots = styled.div` border: 2px solid green !imporant; height: 30px; background: white; width: 16px; height: 16px; border: solid 1px #d2d2d2; border-radius: 20px; top: 25px; position: relative; ${Icon}: hover { background:black; } } ` I want to display `Icon` on the hover of this div but i dont understand why it is not working, Any suggestions please?
There is no problem with your code except on hover you don't change the color from its default value `black` const Icon = styled.div` width: 100px; height: 100px; background: black; `; export const Dots = styled.div` ${Icon}:hover { background: red; } `; export default function App() { return ( <Dots> <Icon /> </Dots> ); } <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "reactjs, styled components" }
Random value of "Called asynchronously" in Application Insights logs I'm developing an API (using Web API 2.3) which is consumed by an AngularJS web app. I've enabled Azure Application Insights, and I noticed that, for the same operation, the same call is either **Called asynchronously = false** or **Called asynchronously = true**. For example: ![enter image description here]( ![enter image description here]( I did not change anything between these two calls (they're called within a second). How shall I understand this?
ApplicationInsights cannot reliably detect if dependency is sync or async. This feature is removed in the latest SDK and soon will be gone in UI.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "asp.net, angularjs, azure, asynchronous, azure application insights" }
Calculate the average number of hours in table per month I have a table named "loginhistory", and I need to calculate the most active hour of the month. How can i do it? My table structure is: id, userId, date (datetime), ip. I tried to do it in PHP but I did not succeed there either. I prefer the calculation to be done only in MySql. I expect the output to be just the number of the most active hour.
It does not matter checking average number if needed to pick active hour. Cause `average = count / days` and since `days` is the same for whole calculation (let's say `30`) the greatest `count` will be active hour in list. Just select by date range and group by hour and pick 1st one from descending sort: SELECT HOUR(date) AS hour, COUNT(id) AS logins, ( COUNT(id) / DAY(LAST_DAY('2019-01-01')) ) AS logins_avg FROM loginhistory WHERE date >= '2019-01-01 00:00:00' AND date < '2019-02-01 00:00:00' GROUP BY HOUR(date) ORDER BY logins DESC LIMIT 1
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Two Submit Buttons on Single Form Is it possible to have two submit buttons on a single form, one of which launches the submit but also passes a parameter to the URL? Perhaps using js/jquery to intercept the action and append the param somehow. i.e., <form action="/doStuff" method="post"> <input id="name" type="text"></input> <button id="save" type="submit">Save</button> <button id="save-with-param" type="submit">Save as Draft</button> </form> Clicking save would send: localhost:8080/myApp/doStuff and clicking `save-with-param` would send: localhost:8080/myApp/doStuff?param=XYZ
On all moder browsers, you can use `formaction` attribute: <form action="/doStuff" method="post"> <input id="name" type="text"></input> <button id="save" type="submit">Save</button> <button id="save-with-param" type="submit" formaction="/doStuff?param=XYZ">Save as Draft</button> </form> To support older browsers, e.g IE9<, you could add support using: ;(function ($) { $(function () { if (typeof document.createElement('input').formAction === "undefined") { $(':submit[formaction]').closest('form').data('defaultFormAction', this.action).on('submit', function () { var $focused = $(':focus'); $(this).attr('action', $focused.is('[formaction]') ? $focused.attr('formAction') : $(this).data('defaultFormAction')); }); } }); }(jQuery));
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, html, forms" }
How to remove a map in QGIS GRASS Plugin In QGIS Desktop 2.18.14 with GRASS 7.2.2, I started cleaning vector layers and it worked nicely. Issue: every time I load a shapefile onto GRASS Plugin by `v.in.ogr` (`v.in.ogr.qgis`), it creates a map (its own vector set) within GRASS Database. How can I remove these maps? Most of them are just temporally files and I do not want them to stay in the harddisk forever. In earlier documentation there appears a module(?) "GRASS Browser" which could be used to delete maps, or probably `g.remove` in GRASS (standalone) is the function I need, but I cannot locate them. **EDIT** I might have begun with a wrong assumption that we needed to clean mapsets / maps levels. GRASS users can simply remove _Location_ by deleting the folder and start over. It seems fairly practical way to deal with pile of maps.
I don't think the tool is listed in the toolset. But you should still be able to access the `g.remove` module from the **GRASS shell** and use the command prompt with something like: g.remove type=vector name='myVectorMap'
stackexchange-gis
{ "answer_score": 2, "question_score": 2, "tags": "qgis, qgis grass plugin" }
Can the Pi 4 power 2 external USB 3 HDDs? I would like to connect two external 2.5 HDDs a Pi 4. Can the Pi 4 power two of them at once? This is the model I have in mind: WD 2TB Elements
Not without voiding your warranty. An RPi4 can deliver a maximum of 1.2 A to all the USB ports together. This is done to protect the USB-C connector which is rated for 3A maximum. The disks you have in mind consume up to 1 A each. Without touching to the Pi, you'll need to use a powered USB hub or a bigger-capacity single disk. If you don't care about the warranty of your Raspberry and you're powering it externally, you can bypass the current limitation by connecting the 5V GPIO pin to the Ubat pin of USB directly (check out the semi-translucent copper wire): ![enter image description here]( P.S. A small 5V capacitor between the USB 5V and nearby GND (I used 300 uF between the same point where the wire arrives, and one of the 4 bigger solder joins) greatly improves the stability of the USB w.r.t hot-plugging new devices. Otherwise hot-plugging a second HDD may produce a voltage dip which reboots the HDD that was already connected.
stackexchange-raspberrypi
{ "answer_score": 20, "question_score": 19, "tags": "usb power, pi 4" }
PayPal Express Checkout Validating Payment How can we validate a payment Success/failure using response Token from Paypal in PayPal Express Check Out.
The DoExpressCheckoutPayment response (if Successful) will include a PAYMENTINFO_n_PAYMENTSTATUS parameter that you can check to see if the payment associated with the API call is actually completed or not. If this param has a value of "Completed" then you know you're good to go. It could be "Pending", though, in cases where an e-check is used for payment, fraud filters flag the transaction, etc. Because of this it is recommended that you use Instant Payment Notification (IPN) in order to handle all post-transaction processing tasks like updating your database, sending email notifications, etc.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "paypal, payment gateway, paypal sandbox" }
Create a mousemove event for a canvas library I am working on a canvas library and I have the following class: export default class Layer { constructor(ypcanvas) { this.ypcanvas = ypcanvas; this.container = ypcanvas.container; this.can = document.createElement("canvas"); this.ctx = this.can.getContext("2d"); }} (This is just a little excerpt of the Layer class) You can import the class and then create a new Layer like this: let layer = new Layer(ypcanvas); How could i accomplish an event like the following: layer.on('mouseout', function () { }); or layer.mousedown(function () { }) Or somethign equivalent to that, so that the user of my library can just call that event without having to addEventListener the layer canvas. Thx in advance.
You can do something like this: class MyLibClass { constructor(elementId) { this.elementId = elementId } mouseDown(callback) { document.getElementById(this.elementId).addEventListener("mousedown", callback) } } new MyLibClass("lib").mouseDown(() => alert("hey")) #lib { width: 100px; height: 100px; background: blue; } <div id="lib"></div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, events, canvas" }
how to remove these blue boxes without deleting my drawing (so that the artboard can be resized without whitespace) ### Question: How can I get rid of the white space around my graphic so that the artboard can be fitted to the graphic itself? ### Observed behavior: Object->Artboards->"Fit to selected art" crops the artboard to the edge of the blue boxes highlighted in the image below. I tried to fix this by deleting the blue boxes but that also deletes the purple/green/blue graphic shown in the picture below. ### Expected behavior: Normally, I would be able to Object->Artboards->"Fit to selected art". This would automatically crop the artboard to the edge of the purple/green/blue graphic in the picture below. ![enter image description here](
From what you are describing it sounds like the boxes are grouped with your artwork. Check in your layers panel. It's quite hard to give you precise advice without seeing the layers panel to see how this has been constructed. This may work: Ungroup everything until there are no groups left, and select and delete the boxes. Regroup your artwork if necessary. Another possibility is that these bounding boxes are clipping masks, if so then release them, and delete them. If the artwork is a raster image, you may have to make a new clipping mask and apply it to the image.
stackexchange-graphicdesign
{ "answer_score": 3, "question_score": 2, "tags": "adobe illustrator" }
fetch all youtube videos using curl I'm a beginner at PHP. I have one task in my project, which is to fetch all videos from a YouTube link using curl in PHP. Is it possible to show all videos from YouTube? I found this code with a Google search: <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ' curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $contents = curl_exec ($ch); echo $contents; curl_close ($ch); ?> It shows the YouTube site, but when I click any video it will not play.
You can get data from youtube oemebed interface in two formats `Xml` and `Json` which returns metadata about a video: Using your example, a call to: So, You can do like this: $url = "Your_Youtube_video_link"; Example : $url = " $youtube = " . $url. "&format=json"; $curl = curl_init($youtube); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $return = curl_exec($curl); curl_close($curl); $result = json_decode($return, true); echo $result['html']; Try it...Hope it will help you.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php, youtube" }
iOS versions on device do not match supported versions by Xcode When I connect my iPod to MacBook I get this dialog window: !this dialog window
Seems that reinstalling Xcode helped fix the problem.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "xcode, ios" }
Get script to create database including initializer data I wonder if there's a possibility with Entity Framework's Migrations to get the sql script to create the content of my database including all the data from my seed method in the Configuration class: protected override void Seed(Sotasa.DAL.SqlContext context) { //Data I'd like to be included to the script } Help of the Update-Database command doesn't look like it could be done: Update-Database [-SourceMigration <String>] [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String> [<CommonParameters>]
That is not possible. (To have data generated in Seed method generating SQL statements). An alternative workaround is to use a script to build -> create database -> script the database with data? (Powershell probably can do it tapping into sql server management objects.)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 5, "tags": "entity framework, ef code first, entity framework 5, entity framework migrations" }
Why does the using statement work on IEnumerator and what does it do? Back when I was learning about `foreach`, I read somewhere that this: foreach (var element in enumerable) { // do something with element } is basically equivalent to this: using (var enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) { var element = enumerator.Current; // do something with element } } Why does this code even compile if neither `IEnumerator` nor `IEnumerator<T>` implement `IDisposable`? C# language specification only seems to mention the `using` statement in the context of `IDisposable`. What does such an `using` statement do?
Please, check the following link .aspx) about **foreach** statement. It uses try/finally block with Dispose call if it's possible. That's the code which is behind **using** statement.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 6, "tags": "c#, language lawyer" }
Setting Default Printing Options For A Sharepoint 2010 List Item I need to change our printer default settings to print out list item (edit form). Can this be done from within SharePoint 2010? If we right click in the edit form and select print the result is too small to read. if we use "print preview" we can change the "Change Print Size" from "Shrink to fit" to 100%. Unfortunately this causes the printing options to change and we then need to go to print-options and reset it to "Only the selected frame" I realize this may not be a "SharePoint 2010 question" but I have no-one but ya'll to ask!
I don't think it's possible to change printer default settings in the SharePoint 2010. You should change printer default settings in the explorer printer settings.
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint server, printing, settings, default" }
How do I Specify PDF Output Path in Chrome Headless Mode This page shows that you can now use chrome to generate a PDF of a webpage using the following CLI command: chrome --headless --disable-gpu --print-to-pdf However, it does not state how to specify the output path. How do you specify the output path?
chrome --headless --disable-gpu --print-to-pdf="C:/temp/pdftest.pdf" source: ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 30, "question_score": 17, "tags": "pdf, google chrome headless" }
Wait map function before render I'd like to use `map()` in NodeJS to change items of my array before rending an EJS template. However, sometimes the `map()` is not finished before the render and I get an error 500... My code : var newCards = cards.map(function(card) { switch(card.display) { case 'number': dbConnexion.query(card.query).success( function(results) { card.results = results.length; }); break; case 'table': dbConnexion.query(card.query).success( function(results) { card.results = results; }); break; } return card; }); response.render('myview', { newCards: newCards });
You are using async functions within map, you should promisify your map and wait promises to complete. let promises = cards.map(function(card) { return new Promise(function(resolve, reject) { switch(card.display) { case 'number': dbConnexion.query(card.query).success( function(results) { card.results = results.length; resolve(card); }); break; case 'table': dbConnexion.query(card.query).success( function(results) { card.results = results; resolve(card); }); break; } }); }); Promise.all(promises).then(() => { response.render('myview', { newCards: newCards }); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "node.js" }
How I can stop the " while loop " if the user enter number <0? in this example : int numbers=0 ,sum=0; while (numbers >=0) { cout<<"Enter positive numbers: "; cin>>numbers; sum += numbers; } cout<<"The result = "<<sum<<"\n"; Can u help me what I should to do please?
In the loop, you'll have to deal with two situations. 1. The user enters invalid input or EOF. 2. The user enters a number less than 0. For the first, you'll need to use: if ( cin >> numbers ) { // Reading to numbers was successful. } else { // Deal with the error. } For the second situation, you'll need to use: if ( numbers < 0 ) { break; } Put it all together, while ( true ) { cout << "Enter positive numbers: "; if ( cin >> numbers ) { if ( numbers < 0 ) { break; } } else { // Deal with error. Perhaps break out of the loop too? break } sum += numbers; } cout << "The result = " << sum << "\n";
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -3, "tags": "c++" }
Does holding an Activity implemented interface will cause memory leak? I have an Activity which implements an interface, and a AsyncTask using the interface update the status. I understand that if the AyncTask hold an reference of the Activity and outlive the Activity will cause the memory leak, but if the AyncTask just holding part of the memory, ie, the interface, will it also cause memory leak??
Yes it will. The interface is just a definition what methods a certain objects provides. It is still a reference to the original Object.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "android, memory leaks, android activity" }
How two cars are getting at the same point of the road (obstacle, cyclist, another car parked on a small part of the road) in the same time? You have an ordinary road, two ways. You are driving on the right part of the road and you see a person walking on the same part 400m away, you have to slow down or to accelerate because from the other way is coming another car. What I always see in this situation is this: if you are going to maintain the same speed, the opposite direction car is going to meet with you exactly where the person is, exactly at the obstacle. Can this be explained by physics? Thanks guys! Maybe for most of the people around here this seems simple but I want to know more about this.
The location of the pedestrian relative to the two cars when they meet will depend on the speed of each car, the initial distance between the pedestrian and the other car as well as yours, and to a lesser extent on how fast the pedestrian is walking assuming the speeds of the cars is much greater than the pedestrian. Considering all the variables I don’t see how you can always meet the other car exactly where the pedestrian is. Hope this helps
stackexchange-physics
{ "answer_score": 1, "question_score": -1, "tags": "everyday life, velocity" }
How to overlay a stem plot over a box plot in MATLAB? I have a vector A=[1 2 3 3 3 4 5] I am able to show its box plot with boxplot(A, 'orientation', 'horizontal') I can also show its distribution with a stem plot like this [nelements, centers] = hist(A); stem(centers, nelements/numel(A), 'blue'); My question is how to combine these two plots into one figure? The figure should have its `y-axis` as probability and `x-axis` as the `A` values. As for the height of the box plot in the figure, it does not matter. How may I do this?
Use `hold on` as follows, and be aware that you need to vertically move (using `'position'` again) your `boxplot` to fit the axes of `stem` boxplot(A, 'orientation', 'horizontal','position',0.1); hold on [nelements, centers] = hist(A); stem(centers, nelements/numel(A), 'blue'); hold off !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "matlab, plot" }