INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to make a <td> on more than one row?
How I can make a TD one more than one row in HTML?
To make it like this:
<
The avatar is a TD and the sidebar another, but they are both in the same table of the TD "some text"...
It's for a profile page... | You could check out the `rowspan` and `colspan` attributes.
As explained here. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "html, css"
} |
In which format bitcoin protocol send message?
I'm writing a small p2p network and I don't know if I have to transmit message (between nodes) in clear text or in another format ? How is it for bitcoin protocol ? | > **in clear text or in another format? How is it for bitcoin protocol?**
In binary. With numbers mostly in little-endian byte-order. Over TCP with a conventional target port number.
The details are at <
For example:
> ## Message structure
>
> Field Size | Description | Data type | Comments
> ---|---|---|---
> 4 | magic | uint32_t | Magic value indicating message origin network, and used to seek to next message when stream state is unknown
> 12 | command | char[12] | ASCII string identifying the packet content, NULL padded (non-NULL padding results in packet rejected)
> 4 | length | uint32_t | Length of payload in number of bytes
> 4 | checksum | uint32_t | First 4 bytes of sha256(sha256(payload))
> ? | payload | uchar[] | The actual data
Unless message size and volume is important, I would instead use JSON in UTF8 for any protocol I create. You should make your own evaluation.
You might also want to consider the Gossip protocol | stackexchange-bitcoin | {
"answer_score": 0,
"question_score": 0,
"tags": "protocol"
} |
How To Mix Set Terms With Random Elements
I would like to generate a random set of coordinates within a certain range and then print the results in the form of hours, minutes, seconds (e.g. 39° 50' 30" N).
What I have so far:
#Set the seed for random number generation
set.seed(0112)
#Define the integers for each part of the coordinates
h <- sample.int(38:41, 1)
m <- sample.int(52, 1)
s <- sample.int(31, 1)
#Print the results
print(paste("h","°","m","'","s", "", "N"), quote = FALSE)
Which results in:
##[1] h ° m ' s N
How do I get the numbers I've generated to show up in the print results rather than the name that I've given the integers? | Remove them from quotes (`""`) in `paste`
paste(h,"°",m,"'",s, "", "N")
#[1] "15 ° 48 ' 31 N"
* * *
The purpose of `quote` in `print` is different. From `?print`
> quote - logical, indicating whether or not strings should be printed with surrounding quotes.
See for example
print(paste(h,"°",m,"'",s, "", "N"), quote = TRUE)
#[1] "15 ° 48 ' 31 N"
print(paste(h,"°",m,"'",s, "", "N"), quote = FALSE)
#[1] 15 ° 48 ' 31 N
Notice how output is surrounded by quotes (`"`) in first case and not in second case. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r"
} |
Serving a file generated dynamically by the model, in ASP.NET MVC
I'm still new to web app development, so bear with me if this sounds a little silly.
I have to implement functionality into an ASP.NET MVC2 website so that users can download an .rdp file that is generated _after_ clicking a URL.
The reason they need to be generated is that the user names for the machines are shared, but sometimes change, and the users don't necessarily know what they are.
Generating the file would be fine, but my questions are: a) What's the best way of returning the file from my business layer
b) A push in the right direction as to what I need to implement in my controller in order to be able to handle the request, as well as be able to serve up the generated file. | Take a look here for an example:
How can I present a file for download from an MVC controller?
You'd have an `ActionResult` inside your Controller that would return a `File` to the user. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "c#, asp.net mvc"
} |
Fourier transform of a Generalized Gaussian
I've got a family of functions called Generalized Gaussians.
They're given by:
$f(x) = \exp(-ax^{2p})$
Where $p \in \\{1,2,3,\ldots\\}$
Could anyone tell me how to find their Fourier transforms? | Here is a method: we define $g(t):=\int_{\mathbb R}e^{itx}e^{-x^{2p}}\mathrm dx$. Then, taking the derivative under the integral and integrating by parts, we derive the differential equation $$g^{(2p-1)}(t)=(-1)^p\frac t{2p}g(t).$$ The solutions of this equation are analytic, hence we can find a recurrence relation between the coefficients. | stackexchange-math | {
"answer_score": 2,
"question_score": 5,
"tags": "fourier analysis"
} |
Counting cats with regular expressions
So I want to match a string with the word "cat" in it a bunch of times, such as:
"cat cat cat cat cat"
or
"cat cat cat cat"
If there's anything else besides "cat" or whitespace, I don't want to match. So I can do:
^(cat\s*)+$
However, I want to find out how many cats appear in the string. One way to do this would be to count the number of groups, however the above regular expression will only give me a single group with the first cat, not a capture per cat. Is there a way to do this using regular expressions? | You want to do two different things - validate a string and count word occurrences. Usually you cannot do these two things in one step.
var str = "cat cat cat cat cat";
var count = 0;
if ( /^(cat\s*)+$/.test(str) ) {
count = str.match(/cat/g).length;
}
In .NET regex you have Group.Captures which lists all the occurrences where a group matched, not just the last one, like in other regex engines. Here you could do both validating and counting in one step. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "ruby, regex"
} |
How to check that a key exists with jsonpath in a Camel route?
This JSON object below needs to be checked if a key exists or not. If key exists and value is empty then I want set `TH` as default language.
How to do that in camel route?
{ "languagePreference":"" }
//set default value of language preference as TH
.setHeader("languagePreference").jsonpath("$.languagePreference") | You can use the **`suppressExceptions`** flag
.setHeader("languagePreference").jsonpath("$.languagePreference", true)
This will not throw an exception if the key is missing. After that, you can check for a value in the header, and then you can assign the desired value if header is empty (There are many ways to check the header value).
//.choice().when(PredicateBuilder.or(header("languagePreference").isNull() , header("languagePreference").isEqualTo("")))
.choice().when().simple("${header.languagePreference} == null || ${header.languagePreference} == ''")
.setHeader("languagePreference").constant("TH")
.end() | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "json, apache camel, jsonpath, spring camel, camel http"
} |
Vídeo en java como mensaje emergente
Seguro que todos recordareis la mítica escena de Parque Jurásico en la que se aparecía la animación de _"no has dicho la palabra mágica"_ me estoy proponiendo hacer algo parecido en java a modo de prueba pero no se como llamar a mi vídeo ( almacenado en el propio pc).
El código sería el siguiente:
public static void main(String[] args) {
System.out.println("Introduce una clave maestra");
Scanner sc = new Scanner(System.in);
String masterclave=sc.next();
System.out.println("Intruduce una clave");
String clave=sc.next();
if(clave.compareTo(masterclave)==0){
System.out.println("Clave correcta");
}
else {
System.out.println("VIDEO");
}
} | Prueba con este código:
try{
Runtime run = Runtime.getRuntime();
Process proc = run.exec("start C:\\video.mp4");
}
catch (IOException e){
e.printStackTrace();
}
Tal vez te pueda servir. | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, video"
} |
What does "it" stand for?
> The faeces contain nitrogen and **it** is that which fertilises the desert soil.
source: A collection of a bunch of sentences
What does "it" stand for?
I'm considering two possibilities:
1, "it" refers to nitrogen. And "that which" can be replaced by "what".
2, "it is....which..." work together to make the cleft sentence construction. | "It" does not technically refer to either the nitrogen or the faeces, but acts as a placeholder until "that which fertilises the desert soil" is identified. The word " _that_ " then refers to the _nitrogen_ :
> The faeces contain nitrogen and it is **that** which fertilises the desert soil.
It is the answer to the question "What is that which fertilises the desert soil?". | stackexchange-ell | {
"answer_score": 2,
"question_score": 0,
"tags": "pronouns, cleft constructions"
} |
How to have a a url be like example.com/projects/projectName?
I would like to know how I can have a website that has links to deeper pages like so: www.example.com/ then I click on "Projects" (that becomes www.example.com/Projects) and then I click on a project (Which now becomes www.example.com/Projects/projectName/) How would I do that??? Please help, I really need these.
EDIT: Why are people down voting my question? | This is usually done with folders.
When you open www.example.com/Projects you are actually accessing www.example.com/Projects/index.html then let's say you want to access the project the folder Foobar so you type in www.example.com/Projects/Foobar/ and you are served www.example.com/projects/Foobar/index.html
However this can also be done with PHP URL rewriting and the use of a .htaccess fie.
Also when linking make sure that you start with a backslash (Absolute URLs) e.g. href="/projects/test"
If the link was to "projects/test" and you were on that page then if you clicked on that link you would be taken to "projects/test/projects/test" | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -4,
"tags": "html, css, web"
} |
Uploaded files have permission 000
two days ago i updated wp to the newest version and this problem occurs since then. when i upload files to the media library, their file permissions are set to 000. means no rights. the files are copied to the server, but since nobody has any right to read / write / execute i can't do anything with it (the files are defenetly on the server, but wp can not create the thumbnails etc. and i can't view the files with my ftp client, but when i download them, they are just fine). the uploads folder and all containing folders have 777 and i cant find any solution to this. is it some hosting problem, that just popped up??
thanks for the help | i deactivated all the plugins and reactivated them back again, just to find out than one of those was currupted / outdated. now everything works fine again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permissions, uploads"
} |
WPF RichTextBox as a text queue for logging purposes
I would like to use a RichTextBox WPF control to print log outputs, but I am wondering what is the most efficient way to remove the "oldest" lines after there are for example more than 10,000 lines displayed, if it is possible to actually implement a queue behaviour, especially as there is no easy "Text" property to play with.
Unfortunately, I am not able to achieve this result with nlog either probably due to a bug or a limitation. | If you extend the original control with a LineCount int property, it is possible to use this (inspired by some code given here):
if (this.MaxLines > 0)
{
this.lineCount++;
if (this.lineCount > this.MaxLines)
{
tr = new TextRange(rtbx.Document.ContentStart, rtbx.Document.ContentEnd);
tr.Text = tr.Text.Remove(0, tr.Text.IndexOf('\n'));
this.lineCount--;
}
}
//And for auto scrolling
if (this.AutoScroll)
{
rtbx.ScrollToEnd();
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "c#, wpf, logging, queue, richtextbox"
} |
Toroid with variable current and Ampere's Law
Say you have a current $I(t)$ (notice the **time dependence** ) flowing through a Toroid with $N$ total loops and all the usual approximations: $(b-a) \ll r,\; B=0$ outside.

You are asked to calculate the magnetic field $B$. Could you apply _Ampere's Law_ to obtain the familiar form of $B$ found for example here?:
$$B~=~\frac{\mu N I}{2\Pi r}.$$ | You will in general also need to include the term from the time varying electric field. In integral form:
$$ \oint_{\partial A}{\vec{B}\cdot d\vec{s}} = \mu_0I + \frac{1}{c^2}\frac{\partial}{\partial t}\int_{A}\vec{E}\cdot dA $$
If $I(t)$ changes slowly so that the second term is small, you can do the calculation as in the static case.
For any given application, it's important to examine the approximations you are making, and determine if they are justified in your particular case. Here, you should also realize that Ampere's Law is telling you the component of B along the path of integration. Inside the toroid, there is a radial component as well. | stackexchange-physics | {
"answer_score": 2,
"question_score": 1,
"tags": "electromagnetism, homework and exercises, electricity"
} |
Creating an distributed RDD in Spark
I am aware that to create an RDD, we have 2 ways:
1. Parallelise an existing collection in a driver program.
2. Referencing Data from an external storage system such as HDFS, HBase, etc.
However, I would like to know what happens when I read data from a Data Lake such as (Azure Data Lake Storage Gen 2, `ADLS Gen 2`). For instance, If I have the following command:
df = spark.read.csv("path to ADLS Gen 2").rdd
I would like to know how the data is read; is it into the driver? Or is it directly into the worker nodes?
Then, where does the processing happen in case we applied some transformation on the `Dataframe` or `RDD`? this question exists only if the data is loaded into the driver node.
Please note that I am new to Spark and I'm still learning about the tool. | The data are read on worker nodes,unless the program running on the cluster forces the driver node to read them.Of course,Spark workers don't load the entire RDD on their local memory;which rdd partition goes to which worker is handled by the driver manager.
This means that when you apply transformations on a session,the Spark takes the following steps:
1.Creates a DAG for computing transformations and actions in the most possible efficient way.
2.Sends a jar file,having general info about the program and specific info about the processing this worker must apply, to all active workers of the cluster.
The above are given in a very abstract way ,since there are much more going inside a spark cluster when deploying an application,but the main idea is that **workers read the files and what they have to do to them,is coming from the driver through the network** | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "apache spark, apache spark sql, rdd"
} |
image is not loading , .htaccess file problem
Someone tell me, where i'm doing wrong . this is my .htaccess file code
Options -Indexes
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)/$ /$1 [R=301,L]
RewriteRule ^(.*)$ Core/index.php?app=$1 [QSA,L]
Here everything looks good. every request go to Core/index.php file. but when I type a URL to any file ( images, video ...) which is in current server, then file is not loading in browser. instead of file loading , it loads index.php page again (I found in Network panel of the browser) | Could you please try following, based on your shown attempts. You should write rule of removing `/` at last before your other rule of rewriting.
Please make sure to clear your browser cache before testing your URLs.
Options -Indexes
RewriteEngine on
RewriteRule ^(.*)/$ /$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ Core/index.php?app=$1 [QSA,L] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "apache, .htaccess, mod rewrite, url rewriting, friendly url"
} |
C#-Regular expression for email, but exclude "hotmail,gmail,yahoo"
How can I rewrite this regular expression in order to match all email addresses, but not those
which contains " **hotmail,gmail and yahoo** ". So far I wrote this:
^([a-zA-Z0-9_\-\.]+)@(?<!hotmail|gmail|yahoo)((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$ | Change the negative lookbehind to a negative lookahead by removing the `<`, and reposition it as follows
^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(?!hotmail|gmail|yahoo)(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$
The above assumes that `"hotmail,gmail and yahoo"` would directly follow the `@`.
Shorter equivalent:
@"^([\w.-]+)@(\[(\d{1,3}\.){3}|(?!hotmail|gmail|yahoo)(([a-zA-Z\d-]+\.)+))([a-zA-Z]{2,4}|\d{1,3})(\]?)$" | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "c#, regex"
} |
How do I remove linebreaks ONLY if they occur inside html tags?
Sorry, another python newbie question. I have a string:
my_string = "<p>this is some \n fun</p>And this is \n some more fun!"
I would like:
my_string = "<p>this is some fun</p>And this is \n some more fun!"
In other words, how do I get rid of '\n' **only** if it occurs inside an html tag?
I have:
my_string = re.sub('<(.*?)>(.*?)\n(.*?)</(.*?)>', 'replace with what???', my_string)
Which obviously won't work, but I'm stuck. | You should try using BeautifulSoup (`bs4`), this will allow you to parse XML tags and pages.
>>> import bs4
>>> my_string = "<p>this is some \n fun</p>And this is \n some more fun!"
>>> soup = bs4.BeautifulSoup(my_string)
>>> p = soup.p.contents[0].replace('\n ','')
>>> print p
This will pull out the new line in the p tag. If the content has more than one tag, `None` can be used as well as a for loop, then gathering the children (using the `tag.child` property).
For example:
>>> tags = soup.find_all(None)
>>> for tag in tags:
... if tag.child is None:
... tag.child.contents[0].replace('\n ', '')
... else:
... tag.contents[0].replace('\n ', '')
Though, this might not work exactly the way you want it (as web pages can vary), this code can be reproduced for your needs. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "python, html parsing"
} |
Existence of certain graph gadget related to coloring odd hole free graph
Crossposted from MO.
Wondering about the existence of graph gadget related to coloring (or 3-coloring) odd hole free graphs.
Let $G$ be simple $k$-chromatic connected graph with two vertices $u,v$.
Is it possible $G$ to satisfy:
1. All **induced** $uv$ paths have odd order (even number of edges).
2. In all proper $k$ colorings, $u$ and $v$ have distinct colors
3. (optional) $G$ doesn't contain induced $C_{2n+1}$ for $n>1$
If this is possible, there is reduction $F$ to odd hole free $F'$.
Replace an edge $u'v'$ by the gadget $G$ where $u'=u,v'=v$ and the rest vertices of $G$ are new vertices.
According to graphclasses coloring odd hole free is NP hard and 3-coloring is unknown.
Computer search suggest small gadgets don't exist (modulo errors). | One can extract an argument that this cannot work from the paper found by OP in the MO thread. Suppose $G=(V,E)$ is as required, and $c:V\to[k]$ is a $k$-coloring. By the assumption, $c(u)\neq c(v)$. Consider the (bipartite) subgraph $H$ induced by $\\{x\in V\ |\ c(x)\in\\{c(u),c(v)\\}\\}$.
If $u$ and $v$ are in the same connected component of $H$, pick any shortest path in $H$ between $u$ and $v$; it is an induced path in $G$, with colors alternating between $c(u),c(v)$, and must have an odd number of edges because the colors at its ends differ. This contradicts the assumption.
So $u,v$ are in different connected components; but then one can toggle the coloring of one of these components to obtain a coloring $c'$ with $c'(u)=c'(v)$, contradiction. | stackexchange-cstheory | {
"answer_score": 4,
"question_score": 5,
"tags": "graph theory, graph colouring"
} |
How to support window.print() in a embedded web browser using JavaFx java 1.7
I have created an embedded browser **using jdk1.7 (and bundled javafx with jdk 7).** However a button on html page having `onClick="window.print()"` **is not working**.
Any idea how can this be fix.
Thanks and Regards, Rahul | As you note in your question, Java 7 will not work for printing WebView content as it lacks the required functionality to do so.
Try Java 8, it adds printing support, though I don't know if printing of WebView content is supported when triggered through JavaScript. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, javafx, embedded browser"
} |
How to properly name gotoAndPlay function
I wonder why did guys at Adobe/Macromedia choose function name:
gotoAndPlay();
and not:
goToAndPlay(); // _Capitalized To_
Is there a logical explanation? | Sure. **goto** is a word used in technical nomenclature: < The function name uses a conflation of that _goto_ and the English phrase _go to_. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "flash"
} |
Where I should put my python scripts in Linux?
My python program consists of several files:
* the main execution python script
* python modules in *.py files
* config file
* log files
* executables scripts of other languages.
All this files should be available only for root. The main script should run on startup, e.g. via upstart.
**Where I should put all this files in Linux filesystem?
What's the better way for distribution my program?** pip, easy_install, deb, ...? I haven't worked with any of these tool, so I want something easy for me. The minimum supported Linux distributive should be Ubuntu. | For sure, if this program is to be available only for `root`, then the main execution python script have to go to `/usr/sbin/`.
Config files ought to go to `/etc/`, and log files to `/var/log/`.
Other python files should be deployed to `/usr/share/pyshared/`.
Executable scripts of other languages will go either in `/usr/bin/` or `/usr/sbin/` depending on whether they should be available to all users, or for root only. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 13,
"tags": "python, linux, open source"
} |
現在のカーソル位置から単語の先頭までをregionに収める方法
`narrow-to-region`region
narrow `save-excursion`
(let* ((current-point (point)))
(narrow-to-region (progn (backward-word) (point)) current-point))
`backward-word-point` | `thingatpt.el` `bounds-of-thing-at-point` (`autoloaded function`)
(narrow-to-region (car (bounds-of-thing-at-point 'word)) (point))
# … | stackexchange-ja_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "elisp"
} |
Calling REST WS from command line
I read that REST WS can be called from a command line. I know that they can be invoked from program code, but how directly from command line? I looked around the internet to know how this can be done, but didn't find any information on this. Can anyone please tell me how this can be done? I have developed a rest ws app in grails. | You can use curl from the commandline of any unix-like os.
For example, you can test some sample Facebook API like this:
curl <
or to POST:
curl -X POST -d "param1=value1¶m2=value2" < | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "web services, rest, grails, command line"
} |
How do I set the color for a tabview in android?
I want to change the colour of a tabview from the default grey (and black when not selected) to red and green when not selected.
In the tab Widget class I'm trying to set the colour using these functions
tabHost.setBackgroundColor(Color.RED);
tabHost.getTabWidget().setBackgroundColor(Color.GREEN);
But they don't work, its still the default colour. How do I manually set the background and tab colours of a tab widget in android? Also, is it possible to do it in xml? | See Step 4. at this blog, it's how I have done it, very simple, easy to change and tweak if you need to and it's all in XML.
Custom tabs in android tabhost | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, android widget, android tabhost"
} |
Cannot execute owned file on Ubuntu 14.04 LTS
I have a file I need to execute as `userme`. The following command runs just fine:
# sudo /usr/lib/squid3/squid_radius_auth -f /etc/squid3/radius-config
However, when I run as `userme`, it gives the following error:
# sudo -u userme /usr/lib/squid3/squid_radius_auth -f /etc/squid3/radius-config
sudo: unable to execute /usr/lib/squid3/squid_radius_auth: Permission denied
I have tried these:
# sudo chown userme:userme /usr/lib/squid3/squid_radius_auth
# sudo chmod 777 /usr/lib/squid3/squid_radius_auth
# sudo chmod +x /usr/lib/squid3/squid_radius_auth
but this doesn't work. I just cant get it to run as non-root. | Found the answer here:
> It is not enough to have read permission on a file in order to read it. You also need to have read permission on the directory it belongs to.
The solution here was:
chmod 775 /usr/lib/squid3/ | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -1,
"tags": "ubuntu, permissions, file permissions, sudo, user permissions"
} |
Python: Filtering sublists based on maximum value spread
I have a list of lists. Each sublist contains 2 items, and for n occurences, second item of the sublist is the same.
I want to keep only the first sublist, because spread is the largest in the first one. Here's what I have:
[[0, 3],
[1, 3],
[2, 3],
[314, 335],
[315, 335],
[316, 335],
[317, 335],
[318, 335],
[319, 335],
[320, 335],
[321, 335],
[322, 335],
[323, 335],
[324, 335],
[325, 335],
[326, 335],
[327, 335],
[328, 335],
[329, 335],
[330, 335],
[331, 335],
[332, 335],
[333, 335],
[334, 335],
[645, 647],
[646, 647]]
And I want to keep:
[[0, 3],
[314, 335],
[645, 647]]
Any ideas on how to do so? | This is one approach.
**Ex:**
seen = set()
result = []
for i in data:
if i[1] not in seen: #Check if second item in set
result.append(i) #Add to result
seen.add(i[1]) #Add second item to set
print(result) #--> [[0, 3], [314, 335], [645, 647]] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python"
} |
Not able to convert Date String to required format using MomentJS
I am trying to convert a `Date String` of format
`Mon Dec 03 2018 05:30:00 GMT+0530 (India Standard Time)`
into a format of `YYYY-MM-DD` so as to use it for a value in `input date` but it's not able to parse it.
I tried using these formats but it didn't work.
` moment(new Date(Mon Dec 03 2018 05:30:00 GMT+0530 (India Standard Time))).format("YYYY-MM-DD") `
But since it's not a `Date.parse()` format, it doesn't work.
Any ideas would be welcome. | You need to pass the dateFormat while creating the moment object, inorder for it to recognize and parse non-default formats.
Try,
var dateFormat = "ddd MMM DD YYYY HH:mm:ss zZZ";
var m = moment("Mon Dec 03 2018 05:30:00 GMT+0530 (India Standard Time)", dateFormat);
m.format("YYYY-MM-DD");
More details for parsing from string: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "momentjs"
} |
Users with less than 2k reputation appear as reviewers
I was looking into the stackoverflow review page. It appears that something is wrong with the Suggested edit section. As per the other sections, it should display people who are reviewing these posts. But looks due to some issues that it is showing people whose posts has been suggested for edits.
To check this issue, just hover over the people, and you will see the people having much less reputation than the 2k appear in this queue.
> ,' ','0') + '-' +
REPLACE(STR(A.UserTestId,5),' ','0') + '-' +
REPLACE(STR(A.Sequence,2),' ','0') as TestId,
When Sequence is null then TestId returns as null. If Sequence is null what I would like is for just the zero padded AdminTestID the "-" and the zero padded UserTestId to appear. | You can use CASE to branch between two scenarios when Sequence is null or not. You can also use ISNULL and COALESCE for null checking
Added code sample, as requested in comments
REPLACE(STR(temp.AdminTestId,5),' ','0') + '-' +
REPLACE(STR(A.UserTestId,5),' ','0') +
ISNULL('-' + REPLACE(STR(A.Sequence,2),' ','0'),'') as TestId, | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sql server"
} |
SQL server 2016/2017 in terms of better performance
Which SQL version or edition should we use out of SQL server 2017std/ent or 2016std/ent in terms of better performance gain when you are dealing with SP's (approx 1000 or more)in single database which are equipped with complex joins over tables, views, udfs and also having SORT and ORDERBY clauses in many of the SPs. Thanks | There is not much different between 2016 and 2017 especially in terms of performance (except following points). I believe, the main aim of SQL 2017 is to cover cross platform support (Windows, Linux and Docker).
1. Adaptive Query Processing
2. Automatic database tuning
Of course always newer versions would be having additional benefit in general, you need to consider other aspects while deciding on version/edition, hope this blog post would be useful | stackexchange-dba | {
"answer_score": 0,
"question_score": 0,
"tags": "sql server"
} |
Why does Solving system of quadratic equations gives extra roots?
Consider these system of Equations \begin{align*} \begin{cases} x^2+4x+4=0\\\\\\\ x^2+5x+6=0 \end{cases} \end{align*}
For solving them We have
Method 1-
Subtract both equations
So $-x-2=0$
Hence, $x=-2$
Method-2
Add both equations
$2x^2+9x+10=0$
After applying quadratic formula,we get
$x=-2$ or $x=-5/2$. But only $x=-2$ satisfies the system of equation.
Why is the $-5/2$ not satisying the system of equations,what is intuition behind the error in method 2? | **HINT**
You can factor both polynomials according to your preferred method in order to obtain:
\begin{align*} \begin{cases} x^{2} + 4x + 4 = 0\\\\\\\ x^{2} + 5x + 6 = 0 \end{cases} \Longleftrightarrow \begin{cases} (x+2)^{2} = 0\\\\\\\ (x+2)(x+3) = 0 \end{cases} \end{align*}
Can you take it from here? | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "algebra precalculus, systems of equations, quadratics"
} |
does a remote process continue if initiated from my local? What are the rules on this?
Scenario:
1. I `ssh` into remote server A from my terminal on my local computer
2. Now, logged into server A, I execute (for example):
scp -rp root@serverB:/path/to/files .
and the process begins transferring files from A to B 3\. I'm watching the progress and my computer dies.
Does the process continue on server A-B? What is the justification for this if it's the case? Are there processes that are dependent on the connection between my local and server A to continue? | No, it does not continue. Once your connection to the serverA is closed, the system terminates your shell and all processes running under them including `scp`. The rationale behind this is hygiene. You don't want to have running processes on your server, which do not belong to any active user.
You can prevent this behavior using `screen`, `tmux` or simply `nohup`, as described in many other questions. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 2,
"tags": "command line, server, ssh, crash"
} |
MySQL GROUP_CONCAT of a range of numbers
I have a table like...
year_from| year_to |...
---------|---------|----
1990 | 1993 |... -> 1990 1991 1992 1993
2000 | 2004 |... -> 2000 2001 2002 2003 2004
2003 | 2005 |... -> 2003 2004 2005
and I am trying to find out if there is a way to generate a column only with SQL in a clean way printing the rage (kind of mix between a loop and GROUP_CONCAT in nested selects), but I do not get it. This will be for a fulltext search column index from other tables, and because I have a restricted version of MySQL (5.6), actually the performance is not critical in this issue, the priority is to keep a single sql and avoid to create any procedure. Any comments are welcome! & thanks in advance | You can do it using a derived table containing all available years, something like this:
SELECT s.year_from,s.year_to,GROUP_CONCAT(t.year_col SEPARATOR ' ') as new_col
FROM(
SELECT 1990 as year_col UNION ALL SELECT 1991 UNION ALL SELECT 1992 ...--ALL THE YEARS HERE
) t
INNER JOIN YourTable s
ON(t.year between s.year_from and s.year_to)
GROUP BY s.year_from,s.year_to
Which will produce :
year_from | year_to | new_col
1990 1993 1990 1991 1992 1993
.... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "mysql, loops, range, group concat"
} |
Where in the Aruch HaShulchan He'Atid are Hilchot Sotah?
I have an Aruch HaShulchan He'Atid, as well as a normal Aruch HaShulchan, and I'm looking up something about Sotah for a Chaburah. Does anyone know where I can find Hilchot Sotah in the Aruch HaShulchan? | Hilchot Sotah is in the regular Aruch Hashulchan. It is one siman long and it is the very last siman in the Even Ha'ezer section (# 178). The siman is titled:
> דיני סוטה בזמן הבית ובזמן הזה ובו פ"ז סעיפים
>
> The laws of Sotah in the times of the temple and nowadays, and it contains 87 paragraphs.
Here is the first page. | stackexchange-judaism | {
"answer_score": 4,
"question_score": 4,
"tags": "halacha, aruch hashulchan"
} |
How to count objects with a particular day in mongodb and php
I have a date saved as a string like this `tdate:"2016-11-26 2:23:11"` in mongodb. I want to count all objects which have this date `2016-11-26`. This is how I am trying to do using `php` but have no luck.
date_authenticated has this format `"Y-m-d H:i:s"` while I want to get all objects by `day` which should have this format `"Y-m-d"`
function count_auth($tdate) {
$collection = 'mycollection';
return $this->db->{$collection}->count(array('date_authenticated' => $tdate));
} | If you have saved the date as a string you can find entries with MongoRegex like described in PHP mongo find field starts with. In your case it should be something like:
$startsWithRegex = '/^2016-11-26/';
$this->db->{$collection}->count(['date_authenticated' => array('$regex'=>new MongoRegex($startsWithRegex))]);
However I recommend you reading Find objects between two dates MongoDB as you can perform better queries if you handle dates properly. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "php, mongodb"
} |
Django Storage Backend for local development that proxies to live site?
I have to work on several projects with huge amounts of user-generated media files. In the past, I rsynced the content every couple of days, but my local development machine fills up more and more with data that is, for the most part, not needed.
I remember reading about a storage backend that would proxy local file access to the live site, but I can't for the life of me find it anymore.
BTW: I can't simply mount the media directory through ssh/smbfs, since I don't want development code to delete or damage live data :) | I went ahead and created one. Very limited ATM but it works.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "python, django"
} |
No aparece Plantilla MVC5 Visual Studio 2013
Instale el vs2013 ultimate, update 1, update 5, pack lenguaje ingles, web developper tools.... Y sigue sin aparecer la plantilla MVC cuando selecciono en C# ASP.NET

The output: `is a nice girl`
1. I didn't use dereferencing operator in my `printf` statement,
**why it is giving me the content of the array, and not the address?**
2. When I write `char*ptr=str[6]` i get `Error: cannot convert char to char*` -
**what does this error mean?**
3. Is it so that to refer to an array address we need to put `&str[6]` but we do not need to put while we do in `str+6`? If it is so, what's the logic behind it? | When you use a code such as below
char str[]="banti is a nice girl";
printf("%s",str);
then the array str is converted to a pointer to its first element of type `char *`
So the code above is equivalent to
char str[]="banti is a nice girl";
char *ptr=str;
printf("%s",ptr);
When function printf process format specifier `%s` it considers the corresponding argument as a pointer of type `char *` and outputs all characters pointed by the pointer until it meets a terminating zero.
So in this code snipped
char str[]="banti is a nice girl";
char *ptr=str + 6;
printf("%s",ptr);
You simply shift right the pointer to 6 characters and the function printf starts to output characters from `str + 6` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c++, c, arrays, pointers, printf"
} |
AWS Java API for Spot automated bidding maximum price and allocation strategy
I just realized that AWS has new Spot instance launch wizard and adding some new options like Maximum Price and Allocation Strategy options.
 that I could use to set those mentioned options. I'm using AWS SDK version 1.11.77. Any suggestion or information how to use these options through API is appreciated. | It's not the same API. This one is called spot fleet.
`aws request-spot-fleet ...`
API Reference
Note also that a fleet can be a "fleet" of just one, of course. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, amazon web services"
} |
Determine the largest size n of a problem that can be solved in time t , assuming that the algorithm to solve the problem takes f(n) microseconds.
For each function f(n) and time t in the following table, determine the largest size n of a problem that can be solved in time t , assuming that the algorithm to solve the problem takes f(n) microseconds.
$ to the time we are plotting for $f(n)$ to run we can solve for the largest input $n$ that $f$ can run on within the time limit.
$1$ second:
$log(n^2) = 1,000,000 \implies n^2 = e^{1,000,000} \implies n = e^{500,000}$
$1$ minute:
$log(n^2) = 60,000,000 \implies n^2 = e^{60,000,000} \implies n = e^{30,000,000}$
the rest can be similarly done.
P.S. make sure to floor the values of n you get from these equations because n is an integer length input. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "algorithms, data structure"
} |
Connecting a battery powered circuit to the earh ground
In the following circuit what would be the effect of tying a circuit to the ground from the -2V rail ? I know that no current would flow to the ground since there is no closed loop formed, but assuming the ground is at zero volt level, would the ground pull the -2v rail to zero and change all the node voltages in the circuit accordingly ? And does a setup like this have any usage in real life applications ?
!schematic
simulate this circuit - Schematic created using CircuitLab | In the absence of a ground, how you choose to label the nodes in the circuit is entirely arbitrary. You could use +4V and 0V (which is more conventional), or +2V and -2V, or 0V and -4V. Because you can only measure voltages _between_ two points, it's up to you to choose which point you consider to be 0V and measure relative to that.
By convention, the Earth is at 0V. So if you tie one line to ground, that will now be at 0V. Doing so has no effect on the circuit - you've just chosen which line is now considered to be 0V.
There are no real-life applications of this. | stackexchange-electronics | {
"answer_score": 3,
"question_score": 1,
"tags": "dc, earth"
} |
How to replace the txt file in a directory
There is directory A, which contains several subdirectories of txt files. There is another directory B, which contains txt files. There are several txt files in A that have the same name in B but different content. Now I want to move the txt files in B to A and cover the files with the same name. My Code is as below:
import shutil
import os
src = '/PATH/TO/B'
dst = '/PATH/TO/A'
file_list = []
for filename in os.walk(dst):
file_list.append(filename)
for root, dirs, files in os.walk(src):
for file in files:
if file in file_list:
##os.remove(dst/file[:-4] + '.txt')
shutil.move(os.path.join(src,file),os.path.join(dst,file))
But when I run this, it did nothing. Can anyone help me about it? | The following will do what you want. You need to be careful to preserve the subdirectory structure so as to avoid `FileNotFound` exceptions. Test it out in a test directory before clobbering the actual directories you want modified so you know that it does what you want.
import shutil
import os
src = 'B'
dst = 'A'
file_list = []
dst_paths = {}
for root, dirs, files in os.walk(dst):
for file in files:
full_path = os.path.join(root, file)
file_list.append(file)
dst_paths[file] = full_path
print(file_list)
print(dst_paths)
for root, dirs, files in os.walk(src):
for file in files:
if file in file_list:
b_path = os.path.join(root, file)
shutil.move(b_path,dst_paths[file]) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "python"
} |
convert (void *) to (SInt16 *) to Swift
I'm trying to convert the following from Objective-C to Swift:
-(int)fillBuffer:(void *)buffer {
SInt16* p = (SInt16 *)buffer;
// ...
p[33] = 0
}
I've come to understand that `(void *)` maps to the `UnsafeMutableRawPointer?` type in Swift.
However, I'm missing a step in converting it into something that can take the subscript operation.
So far, I've got this:
func fill(buffer: UnsafeMutableRawPointer!) -> Int {
buffer[33] = 0
}
Looking for feedback and advice. Thanks in advance! | Casting a void pointer to a typed pointer
SInt16* p = (SInt16 *)buffer;
is done in Swift with `assumingMemoryBound()`:
func fillBuffer(_ buffer: UnsafeMutableRawPointer) -> Int {
let p = buffer.assumingMemoryBound(to: Int16.self)
// ...
p[33] = 0
return 0
}
Test code:
var i16Array = Array(repeating: Int16(99), count: 40)
print(i16Array[33]) // 99
_ = fillBuffer(&i16Array) // passes a pointer to the element storage to the function
print(i16Array[33]) // 0 | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "objective c, swift"
} |
SQL query of customers by area code
I have a SQL Server database with customer information and need to run a query on the number of customers per area code. All phone numbers are U.S. phone numbers and stored as 10 digit numbers in a text field (no hyphens, parentheses or any other characters). I'm not a big whiz when it comes to writing SQL statements, so any help or guidance would be greatly appreciated. | I believe the first 3 digits in a phone number is the area code.
You can do something like
SELECT LEFT(PhoneNumber, 3) AS AreaCode
,COUNT(*) TotalNumberOfCustomer
FROM TableName
GROUP BY LEFT(PhoneNumber, 3) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, sql server"
} |
How can I get the tags for a headline in a clock report formula?
I'd like to understand how to retrieve the tags for a headline that is being processed by a clock mode report formula. Suppose I have a clock report table defined like this.
#+BEGIN: clocktable :maxlevel 2 :scope nil :formula "$3='(headline-get-tags $1)::@2$3=string(\"Tags\")"
#+END:
I can define a simple formula that returns the length of the headline, but I have yet to find an easy way to find the tags associated with the headline.
(defun headline-get-tags (headline)
"Return the tags for a headline"
(length headline))
Is there a simple way to get the tags with a headline? | Clock tables support a `:properties` option:
#+BEGIN: clocktable :properties ("ALLTAGS")
#+END:
And it turns out that tags are available by the _special_ property name `ALLTAGS`. Here are the others:
< | stackexchange-emacs | {
"answer_score": 5,
"question_score": 1,
"tags": "org mode"
} |
Extracting values starting at certain point using ArcGIS for Desktop?
I have a '2015 Temp' shapefile that tells me the temp_min and temp_max for the entire year at one site. I want to make a new file from this where I have the day where temp_min fell above 40 degrees and all the following days until the first day where temp_max is above 75. Essentially, I am trying to find the growing season for a crop. For example, March 3 was the first day it hit above 40 and July 7 was the first day it hit above 75. I want to extract March 3 - July 7.
I know I can use 'Select'. But as far as I understand it, this only gets me days where it's above 40 but not all days that follow the first day when it was above 40.
Is there a way to do this?
I am using ArcGIS 10.4 for Desktop with the Spatial Analyst extension enabled. | It looks like a perfect task for GIS, similar to this:
* Convert your records to points
* Points to line
* Draw horizontal line – growing season threshold
* Intersect 2 lines to find start and end of growing season (x coordinate of intersection points converted to days)
 is your season? You need more robust definition of season start and end. | stackexchange-gis | {
"answer_score": 1,
"question_score": 3,
"tags": "arcgis desktop, select by attribute, arcgis 10.4"
} |
remove index.php codeigniter in localhost/folder/my_codeigniter/
i have try a few solution from any source, but still cannot remove index.php if my project in other folder like : **< , all .htaaccess and configuration work fine if my project in **<
hope you can help me, thanks! | You can create a .htaccess file on your project root folder. File content like this;
RewriteEngine on
RewriteCond $1 !^(index\.php|assets)
RewriteRule ^(.*)$ /your-project/index.php/$1 [L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, codeigniter"
} |
How to get into the castle with a drawbridge?
So i stumbled upon this castle that has some sort of treasure in it. I went all the way around and cant find a way to get in. Here are some screenshots detailing the location and look

}
}
But when I put package B in some other file,then compilation fails saying not found value a
// In secondfile.scala
import A.test
package B{
class test1 extends test{
println(a)
}
}
I am running this code in intellij. what can be the reason of this? Are not the two codes same? | I think you've found a bug. I can reproduce it in Eclipse with Scala IDE `2.0.0-beta9 with Scala 2.9.0-1`. First, let's create Foo.scala:
package a
class Foo {
protected[Foo] var x = 0
}
and then Bar.scala:
package b
class Bar extends a.Foo {
println(x) // Error: Not found: value x
}
Eclipse telling us, there is an error. But after cleaning a project this error disappears. And I checked, with `scalac` everything compiles with first attempt (who would doubt).
Update:
I've opened a ticket #1000567 on Scala IDE bugtracker regarding this issue. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "scala, import, intellij idea, package, protected"
} |
correlated delete performance problems
In my Access DB (inside a C# app), I initially had this query:
DELETE
FROM ModelRule
WHERE RuleID NOT IN (SELECT RuleID FROM Rule)
With 700K rules this is intolerably slow. So I resorted to C# looping:
foreach ( DataRow row in dtRulesToPurge.Rows ) {
[pseudocode:] "DELETE FROM ModelRule WHERE RuleID = " + row["ID"];
[pseudocode:] Give user feedback/progressbar/counts
}
The `foreach` seems faster, but mainly (at least) I can give users feedback via progress bar. This approach takes minutes. The correlated subquery takes _at least minutes_ , but I always gave up and killed it before it actually finished - I suspect it takes longer.
BUT I have a little tickle in my mind that says there may be a FAST way to do these deletes via a better subquery or some kind of join, or etc, that would be far better than either of my 2 approaches above.
Would love to get your thoughts. | I prefer `NOT EXISTS`, so I would write:
DELETE FROM ModelRule
WHERE NOT EXISTS (SELECT 1
FROM Rule
WHERE ModelRule.RuleID = RULE.RuleID
);
Then for performance, you want an index on `RULE(RuleID)`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, sql, ms access"
} |
How to remove items from a list?
Here is the code I have so far:
def remove(lst: list, pos: int):
pass
def test_remove():
lst = ['Turkey',
'Stuffing',
'Cranberry sauce',
'Green bean casserole',
'Sweet potato crunch',
'Pumpkin pie']
remove(lst, 2)
assert lst == ['Turkey',
'Stuffing',
'Green bean casserole',
'Sweet potato crunch',
'Pumpkin pie',
None]
lst = [5, 10, 15]
remove(lst, 0)
assert lst == [10, 15, None]
lst = [5]
remove(lst, 0)
assert lst == [None]
if __name__ == "__main__":
test_remove()
Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.
Any ideas on where I should start? | > Write code in remove() to remove the item in slot pos, shifting the items beyond it to close the gap, and leaving the value None in the last slot.
You can use the `pop` method of `list` to remove the item and then append `None` to the list.
def remove(lst: list, pos: int):
lst.pop(pos)
lst.append(None) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, list, testing, items"
} |
Call to a member function bind_param() on a non-object in? so what i will do?
$employee_stmt=$con->prepare("INSET INTO employee (emp_name, emp_desig, emp_salary, years_exp, emp_status, emp_adr, city, pin_code, emp_phone, emp_email, emergency_contact, emergency_phone, blood_group, known_health_issue)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
$employee_stmt->bind_param('ssssssssssssss',$_POST['employee_name'],$_POST['designation'],$_POST['salary'],$_POST['exp'],$_POST['emp_status'],$_POST['address'],$_POST['city'],$_POST['pin'],$_POST['phone'],$_POST['emp_email'],$_POST['emr_contact'],$_POST['emr_phone'],$_POST['blood_group'],$_POST['health_issue']); | Looks like your statement can not be prepared. You should check SQL for errors. (For example in post `INSET` used instead of `INSERT`). | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql"
} |
Is there any way to execute docker push command from the dockerfile itself?
I tried running docker push command from the docker file but it throw an error
The command returned a non-zero code: 127 | No there isn't. Dockerfile is an image build description format, it is not a general purpose scripting language.
Write a wrapper script if you need to do something that requires a scripting language. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -3,
"tags": "docker, artifactory"
} |
Excel: count numbers greater than 3 in strings in range of cells
I have a spreadsheet tracking games of fifa 15 between me and my friend. We track goal scorers for each game in this format
Messi(2), Neymar, Suarez(4)
Goal scorers are recorded every game My goal is to count the number of hattricks scored total. In this particular game Suarez scored a hattrick since he score more than 3 goals. I am looking for a formula, any help is welcome. Thank you | Well if the cells are formatted exactly as shown, you could try:-
=SUM(LEN(A2:A4)-LEN(SUBSTITUTE(A2:A4,{"(3)","(4)","(5)","(6)"},"")))/3
where you would need to adjust the range A2:A4 to suit your data.
This assumes that even Messi is unlikely to score more than 6 goals in one match and if he did score 6 goals it would still count as one hat-trick.
It has to be entered as an array formula using ` Ctrl `` Shift `` Enter `
!enter image description here | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "string, excel, count"
} |
Rake preconfiguration?
How do I do this in the Ruby-way?
# Rakefile
desc "Run task on server #1"
task :one do
# Do somethin on server 1
Srv1.exec "..."
end
desc "Run task on server #2"
task :two do
# Do somethin on server 2
Srv2.exec "..."
end
desc "Run task on both servers"
task :both do
# Do somethin on both servers
Serv1.exec "..."
Serv2.exec "..."
end
How do I require the end execution configuration code? How do I do scaling (if I need Serv3)? Should `Serv1` be a class or something else?
What I need to do is to control a Vagrant VM with Rake, run custom tasks inside Vagrant, synchronize data with the host system, run some code on production and send the result to Vagrant, etc. | At first, I'll fix a minor correction for your model. Do the `both` task with more simple method:
desc "Run task on both servers"
task :both => [ :one, :two ]
> How do I require the end execution configuration code? How do I do scaling (if I need Serv3)? Should Serv1 be a class or something else?
Just create a class `Serv`, and pass to it a number of server or something else. So you'll get:
desc "Run task on a server"
task :one do
# Do somethin on a server
Serv.new( ENV[ 'SERVER_NUMBER' ] ).exec "..."
end
desc "Run task on all servers"
task :one do
# Do somethin on all servers
Serv.exec "..."
end | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby, rake"
} |
On accident- part of speech
Is 'on' still a preposition in the phrase 'on accident', or 'on purpose'? I have noticed Americans say 'on accident', where I would say 'by accident'. | > Is on still a preposition in the phrase on accident, or on purpose? I have noticed Americans say on accident, where I would say by accident.
Yes, it is still a preposition. It's just the wrong preposition!
I can find one example in print, i.e.
You're Not Here on Accident. You're Here on Assignment!
However that seems to be a form of wordplay. Where have you seen or heard the phrase 'on accident' being used. Did you hear it in everyday conversation? In what kind of sentence? | stackexchange-english | {
"answer_score": 2,
"question_score": 2,
"tags": "grammar"
} |
How can you access icons from a Multi-Icon (.ico) file using index in C#
I want to use the **4th image** from the ico file : `C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033\VS2008ImageLibrary\VS2008ImageLibrary\Objects\ico_format\WinVista\Hard_Drive.ico`
If I see this icon using Windows Photo Viewer, shows me 13 different icons.
I have dumped this ico in a resource file, how can I retreive the required icon using index. | In WPF, you can do something like this:
Stream iconStream = new FileStream ( @"C:\yourfilename.ico", FileMode.Open );
IconBitmapDecoder decoder = new IconBitmapDecoder (
iconStream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.None );
// loop through images inside the file
foreach ( var item in decoder.Frames )
{
//Do whatever you want to do with the single images inside the file
this.panel.Children.Add ( new Image () { Source = item } );
}
// or just get exactly the 4th image:
var frame = decoder.Frames[3];
// save file as PNG
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(frame);
using ( Stream saveStream = new FileStream ( @"C:\target.png", FileMode.Create ))
{
encoder.Save( saveStream );
} | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 8,
"tags": "c#, indexing, icons"
} |
Removing an item from a generic Dictionary?
I have this:
public static void Remove<T>(string controlID) where T: new()
{
Logger.InfoFormat("Removing control {0}", controlID);
T states = RadControlStates.GetStates<T>();
//Not correct.
(states as SerializableDictionary<string, object>).Remove(controlID);
RadControlStates.SetStates<T>(states);
}
states will always be a SerializableDictionary with string keys. The values' type vary. Is there a way to express this? Casting to `SerializableDictioanry<string, object>` always yields null. | You can use the non-generic dictionary interface for this:
(states as IDictionary).Remove(controlID); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "c#, refactoring, templating"
} |
Averages and differences
A student asked me a question that I couldn't answer, and I said I'd find out.
I set a problem which was, given a set of numbers, was the mean over 50 where the numbers are: 56, 42, 47, 59 and 48
The mean is 50.4. A student asked why it wasn't 52, and I was confused. they said they had added up the differences between 50 and the five numbers (so 50-42 = 8, 50-47=3, 48-50=2, 2+3+8=13 then 56-50=6, 59-50=9, 9+6=15) then as the difference is 2 (15-13=2) it should be 52.
This got me thinking that it was quite a clever way to work things out, and I get a feeling that something like this _should_ work, but I can't explain why it doesn't (apart from the glib answer that "you don't do means like that" - I don't want to crush his enquiring mind!).
Thanks in advance.
Marc | The difference between each value and the mean sums to $2$, yes, but to find the mean you sum the values and divide by the count of the values -- here, that's $5$. So the difference has to be divided by $5$ as well before it can be added, and $2/5=0.4$. | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "average"
} |
Order List Using Caml Query in a text field as a number on SP 2010
How can I order a Column where the type is text, but all the values stored are numeric,
I want to order it descending but considering the Column a Numeric field without changing the column type
Thank you | So This was my solution :
I created a Calculated column based on the original column with output type as numeric
There was a problem though. the calculated column at the beginning was returning the result as text too.
To fix this issue I had to do the following :
> 1.- ad a +"0" to the formula
I don't know how or why this worked, but doing this it transformed all the items into numeric. | stackexchange-sharepoint | {
"answer_score": 0,
"question_score": 0,
"tags": "2010, caml query, ssom"
} |
What's the current through the 2Ω resistance? The question requires me to find the answer by using Thevenin's theorem
This is the circuit. I have found Thevenin equivalent resistance to be 5 ohm. Is that correct? I am not able to find the Thevenin equivalent voltage across the load resistance.
||(6+4)] = 5 ohm | As a hint, consider that your circuit behaves exactly the same as this one:
!schematic
simulate this circuit - Schematic created using CircuitLab
Now you should be able to see how you can apply Thevenin's theorem (two times) to simplify this circuit to the point where you'll be able to find the current through R5 by inspection. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 1,
"tags": "thevenin"
} |
How many days the verification could take?
I first time bought a smaller piece of bitcoin and wanted to do some shopping from that, but I still my wallet contains only not confirmed bitcoins.
My questions are:
1. Why the confirmation takes so long?
2. I saw a page that shows the total count of unconfirmed transactions, its increasing, not decreasing - could it mean that my transaction will never be confirmed?
3. How does the confirmation work?
Thanks! | Because you have paid a lower fee than others, so your transaction is put last. Your coins will return to your wallet, but can take up to 4-6 days before that happens. Hope it helps you. | stackexchange-bitcoin | {
"answer_score": 0,
"question_score": 0,
"tags": "transactions, confirmations"
} |
change default email client for xubuntu 18.04
My "Settings/Preferred Application" is set to Evolution, yet when there is an email link in a web page Thunderbird is activated. I did some Internet research but could not find solution. I do not have 'Activities/Details' menu or similar. This is xubuntu 18.04 with Firefox as web browser and Evolution as email client. I abandoned Thunderbird because Lightning started to loose home calendar and I had to remove and re-install Lightning. Fortunately, my calendar entries were still there. | Change the preference in Firefox. type `about:preferences` in the address bar and scroll down. Then type `mail` in the box.
` you will get a dropdown menu with other choices. Hopefully Evolution will be one of the choices. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 2,
"tags": "email client"
} |
How to check if LeftClick is pressed C#
I need to check if a user has left click being held anyone know how I would need to accomplish this?
I already tried messing around with System.Windows.Input but I couldn't figure it out
This is a windows forms app but I need it to work outside of the form I prefer a simpler answer | Alot of useful answers on Stack overflow. Try this >> c# Detect mouse clicks anywhere (Inside and Outside the Form)
This should allow you to detect left clicks in or outside your program. If you want an event for a control in your form, try the .Click event. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, winforms"
} |
wxHaskell not find module `Distribution.Compat.Exception'
I am trying install wxhaskell on ubuntu (and I have already installed wxwidget and it works well in codeblock)
I run `cabal install wxc` in terminal
and here is output
/tmp/wxc-0.92.1.1-2711/wxc-0.92.1.1/Setup.hs:25:8:
Could not find module Distribution.Compat.Exception
It is a member of the hidden package Cabal-1.22.5.0.
it is a hidden module in the package Cabal-1.16.0
Use -v to see a list of the files searched for.
Failed to install wxc-0.92.1.1
cabal: Error: some packages failed to install:
wxc-0.92.1.1 failed during the configure step. The exception was:
ExitFailure 1
actually, I can find `Distribution.Compat.Exception` and I tried `sudo ghc-pkg expose Cabal-1.16.0`
`sudo ghc-pkg expose Cabal-1.22.5.0` but nothing changed
someone help me out, great thanks! | If you are using ubuntu I think I have a solution. If you install GHC in ubuntu via "apt-get install ghc", all ghc packages are installed in /usr/lib/ghc/xyz. If you have installed ghc manually, not with a package manager, I don't know a solution.
Try this:
sudo cabal install cabal-install --global
Then do all the wxHaskell specific cabal installs the same way. So:
sudo cabal install wxdirect --global
sudo cabal install wxc --global
...
If this doesn't work, try this:
rm -rf ~/.ghc | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "cabal, cabal install, wxhaskell"
} |
Create a double value from two separate variables C#
I have two seperate variables x and y of Integer types
Lets say x = 123 and y = 456. I want to create a double using these two variables such that result = 123.456.
How do i get this? | public static double Combine(int x, int y)
{
if (x < 0 || y < 0) throw new NotSupportedException(); // need to specify
// how it should behave when x or y is below 0
if (y == 0) return x;
var fractionMultipler = (int)Math.Floor(Math.Log10(y)) + 1;
var divider = Math.Pow(10, fractionMultipler);
return x + (y / divider);
}
Sample:
var z = Combine(30, 11123); // result 30.11123 | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "c#, math, logic"
} |
Using Tcl to create a filtered list from an existing list using a pattern in Tcl
My goal is to take a an existing list and then create a filter list based on a specific pattern. I do not want to use a for loop or while loop.
Example of what I want
set existing_list [list "color_blue12312" "color_blue32311" "color_green123j11" "color_green234321" "color_purple213123" "color_purple234234234"]
set purple_list [lsearch existing_list color_purple*]
puts $purple_list
This should print in the terminal:
color_purple213123 color_purple234234234 | You're looking for the `-all` (Returns all matches) and `-inline` (Returns the matched element(s), not indices) options to `lsearch`:
set existing_list {color_blue12312 color_blue32311 color_green123j11
color_green234321 color_purple213123 color_purple234234234}
set purple_list [lsearch -all -inline $existing_list color_purple*]
puts $purple_list | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "tcl"
} |
Solve the following linear congruences
For any integers $a, b$, let $N_{a,b}$ denote the number of positive integers $x<1000$ satisfying $x\equiv a\pmod{27}$ and $x\equiv b\pmod{37}$. Then find $N_{a,b}$.
**progress:** $x\equiv a\pmod{27}$ and $x\equiv b\pmod{37}$ implies
$x=27m+a$ and $x=37n+b$ for some integers $m,n$. For common sosultion, $27m+a=37n+b\implies 27m-37n=b-a$. Now $\gcd(27,37)=1$ sow there exists integers $u,v$ such that $27u+37v=1$.
Is it possible to solve using this relation ?
Thank u in advance | The numbers $u$ and $v$ can be found with the extended euclidean algorithm
$37=27\times 1+10$
$27=2\times 10+7$
$10=7\times 1+3$
$7=3\times 2+1$
Giving $1=7-3\times 2=7-(10-7)\times 2=3\times 7-2\times 10=3(27-2\times 10)-2\times 10=3\times 27-8\times 10=3\times 27-8\times (37-27)=11\times 27-8\times 37$
This gives the inverses : $27^{-1}=11 \pmod{37}$ and $37^{-1}=-8=19 \pmod {27}$
Now, the number $u=19\times 37\times a+11\times 27\times b$ satisfies $u\equiv a\pmod {27}$ and $u\equiv b\pmod{37}$. Taking $u$ modulo $27\times 37=999$ gives the smallest solution. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "number theory, congruences"
} |
How to ask user for keys in dictionary, and if it is in dictionary, display the values
how to display key(integers)in dictionary when user enters key(integers)
string = input("Please enter a name> ")
def enumerate_string(string):
s = {}
for i,letter in enumerate(string):
s[i] = letter
x = enumerate_string(string)
string2 = input("enter several integers separated by a comma ")
string3 = string2.split(',')
if string3 in set(x):
print(x[string3]) | I am updating part of your code:
string2 = input("enter several integers separated by a comma ") # 0,1,2
string3 = string2.split(',') # string3 is a list of numbers but as strings
# ['0','1','2']
string3=[int(num) for num in string3] # [0,1,2]
for num in string3:
print(x.get(num))# will return the value corresponding to the key | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
Python: Pass or Sleep for long running processes?
I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like:
while True:
pass
or
while True:
time.sleep(1)
Which one will have the least impact on a system? What is the preferred way to do nothing, but keep a python app running? | I would imagine _time.sleep()_ will have less overhead on the system. Using _pass_ will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended.
**EDIT** : just to prove the point, if you launch the python interpreter and run this:
>>> while True:
... pass
...
You can watch Python start eating up 90-100% CPU instantly, versus:
>>> import time
>>> while True:
... time.sleep(1)
...
Which barely even registers on the Activity Monitor (using OS X here but it should be the same for every platform). | stackexchange-stackoverflow | {
"answer_score": 88,
"question_score": 61,
"tags": "python"
} |
Schlafli symbol determining number of faces
Schlafli symbols are used to describe polytopes, but can also be used to describe more general objects through the use of flags. In particular, some information can be readily 'read-off' from a Schlafli symbol (like the number of edges in a face).
I was wondering how the number of faces in a volume is encoded in a Schlafli symbol. For example, we know that
a tetrahedron $\\{3,3\\}$ has $4$ faces,
an octahedron $\\{3,4\\}$ has $8$ faces,
a cube $\\{4,3\\}$ has $6$ faces,
and an icosahedron $\\{3,5\\}$ has $20$ faces.
Without considering the interior angles, is there a way to read off this face information from the Schlafli symbol by considering flag orbits?
Thanks! | This has nothing to do with flag orbits, but if you just want to count faces (and, while we're at it, vertices and edges) ...
Let a $\\{p,q\\}$-hedron) have $f$ faces (each a regular $p$-gon), $v$ vertices (each of degree $q$), and $e$ edges. Then $pf$ counts each edge twice, as does $qv$: $$pf = 2e= qv \tag{1}$$ Moreover, Euler's polyhedron formula tells us $$v-e+f=2 \tag{2}$$ So, we have three equations in three unknowns, which we can readily solve:
> $$v = \frac{4 p}{2(p+q) - p q} \qquad e = \frac{2 p q}{2(p+q)-p q} \qquad f = \frac{4 q}{2(p+q) - p q} \tag{$\star$}$$
* * *
As for gleaning more information from Schläfli symbols, this question mentions a formula for the dihedral angle of a $\\{p,q\\}$-hedron: $$\sin\frac{\theta}{2} = \frac{\cos(\pi/q)}{\sin(\pi/p)}$$ My answer gives the extension for the dichoral angle of a $\\{p,q,r\\}$-tope. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "combinatorics, geometry, polygons, tiling"
} |
Using Ito's Lemma to derive $\int^{T}_0 W_tdW_t =\frac{1}{2} W_{T}^2-\frac{1}{2} T$ where $W_t$ is brownian motion and $W_t=0$
Using Ito's Lemma, derive $$\int^{T}_0 W_tdW_t =\frac{1}{2} W_{T}^2-\frac{1}{2} T$$ where $W_t$ is brownian motion and $W_t=0$
* * *
**Appreciate a hint ; dont know where to start.**
* * * | Hint: try applying Ito's lemma to $X_t=f(t,W_t)$ for $f(t,x)=\frac{1}{2}x^2$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "brownian motion"
} |
Foreign key in same table, unable to get right query
I've got a very simple table that looks something like this. Iet's call the table 'family' the columns are ID, name, age and parent so:
ID Name Age Parent
------------------------------
1 Bob 50 NULL
2 Matt 20 1
3 Rick 18 1
ID is the primary key and Parent is a foreign key referencing ID What I'm trying to do is to list every parents ID and name. My current query looks like this:
Select ID, Name
from family
where ID = Parent;
But this is comes up with no results. How is my query incorrect? Shouldn't it show all records for all the parent ID's found? Thanks! The result that I am looking for would look like this:
ID Name
--------------
1 Bob
And if the table was larger and had multiple parents, they would of course be listed in the result as well. | Your query attempt does not compare rows against each other, this is (posssibly) the simplest:
SELECT ID, Name
FROM family
WHERE ID IN (SELECT Parent FROM family)
;
This alternative MIGHT be faster:
SELECT DISTINCT p.ID, p.Name
FROM family AS p
INNER JOIN family AS c ON p.ID = c.Parent
; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql, foreign keys"
} |
Error while calling a phone number from iPhone app
I am using following code to make a phone call from my iPhone app:
NSURL *myPhone1 = [NSURL URLWithString:@"14165551212"];
[myPhone1 scheme:@"tel://"];
NSURLRequest *myPhoneReq = [[NSURLRequest alloc ] requestWithURL:myPhone1];
NSURLConnection *myCon = [[NSURLConnection alloc] initWithRequest:myPhoneReq delegate:self];
but getting following error: 'NSInvalidArgumentException', reason: '-[NSURL scheme:]: unrecognized selector sent to instance 0x6a10ba0
Any idea how to achieve this? | [[UIApplication sharedApplication]
openURL:[NSURL URLWithString:@"tel: 14165551212"]];
will not work in simulator | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "iphone"
} |
Path of linux home in spring mvc property file
I have deployed a java web application to the tomcat in Linux server. The application used to save and retrieve files like images, xls files etc. I have specified the path in the property file of java application. Unfortunately the application is not storing the files on the location which i have given in property files. Can someone help me to correct the property file ?
base_path=\\home\\TestAppUploads\\
sectionImagePath=SectionImages
questionImages=QuestionImages
answerDescrImages=AnswerDescrImages
optionImages=OptionImages
userImages=UserImages
announcementImages=AnnouncementImages | This is just my first tought: have you tried the normal slash? Because linux uses different slashes in path.
For example: **_base_path** =/home/testinguser_
I know this is a property file but if you want to handle this kind of problem inside your Java code you might want to use **_File.separator_**
But it would be helpfull if you could paste here the error log | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "java, linux, spring, spring mvc, tomcat"
} |
Is there a geometric interpretation of the exponential function of real numbers?
I can visualize the exponential function with the graph $y = e^x$, but I can do that for almost any function.
In addition to its graph, the function $f(x) = x^n$ can be visualized as the volume of a box with sides of length $x$ in n-dimensional space, and the trigonometric functions can be interpreted as side lengths of certain right triangles.
Is there a similar geometric interpretation of the exponential function? | There's a geometric interpretation of the natural log. From the definition
$$ \log x = \int_1^x {1 \over t} \: dt $$
we see that the area between the "standard" hyperbola $xy = 1$ and the horizontal axis between $1$ and $x$ is $\log x$.
So, turning this around, the line $x = e^t$ is the vertical line such that the area between $x = 1$ and $x = e^t$, between this hyperbola and the $x$-axis, is $t$. | stackexchange-math | {
"answer_score": 5,
"question_score": 11,
"tags": "real analysis, geometry, visualization"
} |
complexity of calling a function with a for loop
Im quite new to computational complexity, but i know that a nested for loop will give O(n^2). in my case i have a for loop that calls a function which has a for loop within it. will the complexity be O(n) or worse?
public static void main(String[] args) {
for(int i = 0; i < 10; i++){
if(i != 0){
System.out.println();
printt(i);
}
}
}
public static void printt(int i){
for(int j = 0; j <= 10; j++ ){
if(j !=0 ){
System.out.print(j*i+" ");
}
}
}
} | Think of the number of print statements(the second one itc) that are executed if you run this snippet of code.
The easiest way to reason about this is to go ahead and run the program, and you will notice that you have **81** values being printed out, which tells you that you have 9 calls to the nested function for each run of the outer loop (9 time again). So it ends up being _O(n^2)_. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "time complexity, big o"
} |
How can I add multiple numbers to a variable
I'm trying to use `+=` to add multiple numbers to a variable.
I'm trying to do something like this: `score += var1, var2, var3`
However, the only thing I know how to do now is
score += p;
score += v;
score += t; | You can simply do:
score += var1 + var2 + var3; | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "c++, variables, variable assignment, compound assignment"
} |
Why can't the Lost Boys fly?
In Peter Pan, all you need to do to fly is think of a wonderful thought, any happy little thought. All it takes is faith and trust ohh and there's dust. Pixie dust.
Why then can't the Lost Boys fly? They have fun all day and they are around TinkerBell enough to get plenty of pixie dust... do they just choose not to fly? | They can (and do) in the broadway version -- the penultimate scene has them arrive in the window at the Darling residence for a rousing chorus of "I _will_ grow up." Since the only way to and from Neverland is flight, it would follow that they were able to fly.
For that matter, they are fully capable in **Hook** as well, provided that they obtain the magical dust. Recall the finding of marbles in one of the final scenes -- fairy dust was included in the bag which lead to a rather elderly lost "boy" taking flight.
My guess is that it is a supply issue. Tinkerbell and her folk are simply unable to provide sufficient dust to lift the entire group off of the ground continuously, so the material is rationed. Peter's special relationship with Tinkerbell specifically likely keeps him in constant supply, but the others do not have this boon. | stackexchange-scifi | {
"answer_score": 12,
"question_score": 12,
"tags": "peter pan, j m barrie"
} |
Bind a method of an object to an event of an element
I want to bind a method of an object to an event of an element. For example:
function ABC()
{
this.events_list = function() {
}
this.events_list.clickElement = function() {
alert("hello world");
}
this.bindEvents() = function() {
$("#element").click(this.events_list.clickElement);
}
}
var _abc = ABC();
_abc.bindEvents();
The above code is not binding the click event to `clickElement` method. | Does `#element` exist before you call `_abc.bindEvents()`. You can wrap it all in
$(document).ready(function() {
var _abc = ABC();
_abc.bindEvents();
});
function ABC()
{
this.events_list = function() {
}
this.events_list.clickElement = function() {
alert("hello world");
}
this.bindEvents() = function() {
$("#element").click(this.events_list.clickElement);
}
}
Will need to see more of your use case to do more. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "javascript, jquery, jquery events"
} |
Why are we trying to keep trees balanced
I see many questions that are talking about balanced tree.
For instance R-Tree are better than KD-Tree as they are balanced.
What is the advantage of using a balanced tree over a non-balanced tree? | Searching this tree
O
\
O
\
O
\
O
\
O
\
O
\
O
Is going to take Θ(N) time. Searching this tree
O
/ \
O O
/ \ / \
O O O O
Is going to take Θ(logN) time. Since search time is proportional to the height of the tree. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 2,
"tags": "algorithm, tree"
} |
invalid arithmetic operatior
I am trying to multiply a integer value with a decimal `value = 2*1.5`. but how it gives me this **error** ,`"invalid arithmetic operator"`.
I researched online and most of the solution provided is just to add that | bc behind the decimal value but however I tried it and it still doesn't work,
results=$((2*"1.5"|bc))
echo $results | try this
results=`bc <<< "scale=2; 2*1.5"`
echo $results
here scale=2 means it will consider 2 decimal places
Please don't forget "`" tilde sign which is important above | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "bash, shell"
} |
A standard Unix command-line tool for piping to a socket
I have some applications, and standard Unix tools sending their output to named-pipes in Solaris, however named pipes can only be read from the local storage (on Solaris), so I can't access them from over the network or place the pipes on an NFS storage for networked access to their output.
Which got me wondering if there was an analogous way to forward the output of command-line tools directly to sockets, say something like:
mksocket mysocket:12345
vmstat 1 > mysocket 2>&1 | Netcat is great for this. Here's a page with some common examples.
Usage for your case might look something like this:
1. Server listens for a connection, then sends output to it:
`server$ my_script | nc -l 7777`
2. Remote client connects to `server` on port 7777, receives data, saves to a log file:
`client$ nc server 7777 >> /var/log/archive` | stackexchange-stackoverflow | {
"answer_score": 28,
"question_score": 24,
"tags": "unix, sockets, command line, named pipes"
} |
How can I identify what node my python program is running on?
My research lab has access to 24 nodes from my schools cluster. Sometimes my programs run significantly faster then other times and I want to try to diagnose the problem by finding out what nodes they are running on to see if some are slower then others. What is the best method, using python, to have my output file also tell me what node the program was computed on? | Use the `Platform` module. Integrate a couple simple functions in your `Node()` class
import platform
class Node(object):
...
def get_device_os():
""" Get the devices operating system. """
return platform.system()
def get_device_name():
""" Get the devices name. """
return platform.node() | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, python 2.7"
} |
Rails 4 relation tables
Hello I am attempting to add categories to my posts and I am a little confused on how to set up the relation for this one.
Should a post have_many categories or should a category have_many posts?
Ideally what I want to do is have one table that I seed with particular categories which in my head is a table with id's and a simple alias column for each category name.
When making a post I want a select with all the categories in place and just assign a value. So if I picked value = 1 it should probably place the "1" into the categories_id column which gets referenced and I know that 1 = Some category.
Maybe? | In your case,it should be **`categories has_many posts`** and **`post belongs to category`**
Class Category < ActiveRecord::Base
has_many :posts, dependent: :destroy
end
Class Post < ActiveRecord::Base
belongs_to :category
end
By giving this,you should be having a **`category_id(Foreign key)`** in your posts table.
So when you are creating a post,you can able to select categories through a **`collection_select`** or **`select`**.
Hope it helps! | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ruby on rails, activerecord, relational database, foreign key relationship"
} |
Apache NIFI Faild to bind to xxx
I try to start my nifi server with toolkit, when I set the "nifi.properties" https-host be 127.0.0.1 my server can start, and I use "jps" can see the nifi is on running, meanwhile the log file shows nifi is running, but I can't through my cloud server ip+port to visited nifi.
When I change the config of "https-host" to be my public IP adress, the log shows faild to bind the IP. Did somebody have same problem with me.
error info | The reason is that to make the NiFi instance available through the Public IP, change the property of 127.0.0.1 to 0.0.0.0 and then restart NiFi. After restarting NiFi, try browsing to the public IP address. Another option is to replace the 127.0.0.1 with the public IP address of the host and then restart NiFi. After restarting NiFi, try browsing to the public IP address. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, apache nifi"
} |
Adding Strings to List with the number of a certain letter in them increasing
So I have two int's `v` and `w`, a string `q`, and a list `list`. I need to make it so that `list` adds a string with a duplication of `q`, ranging from `v` through `w`.
For example: v is 2, w is 4, q is "a". list should be [aa, aaa, aaaa] by the time the program is done.
I have done various programs similar to this, and I felt like this would be easy, and I still think it is but for some reason I am missing something. I have attempted to solve this by doing
for (int j = v; j <= w; j++) {
String s = "";
for (int k = 0; k < j ; k++) {
s+=q;
}
list.add(s);
}
But that just gives a constant number of Qs. Not changing. | First, prefer `StringBuilder` to `String` concatenation (that _pollutes_ the `intern` cache for one). And you need to begin by looping `v` times to create your initial `String`; then append `q`. Something like
int v = 2;
int w = 4;
String q = "a";
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < v; i++) {
sb.append(q);
}
for (int j = v; j <= w; j++) {
list.add(sb.toString());
sb.append(q);
}
System.out.println(list);
Output is (as requested)
[aa, aaa, aaaa] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "java, loops, arraylist"
} |
GD commands display raw image text instead of an image
Hey i was trying to learn the GD library and i can't get my code to work, it displays raw image text instead of the actual PNG i want to display. I have Png Support enabled in the GD section by the way.
Code is very simple:
`<?php $picture = imagecreatefrompng("test.png"); imagepng($picture); ?>`
but the result comes down to something like this:
PNG IHDR.b pHYs+ IDATx etc. | You have to tell the Browser, that it is image data.
Add
header("Content-type:image/png");
So it should be:
<?php
header("Content-type:image/png");
$picture = imagecreatefrompng("test.png");
imagepng($picture);
?>
For more information and other image type you can look here PHP, display image with Header() | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, gd"
} |
Group By and HAVING along with Distinct
I have ItemDetails table that has item and vendor information. There are duplicate records for item-vendor association – that is okay in my scenario.
Now, I need to find out items for which more than one distinct vendors exists. What are the SQL queries for this? I am looking for multiple approaches for this.
The following query is not correct. It is listing both ‘A1’ and ‘A2’. The correct query should return ‘A2’ only.
SELECT Item FROM @ItemDetails
GROUP BY Item
HAVING COUNT(*) > 1
**TABLE**
DECLARE @ItemDetails TABLE (MyPrimaryKey INT, Item VARCHAR(5), VendorID VARCHAR(5))
INSERT INTO @ItemDetails VALUES (1, 'A1', 'V1')
INSERT INTO @ItemDetails VALUES (2, 'A1', 'V1')
INSERT INTO @ItemDetails VALUES (2, 'A2', 'V1')
INSERT INTO @ItemDetails VALUES (2, 'A2', 'V2') | The idea is to gather items which produced by single vendor and after that filter out other
select a.item
from ItemDetails as a
where a.item not in (
select b.item
from ItemDetails as b
group by b.Item, b.VendorId
having count(*) = 1
)
but after one minute I found the easiest way
select item
from ItemDetails
group by Item
having count(distinct VendorId) > 1 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sql server"
} |
How to get database credentials into a c# application without committing it to source code?
I've got a beginners question that's hopefully easy, but I can't seem to find a straightforward answer, and I can imagine there's dozens of ways to accomplish this.
I have a c# application that connects to a database using SQL authentication (so I can't use trusted AD connection) and I've got a hard-coded connection string with the password in the source code. Unfortunately, I want to commit this source code to git version control, but I do not want the password in the source code.
What's the standard way to resolve this issue? Should I create a config file that's required to be read at runtime? Is there anyway to have this compiled down into the binary so I can distribute it without end-users needing the database credentials?
Thanks | you should never store passwords or other sensitive data in source code, and you shouldn't use production secrets in development and test mode.
Best Approach will be storing sensitive info in environment variables.check this link
Other option save it into external file with extension .config as iis will ignore this file also exclude this file from source tree.check this link | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "c#, git"
} |
Can your previous employer force you to help them with something?
I got an aggressive call from my former manager, and he wants me to tell them how to fix something. The problem is that I don't remember and I no longer work for them, so can he sue me for not helping them? Do I even have any obligation towards my former employer even if I could help? It sounds ridiculous and I've experienced seen something like this before. Assume that this takes place in the U.S. or Canada. | It is not uncommon for an employer to ask a former employee to assist with something as a courtesy, and sometimes the former employee will choose to do so. If it requires more than a small amount of time, this may be done under a short-term consulting contract for pay.
But unless there was a contract of employment requiring such post-employment advice, there is no **legal** obligation for the former employee to provide such assistance. The most the former employer could do is give a poor reference if asked by potential future employers, and most large corporate employers now only give job title, salary range, and dates of employment to avoid claims of incorrect or defamatory statements in such references. | stackexchange-law | {
"answer_score": 8,
"question_score": 1,
"tags": "united states, canada, harassment, labor"
} |
Boolean expression with numpy arrays
Basically i am trying out boolean expressions with numpy arrays , for example something like this:
import numpy as np
a = np.array([1,0,1])
b = np.array([0,1,1])
c = np.array([1,0,1])
if (a ==b) or (a==c):
d = [2,5,5]
else : d = [1,5,5]
print d
This returns an error
**ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()**
What would be the correct way to code this? | the condition should read:
if (a==b).all() or (a==c).all():
see this question | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "python, arrays, numpy, boolean expression"
} |
Get a pointer pointer for a smart pointer
I have a smart pointer for an object, that I need to pass to a method, that only accepts a pointer pointer.
Here's an example, where the original smart pointer loses the ownership.
int main(int argc, char* argv[])
{
std::unique_pointer<pcap_if_t> object;
auto object_pointer = object.get();
pcap_findalldevs(&object_pointer, ...); // The unique_ptr loses ownership after being passed to the function
}
How would I accomplish this, without the original smart pointer losing the pointer ownership?
**EDIT:**
The function I'm calling is _pcap_findalldevs_ in libpcap. I'm afraid that the function might be the cause of losing ownership.
I have updated my code example to reflect the what I actually do. | Function which takes pointer to pointer usually does so because it might change it, and `pcap_findalldevs` is indeed does that. And that pointer should be released with call to `pcap_freealldevs`.
So your best bet is `unique_ptr` with custom deleter aquiring ownership from raw pointer:
struct pcap_deleter
{
void operator()(pcap_if_t* ptr)
{
pcap_freealldevs(ptr);
}
};
//...
using pcap_ptr = std::unique_ptr<pcap_if_t, pcap_deleter>
pcap_ptr get_devs() {
pcap_if_t* object_pointer;
pcap_findalldevs(&object_pointer, ...);
return pcap_ptr(object_pointer);
}
//...
auto object = get_devs(); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 5,
"tags": "c++, pointers, smart pointers, unique ptr"
} |
Bind Checkboxes to int array/enumerable in MVC
@Html.CheckBox("orderNumbers", new { value = 1 })
@Html.CheckBox("orderNumbers", new { value = 2 })
@Html.CheckBox("orderNumbers", new { value = 3 })
@Html.CheckBox("orderNumbers", new { value = 4 })
@Html.CheckBox("orderNumbers", new { value = 5 })
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }
If I use the first signature in my action method, I get an empty `IEnumerable`.
If I use the second signature I do receive the values but I also receive a false value for the unselected values (because of MVCs pattern of shadowing all checkboxes with a hidden field).
e.g. I will receive something like `orderNumbers = { "1", "2", "false", "4", "false" }`
Why can't I just get the list of numbers? | Because thats how the provided `CheckBoxFor` helper is working.
You have to generate the html for the checkboxes yourself. Then the hidden inputs are not generated and you will get only the selected integer values. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 19,
"tags": "asp.net mvc 3, int, ienumerable, checkbox, model binding"
} |
Reading from a file in C# without the newline character
i want to read from a text file in C#. But I want all the lines in the file to be concatenated into one line.
for example if i have in the file as
ABCD
EFGH
I need to read ABCDEFGH as one line.
I can do this by reading one line at a time from the file and concatenating that line to a string in a loop. But are there any faster method to do this? | string.Join(" ", File.ReadAllLines("path"));
Replace " " with "" or any other alternative "line-separator"
**Example file:**
> some line
>
> some other line
>
> and yet another one
_With " " as separator:_ some line some other line and yet another one
_With "" as separator:_ some linesome other lineand yet another one | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "c#, file"
} |
Replace all spaces between certain characters with regex
I want to replace all spaces with certain words with the help of regex
from
<h3>Chinese Fan Palms</h3>
to
<h3>ChinesehoneyFanhoneyPalms</h3>
My Replace word is **honey** | I hope this is what you are looking for,
Find:`(^<h3>|\G).*?\K ` note! After `\K` there is a single space ...
Replace with:`Honey`
This regex only effects if the line starts with `<h3>` .... | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "regex, notepad++"
} |
SQLCriterion ArgumentOutOfRangeException
What is the correct syntax to create a SQLCriterion?
I have the following code:
var sqlCriterion = new SQLCriterion(
new SqlString("{alias}.Id IN (SELECT Id FROM dbo.fGetSomeIds(?1, ?2))"),
new object[] { "param1", "param2" },
new IType[] { NHibernateUtil.String, NHibernateUtil.String });
query.Where(sqlCriterion);
where query is my QueryOver-instance (created with NHibernateSession)
When I call query.List() I get the following exception:
Index was out of range. Must be non-negative and less than the size of the collection parameter name:index
which is thrown somewhere in NHibernate.Criterion.SQLCriterion.ToSqlString(..)
Is the syntax of my SQLCriterion-constructor wrong or am I missing something else? | This adjustment should make it:
var criterion = NHibernate.Criterion.Expression
.Sql("({alias}.Id IN (SELECT Id FROM dbo.fGetSomeIds(?, ?))"
+ " AS MyCriteria",
new object[] { "param1", "param2" },
new IType[] { NHibernateUtil.String, NHibernateUtil.String });
// query.Where(sqlCriterion);
query.Where(criterion); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "c#, .net, nhibernate, queryover"
} |
Log4j DailyRollingFileAppender
I have a log file currently configured to roll over every hour. When it is first created it is called logfile.log, and once it rolls over it is renamed to logfile.log.YYYY-MM-DD-HH.
What I would like is for the log file to be created immediately using the logfile.log.YYYY-MM-DD-HH naming convention as opposed to logfile.log.
Any ideas? | Take a look at this post:
* <
It discusses the use of DatedFileAppender described here:
* <
I never used this one, but it seems to be doing exactly what you need. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "logging, log4j, appender, rollingfileappender"
} |
Error when creating site from site template
I am having the exact issue here: <
I saved a site as a template and then attempted to create a new site using the template and the error occurs: "The type of this column cannot be changed because it is currently being indexed."
However, when I go to Central Admin and click services > Managed Metadata Service it takes me to the Term Store Management setting page.
What am I missing?
thx KS | To get to those four checkboxes, highlight the MM Service Connection(just below the Managed Metadata Service), and select "Properties" from the ribbon. | stackexchange-sharepoint | {
"answer_score": 1,
"question_score": 0,
"tags": "managed metadata, site template, managed metadata service"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.