text:
Q: How to automatically put the part of a variable name after the first letter in symbolized subscripts? So here is what I have thought:
Use ToString and StringLength in order to get the number of characters in the variable name.
If it is bigger than one, change variable name by putting everything but the first character as subscript.
Symbolize subscipt to avoid issues.
Example:
Going from $ux1 - i1$ to $u_{x1}-i_1$
$x$ is a variable but I do not want any interference with u_{x...}!
About the symbolization of subscripts I looked up and found this:
Needs["Notation`"];
Symbolize[ParsedBoxWrapper[SubscriptBox["_", "_"]]];

For the rest I have not been able to do it mainly because I do not manage to make the function go through an expression and change all the elements of it. I also tried to use Replace but failed.

A: It is not entirely clear to me what you are actually trying to accomplish.  Using subscripts in Mathematica often needlessly complicates things.  Since you are looking for an automated replacement I think you prefer not to enter subscripts manually which I think is wise.  I believe it also means you are looking for a formatting function.
A basic approach is to work with strings.  We may write:
ux1 - i1 /. s_Symbol /; Context[s] === $Context :>
  (Subscript[#, "" <> ##2] & @@ Characters @ SymbolName[s])

If string output is not acceptable we may wish to use HoldForm to keep elements from evaluating.  This is important if for example x1 or i are Symbols with a value:
x1 = i = "Fail!";

ux1 - i1 /. s_Symbol /; Context[s] === $Context :>
 (HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@ Characters @ SymbolName[s])

Additionally you may consider the case where these replacements must be done inside a held expression, where e.g. i1 has a global value.  You will need Unevaluated and RuleCondition:
i1 = x1 = i = "Fail!";

Hold[ux1 - i1] /. s_Symbol /; Context[s] === $Context :>
  RuleCondition[HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@
     Characters @ SymbolName @ Unevaluated @ s]

If I am correct that you want this for formatting purposes you might make use of a formatting wrapper, which will allow you to extract the original unmodified expression, or define rules for function to work with that expression.
MakeBoxes[subscriptForm[expr_], fmt_] :=
 MakeBoxes[#, fmt] &[
  expr /. s_Symbol /; Context[s] === $Context :>
    RuleCondition[HoldForm @@@ MakeExpression /@ Subscript[#, "" <> ##2] & @@
      Characters @ SymbolName @ Unevaluated @ s]
 ]

Now:
expr = subscriptForm[Hold[ux1 - i1]]

First @ expr

Hold[ux1 - i1]

A: You mean something like this?
f[x_] := If[Length[#] > 1 && MemberQ[Names[$Context <> "*"], ToString@x],
    Subscript[ToExpression@First@#, ToExpression@StringJoin@Rest@#], x]&
    @ StringSplit[ToString[x], ""];

It first defines a pure function, where # is the unnamed argument. Then it applies it to the list of characters of x converted to a string. A simpler example of this method:
# Log[2, #] & @ 3

This is the same as 3 Log[2, 3].
Use the expression from above like this on general expressions:
Map[f, ux1 - i1, -1]

-Subscript[i, 1] + Subscript[u, x1]

It should work for simple expressions, but I can't guarantee it for more complex stuff. I always avoid ToExpression wherever I can (which is pretty much always). There are lots of opportunities for unforeseen side effects...


text:
Q: SQL INNER JOIN two arrays of values from the same table I have a simplified query where I just need to get the intersection of two arrays. When there is a positive intersection, I am getting the expected result returned. But if there is no result, I get all rows returned from the entire table, as opposed to the expected zero rows.
This is one query where I get one row returned, as expected:
SELECT ID FROM table_name WHERE ID IN (7188,2442,10350) AND ID IN (10350,6936)

It returns one row with the ID 10350, as expected.
But if I try this query:
SELECT ID FROM table_name WHERE ID IN (7188,2442) AND ID IN (10350,6936)

it returns the entire table, instead of zero rows.
Clearly, my syntax is incorrect, but I don't know how to write the proper query that will find the intersection of two arrays. Can I please find out how to write such an intersection the correct way? Please notice that this is only one table (as opposed to an INNER JOIN from multiple tables). I have to use multiple arrays as the sets to be compared.
I've searched SO and Google for a long time, but nothing seems to come up. It seems like there should be a simple answer to this.

A: I was running this query and getting an empty result after all. But then I sent the result immediately to a WordPress function, which happens to return all rows if you call an empty array as one of the values in $args.
When I saw your comments that the finding wasn't being replicated, I realized I needed to isolate the problem further. So those comments helped me solve the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regular expression doesn't work in Go forgive me for being a regex amateur but I'm really confused as to why this doesn't piece of code doesn't work in Go
package main

import (
    "fmt"
    "regexp"
)

func main() {
    var a string = "parameter=0xFF"
    var regex string = "^.+=\b0x[A-F][A-F]\b$"
    result,err := regexp.MatchString(regex, a)
    fmt.Println(result, err)
}
// output: false <nil>

This seems to work OK in python
import re

p = re.compile(r"^.+=\b0x[A-F][A-F]\b$")
m = p.match("parameter=0xFF")
if m is not None:
    print m.group()

// output: parameter=0xFF

All I want to do is match whether the input is in the format <anything>=0x[A-F][A-F]
Any help would be appreciated

A: Have you tried using raw string literal (with back quote instead of quote)?
Like this:
var regex string = `^.+=\b0x[A-F][A-F]\b$`

A: You must escape the \ in interpreted literal strings :
var regex string = "^.+=\\b0x[A-F][A-F]\\b$"

But in fact the \b (word boundaries) appear to be useless in your expression.
It works without them :
var regex string = "^.+=0x[A-F][A-F]$"

Demonstration


text:
Q: Odd results from mongoid using Debian squeeze mongodb I'm experiencing odd results in data returned from gem, mongoid using mongodb on Debian squeeze. The data is good. How can I stop these consistent failures to return the data correctly?
My mongodb is the latest in Debian squeeze backports and I'm using gem mongoid.
$ dpkg-query -l mongodb
mongodb 1:2.0.0-2~bpo60+1

I did $ sudo apt-get -t squeeze-backports install mongodb to get the newest version.

A: For anyone experiencing odd problems on Debian squeeze mongodb, it seems that currently the Debian backports metapackage mongodb doesn't require its dependencies (such as mongodb-server) to be from backports, nor to be of the same version. So, installing simply with $ sudo apt-get -t squeeze-backports install mongodb often fails silently.
A Debian mongodb bug report 703580 can be seen here.
To avoid this problem, just install all its dependencies from backports explicitly:
$ sudo apt-get -t squeeze-backports install mongodb mongodb-clients mongodb-dev mongodb-server
$ mongo
MongoDB shell version: 2.0.0
connecting to: test
> db.serverStatus().version
2.0.0
$ dpkg-query -l 'mongodb*'
||/ Name             Version            Description
+++-================-==================-==============
ii  mongodb          1:2.0.0-2~bpo60+1  object/document-oriented database (metapackage)
ii  mongodb-clients  1:2.0.0-2~bpo60+1  object/document-oriented database (client apps)
ii  mongodb-dev      1:2.0.0-2~bpo60+1  object/document-oriented database (development)
ii  mongodb-server   1:2.0.0-2~bpo60+1  object/document-oriented database (server package)


text:
Q: haskell-stack getting TlsExceptionHostPort error Been running stack/ghc inside Debian 8.2 via vagrant for a while. This morning:
$  stack setup
Run from outside a project, using implicit global project config
Using resolver: lts-4.2 from implicit global project's config file: /home/vagrant/.stack/global-project/stack.yaml
Downloading lts-4.2 build plan ...TlsExceptionHostPort (HandshakeFailed (Error_Protocol ("certificate has expired",True,CertificateExpired))) "raw.githubusercontent.com" 443

$  stack --version
Version 1.0.2, Git revision fa09a980d8bb3df88b2a9193cd9bf84cc6c419b3 (3084 commits) x86_64

The same error remains even if I delete ~/.stack. Did I mess something up?

A: You might want to try running stack -v setup to be able to see which files are being downloaded.
Then identify which file(s) cannot be downloaded due to this TlsExceptionHostPort - hopefully there won't be too many of them - and run:
curl -0 https://raw.githubusercontent.com/path_to_your_file > your_file

Once your blocking file(s) have been downloaded, re-run stack setup.
This might not be a clean approach, but it worked for me.


text:
Q: .NET numeric library supporting decimal and NaN I wonder if there is any .NET numeric library which supports decimal and NaN?
I searched in Google, but only found some ones without decimal or NaN support. Do you know any one supporting decimal and NaN?

Sorry for not enough information! Actually I want to port some R code into C#. R has NA for missing data in matrix. As I can imagine, one way in C# to handle this situation is to store data with missing ones in Nullable< decimal > temporarily, and remove the NAs and translate Nullable< decimal > into decimal before calculation; another ways is to use a library support Nullable< decimal > or NaN directly, therefore saving the time without copying large data. Is there a better ways?

A: If you mean NaN for the decimal type, well, NaN is not a number; in which case you could return a null version of a nullable decimal, as per this:
Why is Nan (not a number) only available for doubles?

A: Can you provide an example of where you would need this? .Net supports decimal and also decimal.TryParse().
Otherwise I don't think you would need a library for this.


text:
Q: How do I add child class objects to a vector of their parent class (C++)? I have various shape classes, from rectangle, circle, square, pentagon, etc., all child classes of the Shape class, and all of which have a getArea() method that returns their area.  I'm trying to make a vector of Shape that can add the areas of all those shapes so I can use a function to calculate the total area.  This is the part of the code I'm having trouble with.  I haven't finished writing the getTotalArea method but that will be easy.  I just need to know how to name that method (the getTotalArea method) and what reference or pointer to use.  Also the only way I could get the bottom part of the main method to compile was to use a pointer for the Shape in vector and reference to the child objects when adding them to the vector:
vector<Shape*> shapes;
shapes.push_back(&circle);

Any ideas?  I greatly appreciate your help.

#include <iostream>
#include "shape.h"
#include "point.h"
#include <vector>
using namespace std;
double getTotalArea(vector<Shape> sh)
{
  return 0;
}
int main(int argc, char** argv)
{
  vector<Point> my_points;
  my_points.push_back(Point(2, 3));
  my_points.push_back(Point(1, 1));
  my_points.push_back(Point(3, 1));
  cout << "Points for a triangle:\n\n";
  Triangle triangle(my_points);
  cout << triangle << "area = " << triangle.getArea();
  my_points.clear();

  my_points.push_back(Point(2, 7));
  my_points.push_back(Point(9, 7));
  my_points.push_back(Point(2, 3));
  my_points.push_back(Point(9, 3));
  cout << "\n\nPoints for a rectangle:\n\n";
  Rectangle rectangle(my_points);
  cout << rectangle << "area = " << rectangle.getArea();
  my_points.clear();

  my_points.push_back(Point(0, 5));
  my_points.push_back(Point(5, 5));
  my_points.push_back(Point(0, 0));
  my_points.push_back(Point(5, 0));
  cout << "\n\nPoints for a square:\n\n";
  Square square(my_points);
  cout << square << "area = " << square.getArea();
  my_points.clear();

  my_points.push_back(Point(0, 5));
  my_points.push_back(Point(6, 6));
  my_points.push_back(Point(10, 5));
  my_points.push_back(Point(8, 3));
  my_points.push_back(Point(1, 2));
  cout << "\n\nPoints for a pentagon:\n\n";
  Pentagon pentagon(my_points);
  cout << pentagon << "area = " << pentagon.getArea();
  my_points.clear();

  my_points.push_back(Point(3, 5));
  cout << "\n\nLength of semi-major axis and length of semi-minor axis for an oval (put in a Point object)):\n\n";
  Oval oval(my_points);
  cout << oval << "area = " << oval.getArea();
  my_points.clear();

  cout << "\n\nRadius of a circle (first parameter of a Point object - second is ignored):\n\n";
  my_points.push_back(Point(12, 0));  //the second argument here can also be NULL
  Circle circle(my_points);
  cout << circle << "area = " << circle.getArea();
  my_points.clear();

  vector<Shape*> shapes;
  shapes.push_back(&circle);
  shapes.push_back(&rectangle);
  shapes.push_back(&square);
  shapes.push_back(&pentagon);
  shapes.push_back(&oval);
  shapes.push_back(&circle);
  double totalArea = getTotalArea(shapes);

  return 0;
}

I solved the problem I was having, thanks to some of you who pointed me in the right direction.  This is what I got, and it works without flaw:
  //a function outside the main method
  void displayTotalArea(vector<Shape*>& sh)
  {
     double total = 0;

     for (int x = 0; x < sh.size(); x++)
     {
       total += sh[x]->getArea();
     }
     cout << "\n\nTotal area of all shapes = " << total;
  }

  //in the main method
  vector<Shape*> shapes;
  shapes.push_back(&pentagon);
  shapes.push_back(&triangle);
  shapes.push_back(&rectangle);
  shapes.push_back(&square);
  shapes.push_back(&pentagon);
  shapes.push_back(&oval);
  shapes.push_back(&circle);
  displayTotalArea(shapes);

A: If I understood what you are up to, this would do fine:
double getTotalArea(const vector<Shape*>& sh)
{
    double tot = 0;

    for (Shape* s : sh)
        tot += s->getArea();

    return tot;
}

to add child to the container (and then using vector<Shape> instead of vector<Shape*>, that is better since when the vector goes out of scope, with the non-pointer version it would release the shapes):
Triangle t;
Oval v;
std::vector<Shape> container;
container.push_back(t);
container.push_back(v);

this compiles ok:
#include <iostream>
#include <vector>

class A {};
class B : public A {};
class C : public A {};

int main()
{
    std::vector<A> vec;
    vec.push_back(B());
    vec.push_back(C());

    B instance;
    vec.push_back(instance);

    return 0;
}


text:
Q: solr group query to return results along with normal results i am trying a group query in solr which is
http://localhost:8983/solr/venue/select?q=allText%3A%22holiday+inn%22&rows=100&wt=json&indent=true&group=true&group.query=title:(holiday%20inn)&group.limit=10

this gives me results where "holiday inn" matches in title, allText field is a copy field which has values from fields title,location and description
what i tried was setting
group.main=true

but after doing this it gives me all the records without the grouping.
what i want is all records with the groupings
thanks in advance
the query i used after the suggestion was
http://localhost:8983/solr/venue/select?wt=json&indent=true&q=*%3A*&wt=json&rows=100000&fq=title:%22holiday%20inn%22&fl=title&group=true&group.field=title&group.limit=100000

and this gave me result
"responseHeader":{
"status":0,
"QTime":30,
"params":{
  "q":"allText:(holiday inn)",
  "indent":"true",
  "fl":"title",
  "group.limit":"100000",
  "fq":"title:\"holiday inn\"",
  "rows":"100000",
  "wt":["json",
    "json"],
  "group.field":"title",
  "group":"true"}},
"grouped":{
"title":{
  "matches":1,
  "groups":[{
      "groupValue":"holiday",
      "doclist":{"numFound":1,"start":0,"docs":[
          {
            "id":209,
            "title":"Holiday Inn"}]
      }}]}}]

along with the group result which is correct can i also get the result for q=allText:(holiday inn) which without the group gives 25 matched results??

A: This is a working sample Group QUERY
q=*%3A*&wt=json&rows=100000&fq=reported_dt:[2015-10-25T14:55:13.000Z%20TO%202015-12-04T08:38:08.000Z]&fl=reported_dt project_status_val&group=true&group.field=project_number&group.limit=100000

The difference i see you dont Have a numeric group field in your QUERY.


text:
Q: What algorithm is fast and good (optimized) for comparing candidates? I'm using Vim plugin neocomplcache. And I hope a better compare_func for neocomplcache's popup menu candidates.
You can find the default compare_func at here.
And here is the issue I post on GitHub.
Reference:

*

*neocomplcache
I'm still newbie on programming, I'm not good on algorithm, basiclly totally do not know the algorithm.
Anyway, I want to know what algorithm or ways is good for this case.
And thanks.


text:
Q: Django testing MySQL permission I am going through the Django tutorial and I've run into some trouble because I'm using MySQL as my database.
When I run
    python manage.py test polls

I get
    Creating test database for alias 'default'...
    Got an error creating the test database: (1044, "Access denied for user 'USER123'@'%' to database 'test_USER123'")
    Type 'yes' if you would like to try deleting the test database 'test_USER123', or 'no' to cancel:

This is my settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
            'NAME': 'USER123',                      # Or path to database file if using sqlite3.
    # The following settings are not used with sqlite3:
            'USER': 'USER123',
            'PASSWORD': 'PASSWORD',
            'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
            'PORT': '',                      # Set to empty string for default.
}

}
I was wondering if anyone would explain to me what's wrong and what's going on. Thank you!


text:
Q: Redux-Saga take function with additional arguments I'm trying to create a set of 'taker' functions : functions passed to the take effect in order to share them and make sagas easier to test.
A taker looks like this:
export const takeFn = action => action.type === 'ACTION_TYPE'

In the saga:
yield take(takeFn)

That works fine but I don't know how to pass an extra argument to my taker:
export const takeFn = action => action.type === 'ACTION_TYPE' && action.payload.arg === **arg**

Any ideas?

A: Sounds like you'll want to make it a higher order function. You pass in some value that you want to check, and you'll get returned a taker function that will check that. For example:
export const makeTaker = arg => action => action.type === 'ACTION_TYPE' && action.payload.arg === arg;

// ...

yield take(makeTaker('hello'))


text:
Q: Finding the MSE of a uniformly distributed random variable Below is a problem I did from the book "Mathematical Statistics with Applications". It is problem 8.6. For parts a and b, I believe I did the correctly since my answer match's the answer in the back of the book. However, it does not for part c. I would like to know what I did wrong.
Problem:
The reading on a voltage meter connected to a test circuit is uniformly distributed over the interval $(\theta,\theta+1)$ where $\theta$ is the true but unknown voltage of the circuit. Suppose that $Y_1, Y_2, ..., Y_n$ denotes the a random sample of such readings.
(a) Show that $\overline{Y}$ is a biased estimator of $\theta$ and compute the bias.
(b) Find a function of $\overline{Y}$ that is an unbiased estimator of $\theta$.
(c) Find $MSE(\overline{Y})$ when $\overline{Y}$ is used as estimator of $\theta$.
Answer:(a)
Since each reading is going to be above the actual reading, $\overline{Y}$ must be above the actual mean. Let $B$ be the bias we seek.
\begin{align*}
B &= E(\overline{Y}) - Y \\
E(\overline{Y}) &= \int_{\theta}^{\theta+1} y \, dy = \frac{y^2}{2} \Big|_{\theta}^{\theta+1} \\
E(\overline{Y}) &= \frac{(\theta+1)^2}{2} - \frac{\theta^2}{2} = \frac{\theta^2 + 2\theta + 1}{2} - \frac{\theta^2}{2} \\
E(\overline{Y}) &= \frac{2\theta + 1}{2} \\
B &= \frac{2\theta + 1}{2} - \theta \\
B &= \frac{1}{2}
\end{align*}
Part b:
Let $u$ be the unbiased estimator we seek:
$$ u = \overline{Y} - \frac{1}{2} $$
Part c:
\begin{align*}
MSE(\overline{Y}) &= V(\overline{Y}) + B^2 \\
\text{Now we need to find the variance of $\overline{Y}$.} \\
MSE(\overline{Y}) &= E((\overline{Y} - Y)^2) \\
E((\overline{Y} - Y)^2) &= \int_{\theta}^{\theta+1} \left( \frac{2\theta + 1}{2} - y \right)^2 \, dy \\
E((\overline{Y} - Y)^2) &= \int_{\theta}^{\theta+1} \left( \theta + \frac{1}{2} - y \right)^2 \, dy  \\
E((\overline{Y} - Y)^2) &= -\frac{ \left( \theta + \frac{1}{2} - y \right)^3}{3} \Big|_{\theta}^{\theta+1} \\
E((\overline{Y} - Y)^2) &= -\frac{ \left( \theta + \frac{1}{2} - \left( \theta+1 \right)  \right)^3}{3} +
 \frac{ \left( \theta + \frac{1}{2} - \theta \right)^3}{3} \\
E((\overline{Y} - Y)^2) &= -\frac{\left( - \frac{1}{2} \right) ^3}{3} + \frac{\left( \frac{1}{2} \right) ^3}{3} \\
E((\overline{Y} - Y)^2) &= \frac{ \frac{1}{8} }{3} + \frac{ \frac{1}{8}} {3} \\
E((\overline{Y} - Y)^2) &= \frac{1}{12} \\
\end{align*}
However, the book gets:
$$ \frac{1}{12n} + \frac{1}{4} $$
Based upon the comments I got from George Dewhirst. I am going to try again.
\begin{align*}
MSE &= E\left( \left( \frac{1}{y_n} \sum_{i = 1}^{n} y_i - \frac{2 \theta + 1}{2} \right) ^ 2 \right)
\end{align*}
I am going to look at the special case of $n = 1$.
\begin{align*}
MSE &= E\left( \left( y_1 - \frac{2 \theta + 1}{2} \right) ^ 2 \right) \\
MSE &= \int_{\theta}^{\theta+1} \left( y_1 - \frac{2 \theta + 1}{2} \right) ^ 2 \, dy_1 \\
MSE &= \frac{ \left( y_1 - \frac{2 \theta + 1}{2} \right) ^ 3}{3} \big|_{\theta}^{\theta+1} \\
MSE &= \frac{ \left( \theta + 1 - \frac{2 \theta + 1}{2} \right) ^ 3}{3} - \frac{ \left( \theta - \frac{2 \theta + 1}{2} \right) ^ 3}{3} \\
MSE &= \frac{ \left( \frac{1}{2} \right) ^ 3}{3} - \frac{ \left( \frac{-1}{2} \right) ^ 3 }{3}  = \frac{1}{24} + \frac{1}{24} \\
MSE &= \frac{1}{12}
\end{align*}
For the special case of $n = 1$ the book gets $\frac{1}{12} + \frac{1}{4}$ or $\frac{1}{3}$. Hence, I conclude my answer is wrong.
I know have what I believe to be the correct solution. I am hoping that somebody can confirm that it is right or tell me where I went wrong.
Part c:
\begin{align*}
MSE(\overline{Y}) &= V(\overline{Y}) + B^2 \\
\text{Now we need to find the variance of $\overline{Y}$.} \\
\end{align*}
Recall that the variance of a uniformly distributed random variable on the interval $[a,b]$ is $\frac{b-a}{12}$. Hence the variance
of $y_i$ is $\frac{1}{12}$.
\begin{align*}
Var(\overline{Y}) &= \left( \frac{1}{n} \right) \sum_{i = 1}^{n} {\frac{1}{12}} \\
Var(\overline{Y}) &= \frac{1}{12n} \\
MSE( \overline{\theta} ) &= Var( \overline{\theta} ) + B^2 \\
MSE( \overline{\theta} ) &= \frac{1}{12} + \left( \frac{1}{2} \right) ^2 \\
MSE( \overline{\theta} ) &= \frac{1}{12n} + \frac{1}{4} \\
\end{align*}

A: The formula for correlation is:
$$\rho = \frac{\sigma_{xy}}{ \sigma_x \sigma_y } $$
Observe that the $E(X) = E(Y) = 0$.
\begin{align*}
E(X^2) &= \int_{-1}^{1} \frac{x^2}{2} \, dx = \frac{x^3}{6} \Big|_{-1}^{1} = \frac{1}{6} - \frac{-1}{6} \\
E(X^2) &= \frac{1}{3} \\
\sigma_x^2 &= E(X^2) - (E(x))^2 = \frac{1}{3} \\
\sigma_x &=\frac{ \sqrt{3} }{3} \\
E(Y^2) &= \int_{-1}^{1} y^2 f(y) \, dy = \int_{-1}^{0} y^2 f(y) \, dy + \int_{0}^{1} y^2 f(y) \, dy \\
E(Y^2) &= 2 \int_{-1}^{1} y^2 f(y) \, dy = \int_{-1}^{0} y^2 f(y) \, dy \\
\int_{-1}^{0} y^2 (y+1) \, dy &= \int_{-1}^{0} y^3 + y^2 \,\, dy = \frac{y^4}{4} + \frac{y^3}{3} \Big|_{-1}^{0} \\
\int_{-1}^{0} y^2 (y+1) \, dy &= 0 - \left( \frac{1}{4} - \frac{1}{3} \right) \\
\int_{-1}^{0} y^2 (y+1) \, dy &= \frac{1}{12} \\
E(Y^2) &= \frac{1}{6} \\
\sigma_y^2 &= E(Y^2) - (E(y))^2 = \frac{1}{6} \\
\sigma_y &= \frac{1}{\sqrt{6}} = \frac{ \sqrt{6} } {6}
\end{align*}
Now we need to find $\sigma_{xy}$.To do this, we need to find $E(XY)$. Observe that if $-1\leq x \leq 0$ then the area under the $f(x)$
between $x = -1$ and $x = 0$ is $\left( \frac{1}{2}\right) (x + 1)$. Now we need to find $y$ in terms of $x$.
\begin{align*}
\left( \frac{1}{2}\right) (x + 1) &= \int_{-1}^{y} y + 1 \, dy = \frac{y^2}{2} + y \Big|_{-1}^{y} \\
\left( \frac{1}{2}\right) (x + 1) &= \frac{y^2}{2} + y - \left( \frac{1}{2} - 1 \right) \\
\left( \frac{1}{2}\right) (x + 1) &= \frac{y^2}{2} + y + \frac{1}{2} \\
x + 1 &= y^2 + 2y + 1 \\
x &= y^2 + 2y \\
E(XY) &= 2 \int_{-1}^{0} (y^2+y)(y)(y+1) \, dy \\
\int_{-1}^{0} (y^2+y)(y)(y+1) \, dy &= \int_{-1}^{0} y^4 + y^3 + y^3 + y^2 \, dy \\
\int_{-1}^{0} (y^2+y)(y)(y+1) \, dy &= \int_{-1}^{0} y^4 + 2y^3 + y^2 \, dy \\
\int_{-1}^{0} (y^2+y)(y)(y+1) \, dy &=  \frac{y^5}{5}+ \frac{2y^4}{4} + \frac{y^3}{3} \Big|_{-1}^{0} \\
\int_{-1}^{0} (y^2+y)(y)(y+1) \, dy &=0 - \left( -\frac{1}{5} + \frac{2}{4} - \frac{1}{3} \right) =
\frac{1}{5} - \frac{2}{4} + \frac{1}{3}  \\
\int_{-1}^{0} (y^2+y)(y)(y+1) \, dy &= \frac{1}{30} \\
\end{align*}
%
% Work to do to find E(XY)
%
Now, we want to find a relationship between $X$ and $Y$. We will consider the case where $0 \leq x \leq 1$. The area under both curves
must be the same.
\begin{align*}
\left( \frac{1}{2}\right) \left( x + 1 \right) &= \left( \frac{1}{2}  \right) \left( y + 1 \right) \left( y + 1 \right)  \\
x + 1 &= y^2 + 2y + 1 \\
x &= y^2 + 2y \\
E(XY) &= 2 \int_{-1}^0 xy (y+1) \, dy = 2 \int_{-1}^0 (y^2 + 2y)y (y+1) \, dy \\
\end{align*}
Using an online integral calculator, I find the value of this integral to be $\frac{7}{30}$.
\begin{align*}
E(XY) &= \frac{7}{30} \\
\rho &= \frac{ \left( \frac{7}{30} \right) }{ \left( \frac{ \sqrt{3} }{3}  \right) \left( \frac{ \sqrt{6} } {6} \right)  } =
\frac{ 7(18) } { 30 \sqrt{18} } \\
\rho &= \frac{7(9)}{ 15 \sqrt{18 } } = \frac{7(9)}{ 15 \sqrt{9(2) } } \\
\rho &= \frac{63}{45 \sqrt{2} } \\
\rho &\doteq 0.98994 \\
\end{align*}


text:
Q: Git-hooks pre-push script does not receive input via STDIN The git-hooks pre-push documentation states that the first line of stdin will be populated with the local ref and sha, and the remote ref and sha as such:
<local ref> SP <local sha1> SP <remote ref> SP <remote sha1> LF

However, my simple pre-push script:
#!/bin/bash

echo "params=[$@]"

read line
echo "stdin=[$line]"

exit 1

returns the following output when a $git push is run:
params=[origin [url]:[branch].git]
stdin=[]
error: failed to push some refs to '[remote]'

The parameters to the script are as specified in the documentation (name and path of the remote).  The error is expected because my script exits with a status of 1.  However, I can't seem to figure out why I'm not receiving the local and remote refs on stdin as specified by the documentation.
Is this a bug in git?  Or, am I missing something?

A: Apologies if this is stating the obvious, but if there's nothing to push, you won't get any lines on stdin. The sample .git/hooks/pre-push.sample has a while loop:
IFS=' '
while read local_ref local_sha remote_ref remote_sha
do
    ...
done

and that appears to work when I try it here with an echo inside that loop and nothing else - I get nothing when I have nothing to push, and output when I do.


text:
Q: Post URL with PHP script I have a little issue. I generate an URL with my PHP script like this :
http://emoncms.org/input/post.json?json={CONSO:1.5828060}&apikey=MyApiKey

I use the code below to send the URL to the Internet, but it doesn't work:
$client = new Client('http://emoncms.org');
$query ='/input/post.json';
$query .= '?json={CONSO:' . $CONSO . '}' . '&apikey=MyApiKey';

$request = $client->post($query);
$response = $request->send();

However, when I put the URL in my browser, it works ! But not with my PHP script... :(
Can you help me please ?

A: Please do as follows.
$client = new Client('http://emoncms.org');
$query ='/input/post.json';
$MyApiKey = "yourapikey";
$query .= '?json={CONSO:' . $CONSO . '}' . '&apikey='.$MyApiKey;

$request = $client->post($query);
$response = $request->send();

A: I recommend using cURL to post data to a url from PHP. You can do it your way, I just prefer cURL myself.
I have built several APIs using this method:
    $ch = curl_init('http://emoncms.org/input/post.json');
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $result = curl_exec($ch);
    curl_close($ch);

You assign $post whatever data you want to post. It accepts an array so instead of doing
$query ='/input/post.json';
$query .= '?json={CONSO:' . $CONSO . '}' . '&apikey='MyApiKey';

You can instead do:
$post = array(
    'json'   => "{CONSO:$CONSO}",
    'apikey' => 'api_key_goes_here
);

$result will be the response from the server. If it is a json response you can simply do $result = json_decode($result, true);
If the server needs a query instead of post data, I would change the cURL request to send a query instead of posting. The server may allow either one, but I would just check to make sure.
Also: If you are sending json, why dont you use json_encode($data);? I find it a lot better then writing custom json yourself. But it's up to you.


text:
Q: Unable to refer an object/variable dynamically during runtime using eval I'm trying to import an image in NextJS:
import linkedin from "../public/images/linkedin.webp";

While referencing this variable dynamically during runtime:
const socialButtons = [];

for (let i = 0; i < Object.keys(data.socials).length; i++) {
  socialButtons.push(
    <Image
      src={eval(Object.keys(data.socials)[i])}  //this line gives error
      width={48}
      height={48}
      alt="linkedin"
    />
  );
}

I'm getting this error:
Unhandled Runtime Error

ReferenceError: linkedin is not defined


text:
Q: Where is a dimension structure tab in Visual Studio? Where can I find a dimension structure tab in Microsoft Visual Studio 2019? Is there a shortcut for it?

A: I think I found an answer. You just have to simply double click on one of your created dimensions in the solution explorer.


text:
Q: Argument is not Numerical or Logical: returning NA I have a data set with weight values in a CSV file. My goal is to find the standard deviation of these values.
I have tried assigning a variable to the file, attaching it, then using the standard deviation function sd(), to find the standard deviation. In return, I get this error message:

Argument is not Numerical or Logical: returning NA

My file looks like this:
weight.g
54.4
24.2
84.9
56.5

This is the code that I'm using:
brains <- read.csv(file.choose())
attach(brains)
sd(brains)


text:
Q: WebStorm - TypeScript and allowSyntheticDefaultImports flag TypeScript 1.8 added allowSyntheticDefaultImports flag.
I have a TypeScript project targeting es6, which afterwards gets transpiled with Babel to ES5.
Currently, WebStorm's intellisense does not recognize this flag, and thus says that using default import from a module which does not export a default is disallowed. This means that I am not getting the definitions correctly..
Since I do not want to update all of the definition files manually, is there any other way to 'teach' WebStorm this rule, until JetBrains officially release a new version which supports it (I already submitted a ticket there).

A: WebStorm doesn't appear to use the TypeScript language service, so there isn't any way that I'm aware of to fix this.
In the mean time you can use non-ES6 style imports:
import foo = require("foo");

which should basically compile down to:
var foo = require("foo");


text:
Q: How does sklearn.preprocessing.normalize normalize data, and can I replicate on new data with mean and standard deviation? I was working on a data science problem, and I used sklearn's preprocessing normalize function to normalize my dataset. Now, once I saved my model, I want to know how to apply those transformations to a new data point so I can feed it into the model and get a prediction.
What I have saved is
finalmodel.pkl
finalmodel.sav
statistics.csv

The statistics sheet has the mean and standard deviation from each column. Is the normalization the usual dividing by standard deviation after subtraction from mean, or does sklearn employ some other strategies?

A: Independently of what normalization system you use, sklearn.preprocessing.normalize also provides the argument return_norm, which you can set to True and store the norms used for later use.
Here's an example, using L2 (a.k.a. Taxicab distance):
from sklearn.preprocessing import normalize
import numpy as np

x = np.array([[3, 4], [5, 6]])
values, norms = normalize(x, norm='l1', return_norm=True)

you will now notice that:
values

Out[18]: array([[0.42857143, 0.57142857],
               [0.45454545, 0.54545455]])

norms

Out[19]: array([ 7., 11.])

Now, just as a check, divide one array item by the corresponding column norm:
3/7

Out[20]:  0.42857142857142855


text:
Q: Population Modeling Statistics on a Map I've got a question regarding the modeling of populations.
So I am programming a population map that is geometrically amendable. For this, one can define an area and define the number of people living there.
I want to make this amendable to the point of where population definitions can overlap. It is quite obvious what to do when one defines an area (A1) with a specific number of people living there and then a second definition comes of an area (A2) inside that area: The surplus or dearth of people living in A2 (compared with how many people would live in A2 according to A1) is negated from people living in A1-A2.
But how can I handle the situation of partial overlaps of two defined areas?
Any help would be appreciated, even if you can just point me in the direction of how I could figure this out.

A: If I understand what you want to do, it is not really a statistical issue per se. As I understand it, you have a map of piecewise-constant areal population density (i.e. $\frac{\text{people}}{\text{area}}$), defined by a set of polygons.
So consider a particular polygon $A$ with density $\rho$ and population $N=\rho|A|$, where $|A|$ is the polygon area.
So to add a new polygon $B$, you first compute $C=A\cap{B}$, $A'=A-C$, and $B'=B-C$. If you intend that the populations in the overlap area are independent*, then $N_C=(\rho_A+\rho_B)|C|$. You would then subtract these contributions from the residual polygons, i.e. $N_{A'}=N_A-\rho_A|C|$ and $N_{B'}=N_B-\rho_B|C|$. Note that the densities of the residual polygons are unchanged, $\rho_{A'}=\rho_A$, $\rho_{B'}=\rho_B$.
*This is one interpretation of the example you gave where $B=C$ so $B'=\emptyset$. If the overlap-populations are not independent, then this would be double counting! This is the part that is not clear to me from your description.

Update: Based on the clarification, the assumption $\rho_C=\rho_A+\rho_B$ is not appropriate.
So then the uncertainty all boils down to how you estimate $\rho_C$. (The assumption $\rho_{A'}=\rho_A$ and $\rho_{B'}=\rho_B$ still seems valid.)
I am not sure if there is a "correct" answer here (but hopefully someone chimes in, if there is!).
A reasonable approach is to model the density in the overlap as a weighted average of the component densities
$$\rho_C\approx\frac{w_A\rho_A+w_B\rho_B}{w_A+w_B}$$
One possible approach for weighting could be based on the relative area of a component to the overlap, i.e.
$$w_A=\frac{|C|}{|A|}\,,\,w_B=\frac{|C|}{|B|}$$
This captures the idea that if $|A|\gg|C|$ and $|B|\approx|C|$, then $\rho_C\approx\rho_B$, which seems close to your example qualitatively.
(Note that $|C|$ could be omitted from the weights here, as the constant factor will cancel out.)


text:
Q: C Makefile from "learncodethehardway" not working I am having an issue learning C. I was using a website called learncodethehardway, and I was on this page: http://c.learncodethehardway.org/book/ex2.html . I have looked all over the web, and i cannot find the answer to my problem. I am supposed to run the code;
CFLAGS=-Wall -g

clean:
    rm -f ex1

but no matter what I do, I get these errors:

"no type or storage class" for CFLAGS
  "'Wall' undeclared(not in a function)"
  "g undeclared here (not in a function)"
  "error: expected ',' or ';' before 'clean'

As the instructions say: i should do the command: 'run clean', but all this does is give me the response: 'make: *** No rule to make target 'clean'. Stop.'
If anyone can make sense of this and help me out, that would be greatly appreciated!

A: That is not code that you are supposed to run. That is the content of a file called Makefile that is interpreted by a program called make that will follow those instructions and will build your application. So, create that file, paste that code into it and run make and it should work.


text:
Q: IllegalArgumentException : Unknown entity in Hibernate xml configuration I am trying to test the Hibernate @Any mapping. But i am facing a problem : IllegalArgumentException: Unknown entity. I am using hibernate XML based configuration, in a maven project.
i have checked this question : Unknown Entity
and also this one Unknown Entity 2
But i think they are not the things, i am looking for.
CFG file
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/concretepage</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">2993JGda</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">create</property>

    <mapping class="com.concretepage.entity.Boy"/>
    <mapping class="com.concretepage.entity.Girl"/>
    <mapping class="com.concretepage.entity.StudentInfo"/>
    <mapping class="com.concretepage.entity.College"/>
    <mapping package="com.concretepage.entity"/>
   </session-factory>
</hibernate-configuration>

Entity Classes
Student
package com.concretepage.entity;

public interface Student {
    String getName();
    int getAge();
}

Boy
@Entity
@Table(name="boy")
public class Boy implements Student {
    @Id
    private int id;
    @Column(name="name")
    private String name;
    @Column(name="age")
    private int age;
//getter-Setter

HibernateUtil
package com.concretepage;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
     private static SessionFactory sessionFactory ;
     static {
           Configuration configuration = new Configuration().configure();
           StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
                applySettings(configuration.getProperties());
           sessionFactory = configuration.buildSessionFactory(builder.build());
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static void closeSessionFactory() {
        sessionFactory.close();
    }
}

Main class/Execution class
public class HibernateManyToAnyDemo {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Boy boy = new Boy();
        boy.setId(1);
        boy.setName("Mukesh");
        boy.setAge(30);
        session.persist(boy);
        //other codes...

Now when i am running the program i am facing :
Exception in thread "main" java.lang.IllegalArgumentException: Unknown entity: com.concretepage.entity.Boy
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:713)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:696)
    at com.concretepage.HibernateManyToAnyDemo.main(HibernateManyToAnyDemo.java:21)

I am not understanding why it is happing. Another thing is that in the configuration i have given hibernate DDL update. so that table should be created in the database. But table is not being created there.
So far two questions i have seen according to them : have to use package-scan, but i think it is not needed in my example cause, i am mapping them in cfg file and i have also used @Entity annotation properly.
Any help, comment will be appreciated.

A: You can debug into the configure method of new Configuration().configure() to see what is happening. Hibernate tries to find a file name hibernate.cfg.xml on the class path, so if you don't see the DDL export happening, the file is most likely not found. If you are using Maven to build your project, make sure the file is directly contained in src/main/resources, otherwise it will not be picked up.


text:
Q: I am encountering "error: The operator '[]' isn't defined for the type 'Object'." How do i solve this? I am following this tutorial to make a chat app.
I am encountering this problem, as the tutorial is outdated, things have changed and the function QueryDocumentSnapshot has changed how it works. I tried using different methods but nothing. Hoping to get some help here, here is the code:
import 'package:chat_app/services/database.dart';
import 'package:chat_app/widgets/widget.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SearchScreen extends StatefulWidget {
  const SearchScreen({Key? key}) : super(key: key);

  @override
  _SearchScreenState createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {

  DatabaseMethods databaseMethods = new DatabaseMethods();
  TextEditingController searchTextEditingController = new TextEditingController();

  late QuerySnapshot searchSnapshot;

  initiateSearch(){
    databaseMethods
        .getUserByUsername(searchTextEditingController.text)
        .then((val) {
      setState(() { searchSnapshot = val; });
    });
  }

  Widget searchList() {
    return searchSnapshot!= null ? ListView.builder(
        itemCount: searchSnapshot.docs.length,
        shrinkWrap: true,
        itemBuilder: (context, index) {
          return SearchTile(
            //TODO: controlla che funzioni
              userName:  searchSnapshot.docs[index].data()!['name'],
              userEmail: searchSnapshot.docs[index].data()!['email']
          );
    }) : Container();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBarMain(context),
      body: Container(
        child: Column(
          children: [
            Container(
              color: Color(0x54000000),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
              child: Row(
                children: [
                  Expanded(
                      child: TextField(
                        controller: searchTextEditingController,
                        style: TextStyle(
                          color: Colors.white
                        ),
                        decoration: InputDecoration(
                          hintText: "search username...",
                          hintStyle: TextStyle(
                            color:Colors.white54
                          ),
                          border: InputBorder.none
                        ),
                      )
                  ),
                  GestureDetector(
                    onTap: (){
                      initiateSearch();
                    },
                    child: Container(
                      height: 40,
                        width: 40,
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              const Color(0x36FFFFFF),
                              const Color(0x0FFFFFFF)
                            ]
                          ),
                          borderRadius: BorderRadius.circular(40)
                        ),
                        padding: EdgeInsets.all(8),
                        child: Image.asset("assets/images/search_white.png")
                    ),
                  )
                ],
              ),
            ),
            searchList()
          ],
        ),
      ),
    );
  }
}

class SearchTile extends StatelessWidget {

  final String userName;
  final String userEmail;
  SearchTile({required this.userName, required this.userEmail});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: [
          Column(
            children: [
              Text(userName, style: simpleTextStyle(),),
              Text(userEmail, style: simpleTextStyle(),)
            ],
          ),
          Spacer(),
          Container(
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(30)
            ),
            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
            child: Text("Message"),
          )
        ],
      ),
    );
  }
}

The problem resides here specifically:

  Widget searchList() {
    return searchSnapshot!= null ? ListView.builder(
        itemCount: searchSnapshot.docs.length,
        shrinkWrap: true,
        itemBuilder: (context, index) {
          return SearchTile(
            //TODO: controlla che funzioni
              userName:  searchSnapshot.docs[index].data()!['name'],
              userEmail: searchSnapshot.docs[index].data()!['email']
          );
    }) : Container();
  }

Any help is appreciated!

A: Try this:
  Widget searchList() {
    return searchSnapshot!= null ? ListView.builder(
        itemCount: searchSnapshot.docs.length,
        shrinkWrap: true,
        itemBuilder: (context, index) {
        final _searchSnapshot = searchSnapshot.docs[index].data() as Map<String, dynamic>;
          return SearchTile(
            //TODO: controlla che funzioni
              userName:  _searchSnapshot['name'],
              userEmail: _searchSnapshot['email']
          );
    }) : Container();
  }


text:
Q: Login Failed for linked server How to create a linked server...?
1st Server name is ABC.DATABASE1
2nd server name is EFG.DATABASE2

EFG database username is sa password is sa
I want to retrive the data's from 2nd server thourgh 1st server
In the 1st server, i exectue the store procedure like this....
exec sp_linkedserver 'EFG'

Executed successfully,
When i tried to retrive the data, it is showing error as "login failed for user sa, Reason: Not associated with trusted sql server connection"
How to solve this problem...
Need help

A: In Microsoft SQL Server Management Studio check the login configuration of your linked servers properties on the *Security" tab and create a mapped remote login for your local sa account or configure an alternative login for all connections.
To create a linked server with a login mapping by executing sp_linkedserver, try
sp_addlinkedsrvlogin @rmtsrvname = N'EFG', @locallogin = N'sa', @useself = N'False',
                     @rmtuser = N'your_remote_user', @rmtpassword = N'remotepassword'

To create a linked server with an alternative login, try
sp_addlinkedsrvlogin @rmtsrvname = N'EFG', @locallogin = NULL , @useself = N'False',
                     @rmtuser = N'your_remote_user', @rmtpassword = N'remotepassword'


text:
Q: How to detect the next n words in a string after a word (that can occur multiple times) and separate them in an array I have a string s in which I have to detect the word "car" and print the next 2 words. However, currently when I print words[i1], it gives me "is awesome". but it should give me "is", then "cool", then "is", then "awesome" in different lines(n=2 in the above case).
Can anybody tell me what is wrong with this code?
String s="car is cool car is awesome.";
int index = contents.indexOf(s);
while(index >= 0) {
   String[] words = new String[n];
   for (int i3=0;i3<n;i3++){
       words[i3]="";
   }
   int i1=0, i2=index;
   while(true){
       if(i1==n) break;
       if(i2>=contents.length()) break;
       while(true) {
           if(i2>=contents.length()) break;
           if((contents.charAt(i2)+"")==" ") break;
           words[i1]+=(contents.charAt(i2)+"");
           i2++;
       }
       System.out.println(words[i1]);
       i1++;
   }
    index = contents.indexOf(s, index+1);
}

A: You can achieve what you wanted using this piece of code:
String s = "car is cool car is awesome.";
int index = s.indexOf("car ");

if(index >= 0) {
    index += "car ".length()
    String[] words = s.substring(index).split(" ");

    // if you need n words after "car"
    for (int i = 0; i < words.length && i < n; i++) {
        System.out.println(words[i]);
    }
}

If there are not n words after "car" or any given string, this will print the maximum no. of words.
contents is not in the code you shared.
There is a very common bug in your program at this line:
if((contents.charAt(i2)+"")==" "

It should rather be
if( " ".equals((contents.charAt(i2)+"") )

A: A solution based on splitting the string:
final int n = 2;
final String sentence="car is cool car is awesome.";
final String[] words = sentence.split("\\W+");
for ( int i = 0; i < words.length; ++i ){
    if ( words[i].equals("car") ){
        for ( int j = 0; j < n && ++i < words.length; ++j )
           System.out.println( words[i] );
    }
}

A different solution based on regular expressions:
final int n = 2;
final String s = "I like my car. My car is cool. It's an awesome car to drive.";
final String word = "car";
final String separatorRE = " ,.";
final Pattern p = Pattern.compile( String.format( "(?<=[%s]|^)%s(?=[%s]|$)", separatorRE, word, separatorRE ) );
final Pattern q = Pattern.compile( String.format( "(?<=[%s])[^%s]+(?=[%s]|$)", separatorRE, separatorRE, separatorRE ) );
final Matcher m = p.matcher(s);
while ( m.find() ){
    int i = 0;
    Matcher mw = q.matcher(s);
    mw.region( m.end(), s.length());
    while ( ++i <= n && mw.find() )
        System.out.println( mw.group() );
}

A: I was making a mistake of not updating i2 before break inside the innermost while loop. Now it works correctly. Plus, if we want to add more separators, we can do so by adding more conditions in that same statement using ||.
String s="car is cool car is awesome.";
int index = contents.indexOf(s);
while(index >= 0) {
   String[] words = new String[n];
   for (int i3=0;i3<n;i3++){
       words[i3]="";
   }
   int i1=0, i2=index;
   while(true){
       if(i1==n) break;
       if(i2>=contents.length()) break;
       while(true) {
           if(i2>=contents.length()) break;
           if((contents.charAt(i2)+"").equals(" ")){i2++; break;}
           words[i1]+=(contents.charAt(i2)+"");
           i2++;
       }
       System.out.println(words[i1]);
       i1++;
   }
    index = contents.indexOf(s, index+1);
}


text:
Q: IdTCPServer does not release clients who disconnect abruptly I tested a simulation disconnect of multiple clients by cutting their internet connection.  I found that TIdTCPServer did not discharge their threads, it did not detect their disconnect.  By comparison, when I closed a client manually, the server detected the disconnection and discharged its thread.

A: Abnormal disconnects are not detected by the OS in a timely manner.  It can take a considerable amount of time for a lost socket connection to timeout internally so the OS can invalidate it.  Until the OS does that, Indy has no way of knowing that the client connection is gone.
To account for that, you should either:

*

*implement a timeout in your application-layer data protocol.  If you are expecting a client to send something to your server, and it does not do so for a certain amount of time, assume the client is gone and close the connection.  During periods of idle activity, require clients to send a heartbeat command to your server at regular intervals to keep their connections alive.  You can use the AContext.Connection.IOHandler.CheckForDataOnSource() method to wait for data to arrive, or you can use the AContext.Binding.SetSockOpt() method to specify an SO_RCVTIMEO timeout on blocking reads.

*if you cannot change your data protocol, you can at least enable TCP-level keep-alives on the socket itself.  In the server's OnConnect event, you can call the AContext.Binding.SetKeepAliveValues() method to enable keep-alives.  The OS will then handle the keep-alives for you, and will invalidate the connection if the timeout elapses.
With that said, also make sure that your server event handlers are not swallowing Indy exceptions (derived from EIdException).  That can also cause the server to not terminate threads correctly, if a connection is lost and Indy raises an exception about it but you are not allowing the server to process it.  If you need to catch exceptions (for logging, etc), make sure to re-raise any EIdException-derived exception and let the server handle it.


text:
Q: CUDA's Mersenne Twister for an arbitrary number of threads CUDA's implementation of the Mersenne Twister (MT) random number generator is limited to a maximal number of threads/blocks of 256 and 200 blocks/grid, i.e. the maximal number of threads is 51200.
Therefore, it is not possible to launch the kernel that uses the MT with
kernel<<<blocksPerGrid, threadsPerBlock>>>(devMTGPStates, ...)

where
int blocksPerGrid = (n+threadsPerBlock-1)/threadsPerBlock;

and n is the total number of threads.
What is the best way to use the MT for threads > 51200?
My approach if to use constant values for blocksPerGrid and threadsPerBlock, e.g. <<<128,128>>> and use the following in the kernel code:
__global__ void kernel(curandStateMtgp32 *state, int n, ...) {

    int id = threadIdx.x+blockIdx.x*blockDim.x;

    while (id < n) {

        float x = curand_normal(&state[blockIdx.x]);
        /* some more calls to curand_normal() followed
           by the algorithm that works with the data */

        id += blockDim.x*gridDim.x;
    }
}

I am not sure if this is the correct way or if it can influence the MT status in an undesired way?
Thank you.

A: I suggest you read the CURAND documentation carefully and thoroughly.
The MT API will be most efficient when using 256 threads per block with up to 64 blocks to generate numbers.
If you need more than that, you have a variety of options:

*

*simply generate more numbers from the existing state - set (i.e. 64
blocks, 256 threads), and distribute these numbers amongst the
threads that need them.

*Use more than a single state per block (but this does not allow you to exceed the overall limit within a state-set, it just addresses the need for a single block.)

*Create multiple MT generators with independent seeds (and therefore independent state-sets).

Generally, I don't see a problem with the kernel that you've outlined, and it's roughly in line with choice 1 above.  However it does not allow you to exceed 51200 threads.  (your example has <<<128, 128>>> so 16384 threads)

A: Following Robert's answer, below I'm providing a fully worked example on using cuRAND's Mersenne Twister for an arbitrary number of threads. I'm using Robert's first option to generate more numbers from the existing state-set and distributing these numbers amongst the threads that need them.
// --- Generate random numbers with cuRAND's Mersenne Twister

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include <cuda.h>
#include <curand_kernel.h>
/* include MTGP host helper functions */
#include <curand_mtgp32_host.h>

#define BLOCKSIZE   256
#define GRIDSIZE    64

/*******************/
/* GPU ERROR CHECK */
/*******************/
#define gpuErrchk(x) do { if((x) != cudaSuccess) { \
    printf("Error at %s:%d\n",__FILE__,__LINE__); \
    return EXIT_FAILURE;}} while(0)

#define CURAND_CALL(x) do { if((x) != CURAND_STATUS_SUCCESS) { \
    printf("Error at %s:%d\n",__FILE__,__LINE__); \
    return EXIT_FAILURE;}} while(0)

/*******************/
/* iDivUp FUNCTION */
/*******************/
__host__ __device__ int iDivUp(int a, int b) { return ((a % b) != 0) ? (a / b + 1) : (a / b); }

/*********************/
/* GENERATION KERNEL */
/*********************/
__global__ void generate_kernel(curandStateMtgp32 * __restrict__ state, float * __restrict__ result, const int N)
{
    int tid = threadIdx.x + blockIdx.x * blockDim.x;
    for (int k = tid; k < N; k += blockDim.x * gridDim.x)
        result[k] = curand_uniform(&state[blockIdx.x]);
}

/********/
/* MAIN */
/********/
int main()
{
    const int N = 217 * 123;

    // --- Allocate space for results on host
    float *hostResults = (float *)malloc(N * sizeof(float));

    // --- Allocate and initialize space for results on device
    float *devResults; gpuErrchk(cudaMalloc(&devResults, N * sizeof(float)));
    gpuErrchk(cudaMemset(devResults, 0, N * sizeof(float)));

    // --- Setup the pseudorandom number generator
    curandStateMtgp32 *devMTGPStates; gpuErrchk(cudaMalloc(&devMTGPStates, GRIDSIZE * sizeof(curandStateMtgp32)));
    mtgp32_kernel_params *devKernelParams; gpuErrchk(cudaMalloc(&devKernelParams, sizeof(mtgp32_kernel_params)));
    CURAND_CALL(curandMakeMTGP32Constants(mtgp32dc_params_fast_11213, devKernelParams));
    //CURAND_CALL(curandMakeMTGP32KernelState(devMTGPStates, mtgp32dc_params_fast_11213, devKernelParams, GRIDSIZE, 1234));
    CURAND_CALL(curandMakeMTGP32KernelState(devMTGPStates, mtgp32dc_params_fast_11213, devKernelParams, GRIDSIZE, time(NULL)));

    // --- Generate pseudo-random sequence and copy to the host
    generate_kernel << <GRIDSIZE, BLOCKSIZE >> >(devMTGPStates, devResults, N);
    gpuErrchk(cudaPeekAtLastError());
    gpuErrchk(cudaDeviceSynchronize());
    gpuErrchk(cudaMemcpy(hostResults, devResults, N * sizeof(float), cudaMemcpyDeviceToHost));

    // --- Print results
    //for (int i = 0; i < N; i++) {
    for (int i = 0; i < 10; i++) {
        printf("%f\n", hostResults[i]);
    }

    // --- Cleanup
    gpuErrchk(cudaFree(devMTGPStates));
    gpuErrchk(cudaFree(devResults));
    free(hostResults);

    return 0;
}


text:
Q: Core Data - sharing NSManagedObjects among multiple threads I suffered all the consequences of using a single MOC in multiple threads - my app crashes at random points because the MOC is created in the main thread and I also use it to fill the DB in another thread.
Though the code is synchronized (@synchronize) using a global singleton the app crashes.
I read that using a separate MOC for each thread will make things ok but I also read that it is considered also a bad approach to share NSManagedObjects across threads.
My use case is the following:
1)I load and parse XML from a server and during the parsing I insert each new NSManagedObject in the database. This all happens in a separate thread.
2)From the main thread the user interacts with the UI which reads data from the database.
In both threads I use NSManagedObjects. How would you suggest me to fix this? I failed multiple times already.
Most often the app creashed with error suggesting that I am modifying a collection while enumerating it which is not true as the code is synchronized and while I am iterating it no modifying happens and vice versa - while I modify it I don't iterate and I save once I am done.

A: Use one NSManagedObjectContext per thread. If you communicate between threads, pass the NSManagedObjectID, which is thread safe, and fetch the object again from you thread context. In my apps I sometimes even use one context per controller.
To manage the different contexts, register an Observer for the NSManagedObjectContextDidChangeNotification. Within this notification handling, you pass the notification to each of your contexts via the mergeChangesFromContextDidSaveNotification: method. This method is thread save and makes the context update its state.
After this you have to refresh your views. If you have a table view based application, have a look at NSFetchedResultsController. This helps you update the table automatically with appropriate animations. If you don't use table views, you have to implement the UI update yourself.

A: If you are only supporting iOS 5 and above you don't need to deal with NSManagedObjectID and merging contexts anymore. You can use the new concurrency types of NSManagedObjectContext instead. Then do your operations within managedObjectContext:performBlock and they will be merged automatically.
See the answer from svena here for more information:
Core Data and Concurrency using NSOperationQueues


text:
Q: Thunderbird > 4.x on Linux does not honour default browser Under KDE 4.7 I have "chromium-browser-chromium" set as my default browser in system settings.
This works for KDE apps, but not Thunderbird.  I suspect that Thunderbird is looking for the default browser in a GTK type config place, rather than a KDE setting.
So while KDE apps open links in Chromium, Thunderbird (I am currently in tb6.0, but the same behaviour happens in previous versions) opens links in Firefox.
I know I can force the issue in prefs.js but I would like to get thunderbird to respect the system setting.  How can I do this?

A: Thunderbird (at least version 6 here) appears to be using the XDG MIME actions specification. The preferences are stored in ~/.local/share/applications/mimeapps.list, and all desktop environments are supposed to respect them.

[Default Applications]
text/html=chromium.desktop
x-scheme-handler/http=chromium.desktop

Older versions of Thunderbird may still be using GNOME's Gvfs for this. You can check using gconftool-2:
$ gconftool-2 --get /desktop/gnome/url-handlers/http/command
firefox %s

If that's the case, the best option is to configure Gvfs to use xdg-open for all URL schemes, which in turn should invoke the right program from mimeapps.list:
$ for scheme in http https about unknown; do
    gconftool-2 --set /desktop/gnome/url-handlers/$scheme/command \
        --type string "xdg-open %s"
done

Or you could try xdg-settings, which... honestly, I'm not sure what it does:
$ xdg-settings set default-web-browser chromium.desktop

A: Here's one thing that works for me: http://community.linuxmint.com/tutorial/view/1391
Basically, the idea is to set network.protocol-handler.warn-external.http to true. Same applies to network.protocol-handler.warn-external.https for https protocol and maybe network.protocol-handler.warn-external.ftp for FTP. After applying that, Thunderbird will ask you which program to open the URL with and allow you to remember the choice.


text:
Q: What is the Rust compiler saying here? error[E0621]: explicit lifetime required in the type of `is`
  --> src/bee.rs:76:45
   |
75 | fn compute_instruction_set<'a>(is: &'a mut InstructionSet) {
   |                                    ---------------------- help: add explicit lifetime `'a` to the type of `is`: `&'a mut [OpCode<'a>; 255]`
76 |     let mut isb = InstructionSetBuilder{is: is, pos: 0};
   |                                             ^^ lifetime `'a` required

This is the code:
type InstructionSet<'a> = [OpCode<'a>; 0xff];
...
struct InstructionSetBuilder<'a> {
    is: &'a mut [OpCode<'a>],
    pos: usize,
}
...
fn compute_instruction_set<'a>(is: &'a mut InstructionSet) {
    let mut isb = InstructionSetBuilder{is: is, pos: 0};
...
}

Why do I need to set yet another 'a lifetime param?
Where?
I tried several combinations, all broke the syntax...

A: type InstructionSet<'a> = [OpCode<'a>; 0xff];

This type alias is generic over a lifetime 'a. So you must specify it. Try this instead.
fn compute_instruction_set<'a>(is: &'a mut InstructionSet<'a>) {
    let mut isb = InstructionSetBuilder{is: is, pos: 0};
...
}


text:
Q: Why does threading not work in a Flask app when its run with gunicorn? When files are uploaded to my flask app a thread id is generated. This is used by the frontend to later get the progress details of the file reading process (the cert_details route)
The cert_details route reads in data from a PDF using tesseract, opencv etc. This is quite a resource intensive process and can take a while to perform
While the process is running, I want to be able to update the front end with the progress (i.e how many files read in). Hence I have made a separate thread that has a value 'progress' that increases each time a file has been processed.
The app works without gunicorn i.e when the docker command is CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
If I change it to use gunicorn CMD ["gunicorn","--timeout", "60", "--bind", "0.0.0.0:5000", "app:app"]  , the progress bar doesn't get updated until the file reading process has finished (which defeats the purpose of the progress bar).
Why does the threading not work with gunicorn? Is there an alternative approach that I have to take or could it be related to thread starvation?
import threading
from flask import Flask, flash, request, redirect, url_for, jsonify, send_from_directory, send_file
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

class ExportingThread(threading.Thread):
    def __init__(self):
        self.progress = 0
        super().__init__()

exporting_threads = {}

@app.route('/uploads', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        if 'files[]' not in request.files:

            return {'status':'File upload unsuccesful'}

        files = request.files.getlist('files[]')

        for file in files:
            if file and allowed_file(file.filename):

                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            else:
                return {'status':'Non pdf file type uploaded'}
        global thread_id
        thread_id = random.randint(0, 10000)
        return {'status':'sucessful'}

@app.route('/get_thread_id')
def get_thread():
    global thread_id
    return str(thread_id)

@app.route('/progress', methods=['POST'])
def progress():

    data = request.json

    thread_id = data['thread_id']

    global exporting_threads
    if thread_id in exporting_threads:
       return str(exporting_threads[thread_id].progress)
    else:
        return '0'

@app.route('/cert_details', methods=['POST'])
def get_details():

    data = request.json

    if 'filenames' not in data:
        return {'error':'filenames not found'}
    else:

        filenames =data['filenames']

        details =[]

        global exporting_threads
        global thread_id

        exporting_threads[thread_id] = ExportingThread()
        exporting_threads[thread_id].start()

        for file in filenames:
            #this is the resource intensive process using ocr / opencv
            details.append( get_certficate_details( UPLOAD_FOLDER_LOCATION + file, file ) )
            exporting_threads[thread_id].progress += 1

        return jsonify(file_details =  details)


text:
Q: How to validate alphabets in android? How to validate edittext field so that it should not accept alphabets when entered and it should accept only numbers? I have written the code for empty edittext...i.e if nothing is entered in the editetext an alert will be raised. But how to make my edittext to accept only numbers and not alphabets?
    Help me regarding this....Will be thankful to you...

A: set the InputType as number to your EditField to accept only number
For Example
<EditText

                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_margin="5dp"
                android:inputType="number"
                android:singleLine="true" />

A: You Simply need to use Input Type as Numeric in your xml file just like below
android:inputType="number"

A: You Can use regularexpressions
   if (!Pattern.matches("^[0-9 ]*$", s))

    {
       et.setError("Allow only Numerics");

     }

or
     u  specify
        android:inputType="number"

for your edittext in ur xml file

A: use this in your edittext :
android:hint="@string/phone_no_hint"
android:digits="0123456789"
android:inputType="phone"

A: Use android:inputType="number" in the declaration of the EditText. This will simply disallow entry of anything other than numbers by displaying a numeric keypad.


text:
Q: I need help to automatically DEcensore a text (lot's of text to be prosseced) I have a web story that has cencored word in it with asterix
right now i'm doing it with a simple and dumb str.replace
but as you can imagine this is a pain and I need to search in the text to find all instance of the censoring
here is bastard instance that are capitalized, plurial and with asterix in different places
toReplace = toReplace.replace("b*stard", "bastard")
toReplace = toReplace.replace("b*stards", "bastards")
toReplace = toReplace.replace("B*stard", "Bastard")
toReplace = toReplace.replace("B*stards", "Bastards")
toReplace = toReplace.replace("b*st*rd", "bastard")
toReplace = toReplace.replace("b*st*rds", "bastards")
toReplace = toReplace.replace("B*st*rd", "Bastard")
toReplace = toReplace.replace("B*st*rds", "Bastards")

is there a way to compare all word with "*" (or any other replacement character) to an already compiled dict and replace them with the uncensored version of the word ?
maybe regex but I don't think so

A: Using regex alone will likely not result in a full solution for this.  You would likely have an easier time if you have a simple list of the words that you want to restore, and use Levenshtein distance to determine which one is closest to a given word that you have found a * in.
One library that may help with this is fuzzywuzzy.
The two approaches that I can think of quickly:

*

*Split the text so that you have 1 string per word. For each word, if '*' in word, then compare it to the list of replacements to find which is closest.

*Use re.sub to identify the words that contain a * character, and write a function that you would use as the repl argument to determine which replacement it is closest to and return that replacement.

Additional resources:

*

*Python: find closest string (from a list) to another string

*Find closest string match from list

*How to find closest match of a string from a list of different length strings python?

A: You can use re module to find matches between the censored word and words in your wordlist.
Replace * with . (dot has special meaning in regex, it means "match every character") and then use re.match:
import re

wordlist = ["bastard", "apple", "orange"]

def find_matches(censored_word, wordlist):
    pat = re.compile(censored_word.replace("*", "."))
    return [w for w in wordlist if pat.match(w)]

print(find_matches("b*st*rd", wordlist))

Prints:
['bastard']

Note: If you want match exact word, add $ at the end of your pattern. That means appl* will not match applejuice in your dictionary for example.


text:
Q: How to transform a Grayscale background SVG, to white or black colors I have Gray SVG icons next to each Menu item (inherited from another project) and displaied as background.
I need to show them black or white but I don't how to achieve this.
As backgrounds I can't use fill css property. I tried with filter:brightness(100) to make them white but I loose anti-aliasing (and analogue with filter:brightness(0) to make them black).
Mask has still serious compatibility issues (e.g. Firefox does not allow external svg).
I tried also to import them as data-uri with LESS feature, but it was unuseful, so.... any suggestion?


text:
Q: RoR - Values from forms are not getting passed to controller I have a subscriber form page, where based on the country selected I display the state field via jquery. That part works fine but even after selecting a state when I post, I get an error "state value can't be blank". Not sure what I am missing.
Here is the code.
    <% if session[:selcountry] == "USA" %>

    <%= label_tag :state %> *

    <%= select_tag :state, options_for_select(us_states), class: "form-
    control" %>

    <% else %>

    <%= label_tag :province %> *

    <%= select_tag :state, options_for_select(can_states), class: "form-
    control" %>

    <%= label_tag :state %> *

    <%= text_field_tag :state, @subscriber.state, class: "form-control" %>

    <% end %>

Any pointers would be great.
TIA


text:
Q: Nesting fixed effects in random effects I'm fitting a multilevel model that has a random effect nested within a fixed effect:
df <- tibble(
  id = seq(1:500)
) %>%
  mutate(treatment = rbinom(n = 500, size = 1, prob = 8/9))

df <- as.data.frame(lapply(df, rep, 6)) %>%
  arrange(id, treatment) %>%
  mutate(scenario = rep(seq(1:6), 500)) %>%
  mutate(magnitude_manipulation = case_when(
    treatment == 1 & scenario == 1 ~ "very_low",
    treatment == 1 & scenario == 2 ~ "mid_low",
    treatment == 1 & scenario == 3 ~ "low",
    treatment == 1 & scenario == 4 ~ "high",
    treatment == 1 & scenario == 5 ~ "mid_high",
    treatment == 1 & scenario == 6 ~ "very_high"
  ),
  magnitude_manipulation = factor(magnitude_manipulation, ordered = TRUE, levels = c("very_low", "mid_low", "low", "high", "mid_high", "very_high")),
  outcome = round(rnorm(3000, 100, 15)))

That is, magnitude_manipulation is nested in treatment - there are no levels of magnitude_manipulation when treatment is equal to 0, but 6 levels when treatment is equal to 1. What would be the appropriate way to model this data with lmer?
This is my best shot so far:
lmer(outcome ~ treatment + (1 | magnitude_manipulation) + (1 | scenario) + (1 | id), data = df)

I also have random effects for scenario and person because these are repeated factors. Any assistance would be greatly appreciated because although this topic has been addressed before, I'm not sure I'm applying it correctly.

A: This doesn't make complete sense to me.
You have created a variable based on levels of one fixed effect and a random effect and then included that as a grouping factor for random intercepts along with the other factors too.
It is not clear what your research question is, but the model that seems most appropriate to me is:
lmer(outcome ~ treatment * scenario + (1 | id), data = df)


text:
Q: Displayed layout width doesn't match coded width (drupal site) I'm working on a drupal website with a fixed-width div layout. Everything lines up and etc., but for some reason the whole thing is about 15px wider than it should be. The width should be 900px but shows up as something like 915px. It's even stretching the background image of the header div. This happens in Firefox, not IE (for who knows what reason), and I am using the standard box model. Is there something that the drupal elements could be doing? I've been trying to resize children like crazy in Firebug but nothing seems to be working. The only thing I can think of from this point is to leave it as it is or start all over. Any help would be greatly appreciated.
Page template HTML:

<?php print fiberop_user_bar() ?>

<?php print $breadcrumb; ?>

            <?php print $left; ?>

            <?php if ($mission): ?>
<?php print $mission; ?>
<?php endif; ?>

            <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
            <?php if ($tabs): ?>
<?php print $tabs; ?>
<?php endif; ?>
            <?php if ($show_messages): print $messages; endif; ?>
            <?php print $help; ?>

            <?php print $content; ?>

            <?php print $right; ?>

    <?php if ($footer_message || $footer) : ?>

        <?php print $footer_message . $footer;?>

    <?php endif; ?>

Actual rendered HTML (sorry it's such a mess):

Not logged in.

Navigation

Home

News and Events

Corporate

History

company Personnel Listing

company Policies

Customer Support

Products and Services

Customer Brochures

Sales brochures

User guides

Products

Internet Services

  Int'l Prepaid Phone Card

internet Prepaid Account

Services

Local Phone Service

Long Distance Call and Fax

Digital Cable Television

Digital GSM Wireless

Enhanced Calling Services

Internal Wiring Maintenance Plan (IMP)

Promotions

Resources

Image Albums

Welcome to Company Corporate Portal

Welcome

                Article with Picture

                October 6, 2009, 11:02 am

This is a test of an article with a picture.

Lorem ipsum dolor sit amet, consectetur adipisicing...

                company article

                September 30, 2009, 12:14 pm

Article text

                company-article2

                September 30, 2009, 12:07 pm

Article text...

User login

    <form action="/content/welcome-company-corporate-portal?destination=node%2F1"  accept-charset="UTF-8" method="post" id="user-login-form">

 Username: *

 <input type="text" maxlength="60" name="name" id="edit-name" size="15" value="" class="form-text required" />

 Password: *
 <input type="password" name="pass" id="edit-pass"  maxlength="60"  size="15"  class="form-text required" />

<input type="submit" name="op" id="edit-submit" value="Log in"  class="form-submit" />

Create new account

Request new password

<input type="hidden" name="form_build_id" id="form-205b20d5edaf8893b9321c6fd3c147fd" value="form-205b20d5edaf8893b9321c6fd3c147fd"  />

<input type="hidden" name="form_id" id="edit-user-login-block" value="user_login_block"  />

</form>

Who's online

    There are currently 0 users and 0 guests online.

CSS:
body, div {
    margin: 0;
    padding: 0;
    }
body {
    background-color: #05142D;
    font-family: Verdana, Arial, sans-serif;
    font-size: 12px;
    line-height: 1.3em;
    margin: 0 auto;
    text-align: center;
    }
#container {
    width: 900px;
    margin: 0 auto;
    text-align: left;
    clear: both;
    }
#content-supheader {
    background-color: transparent;
    color: #FFF;
    font-size: 0.9em;
    height: 15px;
    width: 890px;
    padding: 5px;
    }
#content-supheader a, #content-supheader a:link {
    font-family: Verdana, Arial, sans-serif;
    }
#content-header {
    background-color: #CFCFCF;
    background-image: url("pnccheader.jpg");
    background-repeat: no-repeat;
    color: #FFF;
    font-size: 0.9em;
    height: 150px;
    width: 900px;
    padding: 0;
    margin: 0;
    }
#content-subheader {
    background-color: #000;
    color: #FFF;
    font-size: 0.9em;
    height: 15px;
    width: 890px;
    padding: 5px;
    }
#content-body {
    background-color: #FFF;
    height: auto;
    width: 900px;
    padding: 0px;
    overflow:hidden; /* overflow: auto; causes grayed-out x and y scrollbars to appear */
    }
.square {
    background-color: transparent;
    /* border: 1px solid #000; --> if border are used, must correct height & width of div for height & width of border, otherwise divs get pushed down */
    width: 190px; /* ~13 extra pixels that show up from somewhere! From block? */
    float:left; /* alternately display:inline; can be used, but divs wrap in FF */
    font-size: 0.9em;
    /* overflow: hidden; */
    padding: 5px;
    }
#middle {
    background-color: #FFF;
    border: 1px solid #C0C0C0;
    float:left;
    font-size: 0.9em;
    height: auto;
    width: 458px;
    margin: 5px 0px;
    padding: 10px;
    /* overflow: scroll; */
    }
#content-footer {
    background-color: transparent;
    background-image: url("bottomBG2.jpg");
    background-repeat: no-repeat;
    color: #FFF;
    font-size: .9em;
    height: auto;
    Width: 890px;
    padding: 5px;
    padding-top: 40px;
    text-align: center;
    }
#content-footer * h2, #content-footer * h3 {
    font-size: 1em;
    }
#content-footer ul {
    list-style: none;
    display: inline;
    }
h1 {
    font-family: Verdana, Arial, sans-serif;
    font-size: 2em;
    display: inline;
    }
h2 {
    font-family: Georgia, "Times New Roman", serif;
    font-size: 1.5em;
    display: inline;
    }
h3 {
    font-family: Verdana, Arial, sans-serif;
    font-size: 1.5em;
    display: inline;
    }
h4 {
    font-family: Georgia, "Times New Roman", serif;
    font-size: 1em;
    display:inline;
    }
h5 {
    display:inline;
    }
hr {
    background-color: #000;
    color: #000;
    height: 1px;
    }
ul li {
    font-family: Verdana, Arial, sans-serif;
    font-size: 1em;
    line-height: 1.5em;
    }
ul ul li {
    font-family: Verdana, Arial, sans-serif;
    }
a, a:link {
    color: #336699;
    text-decoration: none;
    }
a:visited {
    color: #336699;
    text-decoration: none;
    }
a:hover {
    color: #003366; /*800080 = nice purple*/
    text-decoration: underline;
    }
a:active {
    color: #003366;
    text-decoration: none;
    }

A: I can't say why that's happening, but have you tried the Web Devloper extension for FireFox?  If you go into the "CSS" menu then choose "View Style Information", you may be able to get some extra details about what styles FireFox thinks apply to the elements in question.


text:
Q: Http Responding 403 Forbidden just in Post Request in GET request is ok I have
public function reciveNotification()
and it is alowded as following
$this->Auth->allow(["reciveNotification"]);

When I do GET Request it working good but by POST request I am facing to 403 Forbidden
what am I doing wrong?
GET:
HTTP/1.1 200 OK
Date: Wed, 24 Apr 2019 11:06:43 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Length: 0
Content-Type: text/html; charset=UTF-8

POST:
HTTP/1.1 403 Forbidden
Date: Wed, 24 Apr 2019 11:05:52 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Length: 836
Content-Type: text/html; charset=UTF-8


text:
Q: How to get a Module by its name in Java 9? How to get java.lang.Module by string name in Java 9?
For example, we have
String name = "some.module";
Module module = //how to get here it?

A: One way to get your module from the boot layer which consists at least java.base after its initialization is:
String moduleName = "my.module";
Module m = ModuleLayer.boot().findModule(moduleName).orElse(null);

though preferably a safe way IMO, would be to get a module would be using the Configuration and the system ClassLoader to get the ModuleLayer of your module and then findModule as :
Path path = Paths.get("/path/to/your/module");

ModuleFinder finder = ModuleFinder.of(path);
ModuleLayer parent = ModuleLayer.boot();

Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of(moduleName));
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

ModuleLayer layer = parent.defineModulesWithOneLoader(configuration, systemClassLoader);
Module m = layer.findModule(moduleName).orElse(null);


text:
Q: Is it possible to change the Windows cursor scheme with the command prompt? I would like to know if it is possible to change the cursor scheme of Windows 8 with a command prompt. I want to have it run on start up, since I can't seem to figure out how to change it permanently. If there is any other way to change it permanently, please let me know. The problem I am having is that I cannot copy my custom cursor files to C:\Windows\Cursors, because it says I don't have permission even though I am the administrator of the computer, and the only user on the computer.

A: Try going to the file "C:\windows\cursors" file in explorer. Right click on it and go to properties. Then move to the security tab and the click on add button to add a your list to the permissions if you are not already on the list. Make sure it is your specific user name and not just the administrator group.


text:
Q: pandas: MultiIndex Slicing - Mixing slices and lists I am attempting to use the (not really) new slicing operator in pandas, but there is something I am not quite getting.  Suppose I generate the following hierarchical dataframe:
#Generate container to hold component DFs
df_list=[]

#Generate names for third dimension positions
third_names=['front','middle','back']

#For three positions in the third dimension...
for lab in third_names:
    #...generate the corresponding section of raw data...
    d=DataFrame(np.random.uniform(size=20).reshape(4,5),columns='a b c d e'.split(' '))
    #...name the columns dimension...
    d.columns.name='dim1'
    #...generate second and third dims (to go in index)...
    d['dim2']=['one','two','three','four']
    d['dim3']=lab
    #...set index...
    d.set_index(['dim3','dim2'],inplace=True)
    #...and throw the DF in the container
    df_list.append(d)

#Concatenate component DFs together
d3=pd.concat(df_list)

d3_long=d3.stack().sortlevel(0)

print d3_long

Yields:
dim3    dim2   dim1
back    four   a       0.501184
               b       0.627202
               c       0.329643
               d       0.484261
               e       0.884803
        one    a       0.834231
               b       0.918897
               c       0.196537
               d       0.242109
               e       0.860124
        three  a       0.782651
               b       0.998361
               c       0.849685
               d       0.210377
               e       0.866776
        two    a       0.908422
               b       0.737073
               c       0.064402
               d       0.240718
               e       0.044409
front   four   a       0.100877
               b       0.963870
               c       0.254075
               d       0.126556
               e       0.033631
        one    a       0.243552
               b       0.999168
               c       0.752251
               d       0.684718
               e       0.353013
        three  a       0.938928
               b       0.112993
               c       0.615178
               d       0.430318
               e       0.330437
        two    a       0.301921
               b       0.645425
               c       0.464172
               d       0.824765
               e       0.606823
middle  four   a       0.814888
               b       0.228860
               c       0.333184
               d       0.622176
               e       0.151248
        one    a       0.547780
               b       0.592404
               c       0.684111
               d       0.885605
               e       0.601560
        three  a       0.340951
               b       0.839149
               c       0.800098
               d       0.663753
               e       0.215224
        two    a       0.138430
               b       0.917627
               c       0.342968
               d       0.406744
               e       0.822957
dtype: float64

I can get at the first two dimensions with behavior I expect...
print d3_long.loc[(slice('front','middle'),slice('two','four')),:]

Yields:
dim3    dim2   dim1
front   four   a       0.100877
               b       0.963870
               c       0.254075
               d       0.126556
               e       0.033631
        one    a       0.243552
               b       0.999168
               c       0.752251
               d       0.684718
               e       0.353013
        three  a       0.938928
               b       0.112993
               c       0.615178
               d       0.430318
               e       0.330437
        two    a       0.301921
               b       0.645425
               c       0.464172
               d       0.824765
               e       0.606823
middle  four   a       0.814888
               b       0.228860
               c       0.333184
               d       0.622176
               e       0.151248
        one    a       0.547780
               b       0.592404
               c       0.684111
               d       0.885605
               e       0.601560
        three  a       0.340951
               b       0.839149
               c       0.800098
               d       0.663753
               e       0.215224
        two    a       0.138430
               b       0.917627
               c       0.342968
               d       0.406744
               e       0.822957
dtype: float64

However, the following call yields the exact same result.
d3_long.loc[(slice('front','middle'),slice('two','four'),slice('b','d')),:]

It's like it's ignoring the third level of the MultiIndex.  And when I try to use a list construct to get specific locations...
d3_long.loc[(slice('front','middle'),slice('two','four'),['b','d']),:]

It yields a TypeError.  Any thoughts?

A: d3_long is actually a Series, so you don't need the last : in your slicer.  Note that your second level slice('two','four') doesn't select anything (it'd be equivalent to [-1:1]).
But if you reverse the order, it should give what you expect.
In [82]: d3_long.loc[slice('front','middle'),slice('four','two'), ['b','d']]
Out[82]:
dim3    dim2   dim1
front   four   b       0.301573
               d       0.478005
        one    b       0.306292
               d       0.281984
        three  b       0.108174
               d       0.776523
        two    b       0.028694
               d       0.527417
middle  four   b       0.285103
               d       0.647165
        one    b       0.807411
               d       0.309446
        three  b       0.277752
               d       0.939555
        two    b       0.470019
               d       0.447640
dtype: float64


text:
Q: RandomChoice or RandomSample I am trying to get multiple sets of random integers using RandomChoice[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {4, 3}].
However, I always get repeats such as {{6, 6, 7}, {8, 2, 7}, {1, 7, 1}, {8, 6, 5}}. Can I please ask how to solve this?
Can I please also ask how to get all the possible integers without repeating numbers?
I am very new to Mathematica and can't find it in the examples.
Best


text:
Q: Could not access file PHP Mailer I have a form for file upload in YII.I have to send the file uploaded as attachment through the mail. The mail is sending ,but the attachment is not working.I am using PHP mailer http://www.yiiframework.com/extension/phpmailer/
  <?php echo $form->fileField($model,'career_resume',array('file','size'=>300,'maxlength'=>300)); ?>

Here is my controller
public function actionCreate()
{
            $this->layout='static_inner';

    $model=new LriCareer;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

            if(isset($_POST['LriCareer']))
    {
                    $rnd = rand(0,9999);
        $model->attributes=$_POST['LriCareer'];
                    if($uploadedFile=CUploadedFile::getInstance($model,'career_resume'))
                    {

                        $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name
                        $model->career_resume = $fileName;

                        if($model->save())
                        {
                            $uploadedFile->saveAs(dirname(Yii::app()->basePath) . '/images/resumes/'.$fileName);
                            chmod($_SERVER['DOCUMENT_ROOT'].'/LRI-Original/images/resumes/'.$fileName, 0755);
                            $careername=$_POST['LriCareer']['career_name'];
                            $careeremail=$_POST['LriCareer']['career_email'];
                            $careerphone=$_POST['LriCareer']['career_phone'];
                            $careerpost=$_POST['LriCareer']['career_post'];
                            if($careerpost==1)
                            {
                                $careerpost='Product Manager-Healthcare';
                            }
                            else if($careerpost==2)
                            {
                                $careerpost='Technical Writer';
                            }
                            else if($careerpost==3)
                            {
                                $careerpost='Business Analyst';
                            }
                            else if($careerpost==4)
                            {
                                $careerpost='Quality Assurance Analyst (QA)';
                            }
                            else if($careerpost==5)
                            {
                                $careerpost='Support Engineers';
                            }

//                              $this->redirect('lriCareer/send');
                            Yii::import('application.extensions.phpmailer.JPhpMailer');
                            $mail = new JPhpMailer;
                            $mail->IsSMTP();
                            $mail->Host = 'smtp.googlemail.com:465';
                            $mail->SMTPSecure = "ssl";
                            $mail->SMTPAuth = true;
                            $mail->Username = '565676576@gmail.com';
                            $mail->Password = '12356756#';
                            $mail->SetFrom('565676576@gmail.com', 'Lri Career');
                            $mail->Subject = 'LongRiver Career';
                            $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
                            $mail->AddAttachment((Yii::app()->basePath) . '/images/resumes/'.$fileName);
//                                $mail->setAttachment(dirname(Yii::app()->basePath) . '/images/resumes/'.$fileName);
//                                $mail->AddAttachment($path,$name,$encoding ='base64',$type = 'application/octet-stream');
                            $mail->MsgHTML('Name'.'     '."$careername".'
'.
                                    'Email'.'     '."$careeremail".'
'.
                                    'Phone'.'     '."$careerphone".'
'.
                                    'Post'.'         '."$careerpost".'
'.
                                    'Resume'.'       '."$fileName".'
'.

'My Twitter');
                            $mail->AddAddress('pachukutti@pandarakalan.com', 'rakshasi');
                            $mail->Send();

                            $this->render('send');
                        }

                    }
                    else
                    {
                         if($model->save())
            $this->redirect(array('view','id'=>$model->career_id));
                    }
    }

    $this->render('create',array(
        'model'=>$model,
    ));

    }

From here i have implemented the attachment http://www.yiiframework.com/forum/index.php/topic/41330-phpmailer/
1.I have tried to set the permission to the file but still its not working
Can any one out there look into the problem please

A: you can do it by
$path=$_SERVER['DOCUMENT_ROOT'].'/LRI-Original/images/resumes/'.$fileName;
$name=$fileName;
$mail->AddAttachment($path,$name,$encoding ='base64',$type = 'application/octet-stream');

now it should ,i have tested it on my machine

A: I am using php mailer which is working very fine for me here is the code
$attachment = Yii::app()->baseUrl ."/uploads/images/".abc.jpg;
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'xxxxxx';
$mail->SMTPAuth = true;
$mail->Username = 'xxxx';
$mail->Password = 'xxxx';
$mail->SetFrom('webmastr@example.com', 'Admin');
$mail->AddAttachment($attachment);

$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$mail->MsgHTML($body_html);

$send_to = $send_to . ("Name" . " <email@email.com>;");
$mail->AddAddress($t["email"], $t["name"]);
$mail->Send();

This code is working very fine for me for php mailer in Yii

A: email attach not working in yii  but i can send email
$attachment = Yii::app()->baseUrl ."/upload/abc.jpg";
$mail = new PHPMailer;
$mail->IsSMTP();
$mail =Yii::app()->Smtpmail;
$mail->SetFrom($from, 'Admin');
$mail->SMTPAuth = true;
$mail->AddAttachment($attachment);
//$mail->AddAttachment($attachment, $name = '', $encoding = 'base64',
$type = 'image/jpeg');
$mail->Subject = $subject;
$mail->MsgHTML($view);
$mail->IsHTML(true);
if(!$mail->Send())

========================================================================


text:
Q: How to test if scroll is fired in react component? I'm trying to write a test for testing whether the scroll event fires or not when given a shouldScroll prop, can somebody help me out here please? This is the code I'm trying to test:
export default class HelloWorld extends React.Component {
  componentDidMount() {
    if (this.props.shouldScroll) {
      window.addEventListener('scroll', this.test);
    }
  }

  test() {
    console.log('scrolled...');
  }

  render() {
    return (

        hello world

    );
  }
}

Test:
it('should fire onScroll event', () => {
  // how do I test above???
});

A: You have to give test(event) for it to work. Also, you need to have a page that is long enough to have a scrollbar so that scroll event will be triggered.
You can add hello world
 multiple times so that page will be long enough to have scrollbar.
  test(event) {
   console.log('scrolled...');
  }


text:
Q: Equivalent of cosine law to find moment of inertia Similar to how the perpendicular axis theorem is analogous to the Pythagoras' theorem I wanted to find an expression analogous to the cosine law to find the moment of inertia. In other words given two axis $L_1$ and $L_2$ (Slope of the angle between them $= m$) and the moment of inertia of a body with respect to these axis is $I_1$ and $I_2$ respectively. We have to find the moment of inertia with respect to an axis perpendicular to to these axis in terms of the given quantities. I got this expression
$$ \frac 1 {m^2} \left( (I_1+I_2)(1+m^2) + \sqrt{I_1I_2(1+m^2)} \,\right).  $$
Can someone please check this because I am getting wrong answers using this expression.

A:
You have the line $L_1$ with the inertia tensor $T_{L1}$
$$T_{L1}=\left[ \begin {array}{ccc} { I_1}&0&0\\ 0&0&0
\\0&0&0\end {array} \right]
$$
and the line $L_2$  with the inertia tensor $T_{L2}$
$$T_{L2}=\left[ \begin {array}{ccc} { I_2}&0&0\\ 0&0&0
\\0&0&0\end {array} \right]
$$
to obtain the inertia tensor in $x~,y~,z$ perpendicular local system ,you have to transform the inertia tensor $T_{L2}$ with the transformation matrix R (which is a rotation about the z axis with the angle $\alpha$).
thus:
$$T_{xyz}=T_{L1}+R\,T_{L2}\,R^T$$
with
$$R=\left[ \begin {array}{ccc} \cos \left( \alpha \right) &-\sin \left(
\alpha \right) &0\\ \sin \left( \alpha \right) &\cos
 \left( \alpha \right) &0\\ 0&0&1\end {array}
 \right]
$$
$$T_{xyz}=\left[ \begin {array}{ccc} I_{{1}}+ \left( \cos \left( \alpha
 \right)  \right) ^{2}I_{{2}}&\cos \left( \alpha \right) I_{{2}}\sin
 \left( \alpha \right) &0\\\cos \left( \alpha
 \right) I_{{2}}\sin \left( \alpha \right) & \left( \sin \left( \alpha
 \right)  \right) ^{2}I_{{2}}&0\\ 0&0&0\end {array}
 \right]
$$