text:
Q: After adding a external script how to read the response of the URL of the source? Here is the sample code.
var s=document.createElement("script");
s.src="http://example.com";
document.body.appendChild(s);

After executing the last line there will be a get request.
And the response will be 200 , How can I read the response of this request.

A: While you can't get the actual respone, you can set s.onerror and s.onload to determine whether or not it loaded successfully.

function importScript (sSrc, fOnload) {
    var oScript = document.createElement("script");
    oScript.type = "text\/javascript";
    oScript.onerror = loadError;
    if (fOnload) { oScript.onload = fOnload; }
    document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
    oScript.src = sSrc;
}

function loadError (oError) {
  alert("The script " + oError.target.src + " is not accessible.");
}

importScript("https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js", function() { alert("It Worked"); });
importScript("https://example.com/broken.js", function() { alert("It Worked"); });

If you do need to get the actual response, you will probably need to set up a proxy, so that you can hit something like https://your-own-server.com/getJsonFrom?src=http://example.com and then you can have your server do the request, and then you are reading the response from your own server.
Or, if you have control over the other server, you can have it return, instead of
{ some: "data" }

it would instead return
callback({ some:  "data" });

and then you can define callback to do whatever you want with it:
function callback(data) {
    console.log(data)
}

A: The only way is if the script returned from that url calls you back.
Usually it's achieved with a function name parameter, such as callback.
For example:
image you have on your site
window.globalCallback = (data) => alert(data)

if GET http://example.com?callback=globalCallback returned a javascript file such as:
globalCallback("some data");

Then you would get "some data" alerted to you.
That's jsonp in a nutshell.


text:
Q: Adding multi-level attributes to nodes using NetworkX I am trying to export a graph file with some visualization specifications . I could not figure out how to add multi-level attributes .
Import networkx as nx
#Create the Graph
g = nx.Graph()
g.add_edge('Andre',   'Beverly')
g.add_edge('Andre',   'Diane')
g.add_edge('Andre',   'Carol')
g.add_edge('Andre',   'Fernando')
g.add_edge('Beverly', 'Diane')
nx.draw(g)

Add attributes to the nodes
what I would like to do is to add position but using a specific attribute (names and structure)
# compute position
pos = nx.spring_layout(g)

# add attribute
g.node["Andre"]["viz"]["position"]["x"]= pos["Andre"][0]
g.node["Andre"]["viz"]["position"]["y"]= pos["Andre"][1]

this does not work
I have in fact two questions :

*

*how can I add a multi-level attributes

*Is there a way to do this in iterations (I could still write a function but I wonder if there is a way to do from networkx that I have not seen)

For Info : What I am really after, is a way to export network graph into a gexf file which I could open with gexf-js without passing by gephi.
P.S: I have this question  and other related to this, but to my knowledge they do not address what I am after.

A: After you calculate the positions in spring_layout():
for node in g.nodes():
    g.node[node]["viz"] = {'position': {'x': pos[node][0],
                                        'y': pos[node][1]
                                        }
                           }

print g.nodes(data=True)

Results in:
[('Beverly',
  {'viz': {'position': {'x': 0.00089466691490215525,
     'y': 0.69872879243427066}}}),
 ('Andre',
  {'viz': {'position': {'x': 0.55837798068966304, 'y': 0.47862178288009244}}}),
 ('Carol', {'viz': {'position': {'x': 1.0, 'y': 0.95632397309056527}}}),
 ('Diane', {'viz': {'position': {'x': 0.0, 'y': 0.25644757276893704}}}),
 ('Fernando', {'viz': {'position': {'x': 0.9957995595107102, 'y': 0.0}}})]

And then you can work on getting nx.write_gexf(g, 'somefile.gexf') to work :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run deno compiled executable on a mac? I am able to create PC and Mac executables from Windows 10 with Deno just fine:
"deno.exe" compile --unstable --allow-all --target x86_64-pc-windows-msvc --output myapp_x86pc myapp.js

"deno.exe" compile --unstable --allow-all --target x86_64-apple-darwin --output myapp_x86mac myapp.js

"deno.exe" compile --unstable --allow-all --target aarch64-apple-darwin --output myapp_aarchmac myapp.js

But how to actually test and run the produced binary on a Mac? Does the file need a specific extension, or does it perhaps need to be packaged or signed somehow in order to run?
Trying to run the myapp_x86mac through finder results in a dialog about unknown developer id, and I can seemingly add a security exception, but it still won't run. And trying to run it from terminal just results in zsh: Permission denied.
Is it even possible to create a working Deno OSX executable without full Apple development environment? I don't own a Mac or Apple ID for that matter, and need a loaner Mac to do testing, so I can't mess too much with the machine. I just want something that is easy to distribute and run on various machines, but for limited audience so I would like to avoid full Apple Store publishing "experience".

A: As of right now, no. You need to have XCODE installed or at least the XCODE commandline tools.


text:
Q: Single Source File for Grapes (@Grab) and imports for Use in Multiple Scripts I would like to simplify my Groovy scripts by concentrating the same boiler-plate code at the beginning of each script that contains @Grapes (@GrabConfig and @Grab) as well as the multiple import lines.  In this way I can update a single source file when updates are required to simplify the maintenance of all of the scripts that utilize that boiler-plate code.
I understand that I can utilize the "--configscript" to simplify the import lines but I have not found a solution for the @Grapes boiler-plate lines.
I also understand that the @Grapes boiler-plate lines can be removed if I were to download the artifacts and place their dependent jar files on the classpath.  However, I really do like the simplified maintenance of not continually looking for downloads and classpath management.
Thanks in advance.


text:
Q: PropertyEditor databinder in Spring 3 I am reading the Validator part in Spring3 Reference where the PropertyEditor DataBinder ConversionService Formatter are introduced.
IMO, these components are used for converting object to string and string to object,  for example, in a Spring Web application, the http requests parameters may be parsed and assembled to a form object like this:
@Controller
public class UserController {

    @RequestMapping("/user", method=RequestMethod.POST)
    public void addUser(User user) { /* ... */ }
}

With html:
<form>
  <input name="user.name" />
  <input name="user.email" />
</form>

Where the user object should be auto created and filled with properties from the http form.
But I am confused with the PropertyEditor DataBinder ConversionService Formatter concepts.
Is there a clear explanation?

A: PropertyEditor is part of the JDK. It was intended for forms in desktop applications and is more than a simple converter. It's supported by Spring, but I don't recommend it.
A Formatter is a specialized String <-> other type converter. It is used when a type can be represented as a string in a variety of formats (sic!). Dates for example.
Arbitrary type conversions are mostly accomplished by a Converter or a GenericConverter.
A ConversionService is a service that calls converters, formatters etc. You usually don't implement one yourself, but simply register your own converters.
The DataBinder is the component that manages the whole process. Before a controller method is called Spring creates a DataBinder and calls its bind method. The binder calls the necessary conversion services which in turn call the converters.


text:
Q: C copy static array into a structure I have a structure that looks like this:
typedef struct object {
  entry **entries;
} object;

typedef struct entry {
  int value;
} entry;

Somewhere in my code i have a static array of entries(initialized with some random data);
entry entries[][] = {... (doesn't matter)...};

How can i copy these entries into an object?
I need something like this:
object obj;
obj.entries = entries;

Edit: I do not want to copy every element in a 'for' loop.
After suggestions:
Ok. I have:
entry entries[initial_height][initial_width];
....initialize entries...
object obj;
int i;
obj.entries = (entry**) malloc(initial_height * sizeof(entry*));

for (i = 0 ; i < initial_height; i++) {
    obj.entries[i] = (entry*) malloc(initial_width * sizeof(entry));
}

memcpy(obj.entries, entries, sizeof(entry) * initial_height * initial_width);

printf("%d\n", entries[0][0].value);
printf("%d\n", obj.entries[0][0].value);

And i'm getting a segmentation fault(the first print works). What am i still doing wrong?

A: Your problem lies with memcpy. The basic idea in memcpy is that it starts from the 2 pointers specified in the parameters of memcpy and copies the number of bytes specified by you.
In your case you follow 2 steps::
1) You declare an array of pointers of entry.
2) You declare arrays of entry and save the pointer returned by malloc into the array of pointers declared in (1).
You should also take into consideration that your every array declared in step (2) could be declared anywhere in the memory not necessarily contiguously.
So, when you call memcpy(obj.entries[i], entries[i], sizeof(entry) * initial_width); you start copying bytes of entries to the array of pointers obj.entries[i] which is only of size initial_height * sizeof(entry*), so anything you copied beyond this limit, is corrupting the memory, which is the reason you get a segmentation fault. (Since you also over-write the bytes storing the location of dynamically declared arrays of entry)
A possible approach to do it would be as follows ::
for(int i = 0; i < initial_height; i++) {
    memcpy(obj.enteries[i], entries[i], sizeof(entry) * initial_width);
}

You will anyway have to use 1 for loop if you want to create your 2D array dynamically. In case you don't want this either, you will have to declare a static array!

A: It would be better to allocate and copy at the same place:
for (i = 0 ; i < initial_height; i++) {
    obj.entries[i] = (entry*) malloc(initial_width * sizeof(entry));
    memcpy(obj.entries[i], entries[i], sizeof(entry) * initial_width);
}


text:
Q: Why variables that I export in bash script does not work on EC2? When I create EC2 inst. I use bash script into user data where I export variable AWS credentials and then run the command to copy files from S3 bucket. But this command is not executed.
#! /bin/bash
export AWS_ACCESS_KEY_ID=MYACCESSKEY
export AWS_SECRET_ACCESS_KEY=MYSECRETKEY
aws s3 cp s3://mys3bucket/ ./

How to fix it?

A: It is run on its own bash process which dies at the end of your script.
Exported variables are preserved only for the lifetime of your script and they are also visible from child processes of your script.


text:
Q: Can I put a function in Fullcalendar's headerToolbar item? headerToolbar:{
  left:'prevYear prev today next nextYear',
  center:'title',
  right:'dayGridMonth,dayGridWeek,timeGridDay,listMonth'
},
date : moment().format('YYYY-MM')

While making Fullcalendar, I suddenly became curious
When I press the prev button in the headerToolbar, I want to make the variable date a month ago. Can I make it so that the function can be executed when I press the prev button?
/admin/visit/schedule/month?managerId"+this.managerId+"&date="+this.date

In this way, when the month of the calendar is changed, the variable date is changed and I am trying to call the api using it.

A: You can create a custom button to do your 'prev' functionality, and use that instead of the included prev button, as shown.
headerToolbar:{
    left:'prevYear myPrevButton today next nextYear',
    center:'title',
    right:'dayGridMonth,dayGridWeek,timeGridDay,listMonth'
},
customButtons: {
    myPrevButton: {
        text: 'Prev',
        click: function() {
            // do something
        }
    }
},
date : moment().format('YYYY-MM')


text:
Q: Longest common substring matrix I am very new with python and am struggling in creating a matrix that expresses the longest common substring. I am looking for a result like this: LCS matrix
This is my code so far.
def compute_lcs(X, Y):
    m = len(X)
    n = len(Y)
# An (m) times (n) matrix
    matrix = [[0] * (n) for _ in range(m)]
    for i in range(1, m):
        for j in range(1, n):
            if X[i] == Y[j]:
                if i == 0 or j == 0:
                    matrix[i][j] = 1
            else:
                matrix[i][j] = matrix[i-1][j-1]+1
        else:
            matrix[i][j] = 0
    return matrix

b = compute_lcs('AACTGGCAG','TACGCTGGA')
for y in b:
    print (y)

Current Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 1, 1, 1, 1, 1, 0]
[0, 1, 0, 2, 0, 2, 2, 2, 0]
[0, 1, 2, 1, 3, 0, 3, 3, 0]
[0, 1, 2, 0, 2, 4, 0, 0, 0]
[0, 1, 2, 0, 1, 3, 0, 0, 0]
[0, 1, 0, 3, 0, 2, 4, 1, 0]
[0, 0, 2, 1, 4, 1, 3, 5, 0]
[0, 1, 1, 0, 2, 5, 0, 0, 0]

Expected Output:
[0, 0, 0, 1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 2, 0, 0, 0, 0, 1, 0]
[0, 0, 0, 0, 1, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 2, 0, 0]
[0, 0, 0, 2, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 3, 1, 0, 0, 0]
[0, 0, 0, 0, 1, 4, 0, 0, 1]
[1, 1, 0, 0, 0, 0, 0, 1, 0]

However my result is a matrix that shows incorrect values. When I do the matrix by hand, the correct output looks like this: Correct output. I feel like my logic makes sense, what am I doing incorrectly?
Thanks everyone.

A: First off, to make things clear, the longest common subsequence problem is not the same as the longest common substring problem. What you're trying to solve is the latter; better not to confuse the two.
Secondly, your else branches are not aligned under the appropriate if conditions.
Whenever the strings match X[i] == Y[j], we set the matrix element to 1 if the index i or j is 0 since i-1 or j-1 at 0 gives -1 (unfortunately, this is also the index for last item in Python) which is not what we want, otherwise we increment for higher indices i, j > 1.
Thirdly, your looping should start at 0 not 1 since we start from the first characters in the strings which are at indices 0:
def compute_lcs(X, Y):
   m = len(X)
   n = len(Y)
   # An (m) times (n) matrix
   matrix = [[0] * n for _ in range(m)]
   for i in range(0, m):
      for j in range(0, n):
          if X[i] == Y[j]:
              if i == 0 or j == 0:
                  matrix[i][j] = 1
              else:
                  matrix[i][j] = matrix[i-1][j-1]+1
          else:
              matrix[i][j] = 0
  return matrix

To get the exact matrix shown in the expected output, you should swap the order of the arguments or transpose the matrix before printing. Note however that these are not necessary (swapping or transposing) and only serve for formatting purposes:
b = compute_lcs('TACGCTGGA', 'AACTGGCAG')
for y in b:
    print (y)

[0, 0, 0, 1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 1, 0]
[0, 0, 2, 0, 0, 0, 1, 0, 0]
[0, 0, 0, 0, 1, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 0, 2, 0, 0]
[0, 0, 0, 2, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 3, 1, 0, 0, 1]
[0, 0, 0, 0, 1, 4, 0, 0, 1]
[1, 1, 0, 0, 0, 0, 0, 1, 0]


text:
Q: Determine whether $ARGV[X] is passed a string or a file in perl. Is there a way, other than checking for suffixes? Or should I stick with checking for .txt?

A: @ARGV is just a list of command-line arguments provided to the script, see perlvar
If you want to know whether one of those arguments is a file, you probably want -e, see file tests
If you expect the first argument to be a filename, something like:
my $filename = shift @ARGV;
die "script.pl FILENAME expected" unless -e $filename;


text:
Q: first term in the product rule At the moment I am studying a Calculus book. This book states that if you have a function defined like this:
$
 f(x)=x^3
$
Than if you expand that function according to the Power Rule with the Binomial Theorem the derivative would be $3x^2$. I do understand that the derivative is $3x^2$. However it does not make sense when I use that theorem and then simplify the it.
The simplification of the derivative:
$
 f(x)= \frac{ f(x + h)^3 - f(x)^3 }{ h }
$
$
 f(x)= \frac{  (x + h)(x + h)(x + h) - x^{3} }{ h }
$
$
 f(x)= \frac{  x^{2}+ 2xh + h^{2}(x + h) - x^{3} }{ h }
$
$
 f(x)= \frac{  x^{3} + x^{2}h + 2x^{2}h + 2xh^{2} + h^{2} + h^{3}- x^{3} }{ h }
$
$
 f(x)= 3x^{2}  + 3xh +  h^{2}
$
So the book states, that because of that every term, except the first one, has h as a factor and therefore approaches 0. Therefore the answer is.
$
 f(x)= 3x^{2}
$
Why is it, that only the first term is important and not the other two?
$
 f(x)= 3x^{2}  + 3xh +  h^{2}
$

A: First, it is not convenient to denote
$$
 \frac{ f(x + h)^3 - f(x)^3 }{ h }
$$
by $f(x)$ for two reasons: we have already defined $f$ to be the function $x\mapsto x^3$ and the variable of this function is $h$ since finally we pass to the limit $h\to0$.
Now to answer your question: if we pass to the limit $h\to 0$ the terms $3xh$ and $h^2$ vanishes and remains the term $3x^2$ which represents the derivative of $x^3$.

A: The derivative of $f(x)$ is denoted by $f'(x)$ and is defined as
$\lim_{h\rightarrow 0} \dfrac{f(x+h)-f(x)}h$.
If you choose $f(x)=x^3$, we have
$f'(x)=\lim_{h\rightarrow 0} \dfrac{f(x+h)-f(x)}h=\lim_{h\rightarrow0} \dfrac{(x+h)^3-x^3}h=\lim_{h\rightarrow0}\dfrac{3x^2h+3xh^2+h^3}h$.
Intuitively, $\lim_{x\rightarrow a}g(x)$ is the expression to which the value of  the function $g$ gets close to when evaluated at values very close to $a$ but not at $a$.
Since for all $h\ne 0$, $\dfrac{3x^2h+2xh^2+h^3}h=3x^2+3xh+h^2$, the derivative is given by $\lim_{h\rightarrow 0}3x^2+3xh+h^2$.
Now as $h$ approaches $0$, $3x^2+3xh+h^2$ gets close to $3x^2$ since $3xh+h^2$ gets close to $0$ and thus the derivative is $3x^2$.
Added:
If someone is asking you what $\lim_{h\rightarrow0}3x^2+3xh+h^2$ is, they are asking you what will $3x^2+3xh+h^2$ come close to if you substitute for $h$ values very close to $0$ (but not $0$ itself). Take an example: Find $\lim_{x\rightarrow 2} \frac{(x+2)(x-2)}{x-2}$. Now try to put values for $x$ that are very close to $2$ and see what the function, $f(x)=\frac{(x+2)(x-2)}{x-2}$ gets close to. For $x=2.1$, $f(x)=4.1$. Similarly $f(2.01)=4.01$, $f(2.001)=4.001$, $f(2.00001)=4.00001$. Also for values below $2$, $f(1.9)=3.9$, $f(1.999)=3.999$, $f(1.999999)=3.999999$. It is evident that the function $f$ is approaching $4$, as you input values close to $2$. Note that the function is itself undefined at $x=2$, but that does not matter since the limit only cares about how the function behaves near $2$ but not at $2$. So, $\lim_{x\rightarrow 2} \frac{(x+2)(x-2)}{x-2}=4$

A: It is not 'f(x)=' but its 'as limit h approaches 0'. So, after simplification you put h=0 and thus, the other terms cancel out. The book shows the method of differentiating using first principle.

A: In the early development of the calculus, mathematicians were interested in the effects of "small changes" in the domain ($x$ values) of a given function on the range of the given function (the values $f(x)$ which result)
A small change was called a differential, which we will write "$\text{d}x$". In some sense this can be thought of as the value $h$ you have above, and as $\text{d}x$ gets very small, or similarly $h$ gets very small, we understand it to "go to zero." This is the reason we ignore the terms with coefficients of orders of $h$ in your equation.
Here's an interesting example from history by Euler (adapted from Dunham 2008, "The Calculus Gallery," pp.53-54), which would not meet today's standard of proof, but might give some insight into what's going on:
Euler was interested in differentials of the sine function. He started with the power series of $\sin(x)$ and $\cos(x)$, thus
$$\sin x = x-x^3/3!+x^5/5!-\cdots$$ and $$\cos x = 1-x^2/2!+x^4/4!-\cdots.$$
He then substituted $\text{d}x$ into both (which he understood to be "infinitely small" - whatever that means!):
$$\sin(\text{d}x) = \text{d}x-(\text{d}x)^3/3!+\cdots$$ and $$\cos(\text{d}x)=1-(\text{d}x)^2/2!+\cdots.$$
The higher powers of $\text{d}x$ (such as $(\text{d}x)^2$ and $(\text{d}x)^3$ etc.) were considered insignificant (since they "are zero even more so than $\text{d}x$ or a constant" - again whatever that means!). Hence, we can write (*)
$$\sin(\text{d}x)=\text{d}x$$ and $$\cos(\text{d}x)=1.$$
Euler then considered the function $y=\sin(x)$, and using the idea of the differential considered:
$$y+\text{d}y = \sin(x+\text{d}x).$$
Using a trigonometric identity this gives
$$y+\text{d}y=\sin(x)\cos(\text{d}x)+\cos(x)\sin(\text{d}x),$$
which using (*) gives
$$y+\text{d}y = \sin(x)+\cos(x)\text{d}x.$$
Subtracting $y$ from both sides then gave
$$\text{d}y = \sin(x)+\cos(x)\text{d}x-y,$$
which simplifies to $$\text{d}y = \cos(x)\text{d}x.$$
In modern notation this tells us that $$\frac{\text{d}y}{\text{d}x} = \cos(x),$$
 i.e. the derivative of $y=\sin(x)$ is $\cos(x)$ !


text:
Q: Pip error: Microsoft Visual C++ 14.0 is required I just ran the following command:
pip install -U steem

and the installation worked well until it failed to install pycrypto.
Afterwards I did the
pip install cryptography

command because I thought it was the missing package.
So my question is, how I can install steem without the pycrypto-error (or the pycrypto-package in addition) and how to uninstall the cryptography-Package which I don't need.
(I'm using Windows 7 and Python 3)
Requirement already up-to-date: python-dateutil in c:\users\***\appdata\lo
cal\programs\python\python36\lib\site-packages (from dateparser->maya->steem)
...
Installing collected packages: urllib3, idna, chardet, certifi, requests, pycryp
to, funcy, w3lib, voluptuous, diff-match-patch, scrypt, prettytable, appdirs, la
ngdetect, ruamel.yaml, humanize, tzlocal, regex, dateparser, pytzdata, pendulum,
maya, ecdsa, pylibscrypt, ujson, toolz, steem
Running setup.py install for pycrypto ... error
Complete output from command c:\users\***\appdata\local\programs\pytho
n\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\
***~1\\AppData\\Local\\Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(
tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();
exec(compile(code, __file__, 'exec'))" install --record C:\Users\***N~1\AppDat
a\Local\Temp\pip-igpkll6u-record\install-record.txt --single-version-externally-
managed --compile:
running install
running build
running build_py
...
building 'Crypto.Random.OSRNG.winrandom' extension
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

----------------------------------------
Command "c:\users\***\appdata\local\programs\python\python36\python.exe -u
-c "import setuptools, tokenize;__file__='C:\\Users\\***N~1\\AppData\\Local\\
Temp\\pip-build-k6flhu5k\\pycrypto\\setup.py';f=getattr(tokenize, 'open', open)(
__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code,   __fil
e__, 'exec'))" install --record C:\Users\***N~1\AppData\Local\Temp\pip-igpkll6
u-record\install-record.txt --single-version-externally-managed --compile"   faile
d with error code 1 in C:\Users\***N~1\AppData\Local\Temp\pip-build-    k6flhu5k\p
ycrypto\

A: If you already have Visual Studio Build Tools installed but you're still getting that error, then you may need to "Modify" your installation to include the Visual C++ build tools.
To do that:

*

*Open up the Visual Studio Installer (you can search for it in the Start Menu if needed).

*Find Visual Studio Build Tools and click "Modify":

*Add a checkmark to Visual C++ build tools and then click "Modify" in the bottom right to install them:

After the C++ tools finish installing, run the pip command again and it should work.

A: I faced the same problem. Found the fix here.
Basically just install this.
shasum output:
3e0de8af516c15547602977db939d8c2e44fcc0b  visualcppbuildtools_full.exe

md5sum output:
MD5 (visualcppbuildtools_full.exe) = 8d4afd3b226babecaa4effb10d69eb2e

Run your pip installation command again. If everything works fine, its good. Or you might face the following error like me:
Finished generating code
    LINK : fatal error LNK1158: cannot run 'rc.exe'
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1158

Found the fix for the above problem here:
Visual Studio can't build due to rc.exe
That basically says
Add this to your PATH environment variables:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

Copy these files:

rc.exe
rcdll.dll

From

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

To

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin

It works like a charm

A: As an alternative to installing Visual C++, there is a way by installing an additional package in Conda (this option doesn't require admin rights). This worked for me:
conda install libpython m2w64-toolchain -c msys2

A: Pycrypto has vulnerabilities assigned the CVE-2013-7459 number, and the repo hasn't accept PRs since June 23, 2014.
Pycryptodome is a drop-in replacement for the PyCrypto library, which exposes almost the same API as the old PyCrypto, see  Compatibility with PyCrypto.
If you haven't install pycrypto yet, you can use pip install pycryptodome to install pycryptodome in which you won't get Microsoft Visual C++ 14.0 issue.

A: Updated link here for download  Microsoft Visual C++ 14.0

*

*Download
It works for me without a Visual Studio downloader

A: I got this error when I tried to install pymssql even though Visual C++ 2015 (14.0) is installed in my system.
I resolved this error by downloading the .whl file of pymssql from here.
Once downloaded, it can be installed by the following command :
pip install python_package.whl

Hope this helps

A: I landed on this question after searching for "Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". I got this error in Azure DevOps when trying to run pip install to build my own Python package from a source distribution that had C++ extensions. In the end all I had to do was upgrade setuptools before calling pip install:
pip install --upgrade setuptools

So the advice here about updating setuptools when installing from source archives is right after all:). That advice is given here too.

A: You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.
Alternate link: https://wiki.python.org/moin/WindowsCompilers#Microsoft_Visual_C.2B-.2B-_14.2_standalone:_Build_Tools_for_Visual_Studio_2019_.28x86.2C_x64.2C_ARM.2C_ARM64.29
In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.
I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.
After you have installed Visual C++, just re-run the original command:
pip install -U steem

To find out what the various install options mean, run this command:
pip help install

The help for the -U option says
-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

A: On Windows, I strongly recommand installing the latest version of Visual Studio Community. It's free, you will maybe miss some build tools if you only install vc_redist, so you can easily install package by pip instead of wheel, it save lot of time.

A: Try doing this:
py -m pip install pipwin
py -m pipwin install PyAudio

A: Three steps I follow for this error:

*

*C++ Build tools are installed

*pip install --upgrade setuptools

*try using conda to install, conda may have the compiled version which won't need the build tools

A: None of the solutions proposed by other people here worked for me.
So in my case I had to uinstall ALL older versions
of Microsoft Visual C++ Redistributable from my computer:

Only the newest one (in my case 2015-2022) should be left!
After uinstalling I ran this command:
pip install <your_lib_name>

and everything worked great after that.

A: Killer solution: install nodejs and tick the option of install chocolatey and other necessary tools... and it will install the tools required to setup a development environment.


text:
Q: Responsive rectangle with image fit to maximum size while keeping aspect ratio I'm trying to create a responsive rectangle that has:

*

*height that is 62% of width

*background: linear-gradient

*inside the rectangle is an image centered vertically and horizontally with a maximum size, all images have the same width: 400px but a different height
What I have done before:

*

*for getting responsive rectangle I used this approach:

.responsive-rectangle {
  width: 100%;
  max-width: 450px;
  background: -webkit-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -moz-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -o-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: linear-gradient(to top, #0071B4, rgba(0, 113, 180, .8));
}
.responsive-rectangle:before {
  content: "";
  display: block;
  padding-top: 62%;
}

jsfiddle

*to align the image inside rectangle I have used display: flex; and text-align:center; with an .img-wrapper:

.responsive-rectangle {
  width: 100%;
  max-width: 450px;
  background: -webkit-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -moz-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -o-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: linear-gradient(to top, #0071B4, rgba(0, 113, 180, .8));
  display: flex;
  text-align: center;
}
.responsive-rectangle:before {
  content: "";
  display: block;
  padding-top: 62%;
}
.image-wrapper {
  margin: auto;
}
img {
  width: 100%;
  height: 100%;
}

jsfiddle
This works perfect in case with image 400px x 220px,
but with images that have a bigger height the correct aspect ratio is not used:

.responsive-rectangle {
  width: 100%;
  max-width: 450px;
  background: -webkit-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -moz-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: -o-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
  background: linear-gradient(to top, #0071B4, rgba(0, 113, 180, .8));
  display: flex;
  text-align: center;
}
.responsive-rectangle:before {
  content: "";
  display: block;
  padding-top: 62%;
}
.image-wrapper {
  margin: auto;
}
img {
  width: 100%;
  height: 100%;
}

jsfiddle
Is there any approach that can solve my problem?
Edit:
Oh I forgot to note that background-image is not good solution because it does not support SEO.

A: The problem with your final code is that the pseudo element used for keeping the aspect ratio is not actually performing its desired role. This is because .responsive-rectangle is set to display: flex;. To maintain the aspect ratio you can make the following modifications:

*

*Remove the .responsive-rectangle:before rule as the calculation can be done on .image-wrapper itself

*Remove display: flex; from .responsive-rectangle

*Remove the existing rules for .image-wrapper and replace them with:

*

*padding-top: 62%; to ensure the correct aspect ratio is used

*position: relative; to allow img to be positioned relative to .image-wrapper

*width: 100%; to ensure it will fill the entire width of .responsive-rectangle

*Remove the existing rules for img and replace them with:

*

*bottom: 0;, left: 0;, margin: auto;, right: 0; and top: 0; to allow the image to be centered in .image-wrapper

*position: absolute; to position it relative to .image-wrapper

*max-height: 100%; and max-width: 100%; to ensure the image does not exceed its natural height and width while keeping its aspect ratio

.responsive-rectangle {
    background: -webkit-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
    background: -moz-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
    background: -o-linear-gradient(bottom, #0071B4, rgba(0, 113, 180, .8));
    background: linear-gradient(to top, #0071B4, rgba(0, 113, 180, .8));
    float: left;
    margin: 0 5px;
    max-width: 450px;
    text-align:center;
    width: 100%;
}
.image-wrapper {
    padding-top: 62%;
    position: relative;
    width: 100%;
}
img {
    bottom: 0;
    left: 0;
    margin: auto;
    max-height: 100%;
    max-width: 100%;
    right: 0;
    position: absolute;
    top: 0;
}

http://jsfiddle.net/p23pgqp3/

A: I had to lay them out next to each other to see the issue. Here is a solution to your problem, just use the image as a background:

and then center it
.image-wrapper {
    background-repeat: no-repeat;
    width: 100%;
    background-size: contain;
    background-position: center center;
}

http://jsfiddle.net/bmdqsqx1/1/


text:
Q: display hidden divs when another div is clicked I am currently try create a custom navigation on websites homepage that uses tiles for navigation.
I am using MVCSiteMapProvider for MVC5 to display live tiles on the homepage as well as a standard bootstrap navbar, when the user loads the homepage only the main parent navigation any values nested under the parent are hidden.
The CSHTML below is what I have managed to create so far:

        @{
            var nodes = MvcSiteMapProvider.SiteMaps.Current.CurrentNode;
        }

        @foreach (var node in nodes.RootNode.ChildNodes)
        {

@node.Title

            foreach (var childNode in node.ChildNodes)
            {

@childNode.Title

            }
        }

I need some guidance on how to display multiple divs when one of the parent tiles (div) is clicked.
I only want to show the child elements, currently I am try to do this using the id of the parent div as a class on it child elements, when the parent is clicked the other top level divs should be hidden and the child elements and parent should be visible.
Any advice would be very much appreciated.

A: Try this:

@node.Title

@childNode.Title

@childNode.Title

@childNode.Title

@node.Title

@childNode.Title

@childNode.Title

@childNode.Title

$('.live-tile').on('click', function () {
  $('.main-content>div').not('.live-tile').addClass('hidden');// hide all divs on click
  $('.main-content>div').removeClass('clicked');
  $(this).addClass('clicked');
  $('.clicked').nextUntil( '.live-tile', "div.hidden" ).removeClass('hidden');// now show the next hidden ones
});


text:
Q: How to use angular-gettext in a config phase? I'm using angular-gettext, angular-breadcrumb and angular-ui-router.
I have my app configuration similar to this:
app.config(function($stateProvider) {

  $stateProvider.state('welcome', {
     url : '/',
     templateUrl: 'index.html',
     ncyBreadcrumb : {
        label : 'Home'
     }
  });

});

I would like to be able to translate the label for the breadcrumb ('Home') by angular-gettext. In order to this I need to include gettext tools into the app.config() function. Something like this would be ideal, however gettextCatalog isn't available during the config phase:
app.config(function($stateProvider, gettextCatalog) {

  $stateProvider.state('welcome', {
     url : '/',
     templateUrl: 'index.html',
     ncyBreadcrumb : {
        label : gettextCatalog.getString('Home')
     }
  });

});

Is there any other way to achieve this with these plugins, especially with the angular-gettext?

A: According to the angular-breadcrumb docs:

The property ncyBreadcrumbLabel can contains bindings which are evaluated against the scope of the current state controller.

I haven't tested this, but I would think you could use the gettextCatalog module in your controller:
$stateProvider.state('home', {
  url: '/',
  templateUrl: 'index.html',
  controller: function($scope, gettextCatalog) {
    $scope.label = gettextCatalog.getString('Home');
  },
  ncyBreadcrumb: {
    label: '{{label}}'
  }
})


text:
Q: ios NSFetchRequest, order child objects Hi would like to know how to specify a FetchRequest where i can order the objects in a relationship.
   |  Parent         |        | Child        |
   |     - name      |------->|   - name     |
   |     - position  |        |   - position |

For example if i have a parent table that contains a position attribute and has a one to many relationship with a child table that has a also has a position attribute. How do i return the parent objects (ordered by position) that contain the child objects ordered by position.
e.g
parent 1
   child 1
   child 2
   child 3

parent 2
   child 15
   child 16

parent 3
   child 22
   child 23
   child 24

Obviously the below code will order the parent objects correctly, but how do i make the child objects that are returned with the each parent to be in the correct order
    NSFetchRequest* fetchReqest = [[NSFetchRequest alloc] init];

    NSEntityDescription* entity = [NSEntityDescription entityForName:@"parent"  inManagedObjectContext:managedObjectContext];
    [fetchReqest setEntity:entity];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                        initWithKey:@"position" ascending:YES];
    [fetchReqest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSArray* parentsThatContainChildren =  [managedObjectContext executeFetchRequest:fetchReqest error:nil];

Cheers

A: There's 2 strategies to this:

*

*Perform a separate fetch request for the children with the NSSortDescriptor. Pro: you keep this in the FetchController. Con: multiple fetch requests can slow you down

*Sort the returned children in the NSArray* parentsThatContainChildren.

For #2, you can check this out :
NSSortDescriptor *positionSort = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES];

NSArray *children = [[parent.children allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:positionSort]];


text: Q: muParser in Xcode I want to use the muparser library in an c++ application. I use Xcode und Mac Os X El Capitan to code. The library was installed using HomeBrew as brew install muparser but if I compile this sample code I get errors of the type Undefined symbols for architecture x86_64. I searched a bit and found that it might be due to static libraries which are compiled only for 32 bit. Question: Can I fix this somehow by either telling HomeBrew to install the 64 bit variant or directly in Xcode?


text:
Q: Can objects make each other 'undeletable' by referencing each other? So lets say there are two classes:
public class A {
    B reference = new B(this) //B isn't garbage collected because A references it
}

public class B {
    A reference // A isn't garbage collected because B references it
    public B(A ref) {
      reference = ref;
    }
}

And then a third class creates a new A object. Then, when it wants to get ride of it, it sets that pointer to null. Wouldn't there be some weird persistant loop caused by A and B because they both reference each other? Neither can be collected because they keep each other "alive". Or is the JVM too smart for that and realizes that the rest of the program doesn't know about them?
It feels like this might cause some sort of memory leak.
If this is possible, how do you fix it? Bidirectional references are very common in code. There are many cases when object 1 knows about object 2 and object 2 knows about object 1. How do you make sure that they are deleted.
NOTE: I wrote all this in my web browser, so forgive any errors

A: If only references to A and B are A and B themselves , then they are eligible for garbage collection.
Java's GC considers objects eligible for garbage collection if they aren't reachable through a chain starting at a garbage collection root. Even though objects may point to each other to form a cycle, they're still garbage if they're cut off from the root.

A: Garbage collection starts from roots of active objects, so you need to concentrate on these sets.  If you have a long chain of objects that are referenced from an active object (something pointed to by stuff currently being used) then you can create memory leaks, but if you turn a reference to null, the objects will still be garbage collected.
In other words, if you have A->B and B->A but nothing pointing to both, they'll still be collected: because they can't be reached from the root set of live objects.
The root set comes from the set of all threads in the program:
http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx
and
What are the roots?

A: No. The garbage collector doesn't count references to know is an object is collectable or not. An object is collectable if it's not reachable any more through a chain of strong references from any root (static variable, or running thread).


text:
Q: Google MDL: drawer icon not centered I'm trying the fixed tab example from the Google MDL documentation. Here is my code:
CODE

          Title

          Tab 1
          Tab 2
          Tab 3

        Title

OUTPUT

The problem is my drawer icon position is wrong!  It is aligned to the top instead of center. What is wrong here?

A: I found this answer and it solved the problem! You need to add the <!DOCTYPE html> to the source and everything will work properly.


text:
Q: how to show list of available wifi in android application for API 8? I'm working on an android application that should search available wifi and connect to the chosen network. first of all I want to show all wifi networks in my app. I found some tutorial but all of theme need API 14 and I have to use API 8 for this approach.
Any idea would be great.
Thanks.

A: Unfortunately you MUST have API 14 as a minSdkVersion. There simply is not such a function in earlier API(s), thats why Google added it.
Change the minSdkVersion under your AndroidManifest.xml to show android:minSdkVersion="14"


text:
Q: Inner Relative Layout Not getting below as defined and missing controls Here is my xml code
<?xml version="1.0" encoding="utf-8"?>

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:id="@+id/RelativeLayout01"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"

                    >
            <ImageView
                        android:id="@+id/default1"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:background="@drawable/default1"

                        android:scaleType="fitXY">
            </ImageView>

            <ImageView
                        android:id="@+id/postscore"
                        android:layout_marginTop="19dp"
                        android:layout_width="180dp"
                        android:layout_height="45dp"

                        android:src="@drawable/fc_postyour_best_score_bg"
                        android:layout_alignParentRight="true"
                        android:scaleType="fitXY">
            </ImageView>

            <ToggleButton
                         android:id="@+id/fsvibrate_on"
                         android:layout_width="135dp"
                         android:layout_height="35dp"

                         android:textOff=""
                         android:textOn=""

                         android:layout_alignParentRight="true"
                         android:background="@drawable/fsvibrate_on">
            </ToggleButton>

            <ImageButton
                        android:id="@+id/fcplaydown"
                        android:layout_width="215dp"
                        android:layout_height="53dp"
                        android:background="@drawable/button1"

                        android:layout_centerInParent="true"
                        android:layout_marginBottom="5dip">
            </ImageButton>
            <RelativeLayout
                        android:id="@+id/RelativeLayout02"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/fcplaydown"
                        android:layout_alignLeft="@id/fcplaydown"
                        >

            <ToggleButton
                        android:id="@+id/fcsoundondown"
                        android:layout_width="101dp"
                        android:layout_height="55dp"
                        android:textOff=""
                        android:textOn=""
                        android:background="@drawable/fcsoundondown">
            </ToggleButton>

            <ImageButton
                        android:id="@+id/fchelpdown"
                        android:layout_width="103dp"
                        android:layout_height="53dp"

                        android:background="@drawable/fchelpdown"
                        android:layout_alignBottom="@id/fcsoundondown"

                        >
            </ImageButton>

            <ImageButton
                        android:id="@+id/fcboards_down"
                        android:layout_width="101dp"
                        android:layout_height="55dp"
                        android:layout_marginTop="5dip"
                        android:layout_below="@id/fcsoundondown"
                        android:layout_alignLeft="@id/fcsoundondown"
                        android:background="@drawable/fcleaderboards_down">

            </ImageButton >

            <ImageButton
                        android:id="@+id/fcments_down"
                        android:layout_width="103dp"
                        android:layout_height="53dp"

                        android:background="@drawable/fcachivements_down"
                        android:layout_alignBottom="@id/fcboards_down"

                        android:layout_alignRight="@id/fchelpdown">
            </ImageButton>
            </RelativeLayout>

            <ImageView
                        android:id="@+id/android"
                        android:layout_width="fill_parent"
                        android:layout_height="48dp"
                        android:background="@drawable/android"
                        android:layout_alignBottom="@id/default1">

                            </ImageView>

        </RelativeLayout>

I have 2 problems

*

*The RelativeLayout02 is not getting below as defined but it is comming after @+id/postscore

*I can not see @+id/fcsoundondown" and @+id/fcboards_down

A: There is no such id fcleaderboards_down and you have used it inside the image button android:layout_alignBottom="@id/fcleaderboards_down".


text:
Q: ¿Como comprimir varios pdf generados por CrystalReport? A partir de ahora, estoy generando archivos PDF mediante programación utilizando Crystal Report, y quiero que todos esos PDF se compriman pero no encuentro por ningun lado un tutorial o un blog que explique esto.
Hasta el momento voy haciendo esto::
//Generar reportes
    [HttpPost]
    public ActionResult Generarreportes(string[] Param)
    {
        //Creo una lista en donde almacenaré los reportes creados
        List<ReportDocument> list_temp = new List<ReportDocument>();

        //Aqui creo los reportes y los añado a la lista
        for (int i = 1; i <= Param.Length - 1; i++)
        {
            DataTable dtInteresado = new DataTable();
            dtInteresado = TablaInteresadoIndividual(obtenerInteresado(Param[0], Param[i]));

            ReportClass Reporte = new ReportClass();
            Reporte.Load(Path.Combine(Server.MapPath("~/Reportes/"), "ReporteInscritos.rpt"));
            Reporte.SetDataSource(dtInteresado);

            list_temp.Add(Reporte);
        }

        //Y aquí supuestamente deberia estar el código de cómo comprimir todos esos docuemntos, pero desconozco el procedimiento...

        .......

        //Intenté con esto pero me marca error.
        Stream stream = list_temp.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);

        return File(stream, "application/pdf", "ReporteInscritos.pdf"); ;
    }


text:
Q: Can not run test cases with DataRow attribute in MTM I am trying to run a test case like the one mentioned below in Microsoft Test Manager. I created a test case in MTM under a test suite and attached the below created test case in the automation script.
public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

[TestMethod]
[DataRow(3, 4, 7)]
[DataRow(5, 6, 11)]
public void When_add_two_numbers(int firstNumber, int secondNumber, int expectedResult)
{
    //Arrange
    Calculator calc=new Calculator();

    //Act
    var actualResult = calc.Add(firstNumber, secondNumber);

    //Assert
    Assert.AreEqual(expectedResult,actualResult);
}

Because MSTest now supports DataTestMethod and DataRow attributes then I expect such data driven tests to be able to run on MTM as well. Is it not supported by MTM? If not then what is the workaround?
I am getting below error when I am trying to run this test case in MTM.

"Method" does not have correct signature. Test method marked with the [TestMethod] attribute must be non-static, public, does not return a value and should not take any parameter. for example: public void Test.Class1.Test().

A: You need to replace [TestMethod] by [DataTestMethod]
[DataTestMethod] //<-- THIS IS REQUIRED
[DataRow(3, 4, 7)]
[DataRow(5, 6, 11)]
public void When_add_two_numbers(int firstNumber, int secondNumber, int expectedResult) {
    //...
}

so that test methods can have parameters and uses them to parametrize the test.


text:
Q: Finding the child widget in a group box I have QPushButton object and a QLabel object laid out in a QGridLayout layout. This QGridLayout is set to a QGroupBox object. How do I now retrieve the QPushButton that is effectively present in this group box?
I have tried the following code but it does not return a valid QPushButton object.
    QGroupBox *grpBox = 0;
    grpBox = (QGroupBox *)ui.tableWidget->cellWidget(fromRow, 0);
    QGridLayout * gridLayout = (QGridLayout *)grpBox->layout();
    QPushButton *btn = gridLayout->findChild<QPushButton *>("+");

Thanks,
Rakesh.

A: findChild actually works. It should have been called on QGroupBox object.


text:
Q: Can you give columns a "variable name" for a specific sheet in Excel VBA Ok, so I have read this:
Can you give columns in Excel a variable name?
and from my understanding, I can essentially setting "Name" to equal A, such that when I do:
For i = 1 to 100

worksheets(Sheet1).Range(Name & i).Value = "poop"

next i

It will fill Cells A1:A100 with poop.
However, if I were to type:
worksheets(Sheet2).Range(Name & i).Value = "poop"

it would also fill A1:A100, except in Sheet 2 now.
Is there any way where "Name" is Sheet-specific?  Something like:
Sheet1.Name = "A"
Sheet1.Name = "F"
For i = 1 to 100

worksheets(Sheet1).Range(Name & i).Value = "poop"
worksheets(Sheet2).Range(Name & i).Value = "poop"

Would result in sheet1 having column A full of poop and sheet 2 have column F full of poop.  Maybe I'm being too picky because I know I can type "Sheet1.Name" and "Sheet2.Name" because they're of that object, but I'm trying to avoid that since I've already specified it in Worksheets() and it would make the code cleaner.
I was thinking I'd have to put it in to each sheet's module, maybe as a private because they are both called "Name", but I really don't know...

A: Code:
Worksheets(Sheet1).Range("A:A").Name = "PoopRange"

Then:
Range("PoopRange") will always refer to Sheet1, Column A.
You can use Range("PoopRange").Cells(i,1) to loop through each cell in that column.

A: You'll want to create a new range object and then set that range object. A range can be a set of cells or a column or a row:
Dim rngCol as Range
Dim rngGroup as Range

Set rngCol = Worksheets("Sheet1").Range("A:A")
Set rngGroup = Worksheets("Sheet1").Range("A1:F100")

rngCol.Value = "Poop"
rngGroup.Value = "Poop"

Or you can iterate through these after setting them:
For each rngCell in rngCol
     rngCell.Value = "Poop"
Next rngCell


text:
Q: Is there a way to get touch position on mobile browsers when selecting text? I am trying to create simple eased scrolling. But I have hit a hurdle on mobile browsers with the selectionchange event and touchmove. I am trying to scroll the page when a user selects text and the selection moves past the current viewing area. But on mobile the touchmove event is fired after the user is finished selecting the text and removes their finger from the screen then places their finger back to the screen. I have only tested in android on chrome and opera but the effect is the same.
Is there a way to scroll my page when the user is selecting text or is this an impossibility?
Here is a sandbox Codesandbox.
And here is simple code:
const handleSelectionTouchmove = (e) => {
  const pageY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
  console.log(pageY)
};

const handleSelectionTouchend = () => {
  window.removeEventListener("touchmove", handleSelectionTouchmove);
  window.removeEventListener("touchmove", handleSelectionTouchend);
};

const onSelectionChange = (e) => {
  const selection = window.getSelection();

  if (!selection.isCollapsed) {
    window.addEventListener("touchmove", handleSelectionTouchmove);
    window.addEventListener("touchend", handleSelectionTouchend);
  }
};

Note:I have also tried using Pointer Events but the same thing happpens. I have also tried just setting a constant touchmove event and then setting a boolean isSelecting in the selectionchange event if the !selection.isCollapsed but the touch event is disabled when selecting. I have also tried just using the selectionchange event listener to just get the bounding client rect of the selection and go from there but then I run into isssues of selection direction and not accurately being able to find the selection point. In the codesandbox I have that code commented out if you wish to try it.


text:
Q: Safest way to remove argument order and provide default values at the same time in Python I am trying to write Python 2.7 cod that is easier to scale by removing argument order while providing default values in the case that requirements change. Here is my code:
# Class:
class Mailer(object):
    def __init__(self, **args):
        self.subject=args.get('subject', None)
        self.mailing_list=args.get('mailing_list', None)
        self.from_address=args.get('from_address', None)
        self.password=args.get('password', None)
        self.sector=args.get('sector', "There is a problem with the HTML")
# call:
mailer=Mailer(
    subject="Subject goes here",
    password="password",
    mailing_list=("email@email.com", "email@email.com","email@email.com"),
    mailing_list=("email@email.com", "email@email.com"),
    from_address="email@email.com",
    sector=Sector()

)
I'm still new to the language so if there is a better way to achieve this, I'd really like to know. Thanks in advance.

A: Try this way of initialize your class:
class Mailer(object):
    def __init__(self, **args):
        for k in args:
            self.__dict__[k] = args[k]

A: The problem with the way you're doing it is that there is no documentation about what arguments the class accepts, so help(Mailer) is useless. What you should do is provide default argument values in the __init__() method where possible.
To set the arguments as attributes on the instance, you can use a little introspection, as in another answer I wrote, to avoid all the boilerplace self.foo = foo stuff.
class Mailer(object):
    def __init__(self, subject="None", mailing_list=(),
                 from_address="noreply@example.com", password="hunter42",
                 sector="There is a problem with the HTML"):

    # set all arguments as attributes of this instance
    code     = self.__init__.__func__.func_code
    argnames = code.co_varnames[1:code.co_argcount]
    locs     = locals()
    self.__dict__.update((name, locs[name]) for name in argnames)

You can provide the arguments in any order if you make the call using explicit argument names, regardless of how they're defined in the method, so your example call will still work.


text:
Q: RegEx match only final domain name from any email address I want to match only parent domain name from an email address, which might or might not have a subdomain.
So far I have tried this:
new RegExp(/.+@(:?.+\..+)/);

The results:
Input: abc@subdomain.maindomain.com
Output: ["abc@subdomain.domain.com", "subdomain.maindomain.com"]

Input: abc@maindomain.com
Output: ["abc@maindomain.com", "maindomain.com"]

I am interested in the second match (the group).
My objective is that in both cases, I want the group to match and give me only maindomain.com
Note: before the down vote, please note that neither have I been able to use existing answers, nor the question matches existing ones.

A: One simple regex you can use to get only the last 2 parts of the domain name is
/[^.]+\.[^.]$/

It matches a sequence of non-period characters, followed by period and another sequence of non-periods, all at the end of the string. This regex doesn't ensure that this domain name happens after a "@". If you want to make a regex that also does that, you could use lazy matching with "*?":
/@.*?([^.]+\.[^.])$/

However,I think that trying to do everything at once tends to make the make regexes more complicated and hard to read. In this problem I would prefer to do things in two steps: First check that the email has an "@" in it. Then you get the part after the "@" and pass it to the simple regex, which will extract the domain name.
One advantage of separating things is that some changes are easier. For example, if you want to make sure that your email only has a single "@" in it its very easy to do in a separate step but would be tricky to achieve in the "do everything" regex.

A: You can use this regex:
/@(?:[^.\s]+\.)*([^.\s]+\.[^.\s]+)$/gm

Use captured group #1 for your result.

*

*It matches @ followed by 0 or more instance of non-DOT text and a DOT i.e. (?:[^.\s]+\.)*.

*Using ([^.\s]+\.[^.\s]+)$ it is matching and capturing last 2 components separated by a DOT.

RegEx Demo

A: With the following maindomain should always return the maindomain.com bit of the string.
var pattern = new RegExp(/(?:[\.@])(\w[\w-]*\w\.\w*)$/);

var str = "abc@subdomain.maindomain.com";
var maindomain = str.match(pattern)[1];

http://codepen.io/anon/pen/RRvWkr
EDIT: tweaked to disallow domains starting with a hyphen i.e - '-yahoo.com'


text:
Q: Spark dataframes groupby into list I am trying to do some analysis on sets. I have a sample data set that looks like this:
orders.json
{"items":[1,2,3,4,5]}
{"items":[1,2,5]}
{"items":[1,3,5]}
{"items":[3,4,5]}

All it is, is a single field that is a list of numbers that represent IDs.
Here is the Spark script I am trying to run:
val sparkConf = new SparkConf()
  .setMaster("local[*]")
  .setAppName("Dataframe Test")

val sc = new SparkContext(sparkConf)
val sql = new SQLContext(sc)

val dataframe = sql.read.json("orders.json")

val expanded = dataframe
  .explode[::[Long], Long]("items", "item1")(row => row)
  .explode[::[Long], Long]("items", "item2")(row => row)

val grouped = expanded
  .where(expanded("item1") !== expanded("item2"))
  .groupBy("item1", "item2")
  .count()

val recs = grouped
  .groupBy("item1")

Creating expanded and grouped is fine, in a nutshell expanded is a list of all the possible sets of two IDs where the two IDs were in the same original set. grouped filters out IDs that were matched with themselves, then groups together all the unique pairs of IDs and produces a count for each. The schema and data sample of grouped are:
root
 |-- item1: long (nullable = true)
 |-- item2: long (nullable = true)
 |-- count: long (nullable = false)

[1,2,2]
[1,3,2]
[1,4,1]
[1,5,3]
[2,1,2]
[2,3,1]
[2,4,1]
[2,5,2]
...

So, my question is: how do I now group on the first item in each result so that I have a list of tuples? For the example data above, I would expect something similar to this:
[1, [(2, 2), (3, 2), (4, 1), (5, 3)]]
[2, [(1, 2), (3, 1), (4, 1), (5, 2)]]

As you can see in my script with recs, I thought you would start by doing a groupBy on 'item1' which is the first item in each row. But after that you are left with this GroupedData object that has very limited actions on it. Really, you are only left with doing aggregations like sum, avg, etc. I just want to list the tuples from each result.
I could easily use RDD functions at this point, but that departs from using Dataframes. Is there a way to do this with the dataframe functions.

A: You can build that with org.apache.spark.sql.functions (collect_list and struct) available since 1.6
val recs =grouped.groupBy('item1).agg(collect_list(struct('item2,'count)).as("set"))

+-----+----------------------------+
|item1|set                         |
+-----+----------------------------+
|1    |[[5,3], [4,1], [3,2], [2,2]]|
|2    |[[4,1], [1,2], [5,2], [3,1]]|
+-----+----------------------------+

You can use collect_set also
Edit: for information, tuples don't exist in dataframes. The closest structures are struct since they are the equivalent of case classes in the untyped dataset API.
Edit 2: Also be warned that collect_set comes with the caveat that the result is actually not a set (there is no datatype with set properties in the SQL types). That means that you can end up with distinct "sets" which differ by their order (in version 2.1.0 at least). Sorting them with sort_array is then necessary.


text:
Q: ¿Cómo validan una inserción o una selección de datos en PHP? Tengo esta inquietud de hace un rato ya que yo valido con mysqli_num_rows y me arroja errores casi siempre, aunque siempre lo resuelvo, pero quisiera saber de que otra forma se puede hacer esto.
public function AgregarNewAlbum(){

    $acciones = 0;
    $estado  = false;
    $mensaje = "Inciando...";
    $contenido = "";

    if($_POST){
        //INCLUIMOS EL SCRIPT DE CONEXION E INSTANCIAMOS UN OBJETO DE CONEXION
        include_once 'modelo/class.Conexion.php';
        $db = new Conexion();

        $nombreAlbum = $_POST['newAlbum'];
        $descripcionAlbum = $_POST['descripcionAlbum'];
        //ISERTAMOS UN NEW ALBUM
        $sql =  $db->query("INSERT INTO albunes(nombre_album, descripcion_album)VALUES('".$nombreAlbum."','".$descripcionAlbum."')");
        if(!mysql_error()){

            if($wa = $db->rows($sql)>0){
                echo var_dump($wa);
                $acciones = 1;
                $estado = true;
                $mensaje = "NUEVO ALBUM AGREGADO CORRECTAMENTE";

                $sql = $db->query("SELECT * FROM albunes");

                $contenido .='<option>Seleccione Album</option>';

                while($rew = $db->recorrer($sql)){
                    $contenido .= "<option value='".$rew['id_album']."'>".$rew['nombre_album']."</option>";
                }

            //$salidaJson = array("contenido" => $contenido);
            }else{
                $accion = 0;
                $estado = false;
                $mensaje = "NO SE PUDO AGREGAR EL NUEVO ALBUM";

            }

        }else{
            $acciones = 0;
            $estado = false;
            $mensaje = "ERROR,NO SE HA PODIDO AGREGAR EL NUEVO ALBUM ".mysql_error().' - '.mysql_errno();
        }

    }else{

       $mensaje = "NO EXISTEN VARIABLES POST";
    }

    $salidaJson = array("respuesta" => $estado,
                "mensaje" => $mensaje,
                "contenido" => $contenido,
                "acciones" => $acciones);

    echo json_encode($salidaJson);
}
´

Esto me genera el siguiente error:

Warning:  mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\dagg\htdocs\escuelanevada\Intranet\modelo\class.Conexion.php on line 13{"respuesta":false,"mensaje":"NO SE PUDO AGREGAR EL NUEVO ALBUM","contenido":"","acciones":0}"

Pero se inserta perfectamente el nuevo álbum, ¿qué será?

A: Lo que sucede es que la consulta que estás ejecutando arroja errores. eso hace que el resultado de mysqli_query (o mysqli::query si usas el api OOP) no retorne un mysqli_result sino boolean.
Debes validar el resultado de la consulta, es decir:
$resultado =  $db->query("INSERT INTO ...");

if (! $resultado ) {
     // este error lo puedes obtener usando
     // mysqli_error($db) o $db->error;
     return "Error no inserto, ";
} else {
    $lastID = $db->insert_id; // o mysqli_insert_id($db);
    return "Ultimo ID insertado es {$lastID}";
}

El manejo de errores es a tu gusto, es recomendable usar excepciones.

A: No hace que falta que vuelvas a comprobar la inserción con $wa = $db->rows($sql)>0. En mysqli la función query retorna TRUE si estás haciendo un INSERT y ha ido bien.
http://php.net/manual/es/mysqli.query.php

A: Tomando de referencia la respuesta:
Mysqli always return true
y para ampliar la respuesta de Ariel Andres Navarrete Garcia, msqli_query() responde TRUEsiempre que sea un query que no falle; es decir, no depende de que retorne resultados o no.
Dicho esto, la manera adecuada de validar mysqli_query() seria con un or die(mysqli_error()). y ya luego puedes comprobar el count de lo que te retorne con mysqli_num_rows().


text:
Q: The convergence in $L^p$ space If a sequence ${f_i},f \in {L^p}([0,1]){\kern 1pt} {\kern 1pt} (1 < p < \infty )$ such that ${f_i}$ converges weakly to $f$ and ${\left\| {{f_i}} \right\|_p} \to {\left\| f \right\|_p}$, then is ${\left\| {{f_i} - f} \right\|_p} \to 0$ right?

A: Assume WLOG that $\|f_i\| = \|f\| = 1$. Assume that we don't have convergence of $f_n$ to $f$ in norm. So by local uniform convexity we have a subsequence of $(f_n)$ still denoted by $f_n$ such that
$$\left \|\frac{f_n + f}{2}\right \| < C < 1 \text{ for all $n$}.\tag{1}$$
By Hahn-Banach there is a $\varphi \in L^q$ such that $\varphi(f) = 1$ and $\|\varphi\| = 1$.
For this $\varphi$ $(1)$ implies that $|\varphi(f_n) + 1| < 2C$, hence $f_n$ does not converge weakly to $f$.


text:
Q: How assistant model works in swift? I build a new class called StaticCellTableViewController. Now I want to connect some element from the Main.storyboard to it. But I can't have these two windows side by side.
I go the StaticCellTableViewController and click assistant. It gives me two StaticCellTableViewController windows.

I try to click assistant in the Main.storyboard window. It gives me another class like this.

But I want the Main.storyboard window and the StaticCellTableViewController class side by side so I can drag elements to it. How can I do that?

A: You do not need Assistant any more. Don't use it. Editor panes can now contain anything.
So open two normal editor panes. Click in one pane. Click your view controller in the navigator. Click in the other pane. Click your storyboard in the navigator. Done.


text:
Q: golang struct not implementing interface? I am a beginner with go so bear with me on this. I have an interface defined as the following:
type DynamoTable interface {
    Put(item interface{}) interface{ Run() error }
}

also I have a Repo struct like so:
type TenantConfigRepo struct {
    table DynamoTable
}

and i have a struct dynamo.Table which has a Put function defined like so:
func (table dynamo.Table) Put(item interface{}) *Put

and the Put struct has a Run function as follows:
func (p *Put) Run() error

What I am trying to do is have a generic DynamoTable interface which will then be used for mocking and unit tests. however this is causing an issue with creating a new Repo:
func newDynamoDBConfigRepo() *TenantConfigRepo {
    sess := session.Must(session.NewSession())
    db := dynamo.New(sess)
    table := db.Table(tableName) //=> this returns a type dynamo.Table
    return &TenantConfigRepo{
        table: table,
    }
}

This however is throwing an error like so
cannot use table (variable of type dynamo.Table) as DynamoTable value in struct literal: wrong type for method Put (have func(item interface{}) *github.com/guregu/dynamo.Put, want func(item interface{}) interface{Run() error})
this is very strange for me because from what i see is the interface that has a Run() error should be sufficient for the Put struct since it has the same signature. I am not sure what i am doing wrong here.
Thanks!.

A:
wrong type for method Put (have func(item interface{}) *github.com/guregu/dynamo.Put, want func(item interface{}) interface{Run() error})

your function returns a *Put.   The interface expects an interface{Run() error}.  A *Put might satisfy this interface, but they're still different types.  A function signature returning a type that satisfies that interface is not interchangeable with a function signature returning that interface.
So, start by giving your interface a name.  We refer to it in 2 places, and you should avoid anonymous interface (and struct) definitions because they have no inherent benefit and make your code more verbose and less DRY.
type Runner interface{
   Run() error
}

Now update DynamoTable to use that interface
type DynamoTable interface {
    Put(item interface{}) Runner
}

You say dynamo.Table is outside of your control.  But you can create a new type equal to dynamo.Table and then override the put method.
In overridden method, we'l cast our dynamoTable back to dynamo.Table, call the original dynamo.Table.Put, and then return the result.
type dynamoTable dynamo.Table

func (table *dynamoTable) Put(item interface{}) Runner {
  return (*dynamo.Table)(table).Put(item)
}

dynamo.Table Can still return a *Put because *Put implements Runner.  The return value will be Runner and the underlying type will be *Put.  Then the interface will be satisfied, and that error will be fixed.
https://go.dev/play/p/y9DKgwWbXOO illustrates how this retype and override process works.


text:
Q: How to iterate over functions from a library? import hashlib

digest = ["sha1", "sha256", "md5"]

s = "5UA@/Mw^%He]SBaU".encode('utf-8')
h = "3281e6de7fa3c6fd6d6c8098347aeb06bd35b0f74b96f173c7b2d28135e14d45"

dictionary = open("dictionary.txt", "r")
for i in digest:
    for line in dictionary:
        testString = bytes(line, 'utf-8')
        h2 = hashlib.digest[i](testString + s).hexdigest()
        print(h2)
        if h in h2:
            print("the password is:", line)

I am trying to figure out a way to iterate the digests of hashlib. Is a list viable for this? (I know it doesn't work as I'm passing it a string).
Alternatively, what options exist for doing this sort of iteration?

A: If you just want to iterate over a few known functions, I suggest that instead of having a list of names and digging out the corresponding functions, you simply have a list of functions:
digest = [ hashlib.sha1, hashlib.sha256, hashlib.md5 ]
...
for d in digest:
    ...
    hasher = d()
    hasher.update(testString + s)
    h2 = hasher.hexdigest()


text:
Q: Push Notification working well in ios 8 but not in ios 7 I am trying to implement push notification in app.
I have done that for ios 8. on iPad OS is ios8. I got push notification on iPad.
on iPhone OS is iOS7. whenever I compile app on iPhone I got error
/* Failed to get token, error: Error Domain=NSCocoaErrorDomain Code=3000 "no valid 'aps-environment' entitlement string found for application" UserInfo=0x16d246c0 {NSLocalizedDescription=no valid 'aps-environment' entitlement string found for application}*/
My app delegate methods are
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
    // Let the device know we want to receive push notifications
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
}

return YES;
}

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
  {
NSLog(@"My token is: %@", deviceToken);
}

 - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
  {
     NSLog(@"Failed to get token, error: %@", error);
 }

Appreciate for help

A: The message indicates you are using a different signing certificate for iPad/iOS 7 than for iPhone/iOS 8, one without the permission for push notifications set. It has nothing to do with your code.

A: Sounds like your app is picking up the wrong provisioning profile for whatever reason. Does it start working if you explicitly specify the provisioning profile?


text:
Q: undefined method `trigger' for Pusher:Module I am just getting started with the pusher
In config/initializers/pusher.rb
require 'pusher'

Pusher.app_id = 'xxx'
Pusher.key = 'xxx'
Pusher.secret = 'xxx'
Pusher.logger = Rails.logger
Pusher.encrypted = true

In the application.html.erb

// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;

var pusher = new Pusher('xxx', {
  encrypted: true
});

var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
  alert(data.message);
});

In the controller
require 'pusher'
class CheckPushController < ApplicationController
  def show
    Pusher.trigger('test_channel', 'my_event', {
      message: 'hello world'
    })
  end
end

I used the same, in the dashboard I was able to send a trigger to test_channel. However when reloaded the page, I am getting
undefined method `trigger' for Pusher:Module


text:
Q: c# storing images into sql multiple selection I want to store images into sql using c# application. So I have this code, and multiple selection is true. I know that I need to use an array filenames. Can you help me to realize it? I just need to select more than one file in folder and store thme in sql data base.
browse images:
 private void btnBrowseImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            openFileDialog1.Title = "Sekili sec";

            openFileDialog1.InitialDirectory = "E:\\IKA";
            openFileDialog1.Filter = "All files (*.jpg)|*.jpg";
           // openFileDialog1.FilterIndex = 10;
            openFileDialog1.RestoreDirectory = true;

if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    txtImagePath.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

file to binary
byte[] ReadImageToBytes(string sPath)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Open,
                                                    FileAccess.Read);

            //Use BinaryReader to read file stream into byte array.
            BinaryReader br = new BinaryReader(fStream);

            data = br.ReadBytes((int)numBytes);
            return data;
        }

saving them in sql:
private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //Read Image Bytes into a byte array
                byte[] imageSampleData = ReadImageToBytes(txtImagePath.Text);

                //Initialize SQL Server Connection
             //   SqlConnection con = new SqlConnection(txtConnectionString.Text);

                String strConnString = "Data Source=1.1.1.1;Initial Catalog=Test1;User Id=dffr;Password=dffr;";
                SqlConnection con = new SqlConnection(strConnString);
                //Set insert query
                string query = "INSERT INTO tblImages (FullPath,MyImageSample) values(@FullPath, @MyImageSample)";

                //Initialize SqlCommand object for insert.
                SqlCommand cmd = new SqlCommand(query, con);

                cmd.Parameters.Add(new SqlParameter("@FullPath",
                                            (object)txtImagePath.Text));

                cmd.Parameters.Add(new SqlParameter("@MyImageSample",
                                                    (object)imageSampleData));

                //Open connection and execute insert query.
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

            }
            catch
            {
                MessageBox.Show("Error while saving image.", "Error");
            }
        }

A: You need to use FileNames property to get the list of selected files.
 foreach(string filename in openFileDialog1.FileNames)
 {
    //1. read file
    //2. store content of file into database.
 }


text:
Q: How to correctly run this simulation? I am trying to create a simulation but for some reason or other I get an "list index out of range" error. I am not sure what I am doing wrong precisly.
import numpy as np
import math

roomPrice = 280
dayAvailable = [1, 2, 3, 4, 5]
dayDemand = [[1], [2], [3], [4], [5], [1,2], [2,3], [3,4], [4,5], [1,2,3]]
customers = np.random.poisson(lam=250, size=1000)
deny = 0
customersDenied = []
bookings = []
customersHelped = 0
capacityFull = 0

def priceAccept(p):
    value = 1/(1+math.exp(0.025*p-7.5))
    return value

for c in customers:
    capacity = [50, 50, 50, 50, 50]
    probability = np.random.choice([0,1,2,3,4,5,6,7,8,9,],
                                   size = c,
                                   p = [0.15,0.05,0.1,
                                        0.05,0.1,0.2,
                                        0.1,0.1,0.05,0.1])
    for prob in probability:
        for i in dayDemand[prob]:
            if capacity[i] == 0:
                capacityFull += 1
                deny += 1
        if capacityFull == 0:
            priceAcceptCustomer = np.random.choice([1,0], size = 1, p=[priceAccept(roomPrice),1-priceAccept(roomPrice)])
            if priceAcceptCustomer == 1:
                for d in dayDemand[prob]:
                    if capacity[d-1] > 0:
                        capacity[d-1] -= 1
                        customersHelped += 1
    bookings.append(customersHelped)
    customersDenied.append(deny)

It keeps returning the following at if capacity[i] == 0:

IndexError: list index out of range

How can I fix this simulation to run correctly?

A: Array indexation begin with 0. So, the maximum value of i for capacity is 4. Thus, IndexError: list index out of range will be raised when i will be equal to 5.

A: Because the size of dayDemand is 10, capacity is 5:
print(len(dayDemand))   # 10
print(len(capacity))    # 5

If i > 4 in the loop below, you will get this error because capacity is not the 6th or capacity[5] element of the array
for i in dayDemand[prob]:
    if capacity[i] == 0:
        capacityFull += 1


text:
Q: Can not run projects grey run button - Intellij intellij image
I cant run anything, how do i fix the grey run button?
Ive tried to add a new configuration but i cant add a main class

A: Your folder is not marked as src root. You can click on your src folder with right mouse button, find option "Mark Directory As" and hit "Sources root"


text:
Q: How to install Mockito into Eclipse using Gradle I want to use Mockito in my Eclipse, and you can only install it through build programs such as maven or Gradle, I chose to use Gradle. I am a beginner in using Gradle, but I just need to install Mockito and be able to use it as a dependency.

A: You don't actually "install" Mockito. You just add it to your dependency management system. Since you're using Gradle, all you have to do is add it to your build.gradle file. I'm assuming you've started with a blank Gradle project or something like that, which included a default build.gradle file.
Somewhere in that file you'll declare all your project dependencies:
dependencies {
    // other dependencies will be here, just add the following line:
    testCompile("org.mockito:mockito-core:1.10.19")
}
You can find out Mockito's artifact/group ids and available versions here: http://mvnrepository.com/search?q=mockito


text:
Q: Laravel 5 belongsTo relation in same table chaining I have a model like this
Document [id, text, previous_document_id]

And when I retrieve data, I can use this relation:
public function previous()
    {
        return $this->belongsTo('App\Models\Document', 'previous_document_id');
    }

to get a document with it's previous document.
But there is a situation like this: document->previous_document->previous_document and so on.
How can I get this chain ?
Edit:
I don't know how many previous documents exist
Edit2:
Solution is:
public function previous()
{
return $this->belongsTo('App\Models\Document', 'previous_document_id')->with('previous');
}


text:
Q: using rounded corners on galleryview plugin I have a jquery galleryview plugin running to display photos. i would like to add rounded corners to the photos, so i tried applying the corners plugin to the .panel holding the image. unfortunately it doesnt work. the photo starts square and then when it transitions you can see the rounding for a second and then it ends square again.
any thoughts on how to go about this would be appreciated.
the site is in production at www.dnbsandox.com/caliaq/
you can see that corners.js plugin is working on the box holding the gallery (div#photos).

A: You need not to use the rounded corners.js you can do this with css,
div#photos{
-moz-border-radius: 5px; //mozilla
-webkit-border-radius: 5px; //safari
}


text:
Q: A way to extract hands from a video I wonder whether it would be possible to extract only hands from a video with matlab. In the video hands perform some gesture. Because first frames are only background I tried in this way:
readerObj = VideoReader('VideoWithHands.mp4');
nFrames = readerObj.NumberOfFrames;
fr = get(readerObj, 'FrameRate');
writerObj = VideoWriter('Hands.mp4', 'MPEG-4');
set(writerObj, 'FrameRate', fr);
open(writerObj);
bg = read(readerObj, 1);   %background
for k = 1 : nFrames
      frame = read(readerObj, k);
      hands = imabsdiff(frame,bg);
      writeVideo(writerObj,hands);
end
close(writerObj);

But I realized that colors of the hands are not "real" and they are transparent. Is there a better way to extract them from video keeping colors and opacity level exploiting the first frames (background)?
EDIT: Well, I have found a good setting for vision.ForegroundDetector object, now hands are white logical regions but when I try to visualize them with:
videoSource = vision.VideoFileReader('VideoWithHands.mp4', 'VideoOutputDataType', 'uint8');

detector = vision.ForegroundDetector('NumTrainingFrames', 46, 'InitialVariance', 4000, 'MinimumBackgroundRatio', 0.2);

videoplayer = vision.VideoPlayer();
hands = uint8(zeros(720,1280,3));
while ~isDone(videoSource)

    frame = step(videoSource);
    fgMask = step(detector, frame);

    [m,n] = find(fgMask);
    a = [m n];
    if isempty(a)==true

        hands(:,:,:) = uint8(zeros(720,1280,3));
    else

        hands(m,n,1) = frame(m,n,1);
        hands(m,n,2) = frame(m,n,2);
        hands(m,n,3) = frame(m,n,3);

    end

    step(videoplayer, hands)

end

release(videoplayer)
release(videoSource)

or put them into a videofile with:
eaderObj = VideoReader('Video 9.mp4');
nFrames = readerObj.NumberOfFrames;
fr = get(readerObj, 'FrameRate');

writerObj = VideoWriter('hands.mp4', 'MPEG-4');

set(writerObj, 'FrameRate', fr);

detector = vision.ForegroundDetector('NumTrainingFrames', 46, 'InitialVariance', 4000, 'MinimumBackgroundRatio', 0.2);
open(writerObj);

bg = read(readerObj, 1);

frame = uint8(zeros(size(bg)));

for k = 1 : nFrames

frame = read(readerObj, k);

   fgMask =  step(detector, frame);

[m,n] = find(fgMask);

hands = uint8(zeros(720,1280));

if isempty([m n]) == true

    hands(:,:) = uint8(zeros(720,1280));

else

    hands(m,n) = frame(m,n);

end

 writeVideo(writerObj,mani);

end

close(writerObj);

...my PC crashes. Some suggestion?

A: So you're trying to cancel out the background, making it black, right?
The easiest way to do this should be to filter it, you can do that by comparing your difference data to a threshold value and then using the result as indices to set a custom background.
filtered = imabsdiff(frame,bg);
bgindex = find( filtered < 10 );
frame(bgindex) = custombackground(bgindex);

where custombackground is whatever image file you want to put into the background. If you want it to be just black or white, use 0 or 255 instead of custombackground(bgindex). Note that the numbers depend on your video data's format and could be inaccurate (except 0, this one should always be right). If too much gets filtered out, lower the 10 above, if too much remains unfiltered, increase the 10.
At the end, you write your altered frame back into the video, so it just replaces the hands variable in your code.
Also, depending on your format, you might have to do the comparison across RGB values. This is slightly more complicated as it involves checking 3 values at the same time and doing some magic with the indices. This is the RGB version (works with anything containing 3 color bands):
filtered = imabsdiff(frame,bg); % differences at each pixel in each color band
totalfiltered = sum(filtered,3); % sums up the differences
                                 % in each color band (RGB)
bgindex = find( totalfiltered < 10 ); % extracts indices of pixels
                                      % with color close to bg
allind = sub2ind( [numel(totalfiltered),3] , repmat(bgindex,1,3) , ...
                  repmat(1:3,numel(bgindex),1) ); % index magic

frame(allind) = custombackground(allind); % copy custom background into frame

EDIT :
Here's a detailed explanation of the index magic.
Let's assume a 50x50 image. Say the pixel at row 2, column 5 is found to be background, then bgindex will contain the number 202 (linear index corresponding to [2,5] = (5-1)*50+2 ). What we need is a set of 3 indices corresponding to the matrix coordinates [2,5,1], [2,5,2] and [2,5,3]. That way, we can change all 3 color bands corresponding to that pixel. To make calculations easier, this approach actually assumes linear indexing for the image and thus converts it to a 2500x1 image. Then it expands the 3 color bands, creating a 2500x3 matrix. We now construct the indices [202,1], [202,2] and [202,3] instead.
To do that, we first construct a matrix of indices by repeating our values. repmat does this for us, it creates the matrices [202 202 202] and [1 2 3]. If there were more pixels in bgindex, the first matrix would contain more rows, each repeating the linear pixel coordinates 3 times. The second matrix would contain additional [1 2 3] rows. The first argument to sub2ind is the size of the matrix, in this case, 2500x3, so we calculate the number of pixels with numel applied to the sum vector (which collapses the image's 3 bands into 1 value and thus has 1 value per pixel) and add a static 3 in the second dimension.
sub2ind now takes each element from the first matrix as a row index, each corresponding element from the second matrix as a column index and converts them to linear indices into a matrix of the size we determined earlier. In our example, this results in the indices [202 2702 5202]. sub2ind preserves the shape of the inputs, so if we had 10 background pixels, this result would have the size 10x3. But since linear indexing doesn't care about the shape of the index matrix, it just takes all of those values.
To confirm this is correct, let's revert the values in the example. The original image data would have the size 50x50x3. For an NxMxP matrix, a linear index to the subscript [n m p] can be calculated as ind = (p-1)*M*N + (m-1)*N + n. Using our values, we get the following:
[2 5 1] => 202
[2 5 2] => 2702
[2 5 3] => 5202

ind2sub confirms this.

A: Yes, there is a better way.  The computer vision system toolbox includes a vision.ForegroundDetector object that does what you need. It implements the Gaussian Mixture Model algorithm for background subtraction.


text:
Q: UI components dont update after backing bean value has changed <h:form>

                    First Name:
                    <h:outputText value="#{profile.firstName}"
                            rendered="#{not profile.canEdit}" />
                    <h:inputText value="#{profile.firstName}"
                            rendered="#{profile.canEdit}" required="true" />
                    <h:commandButton value="Edit"
                            action="#{profile.editDetail}" />
                    <h:commandButton value="Cancel" type="button"
                            action="#{profile.cancelBtn}" />

                    Last Name:
                    <h:outputText value="#{profile.lastName}"
                            rendered="#{not profile.canEdit}" />
                    <h:inputText value="#{profile.lastName}"
                            rendered="#{profile.canEdit}" required="true" />
                    <h:commandButton value="Edit"
                            action="#{profile.editDetail}" />
                    <h:commandButton value="Cancel" type="button"
                            action="#{profile.cancelBtn}" />

                    Email:
                    <h:outputText value="#{profile.email}"
                            rendered="#{not profile.canEdit}" />
                    <h:inputText value="#{profile.email}" id="email"
                            rendered="#{profile.canEdit}" required="true" />
                    <h:commandButton value="Edit"
                            action="#{profile.editDetail}" />
                    <h:commandButton value="Cancel" type="button"
                            action="#{profile.cancelBtn}" />
                    <h:message for="email" value="#{profile.errorMessage}"
                            rendered="#{profile.errorMessage ne null}" />

                    Password:
                    <h:outputText value="#{profile.password}"
                            rendered="#{not profile.canEdit}" />
                    <h:commandButton value="Edit"
                            action="#{profile.editDetail}" />
                    <h:commandButton value="Cancel" type="button"
                            action="#{profile.cancelBtn}" />

                <h:panelGroup rendered="#{profile.canEdit}">

                        Old Password:
                        <h:inputText value="#{profile.password}" required="true" />
                        <h:outputText rendered="#{profile.errorMessage != null}"
                                value="#{profile.errorMessage}"></h:outputText>

                        New Password:
                        <h:inputSecret value="#{profile.newPassword}"
                                required="true" />

                        Confirm Password:
                        <h:inputSecret value="#{profile.confirmPassword}"
                                required="true" />
                        <h:outputText
                                rendered="#{profile.confirmPassword != profile.newPassword}"
                                value="Passwords donot match!!"></h:outputText>

                        <h:commandButton action="#{profile.savePassword}"
                                value="Save Password"
                                disabled="#{profile.confirmPassword != profile.newPassword}" />
                        <h:commandButton action="#{profile.cancelBtn}" value="Cancel" type="button"/>

                </h:panelGroup>

                    Gender
                    #{profile.gender}

                    City
                    #{profile.city}

                    State
                    #{profile.state}

                    Country
                    #{profile.country}

                    Zip-Code
                    #{profile.zipCode}

                    Phone Number
                    #{profile.phoneNumber}

                    <h:commandButton action="#{profile.saveDetails}"
                            disabled="#{profile.canEdit eq 'false'}" value="Save" />
                    <h:commandButton action="#{profile.cancelBtn}" type="button"
                            value="Cancel" />

        </h:form>

My code snippet of my backing bean
public String InitializeValues(){

    customer = (CustomerVO) sessionManager.getSession("CustomerBean");
    System.out.println("inside profilepagecontroller"+"\n"+ customer);
    setFirstName(customer.getFirstName());
    this.setLastName(customer.getLastName());
    this.setEmail(customer.getEmail());
    this.setPassword(customer.getPassword());
    this.setCity(customer.getCity());
    this.setState(customer.getState());
    this.setCountry(customer.getCountry());
    this.setPhoneNumber(customer.getPhoneNumber());
    this.setGender(customer.getGender());
    this.setZipCode(customer.getZipCode());
    this.setCustomerId(customer.getCustomerId());

    return "ProfilePage";

}

public String editDetail(){
    setCanEdit(true);
    setCanSave(true);
    return null;
}

public String cancelBtn(){
    setCanEdit(false);
    return "ProfilePage";
}

Problems and solutions i need

*

*when i click on cancelbutton, canEdit sets to false, but the
inputText does not get 'un'rendered on the screen. it does not render
outputText.

*how do i get only a particular field in edit mode after i click edit?( creating separate boolean values for each field obv not
feasible)

*setter methods set the values of fields of backing beans. after i run the code, same are not displayed on the screen. 'this' gets all
the values which i need to display,  but not displayed on screen.

A:
when i click on cancelbutton, canEdit sets to false, but the inputText
  does not get 'un'rendered on the screen. it does not render outputText

Your commandButton has type="button" that shouldn't be the case.

how do i get only a particular field in edit mode after i click edit?(
  creating separate boolean values for each field obv not feasible)

Huh Sure it is feasible. The only scenario I'd see you using that is if validation didn't pass for some component. Then I think you could try #{component.valid} in rendered. The problem is that all the component will be vaalid at the start then the invalid will not be rendered. To solve that check if the request is a postback:
public boolean isPostback(){
    return FacesContext.getCurrentInstance().isPostback();
}
rendered="#{component.valid and not mybean.postback}"

setter methods set the values of fields of backing beans. after i run
  the code, same are not displayed on the screen. 'this' gets all the
  values which i need to display, but not displayed on screen.

I don't understand that question is it your capitalized method Initialize that your are talking about ? you should post the whole bean as well cuz it's never called here.