text:
Q: Is there any difference between these sentences Is there any difference between these two sentences?

*

*She entered his room without him knowing.

*She entered his room without making him know.
Please explain the meaning of these two sentences.

A: The first sentence is correct and means that he was not aware that she had entered the room. (You will also see such sentences written as: ....without his knowing..., which has the same meaning.)
The second sentence is awkward. I think it is trying to say that she entered the room without letting him know. That is to say, without informing him.
This means something quite different.
It is also ambiguous. The question is: know about what? It might mean that she did not let him know that she had entered the room. Alternatively, it might mean refer to something else that she kept to herself, rather than informing him. You would need to know the context in order to be sure of the meaning.


text:
Q: How to assign result of a sql query to a variable and use it into a built in function? Looking for a solution In Postgresql
declare n_rows integer := select count(*) from sample;

SELECT generate_series AS serial_num
FROM generate_series(0, n_rows + 1)

A: SQL has no variables, so short of using a function, you can use a common table expression:
with var as (
   select count(*) as n_rows
   from sample
)
SELECT g.serial_num
FROM var, generate_series(0, n_rows + 1) as g(serial_num)

Or just:
SELECT *
FROM generate_series(0, (select count(*) + 1 from sample)) as g(serial_num)

redpajama_set_name: RedPajamaStackExchange


text:
Q: PWA reset password link on Android device, when selecting to open with App We have a PWA app that adds the APP Icon for the PWA onto an Android devices home page (as expected). In the app we have a login with a reset password option if the user has forgotten their password
When an email is sent to the user with a link back to the ResetPassword page, opening the link on an adroid device gives the following:

If you open with the actual PWA App, then it ignores the page link address and just directs directly to the startup page for the PWA
If you open with Chrome then the correct page is displayed.
Why would opening with the PWA App ignore the location of the Link? Anyone?

A: PWA always loads the URL given in start_url attribute in manifect.json file. With the Intent filters, you can make your PWA open on clicking relevant URL or domain.
Look at "Effectively managing your app's scope" section in this article on how scoping and start URL works.
Unfortunately, there seems to be no way to make the start URL dynamic with the user requested URL in this case.


text:
Q: Почему так происходит? C++, инициализация данных Имеется вот такой код
class Test {
    double* data;
public:
    Test();
    Test(int a);
};
Test::Test() {
    Test(5);
}
Test::Test(int a) {
    data = new double [a];
}

однако если в программе вызвать
Test* test = new Test();

data будет 0x0000000000000000 почему так происходит? если инициализировать при помощи второго конструктора( с параметром который) тогда всё нормально сразу, но только стоит вложенный использовать все данные куда то пропадают, при отладке их тоже видно, до момента выхода из второго конструктора

A: Вызов конструктора, как и другие действия инициализации, должен находится в списке инициализации, а не в теле функции:
Test::Test(): Test{5} {
}
Test::Test(int a): data{new double [a]} {

}

Test(5); в теле функции создает безымянный временный объект, а не вызывает конструктор для этого объекта.
data = new double [5]; присваивает новое значение указателю, а не инициализирует его (хотя тут это ни на что не влияет).

A: Предлагаю такой вариант:
...

Test::Test() {
    data = new double [5];
}

...


text:
Q: Minimum variance portfolio under participation constraint in R cran I would like to find the minimum variance portfolio for 3 risky assets where the sum of the weights of all assets =  2 and weight of asset1 is set at +1 (i.e the problem would be to  minimise the portfolio vol by adjusting only the weights for asset asset 2 and 3 subject to them not being more than 1 and >=0.  I have found the below snippet of code that minimise the risk for a 3 asset portfolio, but I am unsure about how to incorporate the weight constraints. Any help / suggestions are welcome.
 covmat <- matrix(c(3.235343e-02, -3.378191e-03, -1.544574e-05,
                  -3.378191e-03,  8.769166e-03,  1.951734e-06,
                  -1.544574e-05,  1.951734e-06,  2.186799e-06),3,3)

    mat <- rbind(cbind(2*covmat,rep(1, 3)), c(rep(1, 3), 0))
    vec <-  c(rep(0, 3),1)
    smat <-  solve(mat)%*%vec
    smat[1:3,1]

Thank you,

A: R has a QP (quadratic programming) solver that is designed for these type of problems:
library(quadprog)
covmat <- matrix(c(3.235343e-02, -3.378191e-03, -1.544574e-05,
                   -3.378191e-03,  8.769166e-03,  1.951734e-06,
                   -1.544574e-05,  1.951734e-06,  2.186799e-06),3,3)
# linear constraint matrix
A <- rbind(c(1,1,1),diag(3))
# rhs
b <- c(2,1,0,0)
# solve QP model
solve.QP(covmat,dvec=rep(0,3),Amat=t(A),bvec=b,meq=2)$solution

Output:
[1] 1.0000000 0.3835757 0.6164243


text:
Q: How to remove label from group tag in Odoo 11 in views I want to show only the photo without the label which show the word Image and the line as showing in the photo
i use group tag to make the screen two sides and i want only the photo in the left side without the label of it which is appear by default in group
Is there ant ideas ?

A: Add the attribute nolabel="1" to your image field element
<field name="field_name" nolabel="1" />


text:
Q: Find $A^{100}+A^5$ Let $A= \begin{pmatrix} 1&-1 \\ 2&-2 \\  \end{pmatrix}$. We are to find $A^{100} +A^5$
My attempt : I found characteristic equation , $x^2+x=0$, so eigenvalues are $0$ and $-1$ hence its diagnol matrix is $$D=  \begin{pmatrix} 0&0 \\ 0&-1 \\  \end{pmatrix}$$  So $D^{100}+D^5$ is null matrix.
But I am getting something else if I use method given here To Find $A^{50}$ by achille hui.
Please help in this matter. Thanks

A: Observe the following computation:
$$
A^2 \;\; =\;\; \left [ \begin{array}{cc}
1 & -1 \\
2 & -2\\
\end{array} \right ]\left [ \begin{array}{cc}
1 & -1 \\
2 & -2\\
\end{array} \right ] \;\; =\;\; \left [ \begin{array}{cc}
-1 & 1 \\
-2 & 2\\
\end{array} \right ].
$$
Similarly if we compute $A^3$ we find
$$
A^3 \;\; =\;\; \left [ \begin{array}{cc}
-1 & 1 \\
-2 & 2\\
\end{array} \right ]  \left [ \begin{array}{cc}
1 & -1 \\
2 & -2\\
\end{array} \right ] \;\; =\;\;  \left [ \begin{array}{cc}
1 & -1 \\
2 & -2\\
\end{array} \right ].
$$
Therefore we have that $A^{2n} = -A$ and $A^{2n+1} = A$ for all $n \in \mathbb{N}$.  We conclude that
$$
A^{100} + A^5 \;\; =\;\; -A + A \;\; =\;\; \textbf{0}_{2\times 2}.
$$

A: If its characteristic equation is $x^2 + x = 0$, then that means that $x^2 = -x$, ie, $A^2 = -A$.
Thus, $A^{100} = (A^2)^{50} = (-A)^{50} = A^{50} = (A^2)^{25} = (-A)^{25} = -A^{25}$
At this point you've got an odd power, so simply factor out $-A$, so
$$\cdots = -A\cdot A^{24} = -A\cdot (A^2)^{12} = -A\cdot (-A)^{12} = -A\cdot A^{12} = -A\cdot (A^2)^6 = -A\cdot(-A)^6 = -A\cdot A^6$$
$$\cdots = -A\cdot (A^2)^3 = -A\cdot (-A)^3 = (-A)^4 = A^4 = (A^2)^2 = (-A)^2 = A^2 = -A$$
Thus, this shows that $A^{100} = -A$.
Doing the same thing with $A^5$ gives $A^5 = A\cdot (A^2)^2 = A\cdot (-A)^2 = A\cdot A^2 = A\cdot (-A) = -A^2 = -(-A) = A$.
Thus, indeed $A^{100} + A^5 = 0$.
This was the dumb way, but it's a method that's easily generalizable.
In this case, it's easier if you consider the powers of $A$:
$A^2 = -A$
$A^3 = A\cdot A^2 = A\cdot -A = -A^2 = A$
$A^4 = A\cdot A^3 = A\cdot A = A^2 = -A$
at which point you'll notice that $A^k = A$ if $k$ is odd, and otherwise $A^k = -A$ if $k$ is even. Thus, $A^{100} = -A$ and $A^5 = A$, so $A^{100} + A^5 = -A + A = 0$.

A: If you know that $A^2+A=0$, which follows from the value you computed for the characteristic polynomial and is easily checked explicitly, then you can compute the value of any polynomial $P[A]$ in$~A$ by computing the remainder $R$ of $P$ by $X^2+X$, and then computing $R[A]$. In the current case you are suspecting that $P[A]=0$, which amounts to saying $R=0$ (since $R$ is of degree at most $1$, and $c_0I+c_1A=0$ only holds for the given $A$ if $c_0=c_1=0$). You could check explicitly that $X^2+X$ divides $X^{100}+X^5$.
Since in this $X^2+X$ has the easy factorisation $X(X+1)$ with easy simple roots, there is a standard trick to find the remainder $R$ without doing the whole long division: since $P=Q(X^2+X)+R$ for some quotient$~Q$, you get $P[\lambda]=R[\lambda]$ for each root$~\lambda$ of $X^2+X$, that is for $\lambda\in\{0,-1\}$. You compute $P[0]=0=P[-1]$ easily for $P=X^{100}+X^5$, so you must have $R[0]=0=R[-1]$. With $R$ of degree at most$~1$ this forces $R=0$. So indeed you can be sure that $P[A]=0$.
Of course your argument with an explicit diagonal matrix $D$ similar to $A$ is also perfectly valid.


text:
Q: Response surface and variables importance Disclaimer: I'm not expert in math; the solution to this problem may be trivial.
I have a process based on a deterministic computer simulation where two continuous input variables $x_1$ and $x_2$ (under my control) produce a continuous output variable $y$.

My objective is to determine which one of the two variables affects the variability of $y$ the most and I would like the answer to be generalizable to any number of independent variables.
Mathematically speaking, my model is $y=f(x_1,x_2)$, with $f:X \rightarrow R $ being a continous unknown function in $X$ which is a simply connected domain.
Lack of random variation in $y$ suggest me that a statistical approach is not the right way to address the problem .
If I knew $f$ ,$ \frac{\partial f }{\partial x_1}$ and $\frac{\partial f}{\partial x_2}$ answer my question but only if $ \frac{\partial f }{\partial x_1}$ depends solely on $x_1$ (and same for $ \frac{\partial f}{\partial x_2}$). If it's not the case I do not know how to properly answer the question even by knowing $f$.

My naive approach:
I was thinking about "meshing" the $X$ domain in regions where $f$ is approximated by a linear  o by a quadratic model.

Let us define:
$L(x_1,x_2)=\beta_0+\beta_1x_1 + \beta_2x_2$
$Q(x_1,x_2)=\beta_0+\beta_1x_1 + \beta_2x_2 + \beta_3x_1x_2 +\beta_4x_1^2 + \beta_5x_2^2 $
In domain regions where linear approximation holds, $\frac{\partial L}{\partial x_1}=\beta_1$ and $\frac{\partial L}{\partial x_2}=\beta_2$ and this should be nice because I can directly compare the coefficient in order to assess which of the two variable influences $y$ the most.
In those region where linear approximation does not hold, the presence of the interaction term disrupts my interpretation because $\frac{\partial Q }{\partial x_1} = \beta_1 +\beta_3x_2 + 2\beta_4x_1$ depends on $x_2$ (and similar for $\frac{\partial Q }{\partial x_2}$)
Some thougts: linear approximation may be incorrect where sub-regions contain minima, maxima or saddle points. Does avoiding them by partitioning the domain with a finite number of "holes" could solve the issue? (I may use an optimization algorithm such as gradient descent in order to find them)

A: I believe your question is both utterly meaningless and highly relevant! The relevant part is clear to you because you wouldn't ask otherwise. For all others: One of the basic challenges to understand complicated computer models is to understand what is driving the results. A popular buzzword in this context is model "explainability".
So I agree, the problem itself and your thoughts on it are perfectly reasonable. That said, the question as stated is meaningless as a mathematical statement and hopeless in this generality from an applied perspective. You will need to sharpen your thinking around (at least) three issues:

*

*The operational definition of your question

*Assumptions on your function

*Clarity about the inputs respectively your coordinates.

The operational definition of your question:
As the commentator already stated "which one of the two variables affects the variability of y the most" is too fuzzy to be workable. For the sake of argument I will sharpen this (somewhat) to: "Is $x$ or $y$ more important in causing $f$ to be large?" Mathematically the answer is now clear: Take a "large" threshold $\tau$, define a measure of "importance" and apply it to the set $f^{-1}([\tau,\infty[)\subset\mathbb{R}^2.$ The problem is, even if $f$ is really "nice", e.g. infinitely differentiable, $f^{-1}([\tau,\infty[)$ can have any crazy shape. This makes it impossible to come up with a natural notion of importance. So, unless you have a clear externally defined and operational notion of importance your problem will be infeasible.
Assumptions on your function:
As you noticed yourself, 1) above makes restricting your class of functions as much as possible a key concern. So what do you know about your function? Available to you may be properties like "smooth", "convex", "monotonic in x or y", "where are the critical points" and so on. Your idea of approximating $f$ with simple functions is a very good and valid one. Prior knowledge about $f$ then helps in finding good approximations.
Clarity about the inputs respectively your coordinates:
You seem to treat your $x$ and $y$ coordinates as fixed. This is most likely because they are externally given by the process you simulate. But is this really true? Take for example a physical process where stuff ($x$) is ground  at a certain temperature ($y$) to produce output $L(x,y)=\beta_0+\beta_1 x+\beta_2 y$. You would say $x$ is more important than $y$ iff $\beta_1 > \beta_2$. But the beta-factors depend on units of measurement. If you stop measuring the stuff you grind in tons but state $x$ in milligrams the new factor $\tilde{\beta}_1$ will be larger than $\beta_1$ by a factor of $10^{12}$. Often in applications another natural invariant is monotonic reparametrizations.
This can be driven further and actually might help a lot depending on the requirements of your problem. Take your linear $L$ example. Arguably it is not enough for either $x_1$ or $x_2$ to be large alone to achieve a large $L$. Both must be large at the same time. So the "really important" variable is $z=\beta_1 x+\beta_2 y.$ Now you can answer "What drives $L$?" easily because the result is driven clearly and only by "z". This idea works more generally. As long as the gradient of your function does not vanish, you can reparametrize it by its level surfaces. The coordinate orthogonal to those level surfaces is then your single variable $z$.
Further remarks:
Even though your problem is deterministic, probabilistic approaches may be very useful to you. This is because of two reasons. First, putting some probability distributions on your inputs is often a very intuitive model for variability. Furthermore, by averaging/integrating over inputs you will get rid of some of the complexity involved. In your case you could use normal distributions $X$ and $Y$ with variance $\sigma^2_i$ as inputs and calculate the variance of the random variable $f(X,Y)$ as a function of the variance of the inputs.
The second reason is that the people thinking about Uncertainty Quantification have been analysing these kind of problems for a long time.


text:
Q: How to deserialize JSON to model object with Spring's RestController I'm developing a REST web application using Betfair's API, so I need to serialize/deserialize JSON in order to send HttpRequest and read HttpResponse.
I'm using Spring MVC so I want to use Jackson with @RestController, @RequestBody and @ResponseBody but I'm struggling to understand how they work.
In the following example I'm sending a POST request to Betfair to obtain user's firstname and lastname. I think that the HTTP Response should be deserialized into my model object AccountDetailsResponse, because I'm using @RequestBody annotation, but no value is shown in the home web page (only "Welcome, "). No exception is thrown.
Controller
@EnableWebMvc
@RestController
public class LoginController {
    private final String APP_KEY = "myAppKey";
    private final String LOGIN_END_POINT = "https://identitysso.betfair.it/api/login";
    private final String LOGOUT_END_POINT = "https://identitysso.betfair.it/api/logout";
    private final String ACCOUNT_END_POINT = "https://api.betfair.com/exchange/account/json-rpc/v1";
    private String token;

    @RequestMapping(value = "/index", method = RequestMethod.POST, params = { "firstName", "lastName" })
    public ModelAndView getAccountDetails(User user, @RequestBody AccountDetailsResponse accountDetails) {
        String response = null;

        JsonRequest jsonRequest = new JsonRequest();
        jsonRequest.setJsonrpc("2.0");
        jsonRequest.setMethod("AccountAPING/v1.0/getAccountDetails");
        jsonRequest.setId("1");

        response = HttpRequestHandler.sendRequest("POST", ACCOUNT_END_POINT, APP_KEY, jsonRequest);

        if(response.equals("ERROR")) {
            String message = "Error";
            return new ModelAndView("home", "message", message);
        }

        else {
            user.setFirstName(accountDetails.getResult().getFirstName());
            user.setLastName(accountDetails.getResult().getLastName());

            return new ModelAndView("home", "user", user);
        }
    }
}

N.B. I've omitted the showLoginForm (value = "/index", method = RequestMethod.GET) and doLogin (value = "/index", method = RequestMethod.POST, params = { "email", "password" })
HttpRequestHandler
public static String sendPostRequest(String url, String APP_KEY, JsonRequest jsonRequest) {
    try {
        URL urlRequest = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlRequest.openConnection();

        connection.setRequestMethod("POST");
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("X-Application", APP_KEY);

        int responseCode = connection.getResponseCode();

        if(responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }

            in.close();

            if(response.toString().contains("error")) {
                return "ERROR";
            }
            else
                return response.toString();
        }
        else
            return "ERROR";

    }
    catch (MalformedURLException e) {
        return "ERROR";
    }
    catch (IOException e) {
        return "ERROR";
    }
}

home.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>RestController test</title>

Welcome,

User
public class User {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private Double toBetBalance;
    private boolean logged;

    public User() { }

    //getters and setters
}

AccountDetailsResponse
public class AccountDetailsResponse {
    private String jsonrpc;
    private Result result;
    private String id;

    public AccountDetailsResponse() { }

    //getters and setters
}

Result
public class Result {
    private String currencyCode;
    private String firstName;
    private String lastName;
    private String localeCode;
    private String region;
    private String timezone;
    private Float discountRate;
    private Integer pointsBalance;
    private String countryCode;

    public Result() { }

    //getters and setters
}

JSON response from Betfair
[
   {
      "jsonrpc":"2.0",
      "result":{
         "currencyCode":"EUR",
         "firstName":"My name",
         "lastName":"My lastname",
         "localeCode":"it_IT",
         "region":"GBR",
         "timezone":"CET",
         "discountRate":0.0,
         "pointsBalance":0,
         "countryCode":"IT"
      },
      "id":1
   }
]

POM dependencies
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
    </dependency>

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.2</version>
    </dependency>

</dependencies>

Where am I wrong?

A: Shouldn't you be doing
response.getResult().getFirstName();
response.getResult().getLastName();

in the LoginController 's else block?

A: What OP needs is a Spring resource called RestTemplate. That's used to make a request to a URL, which response can be bound to a custom class, with Jackson taking care of the deserialization.
Take a look at the exchange method.


text:
Q: Alternative of using select query in case when statement in spark sql I am trying to run a query with select in case when statement. something like this:
select case when cust_id in (select cust_id from tab_cust) then 'Eligible' else 'Not Eligible' end as Eligibility
from tab_product;

but running this query in spark sql is giving error:

Table or view not found: tab_cust

But if I use same select query as subquery in where, no error is given but that will exclude set of records, which I don't want.
Is there any way to perform this query without using select statement in case when to get the same result?

A: Seems like you want to test if a value in one table is in another table.  True?  I use JOINs for this.  Here is a pyspark example.
from pyspark.sql.types import *

custSchema = StructType([
  StructField("cust_id", IntegerType())
])

productDF = spark.createDataFrame([(1,),
                                   (2,),
                                   (3,)
                                  ], schema=custSchema)

productDF.createOrReplaceTempView("tab_product")

customerDF = spark.createDataFrame([(2,),
                                    (3,),
                                    (4,)
                                  ], schema=custSchema)

customerDF.createOrReplaceTempView("tab_cust")

spark.sql("""
  SELECT tab_product.cust_id, nvl2(tab_cust.cust_id, 'Eligible', 'Not Eligible') as Eligibility
  FROM tab_product LEFT OUTER JOIN tab_cust
   ON tab_product.cust_id = tab_cust.cust_id
  """).show()

gives:
+-------+------------+
|cust_id| Eligibility|
+-------+------------+
|      1|Not Eligible|
|      3|    Eligible|
|      2|    Eligible|
+-------+------------+


text:
Q: VB6 file losing its secure certificate validation when executed from another program I have a small VB6 exe file that I have signed using a code signing certificate from GoDaddy.
I signed the file using Micrsoft's SignTool.
I put the file on a Windows PC and execute it. No problem. Certificate is valid.
I can run it multiple times, and still valid.
I then I have another program (Access DB) that calls this file using a shell command.
Once it calls that file, it immediately makes the file's certificate invalid: "The Digital Signature Is Invalid"
This VB6 file has never been a problem for years.  I recently had to make a small change to the file. Just one line of code.
I'm stumped.
Note: The VB6 file performs on FTP file download.


text:
Q: Java - A value resets to 0 unexpectedly I'm making a derivative calculator that asks the user for the degree of their polynomial and then the coefficients for each term, partly because I'm an inexperienced programmer and can't parse input like 3x^4/4 + sin(x).
Here's my class.
package beta;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

public class DerivativeCalculator
{
    public DerivativeCalculator(String d, String v)
    {
        int degree = Integer.parseInt(d);

        double value = Double.parseDouble(v);

        coeffList = new ArrayList<Double>();
        for (int i = 0; i <= degree; i++)
        {
            String console = JOptionPane.showInputDialog("Enter the coefficient of the "
                    + "x^" + i + " term.");
            Double coeff = Double.parseDouble(console);

            coeffList.add(coeff);
        }

    }
    public double calc()
    {
        double dx = 0.0001;

        double x1 = value;
        double y1 = 0;
        for (int d = degree; d >= 0; d--)
        {
            y1 += coeffList.get(d) * Math.pow(x1, d);
        }

        double x2 = x1 + dx;
        double y2 = 0;
        for (int d = degree; d >= 0; d--)
        {
            y2 += coeffList.get(d) * Math.pow(x2, d);
        }

        double slope = (y2 - y1)/ (x2 - x1);

        DecimalFormat round = new DecimalFormat("##.##");
        round.setRoundingMode(RoundingMode.DOWN);

        return Double.valueOf(round.format(slope));
    }

    public String getEquation()
    {
        String equation = "";
        for (int d = degree; d >= 0; d--)
        {
            equation = equation + String.valueOf(coeffList.get(d)) + "x^" + String.valueOf(d) + " + ";
        }
        return equation;
    }

    public String getValue()
    {
        return String.valueOf(value);
    }

    private int degree;
    private double value;
    private List<Double> coeffList;

}

Now here's my test class.
package beta;

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JApplet;
import javax.swing.JOptionPane;

public class DerivativeCalculatorTest extends JApplet
{
    public void paint(Graphics g)
    {
        Graphics2D g2 = (Graphics2D)g;

        String d = JOptionPane.showInputDialog("Enter the degree of your polynomial: ");
        String v = JOptionPane.showInputDialog("Enter the x value "
                + "at which you want to take the derivative");

        DerivativeCalculator myDerivCalc = new DerivativeCalculator(d, v);
        g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
        g2.drawString(myDerivCalc.getEquation(), 10, 40);
        g2.drawString(myDerivCalc.getValue(), 10, 70);
    }

}

Running this creates an applet window that displays
5.0x^0+
0.0
0.0

which is not the correct derivative.
I debugged my program and everything runs as expected until the view switches to my test class and it executes g2.drawString(String.valueOf(myDerivCalc.calc()), 10, 100);
After it executes this line, degree (the degree of the polynomial) resets to 0 even though the user entered 5. This then messes up all the for loops in my class.
Why does this happen? Any suggestions on fixing this? Thanks

A: You redefine degree and value as local variables inside your constructor. They shadow your class variables with the same name.
Do not re-declare them.
Instead of
  int degree = <something>;
  double value = <something>;

you need
  degree = <something>;
  value = <something>;

A: Isn't 5.0x^0 = 5.0 * 1 = 5.0, and the derivative of that is 0..
I believe your code is working.


text:
Q: How to create a custom while block I know that in ruby we can use a while loop, but I want to know if I can create a custom one so I can make something like this:
custom_while i < 5 do
    puts i
    i += 1
end

I currently have this code:
def custom_while(condition)
    loop do
        break if not condition
        yield
    end
end

i = 0
custom_while i < 5 do
    puts i
    i += 1
end

However, when condition is evaluated, it always get true (because it considers the first evaluation of i < 5 = true only.
Any help will be appreciated!
Note: This is for educational purposes only.

A: You almost had it. So, your problem is that the condition is only evaluated once? Well, what construct do we know that we can evaluate as often as we want? That's right: functions! So, let's make condition a function (or a Proc in Ruby lingo):
def custom_while(condition)
  loop do
    break unless condition.()
    yield
  end
end

i = 0
custom_while -> { i < 5 } do
  puts i
  i += 1
end
# 0
# 1
# 2
# 3
# 4

This is unfortunately not as nice looking as in other languages. Ruby's syntax and semantics are aggressively optimized for methods that take exactly 1 "function" as an argument. Ruby has a special syntactically and semantically light-weight construct for that, namely blocks. As soon as you have more than one, though, you're out of luck.
Compare this with languages that have proper block literals, like Smalltalk, for example. In Smalltalk, you could write a method while:do:, and call it like this:
i := 0.
while: [i < 5] do: [Transcript write: i. i := i + 1].

In fact, in Smalltalk, the syntax for blocks is so lightweight that there are no control structures at all in the language. if/then/else is simply an instance method of Boolean, for example:
i % 2 == 0 ifTrue: [Transcript write: "even"] ifFalse: [Transcript write: "odd"].

And while is actually an instance method of Block, so in reality, your example would look like this:
i := 0.
[i < 5] whileTrue: [Transcript write: i. i := i + 1]

Note: I make no guarantees for the Smalltalk code, I didn't test it.

A: The problem is, the condition is being evaluated before it's passed in, so it will never change.
Make the condition a function that you evaluate inside the loop, or use a macro to make it cleaner.


text:
Q: How declared a CONDENSED NUMERIC Variable in COBOL My COBOL problem is:
That i have data in the table at data base : my data is  :
Z-ZYSR-MONTAN(IZYSR) that have a format : NOT NULL NUMBER(11,2) .
so I have a program that I need to move my data in one variable "H-ZYSR-MONTAN " and after I will move this in one colonne Z8 when I compile I obtained Excel with data in the different colonne.
my question how to declare the variable to obtain the good result?
I do this but I can't obtient the right resultat:
My data in the beging:
2223,55
-10,98
-1,08
82,61
variables that I declare:

05  H-ZYSR-MONTAN           PIC S9(11)V9(2) COMP-3.

* Taux horaire formation
            05  W-Z18                  PIC S9(11)V9(2) COMP-3.
            05  FILLER                 PIC X(001) VALUE ';'.

The code:

    ALIM-WZ18 SECTION.
             MOVE Z-ZYSR-NOMBRE TO IZYSR.
             MOVE ZERO TO H-ZYSR-MONTAN.

          IF Z-ZYSR-NOMBRE > ZERO
             PERFORM VARYING IZYSR FROM Z-ZYSR-NOMBRE BY -1 UNTIL
                             IZYSR = ZERO
                IF Z-ZYSR-CODRUB(IZYSR) = 'THF'
                   MOVE Z-ZYSR-MONTAN(IZYSR) TO
                        H-ZYSR-MONTAN

                   MOVE ZERO TO IZYSR
                END-IF
             END-PERFORM
               MOVE H-ZYSR-MONTAN TO W-Z18
               END-IF.

The resultat that i obtain is like this  :
Z18
€
" "
0
0
@
0
P
@
I never obtain the same like:
2223,55
-10,98
-1,08
82,61

A: As I understand the problem, you only need to change the formatting of W-Z18 from PIC S9(11)V9(2) COMP-3 to PIC -(12),99, as shown below.
Does this help?
   environment division.
   configuration section.
   special-names.
       decimal-point is comma.
   data division.
   working-storage section.
   1 filler.
    2 test-values.
     3 pic s9(11)v99 comp-3 value 2223,55.
     3 pic s9(11)v99 comp-3 value -10,98.
     3 pic s9(11)v99 comp-3 value -1,08.
     3 pic s9(11)v99 comp-3 value 82,61.
    2 filler redefines test-values.
     3 test-value comp-3 pic s9(11)v99 occurs 4.

   1 W-Z18 PIC -(12),99.

   1 i binary pic 9(4).
   procedure division.
   begin.
       perform varying i from 1 by 1 until i > 4
           move test-value (i) to W-Z18
           display W-Z18
       end-perform
       stop run
       .

Results:
        2223,55
         -10,98
          -1,08
          82,61


text:
Q: Изменение документа в mongodb по времени В MongoDB можно создать индекс для удаления документа по времени (TTL). Имеется ли подобные средства для обновления документа. Либо его создание. Задача состоит в том что бы после определенного времени после создания документа обновить в ней некоторые поля. Спасибо!

A: Эту задачу в реляционных базах данных решают триггеры. В MongoDB подобного функционала нет.
Есть так называемые Tailable Cursors с помощью которых можно подобный функционал создать.
Некоторые реализации на JavaScript:

*

*https://github.com/afharo/mongo-trigger

*https://github.com/iddogino/mongoTriggers (без tailable cursors, но идея та же)


text:
Q: How to upsert record from one object to other There are 2 objects. Object A and object B with same fields. There is no relationship between them (no lookup). When a record is inserted in object A, object B should be checked to see if the same record exists. If it exists then update it else create a new one. How do I do this.  Please assist.
Regards,
Sfdcdev

A: You'll probably need a trigger on Object A:
trigger on ObjectA (after insert){
 TriggerHelper.checkExistenceInObjectB(trigger.new);
}

public class TriggerHelper{
  public static void checkExistenceInObjectB(List<ObjectA> l){
   //some code to query objects B based on your objects A criteria
   //some code to treat or create objects B
   //insert or update your list of objects B:
   upsert listOfObjectsB;
  }
}


text:
Q: coloring only a Button in Kivy in a RecycleGridLayout I'm trying to develop a program written in python using Kivy for the graphic elements.
BoxLayout:
        RecycleView:
            viewclass: 'Button'
            data: [{'text': str(x)} for x in root.data_items]

            RecycleGridLayout:
                cols: 5
                cols_minimum: {0: 400, 1: 180, 2: 62, 3: 62, 4: 62}
                size_hint: 1, None
                default_size: None, dp(35)
                default_size_hint: 1, None
                height: self.minimum_height

I used this code to create a grid layout of buttons.
I need a particular Button of the grid to be colored different from the others only if a condition is fulfilled.
The condition is checked in the .py file
sql_conn.execute("SELECT ...")
rows = sql_conn.fetchall()
for row in rows:
    for col in row:
        self.data_items.append(col)
    if row[2] == row[4]:

As you can see I have a query that fetches all the elements for the grid layout.
The query get some elements from the database and in particular QTA (total quantity) and OK (how many products have been checked).
In the grid layout there will be the name of the products followed by their total and checked quantities.
If the two quantities of the product are the same i want the QTA button to be colored in green.
I tried lot of things but I was able to color only all the buttons of the grid layout.
If I try something like this I will abviously color all the buttons
rows = sql_conn.fetchall()
for row in rows:
    for col in row:
        self.data_items.append(col)
    if row[2] == row[4]:
        Button.background_color = [0,255,0,0.3]

Can someone help me?

A: RecycleView receives as a data list of dictionaries, in those dictionaries the properties of the elements are indicated, so we must create those properties and then copy it, in your code I see that those dictionaries are creating them in the .kv, now you must do it in the .py as I show below:
*.py
rows = sql_conn.fetchall()
values = []
for row in rows:
    change_color = row[2] == row[4]
    for i, col in enumerate(row):
        text = str(col)
        color =  [0, 255, 0, 0.3] if i == 4 and change_color else [1, 1, 1, 1]
        d = dict(text=text, background_color=color)
        values.append(d)

self.data_items = values

*.kv
BoxLayout:
    RecycleView:
        viewclass: 'Button'
        data: root.data_items # <----

        RecycleGridLayout:
            cols: 5
            cols_minimum: {0: 400, 1: 180, 2: 62, 3: 62, 4: 62}
            size_hint: 1, None
            default_size: None, dp(35)
            default_size_hint: 1, None
            height: self.minimum_height


text:
Q: Get QKeySequenceEdit value Am having issues getting the value of my "QKeySequenceEdit", I need to get this value to print it on a label and console.
This is my code:
  ##Create my KeySecuenceEdit
        self.ksec_hotkey = QtWidgets.QKeySequenceEdit(self.gpb_main)##it is inside of a groupbox
        self.ksec_hotkey.setGeometry(QtCore.QRect(10, 75, 85, 27))
        self.ksec_hotkey.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.ksec_hotkey.setObjectName("ksec_hotkey")
        self.ksec_hotkey.keySequenceChanged.connect(self.show_ksec)##Call my function here

    ##function to get and print keySequenceEdit value
    def show_ksec(self):
        ksec_value = self.ksec_hotkey.keySequence()
        #print(str(ksec_value))   ##does not work
        #print(ksec_value.__dict__)   ##.__dict__  or .__repr__ does not work
        print(ksec_value)   ##prints "<PyQt5.QtGui.QKeySequence object at 0x7f28386a5dd0>"
        self.lbl_print_hotkey.setText(" : " + str(ksec_value))   ##prints "<PyQt5.QtGui.QKeySequence object at 0x7f28386a5dd0>"

My code prints: "<PyQt5.QtGui.QKeySequence object at 0x7f28386a5dd0>".
I read about issues with classes, so this is my program so far:
class Ui_MainWindow(object):

    ##here is my function to print
    def show_ksec(self):

    ##here is where my qkeysequence and all my widgets are
    def setupUi(self, MainWindow):

A: You have to use the toString() method of QKeySequence:
keysequence = self.ksec_hotkey.keySequence()
text = keysequence.toString(QKeySequence.NativeText)
# or
# text = keysequence.toString(QKeySequence.PortableText)
self.lbl_print_hotkey.setText(f" : {text}")


text:
Q: AWS Cognito prevent creating duplicate phone number While registering users in AWS Cognito user pool we are choosing the option to "allow email addresses" as the username to sign up and sign in. In the required attributes there is also phone number. But the same phone number can be used again for another user, while the email id is unique. Is there any way to stop the phone number being duplicated,so that both the phone number and email id is unique for each user?

A: You can use Pre-Signup Lambda trigger to check whether the phone number is already in use and handle accordingly.


text:
Q: How to provide access to a pod so that it can list and get other pods and other resource in the namespaces/cluster I have been working on creating a application which can perform verification test on the deployed istio components in the kube-cluster. The constraint in my case is that I have run this application as a pod inside the kubernetes and I cannot provide cluster-admin role to the pod of the application so that it can do all the operations. I have to create a restricted ClusterRole just to provide enough access so that application list and get all the required deployed istio resources (Reason for creating a cluster role is because when istio is deployed it created both namespace level and cluster level resources). Currently my application won't run at all if I use my restricted ClusterRole and outputs and error
Error: failed to fetch istiod pod, error: pods is forbidden: User "system:serviceaccount:istio-system:istio-deployment-verification-sa" cannot list resource "pods" in API group "" in the namespace "istio-system"

Above error doesn't make sense as I have explicitly mentioned the core api group in my ClusterRole and also mentioned pods as a resource in the resourceType child of my ClusterRole definition.
Clusterrole.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: {{ .Values.clusterrole.name }}
  namespace: {{ .Values.clusterrole.clusterrolens}}
rules:
- apiGroups:
  - "rbac.authorization.k8s.io"
  - "" #enabling access to core API
  - "networking.istio.io"
  - "install.istio.io"
  - "autoscaling"
  - "apps"
  - "admissionregistration.k8s.io"
  - "policy"
  - "apiextensions.k8s.io"
  resources:
  - "clusterroles"
  - "clusterolebindings"
  - "serviceaccounts"
  - "roles"
  - "rolebindings"
  - "horizontalpodautoscalers"
  - "configmaps"
  - "deployments"
  - "mutatingwebhookconfigurations"
  - "poddisruptionbudgets"
  - "envoyfilters"
  - "validatingwebhookconfigurations"
  - "pods"
  - "wasmplugins"
  - "destinationrules"
  - "envoyfilters"
  - "gateways"
  - "serviceentries"
  - "sidecars"
  - "virtualservices"
  - "workloadentries"
  - "workloadgroups"
  - "authorizationpolicies"
  - "peerauthentications"
  - "requestauthentications"
  - "telemetries"
  - "istiooperators"
  resourceNames:
  - "istiod-istio-system"
  - "istio-reader-istio-system"
  - "istio-reader-service-account"
  - "istiod-service-account"
  - "wasmplugins.extensions.istio.io"
  - "destinationrules.networking.istio.io"
  - "envoyfilters.networking.istio.io"
  - "gateways.networking.istio.io"
  - "serviceentries.networking.istio.io"
  - "sidecars.networking.istio.io"
  - "virtualservices.networking.istio.io"
  - "workloadentries.networking.istio.io"
  - "workloadgroups.networking.istio.io"
  - "authorizationpolicies.security.istio.io"
  - "peerauthentications.security.istio.io"
  - "requestauthentications.security.istio.io"
  - "telemetries.telemetry.istio.io"
  - "istiooperators.install.istio.io"
  - "istiod"
  - "istiod-clusterrole-istio-system"
  - "istiod-gateway-controller-istio-system"
  - "istiod-clusterrole-istio-system"
  - "istiod-gateway-controller-istio-system"
  - "istio"
  - "istio-sidecar-injector"
  - "istio-reader-clusterrole-istio-system"
  - "stats-filter-1.10"
  - "tcp-stats-filter-1.10"
  - "stats-filter-1.11"
  - "tcp-stats-filter-1.11"
  - "stats-filter-1.12"
  - "tcp-stats-filter-1.12"
  - "istio-validator-istio-system"
  - "istio-ingressgateway-microservices"
  - "istio-ingressgateway-microservices-sds"
  - "istio-ingressgateway-microservices-service-account"
  - "istio-ingressgateway-public"
  - "istio-ingressgateway-public-sds"
  - "istio-ingressgateway-public-service-account"
  verbs:
  - get
  - list

Application I have built leverage the istioctl docker container published by istio on dockerhub. Link.
I want to understand what changes are required in above ClusterRole definition so that I can perform the get and list operations for the pods in the namespace.
I would also want to understand that is it possible that the error I am getting is trying to reference some other resource in the cluster?
Cluster information:
Kubernetes version: 1.20
Istioctl docker image version: 1.12.2
Istio version: 1.12.1

A: As OP mentioned in the comment problem is resolved after my suggestion:

Please run the command kubectl auth can-i list pods --namespace istio-system --as system:serviceaccount:istio-system:istio-deployment-verification-sa and attach result to the question. Look also here

OP has confirmed that problem is resolved:

thanx for the above command using above I was finally able to nail down the issue and found the issue to be with first resourceName and second we need to mention core api in the api group before any other. Thank you issue is resolved now.


text:
Q: ti.draggable android module doesn't work on intel cpu I've got error on Samsung - Galaxy Tab 3 (GT-P5210) 4.2.2 (Intel Atom Z2560 1600 Mhz) from app using ti.draggable:

java.lang.UnsatisfiedLinkError: Cannot load library:
  load_library(linker.cpp:761): not a valid ELF executable:
  /data/app-lib/sc.gm.sm-1/libti.draggable.so   at
  java.lang.Runtime.loadLibrary(Runtime.java:371)   at
  java.lang.System.loadLibrary(System.java:535)     at
  org.appcelerator.kroll.runtime.v8.V8Runtime.loadExternalModules(V8Runtime.java:114)
    at
  org.appcelerator.kroll.runtime.v8.V8Runtime.initRuntime(V8Runtime.java:81)
    at org.appcelerator.kroll.KrollRuntime.doInit(KrollRuntime.java:175)
    at
  org.appcelerator.kroll.KrollRuntime$KrollRuntimeThread.run(KrollRuntime.java:109)

At the same time on Samsung - Galaxy Tab 2 10.1 (GT-P5110) it's okey, it has CPU TI OMAP4430 1000 Mhz
Does some know how to fix it?

A: This means that the library does not contain native module (.so) for x86 architecture or it wasn't included in to your .apk. Unfortunately, I haven't worked with titanium. Try to specify some 'build targets' options etc...

A: ti.draggable has an x86 shared object included. If the application included this shared object, you shouldn't be seeing the issue that you are currently reporting. Here is the link to the archive with x86 libs. Since this is a native library, there can be issues in running on a platform if the corresponding .so is absent.


text:
Q: How do I initialise Swagger Client for the browser with an auth token? In a browser-based (Cordova) app, I am trying to configure a swagger-client for the Strava REST API, to use an existing auth token in the request header.
Following the little guidance there is at
 https://github.com/swagger-api/swagger-js/blob/master/docs/MIGRATION_2_X.md I have come up with the following
    window.stravaClient = new SwaggerClient("https://developers.strava.com/swagger/swagger.json",
{ authorizations: { Authorization: 'Bearer '+ authToken }})

But, I keep getting the error:
TypeError: undefined is not a function (near '...).then( function() {...')


text:
Q: Running Gutenberg React in Development Mode Is there a way to enable WordPress to run the non-minified version of React while developing Gutenberg blocks?
I am receiving an error from React while learning to create Gutenberg blocks.
react-dom.min.b75d8b30.js:62 Error: Minified React error #130; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

It would be very helpful to get the full error. I am using the Gutenberg suggested abstraction, wp.element.createElement in order to create the elements. So my plugin has no direct access to React.

A: It took me way too long to find this but all you have to do is set SCRIPT_DEBUG to true. Simply add this line to wp-config.php:
define('SCRIPT_DEBUG', true);


text:
Q: Changing the legend in chartSeries to display values - Quantmod addTA Is it possible to change the legend on the plot displayed in Quantmod so that values are displayed rather than the variable name? For example:
library("quantmod")
getSymbols("YHOO")
temp1 <- 6
temp2 <- "SMA"
barChart(YHOO)
addTA(ADX(YHOO, n=temp1, maType=temp2))

The legend that is displayed in the plot is ADX(YHOO, n=temp1, maType=temp2). I would like it to display the specific values instead i.e. ADX(YHOO, n=6, maType='SMA').

A: There isn't a way to do this automatically with addTA, because it would need to know which of the the parameters of the TA call it needs to evaluate.  But you can do it manually by setting the legend= argument yourself.
One way to do it is to use paste (or paste0).
barChart(YHOO)
Legend <- paste0('ADX(YHOO, n=',temp1,', maType=',temp2,')')
addTA(ADX(YHOO, n=temp1, maType=temp2), legend=Legend)

Or you could create and manipulate the call to get what you want.
barChart(YHOO)
callTA <- call("ADX",quote(YHOO),n=temp1,maType=temp2)
eval(call("addTA", callTA, legend=deparse(callTA)))

A: The following is a partial solution which displays the values rather than variable names in the legend as well as the relevant output values for the TA. However, unlike the default settings of addTA, the text for each output value doesn't match the colour of the line on the addTA plot. Unfortunately I haven't worked out how to get the text of the output values to match the colour of its relevant line on the addTA plot. Any suggestions?
  library("quantmod")
  getSymbols("YHOO")
  barChart(YHOO, subset="last 4 months")
  col <- c("red", "blue", "green", "orange")
  temp1 <- 8
  temp2 <- "SMA"
  temp <- ADX(HLC(YHOO), n=temp1, maType=temp2)
  legend <- rep(NA, NCOL(temp)+1)
  legend[1] <- paste("ADX(HLC(YHOO)", "n=", temp1, "maType=", temp2)
  for(x in 2:(NCOL(temp)+1)){
      legend[x] <- (paste(colnames(temp[,(x-1)]),": ", round(last(temp[,(x-1)]),3), sep=""))
  }
  addTA(temp, legend = legend, col=col)


text:
Q: Trying to convert Cross-Filter Report to a SOQL query I need to convert a cross-filter report of Leads and Activities to a SOQL query.
Filters

*

*All Leads

*Created Date: All Time

Cross Filters
Leads without Activities

*

*Subject contains: voicemail, call, etc

*Created Date equals LAST 90 DAYS

This is what I have done so far, I'm struggling to find the logic to only include "Leads without valid activities in the last 90 days":
[SELECT Id, (SELECT Id FROM Tasks
                       WHERE CreatedDate <= :d
                         AND Subject LIKE :subjects)
            FROM Lead WHERE OwnerId != sfAdmin.Id]
//d = "LAST 90 Days in my code"
//subjects = "List of all the valid subjects"
//sfAdmin.Id = "Id of a specific user"

A: This query is actually not supported in SOQL, if you want your root query object to remain Lead. With other child objects, you could do it via Left Inner Join, also known as semi join inner select. Here's what it would look like:
SELECT ... FROM Lead WHERE Id IN (
    SELECT WhatId FROM Task
    WHERE CreatedDate = LAST_90_DAYS
    AND Subject IN ('Voicemail, 'Call')
)

However, trying to run this query will yield an error:

Entity 'Task' is not supported for semi join inner selects

Your alternatives are to create a rollup that you can use as a filter, or to query the Task records as step 1, then use it to filter Lead ids in step 2. The latter would look like:
Set<Id> leadIds = new Map<Id, AggregateResult>([
    SELECT WhatId Id FROM Task
    WHERE What.Type = 'Lead'
    AND CreatedDate = LAST_90_DAYS
    AND Subject IN ('Voicemail', 'Call')
    GROUP BY WhatId
]).keySet();
List<Lead> filteredLeads = [SELECT ... FROM Lead WHERE Id IN :leadIds];

If you don't mind switching your primary query object to be Task, it may be simpler to do that, and you can do your filtering accordingly.


text:
Q: How to save enum class in a HashMap? Let us say we have following enums:
public enum AnimalImages {
TIGER,BEAR,WOLF;
}

public enum CarImages {
BMW,VW,AUDI;
}

Now I want to save these enum classes in a HashMap:
Map<String,Enum<?>> enumMap=new HashMap<String,Enum<?>>();
enumMap.put("AnimalImages",???????);

What I should enter instead of the question marks?

A: To explicitly answer to your question, you have to put the enum value as this:
Map<String,Enum<?>> enumMap=new HashMap<String,Enum<?>>();
enumMap.put("AnimalImages", AnimalImages.TIGER);

However, if you want to put all the value belonging to an enum, then you could leverage values() method and also change your map to Map<String,Enum<?>[]> so you can use this:
Map<String,Enum<?>[]> enumMap=new HashMap<String,Enum<?>[]>();  // Note Enum<?>[] array
enumMap.put("AnimalImages", AnimalImages.values());
enumMap.put("CarImages", CarImages.values());

Another approach, with a shorten signature can be something like this:
Map<String, Object> enumMap = new HashMap<String,Object>();
enumMap.put("AnimalImages", AnimalImages.values());
enumMap.put("CarImages", CarImages.values());

Another way that bali182 pointed in this comment, you could use:
Map<String, Collection<? extends Enum<?>>> enumMap = new HashMap<>();
enumMap.put("AnimalImages", Arrays.asList(AnimalImages.values()));
enumMap.put("CarImages", Arrays.asList(AnimalImages.values()));

A: To answer your question:
enumMap.put("AnimalImages", AnimalImages.WOLF);
enumMap.put("Cars", CarImages.AUDI);

But you can also do
Map<String, AnimalImages> enumMap = new HashMap<String, AnimalImages>();

And this way enumMap.get("AnimalImages"), and this way you won't have to type check and cast it.

A: If the requirement is to create a Map that contains all values of a given enum, I would use a mapping of String keys into EnumSet values:
Map<String, EnumSet<?>> enumMap = new HashMap<String, EnumSet<?>>();
enumMap.put("AnimalImages", EnumSet.allOf(AnimalImages.class));
enumMap.put("CarImages", EnumSet.allOf(CarImages.class));

for (Map.Entry<String, EnumSet<?>> e : enumMap.entrySet()) {
    System.out.println(String.format("key: [%s], values: %s",
        e.getKey(), e.getValue().toString()));
}

EnumSet is a specialized Set implementation, which is represented internally as a bit vector. Its sole purpose is to provide an efficient and easy way to store enums.


text:
Q: Node.js Read daily tip from a text document I am currently working on a Discord bot and was wondering if there is a way to get the bot to automatically post a daily tip, which it would read from a text file and display it on the relevant Dicord channel.
I can get it to display the whole file repeatedly (I have been testing it with a 5 second timeout), however, I cannot get it to display the first line only, wait 5 seconds, display the second line only, wait 5 seconds etc.
Any advice would be greatly appreciated.

A: First, you need to convert the text file containing tips into an Array. Let's assume you entered all your tips an array called dailyTips. You can use bot.setInterval(() => {...}, time) in your bot.on('ready', () => {...} event. The bot will execute the command every milli-seconds you specify in time.
let dailyTips = ['...', '...', '...'];

bot.on('ready', () => {
  bot.setInterval(() => {
    let toSendChannel = bot.channels.get('id'); // The channel you will send the tip in
    let tip = dailyTips[Math.floor(Math.random() * dailyTips.length)]; // get random tip from the array
    toSendChannel.send(tip);
  }, 86400000); // 1 day = 86400000 ms
});

bot.login(token);

I hope I cleared everything out for you.


text:
Q: Rails not accounting for daylight savings time ActiveSupport::TimeZone.new("Pacific Time (US & Canada)")
=> (GMT-08:00) Pacific Time (US & Canada)

...but right now, in LA it's GMT-07:00 because of DST. See http://www.timeanddate.com/worldclock/city.html?n=137
Is this a bug, an error in my settings, or am I creating the TimeZone object improperly? Can't seem to figure it out

A: Figured it out. Turns out the TimeZone object does have a concept of 'now':
tz = ActiveSupport::TimeZone.new("Pacific Time (US & Canada)")
=> (GMT-08:00) Pacific Time (US & Canada)
tz.parse('8:00AM')
=> Fri, 12 Oct 2012 08:00:00 PDT -07:00

So you can still create TimeWithZone objects with the proper offset using the TimeZone-- despite the fact that its to_s method displays the incorrect offset.

A: I don't believe ActiveSupport::TimeZone objects have a concept of "now". You can initialize a TimeZone with whatever utc_offset in seconds from you want with ::create:
ActiveSupport::TimeZone.create("Pacific Time (US & Canada)", -(60 * 60 * 7))
#  => (GMT-07:00) Pacific Time (US & Canada)

The concept of now in relation to daylight savings time makes more sense when dealing with ActiveSupport::TimeWithZone objects. When you make your Rails app time zone aware by setting the time zone in application.rb:
config.time_zone = 'Pacific Time (US & Canada)'

...and you use Time.zone.now, the result will take into account daylight savings time, GMT-07:00. So at the time of this post:
Time.zone.now
=> Fri, 12 Oct 2012 07:03:51 PDT -07:00

Time.zone.now.class
=> ActiveSupport::TimeWithZone


text:
Q: ¿Cómo puedo mover un objeto con jquery dentro de un div? Hola muy buenas a todos.
Quería saber como puedo mover un objeto (como por ejemplo un div con forma de cuadrado) dentro de un div.
Los obstaculos los he creado a traves de constructores y jquery, pero a la hora de crear el personaje y hacer que se mueva de izq a dch y viceversa o saltar, no soy capaz :(

Estoy empezando con jquery y estoy un poco perdido.

A: Interesante pero sólo con css y javascript te será bastante complejo podría decir, haz pensado en usar flash? bueno de todas formas te dejo un pequeño ejemplo "animate" de jQuery, espero que te sirva.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title></title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd"
        crossorigin="anonymous">


text:
Q: Login Controller using HashMapping Javafx Hey so im having a problem with my login controller (MVC pattern). Im trying to create a login screen that will remember user logins and all that jazz. But when i try logging in it always comes up as an error or unfound user. Im not sure why...
Right now the only user in the HashMap is ("admin", "pass")
Input in Login
Username: Admin
Password: Pass
Output: User not Registered
or I get a NPE at the password check
public LoginController(LoginWindowGui view){
view.setLoginListner(new LoginListener(){

  @Override
  public void buttonClicked(LoginEvent le) {
    model = le.getPerson();
    model.setUserName(le.getPerson().getUserName());
    model.setPassword(le.getPerson().getPassword());
    System.out.println(le.getSource());
    System.out.println(le.getPerson());

    if(RememberUserLogins.userMap.containsKey("admin")){
      String storedPassword = RememberUserLogins.userMap.get(model.getPassword());
       if(storedPassword.equals("pass")){
         System.out.println("Login Scussfull!!!");
       } else {
         System.out.println("Password Incorrect.");
       }
    } else {
      System.out.println("User not Registered, "
          + "Please Register now.");
    }

    System.out.println(RememberUserLogins.userMap);

  }
});

A: You are mixing up user with password when you call:
RememberUserLogins.userMap.get(model.getPassword());

You checked if the map contains key ("admin"), but then you call get() on the value not the key, which returns null, and causes the NPE


text:
Q: Stored procedure won't return 0 this is my sp
CREATE PROCEDURE DeteleTitle
(
@TitleID int
)
AS
BEGIN
IF EXISTS(Select TitleID from Titles WHERE TitleID=@TitleID)
BEGIN
DELETE FROM Titles WHERE  TitleID=@TitleID
SELECT @TitleID
END
ELSE
BEGIN
SELECT 0
END
END

Method where I am calling it is:-
public Int32 DeleteTitle(Int32 TitleID)
{
try
{
int ds=0;
SqlParameter[] sqlparam=new SqlParameter[1];
sqlparam[0]=(@TitleID,TitleID);
ds=Convert.ToInt32(SqlHelper.ExecuteScalar(ConfigurationManager.ConnectionStrings["con"].ConnectionString,CommandType.StoredProcedure,"DeleteTitle",sqlparam).Tables[0]);
return ds;
}

catch(Exception ex)
{
return 0;
}
}

Now TitleID is a Foreign Key in many Tables. If some Table's record is using TitleID, then it throws this exception that says "Foreign Key Violation n stuff". In my Stored procedure above, I am selecting zero in the else block in case delete is not successful. When delete IS successful, it returns TitleID's value like 50, 99 or whatever. Now what is happening is , when delete is not successful, it is not returning zero. I wanted a message to be displayed on screen based on this zero value returned by Delete Stored procedure but when it didn't return any value (when delete failed), I returned zero in the catch block of my DeleteTitle() method.
Now I have two questions:-

*

*Why did the Stored procedure not return zero when delete failed?

*Is returning zero in the catch block like I have done above the right way? I didn't know how you retrieve Foreign key Exception number and stuff so I just returned zero there in catch block.

A: You'd want a TRY...CATCH in your procedure, not an IF...ELSE.
If you think about it, you're already in the IF portion of your statement when the DELETE fails with the foreign key violation. How could your code possibly jump to the ELSE block?

A: The problem is that your if statement will not execute the ELSE statement if it fails with an exception.  Your IF statement also appears incorrect- shouldn't it be IF EXISTS, [then delete record?]  The way it's written now, if the record exists it will NOT be deleted.
The extended problem is that it is considered bad practice to rely on an exception (in C#, SQL, or any other language) as a method for flow control.
You would be better off explicitly checking for related records by using the EXISTS statement for each related table.

A: If Tables is a collection of tables, you'd need another [0] for the first column of the first table.

A: use this:
CREATE PROCEDURE DeteleTitle
(
@TitleID int
)
AS
BEGIN TRY
    DELETE FROM Titles WHERE TitleID=@TitleID
    SELECT CASE
               WHEN @@ROWCOUNT>0 THEN @TitleID
               ELSE 0 --row did not exist
           END
END TRY
BEGIN CATCH
    SELECT 0 --delete failed
END CATCH
go

When multiple tables are "linked" via foreign keys and you delete a parent row you get an error like you are reporting, because the child data can't exist without a parent.  You might want to look into cascade deletes, or add code in this procedure to delete from the tables that are associated with Titles via foreign keys.  Add these deletes before the DELETE FROM Titles. do it like this:
CREATE PROCEDURE DeteleTitle
(
@TitleID int
)
AS
BEGIN TRY
    BEGIN TRANSACTION

    DELETE FROM YourOtherTablesA WHERE TitleID=@TitleID
    DELETE FROM YourOtherTablesB WHERE TitleID=@TitleID

    DELETE FROM Titles WHERE TitleID=@TitleID
    SELECT CASE
               WHEN @@ROWCOUNT>0 THEN @TitleID
               ELSE 0 --row did not exist
           END
    COMMIT
END TRY
BEGIN CATCH
    IF XACT_STATE()!=0
    BEGIN
        ROLLBACK TRANSACTION
    END
    SELECT 0 --delete failed
END CATCH
go

A: You can use @@ERROR for the output result. @@ERROR = 0 mean successful else unsuccessful operation
CREATE PROCEDURE DeteleTitle
(
    @TitleID int
)
AS

BEGIN
    IF EXISTS(Select TitleID from Titles WHERE TitleID=@TitleID)
    BEGIN
        DELETE FROM Titles WHERE  TitleID=@TitleID
    END

    Select @@ERROR

END


text:
Q: Can Ansible's win_powershell thoroughly process a boolean win_powershell seems to choke when I attempt to pass a Boolean variable through it to register a tested discrete state on a remote guest/target (for later consumption).  For numerous attempts to provide compliant statements, I get errors such as ...

*

*was not followed by a valid variable name character. Consider using ${} to delimit the name.

*Last close parenthesis is an invalid character

*Cannot convert string to bool

*Colon is unexpected token

*$True is unexpected token

*Unable to convert to dictionary

*Must either be a JSON string or in the key=value form
My goal was to use the win_powershell module to execute a powershell script ...
  $IsInstalled = ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0

... on a remote host and consume the IsInstalled variable later in the Playbook.  (the p/s statement executes flawlessy when invoked directly).
My task ended up looking like the below with all of the various/unsuccessful attempts commented out. Notice that I resorted to the simplest of tests in the end which infers that processing a boolean via win_powershell is not do-able. I'm hoping somebody can prove me wrong and/or confirm that I need to get such resolve by processing a string variable instead.
BTW (for the innocent by-stander) there are no hits for the word bool in the Ansible documentation for win_powershell.  However, the description for parameters includes the word dictionary and term key=value pairs. If these descriptions are restraints, it should be (I wish it were) stated as such (more emphatic).
Key points observed along the way, …

*

*An = operator always produces a string; use json syntax for other variable types; a : (colon) for other types such as boolean.

*Consider using ${} to delimit the variable name (but how?)

*Enclose any boolean equates with single '

*I found some other blogs/posts but nothing in layman (json newbie) terms (that I could understand).

Anybody have a solution to make a Boolean work as sought or should I (just) try to process the needed state as a string variable?  Check out these blogs …
powershell - Variable reference is not valid. ':' was not followed by a valid variable name character
How can you use an object's property in a double-quoted string?
Here's my task efforts (with failed statements being commented) ...
   - name: Test for installed SQL Server
      ansible.windows.win_powershell:
        script: |
          [CmdletBinding()]
          param (
            [bool]$IsInstalled
          )
          # $IsInstalled = ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0
          # $IsInstalled: ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0
          # $IsInstalled: ${ ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0 }
          # ${IsInstalled}: ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0
          # if ( ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0 ) # last close paren is invalid character
          # if ( '((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server").Length -gt 0' ) # cannot convert string to bool
          if ( $False ) # a sanity check ...
             # { $IsInstalled: $True }
             # { ${ $IsInstalled}: $True }
             # { ${IsInstalled}: $True } # colon is unexpected token
             # { ${IsInstalled} = $True } # equals outputs a string; cannot convert to boolean (i knew that but what the hey)
             # { ${ $IsInstalled: } $True } # unexpected token $True
             { '$IsInstalled: $True' }
          else
             # { $IsInstalled: $False }
             # { ${ $IsInstalled}: $False }
             # { ${IsInstalled}: $False }
             # { ${IsInstalled} = $False }
             # { ${ $IsInstalled: } $False }
             { '$IsInstalled: $False' }
        parameters:
          # IsInstalled: $True # cannot convert string to bool
          # 'IsInstalled: $True' # is of type System.String ... unable to convert to dict ... must either be a JSON string or in the key=value form"
}
      register: SQLtest

I was expecting the first (commented) statement to work; done. That is, to register SQLtest.IsInstalled as a boolean state for later consumption.

A: Here's an exact solution that did work; i couldn't get the templating to work, ...
    - name: Test for installed SQL Server
        ansible.windows.win_powershell:
          script: |
            ((gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Match "Microsoft SQL Server 2019 ").Length -gt 0
        register: SQLtest

... as consumed later in a when conditional ...
    when: not SQLtest.output

It's always simple (once you know how) ...


text:
Q: pandas dataframe adding extra row on all entries after the 1st When I add entries to my pandas dataframe, it is doing just as I want it to do for the 1st entry, but after that, it is giving an extra row with only 1 of the entries. It doesn't mater what I put in for the field for that entry, the extra row is always the same.
self.df_DT = self.df_DT.append({self.HeaderHourNumber: self.comboBox_DT_Hourly.currentText(),
                              self.HeaderMainZone: self.comboBox_Main_Zone1.currentText(),
                              self.HeaderDetailedIssue: self.comboBox_Detail_Issue1.currentText(),
                              self.HeaderDTmin: self.line_DT_min.text(),
                              self.HeaderMaintence: self.comboBox_Maint.currentText(),
                              self.HeaderNotes: self.textEdit_DT_Notes.toPlainText()}, ignore_index=True)

self.df_DT = self.df_DT.sort_values(self.HeaderHourNumber)

self.model_DT = PandasModel(self.df_DT)

self.tableView_DT.setModel(self.model_DT)

When I run it, it gives me this:
Hour Number Main Zone  ... Maintence Called?       Notes
                       ...                No
                       ...                No
                       ...                No
      2    Thiele      ...               Yes        some notes
      4    Thiele      ...               Yes        some notes
      6    Thiele      ...               Yes        some notes
      9    Thiele      ...               Yes        some notes

The 'Maintence Called' section is the only section that has anything in the extra rows and it always says 'No'.


text:
Q: Can we zoom the image to full size of device as media player in iOS? We can zoom media player to full size in iOS by pitch action.How to implement this type of zooming in the case of ImageView in iOS?

A: Steps :
1) You need to add the UIImageView as a subview of a UIScrollView.
2) Install a UITapGestureRecognizer on the scroll view and set the numberOfTapsRequired property to 1.
3) In the callback method of the gesture recognizer, just set the zoomScale property of the scroll view to your desired zoom amount.
4) Don't forget to set maximumZoomScale and minimumZoomScale on the UIScrollView as well.

A: *

*Add Pinch Recognizer to imageView

*Inside the recognizer method - set image view frame to full view size with animation

*Also hide status bar using [setStatusBarHidden:YES] on UIApplication


text:
Q: Form validation datatype error in javascript I get Login Done in all the cases and also this treats the value as the string instead of the number ....

function valid() {

  let value = document.getElementById('box').value;

  alert(typeof value)
  if (isNaN(value) || value < 1 || value > 20) {
    alert("Login Done")
  } else if (name = '') {
    alert("try agin")
  }
}

A: Negate the isNaN(value) check. Also convert it to a number before the comparison to reduce the confusion

function valid() {

  let value = document.getElementById('box').value;

  let parsedValue = isNaN(value) ? 1 : parseInt(value, 10);

  console.log(typeof value);
  console.log(typeof parsedValue);

  if (parsedValue < 1 || parsedValue > 20) {
    console.log("Login Done")
  } else {
    console.log("try agin")
  }
}

valid();

document.getElementById('box').addEventListener('keyup', valid);
<input id="box" value="21" />


text:
Q: why does it say "module does not exist" despite multiple installations I am running the following steps in Mac Terminal:

*

*sudo easy_install pip

*sudo pip install virtualenv

*virtualenv NameOfFolder

*cd NameOfFolder

*source bin/activate

*sudo pip install django

*django-admin startproject NameOfFolderSub1

*cd NameOfFolderSub1

*python manage.py runserver

At this last steps, it communicates this msg occurred:

Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

Attempted to check the Django version using this command in Terminal:
python -m django --version
it confirmed that django is not there with the following msg:
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3: No module named django

What did I do wrong int he step-by-step installation above ?
Appreciate the help.
The code in manage.py is as follows:
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxx.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

A: You've done sudo pip install django. Don't do that. You're in a virtualenv; just install directly without sudo; and use pip3 instead of pip.


text:
Q: Solution of differential equation with two variable I have a differential equation with variables x(t) and y(t), and a following differential equation:
$$xy \frac{d}{dt}\Big{(}\frac{x}{y}\Big{)} = c_{1} (y-x)-c_{2} \quad c_{1}~ \text{and}~c_{2}~\text{are}~\text{constants}$$
This equation comes from a coupled differential equation system, which describes the derivatives of x(t) and y(t).
Maybe a new variable which contains x(t) and y(t) can help to find the solution of this equation instead of solving the original equation system.
(The original system is
$$\frac{dx}{dt} = \gamma xy-\alpha xy-\gamma x^{2}-\gamma\beta x\qquad(1)\\
\frac{dy}{dx} = \gamma xy-\alpha xy-\gamma y^{2}\qquad (2)$$
I tried to simplifying the system with these steps:
$$ \frac{\dot{x}}{x} = \gamma y-\alpha y-\gamma x-\gamma\beta \qquad(1) \\
\frac{\dot{y}}{y} = \gamma x-\alpha x-\gamma y \qquad(2)\\
(1)-(2) \rightarrow \frac{\dot{x}}{x}-\frac{\dot{y}}{y} = (2\gamma-\alpha)(y-x)-\gamma\beta\\
\frac{\dot{x}y-\dot{y}x}{xy} = (2\gamma-\alpha)(y-x)-\gamma\beta\\
\frac{y}{x}\frac{d}{dt}\Big(\frac{x}{y}\Big) = (2\gamma-\alpha)(y-x)-\gamma\beta \\
\frac{y}{x}\frac{d}{dt}\Big{(}\frac{x}{y}\Big{)} = c_{1} (y-x)-c_{2} \qquad \text{where}~c_{1} =2\gamma-\alpha\qquad~c_{2} = \gamma\beta $$


text:
Q: Change Xmlspy editor background color I was wondering if anyone of you knows if it is possible to change Altova's XMLSPY editor background color.
I've googled but I didn't find anything about this topic, and I'm sadly assuming there's no hope to change the bg color.

A: Tools -> Options
Go to the text fonts tab and check "use the same for all". Press the icon above and set the background to a darker color.
Of course the usual text is black so make sure to change that to a lighter color. Just look at the preview and click on any text you can't see. Click on the icon with a little 'a' and set the text to a lighter color.

A: As I understand the question - it's not about font color nor font background - but how to change editor background which is for me (version 2015 sp1) blueish gradient.
I have gone thru the "options" and "customize" menu and there is nothing in that regard.
Their sister product UModel can do that by finding "Styles" docking window and looking for "Diag. Background Color" and setting it to e.g. "White" instead "gradient".
Unfortunately I don't see equivalent feature in XML Spy.
Also, I quickly looked at the exe file where I saw plenty of RGB values stored, I don't know does that mean the value is hard coded or it's just complicated to find background image settings.


text:
Q: Decode special characters from json data in c# I am getting data in json format from a url. Everything is working perfect, but one small issue is that in the data that I am getting there are some special characters, for example :

Get 50% off on Pizzas between 11am – 5pm.

– here means that it is '-', but how can I decode it in c# so that it takes it as '-'.
I have tried using Html.decode method, it is working fine with URLs but not with data.
I cannot replace – with '-' everywhere because this is not a single case, there are other similar characters too.

A: Works fine:
https://dotnetfiddle.net/H9rpLe
using System;

public class Program
{
    public static void Main()
    {
        string data = System.Net.WebUtility.HtmlDecode("Get 50% off on Pizzas between 11am – 5pm");

        Console.WriteLine(data);
    }
}

Output: Get 50% off on Pizzas between 11am – 5pm

A: I think this is a duplicate of this question.

You can use HttpUtility.HtmlDecode
If you are using .NET 4.0+ you can also use WebUtility.HtmlDecode which does not require an extra assembly reference as it is available in the System.Net namespace.

A: Try decoding it twice as it seems you have it encoded twice. First decoding will convert – to –, then second decoding will make it –.
using System;
using System.Web;

public class Test
{
    public static void Main()
    {
        string s = "Get 50% off on Pizzas between 11am – 5pm.";
        Console.WriteLine(s);

        string d = HttpUtility.HtmlDecode(s);
        Console.WriteLine(d);

        string e = HttpUtility.HtmlDecode(d);
        Console.WriteLine(e);
    }
}


text:
Q: Bash for loop how to solve variable with space? In some case, quotes can solve a param which contains space.
$ command "param 1" "param 2" ...

And it can also work for for loop.
$ for v in a "b c" "d e"
do
    echo "|$v|"
done
|a|
|b c|
|d e|

But when I use a variable after in, it not working:
$ var='a "b c" "d e"'
$ echo $var
  a "b c" "d e"
$ for v in $var
  do
      echo "|$v|"
  done
 |a|
 |"b|
 |c"|
 |"d|
 |e"|

It not working. How do I resolve this problem ?

A: That is why arrays were invented:
$ var=(a "b c" "d e")
$ for v in "${var[@]}"; do echo "|$v|"; done
|a|
|b c|
|d e|

Discussion
Consider:
var='a "b c" "d e"'

The problem with the above is that, once you quote a quote, it loses its magic.  The double-quotes inside the single-quoted string above are characters, just like any other characters: they no longer bind anything together.  That is why the output looks like this:
|a|
|"b|
|c"|
|"d|
|e"|

Reading arrays from the terminal
Arrays can be entered in newline-separated form using readarray:
$ readarray -tn3 var
a
b c
d e
$ for v in "${var[@]}"; do echo "|$v|"; done
|a|
|b c|
|d e|

-n3 limits the input to three lines.  -t tells readarray to discard the newline character.

A: As mentioned in comments and another answer, use an array if you can. That really is the best option.
If you are forced to work with strings (for some odd reason not described in your question) change your internal field separator, and then use your custom defined one to separate fields.
#Copy the current IFS
SaveIFS=$IFS
IFS=';'

var='a;b c;d e;'
for v in $var; do
    echo $v
done

#Revert when done
IFS=$SaveIFS


text:
Q: using Polymorphic arrays in java i have a superclass Dinosaur with only one subclass Tyrano
i have Dinosaur with these attributes:
public Dinosaur(String name, String size, String movement, String diet, String terainType){
    ...
    //i've already made the setters and getters along with some helper functions
    }

and i have Tyrano with 2 additional attributes which are teeth and hobby
public Tyrano(String name, String size, String movement, String diet, String terainType, int teeth, String hobby){
    ...
    //made setters and getters with some helper functions
    }

now in my driver program i want to make an array type Dinosaur that will accept multiple subclasses of Dinosaur one of them which is the subclass Tyrano i don't know if its possible but my instructor said it is so here's what i did, this is on the main:
Dinosaur[] dinoList = new Dinosaur[9];
dinoList[0] = new Tyrano("Gary", "Large", "other dino Meat", "Land", 30, "singing");
int teeth = dinoList[0].getTeeth();
String hobby = dinoList[0].getHobby();
...//i also called the helper functions that were in Tyrano

it gets an error:
error: cannot find symbol
       dinoList[0].getTeeth();
                  ^
error: cannot find symbol
       dinoList[0].getHobby();
                  ^
...//along with same errors with the helper functions that were in Tyrano
...//it also happens when i call setters that were unique for the subclass Tyrano

and i don't know why it's doing this, i've double checked and i have no syntactical errors and i've already defined the helper functions, also those getters and setters, but there's no problem for the common ones which are found in the superclass Dinosaur

A: If getTeeth() and getHobby() do not exist for Dinosaur class, you can't call them from a reference to a Dinosaur. Even if the actual instance stored in dinoList[0] is a Tyrano, you can't access its unique methods without casting the reference to a Tyrano.
This will work :
if (dinoList[0] instanceof Tyrano) {
    Tyrano t = (Tyrano) dinoList[0];
    int teeth = t.getTeeth();
    String hobby = t.getHobby();
}

A: If you use the subclass from an array that contains its superclass, then you have access only to the methods that are available in the superclass, as these are the methods common among all subclasses.
public class Dinosaur
{
    private String hobby;

    public String getHobby() {
        return hobby;
    }
    ...
}

public class Tyrano extends Dinosaur
{
    private String teeth;

    public String getTeeth() {
        return teeth;
    }
    ...
}

Then you have the following
 Dinosaur dinosaur = new Tyrano();
 String hobby = dinosaur.getHobby(); //this works
 String teeth = dinosaur.getTeeth(); //this is compile error!
 if(dinosaur instanceof Tyrano) {
     Tyrano tyrano = (Tyrano) dinosaur; //casting
     teeth = tyrano.getTeeth(); //this works
 }

A: This is a typical mistake. The point is, you have an array of Dinosaurs which don't have teeth or hobbies, is like if you have an array of Person and one of this "person" is a Teacher... not all the Person are Teacher like not all the Dinosaur have teeth.
So, you need to ask your Dinosaur "are you a Tyrano?" and if the answer is "yes" then... ask him "then, like a Tyrano, what is your hobbie?".
Let me put that in code:
//are you a Tyrano?
if(Tyrano.class.isAssignableFrom(dinoList[0].getClass())){
        // so, I treat you like a Tyrano
        Tyrano tyranoDyno= (Tyrano) dinoList[0];
        //tell me... teeth and hobbies please?
        int teeth = tyranoDyno.getTeeth();
        String hobby = tyranoDyno.getHobby();
}

A: When you create a subclass, the subclass inherits the fields and methods from its superclass. So Tyrano has everything that Dinosaur has, and a bit more (teeth and hobby).
You could make another class, say Stego, which also extends Dinosaur and adds a field for armour.
Now your array of dinosaurs could contain both Tyrano and Stego types (they are both dinosaurs so this is fine). But your program has no way of predicting which type they will be. Since Stego has no teeth or hobby, and Tyrano has no armour, you can't use these fields directly (instead do as Eran suggested). You are however free to use all the fields from Dinosaur, since all dinosaurs are guaranteed to have inherited these


text:
Q: Sampling with replacement with multiple attempts Let us consider sampling over $N$ objects in a bowl. $Q$ sampling attempts are made, each attempt consisting in picking $K_i\leq N$ objects, with $i = 1,\dots, Q$. After each attempt, the objects are put back in the bowl.
How to calculate the probability that, after the $Q$ attempts, each object of the bowl has been picked at least once?
For example, let us assume $N$=4, $Q$=2, $K_1$=2, $K_2$=3. Let us denote the objects as (1,2,3,4). In the first attempt, there are ${4}\choose{2}$ = 6 possibilities, i.e. ((1,2) (1,3) (1,4), (2,3), (2,4), (3,4)). In the second attempt, there are ${4}\choose{3}$ = 4 possibilities, i.e. ((1,2,3), (1,2,4), (1,3,4), (2,3,4)). The set of all possible combinations is therefore given by $6 \cdot 4$=24 combinations. From inspection, I can see that 12 combinations out of the 24, are those who cover all the 4 elements. Therefore result is 12/24=1/2. But how to come up with a general formula??

A: This answer doesn't answer the general question. It only covers the special case Q=2 that OP asked for in a comment.
When $Q=2$ we have two attempts $K1$ and $K2$ where $1<=K1<=N$ and $1<=K2<=N$. Further, $K1+K2>=N$.
In the first attempt $K1$ unique numbers will be picked.
In the second attempt there will be $N-K1$ unique numbers and $K1$ duplicates (of the first attempt) to pick from. Further it's know that $K2 >= N-K1$.
So for the whole experiment to be a succes, we must pick all $N-K1$ unique numbers in the $K2$ picks. The number of combinations giving succes is then found as:
$$NumberOfCombinationGivingSucces = \binom{K2}{N-K1}$$
Now consider the case where $K2>=K1$
In this case the number of duplicates picked in the second attempt will be in the range "NumbersToPick - NumberOfUniqueNumbers" to "NumbersOfDuplicates". Or as a formula the range is from $K2-(N-K1)$ to $K1$. So we can calculate the total number of combinations like:
$$TotalNumberOfCombinations = \sum_{i=K2-(N-K1)}^{K1}{\binom{K2}{i}}$$
So with the restrictions a) $Q=2$ b) $K1+K2>=N$ and c) $K2>=K1$ the probability of picking all N numbers in the two attempts $K1$ and $K2$ is:
$$P = \frac{\binom{K2}{N-K1}}{\sum_{i=K2-(N-K1)}^{K1}{\binom{K2}{i}}}$$
Using the same principle the case $K2<K1$ can be calculated.


text:
Q: Code python to check credit card and bank I'm working on a small script to check credit cards and bank validity but for a crazy reason I get an error I do not understand.
#!/usr/bin/python
# -*- coding: utf-8 -*-
def digitSum(myString):

    length = len(myString)
    oddSum = 0
    evenSum = 0

    #base case
    if (length ==0):
        return 0

    #length > 0
    else:
        #if even
        if (length % 2 ==0):
            last = int(myString[-1])
            evenSum += last

            return evenSum + digitSum(myString[:-1])

        else:
            last = int(myString[-1])
            last = 2 * last
            part_sum = last // 10 + last % 10
            oddSum += part_sum

            return oddSum + digitSum(myString[:-1])

def luhns():
    myString = input("Entrez les 16 numéros de la Carte de Crédit ")

    total = digitSum(myString)
    if (total % 10 == 0):

        if total[:1] == "4":
            cardtype = "Visa"
        if int(total[:2]) >= 51 and int(total[:2]) <= 55:
            cardtype = "Master Card"
        if total[:2] == "34" or total[:2] == "37":
            cardtype = "American Express"
        if total[:4] == "6011":
            cardtype = "Discover"
        if total[:2] == "36":
            cardtype = "DINERS"
        if int(total[:3]) >= 300 and int(total[:3]) <= 305:
            cardtype = "DINERS"

        return cardtype

        print ('Carte valide') + cardtype
    else:
        print ('Carte invalide')

def main():
    luhns()

#Python call to main()
main()

This is the error I'm getting:
Entrez les 16 numéros de la Carte de Crédit 11111
Traceback (most recent call last):
  File "/Volumes/Python/LuhnsAlgorithm.py", line 61, in <module>
    main()
  File "/Volumes/Python/LuhnsAlgorithm.py", line 58, in main
    luhns()
  File "/Volumes/Python/LuhnsAlgorithm.py", line 34, in luhns
    total = digitSum(myString)
  File "/Volumes/Python/LuhnsAlgorithm.py", line 5, in digitSum
    length = len(myString)
TypeError: object of type 'int' has no len()
logout

A: Depending upon whether you're using Python 2 or 3 input behaves differently.
Python 2 input will evaluate the input string and convert it into an integer, if it's an integer.
You are probably using Python 2.
If you don't want it evaluated you need to use raw_input.
See answers to Differences between input and raw_input

A: First of all your function name says you try to sum digits.
Then you wrote myString as parameter, and trying to  find the length of that String. But I think you are passing Numbers to that function while calling and trying to find the length of that numbers but actually in python you can't find the length of numbers.
So your error is at line number 5.
Rethink on your logic.


text:
Q: How to make Emacs transparent with i3-wm? As instructed here I added the following lines to my emacs configuration file:
(set-frame-parameter (selected-frame) 'alpha '(85 . 50))
(add-to-list 'default-frame-alist '(alpha . (85 . 50)))

But nothing changed. Every post that I checked on-line suggested that the above should work.
So I logged out of my i3 windows manager and logged in using Mate Desktop and viola the transparency worked!
So question now is: what else do I have to do to make emacs transparent on i3?
EDIT: I am using feh to set up my desktop background.
p.s.: I have the gnome terminal transparent on i3 and it works fine.

A: You want this: https://github.com/vava/i3-emacs
Clone it into your emacs folder:
git -C ~/.emacs.d/ clone https://github.com/vava/i3-emacs
then add the following lines to your init.el:
;; i3 integration
(add-to-list 'load-path "~/.emacs.d/i3-emacs")
(require 'i3)
(require 'i3-integration)

Note: This only seems to have an effect when emacs is run in a terminal, i.e. emacs -nw, although I have only just found it myself so not sure if it can apply to "GUI Emacs" too.


text:
Q: recursive function php + mysql to tree menu
Possible Duplicate:
PHP / MySQL build tree menu

I need get data between two level build menu.
ID | Parent    | Name    |
 1 | 0         | Cat1    |
 2 | 1         | SubCat1 |
 3 | 0         | Cat2    |
 4 | 3         | SubCat2 |
 5 | 4         | SubCat3 |
 6 | 3         | SubCat4 |
 7 | 3         | SubCat5 |

Level 1: Cat1 and Cat2
Level 2: SubCat1, SubCat2 and Subcat4
Level 3: SubCat3 and SubCat5

*

*Cat1

*

*SubCat1

*Cat2

*

*SubCat2

*

*SubCat3

*SubCat5

*SubCat4

I want to level 2 and level 3 menus list data. How I call between 2,3 row?

A: The correct name here for this data is an adjacent list hierarchy
There is a guide on this website to produce this in MySQL
http://kod34fr33.wordpress.com/2008/05/06/adjacency-list-tree-on-mysql/


text:
Q: How to parse an HTML node's attributes I use C# and need to parse an HTML to read the attributes into key value pairs.
e.g given the following HTML snippet

Please note that the attributes can be
1. key="value" pairs e.g class="someclass"
2. key=value pairs e.g id=my_ID (no quotes for values)
3. plain attributes e.g myAttribute, which doesn't have a "value"
I need to store them into a dictionary with key value pairs as follows
key=myAttribute value=""
key=style value="BORDER-BOTTOM: medium none; BACKGROUND-COLOR: transparent; BORDER-TOP: medium none"
key=id value="my_ID"
key=anotherAttribNamedDIV value=""
key=class value="someclass"
I am looking for regular expressions to do this.

A: You can do this with the HtmlAgilityPack
string myDiv = @"

";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(myDiv);
HtmlNode node = doc.DocumentNode.SelectSingleNode("div");

Literal1.Text = "";

foreach (HtmlAttribute attr in node.Attributes)
{
    Literal1.Text += attr.Name + ": " + attr.Value + "
";
}

A: HtmlDocument docHtml = new HtmlWeb().Load(url);


text:
Q: How to get subclipse source code and build it? I want to download the svn plugin--subclipse  source code, and then build it by myself, then intergrate subclipse to the eclipse 4.5.
Can you tell me how or where to get the subclipse source code and how to build it please?
Please help me. Thank you very much.

I have get the source code from this link below:
http://subclipse.tigris.org/source/browse/subclipse/
I have build the subclipse by ant, Now I will try to use Eclipse to build it.
Thank you very much for everyone's reply.

A: There is a wiki page with some information.
Subclipse Development
I do not maintain it much, but the process has never really changed so I would assume it is up to date.  I build Subclipse by building the Update Site project via the Eclipse UI.

A: The source code is here: http://subclipse.tigris.org/source/browse/subclipse/
To build it, try importing the projects into Eclipse. Once you have a specific problem, please ask an additional question on SO.


text:
Q: Postman: issue with scaling, perhaps turn off response printing? I have an API that returns the values for n rows in a csv file.
If the table is 100 "rows" (for lack of a better term) and I get the values in every row, it takes x seconds and has a size of y KB. If the table is 100 rows and I get the values for half the rows, it takes ~x/2 seconds and has a size of ~y/2.This makes sense.
The problem comes when I get to the real size of the file -- millions of rows.  It's not giving me the correct values.  The sizes and times don't pass the smell test (they're too low), and they're the same.The values in the entire table, half the table, whatever -- the time it takes to return the values are the same and the size of what's being returned is the same.
I have a suspicion that it's the printed response.  What... it's gonna print four million rows in that wee little panel at the bottom of the screen?
Is there a way to just get the metadata (status, time, size) and not print the response?  A setting or something?  That's all I need anyways.
(PS: Response is JSON if that matters)